From 0c5173d25b88c72566f3963dabff6500f52cbbea Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 09:17:52 +0800 Subject: [PATCH 1/3] fix(remote): default IM bot turns to read --- .../src/agentic/coordination/coordinator.rs | 3 + .../remote_connect/bot/command_router.rs | 44 ++++- .../service/remote_connect/remote_server.rs | 1 + .../services-core/src/session/metadata.rs | 154 +++++++++++++++--- .../src/remote_connect.rs | 15 +- .../tests/remote_connect_contracts.rs | 32 ++++ .../src/flow_chat/store/FlowChatStore.test.ts | 22 +++ .../src/flow_chat/store/FlowChatStore.ts | 5 + .../store/sessionActivityStore.test.ts | 29 ++++ .../flow_chat/store/sessionActivityStore.ts | 8 + 10 files changed, 284 insertions(+), 29 deletions(-) diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index 9bfd4cff03..ae428eefca 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -7240,6 +7240,9 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet default_permission_mode_from_global_config().await, ); let mut metadata = Self::ensure_user_message_metadata_object(user_message_metadata.take()); + // Stamp the admitted ingress so live observers and persisted receipts + // agree even when no desktop client is connected. + metadata["submissionSource"] = serde_json::json!(submission_policy.trigger_source); if submission_policy.trigger_source != openbitfun_runtime_ports::DialogTriggerSource::ScheduledJob { diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs index 90ab439a46..8d866a036e 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs @@ -3764,6 +3764,7 @@ async fn execute_remote_forward( submission_finished: Option>, ) -> ForwardedTurnResult { use openbitfun_services_integrations::remote_connect::bot::remote_turn::observe_turn; + use openbitfun_services_integrations::remote_connect::REMOTE_CAPABILITY_BOT_READ_RECEIPTS_V1; let s = strings_for(current_bot_language().await); let target = forward.remote_target.as_ref().unwrap(); let current = || fence.is_lifecycle_current() && fence.identity_epoch() == epoch; @@ -3775,14 +3776,30 @@ async fn execute_remote_forward( if !current() { return empty(); } + let mut command = serde_json::json!({ + "cmd":"send_message", "session_id":target.session_id, + "content":forward.content, "turn_id":forward.turn_id, + "image_contexts":forward.image_contexts, + }); + // Old hosts keep accepting messages with their existing receipt behavior. + // Only advertise bot ingress after the target confirms it can honor it. + if let Ok(info) = target + .rpc(serde_json::json!({"cmd":"get_workspace_info"})) + .await + { + if info["capabilities"].as_array().is_some_and(|capabilities| { + capabilities.iter().any(|capability| { + capability.as_str() == Some(REMOTE_CAPABILITY_BOT_READ_RECEIPTS_V1) + }) + }) { + command["source"] = serde_json::json!("bot"); + } + } + if !current() { + return empty(); + } // Submission is never retried blindly: older peers need not deduplicate. - let sent = target - .rpc(serde_json::json!({ - "cmd":"send_message", "session_id":target.session_id, - "content":forward.content, "turn_id":forward.turn_id, - "image_contexts":forward.image_contexts, - })) - .await; + let sent = target.rpc(command).await; drop(submission_finished); if !current() { return empty(); @@ -5109,7 +5126,7 @@ mod handle_chat_tests { } } "get_workspace_info" => serde_json::json!({"resp":"workspace_info", "capabilities": - if supports_interaction { vec!["user_question_interaction_v1", "session_attachments_v1"] } else { vec![] } + if supports_interaction { vec!["user_question_interaction_v1", "session_attachments_v1", "bot_read_receipts_v1"] } else { vec![] } }), "store_session_attachment" => { assert!(supports_interaction); @@ -5273,6 +5290,17 @@ mod handle_chat_tests { 1 ); let observed = calls.lock().unwrap(); + assert_eq!( + observed + .iter() + .find(|call| call["cmd"] == "send_message") + .unwrap()["source"], + if supports_interaction { + serde_json::json!("bot") + } else { + Value::Null + } + ); let activity = observed .iter() .position(|call| call["cmd"] == "start_question_interaction"); diff --git a/src/crates/assembly/core/src/service/remote_connect/remote_server.rs b/src/crates/assembly/core/src/service/remote_connect/remote_server.rs index 086442fb58..aac6af9534 100644 --- a/src/crates/assembly/core/src/service/remote_connect/remote_server.rs +++ b/src/crates/assembly/core/src/service/remote_connect/remote_server.rs @@ -642,6 +642,7 @@ mod tests { let command = RemoteCommand::SendMessage { session_id: "session-1".to_string(), content: "hello".to_string(), + source: None, display_content: None, turn_id: Some("harmony-turn-1".to_string()), agent_type: Some("code".to_string()), diff --git a/src/crates/services/services-core/src/session/metadata.rs b/src/crates/services/services-core/src/session/metadata.rs index 8513bc7a7f..8e3b0a0bee 100644 --- a/src/crates/services/services-core/src/session/metadata.rs +++ b/src/crates/services/services-core/src/session/metadata.rs @@ -346,6 +346,15 @@ fn refresh_latest_turn(metadata: &mut SessionMetadata, turn: &DialogTurnData) { && openbitfun_core_types::background_delivery::BackgroundDelivery::from_metadata(turn.user_message.metadata.as_ref(), &turn.turn_id) .is_some_and(|delivery| delivery.execution_generation == turn.recovery_epoch.unwrap_or(0) && delivery.disposition == openbitfun_core_types::background_delivery::BackgroundReportDisposition::Quiet && delivery.suppresses_report()); + let source = turn + .user_message + .metadata + .as_ref() + .and_then(|metadata| metadata.get("submissionSource")) + .and_then(Value::as_str); + // IM is the reading surface for bot turns. Keep any earlier desktop result + // unread, but do not create another receipt for this turn on the host. + let bot = source == Some("bot"); let mut unread_target = previous_unread_target; if !same_outcome && !quiet { if let Some(outcome) = match turn.status { @@ -354,15 +363,25 @@ fn refresh_latest_turn(metadata: &mut SessionMetadata, turn: &DialogTurnData) { TurnStatus::Cancelled => Some("interrupted"), TurnStatus::InProgress => None, } { - metadata.unread_completion = Some(outcome.to_string()); metadata.needs_user_attention = None; - unread_target = Some(next.clone()); + if !bot { + metadata.unread_completion = Some(outcome.to_string()); + unread_target = Some(next.clone()); + } } } let custom = metadata .custom_metadata .get_or_insert_with(|| serde_json::json!({})); if let Some(object) = custom.as_object_mut() { + if let Some(source) = source { + object.insert( + "lastTurnSource".to_owned(), + Value::String(source.to_owned()), + ); + } else { + object.remove("lastTurnSource"); + } if let Some(delivery) = openbitfun_core_types::background_delivery::BackgroundDelivery::from_metadata( turn.user_message.metadata.as_ref(), @@ -505,31 +524,126 @@ mod background_delivery_contracts { } } +#[cfg(test)] +mod bot_read_contracts { + use super::super::types::UserMessageData; + use super::*; + + fn turn(id: &str, index: usize, source: Option<&str>) -> DialogTurnData { + let mut turn = DialogTurnData::new( + id.into(), + index, + "session".into(), + UserMessageData { + id: format!("{id}-input"), + content: "hello".into(), + timestamp: index as u64, + metadata: source.map(|source| serde_json::json!({ "submissionSource": source })), + }, + ); + turn.status = TurnStatus::Completed; + turn + } + + #[test] + fn bot_results_stay_read_after_reload_and_legacy_observer_writes() { + for status in [ + TurnStatus::Completed, + TurnStatus::Error, + TurnStatus::Cancelled, + ] { + let mut metadata = SessionMetadata::new( + "session".into(), + "Bot".into(), + "Standard".into(), + "model".into(), + ); + let mut bot = turn("bot", 0, Some("bot")); + bot.status = status; + metadata.needs_user_attention = Some("tool_confirm".into()); + refresh_latest_turn(&mut metadata, &bot); + assert!(metadata.unread_completion.is_none()); + assert!(metadata.needs_user_attention.is_none()); + assert_eq!(metadata.last_turn.as_ref().unwrap().turn_id, "bot"); + + let mut reloaded: SessionMetadata = + serde_json::from_value(serde_json::to_value(&metadata).unwrap()).unwrap(); + let persisted: DialogTurnData = + serde_json::from_value(serde_json::to_value(&bot).unwrap()).unwrap(); + refresh_latest_turn(&mut reloaded, &persisted); + let mut old_observer = reloaded.clone(); + old_observer.unread_completion = Some("completed".into()); + apply_session_unread_completion(&mut reloaded, &old_observer); + assert!(reloaded.unread_completion.is_none()); + + // Legacy turns without a source retain their unread semantics. + refresh_latest_turn(&mut reloaded, &turn("legacy", 1, None)); + assert_eq!(reloaded.unread_completion.as_deref(), Some("completed")); + assert!(reloaded + .custom_metadata + .as_ref() + .unwrap() + .get("lastTurnSource") + .is_none()); + } + } + + #[test] + fn bot_turn_keeps_an_earlier_desktop_result_and_its_read_receipt() { + let mut metadata = SessionMetadata::new( + "session".into(), + "Mixed".into(), + "Standard".into(), + "model".into(), + ); + refresh_latest_turn(&mut metadata, &turn("desktop", 0, Some("desktop_ui"))); + let mut receipt = metadata.clone(); + receipt.unread_completion = None; + let bot = turn("bot", 1, Some("bot")); + refresh_latest_turn(&mut metadata, &bot); + assert_eq!( + unread_completion_target(&metadata).unwrap().turn_id, + "desktop" + ); + apply_session_unread_completion(&mut metadata, &receipt); + assert!(metadata.unread_completion.is_none()); + refresh_latest_turn(&mut metadata, &bot); + assert!(metadata.unread_completion.is_none()); + } +} + /// A delayed UI acknowledgement must not clear a newer completion. New clients /// name the rendered Turn/generation; old clients retain the finish-time guard. pub fn apply_session_unread_completion(current: &mut SessionMetadata, incoming: &SessionMetadata) { let current_target = unread_completion_target(current); let incoming_target = receipt_target(incoming); - // An older observer may still mark a quiet completion as new unread work. + // An older observer may still mark a quiet or bot completion as unread work. // Read receipts remain client-owned, while the host owns result creation. - let suppressed_latest = current - .last_turn + let bot_latest = current + .custom_metadata .as_ref() - .and_then(|last| { - let value = current - .custom_metadata - .as_ref()? - .get("lastBackgroundDelivery")?; - let delivery: openbitfun_core_types::background_delivery::BackgroundDelivery = - serde_json::from_value(value.clone()).ok()?; - Some( - delivery.run_id == last.turn_id - && delivery.execution_generation == last.execution_generation.unwrap_or(0) - && last.status == TurnStatus::Completed - && delivery.suppresses_report(), - ) - }) - .unwrap_or(false); + .and_then(|custom| custom.get("lastTurnSource")) + .and_then(Value::as_str) + == Some("bot"); + let suppressed_latest = bot_latest + || current + .last_turn + .as_ref() + .and_then(|last| { + let value = current + .custom_metadata + .as_ref()? + .get("lastBackgroundDelivery")?; + let delivery: openbitfun_core_types::background_delivery::BackgroundDelivery = + serde_json::from_value(value.clone()).ok()?; + Some( + delivery.run_id == last.turn_id + && delivery.execution_generation == last.execution_generation.unwrap_or(0) + && last.status == TurnStatus::Completed + && delivery.suppresses_report(), + ) + }) + .unwrap_or(false); if current_target.is_none() && incoming.unread_completion.is_some() && suppressed_latest { return; } diff --git a/src/crates/services/services-integrations/src/remote_connect.rs b/src/crates/services/services-integrations/src/remote_connect.rs index 5c7132d00f..572b046819 100644 --- a/src/crates/services/services-integrations/src/remote_connect.rs +++ b/src/crates/services/services-integrations/src/remote_connect.rs @@ -563,6 +563,7 @@ pub const REMOTE_FILE_MAX_READ_BYTES: u64 = 30 * 1024 * 1024; pub const REMOTE_FILE_MAX_CHUNK_BYTES: u64 = 3 * 1024 * 1024; pub const REMOTE_CAPABILITY_HARNESS_PROFILES_V1: &str = "harness_profiles_v1"; pub const REMOTE_CAPABILITY_DIALOG_STEER_V1: &str = "dialog_steer_v1"; +pub const REMOTE_CAPABILITY_BOT_READ_RECEIPTS_V1: &str = "bot_read_receipts_v1"; pub const REMOTE_CAPABILITY_USER_QUESTION_INTERACTION_V1: &str = "user_question_interaction_v1"; pub const REMOTE_CAPABILITY_BACKGROUND_RESULT_DELIVERY_V1: &str = "background_result_delivery_v1"; pub const REMOTE_CAPABILITY_SESSION_ROLLBACK_V1: &str = "session_rollback_v1"; @@ -580,6 +581,7 @@ fn remote_host_capabilities() -> Vec { "workspace_id_references_v1".to_string(), REMOTE_CAPABILITY_HARNESS_PROFILES_V1.to_string(), REMOTE_CAPABILITY_DIALOG_STEER_V1.to_string(), + REMOTE_CAPABILITY_BOT_READ_RECEIPTS_V1.to_string(), "dialog_queue_v1".to_string(), REMOTE_CAPABILITY_PLAN_BUILD_V1.to_string(), REMOTE_CAPABILITY_SESSION_ATTACHMENTS_V1.to_string(), @@ -2951,6 +2953,10 @@ pub enum RemoteCommand { SendMessage { session_id: String, content: String, + /// Optional ingress hint retained by bot forwards across devices. Older + /// hosts ignore it; absent/unknown values keep the transport's source. + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, #[serde(default)] display_content: Option, /// Client-generated stable identity for the turn. Older clients omit it; @@ -3495,6 +3501,7 @@ where RemoteCommand::SendMessage { session_id, content, + source: ingress_source, display_content, turn_id, agent_type, @@ -3520,7 +3527,13 @@ where display_content: display_content.clone(), agent_type: agent_type.clone(), image_contexts: resolved_contexts, - policy: RemoteDialogSubmissionPolicy::for_source(source), + policy: RemoteDialogSubmissionPolicy::for_source( + if ingress_source.as_deref() == Some("bot") { + RemoteConnectSubmissionSource::Bot + } else { + source + }, + ), turn_id: turn_id.clone(), }) .await, diff --git a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs index bd02a6201c..af26a522c7 100644 --- a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs +++ b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs @@ -1262,6 +1262,7 @@ async fn remote_connect_command_owner_routes_send_message_and_prefers_explicit_i &RemoteCommand::SendMessage { session_id: "session-1".to_string(), content: "hello".to_string(), + source: None, display_content: None, turn_id: Some("harmony-turn-1".to_string()), agent_type: Some("code".to_string()), @@ -1304,6 +1305,34 @@ async fn remote_connect_command_owner_routes_send_message_and_prefers_explicit_i assert_eq!(submitted.turn_id.as_deref(), Some("harmony-turn-1")); } +#[tokio::test] +async fn remote_connect_command_preserves_bot_ingress_and_legacy_send_payloads() { + for (source, expected) in [ + (None, RemoteConnectSubmissionSource::Relay), + (Some("bot"), RemoteConnectSubmissionSource::Bot), + (Some("future_source"), RemoteConnectSubmissionSource::Relay), + ] { + let host = RecordingCommandHost::default(); + let mut payload = serde_json::json!({ + "cmd": "send_message", "session_id": "session", "content": "hello" + }); + if let Some(source) = source { + payload["source"] = serde_json::json!(source); + } + let command: RemoteCommand = serde_json::from_value(payload).unwrap(); + let encoded = serde_json::to_value(&command).unwrap(); + assert_eq!( + encoded.get("source").and_then(serde_json::Value::as_str), + source + ); + let round_trip: RemoteCommand = serde_json::from_value(encoded).unwrap(); + let response = + handle_remote_command(&host, &round_trip, RemoteConnectSubmissionSource::Relay).await; + assert!(matches!(response, RemoteResponse::MessageSent { .. })); + assert_eq!(host.submitted_dialog().policy.source, expected); + } +} + #[tokio::test] async fn remote_connect_command_owner_builds_a_projected_plan_with_hidden_execution_copy() { let host = RecordingCommandHost { @@ -2364,6 +2393,7 @@ fn remote_connect_workspace_response_helpers_own_wire_shape() { "workspace_id_references_v1", REMOTE_CAPABILITY_HARNESS_PROFILES_V1, REMOTE_CAPABILITY_DIALOG_STEER_V1, + "bot_read_receipts_v1", "dialog_queue_v1", REMOTE_CAPABILITY_PLAN_BUILD_V1, "session_attachments_v1", @@ -2615,6 +2645,7 @@ fn remote_connect_session_response_helpers_own_pagination_and_timestamps() { "workspace_id_references_v1", REMOTE_CAPABILITY_HARNESS_PROFILES_V1, REMOTE_CAPABILITY_DIALOG_STEER_V1, + "bot_read_receipts_v1", "dialog_queue_v1", REMOTE_CAPABILITY_PLAN_BUILD_V1, "session_attachments_v1", @@ -2777,6 +2808,7 @@ fn remote_connect_command_wire_shape_lives_in_owner_contract() { let command = RemoteCommand::SendMessage { session_id: "session-1".to_string(), content: "hello".to_string(), + source: None, display_content: None, turn_id: Some("harmony-turn-1".to_string()), agent_type: Some("code".to_string()), 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 6af88ef7c7..a91945dfdc 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -844,6 +844,28 @@ describe('FlowChatStore metadata persistence callbacks', () => { expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBe('completed'); }); + it.each(['completed', 'error', 'interrupted'] as const)('keeps bot %s results read without persisting another receipt', (outcome) => { + const session = completedSession(); + session.hasUnreadCompletion = undefined; + session.dialogTurns[0].userMessage.metadata = { submissionSource: 'bot' }; + flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]) })); + const persist = vi.fn(); + flowChatStore.registerPersistUnreadCompletionCallback(persist); + + flowChatStore.markSessionUnreadCompletion(session.sessionId, outcome, session.dialogTurns[0].id); + expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBeUndefined(); + expect(persist).not.toHaveBeenCalled(); + + // A bot result cannot acknowledge an earlier desktop result in this session. + flowChatStore.applySessionActivityReceipt({ + sessionId: session.sessionId, execution: 'idle', pendingApprovals: 0, pendingQuestions: 0, + unreadCompletion: 'completed', unreadTurn: { turnId: 'desktop', turnIndex: 0, status: 'completed' }, + }); + flowChatStore.markSessionUnreadCompletion(session.sessionId, outcome); + expect(flowChatStore.getState().sessions.get(session.sessionId)?.unreadCompletionTurnId).toBe('desktop'); + expect(persist).not.toHaveBeenCalled(); + }); + it('attaches the completion to its owner when a follow-up turn already exists', () => { const session = completedSession(); session.dialogTurns.push({ ...session.dialogTurns[0], id: 'queued-follow-up', status: 'pending' }); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 82e4fffbb6..8f0e99d902 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -7420,6 +7420,11 @@ export class FlowChatStore { completionKind: 'completed' | 'error' | 'interrupted', turnId?: string, ): void { + const session = this.state.sessions.get(sessionId); + const turn = turnId ? session?.dialogTurns.find(candidate => candidate.id === turnId) + : session && lastUserDialogTurn(session); + if (turn?.userMessage.metadata?.submissionSource === 'bot') return; + this.setState(prev => { const session = prev.sessions.get(sessionId); if (!session) return prev; diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts index 9f055973c5..1fd5e21a2b 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts @@ -8,6 +8,35 @@ const summary = (execution = 'idle', id = 'session'): SessionActivitySummary => }); describe('session activity read projection', () => { + it.each(['completed', 'failed', 'cancelled', 'interrupted'])('keeps bot %s results read on local and peer surfaces', (outcome) => { + for (const surface of ['local', 'peer']) { + const store = new SessionActivityStore(); + store.observe(surface, 'agentic://dialog-turn-started', { + sessionId: 'session', turnId: 'bot', userMessageMetadata: { submissionSource: 'bot' }, + }); + store.observe(surface, 'agentic://dialog-turn-' + outcome, { sessionId: 'session', turnId: 'bot' }); + expect(store.get('session', surface)?.summary?.unreadCompletion).toBeUndefined(); + expect(store.get('session', surface)?.summary?.lastTurn?.turnId).toBe('bot'); + store.observe(surface, 'agentic://dialog-turn-started', { sessionId: 'session', turnId: 'desktop' }); + store.observe(surface, 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'desktop' }); + expect(store.get('session', surface)?.summary?.unreadCompletion).toBe('completed'); + } + }); + + it('preserves earlier unread work across bot recovery and host refreshes', () => { + const store = new SessionActivityStore(); + store.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'desktop' }); + store.observe('peer', 'agentic://dialog-turn-started', { + sessionId: 'session', turnId: 'bot', userMessageMetadata: { submissionSource: 'bot' }, + }); + store.applyRead(store.beginRead('peer'), [store.get('session', 'peer')!.summary!]); + store.observe('peer', 'agentic://dialog-turn-recovered', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); + store.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); + expect(store.get('session', 'peer')?.summary).toMatchObject({ + unreadCompletion: 'completed', unreadTurn: { turnId: 'desktop' }, lastTurn: { turnId: 'bot' }, + }); + }); + it('keeps a prior unread result across a newer quiet run and acknowledges its original identity', () => { activateSurface('local'); const store = new SessionActivityStore(); diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts index 3a9ae055d4..45afcbcd85 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts @@ -16,6 +16,8 @@ interface Entry { stale: boolean; acknowledged?: { turnId: string; status?: SessionLastTurn['status']; executionGeneration?: number; recoveryPending?: boolean }; position?: { streamId: string; cursor: number }; + /** Preserve the live ingress fact even when this surface has no transcript. */ + botTurnId?: string; } const blank = (sessionId: string): SessionActivitySummary => ({ @@ -148,6 +150,10 @@ export class SessionActivityStore { if (generation !== undefined && summary.lastTurn?.turnId === turnId && (summary.lastTurn?.executionGeneration ?? -1) > generation) return; const starting = eventName === 'agentic://dialog-turn-started' || eventName === 'agentic://dialog-turn-recovered'; + const userMetadata = event.userMessageMetadata as Record | undefined; + const botTurnId = eventName === 'agentic://dialog-turn-started' + ? userMetadata?.submissionSource === 'bot' ? turnId : undefined + : previous?.botTurnId; const settling = ['agentic://dialog-turn-completed', 'agentic://dialog-turn-failed', 'agentic://dialog-turn-cancelled', 'agentic://dialog-turn-interrupted'].includes(eventName); let newResult = false; @@ -173,6 +179,7 @@ export class SessionActivityStore { // Learning an optional recovery fact from a replay is not a new result. // A known paused -> cancelled transition is, even within one generation. newResult = (!sameOutcome || summary.lastTurn?.recoveryPending !== undefined) + && (!turnId || botTurnId !== turnId) && (outcome !== 'completed' || shouldDeliverBackgroundCompletion(event)); summary = { ...summary, execution: outcome === 'error' ? 'error' : 'idle', activeTurnId: undefined, @@ -202,6 +209,7 @@ export class SessionActivityStore { this.entries(surfaceId).set(sessionId, { summary, eventVersion: ++this.eventVersion, readSequence: previous?.readSequence ?? 0, checkedAt: previous?.checkedAt ?? 0, stale: true, position: position ?? previous?.position, + botTurnId, acknowledged: starting || newResult ? undefined : previous?.acknowledged, }); this.notify(surfaceId, sessionId); From a5d6f4c3c3cf23d828cd3c1ac2aba8c0154a118c Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 09:24:17 +0800 Subject: [PATCH 2/3] fix(session): retain bot read state across mid-turn reconnects --- .../assembly/core/src/product_runtime.rs | 7 +++++++ .../services-core/src/session/page.rs | 21 +++++++++++++++++++ .../src/flow_chat/store/FlowChatStore.test.ts | 14 +++++++++++++ .../src/flow_chat/store/FlowChatStore.ts | 5 ++++- .../store/sessionActivityStore.test.ts | 14 ++++++++++++- .../flow_chat/store/sessionActivityStore.ts | 17 ++++++++------- .../src/shared/types/session-history.ts | 2 ++ 7 files changed, 71 insertions(+), 9 deletions(-) diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index 32dece76e0..07b45a00d1 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -1510,6 +1510,12 @@ impl CoreAgentRuntimeCompatibility { }; let unread_turn = openbitfun_services_core::session::unread_completion_target(&metadata); + let last_turn_source = metadata + .custom_metadata + .as_ref() + .and_then(|custom| custom.get("lastTurnSource")) + .and_then(serde_json::Value::as_str) + .map(str::to_owned); SessionActivitySummary { pending_approvals: approvals .get(&metadata.session_id) @@ -1523,6 +1529,7 @@ impl CoreAgentRuntimeCompatibility { execution: execution.to_string(), active_turn_id, last_turn: metadata.last_turn, + last_turn_source, unread_completion: metadata.unread_completion, unread_turn, } diff --git a/src/crates/services/services-core/src/session/page.rs b/src/crates/services/services-core/src/session/page.rs index 2e52a79cdf..9c2264f7a6 100644 --- a/src/crates/services/services-core/src/session/page.rs +++ b/src/crates/services/services-core/src/session/page.rs @@ -84,6 +84,9 @@ pub struct SessionActivitySummary { pub pending_questions: usize, #[serde(default, skip_serializing_if = "Option::is_none")] pub last_turn: Option, + /// Admitted ingress of last_turn, including while a controller was offline. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_turn_source: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub unread_completion: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -477,6 +480,24 @@ fn session_metadata_page_cursor(metadata: &SessionMetadata, revision: Option { expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBe('completed'); }); + it('keeps a reconnecting bot completion read before its transcript is loaded', () => { + const session = createSession({ sessionId: 'bot-reconnect', dialogTurns: [], historyState: 'metadata-only' }); + flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]) })); + sessionActivityStore.applyRead(sessionActivityStore.beginRead(), [{ + sessionId: session.sessionId, execution: 'running', pendingApprovals: 0, pendingQuestions: 0, + lastTurn: { turnId: 'bot', turnIndex: 0, status: 'inprogress' }, lastTurnSource: 'bot', + }]); + const persist = vi.fn(); + flowChatStore.registerPersistUnreadCompletionCallback(persist); + flowChatStore.markSessionUnreadCompletion(session.sessionId, 'completed', 'bot'); + expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBeUndefined(); + expect(persist).not.toHaveBeenCalled(); + }); + it.each(['completed', 'error', 'interrupted'] as const)('keeps bot %s results read without persisting another receipt', (outcome) => { const session = completedSession(); session.hasUnreadCompletion = undefined; diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 8f0e99d902..d9776ebae0 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -7423,7 +7423,10 @@ export class FlowChatStore { const session = this.state.sessions.get(sessionId); const turn = turnId ? session?.dialogTurns.find(candidate => candidate.id === turnId) : session && lastUserDialogTurn(session); - if (turn?.userMessage.metadata?.submissionSource === 'bot') return; + const activity = sessionActivityStore.get(sessionId)?.summary; + const resultTurnId = turnId ?? turn?.id; + if (turn?.userMessage.metadata?.submissionSource === 'bot' + || (resultTurnId && activity?.lastTurn?.turnId === resultTurnId && activity.lastTurnSource === 'bot')) return; this.setState(prev => { const session = prev.sessions.get(sessionId); diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts index 1fd5e21a2b..deee181fa1 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts @@ -8,6 +8,18 @@ const summary = (execution = 'idle', id = 'session'): SessionActivitySummary => }); describe('session activity read projection', () => { + it('keeps a bot result read when reconnecting after its start event', () => { + const store = new SessionActivityStore(); + const hostSummary = { + ...summary('running'), activeTurnId: 'bot', lastTurnSource: 'bot', + lastTurn: { turnId: 'bot', turnIndex: 0, status: 'inprogress' as const }, + }; + store.applyRead(store.beginRead('peer'), [hostSummary]); + store.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'bot' }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + expect(store.get('session', 'peer')?.summary?.execution).toBe('idle'); + }); + it.each(['completed', 'failed', 'cancelled', 'interrupted'])('keeps bot %s results read on local and peer surfaces', (outcome) => { for (const surface of ['local', 'peer']) { const store = new SessionActivityStore(); @@ -29,7 +41,7 @@ describe('session activity read projection', () => { store.observe('peer', 'agentic://dialog-turn-started', { sessionId: 'session', turnId: 'bot', userMessageMetadata: { submissionSource: 'bot' }, }); - store.applyRead(store.beginRead('peer'), [store.get('session', 'peer')!.summary!]); + store.applyRead(store.beginRead('peer'), [{ ...store.get('session', 'peer')!.summary!, lastTurnSource: undefined }]); store.observe('peer', 'agentic://dialog-turn-recovered', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); store.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); expect(store.get('session', 'peer')?.summary).toMatchObject({ diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts index 45afcbcd85..bc9018640c 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts @@ -16,8 +16,6 @@ interface Entry { stale: boolean; acknowledged?: { turnId: string; status?: SessionLastTurn['status']; executionGeneration?: number; recoveryPending?: boolean }; position?: { streamId: string; cursor: number }; - /** Preserve the live ingress fact even when this surface has no transcript. */ - botTurnId?: string; } const blank = (sessionId: string): SessionActivitySummary => ({ @@ -63,6 +61,10 @@ export class SessionActivityStore { // Reads are ordered independently so a slower previous read cannot regress it. if (previous && (previous.eventVersion > read.eventVersion || previous.readSequence > read.sequence)) continue; const previousTurn = previous?.summary?.lastTurn; + if (summary.lastTurnSource === undefined && summary.lastTurn + && summary.lastTurn.turnId === previousTurn?.turnId) { + summary = { ...summary, lastTurnSource: previous?.summary?.lastTurnSource }; + } if (summary.lastTurn && summary.lastTurn.recoveryPending === undefined && previousTurn && previousTurn.turnId === summary.lastTurn.turnId && previousTurn.status === summary.lastTurn.status && (previousTurn.executionGeneration ?? 0) === (summary.lastTurn.executionGeneration ?? 0)) { @@ -151,15 +153,16 @@ export class SessionActivityStore { && (summary.lastTurn?.executionGeneration ?? -1) > generation) return; const starting = eventName === 'agentic://dialog-turn-started' || eventName === 'agentic://dialog-turn-recovered'; const userMetadata = event.userMessageMetadata as Record | undefined; - const botTurnId = eventName === 'agentic://dialog-turn-started' - ? userMetadata?.submissionSource === 'bot' ? turnId : undefined - : previous?.botTurnId; + const turnSource = eventName === 'agentic://dialog-turn-started' + ? typeof userMetadata?.submissionSource === 'string' ? userMetadata.submissionSource : undefined + : turnId && summary.lastTurn?.turnId === turnId ? summary.lastTurnSource : undefined; const settling = ['agentic://dialog-turn-completed', 'agentic://dialog-turn-failed', 'agentic://dialog-turn-cancelled', 'agentic://dialog-turn-interrupted'].includes(eventName); let newResult = false; if (starting) { summary = { ...summary, execution: 'running', activeTurnId: turnId, pendingApprovals: 0, pendingQuestions: 0, + lastTurnSource: turnSource, unreadTurn: summary.unreadCompletion ? summary.unreadTurn ?? summary.lastTurn : undefined, lastTurn: turnId ? { turnId, turnIndex: typeof event.turnIndex === 'number' ? event.turnIndex : summary.lastTurn?.turnIndex ?? 0, @@ -179,10 +182,11 @@ export class SessionActivityStore { // Learning an optional recovery fact from a replay is not a new result. // A known paused -> cancelled transition is, even within one generation. newResult = (!sameOutcome || summary.lastTurn?.recoveryPending !== undefined) - && (!turnId || botTurnId !== turnId) + && turnSource !== 'bot' && (outcome !== 'completed' || shouldDeliverBackgroundCompletion(event)); summary = { ...summary, execution: outcome === 'error' ? 'error' : 'idle', activeTurnId: undefined, + lastTurnSource: turnSource, pendingApprovals: 0, pendingQuestions: 0, unreadCompletion: newResult ? outcome : summary.unreadCompletion, unreadTurn: newResult ? { turnId: turnId ?? '', turnIndex: typeof event.turnIndex === 'number' ? event.turnIndex : summary.lastTurn?.turnIndex ?? 0, @@ -209,7 +213,6 @@ export class SessionActivityStore { this.entries(surfaceId).set(sessionId, { summary, eventVersion: ++this.eventVersion, readSequence: previous?.readSequence ?? 0, checkedAt: previous?.checkedAt ?? 0, stale: true, position: position ?? previous?.position, - botTurnId, acknowledged: starting || newResult ? undefined : previous?.acknowledged, }); this.notify(surfaceId, sessionId); diff --git a/src/web-ui/src/shared/types/session-history.ts b/src/web-ui/src/shared/types/session-history.ts index 0ddfa6d96e..07a8cfc990 100644 --- a/src/web-ui/src/shared/types/session-history.ts +++ b/src/web-ui/src/shared/types/session-history.ts @@ -162,6 +162,8 @@ export interface SessionActivitySummary { pendingApprovals: number; pendingQuestions: number; lastTurn?: SessionLastTurn; + /** Admitted ingress of lastTurn; omitted by older hosts. */ + lastTurnSource?: string; unreadCompletion?: 'completed' | 'error' | 'interrupted'; /** A quiet run can be newer than the unread user-facing result. */ unreadTurn?: SessionLastTurn; From a73df066d8f9b1270c4902fedb3efe7f2e66a3a8 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 10:46:31 +0800 Subject: [PATCH 3/3] fix(remote): mark results read after IM delivery succeeds --- .../src/agentic/coordination/coordinator.rs | 3 - .../assembly/core/src/product_runtime.rs | 10 +- .../remote_connect/bot/command_router.rs | 185 ++++++++-- .../src/service/remote_connect/bot/feishu.rs | 15 +- .../service/remote_connect/bot/telegram.rs | 17 +- .../src/service/remote_connect/bot/weixin.rs | 113 ++++-- .../service/remote_connect/remote_server.rs | 1 - .../core/src/service_agent_runtime.rs | 45 +++ src/crates/contracts/events/AGENTS.md | 1 + src/crates/contracts/events/src/agentic.rs | 13 + .../events/src/frontend_projection.rs | 33 ++ .../services-core/src/session/metadata.rs | 321 +++++++++++------- .../services/services-core/src/session/mod.rs | 10 +- .../services-core/src/session/page.rs | 33 +- .../src/remote_connect.rs | 105 +++++- .../src/remote_connect/session_records.rs | 18 +- .../tests/remote_connect_contracts.rs | 34 +- .../services/sessionNavStatusService.test.ts | 21 +- .../services/sessionNavStatusService.ts | 1 + .../src/flow_chat/store/FlowChatStore.test.ts | 56 ++- .../src/flow_chat/store/FlowChatStore.ts | 12 +- .../store/sessionActivityStore.test.ts | 71 ++-- .../flow_chat/store/sessionActivityStore.ts | 29 +- .../api/service-api/AgentAPI.ts | 4 + .../src/shared/types/session-history.ts | 4 +- 25 files changed, 789 insertions(+), 366 deletions(-) diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index ae428eefca..9bfd4cff03 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -7240,9 +7240,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet default_permission_mode_from_global_config().await, ); let mut metadata = Self::ensure_user_message_metadata_object(user_message_metadata.take()); - // Stamp the admitted ingress so live observers and persisted receipts - // agree even when no desktop client is connected. - metadata["submissionSource"] = serde_json::json!(submission_policy.trigger_source); if submission_policy.trigger_source != openbitfun_runtime_ports::DialogTriggerSource::ScheduledJob { diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index 07b45a00d1..27817281ee 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -1510,12 +1510,8 @@ impl CoreAgentRuntimeCompatibility { }; let unread_turn = openbitfun_services_core::session::unread_completion_target(&metadata); - let last_turn_source = metadata - .custom_metadata - .as_ref() - .and_then(|custom| custom.get("lastTurnSource")) - .and_then(serde_json::Value::as_str) - .map(str::to_owned); + let read_turn = + openbitfun_services_core::session::read_completion_target(&metadata); SessionActivitySummary { pending_approvals: approvals .get(&metadata.session_id) @@ -1529,9 +1525,9 @@ impl CoreAgentRuntimeCompatibility { execution: execution.to_string(), active_turn_id, last_turn: metadata.last_turn, - last_turn_source, unread_completion: metadata.unread_completion, unread_turn, + read_turn, } }) .collect(), diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs index 8d866a036e..3259b1f02e 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs @@ -89,11 +89,81 @@ pub struct ForwardRequest { } pub struct ForwardedTurnResult { + pub completion_kind: Option<&'static str>, + pub turn_id: Option, pub completed_remote_tools: Vec, pub display_text: String, pub full_text: String, } +pub(crate) async fn acknowledge_delivered_result( + session_id: &str, + turn_id: &str, + completion_kind: Option<&str>, + target: Option<&RemoteBotTarget>, +) -> Result { + use openbitfun_services_integrations::remote_connect::{ + RemoteSessionRuntimeHost, REMOTE_CAPABILITY_SESSION_RESULT_ACK_V1, + }; + if let Some(target) = target { + let info = target + .rpc(serde_json::json!({"cmd":"get_workspace_info"})) + .await?; + if !info["capabilities"].as_array().is_some_and(|values| { + values + .iter() + .any(|value| value.as_str() == Some(REMOTE_CAPABILITY_SESSION_RESULT_ACK_V1)) + }) { + return Err( + "Execution host does not support result acknowledgement; upgrade that device" + .into(), + ); + } + let reply = target + .rpc(serde_json::json!({ + "cmd":"acknowledge_session_result", "session_id":session_id, + "turn_id":turn_id, "completion_kind":completion_kind, + })) + .await?; + if reply["resp"] != "session_result_acknowledged" + || reply["session_id"] != session_id + || reply["turn_id"] != turn_id + { + return Err("Invalid session result acknowledgement response".into()); + } + return reply["acknowledged"] + .as_bool() + .ok_or_else(|| "Missing result acknowledgement".into()); + } + crate::service_agent_runtime::CoreServiceAgentRuntime::remote_session_host()? + .acknowledge_session_result(session_id, turn_id, completion_kind) + .await +} + +/// All provider chunks must succeed before acknowledging the final reply. +/// A receipt failure never resends an already delivered IM message. +pub(crate) async fn deliver_final_reply( + session_id: &str, + turn_id: &str, + target: Option<&RemoteBotTarget>, + result: &ForwardedTurnResult, + send: impl std::future::Future>, +) -> anyhow::Result<()> { + if result.display_text.is_empty() { + return Ok(()); + } + send.await?; + if let Some(kind) = result.completion_kind { + let turn_id = result.turn_id.as_deref().unwrap_or(turn_id); + if let Err(error) = + acknowledge_delivered_result(session_id, turn_id, Some(kind), target).await + { + warn!("Failed to acknowledge delivered IM result for session {session_id}, turn {turn_id}: {error}"); + } + } + Ok(()) +} + // ── BotCommand ───────────────────────────────────────────────────── pub fn welcome_message(language: BotLanguage) -> &'static str { @@ -3529,6 +3599,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission( ) -> ForwardedTurnResult { if !runtime_fence.is_lifecycle_current() || runtime_fence.identity_epoch() != identity_epoch { return ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: String::new(), full_text: String::new(), @@ -3572,6 +3644,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission( if let Err(e) = submission { let msg = format!("{}{e}", s.send_failed_prefix); return ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: msg.clone(), full_text: msg, @@ -3678,6 +3752,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission( if turn_id == target_turn_id { let msg = format!("{}{}", s.error_prefix, error); return ForwardedTurnResult { + completion_kind: Some("error"), + turn_id: None, completed_remote_tools: Vec::new(), display_text: msg.clone(), full_text: msg, @@ -3687,6 +3763,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission( TrackerEvent::TurnCancelled { turn_id } => { if turn_id == target_turn_id { return ForwardedTurnResult { + completion_kind: Some("interrupted"), + turn_id: None, completed_remote_tools: Vec::new(), display_text: s.task_cancelled.to_string(), full_text: s.task_cancelled.to_string(), @@ -3738,6 +3816,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission( let display_text = full_text.clone(); ForwardedTurnResult { + completion_kind: Some("completed"), + turn_id: None, completed_remote_tools: Vec::new(), display_text: if display_text.is_empty() { s.no_response.to_string() @@ -3750,6 +3830,8 @@ pub(crate) async fn execute_forwarded_turn_with_submission( .await; result.unwrap_or_else(|_| ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: s.timeout_one_hour.to_string(), full_text: String::new(), @@ -3764,11 +3846,12 @@ async fn execute_remote_forward( submission_finished: Option>, ) -> ForwardedTurnResult { use openbitfun_services_integrations::remote_connect::bot::remote_turn::observe_turn; - use openbitfun_services_integrations::remote_connect::REMOTE_CAPABILITY_BOT_READ_RECEIPTS_V1; let s = strings_for(current_bot_language().await); let target = forward.remote_target.as_ref().unwrap(); let current = || fence.is_lifecycle_current() && fence.identity_epoch() == epoch; let empty = || ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: String::new(), full_text: String::new(), @@ -3776,30 +3859,14 @@ async fn execute_remote_forward( if !current() { return empty(); } - let mut command = serde_json::json!({ - "cmd":"send_message", "session_id":target.session_id, - "content":forward.content, "turn_id":forward.turn_id, - "image_contexts":forward.image_contexts, - }); - // Old hosts keep accepting messages with their existing receipt behavior. - // Only advertise bot ingress after the target confirms it can honor it. - if let Ok(info) = target - .rpc(serde_json::json!({"cmd":"get_workspace_info"})) - .await - { - if info["capabilities"].as_array().is_some_and(|capabilities| { - capabilities.iter().any(|capability| { - capability.as_str() == Some(REMOTE_CAPABILITY_BOT_READ_RECEIPTS_V1) - }) - }) { - command["source"] = serde_json::json!("bot"); - } - } - if !current() { - return empty(); - } // Submission is never retried blindly: older peers need not deduplicate. - let sent = target.rpc(command).await; + let sent = target + .rpc(serde_json::json!({ + "cmd":"send_message", "session_id":target.session_id, + "content":forward.content, "turn_id":forward.turn_id, + "image_contexts":forward.image_contexts, + })) + .await; drop(submission_finished); if !current() { return empty(); @@ -3812,6 +3879,8 @@ async fn execute_remote_forward( Some(id) => id.to_string(), None => { return ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: format!("{}Missing remote turn ID", s.send_failed_prefix), full_text: String::new(), @@ -3821,6 +3890,8 @@ async fn execute_remote_forward( } result => { return ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: format!( "{}{}", @@ -3861,6 +3932,12 @@ async fn execute_remote_forward( _ => turn.text.clone(), }; return ForwardedTurnResult { + completion_kind: Some(match turn.status.as_str() { + "failed" | "error" => "error", + "cancelled" => "interrupted", + _ => "completed", + }), + turn_id: Some(turn_id.clone()), completed_remote_tools: shown.into_keys().collect(), display_text, full_text: turn.text, @@ -3942,6 +4019,8 @@ async fn execute_remote_forward( } Ok(reply) => { return ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: format!( "{}{}", @@ -3959,6 +4038,8 @@ async fn execute_remote_forward( ) || error.contains("HTTP 403") { return ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: format!("{}{error}", s.error_prefix), full_text: String::new(), @@ -3974,6 +4055,8 @@ async fn execute_remote_forward( }) .await; result.unwrap_or_else(|_| ForwardedTurnResult { + completion_kind: None, + turn_id: None, completed_remote_tools: Vec::new(), display_text: s.timeout_one_hour.to_string(), full_text: String::new(), @@ -5126,8 +5209,15 @@ mod handle_chat_tests { } } "get_workspace_info" => serde_json::json!({"resp":"workspace_info", "capabilities": - if supports_interaction { vec!["user_question_interaction_v1", "session_attachments_v1", "bot_read_receipts_v1"] } else { vec![] } + if supports_interaction { vec!["user_question_interaction_v1", "session_attachments_v1", "session_result_ack_v1"] } else { vec![] } }), + "acknowledge_session_result" => { + assert!(supports_interaction); + assert_eq!(command["session_id"], "session-a"); + assert_eq!(command["turn_id"], "accepted-turn"); + assert_eq!(command["completion_kind"], "completed"); + serde_json::json!({"resp":"session_result_acknowledged","session_id":"session-a","turn_id":"accepted-turn","acknowledged":true}) + } "store_session_attachment" => { assert!(supports_interaction); assert_eq!(command["session_id"], "session-a"); @@ -5266,6 +5356,40 @@ mod handle_chat_tests { .await .unwrap(); assert_eq!(result.full_text, "![image](result.png)"); + let ack_count = || { + calls + .lock() + .unwrap() + .iter() + .filter(|call| call["cmd"] == "acknowledge_session_result") + .count() + }; + assert_eq!( + ack_count(), + 0, + "completion alone must not acknowledge delivery" + ); + assert!(deliver_final_reply( + "session-a", + "requested-turn", + Some(&target), + &result, + async { Err(anyhow::anyhow!("provider rejected final chunk")) } + ) + .await + .is_err()); + assert_eq!(ack_count(), 0, "a partial or failed IM send stays unread"); + deliver_final_reply( + "session-a", + "requested-turn", + Some(&target), + &result, + async { Ok(()) }, + ) + .await + .unwrap(); + assert_eq!(ack_count(), usize::from(supports_interaction)); + assert_eq!(result.completed_remote_tools.len(), 2); assert!(result .completed_remote_tools @@ -5290,17 +5414,6 @@ mod handle_chat_tests { 1 ); let observed = calls.lock().unwrap(); - assert_eq!( - observed - .iter() - .find(|call| call["cmd"] == "send_message") - .unwrap()["source"], - if supports_interaction { - serde_json::json!("bot") - } else { - Value::Null - } - ); let activity = observed .iter() .position(|call| call["cmd"] == "start_question_interaction"); diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs b/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs index 1e39d3512b..10d01b687f 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs @@ -17,8 +17,8 @@ use std::sync::Arc; use tokio::sync::RwLock; use super::command_router::{ - complete_im_bot_pairing, current_bot_language, execute_forwarded_turn, handle_command, - parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler, + complete_im_bot_pairing, current_bot_language, deliver_final_reply, execute_forwarded_turn, + handle_command, parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler, BotInteractiveRequest, BotLanguage, BotMessageSender, HandleResult, }; use super::{ @@ -605,6 +605,7 @@ impl FeishuBot { if let Some(forward) = result.forward_to_session { let output_session_id = forward.session_id.clone(); + let output_turn_id = forward.turn_id.clone(); let output_remote_target = forward.remote_target.clone(); let output_identity_epoch = command_identity_epoch; let bot = self.clone(); @@ -671,7 +672,15 @@ impl FeishuBot { .await; } if !result.display_text.is_empty() { - if let Err(err) = bot.send_message(&cid, &result.display_text).await { + if let Err(err) = deliver_final_reply( + &output_session_id, + &output_turn_id, + output_remote_target.as_ref(), + &result, + bot.send_message(&cid, &result.display_text), + ) + .await + { warn!("Failed to send Feishu final message to {cid}: {err}"); } } diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs b/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs index de92d8b5fa..331162ebd8 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs @@ -15,8 +15,8 @@ use std::sync::Arc; use tokio::sync::RwLock; use super::command_router::{ - complete_im_bot_pairing, current_bot_language, execute_forwarded_turn, handle_command, - parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler, + complete_im_bot_pairing, current_bot_language, deliver_final_reply, execute_forwarded_turn, + handle_command, parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler, BotInteractiveRequest, BotLanguage, BotMessageSender, HandleResult, }; use super::{ @@ -440,6 +440,7 @@ impl TelegramBot { if let Some(forward) = result.forward_to_session { let output_session_id = forward.session_id.clone(); + let output_turn_id = forward.turn_id.clone(); let output_remote_target = forward.remote_target.clone(); let output_identity_epoch = command_identity_epoch; let bot = self.clone(); @@ -495,7 +496,17 @@ impl TelegramBot { .await; } if !result.display_text.is_empty() { - bot.send_message(chat_id, &result.display_text).await.ok(); + if let Err(error) = deliver_final_reply( + &output_session_id, + &output_turn_id, + output_remote_target.as_ref(), + &result, + bot.send_message(chat_id, &result.display_text), + ) + .await + { + log::warn!("Failed to send Telegram final message to {chat_id}: {error}"); + } } bot.notify_files_ready( chat_id, diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs index a72f110baf..3402968ea0 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs @@ -20,9 +20,10 @@ use std::time::Duration; use tokio::sync::{Mutex, Notify, RwLock}; use super::command_router::{ - complete_im_bot_pairing, current_bot_language, execute_forwarded_turn_with_submission, - handle_command, parse_command, welcome_message, BotChatState, BotInteractionHandler, - BotInteractiveRequest, BotMessageSender, HandleResult, + acknowledge_delivered_result, complete_im_bot_pairing, current_bot_language, + deliver_final_reply, execute_forwarded_turn_with_submission, handle_command, parse_command, + welcome_message, BotChatState, BotInteractionHandler, BotInteractiveRequest, BotMessageSender, + HandleResult, }; use super::{ load_bot_persistence, update_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, @@ -77,6 +78,7 @@ const MAX_PROACTIVE_PUSH_BYTES: usize = weixin_provider::MAX_TEXT_CHUNK; struct PendingOutbound { id: String, session_id: String, + turn_id: Option, text: String, queued_at: i64, } @@ -204,8 +206,8 @@ fn bounded_proactive_text(text: &str) -> String { /// oldest outputs are dropped first, and when the newest output alone exceeds /// the cap its head is sent, because the newest answer is the one the user is /// waiting for. -fn merge_pending(pending: &[PendingOutbound]) -> String { - let mut kept: Vec<&str> = Vec::new(); +fn merged_delivery(pending: &[PendingOutbound]) -> (String, Vec<&PendingOutbound>) { + let mut kept = Vec::new(); let mut bytes = 0usize; // Walk newest first so the byte cap drops the oldest output. for item in pending.iter().rev() { @@ -222,19 +224,29 @@ fn merge_pending(pending: &[PendingOutbound]) -> String { break; } bytes += separator + text.len(); - kept.push(text); + kept.push(item); } if kept.is_empty() { return pending .iter() .rev() - .map(|item| item.text.trim()) - .find(|text| !text.is_empty()) - .map(bounded_proactive_text) + .find(|item| !item.text.trim().is_empty()) + .map(|item| (bounded_proactive_text(&item.text), vec![item])) .unwrap_or_default(); } kept.reverse(); - kept.join(PENDING_SEPARATOR) + ( + kept.iter() + .map(|item| item.text.trim()) + .collect::>() + .join(PENDING_SEPARATOR), + kept, + ) +} + +#[cfg(test)] +fn merge_pending(pending: &[PendingOutbound]) -> String { + merged_delivery(pending).0 } #[derive(Debug, Clone)] @@ -459,8 +471,14 @@ impl WeixinBot { return; } for peer_id in self.peers_for_session(session_id).await { - self.queue_proactive(&peer_id, session_id, text, &format!("session {session_id}")) - .await; + self.queue_proactive( + &peer_id, + session_id, + None, + text, + &format!("session {session_id}"), + ) + .await; } } @@ -482,18 +500,32 @@ impl WeixinBot { return; } for peer_id in peers { - self.queue_proactive(&peer_id, &session_id, &text, &format!("turn {turn_id}")) - .await; + self.queue_proactive( + &peer_id, + &session_id, + Some(&turn_id), + &text, + &format!("turn {turn_id}"), + ) + .await; } } - async fn queue_proactive(&self, peer_id: &str, session_id: &str, text: &str, source: &str) { + async fn queue_proactive( + &self, + peer_id: &str, + session_id: &str, + turn_id: Option<&str>, + text: &str, + source: &str, + ) { if text.trim().is_empty() { debug!("weixin: proactive push skipped for peer {peer_id}: {source} has no text"); return; } info!("weixin: queueing proactive push for peer {peer_id} from {source}"); - self.enqueue_outbound(peer_id, session_id, text).await; + self.enqueue_turn_outbound(peer_id, session_id, turn_id, text) + .await; self.outbound_wakeup.notify_one(); } @@ -552,7 +584,13 @@ impl WeixinBot { turns.iter().any(|tracked| tracked == turn_id) } - async fn enqueue_outbound(&self, peer_id: &str, session_id: &str, text: &str) { + async fn enqueue_turn_outbound( + &self, + peer_id: &str, + session_id: &str, + turn_id: Option<&str>, + text: &str, + ) { let now = chrono::Utc::now().timestamp(); let dropped = { let mut pending = self.pending_outbound.lock().await; @@ -562,6 +600,7 @@ impl WeixinBot { PendingOutbound { id: uuid::Uuid::new_v4().to_string(), session_id: session_id.to_string(), + turn_id: turn_id.map(str::to_owned), text: bounded_proactive_text(text), queued_at: now, }, @@ -603,7 +642,7 @@ impl WeixinBot { if pending.is_empty() { return; } - let merged = merge_pending(&pending); + let (merged, delivered) = merged_delivery(&pending); if merged.trim().is_empty() { // Nothing deliverable in the backlog, so it is not worth a reply. self.confirm_pending_sent(peer_id, &pending).await; @@ -628,6 +667,15 @@ impl WeixinBot { } return; } + for item in delivered { + if let Some(turn_id) = item.turn_id.as_deref() { + if let Err(error) = + acknowledge_delivered_result(&item.session_id, turn_id, None, None).await + { + warn!("Failed to acknowledge proactive IM result for turn {turn_id}: {error}"); + } + } + } info!( "weixin: proactive push delivered to peer {peer_id} (one reply for {} queued message(s))", pending.len() @@ -1385,6 +1433,7 @@ impl WeixinBot { // hook from delivering the same answer a second time. self.mark_own_turn(&forward.turn_id).await; let output_session_id = forward.session_id.clone(); + let output_turn_id = forward.turn_id.clone(); let output_remote_target = forward.remote_target.clone(); let output_identity_epoch = command_identity_epoch; let bot = self.clone(); @@ -1453,7 +1502,15 @@ impl WeixinBot { .await; } if !turn_result.display_text.is_empty() { - if let Err(err) = bot.send_text(&peer, &turn_result.display_text).await { + if let Err(err) = deliver_final_reply( + &output_session_id, + &output_turn_id, + output_remote_target.as_ref(), + &turn_result, + bot.send_text(&peer, &turn_result.display_text), + ) + .await + { warn!("weixin: send final reply to peer {peer} failed: {err}"); } } @@ -1598,6 +1655,7 @@ mod tests { PendingOutbound { id: uuid::Uuid::new_v4().to_string(), session_id: "session".to_string(), + turn_id: None, text: text.to_string(), queued_at, } @@ -1611,6 +1669,23 @@ mod tests { .collect() } + #[test] + fn merged_delivery_only_acknowledges_results_included_in_the_im_reply() { + let old = "a".repeat(MAX_PROACTIVE_PUSH_BYTES); + let mut pending = backlog(&[&old, "latest"]); + pending[0].turn_id = Some("old-turn".into()); + pending[1].turn_id = Some("new-turn".into()); + let (text, delivered) = merged_delivery(&pending); + assert_eq!(text, "latest"); + assert_eq!( + delivered + .iter() + .filter_map(|item| item.turn_id.as_deref()) + .collect::>(), + vec!["new-turn"] + ); + } + #[test] fn proactive_push_waits_for_durable_completion_and_ignores_history_edits() { let early = AgenticEvent::DialogTurnCompleted { diff --git a/src/crates/assembly/core/src/service/remote_connect/remote_server.rs b/src/crates/assembly/core/src/service/remote_connect/remote_server.rs index aac6af9534..086442fb58 100644 --- a/src/crates/assembly/core/src/service/remote_connect/remote_server.rs +++ b/src/crates/assembly/core/src/service/remote_connect/remote_server.rs @@ -642,7 +642,6 @@ mod tests { let command = RemoteCommand::SendMessage { session_id: "session-1".to_string(), content: "hello".to_string(), - source: None, display_content: None, turn_id: Some("harmony-turn-1".to_string()), agent_type: Some("code".to_string()), diff --git a/src/crates/assembly/core/src/service_agent_runtime.rs b/src/crates/assembly/core/src/service_agent_runtime.rs index 07bcaa998a..cdfdf38660 100644 --- a/src/crates/assembly/core/src/service_agent_runtime.rs +++ b/src/crates/assembly/core/src/service_agent_runtime.rs @@ -3797,6 +3797,51 @@ impl RemoteSessionRuntimeHost for CoreRemoteSessionRuntimeHost { .map_err(|error| format!("Failed to restore session: {error}")) } + async fn acknowledge_session_result( + &self, + session_id: &str, + turn_id: &str, + completion_kind: Option<&str>, + ) -> Result { + let binding = CoreServiceAgentRuntime::resolve_session_workspace_binding(session_id) + .await + .ok_or_else(|| { + format!("Session workspace binding not available for session: {session_id}") + })?; + ensure_remote_binding_runtime_ownership(self.coordinator.as_ref(), &binding).await?; + let mut receipt = None; + self.coordinator + .get_session_manager() + .update_session_metadata(&binding.session_storage_dir(), session_id, |metadata| { + receipt = openbitfun_services_core::session::acknowledge_session_result( + metadata, + turn_id, + completion_kind, + ); + }) + .await + .map_err(|error| error.to_string())?; + let Some(receipt) = receipt else { + return Ok(false); + }; + let completion_kind = match receipt.status { + openbitfun_services_core::session::TurnStatus::Completed => "completed", + openbitfun_services_core::session::TurnStatus::Error => "error", + openbitfun_services_core::session::TurnStatus::Cancelled => "interrupted", + openbitfun_services_core::session::TurnStatus::InProgress => return Ok(false), + }; + self.coordinator + .emit_event(AgenticEvent::SessionResultRead { + session_id: session_id.to_string(), + turn_id: receipt.turn_id, + execution_generation: receipt.execution_generation.unwrap_or(0), + completion_kind: completion_kind.to_string(), + recovery_pending: receipt.recovery_pending, + }) + .await; + Ok(true) + } + async fn update_session_title(&self, session_id: &str, title: &str) -> Result { self.coordinator .update_session_title(session_id, title) diff --git a/src/crates/contracts/events/AGENTS.md b/src/crates/contracts/events/AGENTS.md index 39e889afa5..381f953491 100644 --- a/src/crates/contracts/events/AGENTS.md +++ b/src/crates/contracts/events/AGENTS.md @@ -21,6 +21,7 @@ It describes events; it does not own event delivery or product decisions. ```bash cargo check -p openbitfun-events +cargo test --locked -p openbitfun-events --lib frontend_projection::tests::result_read_projects_the_same_turn_identity_for_peer_and_local_consumers node scripts/check-core-boundaries.mjs ``` diff --git a/src/crates/contracts/events/src/agentic.rs b/src/crates/contracts/events/src/agentic.rs index 03f00f4e11..16c2dc9558 100644 --- a/src/crates/contracts/events/src/agentic.rs +++ b/src/crates/contracts/events/src/agentic.rs @@ -126,6 +126,16 @@ pub enum AgenticEvent { new_state: String, }, + /// An owning host durably acknowledged a result through another surface. + SessionResultRead { + session_id: String, + turn_id: String, + execution_generation: u32, + completion_kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + recovery_pending: Option, + }, + /// The authoritative visible history for a session changed outside the /// append-only turn lifecycle (for example, after restoring a checkpoint). /// Consumers should invalidate cached transcript projections for this @@ -708,6 +718,7 @@ impl AgenticEvent { Self::SessionCreated { session_id, .. } | Self::SessionStateChanged { session_id, .. } | Self::SessionHistoryChanged { session_id, .. } + | Self::SessionResultRead { session_id, .. } | Self::SessionDeleted { session_id } | Self::SessionTitleGenerated { session_id, .. } | Self::PromptSuggestionGenerated { session_id, .. } @@ -743,6 +754,7 @@ impl AgenticEvent { pub fn turn_id(&self) -> Option<&str> { match self { Self::DialogTurnStarted { turn_id, .. } + | Self::SessionResultRead { turn_id, .. } | Self::DialogTurnCompleted { turn_id, .. } | Self::DialogTurnCancelled { turn_id, .. } | Self::DialogTurnInterrupted { turn_id, .. } @@ -777,6 +789,7 @@ impl AgenticEvent { Self::SessionStateChanged { .. } | Self::SessionHistoryChanged { .. } + | Self::SessionResultRead { .. } | Self::SessionTitleGenerated { .. } | Self::SessionModelFallbackApplied { .. } | Self::SessionReasoningPresetAutoCleared { .. } diff --git a/src/crates/contracts/events/src/frontend_projection.rs b/src/crates/contracts/events/src/frontend_projection.rs index d9ad0c6442..3250c5427e 100644 --- a/src/crates/contracts/events/src/frontend_projection.rs +++ b/src/crates/contracts/events/src/frontend_projection.rs @@ -408,6 +408,18 @@ pub fn project_agentic_frontend_event(event: AgenticEvent) -> Option Some(AgenticFrontendEvent::new( + "agentic://session-result-read", + json!({ "sessionId": session_id, "turnId": turn_id, + "executionGeneration": execution_generation, "completionKind": completion_kind, + "recoveryPending": recovery_pending }), + )), AgenticEvent::SessionHistoryChanged { session_id, settled_turn_id, @@ -895,6 +907,27 @@ mod tests { ); } + #[test] + fn result_read_projects_the_same_turn_identity_for_peer_and_local_consumers() { + let event = AgenticEvent::SessionResultRead { + session_id: "session".into(), + turn_id: "turn".into(), + execution_generation: 2, + completion_kind: "completed".into(), + recovery_pending: Some(false), + }; + let event: AgenticEvent = + serde_json::from_value(serde_json::to_value(event).unwrap()).unwrap(); + assert_eq!(event.session_id(), Some("session")); + assert_eq!(event.turn_id(), Some("turn")); + let projected = project_agentic_frontend_event(event).unwrap(); + assert_eq!(projected.event_name, "agentic://session-result-read"); + assert_eq!( + projected.payload, + json!({"sessionId":"session", "turnId":"turn", "executionGeneration":2, "completionKind":"completed", "recoveryPending":false}) + ); + } + #[test] fn reasoning_preset_auto_clear_projects_canonical_auto_transition() { let projected = diff --git a/src/crates/services/services-core/src/session/metadata.rs b/src/crates/services/services-core/src/session/metadata.rs index 8e3b0a0bee..81dd6777f1 100644 --- a/src/crates/services/services-core/src/session/metadata.rs +++ b/src/crates/services/services-core/src/session/metadata.rs @@ -346,16 +346,9 @@ fn refresh_latest_turn(metadata: &mut SessionMetadata, turn: &DialogTurnData) { && openbitfun_core_types::background_delivery::BackgroundDelivery::from_metadata(turn.user_message.metadata.as_ref(), &turn.turn_id) .is_some_and(|delivery| delivery.execution_generation == turn.recovery_epoch.unwrap_or(0) && delivery.disposition == openbitfun_core_types::background_delivery::BackgroundReportDisposition::Quiet && delivery.suppresses_report()); - let source = turn - .user_message - .metadata - .as_ref() - .and_then(|metadata| metadata.get("submissionSource")) - .and_then(Value::as_str); - // IM is the reading surface for bot turns. Keep any earlier desktop result - // unread, but do not create another receipt for this turn on the host. - let bot = source == Some("bot"); let mut unread_target = previous_unread_target; + let read = + read_completion_target(metadata).is_some_and(|receipt| same_completion(&receipt, &next)); if !same_outcome && !quiet { if let Some(outcome) = match turn.status { TurnStatus::Completed => Some("completed"), @@ -364,7 +357,7 @@ fn refresh_latest_turn(metadata: &mut SessionMetadata, turn: &DialogTurnData) { TurnStatus::InProgress => None, } { metadata.needs_user_attention = None; - if !bot { + if !read { metadata.unread_completion = Some(outcome.to_string()); unread_target = Some(next.clone()); } @@ -374,14 +367,6 @@ fn refresh_latest_turn(metadata: &mut SessionMetadata, turn: &DialogTurnData) { .custom_metadata .get_or_insert_with(|| serde_json::json!({})); if let Some(object) = custom.as_object_mut() { - if let Some(source) = source { - object.insert( - "lastTurnSource".to_owned(), - Value::String(source.to_owned()), - ); - } else { - object.remove("lastTurnSource"); - } if let Some(delivery) = openbitfun_core_types::background_delivery::BackgroundDelivery::from_metadata( turn.user_message.metadata.as_ref(), @@ -413,6 +398,167 @@ pub fn unread_completion_target(metadata: &SessionMetadata) -> Option Option { + metadata + .custom_metadata + .as_ref()? + .get("readCompletionTarget") + .and_then(|value| serde_json::from_value(value.clone()).ok()) +} + +fn same_completion(left: &SessionLastTurn, right: &SessionLastTurn) -> bool { + left.turn_id == right.turn_id + && left.execution_generation.unwrap_or(0) == right.execution_generation.unwrap_or(0) + && left.status == right.status + && left + .recovery_pending + .zip(right.recovery_pending) + .is_none_or(|(a, b)| a == b) +} + +#[cfg(test)] +mod delivered_result_contracts { + use super::super::types::UserMessageData; + use super::*; + + fn turn(id: &str, index: usize, status: TurnStatus) -> DialogTurnData { + let mut turn = DialogTurnData::new( + id.into(), + index, + "session".into(), + UserMessageData { + id: format!("{id}-input"), + content: "hello".into(), + timestamp: index as u64, + metadata: Some(serde_json::json!({"submissionSource":"bot"})), + }, + ); + turn.status = status; + turn + } + + #[test] + fn only_successful_delivery_clears_a_result_and_survives_reload_and_old_writers() { + for (kind, status) in [ + ("completed", TurnStatus::Completed), + ("error", TurnStatus::Error), + ("interrupted", TurnStatus::Cancelled), + ] { + let mut metadata = SessionMetadata::new( + "session".into(), + "Bot".into(), + "Standard".into(), + "model".into(), + ); + let turn = turn("bot", 0, status); + refresh_latest_turn(&mut metadata, &turn); + assert_eq!(metadata.unread_completion.as_deref(), Some(kind)); + let old_observer = metadata.clone(); + assert!(acknowledge_session_result(&mut metadata, "bot", Some(kind)).is_some()); + assert!(metadata.unread_completion.is_none()); + let mut reloaded: SessionMetadata = + serde_json::from_value(serde_json::to_value(metadata).unwrap()).unwrap(); + refresh_latest_turn(&mut reloaded, &turn); + apply_session_unread_completion(&mut reloaded, &old_observer); + assert!(reloaded.unread_completion.is_none()); + assert!(acknowledge_session_result(&mut reloaded, "bot", Some(kind)).is_some()); + } + } + + #[test] + fn delivery_before_terminal_persistence_does_not_lose_the_receipt() { + let mut metadata = SessionMetadata::new( + "session".into(), + "Bot".into(), + "Standard".into(), + "model".into(), + ); + let mut turn = turn("bot", 0, TurnStatus::InProgress); + refresh_latest_turn(&mut metadata, &turn); + assert!(acknowledge_session_result(&mut metadata, "bot", Some("completed")).is_some()); + turn.status = TurnStatus::Completed; + refresh_latest_turn(&mut metadata, &turn); + assert!(metadata.unread_completion.is_none()); + turn.recovery_epoch = Some(1); + refresh_latest_turn(&mut metadata, &turn); + assert_eq!(metadata.unread_completion.as_deref(), Some("completed")); + } + + #[test] + fn delayed_delivery_does_not_clear_another_turn_or_pending_interaction() { + let mut metadata = SessionMetadata::new( + "session".into(), + "Mixed".into(), + "Standard".into(), + "model".into(), + ); + refresh_latest_turn(&mut metadata, &turn("bot", 0, TurnStatus::Completed)); + refresh_latest_turn(&mut metadata, &turn("desktop", 1, TurnStatus::Error)); + metadata.needs_user_attention = Some("tool_confirm".into()); + assert!(acknowledge_session_result(&mut metadata, "bot", Some("completed")).is_none()); + assert_eq!(metadata.unread_completion.as_deref(), Some("error")); + assert_eq!( + metadata.needs_user_attention.as_deref(), + Some("tool_confirm") + ); + } +} + +/// Acknowledge only the delivered Turn, preserving another Turn's unread result. +/// The terminal event can precede its metadata write. A known completion kind +/// records that receipt first, and the subsequent save honors it. +pub fn acknowledge_session_result( + metadata: &mut SessionMetadata, + turn_id: &str, + completion_kind: Option<&str>, +) -> Option { + let unread = unread_completion_target(metadata); + let mut receipt = unread + .as_ref() + .filter(|turn| turn.turn_id == turn_id) + .or_else(|| { + metadata + .last_turn + .as_ref() + .filter(|turn| turn.turn_id == turn_id) + })? + .clone(); + let status = match completion_kind { + Some("completed") => TurnStatus::Completed, + Some("error") => TurnStatus::Error, + Some("interrupted") => TurnStatus::Cancelled, + Some(_) => return None, + None => receipt.status.clone(), + }; + if status == TurnStatus::InProgress + || (receipt.status != TurnStatus::InProgress && receipt.status != status) + { + return None; + } + receipt.status = status; + if receipt.status != TurnStatus::Cancelled { + receipt.recovery_pending = Some(false); + } + let should_clear = unread + .as_ref() + .is_some_and(|turn| same_completion(turn, &receipt)); + let custom = metadata + .custom_metadata + .get_or_insert_with(|| serde_json::json!({})); + let object = custom.as_object_mut()?; + object.insert( + "readCompletionTarget".into(), + serde_json::to_value(&receipt).ok()?, + ); + if should_clear { + metadata.unread_completion = None; + object.remove("unreadCompletionTarget"); + } + Some(receipt) +} + fn receipt_target(metadata: &SessionMetadata) -> Option { metadata .custom_metadata @@ -524,126 +670,39 @@ mod background_delivery_contracts { } } -#[cfg(test)] -mod bot_read_contracts { - use super::super::types::UserMessageData; - use super::*; - - fn turn(id: &str, index: usize, source: Option<&str>) -> DialogTurnData { - let mut turn = DialogTurnData::new( - id.into(), - index, - "session".into(), - UserMessageData { - id: format!("{id}-input"), - content: "hello".into(), - timestamp: index as u64, - metadata: source.map(|source| serde_json::json!({ "submissionSource": source })), - }, - ); - turn.status = TurnStatus::Completed; - turn - } - - #[test] - fn bot_results_stay_read_after_reload_and_legacy_observer_writes() { - for status in [ - TurnStatus::Completed, - TurnStatus::Error, - TurnStatus::Cancelled, - ] { - let mut metadata = SessionMetadata::new( - "session".into(), - "Bot".into(), - "Standard".into(), - "model".into(), - ); - let mut bot = turn("bot", 0, Some("bot")); - bot.status = status; - metadata.needs_user_attention = Some("tool_confirm".into()); - refresh_latest_turn(&mut metadata, &bot); - assert!(metadata.unread_completion.is_none()); - assert!(metadata.needs_user_attention.is_none()); - assert_eq!(metadata.last_turn.as_ref().unwrap().turn_id, "bot"); - - let mut reloaded: SessionMetadata = - serde_json::from_value(serde_json::to_value(&metadata).unwrap()).unwrap(); - let persisted: DialogTurnData = - serde_json::from_value(serde_json::to_value(&bot).unwrap()).unwrap(); - refresh_latest_turn(&mut reloaded, &persisted); - let mut old_observer = reloaded.clone(); - old_observer.unread_completion = Some("completed".into()); - apply_session_unread_completion(&mut reloaded, &old_observer); - assert!(reloaded.unread_completion.is_none()); - - // Legacy turns without a source retain their unread semantics. - refresh_latest_turn(&mut reloaded, &turn("legacy", 1, None)); - assert_eq!(reloaded.unread_completion.as_deref(), Some("completed")); - assert!(reloaded - .custom_metadata - .as_ref() - .unwrap() - .get("lastTurnSource") - .is_none()); - } - } - - #[test] - fn bot_turn_keeps_an_earlier_desktop_result_and_its_read_receipt() { - let mut metadata = SessionMetadata::new( - "session".into(), - "Mixed".into(), - "Standard".into(), - "model".into(), - ); - refresh_latest_turn(&mut metadata, &turn("desktop", 0, Some("desktop_ui"))); - let mut receipt = metadata.clone(); - receipt.unread_completion = None; - let bot = turn("bot", 1, Some("bot")); - refresh_latest_turn(&mut metadata, &bot); - assert_eq!( - unread_completion_target(&metadata).unwrap().turn_id, - "desktop" - ); - apply_session_unread_completion(&mut metadata, &receipt); - assert!(metadata.unread_completion.is_none()); - refresh_latest_turn(&mut metadata, &bot); - assert!(metadata.unread_completion.is_none()); - } -} - /// A delayed UI acknowledgement must not clear a newer completion. New clients /// name the rendered Turn/generation; old clients retain the finish-time guard. pub fn apply_session_unread_completion(current: &mut SessionMetadata, incoming: &SessionMetadata) { let current_target = unread_completion_target(current); let incoming_target = receipt_target(incoming); - // An older observer may still mark a quiet or bot completion as unread work. + if incoming.unread_completion.is_some() + && read_completion_target(current) + .as_ref() + .zip(incoming_target.as_ref()) + .is_some_and(|(read, incoming)| same_completion(read, incoming)) + { + return; + } + // An older observer may still mark a quiet completion as new unread work. // Read receipts remain client-owned, while the host owns result creation. - let bot_latest = current - .custom_metadata + let suppressed_latest = current + .last_turn .as_ref() - .and_then(|custom| custom.get("lastTurnSource")) - .and_then(Value::as_str) - == Some("bot"); - let suppressed_latest = bot_latest - || current - .last_turn - .as_ref() - .and_then(|last| { - let value = current - .custom_metadata - .as_ref()? - .get("lastBackgroundDelivery")?; - let delivery: openbitfun_core_types::background_delivery::BackgroundDelivery = - serde_json::from_value(value.clone()).ok()?; - Some( - delivery.run_id == last.turn_id - && delivery.execution_generation == last.execution_generation.unwrap_or(0) - && last.status == TurnStatus::Completed - && delivery.suppresses_report(), - ) - }) - .unwrap_or(false); + .and_then(|last| { + let value = current + .custom_metadata + .as_ref()? + .get("lastBackgroundDelivery")?; + let delivery: openbitfun_core_types::background_delivery::BackgroundDelivery = + serde_json::from_value(value.clone()).ok()?; + Some( + delivery.run_id == last.turn_id + && delivery.execution_generation == last.execution_generation.unwrap_or(0) + && last.status == TurnStatus::Completed + && delivery.suppresses_report(), + ) + }) + .unwrap_or(false); if current_target.is_none() && incoming.unread_completion.is_some() && suppressed_latest { return; } diff --git a/src/crates/services/services-core/src/session/mod.rs b/src/crates/services/services-core/src/session/mod.rs index 4a95bde9b5..a91a5a9221 100644 --- a/src/crates/services/services-core/src/session/mod.rs +++ b/src/crates/services/services-core/src/session/mod.rs @@ -26,11 +26,11 @@ pub use memory_workspace::{ MemoryWorkspaceDiff, MemoryWorkspaceGitError, }; pub use metadata::{ - apply_session_title_metadata, apply_session_unread_completion, build_session_index_snapshot, - build_session_metadata, estimate_turn_message_count, merge_session_custom_metadata, - normalized_session_relationship, refresh_session_metadata_from_turns, - remove_session_index_entry, set_deep_review_cache, set_deep_review_run_manifest, - set_review_target_evidence, set_session_relationship, + acknowledge_session_result, apply_session_title_metadata, apply_session_unread_completion, + build_session_index_snapshot, build_session_metadata, estimate_turn_message_count, + merge_session_custom_metadata, normalized_session_relationship, read_completion_target, + refresh_session_metadata_from_turns, remove_session_index_entry, set_deep_review_cache, + set_deep_review_run_manifest, set_review_target_evidence, set_session_relationship, try_refresh_session_metadata_for_saved_turn, unread_completion_target, upsert_session_index_entry, SessionMetadataBuildFacts, }; diff --git a/src/crates/services/services-core/src/session/page.rs b/src/crates/services/services-core/src/session/page.rs index 9c2264f7a6..305e8574e9 100644 --- a/src/crates/services/services-core/src/session/page.rs +++ b/src/crates/services/services-core/src/session/page.rs @@ -84,13 +84,13 @@ pub struct SessionActivitySummary { pub pending_questions: usize, #[serde(default, skip_serializing_if = "Option::is_none")] pub last_turn: Option, - /// Admitted ingress of last_turn, including while a controller was offline. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub last_turn_source: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub unread_completion: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub unread_turn: Option, + /// Durable read receipt, including results delivered through another surface. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read_turn: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -480,26 +480,19 @@ fn session_metadata_page_cursor(metadata: &SessionMetadata, revision: Option Vec { "workspace_id_references_v1".to_string(), REMOTE_CAPABILITY_HARNESS_PROFILES_V1.to_string(), REMOTE_CAPABILITY_DIALOG_STEER_V1.to_string(), - REMOTE_CAPABILITY_BOT_READ_RECEIPTS_V1.to_string(), + REMOTE_CAPABILITY_SESSION_RESULT_ACK_V1.to_string(), "dialog_queue_v1".to_string(), REMOTE_CAPABILITY_PLAN_BUILD_V1.to_string(), REMOTE_CAPABILITY_SESSION_ATTACHMENTS_V1.to_string(), @@ -1521,6 +1521,14 @@ pub trait RemoteSessionRuntimeHost: Send + Sync { } async fn ensure_session_loaded(&self, session_id: &str) -> Result<(), String>; async fn update_session_title(&self, session_id: &str, title: &str) -> Result; + async fn acknowledge_session_result( + &self, + _session_id: &str, + _turn_id: &str, + _completion_kind: Option<&str>, + ) -> Result { + Err("Host does not support session result acknowledgement".into()) + } async fn resolve_session_storage_dir(&self, session_id: &str) -> Option; async fn load_remote_chat_messages( &self, @@ -1818,6 +1826,31 @@ where Err(message) => RemoteResponse::Error { message }, } } + RemoteCommand::AcknowledgeSessionResult { + session_id, + turn_id, + completion_kind, + } => { + if completion_kind + .as_deref() + .is_some_and(|kind| !matches!(kind, "completed" | "error" | "interrupted")) + { + return RemoteResponse::Error { + message: "Invalid session completion kind".into(), + }; + } + match host + .acknowledge_session_result(session_id, turn_id, completion_kind.as_deref()) + .await + { + Ok(acknowledged) => RemoteResponse::SessionResultAcknowledged { + session_id: session_id.clone(), + turn_id: turn_id.clone(), + acknowledged, + }, + Err(message) => RemoteResponse::Error { message }, + } + } RemoteCommand::UpdateSessionTitle { session_id, title } => { if let Err(message) = host.ensure_session_loaded(session_id).await { return RemoteResponse::Error { message }; @@ -2945,6 +2978,13 @@ pub enum RemoteCommand { session_id: String, title: String, }, + /// Idempotent acknowledgement of a result successfully delivered to a controller. + AcknowledgeSessionResult { + session_id: String, + turn_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + completion_kind: Option, + }, GetSessionMessages { session_id: String, limit: Option, @@ -2953,10 +2993,6 @@ pub enum RemoteCommand { SendMessage { session_id: String, content: String, - /// Optional ingress hint retained by bot forwards across devices. Older - /// hosts ignore it; absent/unknown values keep the transport's source. - #[serde(default, skip_serializing_if = "Option::is_none")] - source: Option, #[serde(default)] display_content: Option, /// Client-generated stable identity for the turn. Older clients omit it; @@ -3206,6 +3242,11 @@ pub enum RemoteResponse { sessions: Vec, has_more: bool, }, + SessionResultAcknowledged { + session_id: String, + turn_id: String, + acknowledged: bool, + }, SessionCreated { session_id: String, /// Owning workspace record ID; authoritative for controllers that pin @@ -3479,6 +3520,7 @@ where | RemoteCommand::SetSessionModel { .. } | RemoteCommand::SetModelDefaults { .. } | RemoteCommand::UpdateSessionTitle { .. } + | RemoteCommand::AcknowledgeSessionResult { .. } | RemoteCommand::GetSessionMessages { .. } | RemoteCommand::DeleteSession { .. } | RemoteCommand::RollbackSessionToTurn { .. } => host.handle_session_command(command).await, @@ -3501,7 +3543,6 @@ where RemoteCommand::SendMessage { session_id, content, - source: ingress_source, display_content, turn_id, agent_type, @@ -3527,13 +3568,7 @@ where display_content: display_content.clone(), agent_type: agent_type.clone(), image_contexts: resolved_contexts, - policy: RemoteDialogSubmissionPolicy::for_source( - if ingress_source.as_deref() == Some("bot") { - RemoteConnectSubmissionSource::Bot - } else { - source - }, - ), + policy: RemoteDialogSubmissionPolicy::for_source(source), turn_id: turn_id.clone(), }) .await, @@ -5123,6 +5158,7 @@ mod tests { #[derive(Default)] struct FakeSessionHost { + read_receipts: Mutex)>>, created_requests: Mutex>, list_identities: Mutex>, model_updates: Mutex>)>>, @@ -5140,6 +5176,33 @@ mod tests { rollback_requests: Mutex)>>, } + #[tokio::test] + async fn delivered_result_ack_routes_the_named_turn_and_validates_completion_kind() { + let host = FakeSessionHost::default(); + let payload = serde_json::json!({"cmd":"acknowledge_session_result", "session_id":"session", "turn_id":"delivered"}); + let command: RemoteCommand = serde_json::from_value(payload.clone()).unwrap(); + assert_eq!(serde_json::to_value(&command).unwrap(), payload); + assert!(matches!( + handle_remote_session_command(&host, &command).await, + RemoteResponse::SessionResultAcknowledged { + acknowledged: true, + .. + } + )); + assert_eq!( + *host.read_receipts.lock().unwrap(), + vec![("session".into(), "delivered".into(), None)] + ); + let invalid: RemoteCommand = serde_json::from_value(serde_json::json!({ + "cmd":"acknowledge_session_result", "session_id":"session", "turn_id":"delivered", "completion_kind":"running" + })).unwrap(); + assert!(matches!( + handle_remote_session_command(&host, &invalid).await, + RemoteResponse::Error { .. } + )); + assert_eq!(host.read_receipts.lock().unwrap().len(), 1); + } + fn fake_workspace( workspace_id: &str, path: &str, @@ -5342,6 +5405,20 @@ mod tests { }) } + async fn acknowledge_session_result( + &self, + session_id: &str, + turn_id: &str, + completion_kind: Option<&str>, + ) -> Result { + self.read_receipts.lock().unwrap().push(( + session_id.into(), + turn_id.into(), + completion_kind.map(str::to_owned), + )); + Ok(true) + } + async fn update_session_title( &self, _session_id: &str, diff --git a/src/crates/services/services-integrations/src/remote_connect/session_records.rs b/src/crates/services/services-integrations/src/remote_connect/session_records.rs index 68ca128807..2738b46441 100644 --- a/src/crates/services/services-integrations/src/remote_connect/session_records.rs +++ b/src/crates/services/services-integrations/src/remote_connect/session_records.rs @@ -23,9 +23,11 @@ pub fn session_event_publication(name: &str, payload: &Value) -> SessionEventPub persist_control: false, }; } - // A next-input suggestion is not transcript content; its source turn was - // already synchronized by the completion event that precedes it. - if name == "agentic://prompt-suggestion" { + // Suggestions and read receipts are controls, not transcript mutations. + if matches!( + name, + "agentic://prompt-suggestion" | "agentic://session-result-read" + ) { return SessionEventPublication { synchronize_records: false, persist_control: true, @@ -181,4 +183,14 @@ mod publication_tests { assert!(!policy.synchronize_records); assert!(policy.persist_control); } + + #[test] + fn read_receipts_replay_without_rebuilding_transcripts() { + let policy = session_event_publication( + "agentic://session-result-read", + &json!({"sessionId":"session", "turnId":"turn"}), + ); + assert!(policy.persist_control); + assert!(!policy.synchronize_records); + } } diff --git a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs index af26a522c7..e6799dfb83 100644 --- a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs +++ b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs @@ -1262,7 +1262,6 @@ async fn remote_connect_command_owner_routes_send_message_and_prefers_explicit_i &RemoteCommand::SendMessage { session_id: "session-1".to_string(), content: "hello".to_string(), - source: None, display_content: None, turn_id: Some("harmony-turn-1".to_string()), agent_type: Some("code".to_string()), @@ -1305,34 +1304,6 @@ async fn remote_connect_command_owner_routes_send_message_and_prefers_explicit_i assert_eq!(submitted.turn_id.as_deref(), Some("harmony-turn-1")); } -#[tokio::test] -async fn remote_connect_command_preserves_bot_ingress_and_legacy_send_payloads() { - for (source, expected) in [ - (None, RemoteConnectSubmissionSource::Relay), - (Some("bot"), RemoteConnectSubmissionSource::Bot), - (Some("future_source"), RemoteConnectSubmissionSource::Relay), - ] { - let host = RecordingCommandHost::default(); - let mut payload = serde_json::json!({ - "cmd": "send_message", "session_id": "session", "content": "hello" - }); - if let Some(source) = source { - payload["source"] = serde_json::json!(source); - } - let command: RemoteCommand = serde_json::from_value(payload).unwrap(); - let encoded = serde_json::to_value(&command).unwrap(); - assert_eq!( - encoded.get("source").and_then(serde_json::Value::as_str), - source - ); - let round_trip: RemoteCommand = serde_json::from_value(encoded).unwrap(); - let response = - handle_remote_command(&host, &round_trip, RemoteConnectSubmissionSource::Relay).await; - assert!(matches!(response, RemoteResponse::MessageSent { .. })); - assert_eq!(host.submitted_dialog().policy.source, expected); - } -} - #[tokio::test] async fn remote_connect_command_owner_builds_a_projected_plan_with_hidden_execution_copy() { let host = RecordingCommandHost { @@ -2393,7 +2364,7 @@ fn remote_connect_workspace_response_helpers_own_wire_shape() { "workspace_id_references_v1", REMOTE_CAPABILITY_HARNESS_PROFILES_V1, REMOTE_CAPABILITY_DIALOG_STEER_V1, - "bot_read_receipts_v1", + "session_result_ack_v1", "dialog_queue_v1", REMOTE_CAPABILITY_PLAN_BUILD_V1, "session_attachments_v1", @@ -2645,7 +2616,7 @@ fn remote_connect_session_response_helpers_own_pagination_and_timestamps() { "workspace_id_references_v1", REMOTE_CAPABILITY_HARNESS_PROFILES_V1, REMOTE_CAPABILITY_DIALOG_STEER_V1, - "bot_read_receipts_v1", + "session_result_ack_v1", "dialog_queue_v1", REMOTE_CAPABILITY_PLAN_BUILD_V1, "session_attachments_v1", @@ -2808,7 +2779,6 @@ fn remote_connect_command_wire_shape_lives_in_owner_contract() { let command = RemoteCommand::SendMessage { session_id: "session-1".to_string(), content: "hello".to_string(), - source: None, display_content: None, turn_id: Some("harmony-turn-1".to_string()), agent_type: Some("code".to_string()), diff --git a/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts b/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts index 31778d0cbd..5bca88db9c 100644 --- a/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts +++ b/src/web-ui/src/flow_chat/services/sessionNavStatusService.test.ts @@ -21,7 +21,7 @@ const sources = vi.hoisted(() => ({ machineListeners: new Set<(sessionId: string, machine: SessionStateMachine) => void>(), })); vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({ agentAPI: Object.fromEntries([ - 'onSessionStateChanged', 'onSessionHistoryChanged', 'onSessionDeleted', 'onDialogTurnStarted', + 'onSessionStateChanged', 'onSessionHistoryChanged', 'onSessionResultRead', 'onSessionDeleted', 'onDialogTurnStarted', 'onDialogTurnCompleted', 'onDialogTurnFailed', 'onDialogTurnCancelled', 'onDialogTurnInterrupted', 'onDialogTurnRecovered', 'onToolEvent', ].map(name => [name, (callback: (event: unknown) => void) => { sources.events.set(name, callback); @@ -285,7 +285,7 @@ describe('navigation status synchronization', () => { await vi.advanceTimersByTimeAsync(100); expect(sources.read).toHaveBeenCalledTimes(1); expect(sources.read.mock.calls[0][0].sessionIds).toHaveLength(40); - expect(sources.events.size).toBe(10); + expect(sources.events.size).toBe(11); for (const id of ids) { expect(sessionNavStatusService.getSnapshot(id).kind).toBe('running'); expect(sources.sessions.get(id)?.dialogTurns).toHaveLength(0); @@ -305,6 +305,23 @@ describe('navigation status synchronization', () => { expect(sources.sessions.get(id)?.unreadCompletionTurnId).toBe('new'); }); + it('clears an unopened row only after the host confirms IM delivery', async () => { + const id = 'im-delivered'; + sources.sessions.set(id, row(id)); + sources.read.mockResolvedValue(response([activity(id, 'idle')])); + install(id); + await vi.advanceTimersByTimeAsync(100); + sources.events.get('onDialogTurnStarted')!({ sessionId: id, turnId: 'turn', userMessageMetadata: { submissionSource: 'bot' } }); + sources.events.get('onDialogTurnCompleted')!({ sessionId: id, turnId: 'turn' }); + expect(sessionNavStatusService.getSnapshot(id).kind).toBe('unread'); + sources.events.get('onSessionResultRead')!({ sessionId: id, turnId: 'turn', executionGeneration: 0, completionKind: 'completed' }); + expect(sessionNavStatusService.getSnapshot(id).kind).toBe('idle'); + sources.events.get('onDialogTurnCompleted')!({ sessionId: id, turnId: 'turn' }); + expect(sessionNavStatusService.getSnapshot(id).kind).toBe('idle'); + expect(sources.sessions.get(id)?.hasUnreadCompletion).toBeUndefined(); + expect(sources.sessions.get(id)?.dialogTurns).toHaveLength(0); + }); + it('reconciles only the permission owner and delegated parent when their mailbox changes', async () => { const ids = ['approval-owner', 'delegated-parent', 'unaffected']; ids.forEach(id => sources.sessions.set(id, row(id))); diff --git a/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts b/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts index 83f097dac5..770cf1a5bc 100644 --- a/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts +++ b/src/web-ui/src/flow_chat/services/sessionNavStatusService.ts @@ -164,6 +164,7 @@ export function installSessionNavStatusService(): () => void { const events: Array<[string, (callback: (event: AgenticEvent) => void) => () => void]> = [ ['agentic://session-state-changed', callback => agentAPI.onSessionStateChanged(callback)], ['agentic://session-history-changed', callback => agentAPI.onSessionHistoryChanged(callback)], + ['agentic://session-result-read', callback => agentAPI.onSessionResultRead(callback)], ['agentic://session-deleted', callback => agentAPI.onSessionDeleted(callback)], ['agentic://dialog-turn-started', callback => agentAPI.onDialogTurnStarted(callback)], ['agentic://dialog-turn-completed', callback => agentAPI.onDialogTurnCompleted(callback)], 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 5b1a71ca86..2e491d68f6 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -797,6 +797,26 @@ describe('FlowChatStore metadata persistence callbacks', () => { }); }); + it.each(['ready', 'metadata-only'] as const)('honors a delivered IM receipt before a late completion with %s history', historyState => { + const session = { ...completedSession(), sessionId: `im-delivery-${historyState}`, historyState, + hasUnreadCompletion: undefined, unreadCompletionTurnId: undefined }; + if (historyState === 'metadata-only') session.dialogTurns = []; + flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]) })); + const persist = vi.fn(); + flowChatStore.registerPersistUnreadCompletionCallback(persist); + const lastTurn = { turnId: 'finished-turn', turnIndex: 0, status: 'completed' as const, executionGeneration: 2 }; + sessionActivityStore.applyRead(sessionActivityStore.beginRead(), [{ + sessionId: session.sessionId, execution: 'idle', pendingApprovals: 1, pendingQuestions: 0, + lastTurn, readTurn: lastTurn, + }]); + flowChatStore.markSessionUnreadCompletion(session.sessionId, 'completed', 'finished-turn'); + expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBeUndefined(); + expect(persist).not.toHaveBeenCalled(); + flowChatStore.markSessionUnreadCompletion(session.sessionId, 'completed', 'next-turn'); + expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBe('completed'); + expect(persist).toHaveBeenCalledOnce(); + }); + it.each(['new', 'metadata-only', 'ready'] as const)( 'explicitly acknowledges a %s session and keeps a refreshed result read', (historyState) => { const session = { ...completedSession(), sessionId: `explicit-read-${historyState}`, historyState }; @@ -844,42 +864,6 @@ describe('FlowChatStore metadata persistence callbacks', () => { expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBe('completed'); }); - it('keeps a reconnecting bot completion read before its transcript is loaded', () => { - const session = createSession({ sessionId: 'bot-reconnect', dialogTurns: [], historyState: 'metadata-only' }); - flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]) })); - sessionActivityStore.applyRead(sessionActivityStore.beginRead(), [{ - sessionId: session.sessionId, execution: 'running', pendingApprovals: 0, pendingQuestions: 0, - lastTurn: { turnId: 'bot', turnIndex: 0, status: 'inprogress' }, lastTurnSource: 'bot', - }]); - const persist = vi.fn(); - flowChatStore.registerPersistUnreadCompletionCallback(persist); - flowChatStore.markSessionUnreadCompletion(session.sessionId, 'completed', 'bot'); - expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBeUndefined(); - expect(persist).not.toHaveBeenCalled(); - }); - - it.each(['completed', 'error', 'interrupted'] as const)('keeps bot %s results read without persisting another receipt', (outcome) => { - const session = completedSession(); - session.hasUnreadCompletion = undefined; - session.dialogTurns[0].userMessage.metadata = { submissionSource: 'bot' }; - flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]) })); - const persist = vi.fn(); - flowChatStore.registerPersistUnreadCompletionCallback(persist); - - flowChatStore.markSessionUnreadCompletion(session.sessionId, outcome, session.dialogTurns[0].id); - expect(flowChatStore.getState().sessions.get(session.sessionId)?.hasUnreadCompletion).toBeUndefined(); - expect(persist).not.toHaveBeenCalled(); - - // A bot result cannot acknowledge an earlier desktop result in this session. - flowChatStore.applySessionActivityReceipt({ - sessionId: session.sessionId, execution: 'idle', pendingApprovals: 0, pendingQuestions: 0, - unreadCompletion: 'completed', unreadTurn: { turnId: 'desktop', turnIndex: 0, status: 'completed' }, - }); - flowChatStore.markSessionUnreadCompletion(session.sessionId, outcome); - expect(flowChatStore.getState().sessions.get(session.sessionId)?.unreadCompletionTurnId).toBe('desktop'); - expect(persist).not.toHaveBeenCalled(); - }); - it('attaches the completion to its owner when a follow-up turn already exists', () => { const session = completedSession(); session.dialogTurns.push({ ...session.dialogTurns[0], id: 'queued-follow-up', status: 'pending' }); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index d9776ebae0..e77eee5c6f 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -7423,10 +7423,16 @@ export class FlowChatStore { const session = this.state.sessions.get(sessionId); const turn = turnId ? session?.dialogTurns.find(candidate => candidate.id === turnId) : session && lastUserDialogTurn(session); - const activity = sessionActivityStore.get(sessionId)?.summary; + const summary = sessionActivityStore.get(sessionId)?.summary; const resultTurnId = turnId ?? turn?.id; - if (turn?.userMessage.metadata?.submissionSource === 'bot' - || (resultTurnId && activity?.lastTurn?.turnId === resultTurnId && activity.lastTurnSource === 'bot')) return; + const generation = Math.max(turn?.recovery?.executionGeneration ?? turn?.recoveryEpoch ?? 0, + summary?.lastTurn?.turnId === resultTurnId ? summary?.lastTurn?.executionGeneration ?? 0 : 0); + if (resultTurnId && summary?.readTurn?.turnId === resultTurnId + && (summary.readTurn.executionGeneration ?? 0) === (generation ?? 0) + && summary.readTurn.status === (completionKind === 'interrupted' ? 'cancelled' : completionKind) + && (summary.readTurn.recoveryPending === undefined || summary.lastTurn?.turnId !== resultTurnId + || summary.lastTurn.recoveryPending === undefined + || summary.readTurn.recoveryPending === summary.lastTurn.recoveryPending)) return; this.setState(prev => { const session = prev.sessions.get(sessionId); diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts index deee181fa1..32be106ac4 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.test.ts @@ -8,47 +8,50 @@ const summary = (execution = 'idle', id = 'session'): SessionActivitySummary => }); describe('session activity read projection', () => { - it('keeps a bot result read when reconnecting after its start event', () => { - const store = new SessionActivityStore(); - const hostSummary = { - ...summary('running'), activeTurnId: 'bot', lastTurnSource: 'bot', - lastTurn: { turnId: 'bot', turnIndex: 0, status: 'inprogress' as const }, - }; - store.applyRead(store.beginRead('peer'), [hostSummary]); - store.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'bot' }); - expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); - expect(store.get('session', 'peer')?.summary?.execution).toBe('idle'); - }); - - it.each(['completed', 'failed', 'cancelled', 'interrupted'])('keeps bot %s results read on local and peer surfaces', (outcome) => { - for (const surface of ['local', 'peer']) { + it.each(['completed', 'error', 'interrupted'] as const)('keeps %s unread until successful IM delivery and accepts the receipt before completion', (kind) => { + for (const receiptFirst of [false, true]) { const store = new SessionActivityStore(); - store.observe(surface, 'agentic://dialog-turn-started', { - sessionId: 'session', turnId: 'bot', userMessageMetadata: { submissionSource: 'bot' }, - }); - store.observe(surface, 'agentic://dialog-turn-' + outcome, { sessionId: 'session', turnId: 'bot' }); - expect(store.get('session', surface)?.summary?.unreadCompletion).toBeUndefined(); - expect(store.get('session', surface)?.summary?.lastTurn?.turnId).toBe('bot'); - store.observe(surface, 'agentic://dialog-turn-started', { sessionId: 'session', turnId: 'desktop' }); - store.observe(surface, 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'desktop' }); - expect(store.get('session', surface)?.summary?.unreadCompletion).toBe('completed'); + const terminal = kind === 'completed' ? 'completed' : kind === 'error' ? 'failed' : 'cancelled'; + const complete = () => store.observe('peer', `agentic://dialog-turn-${terminal}`, { sessionId: 'session', turnId: 'bot', executionGeneration: 0 }); + store.observe('peer', 'agentic://dialog-turn-started', { sessionId: 'session', turnId: 'bot', userMessageMetadata: { submissionSource: 'bot' } }); + if (!receiptFirst) { + complete(); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBe(kind); + } + const stale = store.beginRead('peer'); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'bot', executionGeneration: 0, completionKind: kind }); + complete(); + store.applyRead(stale, [{ ...summary(), unreadCompletion: kind }]); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + const snapshot = store.get('session', 'peer')!.summary!; + const reconnected = new SessionActivityStore(); + reconnected.applyRead(reconnected.beginRead('peer'), [snapshot]); + reconnected.observe('peer', `agentic://dialog-turn-${terminal}`, { sessionId: 'session', turnId: 'bot', executionGeneration: 0 }); + expect(reconnected.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + reconnected.observe('peer', 'agentic://dialog-turn-recovered', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); + reconnected.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); + expect(reconnected.get('session', 'peer')?.summary?.unreadCompletion).toBe('completed'); } }); - it('preserves earlier unread work across bot recovery and host refreshes', () => { + it('does not let an old IM receipt clear a newer result or a different device', () => { const store = new SessionActivityStore(); - store.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'desktop' }); - store.observe('peer', 'agentic://dialog-turn-started', { - sessionId: 'session', turnId: 'bot', userMessageMetadata: { submissionSource: 'bot' }, - }); - store.applyRead(store.beginRead('peer'), [{ ...store.get('session', 'peer')!.summary!, lastTurnSource: undefined }]); - store.observe('peer', 'agentic://dialog-turn-recovered', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); - store.observe('peer', 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'bot', executionGeneration: 1 }); - expect(store.get('session', 'peer')?.summary).toMatchObject({ - unreadCompletion: 'completed', unreadTurn: { turnId: 'desktop' }, lastTurn: { turnId: 'bot' }, - }); + for (const surface of ['local', 'peer']) store.observe(surface, 'agentic://dialog-turn-completed', { sessionId: 'session', turnId: 'desktop' }); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'bot', executionGeneration: 0, completionKind: 'completed' }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBe('completed'); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'desktop', executionGeneration: 0, completionKind: 'completed' }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + expect(store.get('session', 'local')?.summary?.unreadCompletion).toBe('completed'); }); + it('keeps a cancellation unread after an interrupted checkpoint was delivered', () => { + const store = new SessionActivityStore(); + store.observe('peer', 'agentic://dialog-turn-interrupted', { sessionId: 'session', turnId: 'turn', executionGeneration: 1 }); + store.observe('peer', 'agentic://session-result-read', { sessionId: 'session', turnId: 'turn', executionGeneration: 1, completionKind: 'interrupted', recoveryPending: true }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBeUndefined(); + store.observe('peer', 'agentic://dialog-turn-cancelled', { sessionId: 'session', turnId: 'turn', executionGeneration: 1 }); + expect(store.get('session', 'peer')?.summary?.unreadCompletion).toBe('interrupted'); + }); it('keeps a prior unread result across a newer quiet run and acknowledges its original identity', () => { activateSurface('local'); const store = new SessionActivityStore(); diff --git a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts index bc9018640c..03bb76a328 100644 --- a/src/web-ui/src/flow_chat/store/sessionActivityStore.ts +++ b/src/web-ui/src/flow_chat/store/sessionActivityStore.ts @@ -61,10 +61,6 @@ export class SessionActivityStore { // Reads are ordered independently so a slower previous read cannot regress it. if (previous && (previous.eventVersion > read.eventVersion || previous.readSequence > read.sequence)) continue; const previousTurn = previous?.summary?.lastTurn; - if (summary.lastTurnSource === undefined && summary.lastTurn - && summary.lastTurn.turnId === previousTurn?.turnId) { - summary = { ...summary, lastTurnSource: previous?.summary?.lastTurnSource }; - } if (summary.lastTurn && summary.lastTurn.recoveryPending === undefined && previousTurn && previousTurn.turnId === summary.lastTurn.turnId && previousTurn.status === summary.lastTurn.status && (previousTurn.executionGeneration ?? 0) === (summary.lastTurn.executionGeneration ?? 0)) { @@ -152,17 +148,24 @@ export class SessionActivityStore { if (generation !== undefined && summary.lastTurn?.turnId === turnId && (summary.lastTurn?.executionGeneration ?? -1) > generation) return; const starting = eventName === 'agentic://dialog-turn-started' || eventName === 'agentic://dialog-turn-recovered'; - const userMetadata = event.userMessageMetadata as Record | undefined; - const turnSource = eventName === 'agentic://dialog-turn-started' - ? typeof userMetadata?.submissionSource === 'string' ? userMetadata.submissionSource : undefined - : turnId && summary.lastTurn?.turnId === turnId ? summary.lastTurnSource : undefined; const settling = ['agentic://dialog-turn-completed', 'agentic://dialog-turn-failed', 'agentic://dialog-turn-cancelled', 'agentic://dialog-turn-interrupted'].includes(eventName); let newResult = false; - if (starting) { + if (eventName === 'agentic://session-result-read') { + if (!turnId || !['completed', 'error', 'interrupted'].includes(String(event.completionKind))) return; + const status = event.completionKind === 'interrupted' ? 'cancelled' : event.completionKind as 'completed' | 'error'; + const unread = summary.unreadTurn ?? summary.lastTurn; + const matches = unread?.turnId === turnId && (unread.executionGeneration ?? 0) === (generation ?? 0) + && unread.status === status; + summary = { ...summary, + readTurn: { turnId, turnIndex: unread?.turnIndex ?? 0, status, executionGeneration: generation, + recoveryPending: typeof event.recoveryPending === 'boolean' ? event.recoveryPending : undefined }, + unreadCompletion: matches ? undefined : summary.unreadCompletion, + unreadTurn: matches ? undefined : summary.unreadTurn, + }; + } else if (starting) { summary = { ...summary, execution: 'running', activeTurnId: turnId, pendingApprovals: 0, pendingQuestions: 0, - lastTurnSource: turnSource, unreadTurn: summary.unreadCompletion ? summary.unreadTurn ?? summary.lastTurn : undefined, lastTurn: turnId ? { turnId, turnIndex: typeof event.turnIndex === 'number' ? event.turnIndex : summary.lastTurn?.turnIndex ?? 0, @@ -182,11 +185,13 @@ export class SessionActivityStore { // Learning an optional recovery fact from a replay is not a new result. // A known paused -> cancelled transition is, even within one generation. newResult = (!sameOutcome || summary.lastTurn?.recoveryPending !== undefined) - && turnSource !== 'bot' + && !(turnId && summary.readTurn?.turnId === turnId + && (summary.readTurn.executionGeneration ?? 0) === (generation ?? summary.lastTurn?.executionGeneration ?? 0) + && summary.readTurn.status === (outcome === 'interrupted' ? 'cancelled' : outcome) + && (summary.readTurn.recoveryPending === undefined || summary.readTurn.recoveryPending === recoveryPending)) && (outcome !== 'completed' || shouldDeliverBackgroundCompletion(event)); summary = { ...summary, execution: outcome === 'error' ? 'error' : 'idle', activeTurnId: undefined, - lastTurnSource: turnSource, pendingApprovals: 0, pendingQuestions: 0, unreadCompletion: newResult ? outcome : summary.unreadCompletion, unreadTurn: newResult ? { turnId: turnId ?? '', turnIndex: typeof event.turnIndex === 'number' ? event.turnIndex : summary.lastTurn?.turnIndex ?? 0, diff --git a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts index f0bba2373b..35a861a8c8 100644 --- a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts @@ -1446,6 +1446,10 @@ export class AgentAPI { return api.listen('agentic://session-history-changed', callback); } + onSessionResultRead(callback: (event: AgenticEvent) => void): () => void { + return api.listen('agentic://session-result-read', callback); + } + onSessionModelFallbackApplied( callback: (event: SessionModelFallbackAppliedEvent) => void ): () => void { diff --git a/src/web-ui/src/shared/types/session-history.ts b/src/web-ui/src/shared/types/session-history.ts index 07a8cfc990..9d40848e39 100644 --- a/src/web-ui/src/shared/types/session-history.ts +++ b/src/web-ui/src/shared/types/session-history.ts @@ -162,11 +162,11 @@ export interface SessionActivitySummary { pendingApprovals: number; pendingQuestions: number; lastTurn?: SessionLastTurn; - /** Admitted ingress of lastTurn; omitted by older hosts. */ - lastTurnSource?: string; unreadCompletion?: 'completed' | 'error' | 'interrupted'; /** A quiet run can be newer than the unread user-facing result. */ unreadTurn?: SessionLastTurn; + /** Durable acknowledgement from another delivery surface, such as IM. */ + readTurn?: SessionLastTurn; } export interface ReviewActionPersistedState {