From b452e50f6c81bc5eaa7fbc9d0ffb4f7633db5dac Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 20:25:31 +0800 Subject: [PATCH 1/7] fix(web-ui): Stream /btw replies on peer surfaces A peer host only streams a session's events to a controller that subscribed to it, and the surface subscribes only its active session. A side question renders beside that session, so the host ran the turn while the panel stayed empty, and every retry reused the request id and was refused as Processing. Open the child session's relay subscription once btw_ask_stream is accepted. The host replays from its records, so earlier events are not lost. --- .../services/BtwThreadService.test.ts | 33 +++++++++++++++++++ .../flow_chat/services/BtwThreadService.ts | 23 +++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts b/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts index 36786cb588..70d400d9c3 100644 --- a/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts +++ b/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts @@ -10,6 +10,7 @@ const mockUpdateSessionModelName = vi.fn(); const mockUpdateSessionReasoningPreset = vi.fn(); const mockEnsureBackendSession = vi.fn(); const mockUpdateSessionModelPool = vi.fn(); +const mockLoadRelaySessionHistory = vi.fn(); const sessions = new Map(); @@ -26,6 +27,7 @@ vi.mock('../store/FlowChatStore', () => ({ flowChatStore: { getState: () => ({ sessions }), updateSessionModelPool: (...args: any[]) => mockUpdateSessionModelPool(...args), + loadRelaySessionHistory: (...args: any[]) => mockLoadRelaySessionHistory(...args), addExternalSession: (...args: any[]) => mockAddExternalSession(...args), updateSessionRelationship: (...args: any[]) => mockUpdateSessionRelationship(...args), updateSessionBtwOrigin: (...args: any[]) => mockUpdateSessionBtwOrigin(...args), @@ -64,6 +66,7 @@ import { sendMessageToBtwSession, startBtwThread, } from './BtwThreadService'; +import { activateSurface, surfaceIdForDevice } from '@/infrastructure/peer-device/deviceSurface'; describe('BtwThreadService', () => { beforeEach(() => { @@ -87,6 +90,7 @@ describe('BtwThreadService', () => { ], }); mockAskStream.mockResolvedValue({ ok: true }); + mockLoadRelaySessionHistory.mockResolvedValue(undefined); mockCreateSession.mockResolvedValue({ sessionId: 'child-1', }); @@ -338,6 +342,35 @@ describe('BtwThreadService', () => { ); }); + it('subscribes to the side question stream once a peer host accepts it', async () => { + sessions.set('btw-child', { sessionId: 'btw-child', sessionKind: 'btw', config: {}, dialogTurns: [] }); + activateSurface(surfaceIdForDevice('peer-device-1')); + try { + await sendMessageToBtwSession({ parentSessionId: 'parent-1', childSessionId: 'btw-child', question: 'Any news?' }); + } finally { + activateSurface(surfaceIdForDevice(null)); + } + expect(mockLoadRelaySessionHistory).toHaveBeenCalledWith('btw-child'); + expect(mockAskStream.mock.invocationCallOrder[0]) + .toBeLessThan(mockLoadRelaySessionHistory.mock.invocationCallOrder[0]); + }); + + it('does not open a relay subscription on the local surface or after a refused question', async () => { + sessions.set('btw-child', { sessionId: 'btw-child', sessionKind: 'btw', config: {}, dialogTurns: [] }); + await sendMessageToBtwSession({ parentSessionId: 'parent-1', childSessionId: 'btw-child', question: 'Any news?' }); + expect(mockLoadRelaySessionHistory).not.toHaveBeenCalled(); + + mockAskStream.mockRejectedValueOnce(new Error('host refused')); + activateSurface(surfaceIdForDevice('peer-device-1')); + try { + await expect(sendMessageToBtwSession({ parentSessionId: 'parent-1', childSessionId: 'btw-child', question: 'Again?' })) + .rejects.toThrow('host refused'); + } finally { + activateSurface(surfaceIdForDevice(null)); + } + expect(mockLoadRelaySessionHistory).not.toHaveBeenCalled(); + }); + it('discards the local placeholder when the first /btw request fails', async () => { const error = new Error('backend refused'); mockAskStream.mockRejectedValueOnce(error); diff --git a/src/web-ui/src/flow_chat/services/BtwThreadService.ts b/src/web-ui/src/flow_chat/services/BtwThreadService.ts index 222d22234c..e140218321 100644 --- a/src/web-ui/src/flow_chat/services/BtwThreadService.ts +++ b/src/web-ui/src/flow_chat/services/BtwThreadService.ts @@ -17,6 +17,9 @@ import { requireSessionWorkspaceId, sessionWorkspaceId } from '../utils/sessionW import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; import { assertSessionConversationCanSubmit } from '../session-drivers/conversationCapability'; import { trackBtwSessionSubmission } from './btwSessionSubmission'; +import { createLogger } from '@/shared/utils/logger'; + +const log = createLogger('BtwThreadService'); export function createBtwRequestId(prefix = 'btw'): string { try { @@ -298,6 +301,25 @@ export function createBtwSessionPlaceholder(params: { return { childSessionId, parentDialogTurnId, parentTurnIndex }; } +/** + * A peer host only streams a session's events to a controller that subscribed + * to it, and the surface subscribes only its active session. A side question + * renders beside that session, so without its own subscription the host runs + * the turn while the panel stays empty. The host has created the child once + * `btw_ask_stream` is accepted; the subscription replays from its records, so + * events emitted before it opens are not lost. It closes with the session. + */ +function followBtwSessionOnPeer( + scope: ReturnType, + childSessionId: string, +): void { + if (scope.surfaceId === 'local' || !scope.isCurrent()) return; + void flowChatStore.loadRelaySessionHistory(childSessionId).catch(error => { + if (!scope.isCurrent()) return; + log.warn('Side question stream subscription failed', { childSessionId, error }); + }); +} + export async function sendMessageToBtwSession(params: { parentSessionId: string; childSessionId: string; @@ -349,6 +371,7 @@ export async function sendMessageToBtwSession(params: { ...(params.initialModelSelection ? { initialModelSelection: params.initialModelSelection } : {}), ...(params.initialModelTarget ? { initialModelTarget: params.initialModelTarget } : {}), })); + followBtwSessionOnPeer(scope, params.childSessionId); if (scope.isCurrent() && params.initialModelTarget?.selection.kind === 'pool') { const current = flowChatStore.getState().sessions.get(params.childSessionId); if (current?.config.modelPoolId === params.initialModelTarget.selection.pool_id) { From 4a9ed7cbaedc414cb359d02e471b44d8bf73415c Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 20:25:31 +0800 Subject: [PATCH 2/7] feat(cli): Answer session parity commands on the CLI peer host Controllers saw these features fail only when driving a CLI host: - cancel_session, so closing a /btw side question no longer errors - fork_session and copy_session (session_fork_v1, whole_session_copy_v1) - load_persisted_session_metadata, used after create and fork - interrupt_dialog_turn and recover_interrupted_dialog_turn (recoverable_interruption_v1, also advertised by Desktop) - compact_session, unarchive_session, list_archived_sessions, get_session_lineage, and the thread goal mutations - get_session_file_diff_stats through LocalWorkspaceSnapshotPort Subscription account commands now carry a reason that reports them as unavailable on CLI hosts instead of asking the user to update. --- src/apps/cli/src/peer_host/commands/dialog.rs | 166 ++++++++++++++- src/apps/cli/src/peer_host/commands/goal.rs | 191 ++++++++++++++++++ src/apps/cli/src/peer_host/commands/mod.rs | 41 ++++ .../cli/src/peer_host/commands/session.rs | 165 ++++++++++++++- .../cli/src/peer_host/commands/snapshot.rs | 110 +++++++++- .../assembly/core/src/product_runtime.rs | 28 ++- .../generated/remote-surface-registry.json | 78 ++++--- .../src/remote_surface/capabilities.rs | 20 +- .../product-domains/src/remote_surface/mod.rs | 25 +-- .../src/remote_surface/table.rs | 59 +++--- src/crates/contracts/runtime-ports/src/lib.rs | 1 + .../src/local_workspace_snapshot.rs | 26 +++ .../api/generated/remoteSurface.ts | 9 +- 13 files changed, 824 insertions(+), 95 deletions(-) create mode 100644 src/apps/cli/src/peer_host/commands/goal.rs diff --git a/src/apps/cli/src/peer_host/commands/dialog.rs b/src/apps/cli/src/peer_host/commands/dialog.rs index 09ca1387af..2673b10d8e 100644 --- a/src/apps/cli/src/peer_host/commands/dialog.rs +++ b/src/apps/cli/src/peer_host/commands/dialog.rs @@ -7,13 +7,14 @@ use std::time::{Duration, Instant}; use serde_json::{json, Value}; use tokio::sync::Mutex as AsyncMutex; -use openbitfun_agent_runtime::sdk::AgentUserAnswersRequest; +use openbitfun_agent_runtime::sdk::{AgentUserAnswersRequest, PortErrorKind, RuntimeError}; use openbitfun_runtime_ports::{ - AgentDialogTurnRequest, AgentInputAttachment, AgentSubmissionSource, - AgentTurnCancellationRequest, DialogSubmissionPolicy, DialogTriggerSource, + AgentDialogTurnRecoveryRequest, AgentDialogTurnRequest, AgentInputAttachment, + AgentSubmissionSource, AgentTurnCancellationRequest, AgentTurnInterruptionRequest, + DialogSubmissionPolicy, DialogTriggerSource, }; -use crate::peer_host::args::{get_string, optional_string, request_value}; +use crate::peer_host::args::{get_string, optional_bool, optional_string, request_value}; use crate::peer_host::state::{PeerHostState, PeerTurnKey}; /// How long an accepted submission stays replayable. @@ -372,6 +373,163 @@ pub(crate) async fn cancel_dialog_turn( Ok(json!({ "success": true })) } +/// Stop a Turn so it can be resumed later, like Desktop `interrupt_dialog_turn`. +/// +/// Sessions the runtime cannot interrupt recoverably (external routes, Goal, +/// remote, non-standard sessions) or an interruption that times out fall back +/// to the hard cancellation `cancel_dialog_turn` performs, so Stop always works. +pub(crate) async fn interrupt_dialog_turn( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = get_string(request, "sessionId")?; + let dialog_turn_id = get_string(request, "dialogTurnId")?; + let interruption = state + .agent_runtime + .interrupt_turn(AgentTurnInterruptionRequest { + session_id: session_id.clone(), + turn_id: dialog_turn_id.clone(), + source: Some(AgentSubmissionSource::Cli), + wait_timeout_ms: Some(30_000), + }) + .await; + match interruption { + Ok(_) => Ok(Value::Null), + Err(RuntimeError::Port(error)) + if matches!( + error.kind, + PortErrorKind::InvalidRequest | PortErrorKind::Timeout + ) => + { + let reason = if error.kind == PortErrorKind::Timeout { + "recoverable interruption timed out" + } else { + "recoverable interruption unavailable" + }; + state + .agent_runtime + .cancel_turn(AgentTurnCancellationRequest { + session_id, + turn_id: Some(dialog_turn_id), + source: Some(AgentSubmissionSource::Cli), + requester_session_id: None, + reason: Some(reason.to_string()), + wait_timeout_ms: None, + cancel_descendants: true, + }) + .await + .map(|_| Value::Null) + .map_err(|error| format!("Failed to cancel dialog turn: {}", error.into_message())) + } + Err(error) => Err(format!( + "Failed to interrupt dialog turn: {}", + error.into_message() + )), + } +} + +/// Resume a Turn that `interrupt_dialog_turn` stopped, like Desktop +/// `recover_interrupted_dialog_turn`. The runtime compares the caller's +/// execution generation, so a stale controller cannot resume twice. +pub(crate) async fn recover_interrupted_dialog_turn( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let execution_generation = request + .get("executionGeneration") + .or_else(|| request.get("execution_generation")) + .and_then(Value::as_u64) + .and_then(|value| u32::try_from(value).ok()) + .ok_or("executionGeneration is required")?; + let outcome = state + .agent_runtime + .recover_interrupted_turn(AgentDialogTurnRecoveryRequest { + session_id: get_string(request, "sessionId")?, + turn_id: get_string(request, "dialogTurnId")?, + execution_generation, + workspace_path: optional_string(request, "workspacePath"), + workspace_id: optional_string(request, "workspaceId"), + remote_connection_id: optional_string(request, "remoteConnectionId"), + remote_ssh_host: optional_string(request, "remoteSshHost"), + }) + .await + .map_err(|error| { + format!( + "Failed to recover interrupted dialog turn: {}", + error.into_message() + ) + })?; + serde_json::to_value(outcome).map_err(|error| error.to_string()) +} + +/// Compact a session's context on request (`/compact`), like Desktop +/// `compact_session`. The compaction runs as a detached Turn whose events reach +/// the controller through the normal session stream. +pub(crate) async fn compact_session(state: &PeerHostState, args: &Value) -> Result { + let request = request_value(args); + let session_id = get_string(request, "sessionId")?; + let session_id = session_id.trim().to_string(); + if session_id.is_empty() { + return Err("session_id is required".to_string()); + } + let coordinator = openbitfun_core::agentic::coordination::get_global_coordinator() + .ok_or("Conversation coordinator is unavailable")?; + if coordinator + .get_session_manager() + .get_session(&session_id) + .is_none() + { + let storage = super::session::resolved_session_storage_path(state, request).await?; + coordinator + .restore_session_from_storage_path(&storage, &session_id) + .await + .map_err(|error| format!("Failed to restore session before compacting: {error}"))?; + } + let turn_id = coordinator + .start_manual_compaction_detached(session_id, optional_string(request, "turnId")) + .await + .map_err(|error| format!("Failed to compact session: {error}"))?; + Ok(json!({ + "success": true, + "message": "Session compaction accepted", + "turnId": turn_id, + })) +} + +/// Cancel whatever Turn the Session is running, without naming it. +/// +/// Mirrors the Desktop `cancel_session` command and its response shape. A +/// controller needs it when it does not know the active Turn id, for example +/// closing a `/btw` side question whose first events have not arrived yet. +/// Like `cancel_dialog_turn`, cancellation follows visibility, not ownership. +pub(crate) async fn cancel_session(state: &PeerHostState, args: &Value) -> Result { + let request = request_value(args); + let session_id = get_string(request, "sessionId")?; + if session_id.trim().is_empty() { + return Err("sessionId is required".to_string()); + } + let result = state + .agent_runtime + .cancel_turn(AgentTurnCancellationRequest { + session_id, + turn_id: None, + source: Some(AgentSubmissionSource::Cli), + requester_session_id: None, + reason: Some("Peer controller requested cancellation".to_string()), + wait_timeout_ms: Some(5_000), + // Tree cancellation opts out so a parent does not stop its children. + cancel_descendants: optional_bool(request, "cancelDescendants").unwrap_or(true), + }) + .await + .map_err(|error| format!("Failed to cancel session: {}", error.into_message()))?; + Ok(json!({ + "cancelled": result.requested, + "dialogTurnId": result.turn_id, + })) +} + /// Cancel a single running tool execution on this host. /// /// The controller renders Terminal cards for Turns this host owns, including diff --git a/src/apps/cli/src/peer_host/commands/goal.rs b/src/apps/cli/src/peer_host/commands/goal.rs new file mode 100644 index 0000000000..06c10fd4a8 --- /dev/null +++ b/src/apps/cli/src/peer_host/commands/goal.rs @@ -0,0 +1,191 @@ +//! Thread goal HostInvoke handlers for CLI Peer Host. +//! +//! These mirror the Desktop goal commands so a controller can activate, pause, +//! resume, edit, and clear a session goal on this host exactly as it does +//! locally. Reading a goal stays with `session::get_session_thread_goal`. + +use std::path::PathBuf; +use std::sync::Arc; + +use openbitfun_core::agentic::coordination::{get_global_coordinator, ConversationCoordinator}; +use openbitfun_core::agentic::goal_mode::ThreadGoalStatus; +use serde_json::{json, Value}; + +use crate::peer_host::args::{get_string, optional_string, request_value}; +use crate::peer_host::state::PeerHostState; + +use super::session::resolved_session_storage_path; + +fn coordinator() -> Result, String> { + get_global_coordinator().ok_or_else(|| "Conversation coordinator is unavailable".to_string()) +} + +fn required_session_id(request: &Value) -> Result { + let session_id = get_string(request, "sessionId")?.trim().to_string(); + if session_id.is_empty() { + return Err("session_id is required".to_string()); + } + Ok(session_id) +} + +/// Load the session into the coordinator when it is only persisted. +async fn ensure_session_loaded( + state: &PeerHostState, + coordinator: &ConversationCoordinator, + request: &Value, + session_id: &str, + purpose: &str, +) -> Result<(), String> { + if coordinator + .get_session_manager() + .get_session(session_id) + .is_some() + { + return Ok(()); + } + let storage = resolved_session_storage_path(state, request).await?; + coordinator + .restore_session_from_storage_path(&storage, session_id) + .await + .map(|_| ()) + .map_err(|error| format!("Failed to restore session before {purpose}: {error}")) +} + +/// The goal APIs address a session by its execution workspace. +async fn goal_workspace_path( + state: &PeerHostState, + coordinator: &ConversationCoordinator, + request: &Value, + session_id: &str, +) -> Result { + ensure_session_loaded( + state, + coordinator, + request, + session_id, + "thread goal access", + ) + .await?; + coordinator + .get_session_manager() + .get_session(session_id) + .and_then(|session| session.config.workspace_path.clone()) + .map(PathBuf::from) + .ok_or_else(|| format!("Session workspace_path is missing: {session_id}")) +} + +fn parse_goal_status(status: &str) -> Result { + match status.trim().to_ascii_lowercase().as_str() { + "active" => Ok(ThreadGoalStatus::Active), + "paused" => Ok(ThreadGoalStatus::Paused), + "blocked" => Ok(ThreadGoalStatus::Blocked), + "usagelimited" | "usage_limited" => Ok(ThreadGoalStatus::UsageLimited), + "budgetlimited" | "budget_limited" => Ok(ThreadGoalStatus::BudgetLimited), + "complete" => Ok(ThreadGoalStatus::Complete), + other => Err(format!("unsupported thread goal status: {other}")), + } +} + +pub(crate) async fn activate_session_goal( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = required_session_id(request)?; + let coordinator = coordinator()?; + ensure_session_loaded( + state, + &coordinator, + request, + &session_id, + "activating goal mode", + ) + .await?; + let user_hint = optional_string(request, "userHint") + .map(|hint| hint.trim().to_string()) + .filter(|hint| !hint.is_empty()); + let goal = coordinator + .activate_session_goal(session_id, user_hint) + .await + .map_err(|error| error.to_string())?; + Ok(json!({ "success": true, "goal": goal })) +} + +pub(crate) async fn set_session_thread_goal_status( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = required_session_id(request)?; + let status = parse_goal_status(&get_string(request, "status")?)?; + let coordinator = coordinator()?; + let workspace = goal_workspace_path(state, &coordinator, request, &session_id).await?; + let goal = coordinator + .set_thread_goal_status(&session_id, workspace.as_path(), status) + .await + .map_err(|error| error.to_string())?; + serde_json::to_value(goal).map_err(|error| error.to_string()) +} + +pub(crate) async fn update_session_thread_goal_objective( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = required_session_id(request)?; + let objective = get_string(request, "objective")?.trim().to_string(); + if objective.is_empty() { + return Err("objective is required".to_string()); + } + let coordinator = coordinator()?; + let workspace = goal_workspace_path(state, &coordinator, request, &session_id).await?; + let goal = coordinator + .update_thread_goal_objective(&session_id, workspace.as_path(), objective) + .await + .map_err(|error| error.to_string())?; + serde_json::to_value(goal).map_err(|error| error.to_string()) +} + +pub(crate) async fn clear_session_thread_goal( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = required_session_id(request)?; + let coordinator = coordinator()?; + let workspace = goal_workspace_path(state, &coordinator, request, &session_id).await?; + coordinator + .clear_thread_goal(&session_id, workspace.as_path()) + .await + .map_err(|error| error.to_string())?; + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn goal_status_accepts_the_desktop_spellings() { + for (wire, expected) in [ + ("active", ThreadGoalStatus::Active), + ("Paused", ThreadGoalStatus::Paused), + ("blocked", ThreadGoalStatus::Blocked), + ("usageLimited", ThreadGoalStatus::UsageLimited), + ("usage_limited", ThreadGoalStatus::UsageLimited), + ("budgetLimited", ThreadGoalStatus::BudgetLimited), + ("complete", ThreadGoalStatus::Complete), + ] { + assert_eq!(parse_goal_status(wire).unwrap(), expected, "{wire}"); + } + assert!(parse_goal_status("archived").is_err()); + } + + #[test] + fn blank_session_ids_are_rejected_before_any_runtime_access() { + assert_eq!( + required_session_id(&json!({ "sessionId": " " })).unwrap_err(), + "session_id is required" + ); + } +} diff --git a/src/apps/cli/src/peer_host/commands/mod.rs b/src/apps/cli/src/peer_host/commands/mod.rs index 3bc5c8b43f..8573f079f0 100644 --- a/src/apps/cli/src/peer_host/commands/mod.rs +++ b/src/apps/cli/src/peer_host/commands/mod.rs @@ -6,6 +6,7 @@ mod dialog; mod external_sources; mod filesystem; mod git; +mod goal; mod model_pools; mod models; mod permission; @@ -159,6 +160,9 @@ pub(crate) fn dispatch<'a>( "list_persisted_sessions" => Box::pin(session::list_persisted_sessions(state, args)), "list_persisted_sessions_page" => Box::pin(session::list_persisted_sessions_page(state, args)), "save_session_metadata" => Box::pin(session::save_session_metadata(state, args)), + "load_persisted_session_metadata" => { + Box::pin(session::load_persisted_session_metadata(state, args)) + } "list_persisted_sessions_count" => { Box::pin(session::list_persisted_sessions_count(state, args)) } @@ -177,8 +181,21 @@ pub(crate) fn dispatch<'a>( "delete_session" => Box::pin(session::delete_session(state, args)), "rename_session" => Box::pin(session::rename_session(state, args)), "archive_session" => Box::pin(session::archive_session(state, args)), + "unarchive_session" => Box::pin(session::unarchive_session(state, args)), + "list_archived_sessions" => Box::pin(session::list_archived_sessions(state, args)), + "get_session_lineage" => Box::pin(session::get_session_lineage(state, args)), + "fork_session" => Box::pin(session::fork_session(state, args)), + "copy_session" => Box::pin(session::copy_session(state, args)), "touch_session_activity" => Box::pin(session::touch_session_activity(state, args)), "get_session_thread_goal" => Box::pin(session::get_session_thread_goal(state, args)), + "activate_session_goal" => Box::pin(goal::activate_session_goal(state, args)), + "set_session_thread_goal_status" => { + Box::pin(goal::set_session_thread_goal_status(state, args)) + } + "update_session_thread_goal_objective" => { + Box::pin(goal::update_session_thread_goal_objective(state, args)) + } + "clear_session_thread_goal" => Box::pin(goal::clear_session_thread_goal(state, args)), "update_session_mode" => Box::pin(session::update_session_mode(state, args)), "update_session_model" => Box::pin(session::update_session_model(state, args)), "ensure_coordinator_session" => Box::pin(session::ensure_coordinator_session(state, args)), @@ -190,11 +207,20 @@ pub(crate) fn dispatch<'a>( // Snapshot / rollback "rollback_session_to_turn" => Box::pin(snapshot::rollback_session_to_turn(state, args)), "get_session_files" => Box::pin(snapshot::get_session_files(state, args)), + "get_session_file_diff_stats" => { + Box::pin(snapshot::get_session_file_diff_stats(state, args)) + } // Dialog / tools "manage_dialog_queue" => Box::pin(dialog::manage_dialog_queue(state, args)), "start_dialog_turn" => Box::pin(dialog::start_dialog_turn(state, args)), "cancel_dialog_turn" => Box::pin(dialog::cancel_dialog_turn(state, args)), + "cancel_session" => Box::pin(dialog::cancel_session(state, args)), + "compact_session" => Box::pin(dialog::compact_session(state, args)), + "interrupt_dialog_turn" => Box::pin(dialog::interrupt_dialog_turn(state, args)), + "recover_interrupted_dialog_turn" => { + Box::pin(dialog::recover_interrupted_dialog_turn(state, args)) + } "start_user_question_interaction" => Box::pin(dialog::start_user_question_interaction(state, args)), "submit_user_answers" => Box::pin(dialog::submit_user_answers(state, args)), // Per-tool interrupt. The controller renders Terminal cards for Turns @@ -331,6 +357,21 @@ pub(crate) const HANDLED_COMMANDS: &[&str] = &[ "apply_external_source_control_action_command", "archive_session", "cancel_dialog_turn", + "cancel_session", + "fork_session", + "activate_session_goal", + "set_session_thread_goal_status", + "update_session_thread_goal_objective", + "clear_session_thread_goal", + "compact_session", + "unarchive_session", + "list_archived_sessions", + "get_session_lineage", + "interrupt_dialog_turn", + "recover_interrupted_dialog_turn", + "get_session_file_diff_stats", + "load_persisted_session_metadata", + "copy_session", "cancel_tool", "check_path_exists", "choose_external_mcp_conflict_command", diff --git a/src/apps/cli/src/peer_host/commands/session.rs b/src/apps/cli/src/peer_host/commands/session.rs index f32e3af60d..dacd71e76e 100644 --- a/src/apps/cli/src/peer_host/commands/session.rs +++ b/src/apps/cli/src/peer_host/commands/session.rs @@ -16,9 +16,11 @@ use openbitfun_core::util::errors::OpenBitFunError; use openbitfun_events::{project_agentic_frontend_event, AgenticEvent}; use openbitfun_product_domains::product_search::SessionContentSearchRequest; use openbitfun_runtime_ports::{ - AgentSessionArchiveRequest, AgentSessionCreateRequest, AgentSessionDeleteRequest, - AgentSessionModeUpdateRequest, AgentSessionRenameRequest, AgentSessionUsageRequest, - AgentThreadGoalGetRequest, SessionStoragePathRequest, SessionTurnWindowRequest, + AgentSessionArchiveRequest, AgentSessionArchiveStateRequest, AgentSessionCreateRequest, + AgentSessionDeleteRequest, AgentSessionForkAtTurnRequest, AgentSessionForkRequest, + AgentSessionLineageRequest, AgentSessionModeUpdateRequest, AgentSessionRenameRequest, + AgentSessionUsageRequest, AgentThreadGoalGetRequest, SessionStoragePathRequest, + SessionTurnWindowRequest, }; use crate::diagnostics::{OUTCOME_UNKNOWN_ERROR_CODE, SESSION_IN_USE_ERROR_CODE}; @@ -374,6 +376,26 @@ pub(crate) async fn list_persisted_sessions_count( /// CLI Peer observers can acknowledge results and persist title presentation /// without projecting Session history back into the Runtime. +/// Read one session's persisted metadata, like Desktop +/// `load_persisted_session_metadata`. Direct lookups also reach hidden child +/// sessions, which list-level visibility filtering would drop. A controller +/// uses it to adopt a freshly created or forked session and to seed title +/// metadata; `null` means the host has no such session. +pub(crate) async fn load_persisted_session_metadata( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = validated_session_id(request)?; + let workspace_path = resolved_session_storage_path(state, request).await?; + let metadata = state + .compatibility + .load_persisted_session_metadata(&workspace_path, &session_id) + .await + .map_err(|error| format!("Failed to load persisted session metadata: {error}"))?; + serde_json::to_value(metadata).map_err(|error| error.to_string()) +} + pub(crate) async fn save_session_metadata( state: &PeerHostState, args: &Value, @@ -761,6 +783,143 @@ pub(crate) async fn rename_session(state: &PeerHostState, args: &Value) -> Resul Ok(Value::Null) } +/// Fork a session through the selected persisted turn, like Desktop +/// `fork_session`. A controller uses it to branch from a turn and to save a +/// temporary `/btw` side question as an independent session. +pub(crate) async fn fork_session(state: &PeerHostState, args: &Value) -> Result { + let request = request_value(args); + let source_turn_id = get_string(request, "sourceTurnId")?; + if source_turn_id.trim().is_empty() { + return Err("source_turn_id is required".to_string()); + } + branch_session(state, request, Some(source_turn_id)).await +} + +/// Copy the whole session through its latest persisted turn, like Desktop +/// `copy_session` (advertised as `whole_session_copy_v1`). +pub(crate) async fn copy_session(state: &PeerHostState, args: &Value) -> Result { + branch_session(state, request_value(args), None).await +} + +/// The Agent Runtime owns session copy semantics; this only resolves the +/// owning workspace and projects the result in Desktop's `SessionBranchResult` +/// wire shape. +async fn branch_session( + state: &PeerHostState, + request: &Value, + source_turn_id: Option, +) -> Result { + let source_session_id = get_string(request, "sourceSessionId")?; + openbitfun_agent_runtime::session_control::validate_session_id(&source_session_id)?; + let scope = ensure_session_workspace_runtime_ownership(state, request).await?; + let workspace_id = optional_string(request, "workspaceId"); + // The runtime resolves an owning workspace ID itself; the path is only the + // pre-ID upgrade input for controllers that cannot send one. + let workspace_path = if workspace_id.is_some() { + String::new() + } else { + scope.workspace_path.to_string_lossy().to_string() + }; + let result = match source_turn_id { + Some(source_turn_id) => { + state + .agent_runtime + .fork_session_at_turn(AgentSessionForkAtTurnRequest { + workspace_id, + workspace_path, + source_session_id, + source_turn_id, + remote_connection_id: scope.remote_connection_id, + remote_ssh_host: scope.remote_ssh_host, + }) + .await + } + None => { + state + .agent_runtime + .fork_session(AgentSessionForkRequest { + workspace_id, + workspace_path, + source_session_id, + remote_connection_id: scope.remote_connection_id, + remote_ssh_host: scope.remote_ssh_host, + }) + .await + } + } + .map_err(|error| format!("Failed to fork session: {}", error.into_message()))?; + Ok(json!({ + "sessionId": result.session_id, + "sessionName": result.session_name, + "agentType": result.agent_type, + })) +} + +/// Restore an archived session, like Desktop `unarchive_session`. Without it a +/// session archived from a controller could never come back on this host. +pub(crate) async fn unarchive_session( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = validated_session_id(request)?; + let scope = ensure_session_workspace_runtime_ownership(state, request).await?; + state + .agent_runtime + .set_session_archived(AgentSessionArchiveStateRequest { + workspace_id: optional_string(request, "workspaceId"), + workspace_path: scope.workspace_path.to_string_lossy().to_string(), + session_id, + archived: false, + remote_connection_id: scope.remote_connection_id, + remote_ssh_host: scope.remote_ssh_host, + }) + .await + .map_err(|error| format!("Failed to save session metadata: {}", error.into_message()))?; + Ok(Value::Null) +} + +/// The workspace's archived sessions, like Desktop `list_archived_sessions`. +pub(crate) async fn list_archived_sessions( + state: &PeerHostState, + args: &Value, +) -> Result { + use openbitfun_core::service::session::SessionStatus; + let request = request_value(args); + let workspace_path = resolved_session_storage_path(state, request).await?; + let archived: Vec<_> = state + .compatibility + .list_persisted_sessions(&workspace_path) + .await + .map_err(|error| format!("Failed to list sessions: {error}"))? + .into_iter() + .filter(|session| session.status == SessionStatus::Archived) + .collect(); + serde_json::to_value(archived).map_err(|error| error.to_string()) +} + +/// The fork/branch tree around a session, like Desktop `get_session_lineage`. +pub(crate) async fn get_session_lineage( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = validated_session_id(request)?; + let scope = session_storage_request(state, request).await?; + let lineage = state + .agent_runtime + .get_session_lineage(AgentSessionLineageRequest { + workspace_id: optional_string(request, "workspaceId"), + workspace_path: scope.workspace_path.to_string_lossy().to_string(), + anchor_session_id: session_id, + remote_connection_id: scope.remote_connection_id, + remote_ssh_host: scope.remote_ssh_host, + }) + .await + .map_err(|error| format!("Failed to load session lineage: {}", error.into_message()))?; + serde_json::to_value(lineage).map_err(|error| error.to_string()) +} + pub(crate) async fn archive_session(state: &PeerHostState, args: &Value) -> Result { let request = request_value(args); let session_id = validated_session_id(request)?; diff --git a/src/apps/cli/src/peer_host/commands/snapshot.rs b/src/apps/cli/src/peer_host/commands/snapshot.rs index da28bcbedb..02b39820ce 100644 --- a/src/apps/cli/src/peer_host/commands/snapshot.rs +++ b/src/apps/cli/src/peer_host/commands/snapshot.rs @@ -6,7 +6,8 @@ use serde_json::{json, Value}; use openbitfun_core::service::workspace::{WorkspaceInfo, WorkspaceKind}; use openbitfun_runtime_ports::{ - AgentSessionRollbackToTurnRequest, LocalWorkspaceSnapshotPort, + AgentSessionRollbackToTurnRequest, LocalWorkspaceSnapshotFileDiffStats, + LocalWorkspaceSnapshotFileRequest, LocalWorkspaceSnapshotPort, LocalWorkspaceSnapshotSessionRequest, LocalWorkspaceSnapshotStats, PortError, PortErrorKind, }; @@ -136,6 +137,65 @@ pub(crate) async fn get_session_files( .collect::>())) } +/// Desktop's `SessionFileDiffStats` wire shape, read by the file badges. +fn file_diff_stats_to_json(stats: LocalWorkspaceSnapshotFileDiffStats) -> Value { + json!({ + "filePath": stats.file_path, + "linesAdded": stats.lines_added, + "linesRemoved": stats.lines_removed, + "approximate": stats.approximate, + "changeKind": stats.change_kind, + }) +} + +pub(super) async fn local_snapshot_file_diff_stats( + port: &dyn LocalWorkspaceSnapshotPort, + request: LocalWorkspaceSnapshotFileRequest, +) -> Result { + port.get_session_file_diff_stats(request) + .await + .map(file_diff_stats_to_json) + .map_err(|error| { + format!( + "Failed to get session file diff stats: {}", + snapshot_compatibility_error(error) + ) + }) +} + +/// Line-level change of one session file, like Desktop +/// `get_session_file_diff_stats`. A controller renders it as the file badges +/// and toolbars of the session's changed files. +pub(crate) async fn get_session_file_diff_stats( + state: &PeerHostState, + args: &Value, +) -> Result { + let request = request_value(args); + let session_id = get_string(request, "sessionId")?; + let file_path = get_string(request, "filePath")?; + let workspace = resolve_snapshot_workspace(state, request).await?; + + openbitfun_agent_runtime::session_control::validate_session_id(&session_id)?; + require_local_snapshot_workspace(&workspace)?; + let scope = ensure_session_workspace_runtime_ownership(state, request).await?; + let storage_path = resolved_session_storage_scope(state, scope).await?; + let read = state + .compatibility + .begin_persisted_session_read(&storage_path, &session_id) + .await + .map_err(|error| format!("Failed to open a consistent snapshot view: {error}"))?; + local_snapshot_file_diff_stats( + state.local_workspace_snapshot.as_ref(), + LocalWorkspaceSnapshotFileRequest { + workspace_id: workspace.id, + session_id, + file_path, + max_turn_exclusive: read.visible_turn_end(), + }, + ) + .await +} + pub(crate) async fn rollback_session_to_turn( state: &PeerHostState, args: &Value, @@ -188,6 +248,7 @@ mod tests { use std::sync::Mutex; use openbitfun_runtime_ports::{ + LocalWorkspaceSnapshotFileDiffStats, LocalWorkspaceSnapshotFileRequest, LocalWorkspaceSnapshotPort, LocalWorkspaceSnapshotSessionRequest, LocalWorkspaceSnapshotStats, LocalWorkspaceSnapshotTurnRequest, PortError, PortErrorKind, PortResult, @@ -195,7 +256,7 @@ mod tests { use serde_json::json; use super::{ - local_snapshot_session_files, local_snapshot_session_stats, + local_snapshot_file_diff_stats, local_snapshot_session_files, local_snapshot_session_stats, require_complete_rollback_workspace, require_local_snapshot_workspace, snapshot_compatibility_error, }; @@ -206,6 +267,7 @@ mod tests { stats_calls: AtomicUsize, file_request: Mutex>, stats_request: Mutex>, + diff_request: Mutex>, } #[async_trait::async_trait] @@ -238,6 +300,21 @@ mod tests { }) } + async fn get_session_file_diff_stats( + &self, + request: LocalWorkspaceSnapshotFileRequest, + ) -> PortResult { + let file_path = request.file_path.clone(); + *self.diff_request.lock().expect("diff request lock") = Some(request); + Ok(LocalWorkspaceSnapshotFileDiffStats { + file_path, + lines_added: 4, + lines_removed: 1, + approximate: false, + change_kind: "modify".to_string(), + }) + } + async fn rollback_workspace_files_to_turn( &self, _request: LocalWorkspaceSnapshotTurnRequest, @@ -246,6 +323,35 @@ mod tests { } } + #[tokio::test] + async fn file_diff_stats_keep_desktop_wire_shape_and_visible_turn_end() { + let port = RecordingSnapshotPort::default(); + let stats = local_snapshot_file_diff_stats( + &port, + LocalWorkspaceSnapshotFileRequest { + workspace_id: "workspace".to_string(), + session_id: "session-1".to_string(), + file_path: "/repo/src/main.rs".to_string(), + max_turn_exclusive: Some(3), + }, + ) + .await + .unwrap(); + assert_eq!( + stats, + json!({ + "filePath": "/repo/src/main.rs", + "linesAdded": 4, + "linesRemoved": 1, + "approximate": false, + "changeKind": "modify", + }) + ); + let request = port.diff_request.lock().unwrap().clone().unwrap(); + assert_eq!(request.max_turn_exclusive, Some(3)); + assert_eq!(request.workspace_id, "workspace"); + } + #[tokio::test] async fn snapshot_kind_is_authoritative_without_transport_inference() { use openbitfun_core::service::workspace::WorkspaceInfoRuntimeExt; diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index 313c527d9d..a5e83d97f3 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -34,8 +34,9 @@ use openbitfun_product_domains::product_search::{ #[cfg(feature = "product-search")] use openbitfun_runtime_ports::ProductSearchPort; use openbitfun_runtime_ports::{ - AgentContextReloadPort, AgentContextReloadRequest, ClockPort, LocalWorkspaceSnapshotPort, - LocalWorkspaceSnapshotSessionRequest, LocalWorkspaceSnapshotStats, + AgentContextReloadPort, AgentContextReloadRequest, ClockPort, + LocalWorkspaceSnapshotFileDiffStats, LocalWorkspaceSnapshotFileRequest, + LocalWorkspaceSnapshotPort, LocalWorkspaceSnapshotSessionRequest, LocalWorkspaceSnapshotStats, LocalWorkspaceSnapshotTurnRequest, PortError, PortErrorKind, PortResult, RuntimeServiceCapability, RuntimeServicePort, SessionStoragePathRequest, SessionStorePort, SessionTranscriptRequest, SessionTurnWindowRequest, SessionViewRestoreTiming, @@ -755,6 +756,29 @@ impl LocalWorkspaceSnapshotPort for CoreLocalWorkspaceSnapshot { }) } + async fn get_session_file_diff_stats( + &self, + request: LocalWorkspaceSnapshotFileRequest, + ) -> PortResult { + validate_persisted_session_id(&request.session_id).map_err(runtime_port_error)?; + let manager = local_snapshot_manager_for_view(&request.workspace_id).await?; + let stats = manager + .get_session_file_diff_stats_before( + &request.session_id, + &request.file_path, + request.max_turn_exclusive, + ) + .await + .map_err(snapshot_port_error)?; + Ok(LocalWorkspaceSnapshotFileDiffStats { + file_path: stats.file_path, + lines_added: stats.lines_added, + lines_removed: stats.lines_removed, + approximate: stats.approximate, + change_kind: stats.change_kind, + }) + } + async fn rollback_workspace_files_to_turn( &self, request: LocalWorkspaceSnapshotTurnRequest, diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 63db5cbc41..625f79e1a4 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:67a20e107dd93ffd", + "digest": "fnv1a64:93880f665967283d", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -55,6 +55,8 @@ "workspace_html_preview_v1", "workspace_latex_preview_v1", "whole_session_copy_v1", + "session_fork_v1", + "recoverable_interruption_v1", "session_trajectory_v1", "session_reference_browse_v1", "user_question_response", @@ -111,6 +113,8 @@ "workspace_html_preview_v1", "workspace_latex_preview_v1", "whole_session_copy_v1", + "session_fork_v1", + "recoverable_interruption_v1", "session_trajectory_v1", "session_reference_browse_v1", "user_question_response", @@ -141,6 +145,9 @@ "remote_connect_control_v1", "cancel_tool", "tool_catalog", + "whole_session_copy_v1", + "session_fork_v1", + "recoverable_interruption_v1", "session_trajectory_v1", "chat_mcp_catalog_v1", "workspace_icon_v1", @@ -438,8 +445,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -805,8 +811,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -818,7 +823,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -990,8 +995,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -1025,8 +1029,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -1289,8 +1292,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -2305,8 +2307,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -3237,8 +3238,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -3271,8 +3271,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -3434,7 +3433,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -3446,7 +3445,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -4193,8 +4192,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -4240,8 +4238,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -4459,7 +4456,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -4471,7 +4468,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -4553,8 +4550,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -4622,7 +4618,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -4634,7 +4630,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -5702,8 +5698,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -5738,7 +5733,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -5750,7 +5745,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -7326,8 +7321,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -7351,7 +7345,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -7923,7 +7917,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -7935,7 +7929,7 @@ }, "cliPeer": { "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "reason": "the CLI peer host does not manage subscription account sign-in" } }, { @@ -8274,8 +8268,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { @@ -8412,8 +8405,7 @@ "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index e3840beedc..d738b3f6d3 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -113,6 +113,12 @@ pub enum PeerHostCapability { WorkspaceLatexPreviewV1, /// `copy_session` copies a whole session without a caller-selected turn id. WholeSessionCopyV1, + /// `fork_session` branches a session at a persisted turn. Every Desktop host + /// has implemented it; CLI hosts gained it together with this key. + SessionForkV1, + /// `interrupt_dialog_turn` stops a Turn so `recover_interrupted_dialog_turn` + /// can resume it. Without this key a controller uses hard cancellation. + RecoverableInterruptionV1, /// Bounded session trajectory summaries and host-side body search. SessionTrajectoryV1, /// `search_referenceable_sessions` accepts an omitted query to browse. @@ -184,6 +190,8 @@ impl PeerHostCapability { Self::WorkspaceHtmlPreviewV1, Self::WorkspaceLatexPreviewV1, Self::WholeSessionCopyV1, + Self::SessionForkV1, + Self::RecoverableInterruptionV1, Self::SessionTrajectoryV1, Self::SessionReferenceBrowseV1, Self::UserQuestionResponse, @@ -245,6 +253,8 @@ impl PeerHostCapability { Self::SessionTrajectoryV1 => "session_trajectory_v1", Self::SessionReferenceBrowseV1 => "session_reference_browse_v1", Self::WholeSessionCopyV1 => "whole_session_copy_v1", + Self::SessionForkV1 => "session_fork_v1", + Self::RecoverableInterruptionV1 => "recoverable_interruption_v1", Self::UserQuestionResponse => "user_question_response", Self::UserQuestionInteractionV1 => "user_question_interaction_v1", Self::SshNoneAuthV1 => "ssh_none_auth_v1", @@ -309,6 +319,8 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::WorkspaceHtmlPreviewV1, PeerHostCapability::WorkspaceLatexPreviewV1, PeerHostCapability::WholeSessionCopyV1, + PeerHostCapability::SessionForkV1, + PeerHostCapability::RecoverableInterruptionV1, PeerHostCapability::SessionTrajectoryV1, PeerHostCapability::SessionReferenceBrowseV1, PeerHostCapability::UserQuestionResponse, @@ -342,6 +354,9 @@ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::RemoteConnectControlV1, PeerHostCapability::CancelTool, PeerHostCapability::ToolCatalog, + PeerHostCapability::WholeSessionCopyV1, + PeerHostCapability::SessionForkV1, + PeerHostCapability::RecoverableInterruptionV1, PeerHostCapability::SessionTrajectoryV1, PeerHostCapability::ChatMcpCatalogV1, PeerHostCapability::WorkspaceIconV1, @@ -466,7 +481,10 @@ mod tests { Some(&Value::Bool(true)) ); assert!(!cli.contains_key("product_control_presentation_v1")); - assert!(!cli.contains_key("whole_session_copy_v1")); + // CLI hosts gained `copy_session` and `fork_session` together. + assert_eq!(cli["whole_session_copy_v1"], true); + assert_eq!(cli["session_fork_v1"], true); + assert_eq!(cli["recoverable_interruption_v1"], true); assert!(!cli.contains_key("review_platform_v1")); assert!(!cli.contains_key("host_terminal_workspace_v1")); assert_eq!( diff --git a/src/crates/contracts/product-domains/src/remote_surface/mod.rs b/src/crates/contracts/product-domains/src/remote_surface/mod.rs index 47c1428ea3..ef4c2a7d58 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/mod.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/mod.rs @@ -803,18 +803,19 @@ mod tests { } #[test] - fn whole_session_copy_runs_on_desktop_and_is_explicitly_unsupported_on_cli() { - let copy = operation("copy_session").unwrap(); - assert_eq!(copy.remote_workspace, RemoteWorkspaceStance::Routed); - assert_eq!(copy.peer, PeerStance::Proxied); - assert_eq!( - peer_host_verdict("copy_session", PeerHostKind::Desktop), - PeerHostVerdict::Execute - ); - assert!(matches!( - peer_host_verdict("copy_session", PeerHostKind::Cli), - PeerHostVerdict::Refuse(PeerRefusal::HostUnsupported { .. }) - )); + fn session_fork_and_whole_session_copy_run_on_both_peer_hosts() { + for command in ["copy_session", "fork_session"] { + let operation = operation(command).unwrap(); + assert_eq!(operation.remote_workspace, RemoteWorkspaceStance::Routed); + assert_eq!(operation.peer, PeerStance::Proxied); + for host in [PeerHostKind::Desktop, PeerHostKind::Cli] { + assert_eq!( + peer_host_verdict(command, host), + PeerHostVerdict::Execute, + "{command} must run on {host:?}" + ); + } + } } #[test] diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index a7e2635427..a26f322eb7 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -72,6 +72,11 @@ pub(super) const CLI_NO_REMOTE_WORKSPACE_UI: HostSupport = HostSupport::Unsuppor pub(super) const CLI_NO_ACP_CLIENT_HOST: HostSupport = HostSupport::Unsupported { reason: "ACP agents cannot be managed or launched from a controller on the CLI peer host yet; use the `acp clients` commands on that device", }; +/// Subscription sign-in is a Desktop account surface; no CLI version offers it, +/// so the controller reports it as unavailable rather than "update the host". +pub(super) const CLI_NO_SUBSCRIPTION_ACCOUNTS: HostSupport = HostSupport::Unsupported { + reason: "the CLI peer host does not manage subscription account sign-in", +}; pub(super) const CLI_NO_DIAGNOSTICS_BUNDLE: HostSupport = HostSupport::Unsupported { reason: "the CLI peer host does not export diagnostics bundles; collect its log directory on that device instead", }; @@ -113,7 +118,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("account_unsubscribe_session", Agnostic, ControllerLocal, REFUSED), op("account_update_device_alias", Agnostic, ControllerLocal, REFUSED), op("acknowledge_external_ecosystems_command", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), - op("activate_session_goal", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("activate_session_goal", Unaudited, Proxied, HANDLED), op("add_skill", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("append_flow_chat_diagnostics", LocalOnly, ControllerLocal, REFUSED), op("apply_external_hook_import_command", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), @@ -144,8 +149,8 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("cancel_insights_generation", LocalOnly, ControllerLocal, REFUSED), op("cancel_mcp_remote_oauth", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("cancel_search", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), - op("cancel_session", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("cancel_subscription_login", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("cancel_session", Unaudited, Proxied, HANDLED), + op("cancel_subscription_login", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), op("cancel_tool", Agnostic, Proxied, HANDLED), op("cancel_transfer", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("canonicalize_agent_profile_configs", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -160,10 +165,10 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("clear_decision_model_credential", Agnostic, Proxied, HANDLED), op("clear_mcp_remote_auth", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("clear_project_permission_grants", Agnostic, Proxied, HANDLED), - op("clear_session_thread_goal", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("clear_session_thread_goal", Unaudited, Proxied, HANDLED), op("clear_web_search_credential", Agnostic, Proxied, HANDLED), op("close_workspace", Routed, Proxied, CLI_NOT_IMPLEMENTED), - op("compact_session", Routed, Proxied, CLI_NOT_IMPLEMENTED), + op("compact_session", Routed, Proxied, HANDLED), op("compile_workspace_latex", Routed, Proxied, CLI_NOT_IMPLEMENTED), op("compress_path", Routed, Proxied, CLI_NOT_IMPLEMENTED), op("compute_diff", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), @@ -185,7 +190,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("confirm_frontend_update", LocalOnly, ControllerLocal, REFUSED), op("control_background_command", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("control_deep_review_queue", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("copy_session", Routed, Proxied, CLI_NOT_IMPLEMENTED), + op("copy_session", Routed, Proxied, HANDLED), op("create_acp_flow_session", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("create_assistant_workspace", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("create_control_conversation", Agnostic, Proxied, HANDLED), @@ -272,7 +277,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("export_local_file_to_path", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), op("export_session_transcript", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("fetch_mcp_app_resource", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("fork_session", Routed, Proxied, CLI_NOT_IMPLEMENTED), + op("fork_session", Routed, Proxied, HANDLED), op("frontend_update_candidate_failed", LocalOnly, ControllerLocal, REFUSED), op("frontend_update_candidate_ready", LocalOnly, ControllerLocal, REFUSED), op("gen_ui_provider_call", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), @@ -356,10 +361,10 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("get_recent_workspaces", Agnostic, Proxied, HANDLED), op("get_runtime_capabilities", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_runtime_logging_info", Unaudited, Proxied, HANDLED), - op("get_session_file_diff_stats", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("get_session_file_diff_stats", Unaudited, Proxied, HANDLED), op("get_session_files", Unaudited, Proxied, HANDLED), op("get_session_interaction_mailbox", Agnostic, Proxied, HANDLED), - op("get_session_lineage", Routed, Proxied, CLI_NOT_IMPLEMENTED), + op("get_session_lineage", Routed, Proxied, HANDLED), op("get_session_model_target", Agnostic, Proxied, HANDLED), op("get_session_operations", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_session_permission_mode", Routed, Proxied, HANDLED), @@ -373,8 +378,8 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("get_startup_native_trace", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("get_statistics", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("get_subagent_detail", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("get_subscription_account_quota", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), - op("get_subscription_login_status", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("get_subscription_account_quota", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), + op("get_subscription_login_status", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), op("get_system_info", Agnostic, Proxied, HANDLED), op("get_token_usage_statistics", Agnostic, Proxied, HANDLED), op("get_tool_info", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -438,11 +443,11 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("install_acp_client_cli", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("install_pending_update", Agnostic, ControllerLocal, REFUSED), op("install_update", Agnostic, ControllerLocal, REFUSED), - op("interrupt_dialog_turn", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("interrupt_dialog_turn", LocalOnly, Proxied, HANDLED), op("list_agent_companion_pets", Unaudited, ControllerLocal, REFUSED), op("list_agent_tool_names", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("list_ai_models_by_config", Unaudited, Proxied, HANDLED), - op("list_archived_sessions", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("list_archived_sessions", Unaudited, Proxied, HANDLED), op("list_background_command_activities", Unaudited, Proxied, SOFT_EMPTY_BACKGROUND_COMMANDS), op("list_cron_jobs", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("list_directory_files", Routed, Proxied, HANDLED), @@ -461,22 +466,22 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("list_sessions", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("list_skill_market", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("list_subagents", Routed, Proxied, HANDLED), - op("list_subscription_account_instances", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), - op("list_subscription_accounts", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("list_subscription_account_instances", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), + op("list_subscription_accounts", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), op("list_visible_subagents", Routed, Proxied, HANDLED), op("load_acp_json_config", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("load_agent_companion_pet_spritesheet", LocalOnly, ControllerLocal, REFUSED), op("load_git_repo_history", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("load_insights_report", LocalOnly, ControllerLocal, REFUSED), op("load_mcp_json_config", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("load_persisted_session_metadata", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("load_persisted_session_metadata", Unaudited, Proxied, HANDLED), op("load_session_event_backfill", Agnostic, Proxied, HANDLED), op("load_session_trajectory", Routed, Proxied, HANDLED), op("load_session_turn_window", Routed, Proxied, HANDLED), op("load_session_turns", Unaudited, Proxied, HANDLED), op("local_file_download", Agnostic, ControllerLocal, REFUSED), - op("logout_subscription_account", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), - op("logout_subscription_account_instance", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("logout_subscription_account", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), + op("logout_subscription_account_instance", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), op("manage_dialog_queue", Routed, Proxied, HANDLED), op("mark_miniapp_web_surface_ready", Agnostic, ControllerLocal, REFUSED), op("mark_openbitfun_control_surface_ready", Agnostic, ControllerLocal, REFUSED), @@ -566,11 +571,11 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("read_file_content", Routed, Proxied, HANDLED), op("read_mcp_resource", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("record_voice_exchange", Agnostic, Proxied, HANDLED), - op("recover_interrupted_dialog_turn", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("recover_interrupted_dialog_turn", LocalOnly, Proxied, HANDLED), op("refresh_model_client", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("refresh_models_dev_catalog_now", LocalOnly, Proxied, HANDLED), - op("refresh_subscription_account", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), - op("refresh_subscription_account_instance", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("refresh_subscription_account", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), + op("refresh_subscription_account_instance", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), op("reject_file", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("reject_operation", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("reload_config", Unaudited, Proxied, HANDLED), @@ -704,9 +709,9 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("set_prevent_sleep_enabled", LocalOnly, ControllerLocal, REFUSED), op("set_primary_assistant_workspace", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("set_session_memory_mode", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("set_session_thread_goal_status", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("set_session_thread_goal_status", Unaudited, Proxied, HANDLED), op("set_subagent_timeout", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), - op("set_subscription_account_enabled", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("set_subscription_account_enabled", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), op("set_tray_unread_count", LocalOnly, ControllerLocal, REFUSED), op("set_workspace_icon", Agnostic, Proxied, HANDLED), op("show_agent_companion_desktop_pet", LocalOnly, ControllerLocal, REFUSED), @@ -754,8 +759,8 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("start_mcp_server", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("start_search_file_contents_stream", Routed, Proxied, CLI_NOT_IMPLEMENTED), op("start_search_filenames_stream", Routed, Proxied, CLI_NOT_IMPLEMENTED), - op("start_subscription_account_login", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), - op("start_subscription_login", LocalOnly, Proxied, CLI_NOT_IMPLEMENTED), + op("start_subscription_account_login", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), + op("start_subscription_login", LocalOnly, Proxied, CLI_NO_SUBSCRIPTION_ACCOUNTS), op("start_user_question_interaction", Agnostic, Proxied, HANDLED), op("startup_window_control", LocalOnly, ControllerLocal, REFUSED), op("steer_dialog_turn", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), @@ -785,7 +790,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("test_image_generation_service", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("toggle_main_window_fullscreen", LocalOnly, ControllerLocal, REFUSED), op("touch_session_activity", Unaudited, Proxied, HANDLED), - op("unarchive_session", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("unarchive_session", Unaudited, Proxied, HANDLED), op("update_active_turn_permission_mode", Routed, Proxied, HANDLED), op("update_app_status", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("update_cron_job", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -797,7 +802,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("update_session_model", Unaudited, Proxied, HANDLED), op("update_session_model_target", Agnostic, Proxied, HANDLED), op("update_session_permission_mode", Routed, Proxied, HANDLED), - op("update_session_thread_goal_objective", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("update_session_thread_goal_objective", Unaudited, Proxied, HANDLED), op("update_session_title", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("update_subagent", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("update_subagent_config", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), diff --git a/src/crates/contracts/runtime-ports/src/lib.rs b/src/crates/contracts/runtime-ports/src/lib.rs index 2abb7e34a6..f1f2e8a1a8 100644 --- a/src/crates/contracts/runtime-ports/src/lib.rs +++ b/src/crates/contracts/runtime-ports/src/lib.rs @@ -33,6 +33,7 @@ mod web_search; pub use hook_function::*; #[cfg(feature = "workspace-ports")] pub use local_workspace_snapshot::{ + LocalWorkspaceSnapshotFileDiffStats, LocalWorkspaceSnapshotFileRequest, LocalWorkspaceSnapshotPort, LocalWorkspaceSnapshotSessionRequest, LocalWorkspaceSnapshotStats, LocalWorkspaceSnapshotTurnRequest, }; diff --git a/src/crates/contracts/runtime-ports/src/local_workspace_snapshot.rs b/src/crates/contracts/runtime-ports/src/local_workspace_snapshot.rs index 9106775349..2ebff6b734 100644 --- a/src/crates/contracts/runtime-ports/src/local_workspace_snapshot.rs +++ b/src/crates/contracts/runtime-ports/src/local_workspace_snapshot.rs @@ -32,6 +32,27 @@ pub struct LocalWorkspaceSnapshotStats { pub total_changes: usize, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LocalWorkspaceSnapshotFileRequest { + pub workspace_id: String, + pub session_id: String, + pub file_path: String, + /// Exclusive visible turn end supplied by the session lifecycle owner. + pub max_turn_exclusive: Option, +} + +/// Line-level change of one session file, without its contents. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LocalWorkspaceSnapshotFileDiffStats { + pub file_path: String, + pub lines_added: usize, + pub lines_removed: usize, + /// Derived from per-operation summaries instead of a full baseline diff. + pub approximate: bool, + /// `create`, `modify`, or `delete`. + pub change_kind: String, +} + #[async_trait::async_trait] pub trait LocalWorkspaceSnapshotPort: Send + Sync { /// Prepares the existing local snapshot owner for a workspace. @@ -47,6 +68,11 @@ pub trait LocalWorkspaceSnapshotPort: Send + Sync { request: LocalWorkspaceSnapshotSessionRequest, ) -> PortResult; + async fn get_session_file_diff_stats( + &self, + request: LocalWorkspaceSnapshotFileRequest, + ) -> PortResult; + /// Restores only workspace files. Conversation-history mutation remains a /// separate host/runtime-owner operation. async fn rollback_workspace_files_to_turn( diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 3a9455290d..7ed55be916 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:67a20e107dd93ffd" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:93880f665967283d" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -210,6 +210,8 @@ export const PEER_HOST_CAPABILITY_IDS = [ "workspace_html_preview_v1", "workspace_latex_preview_v1", "whole_session_copy_v1", + "session_fork_v1", + "recoverable_interruption_v1", "session_trajectory_v1", "session_reference_browse_v1", "user_question_response", @@ -273,6 +275,8 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "workspace_html_preview_v1", "workspace_latex_preview_v1", "whole_session_copy_v1", + "session_fork_v1", + "recoverable_interruption_v1", "session_trajectory_v1", "session_reference_browse_v1", "user_question_response", @@ -303,6 +307,9 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "remote_connect_control_v1", "cancel_tool", "tool_catalog", + "whole_session_copy_v1", + "session_fork_v1", + "recoverable_interruption_v1", "session_trajectory_v1", "chat_mcp_catalog_v1", "workspace_icon_v1", From 73e1ea40d08b833d91bec480656d8fa61acb1d67 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Wed, 18 Nov 2026 20:25:31 +0800 Subject: [PATCH 3/7] fix(web-ui): Negotiate peer fork, Stop, and side question close - Hide turn fork and side question "save as fork" on CLI hosts that do not advertise session_fork_v1 instead of failing them. - Interrupt recoverably on Stop when the rendered host advertises recoverable_interruption_v1; older hosts keep hard cancellation. - Close a side question with btw_cancel when an older CLI host refuses cancel_session, then delete it as before. - Show subscription accounts as unavailable on hosts that refuse them rather than offering a retry that cannot succeed. --- .../settings/pages/ai/ModelSettingsPage.tsx | 21 ++++++++++-- .../modern/ForkSessionButton.test.tsx | 26 +++++++++++++++ .../components/modern/ForkSessionButton.tsx | 10 +++++- .../services/BtwSessionLifecycle.test.ts | 26 +++++++++++++-- .../flow_chat/services/BtwSessionLifecycle.ts | 25 +++++++++++++-- .../state-machine/SessionStateMachine.test.ts | 23 ++++++++++++- .../state-machine/SessionStateMachine.ts | 6 ++-- .../api/adapters/peer-device-adapter.ts | 3 ++ .../peer-device/PeerConnectionManager.ts | 8 +++++ .../src/infrastructure/peer-device/README.md | 20 +++++++++++- .../peerCapabilityResolution.test.ts | 22 +++++++++++++ .../peer-device/peerCapabilityResolution.ts | 23 +++++++++++++ .../peer-device/renderedHostCapabilities.ts | 32 +++++++++++++++++++ 13 files changed, 232 insertions(+), 13 deletions(-) create mode 100644 src/web-ui/src/infrastructure/peer-device/renderedHostCapabilities.ts diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx index 8f4680b4b1..38b2bec530 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx @@ -120,6 +120,7 @@ import { i18nService, useI18n } from '@/infrastructure/i18n'; import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; import { ResponsesRequestSettingsFields } from '@/infrastructure/config/components/ResponsesRequestSettingsFields'; import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; +import { peerHostRefusalMessage } from '@/infrastructure/peer-device/peerHostRefusal'; import { canEditAccountPoolsOnSurface, canEditChannelRoutingOnSurface, canQuerySubscriptionQuotaOnSurface, canQueryModelQuotaOnSurface, canQueryGrokQuotaOnSurface } from '@/infrastructure/peer-device/peerCapabilityResolution'; import { isPeerDeviceModeActive } from '@/infrastructure/peer-device/peerModeFlag'; import { isTauriRuntime } from '@/infrastructure/runtime'; @@ -471,6 +472,8 @@ const ModelSettingsPage: React.FC = () => { const [routerSettingsScope, setRouterSettingsScope] = useState | null>(null); const [routerAvailability, setRouterAvailability] = useState<{ surfaceKey: string; status: ModelRoutingStatus } | null>(null); const [subscriptionLoadError, setSubscriptionLoadError] = useState(false); + /** Set when the rendered peer host does not offer subscription accounts at all. */ + const [subscriptionUnavailable, setSubscriptionUnavailable] = useState(null); const [isConfigLoading, setIsConfigLoading] = useState(!modelSeed.loaded); const [configLoadError, setConfigLoadError] = useState(false); const [proxyLoadState, setProxyLoadState] = useState<'loading' | 'ready' | 'error'>(proxySeed.loaded ? 'ready' : 'loading'); @@ -906,6 +909,7 @@ const ModelSettingsPage: React.FC = () => { const isCurrent = () => scope.isCurrent() && requestId === subscriptionAccountsReadRef.current; setIsLoadingSubscriptions(true); setSubscriptionLoadError(false); + setSubscriptionUnavailable(null); try { const items = await aiApi.listSubscriptionAccounts(); if (!isCurrent()) return; @@ -931,12 +935,22 @@ const ModelSettingsPage: React.FC = () => { } } catch (e) { if (!isCurrent()) return; + // A host that does not offer subscription accounts is not a transient + // failure: say so instead of offering a retry that cannot succeed. + const unavailable = peerHostRefusalMessage(e, t); + if (unavailable) { + setSubscriptionAccounts([]); + setAccountInstances([]); + setSubscriptionUnavailable(unavailable); + log.debug('Subscription accounts are unavailable on this host', { error: String(e) }); + return; + } setSubscriptionLoadError(true); log.warn('list_subscription_accounts failed', { error: String(e) }); } finally { if (isCurrent()) setIsLoadingSubscriptions(false); } - }, []); + }, [t]); useEffect(() => { const refresh = () => { void refreshSubscriptionAccounts(); }; @@ -4448,8 +4462,11 @@ const ModelSettingsPage: React.FC = () => { void refreshSubscriptionAccounts()} /> )} + {subscriptionUnavailable && !isLoadingSubscriptions && ( +