From 930612716b6ce9e29904c5f70b820b1003299f24 Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Mon, 16 Nov 2026 17:07:26 +0800 Subject: [PATCH 1/2] fix(acp): recover queued turns and keep metadata readable Restore the running ACP turn and drain queued input after frontend reload. Allocate a storage index for replayed turns so the original response is saved. Serve session metadata from a watch snapshot while a request owns the protocol receiver. Cover live updates, queue ordering and reconnects in the controlled ACP fixture. --- docs/architecture/session-projection.md | 29 ++ src/apps/desktop/AGENTS-CN.md | 5 + src/apps/desktop/AGENTS.md | 5 + src/apps/desktop/src/api/acp_client_api.rs | 112 ++++- src/apps/desktop/src/api/agentic_api.rs | 40 +- src/apps/desktop/src/lib.rs | 9 + src/apps/desktop/src/runtime/mod.rs | 5 + .../src/runtime/session_application.rs | 53 ++- .../src/runtime/session_host_effects.rs | 40 ++ src/crates/interfaces/acp/AGENTS-CN.md | 11 + src/crates/interfaces/acp/AGENTS.md | 15 + .../interfaces/acp/src/client/execution.rs | 410 ++++++++++++++++++ .../interfaces/acp/src/client/manager.rs | 283 ++++++++++-- src/crates/interfaces/acp/src/client/mod.rs | 4 + .../components/PendingQueuePanel.test.tsx | 20 +- .../EventHandlerModule.test.ts | 33 ++ .../flow-chat-manager/EventHandlerModule.ts | 11 +- .../flow-chat-manager/MessageModule.test.ts | 13 + .../flow-chat-manager/MessageModule.ts | 23 +- .../PeerSessionRefreshModule.test.ts | 14 +- .../PeerSessionRefreshModule.ts | 35 +- .../state-machine/SessionStateMachine.ts | 1 + .../src/flow_chat/store/FlowChatStore.test.ts | 50 ++- .../src/flow_chat/store/FlowChatStore.ts | 59 ++- .../api/service-api/ACPClientAPI.ts | 2 + .../api/service-api/AgentAPI.ts | 2 + tests/e2e/AGENTS-CN.md | 9 + tests/e2e/AGENTS.md | 13 + tests/e2e/fixtures/controlled-acp-agent.mjs | 93 ++++ tests/e2e/helpers/acp-queue-observer.mjs | 53 +++ .../e2e/page-objects/AcpQueueRecoveryPage.mjs | 48 ++ tests/e2e/scripts/run-acp-queue-recovery.mjs | 278 ++++++++++++ 32 files changed, 1682 insertions(+), 96 deletions(-) create mode 100644 src/crates/interfaces/acp/src/client/execution.rs create mode 100644 tests/e2e/fixtures/controlled-acp-agent.mjs create mode 100644 tests/e2e/helpers/acp-queue-observer.mjs create mode 100644 tests/e2e/page-objects/AcpQueueRecoveryPage.mjs create mode 100644 tests/e2e/scripts/run-acp-queue-recovery.mjs diff --git a/docs/architecture/session-projection.md b/docs/architecture/session-projection.md index e04b01edc0..212ca0bc00 100644 --- a/docs/architecture/session-projection.md +++ b/docs/architecture/session-projection.md @@ -44,6 +44,35 @@ at delayed delivery time; replacement listeners cannot receive old events. A Session restore fences only that Session. Events buffered for other Sessions during the read must be flushed, never cleared with the restored projection. +### ACP execution authority + +Desktop ACP prompts record their portable lifecycle, text and tool facts in the +same host journal before delivery to local views and Peer host streams. The ACP +service owns prompt admission and terminal facts independently of its long-held +protocol session mutex. Repeated admission of the same Turn/input is idempotent; +a different Turn cannot replace a running or cancelling prompt. + +`restore_session_view` advertises this additive authority with +`executionProjection: "acp"`. Its state comes from the ACP owner, not the native +coordinator's idle shell. Both active and terminal ACP journal snapshots can be +replayed through the existing Session read fence. A terminal replay must clear +the repaired gap and wake the queue after the fence settles. A reloaded ACP queue +waits for history/execution hydration before using an idle frontend machine. +When replay reconstructs an ACP turn, the hydrated history supplies its storage +index so terminal output is saved with the conversation. +Older hosts without this marker keep persisted-history loading; a required ACP +execution repair fails visibly and retains queued input rather than claiming +that the native idle shell repaired it. CLI Peer hosts still explicitly reject +ACP client-host operations; this change does not add that capability. + +ACP model/options/command reads use a session-scoped metadata watch snapshot +while the protocol receiver is owned by a running request. The single receiver +publishes command, configuration and context updates before their frontend +notifications. Cold reads wait for initialization/publication; idle reads retain +the existing bounded notification drain. Model/config mutations publish accepted +state before returning. This is an in-memory observation projection, with no wire +or persisted-shape changes; reconnect creates a fresh session snapshot. + ## The problem this replaces Seven independent writers currently produce a Session's on-screen state: diff --git a/src/apps/desktop/AGENTS-CN.md b/src/apps/desktop/AGENTS-CN.md index 88de17453b..03d916628a 100644 --- a/src/apps/desktop/AGENTS-CN.md +++ b/src/apps/desktop/AGENTS-CN.md @@ -76,6 +76,11 @@ pnpm run prepare:dsh-profile # 可选:本地 DeepSeek Harness 会话 ## 验证 +验证 ACP 取消请求兼容性时,运行 +`cargo test --locked -p openbitfun-desktop --no-default-features --lib acp_cancel_request`, +覆盖旧请求反序列化与往返,以及可选的 Turn 绑定字段。 +ACP 队列恢复的原生验收脚本见 `tests/e2e/AGENTS.md`。 + ```bash cargo check -p openbitfun-desktop && cargo test -p openbitfun-desktop ``` diff --git a/src/apps/desktop/AGENTS.md b/src/apps/desktop/AGENTS.md index 86bd5b5193..be286fb34a 100644 --- a/src/apps/desktop/AGENTS.md +++ b/src/apps/desktop/AGENTS.md @@ -103,6 +103,11 @@ The `devtools` Cargo feature exists for debugging UI/UX in the desktop app. When ## Verification +For ACP cancellation request compatibility, run +`cargo test --locked -p openbitfun-desktop --no-default-features --lib acp_cancel_request`. +It covers legacy payload deserialization/round trips and the optional Turn binding. +Native ACP queue recovery uses the focused runner in `tests/e2e/AGENTS.md`. + Application updates use the official `tauri-plugin-updater` for discovery, download and signature verification. `src/update_maintenance` owns native authorization, publication/recovery and Windows process handoff; keep those diff --git a/src/apps/desktop/src/api/acp_client_api.rs b/src/apps/desktop/src/api/acp_client_api.rs index c2ab7a062a..4acee95aed 100644 --- a/src/apps/desktop/src/api/acp_client_api.rs +++ b/src/apps/desktop/src/api/acp_client_api.rs @@ -169,6 +169,8 @@ pub struct StartAcpDialogTurnRequest { pub struct CancelAcpDialogTurnRequest { pub session_id: String, pub client_id: String, + #[serde(default)] + pub turn_id: Option, /// Workspace identity; authoritative when present. #[serde(default)] pub workspace_id: Option, @@ -205,8 +207,55 @@ pub struct ProbeAcpClientRequirementsRequest { pub force_refresh: bool, } +// One ordered delivery task per admitted prompt; disconnecting a WebView +// never cancels it. Both local views and Peer host streams consume this path. +#[derive(Clone)] +struct AcpEventEmitter { + service: std::sync::Arc, + sender: tokio::sync::mpsc::UnboundedSender, +} + +impl AcpEventEmitter { + fn new(app: AppHandle, service: std::sync::Arc) -> Self { + let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + tokio::spawn(async move { + let transport = openbitfun_transport::TauriTransportAdapter::new(app); + while let Some(event) = receiver.recv().await { + crate::deliver_projected_event(&transport, event).await; + } + }); + Self { service, sender } + } + + fn emit( + &self, + name: &str, + mut payload: serde_json::Value, + ) -> Result<(), openbitfun_core::util::errors::OpenBitFunError> { + use openbitfun_core::util::errors::OpenBitFunError; + self.service + .record_dialog_event(name, &mut payload) + .map_err(OpenBitFunError::service)?; + self.publish(name, payload) + } + + fn publish( + &self, + name: &str, + payload: serde_json::Value, + ) -> Result<(), openbitfun_core::util::errors::OpenBitFunError> { + use openbitfun_core::util::errors::OpenBitFunError; + self.sender + .send(openbitfun_events::AgenticFrontendEvent { + event_name: name.into(), + payload, + }) + .map_err(|_| OpenBitFunError::service("ACP event delivery stopped")) + } +} + fn emit_acp_model_round_completed( - app_handle: &AppHandle, + app_handle: &AcpEventEmitter, session_id: &str, turn_id: &str, round_id: String, @@ -414,19 +463,19 @@ pub async fn start_acp_dialog_turn( None => (None, None, None), }; + let Some(start) = service.admit_dialog_turn( + &session_id, + &turn_id, + &request.client_id, + &user_input, + &original_user_input, + )? + else { + return Ok(()); + }; + let app_handle = AcpEventEmitter::new(app_handle, service.clone()); app_handle - .emit( - "agentic://dialog-turn-started", - serde_json::json!({ - "sessionId": session_id, - "turnId": turn_id, - "turnIndex": null, - "userInput": user_input, - "originalUserInput": original_user_input, - "userMessageMetadata": null, - "subagentParentInfo": null, - }), - ) + .publish("agentic://dialog-turn-started", start) .map_err(|e| e.to_string())?; tokio::spawn(async move { let mut current_round_id: Option = None; @@ -715,6 +764,7 @@ pub async fn cancel_acp_dialog_turn( &request.client_id, scope.map(|scope| scope.workspace_path), request.session_id, + request.turn_id.as_deref(), ) .await .map_err(|e| e.to_string()) @@ -905,3 +955,39 @@ pub async fn submit_acp_permission_response( .await .map_err(|e| e.to_string()) } + +#[cfg(test)] +mod tests { + use super::CancelAcpDialogTurnRequest; + use serde_json::json; + + #[test] + fn acp_cancel_request_preserves_legacy_payload_round_trip() { + let legacy = json!({ + "sessionId": "session-1", + "clientId": "controlled", + "workspacePath": "/workspace", + "remoteConnectionId": "remote-1" + }); + let request: CancelAcpDialogTurnRequest = serde_json::from_value(legacy.clone()).unwrap(); + assert!(request.turn_id.is_none()); + let encoded = serde_json::to_value(&request).unwrap(); + for (key, value) in legacy.as_object().unwrap() { + assert_eq!(&encoded[key], value); + } + let decoded: CancelAcpDialogTurnRequest = serde_json::from_value(encoded).unwrap(); + assert!(decoded.turn_id.is_none()); + assert_eq!(decoded.remote_connection_id.as_deref(), Some("remote-1")); + } + + #[test] + fn acp_cancel_request_round_trips_the_optional_turn_binding() { + let request: CancelAcpDialogTurnRequest = serde_json::from_value(json!({ + "sessionId": "session-1", "clientId": "controlled", "turnId": "turn-1" + })) + .unwrap(); + let decoded: CancelAcpDialogTurnRequest = + serde_json::from_value(serde_json::to_value(request).unwrap()).unwrap(); + assert_eq!(decoded.turn_id.as_deref(), Some("turn-1")); + } +} diff --git a/src/apps/desktop/src/api/agentic_api.rs b/src/apps/desktop/src/api/agentic_api.rs index c76e19cd35..c20193db28 100644 --- a/src/apps/desktop/src/api/agentic_api.rs +++ b/src/apps/desktop/src/api/agentic_api.rs @@ -621,6 +621,9 @@ pub struct RestoreSessionWithTurnsResponse { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct RestoreSessionViewResponse { + /// Additive capability/authority marker. Older hosts omit it. + #[serde(skip_serializing_if = "Option::is_none")] + pub execution_projection: Option<&'static str>, pub session: SessionResponse, pub turns: Vec, pub interaction_snapshot: SessionInteractionSnapshot, @@ -675,6 +678,16 @@ fn frontend_event_projection_snapshot( } } +fn enrich_acp_replay_event(name: &str, payload: &mut serde_json::Value) { + // ACP does not provide an absolute persisted Turn ordinal. Preserve the + // established live-wire absence rather than inventing ordinal zero. + if name == "agentic://dialog-turn-started" { + payload["turnIndex"] = serde_json::Value::Null; + } else if name == "agentic://model-round-started" { + payload["renderHints"] = serde_json::json!({"disableExploreGrouping":true}); + } +} + /// Incremental catch-up answer, in the same event shape the snapshot uses so a /// client applies both through one path. #[derive(Debug, Serialize)] @@ -3822,9 +3835,17 @@ pub async fn restore_session_view( let session = restored.session; let mut turns = restored.turns; let interaction_snapshot = restored.interaction_snapshot; - let runtime_event_snapshot = restored + let execution_projection = restored.execution_projection; + let mut runtime_event_snapshot = restored .runtime_event_snapshot .map(frontend_event_projection_snapshot); + if execution_projection == Some("acp") { + if let Some(snapshot) = runtime_event_snapshot.as_mut() { + for event in &mut snapshot.events { + enrich_acp_replay_event(&event.event_name, &mut event.payload); + } + } + } let current_context_usage = restored.current_context_usage; let total_turn_count = restored.total_turn_count; let turn_catalog = restored.turn_catalog; @@ -3876,6 +3897,7 @@ pub async fn restore_session_view( ); Ok(RestoreSessionViewResponse { + execution_projection, session: session_to_response_with_turn_count(session, total_turn_count), turns, interaction_snapshot, @@ -3913,7 +3935,7 @@ pub async fn load_session_event_backfill( runtime: State<'_, DesktopRuntimeContext>, request: LoadSessionEventBackfillRequest, ) -> Result { - Ok(session_event_backfill_to_response( + let mut response = session_event_backfill_to_response( runtime.session_application().session_events_since( &request.session_id, &request.stream_id, @@ -3922,7 +3944,19 @@ pub async fn load_session_event_backfill( runtime .session_application() .session_interaction_snapshot(&request.session_id), - )) + ); + if runtime + .session_application() + .has_acp_execution(&request.session_id) + { + if let Some(events) = response["events"].as_array_mut() { + for event in events { + let name = event["eventName"].as_str().unwrap_or_default().to_owned(); + enrich_acp_replay_event(&name, &mut event["payload"]); + } + } + } + Ok(response) } #[derive(Debug, Deserialize)] diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index fbe03d1f6d..da9d797e2e 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -2464,6 +2464,15 @@ async fn deliver_event_to_webview( attach_session_event_cursor(&mut projected.payload, cursor); } + deliver_projected_event(transport, projected).await; +} + +/// Final product delivery for native and ACP projections alike. ACP records +/// before enqueueing here; native events record after text coalescing above. +pub(crate) async fn deliver_projected_event( + transport: &TauriTransportAdapter, + projected: openbitfun_events::AgenticFrontendEvent, +) { for hub in api::remote_connect_api::host_stream_hubs().await { if let Some(session_id) = projected .payload diff --git a/src/apps/desktop/src/runtime/mod.rs b/src/apps/desktop/src/runtime/mod.rs index 549396aa75..9d4b001469 100644 --- a/src/apps/desktop/src/runtime/mod.rs +++ b/src/apps/desktop/src/runtime/mod.rs @@ -40,6 +40,11 @@ impl DesktopRuntimeContext { acp_client_service: Option>, session_event_journal: Arc, ) -> Result { + if let Some(service) = acp_client_service.as_ref() { + service.configure_execution_journal(Arc::new( + session_host_effects::AcpJournalAdapter(session_event_journal.clone()), + ))?; + } let host_effects = Arc::new(ProductionDesktopSessionHostEffects::new(acp_client_service)); let session_application = DesktopSessionApplication::build( coordinator, diff --git a/src/apps/desktop/src/runtime/session_application.rs b/src/apps/desktop/src/runtime/session_application.rs index 8ba66e6565..a0114f3395 100644 --- a/src/apps/desktop/src/runtime/session_application.rs +++ b/src/apps/desktop/src/runtime/session_application.rs @@ -17,7 +17,7 @@ use openbitfun_agent_runtime::sdk::{ SessionEventJournal, SessionEventProjectionSnapshot, SessionInteractionSnapshot, }; use openbitfun_core::agentic::coordination::{ConversationCoordinator, DialogScheduler}; -use openbitfun_core::agentic::core::Session; +use openbitfun_core::agentic::core::{ProcessingPhase, Session, SessionState}; use openbitfun_core::agentic::persistence::{SessionBranchResult, SessionMetadataPage}; use openbitfun_core::agentic::session::SessionViewRestoreTiming; use openbitfun_core::product_runtime::{CoreAgentRuntimeCompatibility, CoreProductAgentRuntime}; @@ -125,6 +125,7 @@ fn local_command_turn_record_request( #[derive(Debug)] pub(crate) struct DesktopSessionViewRestore { + pub execution_projection: Option<&'static str>, pub session: Session, pub turns: Vec, pub interaction_snapshot: SessionInteractionSnapshot, @@ -231,6 +232,15 @@ impl DesktopSessionScopeResolver { #[async_trait] pub(crate) trait DesktopSessionHostEffects: Send + Sync { async fn release_session(&self, session_id: &str); + fn supports_acp_projection(&self) -> bool { + false + } + fn acp_execution_snapshot( + &self, + _session_id: &str, + ) -> Option { + None + } } #[derive(Clone)] @@ -866,6 +876,12 @@ impl DesktopSessionApplication { .session_events_since(session_id, stream_id, cursor) } + pub(crate) fn has_acp_execution(&self, session_id: &str) -> bool { + self.host_effects + .acp_execution_snapshot(session_id) + .is_some() + } + pub(crate) async fn restore_session_view( &self, request: DesktopSessionScopeRequest, @@ -899,9 +915,41 @@ impl DesktopSessionApplication { .map_err(|error| DesktopSessionApplicationError::Core(error.to_string()))?; overlay_live_session_state(&mut session, live_session); let interaction_snapshot = self.agent_runtime.session_interaction_snapshot(session_id); - let runtime_event_snapshot = self + let mut runtime_event_snapshot = self .agent_runtime .session_event_projection_snapshot(session_id); + // Native coordinator state is not the execution authority for an + // external ACP prompt. Read its facts without acquiring its long-held + // protocol session mutex. The journal is shared with live delivery. + let execution_projection = if session.agent_type.starts_with("acp:") + && self.host_effects.supports_acp_projection() + { + if let Some(acp) = self.host_effects.acp_execution_snapshot(session_id) { + session.state = if acp.running { + SessionState::Processing { + current_turn_id: acp.projection.active_turn_id.clone().unwrap_or_default(), + phase: ProcessingPhase::Streaming, + } + } else { + SessionState::Idle + }; + runtime_event_snapshot = Some(SessionEventProjectionSnapshot { + session_id: acp.projection.session_id, + stream_id: acp.projection.stream_id, + cursor: acp.projection.cursor, + active_turn_id: acp.projection.active_turn_id, + events: acp.projection.events, + }); + } else { + // No prompt is owned by this host process. Do not revive a + // pre-restart execution from a persisted intermediate record. + session.state = SessionState::Idle; + runtime_event_snapshot = None; + } + Some("acp") + } else { + None + }; let current_context_usage = self .compatibility .load_persisted_session_metadata(&storage_path, session_id) @@ -910,6 +958,7 @@ impl DesktopSessionApplication { .and_then(|metadata| metadata.current_context_usage); timings.resolve_storage_path_duration_ms = resolve_storage_path_duration_ms; Ok(DesktopSessionViewRestore { + execution_projection, session, turns, interaction_snapshot, diff --git a/src/apps/desktop/src/runtime/session_host_effects.rs b/src/apps/desktop/src/runtime/session_host_effects.rs index fe281d3030..07d356ec1d 100644 --- a/src/apps/desktop/src/runtime/session_host_effects.rs +++ b/src/apps/desktop/src/runtime/session_host_effects.rs @@ -4,6 +4,33 @@ use async_trait::async_trait; use super::session_application::DesktopSessionHostEffects; +pub(super) struct AcpJournalAdapter(pub Arc); + +impl openbitfun_acp::client::AcpProjectionJournal for AcpJournalAdapter { + fn record( + &self, + event: &openbitfun_events::AgenticEvent, + ) -> Option { + self.0 + .record(event) + .map(|cursor| openbitfun_acp::client::AcpEventCursor { + stream_id: cursor.stream_id, + cursor: cursor.cursor, + }) + } + + fn snapshot(&self, session: &str) -> openbitfun_acp::client::AcpEventProjectionSnapshot { + let snapshot = self.0.snapshot(session); + openbitfun_acp::client::AcpEventProjectionSnapshot { + session_id: snapshot.session_id, + stream_id: snapshot.stream_id, + cursor: snapshot.cursor, + active_turn_id: snapshot.active_turn_id, + events: snapshot.events, + } + } +} + pub(super) struct ProductionDesktopSessionHostEffects { acp_client_service: Option>, } @@ -16,6 +43,19 @@ impl ProductionDesktopSessionHostEffects { #[async_trait] impl DesktopSessionHostEffects for ProductionDesktopSessionHostEffects { + fn supports_acp_projection(&self) -> bool { + self.acp_client_service.is_some() + } + + fn acp_execution_snapshot( + &self, + session_id: &str, + ) -> Option { + self.acp_client_service + .as_ref()? + .execution_snapshot(session_id) + } + async fn release_session(&self, session_id: &str) { if let Some(service) = self.acp_client_service.as_ref() { service.release_openbitfun_session(session_id).await; diff --git a/src/crates/interfaces/acp/AGENTS-CN.md b/src/crates/interfaces/acp/AGENTS-CN.md index f48b8e36de..2ad4df85c2 100644 --- a/src/crates/interfaces/acp/AGENTS-CN.md +++ b/src/crates/interfaces/acp/AGENTS-CN.md @@ -26,4 +26,15 @@ tool-card 投影,选择 Core Agent Runtime 与具体 SSH 能力;`server` 负 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::execution::tests ``` + +执行状态测试覆盖请求准入回执、按 Turn 绑定取消和实时事件与重放游标的一致性。 +ACP owner 先记录执行事件,再由宿主发布;执行快照查询不获取长请求持有的协议会话锁。 +Desktop 注入既有的会话事件日志,通过可选的 `executionProjection: "acp"` 恢复字段标明权威来源。 + +元数据并发验证: +`cargo test -p openbitfun-acp --no-default-features --features client,openbitfun-core/git --lib client::manager::tests::metadata_`。 +协议接收器仍串行持有;按会话保存的 watch 快照支持长请求或变更期间的读取。 +首次读取等待快照发布或初始化锁释放;模型、配置变更和流内元数据更新后发布新快照。 +空闲读取仍排空待处理通知;重建连接不得复用旧快照,不能增加第二个协议流读取者来解决阻塞。 diff --git a/src/crates/interfaces/acp/AGENTS.md b/src/crates/interfaces/acp/AGENTS.md index ca85d42db9..99f3e68b2b 100644 --- a/src/crates/interfaces/acp/AGENTS.md +++ b/src/crates/interfaces/acp/AGENTS.md @@ -47,6 +47,7 @@ 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 +cargo test -p openbitfun-acp --no-default-features --features client,openbitfun-core/git --lib client::execution::tests ``` The focused client prompt tests cover protocol errors, retry, cancellation, @@ -57,3 +58,17 @@ 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. + +For metadata concurrency, run +`cargo test -p openbitfun-acp --no-default-features --features client,openbitfun-core/git --lib client::manager::tests::metadata_`. +The protocol receiver remains serialized. A session-scoped watch snapshot serves +reads while a prompt or mutation owns it; cold readers wait for publication or +initialization-lock release. Publish after model/config changes and stream metadata +updates. Idle readers still drain pending notifications. Recreated connections +must not reuse an old snapshot. Do not solve this by adding a second stream reader. + +The execution tests cover prompt admission receipts, turn-bound cancellation, +and coherent live/replay cursors. The ACP owner records execution events before +the host publishes them and reads execution snapshots without the long-held +protocol session mutex. Desktop injects its existing session event journal; +the additive `executionProjection: "acp"` restore marker identifies that authority. diff --git a/src/crates/interfaces/acp/src/client/execution.rs b/src/crates/interfaces/acp/src/client/execution.rs new file mode 100644 index 0000000000..5027508052 --- /dev/null +++ b/src/crates/interfaces/acp/src/client/execution.rs @@ -0,0 +1,410 @@ +//! Host-owned execution facts for ACP prompts. Independent of the protocol +//! session mutex, which is held for the complete streaming request. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use openbitfun_events::AgenticEvent; +use serde_json::{json, Value}; + +/// Host-injected observation port. The ACP client does not select a Runtime +/// implementation; hosts adapt their existing ordered journal to these facts. +pub trait AcpProjectionJournal: Send + Sync { + fn record(&self, event: &AgenticEvent) -> Option; + fn snapshot(&self, session: &str) -> AcpEventProjectionSnapshot; +} + +#[derive(Debug, Clone)] +pub struct AcpEventCursor { + pub stream_id: String, + pub cursor: u64, +} + +#[derive(Debug, Clone)] +pub struct AcpEventProjectionSnapshot { + pub session_id: String, + pub stream_id: String, + pub cursor: u64, + pub active_turn_id: Option, + pub events: Vec, +} + +fn attach_cursor(payload: &mut Value, cursor: AcpEventCursor) { + payload["__openbitfunRuntimeStreamId"] = cursor.stream_id.into(); + payload["__openbitfunRuntimeEventCursor"] = cursor.cursor.into(); +} + +#[derive(PartialEq, Eq)] +struct SubmissionReceipt { + client: String, + input: String, + original_input: String, +} + +#[derive(Debug, Clone)] +pub struct AcpExecutionSnapshot { + pub running: bool, + pub cancelling: bool, + pub projection: AcpEventProjectionSnapshot, +} + +struct Execution { + turn_id: String, + running: bool, + cancelling: bool, + // Keep admission receipts for the lifetime of the ACP session, like its + // remote session handle. Explicit session release drops both. A frontend + // reload/retry must not submit an accepted prompt a second time. + receipts: HashMap, +} + +struct State { + journal: Option>, + sessions: HashMap, +} + +pub(super) struct AcpExecutions(Mutex); + +impl Default for AcpExecutions { + fn default() -> Self { + Self(Mutex::new(State { + journal: None, + sessions: HashMap::new(), + })) + } +} + +impl AcpExecutions { + pub(super) fn configure_journal( + &self, + journal: Arc, + ) -> Result<(), String> { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if !state.sessions.is_empty() { + return Err("Cannot replace the ACP journal after prompt admission".into()); + } + state.journal = Some(journal); + Ok(()) + } + + /// `None` is an identical, already accepted request, not a new prompt. + pub(super) fn admit( + &self, + session: &str, + turn: &str, + client: &str, + input: &str, + original_input: &str, + ) -> Result, String> { + if session.trim().is_empty() || turn.trim().is_empty() || client.trim().is_empty() { + return Err("ACP session, turn and client ids are required".into()); + } + let fingerprint = SubmissionReceipt { + client: client.into(), + input: input.into(), + original_input: original_input.into(), + }; + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let journal = state + .journal + .clone() + .ok_or("ACP execution projection is unavailable")?; + let execution = state + .sessions + .entry(session.into()) + .or_insert_with(|| Execution { + turn_id: String::new(), + running: false, + cancelling: false, + receipts: HashMap::new(), + }); + if let Some(accepted) = execution.receipts.get(turn) { + return if accepted == &fingerprint { + Ok(None) + } else { + Err("ACP turn id was already accepted with different input".into()) + }; + } + if execution.running { + return Err("ACP session is still executing its previous turn".into()); + } + execution.turn_id = turn.into(); + execution.running = true; + execution.cancelling = false; + execution.receipts.insert(turn.into(), fingerprint); + let event = AgenticEvent::DialogTurnStarted { + session_id: session.into(), + turn_id: turn.into(), + turn_index: 0, + user_input: input.into(), + original_user_input: Some(original_input.into()), + user_message_metadata: None, + session_binding: None, + }; + let cursor = journal.record(&event).expect("start has a journal cursor"); + let mut projected = openbitfun_events::project_agentic_frontend_event(event) + .expect("start has a frontend projection") + .payload; + projected["turnIndex"] = Value::Null; + attach_cursor(&mut projected, cursor); + Ok(Some(projected)) + } + + pub(super) fn cancel( + &self, + session: &str, + expected_turn: Option<&str>, + send: impl FnOnce() -> Result<(), String>, + ) -> Result<(), String> { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(execution) = state.sessions.get_mut(session) { + if expected_turn.is_some_and(|turn| turn != execution.turn_id) { + return Err("ACP cancellation belongs to a retired turn".into()); + } + if !execution.running { + return Ok(()); + } + send()?; + // Notification acceptance is not execution completion. + execution.cancelling = true; + Ok(()) + } else if expected_turn.is_some() { + Err("ACP execution state is unavailable".into()) + } else { + send() + } + } + + /// Record before publishing, under the same lock as execution facts. + /// The live envelope and recovery snapshot therefore describe one order. + pub(super) fn record(&self, name: &str, payload: &mut Value) -> Result<(), String> { + let Some(event) = projected_event(name, payload)? else { + return Ok(()); + }; + let session = event.session_id().ok_or("ACP event has no session")?; + let turn = payload["turnId"].as_str().ok_or("ACP event has no turn")?; + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let execution = state + .sessions + .get(session) + .ok_or("ACP turn was not admitted")?; + if execution.turn_id != turn || !execution.running { + return Err("ACP event belongs to a retired turn".into()); + } + if let Some(cursor) = state + .journal + .as_ref() + .ok_or("ACP execution projection is unavailable")? + .record(&event) + { + attach_cursor(payload, cursor); + } + if matches!( + event, + AgenticEvent::DialogTurnCompleted { .. } + | AgenticEvent::DialogTurnCancelled { .. } + | AgenticEvent::DialogTurnFailed { .. } + ) { + let execution = state.sessions.get_mut(session).expect("checked execution"); + execution.running = false; + execution.cancelling = false; + } + Ok(()) + } + + pub(super) fn snapshot(&self, session: &str) -> Option { + let state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let execution = state.sessions.get(session)?; + Some(AcpExecutionSnapshot { + running: execution.running, + cancelling: execution.cancelling, + projection: state.journal.as_ref()?.snapshot(session), + }) + } + + pub(super) fn release(&self, session: &str) { + self.0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .sessions + .remove(session); + } +} + +// ACP's existing frontend projection is preserved for live consumers. Translate +// its portable lifecycle/content facts into the existing journal contract; no +// Tauri, window, transport or filesystem dependency enters this owner. +fn projected_event(name: &str, payload: &Value) -> Result, String> { + let (kind, defaults) = match name { + "agentic://dialog-turn-started" => ( + "DialogTurnStarted", + json!({"turn_index":0,"user_message_metadata":null}), + ), + "agentic://model-round-started" => ( + "ModelRoundStarted", + json!({"model_config_id":"","effective_model_name":""}), + ), + "agentic://model-round-completed" => ( + "ModelRoundCompleted", + json!({"model_config_id":"","effective_model_name":""}), + ), + "agentic://text-chunk" if payload["contentType"] == "thinking" => ( + "ThinkingChunk", + json!({"content":payload["text"],"is_end":payload["isThinkingEnd"].as_bool().unwrap_or(false)}), + ), + "agentic://text-chunk" => ("TextChunk", json!({})), + "agentic://tool-event" => ("ToolEvent", json!({})), + "agentic://dialog-turn-completed" => ( + "DialogTurnCompleted", + json!({"total_rounds":0,"total_tools":0,"duration_ms":0}), + ), + "agentic://dialog-turn-cancelled" => ("DialogTurnCancelled", json!({})), + "agentic://dialog-turn-failed" => ("DialogTurnFailed", json!({})), + _ => return Ok(None), + }; + let mut event = defaults; + event["type"] = kind.into(); + for (source, target) in [ + ("sessionId", "session_id"), + ("turnId", "turn_id"), + ("roundId", "round_id"), + ("roundIndex", "round_index"), + ("userInput", "user_input"), + ("originalUserInput", "original_user_input"), + ("hasToolCalls", "has_tool_calls"), + ("toolEvent", "tool_event"), + ("text", "text"), + ("error", "error"), + ] { + if let Some(value) = payload.get(source) { + event[target] = value.clone(); + } + } + serde_json::from_value(event) + .map(Some) + .map_err(|e| format!("Invalid ACP projection: {e}")) +} + +#[cfg(test)] +mod tests { + use super::*; + #[derive(Default)] + struct Journal(Mutex>); + impl AcpProjectionJournal for Journal { + fn record(&self, event: &AgenticEvent) -> Option { + let mut events = self.0.lock().unwrap(); + events.push(event.clone()); + Some(AcpEventCursor { + stream_id: "host".into(), + cursor: events.len() as u64, + }) + } + fn snapshot(&self, session: &str) -> AcpEventProjectionSnapshot { + let events = self.0.lock().unwrap().clone(); + AcpEventProjectionSnapshot { + session_id: session.into(), + stream_id: "host".into(), + cursor: events.len() as u64, + active_turn_id: events.iter().rev().find_map(|e| { + if let AgenticEvent::DialogTurnStarted { turn_id, .. } = e { + Some(turn_id.clone()) + } else { + None + } + }), + events, + } + } + } + fn store() -> AcpExecutions { + let store = AcpExecutions::default(); + store + .configure_journal(Arc::new(Journal::default())) + .unwrap(); + store + } + fn emit(store: &AcpExecutions, name: &str, extra: Value) -> Value { + let mut payload = json!({"sessionId":"s","turnId":"t"}); + payload + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + store.record(name, &mut payload).unwrap(); + payload + } + + #[test] + fn admission_is_idempotent_and_does_not_replace_running_or_cancelling_work() { + let store = store(); + assert!(store + .admit("s", "t", "client", "hello", "hello") + .unwrap() + .is_some()); + assert_eq!(store.admit("s", "t", "client", "hello", "hello"), Ok(None)); + assert!(store + .admit("s", "t", "client", "different", "different") + .is_err()); + store.cancel("s", Some("t"), || Ok(())).unwrap(); + assert!(store.snapshot("s").unwrap().running); + assert!(store.admit("s", "next", "client", "next", "next").is_err()); + emit(&store, "agentic://dialog-turn-cancelled", json!({})); + assert!(!store.snapshot("s").unwrap().running); + assert!(store + .admit("s", "next", "client", "next", "next") + .unwrap() + .is_some()); + let mut sent = false; + assert!(store + .cancel("s", Some("t"), || { + sent = true; + Ok(()) + }) + .is_err()); + assert!(!sent); + assert!(store + .record( + "agentic://dialog-turn-failed", + &mut json!({"sessionId":"s","turnId":"t","error":"late"}) + ) + .is_err()); + assert!(store.snapshot("s").unwrap().running); + } + + #[test] + fn reload_snapshot_has_start_text_and_terminal_with_the_same_live_cursors() { + let store = store(); + store.admit("s", "t", "client", "hello", "hello").unwrap(); + emit( + &store, + "agentic://model-round-started", + json!({"roundId":"r","roundIndex":0}), + ); + for text in ["one", "two"] { + emit( + &store, + "agentic://text-chunk", + json!({"roundId":"r","text":text}), + ); + } + let active = store.snapshot("s").unwrap(); + assert!(active.running); + assert_eq!(active.projection.cursor, 4); + assert!(active + .projection + .events + .iter() + .any(|e| matches!(e,AgenticEvent::TextChunk{text,..} if text=="two"))); + let live = emit(&store, "agentic://dialog-turn-completed", json!({})); + let terminal = store.snapshot("s").unwrap(); + assert!(!terminal.running); + assert_eq!( + terminal.projection.cursor, + live["__openbitfunRuntimeEventCursor"].as_u64().unwrap() + ); + assert!(matches!( + terminal.projection.events.last(), + Some(AgenticEvent::DialogTurnCompleted { .. }) + )); + assert_eq!(store.admit("s", "t", "client", "hello", "hello"), Ok(None)); + } +} diff --git a/src/crates/interfaces/acp/src/client/manager.rs b/src/crates/interfaces/acp/src/client/manager.rs index 1c448eb988..6651a80b9d 100644 --- a/src/crates/interfaces/acp/src/client/manager.rs +++ b/src/crates/interfaces/acp/src/client/manager.rs @@ -33,7 +33,7 @@ use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; use serde::{Deserialize, Serialize}; use serde_json::json; use tokio::process::{Child, Command}; -use tokio::sync::{oneshot, Mutex, RwLock}; +use tokio::sync::{oneshot, watch, Mutex, MutexGuard, RwLock}; use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt}; use super::builtin_clients::{ @@ -45,6 +45,7 @@ use super::config::{ AcpClientRequirementProbe, AcpClientStatus, RemoteAcpClientRequirementSnapshot, }; use super::dsh_profile::{ensure_bundled_profile, ensure_bundled_profile_remote}; +use super::execution::{AcpExecutionSnapshot, AcpExecutions}; use super::prompt::AcpPrompt; use super::remote_capability_store::RemoteAcpCapabilityStore; use super::remote_session::{preferred_resume_strategies, AcpRemoteSessionStrategy}; @@ -154,6 +155,7 @@ impl AcpSessionConfigValue { } pub struct AcpClientService { + executions: AcpExecutions, config_service: Arc, session_persistence: AcpSessionPersistence, remote_capability_store: RemoteAcpCapabilityStore, @@ -174,13 +176,14 @@ struct AcpClientConnection { status: RwLock, connection: RwLock>>, agent_capabilities: RwLock>, - sessions: DashMap>>, + sessions: DashMap>, cancel_handles: DashMap, shutdown_tx: Mutex>>, child: Mutex>, } struct AcpRemoteSession { + metadata: watch::Sender>, active: Option>, models: Option, config_options: Vec, @@ -193,7 +196,7 @@ struct ResolvedClientSession { client: Arc, cwd: PathBuf, session_key: String, - session: Arc>, + session: Arc, } struct StartClientConfig { @@ -208,8 +211,9 @@ struct AcpCancelHandle { } impl AcpRemoteSession { - fn new() -> Self { + fn new(metadata: watch::Sender>) -> Self { Self { + metadata, active: None, models: None, config_options: Vec::new(), @@ -220,12 +224,68 @@ impl AcpRemoteSession { } } +// The protocol receiver has exactly one owner at a time. Metadata observers +// never take that receiver from a running prompt. An uninitialized observer +// waits for either its first published snapshot or the initialization lock. +struct AcpSessionHandle { + protocol: Mutex, + metadata: watch::Receiver>, +} + +enum AcpMetadataRead<'a> { + Snapshot(AcpSessionOptions), + Protocol(MutexGuard<'a, AcpRemoteSession>), +} + +impl AcpSessionHandle { + fn new() -> Self { + let (sender, metadata) = watch::channel(None); + Self { + protocol: Mutex::new(AcpRemoteSession::new(sender)), + metadata, + } + } + + async fn metadata_or_lock(&self) -> AcpMetadataRead<'_> { + if let Ok(session) = self.protocol.try_lock() { + return AcpMetadataRead::Protocol(session); + } + let mut metadata = self.metadata.clone(); + loop { + if let Some(snapshot) = metadata.borrow_and_update().clone() { + return AcpMetadataRead::Snapshot(snapshot); + } + tokio::select! { + session = self.protocol.lock() => return AcpMetadataRead::Protocol(session), + changed = metadata.changed() => { + // The sender is retained by this handle's protocol state. + changed.expect("ACP session owns its metadata sender"); + } + } + } + } +} + +impl AcpRemoteSession { + fn publish_metadata(&self) -> AcpSessionOptions { + let mut options = session_options_from_state( + self.models.as_ref(), + &self.config_options, + self.context_usage.as_ref(), + ); + options.available_commands = Some(self.available_commands.clone()); + self.metadata.send_replace(Some(options.clone())); + options + } +} + impl AcpClientService { pub fn new( config_service: Arc, path_manager: Arc, ) -> OpenBitFunResult> { Ok(Arc::new(Self { + executions: AcpExecutions::default(), config_service, session_persistence: AcpSessionPersistence::new(path_manager.clone())?, remote_capability_store: RemoteAcpCapabilityStore::new( @@ -239,6 +299,37 @@ impl AcpClientService { })) } + pub fn configure_execution_journal( + &self, + journal: Arc, + ) -> Result<(), String> { + self.executions.configure_journal(journal) + } + + pub fn admit_dialog_turn( + &self, + session: &str, + turn: &str, + client: &str, + input: &str, + original_input: &str, + ) -> Result, String> { + self.executions + .admit(session, turn, client, input, original_input) + } + + pub fn record_dialog_event( + &self, + name: &str, + payload: &mut serde_json::Value, + ) -> Result<(), String> { + self.executions.record(name, payload) + } + + pub fn execution_snapshot(&self, session: &str) -> Option { + self.executions.snapshot(session) + } + /// `workspace_id` is the persisted identity of the owning workspace; /// `workspace_path` is its execution root recorded as an IO projection. pub async fn create_flow_session_record( @@ -849,7 +940,7 @@ impl AcpClientService { for session_key in session_keys { let active_session_id = if let Some((_, session)) = client.sessions.remove(&session_key) { - let mut session = session.lock().await; + let mut session = session.protocol.lock().await; let session_id = session .active .as_ref() @@ -902,6 +993,7 @@ impl AcpClientService { } } + self.executions.release(openbitfun_session_id); released } @@ -979,7 +1071,10 @@ impl AcpClientService { ) .await?; - let mut session = resolved.session.lock().await; + let mut session = match resolved.session.metadata_or_lock().await { + AcpMetadataRead::Snapshot(options) => return Ok(options), + AcpMetadataRead::Protocol(session) => session, + }; self.ensure_remote_session( &resolved.client, &resolved.session_key, @@ -990,12 +1085,7 @@ impl AcpClientService { ) .await?; drain_pending_session_metadata_updates(&mut session).await?; - 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()); + let options = session.publish_metadata(); debug!( "ACP session metadata loaded: client_id={} session_id={} duration_ms={}", client_id, @@ -1013,27 +1103,16 @@ impl AcpClientService { session_storage_path: Option, openbitfun_session_id: String, ) -> OpenBitFunResult> { - let resolved = self - .resolve_or_create_client_session( + let options = self + .get_session_options( client_id, workspace_path, - remote_connection_id.as_deref(), - &openbitfun_session_id, + remote_connection_id, + session_storage_path, + openbitfun_session_id, ) .await?; - - let mut session = resolved.session.lock().await; - self.ensure_remote_session( - &resolved.client, - &resolved.session_key, - &resolved.cwd, - &openbitfun_session_id, - session_storage_path.as_deref(), - &mut session, - ) - .await?; - drain_pending_session_metadata_updates(&mut session).await?; - Ok(session.available_commands.clone()) + Ok(options.available_commands.unwrap_or_default()) } pub async fn set_session_model( @@ -1050,7 +1129,7 @@ impl AcpClientService { ) .await?; - let mut session = resolved.session.lock().await; + let mut session = resolved.session.protocol.lock().await; self.ensure_remote_session( &resolved.client, &resolved.session_key, @@ -1060,6 +1139,7 @@ impl AcpClientService { &mut session, ) .await?; + session.publish_metadata(); let active = session .active .as_ref() @@ -1082,6 +1162,7 @@ impl AcpClientService { if let Some(models) = session.models.as_mut() { models.current_model_id = request.model_id.clone().into(); } + session.publish_metadata(); if let Some(session_storage_path) = session_storage_path.as_deref() { self.session_persistence .update_model_id( @@ -1114,6 +1195,7 @@ impl AcpClientService { .await .map_err(protocol_error)?; session.config_options = response.config_options; + session.publish_metadata(); if let Some(session_storage_path) = session_storage_path.as_deref() { self.session_persistence .update_model_id(session_storage_path, &request.session_id, &request.model_id) @@ -1148,7 +1230,7 @@ impl AcpClientService { ) .await?; - let mut session = resolved.session.lock().await; + let mut session = resolved.session.protocol.lock().await; self.ensure_remote_session( &resolved.client, &resolved.session_key, @@ -1158,6 +1240,7 @@ impl AcpClientService { &mut session, ) .await?; + session.publish_metadata(); let active = session .active .as_ref() @@ -1186,6 +1269,7 @@ impl AcpClientService { .await .map_err(protocol_error)?; session.config_options = response.config_options; + session.publish_metadata(); Ok(session_options_from_state( session.models.as_ref(), @@ -1214,7 +1298,7 @@ impl AcpClientService { .await?; let run = async { - let mut session = resolved.session.lock().await; + let mut session = resolved.session.protocol.lock().await; self.ensure_remote_session( &resolved.client, &resolved.session_key, @@ -1226,6 +1310,7 @@ impl AcpClientService { .await?; discard_pending_session_updates_if_needed(&mut session).await; + session.publish_metadata(); let active = session .active .as_mut() @@ -1269,7 +1354,7 @@ impl AcpClientService { .await?; let run = async { - let mut session = resolved.session.lock().await; + let mut session = resolved.session.protocol.lock().await; self.ensure_remote_session( &resolved.client, &resolved.session_key, @@ -1281,6 +1366,7 @@ impl AcpClientService { .await?; discard_pending_session_updates_if_needed(&mut session).await; + session.publish_metadata(); let mut prompt = { let active = session .active @@ -1351,6 +1437,7 @@ impl AcpClientService { client_id: &str, workspace_path: Option, openbitfun_session_id: String, + expected_turn_id: Option<&str>, ) -> OpenBitFunResult<()> { let connection_id = session_client_connection_id(client_id, &openbitfun_session_id); let client = self @@ -1374,10 +1461,14 @@ impl AcpClientService { )) })?; - handle - .connection - .send_notification(CancelNotification::new(handle.session_id.clone())) - .map_err(protocol_error)?; + self.executions + .cancel(&openbitfun_session_id, expected_turn_id, || { + handle + .connection + .send_notification(CancelNotification::new(handle.session_id.clone())) + .map_err(|error| error.to_string()) + }) + .map_err(OpenBitFunError::service)?; Ok(()) } @@ -1454,7 +1545,7 @@ impl AcpClientService { let session = client .sessions .entry(session_key.clone()) - .or_insert_with(|| Arc::new(Mutex::new(AcpRemoteSession::new()))) + .or_insert_with(|| Arc::new(AcpSessionHandle::new())) .clone(); Ok(ResolvedClientSession { client, @@ -2579,6 +2670,16 @@ fn update_session_from_events(session: &mut AcpRemoteSession, events: &[AcpClien update_session_context_usage(session, events); update_session_available_commands(session, events); update_session_config_options(session, events); + if events.iter().any(|event| { + matches!( + event, + AcpClientStreamEvent::ContextUsageUpdated(_) + | AcpClientStreamEvent::AvailableCommandsUpdated(_) + | AcpClientStreamEvent::ConfigOptionsUpdated(_) + ) + }) { + session.publish_metadata(); + } } fn update_session_context_usage(session: &mut AcpRemoteSession, events: &[AcpClientStreamEvent]) { @@ -2824,6 +2925,112 @@ mod tests { )) } + async fn cached_metadata(handle: &AcpSessionHandle) -> AcpSessionOptions { + match tokio::time::timeout(Duration::from_secs(1), handle.metadata_or_lock()) + .await + .expect("metadata must not wait for the running prompt") + { + AcpMetadataRead::Snapshot(options) => options, + AcpMetadataRead::Protocol(_) => panic!("the prompt still owns the protocol"), + } + } + + #[tokio::test] + async fn metadata_reads_do_not_acquire_the_running_protocol_receiver() { + let handle = AcpSessionHandle::new(); + let mut protocol = handle.protocol.lock().await; + protocol.models = Some(SessionModelState::new( + "model-a", + vec![agent_client_protocol::schema::ModelInfo::new( + "model-a", "Model A", + )], + )); + protocol.publish_metadata(); + let snapshot = cached_metadata(&handle).await; + assert_eq!(snapshot.current_model_id.as_deref(), Some("model-a")); + assert_eq!(snapshot.available_commands, Some(vec![])); + assert!(handle.protocol.try_lock().is_err()); + } + + #[tokio::test] + async fn metadata_cold_read_wakes_on_publication_before_prompt_releases_its_lock() { + let handle = AcpSessionHandle::new(); + let protocol = handle.protocol.lock().await; + let mut read = Box::pin(handle.metadata_or_lock()); + assert!(tokio::time::timeout(Duration::from_millis(10), &mut read) + .await + .is_err()); + protocol.publish_metadata(); + assert!(matches!( + tokio::time::timeout(Duration::from_secs(1), read) + .await + .unwrap(), + AcpMetadataRead::Snapshot(_) + )); + assert!(handle.protocol.try_lock().is_err()); + } + + #[tokio::test] + async fn metadata_stream_updates_publish_commands_config_and_usage_together() { + let handle = AcpSessionHandle::new(); + let mut protocol = handle.protocol.lock().await; + protocol.publish_metadata(); + update_session_from_events( + &mut protocol, + &[ + AcpClientStreamEvent::AvailableCommandsUpdated(vec![AcpAvailableCommand { + name: "inspect".into(), + description: "Inspect a path".into(), + input_hint: None, + }]), + AcpClientStreamEvent::ConfigOptionsUpdated(vec![SessionConfigOption::boolean( + "web-search", + "Web search", + true, + )]), + AcpClientStreamEvent::ContextUsageUpdated(AcpSessionContextUsage { + used: 19, + size: 1000, + cost: None, + }), + ], + ); + let snapshot = cached_metadata(&handle).await; + assert_eq!(snapshot.available_commands.unwrap()[0].name, "inspect"); + assert_eq!(snapshot.config_options[0].id, "web-search"); + assert_eq!(snapshot.context_usage.unwrap().used, 19); + update_session_from_events( + &mut protocol, + &[AcpClientStreamEvent::AvailableCommandsUpdated(vec![])], + ); + assert_eq!( + cached_metadata(&handle).await.available_commands, + Some(vec![]) + ); + } + + #[tokio::test] + async fn metadata_idle_reads_can_drain_and_recreated_sessions_have_no_old_snapshot() { + let old = AcpSessionHandle::new(); + old.protocol.lock().await.publish_metadata(); + assert!(matches!( + old.metadata_or_lock().await, + AcpMetadataRead::Protocol(_) + )); + let recreated = AcpSessionHandle::new(); + let initializing = recreated.protocol.lock().await; + assert!( + tokio::time::timeout(Duration::from_millis(10), recreated.metadata_or_lock()) + .await + .is_err() + ); + drop(initializing); // failed/cancelled initialization must release its waiter + assert!(matches!( + recreated.metadata_or_lock().await, + AcpMetadataRead::Protocol(_) + )); + } + #[test] fn claims_only_one_client_start_for_a_connection() { let clients = DashMap::new(); diff --git a/src/crates/interfaces/acp/src/client/mod.rs b/src/crates/interfaces/acp/src/client/mod.rs index 87fa28db65..8b6124bbbc 100644 --- a/src/crates/interfaces/acp/src/client/mod.rs +++ b/src/crates/interfaces/acp/src/client/mod.rs @@ -1,6 +1,7 @@ mod builtin_clients; mod config; mod dsh_profile; +mod execution; mod manager; mod prompt; mod remote_capability_store; @@ -19,6 +20,9 @@ pub use config::{ AcpClientRequirementProbe, AcpClientStatus, AcpClientSubagentConfig, AcpRequirementProbeItem, RemoteAcpClientRequirementSnapshot, }; +pub use execution::{ + AcpEventCursor, AcpEventProjectionSnapshot, AcpExecutionSnapshot, AcpProjectionJournal, +}; pub use manager::{ AcpClientPermissionResponse, AcpClientService, AcpSessionConfigValue, CreateAcpFlowSessionRecordResponse, SetAcpSessionConfigOptionRequest, diff --git a/src/web-ui/src/flow_chat/components/PendingQueuePanel.test.tsx b/src/web-ui/src/flow_chat/components/PendingQueuePanel.test.tsx index 6434575973..ede80499b4 100644 --- a/src/web-ui/src/flow_chat/components/PendingQueuePanel.test.tsx +++ b/src/web-ui/src/flow_chat/components/PendingQueuePanel.test.tsx @@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({ queueSetStatus: vi.fn(), steerDialogTurn: vi.fn(), items: [] as Array>, + acp: false, })); const queuedItem = { @@ -104,7 +105,7 @@ vi.mock('@/shared/utils/logger', () => ({ })); vi.mock('../utils/acpSession', () => ({ - isAcpFlowSession: () => false, + isAcpFlowSession: () => mocks.acp, })); async function selectQueueMenuAction(container: HTMLElement, action: 'edit' | 'collapse') { @@ -125,6 +126,7 @@ describe('PendingQueuePanel', () => { root = createRoot(container); mocks.drainPendingQueueForSession.mockResolvedValue(undefined); mocks.items = [queuedItem]; + mocks.acp = false; }); afterEach(() => { @@ -157,6 +159,22 @@ describe('PendingQueuePanel', () => { expect(container.querySelector('[data-openbitfun-part="title"]')?.textContent).toBe('pendingQueue.title1'); }); + it('promotes ACP send-now for terminal drain without injecting native steering', async () => { + mocks.acp = true; + await act(async () => { + root.render( true} />); + }); + await act(async () => container.querySelector( + 'button[aria-label="pendingQueue.actions.sendNow"]', + )!.click()); + expect(mocks.steerDialogTurn).not.toHaveBeenCalled(); + expect(mocks.promoteForExplicitDrain).toHaveBeenCalledWith('session-1', 'queued-1'); + expect(mocks.drainPendingQueueForSession).toHaveBeenCalledWith('session-1', { + allowInterruptedRecoveryAbandon: true, + }); + expect(mocks.queueRemove).not.toHaveBeenCalled(); + }); + it('submits only one steering request while send-now is in flight', async () => { let resolveSteering: ((value: { success: boolean; steeringId: string }) => void) | undefined; mocks.steerDialogTurn.mockImplementation( diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts index 3a5d57eaf7..80e544bb49 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts @@ -196,6 +196,39 @@ describe('remote-driven turn on an unloaded session', () => { }); }); +describe('ACP turn replay', () => { + beforeEach(() => { resetFlowChatStore(); stateMachineManager.clear(); }); + afterEach(() => { resetFlowChatStore(); stateMachineManager.clear(); }); + + it.each([ + { historyState: 'ready', storageTurnIndex: 5 }, + { historyState: 'metadata-only', storageTurnIndex: undefined }, + ] as const)('assigns a recovered storage slot only with ready history ($historyState)', ({ historyState, storageTurnIndex }) => { + const store = FlowChatStore.getInstance(); + store.setState(() => ({ + sessions: new Map([['session-1', { + ...createFinishingSession(), + config: { agentType: 'acp:controlled' }, + historyState, + dialogTurns: [{ ...createFinishingTurn(), status: 'completed', storageTurnIndex: 4 }], + }]]), + })); + const start = { + sessionId: 'session-1', turnId: 'replayed-turn', turnIndex: null, userInput: 'Continue', + }; + __test_only__.handleDialogTurnStarted(createFlowChatContext(), start); + __test_only__.handleDialogTurnStarted(createFlowChatContext(), start); + + const turns = store.getState().sessions.get('session-1')?.dialogTurns; + expect(turns).toHaveLength(2); + expect(turns?.[1]).toMatchObject({ + id: 'replayed-turn', + storageTurnIndex, + backendTurnIndex: undefined, + }); + }); +}); + describe('turn finalization', () => { beforeEach(() => { resetFlowChatStore(); stateMachineManager.clear(); }); afterEach(() => { resetFlowChatStore(); stateMachineManager.clear(); }); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts index 10207653c0..99efbb403c 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts @@ -114,6 +114,7 @@ import { stripOptimisticTurnAdoption, } from '../../utils/optimisticTurnAdoption'; import { isAcpFlowSession } from '../../utils/acpSession'; +import { nextStorageTurnIndex, resolveStorageTurnIndex } from '../../utils/flowChatTurnIdentity'; import { workspaceManager } from '@/infrastructure/services/business/workspaceManager'; import { resolveLegacySessionWorkspace } from '@/infrastructure/api/service-api/legacyWorkspaceCompatibility'; @@ -2161,6 +2162,12 @@ function handleDialogTurnStarted(context: FlowChatContext, event: any): void { } if (!dialogTurn) { + const backendTurnIndex = typeof turnIndex === 'number' ? turnIndex : undefined; + let storageTurnIndex = backendTurnIndex; + if (storageTurnIndex === undefined && freshSession?.historyState === 'ready' && isAcpFlowSession(freshSession)) { + // ACP replay can reconstruct a turn after the optimistic copy was lost. + storageTurnIndex = resolveStorageTurnIndex(freshSession, turnId) ?? nextStorageTurnIndex(freshSession); + } const newTurn: DialogTurn = { id: turnId, sessionId, @@ -2176,8 +2183,8 @@ function handleDialogTurnStarted(context: FlowChatContext, event: any): void { modelRounds: [], status: 'pending', startTime: Date.now(), - storageTurnIndex: typeof turnIndex === 'number' ? turnIndex : undefined, - backendTurnIndex: typeof turnIndex === 'number' ? turnIndex : undefined, + storageTurnIndex, + backendTurnIndex, }; bindSubmittedMessageScrollIntent(sessionId, turnId, newTurn.userMessage.id); const replacedTempTurn = tempTurnId diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts index f3bcce4128..3b355349d3 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts @@ -44,6 +44,7 @@ const mockDispatchRefresh = vi.fn(); const mockBindSession = vi.fn(); const mockEnsureBackendSession = vi.fn(); const mockForkChatSession = vi.fn(); +const mockPrewarmHistoricalSession = vi.fn(); const mockNotificationError = vi.fn(); const mockNotificationWarning = vi.fn(); const mockDispatchJobs = vi.hoisted(() => ({ @@ -159,6 +160,7 @@ vi.mock('../../../shared/notification-system', () => ({ })); vi.mock('./SessionModule', () => ({ + prewarmHistoricalSession: (...args: unknown[]) => mockPrewarmHistoricalSession(...args), forkChatSession: (...args: unknown[]) => mockForkChatSession(...args), ensureBackendSession: (...args: unknown[]) => mockEnsureBackendSession(...args), getModelMaxTokens: vi.fn(async (modelId: string) => modelId === 'primary' ? 32000 : 64000), @@ -306,6 +308,17 @@ describe('MessageModule session writer conflict', () => { expect(mockStartDialogTurn).not.toHaveBeenCalled(); }); + it.each(['metadata-only', 'hydrating', 'failed'])('holds restored ACP queues until execution is hydrated (%s)', async historyState => { + const { session, context } = conflictContext('acp-restoring'); + Object.assign(session, { mode: 'acp:test', config: { agentType: 'acp:test' }, historyState }); + context.userCancelledSessionIds = new Set(); + mockPendingList.mockReturnValue([{ id: 'next', sessionId: session.sessionId, content: 'Continue', status: 'queued', retryCount: 0 }]); + await drainPendingQueue(context, session.sessionId); + expect(mockPendingSetStatus).not.toHaveBeenCalled(); + expect(mockStartDialogTurn).not.toHaveBeenCalled(); + expect(mockPrewarmHistoricalSession).toHaveBeenCalledTimes(historyState === 'metadata-only' ? 1 : 0); + }); + it.each([false, true])('preserves the plan build turn ID while busy, host queue=%s', async hostQueue => { const { context, session } = conflictContext('plan-build'); mockGetCurrentState.mockReturnValue('processing'); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts index e9ae04b1a7..60c8afd7d6 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts @@ -56,7 +56,7 @@ import { } from '../submittedMessagePresentation'; import { finishSubmittedMessageScrollIntent, peekSubmittedMessageScrollIntent } from '../submittedMessageScrollIntent'; import { FLOWCHAT_MESSAGE_SUBMITTED_EVENT } from '../../events/flowchatNavigation'; -import { forkChatSession } from './SessionModule'; +import { forkChatSession, prewarmHistoricalSession } from './SessionModule'; import { viewedExternalForkTurn } from '../../utils/externalHistory'; import { confirmUncertainPeerSubmission, @@ -965,6 +965,14 @@ export async function drainPendingQueue( if (hostQueueSupported(sessionId) && !options?.allowInterruptedRecoveryAbandon) return; const scope = getActiveSurfaceScope(); const session = context.flowChatStore.getState().sessions.get(sessionId); + // Restored ACP queues may wake before history/execution hydration. An idle + // default machine is not evidence that the host's previous prompt ended. + if (!session) return; + if (isAcpFlowSession(session) + && (session.isHistorical || !['ready', 'new'].includes(session.historyState ?? ''))) { + if (session.historyState === 'metadata-only') prewarmHistoricalSession(context, sessionId); + return; + } // Peer content/terminal facts are owned by the canonical subscriber, not // the independent direct-event cursor repaired by local Runtime attach. const peerReady = !isLocalSurface(scope.surfaceId) && session?.historyState === 'ready'; @@ -1107,10 +1115,13 @@ export function installPendingQueueDrainListener(context: FlowChatContext): void // Recovery can confirm an already-idle session without another state-machine // transition. Wake its queue when history becomes trustworthy again. context.flowChatStore.subscribeSelector( - state => isLocalSurface(getActiveSurfaceId()) ? [] : [...state.sessions.values()] - .filter(session => session.historyState === 'ready' && pendingQueueManager.list(session.sessionId).length > 0) - .map(session => session.sessionId), - sessionIds => sessionIds.forEach(schedulePendingQueueDrain), - { isEqual: (a, b) => a.length === b.length && a.every((id, index) => id === b[index]) }, + state => [...state.sessions.values()] + .filter(session => (isLocalSurface(getActiveSurfaceId()) + ? isAcpFlowSession(session) : session.historyState === 'ready') + && pendingQueueManager.list(session.sessionId).length > 0) + .map(session => ({ id: session.sessionId, history: session.historyState, historical: session.isHistorical })), + sessions => sessions.forEach(session => schedulePendingQueueDrain(session.id)), + { isEqual: (a, b) => a.length === b.length && a.every((item, index) => + item.id === b[index]?.id && item.history === b[index]?.history && item.historical === b[index]?.historical) }, ); } diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts index 91891e2293..cdb45a4877 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.test.ts @@ -1110,7 +1110,9 @@ describe('PeerSessionRefreshModule journal apply', () => { vi.useRealTimers(); }); - it.each([true, false])('replays a pristine local active restore when refresh is installed before hydrate: %s', async installBeforeHydrate => { + it.each([[true, false], [false, false], [true, true], [false, true]])( + 'replays a local restore with listener-before-hydrate=%s and background-ACP=%s', + async (installBeforeHydrate, backgroundAcp) => { peerModeMock.active = false; const store = FlowChatStore.getInstance(); const sessionId = 'local-reload'; @@ -1118,7 +1120,7 @@ describe('PeerSessionRefreshModule journal apply', () => { const roundId = 'round-live'; store.setState(prev => ({ ...prev, - activeSessionId: sessionId, + activeSessionId: backgroundAcp ? null : sessionId, sessions: new Map([[sessionId, { sessionId, title: 'Local reload', @@ -1128,7 +1130,7 @@ describe('PeerSessionRefreshModule journal apply', () => { isHistorical: true, isTransient: false, dialogTurns: [], - config: { agentType: 'PaperWriting' }, + config: { agentType: backgroundAcp ? 'acp:controlled' : 'PaperWriting' }, createdAt: 1, lastActiveAt: 1, todos: [], @@ -1172,7 +1174,8 @@ describe('PeerSessionRefreshModule journal apply', () => { } } }, ]; const view = { - session: { sessionId, agentType: 'PaperWriting', state: 'Processing', createdAt: 1, turnCount: 7 }, + executionProjection: backgroundAcp ? 'acp' : undefined, + session: { sessionId, agentType: backgroundAcp ? 'acp:controlled' : 'PaperWriting', state: 'Processing', createdAt: 1, turnCount: 7 }, turns: [{ turnId, turnIndex: 6, sessionId, timestamp: 1, userMessage: { id: 'user-live', content: 'Open LaTeX', timestamp: 1 }, @@ -1194,7 +1197,8 @@ describe('PeerSessionRefreshModule journal apply', () => { expect(store.getState().sessions.get(sessionId)?.dialogTurns[0].modelRounds).toEqual([]); expect(isRuntimeSessionProjectionStale(LOCAL_SURFACE_ID, sessionId)).toBe(true); if (!installBeforeHydrate) cleanup = installPeerSessionRefresh(context); - await vi.advanceTimersByTimeAsync(1); + // A background repair may follow the initial no-active-session timer. + await vi.advanceTimersByTimeAsync(5); expect(restore).toHaveBeenCalledTimes(2); // Live delivery races the host read: the covered prefix must not repeat, diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts index aec3790e41..1eb06bcf00 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PeerSessionRefreshModule.ts @@ -35,6 +35,7 @@ import { } from '../../state-machine/types'; import type { AnyFlowItem, DialogTurn, FlowToolItem, Session } from '../../types/flow-chat'; import { isUnmaterializedSessionDraft } from '../../utils/sessionDraft'; +import { isAcpFlowSession } from '../../utils/acpSession'; import { installLiveSessionInteractionMailbox } from '../liveSessionInteractionStore'; import { agenticEventListener } from '../AgenticEventListener'; import { pendingQueueManager } from './PendingQueueModule'; @@ -507,6 +508,15 @@ export function installPeerSessionRefresh(context: FlowChatContext): () => void } const session = state.sessions.get(sessionId); if (!isSessionProjectionAttachable(session)) { + // A reloaded background ACP session may never have been clicked. Its + // still-running prompt must be recovered without making the controller + // activate that tab. Reuse the existing bounded, deduplicated prewarm. + if (session && isAcpFlowSession(session) && session.historyState === 'metadata-only') { + const scope = getActiveSurfaceScope(); + void import('./SessionModule').then(({ prewarmHistoricalSession }) => { + if (scope.isCurrent()) prewarmHistoricalSession(context, sessionId); + }); + } return; } ensureSubscription(); @@ -787,7 +797,12 @@ export function installPeerSessionRefresh(context: FlowChatContext): () => void } immediateTimer = setTimeout(() => { immediateTimer = null; - void runRefresh(sessionId); + void runRefresh(sessionId).finally(() => { + // A request can return before installing an attachment (for example, + // no active tab during startup). It must not strand a named repair + // queued behind that initial request. + if (!inFlight && immediateTimer === null) drainFollowUpRefresh(); + }); }, 0); } @@ -835,7 +850,23 @@ export function installPeerSessionRefresh(context: FlowChatContext): () => void document.addEventListener('visibilitychange', handleVisibilityChanged); } - scheduleRefresh(); + // Hydration can finish before this listener is installed. Its explicit gap + // is durable, but the notification was not; repair background sessions too, + // without waiting for another token or requiring their tab to be activated. + const initialScope = getActiveSurfaceScope(); + const initialState = context.flowChatStore.getState(); + const initialGaps = new Set(); + if (initialScope.surfaceId === 'local') { + for (const sessionId of initialState.sessions.keys()) { + if (isRuntimeSessionProjectionStale(initialScope.surfaceId, sessionId)) { + initialGaps.add(sessionId); + scheduleRefresh(sessionId); + } + } + } + if (initialGaps.size === 0 || (initialState.activeSessionId && !initialGaps.has(initialState.activeSessionId))) { + scheduleRefresh(initialState.activeSessionId ?? undefined); + } return () => { disposed = true; diff --git a/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts b/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts index ec2a753c74..d8e8d3057a 100644 --- a/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts +++ b/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts @@ -320,6 +320,7 @@ export class SessionStateMachineImpl { await ACPClientAPI.cancelDialogTurn({ sessionId, clientId: acpClientId, + turnId: dialogTurnId ?? undefined, workspaceId: session?.workspaceId || session?.config?.workspaceId, workspacePath: session?.workspacePath || session?.config?.workspacePath, remoteConnectionId: session?.remoteConnectionId, diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index 9a7986f089..3073a2d1a1 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -17,6 +17,7 @@ import type { FlowChatState, ModelRound, Session } from '../types/flow-chat'; import { startupTrace } from '@/shared/utils/startupTrace'; import { projectEffectiveToolItem } from '../utils/toolInvocationIdentity'; import { SessionRecordReplica } from '../session-stream/SessionRecordReplica'; +import { markRuntimeSessionProjectionStale } from '@/infrastructure/peer-device/runtimeSessionEventGate'; import { resetSessionStreamsForTest, sessionStream } from '../session-stream/SessionStream'; import { isSessionBindingLocked } from '../utils/sessionLifecycle'; import { isHostIssuedTurnCatalogRevision } from '../utils/flowChatTurnIdentity'; @@ -4799,7 +4800,11 @@ describe('FlowChatStore historical session hydration state', () => { }); }); - it('does not restore ACP historical sessions through the normal backend path', async () => { + it('keeps persisted ACP history fallback when an older host has no execution projection', async () => { + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: { sessionId: 'acp-1', agentType: 'acp:test', state: 'Idle' }, + turns: [], contextRestoreState: 'pending', + }); apiMocks.loadSessionTurns.mockResolvedValueOnce([]); flowChatStore.setState(() => ({ sessions: new Map([ @@ -4817,8 +4822,49 @@ describe('FlowChatStore historical session hydration state', () => { await flowChatStore.loadSessionHistory('acp-1'); expect(apiMocks.restoreSession).not.toHaveBeenCalled(); - expect(apiMocks.restoreSessionView).not.toHaveBeenCalled(); + expect(apiMocks.restoreSessionView).toHaveBeenCalledTimes(1); expect(apiMocks.restoreSessionWithTurns).not.toHaveBeenCalled(); + expect(apiMocks.loadSessionTurns).toHaveBeenCalledTimes(1); + }); + + it.each(['Processing', 'Idle'])('restores ACP journal authority including terminal snapshots (%s)', async state => { + const snapshot = { + sessionId: 'acp-1', streamId: 'acp-host', cursor: 4, activeTurnId: 'acp-turn', + events: [ + { eventName: 'agentic://dialog-turn-started', payload: { sessionId: 'acp-1', turnId: 'acp-turn', userInput: 'Continue' } }, + { eventName: 'agentic://dialog-turn-completed', payload: { sessionId: 'acp-1', turnId: 'acp-turn' } }, + ], + }; + apiMocks.restoreSessionView.mockResolvedValueOnce({ + executionProjection: 'acp', + session: { sessionId: 'acp-1', agentType: 'acp:test', state, turnCount: 0, createdAt: 1 }, + turns: [], runtimeEventSnapshot: snapshot, contextRestoreState: 'pending', + }); + flowChatStore.setState(() => ({ + sessions: new Map([['acp-1', createSession({ + sessionId: 'acp-1', workspaceId: 'workspace-1', mode: 'acp:test', + config: { agentType: 'acp:test' }, historyState: 'ready', isHistorical: false, + })]]), activeSessionId: 'acp-1', + })); + const result = await flowChatStore.refreshPeerSessionSnapshot('acp-1'); + expect(result.runtimeEventSnapshot).toEqual(snapshot); + expect(result.backendState).toBe(state); + }); + + it('does not claim that an older host repaired an ACP execution gap', async () => { + flowChatStore.setState(() => ({ + sessions: new Map([['acp-1', createSession({ + sessionId: 'acp-1', mode: 'acp:test', config: { agentType: 'acp:test' }, + historyState: 'ready', isHistorical: false, + })]]), activeSessionId: 'acp-1', + })); + markRuntimeSessionProjectionStale(LOCAL_SURFACE_ID, 'acp-1'); + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: { sessionId: 'acp-1', state: 'Idle' }, turns: [], contextRestoreState: 'pending', + }); + await expect(flowChatStore.refreshPeerSessionSnapshot('acp-1')) + .rejects.toThrow('ACP execution recovery is not supported'); + expect(flowChatStore.getState().sessions.get('acp-1')?.historyState).toBe('failed'); }); it('uses view-restored turns without reading the turn files a second time', async () => { diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 58543d0022..885f97b2ac 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -66,6 +66,7 @@ import { } from '@/infrastructure/peer-device/deviceSurface'; import { isRuntimeSessionAttachmentInFlight, + isRuntimeSessionProjectionStale, markRuntimeSessionProjectionStale, } from '@/infrastructure/peer-device/runtimeSessionEventGate'; import { i18nService } from '@/infrastructure/i18n/core/I18nService'; @@ -96,7 +97,7 @@ import { sessionOwningWorkspaceId } from '../utils/sessionOrdering'; import { sessionProjectWorkspacePath } from '../utils/sessionWorkspace'; import type { SessionTitleDescriptor } from '../utils/sessionTitle'; import { deriveContextUsageFromTurns } from '../utils/tokenUsageDisplay'; -import { isAcpAgentType } from '../utils/acpSession'; +import { isAcpAgentType, isAcpFlowSession } from '../utils/acpSession'; import { deriveSessionTitleState, deriveSessionTitleStateFromMetadata, @@ -1018,9 +1019,10 @@ function coerceRuntimeEventSnapshot( sessionId: string, backendActive: boolean, fallbackActiveTurnId?: string, + executionProjection?: 'acp', ): SessionRuntimeEventSnapshot | undefined { if ( - !backendActive || + (!backendActive && executionProjection !== 'acp') || snapshot?.sessionId !== sessionId || typeof snapshot.streamId !== 'string' || !snapshot.streamId || @@ -9056,6 +9058,11 @@ export class FlowChatStore { // This snapshot describes the device it was read from; reconciling it into // the surface that is rendered now would merge two devices' turns. scope.assertCurrent('refreshPeerSessionSnapshot'); + if (isAcpFlowSession(initialSession) && restored.executionProjection !== 'acp' + && isRuntimeSessionProjectionStale(scope.surfaceId, sessionId)) { + this.setSessionHistoryState(sessionId, 'failed'); + throw new Error('ACP execution recovery is not supported by this host'); + } if (restored.interactionSnapshot?.sessionId === sessionId) { liveSessionInteractionStore.reconcilePermissionSnapshot( scope.surfaceId, @@ -9071,6 +9078,7 @@ export class FlowChatStore { sessionId, backendActive, persistTailTurnId, + restored.executionProjection, ); const activeTurnId = backendActive ? runtimeEventSnapshot?.activeTurnId ?? persistTailTurnId @@ -9375,6 +9383,7 @@ export class FlowChatStore { sessionId, backendActive, persistedTailTurnId, + restored.executionProjection, ); const hostExecutingTurnId = backendActive ? runtimeSnapshot?.activeTurnId ?? persistedTailTurnId @@ -9660,7 +9669,7 @@ export class FlowChatStore { let restoredRuntimeEventSnapshot: SessionRuntimeEventSnapshot | undefined; const stateMachineManagerPromise = import('../state-machine'); - if (!isAcpSession) { + { const restoreStartedAt = nowMs(); startupTrace.markPhase('historical_session_restore_start', { remote, @@ -9737,24 +9746,30 @@ export class FlowChatStore { ); notifyHydratingState(); const restored = await restoredPromise; - restoredSessionInfo = restored.session; - turns = restored.turns; - contextRestoreState = - restored.contextRestoreState === 'ready' ? 'ready' : 'pending'; - restoredHistoryPartial = restored.isPartial === true; - restoredLoadedTurnCount = restored.loadedTurnCount; - restoredTotalTurnCount = restored.totalTurnCount; - restoredTurnCatalog = restored.turnCatalog?.sessionId === sessionId - ? restored.turnCatalog - : undefined; - restoredTiming = restored.timings; - restoredCurrentContextUsage = restored.currentContextUsage; - restoredRuntimeEventSnapshot = coerceRuntimeEventSnapshot( - restored.runtimeEventSnapshot, - sessionId, - isBackendSessionActivelyProcessing(restored.session.state), - restored.turns[restored.turns.length - 1]?.turnId, - ); + // Older hosts have only a native Runtime snapshot, which is + // not an execution fact for an ACP prompt. Keep their existing + // persisted-history fallback instead of treating it as idle. + if (!isAcpSession || restored.executionProjection === 'acp') { + restoredSessionInfo = restored.session; + turns = restored.turns; + contextRestoreState = + restored.contextRestoreState === 'ready' ? 'ready' : 'pending'; + restoredHistoryPartial = restored.isPartial === true; + restoredLoadedTurnCount = restored.loadedTurnCount; + restoredTotalTurnCount = restored.totalTurnCount; + restoredTurnCatalog = restored.turnCatalog?.sessionId === sessionId + ? restored.turnCatalog + : undefined; + restoredTiming = restored.timings; + restoredCurrentContextUsage = restored.currentContextUsage; + restoredRuntimeEventSnapshot = coerceRuntimeEventSnapshot( + restored.runtimeEventSnapshot, + sessionId, + isBackendSessionActivelyProcessing(restored.session.state), + restored.turns[restored.turns.length - 1]?.turnId, + restored.executionProjection, + ); + } } catch (error) { if (!isUnsupportedTauriCommandError(error, 'restore_session_view')) { throw error; @@ -10027,7 +10042,7 @@ export class FlowChatStore { }); } } - if (activeTurnId && (restoredRuntimeEventSnapshot || isSurfaceReconcileEnabled())) { + if (restoredRuntimeEventSnapshot || (activeTurnId && isSurfaceReconcileEnabled())) { const { requestPeerSessionRefresh, requestRuntimeProjectionRepair } = await import( '../services/flow-chat-manager/PeerSessionRefreshModule' ); 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 fc7ae16cec..2bfffa152a 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts @@ -86,6 +86,8 @@ export interface StartAcpDialogTurnRequest { export interface CancelAcpDialogTurnRequest { sessionId: string; clientId: string; + /** New hosts bind cancellation to this turn; old hosts ignore it. */ + turnId?: string; /** Workspace identity; authoritative when present. Paths below are IO projections. */ workspaceId?: string; workspacePath?: string; diff --git a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts index dc6564865f..f54523e32d 100644 --- a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts @@ -333,6 +333,8 @@ export interface SessionViewRestoreTiming { } export interface RestoreSessionViewResponse { + /** Explicit execution authority/capability; absent on older hosts. */ + executionProjection?: 'acp'; session: SessionInfo; turns: DialogTurnData[]; /** Absent when talking to an older Peer Host. */ diff --git a/tests/e2e/AGENTS-CN.md b/tests/e2e/AGENTS-CN.md index 8a258670db..9642c3b75d 100644 --- a/tests/e2e/AGENTS-CN.md +++ b/tests/e2e/AGENTS-CN.md @@ -38,6 +38,15 @@ pnpm --dir tests/e2e exec wdio run ./config/wdio.conf.ts --spec "./specs/. 优先运行最窄的相关 spec,必要时再扩大范围。 +验证 ACP 队列恢复时,先完成 Desktop 和生产前端构建,再运行 +`node tests/e2e/scripts/run-acp-queue-recovery.mjs`。该 macOS 原生脚本使用隔离配置、 +真实 stdio 连接的可控 ACP 子进程、产品控件及只读单例诊断,覆盖后台刷新恢复、 +会话切换、运行中元数据读取和实时更新、模型变更快照、ACP 立即发送队列提升、 +延迟取消、提交去重、协议报错和子进程退出重连。ACP 立即发送将消息移到队首、 +等待当前请求结束后执行,不向外部 Agent 注入原生 steering。在输出的临时目录保留 +`acp-queue-recovery.json`、事件日志及截图;前端、二进制和字体配置覆盖参数与其他 +原生负载脚本一致。该测试仅覆盖本地 Desktop,不证明真实模型服务或四种远程场景。 + 静态/流式长会话性能矩阵的负载与指标定义见 [README.zh-CN.md](README.zh-CN.md)。 构建桌面端和生产前端后运行 `pnpm --dir tests/e2e run test:perf:long-session`, 隔离测试首次打开、重复切换、双向连续滚轮输入及轮次栏远距离跳转。 diff --git a/tests/e2e/AGENTS.md b/tests/e2e/AGENTS.md index da57fbfa5d..fcf0e43abb 100644 --- a/tests/e2e/AGENTS.md +++ b/tests/e2e/AGENTS.md @@ -38,6 +38,19 @@ pnpm --dir tests/e2e exec wdio run ./config/wdio.conf.ts --spec "./specs/. Prefer the narrowest relevant spec first, then broaden only if needed. +For ACP queue recovery, finish Desktop and production frontend builds, then run +`node tests/e2e/scripts/run-acp-queue-recovery.mjs`. The isolated macOS native +runner uses a controlled ACP subprocess over real stdio, production controls, +and read-only singleton diagnostics. It covers background reload recovery, +session switching, non-blocking metadata reads and live metadata updates, +model-change publication, ACP send-now queue promotion, delayed cancellation, +admission deduplication, protocol errors and child-process exit/reconnect. +ACP send-now promotes a queued message for execution after the current prompt; +it does not inject native steering into an external agent. It retains `acp-queue-recovery.json`, event logs +and screenshots in the printed temporary directory. Frontend/binary/font-profile +overrides match the other native workload runners. This is local Desktop +coverage; it does not establish live-provider or any remote-scenario behavior. + For the static/streaming long-session performance matrix, see the workload and measurement definitions in [README.md](README.md#long-session-performance). After building Desktop and production frontend assets, run diff --git a/tests/e2e/fixtures/controlled-acp-agent.mjs b/tests/e2e/fixtures/controlled-acp-agent.mjs new file mode 100644 index 0000000000..1efafc8637 --- /dev/null +++ b/tests/e2e/fixtures/controlled-acp-agent.mjs @@ -0,0 +1,93 @@ +import { createInterface } from 'node:readline'; +import { createServer } from 'node:http'; +import { appendFileSync } from 'node:fs'; +import { randomUUID } from 'node:crypto'; + +const sessions = new Map(), active = new Map(); +const event = (type, data = {}) => appendFileSync(process.env.OPENBITFUN_ACP_FIXTURE_LOG, + JSON.stringify({ at: Date.now(), pid: process.pid, type, ...data }) + '\n'); +const send = data => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...data }) + '\n'); +const notify = (sessionId, text) => send({ method: 'session/update', params: { sessionId, + update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } } } }); +const options = () => ({ modes: { currentModeId: 'default', availableModes: [{ id: 'default', name: 'Default' }] }, + models: { currentModelId: 'fixture', availableModels: [{ modelId: 'fixture', name: 'Controlled fixture' }, + { modelId: 'fixture-alt', name: 'Controlled alternative' }] } }); +function finish(token, reason = 'end_turn', error = false) { + const item = [...active.values()].find(item => item.token === token); + if (!item) return false; + clearInterval(item.timer); clearTimeout(item.auto); active.delete(item.sessionId); + if (error) send({ id: item.id, error: { code: -32603, message: 'Controlled ACP transport error' } }); + else { notify(item.sessionId, `\nACP_COMPLETE:${token}\n`); send({ id: item.id, result: { stopReason: reason } }); } + event('finished', { token, reason, error }); return true; +} +const control = createServer(async (request, response) => { + if (request.method === 'GET') { + response.end(JSON.stringify({ pid: process.pid, active: [...active.values()].map(({ token, sessionId, ticks }) => ({ token, sessionId, ticks })), sessions: [...sessions.keys()] })); return; + } + const parts=[]; for await(const part of request)parts.push(part); + const body=JSON.parse(Buffer.concat(parts).toString()); + if (body.action === 'metadata') { + const item = [...active.values()].find(item => item.token === body.token); + if (item) { + const update = update => send({ method: 'session/update', params: { sessionId: item.sessionId, update } }); + update({ sessionUpdate: 'available_commands_update', availableCommands: [ + { name: 'inspect', description: 'Inspect a path' }, + ] }); + update({ sessionUpdate: 'config_option_update', configOptions: [{ + id: 'reasoning', name: 'Reasoning', type: 'select', currentValue: 'high', + options: [{ value: 'medium', name: 'Medium' }, { value: 'high', name: 'High' }], + }] }); + update({ sessionUpdate: 'usage_update', used: 19, size: 1000 }); + } + event('metadata', { token: body.token }); + response.end(JSON.stringify({ found: !!item })); return; + } + if(body.action==='pause'||body.action==='resume') { + const item=[...active.values()].find(item=>item.token===body.token); + if(item){clearInterval(item.timer);if(body.action==='resume')item.timer=setInterval(()=>{item.ticks++;notify(item.sessionId,` ${item.token}:${item.ticks}`)},180);} + event(body.action,{token:body.token});response.end(JSON.stringify({found:!!item}));return; + } + if(body.action==='exit'){event('controlled_exit');response.end('{}');setTimeout(()=>process.exit(7),30);return;} + response.end(JSON.stringify({ finished: finish(body.token, body.reason ?? 'end_turn',body.action==='error') })); +}); +control.listen(0,'127.0.0.1',()=>event('started',{port:control.address().port})); +const lines=createInterface({input:process.stdin}); +lines.on('line',line=>{ + let request;try{request=JSON.parse(line)}catch{return} + const {id,method,params={}}=request; + if(!method){event('client_reply',{id,result:request.result});return;} + event('request',{method,id,sessionId:params.sessionId}); + if(method==='initialize'){send({id,result:{protocolVersion:1,agentInfo:{name:'OpenBitFun controlled ACP fixture',version:'1.0'},agentCapabilities:{loadSession:true,promptCapabilities:{image:false,audio:false,embeddedContext:false}},authMethods:[]}});return;} + if(method==='session/new'){const sessionId='fixture-'+randomUUID();sessions.set(sessionId,{cwd:params.cwd});send({id,result:{sessionId,...options()}});return;} + if(method==='session/load'){sessions.set(params.sessionId,{cwd:params.cwd});send({id,result:options()});return;} + if(method==='session/prompt'){ + const text=(params.prompt??[]).filter(item=>item.type==='text').map(item=>item.text).join('\n'); + const token=[...text.matchAll(/ACP_CASE:([a-z0-9-]+)/g)].at(-1)?.[1]??'unmarked'; + if(active.has(params.sessionId)){send({id,error:{code:-32000,message:'Controlled fixture refuses overlapping prompts'}});return;} + const item={id,sessionId:params.sessionId,token,ticks:0};active.set(params.sessionId,item); + event('prompt',{token,sessionId:params.sessionId});notify(params.sessionId,`ACP_STARTED:${token}\n`); + if (token === 'hold-before-refresh') { + const update = update => send({ method: 'session/update', params: { sessionId: params.sessionId, update } }); + update({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'ACP recovery reasoning' } }); + update({ sessionUpdate: 'tool_call', toolCallId: 'recovery-read', title: 'Read sample.ts', + kind: 'read', status: 'in_progress', rawInput: { file_path: 'sample.ts' }, content: [] }); + update({ sessionUpdate: 'tool_call_update', toolCallId: 'recovery-read', status: 'completed', + content: [{ type: 'content', content: { type: 'text', text: 'Fixture read result' } }] }); + } + + item.timer=setInterval(()=>{item.ticks++;notify(params.sessionId,` ${token}:${item.ticks}`)},180); + if(token.startsWith('auto-'))item.auto=setTimeout(()=>finish(token),250); + if(token.startsWith('error-'))item.auto=setTimeout(()=>finish(token,'end_turn',true),250); + if(token.startsWith('exit-'))item.auto=setTimeout(()=>{event('prompt_exit',{token});process.exit(7)},350); + return; + } + if(method==='session/cancel'){ + const item=active.get(params.sessionId);event('cancel',{token:item?.token}); + if(item&&!item.token.includes('ignore-cancel'))setTimeout(()=>finish(item.token,'cancelled'),item.token.includes('delayed-cancel')?1600:30); + return; + } + if(method==='session/set_mode'||method==='session/set_model'||method==='session/set_config_option'){send({id,result:{}});return;} + if(method==='session/list'){send({id,result:{sessions:[]}});return;} + if(id!==undefined)send({id,error:{code:-32601,message:'Method not implemented by controlled fixture: '+method}}); +}); +lines.on('close',()=>{for(const item of active.values())clearInterval(item.timer);control.close();process.exit(0)}); diff --git a/tests/e2e/helpers/acp-queue-observer.mjs b/tests/e2e/helpers/acp-queue-observer.mjs new file mode 100644 index 0000000000..5b7b5a0cae --- /dev/null +++ b/tests/e2e/helpers/acp-queue-observer.mjs @@ -0,0 +1,53 @@ +// Read-only diagnostics of production singleton exports. No product state is injected. +export async function installObserver(input) { + const { ids, modules } = input; + if (window.__acpTraceInstalled) return; + const f = await import(modules.manager); + const r = await import(modules.state); + const g = await import(modules.gate); + const manager = Object.values(f).find(v => typeof v === 'function' && v.getInstance && v.prototype.sendMessage); + const machines = Object.values(r).find(v => v && typeof v === 'object' && v.getCurrentState && v.getOrCreate); + const c = manager.getInstance().context; + const trace = []; + window.__acpTrace = trace; + const push = value => { + trace.push({ at: Date.now(), ...value }); + if (trace.length > 12000) trace.shift(); + }; + const take = id => { + const s = c.flowChatStore.getState().sessions.get(id); + const mc = machines.get(id); + const t = s?.dialogTurns.at(-1); + return { + id, state: mc?.getCurrentState(), version: mc?.getContext().version, + currentTurn: mc?.getContext().currentDialogTurnId, + gap: g[modules.gap]('local', id), attach: g[modules.attach]('local', id), + cancelGate: c.userCancelledSessionIds.has(id), history: s?.historyState, + lastTurnId: t?.id, lastTurnStatus: t?.status, + rounds: t?.modelRounds?.map(x => ({ id: x.id, status: x.status, + items: x.items?.map(n => ({ id: n.id, type: n.type })) })), + queue: Object.keys(localStorage) + .filter(k => k.startsWith('openbitfun.flowChat.pendingQueue.v1.') && k.includes(encodeURIComponent(id))) + .map(k => JSON.parse(localStorage.getItem(k)).map(x => ({ + id: x.id, content: x.content, status: x.status, retry: x.retryCount, + }))), + }; + }; + g[modules.subscribeGap]((surface, id) => push({ type: 'gap', surface, id, + stack: new Error('gap origin').stack, snapshot: take(id) })); + machines.subscribeGlobal((id) => { + if (ids.includes(id)) push({ type: 'machine', id, snapshot: take(id) }); + }); + let prev = ''; + setInterval(() => { + const values = ids.map(take); + const signature = JSON.stringify(values); + if (signature !== prev) { + prev = signature; + push({ type: 'poll', sessions: values }); + } + }, 80); + window.__acpDiagnosticSnapshot = () => ids.map(take); + window.__acpTraceInstalled = true; + return { installed: true }; +} diff --git a/tests/e2e/page-objects/AcpQueueRecoveryPage.mjs b/tests/e2e/page-objects/AcpQueueRecoveryPage.mjs new file mode 100644 index 0000000000..0c532b0b5f --- /dev/null +++ b/tests/e2e/page-objects/AcpQueueRecoveryPage.mjs @@ -0,0 +1,48 @@ +import { SceneVisibilityPage } from './SceneVisibilityPage.mjs'; +import { writeFile } from 'node:fs/promises'; + +export class AcpQueueRecoveryPage extends SceneVisibilityPage { + async selectSession(id) { + await this.click('[data-testid="nav-session-item"][data-session-id="' + id + '"]'); + await this.until(() => this.execute(id => [...document.querySelectorAll('[role="tab"][aria-selected="true"]')] + .some(node => node.dataset.openbitfunValue?.includes(id)), id), 'selected ' + id, 6000); + } + async modelReady() { + await this.until(() => this.execute(() => document.querySelector('[data-testid="chat-model-selector-btn"]') + ?.innerText.includes('Controlled')), 'ACP model ready', 8000); + } + async sendCase(token) { + await this.enterDraft('ACP_CASE:' + token); + await this.until(() => this.execute(() => { + const button = document.querySelector('[data-testid="chat-input-send-btn"]'); + return button && !button.disabled; + }), 'send enabled', 6000); + await this.click('[data-testid="chat-input-send-btn"]'); + await this.until(() => this.execute(() => { + const input = document.querySelector('[data-testid="chat-input-textarea"]'); + return input && !input.textContent.trim(); + }), 'composer cleared after sending ' + token, 6000); + } + async promoteQueuedCase(index) { + const row = '[data-testid="pending-queue-panel"] [data-openbitfun-product-part="item"]'; + const label = await this.execute(({ row, index }) => { + const item = document.querySelectorAll(row)[index]; + const button = item?.querySelector('[data-openbitfun-product-part="actions"] button'); + if (!button) throw new Error('Missing queued-message send action'); + return button.getAttribute('aria-label'); + }, { row, index }); + await this.click(`${row}:nth-child(${index + 1}) button[aria-label=${JSON.stringify(label)}]`); + } + async refreshDocument() { + const token = await this.execute(() => window.__acpDiagnosticDocument = Math.random().toString()); + await this.request('/session/' + this.session + '/refresh', {}); + await this.until(() => this.execute(token => window.__acpDiagnosticDocument !== token && + !![...document.querySelectorAll('[data-testid="nav-session-item"]')] + .find(node => node.checkVisibility({ checkVisibilityCSS: true })), token) + .catch(() => false), 'new document ready', 10000); + } + async shot(path) { + const base64 = await this.request('/session/' + this.session + '/screenshot'); + await writeFile(path, Buffer.from(base64, 'base64')); + } +} diff --git a/tests/e2e/scripts/run-acp-queue-recovery.mjs b/tests/e2e/scripts/run-acp-queue-recovery.mjs new file mode 100644 index 0000000000..af34c606f6 --- /dev/null +++ b/tests/e2e/scripts/run-acp-queue-recovery.mjs @@ -0,0 +1,278 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { readFile, writeFile, readdir } from 'node:fs/promises'; +import { AcpQueueRecoveryPage } from '../page-objects/AcpQueueRecoveryPage.mjs'; +import { installObserver } from '../helpers/acp-queue-observer.mjs'; +import { openNativeWorkload, delay } from './native-workload-session.mjs'; + +const run = await openNativeWorkload({ Page: AcpQueueRecoveryPage, + label: 'acp-queue-recovery', evidence: process.argv[2], + harnessFiles: [ + 'tests/e2e/scripts/run-acp-queue-recovery.mjs', + 'tests/e2e/page-objects/AcpQueueRecoveryPage.mjs', + 'tests/e2e/page-objects/SceneVisibilityPage.mjs', + 'tests/e2e/helpers/acp-queue-observer.mjs', + 'tests/e2e/fixtures/controlled-acp-agent.mjs', + ], + protocol: { name: 'acp-queue-recovery', version: 2, prewarmMs: 1000, functionalOnly: true }, +}); +const page = run.page; +const result = { passed: false, isolatedProfile: true, realAcpStdio: true, + productStateInjected: false, native: run.report, stages: [] }; +const save = () => writeFile(path.join(run.root, 'acp-queue-recovery.json'), JSON.stringify(result, null, 2)); +const mark = (name, detail) => { result.stages.push({ at: Date.now(), name, ...detail }); console.log(name); }; + +// Discover the production bundle's existing exports. This observes the live +// singleton instances; it does not replace event handlers or write product state. +const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +async function diagnosticsModules() { + const assets = await readdir(path.join(run.root, 'frontend/assets')); + const manager = assets.find(n => /^FlowChatManager-.*\.js$/.test(n)); + const state = assets.find(n => /^ReviewPlatformAPI-.*\.js$/.test(n)); + assert.ok(manager && state, 'Production singleton bundles are available'); + for (const name of assets.filter(n => /^index-.*\.js$/.test(n))) { + const code = await readFile(path.join(run.root, 'frontend/assets', name), 'utf8'); + const gap = code.match(/function ([\w$]+)\([^)]*\)\{return [^{};]*\?\.hasGap\(\)===!0\}/)?.[1]; + const attach = code.match(/function ([\w$]+)\([^)]*\)\{return [^{};]*\?\.isReadInFlight\(\)===!0\}/)?.[1]; + if (!gap || !attach) continue; + const notify = code.match(/\.markProjectionBehind\(\),([\w$]+)\(/)?.[1]; + assert.ok(notify, 'Gap notification function exists'); + const set = code.match(new RegExp('function ' + escape(notify) + '\\([^)]*\\)\\{for\\(const [\\w$]+ of ([\\w$]+)\\)'))?.[1]; + assert.ok(set, 'Gap observer set exists'); + const subscribe = code.match(new RegExp('function ([\\w$]+)\\([^)]*\\)\\{return ' + escape(set) + '\\.add\\('))?.[1]; + const exports = code.slice(code.lastIndexOf('export{')); + const exported = local => { + const key = exports.match(new RegExp('(?:[{,])' + escape(local) + ' as ([\\w$]+)'))?.[1]; + assert.ok(key, 'Diagnostic function is already exported: ' + local); + return key; + }; + return { manager: '/assets/' + manager, state: '/assets/' + state, + gate: '/assets/' + name, gap: exported(gap), attach: exported(attach), + subscribeGap: exported(subscribe) }; + } + throw new Error('No compatible production SessionStream exports; rebuild-specific discovery needs updating'); +} + +let ids, modules; +const select = id => page.selectSession(id); +const modelReady = () => page.modelReady(); +const send = token => page.sendCase(token); +async function events() { + try { return (await readFile(path.join(run.root, 'acp-events.ndjson'), 'utf8')).trim().split('\n').map(JSON.parse); } + catch (error) { if (error.code === 'ENOENT') return []; throw error; } +} +const seen = async (type, token) => (await events()).some(e => e.type === type && e.token === token); +const waitEvent = (type, token) => page.until(() => seen(type, token), type + ' ' + token, 6000); +async function control(token, action = 'finish') { + const rows = await events(); + const prompt = rows.findLast(e => e.type === 'prompt' && e.token === token); + const start = rows.findLast(e => e.type === 'started' && e.pid === prompt.pid); + const response = await fetch('http://127.0.0.1:' + start.port, { + method: 'POST', body: JSON.stringify({ token, action, reason: 'end_turn' }), + }); + return response.json(); +} +async function install() { await page.execute(installObserver, { ids, modules }); } +async function state(id) { return page.execute(id => window.__acpDiagnosticSnapshot?.().find(s => s.id === id), id); } +async function refresh() { await page.refreshDocument(); await install(); } +async function capture(name) { + const value = await page.execute(() => ({ states: window.__acpDiagnosticSnapshot?.(), + trace: window.__acpTrace, text: document.body.innerText.slice(-1000) })); + await writeFile(path.join(run.root, name + '.json'), JSON.stringify(value, null, 2)); + return value; +} + +try { + modules = await diagnosticsModules(); + await page.click('[data-testid="nav-session-item"][data-session-id="workload-history-000"]'); + const workspaceId = await page.execute(async modulePath => { + const m = await import(modulePath); + const manager = Object.values(m).find(v => typeof v === 'function' && v.getInstance && v.prototype.sendMessage); + return manager.getInstance().context.flowChatStore.getState().sessions.get('workload-history-000').workspaceId; + }, modules.manager); + await page.invoke('save_acp_json_config', { jsonConfig: JSON.stringify({ acpClients: { controlled: { + name: 'Controlled ACP', command: process.execPath, args: [path.join(run.root, 'harness/tests/e2e/fixtures/controlled-acp-agent.mjs')], + env: { OPENBITFUN_ACP_FIXTURE_LOG: path.join(run.root, 'acp-events.ndjson') }, enabled: true, + } } }) }); + const create = async name => (await page.invoke('create_acp_flow_session', { request: { + clientId: 'controlled', sessionName: name, workspaceId, workspacePath: run.workspace, + } })).sessionId; + const A = await create('ACP recovery A'), B = await create('ACP switch target B'); + ids = [A, B]; result.ids = { A, B }; result.modules = modules; + await select(A); await modelReady(); await install(); + const saveCase = async (name, detail) => { mark(name, detail); await save(); }; + const promptCount = async token => (await events()).filter(e => e.type === 'prompt' && e.token === token).length; + const snapshot = () => page.invoke('restore_session_view', { request: {sessionId:A,workspaceId,workspacePath:run.workspace,tailTurnCount:8} }); + // Metadata must remain readable while the same ACP prompt owns its receiver. + await send('hold-metadata-reading'); await waitEvent('prompt', 'hold-metadata-reading'); + const assets = await readdir(path.join(run.root, 'frontend/assets')); + const apiModule = '/assets/' + assets.find(name => /^ACPClientAPI-.*\.js$/.test(name)); + const request = { sessionId: A, clientId: 'controlled', workspaceId, workspacePath: run.workspace }; + const readMetadata = () => page.execute(async ({ request, apiModule }) => { + const module = await import(apiModule); + const api = Object.values(module).find(value => typeof value === 'function' && value.getSessionOptions); + const start = performance.now(); + const invoke = window.__TAURI_INTERNALS__.invoke; + const reads = Promise.all([ + invoke('get_acp_session_options', { request }), + invoke('get_acp_session_commands', { request }), + api.getSessionOptions(request), api.getSessionCommands(request), + ]); + let timeout; + try { + const values = await Promise.race([reads, new Promise((_, reject) => { + timeout = setTimeout(() => reject(new Error('ACP metadata blocked by a running prompt')), 2000); + })]); + return { elapsedMs: performance.now() - start, values }; + } finally { clearTimeout(timeout); } + }, { request, apiModule }); + const metadataReads = [await readMetadata()]; + for (let index = 0; index < 3; index++) { + await select(B); await modelReady(); await select(A); await modelReady(); + metadataReads.push(await readMetadata()); + } + assert.ok(!(await seen('finished', 'hold-metadata-reading'))); + await control('hold-metadata-reading', 'metadata'); + let updated; + await page.until(async () => { + updated = await readMetadata(); + return updated.values[0].availableCommands.some(command => command.name === 'inspect') + && updated.values[0].configOptions.some(option => option.id === 'reasoning' && option.currentValue === 'high') + && updated.values[0].contextUsage?.used === 19; + }, 'live metadata snapshot updates', 6000); + assert.ok(updated.values[1].some(command => command.name === 'inspect')); + await saveCase('metadata-reads-and-live-updates-survive-running-session-switches', { metadataReads, updated }); + + // ACP send-now promotes queued input; it must not overlap the running prompt. + await send('auto-acp-queued-first'); await send('auto-acp-promoted-second'); + await page.until(async () => (await state(A)).queue.flat().length === 2, 'two ACP queued messages', 6000); + await page.promoteQueuedCase(1); + await page.until(async () => (await state(A)).queue.flat()[0]?.content.includes('auto-acp-promoted-second'), 'ACP send-now promotion', 4000); + await select(B); await select(A); await modelReady(); + assert.equal(await promptCount('auto-acp-promoted-second'), 0); + assert.equal(await promptCount('auto-acp-queued-first'), 0); + await control('hold-metadata-reading'); + await waitEvent('finished', 'auto-acp-promoted-second'); + await waitEvent('finished', 'auto-acp-queued-first'); + const ordered = (await events()).filter(event => event.type === 'prompt').map(event => event.token); + assert.ok(ordered.indexOf('auto-acp-promoted-second') < ordered.indexOf('auto-acp-queued-first')); + assert.equal(await promptCount('auto-acp-promoted-second'), 1); + assert.equal(await promptCount('auto-acp-queued-first'), 1); + await page.until(async () => (await state(A))?.state === 'idle', 'promoted ACP queue settles', 6000); + await saveCase('acp-send-now-and-switch-preserve-order-and-no-overlap', { ordered }); + + await page.invoke('set_acp_session_model', { request: { ...request, modelId: 'fixture-alt' } }); + await send('hold-model-snapshot'); await waitEvent('prompt', 'hold-model-snapshot'); + const changedModel = await readMetadata(); + assert.equal(changedModel.values[0].currentModelId, 'fixture-alt'); + await control('hold-model-snapshot'); await waitEvent('finished', 'hold-model-snapshot'); + await page.until(async () => (await state(A))?.state === 'idle', 'model snapshot turn settles', 6000); + await saveCase('successful-model-change-is-visible-during-the-next-prompt', { changedModel }); + + await send('hold-before-refresh'); await waitEvent('prompt', 'hold-before-refresh'); + await send('auto-restored-queue'); + await page.until(async () => (await state(A)).queue.flat().length === 1, 'first queue persisted', 6000); + await control('hold-before-refresh','pause'); + await select(B); await refresh(); + // Do not activate A: its persisted queue must acquire its host's running + // execution in the background, without submitting a second ACP prompt. + await page.until(async () => (await state(A))?.state === 'processing' && !(await state(A))?.gap, 'background running execution recovered', 10000); + assert.equal(await promptCount('auto-restored-queue'), 0); + const live = await snapshot(); + assert.equal(live.executionProjection,'acp'); + assert.ok(live.session.state.startsWith('Processing')); + assert.ok(live.runtimeEventSnapshot.events.some(e=>e.eventName==='agentic://dialog-turn-started')); + assert.ok(live.runtimeEventSnapshot.events.some(e => e.eventName === 'agentic://tool-event')); + assert.ok(live.runtimeEventSnapshot.events.some(e => e.eventName === 'agentic://text-chunk' + && e.payload.contentType === 'thinking')); + + await control('hold-before-refresh','resume'); + await delay(500); + assert.equal(await promptCount('auto-restored-queue'),0); + await saveCase('background-reload-keeps-the-original-prompt-running', {state:await state(A),snapshot:live}); + await capture('active-recovery'); + await control('hold-before-refresh'); + await waitEvent('finished','auto-restored-queue'); + await page.until(async()=>(await state(A))?.state==='idle'&&!(await state(A))?.gap,'background queue drained',8000); + assert.equal(await promptCount('auto-restored-queue'),1); + await select(A);await modelReady(); + await page.until(async () => { + const recovered = (await snapshot()).turns.find(turn => turn.turnId === live.runtimeEventSnapshot.activeTurnId); + return recovered?.modelRounds.some(round => round.textItems.some( + item => item.content.includes('ACP_STARTED:hold-before-refresh'), + )); + }, 'original ACP output persisted after replay', 6000); + await saveCase('restored-queue-drained-once-without-another-refresh',{state:await state(A)}); + await page.shot(path.join(run.root,'recovered-queue.png')); + await capture('after-recovery'); + + // Original failure's second turn: completing normally must no longer leave + // a stale presentation gate behind an otherwise idle ACP session. + await send('hold-after-refresh');await waitEvent('prompt','hold-after-refresh'); + await send('auto-after-refresh'); + await page.until(async()=>(await state(A)).queue.flat().length===1,'second queue',6000); + await select(B);await select(A); + await control('hold-after-refresh');await waitEvent('finished','auto-after-refresh'); + await page.until(async()=>(await state(A))?.state==='idle'&&!(await state(A))?.gap,'second queue settles',8000); + assert.equal(await promptCount('auto-after-refresh'),1); + await saveCase('original-stall-sequence-now-drains-automatically',{state:await state(A)}); + + await modelReady(); + await send('hold-delayed-cancel-acceptance');await waitEvent('prompt','hold-delayed-cancel-acceptance'); + await send('auto-after-cancel-acceptance'); + await page.until(async()=>(await state(A)).queue.flat().length===1,'cancel queue',6000); + await page.click('[data-testid="chat-input-cancel-btn"]'); + await select(B);await select(A);await delay(400); + assert.equal(await promptCount('auto-after-cancel-acceptance'),0,'cancel ACK must not release queue'); + await waitEvent('finished','auto-after-cancel-acceptance'); + await page.until(async()=>(await state(A))?.state==='idle'&&!(await state(A))?.cancelGate,'cancelled queue settles',8000); + await saveCase('delayed-cancel-and-switch-drains-after-real-terminal',{state:await state(A)}); + + await select(B);await modelReady(); + const direct={sessionId:B,clientId:'controlled',workspaceId,workspacePath:run.workspace, + turnId:'acceptance-idempotent-turn',userInput:'ACP_CASE:hold-idempotent'}; + await page.invoke('start_acp_dialog_turn',{request:direct}); + await waitEvent('prompt','hold-idempotent'); + await page.invoke('start_acp_dialog_turn',{request:direct}); + await assert.rejects(()=>page.invoke('start_acp_dialog_turn',{request:{...direct,turnId:'overlap',userInput:'ACP_CASE:auto-overlap'}}),/still executing/); + await assert.rejects(()=>page.invoke('start_acp_dialog_turn',{request:{...direct,userInput:'changed'}}),/different input/); + assert.equal(await promptCount('hold-idempotent'),1); + await control('hold-idempotent'); + await waitEvent('finished','hold-idempotent'); + await page.until(async()=>(await state(B))?.state==='idle','direct turn completed',8000); + await page.invoke('start_acp_dialog_turn',{request:direct}); + assert.equal(await promptCount('hold-idempotent'),1,'terminal retry must not re-run prompt'); + await saveCase('duplicate-and-overlapping-submission-admission-correct',{}); + + await send('hold-error-acceptance');await waitEvent('prompt','hold-error-acceptance'); + await send('auto-after-error-acceptance'); + await page.until(async()=>(await state(B)).queue.flat().length===1,'error queue',6000); + await control('hold-error-acceptance','error'); + await waitEvent('finished','auto-after-error-acceptance'); + await page.until(async()=>(await state(B))?.state==='idle','error recovery idle',8000); + await saveCase('protocol-error-drains-follow-up',{}); + + await modelReady(); + await send('hold-exit-acceptance');await waitEvent('prompt','hold-exit-acceptance'); + await send('auto-after-exit-acceptance'); + await page.until(async()=>(await state(B)).queue.flat().length===1,'exit queue',6000); + await control('hold-exit-acceptance','exit'); + await waitEvent('finished','auto-after-exit-acceptance'); + await page.until(async()=>(await state(B))?.state==='idle'&&!(await state(B))?.gap,'restarted ACP settles',8000); + await saveCase('agent-process-exit-reconnects-and-drains',{}); + await capture('final-state'); + result.passed = true; + run.report.functionalPassed = true; + run.report.passed = true; + await save(); + console.log(JSON.stringify({passed:true,root:run.root,frontend:run.report.frontend.revision,cases:result.stages.map(s=>s.name)})); + +} catch (error) { + result.error = error.stack || String(error); + await capture('failure').catch(() => {}); + await page.shot(path.join(run.root, 'failure.png')).catch(() => {}); + await save(); + throw error; +} finally { + await run.close(); +} From 8aa571269e43f929e2a18967b187a68d7e3112e3 Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Wed, 18 Nov 2026 16:44:32 +0800 Subject: [PATCH 2/2] fix(desktop): adapt ACP snapshots at the host boundary Return session execution state and the shared event projection from the host effects port. Convert protocol-specific snapshots in the production adapter so the session application stays independent of the ACP crate. --- .../src/runtime/session_application.rs | 18 +++++-------- .../src/runtime/session_host_effects.rs | 26 +++++++++++++------ 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/src/apps/desktop/src/runtime/session_application.rs b/src/apps/desktop/src/runtime/session_application.rs index a0114f3395..cc26671e24 100644 --- a/src/apps/desktop/src/runtime/session_application.rs +++ b/src/apps/desktop/src/runtime/session_application.rs @@ -229,16 +229,18 @@ impl DesktopSessionScopeResolver { } } +pub(crate) struct DesktopSessionExecutionSnapshot { + pub running: bool, + pub projection: SessionEventProjectionSnapshot, +} + #[async_trait] pub(crate) trait DesktopSessionHostEffects: Send + Sync { async fn release_session(&self, session_id: &str); fn supports_acp_projection(&self) -> bool { false } - fn acp_execution_snapshot( - &self, - _session_id: &str, - ) -> Option { + fn acp_execution_snapshot(&self, _session_id: &str) -> Option { None } } @@ -933,13 +935,7 @@ impl DesktopSessionApplication { } else { SessionState::Idle }; - runtime_event_snapshot = Some(SessionEventProjectionSnapshot { - session_id: acp.projection.session_id, - stream_id: acp.projection.stream_id, - cursor: acp.projection.cursor, - active_turn_id: acp.projection.active_turn_id, - events: acp.projection.events, - }); + runtime_event_snapshot = Some(acp.projection); } else { // No prompt is owned by this host process. Do not revive a // pre-restart execution from a persisted intermediate record. diff --git a/src/apps/desktop/src/runtime/session_host_effects.rs b/src/apps/desktop/src/runtime/session_host_effects.rs index 07d356ec1d..6f7736c660 100644 --- a/src/apps/desktop/src/runtime/session_host_effects.rs +++ b/src/apps/desktop/src/runtime/session_host_effects.rs @@ -1,10 +1,11 @@ use std::sync::Arc; use async_trait::async_trait; +use openbitfun_agent_runtime::sdk::{SessionEventJournal, SessionEventProjectionSnapshot}; -use super::session_application::DesktopSessionHostEffects; +use super::session_application::{DesktopSessionExecutionSnapshot, DesktopSessionHostEffects}; -pub(super) struct AcpJournalAdapter(pub Arc); +pub(super) struct AcpJournalAdapter(pub Arc); impl openbitfun_acp::client::AcpProjectionJournal for AcpJournalAdapter { fn record( @@ -47,13 +48,22 @@ impl DesktopSessionHostEffects for ProductionDesktopSessionHostEffects { self.acp_client_service.is_some() } - fn acp_execution_snapshot( - &self, - session_id: &str, - ) -> Option { - self.acp_client_service + fn acp_execution_snapshot(&self, session_id: &str) -> Option { + let snapshot = self + .acp_client_service .as_ref()? - .execution_snapshot(session_id) + .execution_snapshot(session_id)?; + let projection = snapshot.projection; + Some(DesktopSessionExecutionSnapshot { + running: snapshot.running, + projection: SessionEventProjectionSnapshot { + session_id: projection.session_id, + stream_id: projection.stream_id, + cursor: projection.cursor, + active_turn_id: projection.active_turn_id, + events: projection.events, + }, + }) } async fn release_session(&self, session_id: &str) {