diff --git a/src/crates/interfaces/acp/AGENTS.md b/src/crates/interfaces/acp/AGENTS.md index 38fa9ab570..ca85d42db9 100644 --- a/src/crates/interfaces/acp/AGENTS.md +++ b/src/crates/interfaces/acp/AGENTS.md @@ -34,6 +34,10 @@ Keep these role features additive and do not replace either closure with requests, client choices, and lifecycle state may not. - If a future contract is needed, make it observational: environment identity, capability facts, and request/response DTOs only. +- Session options may include `availableCommands` from the same metadata read. + Keep it optional: missing means an older host uses the commands endpoint; + an empty list is a supported combined snapshot. Do not infer this capability + from a package version. Frontends share in-flight reads, not settled snapshots. ## Verification @@ -42,6 +46,7 @@ cargo check -p openbitfun-acp --no-default-features --features client cargo check -p openbitfun-acp --no-default-features --features server cargo test -p openbitfun-acp cargo test -p openbitfun-acp --no-default-features --features client,openbitfun-core/git --lib client::prompt::tests +cargo test -p openbitfun-acp --no-default-features --features client,openbitfun-core/git --lib client::session_options::tests ``` The focused client prompt tests cover protocol errors, retry, cancellation, @@ -49,3 +54,6 @@ partial output, and transport termination with in-memory agent streams. These fixtures do not require a live provider or a device connection. The explicit Core `git` feature satisfies the worktree tool dependency in the current client closure without enabling the server role or `product-full`. + +The session-options tests cover legacy payload round trips and the additive +combined metadata response. They do not establish live Agent startup latency. diff --git a/src/crates/interfaces/acp/src/client/manager.rs b/src/crates/interfaces/acp/src/client/manager.rs index b140d7aa14..1c448eb988 100644 --- a/src/crates/interfaces/acp/src/client/manager.rs +++ b/src/crates/interfaces/acp/src/client/manager.rs @@ -28,6 +28,7 @@ use openbitfun_core::infrastructure::events::{emit_global_event, BackendEvent}; use openbitfun_core::infrastructure::PathManager; use openbitfun_core::service::config::ConfigService; use openbitfun_core::service::remote_ssh::workspace_state::get_remote_workspace_manager; +use openbitfun_core::util::elapsed_ms_u64; use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -248,7 +249,9 @@ impl AcpClientService { client_id: &str, session_name: Option, ) -> OpenBitFunResult { - self.session_persistence + let started_at = Instant::now(); + let result = self + .session_persistence .create_flow_session_record( session_storage_path, workspace_id, @@ -256,7 +259,12 @@ impl AcpClientService { client_id, session_name, ) - .await + .await; + debug!( + "ACP startup phase completed: client_id={} phase=persist_session duration_ms={} succeeded={}", + client_id, elapsed_ms_u64(started_at), result.is_ok() + ); + result } pub async fn initialize_all(self: &Arc) -> OpenBitFunResult<()> { @@ -569,6 +577,7 @@ impl AcpClientService { workspace_path: Option<&str>, remote_connection_id: Option<&str>, ) -> OpenBitFunResult<()> { + let started_at = Instant::now(); let (connection, remote_connection_id) = loop { if let Some(existing) = self.clients.get(connection_id).map(|entry| entry.clone()) { let status = *existing.status.read().await; @@ -621,6 +630,7 @@ impl AcpClientService { } }; + let transport_started_at = Instant::now(); let transport_result = match remote_connection_id { Some(ref remote_connection_id) => { self.open_transport_for_connection( @@ -643,6 +653,11 @@ impl AcpClientService { .await } }; + debug!( + "ACP startup phase completed: client_id={} connection_id={} phase=transport remote={} duration_ms={} succeeded={}", + client_id, connection_id, remote_connection_id.is_some(), + elapsed_ms_u64(transport_started_at), transport_result.is_ok() + ); let (transport, child, stderr_tail) = match transport_result { Ok(result) => result, Err(error) => { @@ -712,9 +727,13 @@ impl AcpClientService { connection_for_task.sessions.clear(); }); - let (cx, agent_capabilities) = match tokio::time::timeout(CLIENT_STARTUP_TIMEOUT, cx_rx) - .await - { + let initialize_started_at = Instant::now(); + let initialized = tokio::time::timeout(CLIENT_STARTUP_TIMEOUT, cx_rx).await; + debug!( + "ACP startup phase completed: client_id={} connection_id={} phase=initialize duration_ms={} succeeded={}", + client_id, connection_id, elapsed_ms_u64(initialize_started_at), matches!(&initialized, Ok(Ok(_))) + ); + let (cx, agent_capabilities) = match initialized { Ok(Ok(result)) => result, Ok(Err(_)) => { connect_task.abort(); @@ -743,9 +762,10 @@ impl AcpClientService { *connection.agent_capabilities.write().await = Some(agent_capabilities); *connection.status.write().await = AcpClientStatus::Running; info!( - "ACP client started: id={} remote_connection_id={}", + "ACP client started: id={} remote_connection_id={} duration_ms={}", client_id, - remote_connection_id.as_deref().unwrap_or("") + remote_connection_id.as_deref().unwrap_or(""), + elapsed_ms_u64(started_at) ); Ok(()) } @@ -949,6 +969,7 @@ impl AcpClientService { session_storage_path: Option, openbitfun_session_id: String, ) -> OpenBitFunResult { + let started_at = Instant::now(); let resolved = self .resolve_or_create_client_session( client_id, @@ -969,11 +990,19 @@ impl AcpClientService { ) .await?; drain_pending_session_metadata_updates(&mut session).await?; - Ok(session_options_from_state( + let mut options = session_options_from_state( session.models.as_ref(), &session.config_options, session.context_usage.as_ref(), - )) + ); + options.available_commands = Some(session.available_commands.clone()); + debug!( + "ACP session metadata loaded: client_id={} session_id={} duration_ms={}", + client_id, + openbitfun_session_id, + elapsed_ms_u64(started_at) + ); + Ok(options) } pub async fn get_session_commands( @@ -1566,7 +1595,13 @@ impl AcpClientService { where F: Future>, { - match tokio::time::timeout(CLIENT_STARTUP_TIMEOUT, future).await { + let started_at = Instant::now(); + let result = tokio::time::timeout(CLIENT_STARTUP_TIMEOUT, future).await; + debug!( + "ACP startup phase completed: client_id={} connection_id={} phase={} duration_ms={} succeeded={}", + client.client_id, client.id, phase, elapsed_ms_u64(started_at), matches!(&result, Ok(Ok(_))) + ); + match result { Ok(result) => result, Err(_) => { warn!( diff --git a/src/crates/interfaces/acp/src/client/session_options.rs b/src/crates/interfaces/acp/src/client/session_options.rs index 25c0766f23..f00ea97681 100644 --- a/src/crates/interfaces/acp/src/client/session_options.rs +++ b/src/crates/interfaces/acp/src/client/session_options.rs @@ -89,6 +89,9 @@ impl From for AcpPlanEntry { #[derive(Debug, Clone, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub struct AcpSessionOptions { + /// Present on combined metadata reads; absence preserves the legacy commands endpoint. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub available_commands: Option>, #[serde(default)] pub current_model_id: Option, #[serde(default)] @@ -171,6 +174,7 @@ pub(super) fn session_options_from_state( model_config_id: None, config_options: session_config_options, context_usage, + ..Default::default() }; } @@ -182,6 +186,7 @@ pub(super) fn session_options_from_state( model_config_id: Some(option.id.to_string()), config_options: session_config_options, context_usage, + ..Default::default() }; } @@ -356,6 +361,27 @@ mod tests { use super::*; use agent_client_protocol::schema::{ModelInfo, SessionConfigOption}; + #[test] + fn legacy_session_options_round_trip_without_advertising_combined_metadata() { + let legacy = serde_json::json!({ + "currentModelId": null, "availableModels": [], "modelConfigId": null, + "configOptions": [], "contextUsage": null + }); + let options: AcpSessionOptions = serde_json::from_value(legacy.clone()).unwrap(); + assert!(options.available_commands.is_none()); + assert_eq!(serde_json::to_value(options).unwrap(), legacy); + } + + #[test] + fn combined_metadata_distinguishes_empty_commands_from_legacy_absence() { + let mut options = AcpSessionOptions::default(); + options.available_commands = Some(Vec::new()); + let payload = serde_json::to_value(&options).unwrap(); + assert_eq!(payload["availableCommands"], serde_json::json!([])); + let restored: AcpSessionOptions = serde_json::from_value(payload).unwrap(); + assert_eq!(restored.available_commands, Some(Vec::new())); + } + #[test] fn converts_native_model_state() { let state = SessionModelState::new("gpt-5.4", vec![ModelInfo::new("gpt-5.4", "GPT 5.4")]); diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index c8fdc99127..a44bf23f4b 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -207,6 +207,16 @@ also run the focused state contracts: pnpm --dir src/web-ui run test:run src/app/services/sessionSceneLifecycle.test.ts src/flow_chat/services/sessionActivation.test.ts src/flow_chat/services/storeSync.test.ts src/app/stores/sceneStore.test.ts ``` +For ACP creation feedback, retries, metadata loading and cross-version fallback: + +```bash +pnpm --dir src/web-ui run test:run src/app/layout/AcpSessionNotifications.test.tsx src/flow_chat/services/FlowChatManager.test.ts src/infrastructure/api/service-api/ACPClientAPI.test.ts src/flow_chat/components/ModelSelectorAcpMode.test.tsx src/flow_chat/hooks/useAcpSlashCommands.test.ts +``` + +These DOM/API fixtures cover delayed startup, duplicate creation, visible errors, +retry, old-host metadata and simulated SSH/Peer identities. They do not establish +native rendering, real provider latency or live remote behavior. + For top session tabs (one per session, kept per device), selection and reconciliation: ```bash diff --git a/src/web-ui/src/app/layout/AcpSessionNotifications.test.tsx b/src/web-ui/src/app/layout/AcpSessionNotifications.test.tsx new file mode 100644 index 0000000000..eebcb6062a --- /dev/null +++ b/src/web-ui/src/app/layout/AcpSessionNotifications.test.tsx @@ -0,0 +1,110 @@ +// @vitest-environment jsdom +import React, { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AcpSessionNotifications } from './AcpSessionNotifications'; +import { NotificationContainer } from '@/shared/notification-system/components/NotificationContainer'; +import { notificationStore } from '@/shared/notification-system/store/NotificationStore'; +import { activateSurface, getActiveSurfaceScope, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; +import { emitAcpSessionStartup, type AcpSessionStartupDetail } from '@/flow_chat/services/acpSessionStartup'; +import { openMainSession } from '@/flow_chat/services/sessionActivation'; + +vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) })); +vi.mock('@/infrastructure/i18n/core/I18nService', () => ({ i18nService: { t: (key: string) => key } })); +vi.mock('@/flow_chat/services/sessionActivation', () => ({ openMainSession: vi.fn(async () => {}) })); + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +describe('ACP session startup feedback', () => { + let root: Root; + let container: HTMLDivElement; + const start = (overrides: Partial = {}): AcpSessionStartupDetail => ({ + phase: 'start', action: 'create', clientId: 'codex', requestId: 'create-1', + scope: getActiveSurfaceScope(), workspaceId: 'workspace-1', ...overrides, + }); + + beforeEach(() => { + resetDeviceSurfaceForTest(); + vi.useFakeTimers(); + vi.clearAllMocks(); + vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })); + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + act(() => root.render(<>)); + }); + + afterEach(() => { + act(() => root.unmount()); + notificationStore.clearHistory(); + container.remove(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it('renders a persistent spinner before a session exists, then clears it on success', () => { + const detail = start(); + act(() => emitAcpSessionStartup(detail)); + expect(document.querySelector('[role="status"]')?.textContent).toContain('nav.workspaces.startingAcpSession'); + expect(document.querySelector('[data-openbitfun-component="spinner"]')).not.toBeNull(); + expect(notificationStore.getState().activeNotifications[0]).toMatchObject({ duration: 0, closable: false, variant: 'toast' }); + act(() => vi.advanceTimersByTime(60_000)); + expect(notificationStore.getState().activeNotifications).toHaveLength(1); + act(() => emitAcpSessionStartup({ ...detail, phase: 'finish', succeeded: true })); + act(() => vi.advanceTimersByTime(200)); + expect(document.querySelector('.notification-item')).toBeNull(); + }); + + it('shows the actual failure and retries on the same workspace before opening the session', async () => { + const retry = vi.fn(async () => 'new-session'); + const detail = start({ retry }); + act(() => emitAcpSessionStartup(detail)); + act(() => emitAcpSessionStartup({ ...detail, phase: 'finish', succeeded: false, error: 'Agent initialize timed out' })); + expect(document.querySelector('[role="alert"]')?.textContent).toContain('Agent initialize timed out'); + const button = [...document.querySelectorAll('button')].find(item => item.textContent === 'nav.workspaces.retryAcpSession'); + expect(button).toBeDefined(); + await act(async () => button!.click()); + expect(retry).toHaveBeenCalledTimes(1); + expect(openMainSession).toHaveBeenCalledWith('new-session', { workspaceId: 'workspace-1' }); + }); + + it('keeps simultaneous requests for the same agent independent', () => { + const first = start(); + const second = start({ requestId: 'create-2', workspaceId: 'workspace-2' }); + act(() => { emitAcpSessionStartup(first); emitAcpSessionStartup(second); }); + expect(notificationStore.getState().activeNotifications).toHaveLength(2); + act(() => emitAcpSessionStartup({ ...first, phase: 'finish', succeeded: true })); + expect(notificationStore.getState().activeNotifications).toHaveLength(1); + expect(notificationStore.getState().activeNotifications[0].metadata?.requestId).toBe('create-2'); + }); + + it('clears the old device feedback and ignores its late failure', () => { + const detail = start(); + act(() => emitAcpSessionStartup(detail)); + act(() => activateSurface('peer-b')); + act(() => emitAcpSessionStartup({ ...detail, phase: 'finish', succeeded: false, error: 'Old failure' })); + expect(notificationStore.getState().activeNotifications).toHaveLength(0); + }); + + it('does not open a retry result after switching devices', async () => { + let resolve!: (value: string) => void; + const retry = vi.fn(() => new Promise(done => { resolve = done; })); + const detail = start({ retry }); + act(() => emitAcpSessionStartup({ ...detail, phase: 'finish', succeeded: false })); + act(() => [...document.querySelectorAll('button')].find(item => item.textContent === 'nav.workspaces.retryAcpSession')!.click()); + await act(async () => { activateSurface('peer-b'); resolve('old-session'); }); + expect(openMainSession).not.toHaveBeenCalled(); + }); + + it('labels the protocol session initialization separately', () => { + act(() => emitAcpSessionStartup(start({ action: 'restore' }))); + expect(document.querySelector('[role="status"]')?.textContent).toContain('nav.workspaces.initializingAcpSession'); + }); + + it('dismisses an abandoned view without reporting an agent failure', () => { + const detail = start({ action: 'restore' }); + act(() => emitAcpSessionStartup(detail)); + act(() => emitAcpSessionStartup({ ...detail, phase: 'finish', cancelled: true })); + expect(notificationStore.getState().activeNotifications).toHaveLength(0); + }); +}); diff --git a/src/web-ui/src/app/layout/AcpSessionNotifications.tsx b/src/web-ui/src/app/layout/AcpSessionNotifications.tsx new file mode 100644 index 0000000000..96bfd4d594 --- /dev/null +++ b/src/web-ui/src/app/layout/AcpSessionNotifications.tsx @@ -0,0 +1,80 @@ +import { useEffect, useRef } from 'react'; +import { Spinner } from '@openbitfun/ui'; +import { useI18n } from '@/infrastructure/i18n'; +import { onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; +import { notificationService } from '@/shared/notification-system'; +import { openMainSession } from '@/flow_chat/services/sessionActivation'; +import type { AcpSessionStartupDetail } from '@/flow_chat/services/acpSessionStartup'; +import { createLogger } from '@/shared/utils/logger'; + +const log = createLogger('AcpSessionNotifications'); + +export function AcpSessionNotifications(): null { + const { t } = useI18n('common'); + const translate = useRef(t); + translate.current = t; + + useEffect(() => { + const notifications = new Map(); + const clear = () => { + notifications.forEach(id => notificationService.dismiss(id)); + notifications.clear(); + }; + const unsubscribe = onSurfaceActivated(clear); + const handle = (event: Event) => { + const detail = (event as CustomEvent).detail; + if (!detail?.scope?.isCurrent()) return; + const previous = notifications.get(detail.requestId); + if (previous) notificationService.dismiss(previous); + notifications.delete(detail.requestId); + + if (detail.phase === 'start') { + const message = translate.current(detail.action === 'restore' + ? 'nav.workspaces.initializingAcpSession' : 'nav.workspaces.startingAcpSession'); + // Loading notifications are center-only. Use a persistent toast so the + // initial process/adapter startup is visible before a session tab exists. + const id = notificationService.info(message, { + title: detail.clientId, + duration: 0, + closable: false, + messageNode: <> {message}, + metadata: { source: 'acp-session', requestId: detail.requestId }, + }); + notifications.set(detail.requestId, id); + } else if (detail.succeeded === false && !detail.cancelled) { + const id = notificationService.error( + detail.error || translate.current('nav.workspaces.acpSessionStartFailed'), + { + title: `${detail.clientId}: ${translate.current('nav.workspaces.acpSessionStartFailed')}`, + actions: detail.retry ? [{ + label: translate.current('nav.workspaces.retryAcpSession'), + onClick: () => { + notifications.delete(detail.requestId); + if (!detail.scope.isCurrent()) return; + void detail.retry!().then(async sessionId => { + if (sessionId && detail.scope.isCurrent()) { + try { + await openMainSession(sessionId, { workspaceId: detail.workspaceId }); + } catch (error) { + if (detail.scope.isCurrent()) { + notificationService.error(error instanceof Error ? error.message : String(error)); + } + } + } + }).catch(error => log.warn('ACP session retry failed', { error })); + }, + }] : undefined, + }, + ); + notifications.set(detail.requestId, id); + } + }; + window.addEventListener('openbitfun:acp-session-creation', handle); + return () => { + window.removeEventListener('openbitfun:acp-session-creation', handle); + unsubscribe(); + clear(); + }; + }, []); + return null; +} diff --git a/src/web-ui/src/app/layout/AppLayout.tsx b/src/web-ui/src/app/layout/AppLayout.tsx index f422ad4907..440cbf2415 100644 --- a/src/web-ui/src/app/layout/AppLayout.tsx +++ b/src/web-ui/src/app/layout/AppLayout.tsx @@ -39,7 +39,7 @@ import { isMacOSDesktopRuntime } from '@/infrastructure/runtime'; import { flowChatSessionConfigForWorkspace } from '../utils/projectSessionWorkspace'; import { startSessionSceneLifecycle } from '../services/sessionSceneLifecycle'; import { openMainSession } from '@/flow_chat/services/sessionActivation'; -import { notificationService } from '@/shared/notification-system'; +import { AcpSessionNotifications } from './AcpSessionNotifications'; import { api } from '@/infrastructure/api/service-api/ApiClient'; import { AppearanceBackgroundMediaLayer, appearanceRuntime, useAppearance } from '@/infrastructure/appearance'; import { PeerConnectionStatus } from '@/infrastructure/peer-device/PeerConnectionStatus'; @@ -65,14 +65,6 @@ interface AppLayoutProps { className?: string; } -interface AcpSessionCreationEventDetail { - phase?: 'start' | 'finish'; - clientId?: string; - action?: 'create' | 'restore'; - requestId?: string; - succeeded?: boolean; -} - interface WindowModeHint { id: number; title: string; @@ -596,35 +588,6 @@ const AppLayout: React.FC = ({ className = '' }) => { return () => window.removeEventListener('openbitfun:create-acp-session', handler); }, [currentWorkspace]); - React.useEffect(() => { - const handler = (event: Event) => { - const detail = (event as CustomEvent).detail; - const clientId = detail?.clientId?.trim() || 'ACP'; - const action = detail?.action === 'restore' ? 'restore' : 'create'; - const id = detail?.requestId?.trim() || `${action}:${clientId}`; - if (detail?.phase === 'start') { - notificationService.silent({ - title: clientId, - message: tCommon('nav.workspaces.startingAcpSession'), - type: 'info', - metadata: { source: 'acp-session', clientId, action, requestId: id, phase: 'start' }, - }); - } else if (detail?.phase === 'finish') { - const succeeded = detail.succeeded !== false; - notificationService.silent({ - title: clientId, - message: succeeded - ? tCommon('nav.workspaces.acpSessionStarted') - : tCommon('nav.workspaces.acpSessionStartFailed'), - type: succeeded ? 'success' : 'error', - metadata: { source: 'acp-session', clientId, action, requestId: id, phase: 'finish', succeeded }, - }); - } - }; - window.addEventListener('openbitfun:acp-session-creation', handler); - return () => window.removeEventListener('openbitfun:acp-session-creation', handler); - }, [tCommon]); - // Global drag-and-drop React.useEffect(() => { const handleDragStart = (e: DragEvent) => { @@ -674,6 +637,7 @@ const AppLayout: React.FC = ({ className = '' }) => { return ( <> + {aboutDialog}
= ({ className = '' }) => { return ( <> +
= ({ const configLoadState = configEpoch === deviceSurfaceScope.epoch ? configState : 'loading'; const [acpOptions, setAcpOptions] = useState(null); const [acpOptionsLoadState, setAcpOptionsLoadState] = useState<'loading' | 'ready' | 'error'>('loading'); + const acpStartupDismissRef = useRef<(() => void) | null>(null); const [dropdownOpen, setDropdownOpen] = useState(false); const [keyboardNavigationOpen, setKeyboardNavigationOpen] = useState(false); /** Provider whose models the menu is currently showing; null is the provider level. */ @@ -666,7 +668,9 @@ export const ModelSelector: React.FC = ({ return () => { configLoadRequestRef.current += 1; unsubscribe(); }; }, [loadConfigData, deviceSurfaceScope.epoch]); - const loadAcpOptions = useCallback(async () => { + const loadAcpOptions: () => Promise = useCallback(async () => { + const scope = deviceSurfaceScope; + if (!scope.isCurrent()) return; const requestId = ++acpOptionsLoadRequestRef.current; if (!isAcpSession || !acpClientId || !sessionId) { setAcpOptions(null); @@ -676,15 +680,24 @@ export const ModelSelector: React.FC = ({ setAcpOptionsLoadState('loading'); const shouldShowRestoreToast = !acpOptionsRef.current && acpRestoreToastShownRef.current !== sessionId; - const restoreRequestId = `acp-options:${sessionId}:${acpClientId}`; + const startup = { + requestId: createAcpStartupRequestId(), clientId: acpClientId, action: 'restore' as const, scope, + retry: async () => { + if (!scope.isCurrent() || modelSelectionScopeRef.current !== modelSelectionScopeKey + || requestId !== acpOptionsLoadRequestRef.current) return; + acpRestoreToastShownRef.current = null; + await loadAcpOptions(); + }, + }; + const dismissStartup = () => emitAcpSessionStartup({ ...startup, phase: 'finish', cancelled: true }); if (shouldShowRestoreToast) { acpRestoreToastShownRef.current = sessionId; - window.dispatchEvent(new CustomEvent('openbitfun:acp-session-creation', { - detail: { phase: 'start', clientId: acpClientId, action: 'restore', requestId: restoreRequestId }, - })); + emitAcpSessionStartup({ ...startup, phase: 'start' }); + acpStartupDismissRef.current = dismissStartup; } let succeeded = false; + let failure: string | undefined; try { const options = await withTimeout( ACPClientAPI.getSessionOptions({ @@ -699,25 +712,20 @@ export const ModelSelector: React.FC = ({ `Timed out restoring ACP session options for ${acpClientId}`, ); succeeded = true; - if (requestId !== acpOptionsLoadRequestRef.current) return; + if (requestId !== acpOptionsLoadRequestRef.current || !scope.isCurrent()) return; setAcpOptions(options); setAcpOptionsLoadState('ready'); syncAcpContextUsageToStore(sessionId, options); } catch (error) { - if (requestId !== acpOptionsLoadRequestRef.current) return; + failure = error instanceof Error ? error.message : String(error); + if (requestId !== acpOptionsLoadRequestRef.current || !scope.isCurrent()) return; log.warn('Failed to load ACP session model options', { sessionId, acpClientId, error }); setAcpOptionsLoadState('error'); } finally { if (shouldShowRestoreToast) { - window.dispatchEvent(new CustomEvent('openbitfun:acp-session-creation', { - detail: { - phase: 'finish', - clientId: acpClientId, - action: 'restore', - requestId: restoreRequestId, - succeeded, - }, - })); + emitAcpSessionStartup({ ...startup, phase: 'finish', + succeeded: succeeded || requestId !== acpOptionsLoadRequestRef.current, error: failure }); + if (acpStartupDismissRef.current === dismissStartup) acpStartupDismissRef.current = null; } } }, [ @@ -730,6 +738,8 @@ export const ModelSelector: React.FC = ({ sessionId, activeSession?.config.workspaceId, activeSession?.workspaceId, + modelSelectionScopeKey, + deviceSurfaceScope, ]); useEffect(() => { @@ -738,14 +748,19 @@ export const ModelSelector: React.FC = ({ acpRestoreToastShownRef.current = null; setAcpOptions(null); setAcpOptionsLoadState('loading'); - }, [acpClientId, sessionId]); + }, [acpClientId, sessionId, deviceSurfaceScope.epoch]); useEffect(() => { acpOptionsRef.current = acpOptions; }, [acpOptions]); useEffect(() => { - loadAcpOptions(); + void loadAcpOptions(); + return () => { + acpOptionsLoadRequestRef.current += 1; + acpStartupDismissRef.current?.(); + acpStartupDismissRef.current = null; + }; }, [loadAcpOptions]); useEffect(() => { diff --git a/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx b/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx index 9aac9097e6..b8df8aaf37 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx @@ -215,6 +215,47 @@ describe('ModelSelector ACP mode picker', () => { expect(onAvailabilityChange).toHaveBeenLastCalledWith({ status: 'ready', canSend: true }); }); + it('retries failed initialization from the startup notification and ignores it after unmount', async () => { + const events: any[] = []; + const handler = (event: Event) => events.push((event as CustomEvent).detail); + window.addEventListener('openbitfun:acp-session-creation', handler); + try { + vi.mocked(ACPClientAPI.getSessionOptions).mockRejectedValueOnce(new Error('Agent initialize failed')); + await act(async () => root.render()); + const failed = events.find(event => event.phase === 'finish'); + expect(failed).toMatchObject({ succeeded: false, error: 'Agent initialize failed', action: 'restore' }); + vi.mocked(ACPClientAPI.getSessionOptions).mockResolvedValueOnce({ + currentModelId: 'remote', availableModels: [{ id: 'remote', name: 'Remote' }], configOptions: [], + }); + await act(async () => failed.retry()); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(2); + expect(events.filter(event => event.phase === 'start')).toHaveLength(2); + expect(events.at(-1)).toMatchObject({ phase: 'finish', succeeded: true }); + act(() => root.render(null)); + await failed.retry(); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(2); + } finally { + window.removeEventListener('openbitfun:acp-session-creation', handler); + } + }); + + it('dismisses pending startup feedback when its session view is unmounted', async () => { + const events: any[] = []; + const handler = (event: Event) => events.push((event as CustomEvent).detail); + window.addEventListener('openbitfun:acp-session-creation', handler); + let resolve!: (options: AcpSessionOptions) => void; + try { + vi.mocked(ACPClientAPI.getSessionOptions).mockReturnValueOnce(new Promise(done => { resolve = done; })); + await act(async () => root.render()); + act(() => root.render(null)); + expect(events.at(-1)).toMatchObject({ phase: 'finish', cancelled: true, requestId: events[0].requestId }); + await act(async () => resolve({ availableModels: [], configOptions: [] })); + expect(events.at(-1)).toMatchObject({ phase: 'finish', succeeded: true }); + } finally { + window.removeEventListener('openbitfun:acp-session-creation', handler); + } + }); + it('preserves cached ACP information when a background refresh fails', async () => { await renderWithOptions([], { currentModelId: 'remote-model', @@ -262,6 +303,24 @@ describe('ModelSelector ACP mode picker', () => { expect(trigger?.hasAttribute('aria-busy')).toBe(false); }); + it.each(['local', 'peer-b'])('reloads the same session under a new %s activation and rejects stale options', async surfaceId => { + let resolvePrevious!: (options: AcpSessionOptions) => void; + vi.mocked(ACPClientAPI.getSessionOptions) + .mockReturnValueOnce(new Promise(resolve => { resolvePrevious = resolve; })) + .mockResolvedValueOnce({ + currentModelId: 'fresh-model', availableModels: [{ id: 'fresh-model', name: 'Fresh Model' }], configOptions: [], + }); + await act(async () => root.render()); + await act(async () => { activateSurface(surfaceId); }); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(2); + await act(async () => resolvePrevious({ + currentModelId: 'old-model', availableModels: [{ id: 'old-model', name: 'Old Model' }], configOptions: [], + })); + const trigger = container.querySelector('[data-testid="chat-model-selector-btn"]'); + expect(trigger?.textContent).toContain('Fresh Model'); + expect(trigger?.textContent).not.toContain('Old Model'); + }); + it('renders the mode as the whole picker when the agent offers no models', async () => { await renderWithOptions([MODE_OPTION]); diff --git a/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.test.ts b/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.test.ts index 64aaefbe91..375e823d9b 100644 --- a/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.test.ts +++ b/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.test.ts @@ -1,8 +1,18 @@ -import { describe, expect, it } from 'vitest'; +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, createElement } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; -import type { AcpAvailableCommand } from '@/infrastructure/api/service-api/ACPClientAPI'; +import { ACPClientAPI, type AcpAvailableCommand } from '@/infrastructure/api/service-api/ACPClientAPI'; import { acpSessionRef, acpSlashCommandText } from '../utils/acpSession'; -import { filterSlashCommands } from './useAcpSlashCommands'; +import { filterSlashCommands, useAcpSlashCommands } from './useAcpSlashCommands'; + +vi.mock('@/infrastructure/api/service-api/ACPClientAPI', () => ({ + ACPClientAPI: { getSessionCommands: vi.fn(), onAvailableCommandsUpdated: vi.fn() }, +})); + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; const commands: AcpAvailableCommand[] = [ { name: 'compact', description: 'Compact the conversation context' }, @@ -10,6 +20,52 @@ const commands: AcpAvailableCommand[] = [ { name: 'create_plan', description: 'Draft an execution plan', inputHint: 'what to plan' }, ]; +describe('ACP command subscriptions', () => { + let root: Root; + let container: HTMLDivElement; + const session = { sessionId: 'same-session', clientId: 'codex', workspaceId: 'same-workspace' }; + function View() { + const { commands: list } = useAcpSlashCommands(session); + return createElement('div', null, list.map(command => command.name).join(',')); + } + beforeEach(() => { + resetDeviceSurfaceForTest(); + vi.clearAllMocks(); + vi.mocked(ACPClientAPI.onAvailableCommandsUpdated).mockReturnValue(vi.fn()); + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + }); + afterEach(() => { + act(() => root.unmount()); + container.remove(); + }); + + it('reloads commands and subscribes again when devices have identical session IDs', async () => { + vi.mocked(ACPClientAPI.getSessionCommands).mockResolvedValueOnce(commands) + .mockResolvedValueOnce([{ name: 'peer-command', description: 'Peer' }]); + await act(async () => root.render(createElement(View))); + expect(container.textContent).toContain('compact'); + await act(async () => { activateSurface('peer-b'); }); + expect(ACPClientAPI.getSessionCommands).toHaveBeenCalledTimes(2); + expect(ACPClientAPI.onAvailableCommandsUpdated).toHaveBeenCalledTimes(2); + expect(container.textContent).toBe('peer-command'); + const oldCallback = vi.mocked(ACPClientAPI.onAvailableCommandsUpdated).mock.calls[0][0]; + act(() => oldCallback({ sessionId: session.sessionId, clientId: session.clientId, commands })); + expect(container.textContent).toBe('peer-command'); + }); + + it('does not overwrite the new device commands with an old pending read', async () => { + let resolve!: (value: AcpAvailableCommand[]) => void; + vi.mocked(ACPClientAPI.getSessionCommands).mockReturnValueOnce(new Promise(done => { resolve = done; })) + .mockResolvedValueOnce([{ name: 'peer-command', description: 'Peer' }]); + await act(async () => root.render(createElement(View))); + await act(async () => { activateSurface('peer-b'); }); + await act(async () => resolve(commands)); + expect(container.textContent).toBe('peer-command'); + }); +}); + describe('filterSlashCommands', () => { it('returns all commands for an empty query', () => { expect(filterSlashCommands(commands, '')).toHaveLength(3); diff --git a/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts b/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts index 988ee49d3a..f4b22b1a0a 100644 --- a/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts +++ b/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts @@ -1,4 +1,5 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState, useSyncExternalStore } from 'react'; +import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; import { ACPClientAPI, @@ -23,7 +24,7 @@ export function filterSlashCommands( export function useAcpSlashCommands( acpSession: AcpSessionRef | null, ): { commands: AcpAvailableCommand[] } { - const [commands, setCommands] = useState([]); + const scope = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope); const sessionId = acpSession?.sessionId ?? null; const clientId = acpSession?.clientId ?? null; @@ -31,10 +32,12 @@ export function useAcpSlashCommands( const workspacePath = acpSession?.workspacePath; const remoteConnectionId = acpSession?.remoteConnectionId; const remoteSshHost = acpSession?.remoteSshHost; + const identity = scope.key(scope.epoch, sessionId, clientId, workspaceId, workspacePath, remoteConnectionId, remoteSshHost); + const [snapshot, setSnapshot] = useState<{ identity: string; commands: AcpAvailableCommand[] }>({ identity, commands: [] }); useEffect(() => { - setCommands([]); - }, [sessionId]); + setSnapshot({ identity, commands: [] }); + }, [identity]); useEffect(() => { if (!sessionId || !clientId) return; @@ -49,26 +52,26 @@ export function useAcpSlashCommands( remoteSshHost, }) .then((list) => { - if (!cancelled) setCommands(list); + if (!cancelled && scope.isCurrent()) setSnapshot({ identity, commands: list }); }) .catch(() => { - if (!cancelled) setCommands([]); + if (!cancelled && scope.isCurrent()) setSnapshot({ identity, commands: [] }); }); return () => { cancelled = true; }; - }, [sessionId, clientId, workspaceId, workspacePath, remoteConnectionId, remoteSshHost]); + }, [sessionId, clientId, workspaceId, workspacePath, remoteConnectionId, remoteSshHost, identity, scope]); useEffect(() => { if (!sessionId || !clientId) return; return ACPClientAPI.onAvailableCommandsUpdated((event) => { - if (event.sessionId === sessionId && event.clientId === clientId) { - setCommands(event.commands); + if (scope.isCurrent() && event.sessionId === sessionId && event.clientId === clientId) { + setSnapshot({ identity, commands: event.commands }); } }); - }, [sessionId, clientId]); + }, [sessionId, clientId, identity, scope]); - return { commands }; + return { commands: snapshot.identity === identity ? snapshot.commands : [] }; } diff --git a/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts b/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts index 1855c0227d..e62e5264aa 100644 --- a/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts +++ b/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts @@ -227,6 +227,79 @@ describe('FlowChatManager initialization', () => { } }); + it('deduplicates pending ACP creation and emits a visible lifecycle before the backend settles', async () => { + storeMocks.store = { registerPersistUnreadCompletionCallback: vi.fn(), createSession: vi.fn() }; + const deferred = createDeferred(); + storeMocks.createAcpSession.mockReturnValue(deferred.promise); + storeMocks.loadSessionMetadata.mockResolvedValue({ sessionId: 'created', customMetadata: {} }); + const events: any[] = []; + const handler = (event: Event) => events.push((event as CustomEvent).detail); + window.addEventListener('openbitfun:acp-session-creation', handler); + const manager = FlowChatManager.getInstance(); + try { + const config = { workspaceId: 'repo', workspacePath: '/repo', remoteConnectionId: 'ssh-a' }; + const first = manager.createAcpChatSession('codex', config); + const second = manager.createAcpChatSession('codex', { ...config }); + await flushAsyncWork(); + expect(storeMocks.createAcpSession).toHaveBeenCalledTimes(1); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ phase: 'start', clientId: 'codex', workspaceId: 'repo', action: 'create' }); + expect(events[0].scope.isCurrent()).toBe(true); + expect(storeMocks.store.createSession).not.toHaveBeenCalled(); + deferred.resolve({ sessionId: 'created', sessionName: 'Session', agentType: 'acp:codex' }); + await expect(Promise.all([first, second])).resolves.toEqual(['created', 'created']); + expect(events[1]).toMatchObject({ requestId: events[0].requestId, phase: 'finish', succeeded: true }); + } finally { + window.removeEventListener('openbitfun:acp-session-creation', handler); + manager.destroy(); + } + }); + + it('reports ACP startup errors and releases the pending entry for retry', async () => { + storeMocks.store = { registerPersistUnreadCompletionCallback: vi.fn(), createSession: vi.fn() }; + storeMocks.createAcpSession.mockRejectedValue(new Error('Adapter could not start')); + const events: any[] = []; + const handler = (event: Event) => events.push((event as CustomEvent).detail); + window.addEventListener('openbitfun:acp-session-creation', handler); + const manager = FlowChatManager.getInstance(); + try { + await expect(manager.createAcpChatSession('codex', { workspaceId: 'repo', workspacePath: '/repo' })) + .rejects.toThrow('Adapter could not start'); + expect(events[1]).toMatchObject({ phase: 'finish', succeeded: false, error: 'Adapter could not start' }); + await expect(events[1].retry()).rejects.toThrow('Adapter could not start'); + expect(storeMocks.createAcpSession).toHaveBeenCalledTimes(2); + expect(events[2].requestId).not.toBe(events[0].requestId); + } finally { + window.removeEventListener('openbitfun:acp-session-creation', handler); + manager.destroy(); + } + }); + + it('does not reuse or publish ACP creation across device activations', async () => { + storeMocks.store = { registerPersistUnreadCompletionCallback: vi.fn(), createSession: vi.fn() }; + const deferred = createDeferred(); + storeMocks.createAcpSession.mockReturnValue(deferred.promise); + storeMocks.loadSessionMetadata.mockResolvedValue({ sessionId: 'created', customMetadata: {} }); + const manager = FlowChatManager.getInstance(); + try { + const config = { workspaceId: 'repo', workspacePath: '/repo' }; + const old = manager.createAcpChatSession('codex', config); + const oldRejection = expect(old).rejects.toSatisfy(isSurfaceChangedError); + await flushAsyncWork(); + activateSurface('peer-b'); + activateSurface('local'); + const current = manager.createAcpChatSession('codex', config); + await flushAsyncWork(); + expect(storeMocks.createAcpSession).toHaveBeenCalledTimes(2); + deferred.resolve({ sessionId: 'created', sessionName: 'Session', agentType: 'acp:codex' }); + await oldRejection; + await current; + expect(storeMocks.store.createSession).toHaveBeenCalledTimes(1); + } finally { + manager.destroy(); + } + }); + it('creates one empty Claw session when reinitializing a reset workspace', async () => { storeMocks.store = { registerPersistUnreadCompletionCallback: vi.fn(), diff --git a/src/web-ui/src/flow_chat/services/FlowChatManager.ts b/src/web-ui/src/flow_chat/services/FlowChatManager.ts index 59a00f0bdd..1a57310944 100644 --- a/src/web-ui/src/flow_chat/services/FlowChatManager.ts +++ b/src/web-ui/src/flow_chat/services/FlowChatManager.ts @@ -9,6 +9,7 @@ import { requireSessionWorkspaceId } from '../utils/sessionWorkspace'; */ import { processingStatusManager } from './ProcessingStatusManager'; +import { createAcpStartupRequestId, emitAcpSessionStartup } from './acpSessionStartup'; import { FlowChatStore } from '../store/FlowChatStore'; import { useModernFlowChatStore } from '../store/modernFlowChatStore'; import { usePromptSuggestionStore } from '../store/promptSuggestionStore'; @@ -101,6 +102,7 @@ type FlowChatSendMessageOptions = Pick< const EVENT_LISTENER_RETRY_MS = 2000; export class FlowChatManager { + private acpCreationRequests = new Map>(); private static instance: FlowChatManager | null = null; private context: FlowChatContext; private eventListenerInitialized = false; @@ -622,23 +624,39 @@ export class FlowChatManager { async createAcpChatSession(clientId: string, config: SessionConfig = {}): Promise { const surfaceScope = getActiveSurfaceScope(); - const titleDescriptor = createDefaultSessionTitleDescriptor((key, options) => i18nService.t(key, options)); - // The workspace ID is the session's identity; the path is the ACP - // client's execution root and is only kept as an IO projection. - const workspaceId = requireSessionWorkspaceId({ config }); - const workspacePath = - config.workspacePath?.trim() || - this.context.currentWorkspacePath?.trim(); - if (!workspacePath) { - throw new Error('Workspace path is required to create an ACP session'); - } - - window.dispatchEvent(new CustomEvent('openbitfun:acp-session-creation', { - detail: { phase: 'start', clientId, action: 'create' }, - })); + const key = surfaceScope.key(surfaceScope.epoch, config.workspaceId, config.workspacePath, + config.remoteConnectionId, config.remoteSshHost, clientId); + const existing = this.acpCreationRequests.get(key); + if (existing) return existing; + // Install the in-flight entry before the lifecycle event can trigger another caller. + const pending = Promise.resolve().then(() => this.createAcpChatSessionOnce(clientId, config, surfaceScope)) + .finally(() => this.acpCreationRequests.delete(key)); + this.acpCreationRequests.set(key, pending); + return pending; + } + + private async createAcpChatSessionOnce( + clientId: string, config: SessionConfig, surfaceScope: ReturnType, + ): Promise { + surfaceScope.assertCurrent('create ACP session'); + const startup = { + requestId: createAcpStartupRequestId(), clientId, action: 'create' as const, + scope: surfaceScope, workspaceId: config.workspaceId, + retry: async () => { + surfaceScope.assertCurrent('retry ACP session creation'); + return this.createAcpChatSession(clientId, config); + }, + }; + emitAcpSessionStartup({ ...startup, phase: 'start' }); let succeeded = false; + let failure: string | undefined; try { + const titleDescriptor = createDefaultSessionTitleDescriptor((key, options) => i18nService.t(key, options)); + // The workspace ID owns identity; the path is only an execution projection. + const workspaceId = requireSessionWorkspaceId({ config }); + const workspacePath = config.workspacePath?.trim() || this.context.currentWorkspacePath?.trim(); + if (!workspacePath) throw new Error('Workspace path is required to create an ACP session'); const response = await ACPClientAPI.createFlowSession({ clientId, workspaceId, @@ -673,10 +691,11 @@ export class FlowChatManager { succeeded = true; return response.sessionId; + } catch (error) { + failure = error instanceof Error ? error.message : String(error); + throw error; } finally { - window.dispatchEvent(new CustomEvent('openbitfun:acp-session-creation', { - detail: { phase: 'finish', clientId, action: 'create', succeeded }, - })); + emitAcpSessionStartup({ ...startup, phase: 'finish', succeeded, error: failure }); } } diff --git a/src/web-ui/src/flow_chat/services/acpSessionStartup.ts b/src/web-ui/src/flow_chat/services/acpSessionStartup.ts new file mode 100644 index 0000000000..bcc0894224 --- /dev/null +++ b/src/web-ui/src/flow_chat/services/acpSessionStartup.ts @@ -0,0 +1,26 @@ +import type { SurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; + +let requestSequence = 0; + +/** Local correlation only; also works in HTTP Web hosts without crypto.randomUUID. */ +export function createAcpStartupRequestId(): string { + return `acp-startup-${Date.now()}-${++requestSequence}`; +} + +/** Presentation-only lifecycle; host commands and persisted sessions keep their existing contracts. */ +export interface AcpSessionStartupDetail { + phase: 'start' | 'finish'; + action: 'create' | 'restore'; + requestId: string; + clientId: string; + scope: SurfaceScope; + workspaceId?: string; + succeeded?: boolean; + cancelled?: boolean; + error?: string; + retry?: () => Promise; +} + +export function emitAcpSessionStartup(detail: AcpSessionStartupDetail): void { + window.dispatchEvent(new CustomEvent('openbitfun:acp-session-creation', { detail })); +} diff --git a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts index 57d9c55fa4..a83fe79192 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts @@ -1,10 +1,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; const invokeMock = vi.hoisted(() => vi.fn()); +const listenMock = vi.hoisted(() => vi.fn()); vi.mock('./ApiClient', () => ({ api: { invoke: invokeMock, + listen: listenMock, }, })); @@ -26,10 +28,89 @@ function createDeferred() { describe('ACPClientAPI client list startup cache', () => { beforeEach(() => { invokeMock.mockReset(); + listenMock.mockReset().mockReturnValue(vi.fn()); vi.useRealTimers(); vi.stubGlobal('window', { dispatchEvent: vi.fn() }); }); + const sessionRequest = { clientId: 'codex', sessionId: 'session-1', workspaceId: 'repo', workspacePath: '/repo' }; + + it('publishes commands from a successful metadata retry to existing subscribers', async () => { + const ACPClientAPI = await importApi(); + const callback = vi.fn(); + const unsubscribe = ACPClientAPI.onAvailableCommandsUpdated(callback); + const commands = [{ name: 'help', description: 'Help' }]; + invokeMock.mockRejectedValueOnce(new Error('Agent failed')) + .mockResolvedValue({ availableModels: [], configOptions: [], availableCommands: commands }); + await expect(ACPClientAPI.getSessionCommands(sessionRequest)).rejects.toThrow('Agent failed'); + await ACPClientAPI.getSessionOptions(sessionRequest); + expect(callback).toHaveBeenCalledWith({ sessionId: 'session-1', clientId: 'codex', commands }); + unsubscribe(); + await ACPClientAPI.getSessionOptions(sessionRequest); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('shares one initial metadata read for models and slash commands, including an empty command list', async () => { + const ACPClientAPI = await importApi(); + const deferred = createDeferred(); + invokeMock.mockReturnValueOnce(deferred.promise); + const options = ACPClientAPI.getSessionOptions(sessionRequest); + const commands = ACPClientAPI.getSessionCommands({ ...sessionRequest }); + expect(invokeMock).toHaveBeenCalledTimes(1); + deferred.resolve({ availableModels: [], configOptions: [], availableCommands: [] }); + await expect(commands).resolves.toEqual([]); + await options; + expect(invokeMock).toHaveBeenCalledTimes(1); + }); + + it('falls back to the original command endpoint for older hosts', async () => { + const ACPClientAPI = await importApi(); + invokeMock.mockResolvedValueOnce({ availableModels: [], configOptions: [] }) + .mockResolvedValueOnce([{ name: 'help', description: 'Help' }]); + await expect(ACPClientAPI.getSessionCommands(sessionRequest)).resolves.toEqual([{ name: 'help', description: 'Help' }]); + expect(invokeMock).toHaveBeenNthCalledWith(2, 'get_acp_session_commands', { request: sessionRequest }); + }); + + it('releases failed metadata requests so initialization can retry', async () => { + const ACPClientAPI = await importApi(); + invokeMock.mockRejectedValueOnce(new Error('Agent failed')).mockResolvedValueOnce({ availableCommands: [] }); + await expect(ACPClientAPI.getSessionOptions(sessionRequest)).rejects.toThrow('Agent failed'); + await expect(ACPClientAPI.getSessionCommands(sessionRequest)).resolves.toEqual([]); + expect(invokeMock).toHaveBeenCalledTimes(2); + }); + + it('never runs the legacy fallback on another device after a metadata request settles late', async () => { + const ACPClientAPI = await importApi(); + const { activateSurface, isSurfaceChangedError } = await import('@/infrastructure/peer-device/deviceSurface'); + const deferred = createDeferred(); + invokeMock.mockReturnValueOnce(deferred.promise); + const pending = ACPClientAPI.getSessionCommands(sessionRequest); + const rejection = expect(pending).rejects.toSatisfy(isSurfaceChangedError); + activateSurface('peer-b'); + deferred.resolve({ availableModels: [], configOptions: [] }); + await rejection; + expect(invokeMock).toHaveBeenCalledTimes(1); + }); + + it('isolates metadata reads by remote workspace and activation, without retaining settled snapshots', async () => { + const ACPClientAPI = await importApi(); + const { activateSurface } = await import('@/infrastructure/peer-device/deviceSurface'); + const deferred = createDeferred(); + invokeMock.mockImplementation(() => deferred.promise); + const first = ACPClientAPI.getSessionOptions(sessionRequest); + const oldRejection = expect(first).rejects.toBeDefined(); + const remote = ACPClientAPI.getSessionOptions({ ...sessionRequest, remoteConnectionId: 'ssh-a' }); + const remoteRejection = expect(remote).rejects.toBeDefined(); + activateSurface('peer-b'); + activateSurface('local'); + const current = ACPClientAPI.getSessionOptions(sessionRequest); + expect(invokeMock).toHaveBeenCalledTimes(3); + deferred.resolve({ availableCommands: [] }); + await Promise.all([oldRejection, remoteRejection, current]); + await ACPClientAPI.getSessionOptions(sessionRequest); + expect(invokeMock).toHaveBeenCalledTimes(4); + }); + it.each(['clients', 'requirements'])('never reuses cached %s from another device', async (kind) => { const ACPClientAPI = await importApi(); const { activateSurface } = await import('@/infrastructure/peer-device/deviceSurface'); diff --git a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts index 7679896536..fc7ae16cec 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts @@ -172,6 +172,8 @@ export interface AcpContextUsage { } export interface AcpSessionOptions { + /** Included by newer hosts to share the initial metadata read. Missing means use the commands endpoint. */ + availableCommands?: AcpAvailableCommand[]; currentModelId?: string; availableModels: AcpSessionModelOption[]; modelConfigId?: string; @@ -243,6 +245,8 @@ const requirementProbeInFlight = new Map(); export class ACPClientAPI { + private static sessionOptionsInFlight = new Map>(); + private static commandSnapshotListeners = new Set<(event: AcpAvailableCommandsUpdatedEvent) => void>(); private static cacheScope = getActiveSurfaceScope(); private static clientListCache: { @@ -454,16 +458,38 @@ export class ACPClientAPI { return api.invoke('cancel_acp_dialog_turn', { request }); } - static async getSessionOptions( + static getSessionOptions( request: GetAcpSessionOptionsRequest ): Promise { - return api.invoke('get_acp_session_options', { request }); + const scope = getActiveSurfaceScope(); + const key = scope.key(scope.epoch, request.sessionId, request.clientId, request.workspaceId, + request.workspacePath, request.remoteConnectionId, request.remoteSshHost); + const existing = this.sessionOptionsInFlight.get(key); + if (existing) return existing; + const pending = api.invoke('get_acp_session_options', { request }) + .then(options => { + scope.assertCurrent('load ACP session metadata'); + if (Array.isArray(options.availableCommands)) { + const event = { sessionId: request.sessionId, clientId: request.clientId, commands: options.availableCommands }; + this.commandSnapshotListeners.forEach(listener => listener(event)); + } + return options; + }).finally(() => this.sessionOptionsInFlight.delete(key)); + this.sessionOptionsInFlight.set(key, pending); + return pending; } static async getSessionCommands( request: GetAcpSessionOptionsRequest ): Promise { - return api.invoke('get_acp_session_commands', { request }); + const scope = getActiveSurfaceScope(); + const options = await this.getSessionOptions(request); + scope.assertCurrent('load ACP session commands'); + if (Array.isArray(options.availableCommands)) return options.availableCommands; + // Older hosts do not advertise the combined snapshot. Keep their existing path. + const commands = await api.invoke('get_acp_session_commands', { request }); + scope.assertCurrent('publish ACP session commands'); + return commands; } static async setSessionModel( @@ -481,10 +507,19 @@ export class ACPClientAPI { static onAvailableCommandsUpdated( callback: (event: AcpAvailableCommandsUpdatedEvent) => void ): () => void { - return api.listen( + const scope = getActiveSurfaceScope(); + const listener = (event: AcpAvailableCommandsUpdatedEvent) => { + if (scope.isCurrent()) callback(event); + }; + this.commandSnapshotListeners.add(listener); + const unsubscribe = api.listen( 'agentic://acp-available-commands-updated', - callback + listener ); + return () => { + this.commandSnapshotListeners.delete(listener); + unsubscribe(); + }; } static onPlanUpdated(callback: (event: AcpPlanUpdatedEvent) => void): () => void { diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index 764cd4cecd..95edf609cb 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -652,7 +652,9 @@ "revealFailed": "Failed to reveal workspace folder", "copyPathFailed": "Failed to copy path", "createSessionFailed": "Failed to create session", - "startingAcpSession": "Session starting", + "startingAcpSession": "Starting agent; the first start may need to prepare its adapter…", + "initializingAcpSession": "Initializing session and loading models and commands…", + "retryAcpSession": "Retry", "acpSessionStarted": "Session started", "acpSessionStartFailed": "Session failed to start", "renameFailed": "Failed to rename project", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 6cbfbcb886..74e54e766e 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -652,7 +652,9 @@ "revealFailed": "打开工作区目录失败", "copyPathFailed": "复制路径失败", "createSessionFailed": "新建会话失败", - "startingAcpSession": "会话启动中", + "startingAcpSession": "正在启动 Agent,首次启动可能需要准备适配器…", + "initializingAcpSession": "正在初始化会话并加载模型和命令…", + "retryAcpSession": "重试", "acpSessionStarted": "会话启动完成", "acpSessionStartFailed": "会话启动失败", "renameFailed": "重命名项目失败", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index 607835a9db..eaab639de0 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -652,7 +652,9 @@ "revealFailed": "開啟工作區目錄失敗", "copyPathFailed": "複製路徑失敗", "createSessionFailed": "新增會話失敗", - "startingAcpSession": "會話啟動中", + "startingAcpSession": "正在啟動 Agent,首次啟動可能需要準備配接器…", + "initializingAcpSession": "正在初始化會話並載入模型和命令…", + "retryAcpSession": "重試", "acpSessionStarted": "會話啟動完成", "acpSessionStartFailed": "會話啟動失敗", "renameFailed": "重新命名專案失敗",