Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/crates/interfaces/acp/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -42,10 +46,14 @@ 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,
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.
55 changes: 45 additions & 10 deletions src/crates/interfaces/acp/src/client/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -248,15 +249,22 @@ impl AcpClientService {
client_id: &str,
session_name: Option<String>,
) -> OpenBitFunResult<CreateAcpFlowSessionRecordResponse> {
self.session_persistence
let started_at = Instant::now();
let result = self
.session_persistence
.create_flow_session_record(
session_storage_path,
workspace_id,
workspace_path,
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<Self>) -> OpenBitFunResult<()> {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand All @@ -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) => {
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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(())
}
Expand Down Expand Up @@ -949,6 +969,7 @@ impl AcpClientService {
session_storage_path: Option<PathBuf>,
openbitfun_session_id: String,
) -> OpenBitFunResult<AcpSessionOptions> {
let started_at = Instant::now();
let resolved = self
.resolve_or_create_client_session(
client_id,
Expand All @@ -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(
Expand Down Expand Up @@ -1566,7 +1595,13 @@ impl AcpClientService {
where
F: Future<Output = Result<T, Error>>,
{
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!(
Expand Down
26 changes: 26 additions & 0 deletions src/crates/interfaces/acp/src/client/session_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ impl From<agent_client_protocol::schema::PlanEntry> 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<Vec<AcpAvailableCommand>>,
#[serde(default)]
pub current_model_id: Option<String>,
#[serde(default)]
Expand Down Expand Up @@ -171,6 +174,7 @@ pub(super) fn session_options_from_state(
model_config_id: None,
config_options: session_config_options,
context_usage,
..Default::default()
};
}

Expand All @@ -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()
};
}

Expand Down Expand Up @@ -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")]);
Expand Down
10 changes: 10 additions & 0 deletions src/web-ui/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
110 changes: 110 additions & 0 deletions src/web-ui/src/app/layout/AcpSessionNotifications.test.tsx
Original file line number Diff line number Diff line change
@@ -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> = {}): 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(<><AcpSessionNotifications /><NotificationContainer /></>));
});

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<string>(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);
});
});
Loading
Loading