diff --git a/Cargo.lock b/Cargo.lock index 8dfff09b2a..4f3e491bd5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5710,6 +5710,7 @@ dependencies = [ "serde_json", "sha2", "tar", + "tempfile", "tokio", "tokio-util", "uuid", diff --git a/docs/architecture/session-projection.md b/docs/architecture/session-projection.md index 212ca0bc00..d99678ff8b 100644 --- a/docs/architecture/session-projection.md +++ b/docs/architecture/session-projection.md @@ -46,32 +46,57 @@ 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 ACP client on the executing host owns admission, cancellation, agent binding +and the conversation transcript. A repeated submission with the same Turn ID +and input returns its existing admission. The host accepts the input before +contacting the agent. If earlier history is missing, it persists the admission +and assigns the Turn's storage index after replay, before sending the prompt. +The host records ordered text, thoughts and tool events in the Session journal. +On completion it writes the terminal Turn to ordinary conversation history. +If that write fails, the view receives the recorded outcome and a storage warning. +The journal retains the Turn for a later save. Closing a view leaves the Turn +running on the host. A restarted host can recover partial output and report an unknown +outcome when the agent's terminal response was never recorded. + +Views use the existing Session read fence and the optional +`executionProjection: "acp"` marker to hydrate history and execution state. +Older hosts keep their persisted-history path. Older frontends can still send +their checkpoints. The persistence owner protects the runtime-owned range of +ordinary ACP turns. Legacy turns and other session types keep their existing +checkpoint rules. Peer views observe the executing host's state. CLI Peer hosts +continue to report unsupported ACP client operations explicitly. + +Switching views and reloading the WebView read the host's live metadata snapshot +or the saved options. The last confirmed model and conversation are available +with the agent offline. Opening a session that has never saved agent options +attaches it once to obtain them, even if the user never opens the model picker. +Sending or explicitly opening the agent controls can also attach the original +session. Normal reattachment prefers the agent's advertised resume capability. +After an unconfirmed stop the host requires load before sending another prompt. +An agent with neither capability needs a new chat. The old chat keeps its +original binding and local history. If load is available, a known gap takes +priority over resume. The runtime registers its receiver before requesting +load and consumes the history through the response. With complete local +history it extracts only session metadata. With a known gap it matches +stable message IDs and unambiguous legacy history. Consecutive user chunks +without message IDs can represent one prompt or several. The saved prompts +decide where they split, using the text the agent was sent, which the host +keeps when it differs from the visible message. A split counts only when +exactly one placement of the saved prompts explains the replay. Otherwise +only stable IDs repair that replay. A local unsent turn has no position in +the agent's history, so an unanchored remote suffix leaves the gap open. +An unresolvable boundary is remembered together with the local history it +was tried against, so a later attach skips the full replay until that history +changes. An incomplete or still growing replay is not remembered. A load +retires its connection after 60 seconds without an update or 10 minutes +overall. The next attempt uses the saved binding, and the user's input remains +available. + +An accepted turn whose prompt is not sent yet follows its own Turn ID. A stop, +a session release or a newer Turn ends it before the prompt reaches the +agent, including while the agent starts or the saved session loads. Releasing +a session waits for a load already in progress, so no replay writes history +after the session is deleted. ## The problem this replaces diff --git a/src/apps/desktop/src/api/acp_client_api.rs b/src/apps/desktop/src/api/acp_client_api.rs index 4acee95aed..dfa3911fc9 100644 --- a/src/apps/desktop/src/api/acp_client_api.rs +++ b/src/apps/desktop/src/api/acp_client_api.rs @@ -8,6 +8,7 @@ use openbitfun_acp::client::{ SetAcpSessionConfigOptionRequest, SetAcpSessionModelRequest, SubmitAcpPermissionResponseRequest, }; +use openbitfun_core::agentic::image_analysis::ImageContextData; use openbitfun_core::service::workspace::WorkspaceInfo; use openbitfun_runtime_ports::SessionStorePort; use serde::{Deserialize, Serialize}; @@ -150,6 +151,10 @@ pub struct StartAcpDialogTurnRequest { pub user_input: String, #[serde(default)] pub original_user_input: Option, + #[serde(default)] + pub image_contexts: Option>, + #[serde(default)] + pub user_message_metadata: Option, pub turn_id: String, /// Workspace identity; authoritative when present. #[serde(default)] @@ -185,6 +190,8 @@ pub struct CancelAcpDialogTurnRequest { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GetAcpSessionOptionsRequest { + #[serde(default)] + pub observe_only: bool, pub session_id: String, pub client_id: String, /// Workspace identity; authoritative when present. @@ -463,13 +470,42 @@ 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, - )? + let mut user_metadata = request.user_message_metadata; + if let Some(images) = request.image_contexts.filter(|images| !images.is_empty()) { + let mut fields = super::agentic_api::desktop_user_message_metadata(user_metadata); + fields.entry("images").or_insert_with(|| { + let images = images.into_iter().map(|image| { + let name = image + .metadata + .as_ref() + .and_then(|metadata| metadata.get("name")) + .and_then(serde_json::Value::as_str); + serde_json::json!({ + "id": image.id, + "name": name, + "mime_type": image.mime_type, + "image_path": image.image_path, + "data_url": image.data_url, + }) + }); + serde_json::Value::Array(images.collect()) + }); + fields + .entry("original_text") + .or_insert_with(|| original_user_input.clone().into()); + user_metadata = Some(fields.into()); + } + let Some(start) = service + .admit_dialog_turn( + &session_id, + &turn_id, + &request.client_id, + &user_input, + &original_user_input, + user_metadata, + session_storage_path.as_deref(), + ) + .await? else { return Ok(()); }; @@ -480,6 +516,7 @@ pub async fn start_acp_dialog_turn( tokio::spawn(async move { let mut current_round_id: Option = None; let mut current_round_has_tool_calls = false; + let mut terminal = None; let result = service .prompt_agent_stream( &request.client_id, @@ -487,7 +524,8 @@ pub async fn start_acp_dialog_turn( workspace_path, remote_connection_id, request.session_id.clone(), - session_storage_path, + Some(&turn_id), + session_storage_path.clone(), request.timeout_seconds, |event| { match event { @@ -667,33 +705,7 @@ pub async fn start_acp_dialog_turn( ) })?; } - AcpClientStreamEvent::Completed => { - if let Some(round_id) = current_round_id.take() { - emit_acp_model_round_completed( - &app_handle, - &request.session_id, - &request.turn_id, - round_id, - current_round_has_tool_calls, - )?; - } - app_handle - .emit( - "agentic://dialog-turn-completed", - serde_json::json!({ - "sessionId": request.session_id, - "turnId": request.turn_id, - "subagentParentInfo": null, - "partialRecoveryReason": null, - }), - ) - .map_err(|e| { - openbitfun_core::util::errors::OpenBitFunError::service( - e.to_string(), - ) - })?; - } - AcpClientStreamEvent::Cancelled => { + AcpClientStreamEvent::Completed | AcpClientStreamEvent::Cancelled => { if let Some(round_id) = current_round_id.take() { emit_acp_model_round_completed( &app_handle, @@ -703,20 +715,20 @@ pub async fn start_acp_dialog_turn( current_round_has_tool_calls, )?; } - app_handle - .emit( - "agentic://dialog-turn-cancelled", - serde_json::json!({ - "sessionId": request.session_id, - "turnId": request.turn_id, - "subagentParentInfo": null, - }), - ) - .map_err(|e| { - openbitfun_core::util::errors::OpenBitFunError::service( - e.to_string(), - ) - })?; + let name = if matches!(event, AcpClientStreamEvent::Cancelled) { + "agentic://dialog-turn-cancelled" + } else { + "agentic://dialog-turn-completed" + }; + terminal = Some(( + name, + serde_json::json!({ + "sessionId": request.session_id, + "turnId": request.turn_id, + "subagentParentInfo": null, + "partialRecoveryReason": null, + }), + )); } } Ok(()) @@ -725,17 +737,61 @@ pub async fn start_acp_dialog_turn( .await; if let Err(error) = result { - let _ = app_handle.emit( + use openbitfun_core::util::errors::OpenBitFunError; + let mut detail = error.error_detail(); + let detail = match &error { + OpenBitFunError::OutcomeUnknown(_) => { + detail.recovery_constraint = Some("acp_stop_unconfirmed".into()); + detail.retryable = Some(false); + detail.action_hints = vec!["copy_diagnostics".into()]; + Some(detail) + } + OpenBitFunError::Session(reason) => { + detail.provider = Some(format!("acp:{}", request.client_id)); + detail.provider_message = Some(reason.clone()); + Some(detail) + } + OpenBitFunError::AIProvider(_) => Some(detail), + _ => None, + }; + terminal = Some(( "agentic://dialog-turn-failed", serde_json::json!({ "sessionId": request.session_id, "turnId": request.turn_id, "error": error.to_string(), - "errorCategory": null, - "errorDetail": null, + "errorCategory": detail.as_ref().map(|detail| &detail.category), + "errorDetail": detail, "subagentParentInfo": null, }), - ); + )); + } + if let Some((name, mut payload)) = terminal { + match service + .finish_dialog_turn( + &session_id, + session_storage_path.as_deref(), + name, + &mut payload, + ) + .await + { + Ok(()) => { + let _ = app_handle.publish(name, payload); + } + Err(error) => { + log::error!("Failed to commit ACP turn {turn_id}: {error}"); + // A retired turn belongs to a newer execution and is dropped. A + // released session has no execution left, so a view that is still + // mounted (for example after a failed delete) would stay running. + // Settle it with the outcome the agent confirmed, as an uncursored + // event, which live subscribers accept without a snapshot cursor. + // Its history was not written, and that turn is recovered on open. + if service.execution_snapshot(&session_id).is_none() { + let _ = app_handle.publish(name, payload); + } + } + } } }); @@ -795,6 +851,17 @@ pub async fn get_acp_session_options( ), None => (None, None, None), }; + if request.observe_only { + return service + .observe_session_options( + &request.client_id, + &request.session_id, + workspace_path.as_deref(), + session_storage_path.as_deref(), + ) + .await + .map_err(|e| e.to_string()); + } service .get_session_options( &request.client_id, @@ -832,6 +899,18 @@ pub async fn get_acp_session_commands( ), None => (None, None, None), }; + if request.observe_only { + return service + .observe_session_options( + &request.client_id, + &request.session_id, + workspace_path.as_deref(), + session_storage_path.as_deref(), + ) + .await + .map(|options| options.available_commands.unwrap_or_default()) + .map_err(|e| e.to_string()); + } service .get_session_commands( &request.client_id, diff --git a/src/apps/desktop/src/api/agentic_api.rs b/src/apps/desktop/src/api/agentic_api.rs index 320ad2e4bf..a438f2403b 100644 --- a/src/apps/desktop/src/api/agentic_api.rs +++ b/src/apps/desktop/src/api/agentic_api.rs @@ -2679,7 +2679,7 @@ fn desktop_dialog_turn_request( }) } -fn desktop_user_message_metadata( +pub(super) fn desktop_user_message_metadata( metadata: Option, ) -> serde_json::Map { match metadata { diff --git a/src/apps/desktop/src/runtime/session_application.rs b/src/apps/desktop/src/runtime/session_application.rs index cc26671e24..8c9f9eedcf 100644 --- a/src/apps/desktop/src/runtime/session_application.rs +++ b/src/apps/desktop/src/runtime/session_application.rs @@ -27,7 +27,7 @@ use openbitfun_core::service::remote_ssh::SSHConnectionManager; use openbitfun_core::service::session::{ DialogTurnData, DialogTurnKind, SessionContextUsage, SessionMetadata, SessionStatus, SessionTranscriptExport, SessionTranscriptExportOptions, SessionTurnCatalog, - SessionTurnWindowResponse, + SessionTurnWindowResponse, SESSION_PROVIDER_ACP, SESSION_PROVIDER_METADATA_KEY, }; use openbitfun_core::service::session_usage::SessionUsageReport; use openbitfun_core::service::token_usage::TokenUsageService; @@ -237,6 +237,10 @@ pub(crate) struct DesktopSessionExecutionSnapshot { #[async_trait] pub(crate) trait DesktopSessionHostEffects: Send + Sync { async fn release_session(&self, session_id: &str); + fn forget_session_recovery(&self, _session_id: &str) {} + async fn recover_acp_history(&self, _path: &Path, _session: &str) -> Result<(), String> { + Ok(()) + } fn supports_acp_projection(&self) -> bool { false } @@ -874,8 +878,36 @@ impl DesktopSessionApplication { stream_id: &str, cursor: u64, ) -> Option { - self.agent_runtime - .session_events_since(session_id, stream_id, cursor) + let mut backfill = self + .agent_runtime + .session_events_since(session_id, stream_id, cursor)?; + if let SessionEventBackfill::Delta { + cursor: end, + events, + .. + } = &mut backfill + { + if matches!( + events.last(), + Some( + openbitfun_events::AgenticEvent::DialogTurnCompleted { .. } + | openbitfun_events::AgenticEvent::DialogTurnCancelled { .. } + | openbitfun_events::AgenticEvent::DialogTurnFailed { .. } + ) + ) { + if let Some(acp) = self.host_effects.acp_execution_snapshot(session_id) { + // The history write fences terminal delivery for both live subscribers and cursor readers. + if acp.running + && acp.projection.stream_id == stream_id + && acp.projection.cursor < *end + { + events.pop(); + *end = acp.projection.cursor; + } + } + } + } + Some(backfill) } pub(crate) fn has_acp_execution(&self, session_id: &str) -> bool { @@ -901,6 +933,34 @@ impl DesktopSessionApplication { let resolve_storage_path_duration_ms = path_started_at.elapsed().as_millis().min(u64::MAX as u128) as u64; on_storage_path_resolved(resolve_storage_path_duration_ms); + let metadata = self + .compatibility + .load_persisted_session_metadata(&storage_path, session_id) + .await + .map_err(desktop_core_session_error)?; + if self.host_effects.supports_acp_projection() + && metadata.as_ref().is_some_and(|m| { + m.agent_type.starts_with("acp:") + || m.custom_metadata + .as_ref() + .and_then(|v| v.get(SESSION_PROVIDER_METADATA_KEY)) + .and_then(serde_json::Value::as_str) + == Some(SESSION_PROVIDER_ACP) + }) + { + // The saved history is readable even when this recovery cannot write. + // Opening must not depend on it; the next send retries and reports. + if let Err(error) = self + .host_effects + .recover_acp_history(&storage_path, session_id) + .await + { + log::warn!( + "Failed to recover interrupted ACP history while restoring a session: session_id={session_id} error={error}" + ); + } + } + let current_context_usage = metadata.and_then(|m| m.current_context_usage); let (mut session, turns, total_turn_count, turn_catalog, mut timings) = self .compatibility .restore_session_view_from_storage_path( @@ -946,12 +1006,6 @@ impl DesktopSessionApplication { } else { None }; - let current_context_usage = self - .compatibility - .load_persisted_session_metadata(&storage_path, session_id) - .await - .map_err(desktop_core_session_error)? - .and_then(|metadata| metadata.current_context_usage); timings.resolve_storage_path_duration_ms = resolve_storage_path_duration_ms; Ok(DesktopSessionViewRestore { execution_projection, @@ -1062,6 +1116,7 @@ async fn delete_session_with_host_effects( }) .await .map_err(|error| DesktopSessionApplicationError::Runtime(error.into_message()))?; + host_effects.forget_session_recovery(&session_id); Ok(()) } diff --git a/src/apps/desktop/src/runtime/session_host_effects.rs b/src/apps/desktop/src/runtime/session_host_effects.rs index 6f7736c660..121137278e 100644 --- a/src/apps/desktop/src/runtime/session_host_effects.rs +++ b/src/apps/desktop/src/runtime/session_host_effects.rs @@ -13,13 +13,24 @@ impl openbitfun_acp::client::AcpProjectionJournal for AcpJournalAdapter { event: &openbitfun_events::AgenticEvent, ) -> Option { self.0 - .record(event) + .record_until_checkpoint(event) .map(|cursor| openbitfun_acp::client::AcpEventCursor { stream_id: cursor.stream_id, cursor: cursor.cursor, }) } + fn pending_checkpoint(&self, session: &str) -> Vec { + self.0 + .pending_checkpoint(session) + .map(|log| log.events) + .unwrap_or_default() + } + + fn checkpoint_saved(&self, session: &str) { + self.0.checkpoint_saved(session); + } + fn snapshot(&self, session: &str) -> openbitfun_acp::client::AcpEventProjectionSnapshot { let snapshot = self.0.snapshot(session); openbitfun_acp::client::AcpEventProjectionSnapshot { @@ -44,6 +55,20 @@ impl ProductionDesktopSessionHostEffects { #[async_trait] impl DesktopSessionHostEffects for ProductionDesktopSessionHostEffects { + async fn recover_acp_history( + &self, + path: &std::path::Path, + session: &str, + ) -> Result<(), String> { + if let Some(service) = &self.acp_client_service { + service + .recover_stored_dialog_turn(path, session) + .await + .map_err(|e| e.to_string())?; + } + Ok(()) + } + fn supports_acp_projection(&self) -> bool { self.acp_client_service.is_some() } @@ -66,6 +91,12 @@ impl DesktopSessionHostEffects for ProductionDesktopSessionHostEffects { }) } + fn forget_session_recovery(&self, session_id: &str) { + if let Some(service) = self.acp_client_service.as_ref() { + service.forget_session_recovery(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/assembly/core/src/agentic/persistence/manager.rs b/src/crates/assembly/core/src/agentic/persistence/manager.rs index 3afeae9231..65a5435318 100644 --- a/src/crates/assembly/core/src/agentic/persistence/manager.rs +++ b/src/crates/assembly/core/src/agentic/persistence/manager.rs @@ -3522,6 +3522,22 @@ impl PersistenceManager { let _persistence_guard = persistence_lock.lock().await; let observed_revision = self.turn_window_revision(workspace_path, session_id).await; + if let Some(revision) = observed_revision + .as_ref() + .filter(|_| loaded_turns.is_empty()) + { + if let Some(catalog) = self + .cached_complete_turn_catalog( + workspace_path, + session_id, + revision, + visible_total_turn_count, + ) + .await + { + return Ok(catalog); + } + } let mut scanned_paths = None; let (physical_indices, can_persist_physical_projection) = match self .list_indexed_turn_paths(workspace_path, session_id) @@ -3989,6 +4005,25 @@ impl PersistenceManager { &self, workspace_path: &Path, turn: &DialogTurnData, + ) -> OpenBitFunResult<()> { + self.write_dialog_turn(workspace_path, turn, false).await + } + + /// UI checkpoints from older clients may still arrive after the host took + /// ownership. Decide under the same session write lock as the actual update. + pub async fn save_external_view_checkpoint( + &self, + workspace_path: &Path, + turn: &DialogTurnData, + ) -> OpenBitFunResult<()> { + self.write_dialog_turn(workspace_path, turn, true).await + } + + async fn write_dialog_turn( + &self, + workspace_path: &Path, + turn: &DialogTurnData, + observer: bool, ) -> OpenBitFunResult<()> { Self::validate_session_id(&turn.session_id)?; #[cfg(feature = "external-sources")] @@ -4020,6 +4055,17 @@ impl PersistenceManager { turn.session_id )) })?; + if observer + && turn.kind == DialogTurnKind::UserDialog + && metadata + .custom_metadata + .as_ref() + .and_then(|m| m.get("acpRuntimeFromTurn")) + .and_then(|v| v.as_u64()) + .is_some_and(|first| turn.turn_index as u64 >= first) + { + return Ok(()); + } self.ensure_turns_dir(workspace_path, &turn.session_id) .await?; @@ -4244,6 +4290,24 @@ impl PersistenceManager { .map(|file| file.turn)) } + /// Highest Turn position that has a stored file, independent of the + /// metadata Turn count, which can lag behind after an interrupted write. + pub async fn max_stored_turn_index( + &self, + workspace_path: &Path, + session_id: &str, + ) -> OpenBitFunResult> { + Self::validate_session_id(session_id)?; + #[cfg(feature = "external-sources")] + self.ensure_external_session_materialized(workspace_path, session_id) + .await?; + Ok(self + .list_indexed_turn_paths(workspace_path, session_id) + .await? + .last() + .map(|(index, _)| *index)) + } + async fn list_indexed_turn_paths( &self, workspace_path: &Path, @@ -6966,6 +7030,11 @@ mod tests { ) .expect("complete catalog should deserialize"); assert_eq!(persisted_complete, complete); + let read_catalog = + || manager.load_session_turn_catalog(workspace.path(), &session_id, &[], 5); + assert_eq!(read_catalog().await.unwrap(), complete); + std::fs::remove_file(&catalog_path).expect("remove the repaired sidecar"); + assert!(!read_catalog().await.unwrap().complete); } #[tokio::test] diff --git a/src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs b/src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs index 940f70196c..0b5f220706 100644 --- a/src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs +++ b/src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs @@ -97,6 +97,24 @@ impl PersistenceManager { }); } + pub(super) async fn cached_complete_turn_catalog( + &self, + workspace_path: &Path, + session_id: &str, + revision: &TurnWindowRevision, + visible_count: usize, + ) -> Option { + let key = self.turn_catalog_path(workspace_path, session_id); + let cache = self.turn_window_index_cache.lock().await; + let entry = cache.entries.iter().find(|entry| entry.key == key)?; + let catalog = &entry.index.catalog; + (entry.revision == *revision + && !entry.index.needs_catalog_repair + && catalog.complete + && catalog.entries.len() == visible_count) + .then(|| catalog.clone()) + } + pub(super) async fn forget_turn_window_index(&self, workspace_path: &Path, session_id: &str) { let key = self.turn_catalog_path(workspace_path, session_id); self.turn_window_index_cache diff --git a/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs b/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs index 1ad1d80643..0f5d5d7e33 100644 --- a/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs +++ b/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs @@ -734,7 +734,7 @@ impl Default for PathManager { #[cfg(any(test, feature = "test-support"))] impl PathManager { - pub(crate) fn with_user_root_for_tests(user_root: PathBuf) -> Self { + pub fn with_user_root_for_tests(user_root: PathBuf) -> Self { let base = user_root .parent() .map(Path::to_path_buf) diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index a5e83d97f3..94461276d1 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -2134,11 +2134,11 @@ impl CoreAgentRuntimeCompatibility { .is_externally_projected_session(&permit.storage_path, &permit.session_id) .await? { - // No Runtime history branch exists to validate against: the external - // agent owns the conversation and the projection is the only writer. + // Older observers still write checkpoints. The store protects + // the suffix owned by an external session runtime. return self .persistence - .save_dialog_turn(&permit.storage_path, turn) + .save_external_view_checkpoint(&permit.storage_path, turn) .await; } let session = self diff --git a/src/crates/execution/agent-runtime/src/session_event_journal.rs b/src/crates/execution/agent-runtime/src/session_event_journal.rs index 2bfcd46301..f69154435c 100644 --- a/src/crates/execution/agent-runtime/src/session_event_journal.rs +++ b/src/crates/execution/agent-runtime/src/session_event_journal.rs @@ -242,6 +242,30 @@ impl SessionEventJournal { /// the event is not represented by this projection; attachment must always /// release that live event instead of letting a snapshot cursor cover it. pub fn record(&self, event: &AgenticEvent) -> Option { + self.record_event(event, false) + } + + /// An external execution owner acknowledges the terminal event after its + /// canonical conversation write succeeds. Until then the raw log survives. + pub fn record_until_checkpoint(&self, event: &AgenticEvent) -> Option { + self.record_event(event, true) + } + + pub fn pending_checkpoint(&self, session: &str) -> Option { + self.store.as_ref()?.load(session) + } + + pub fn checkpoint_saved(&self, session: &str) { + if let Some(store) = &self.store { + store.discard(session); + } + } + + fn record_event( + &self, + event: &AgenticEvent, + retain_terminal: bool, + ) -> Option { let session_id = event.session_id()?.to_string(); let mut state = lock_state(&self.state); if matches!(event, AgenticEvent::SessionDeleted { .. }) { @@ -288,7 +312,7 @@ impl SessionEventJournal { // Release the lock before touching the store: an append must // never stall the delivery stream it is recording. drop(state); - if terminal { + if terminal && !retain_terminal { store.discard(&session_id); } else { store.append(&session_id, &stream_id, cursor, event); @@ -995,6 +1019,20 @@ mod tests { // Runtime process and replays it instead of comparing cursors. assert_eq!(after.stream_id, before.stream_id); assert_ne!(after.stream_id, restarted.snapshot("session-2").stream_id); + let stopped = AgenticEvent::DialogTurnCancelled { + session_id: "session-1".into(), + turn_id: "turn-1".into(), + }; + first.record_until_checkpoint(&stopped); + let log = restarted + .pending_checkpoint("session-1") + .expect("terminal kept until the history is saved"); + assert!(matches!( + log.events.last(), + Some(AgenticEvent::DialogTurnCancelled { .. }) + )); + restarted.checkpoint_saved("session-1"); + assert!(first.pending_checkpoint("session-1").is_none()); } #[test] diff --git a/src/crates/interfaces/acp/AGENTS-CN.md b/src/crates/interfaces/acp/AGENTS-CN.md index 2ad4df85c2..ad29a78cf3 100644 --- a/src/crates/interfaces/acp/AGENTS-CN.md +++ b/src/crates/interfaces/acp/AGENTS-CN.md @@ -35,6 +35,6 @@ Desktop 注入既有的会话事件日志,通过可选的 `executionProjection 元数据并发验证: `cargo test -p openbitfun-acp --no-default-features --features client,openbitfun-core/git --lib client::manager::tests::metadata_`。 -协议接收器仍串行持有;按会话保存的 watch 快照支持长请求或变更期间的读取。 -首次读取等待快照发布或初始化锁释放;模型、配置变更和流内元数据更新后发布新快照。 -空闲读取仍排空待处理通知;重建连接不得复用旧快照,不能增加第二个协议流读取者来解决阻塞。 +长请求持有协议接收器。切换视图读取宿主的实时快照或已保存的会话选项。显式操作可以重新连接原会话并消费待处理的更新。由唯一的接收器发布模型、命令和配置变化。 + +使用 `client::manager::recovery_tests` 验证会话历史持久化、冷启动查看和响应前的 ACP 历史回放。宿主先将工作区会话的终态写入正式历史,再发布完成事件并清理日志。 diff --git a/src/crates/interfaces/acp/AGENTS.md b/src/crates/interfaces/acp/AGENTS.md index 99f3e68b2b..5144e90ad1 100644 --- a/src/crates/interfaces/acp/AGENTS.md +++ b/src/crates/interfaces/acp/AGENTS.md @@ -61,14 +61,14 @@ 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 prompt owns the protocol receiver. A passive observer reads the host watch +or the saved session options. Explicit agent operations can attach the original +session and process pending metadata. New model, command and configuration facts +are published by the receiver. Keep a single reader for the session stream. -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. +The execution tests cover prompt admission receipts, turn-bound cancellation +and live and replay cursors. Run `client::manager::recovery_tests` for history +persistence, cold observation and pre-response ACP replay. The host saves +workspace-backed turns before publishing terminal events and keeps the journal +until that write succeeds. Desktop injects the session journal and exposes the +additive `executionProjection: "acp"` restore marker. diff --git a/src/crates/interfaces/acp/Cargo.toml b/src/crates/interfaces/acp/Cargo.toml index 4f74aabb6f..b175190100 100644 --- a/src/crates/interfaces/acp/Cargo.toml +++ b/src/crates/interfaces/acp/Cargo.toml @@ -67,7 +67,9 @@ uuid = { workspace = true } sha2 = { workspace = true, optional = true } [dev-dependencies] -tokio = { workspace = true, features = ["rt-multi-thread"] } +openbitfun-core = { path = "../../assembly/core", features = ["test-support"] } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["rt-multi-thread", "test-util"] } [lints] workspace = true diff --git a/src/crates/interfaces/acp/src/client/execution.rs b/src/crates/interfaces/acp/src/client/execution.rs index 5027508052..0830c32c6f 100644 --- a/src/crates/interfaces/acp/src/client/execution.rs +++ b/src/crates/interfaces/acp/src/client/execution.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; +use openbitfun_core::service::session::DialogTurnData; use openbitfun_events::AgenticEvent; use serde_json::{json, Value}; @@ -12,6 +13,8 @@ use serde_json::{json, Value}; pub trait AcpProjectionJournal: Send + Sync { fn record(&self, event: &AgenticEvent) -> Option; fn snapshot(&self, session: &str) -> AcpEventProjectionSnapshot; + fn pending_checkpoint(&self, session: &str) -> Vec; + fn checkpoint_saved(&self, session: &str); } #[derive(Debug, Clone)] @@ -34,13 +37,22 @@ fn attach_cursor(payload: &mut Value, cursor: AcpEventCursor) { payload["__openbitfunRuntimeEventCursor"] = cursor.cursor.into(); } -#[derive(PartialEq, Eq)] struct SubmissionReceipt { client: String, input: String, original_input: String, } +impl SubmissionReceipt { + fn matches(&self, client: &str, input: &str, original_input: &str) -> Result { + if self.client == client && self.input == input && self.original_input == original_input { + Ok(true) + } else { + Err("ACP turn id was already accepted with different input".into()) + } + } +} + #[derive(Debug, Clone)] pub struct AcpExecutionSnapshot { pub running: bool, @@ -49,9 +61,14 @@ pub struct AcpExecutionSnapshot { } struct Execution { + transcript: Option, + awaiting_history: bool, + prompt_submitted: bool, turn_id: String, running: bool, cancelling: bool, + // Wakes a prompt that is still waiting for its session before submission. + pending_cancel: tokio::sync::watch::Sender, // 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. @@ -87,18 +104,37 @@ impl AcpExecutions { Ok(()) } - /// `None` is an identical, already accepted request, not a new prompt. - pub(super) fn admit( + pub(super) fn already_admitted( &self, session: &str, turn: &str, client: &str, input: &str, original_input: &str, - ) -> Result, String> { + ) -> Result { 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 state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + state + .sessions + .get(session) + .and_then(|e| e.receipts.get(turn)) + .map_or(Ok(false), |receipt| { + receipt.matches(client, input, original_input) + }) + } + + /// `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, + transcript: Option<(DialogTurnData, bool)>, + ) -> Result, String> { let fingerprint = SubmissionReceipt { client: client.into(), input: input.into(), @@ -113,39 +149,61 @@ impl AcpExecutions { .sessions .entry(session.into()) .or_insert_with(|| Execution { + transcript: None, + awaiting_history: false, + prompt_submitted: false, turn_id: String::new(), running: false, cancelling: false, + pending_cancel: tokio::sync::watch::channel(false).0, 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()) - }; + return accepted + .matches(client, input, original_input) + .map(|_| None); } if execution.running { return Err("ACP session is still executing its previous turn".into()); } + execution.awaiting_history = transcript.as_ref().is_some_and(|(_, pending)| *pending); + let transcript = transcript.map(|(data, _)| data); + let turn_index = transcript + .as_ref() + .filter(|_| !execution.awaiting_history) + .map(|data| data.turn_index); + let metadata = transcript.as_ref().map(|data| { + let mut fields = data + .user_message + .metadata + .clone() + .unwrap_or_else(|| json!({})); + if let Some(object) = fields.as_object_mut() { + object.insert("acpRuntimeOwnsHistory".into(), true.into()); + } + fields + }); + execution.transcript = transcript; + execution.prompt_submitted = false; execution.turn_id = turn.into(); execution.running = true; execution.cancelling = false; + execution.pending_cancel = tokio::sync::watch::channel(false).0; execution.receipts.insert(turn.into(), fingerprint); let event = AgenticEvent::DialogTurnStarted { session_id: session.into(), turn_id: turn.into(), - turn_index: 0, + turn_index: turn_index.unwrap_or(0), user_input: input.into(), original_user_input: Some(original_input.into()), - user_message_metadata: None, + user_message_metadata: metadata, 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; + projected["turnIndex"] = serde_json::json!(turn_index); attach_cursor(&mut projected, cursor); Ok(Some(projected)) } @@ -175,6 +233,43 @@ impl AcpExecutions { } } + /// An accepted turn can still be waiting for its agent or its saved session. + pub(super) fn cancel_pending(&self, session: &str, expected_turn: Option<&str>) -> bool { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(execution) = state.sessions.get_mut(session) { + if execution.running + && !execution.prompt_submitted + && expected_turn.is_none_or(|id| id == execution.turn_id) + { + execution.cancelling = true; + execution.pending_cancel.send_replace(true); + return true; + } + } + false + } + + /// Subscribe only while this exact turn still owns an unsent prompt. + pub(super) fn pending_cancellation( + &self, + session: &str, + turn: &str, + ) -> Option> { + let state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let execution = state.sessions.get(session)?; + (execution.turn_id == turn && execution.running && !execution.prompt_submitted) + .then(|| execution.pending_cancel.subscribe()) + } + + pub(super) fn is_cancelling(&self, session: &str) -> bool { + self.0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .sessions + .get(session) + .is_some_and(|execution| execution.cancelling) + } + /// 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> { @@ -199,26 +294,154 @@ impl AcpExecutions { { attach_cursor(payload, cursor); } - if matches!( + let execution = state.sessions.get_mut(session).expect("checked execution"); + if let Some(data) = execution.transcript.as_mut() { + super::transcript::apply_event(data, &event, super::transcript::now_ms()); + if !execution.prompt_submitted + && matches!( + event, + AgenticEvent::DialogTurnCancelled { .. } + | AgenticEvent::DialogTurnFailed { .. } + ) + { + data.finish_reason = Some(super::session_persistence::UNSENT_FINISH_REASON.into()); + } + } else 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 journal(&self) -> Result, String> { + self.0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .journal + .clone() + .ok_or_else(|| "ACP execution journal unavailable".into()) + } + + pub(super) fn has_session(&self, session: &str) -> bool { + self.0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .sessions + .contains_key(session) + } + + pub(super) fn is_running(&self, session: &str) -> bool { + self.0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .sessions + .get(session) + .is_some_and(|x| x.running) + } + + /// Queue the wire request before cancellation can switch to the remote handle. + /// `admitted` is the turn this request was accepted for. A request whose turn + /// was released or replaced while its agent started is never sent. + pub(super) fn submit_prompt( + &self, + session: &str, + admitted: Option<&str>, + send: impl FnOnce(Option) -> T, + ) -> Option { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let execution = state.sessions.get_mut(session).filter(|e| e.running); + if let Some(turn) = admitted { + if execution + .as_ref() + .is_none_or(|e| e.turn_id != turn || e.prompt_submitted) + { + return None; + } + } + if let Some(execution) = execution { + if execution.cancelling { + return None; + } + execution.prompt_submitted = true; + let message_id = execution + .transcript + .as_ref() + .map(|data| data.user_message.id.clone()); + return Some(send(message_id)); + } + Some(send(None)) + } + + pub(super) fn completed_transcript(&self, session: &str) -> Option<(DialogTurnData, bool)> { + let state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let execution = state.sessions.get(session)?; + let data = execution.transcript.as_ref()?; + (data.status != openbitfun_core::service::session::TurnStatus::InProgress) + .then(|| (data.clone(), execution.awaiting_history)) + } + + pub(super) fn pending_turn(&self, session: &str) -> Option { + let state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let execution = state.sessions.get(session)?; + execution + .transcript + .as_ref() + .filter(|_| execution.awaiting_history) + .cloned() + } + + pub(super) fn placed_pending_turn(&self, session: &str, index: usize) { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(execution) = state.sessions.get_mut(session) { + if let Some(data) = execution.transcript.as_mut() { + data.turn_index = index; + } + execution.awaiting_history = false; + } + } + + pub(super) fn finish_turn(&self, session: &str, checkpoint_saved: bool) { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(execution) = state.sessions.get_mut(session) { + execution.running = false; + execution.cancelling = false; + if checkpoint_saved { + execution.transcript = None; + } + } + if checkpoint_saved { + if let Some(journal) = &state.journal { + journal.checkpoint_saved(session); + } + } + } + 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)?; + let mut projection = state.journal.as_ref()?.snapshot(session); + if execution.running + && projection.events.last().is_some_and(|event| { + matches!( + event, + AgenticEvent::DialogTurnCompleted { .. } + | AgenticEvent::DialogTurnFailed { .. } + | AgenticEvent::DialogTurnCancelled { .. } + ) + }) + { + projection.events.pop(); + projection.cursor = projection.cursor.saturating_sub(1); + } Some(AcpExecutionSnapshot { running: execution.running, cancelling: execution.cancelling, - projection: state.journal.as_ref()?.snapshot(session), + projection, }) } @@ -275,6 +498,8 @@ fn projected_event(name: &str, payload: &Value) -> Result, ("toolEvent", "tool_event"), ("text", "text"), ("error", "error"), + ("errorCategory", "error_category"), + ("errorDetail", "error_detail"), ] { if let Some(value) = payload.get(source) { event[target] = value.clone(); @@ -286,13 +511,23 @@ fn projected_event(name: &str, payload: &Value) -> Result, } #[cfg(test)] -mod tests { +pub(in crate::client) mod tests { use super::*; #[derive(Default)] - struct Journal(Mutex>); + pub(in crate::client) struct Journal { + events: Mutex>, + pending: Mutex>, + } impl AcpProjectionJournal for Journal { + fn pending_checkpoint(&self, _: &str) -> Vec { + self.pending.lock().unwrap().clone() + } + fn checkpoint_saved(&self, _: &str) { + self.pending.lock().unwrap().clear(); + } fn record(&self, event: &AgenticEvent) -> Option { - let mut events = self.0.lock().unwrap(); + self.pending.lock().unwrap().push(event.clone()); + let mut events = self.events.lock().unwrap(); events.push(event.clone()); Some(AcpEventCursor { stream_id: "host".into(), @@ -300,7 +535,7 @@ mod tests { }) } fn snapshot(&self, session: &str) -> AcpEventProjectionSnapshot { - let events = self.0.lock().unwrap().clone(); + let events = self.events.lock().unwrap().clone(); AcpEventProjectionSnapshot { session_id: session.into(), stream_id: "host".into(), @@ -337,20 +572,25 @@ mod tests { fn admission_is_idempotent_and_does_not_replace_running_or_cancelling_work() { let store = store(); assert!(store - .admit("s", "t", "client", "hello", "hello") + .admit("s", "t", "client", "hello", "hello", None) .unwrap() .is_some()); - assert_eq!(store.admit("s", "t", "client", "hello", "hello"), Ok(None)); + assert_eq!( + store.admit("s", "t", "client", "hello", "hello", None), + Ok(None) + ); assert!(store - .admit("s", "t", "client", "different", "different") + .admit("s", "t", "client", "different", "different", None) .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()); + assert!(store + .admit("s", "next", "client", "next", "next", None) + .is_err()); emit(&store, "agentic://dialog-turn-cancelled", json!({})); assert!(!store.snapshot("s").unwrap().running); assert!(store - .admit("s", "next", "client", "next", "next") + .admit("s", "next", "client", "next", "next", None) .unwrap() .is_some()); let mut sent = false; @@ -368,12 +608,38 @@ mod tests { ) .is_err()); assert!(store.snapshot("s").unwrap().running); + + // A delayed worker reaches the send boundary after another turn takes over. + assert!(store + .submit_prompt("s", Some("t"), |_| panic!("retired prompt sent")) + .is_none()); + assert!(store.submit_prompt("s", Some("next"), |_| ()).is_some()); + + let mut failed = json!({ + "sessionId": "s", "turnId": "next", "error": "Stop was not confirmed", + "errorCategory": "unknown", + "errorDetail": {"category": "unknown", "recoveryConstraint": "acp_stop_unconfirmed", "retryable": false} + }); + store + .record("agentic://dialog-turn-failed", &mut failed) + .unwrap(); + let snapshot = store.snapshot("s").unwrap(); + assert!(!snapshot.running); + let replay = serde_json::to_value(snapshot.projection.events.last().unwrap()).unwrap(); + assert_eq!(replay["error_category"], failed["errorCategory"]); + assert_eq!(replay["error_detail"], failed["errorDetail"]); + store.release("s"); + assert!(store + .submit_prompt("s", Some("next"), |_| panic!("released prompt sent")) + .is_none()); } #[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(); + store + .admit("s", "t", "client", "hello", "hello", None) + .unwrap(); emit( &store, "agentic://model-round-started", @@ -405,6 +671,9 @@ mod tests { terminal.projection.events.last(), Some(AgenticEvent::DialogTurnCompleted { .. }) )); - assert_eq!(store.admit("s", "t", "client", "hello", "hello"), Ok(None)); + assert_eq!( + store.admit("s", "t", "client", "hello", "hello", None), + Ok(None) + ); } } diff --git a/src/crates/interfaces/acp/src/client/manager.rs b/src/crates/interfaces/acp/src/client/manager.rs index 6651a80b9d..3637796f81 100644 --- a/src/crates/interfaces/acp/src/client/manager.rs +++ b/src/crates/interfaces/acp/src/client/manager.rs @@ -1,17 +1,21 @@ +mod replay; use std::collections::HashMap; use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::process::Stdio; -use std::sync::Arc; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; use std::time::{Duration, Instant}; use agent_client_protocol::schema::{ - AgentCapabilities, CancelNotification, ClientCapabilities, CloseSessionRequest, Implementation, - InitializeRequest, LoadSessionRequest, LoadSessionResponse, NewSessionRequest, - NewSessionResponse, PermissionOption, PermissionOptionKind, ProtocolVersion, - RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse, - ResumeSessionRequest, ResumeSessionResponse, SelectedPermissionOutcome, SessionConfigOption, + AgentCapabilities, CancelNotification, ClientCapabilities, CloseSessionRequest, ErrorCode, + Implementation, InitializeRequest, LoadSessionResponse, NewSessionRequest, NewSessionResponse, + PermissionOption, PermissionOptionKind, ProtocolVersion, RequestPermissionOutcome, + RequestPermissionRequest, RequestPermissionResponse, ResumeSessionRequest, + ResumeSessionResponse, SelectedPermissionOutcome, SessionConfigOption, SessionConfigOptionValue, SessionModelState, SetSessionConfigOptionRequest, SetSessionModelRequest, StopReason, }; @@ -21,6 +25,7 @@ use agent_client_protocol::{ use dashmap::mapref::entry::Entry; use dashmap::DashMap; use futures::io::{AsyncRead as FuturesAsyncRead, AsyncWrite as FuturesAsyncWrite}; +use futures::FutureExt; use log::{debug, info, warn}; use openbitfun_agent_tools::ACP_TOOL_PREFIX; use openbitfun_core::agentic::tools::registry::get_global_tool_registry; @@ -33,7 +38,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, watch, Mutex, MutexGuard, RwLock}; +use tokio::sync::{oneshot, watch, Mutex, OwnedMutexGuard, RwLock}; use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt}; use super::builtin_clients::{ @@ -46,7 +51,7 @@ use super::config::{ }; use super::dsh_profile::{ensure_bundled_profile, ensure_bundled_profile_remote}; use super::execution::{AcpExecutionSnapshot, AcpExecutions}; -use super::prompt::AcpPrompt; +use super::prompt::{AcpCancelHandle, AcpPrompt}; use super::remote_capability_store::RemoteAcpCapabilityStore; use super::remote_session::{preferred_resume_strategies, AcpRemoteSessionStrategy}; use super::remote_shell::{remote_user_shell_command, render_remote_env_assignments, shell_escape}; @@ -71,10 +76,10 @@ use super::transport::{handle_transport_closed, AcpTransport}; const CONFIG_PATH: &str = "acp_clients"; const CLIENT_STARTUP_TIMEOUT_SECS: u64 = 60; const CLIENT_STARTUP_TIMEOUT: Duration = Duration::from_secs(CLIENT_STARTUP_TIMEOUT_SECS); +// A full history can span multiple idle timeouts while the agent is still sending updates. +const SESSION_LOAD_TIMEOUT: Duration = Duration::from_secs(10 * 60); const PERMISSION_TIMEOUT: Duration = Duration::from_secs(600); const SESSION_CLOSE_TIMEOUT: Duration = Duration::from_secs(5); -const LOAD_REPLAY_DRAIN_QUIET_WINDOW: Duration = Duration::from_millis(250); -const LOAD_REPLAY_DRAIN_MAX_DURATION: Duration = Duration::from_secs(2); const SESSION_METADATA_DRAIN_QUIET_WINDOW: Duration = Duration::from_millis(250); const SESSION_METADATA_DRAIN_MAX_DURATION: Duration = Duration::from_secs(2); const TURN_COMPLETION_DRAIN_QUIET_WINDOW: Duration = Duration::from_millis(250); @@ -156,6 +161,8 @@ impl AcpSessionConfigValue { pub struct AcpClientService { executions: AcpExecutions, + turn_writes: DashMap>>, + required_restores: DashMap, config_service: Arc, session_persistence: AcpSessionPersistence, remote_capability_store: RemoteAcpCapabilityStore, @@ -170,13 +177,14 @@ struct PendingPermission { } struct AcpClientConnection { + detached_after_stop: AtomicBool, id: String, client_id: String, config: AcpClientConfig, status: RwLock, connection: RwLock>>, agent_capabilities: RwLock>, - sessions: DashMap>, + sessions: DashMap, cancel_handles: DashMap, shutdown_tx: Mutex>>, child: Mutex>, @@ -189,14 +197,15 @@ struct AcpRemoteSession { config_options: Vec, context_usage: Option, available_commands: Vec, - discard_pending_updates_before_next_prompt: bool, + stop_requested: watch::Sender<()>, } +#[derive(Clone)] struct ResolvedClientSession { client: Arc, cwd: PathBuf, session_key: String, - session: Arc, + session: AcpSessionHandle, } struct StartClientConfig { @@ -204,22 +213,16 @@ struct StartClientConfig { config: AcpClientConfig, } -#[derive(Clone)] -struct AcpCancelHandle { - session_id: String, - connection: ConnectionTo, -} - impl AcpRemoteSession { fn new(metadata: watch::Sender>) -> Self { Self { metadata, active: None, + stop_requested: watch::channel(()).0, models: None, config_options: Vec::new(), context_usage: None, available_commands: Vec::new(), - discard_pending_updates_before_next_prompt: false, } } } @@ -227,27 +230,30 @@ 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. +#[derive(Clone)] struct AcpSessionHandle { - protocol: Mutex, + protocol: Arc>, metadata: watch::Receiver>, + released: Arc, } -enum AcpMetadataRead<'a> { +enum AcpMetadataRead { Snapshot(AcpSessionOptions), - Protocol(MutexGuard<'a, AcpRemoteSession>), + Protocol(OwnedMutexGuard), } impl AcpSessionHandle { fn new() -> Self { let (sender, metadata) = watch::channel(None); Self { - protocol: Mutex::new(AcpRemoteSession::new(sender)), + protocol: Arc::new(Mutex::new(AcpRemoteSession::new(sender))), metadata, + released: Arc::new(AtomicBool::new(false)), } } - async fn metadata_or_lock(&self) -> AcpMetadataRead<'_> { - if let Ok(session) = self.protocol.try_lock() { + async fn metadata_or_lock(&self) -> AcpMetadataRead { + if let Ok(session) = self.protocol.clone().try_lock_owned() { return AcpMetadataRead::Protocol(session); } let mut metadata = self.metadata.clone(); @@ -256,7 +262,7 @@ impl AcpSessionHandle { return AcpMetadataRead::Snapshot(snapshot); } tokio::select! { - session = self.protocol.lock() => return AcpMetadataRead::Protocol(session), + session = self.protocol.clone().lock_owned() => 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"); @@ -274,6 +280,7 @@ impl AcpRemoteSession { self.context_usage.as_ref(), ); options.available_commands = Some(self.available_commands.clone()); + options.agent_disconnected = self.active.is_none(); self.metadata.send_replace(Some(options.clone())); options } @@ -286,6 +293,8 @@ impl AcpClientService { ) -> OpenBitFunResult> { Ok(Arc::new(Self { executions: AcpExecutions::default(), + turn_writes: DashMap::new(), + required_restores: DashMap::new(), config_service, session_persistence: AcpSessionPersistence::new(path_manager.clone())?, remote_capability_store: RemoteAcpCapabilityStore::new( @@ -306,16 +315,274 @@ impl AcpClientService { self.executions.configure_journal(journal) } - pub fn admit_dialog_turn( + /// Serializes history writes of one session. Lock order is the session + /// protocol lock, then this gate, then the execution table; nothing holding + /// this gate waits for the protocol lock. + fn turn_gate(&self, session: &str) -> Arc> { + self.turn_writes + .entry(session.to_owned()) + .or_default() + .clone() + } + + pub async fn admit_dialog_turn( &self, session: &str, turn: &str, client: &str, input: &str, original_input: &str, + metadata: Option, + storage: Option<&Path>, ) -> Result, String> { + let gate = self.turn_gate(session); + let _write = gate.lock().await; + if self + .executions + .already_admitted(session, turn, client, input, original_input)? + { + if let Some(path) = storage { + self.checkpoint_completed_turn(path, session) + .await + .map_err(|e| e.to_string())?; + } + return Ok(None); + } + let journal = self.executions.journal()?; + let transcript = if let Some(path) = storage { + self.recover_dialog_turn(path, session, &*journal) + .await + .map_err(|e| e.to_string())?; + if self.executions.is_running(session) { + return self + .executions + .admit(session, turn, client, input, original_input, None); + } + let Some(data) = self + .session_persistence + .prepare_dialog_turn(path, session, turn, client, input, original_input, metadata) + .await + .map_err(|e| e.to_string())? + else { + return Ok(None); + }; + Some(data) + } else { + None + }; + self.executions + .admit(session, turn, client, input, original_input, transcript) + } + + pub async fn finish_dialog_turn( + &self, + session: &str, + storage: Option<&Path>, + name: &str, + payload: &mut serde_json::Value, + ) -> OpenBitFunResult<()> { + let gate = self.turn_gate(session); + let _write = gate.lock().await; self.executions - .admit(session, turn, client, input, original_input) + .record(name, payload) + .map_err(OpenBitFunError::service)?; + if let Some(path) = storage { + if let Err(error) = self.checkpoint_completed_turn(path, session).await { + // The journal owns the observed outcome until the history write can be retried. + // Publish that outcome with the storage error so a view can settle the turn. + log::error!("Failed to save ACP turn history: session_id={session} error={error}"); + self.executions.finish_turn(session, false); + payload["acpHistorySaveError"] = error.to_string().into(); + } + } else { + self.executions.finish_turn(session, true); + } + Ok(()) + } + + pub async fn recover_stored_dialog_turn( + &self, + path: &Path, + session: &str, + ) -> OpenBitFunResult<()> { + let gate = self.turn_gate(session); + let _write = gate.lock().await; + let journal = self + .executions + .journal() + .map_err(OpenBitFunError::service)?; + self.recover_dialog_turn(path, session, &*journal).await + } + + // The caller holds the session write gate. No protocol I/O takes place here. + async fn checkpoint_completed_turn( + &self, + path: &Path, + session: &str, + ) -> OpenBitFunResult { + let Some((mut data, pending)) = self.executions.completed_transcript(session) else { + return Ok(false); + }; + if pending { + self.session_persistence + .place_pending_turn(path, &mut data) + .await?; + } else { + self.session_persistence + .commit_dialog_turn(path, &data) + .await?; + } + self.executions.finish_turn(session, true); + Ok(true) + } + + async fn recover_dialog_turn( + &self, + path: &Path, + session: &str, + journal: &dyn super::execution::AcpProjectionJournal, + ) -> OpenBitFunResult<()> { + use openbitfun_core::service::session::TurnStatus; + if self.checkpoint_completed_turn(path, session).await? { + return Ok(()); + } + if self.executions.is_running(session) { + return Ok(()); + } + let store = &self.session_persistence.manager; + let Some(record) = store.load_session_metadata(path, session).await? else { + return Ok(()); + }; + if let Some(pending) = record + .custom_metadata + .as_ref() + .and_then(|v| v.get(super::session_persistence::PENDING_TURN_KEY)) + { + let mut data: openbitfun_core::service::session::DialogTurnData = + serde_json::from_value(pending.clone())?; + // The original agent cannot have received this prompt: its storage + // position and receipt are committed before session/prompt is issued. + let terminal = journal + .pending_checkpoint(session) + .into_iter() + .rev() + .find(|event| { + event.turn_id() == Some(&data.turn_id) + && matches!( + event, + openbitfun_events::AgenticEvent::DialogTurnFailed { .. } + | openbitfun_events::AgenticEvent::DialogTurnCancelled { .. } + ) + }) + .unwrap_or_else(|| openbitfun_events::AgenticEvent::DialogTurnFailed { + session_id: session.into(), + turn_id: data.turn_id.clone(), + error: "Session recovery was interrupted before the ACP prompt was sent." + .into(), + error_category: None, + error_detail: None, + }); + super::transcript::apply_event(&mut data, &terminal, super::transcript::now_ms()); + self.session_persistence + .place_pending_turn(path, &mut data) + .await?; + journal.checkpoint_saved(session); + return Ok(()); + } + let first = record + .custom_metadata + .as_ref() + .and_then(|v| v.get("acpRuntimeFromTurn")) + .and_then(serde_json::Value::as_u64); + let Some(last) = record.last_turn else { + return Ok(()); + }; + let owned = first.is_some_and(|from| last.turn_index as u64 >= from); + // A completed legacy turn is already durable. Its admission path will + // recognize the existing turn and avoid creating another record. + if !owned && last.status != TurnStatus::InProgress { + return Ok(()); + } + if last.status != TurnStatus::InProgress { + // A previous host may have exited between the history commit and the journal acknowledgement. + if !self.executions.has_session(session) { + journal.checkpoint_saved(session); + } + return Ok(()); + } + let Some(mut data) = store + .load_dialog_turn(path, session, last.turn_index) + .await? + else { + return Ok(()); + }; + let time = super::transcript::now_ms(); + let events = journal.pending_checkpoint(session); + if !owned + && data.model_rounds.is_empty() + && !events + .iter() + .any(|event| event.turn_id() == Some(last.turn_id.as_str())) + { + // Legacy hosts persisted the optimistic input before sending it. + // Keep that record reusable when no output has been observed. + return Ok(()); + } + if owned { + for event in events + .iter() + .filter(|e| e.turn_id() == Some(last.turn_id.as_str())) + { + super::transcript::apply_event(&mut data, event, time); + } + } else if !events.is_empty() { + // Older views checkpointed a prefix of the same journal. Replay + // onto an empty transcript first so that prefix is never doubled. + let mut replayed = data.clone(); + replayed.model_rounds.clear(); + for event in events + .iter() + .filter(|e| e.turn_id() == Some(last.turn_id.as_str())) + { + super::transcript::apply_event(&mut replayed, event, time); + } + let mut merged = data.clone(); + if replay::merge_rounds(&mut merged, &replayed.model_rounds) { + data = merged; + } + if let Some(terminal) = events.iter().rev().find(|e| { + e.turn_id() == Some(last.turn_id.as_str()) + && matches!( + e, + openbitfun_events::AgenticEvent::DialogTurnCompleted { .. } + | openbitfun_events::AgenticEvent::DialogTurnCancelled { .. } + | openbitfun_events::AgenticEvent::DialogTurnFailed { .. } + ) + }) { + super::transcript::apply_event(&mut data, terminal, time); + } + } + if data.status == TurnStatus::InProgress { + let error = OpenBitFunError::OutcomeUnknown( + "The ACP connection ended before the agent confirmed the result.".into(), + ); + let mut detail = error.error_detail(); + detail.recovery_constraint = Some("acp_stop_unconfirmed".into()); + detail.retryable = Some(false); + let terminal = openbitfun_events::AgenticEvent::DialogTurnFailed { + session_id: session.into(), + turn_id: data.turn_id.clone(), + error: error.to_string(), + error_category: Some(detail.category.clone()), + error_detail: Some(detail), + }; + super::transcript::apply_event(&mut data, &terminal, time); + } + self.session_persistence + .commit_dialog_turn(path, &data) + .await?; + journal.checkpoint_saved(session); + Ok(()) } pub fn record_dialog_event( @@ -828,7 +1095,7 @@ impl AcpClientService { Ok(Ok(result)) => result, Ok(Err(_)) => { connect_task.abort(); - self.cleanup_failed_startup(connection_id).await; + self.stop_connection_instance(&connection).await; // The agent is gone; whatever it managed to say on the way out // is all anyone has to go on, so put it in front of the user // rather than only in the log. @@ -845,7 +1112,7 @@ impl AcpClientService { CLIENT_STARTUP_TIMEOUT_SECS ); connect_task.abort(); - self.cleanup_failed_startup(connection_id).await; + self.stop_connection_instance(&connection).await; return Err(startup_timeout_error(client_id, "initialize")); } }; @@ -861,15 +1128,6 @@ impl AcpClientService { Ok(()) } - async fn cleanup_failed_startup(self: &Arc, connection_id: &str) { - if let Err(error) = self.stop_connection(connection_id).await { - warn!( - "Failed to clean up ACP client after startup failure: connection_id={} error={}", - connection_id, error - ); - } - } - pub async fn stop_client(self: &Arc, client_id: &str) -> OpenBitFunResult<()> { let connection_ids = self .clients @@ -888,26 +1146,39 @@ impl AcpClientService { return Ok(()); }; + self.stop_connection_instance(&client).await; + Ok(()) + } + + async fn stop_connection_instance(&self, client: &Arc) { + // A concurrent startup must wait until this instance is out of the registry. + let mut status = client.status.write().await; if let Some(tx) = client.shutdown_tx.lock().await.take() { let _ = tx.send(()); } if let Some(child) = client.child.lock().await.take() { - terminate_child_process_tree(connection_id, child).await; + terminate_child_process_tree(&client.id, child).await; } *client.connection.write().await = None; *client.agent_capabilities.write().await = None; + for session in client.sessions.iter() { + session.released.store(true, Ordering::Release); + } client.sessions.clear(); client.cancel_handles.clear(); - *client.status.write().await = AcpClientStatus::Stopped; - self.clients.remove(connection_id); + *status = AcpClientStatus::Stopped; + self.clients + .remove_if(&client.id, |_, current| Arc::ptr_eq(current, client)); info!( "ACP client stopped: id={} client_id={}", - connection_id, client.client_id + client.id, client.client_id ); - Ok(()) } pub async fn release_openbitfun_session(self: &Arc, openbitfun_session_id: &str) -> bool { + // Session setup holds the protocol lock and may hand it straight to the + // prompt. Retire its pending send before waiting for that lock. + self.executions.cancel_pending(openbitfun_session_id, None); let session_key_prefix = format!("{}:", openbitfun_session_id); let clients = self .clients @@ -915,7 +1186,7 @@ impl AcpClientService { .map(|entry| entry.value().clone()) .collect::>(); let mut released = false; - let mut idle_client_ids = Vec::new(); + let mut idle_clients = Vec::new(); for client in clients { let session_keys = client @@ -940,6 +1211,7 @@ impl AcpClientService { for session_key in session_keys { let active_session_id = if let Some((_, session)) = client.sessions.remove(&session_key) { + session.released.store(true, Ordering::Release); let mut session = session.protocol.lock().await; let session_id = session .active @@ -980,20 +1252,16 @@ impl AcpClientService { && client.sessions.is_empty() && client.cancel_handles.is_empty() { - idle_client_ids.push(client.id.clone()); + idle_clients.push(client); } } - for connection_id in idle_client_ids { - if let Err(error) = self.stop_connection(&connection_id).await { - warn!( - "Failed to stop idle ACP client after session release: id={} error={}", - connection_id, error - ); - } + for client in idle_clients { + self.stop_connection_instance(&client).await; } self.executions.release(openbitfun_session_id); + self.turn_writes.remove(openbitfun_session_id); released } @@ -1004,7 +1272,15 @@ impl AcpClientService { ) -> OpenBitFunResult<()> { self.session_persistence .delete_flow_session_record(session_storage_path, openbitfun_session_id) - .await + .await?; + self.forget_session_recovery(openbitfun_session_id); + Ok(()) + } + + pub fn forget_session_recovery(&self, openbitfun_session_id: &str) { + let prefix = format!("{openbitfun_session_id}:"); + self.required_restores + .retain(|key, _| !key.starts_with(&prefix)); } pub async fn load_json_config(&self) -> OpenBitFunResult { @@ -1053,6 +1329,41 @@ impl AcpClientService { }) } + /// Observing a view never spawns an agent or waits for its protocol lock. + pub async fn observe_session_options( + &self, + client_id: &str, + session_id: &str, + cwd: Option<&str>, + storage: Option<&Path>, + ) -> OpenBitFunResult { + let connection_id = session_client_connection_id(client_id, session_id); + let directory = cwd + .map(PathBuf::from) + .or_else(|| std::env::current_dir().ok()); + if let (Some(directory), Some(client)) = (directory, self.clients.get(&connection_id)) { + if let Some(handle) = client + .sessions + .get(&build_session_key(session_id, client_id, &directory)) + { + if let Some(options) = handle.metadata.borrow().clone() { + return Ok(options); + } + } + } + let mut options = match storage { + Some(path) => { + self.session_persistence + .saved_options(path, session_id) + .await? + } + None => AcpSessionOptions::before_first_snapshot(), + }; + options.agent_disconnected = true; + options.available_commands.get_or_insert_with(Vec::new); + Ok(options) + } + pub async fn get_session_options( self: &Arc, client_id: &str, @@ -1062,18 +1373,23 @@ impl AcpClientService { openbitfun_session_id: String, ) -> OpenBitFunResult { let started_at = Instant::now(); - let resolved = self - .resolve_or_create_client_session( - client_id, - workspace_path, - remote_connection_id.as_deref(), - &openbitfun_session_id, - ) - .await?; - - let mut session = match resolved.session.metadata_or_lock().await { - AcpMetadataRead::Snapshot(options) => return Ok(options), - AcpMetadataRead::Protocol(session) => session, + let (resolved, mut session) = loop { + let resolved = self + .resolve_or_create_client_session( + client_id, + workspace_path.clone(), + remote_connection_id.as_deref(), + &openbitfun_session_id, + ) + .await?; + let metadata = resolved.session.metadata_or_lock().await; + if resolved.client.detached_after_stop.load(Ordering::Acquire) { + continue; + } + match metadata { + AcpMetadataRead::Snapshot(options) => return Ok(options), + AcpMetadataRead::Protocol(session) => break (resolved, session), + } }; self.ensure_remote_session( &resolved.client, @@ -1084,8 +1400,15 @@ impl AcpClientService { &mut session, ) .await?; - drain_pending_session_metadata_updates(&mut session).await?; + let updated = drain_pending_session_metadata_updates(&mut session, false).await?; let options = session.publish_metadata(); + if updated { + if let Some(path) = session_storage_path.as_deref() { + self.session_persistence + .save_options(path, &openbitfun_session_id, &options) + .await?; + } + } debug!( "ACP session metadata loaded: client_id={} session_id={} duration_ms={}", client_id, @@ -1120,7 +1443,7 @@ impl AcpClientService { request: SetAcpSessionModelRequest, session_storage_path: Option, ) -> OpenBitFunResult { - let resolved = self + let mut resolved = self .resolve_or_create_client_session( &request.client_id, request.workspace_path, @@ -1129,7 +1452,13 @@ impl AcpClientService { ) .await?; - let mut session = resolved.session.protocol.lock().await; + let mut session = self + .lock_current_session( + &mut resolved, + &request.session_id, + request.remote_connection_id.as_deref(), + ) + .await?; self.ensure_remote_session( &resolved.client, &resolved.session_key, @@ -1162,21 +1491,13 @@ 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() { + let options = session.publish_metadata(); + if let Some(path) = session_storage_path.as_deref() { self.session_persistence - .update_model_id( - session_storage_path, - &request.session_id, - &request.model_id, - ) + .save_options(path, &request.session_id, &options) .await?; } - return Ok(session_options_from_state( - session.models.as_ref(), - &session.config_options, - session.context_usage.as_ref(), - )); + return Ok(options); } Err(error) => { set_model_error = Some(error); @@ -1195,17 +1516,13 @@ 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() { + let options = session.publish_metadata(); + if let Some(path) = session_storage_path.as_deref() { self.session_persistence - .update_model_id(session_storage_path, &request.session_id, &request.model_id) + .save_options(path, &request.session_id, &options) .await?; } - return Ok(session_options_from_state( - session.models.as_ref(), - &session.config_options, - session.context_usage.as_ref(), - )); + return Ok(options); } if let Some(error) = set_model_error { @@ -1221,7 +1538,7 @@ impl AcpClientService { request: SetAcpSessionConfigOptionRequest, session_storage_path: Option, ) -> OpenBitFunResult { - let resolved = self + let mut resolved = self .resolve_or_create_client_session( &request.client_id, request.workspace_path, @@ -1230,7 +1547,13 @@ impl AcpClientService { ) .await?; - let mut session = resolved.session.protocol.lock().await; + let mut session = self + .lock_current_session( + &mut resolved, + &request.session_id, + request.remote_connection_id.as_deref(), + ) + .await?; self.ensure_remote_session( &resolved.client, &resolved.session_key, @@ -1269,13 +1592,66 @@ impl AcpClientService { .await .map_err(protocol_error)?; session.config_options = response.config_options; - session.publish_metadata(); + let options = session.publish_metadata(); + if let Some(path) = session_storage_path.as_deref() { + self.session_persistence + .save_options(path, &request.session_id, &options) + .await?; + } + Ok(options) + } - Ok(session_options_from_state( - session.models.as_ref(), - &session.config_options, - session.context_usage.as_ref(), - )) + async fn prepare_prompt_session( + self: &Arc, + resolved: &mut ResolvedClientSession, + session_id: &str, + remote_connection: Option<&str>, + storage: Option<&Path>, + timeout_seconds: Option, + ) -> OpenBitFunResult<( + OwnedMutexGuard, + watch::Receiver<()>, + Option, + )> { + let prepare = async { + let mut session = self + .lock_current_session(resolved, session_id, remote_connection) + .await?; + let stop = session.stop_requested.subscribe(); + if resolved.session.released.load(Ordering::Acquire) { + return Err(OpenBitFunError::cancelled( + "ACP prompt was released during session setup", + )); + } + self.ensure_remote_session( + &resolved.client, + &resolved.session_key, + &resolved.cwd, + session_id, + storage, + &mut session, + ) + .await?; + session.publish_metadata(); + Ok::<_, OpenBitFunError>((session, stop)) + }; + // A setup timeout has no execution side effects. Once submitted, only + // the prompt owner can expire its deadline and retire the connection. + if let Some(seconds) = timeout_seconds.filter(|seconds| *seconds > 0) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(seconds); + let (session, stop) = + tokio::time::timeout_at(deadline, prepare) + .await + .map_err(|_| { + OpenBitFunError::tool(format!( + "ACP session setup timed out after {seconds}s" + )) + })??; + Ok((session, stop, Some(deadline))) + } else { + let (session, stop) = prepare.await?; + Ok((session, stop, None)) + } } pub async fn prompt_agent( @@ -1288,7 +1664,7 @@ impl AcpClientService { session_storage_path: Option, timeout_seconds: Option, ) -> OpenBitFunResult { - let resolved = self + let mut resolved = self .resolve_or_create_client_session( client_id, workspace_path, @@ -1297,37 +1673,46 @@ impl AcpClientService { ) .await?; + let mut unconfirmed = None; let run = async { - let mut session = resolved.session.protocol.lock().await; - self.ensure_remote_session( - &resolved.client, - &resolved.session_key, - &resolved.cwd, - &openbitfun_session_id, - session_storage_path.as_deref(), - &mut session, - ) - .await?; - - discard_pending_session_updates_if_needed(&mut session).await; - session.publish_metadata(); + let (mut session, stop_requested, deadline) = self + .prepare_prompt_session( + &mut resolved, + &openbitfun_session_id, + remote_connection_id.as_deref(), + session_storage_path.as_deref(), + timeout_seconds, + ) + .await?; + if stop_requested.has_changed().unwrap_or(false) { + return Err(OpenBitFunError::cancelled( + "ACP prompt cancelled before submission", + )); + } let active = session .active - .as_mut() + .as_ref() .ok_or_else(|| OpenBitFunError::service("ACP session was not initialized"))?; - let mut prompt = AcpPrompt::start(active, prompt); - read_turn_to_string(&mut session, &mut prompt).await + let remote_session_id = active.session_id().to_string(); + let mut prompt = AcpPrompt::start(active, prompt, None, deadline, stop_requested); + let result = read_turn_to_string(&mut session, &mut prompt).await; + if matches!(result, Err(OpenBitFunError::OutcomeUnknown(_))) { + unconfirmed = Some((session, remote_session_id)); + } + result }; - if let Some(seconds) = timeout_seconds.filter(|seconds| *seconds > 0) { - tokio::time::timeout(Duration::from_secs(seconds), run) - .await - .map_err(|_| { - OpenBitFunError::tool(format!("ACP client timed out after {}s", seconds)) - })? - } else { - run.await + let result = run.await; + if let Some((_session_guard, remote_id)) = unconfirmed { + self.detach_unconfirmed_prompt( + &resolved, + &openbitfun_session_id, + session_storage_path.as_deref(), + &remote_id, + ) + .await?; } + result } pub async fn prompt_agent_stream( @@ -1337,6 +1722,7 @@ impl AcpClientService { workspace_path: Option, remote_connection_id: Option, openbitfun_session_id: String, + admitted_turn: Option<&str>, session_storage_path: Option, timeout_seconds: Option, mut on_event: F, @@ -1344,35 +1730,132 @@ impl AcpClientService { where F: FnMut(AcpClientStreamEvent) -> OpenBitFunResult<()> + Send, { - let resolved = self - .resolve_or_create_client_session( - client_id, - workspace_path, - remote_connection_id.as_deref(), - &openbitfun_session_id, - ) - .await?; + if self.executions.is_cancelling(&openbitfun_session_id) { + return on_event(AcpClientStreamEvent::Cancelled); + } + // Starting the agent and its handshake can take a minute, and so can the + // session setup below. Both run on their own tasks so a stop settles this + // turn at once; released handles fence detached setup from reattaching. + let mut cancel = match admitted_turn { + Some(turn) => { + let Some(receiver) = self + .executions + .pending_cancellation(&openbitfun_session_id, turn) + else { + return on_event(AcpClientStreamEvent::Cancelled); + }; + Some(receiver) + } + None => None, + }; + let admission_required = admitted_turn.is_some(); + let resolving = tokio::spawn({ + let service = self.clone(); + let client_id = client_id.to_owned(); + let session_id = openbitfun_session_id.clone(); + let remote_connection = remote_connection_id.clone(); + async move { + let result = service + .resolve_or_create_client_session( + &client_id, + workspace_path, + remote_connection.as_deref(), + &session_id, + ) + .await; + if let Ok(resolved) = &result { + if admission_required && !service.executions.has_session(&session_id) { + resolved.client.sessions.remove(&resolved.session_key); + return Err(OpenBitFunError::cancelled( + "ACP prompt was released during session setup", + )); + } + } + result + } + }); + let resolved = tokio::select! { + joined = resolving => joined.map_err(|error| { + OpenBitFunError::service(format!("ACP client startup task failed: {error}")) + })?, + () = stopped(&mut cancel) => return on_event(AcpClientStreamEvent::Cancelled), + }; + if self.executions.is_cancelling(&openbitfun_session_id) { + return on_event(AcpClientStreamEvent::Cancelled); + } + let mut resolved = resolved?; + let mut unconfirmed = None; let run = async { - let mut session = resolved.session.protocol.lock().await; - self.ensure_remote_session( - &resolved.client, - &resolved.session_key, - &resolved.cwd, - &openbitfun_session_id, + // Setup can wait behind another restore or replay a long history. It + // runs on its own task so a stop settles this turn immediately. The + // session handle remains fenced while release retires the restore. + let setup = tokio::spawn({ + let service = self.clone(); + let mut working = resolved.clone(); + let session_id = openbitfun_session_id.clone(); + let remote_connection = remote_connection_id.clone(); + let storage = session_storage_path.clone(); + async move { + if (admission_required && !service.executions.has_session(&session_id)) + || working.session.released.load(Ordering::Acquire) + { + return ( + working, + Err(OpenBitFunError::cancelled( + "ACP prompt was released during session setup", + )), + ); + } + let prepared = service + .prepare_prompt_session( + &mut working, + &session_id, + remote_connection.as_deref(), + storage.as_deref(), + timeout_seconds, + ) + .await; + (working, prepared) + } + }); + let (rebound, prepared) = tokio::select! { + joined = setup => joined.map_err(|error| { + OpenBitFunError::service(format!("ACP session setup task failed: {error}")) + })?, + () = stopped(&mut cancel) => return on_event(AcpClientStreamEvent::Cancelled), + }; + resolved = rebound; + if self.executions.is_cancelling(&openbitfun_session_id) { + return on_event(AcpClientStreamEvent::Cancelled); + } + let (mut session, stop_requested, deadline) = prepared?; + if let (Some(path), Some(mut data)) = ( session_storage_path.as_deref(), - &mut session, - ) - .await?; - - discard_pending_session_updates_if_needed(&mut session).await; - session.publish_metadata(); - let mut prompt = { - let active = session - .active - .as_mut() - .ok_or_else(|| OpenBitFunError::service("ACP session was not initialized"))?; - AcpPrompt::start(active, prompt) + self.executions.pending_turn(&openbitfun_session_id), + ) { + let gate = self.turn_gate(&openbitfun_session_id); + let _write = gate.lock().await; + self.session_persistence + .place_pending_turn(path, &mut data) + .await?; + self.executions + .placed_pending_turn(&openbitfun_session_id, data.turn_index); + } + if stop_requested.has_changed().unwrap_or(false) { + return on_event(AcpClientStreamEvent::Cancelled); + } + let active = session + .active + .as_ref() + .ok_or_else(|| OpenBitFunError::service("ACP session was not initialized"))?; + let remote_session_id = active.session_id().to_string(); + let Some(mut prompt) = self.executions.submit_prompt( + &openbitfun_session_id, + admitted_turn, + |message_id| AcpPrompt::start(active, prompt, message_id, deadline, stop_requested), + ) else { + return on_event(AcpClientStreamEvent::Cancelled); }; let mut round_tracker = AcpStreamRoundTracker::new(); let mut tool_call_tracker = AcpToolCallTracker::new(); @@ -1382,7 +1865,17 @@ impl AcpClientService { let active = session.active.as_mut().ok_or_else(|| { OpenBitFunError::service("ACP session was not initialized") })?; - prompt.read_update(active).await.map_err(protocol_error)? + prompt + .read_update(active) + .await + .map_err(OpenBitFunError::from) + }; + let message = match message { + Err(error @ OpenBitFunError::OutcomeUnknown(_)) => { + unconfirmed = Some((session, remote_session_id)); + return Err(error); + } + result => result?, }; match message { @@ -1393,6 +1886,27 @@ impl AcpClientService { ) .await?; update_session_from_events(&mut session, &events); + if events.iter().any(|e| { + matches!( + e, + AcpClientStreamEvent::ConfigOptionsUpdated(_) + | AcpClientStreamEvent::AvailableCommandsUpdated(_) + ) + }) { + if let Some(path) = session_storage_path.as_deref() { + if let Err(error) = self + .session_persistence + .save_options( + path, + &openbitfun_session_id, + &session.publish_metadata(), + ) + .await + { + warn!("Failed to persist ACP session options: session_id={openbitfun_session_id}, error={error}"); + } + } + } for event in events { for event in round_tracker.apply(event) { on_event(event)?; @@ -1407,6 +1921,19 @@ impl AcpClientService { &mut on_event, ) .await?; + if let Some(path) = session_storage_path.as_deref() { + if let Err(error) = self + .session_persistence + .save_options( + path, + &openbitfun_session_id, + &session.publish_metadata(), + ) + .await + { + warn!("Failed to persist final ACP session options: session_id={openbitfun_session_id}, error={error}"); + } + } let event = if matches!(stop_reason, StopReason::Cancelled) { AcpClientStreamEvent::Cancelled } else { @@ -1421,15 +1948,47 @@ impl AcpClientService { Ok(()) }; - if let Some(seconds) = timeout_seconds.filter(|seconds| *seconds > 0) { - tokio::time::timeout(Duration::from_secs(seconds), run) + let result = run.await; + if let Some((_session_guard, remote_id)) = unconfirmed { + self.detach_unconfirmed_prompt( + &resolved, + &openbitfun_session_id, + session_storage_path.as_deref(), + &remote_id, + ) + .await?; + } + result + } + + async fn detach_unconfirmed_prompt( + &self, + resolved: &ResolvedClientSession, + openbitfun_session_id: &str, + session_storage_path: Option<&Path>, + remote_session_id: &str, + ) -> OpenBitFunResult<()> { + self.required_restores + .insert(resolved.session_key.clone(), remote_session_id.to_string()); + let saved = if let Some(path) = session_storage_path { + self.session_persistence + .require_restore(path, openbitfun_session_id, remote_session_id) .await - .map_err(|_| { - OpenBitFunError::tool(format!("ACP client timed out after {}s", seconds)) - })? } else { - run.await - } + Ok(()) + }; + self.session_permission_modes.remove(remote_session_id); + resolved + .client + .detached_after_stop + .store(true, Ordering::Release); + self.stop_connection_instance(&resolved.client).await; + saved.map_err(|error| { + warn!("Failed to persist required ACP session restore: session_id={openbitfun_session_id} error={error}"); + OpenBitFunError::OutcomeUnknown(format!( + "The ACP agent did not confirm the stop. Recovery information could not be saved for the next app start. Check the previous work before retrying in this session: {error}" + )) + }) } pub async fn cancel_agent_session( @@ -1439,6 +1998,12 @@ impl AcpClientService { openbitfun_session_id: String, expected_turn_id: Option<&str>, ) -> OpenBitFunResult<()> { + if self + .executions + .cancel_pending(&openbitfun_session_id, expected_turn_id) + { + return Ok(()); + } let connection_id = session_client_connection_id(client_id, &openbitfun_session_id); let client = self .clients @@ -1463,19 +2028,18 @@ impl AcpClientService { 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()) + handle.cancel().map_err(|error| error.to_string()) }) - .map_err(OpenBitFunError::service)?; - Ok(()) + .map_err(OpenBitFunError::service) } pub async fn cancel_openbitfun_session( self: &Arc, openbitfun_session_id: &str, ) -> OpenBitFunResult { + if self.executions.cancel_pending(openbitfun_session_id, None) { + return Ok(true); + } let session_key_prefix = format!("{}:", openbitfun_session_id); for client in self.clients.iter().map(|entry| entry.value().clone()) { let handle = client @@ -1485,10 +2049,7 @@ impl AcpClientService { .map(|entry| entry.value().clone()); if let Some(handle) = handle { - handle - .connection - .send_notification(CancelNotification::new(handle.session_id.clone())) - .map_err(protocol_error)?; + handle.cancel()?; return Ok(true); } } @@ -1545,7 +2106,7 @@ impl AcpClientService { let session = client .sessions .entry(session_key.clone()) - .or_insert_with(|| Arc::new(AcpSessionHandle::new())) + .or_insert_with(AcpSessionHandle::new) .clone(); Ok(ResolvedClientSession { client, @@ -1555,6 +2116,31 @@ impl AcpClientService { }) } + // A prompt or metadata request can already be waiting behind the turn + // that retired this connection. Rebind before submitting any ACP request. + async fn lock_current_session( + self: &Arc, + resolved: &mut ResolvedClientSession, + openbitfun_session_id: &str, + remote_connection_id: Option<&str>, + ) -> OpenBitFunResult> { + loop { + let session = resolved.session.protocol.clone().lock_owned().await; + if !resolved.client.detached_after_stop.load(Ordering::Acquire) { + return Ok(session); + } + drop(session); + *resolved = self + .resolve_or_create_client_session( + &resolved.client.client_id, + Some(resolved.cwd.to_string_lossy().into_owned()), + remote_connection_id, + openbitfun_session_id, + ) + .await?; + } + } + async fn ensure_remote_session( self: &Arc, client: &Arc, @@ -1567,95 +2153,134 @@ impl AcpClientService { if session.active.is_some() { return Ok(()); } - let cx = client.connection().await?; - let persisted_remote_session_id = if let Some(session_storage_path) = session_storage_path { - self.session_persistence - .load_remote_session_id(session_storage_path, openbitfun_session_id) - .await? - } else { - None + let recovery_id = self.required_restores.get(session_key).map(|id| id.clone()); + let record = match session_storage_path { + Some(path) => { + self.session_persistence + .manager + .load_session_metadata(path, openbitfun_session_id) + .await? + } + None => None, }; - let capabilities = client.agent_capabilities.read().await.clone(); - let mut last_resume_error: Option = None; - - for strategy in preferred_resume_strategies( + let (saved_id, saved_required) = record + .as_ref() + .and_then(|m| m.custom_metadata.as_ref()) + .map(super::session_persistence::read_remote_binding) + .unwrap_or_default(); + let require_restore = recovery_id.is_some() || saved_required; + let persisted_remote_session_id = recovery_id.or(saved_id); + let has_history_gap = record + .as_ref() + .is_some_and(AcpSessionPersistence::has_history_gap); + // A replay that already failed to repair this gap would fail again until + // the local history changes, so only a metadata read is needed. + let repair_history = has_history_gap + && !record + .as_ref() + .is_some_and(AcpSessionPersistence::repair_already_attempted); + if (has_history_gap || require_restore) && persisted_remote_session_id.is_none() { + return Err(OpenBitFunError::session("The saved ACP conversation has no original agent session ID. Its local history is available, but the agent cannot reattach to it.")); + } + let capabilities = client.agent_capabilities.read().await; + let mut strategies = preferred_resume_strategies( capabilities.as_ref(), persisted_remote_session_id.as_deref(), - ) { + require_restore, + ); + if repair_history && capabilities.as_ref().is_some_and(|caps| caps.load_session) { + strategies.retain(|step| *step != AcpRemoteSessionStrategy::Load); + strategies.insert(0, AcpRemoteSessionStrategy::Load); + } + drop(capabilities); + let mut strategies = strategies.into_iter().peekable(); + let mut last_resume_error = None; + + while let Some(strategy) = strategies.next() { + // ACP v1 delivers the entire transcript before answering session/load. + // Register the actual session receiver before sending that request. + let mut existing = if strategy != AcpRemoteSessionStrategy::New { + persisted_remote_session_id + .as_ref() + .map(|id| cx.attach_session(NewSessionResponse::new(id.to_owned()), Vec::new())) + .transpose() + .map_err(protocol_error)? + } else { + None + }; + let mut replay = None; let response = match strategy { - AcpRemoteSessionStrategy::Load => { - let Some(remote_session_id) = persisted_remote_session_id.as_deref() else { + AcpRemoteSessionStrategy::Load | AcpRemoteSessionStrategy::Resume => { + let Some(remote_id) = persisted_remote_session_id.as_deref() else { continue; }; - match self - .run_startup_step( + if strategy == AcpRemoteSessionStrategy::Load { + let receiver = existing.as_mut().expect("saved session receiver"); + self.run_startup_step( client, strategy.startup_phase_name(), - cx.send_request(LoadSessionRequest::new( - remote_session_id.to_string(), + SESSION_LOAD_TIMEOUT, + replay::load( + self, + client, + &cx, + remote_id, cwd, - )) - .block_task(), + receiver, + openbitfun_session_id, + repair_history, + ), ) .await - .map_err(protocol_error) - { - Ok(response) => new_session_response_from_load(remote_session_id, response), - Err(error) => { - if is_startup_timeout_error(&error) { - return Err(error); - } - warn!( - "Failed to load ACP remote session, falling back: client_id={}, remote_session_id={}, error={}", - client.id, remote_session_id, error - ); - last_resume_error = Some(error.to_string()); - continue; - } - } - } - AcpRemoteSessionStrategy::Resume => { - let Some(remote_session_id) = persisted_remote_session_id.as_deref() else { - continue; - }; - match self - .run_startup_step( + .map(|(response, history)| { + replay = Some(history); + new_session_response_from_load(remote_id, response) + }) + } else { + self.run_startup_step( client, strategy.startup_phase_name(), - cx.send_request(ResumeSessionRequest::new( - remote_session_id.to_string(), - cwd, - )) - .block_task(), + CLIENT_STARTUP_TIMEOUT, + cx.send_request(ResumeSessionRequest::new(remote_id.to_owned(), cwd)) + .block_task(), ) .await - .map_err(protocol_error) - { - Ok(response) => { - new_session_response_from_resume(remote_session_id, response) - } - Err(error) => { - if is_startup_timeout_error(&error) { - return Err(error); - } - warn!( - "Failed to resume ACP remote session, falling back: client_id={}, remote_session_id={}, error={}", - client.id, remote_session_id, error - ); - last_resume_error = Some(error.to_string()); - continue; - } + .map(|response| new_session_response_from_resume(remote_id, response)) } } - AcpRemoteSessionStrategy::New => self - .run_startup_step( + AcpRemoteSessionStrategy::New => { + self.run_startup_step( client, strategy.startup_phase_name(), + CLIENT_STARTUP_TIMEOUT, cx.send_request(NewSessionRequest::new(cwd)).block_task(), ) .await - .map_err(protocol_error)?, + } + }; + let response = match response { + Ok(response) => response, + Err(error) => { + let can_try_another_method = matches!( + error.code, + ErrorCode::MethodNotFound | ErrorCode::ResourceNotFound + ); + let error = protocol_error(error); + if require_restore { + last_resume_error = Some(error.to_string()); + break; + } + if strategies.peek().is_none() || !can_try_another_method { + return Err(error); + } + warn!( + "ACP session {} failed, falling back: client_id={}, remote_session_id={:?}, error={}", + strategy.as_str(), client.id, persisted_remote_session_id, error + ); + last_resume_error = Some(error.to_string()); + continue; + } }; self.attach_remote_session( @@ -1665,48 +2290,80 @@ impl AcpClientService { session_storage_path, session, response, + existing, + replay, strategy, last_resume_error.clone(), + require_restore, ) .await?; + if require_restore { + self.required_restores.remove(session_key); + } return Ok(()); } - Err(OpenBitFunError::service( - "Failed to initialize ACP remote session".to_string(), - )) + if let Some(error) = last_resume_error { + return Err(OpenBitFunError::session(format!( + "Could not restore the original ACP session. Retry this chat to load its history, or start a new chat to continue separately. Reason: {error}" + ))); + } + let reason = if require_restore { + "The previous ACP turn has an unknown outcome, and this agent does not support loading its saved session." + } else { + "This ACP agent does not support resuming or loading a saved session." + }; + Err(OpenBitFunError::session(format!( + "{reason} Your local history is available here. Start a new chat to continue with this agent." + ))) } async fn run_startup_step( self: &Arc, client: &Arc, phase: &'static str, + timeout: Duration, future: F, ) -> Result where F: Future>, { let started_at = Instant::now(); - let result = tokio::time::timeout(CLIENT_STARTUP_TIMEOUT, future).await; + let result = tokio::time::timeout(timeout, future).await; debug!( "ACP startup phase completed: client_id={} connection_id={} phase={} duration_ms={} succeeded={}", client.client_id, client.id, phase, elapsed_ms_u64(started_at), matches!(&result, Ok(Ok(_))) ); match result { Ok(result) => result, - Err(_) => { - warn!( - "ACP client startup timed out: id={} connection_id={} phase={} timeout_secs={}", - client.client_id, client.id, phase, CLIENT_STARTUP_TIMEOUT_SECS - ); - self.cleanup_failed_startup(&client.id).await; - Err(agent_client_protocol::util::internal_error( - startup_timeout_error_message(&client.client_id, phase), - )) - } + Err(_) => Err(self + .retire_timed_out_connection(client, phase, timeout) + .await), } } + async fn retire_timed_out_connection( + &self, + client: &Arc, + phase: &str, + timeout: Duration, + ) -> Error { + warn!( + "ACP client startup timed out: id={} connection_id={} phase={} timeout_secs={}", + client.client_id, + client.id, + phase, + timeout.as_secs() + ); + client.detached_after_stop.store(true, Ordering::Release); + self.stop_connection_instance(client).await; + agent_client_protocol::util::internal_error(startup_timeout_error_message( + &client.client_id, + phase, + timeout, + )) + } + async fn attach_remote_session( &self, client: &Arc, @@ -1715,25 +2372,37 @@ impl AcpClientService { session_storage_path: Option<&Path>, session: &mut AcpRemoteSession, response: NewSessionResponse, + existing: Option>, + replay: Option, strategy: AcpRemoteSessionStrategy, last_resume_error: Option, + require_restore: bool, ) -> OpenBitFunResult<()> { - let cx = client.connection().await?; let models = response.models.clone(); - let config_options = response.config_options.clone().unwrap_or_default(); - let active = cx - .attach_session(response, Vec::new()) - .map_err(protocol_error)?; + let config_options = response.config_options.clone(); + let active = match existing { + Some(active) => active, + None => client + .connection() + .await? + .attach_session(response, Vec::new()) + .map_err(protocol_error)?, + }; + let metadata = if let Some(mut history) = replay { + let metadata = std::mem::take(&mut history.metadata); + if let Some(path) = session_storage_path { + // Writers of this session's history take the same gate. + let gate = self.turn_gate(openbitfun_session_id); + let _write = gate.lock().await; + history + .reconcile(&self.session_persistence, path, openbitfun_session_id) + .await?; + } + metadata + } else { + Vec::new() + }; let remote_session_id = active.session_id().to_string(); - client.cancel_handles.insert( - session_key.to_string(), - AcpCancelHandle { - session_id: remote_session_id.clone(), - connection: active.connection(), - }, - ); - self.session_permission_modes - .insert(remote_session_id.clone(), client.config.permission_mode); if let Some(session_storage_path) = session_storage_path { self.session_persistence .update_remote_session_state( @@ -1742,14 +2411,31 @@ impl AcpClientService { &remote_session_id, strategy.as_str(), last_resume_error, + require_restore, ) .await?; } + if client.connection.read().await.is_some() { + self.session_permission_modes + .insert(remote_session_id, client.config.permission_mode); + client.cancel_handles.insert( + session_key.to_string(), + AcpCancelHandle::new(&active, session.stop_requested.clone()), + ); + session.active = Some(active); + } + update_session_from_events(session, &metadata); session.models = models; - session.config_options = config_options; - session.discard_pending_updates_before_next_prompt = - matches!(strategy, AcpRemoteSessionStrategy::Load); - session.active = Some(active); + if let Some(options) = config_options { + session.config_options = options; + } + drain_pending_session_metadata_updates(session, true).await?; + let options = session.publish_metadata(); + if let Some(path) = session_storage_path { + self.session_persistence + .save_options(path, openbitfun_session_id, &options) + .await?; + } Ok(()) } @@ -2132,6 +2818,7 @@ fn current_unix_timestamp_ms() -> u64 { impl AcpClientConnection { fn new(id: String, client_id: String, config: AcpClientConfig) -> Self { Self { + detached_after_stop: AtomicBool::new(false), id, client_id, config, @@ -2197,6 +2884,17 @@ async fn wait_for_client_connection( } } +/// Resolves once the accepted turn is stopped or released before its prompt was +/// sent. A released execution drops its sender, which is the same end for this turn. +async fn stopped(cancel: &mut Option>) { + match cancel.as_mut() { + Some(cancel) => { + let _ = cancel.wait_for(|stopped| *stopped).await; + } + None => std::future::pending::<()>().await, + } +} + fn parse_config_value(value: serde_json::Value) -> OpenBitFunResult { let mut config = if value.get("acpClients").is_some() { serde_json::from_value(value).map_err(|error| { @@ -2498,7 +3196,7 @@ async fn read_turn_to_string( .active .as_mut() .ok_or_else(|| OpenBitFunError::service("ACP session was not initialized"))?; - prompt.read_update(active).await.map_err(protocol_error)? + prompt.read_update(active).await? }; match message { @@ -2509,8 +3207,11 @@ async fn read_turn_to_string( update_session_from_events(session, &events); append_agent_text(&mut output, events); } - SessionMessage::StopReason(_) => { + SessionMessage::StopReason(reason) => { drain_pending_turn_text(session, &mut tool_call_tracker, &mut output).await?; + if reason == StopReason::Cancelled { + return Err(OpenBitFunError::cancelled("ACP prompt cancelled")); + } break; } _ => {} @@ -2573,7 +3274,8 @@ fn append_agent_text(output: &mut String, events: Vec) { async fn drain_pending_session_metadata_updates( session: &mut AcpRemoteSession, -) -> OpenBitFunResult<()> { + initial: bool, +) -> OpenBitFunResult { let started_at = Instant::now(); let mut drained_count = 0usize; let mut tool_call_tracker = AcpToolCallTracker::new(); @@ -2581,27 +3283,38 @@ async fn drain_pending_session_metadata_updates( while started_at.elapsed() < SESSION_METADATA_DRAIN_MAX_DURATION { let update = { let Some(active) = session.active.as_mut() else { - return Ok(()); + break; }; - tokio::time::timeout(SESSION_METADATA_DRAIN_QUIET_WINDOW, active.read_update()).await + if initial { + tokio::time::timeout(SESSION_METADATA_DRAIN_QUIET_WINDOW, active.read_update()) + .await + .ok() + } else { + active.read_update().now_or_never() + } }; match update { - Ok(Ok(SessionMessage::SessionMessage(dispatch))) => { + Some(Ok(SessionMessage::SessionMessage(dispatch))) => { let events = acp_dispatch_to_stream_events_with_tracker(dispatch, &mut tool_call_tracker) .await?; update_session_from_events(session, &events); drained_count += 1; } - Ok(Ok(SessionMessage::StopReason(_))) => { + Some(Ok(SessionMessage::StopReason(_))) => { drained_count += 1; } - Ok(Ok(_)) => { + Some(Ok(_)) => { drained_count += 1; } - Ok(Err(error)) => return Err(protocol_error(error)), - Err(_) => break, + Some(Err(_)) => { + // A successful setup already supplied the metadata. A closed receiver + // makes that snapshot offline and future prompts must reattach. + session.active = None; + break; + } + None => break, } } @@ -2612,58 +3325,7 @@ async fn drain_pending_session_metadata_updates( ); } - Ok(()) -} - -async fn discard_pending_session_updates_if_needed(session: &mut AcpRemoteSession) { - if !session.discard_pending_updates_before_next_prompt { - return; - } - - session.discard_pending_updates_before_next_prompt = false; - let started_at = Instant::now(); - let mut discarded_count = 0usize; - while started_at.elapsed() < LOAD_REPLAY_DRAIN_MAX_DURATION { - let update = { - let Some(active) = session.active.as_mut() else { - return; - }; - tokio::time::timeout(LOAD_REPLAY_DRAIN_QUIET_WINDOW, active.read_update()).await - }; - - match update { - Ok(Ok(SessionMessage::SessionMessage(dispatch))) => { - let mut tracker = AcpToolCallTracker::new(); - if let Ok(events) = - acp_dispatch_to_stream_events_with_tracker(dispatch, &mut tracker).await - { - update_session_from_events(session, &events); - } - discarded_count += 1; - } - Ok(Ok(SessionMessage::StopReason(_))) => { - discarded_count += 1; - } - Ok(Ok(_)) => { - discarded_count += 1; - } - Ok(Err(error)) => { - warn!( - "Failed to discard ACP load replay update before prompt: error={}", - error - ); - break; - } - Err(_) => break, - } - } - - if discarded_count > 0 { - info!( - "Discarded ACP load replay updates before prompt: count={}", - discarded_count - ); - } + Ok(drained_count > 0) } fn update_session_from_events(session: &mut AcpRemoteSession, events: &[AcpClientStreamEvent]) { @@ -2718,7 +3380,7 @@ fn update_session_config_options(session: &mut AcpRemoteSession, events: &[AcpCl session.config_options = options; } -fn protocol_error(error: impl std::fmt::Display) -> OpenBitFunError { +pub(super) fn protocol_error(error: impl std::fmt::Display) -> OpenBitFunError { OpenBitFunError::service(format!("ACP protocol error: {}", error)) } @@ -2833,23 +3495,23 @@ fn startup_exit_error_message(client_id: &str, stderr_detail: &str) -> String { const STARTUP_TIMEOUT_ERROR_PREFIX: &str = "ACP startup timed out:"; fn startup_timeout_error(client_id: &str, phase: &str) -> OpenBitFunError { - OpenBitFunError::service(startup_timeout_error_message(client_id, phase)) + OpenBitFunError::service(startup_timeout_error_message( + client_id, + phase, + CLIENT_STARTUP_TIMEOUT, + )) } -fn startup_timeout_error_message(client_id: &str, phase: &str) -> String { +fn startup_timeout_error_message(client_id: &str, phase: &str, timeout: Duration) -> String { format!( "{} client '{}' exceeded {}s during {} and was terminated. Please try again after the client is ready.", STARTUP_TIMEOUT_ERROR_PREFIX, client_id, - CLIENT_STARTUP_TIMEOUT_SECS, + timeout.as_secs(), phase ) } -fn is_startup_timeout_error(error: &OpenBitFunError) -> bool { - error.to_string().contains(STARTUP_TIMEOUT_ERROR_PREFIX) -} - fn select_permission_by_kind( request: &RequestPermissionRequest, preferred: PermissionOptionKind, @@ -2904,11 +3566,14 @@ fn select_permission_option_id(options: &[PermissionOption], approve: bool) -> S }) } +#[cfg(test)] +mod recovery_tests; + #[cfg(test)] mod tests { use super::*; - fn test_client_connection(id: &str) -> Arc { + pub(super) fn test_client_connection(id: &str) -> Arc { Arc::new(AcpClientConnection::new( id.to_string(), "opencode".to_string(), @@ -3076,7 +3741,7 @@ mod tests { #[test] fn formats_startup_timeout_error_message() { assert_eq!( - startup_timeout_error_message("codex", "initialize"), + startup_timeout_error_message("codex", "initialize", CLIENT_STARTUP_TIMEOUT), "ACP startup timed out: client 'codex' exceeded 60s during initialize and was terminated. Please try again after the client is ready." ); } diff --git a/src/crates/interfaces/acp/src/client/manager/recovery_tests.rs b/src/crates/interfaces/acp/src/client/manager/recovery_tests.rs new file mode 100644 index 0000000000..4d6f3345de --- /dev/null +++ b/src/crates/interfaces/acp/src/client/manager/recovery_tests.rs @@ -0,0 +1,1922 @@ +use super::tests::test_client_connection; +use super::*; +use crate::client::execution::tests::Journal; +use crate::client::execution::AcpProjectionJournal; +use crate::client::prompt::tests::Harness; +use agent_client_protocol::schema::{ + AgentCapabilities, SessionCapabilities, SessionResumeCapabilities, +}; +use openbitfun_core::agentic::persistence::PersistenceManager; +use openbitfun_core::service::session::{SessionStorageLayout, TurnStatus}; +use openbitfun_core::service::{config::ConfigManagerSettings, session::SessionMetadata}; + +const CHAT: &str = "acp_chat"; + +struct TestSession { + service: Arc, + storage: PersistenceManager, + journal: Arc, + root: tempfile::TempDir, +} + +impl TestSession { + async fn new() -> OpenBitFunResult { + let root = tempfile::tempdir()?; + let paths = Arc::new(PathManager::with_user_root_for_tests( + root.path().join("user"), + )); + let config = ConfigService::with_settings(ConfigManagerSettings { + path_manager: Some(paths.clone()), + ..Default::default() + }) + .await?; + let storage = PersistenceManager::new(paths.clone())?; + let service = AcpClientService::new(Arc::new(config), paths)?; + let journal = Arc::new(Journal::default()); + service + .configure_execution_journal(journal.clone()) + .map_err(OpenBitFunError::service)?; + Ok(Self { + service, + storage, + journal, + root, + }) + } + + fn layout(&self) -> SessionStorageLayout { + SessionStorageLayout::new( + self.storage + .path_manager() + .project_sessions_dir(self.root.path()), + ) + } + + fn restart(&mut self) -> OpenBitFunResult<()> { + self.service = AcpClientService::new( + self.service.config_service.clone(), + self.storage.path_manager().clone(), + )?; + self.service + .configure_execution_journal(self.journal.clone()) + .map_err(OpenBitFunError::service) + } + + async fn save_history(&self, custom: serde_json::Value) -> OpenBitFunResult<()> { + let mut metadata = SessionMetadata::new( + CHAT.into(), + "chat".into(), + "acp:opencode".into(), + "primary".into(), + ); + metadata.custom_metadata = Some(custom); + self.storage + .create_session_metadata_if_absent(self.root.path(), &metadata) + .await?; + Ok(()) + } + + async fn save_interrupted_prompts(&self, prompts: &[&str]) -> OpenBitFunResult<()> { + self.save_history(json!({"acpRemoteSessionId":"original","acpHistoryGap":true})) + .await?; + for (index, &prompt) in prompts.iter().enumerate() { + let mut turn = super::super::transcript::start_turn( + CHAT, + &format!("turn-{index}"), + index, + "opencode", + prompt, + None, + ); + turn.user_message.id = format!("message-{index}"); + turn.status = TurnStatus::Error; + turn.finish_reason = Some("acp_outcome_unknown".into()); + self.storage + .save_dialog_turn(self.root.path(), &turn) + .await?; + } + Ok(()) + } + + async fn connect(&self, capabilities: Option) -> Harness { + let agent = Harness::new().await; + let key = session_client_connection_id("opencode", CHAT); + let client = test_client_connection(&key); + *client.connection.write().await = Some(agent.active.connection()); + *client.agent_capabilities.write().await = Some(capabilities.unwrap_or_else(|| { + AgentCapabilities::new() + .load_session(true) + .session_capabilities( + SessionCapabilities::new().resume(SessionResumeCapabilities::new()), + ) + })); + *client.status.write().await = AcpClientStatus::Running; + self.service.clients.insert(key, client); + agent + } + + async fn needs_history(&self) -> OpenBitFunResult { + Ok(self + .storage + .load_session_metadata(self.root.path(), CHAT) + .await? + .as_ref() + .is_some_and(AcpSessionPersistence::has_history_gap)) + } + + async fn admit(&self, turn: &str, text: &str) -> OpenBitFunResult> { + self.admit_with(turn, text, text).await + } + + /// `sent` is the prompt text the agent receives; `shown` is the user's message. + async fn admit_with( + &self, + turn: &str, + sent: &str, + shown: &str, + ) -> OpenBitFunResult> { + self.service + .admit_dialog_turn( + CHAT, + turn, + "opencode", + sent, + shown, + None, + Some(self.root.path()), + ) + .await + .map_err(OpenBitFunError::service) + } + + async fn stream( + &self, + turn: &str, + text: &str, + timeout: Option, + on_event: impl FnMut(AcpClientStreamEvent) -> OpenBitFunResult<()> + Send, + ) -> OpenBitFunResult<()> { + let path = self.root.path(); + self.service + .prompt_agent_stream( + "opencode", + text.to_owned(), + Some(path.display().to_string()), + None, + CHAT.into(), + Some(turn), + Some(path.into()), + timeout, + on_event, + ) + .await + } + + /// Open the session so the agent receives `method`, answering with `replay`. + async fn open_with( + &self, + agent: &mut Harness, + method: &str, + replay: &[(&str, &str, Option<&str>)], + ) -> OpenBitFunResult<()> { + let path = self.root.path(); + let (options, ()) = tokio::join!( + self.service.get_session_options( + "opencode", + Some(path.display().to_string()), + None, + Some(path.into()), + CHAT.into(), + ), + async { + let request = agent.request().await; + assert_eq!(request["method"], method); + for &(kind, text, id) in replay { + let mut update = + json!({"sessionUpdate":kind,"content":{"type":"text","text":text}}); + if let Some(id) = id { + update["messageId"] = json!(id); + } + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":update}})).await; + } + agent + .send(json!({"jsonrpc":"2.0","id":request["id"],"result":{}})) + .await; + } + ); + options.map(|_| ()) + } + + async fn prompt(&self, text: &str) -> OpenBitFunResult { + self.service + .prompt_agent( + "opencode", + text.into(), + Some(self.root.path().display().to_string()), + None, + CHAT.into(), + Some(self.root.path().into()), + Some(10), + ) + .await + } +} + +#[tokio::test] +async fn queued_prompt_reloads_the_original_history_after_an_unconfirmed_stop( +) -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + session.save_history(json!("legacy")).await?; + let mut old = session.connect(None).await; + let mut queued = Box::pin(session.prompt("queued")); + let (stopped, ()) = tokio::join!(session.prompt("edit once"), async { + old.reply("session/new", json!({"result": {"sessionId": "original"}})) + .await; + assert_eq!(old.request().await["method"], "session/prompt"); + // Queue behind the same turn before requesting a stop that the agent never confirms. + assert!(futures::poll!(queued.as_mut()).is_pending()); + assert!(session + .service + .cancel_openbitfun_session(CHAT) + .await + .unwrap()); + assert_eq!(old.request().await["method"], "session/cancel"); + }); + assert!(matches!(stopped, Err(OpenBitFunError::OutcomeUnknown(_)))); + let saved = session + .storage + .load_session_metadata(session.root.path(), CHAT) + .await? + .unwrap(); + let fields = saved.custom_metadata.unwrap(); + let binding = || { + session + .service + .session_persistence + .remote_session_binding(session.root.path(), CHAT) + }; + assert_eq!(binding().await?, (Some("original".into()), true)); + assert_eq!(fields["acpLegacyCustomMetadata"], "legacy"); + + let mut agent = session.connect(None).await; + let offline = json!({"error": {"code": -32603, "message": "temporarily offline"}}); + let (failed, load) = tokio::join!(queued, agent.reply("session/load", offline)); + assert_eq!(load["sessionId"], "original"); + assert!( + matches!(failed, Err(OpenBitFunError::Session(reason)) if reason.contains("temporarily offline")) + ); + + let (retried, ()) = tokio::join!(session.prompt("fresh"), async { + let load = agent.reply("session/load", json!({"result": {}})).await; + assert_eq!(load["sessionId"], "original"); + let request = agent.finish_with_text("back online", "end_turn").await; + assert_eq!(request["sessionId"], "original"); + assert_eq!(request["prompt"][0]["text"], "fresh"); + }); + assert_eq!(retried?, "back online"); + assert_eq!(binding().await?, (Some("original".into()), false)); + Ok(()) +} + +#[tokio::test] +async fn a_failed_restore_keeps_the_original_session_for_retry() -> OpenBitFunResult<()> { + for stop_unconfirmed in [false, true] { + let session = TestSession::new().await?; + session + .save_history(json!({ + "acpRemoteSessionId": "original", + "acpRestoreRequired": stop_unconfirmed, + })) + .await?; + let mut agent = session.connect(None).await; + let method = if stop_unconfirmed { + "session/load" + } else { + "session/resume" + }; + let (failed, request) = tokio::join!( + session.prompt("first"), + agent.reply( + method, + json!({"error": {"code": -32603, "message": "offline"}}), + ) + ); + assert_eq!(request["sessionId"], "original"); + assert!(failed.unwrap_err().to_string().contains("offline")); + let binding = || { + session + .service + .session_persistence + .remote_session_binding(session.root.path(), CHAT) + }; + assert_eq!( + binding().await?, + (Some("original".into()), stop_unconfirmed) + ); + + let (retried, ()) = tokio::join!(session.prompt("retry"), async { + if !stop_unconfirmed { + let resume = agent + .reply( + "session/resume", + json!({"error":{"code":-32601,"message":"method unavailable"}}), + ) + .await; + assert_eq!(resume["sessionId"], "original"); + } + let load = agent.reply("session/load", json!({"result": {}})).await; + assert_eq!(load["sessionId"], "original"); + let prompt = agent.finish_with_text("reply", "end_turn").await; + assert_eq!(prompt["sessionId"], "original"); + assert_eq!(prompt["prompt"][0]["text"], "retry"); + }); + assert_eq!(retried?, "reply"); + assert_eq!(binding().await?, (Some("original".into()), false)); + } + Ok(()) +} + +#[tokio::test] +async fn an_agent_without_restore_keeps_the_binding_and_the_unsent_input() -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_history(json!({"acpRemoteSessionId":"original"})) + .await?; + session.admit("attempt", "continue").await?; + let mut agent = session.connect(Some(AgentCapabilities::new())).await; + let error = tokio::select! { + result = session.stream("attempt", "continue", Some(5), |_| Ok(())) => result.unwrap_err(), + request = agent.request() => panic!("unexpected request on a saved session: {request}"), + }; + let mut terminal = json!({"sessionId":CHAT,"turnId":"attempt","error":error.to_string()}); + session + .service + .finish_dialog_turn( + CHAT, + Some(path), + "agentic://dialog-turn-failed", + &mut terminal, + ) + .await?; + let saved = session + .storage + .load_dialog_turn(path, CHAT, 0) + .await? + .unwrap(); + assert_eq!(saved.status, TurnStatus::Error); + assert_eq!(saved.finish_reason.as_deref(), Some("acp_not_sent")); + let reason = saved.error.unwrap(); + assert!(reason.contains("does not support resuming or loading")); + assert!(reason.contains("Start a new chat")); + assert_eq!( + session + .service + .session_persistence + .remote_session_binding(path, CHAT) + .await?, + (Some("original".into()), false) + ); + Ok(()) +} + +#[tokio::test] +async fn missing_record_allows_sending_but_blocks_required_recovery() -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let mut agent = session.connect(None).await; + let stream = session.service.prompt_agent_stream( + "opencode", + "edit once".into(), + Some(session.root.path().display().to_string()), + None, + CHAT.into(), + None, + Some(session.root.path().into()), + Some(10), + |_| Ok(()), + ); + let (stopped, ()) = tokio::join!(stream, async { + agent + .reply("session/new", json!({"result": {"sessionId": "original"}})) + .await; + let request = agent.request().await; + assert_eq!(request["method"], "session/prompt"); + assert_eq!(request["params"]["prompt"][0]["text"], "edit once"); + assert!(session + .service + .cancel_openbitfun_session(CHAT) + .await + .unwrap()); + }); + assert!( + matches!(stopped, Err(OpenBitFunError::OutcomeUnknown(reason)) if reason.contains("could not be saved")) + ); + + let mut replacement = session.connect(None).await; + let (failed, load) = tokio::join!( + session.prompt("retry"), + replacement.reply("session/load", json!({"result": {}})) + ); + assert_eq!(load["sessionId"], "original"); + assert!(matches!(failed, Err(OpenBitFunError::NotFound(_)))); + assert!(!session.service.cancel_openbitfun_session(CHAT).await?); + Ok(()) +} + +#[tokio::test] +async fn cancelled_tool_prompts_never_return_successful_text() -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + session + .save_history(json!({"acpRemoteSessionId": "original"})) + .await?; + let mut agent = session.connect(None).await; + *session + .service + .clients + .get(&session_client_connection_id("opencode", CHAT)) + .unwrap() + .agent_capabilities + .write() + .await = Some(AgentCapabilities::new().load_session(true)); + let (before_submit, ()) = tokio::join!(session.prompt("never send"), async { + agent.reply("session/load", json!({"result": {}})).await; + // Stop through the public entry point while the manager is draining load replay. + tokio::time::timeout(Duration::from_secs(2), async { + while !session + .service + .cancel_openbitfun_session(CHAT) + .await + .unwrap() + { + tokio::task::yield_now().await; + } + }) + .await + .expect("loaded session must become cancellable"); + assert_eq!(agent.request().await["method"], "session/cancel"); + }); + assert!(matches!(before_submit, Err(OpenBitFunError::Cancelled(_)))); + + let (after_submit, ()) = tokio::join!(session.prompt("next"), async { + let request = agent.finish_with_text("partial", "cancelled").await; + assert_eq!(request["sessionId"], "original"); + assert_eq!(request["prompt"][0]["text"], "next"); + }); + assert!(matches!(after_submit, Err(OpenBitFunError::Cancelled(_)))); + Ok(()) +} + +#[tokio::test] +async fn background_turn_survives_view_detach_and_host_restart() -> OpenBitFunResult<()> { + let mut session = TestSession::new().await?; + session.save_history(json!({"provider":"acp"})).await?; + let path = session.root.path().to_owned(); + let metadata = json!({"original_text":"run once"}); + let started = session + .service + .admit_dialog_turn( + CHAT, + "turn-a", + "opencode", + "run once", + "run once", + Some(metadata.clone()), + Some(&path), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + started["userMessageMetadata"]["acpRuntimeOwnsHistory"], + true + ); + for (name, extra) in [ + ( + "agentic://model-round-started", + json!({"roundId":"round-a", "roundIndex":0}), + ), + ("agentic://text-chunk", json!({"text":"before the tool"})), + ( + "agentic://tool-event", + json!({"toolEvent":{"event_type":"Started","tool_id":"tool-a","tool_name":"read","params":{"path":"example"}}}), + ), + ( + "agentic://tool-event", + json!({"toolEvent":{"event_type":"Completed","tool_id":"tool-a","tool_name":"read","result":"done","duration_ms":4}}), + ), + ("agentic://text-chunk", json!({"text":"after the tool"})), + ] { + let mut payload = extra; + payload["sessionId"] = CHAT.into(); + payload["turnId"] = "turn-a".into(); + payload["roundId"] = "round-a".into(); + session + .service + .record_dialog_event(name, &mut payload) + .unwrap(); + } + let stale = session + .storage + .load_dialog_turn(&path, CHAT, 0) + .await? + .unwrap(); + assert!(stale.model_rounds.is_empty()); + let session_dir = session + .storage + .path_manager() + .project_sessions_dir(&path) + .join(CHAT); + let backup = path.join("saved-session"); + std::fs::rename(&session_dir, &backup)?; + std::fs::write(&session_dir, "storage unavailable")?; + let mut terminal = json!({"sessionId":CHAT, "turnId":"turn-a"}); + session + .service + .finish_dialog_turn( + CHAT, + Some(&path), + "agentic://dialog-turn-completed", + &mut terminal, + ) + .await?; + assert!(terminal["acpHistorySaveError"].is_string()); + assert!(!session.service.execution_snapshot(CHAT).unwrap().running); + assert!(matches!( + session.journal.pending_checkpoint(CHAT).last(), + Some(openbitfun_events::AgenticEvent::DialogTurnCompleted { .. }) + )); + std::fs::remove_file(&session_dir)?; + std::fs::rename(&backup, &session_dir)?; + session + .service + .recover_stored_dialog_turn(&path, CHAT) + .await?; + assert!(session.journal.pending_checkpoint(CHAT).is_empty()); + session + .storage + .save_external_view_checkpoint(&path, &stale) + .await?; + session.restart()?; + session + .service + .recover_stored_dialog_turn(&path, CHAT) + .await?; + let saved = session + .storage + .load_dialog_turn(&path, CHAT, 0) + .await? + .unwrap(); + assert_eq!(saved.status, TurnStatus::Completed); + assert_eq!(saved.user_message.metadata, Some(metadata)); + let round = &saved.model_rounds[0]; + assert_eq!(round.text_items[0].content, "before the tool"); + assert_eq!(round.tool_items[0].tool_call.input["path"], "example"); + assert_eq!( + round.tool_items[0].tool_result.as_ref().unwrap().result, + "done" + ); + assert_eq!(round.text_items[1].content, "after the tool"); + assert!(session.admit("turn-a", "run once").await?.is_none()); + Ok(()) +} + +#[tokio::test] +async fn stopping_during_session_restore_settles_before_the_agent_replies() -> OpenBitFunResult<()> +{ + for (method, history) in [ + ("session/resume", json!({"acpRemoteSessionId":"original"})), + ( + "session/load", + json!({"acpRemoteSessionId":"original","acpRestoreRequired":true}), + ), + ] { + let session = TestSession::new().await?; + let path = session.root.path(); + session.save_history(history).await?; + session.admit("turn", "hello").await?; + let mut agent = session.connect(None).await; + let mut cancelled = false; + let mut worker = Box::pin(session.stream("turn", "hello", None, |event| { + cancelled |= matches!(event, AcpClientStreamEvent::Cancelled); + Ok(()) + })); + let restore = tokio::select! { + request = agent.request() => request, + result = &mut worker => panic!("turn settled before {method}: {result:?}"), + }; + assert_eq!(restore["method"], method); + session + .service + .cancel_agent_session( + "opencode", + Some(path.display().to_string()), + CHAT.into(), + Some("turn"), + ) + .await?; + tokio::time::timeout(Duration::from_secs(5), worker) + .await + .expect("turn should settle while the restore response is withheld")?; + assert!(cancelled); + agent + .send(json!({"jsonrpc":"2.0","id":restore["id"],"result":{}})) + .await; + + let mut terminal = json!({"sessionId":CHAT,"turnId":"turn"}); + session + .service + .finish_dialog_turn( + CHAT, + Some(path), + "agentic://dialog-turn-cancelled", + &mut terminal, + ) + .await?; + let saved = session + .storage + .load_dialog_turn(path, CHAT, 0) + .await? + .unwrap(); + assert_eq!(saved.finish_reason.as_deref(), Some("acp_not_sent")); + let (reply, next) = tokio::join!( + session.prompt("next"), + agent.finish_with_text("ok", "end_turn") + ); + assert_eq!(next["prompt"][0]["text"], "next"); + assert_eq!(reply?, "ok"); + } + Ok(()) +} + +#[tokio::test] +async fn opening_a_legacy_session_and_sending_share_one_restore() -> OpenBitFunResult<()> { + let mut session = TestSession::new().await?; + let path = session.root.path().to_owned(); + session + .save_history(json!({"provider": "acp", "acpRemoteSessionId": "original"})) + .await?; + let missing = session + .service + .observe_session_options("opencode", CHAT, path.to_str(), Some(&path)) + .await?; + assert!(missing.needs_initial_options); + assert!(missing.current_model_id.is_none()); + assert!(session.service.clients.is_empty()); + + let mut agent = session.connect(None).await; + let (options, reply) = tokio::join!( + session.service.get_session_options( + "opencode", + Some(path.display().to_string()), + None, + Some(path.clone()), + CHAT.into(), + ), + async { + let restore = agent.request().await; + assert_eq!(restore["method"], "session/resume"); + assert_eq!(restore["params"]["sessionId"], "original"); + let (reply, ()) = tokio::join!(session.prompt("hello"), async { + agent.send(json!({"jsonrpc":"2.0", "id":restore["id"], "result":{ + "models":{"currentModelId":"current","availableModels":[{"modelId":"current","name":"Current"}]} + }})).await; + let prompt = agent.finish_with_text("answer", "end_turn").await; + assert_eq!(prompt["sessionId"], "original"); + assert_eq!(prompt["prompt"][0]["text"], "hello"); + }); + reply + }, + ); + assert_eq!(options?.current_model_id.as_deref(), Some("current")); + assert_eq!(reply?, "answer"); + + session.restart()?; + let cached = session + .service + .observe_session_options("opencode", CHAT, path.to_str(), Some(&path)) + .await?; + assert!(cached.agent_disconnected); + assert!(!cached.needs_initial_options); + assert_eq!(cached.current_model_id.as_deref(), Some("current")); + assert!(session.service.clients.is_empty()); + Ok(()) +} + +#[tokio::test] +async fn interrupted_output_is_reconciled_before_sending_the_next_turn() -> OpenBitFunResult<()> { + let mut session = TestSession::new().await?; + session + .save_history(json!({"acpRemoteSessionId":"original","provider":"acp"})) + .await?; + let path = session.root.path().to_owned(); + session.admit("interrupted", "first").await?; + for (name, mut payload) in [ + ("agentic://model-round-started", json!({"roundIndex":0})), + ("agentic://text-chunk", json!({"text":"partial"})), + ] { + payload["sessionId"] = CHAT.into(); + payload["turnId"] = "interrupted".into(); + payload["roundId"] = "r".into(); + session + .service + .record_dialog_event(name, &mut payload) + .unwrap(); + } + session.restart()?; + session + .service + .recover_stored_dialog_turn(&path, CHAT) + .await?; + assert!(session.service.clients.is_empty()); + let saved = session + .storage + .load_dialog_turn(&path, CHAT, 0) + .await? + .unwrap(); + assert_eq!(saved.model_rounds[0].text_items[0].content, "partial"); + assert_eq!(saved.finish_reason.as_deref(), Some("acp_outcome_unknown")); + assert_eq!(saved.model_rounds[0].status, "error"); + assert!(session.needs_history().await?); + + let admit = || session.admit("next-turn", "next"); + let receipt = admit().await.unwrap().unwrap(); + assert!(receipt["turnIndex"].is_null()); + assert!(session.service.clients.is_empty()); + let mut agent = session.connect(None).await; + let id = saved.user_message.id; + let (result, ()) = tokio::join!( + session.stream("next-turn", "next", None, |_| Ok(()),), + async { + let request = agent.request().await; + assert_eq!(request["method"], "session/load"); + assert_eq!(request["params"]["sessionId"], "original"); + tokio::time::pause(); + tokio::time::sleep(Duration::from_secs(45)).await; + assert!(admit().await.unwrap().is_none()); + for (kind, text, id) in [ + ("user_message_chunk", "first", Some(&id)), + ("agent_message_chunk", "partial recovered", None), + ("user_message_chunk", "first", None), + ("agent_message_chunk", "restored output", None), + ] { + let mut update = + json!({"sessionUpdate":kind, "content":{"type":"text","text":text}}); + if let Some(id) = id { + update["messageId"] = json!(id); + } + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":update}})).await; + if kind == "user_message_chunk" { + // A progressing history replay can legitimately span several startup timeouts. + tokio::time::sleep(Duration::from_secs(45)).await; + } + } + tokio::time::resume(); + agent + .send(json!({"jsonrpc":"2.0","id":request["id"],"result":{}})) + .await; + let sent = agent.finish_with_text("done", "end_turn").await; + assert_eq!(sent["sessionId"], "original"); + assert_eq!(sent["prompt"][0]["text"], "next"); + } + ); + result?; + let mut done = json!({"sessionId": CHAT, "turnId": "next-turn"}); + session + .service + .finish_dialog_turn( + CHAT, + Some(&path), + "agentic://dialog-turn-completed", + &mut done, + ) + .await?; + let repaired = session + .storage + .load_visible_session_turns(&path, CHAT) + .await?; + assert_eq!(repaired.len(), 3); + assert_eq!( + repaired[1].model_rounds[0].text_items[0].content, + "restored output" + ); + assert_eq!( + (repaired[2].turn_index, repaired[2].turn_id.as_str()), + (2, "next-turn") + ); + assert_eq!( + repaired[0].model_rounds[0].text_items[0].content, + "partial recovered" + ); + assert_eq!(repaired[0].turn_id, "interrupted"); + assert_eq!( + repaired[0].finish_reason.as_deref(), + Some("acp_outcome_unknown") + ); + assert!(!session.needs_history().await?); + Ok(()) +} + +#[tokio::test] +async fn a_legacy_interrupted_turn_keeps_its_richer_checkpoint_after_partial_replay( +) -> OpenBitFunResult<()> { + expect_legacy_checkpoint_preserved(&["already"]).await +} + +#[tokio::test] +async fn repeated_prompts_without_message_ids_leave_ambiguous_history_intact( +) -> OpenBitFunResult<()> { + expect_legacy_checkpoint_preserved(&["already saved first reply", "already saved second reply"]) + .await +} + +#[tokio::test] +async fn adjacent_user_chunks_need_a_message_id_to_recover_one_prompt() -> OpenBitFunResult<()> { + for id in [None, Some("c52081b3-45ff-44ab-9c12-48ed2cd97fd4")] { + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_history(json!({"acpRemoteSessionId":"original","acpHistoryGap":true})) + .await?; + let mut known = + super::super::transcript::start_turn(CHAT, "known", 0, "opencode", "earlier", None); + known.status = TurnStatus::Error; + session.storage.save_dialog_turn(path, &known).await?; + let mut agent = session.connect(None).await; + let (options, ()) = tokio::join!( + session.service.get_session_options( + "opencode", + Some(path.display().to_string()), + None, + Some(path.into()), + CHAT.into() + ), + async { + let load = agent.request().await; + assert_eq!(load["method"], "session/load"); + for (kind, text, id) in [ + ( + "user_message_chunk", + "earlier", + Some(known.user_message.id.as_str()), + ), + ("agent_message_chunk", "recovered answer", None), + ("user_message_chunk", "hello", id), + ("user_message_chunk", " again", id), + ] { + let mut update = + json!({"sessionUpdate":kind,"content":{"type":"text","text":text}}); + if let Some(id) = id { + update["messageId"] = json!(id); + } + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":update}})).await; + } + agent + .send(json!({"jsonrpc":"2.0","id":load["id"],"result":{}})) + .await; + } + ); + options?; + let saved = session + .storage + .load_visible_session_turns(path, CHAT) + .await?; + assert_eq!(saved[0].turn_id, "known"); + assert_eq!( + saved[0].model_rounds[0].text_items[0].content, + "recovered answer" + ); + if let Some(id) = id { + assert_eq!(saved.len(), 2); + assert_eq!(saved[1].user_message.id, id); + assert_eq!(saved[1].user_message.content, "hello again"); + assert!(!session.needs_history().await?); + } else { + assert_eq!(saved.len(), 1); + assert!(session.needs_history().await?); + } + } + Ok(()) +} + +async fn expect_legacy_checkpoint_preserved(replies: &[&str]) -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_history(json!({"provider":"acp","acpRemoteSessionId":"original"})) + .await?; + let mut old = + super::super::transcript::start_turn(CHAT, "old-turn", 0, "opencode", "continue", None); + super::super::transcript::start_round(&mut old, "old-round", 0, 42); + super::super::transcript::append_text(&mut old.model_rounds[0], "already saved", false, 42); + session.storage.save_dialog_turn(path, &old).await?; + session + .service + .recover_stored_dialog_turn(path, CHAT) + .await?; + let saved = session + .storage + .load_dialog_turn(path, CHAT, 0) + .await? + .unwrap(); + assert_eq!(saved.model_rounds[0].id, "old-round"); + assert_eq!(saved.finish_reason.as_deref(), Some("acp_outcome_unknown")); + let mut agent = session.connect(None).await; + let (recovered, ()) = tokio::join!( + session.service.get_session_options( + "opencode", + Some(path.display().to_string()), + None, + Some(path.into()), + CHAT.into() + ), + async { + let load = agent.request().await; + assert_eq!(load["method"], "session/load"); + for &reply in replies { + for (kind, text) in [ + ("user_message_chunk", "continue"), + ("agent_message_chunk", reply), + ] { + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":{"sessionUpdate":kind,"content":{"type":"text","text":text}}}})).await; + } + } + agent + .send(json!({"jsonrpc":"2.0","id":load["id"],"result":{}})) + .await; + } + ); + recovered?; + let turns = session + .storage + .load_visible_session_turns(path, CHAT) + .await?; + assert_eq!(turns.len(), 1); + assert_eq!( + turns[0].model_rounds[0].text_items[0].content, + "already saved" + ); + assert!(session.needs_history().await?); + Ok(()) +} + +#[tokio::test] +async fn a_prompt_deadline_preserves_its_binding_and_unknown_outcome() -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session.save_history(json!({})).await?; + let mut agent = session.connect(None).await; + let run = session.service.prompt_agent( + "opencode", + "edit once".into(), + Some(path.display().to_string()), + None, + CHAT.into(), + Some(path.into()), + Some(1), + ); + let (result, ()) = tokio::join!(run, async { + agent + .reply("session/new", json!({"result":{"sessionId":"original"}})) + .await; + assert_eq!(agent.request().await["method"], "session/prompt"); + }); + assert!(matches!(result, Err(OpenBitFunError::OutcomeUnknown(_)))); + assert_eq!( + session + .service + .session_persistence + .remote_session_binding(path, CHAT) + .await?, + (Some("original".into()), true) + ); + Ok(()) +} + +#[tokio::test] +async fn confirmed_load_recovers_history_offline_without_overwriting_an_active_turn( +) -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_history( + json!({"provider":"acp","acpRemoteSessionId":"original","acpHistoryGap":true}), + ) + .await?; + let local = super::super::transcript::start_turn(CHAT, "local", 0, "opencode", "first", None); + session.storage.save_dialog_turn(path, &local).await?; + let mut agent = session.connect(None).await; + let client = session + .service + .clients + .get(&session_client_connection_id("opencode", CHAT)) + .unwrap() + .clone(); + let (options, ()) = tokio::join!( + session.service.get_session_options( + "opencode", + Some(path.display().to_string()), + None, + Some(path.into()), + CHAT.into() + ), + async { + let request = agent.request().await; + assert_eq!(request["method"], "session/load"); + for (kind, text) in [ + ("user_message_chunk", "first"), + ("agent_message_chunk", "partial"), + ("user_message_chunk", "second"), + ("agent_message_chunk", "saved answer"), + ] { + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original", + "update":{"sessionUpdate":kind,"content":{"type":"text","text":text}}}})).await; + } + agent.send(json!({"jsonrpc":"2.0","id":request["id"],"result":{ + "models":{"currentModelId":"chosen","availableModels":[{"modelId":"chosen","name":"Chosen"}]}}})).await; + // The connection monitor can retire the transport before the confirmed response is consumed. + *client.connection.write().await = None; + } + ); + let options = options?; + assert!(options.agent_disconnected); + assert_eq!(options.current_model_id.as_deref(), Some("chosen")); + let turns = session + .storage + .load_visible_session_turns(path, CHAT) + .await?; + assert_eq!(turns.len(), 2); + assert_eq!(turns[0].status, TurnStatus::InProgress); + assert!(turns[0].model_rounds.is_empty()); + assert_eq!( + turns[1].model_rounds[0].text_items[0].content, + "saved answer" + ); + assert!(session.needs_history().await?); + Ok(()) +} + +#[tokio::test] +async fn a_stalled_load_reconnects_to_the_original_session_without_rewriting_complete_history( +) -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_history(json!({"provider":"acp","acpRemoteSessionId":"original"})) + .await?; + let key = session_client_connection_id("opencode", CHAT); + let get_options = || { + session.service.get_session_options( + "opencode", + Some(path.display().to_string()), + None, + Some(path.into()), + CHAT.into(), + ) + }; + for deadline in [CLIENT_STARTUP_TIMEOUT, SESSION_LOAD_TIMEOUT] { + let mut agent = session.connect(None).await; + let old = session.service.clients.get(&key).unwrap().clone(); + *old.agent_capabilities.write().await = Some(AgentCapabilities::new().load_session(true)); + let (result, ()) = tokio::join!(get_options(), async { + let request = agent.request().await; + assert_eq!(request["method"], "session/load"); + assert_eq!(request["params"]["sessionId"], "original"); + tokio::time::pause(); + if deadline == SESSION_LOAD_TIMEOUT { + let interval = CLIENT_STARTUP_TIMEOUT / 2; + for _ in 1..deadline.as_secs() / interval.as_secs() { + tokio::time::sleep(interval).await; + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original", + "update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}})).await; + } + tokio::time::sleep(interval + Duration::from_secs(1)).await; + } else { + tokio::time::advance(deadline + Duration::from_secs(1)).await; + } + tokio::time::resume(); + }); + let error = result.unwrap_err(); + assert!(error.to_string().contains(STARTUP_TIMEOUT_ERROR_PREFIX)); + assert!(error + .to_string() + .contains(&format!("{}s", deadline.as_secs()))); + assert_eq!(*old.status.read().await, AcpClientStatus::Stopped); + assert!(!session.service.clients.contains_key(&key)); + } + let mut replacement = session.connect(None).await; + let client = session.service.clients.get(&key).unwrap().clone(); + *client.agent_capabilities.write().await = Some(AgentCapabilities::new().load_session(true)); + let (result, ()) = tokio::join!(get_options(), async { + let request = replacement.request().await; + assert_eq!(request["method"], "session/load"); + assert_eq!(request["params"]["sessionId"], "original"); + for (kind, text) in [ + ("user_message_chunk", "older input"), + ("agent_message_chunk", "older output"), + ] { + replacement.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":{"sessionUpdate":kind,"content":{"type":"text","text":text}}}})).await; + } + replacement.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":{"sessionUpdate":"tool_call","toolCallId":"old-without-title"}}})).await; + replacement.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"review","description":"Review"}]}}})).await; + replacement + .send(json!({"jsonrpc":"2.0","id":request["id"],"result":{}})) + .await; + }); + assert_eq!(result?.available_commands.unwrap()[0].name, "review"); + assert!(session + .storage + .load_visible_session_turns(path, CHAT) + .await? + .is_empty()); + Ok(()) +} + +#[tokio::test] +async fn restarting_during_history_repair_keeps_the_accepted_unsent_input() -> OpenBitFunResult<()> +{ + let mut session = TestSession::new().await?; + session + .save_history( + json!({"provider":"acp","acpHistoryGap":true,"acpRemoteSessionId":"original"}), + ) + .await?; + let path = session.root.path().to_owned(); + let received = session.admit("accepted", "new").await?; + assert!(received.is_some()); + assert!(session.service.clients.is_empty()); + session.restart()?; + session + .service + .recover_stored_dialog_turn(&path, CHAT) + .await?; + assert!(session.admit("accepted", "new").await?.is_none()); + let turns = session + .storage + .load_visible_session_turns(&path, CHAT) + .await?; + assert_eq!(turns.len(), 1); + assert_eq!(turns[0].user_message.content, "new"); + assert_eq!(turns[0].status, TurnStatus::Error); + assert_eq!(turns[0].finish_reason.as_deref(), Some("acp_not_sent")); + assert!(turns[0] + .error + .as_deref() + .unwrap() + .contains("before the ACP prompt was sent")); + assert!(session.service.clients.is_empty()); + + assert!(session.admit("second", "again").await?.is_some()); + let mut agent = session.connect(None).await; + let mut cancelled = false; + let (result, ()) = tokio::join!( + session.stream("second", "again", Some(5), |event| { + cancelled |= matches!(event, AcpClientStreamEvent::Cancelled); + Ok(()) + },), + async { + let request = agent.request().await; + assert_eq!(request["method"], "session/load"); + session + .service + .cancel_agent_session( + "opencode", + Some(path.display().to_string()), + CHAT.into(), + Some("second"), + ) + .await + .unwrap(); + // Same text as the unsent receipt; it belongs to an earlier remote turn. + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"new"}}}})).await; + agent.send(json!({"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"original","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"earlier remote reply"}}}})).await; + agent + .send(json!({"jsonrpc":"2.0","id":request["id"],"result":{}})) + .await; + } + ); + result?; + assert!(cancelled); + let mut terminal = json!({"sessionId": CHAT, "turnId": "second"}); + session + .service + .finish_dialog_turn( + CHAT, + Some(&path), + "agentic://dialog-turn-cancelled", + &mut terminal, + ) + .await?; + let turns = session + .storage + .load_visible_session_turns(&path, CHAT) + .await?; + assert_eq!(turns.len(), 2); + assert_eq!(turns[0].turn_id, "accepted"); + assert_eq!(turns[0].finish_reason.as_deref(), Some("acp_not_sent")); + assert_eq!(turns[1].turn_id, "second"); + assert_eq!(turns[1].status, TurnStatus::Cancelled); + assert_eq!(turns[1].finish_reason.as_deref(), Some("acp_not_sent")); + assert!(session.needs_history().await?); + Ok(()) +} + +#[tokio::test] +async fn a_lagging_turn_count_never_overwrites_a_saved_turn() -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session.save_history(json!({"provider": "acp"})).await?; + let mut saved = + super::super::transcript::start_turn(CHAT, "saved", 2, "opencode", "earlier", None); + saved.status = TurnStatus::Completed; + session.storage.save_dialog_turn(path, &saved).await?; + // The only turn file is at index 2, and the metadata update was lost. + session + .storage + .update_session_metadata_if_present(path, CHAT, |metadata| { + metadata.turn_count = 0; + metadata.message_count = 0; + metadata.last_turn = None; + Ok(()) + }) + .await?; + + let file = session.layout().turn_path(CHAT, 2); + let original = tokio::fs::read(&file).await?; + tokio::fs::write(&file, b"{").await?; + assert!(session.admit("saved", "earlier").await.is_err()); + assert!(!session.layout().turn_path(CHAT, 3).exists()); + tokio::fs::write(&file, original).await?; + assert!(session.admit("saved", "earlier").await?.is_none()); + + let receipt = session.admit("new", "hello").await?.unwrap(); + assert_eq!(receipt["turnIndex"], 3); + let kept = session + .storage + .load_dialog_turn(path, CHAT, 2) + .await? + .unwrap(); + assert_eq!(kept.turn_id, "saved"); + assert_eq!(kept.user_message.content, "earlier"); + let added = session + .storage + .load_dialog_turn(path, CHAT, 3) + .await? + .unwrap(); + assert_eq!(added.turn_id, "new"); + Ok(()) +} + +#[tokio::test] +async fn repeated_prompts_without_output_are_split_by_the_prompts_saved_locally( +) -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_interrupted_prompts(&["continue", "continue"]) + .await?; + let mut agent = session.connect(None).await; + // The agent replays no IDs: the first prompt was never answered. + session + .open_with( + &mut agent, + "session/load", + &[ + ("user_message_chunk", "continue", None), + ("user_message_chunk", "continue", None), + ("agent_message_chunk", "answer", None), + ], + ) + .await?; + let saved = session + .storage + .load_visible_session_turns(path, CHAT) + .await?; + assert_eq!(saved.len(), 2); + assert!(saved[0].model_rounds.is_empty()); + assert_eq!(saved[1].model_rounds[0].text_items[0].content, "answer"); + Ok(()) +} + +#[tokio::test] +async fn adjacent_chunks_without_ids_join_when_a_saved_prompt_has_that_text() -> OpenBitFunResult<()> +{ + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_history( + json!({"provider":"acp","acpRemoteSessionId":"original","acpHistoryGap":true}), + ) + .await?; + let mut known = + super::super::transcript::start_turn(CHAT, "known", 0, "opencode", "earlier", None); + known.status = TurnStatus::Error; + session.storage.save_dialog_turn(path, &known).await?; + // Without a usable saved prompt the legacy visible text still identifies this turn. + let mut split = super::super::transcript::start_turn( + CHAT, + "split", + 1, + "opencode", + "hello again", + Some(json!({"acpPromptText":7})), + ); + split.status = TurnStatus::Error; + session.storage.save_dialog_turn(path, &split).await?; + let mut agent = session.connect(None).await; + session + .open_with( + &mut agent, + "session/load", + &[ + ( + "user_message_chunk", + "earlier", + Some(&known.user_message.id), + ), + ("agent_message_chunk", "first answer", None), + ("user_message_chunk", "hello", None), + ("user_message_chunk", " again", None), + ("agent_message_chunk", "second answer", None), + ], + ) + .await?; + let saved = session + .storage + .load_visible_session_turns(path, CHAT) + .await?; + assert_eq!(saved.len(), 2); + assert_eq!(saved[1].user_message.content, "hello again"); + assert_eq!( + saved[1].model_rounds[0].text_items[0].content, + "second answer" + ); + assert!(!session.needs_history().await?); + Ok(()) +} + +#[tokio::test] +async fn an_unrepairable_gap_is_not_replayed_again_until_local_history_changes( +) -> OpenBitFunResult<()> { + let mut session = TestSession::new().await?; + let path = session.root.path().to_owned(); + session + .save_history(json!({"acpRemoteSessionId":"original","acpHistoryGap":true})) + .await?; + let mut known = + super::super::transcript::start_turn(CHAT, "known", 0, "opencode", "earlier", None); + known.status = TurnStatus::Error; + session.storage.save_dialog_turn(&path, &known).await?; + let known_id = known.user_message.id.clone(); + // Adjacent chunks the local history cannot place leave the gap in place. + let ambiguous = [ + ("user_message_chunk", "earlier", Some(known_id.as_str())), + ("agent_message_chunk", "recovered answer", None), + ("user_message_chunk", "hello", None), + ("user_message_chunk", " again", None), + ]; + let mut agent = session.connect(None).await; + session + .open_with(&mut agent, "session/load", &ambiguous) + .await?; + assert!(session.needs_history().await?); + + // Nothing changed locally: reattach without decoding the history again. + session.restart()?; + let mut agent = session.connect(None).await; + session.open_with(&mut agent, "session/resume", &[]).await?; + assert!(session.needs_history().await?); + + // A new local turn changes the state, so the next restore tries again. + let mut later = + super::super::transcript::start_turn(CHAT, "later", 1, "opencode", "later", None); + later.status = TurnStatus::Completed; + session.storage.save_dialog_turn(&path, &later).await?; + session.restart()?; + let mut agent = session.connect(None).await; + session.open_with(&mut agent, "session/load", &[]).await?; + Ok(()) +} + +#[tokio::test] +async fn an_interrupted_turn_with_an_expanded_prompt_is_repaired_without_message_ids( +) -> OpenBitFunResult<()> { + let mut session = TestSession::new().await?; + let path = session.root.path().to_owned(); + session + .save_history(json!({"acpRemoteSessionId":"original","provider":"acp"})) + .await?; + // The agent receives and replays more than the message the user sees. + session + .admit_with("interrupted", "@file context\nfirst", "first") + .await?; + for (name, mut payload) in [ + ("agentic://model-round-started", json!({"roundIndex":0})), + ("agentic://text-chunk", json!({"text":"partial"})), + ] { + payload["sessionId"] = CHAT.into(); + payload["turnId"] = "interrupted".into(); + payload["roundId"] = "r".into(); + session + .service + .record_dialog_event(name, &mut payload) + .unwrap(); + } + session.restart()?; + session + .service + .recover_stored_dialog_turn(&path, CHAT) + .await?; + assert!(session.needs_history().await?); + + let mut agent = session.connect(None).await; + session + .open_with( + &mut agent, + "session/load", + &[ + ("user_message_chunk", "@file context\nfirst", None), + ("agent_message_chunk", "partial recovered", None), + ], + ) + .await?; + let repaired = session + .storage + .load_dialog_turn(&path, CHAT, 0) + .await? + .unwrap(); + assert_eq!(repaired.user_message.content, "first"); + assert_eq!( + repaired.model_rounds[0].text_items[0].content, + "partial recovered" + ); + assert!(!session.needs_history().await?); + Ok(()) +} + +#[tokio::test] +async fn a_remote_tail_that_repeats_old_prompt_text_keeps_the_gap() -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session + .save_history( + json!({"provider":"acp","acpRemoteSessionId":"original","acpHistoryGap":true}), + ) + .await?; + for (index, text) in ["继续", "检查", "看结果"].into_iter().enumerate() { + let mut turn = super::super::transcript::start_turn( + CHAT, + &format!("turn-{index}"), + index, + "opencode", + text, + None, + ); + turn.status = TurnStatus::Completed; + session.storage.save_dialog_turn(path, &turn).await?; + } + let mut agent = session.connect(None).await; + // The last prompt reuses words of earlier ones. Those words do not show where + // it begins, and no saved prompt stands at that position. + session + .open_with( + &mut agent, + "session/load", + &[ + ("user_message_chunk", "继续", None), + ("agent_message_chunk", "a1", None), + ("user_message_chunk", "检查", None), + ("agent_message_chunk", "a2", None), + ("user_message_chunk", "看结果", None), + ("agent_message_chunk", "a3", None), + ("user_message_chunk", "继续", None), + ("user_message_chunk", "检查", None), + ("agent_message_chunk", "a4", None), + ], + ) + .await?; + let saved = session + .storage + .load_visible_session_turns(path, CHAT) + .await?; + assert_eq!(saved.len(), 3); + assert!(session.needs_history().await?); + Ok(()) +} + +#[tokio::test] +async fn stopping_a_turn_during_agent_startup_settles_before_initialize_returns( +) -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + let path = session.root.path(); + session.save_history(json!({})).await?; + session.admit("turn", "hello").await?; + let mut agent = Harness::new().await; + let key = session_client_connection_id("opencode", CHAT); + let client = test_client_connection(&key); + // The agent process exists but has not answered initialize. + *client.status.write().await = AcpClientStatus::Starting; + session.service.clients.insert(key, client.clone()); + let mut cancelled = false; + let mut worker = Box::pin(session.stream("turn", "hello", None, |event| { + cancelled |= matches!(event, AcpClientStreamEvent::Cancelled); + Ok(()) + })); + assert!(futures::poll!(worker.as_mut()).is_pending()); + session + .service + .cancel_agent_session( + "opencode", + Some(path.display().to_string()), + CHAT.into(), + Some("turn"), + ) + .await?; + tokio::time::timeout(Duration::from_secs(5), worker) + .await + .expect("turn should settle while initialize is outstanding")?; + assert!(cancelled); + *client.connection.write().await = Some(agent.active.connection()); + *client.agent_capabilities.write().await = Some(AgentCapabilities::new()); + *client.status.write().await = AcpClientStatus::Running; + let mut terminal = json!({"sessionId":CHAT,"turnId":"turn"}); + session + .service + .finish_dialog_turn( + CHAT, + Some(path), + "agentic://dialog-turn-cancelled", + &mut terminal, + ) + .await?; + let saved = session + .storage + .load_dialog_turn(path, CHAT, 0) + .await? + .unwrap(); + assert_eq!(saved.finish_reason.as_deref(), Some("acp_not_sent")); + // The stopped prompt was never sent: the agent's first request is the next turn's. + let (reply, next) = tokio::join!(session.prompt("next"), async { + agent + .reply("session/new", json!({"result":{"sessionId":"original"}})) + .await; + agent.finish_with_text("ok", "end_turn").await + }); + assert_eq!(next["prompt"][0]["text"], "next"); + assert_eq!(reply?, "ok"); + Ok(()) +} + +#[tokio::test] +async fn a_replay_with_a_missing_head_never_places_a_reply_by_repeated_text() -> OpenBitFunResult<()> +{ + let user = "user_message_chunk"; + let agent = "agent_message_chunk"; + for (local, replay, replies) in [ + // Five turns can place AB either before reply-2 or before reply-3. + ( + &["AB", "A", "B"][..], + &[ + (user, "A"), + (user, "B"), + (agent, "reply-2"), + (user, "A"), + (user, "B"), + (agent, "reply-3"), + (user, "A"), + (agent, "reply-4"), + (user, "B"), + (agent, "reply-5"), + ][..], + &[None, None, None][..], + ), + // The local B can be the first B, or the B following an unanswered A. + ( + &["B", "AB"], + &[ + (user, "B"), + (agent, "reply-1"), + (user, "A"), + (user, "B"), + (agent, "reply-2"), + (user, "AB"), + (agent, "reply-3"), + ], + &[None, None], + ), + // The agent stopped replaying just after the newer B. Its AB may follow on retry. + ( + &["B", "AB"], + &[ + (user, "B"), + (agent, "older B"), + (user, "AB"), + (agent, "older AB"), + (user, "B"), + (agent, "newer B"), + ], + &[None, None], + ), + // Replacing the first B leaves just the placement inside the second run. + ( + &["B", "AB"], + &[ + (user, "older"), + (agent, "reply-1"), + (user, "A"), + (user, "B"), + (agent, "reply-2"), + (user, "AB"), + (agent, "reply-3"), + ], + &[Some("reply-2"), Some("reply-3")], + ), + // A saved prompt can also start at a later run and span both chunks. + ( + &["ab"], + &[ + (user, "older"), + (agent, "reply-1"), + (user, "a"), + (user, "b"), + (agent, "reply-2"), + ], + &[Some("reply-2")], + ), + ] { + let session = TestSession::new().await?; + session.save_interrupted_prompts(local).await?; + let mut peer = session.connect(None).await; + let replay: Vec<_> = replay + .iter() + .map(|&(kind, text)| (kind, text, None)) + .collect(); + session + .open_with(&mut peer, "session/load", &replay) + .await?; + let saved = session + .storage + .load_visible_session_turns(session.root.path(), CHAT) + .await?; + assert_eq!(saved.len(), local.len()); + for ((turn, &prompt), &reply) in saved.iter().zip(local).zip(replies) { + assert_eq!(turn.user_message.content, prompt); + let contents: Vec<_> = turn + .model_rounds + .iter() + .flat_map(|round| &round.text_items) + .map(|item| item.content.as_str()) + .collect(); + assert_eq!(contents.as_slice(), reply.as_slice()); + } + assert!(session.needs_history().await?); + } + Ok(()) +} + +#[tokio::test] +async fn incomplete_replay_is_retried_after_restart() -> OpenBitFunResult<()> { + let user = "user_message_chunk"; + let agent = "agent_message_chunk"; + for (local, replay, first_len, replies, missing_head) in [ + // The agent has not replayed any history yet. + ( + &["earlier"][..], + &[(user, "earlier", None), (agent, "finished answer", None)][..], + 0, + &["finished answer"][..], + false, + ), + // The replay stops inside the first saved prompt. + ( + &["abc"], + &[ + (user, "a", None), + (user, "b", None), + (user, "c", None), + (agent, "answer", None), + ], + 2, + &["answer"], + false, + ), + // The replay stops exactly at the end of the first of two saved prompts. + ( + &["ab", "cd"], + &[ + (user, "a", None), + (user, "b", None), + (agent, "first answer", None), + (user, "c", None), + (user, "d", None), + (agent, "second answer", None), + ], + 2, + &["first answer", "second answer"], + false, + ), + // An earlier B/AB looks complete until the latest AB identifies its own turn. + ( + &["B", "AB"], + &[ + (user, "B", None), + (agent, "older B", None), + (user, "A", None), + (user, "B", None), + (agent, "older AB", None), + (user, "B", None), + (agent, "newer B", None), + (user, "AB", Some("message-1")), + (agent, "newer AB", None), + ], + 7, + &["newer B", "newer AB"], + true, + ), + ] { + let mut session = TestSession::new().await?; + session.save_interrupted_prompts(local).await?; + let mut peer = session.connect(None).await; + session + .open_with(&mut peer, "session/load", &replay[..first_len]) + .await?; + assert!(session.needs_history().await?); + let saved = session + .storage + .load_visible_session_turns(session.root.path(), CHAT) + .await?; + assert_eq!(saved.len(), local.len()); + assert!(saved.iter().all(|turn| turn.model_rounds.is_empty())); + + session.restart()?; + let mut peer = session.connect(None).await; + session.open_with(&mut peer, "session/load", replay).await?; + let saved = session + .storage + .load_visible_session_turns(session.root.path(), CHAT) + .await?; + assert_eq!(saved.len(), local.len()); + for ((turn, &prompt), &reply) in saved.iter().zip(local).zip(replies) { + assert_eq!(turn.user_message.content, prompt); + assert_eq!(turn.model_rounds[0].text_items[0].content, reply); + } + assert_eq!(session.needs_history().await?, missing_head); + } + Ok(()) +} + +#[tokio::test] +async fn retrying_any_saved_turn_among_many_does_not_create_another() -> OpenBitFunResult<()> { + let mut session = TestSession::new().await?; + session.save_history(json!({"provider": "acp"})).await?; + for index in 0..9 { + let mut turn = super::super::transcript::start_turn( + CHAT, + &format!("turn-{index}"), + index, + "opencode", + "hello", + None, + ); + turn.status = TurnStatus::Completed; + session + .storage + .save_dialog_turn(session.root.path(), &turn) + .await?; + } + // Restart with all nine catalog entries missing their turn IDs, then retry the oldest. + tokio::fs::remove_file(session.layout().turn_catalog_path(CHAT)).await?; + session.restart()?; + let file = session.layout().turn_path(CHAT, 0); + let original = tokio::fs::read(&file).await?; + tokio::fs::write(&file, b"{").await?; + assert!(session.admit("turn-0", "hello").await.is_err()); + assert!(!session.layout().turn_path(CHAT, 9).exists()); + tokio::fs::write(&file, original).await?; + assert!(session.admit("turn-0", "hello").await?.is_none()); + assert!(session + .storage + .load_dialog_turn(session.root.path(), CHAT, 9) + .await? + .is_none()); + Ok(()) +} + +#[tokio::test] +async fn retrying_legacy_in_progress_turn_keeps_saved_output() -> OpenBitFunResult<()> { + let mut session = TestSession::new().await?; + session.save_history(json!({"provider":"acp"})).await?; + let mut turn = super::super::transcript::start_turn(CHAT, "turn", 0, "opencode", "hello", None); + super::super::transcript::start_round(&mut turn, "round", 0, 1); + super::super::transcript::append_text(&mut turn.model_rounds[0], "partial", false, 2); + session + .storage + .save_dialog_turn(session.root.path(), &turn) + .await?; + + session.restart()?; + assert!(session.admit("turn", "hello").await?.is_none()); + + let saved = session + .storage + .load_dialog_turn(session.root.path(), CHAT, 0) + .await? + .unwrap(); + assert_eq!(saved.model_rounds[0].text_items[0].content, "partial"); + assert_ne!(saved.status, TurnStatus::InProgress); + Ok(()) +} + +#[tokio::test] +async fn releasing_before_or_during_worker_startup_never_sends_the_admitted_prompt( +) -> OpenBitFunResult<()> { + for worker_started in [false, true] { + let session = TestSession::new().await?; + session.save_history(json!({})).await?; + assert!(session.admit("turn", "hello").await?.is_some()); + let mut agent = Harness::new().await; + let connection = agent.active.connection(); + let key = session_client_connection_id("opencode", CHAT); + let client = test_client_connection(&key); + *client.status.write().await = AcpClientStatus::Starting; + session.service.clients.insert(key, client.clone()); + let mut cancelled = false; + let mut worker = Box::pin(session.stream("turn", "hello", None, |event| { + cancelled |= matches!(event, AcpClientStreamEvent::Cancelled); + Ok(()) + })); + if worker_started { + // The worker subscribed to this turn, but the agent has not initialized. + assert!(futures::poll!(worker.as_mut()).is_pending()); + } + session.service.release_openbitfun_session(CHAT).await; + *client.connection.write().await = Some(connection.clone()); + *client.agent_capabilities.write().await = Some(AgentCapabilities::new()); + *client.status.write().await = AcpClientStatus::Running; + + tokio::time::timeout(Duration::from_secs(5), worker) + .await + .expect("released turn should settle")?; + assert!(cancelled); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if client.sessions.is_empty() && client.cancel_handles.is_empty() { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("released startup should not leave ACP session handles"); + assert!( + tokio::time::timeout(Duration::from_millis(50), agent.request()) + .await + .is_err() + ); + } + Ok(()) +} + +#[tokio::test] +async fn releasing_while_the_admitted_turn_loads_never_sends_its_prompt() -> OpenBitFunResult<()> { + let session = TestSession::new().await?; + session + .save_history(json!({"acpRemoteSessionId":"original","acpRestoreRequired":true})) + .await?; + assert!(session.admit("turn", "hello").await?.is_some()); + let mut agent = session.connect(None).await; + let mut cancelled = false; + let mut worker = Box::pin(session.stream("turn", "hello", None, |event| { + cancelled |= matches!(event, AcpClientStreamEvent::Cancelled); + Ok(()) + })); + let load = tokio::select! { + request = agent.request() => request, + result = &mut worker => panic!("turn settled before session/load: {result:?}"), + }; + assert_eq!(load["method"], "session/load"); + assert_eq!(load["params"]["sessionId"], "original"); + let release = session.service.release_openbitfun_session(CHAT); + tokio::pin!(release); + // The pending send must settle even while release is blocked on the load. + assert!(futures::poll!(&mut release).is_pending()); + tokio::time::timeout(Duration::from_secs(5), worker) + .await + .expect("release should cancel the turn before the agent answers session/load")?; + assert!(cancelled); + agent + .send(json!({"jsonrpc":"2.0","id":load["id"],"result":{}})) + .await; + assert!(release.await); + let request = agent.request().await; + assert_eq!(request["method"], "session/cancel", "{request}"); + assert_eq!(request["params"]["sessionId"], "original"); + agent + .active + .connection() + .send_notification(CancelNotification::new("wire-fence")) + .unwrap(); + let next = agent.request().await; + assert_eq!(next["method"], "session/cancel", "{next}"); + assert_eq!(next["params"]["sessionId"], "wire-fence"); + Ok(()) +} diff --git a/src/crates/interfaces/acp/src/client/manager/replay.rs b/src/crates/interfaces/acp/src/client/manager/replay.rs new file mode 100644 index 0000000000..024071d69e --- /dev/null +++ b/src/crates/interfaces/acp/src/client/manager/replay.rs @@ -0,0 +1,640 @@ +//! A load response fences the history the agent sent before it. Register the +//! session receiver first and consume that history independently of live prompts. +use std::collections::HashMap; +use std::ops::Range; +use std::path::Path; + +use agent_client_protocol::schema::{LoadSessionRequest, LoadSessionResponse}; +use agent_client_protocol::{ActiveSession, Agent, ConnectionTo, Dispatch, Error, SessionMessage}; +use futures::FutureExt; +use openbitfun_core::service::session::{DialogTurnData, ModelRoundData, TurnStatus}; +use openbitfun_core::util::errors::OpenBitFunResult; + +use super::super::session_persistence::{ + AcpSessionPersistence, PENDING_TURN_KEY, UNSENT_FINISH_REASON, +}; +use super::super::stream::{ + decode_session_update, AcpClientStreamEvent, AcpStreamRoundTracker, AcpToolCallTracker, +}; +use super::super::transcript; +use super::CLIENT_STARTUP_TIMEOUT; + +#[derive(Default)] +pub(super) struct History { + turns: Vec, + message_ids: Vec>, + /// Byte ranges in the original user text. Without message IDs, adjacent + /// chunks can belong to one prompt or to several unanswered prompts. + runs: Vec>>, + /// The replay was requested to repair a known history gap. + repair: bool, + pub(super) metadata: Vec, + rounds: AcpStreamRoundTracker, + tools: AcpToolCallTracker, +} + +pub(super) async fn load( + service: &super::AcpClientService, + client: &std::sync::Arc, + connection: &ConnectionTo, + remote_id: &str, + cwd: &Path, + active: &mut ActiveSession<'_, Agent>, + session_id: &str, + repair_history: bool, +) -> Result<(LoadSessionResponse, History), Error> { + let response = connection + .send_request(LoadSessionRequest::new(remote_id.to_owned(), cwd)) + .block_task(); + tokio::pin!(response); + let mut history = History { + repair: repair_history, + ..History::default() + }; + let mut finished = None; + loop { + let update = if finished.is_some() { + // The router has received the response. Earlier notifications can + // already be in this session's queue when both futures were ready. + let Some(Ok(update)) = active.read_update().now_or_never() else { + break; + }; + update + } else { + tokio::select! { + biased; + result = &mut response => { finished = Some(result?); continue; } + _ = tokio::time::sleep(CLIENT_STARTUP_TIMEOUT) => { + return Err(service.retire_timed_out_connection(client, "session/load", CLIENT_STARTUP_TIMEOUT).await); + } + update = active.read_update() => update?, + } + }; + if let SessionMessage::SessionMessage(dispatch) = update { + // A load-only agent must replay even for a metadata read. Drain its + // history without decoding messages or tool payloads the host already has. + if !repair_history { + let Dispatch::Notification(message) = &dispatch else { + continue; + }; + if !matches!( + message + .params + .pointer("/update/sessionUpdate") + .and_then(|v| v.as_str()), + Some("available_commands_update" | "config_option_update" | "usage_update") + ) { + continue; + } + } + let (user, events) = decode_session_update(dispatch, &mut history.tools) + .await + .map_err(|error| agent_client_protocol::util::internal_error(error.to_string()))?; + if let Some((id, text)) = user { + history.user_chunk(session_id, &client.client_id, id, text.as_deref()); + } + for event in events { + history.push(event); + } + } + } + Ok(( + finished.expect("history is fenced by the load response"), + history, + )) +} + +impl History { + fn user_chunk(&mut self, session: &str, client: &str, id: Option, text: Option<&str>) { + let previous = self.message_ids.last(); + let same = id.is_some() && previous == Some(&id); + let adjacent = id.is_none() + && previous == Some(&None) + && self.turns.last().is_some_and(|t| t.model_rounds.is_empty()); + if same || adjacent { + if let (Some(turn), Some(run), Some(text)) = + (self.turns.last_mut(), self.runs.last_mut(), text) + { + let content = &mut turn.user_message.content; + let start = content.len(); + content.push_str(text); + if same { + // An explicit message ID fixes the boundary of the whole prompt. + run[0].end = content.len(); + } else { + run.push(start..content.len()); + } + } + return; + } + let turn_id = uuid::Uuid::new_v4().to_string(); + let mut turn = transcript::start_turn( + session, + &turn_id, + self.turns.len(), + client, + text.unwrap_or_default(), + None, + ); + if let Some(id) = &id { + turn.user_message.id.clone_from(id); + } + self.message_ids.push(id); + self.runs + .push(std::iter::once(0..turn.user_message.content.len()).collect()); + self.turns.push(turn); + self.tools = AcpToolCallTracker::default(); + self.rounds = AcpStreamRoundTracker::default(); + } + + fn push(&mut self, event: AcpClientStreamEvent) { + if matches!( + event, + AcpClientStreamEvent::ConfigOptionsUpdated(_) + | AcpClientStreamEvent::AvailableCommandsUpdated(_) + | AcpClientStreamEvent::ContextUsageUpdated(_) + ) { + self.metadata + .retain(|old| std::mem::discriminant(old) != std::mem::discriminant(&event)); + self.metadata.push(event); + return; + } + let Some(turn) = self.turns.last_mut() else { + return; + }; + let time = turn.timestamp; + for event in self.rounds.apply(event) { + match event { + AcpClientStreamEvent::ModelRoundStarted { + round_id, + round_index, + .. + } => { + transcript::start_round(turn, &round_id, round_index, time); + } + AcpClientStreamEvent::AgentText(text) => { + if let Some(round) = turn.model_rounds.last_mut() { + transcript::append_text(round, &text, false, time); + } + } + AcpClientStreamEvent::AgentThought(text) => { + if let Some(round) = turn.model_rounds.last_mut() { + transcript::append_text(round, &text, true, time); + } + } + AcpClientStreamEvent::ToolEvent(event) => { + if let Some(round) = turn.model_rounds.last_mut() { + transcript::update_tool(round, &event, time); + } + } + _ => {} + } + } + } + + /// Local history can start at any chunk boundary in an unidentified run. + /// Keep only the first complete placement. A second one already proves + /// that position cannot identify the replies. + fn unique_placement( + &self, + saved: &[&DialogTurnData], + id_matches: &impl Fn(&DialogTurnData, usize) -> bool, + ) -> Result<(usize, usize), Outcome> { + if saved.is_empty() { + return Err(Outcome::Ambiguous); + } + let open_end = self + .turns + .last() + .is_some_and(|last| last.model_rounds.is_empty()); + let mut first = None; + let mut incomplete = false; + for (run, chunks) in self.runs.iter().enumerate() { + for offset in 0..chunks.len() { + match self.match_from((run, offset), saved, id_matches, |_, _, _| {}) { + Alignment::Complete { .. } if first.is_some() => { + return Err(if open_end { + Outcome::Retry + } else { + Outcome::Ambiguous + }); + } + Alignment::Complete { at_replay_end } => { + first = Some(((run, offset), at_replay_end)); + } + Alignment::Incomplete => incomplete = true, + Alignment::Mismatch => {} + } + } + } + match first { + // A later, unfinished placement can still own the saved prompts if + // the complete match leaves part of this replay unexplained. + Some((_, at_end)) if incomplete && (open_end || !at_end) => Err(Outcome::Retry), + Some((position, _)) => Ok(position), + None if incomplete => Err(Outcome::Retry), + None => Err(Outcome::Ambiguous), + } + } + + /// Walk the saved prompts without allocating per candidate. Only the last + /// prompt in a fully consumed run can own the reply that follows it. + fn match_from( + &self, + (start, offset): (usize, usize), + saved: &[&DialogTurnData], + id_matches: &impl Fn(&DialogTurnData, usize) -> bool, + mut matched: impl FnMut(usize, Range, bool), + ) -> Alignment { + let mut next = 0; + for index in start..self.runs.len() { + let run = &self.runs[index]; + let replayed = &self.turns[index].user_message.content; + let from = if index == start { offset } else { 0 }; + let first = next; + let mut used = 0; + let mut at_boundary = false; + for (i, range) in run.iter().enumerate().skip(from) { + let chunk = &replayed[range.clone()]; + let prompt = transcript::prompt_text(saved[next]); + if !id_matches(saved[next], index) + || (prompt.is_empty() && run.len() > 1) + || !prompt[used..].starts_with(chunk) + { + return Alignment::Mismatch; + } + used += chunk.len(); + at_boundary = used == prompt.len(); + if at_boundary { + next += 1; + used = 0; + if next == saved.len() { + matched(index, first..next, i + 1 == run.len()); + return Alignment::Complete { + at_replay_end: index + 1 == self.runs.len() && i + 1 == run.len(), + }; + } + } + } + if !at_boundary { + // A reply or a new run closes the previous prompt boundary. + return if index + 1 == self.runs.len() && self.turns[index].model_rounds.is_empty() + { + Alignment::Incomplete + } else { + Alignment::Mismatch + }; + } + matched(index, first..next, true); + } + // The replay ended exactly between two saved prompts. + Alignment::Incomplete + } + + pub(super) async fn reconcile( + self, + store: &AcpSessionPersistence, + path: &Path, + session: &str, + ) -> OpenBitFunResult<()> { + let outcome = self.attempt(store, path, session).await?; + // Only a boundary the agent's history cannot settle is remembered. An + // empty, short or still-growing replay can succeed on a later attempt. + if self.repair && outcome == Outcome::Ambiguous { + store.record_repair_attempt(path, session).await?; + } + Ok(()) + } + + async fn attempt( + &self, + store: &AcpSessionPersistence, + path: &Path, + session: &str, + ) -> OpenBitFunResult { + if self.turns.is_empty() { + return Ok(Outcome::Retry); + } + let Some(record) = store.manager.load_session_metadata(path, session).await? else { + return Ok(Outcome::Repaired); + }; + if !AcpSessionPersistence::has_history_gap(&record) { + return Ok(Outcome::Repaired); + } + let custom = record.custom_metadata.as_ref(); + let first_owned = custom.and_then(|v| v.get("acpRuntimeFromTurn")?.as_u64()); + let pending_id = custom.and_then(|v| v.get(PENDING_TURN_KEY)?.get("turnId")?.as_str()); + let mut local = store + .manager + .load_visible_session_turns(path, session) + .await?; + // An older view can have checkpointed the incoming optimistic turn. + // Its admission is already durable and the agent has not seen it yet. + if local + .last() + .is_some_and(|turn| Some(turn.turn_id.as_str()) == pending_id) + { + local.pop(); + } + let locals: Vec<_> = local + .iter() + .filter(|t| { + t.kind == openbitfun_core::service::session::DialogTurnKind::UserDialog + && t.finish_reason.as_deref() != Some(UNSENT_FINISH_REASON) + }) + .collect(); + // An unsent local turn has no position in the agent's history. Appending a remote + // suffix after that receipt would invent an order, and reusing its index would overwrite it. + let trailing_unsent = local + .iter() + .rev() + .find(|t| t.kind == openbitfun_core::service::session::DialogTurnKind::UserDialog) + .is_some_and(|t| t.finish_reason.as_deref() == Some(UNSENT_FINISH_REASON)); + let replay_index_by_id: HashMap<_, _> = self + .message_ids + .iter() + .enumerate() + .filter_map(|(index, id)| Some((id.as_deref()?, index))) + .collect(); + let id_matches = |local: &DialogTurnData, index: usize| match replay_index_by_id + .get(local.user_message.id.as_str()) + { + Some(&identified) => identified == index, + None => { + self.message_ids[index].is_none() + || !first_owned.is_some_and(|first| local.turn_index as u64 >= first) + } + }; + let mut by_position = vec![None; self.turns.len()]; + let mut append_from = None; + let mut matched = 0; + let mut complete = true; + let mut unresolved = Outcome::Retry; + if self.runs.iter().any(|run| run.len() > 1) { + match self.unique_placement(&locals, &id_matches) { + Ok(start) => { + complete = start == (0, 0); + let mut end = start.0; + let mut ends_run = false; + self.match_from(start, &locals, &id_matches, |index, group, at_end| { + end = index + 1; + ends_run = at_end; + let unanswered = group.start..group.end - usize::from(at_end); + matched += unanswered.len(); + complete &= locals[unanswered] + .iter() + .all(|t| t.status == TurnStatus::Completed); + if at_end { + by_position[index] = Some(group.end - 1); + } + }); + if ends_run && self.runs[end..].iter().all(|run| run.len() == 1) { + append_from = Some(end); + } else { + // There is no saved prompt to decide the remaining chunk boundaries. + complete = false; + unresolved = Outcome::Ambiguous; + } + } + Err(outcome) => { + if replay_index_by_id.is_empty() { + return Ok(outcome); + } + // Explicit message IDs can still repair their own turns. + complete = false; + unresolved = outcome; + } + } + } else { + let same_prompt = |local: &DialogTurnData, index: usize| { + transcript::prompt_text(local) == self.turns[index].user_message.content + && id_matches(local, index) + }; + let aligned = self.turns.len() >= locals.len() + && locals + .iter() + .enumerate() + .all(|(i, turn)| same_prompt(turn, i)); + let repeated_tail = aligned + && locals.last().is_some_and(|last| { + (locals.len()..self.turns.len()).any(|i| same_prompt(last, i)) + }); + // A later copy of the local prefix may be the part still being + // replayed. It can start at most one local history's length back. + let last = self.turns.len() - 1; + let partial_tail = aligned + && !locals.is_empty() + && self.turns.len() > locals.len() + && (self.turns.len() - locals.len()..self.turns.len()) + .rev() + .any(|start| { + (self.turns[last].model_rounds.is_empty() + || same_prompt(locals[last - start], last)) + && matches!( + self.match_from((start, 0), &locals, &id_matches, |_, _, _| {}), + Alignment::Incomplete + ) + }); + if partial_tail { + complete = false; + } else if aligned && !repeated_tail { + for (i, owner) in by_position[..locals.len()].iter_mut().enumerate() { + *owner = Some(i); + } + append_from = Some(locals.len()); + } else { + if repeated_tail { + unresolved = Outcome::Ambiguous; + } + // Outside an aligned prefix, use only text unique on both sides. + let mut unique_text = HashMap::new(); + for (i, remote) in self.turns.iter().enumerate() { + let text = remote.user_message.content.as_str(); + if !text.is_empty() { + unique_text + .entry(text) + .and_modify(|index| *index = None) + .or_insert(Some(i)); + } + } + let mut by_text = HashMap::new(); + for (i, local) in locals.iter().enumerate() { + if let Some(&Some(remote)) = unique_text.get(transcript::prompt_text(local)) { + if same_prompt(local, remote) { + by_text + .entry(remote) + .and_modify(|index| *index = None) + .or_insert(Some(i)); + } + } + } + for (remote, owner) in by_text { + by_position[remote] = owner; + } + } + } + let mut local_by_id = HashMap::new(); + for (i, turn) in locals.iter().enumerate() { + local_by_id + .entry(turn.user_message.id.as_str()) + .or_insert(i); + } + // The visible catalog can end before turn files that a lagging metadata + // count does not list yet. Import after every stored file. + let mut next_index = store + .next_free_index(path, session, local.last().map_or(0, |t| t.turn_index + 1)) + .await?; + let mut last_local = None; + let mut written = false; + for (ordinal, (remote, id)) in self.turns.iter().zip(&self.message_ids).enumerate() { + let found = id + .as_ref() + .and_then(|id| local_by_id.get(id.as_str()).copied()) + .or(by_position[ordinal]); + if let Some(i) = found { + if last_local.is_some_and(|last| i <= last) { + complete = false; + continue; + } + last_local = Some(i); + matched += 1; + let previous = locals[i]; + if previous.status == TurnStatus::InProgress { + complete = false; + continue; + } + if previous.status == TurnStatus::Completed { + continue; + } + let mut repaired = previous.clone(); + if !merge_rounds(&mut repaired, &remote.model_rounds) { + complete = false; + continue; + } + if remote.model_rounds.is_empty() { + complete = false; + continue; + } + if serde_json::to_value(&repaired)? != serde_json::to_value(previous)? { + store.manager.save_dialog_turn(path, &repaired).await?; + written = true; + } + } else if append_from.is_some_and(|start| ordinal >= start) + && !trailing_unsent + && matched == locals.len() + { + let mut imported = remote.clone(); + imported.turn_index = next_index; + // ACP v1 replays items, not the previous prompt response. Retain + // that distinction even when the replay contains assistant text. + imported.status = TurnStatus::Error; + imported.finish_reason = Some("acp_outcome_unknown".into()); + imported.error = + Some("ACP history was restored without a confirmed turn outcome.".into()); + for round in &mut imported.model_rounds { + round.status = "completed".into(); + } + store.manager.save_dialog_turn(path, &imported).await?; + next_index += 1; + written = true; + } else { + complete = false; + } + } + if complete && matched == locals.len() { + store.history_repaired(path, session).await?; + return Ok(Outcome::Repaired); + } + if written || !complete { + log::info!("Preserved local ACP history after partial replay: session_id={session}"); + } + Ok(unresolved) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Outcome { + /// No gap remains. + Repaired, + /// Prompt boundaries cannot be told apart from the replay and the saved prompts. + Ambiguous, + /// Anything else may resolve once the agent's history is complete. + Retry, +} + +enum Alignment { + Complete { at_replay_end: bool }, + Incomplete, + Mismatch, +} + +/// Apply only additions supported by the replay. Conflicting or shorter +/// history leaves the original record intact, including item IDs and timing. +pub(super) fn merge_rounds(turn: &mut DialogTurnData, incoming: &[ModelRoundData]) -> bool { + if incoming.len() < turn.model_rounds.len() { + return false; + } + for (index, fresh) in incoming.iter().enumerate() { + let Some(old) = turn.model_rounds.get_mut(index) else { + let mut round = fresh.clone(); + round.turn_id.clone_from(&turn.turn_id); + round.status = "completed".into(); + turn.model_rounds.push(round); + continue; + }; + if old.text_items.len() > fresh.text_items.len() + || old.thinking_items.len() > fresh.thinking_items.len() + { + return false; + } + for (item, next) in old.text_items.iter_mut().zip(&fresh.text_items) { + if !next.content.starts_with(&item.content) + || item + .order_index + .zip(next.order_index) + .is_some_and(|(a, b)| a != b) + { + return false; + } + item.content.clone_from(&next.content); + } + for (item, next) in old.thinking_items.iter_mut().zip(&fresh.thinking_items) { + if !next.content.starts_with(&item.content) + || item + .order_index + .zip(next.order_index) + .is_some_and(|(a, b)| a != b) + { + return false; + } + item.content.clone_from(&next.content); + } + for item in &mut old.tool_items { + let Some(next) = fresh + .tool_items + .iter() + .find(|v| v.tool_call.id == item.tool_call.id) + else { + return false; + }; + if item.tool_result.is_none() && next.tool_result.is_some() { + item.tool_result.clone_from(&next.tool_result); + item.status.clone_from(&next.status); + } + } + old.text_items + .extend_from_slice(&fresh.text_items[old.text_items.len()..]); + old.thinking_items + .extend_from_slice(&fresh.thinking_items[old.thinking_items.len()..]); + for tool in &fresh.tool_items { + if !old + .tool_items + .iter() + .any(|t| t.tool_call.id == tool.tool_call.id) + { + old.tool_items.push(tool.clone()); + } + } + } + true +} diff --git a/src/crates/interfaces/acp/src/client/mod.rs b/src/crates/interfaces/acp/src/client/mod.rs index 8b6124bbbc..0f453eec39 100644 --- a/src/crates/interfaces/acp/src/client/mod.rs +++ b/src/crates/interfaces/acp/src/client/mod.rs @@ -13,6 +13,7 @@ mod session_persistence; mod stream; mod tool; mod tool_card_bridge; +mod transcript; mod transport; pub use config::{ diff --git a/src/crates/interfaces/acp/src/client/prompt.rs b/src/crates/interfaces/acp/src/client/prompt.rs index 45bc2667d6..6d9c314a15 100644 --- a/src/crates/interfaces/acp/src/client/prompt.rs +++ b/src/crates/interfaces/acp/src/client/prompt.rs @@ -1,42 +1,139 @@ use std::future::Future; use std::pin::Pin; +use std::time::Duration; -use agent_client_protocol::schema::{PromptRequest, PromptResponse}; -use agent_client_protocol::{ActiveSession, Agent, Error, SessionMessage}; +use agent_client_protocol::schema::{CancelNotification, PromptRequest, PromptResponse}; +use agent_client_protocol::{ActiveSession, Agent, ConnectionTo, Error, SessionMessage}; +use futures::FutureExt; +use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; +use serde_json::Value; +use tokio::sync::watch; + +use super::manager::protocol_error; + +const PROMPT_CANCEL_GRACE: Duration = Duration::from_secs(5); + +#[derive(Clone)] +pub(super) struct AcpCancelHandle { + pub(super) session_id: String, + pub(super) connection: ConnectionTo, + stop_requested: watch::Sender<()>, +} + +impl AcpCancelHandle { + pub(super) fn new( + active: &ActiveSession<'_, Agent>, + stop_requested: watch::Sender<()>, + ) -> Self { + Self { + session_id: active.session_id().to_string(), + connection: active.connection(), + stop_requested, + } + } + + pub(super) fn cancel(&self) -> OpenBitFunResult<()> { + let sent = self + .connection + .send_notification(CancelNotification::new(self.session_id.clone())); + // The prompt owns recovery even if writing the notification failed. + if self.stop_requested.send(()).is_err() { + sent.map_err(protocol_error)?; + } + Ok(()) + } +} + +#[derive(Debug)] +pub(super) enum PromptError { + Protocol(Error), + OutcomeUnknown(&'static str), +} + +impl From for OpenBitFunError { + fn from(error: PromptError) -> Self { + match error { + PromptError::Protocol(error) => protocol_error(error), + PromptError::OutcomeUnknown(reason) => Self::OutcomeUnknown(reason.into()), + } + } +} /// Own the prompt response separately from the session notification queue. /// ACP 0.12's ActiveSession::send_prompt only queues successful stop reasons; /// its error callback terminates the connection without waking read_update. pub(super) struct AcpPrompt { response: Pin> + Send>>, + cancel_deadline: Pin + Send>>, + deadline: Option, } impl AcpPrompt { - pub(super) fn start(active: &ActiveSession<'_, Agent>, prompt: String) -> Self { - let request = PromptRequest::new(active.session_id().clone(), vec![prompt.into()]); + pub(super) fn start( + active: &ActiveSession<'_, Agent>, + prompt: String, + message_id: Option, + deadline: Option, + mut stop_requested: watch::Receiver<()>, + ) -> Self { + let mut request = PromptRequest::new(active.session_id().clone(), vec![prompt.into()]); + request.message_id = message_id; let response = active.connection().send_request(request).block_task(); Self { + deadline, response: Box::pin(response), + cancel_deadline: Box::pin(async move { + if stop_requested.changed().await.is_ok() { + tokio::time::sleep(PROMPT_CANCEL_GRACE).await; + } else { + std::future::pending::<()>().await; + } + }), } } pub(super) async fn read_update( &mut self, active: &mut ActiveSession<'_, Agent>, - ) -> Result { - tokio::select! { - // Preserve notifications queued before the response, including any - // partial output preceding an error. The response also wakes us - // when the connection drops its pending request sender. + ) -> Result { + let timeout = async { + if let Some(deadline) = self.deadline { + tokio::time::sleep_until(deadline).await; + } else { + std::future::pending::<()>().await; + } + }; + let response = tokio::select! { biased; - update = active.read_update() => update, - response = &mut self.response => { - response.map(|response| SessionMessage::StopReason(response.stop_reason)) + () = &mut self.cancel_deadline => { + // Prefer a real terminal result if it arrived at the deadline. + self.response.as_mut().now_or_never().ok_or_else(|| PromptError::OutcomeUnknown( + "The ACP agent did not confirm the stop. Check the previous turn's work before sending it again." + ))? } - } + // Deliver queued partial output before the terminal response. + update = active.read_update() => match update { + Ok(update) => return Ok(update), + Err(_) => self.response.as_mut().now_or_never().ok_or_else(|| PromptError::OutcomeUnknown( + "The ACP connection closed before the agent confirmed the turn outcome." + ))?, + }, + response = &mut self.response => response, + () = timeout => return Err(PromptError::OutcomeUnknown( + "The ACP prompt timed out before the agent confirmed the turn outcome." + )), + }.map_err(|error| { + // The SDK distinguishes a dropped response channel from an agent's JSON-RPC error. + if error.data.as_ref().and_then(Value::as_str).is_some_and(|detail| detail.starts_with("response to `session/prompt` never received:")) { + PromptError::OutcomeUnknown("The ACP connection closed before the agent confirmed the turn outcome.") + } else { + PromptError::Protocol(error) + } + })?; + Ok(SessionMessage::StopReason(response.stop_reason)) } } #[cfg(test)] #[path = "prompt/tests.rs"] -mod tests; +pub(super) mod tests; diff --git a/src/crates/interfaces/acp/src/client/prompt/tests.rs b/src/crates/interfaces/acp/src/client/prompt/tests.rs index 559b4e2748..c8af4d3c2a 100644 --- a/src/crates/interfaces/acp/src/client/prompt/tests.rs +++ b/src/crates/interfaces/acp/src/client/prompt/tests.rs @@ -4,24 +4,25 @@ use agent_client_protocol::schema::{CancelNotification, NewSessionResponse, Stop use agent_client_protocol::{ActiveSession, Agent, ByteStreams, Client, Error, SessionMessage}; use serde_json::{json, Value}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, ReadHalf, WriteHalf}; -use tokio::sync::oneshot; +use tokio::sync::{oneshot, watch}; use tokio::task::JoinHandle; use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt}; use super::super::transport::{handle_transport_closed, AcpTransport}; -use super::AcpPrompt; +use super::{AcpPrompt, PromptError}; const DEADLINE: Duration = Duration::from_secs(2); -struct Harness { - active: ActiveSession<'static, Agent>, +pub(in crate::client) struct Harness { + stop_requested: watch::Sender<()>, + pub(in crate::client) active: ActiveSession<'static, Agent>, reader: BufReader>, writer: WriteHalf, connection_task: JoinHandle>, } impl Harness { - async fn new() -> Self { + pub(in crate::client) async fn new() -> Self { let (client, agent) = tokio::io::duplex(16 * 1024); let (client_reader, client_writer) = tokio::io::split(client); let (agent_reader, agent_writer) = tokio::io::split(agent); @@ -50,6 +51,7 @@ impl Harness { .expect("connection should start") .expect("connection should publish a session"); Self { + stop_requested: watch::channel(()).0, active, reader: BufReader::new(agent_reader), writer: agent_writer, @@ -57,7 +59,7 @@ impl Harness { } } - async fn request(&mut self) -> Value { + pub(in crate::client) async fn request(&mut self) -> Value { let mut line = String::new(); tokio::time::timeout(DEADLINE, self.reader.read_line(&mut line)) .await @@ -66,19 +68,66 @@ impl Harness { serde_json::from_str(&line).expect("valid ACP JSON-RPC request") } - async fn send(&mut self, message: Value) { + pub(in crate::client) async fn send(&mut self, message: Value) { let mut bytes = serde_json::to_vec(&message).unwrap(); bytes.push(b'\n'); self.writer.write_all(&bytes).await.unwrap(); } - async fn next(&mut self, prompt: &mut AcpPrompt) -> Result { + fn prompt(&self, input: &str) -> AcpPrompt { + AcpPrompt::start( + &self.active, + input.into(), + None, + None, + self.stop_requested.subscribe(), + ) + } + + pub(in crate::client) async fn reply(&mut self, method: &str, mut response: Value) -> Value { + let request = self.request().await; + assert_eq!(request["method"], method); + response["jsonrpc"] = json!("2.0"); + response["id"] = request["id"].clone(); + self.send(response).await; + request["params"].clone() + } + + pub(in crate::client) async fn finish_with_text( + &mut self, + text: &str, + stop_reason: &str, + ) -> Value { + let request = self.request().await; + assert_eq!(request["method"], "session/prompt"); + self.send(json!({ + "jsonrpc": "2.0", "method": "session/update", + "params": {"sessionId": request["params"]["sessionId"], "update": { + "sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text} + }} + })) + .await; + self.send(json!({ + "jsonrpc": "2.0", "id": request["id"], "result": {"stopReason": stop_reason} + })) + .await; + request["params"].clone() + } + + async fn next(&mut self, prompt: &mut AcpPrompt) -> Result { tokio::time::timeout(DEADLINE, prompt.read_update(&mut self.active)) .await .expect("prompt must settle without relying on a user-supplied timeout") } } +fn protocol_failure(error: PromptError) -> Error { + match error { + PromptError::Protocol(error) => error, + other => panic!("expected an agent protocol error, got {other:?}"), + } +} + impl Drop for Harness { fn drop(&mut self) { self.connection_task.abort(); @@ -88,7 +137,7 @@ impl Drop for Harness { #[tokio::test] async fn prompt_error_is_reported_and_the_same_session_can_retry() { let mut harness = Harness::new().await; - let mut prompt = AcpPrompt::start(&harness.active, "offline request".into()); + let mut prompt = harness.prompt("offline request"); let request = harness.request().await; assert_eq!(request["method"], "session/prompt"); assert_eq!(request["params"]["sessionId"], "test-session"); @@ -104,12 +153,12 @@ async fn prompt_error_is_reported_and_the_same_session_can_retry() { } })) .await; - let error = harness.next(&mut prompt).await.unwrap_err(); + let error = protocol_failure(harness.next(&mut prompt).await.unwrap_err()); assert_eq!(error.message, "Network connection failed"); assert_eq!(error.data.unwrap()["code"], "ENETUNREACH"); assert!(!harness.connection_task.is_finished()); - let mut retry = AcpPrompt::start(&harness.active, "retry after reconnect".into()); + let mut retry = harness.prompt("retry after reconnect"); let request = harness.request().await; harness .send(json!({ @@ -127,7 +176,7 @@ async fn prompt_error_is_reported_and_the_same_session_can_retry() { #[tokio::test] async fn partial_output_is_preserved_before_a_prompt_error() { let mut harness = Harness::new().await; - let mut prompt = AcpPrompt::start(&harness.active, "request".into()); + let mut prompt = harness.prompt("request"); let request = harness.request().await; harness .send(json!({ @@ -154,7 +203,7 @@ async fn partial_output_is_preserved_before_a_prompt_error() { SessionMessage::SessionMessage(_) )); assert_eq!( - harness.next(&mut prompt).await.unwrap_err().message, + protocol_failure(harness.next(&mut prompt).await.unwrap_err()).message, "Connection reset" ); } @@ -162,7 +211,7 @@ async fn partial_output_is_preserved_before_a_prompt_error() { #[tokio::test] async fn cancellation_still_returns_the_agent_stop_reason() { let mut harness = Harness::new().await; - let mut prompt = AcpPrompt::start(&harness.active, "request".into()); + let mut prompt = harness.prompt("request"); let request = harness.request().await; harness .active @@ -186,7 +235,7 @@ async fn cancellation_still_returns_the_agent_stop_reason() { #[tokio::test] async fn agent_output_eof_fails_a_pending_prompt_even_if_its_input_is_open() { let mut harness = Harness::new().await; - let mut prompt = AcpPrompt::start(&harness.active, "request".into()); + let mut prompt = harness.prompt("request"); let _ = harness.request().await; harness.writer.shutdown().await.unwrap(); assert!(harness.next(&mut prompt).await.is_err()); @@ -195,7 +244,7 @@ async fn agent_output_eof_fails_a_pending_prompt_even_if_its_input_is_open() { #[tokio::test] async fn stopping_the_connection_wakes_a_pending_prompt() { let mut harness = Harness::new().await; - let mut prompt = AcpPrompt::start(&harness.active, "request".into()); + let mut prompt = harness.prompt("request"); let _ = harness.request().await; harness.connection_task.abort(); assert!(harness.next(&mut prompt).await.is_err()); @@ -204,7 +253,7 @@ async fn stopping_the_connection_wakes_a_pending_prompt() { #[tokio::test] async fn a_final_response_is_preserved_when_the_agent_immediately_closes_output() { let mut harness = Harness::new().await; - let mut prompt = AcpPrompt::start(&harness.active, "request".into()); + let mut prompt = harness.prompt("request"); let request = harness.request().await; harness .send(json!({ @@ -223,7 +272,7 @@ async fn a_final_response_is_preserved_when_the_agent_immediately_closes_output( #[tokio::test] async fn an_error_response_is_preserved_when_the_agent_immediately_closes_output() { let mut harness = Harness::new().await; - let mut prompt = AcpPrompt::start(&harness.active, "request".into()); + let mut prompt = harness.prompt("request"); let request = harness.request().await; harness .send(json!({ @@ -234,7 +283,7 @@ async fn an_error_response_is_preserved_when_the_agent_immediately_closes_output .await; harness.writer.shutdown().await.unwrap(); assert_eq!( - harness.next(&mut prompt).await.unwrap_err().message, + protocol_failure(harness.next(&mut prompt).await.unwrap_err()).message, "Network connection failed" ); } diff --git a/src/crates/interfaces/acp/src/client/remote_session.rs b/src/crates/interfaces/acp/src/client/remote_session.rs index 396c0d9a66..dba46c692a 100644 --- a/src/crates/interfaces/acp/src/client/remote_session.rs +++ b/src/crates/interfaces/acp/src/client/remote_session.rs @@ -19,7 +19,8 @@ impl AcpRemoteSessionStrategy { pub(super) fn startup_phase_name(self) -> &'static str { match self { Self::New => "session creation", - Self::Load | Self::Resume => "session restore", + Self::Load => "session/load", + Self::Resume => "session/resume", } } } @@ -27,81 +28,56 @@ impl AcpRemoteSessionStrategy { pub(super) fn preferred_resume_strategies( capabilities: Option<&AgentCapabilities>, remote_session_id: Option<&str>, + require_restore: bool, ) -> Vec { - let mut strategies = Vec::new(); - let has_remote_session_id = remote_session_id - .map(str::trim) - .is_some_and(|value| !value.is_empty()); - - if has_remote_session_id { - // Prefer loading saved session state over resuming a live stream. Some - // ACP clients continue an unfinished prompt on resume, and ACP update - // notifications are only scoped to the remote session, not a OpenBitFun turn. - if capabilities - .map(|capabilities| capabilities.load_session) - .unwrap_or(false) - { - strategies.push(AcpRemoteSessionStrategy::Load); - } + use AcpRemoteSessionStrategy::{Load, New, Resume}; - if capabilities - .and_then(|capabilities| capabilities.session_capabilities.resume.as_ref()) - .is_some() - { - strategies.push(AcpRemoteSessionStrategy::Resume); - } + if !remote_session_id.is_some_and(|id| !id.trim().is_empty()) { + return if require_restore { vec![] } else { vec![New] }; + } + let can_resume = capabilities.is_some_and(|caps| caps.session_capabilities.resume.is_some()); + let can_load = capabilities.is_some_and(|caps| caps.load_session); + // Resume does not tell us whether an unconfirmed prompt can still emit + // output. Load the saved session before another prompt takes its receiver. + if require_restore { + return if can_load { vec![Load] } else { Vec::new() }; + } + let mut strategies = Vec::new(); + if can_resume { + strategies.push(Resume); + } + if can_load { + strategies.push(Load); } - - strategies.push(AcpRemoteSessionStrategy::New); strategies } #[cfg(test)] mod tests { use super::*; + use agent_client_protocol::schema::{SessionCapabilities, SessionResumeCapabilities}; + use AcpRemoteSessionStrategy::{Load, New, Resume}; #[test] fn falls_back_to_new_without_remote_session_id() { - assert_eq!( - preferred_resume_strategies(Some(&AgentCapabilities::new().load_session(true)), None), - vec![AcpRemoteSessionStrategy::New] - ); - } - - #[test] - fn prefers_load_when_resume_is_not_supported() { - assert_eq!( - preferred_resume_strategies( - Some(&AgentCapabilities::new().load_session(true)), - Some("s1") - ), - vec![ - AcpRemoteSessionStrategy::Load, - AcpRemoteSessionStrategy::New - ] - ); + assert_eq!(preferred_resume_strategies(None, None, false), vec![New]); + assert!(preferred_resume_strategies(None, Some(" "), true).is_empty()); } #[test] - fn prefers_load_before_resume_when_both_are_supported() { - assert_eq!( - preferred_resume_strategies( - Some( - &AgentCapabilities::new() - .load_session(true) - .session_capabilities( - agent_client_protocol::schema::SessionCapabilities::new().resume( - agent_client_protocol::schema::SessionResumeCapabilities::new(), - ), - ), - ), - Some("s1") - ), - vec![ - AcpRemoteSessionStrategy::Load, - AcpRemoteSessionStrategy::Resume, - AcpRemoteSessionStrategy::New - ] + fn restores_existing_sessions_with_the_negotiated_agent() { + let strategies = |caps: &AgentCapabilities, required| { + preferred_resume_strategies(Some(caps), Some("original"), required) + }; + let load_only = AgentCapabilities::new().load_session(true); + let both = load_only.clone().session_capabilities( + SessionCapabilities::new().resume(SessionResumeCapabilities::new()), ); + let resume_only = both.clone().load_session(false); + assert_eq!(strategies(&both, false), vec![Resume, Load]); + assert_eq!(strategies(&both, true), vec![Load]); + assert_eq!(strategies(&load_only, false), vec![Load]); + assert!(strategies(&resume_only, true).is_empty()); + assert!(strategies(&AgentCapabilities::new(), false).is_empty()); } } diff --git a/src/crates/interfaces/acp/src/client/session_options.rs b/src/crates/interfaces/acp/src/client/session_options.rs index f00ea97681..bbbac36083 100644 --- a/src/crates/interfaces/acp/src/client/session_options.rs +++ b/src/crates/interfaces/acp/src/client/session_options.rs @@ -89,6 +89,13 @@ impl From for AcpPlanEntry { #[derive(Debug, Clone, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub struct AcpSessionOptions { + /// A passive read from local history. Sending is available even when the + /// agent has never advertised a selectable model. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub agent_disconnected: bool, + /// The host has no agent-provided options snapshot for this session yet. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub needs_initial_options: bool, /// Present on combined metadata reads; absence preserves the legacy commands endpoint. #[serde(default, skip_serializing_if = "Option::is_none")] pub available_commands: Option>, @@ -104,6 +111,15 @@ pub struct AcpSessionOptions { pub context_usage: Option, } +impl AcpSessionOptions { + pub(super) fn before_first_snapshot() -> Self { + Self { + needs_initial_options: true, + ..Self::default() + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AcpSessionModelOption { diff --git a/src/crates/interfaces/acp/src/client/session_persistence.rs b/src/crates/interfaces/acp/src/client/session_persistence.rs index 14380d8191..910f126bf5 100644 --- a/src/crates/interfaces/acp/src/client/session_persistence.rs +++ b/src/crates/interfaces/acp/src/client/session_persistence.rs @@ -4,7 +4,8 @@ use std::sync::Arc; use openbitfun_core::agentic::persistence::PersistenceManager; use openbitfun_core::infrastructure::PathManager; use openbitfun_core::service::session::{ - SessionMetadata, SESSION_PROVIDER_ACP, SESSION_PROVIDER_METADATA_KEY, + DialogTurnData, SessionMetadata, SessionTurnCatalog, SESSION_PROVIDER_ACP, + SESSION_PROVIDER_METADATA_KEY, }; use openbitfun_core::util::errors::{OpenBitFunError, OpenBitFunResult}; use serde::{Deserialize, Serialize}; @@ -18,6 +19,10 @@ pub(super) const CUSTOM_METADATA_PROVIDER_KEY: &str = SESSION_PROVIDER_METADATA_ pub(super) const CUSTOM_METADATA_PROVIDER_VALUE: &str = SESSION_PROVIDER_ACP; pub(super) const CUSTOM_METADATA_CLIENT_ID_KEY: &str = "acpClientId"; pub(super) const CUSTOM_METADATA_REMOTE_SESSION_ID_KEY: &str = "acpRemoteSessionId"; +const RESTORE_REQUIRED_KEY: &str = "acpRestoreRequired"; +pub(super) const PENDING_TURN_KEY: &str = "acpPendingTurn"; +const REPAIR_ATTEMPT_KEY: &str = "acpHistoryRepairAttempt"; +pub(super) const UNSENT_FINISH_REASON: &str = "acp_not_sent"; pub(super) const CUSTOM_METADATA_RESUME_STRATEGY_KEY: &str = "acpResumeStrategy"; pub(super) const CUSTOM_METADATA_LAST_RESUME_ERROR_KEY: &str = "acpLastResumeError"; @@ -30,7 +35,7 @@ pub struct CreateAcpFlowSessionRecordResponse { } pub(super) struct AcpSessionPersistence { - manager: PersistenceManager, + pub(super) manager: PersistenceManager, } impl AcpSessionPersistence { @@ -99,90 +104,501 @@ impl AcpSessionPersistence { .await } - pub(super) async fn load_remote_session_id( + pub(super) async fn prepare_dialog_turn( + &self, + path: &Path, + session: &str, + turn: &str, + client: &str, + input: &str, + original_input: &str, + user_metadata: Option, + ) -> OpenBitFunResult> { + let record = self + .manager + .load_session_metadata(path, session) + .await? + .ok_or_else(|| { + OpenBitFunError::NotFound(format!("ACP session record not found: {session}")) + })?; + let catalog = self + .manager + .load_session_turn_catalog(path, session, &[], record.turn_count) + .await?; + let first_owned = record + .custom_metadata + .as_ref() + .and_then(|v| v.get("acpRuntimeFromTurn")) + .and_then(Value::as_u64); + let (index, existing) = self + .free_turn_position(path, session, &catalog, turn) + .await?; + if existing { + let previous = self + .manager + .load_dialog_turn(path, session, index) + .await? + .ok_or_else(|| { + OpenBitFunError::NotFound(format!("ACP turn record not found: {turn}")) + })?; + if previous.user_message.content != original_input { + return Err(OpenBitFunError::validation( + "ACP turn id was already used with different input", + )); + } + if first_owned.is_some_and(|first| index as u64 >= first) + || previous.status != openbitfun_core::service::session::TurnStatus::InProgress + { + return Ok(None); + } + } + let mut user_metadata = user_metadata; + if input != original_input { + let mut fields = match user_metadata.take() { + Some(Value::Object(fields)) => fields, + _ => serde_json::Map::new(), + }; + fields.insert(super::transcript::PROMPT_TEXT_KEY.into(), input.into()); + user_metadata = Some(fields.into()); + } + let data = super::transcript::start_turn( + session, + turn, + index, + client, + original_input, + user_metadata, + ); + // A replay may append older turns. Accept the input durably now and + // assign its final disk position after the agent restores the prefix. + let pending = Self::has_history_gap(&record); + if first_owned.is_none() || pending { + self.update_binding(path, session, true, |metadata| { + let fields = custom_fields(metadata); + fields.entry("acpRuntimeFromTurn").or_insert(json!(index)); + if pending { + fields.insert(PENDING_TURN_KEY.into(), serde_json::to_value(&data)?); + fields.insert("acpHistoryGap".into(), true.into()); + } + Ok(()) + }) + .await?; + } + if !pending { + self.manager.save_dialog_turn(path, &data).await?; + } + Ok(Some((data, pending))) + } + + /// A crash after the turn write and before clearing the receipt reuses the same index. + pub(super) async fn place_pending_turn( + &self, + path: &Path, + data: &mut DialogTurnData, + ) -> OpenBitFunResult<()> { + let session = &data.session_id; + let record = self + .manager + .load_session_metadata(path, session) + .await? + .ok_or_else(|| { + OpenBitFunError::NotFound(format!("ACP session record not found: {session}")) + })?; + let catalog = self + .manager + .load_session_turn_catalog(path, session, &[], record.turn_count) + .await?; + data.turn_index = self + .free_turn_position(path, session, &catalog, &data.turn_id) + .await? + .0; + if data.status != openbitfun_core::service::session::TurnStatus::InProgress { + data.finish_reason = Some(UNSENT_FINISH_REASON.into()); + } + self.commit_dialog_turn(path, data).await?; + self.update_binding(path, session, true, |metadata| { + custom_fields(metadata).remove(PENDING_TURN_KEY); + Ok(()) + }) + .await + } + + /// The catalog is truncated to the metadata turn count, which can lag behind + /// the turn files after an interrupted write. Place a new turn after every + /// stored file so it never takes a position that holds a different turn, and + /// recognize a file that already stores this same turn. + pub(super) async fn free_turn_position( + &self, + path: &Path, + session: &str, + catalog: &SessionTurnCatalog, + turn_id: &str, + ) -> OpenBitFunResult<(usize, bool)> { + let (next, existing) = turn_position(catalog, turn_id); + if existing { + return Ok((next, true)); + } + // A derived catalog entry without a turn id is a placeholder for a file it + // has not read yet, and the retried turn can be any of them. Read those + // files once and fold them back into the catalog, so the next lookup is + // served by the complete catalog. + let mut found = None; + let mut read = Vec::new(); + for entry in catalog + .entries + .iter() + .filter(|entry| entry.turn_id.is_none()) + { + if let Some(stored) = self + .manager + .load_dialog_turn(path, session, entry.storage_turn_index) + .await? + { + if stored.turn_id == turn_id { + found = Some(entry.storage_turn_index); + } + read.push(stored); + } + } + if !read.is_empty() { + if let Err(error) = self + .manager + .load_session_turn_catalog(path, session, &read, catalog.entries.len()) + .await + { + log::warn!( + "Failed to refresh the derived ACP turn catalog: session_id={session} error={error}" + ); + } + } + if let Some(index) = found { + return Ok((index, true)); + } + let Some(stored_max) = self.manager.max_stored_turn_index(path, session).await? else { + return Ok((next, false)); + }; + // Normally the catalog already covers every file and this range is empty. + for index in next..=stored_max { + if let Some(stored) = self.manager.load_dialog_turn(path, session, index).await? { + if stored.turn_id == turn_id { + return Ok((index, true)); + } + } + } + Ok((next.max(stored_max + 1), false)) + } + + /// First position after every stored turn file, at or after `from`. + pub(super) async fn next_free_index( + &self, + path: &Path, + session: &str, + from: usize, + ) -> OpenBitFunResult { + Ok(self + .manager + .max_stored_turn_index(path, session) + .await? + .map_or(from, |stored_max| from.max(stored_max + 1))) + } + + pub(super) async fn commit_dialog_turn( + &self, + path: &Path, + data: &openbitfun_core::service::session::DialogTurnData, + ) -> OpenBitFunResult<()> { + if data.finish_reason.as_deref() == Some("acp_outcome_unknown") { + self.update_binding(path, &data.session_id, true, |metadata| { + custom_fields(metadata).insert("acpHistoryGap".into(), Value::Bool(true)); + Ok(()) + }) + .await?; + } + self.manager.save_dialog_turn(path, data).await + } + + pub(super) fn has_history_gap(record: &SessionMetadata) -> bool { + let custom = record.custom_metadata.as_ref().unwrap_or(&Value::Null); + custom["acpHistoryGap"] == true + || (record.turn_count == 0 + && (record.message_count > 0 || record.last_turn.is_some()) + && read_remote_binding(custom).0.is_some()) + } + + pub(super) async fn history_repaired( + &self, + path: &Path, + session: &str, + ) -> OpenBitFunResult<()> { + self.update_binding(path, session, false, |metadata| { + let fields = custom_fields(metadata); + fields.remove("acpHistoryGap"); + fields.remove(REPAIR_ATTEMPT_KEY); + Ok(()) + }) + .await + } + + /// A replay that could not repair the gap would fail the same way again while + /// the local history and the agent session stay the same. Remember the local + /// state it was tried against so only a change retries the full replay. + pub(super) fn repair_already_attempted(record: &SessionMetadata) -> bool { + record + .custom_metadata + .as_ref() + .and_then(|custom| custom.get(REPAIR_ATTEMPT_KEY)) + .and_then(Value::as_str) + .is_some_and(|attempted| attempted == repair_fingerprint(record)) + } + + pub(super) async fn record_repair_attempt( + &self, + path: &Path, + session: &str, + ) -> OpenBitFunResult<()> { + self.update_binding(path, session, false, |metadata| { + let fingerprint = repair_fingerprint(metadata); + custom_fields(metadata).insert(REPAIR_ATTEMPT_KEY.into(), fingerprint.into()); + Ok(()) + }) + .await + } + + pub(super) async fn saved_options( + &self, + path: &Path, + session: &str, + ) -> OpenBitFunResult { + let metadata = self.manager.load_session_metadata(path, session).await?; + let mut options = super::AcpSessionOptions::before_first_snapshot(); + if let Some(record) = metadata { + if let Some(saved) = record + .custom_metadata + .as_ref() + .and_then(|v| v.get("acpSessionOptions")) + { + options = serde_json::from_value(saved.clone()) + .map_err(|error| OpenBitFunError::Deserialization(error.to_string()))?; + } + if options.current_model_id.is_none() + && !record.model_name.is_empty() + && record.model_name != "primary" + { + options.current_model_id = Some(record.model_name); + } + } + Ok(options) + } + + pub(super) async fn save_options( + &self, + path: &Path, + session: &str, + options: &super::AcpSessionOptions, + ) -> OpenBitFunResult<()> { + let snapshot = serde_json::to_value(options) + .map_err(|err| OpenBitFunError::service(err.to_string()))?; + self.update_binding(path, session, false, |metadata| { + if let Some(model_id) = &options.current_model_id { + metadata.model_name.clone_from(model_id); + } + custom_fields(metadata).insert("acpSessionOptions".into(), snapshot); + Ok(()) + }) + .await + } + + #[cfg(test)] + pub(super) async fn remote_session_binding( &self, session_storage_path: &Path, openbitfun_session_id: &str, - ) -> OpenBitFunResult> { + ) -> OpenBitFunResult<(Option, bool)> { let Some(metadata) = self .manager .load_session_metadata(session_storage_path, openbitfun_session_id) .await? else { - return Ok(None); + return Ok((None, false)); }; - Ok(metadata - .custom_metadata - .as_ref() - .and_then(|custom| custom.get(CUSTOM_METADATA_REMOTE_SESSION_ID_KEY)) - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(ToString::to_string)) + Ok(read_remote_binding( + metadata.custom_metadata.as_ref().unwrap_or(&Value::Null), + )) } - pub(super) async fn update_remote_session_state( + pub(super) async fn require_restore( &self, session_storage_path: &Path, openbitfun_session_id: &str, remote_session_id: &str, - resume_strategy: &str, - last_resume_error: Option, ) -> OpenBitFunResult<()> { - self.update_metadata(session_storage_path, openbitfun_session_id, |metadata| { - let mut custom = metadata.custom_metadata.take().unwrap_or_else(|| json!({})); - ensure_object(&mut custom)?; - custom[CUSTOM_METADATA_PROVIDER_KEY] = json!(CUSTOM_METADATA_PROVIDER_VALUE); - custom[CUSTOM_METADATA_REMOTE_SESSION_ID_KEY] = json!(remote_session_id); - custom[CUSTOM_METADATA_RESUME_STRATEGY_KEY] = json!(resume_strategy); - custom[CUSTOM_METADATA_LAST_RESUME_ERROR_KEY] = - last_resume_error.map(Value::String).unwrap_or(Value::Null); - metadata.custom_metadata = Some(custom); - metadata.touch(); - Ok(()) - }) + self.update_binding( + session_storage_path, + openbitfun_session_id, + true, + |metadata| { + let custom = custom_fields(metadata); + write_remote_binding(custom, remote_session_id, true); + metadata.touch(); + Ok(()) + }, + ) .await } - pub(super) async fn update_model_id( + pub(super) async fn update_remote_session_state( &self, session_storage_path: &Path, openbitfun_session_id: &str, - model_id: &str, + remote_session_id: &str, + resume_strategy: &str, + last_resume_error: Option, + require_record: bool, ) -> OpenBitFunResult<()> { - self.update_metadata(session_storage_path, openbitfun_session_id, |metadata| { - metadata.model_name = model_id.to_string(); - metadata.touch(); - Ok(()) - }) + self.update_binding( + session_storage_path, + openbitfun_session_id, + require_record, + |metadata| { + let custom = custom_fields(metadata); + custom.insert( + CUSTOM_METADATA_PROVIDER_KEY.into(), + json!(CUSTOM_METADATA_PROVIDER_VALUE), + ); + write_remote_binding(custom, remote_session_id, false); + custom.insert( + CUSTOM_METADATA_RESUME_STRATEGY_KEY.into(), + json!(resume_strategy), + ); + custom.insert( + CUSTOM_METADATA_LAST_RESUME_ERROR_KEY.into(), + last_resume_error.map(Value::String).unwrap_or(Value::Null), + ); + metadata.touch(); + Ok(()) + }, + ) .await } - async fn update_metadata( + async fn update_binding( &self, session_storage_path: &Path, openbitfun_session_id: &str, + require_record: bool, update: impl FnOnce(&mut SessionMetadata) -> OpenBitFunResult<()>, ) -> OpenBitFunResult<()> { - self.manager + let updated = self + .manager .update_session_metadata_if_present(session_storage_path, openbitfun_session_id, update) - .await - .map(|_| ()) + .await?; + if require_record && !updated { + return Err(OpenBitFunError::NotFound(format!( + "ACP session record not found: {openbitfun_session_id}" + ))); + } + Ok(()) + } +} + +fn repair_fingerprint(record: &SessionMetadata) -> String { + let custom = record.custom_metadata.as_ref().unwrap_or(&Value::Null); + format!( + "{}|{}|{}|{}", + read_remote_binding(custom).0.unwrap_or_default(), + record.turn_count, + record + .last_turn + .as_ref() + .map_or("", |turn| turn.turn_id.as_str()), + custom + .get(PENDING_TURN_KEY) + .and_then(|pending| pending.get("turnId")) + .and_then(Value::as_str) + .unwrap_or_default(), + ) +} + +fn custom_fields(metadata: &mut SessionMetadata) -> &mut serde_json::Map { + let custom = metadata.custom_metadata.get_or_insert(Value::Null); + if let Value::Object(fields) = custom { + return fields; } + let mut fields = serde_json::Map::new(); + if !custom.is_null() { + fields.insert("acpLegacyCustomMetadata".into(), custom.take()); + } + *custom = Value::Object(fields); + custom.as_object_mut().expect("initialized an object") } -fn ensure_object(value: &mut Value) -> OpenBitFunResult<()> { - if value.is_object() { - return Ok(()); +fn turn_position(catalog: &SessionTurnCatalog, turn_id: &str) -> (usize, bool) { + match catalog + .entries + .iter() + .find(|entry| entry.turn_id.as_deref() == Some(turn_id)) + { + Some(entry) => (entry.storage_turn_index, true), + None => ( + catalog + .entries + .last() + .map_or(0, |entry| entry.storage_turn_index + 1), + false, + ), } +} - *value = json!({}); - if value.is_object() { - Ok(()) +pub(super) fn read_remote_binding(custom: &Value) -> (Option, bool) { + let id = custom + .get(CUSTOM_METADATA_REMOTE_SESSION_ID_KEY) + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(ToString::to_string); + (id, custom[RESTORE_REQUIRED_KEY] == true) +} + +fn write_remote_binding( + fields: &mut serde_json::Map, + remote_id: &str, + require_restore: bool, +) { + fields.insert( + CUSTOM_METADATA_REMOTE_SESSION_ID_KEY.into(), + json!(remote_id), + ); + if require_restore { + fields.insert(RESTORE_REQUIRED_KEY.into(), json!(true)); } else { - Err(OpenBitFunError::service( - "Failed to initialize ACP session custom metadata".to_string(), - )) + fields.remove(RESTORE_REQUIRED_KEY); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_repair_marker_only_holds_for_the_local_state_it_was_recorded_against() { + let mut saved = + SessionMetadata::new("s".into(), "chat".into(), "acp:x".into(), "primary".into()); + saved.custom_metadata = + Some(json!({"acpRemoteSessionId": "remote", "acpHistoryGap": true})); + assert!(!AcpSessionPersistence::repair_already_attempted(&saved)); + saved.custom_metadata.as_mut().unwrap()[REPAIR_ATTEMPT_KEY] = json!(3); + assert!(!AcpSessionPersistence::repair_already_attempted(&saved)); + let marker = repair_fingerprint(&saved); + saved.custom_metadata.as_mut().unwrap()[REPAIR_ATTEMPT_KEY] = json!(marker); + assert!(AcpSessionPersistence::repair_already_attempted(&saved)); + saved.turn_count += 1; + assert!(!AcpSessionPersistence::repair_already_attempted(&saved)); + saved.turn_count -= 1; + saved.custom_metadata.as_mut().unwrap()["acpRemoteSessionId"] = json!("another"); + assert!(!AcpSessionPersistence::repair_already_attempted(&saved)); + saved.custom_metadata.as_mut().unwrap()["acpRemoteSessionId"] = json!("remote"); + saved.custom_metadata.as_mut().unwrap()[PENDING_TURN_KEY] = json!({"turnId": "pending"}); + assert!(!AcpSessionPersistence::repair_already_attempted(&saved)); } } diff --git a/src/crates/interfaces/acp/src/client/stream.rs b/src/crates/interfaces/acp/src/client/stream.rs index e7d1d018e3..83820ae924 100644 --- a/src/crates/interfaces/acp/src/client/stream.rs +++ b/src/crates/interfaces/acp/src/client/stream.rs @@ -119,10 +119,27 @@ pub(super) async fn acp_dispatch_to_stream_events_with_tracker( dispatch: agent_client_protocol::Dispatch, tracker: &mut AcpToolCallTracker, ) -> OpenBitFunResult> { + decode_session_update(dispatch, tracker) + .await + .map(|(_, events)| events) +} + +/// User chunks delimit historical turns and carry an optional stable ACP message ID. +pub(super) async fn decode_session_update( + dispatch: agent_client_protocol::Dispatch, + tracker: &mut AcpToolCallTracker, +) -> OpenBitFunResult<( + Option<(Option, Option)>, + Vec, +)> { + let mut user = None; let mut events = Vec::new(); MatchDispatch::new(dispatch) .if_notification(async |notification: SessionNotification| { match notification.update { + SessionUpdate::UserMessageChunk(chunk) => { + user = Some((chunk.message_id.clone(), content_chunk_text(chunk))); + } SessionUpdate::AgentMessageChunk(chunk) => { if let Some(text) = content_chunk_text(chunk) { events.push(AcpClientStreamEvent::AgentText(text)); @@ -170,7 +187,7 @@ pub(super) async fn acp_dispatch_to_stream_events_with_tracker( .await .otherwise_ignore() .map_err(protocol_error)?; - Ok(events) + Ok((user, events)) } fn content_chunk_text(chunk: ContentChunk) -> Option { diff --git a/src/crates/interfaces/acp/src/client/transcript.rs b/src/crates/interfaces/acp/src/client/transcript.rs new file mode 100644 index 0000000000..91ee2b0fe1 --- /dev/null +++ b/src/crates/interfaces/acp/src/client/transcript.rs @@ -0,0 +1,317 @@ +//! Materialize the ACP event stream in the existing conversation history format. +//! The same reducer handles live delivery, journal recovery and agent replay. +use openbitfun_core::service::session::{ + DialogTurnData, ModelRoundData, TextItemData, ThinkingItemData, ToolCallData, ToolItemData, + ToolResultData, TurnStatus, UserMessageData, +}; +use openbitfun_events::{AgenticEvent, ToolEventData}; +use serde_json::Value; + +pub(super) fn now_ms() -> u64 { + chrono::Utc::now().timestamp_millis() as u64 +} + +/// The visible message can differ from the text sent to the agent, which is what +/// an agent replays. Older records carry no such field and use the visible text. +pub(super) const PROMPT_TEXT_KEY: &str = "acpPromptText"; + +pub(super) fn prompt_text(turn: &DialogTurnData) -> &str { + turn.user_message + .metadata + .as_ref() + .and_then(|metadata| metadata.get(PROMPT_TEXT_KEY)) + .and_then(Value::as_str) + .unwrap_or(&turn.user_message.content) +} + +pub(super) fn start_turn( + session: &str, + turn: &str, + index: usize, + client: &str, + input: &str, + metadata: Option, +) -> DialogTurnData { + let user = UserMessageData { + id: uuid::Uuid::new_v4().to_string(), + content: input.to_owned(), + timestamp: now_ms(), + metadata, + }; + let mut data = DialogTurnData::new(turn.into(), index, session.into(), user); + data.agent_type = Some(format!("acp:{client}")); + data +} + +pub(super) fn start_round(turn: &mut DialogTurnData, id: &str, index: usize, timestamp: u64) { + turn.model_rounds.push(ModelRoundData { + id: id.into(), + turn_id: turn.turn_id.clone(), + round_index: index, + round_group_id: None, + timestamp, + start_time: timestamp, + end_time: None, + duration_ms: None, + text_items: Vec::new(), + tool_items: Vec::new(), + thinking_items: Vec::new(), + provider_id: None, + model_config_id: None, + effective_model_name: None, + routing: None, + first_chunk_ms: None, + first_visible_output_ms: None, + stream_duration_ms: None, + ttft_ms: None, + attempt_count: None, + attempt_diagnostics: Vec::new(), + failure_category: None, + token_details: None, + status: "streaming".into(), + }); +} + +pub(super) fn append_text(round: &mut ModelRoundData, text: &str, thinking: bool, time: u64) { + let order = round.text_items.len() + round.thinking_items.len() + round.tool_items.len(); + if thinking { + if let Some(last) = round + .thinking_items + .last_mut() + .filter(|item| item.order_index == order.checked_sub(1)) + { + last.content.push_str(text); + } else { + round.thinking_items.push(ThinkingItemData { + id: format!("{}-thinking-{order}", round.id), + content: text.into(), + reasoning_kind: None, + is_streaming: false, + is_collapsed: true, + timestamp: time, + order_index: Some(order), + status: None, + is_subagent_item: None, + parent_task_tool_id: None, + subagent_session_id: None, + attempt_id: None, + attempt_index: None, + }); + } + } else if let Some(last) = round + .text_items + .last_mut() + .filter(|item| item.order_index == order.checked_sub(1)) + { + last.content.push_str(text); + } else { + round.text_items.push(TextItemData { + id: format!("{}-text-{order}", round.id), + content: text.into(), + is_streaming: false, + is_markdown: true, + timestamp: time, + order_index: Some(order), + status: None, + is_subagent_item: None, + parent_task_tool_id: None, + subagent_session_id: None, + attempt_id: None, + attempt_index: None, + }); + } +} + +pub(super) fn update_tool(round: &mut ModelRoundData, event: &ToolEventData, time: u64) { + let identity = event.identity(); + let order = round.text_items.len() + round.thinking_items.len() + round.tool_items.len(); + let index = round + .tool_items + .iter() + .position(|item| item.tool_call.id == identity.tool_id) + .unwrap_or_else(|| { + round.tool_items.push(ToolItemData { + id: identity.tool_id.clone(), + tool_name: identity.tool_name.clone(), + tool_call: ToolCallData { + input: Value::Null, + id: identity.tool_id.clone(), + }, + tool_result: None, + ai_intent: None, + start_time: time, + end_time: None, + duration_ms: None, + queue_wait_ms: None, + preflight_ms: None, + confirmation_wait_ms: None, + execution_ms: None, + order_index: Some(order), + is_subagent_item: None, + parent_task_tool_id: None, + subagent_session_id: None, + subagent_dialog_turn_id: None, + attempt_id: None, + attempt_index: None, + subagent_model_id: None, + subagent_model_display_name: None, + status: None, + interruption_reason: None, + }); + round.tool_items.len() - 1 + }); + let item = &mut round.tool_items[index]; + match event { + ToolEventData::Started { params, .. } + | ToolEventData::ConfirmationNeeded { params, .. } => { + item.tool_call.input = params.clone(); + item.status = Some( + if matches!(event, ToolEventData::ConfirmationNeeded { .. }) { + "confirming" + } else { + "running" + } + .into(), + ); + } + ToolEventData::Completed { + result, + result_for_assistant, + image_attachments, + duration_ms, + .. + } => { + item.tool_result = Some(ToolResultData { + result: result.clone(), + success: true, + result_for_assistant: result_for_assistant.clone(), + image_attachments: image_attachments.clone(), + error: None, + duration_ms: Some(*duration_ms), + }); + item.duration_ms = Some(*duration_ms); + item.end_time = Some(time); + item.status = Some("completed".into()); + } + ToolEventData::Failed { + error, duration_ms, .. + } + | ToolEventData::Cancelled { + reason: error, + duration_ms, + .. + } => { + item.tool_result = Some(ToolResultData { + result: Value::String(error.clone()), + success: false, + result_for_assistant: None, + image_attachments: None, + error: Some(error.clone()), + duration_ms: *duration_ms, + }); + item.end_time = Some(time); + item.status = Some( + if matches!(event, ToolEventData::Cancelled { .. }) { + "cancelled" + } else { + "error" + } + .into(), + ); + } + ToolEventData::Rejected { .. } => { + item.status = Some("rejected".into()); + item.end_time = Some(time); + } + _ => {} + } +} + +pub(super) fn apply_event(turn: &mut DialogTurnData, event: &AgenticEvent, time: u64) { + match event { + AgenticEvent::ModelRoundStarted { + round_id, + round_index, + .. + } => { + start_round(turn, round_id, *round_index, time); + } + AgenticEvent::TextChunk { text, .. } => { + if let Some(round) = turn.model_rounds.last_mut() { + append_text(round, text, false, time); + } + } + AgenticEvent::ThinkingChunk { content, .. } => { + if let Some(round) = turn.model_rounds.last_mut() { + append_text(round, content, true, time); + } + } + AgenticEvent::ToolEvent { tool_event, .. } => { + if let Some(round) = turn.model_rounds.last_mut() { + update_tool(round, tool_event, time); + } + } + AgenticEvent::ModelRoundCompleted { .. } => { + if let Some(round) = turn.model_rounds.last_mut() { + round.status = "completed".into(); + round.end_time = Some(time); + round.duration_ms = Some(time.saturating_sub(round.start_time)); + } + } + AgenticEvent::DialogTurnCompleted { .. } => turn.status = TurnStatus::Completed, + AgenticEvent::DialogTurnCancelled { .. } => turn.status = TurnStatus::Cancelled, + AgenticEvent::DialogTurnFailed { + error, + error_detail, + .. + } => { + turn.status = TurnStatus::Error; + turn.error = Some(error.clone()); + turn.error_detail = error_detail.clone(); + if error_detail + .as_ref() + .and_then(|d| d.recovery_constraint.as_deref()) + == Some("acp_stop_unconfirmed") + { + turn.finish_reason = Some("acp_outcome_unknown".into()); + } + } + _ => {} + } + if turn.status != TurnStatus::InProgress { + for round in &mut turn.model_rounds { + if round.status == "streaming" { + round.status = match turn.status { + TurnStatus::Completed => "completed", + TurnStatus::Cancelled => "cancelled", + _ => "error", + } + .into(); + round.end_time = Some(time); + round.duration_ms = Some(time.saturating_sub(round.start_time)); + } + if matches!(turn.status, TurnStatus::Cancelled | TurnStatus::Error) { + for tool in &mut round.tool_items { + if matches!(tool.status.as_deref(), Some("running" | "confirming")) { + tool.status = Some( + if turn.status == TurnStatus::Cancelled { + "cancelled" + } else { + "error" + } + .into(), + ); + tool.end_time = Some(time); + } + } + } + } + turn.end_time = Some(time); + turn.duration_ms = Some(time.saturating_sub(turn.start_time)); + turn.has_final_response = Some( + turn.model_rounds + .last() + .is_some_and(|r| !r.text_items.is_empty()), + ); + } +} diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index 16e395009e..b87f42eef2 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -7528,6 +7528,7 @@ export const ChatInput: React.FC = ({
(promise: Promise, timeoutMs: number, message: string): Promise { - return new Promise((resolve, reject) => { - const timeoutId = window.setTimeout(() => reject(new Error(message)), timeoutMs); - promise.then( - value => { - window.clearTimeout(timeoutId); - resolve(value); - }, - error => { - window.clearTimeout(timeoutId); - reject(error); - }, - ); - }); -} - const syncAcpContextUsageToStore = ( sessionId: string | undefined, options: AcpSessionOptions, @@ -376,6 +361,7 @@ export const ModelSelector: React.FC = ({ className = '', dropdownPlacement = 'top', sessionId, + isSceneActive = true, isSubagentSession = false, currentTokens = 0, maxTokens = 0, @@ -689,7 +675,7 @@ export const ModelSelector: React.FC = ({ return () => { configLoadRequestRef.current += 1; unsubscribe(); }; }, [loadConfigData, deviceSurfaceScope.epoch]); - const loadAcpOptions: () => Promise = useCallback(async () => { + const loadAcpOptions = useCallback(async (reason: 'open' | 'observe' | 'connect'): Promise => { const scope = deviceSurfaceScope; if (!scope.isCurrent()) return; const requestId = ++acpOptionsLoadRequestRef.current; @@ -700,14 +686,14 @@ export const ModelSelector: React.FC = ({ } setAcpOptionsLoadState('loading'); - const shouldShowRestoreToast = !acpOptionsRef.current && acpRestoreToastShownRef.current !== sessionId; + const shouldShowRestoreToast = reason === 'connect' && (!acpOptionsRef.current || acpOptionsRef.current.agentDisconnected) && acpRestoreToastShownRef.current !== sessionId; const startup = { requestId: createAcpStartupRequestId(), clientId: acpClientId, action: 'restore' as const, scope, retry: async () => { if (!scope.isCurrent() || modelSelectionScopeRef.current !== modelSelectionScopeKey || requestId !== acpOptionsLoadRequestRef.current) return; acpRestoreToastShownRef.current = null; - await loadAcpOptions(); + await loadAcpOptions(reason); }, }; const dismissStartup = () => emitAcpSessionStartup({ ...startup, phase: 'finish', cancelled: true }); @@ -720,23 +706,25 @@ export const ModelSelector: React.FC = ({ let succeeded = false; let failure: string | undefined; try { - const options = await withTimeout( - ACPClientAPI.getSessionOptions({ - sessionId, - clientId: acpClientId, - workspaceId: activeSession?.workspaceId || activeSession?.config.workspaceId, - workspacePath: activeSession?.workspacePath || activeSession?.config.workspacePath, - remoteConnectionId: activeSession?.remoteConnectionId, - remoteSshHost: activeSession?.remoteSshHost, - }), - ACP_SESSION_OPTIONS_TIMEOUT_MS, - `Timed out restoring ACP session options for ${acpClientId}`, - ); + const options = await ACPClientAPI.getSessionOptions({ + observeOnly: reason !== 'connect', + sessionId, + clientId: acpClientId, + workspaceId: activeSession?.workspaceId || activeSession?.config.workspaceId, + workspacePath: activeSession?.workspacePath || activeSession?.config.workspacePath, + remoteConnectionId: activeSession?.remoteConnectionId ?? activeSession?.config.remoteConnectionId, + remoteSshHost: activeSession?.remoteSshHost, + }); succeeded = true; - if (requestId !== acpOptionsLoadRequestRef.current || !scope.isCurrent()) return; + if (requestId !== acpOptionsLoadRequestRef.current || !scope.isCurrent() + || modelSelectionScopeRef.current !== modelSelectionScopeKey) return; setAcpOptions(options); - setAcpOptionsLoadState('ready'); syncAcpContextUsageToStore(sessionId, options); + if (reason === 'open' && options.needsInitialOptions) { + await loadAcpOptions('connect'); + } else { + setAcpOptionsLoadState('ready'); + } } catch (error) { failure = error instanceof Error ? error.message : String(error); if (requestId !== acpOptionsLoadRequestRef.current || !scope.isCurrent()) return; @@ -751,6 +739,7 @@ export const ModelSelector: React.FC = ({ } }, [ activeSession?.config.workspacePath, + activeSession?.config.remoteConnectionId, activeSession?.remoteConnectionId, activeSession?.remoteSshHost, activeSession?.workspacePath, @@ -775,21 +764,22 @@ export const ModelSelector: React.FC = ({ acpOptionsRef.current = acpOptions; }, [acpOptions]); + const initializeAcpOnOpen = isAcpSession && !externalSelection && isSceneActive; useEffect(() => { - void loadAcpOptions(); + void loadAcpOptions(initializeAcpOnOpen ? 'open' : 'observe'); return () => { acpOptionsLoadRequestRef.current += 1; acpStartupDismissRef.current?.(); acpStartupDismissRef.current = null; }; - }, [loadAcpOptions]); + }, [initializeAcpOnOpen, loadAcpOptions]); useEffect(() => { if (!isAcpSession || !sessionId || !acpClientId) return; return ACPClientAPI.onSessionOptionsChanged((event) => { if (event.sessionId === sessionId && event.clientId === acpClientId) { - loadAcpOptions(); + void loadAcpOptions('observe'); } }); }, [acpClientId, isAcpSession, loadAcpOptions, sessionId]); @@ -1130,6 +1120,11 @@ export const ModelSelector: React.FC = ({ return { status: acpOptionsLoadState === 'error' ? 'load-error' : 'loading', canSend: false }; } + if (acpOptions.needsInitialOptions && !acpOptions.currentModelId) { + return { status: acpOptionsLoadState === 'error' ? 'load-error' : 'loading', canSend: true }; + } + if (acpOptions.agentDisconnected) return { status: 'ready', canSend: true }; + const hasAcpExecutionTarget = Boolean( acpAvailableModels.length > 0 || acpMode || acpFastMode, ); @@ -2088,7 +2083,7 @@ export const ModelSelector: React.FC = ({ setKeyboardNavigationOpen(true); setDropdownOpen(true); if (isAcpSession && !externalSelection && !modelInformationLoading) { - void loadAcpOptions(); + void loadAcpOptions('connect'); } if (!hasSettingsPanel) { openPanel('models', true); @@ -2279,7 +2274,8 @@ export const ModelSelector: React.FC = ({ const displayedAvailability = externalSelection ? externalAvailability : isAcpSession ? acpAvailability : nativeAvailability; const showModelLoadingState = modelInformationLoading && ( - isNativeModelSelection ? configLoadState === 'loading' || !modelCatalog : isAcpSelection ? !acpOptions : !displayedModel + isNativeModelSelection ? configLoadState === 'loading' || !modelCatalog + : isAcpSelection ? !acpOptions || (acpOptions.needsInitialOptions && !displayedModel) : !displayedModel ); useEffect(() => { // An ACP response may hand model ownership entirely to its separate mode control. @@ -2291,7 +2287,8 @@ export const ModelSelector: React.FC = ({ : poolError ? t('modelSelector.pools.loadError') : poolsLoading ? t('modelSelector.status.loading') : t('modelSelector.pools.pendingSelection')); const showModelConfiguration = isNativeModelSelection && nativeAvailability.status === 'unconfigured'; - const modelLabel = showModelConfiguration ? t('modelSelector.noModelSelected') : poolId ? poolLabel : isAcpSelection && !showModelChoices + const modelLabel = showModelConfiguration ? t('modelSelector.noModelSelected') : poolId ? poolLabel + : isAcpSelection && (!showModelChoices || (!displayedModel && displayedAvailability.status === 'ready')) ? t('modelSelector.modelSettings') : currentModelMode === 'smart' ? t('modelSelector.modes.smart') : currentModelMode === 'pool' ? t('modelSelector.modes.pool') @@ -2327,7 +2324,7 @@ export const ModelSelector: React.FC = ({ // A command request is a keyboard interaction: focus the current choice // instead of leaving focus in the composer. setKeyboardNavigationOpen(true); - if (isAcpSelection && !modelInformationLoading) void loadAcpOptions(); + if (isAcpSelection && !modelInformationLoading) void loadAcpOptions('connect'); if (!hasSettingsPanel) { openPanel('models', true); } @@ -2554,7 +2551,7 @@ export const ModelSelector: React.FC = ({ if (nextOpen) { resetDropdownNavigation(); setKeyboardNavigationOpen(event.detail === 0); - if (isAcpSelection && !modelInformationLoading) void loadAcpOptions(); + if (isAcpSelection && !modelInformationLoading) void loadAcpOptions('connect'); if (!hasSettingsPanel) { openPanel('models', true); } diff --git a/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx b/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx index b8df8aaf37..e01dabf1a4 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx @@ -25,6 +25,7 @@ const aiApiMocks = vi.hoisted(() => ({ const flowChatStoreMocks = vi.hoisted(() => { type TestSession = { + workspaceId?: string; workspacePath?: string; remoteConnectionId?: string; remoteSshHost?: string; @@ -111,6 +112,7 @@ describe('ModelSelector ACP mode picker', () => { activateSurface('local'); flowChatStoreMocks.sessions.clear(); flowChatStoreMocks.sessions.set('acp-session', { + workspaceId: 'workspace-1', workspacePath: '/tmp/project', config: { agentType: 'acp:dsh' }, }); @@ -161,6 +163,7 @@ describe('ModelSelector ACP mode picker', () => { }; it('shows loading without duplicating the request and closes the model card for a mode-only response', async () => { + vi.useFakeTimers(); let resolveOptions!: (options: AcpSessionOptions) => void; vi.mocked(ACPClientAPI.getSessionOptions).mockReturnValueOnce(new Promise(resolve => { resolveOptions = resolve; @@ -173,6 +176,9 @@ describe('ModelSelector ACP mode picker', () => { expect(document.body.querySelector('[data-testid="chat-model-selector-loading"]')?.textContent) .toContain('modelSelector.status.loading'); expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(1); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: 'workspace-1' })); + await act(async () => { await vi.advanceTimersByTimeAsync(75_000); }); + expect(trigger.getAttribute('aria-busy')).toBe('true'); await act(async () => resolveOptions({ availableModels: [], configOptions: [MODE_OPTION] })); expect(container.querySelector('[data-testid="chat-model-selector-btn"]')).toBeNull(); @@ -215,38 +221,73 @@ describe('ModelSelector ACP mode picker', () => { expect(onAvailabilityChange).toHaveBeenLastCalledWith({ status: 'ready', canSend: true }); }); - it('retries failed initialization from the startup notification and ignores it after unmount', async () => { + it('restores an old session on opening and lets the startup notification retry a failure', async () => { const events: any[] = []; const handler = (event: Event) => events.push((event as CustomEvent).detail); window.addEventListener('openbitfun:acp-session-creation', handler); try { - vi.mocked(ACPClientAPI.getSessionOptions).mockRejectedValueOnce(new Error('Agent initialize failed')); + vi.mocked(ACPClientAPI.getSessionOptions) + .mockResolvedValueOnce({ agentDisconnected: true, needsInitialOptions: true, availableModels: [], configOptions: [] }) + .mockRejectedValueOnce(new Error('Agent initialize failed')); await act(async () => root.render()); + expect(ACPClientAPI.getSessionOptions).toHaveBeenNthCalledWith(1, expect.objectContaining({ observeOnly: true })); + expect(ACPClientAPI.getSessionOptions).toHaveBeenLastCalledWith(expect.objectContaining({ observeOnly: false })); const failed = events.find(event => event.phase === 'finish'); expect(failed).toMatchObject({ succeeded: false, error: 'Agent initialize failed', action: 'restore' }); vi.mocked(ACPClientAPI.getSessionOptions).mockResolvedValueOnce({ currentModelId: 'remote', availableModels: [{ id: 'remote', name: 'Remote' }], configOptions: [], }); await act(async () => failed.retry()); - expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(2); expect(events.filter(event => event.phase === 'start')).toHaveLength(2); expect(events.at(-1)).toMatchObject({ phase: 'finish', succeeded: true }); + expect(container.querySelector('[data-testid="chat-model-selector-btn"]')?.textContent).toContain('Remote'); act(() => root.render(null)); await failed.retry(); - expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(2); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(3); } finally { window.removeEventListener('openbitfun:acp-session-creation', handler); } }); + it('opens an old session without blocking send while its first model snapshot arrives', async () => { + const missing = { agentDisconnected: true, needsInitialOptions: true, availableModels: [], configOptions: [] }; + let resolve!: (options: AcpSessionOptions) => void; + vi.mocked(ACPClientAPI.getSessionOptions).mockResolvedValueOnce(missing).mockResolvedValueOnce(missing) + .mockReturnValueOnce(new Promise(done => { resolve = done; })); + const availability = vi.fn(); + const selector = (active: boolean) => ; + await act(async () => root.render(selector(false))); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(1); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledWith(expect.objectContaining({ observeOnly: true })); + await act(async () => root.render(selector(true))); + const trigger = container.querySelector('[data-testid="chat-model-selector-btn"]')!; + expect(trigger.textContent).toContain('modelSelector.status.loading'); + expect(availability).toHaveBeenLastCalledWith({ status: 'loading', canSend: true }); + expect(ACPClientAPI.getSessionOptions).toHaveBeenLastCalledWith(expect.objectContaining({ observeOnly: false })); + await act(async () => resolve({ + currentModelId: 'remote', availableModels: [{ id: 'remote', name: 'Remote' }], configOptions: [], + })); + expect(trigger.textContent).toContain('Remote'); + expect(availability).toHaveBeenLastCalledWith({ status: 'ready', canSend: true }); + }); + it('dismisses pending startup feedback when its session view is unmounted', async () => { const events: any[] = []; const handler = (event: Event) => events.push((event as CustomEvent).detail); window.addEventListener('openbitfun:acp-session-creation', handler); let resolve!: (options: AcpSessionOptions) => void; try { - vi.mocked(ACPClientAPI.getSessionOptions).mockReturnValueOnce(new Promise(done => { resolve = done; })); + vi.mocked(ACPClientAPI.getSessionOptions) + .mockResolvedValueOnce({ agentDisconnected: true, availableModels: [], configOptions: [] }) + .mockReturnValueOnce(new Promise(done => { resolve = done; })); await act(async () => root.render()); + expect(events).toHaveLength(0); + expect(ACPClientAPI.getSessionOptions).toHaveBeenLastCalledWith(expect.objectContaining({ observeOnly: true })); + const trigger = container.querySelector('[data-testid="chat-model-selector-btn"]')!; + expect(trigger.textContent).toContain('modelSelector.modelSettings'); + await act(async () => trigger.click()); + expect(ACPClientAPI.getSessionOptions).toHaveBeenLastCalledWith(expect.objectContaining({ observeOnly: false })); act(() => root.render(null)); expect(events.at(-1)).toMatchObject({ phase: 'finish', cancelled: true, requestId: events[0].requestId }); await act(async () => resolve({ availableModels: [], configOptions: [] })); @@ -293,10 +334,9 @@ describe('ModelSelector ACP mode picker', () => { await act(async () => root.render()); await act(async () => root.render()); await act(async () => resolvePrevious({ - currentModelId: 'old-model', - availableModels: [{ id: 'old-model', name: 'Old Model' }], - configOptions: [], + agentDisconnected: true, needsInitialOptions: true, currentModelId: 'old-model', availableModels: [], configOptions: [], })); + expect(ACPClientAPI.getSessionOptions).toHaveBeenCalledTimes(2); const trigger = container.querySelector('[data-testid="chat-model-selector-btn"]'); expect(trigger?.textContent).toContain('New Model'); expect(trigger?.textContent).not.toContain('Old Model'); diff --git a/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts b/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts index f4b22b1a0a..ea12a01020 100644 --- a/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts +++ b/src/web-ui/src/flow_chat/hooks/useAcpSlashCommands.ts @@ -44,6 +44,7 @@ export function useAcpSlashCommands( let cancelled = false; ACPClientAPI.getSessionCommands({ + observeOnly: true, sessionId, clientId, workspaceId, 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 80e544bb49..ab1788108a 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 @@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; import { __test_only__, handleDialogTurnComplete, + initializeEventListeners, handlePromptSuggestion, handleSessionHistoryChanged, handleSessionStateChanged, @@ -23,6 +24,9 @@ import type { FlowChatContext } from './types'; import { markOptimisticDispatchTurnMetadata } from '@/features/dispatch/optimisticDispatchTurn'; import { interruptedTurnRecoveryGate } from '../interruptedTurnRecoveryGate'; import { agentAPI } from '@/infrastructure/api/service-api/AgentAPI'; +import { api } from '@/infrastructure/api/service-api/ApiClient'; +import { agenticEventListener } from '../AgenticEventListener'; +import { i18nService } from '@/infrastructure/i18n'; import { localSessionDriver } from '../../session-drivers/local/LocalSessionDriver'; import * as peerSessionRefresh from './PeerSessionRefreshModule'; import { chatInputSessionSubscriptionKey } from '../../utils/chatInputSessionSubscription'; @@ -1654,11 +1658,12 @@ describe('handleDialogTurnFailed', () => { }); afterEach(() => { + vi.restoreAllMocks(); resetFlowChatStore(); stateMachineManager.clear(); }); - it('keeps a zero-round turn and records the terminal provider error', () => { + it.each([undefined, 'disk full'])('keeps the provider failure when the history save error is %s', async (saveError) => { createSessionWithTurn({ id: 'turn-1', sessionId: 'session-1', @@ -1674,15 +1679,21 @@ describe('handleDialogTurnFailed', () => { const context = createFlowChatContext(); context.userCancelledSessionIds.add('session-1'); - __test_only__.handleDialogTurnFailed(context, { + vi.spyOn(api, 'listen').mockImplementation(() => () => {}); + vi.spyOn(api, 'waitForListenerRegistrations').mockResolvedValue(); + const translate = vi.spyOn(i18nService, 't'); + const cleanup = await initializeEventListeners(context, vi.fn()); + agenticEventListener.dispatchExternal('agentic://dialog-turn-failed', { sessionId: 'session-1', turnId: 'turn-1', error: 'OpenAI Streaming API failed after 10 attempts: connection refused', + acpHistorySaveError: saveError, errorDetail: { category: 'network', provider: 'openai', }, }); + cleanup(); const turn = FlowChatStore.getInstance() .getState() @@ -1699,7 +1710,12 @@ describe('handleDialogTurnFailed', () => { modelRounds: [], }); expect(notificationService.error).not.toHaveBeenCalled(); - expect(notificationService.warning).not.toHaveBeenCalled(); + if (saveError) { + expect(translate).toHaveBeenCalledWith('flow-chat:historyState.turnSaveFailed', { error: saveError }); + expect(notificationService.warning).toHaveBeenCalledOnce(); + } else { + expect(notificationService.warning).not.toHaveBeenCalled(); + } expect(context.userCancelledSessionIds.has('session-1')).toBe(false); }); }); 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 99efbb403c..eaf6076ca2 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 @@ -30,6 +30,7 @@ import { type ParamsPartialToolEvent } from '../EventBatcher'; import { notificationService } from '../../../shared/notification-system/services/NotificationService'; +import { i18nService } from '@/infrastructure/i18n'; import { readBackgroundDelivery, shouldDeliverBackgroundCompletion } from '../../utils/backgroundDelivery'; import { createLogger } from '@/shared/utils/logger'; import { handleThreadGoalUpdated } from '../threadGoalEventService'; @@ -46,6 +47,7 @@ import type { ModelRoundAttemptSupersededEvent, OpenBuiltInBrowserEvent, AcpContextUsageUpdatedEvent, + AgenticEvent, PromptSuggestionEvent, SessionModelFallbackAppliedEvent, SessionReasoningPresetAutoClearedEvent, @@ -898,6 +900,15 @@ export async function initializeEventListeners( }); const afterRelayRecords = relayRecordsBeforeEvent(context); + const onTurnEnd = (handle: (event: AgenticEvent) => void) => + afterRelayRecords((event: AgenticEvent) => { + handle(event); + if (event.acpHistorySaveError) { + notificationService.warning(i18nService.t('flow-chat:historyState.turnSaveFailed', { + error: event.acpHistorySaveError, + })); + } + }); const callbacks: AgenticEventCallbacks = { onSessionCreated: (event) => { handleSessionCreated(context, event); @@ -941,13 +952,13 @@ export async function initializeEventListeners( onModelRoundAttemptSuperseded: afterRelayRecords((event) => { handleModelRoundAttemptSuperseded(context, event); }), - onDialogTurnCompleted: afterRelayRecords((event) => { + onDialogTurnCompleted: onTurnEnd((event) => { handleDialogTurnComplete(context, event, onTodoWriteResult); }), - onDialogTurnFailed: afterRelayRecords((event) => { + onDialogTurnFailed: onTurnEnd((event) => { handleDialogTurnFailed(context, event); }), - onDialogTurnCancelled: afterRelayRecords((event) => { + onDialogTurnCancelled: onTurnEnd((event) => { handleDialogTurnCancelled(context, event, onTodoWriteResult); }), onDialogTurnInterrupted: afterRelayRecords((event) => { diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts index c139dcc0be..9a642166c4 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts @@ -121,6 +121,17 @@ describe('PersistenceModule', () => { }, ); + it('lets the ACP host persist its own turn and checkpoints turns from older hosts', async () => { + const turn = createDialogTurn('completed'); + const context = createContext(turn, { workspaceId: 'workspace-local', config: { agentType: 'acp:codex' } }); + turn.userMessage.metadata = { acpRuntimeOwnsHistory: true }; + await saveDialogTurnToDisk(context, SESSION_ID, TURN_ID); + expect(mockSaveSessionTurn).not.toHaveBeenCalled(); + delete turn.userMessage.metadata.acpRuntimeOwnsHistory; + await saveDialogTurnToDisk(context, SESSION_ID, TURN_ID); + expect(mockSaveSessionTurn).toHaveBeenCalledOnce(); + }); + it('saves a visible result receipt with its retained generation and no metadata read', async () => { const turn = createDialogTurn('completed'); turn.recoveryEpoch = 2; diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts index c88c3f9cb6..6e3c30c47e 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts @@ -9,6 +9,7 @@ import { createLogger } from '@/shared/utils/logger'; import type { UiSessionMetadataField } from '@/infrastructure/api/service-api/SessionAPI'; import { getActiveSurfaceScope, isLocalSurface } from '@/infrastructure/peer-device/deviceSurface'; import type { FlowChatContext, DialogTurn } from './types'; +import { isAcpFlowSession } from '../../utils/acpSession'; import { buildSessionMetadata } from '../../utils/sessionMetadata'; import { settleInterruptedDialogTurn } from '../../utils/dialogTurnStability'; import { @@ -383,6 +384,10 @@ async function performSaveDialogTurnToDisk( log.debug('Dialog turn not found, skipping save', { sessionId, turnId }); return; } + if (isAcpFlowSession(session) && dialogTurn.userMessage.metadata?.acpRuntimeOwnsHistory === true) { + skip('The ACP runtime owns this turn'); + return; + } if (dialogTurn.recovery) { skip('Runtime-owned recovered turns do not support GenUI state updates'); // The Runtime owns the durable snapshot and generation CAS for an 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 5530cbaac8..bc334d36ed 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -4810,6 +4810,7 @@ describe('FlowChatStore historical session hydration state', () => { sessions: new Map([ ['acp-1', createSession({ sessionId: 'acp-1', + workspaceId: fixtureWorkspaceId('D:/workspace/OpenBitFun'), isHistorical: true, historyState: 'metadata-only', mode: 'acp:test', @@ -4854,7 +4855,8 @@ describe('FlowChatStore historical session hydration 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' }, + sessionId: 'acp-1', workspaceId: fixtureWorkspaceId('D:/workspace/OpenBitFun'), + mode: 'acp:test', config: { agentType: 'acp:test' }, historyState: 'ready', isHistorical: false, })]]), activeSessionId: 'acp-1', })); @@ -7920,6 +7922,7 @@ describe('FlowChatStore historical session hydration state', () => { sessions: new Map([ ['history-1', createSession({ sessionId: 'history-1', + workspaceId: fixtureWorkspaceId('D:/workspace/OpenBitFun'), isHistorical: true, historyState: 'metadata-only', mode: 'Standard', @@ -8182,7 +8185,9 @@ describe('FlowChatStore historical session hydration state', () => { await flowChatStore.initializeFromDisk(fixtureWorkspaceId('D:/workspace/OpenBitFun', undefined, undefined), undefined); - expect(flowChatStore.getState().sessions.get('history-1')?.currentTokenUsage).toBeUndefined(); + const session = flowChatStore.getState().sessions.get('history-1'); + expect(session).toBeDefined(); + expect(session?.currentTokenUsage).toBeUndefined(); }); it('ignores invalid persisted current context usage', async () => { diff --git a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts index a83fe79192..138135e9db 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.test.ts @@ -56,7 +56,7 @@ describe('ACPClientAPI client list startup cache', () => { invokeMock.mockReturnValueOnce(deferred.promise); const options = ACPClientAPI.getSessionOptions(sessionRequest); const commands = ACPClientAPI.getSessionCommands({ ...sessionRequest }); - expect(invokeMock).toHaveBeenCalledTimes(1); + expect(invokeMock).toHaveBeenCalledWith('get_acp_session_options', { request: sessionRequest }, { timeout: 0 }); deferred.resolve({ availableModels: [], configOptions: [], availableCommands: [] }); await expect(commands).resolves.toEqual([]); await options; 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 2bfffa152a..eaf790836e 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ACPClientAPI.ts @@ -2,6 +2,9 @@ import { api } from './ApiClient'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; import type { ImageContextData as ImageInputContextData } from './ImageContextTypes'; +// Older hosts may initialize and attach even for a snapshot read. +const ACP_SNAPSHOT_TIMEOUT_MS = 125_000; + export type AcpClientPermissionMode = 'ask' | 'allow_once' | 'reject_once'; export type AcpClientStatus = 'configured' | 'starting' | 'running' | 'stopped' | 'failed'; @@ -96,6 +99,7 @@ export interface CancelAcpDialogTurnRequest { } export interface GetAcpSessionOptionsRequest { + observeOnly?: boolean; sessionId: string; clientId: string; /** Workspace identity; authoritative when present. Paths below are IO projections. */ @@ -174,6 +178,8 @@ export interface AcpContextUsage { } export interface AcpSessionOptions { + agentDisconnected?: boolean; + needsInitialOptions?: boolean; /** Included by newer hosts to share the initial metadata read. Missing means use the commands endpoint. */ availableCommands?: AcpAvailableCommand[]; currentModelId?: string; @@ -465,10 +471,12 @@ export class ACPClientAPI { ): Promise { const scope = getActiveSurfaceScope(); const key = scope.key(scope.epoch, request.sessionId, request.clientId, request.workspaceId, - request.workspacePath, request.remoteConnectionId, request.remoteSshHost); + request.workspacePath, request.remoteConnectionId, request.remoteSshHost, request.observeOnly ? 'snapshot' : 'connect'); const existing = this.sessionOptionsInFlight.get(key); if (existing) return existing; - const pending = api.invoke('get_acp_session_options', { request }) + // The host enforces an inactivity timeout during a connected history replay. + const pending = api.invoke('get_acp_session_options', { request }, + { timeout: request.observeOnly ? ACP_SNAPSHOT_TIMEOUT_MS : 0 }) .then(options => { scope.assertCurrent('load ACP session metadata'); if (Array.isArray(options.availableCommands)) { diff --git a/src/web-ui/src/locales/en-US/flow-chat.json b/src/web-ui/src/locales/en-US/flow-chat.json index b6a371a5be..0cfc93e96b 100644 --- a/src/web-ui/src/locales/en-US/flow-chat.json +++ b/src/web-ui/src/locales/en-US/flow-chat.json @@ -254,6 +254,7 @@ "waitingForModelResponse": "Waiting for model response..." }, "historyState": { + "turnSaveFailed": "This turn ended, but its conversation history could not be saved. {{error}}", "emptyWindow": "No visible messages in this history window.", "loadingTitle": "Loading saved session", "loadingDescription": "Preparing the conversation history.", diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json index 54a5ec4634..a57103efbc 100644 --- a/src/web-ui/src/locales/zh-CN/flow-chat.json +++ b/src/web-ui/src/locales/zh-CN/flow-chat.json @@ -254,6 +254,7 @@ "waitingForModelResponse": "等待模型响应..." }, "historyState": { + "turnSaveFailed": "本轮已结束,会话记录保存失败。{{error}}", "emptyWindow": "这段历史中没有可显示的消息。", "loadingTitle": "正在加载历史会话", "loadingDescription": "正在准备该会话的历史内容。", diff --git a/src/web-ui/src/locales/zh-TW/flow-chat.json b/src/web-ui/src/locales/zh-TW/flow-chat.json index 24c60e06ee..c020ded228 100644 --- a/src/web-ui/src/locales/zh-TW/flow-chat.json +++ b/src/web-ui/src/locales/zh-TW/flow-chat.json @@ -254,6 +254,7 @@ "waitingForModelResponse": "等待模型回應..." }, "historyState": { + "turnSaveFailed": "本輪已結束,對話紀錄儲存失敗。{{error}}", "emptyWindow": "這段歷史中沒有可顯示的訊息。", "loadingTitle": "正在載入歷史會話", "loadingDescription": "正在準備該會話的歷史內容。",