diff --git a/src/crates/assembly/core/src/agentic/core/message.rs b/src/crates/assembly/core/src/agentic/core/message.rs index 6dc0cf31cc..bfee1fc248 100644 --- a/src/crates/assembly/core/src/agentic/core/message.rs +++ b/src/crates/assembly/core/src/agentic/core/message.rs @@ -101,6 +101,28 @@ pub struct ModelExecutionMetadata { pub effective_model_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub routing: Option, + /// Accepted-attempt timing of the model round that produced this message. + /// Durable Turn rounds are rebuilt from the generation journal, so the + /// Runtime keeps these facts here instead of relying on a client checkpoint + /// of `ModelRoundCompleted` having landed before the Turn completes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ModelRoundTimingMetadata { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub first_chunk_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub first_visible_output_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stream_duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ttft_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub attempt_count: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -836,6 +858,12 @@ mod tests { latency_ms: 10, fallback_reason: None, }), + timing: Some(super::ModelRoundTimingMetadata { + duration_ms: Some(1200), + ttft_ms: Some(300), + attempt_count: Some(1), + ..Default::default() + }), }); let value = serde_json::to_value(&message).unwrap(); let restored: Message = serde_json::from_value(value.clone()).unwrap(); @@ -843,11 +871,21 @@ mod tests { restored.metadata.ptc_loaded_deferred_tool_specs, message.metadata.ptc_loaded_deferred_tool_specs ); + let execution = restored.metadata.model_execution.unwrap(); + assert_eq!(execution.model_config_id, "economy"); assert_eq!( - restored.metadata.model_execution.unwrap().model_config_id, - "economy" + execution.timing.and_then(|timing| timing.ttft_ms), + Some(300) ); let mut legacy = value; + // Journals written before round timing existed still deserialize. + let mut untimed = legacy.clone(); + untimed["metadata"]["model_execution"] + .as_object_mut() + .unwrap() + .remove("timing"); + let untimed: Message = serde_json::from_value(untimed).unwrap(); + assert!(untimed.metadata.model_execution.unwrap().timing.is_none()); let metadata = legacy["metadata"].as_object_mut().unwrap(); metadata.remove("ptc_loaded_deferred_tool_specs"); metadata.remove("model_execution"); diff --git a/src/crates/assembly/core/src/agentic/execution/round_executor.rs b/src/crates/assembly/core/src/agentic/execution/round_executor.rs index 7d92330eb3..05f71a306e 100644 --- a/src/crates/assembly/core/src/agentic/execution/round_executor.rs +++ b/src/crates/assembly/core/src/agentic/execution/round_executor.rs @@ -1851,21 +1851,31 @@ impl RoundExecutor { !stream_result.tool_calls.is_empty() ); + // The same facts ride on the assistant message so the durable Turn + // round keeps them even when no client checkpointed this event. + let round_timing = crate::agentic::core::message::ModelRoundTimingMetadata { + duration_ms: Some(elapsed_ms_u64(round_started_at)), + first_chunk_ms: stream_result.first_chunk_ms, + first_visible_output_ms: stream_result.first_visible_output_ms, + stream_duration_ms: Some(stream_processing_ms), + ttft_ms, + attempt_count: Some(lifecycle.attempts_started()), + }; self.emit_event( AgenticEvent::ModelRoundCompleted { session_id: context.session_id.clone(), turn_id: context.dialog_turn_id.clone(), round_id: round_id.clone(), has_tool_calls: !stream_result.tool_calls.is_empty(), - duration_ms: Some(elapsed_ms_u64(round_started_at)), + duration_ms: round_timing.duration_ms, provider_id: None, model_config_id: context.model_config_id.clone(), effective_model_name: context.effective_model_name.clone(), - first_chunk_ms: stream_result.first_chunk_ms, - first_visible_output_ms: stream_result.first_visible_output_ms, - stream_duration_ms: Some(stream_processing_ms), - ttft_ms, - attempt_count: Some(lifecycle.attempts_started()), + first_chunk_ms: round_timing.first_chunk_ms, + first_visible_output_ms: round_timing.first_visible_output_ms, + stream_duration_ms: round_timing.stream_duration_ms, + ttft_ms: round_timing.ttft_ms, + attempt_count: round_timing.attempt_count, failure_category: None, token_details: stream_result .usage @@ -1922,6 +1932,7 @@ impl RoundExecutor { model_config_id: context.model_config_id.clone(), effective_model_name: context.effective_model_name.clone(), routing: lifecycle.routing.clone(), + timing: Some(round_timing), }); debug!("Returning RoundResult: has_more_rounds=false"); @@ -1998,6 +2009,7 @@ impl RoundExecutor { model_config_id: context.model_config_id.clone(), effective_model_name: context.effective_model_name.clone(), routing: lifecycle.routing.clone(), + timing: Some(round_timing), }); // Publish the semantic assistant response before tool execution so diff --git a/src/crates/assembly/core/src/agentic/session/session_manager.rs b/src/crates/assembly/core/src/agentic/session/session_manager.rs index 1821197cca..1665387c75 100644 --- a/src/crates/assembly/core/src/agentic/session/session_manager.rs +++ b/src/crates/assembly/core/src/agentic/session/session_manager.rs @@ -8140,6 +8140,14 @@ impl SessionManager { || !tool_items.is_empty() || !thinking_items.is_empty() { + // Messages written before the Runtime recorded round + // timing leave these unknown rather than claiming 0 ms. + let timing = msg + .metadata + .model_execution + .as_ref() + .and_then(|facts| facts.timing) + .unwrap_or_default(); rounds.push(ModelRoundData { id: round_id, turn_id: turn_id.to_string(), @@ -8151,7 +8159,7 @@ impl SessionManager { thinking_items, start_time: timestamp, end_time: Some(timestamp), - duration_ms: Some(0), + duration_ms: timing.duration_ms, provider_id: None, model_config_id: msg .metadata @@ -8168,11 +8176,11 @@ impl SessionManager { .model_execution .as_ref() .and_then(|facts| facts.routing.clone()), - first_chunk_ms: None, - first_visible_output_ms: None, - stream_duration_ms: None, - ttft_ms: None, - attempt_count: None, + first_chunk_ms: timing.first_chunk_ms, + first_visible_output_ms: timing.first_visible_output_ms, + stream_duration_ms: timing.stream_duration_ms, + ttft_ms: timing.ttft_ms, + attempt_count: timing.attempt_count, attempt_diagnostics: vec![], failure_category: None, token_details: None, @@ -8814,7 +8822,15 @@ impl SessionManager { round.timestamp = existing.timestamp; round.start_time = existing.start_time; round.end_time = existing.end_time.or(round.end_time); - round.duration_ms = existing.duration_ms.or(round.duration_ms); + // Round timing is a Runtime fact carried by the generation + // journal. The client checkpoint only mirrors + // `ModelRoundCompleted`, and for the last round it routinely + // loses the race with Turn completion, so it is a fallback for + // journals written before the Runtime recorded timing. Older + // completion writers persisted `0` for unknown durations. + round.duration_ms = round + .duration_ms + .or(existing.duration_ms.filter(|duration_ms| *duration_ms > 0)); round.provider_id = existing.provider_id.clone(); round.model_config_id = round .model_config_id @@ -8823,11 +8839,13 @@ impl SessionManager { .effective_model_name .or_else(|| existing.effective_model_name.clone()); round.routing = round.routing.or_else(|| existing.routing.clone()); - round.first_chunk_ms = existing.first_chunk_ms; - round.first_visible_output_ms = existing.first_visible_output_ms; - round.stream_duration_ms = existing.stream_duration_ms; - round.ttft_ms = existing.ttft_ms; - round.attempt_count = existing.attempt_count; + round.first_chunk_ms = round.first_chunk_ms.or(existing.first_chunk_ms); + round.first_visible_output_ms = round + .first_visible_output_ms + .or(existing.first_visible_output_ms); + round.stream_duration_ms = round.stream_duration_ms.or(existing.stream_duration_ms); + round.ttft_ms = round.ttft_ms.or(existing.ttft_ms); + round.attempt_count = round.attempt_count.or(existing.attempt_count); round.attempt_diagnostics = existing.attempt_diagnostics.clone(); round.failure_category = existing.failure_category.clone(); round.token_details = existing.token_details.clone(); @@ -10787,6 +10805,7 @@ mod tests { latency_ms: 17, fallback_reason: None, }), + timing: None, }); let restored: Message = serde_json::from_value(serde_json::to_value(routed).unwrap()).unwrap(); @@ -10801,6 +10820,77 @@ mod tests { assert_eq!(rounds[1].routing.as_ref().unwrap().latency_ms, 17); } + #[test] + fn completion_merge_keeps_runtime_round_timing_over_stale_client_checkpoint() { + let timed_message = |round_id: &str, timing| { + let mut message = Message::assistant("answer".into()).with_round_id(round_id.into()); + message.metadata.model_execution = + Some(crate::agentic::core::message::ModelExecutionMetadata { + model_config_id: "model".into(), + effective_model_name: "model".into(), + routing: None, + timing, + }); + message + }; + let mut turn = DialogTurnData::new( + "turn".into(), + 0, + "session".into(), + UserMessageData { + id: "input".into(), + content: "hi".into(), + timestamp: 1, + metadata: None, + }, + ); + // The client checkpointed the final round before its + // `ModelRoundCompleted` arrived, and a checkpoint from an older writer + // recorded an unknown duration as 0. + let mut stale = SessionManager::build_model_rounds_from_messages( + &[timed_message("final", None)], + "turn", + 1, + ); + stale[0].duration_ms = Some(0); + // A legacy journal without timing keeps the client's real facts. + let mut checkpointed = SessionManager::build_model_rounds_from_messages( + &[timed_message("legacy", None)], + "turn", + 1, + ); + checkpointed[0].duration_ms = Some(900); + checkpointed[0].ttft_ms = Some(150); + turn.model_rounds = vec![checkpointed.remove(0), stale.remove(0)]; + + let runtime_timing = crate::agentic::core::message::ModelRoundTimingMetadata { + duration_ms: Some(2172), + first_chunk_ms: Some(10), + first_visible_output_ms: Some(20), + stream_duration_ms: Some(1500), + ttft_ms: Some(690), + attempt_count: Some(1), + }; + SessionManager::append_generation_rounds( + &mut turn, + "turn", + &[ + timed_message("legacy", None), + timed_message("final", Some(runtime_timing)), + ], + 2, + ); + + let legacy = &turn.model_rounds[0]; + assert_eq!(legacy.duration_ms, Some(900)); + assert_eq!(legacy.ttft_ms, Some(150)); + let last = &turn.model_rounds[1]; + assert_eq!(last.duration_ms, Some(2172)); + assert_eq!(last.ttft_ms, Some(690)); + assert_eq!(last.stream_duration_ms, Some(1500)); + assert_eq!(last.attempt_count, Some(1)); + } + #[test] fn classified_edit_history_preserves_detail_and_readable_error() { let assistant = Message::assistant_with_tools( diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index b2ef656a79..9645a6f8e0 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -163,6 +163,30 @@ fn merge_runtime_owned_turn_facts( ) -> DialogTurnData { let mut merged = projected.clone(); merged.agent_type = persisted.agent_type.clone(); + // Round timing comes from the Runtime's accepted attempt. A projection + // saved by a window that missed (or had not yet applied) that round's + // `ModelRoundCompleted` must not erase it from the durable record. + for round in &mut merged.model_rounds { + let Some(persisted_round) = persisted + .model_rounds + .iter() + .find(|candidate| candidate.id == round.id) + else { + continue; + }; + if round.duration_ms.is_none_or(|duration_ms| duration_ms == 0) { + round.duration_ms = persisted_round.duration_ms.or(round.duration_ms); + } + round.first_chunk_ms = round.first_chunk_ms.or(persisted_round.first_chunk_ms); + round.first_visible_output_ms = round + .first_visible_output_ms + .or(persisted_round.first_visible_output_ms); + round.stream_duration_ms = round + .stream_duration_ms + .or(persisted_round.stream_duration_ms); + round.ttft_ms = round.ttft_ms.or(persisted_round.ttft_ms); + round.attempt_count = round.attempt_count.or(persisted_round.attempt_count); + } let Some(persisted_metadata) = persisted .user_message @@ -3314,6 +3338,53 @@ mod tests { ); } + #[test] + fn projected_turn_saves_keep_runtime_round_timing() { + let mut persisted = DialogTurnData::new( + "turn-1".to_string(), + 0, + "session-1".to_string(), + UserMessageData { + id: "user-1".to_string(), + content: "hi".to_string(), + timestamp: 1, + metadata: None, + }, + ); + let round = |id: &str| { + SessionManager::build_model_rounds_from_messages( + &[crate::agentic::core::Message::assistant("answer".into()) + .with_round_id(id.into())], + "turn-1", + 1, + ) + .remove(0) + }; + let mut timed = round("round-1"); + timed.duration_ms = Some(2172); + timed.stream_duration_ms = Some(1500); + timed.ttft_ms = Some(690); + timed.attempt_count = Some(1); + let mut projected_timed = round("round-0"); + projected_timed.duration_ms = Some(900); + let mut persisted_timed = projected_timed.clone(); + persisted_timed.duration_ms = Some(800); + persisted.model_rounds = vec![persisted_timed, timed]; + let mut projected = persisted.clone(); + // The window checkpointed the last round before its completion event. + let mut untimed = round("round-1"); + untimed.duration_ms = Some(0); + projected.model_rounds = vec![projected_timed, untimed]; + + let merged = merge_runtime_owned_turn_facts(&persisted, &projected); + assert_eq!(merged.model_rounds[0].duration_ms, Some(900)); + let last = &merged.model_rounds[1]; + assert_eq!(last.duration_ms, Some(2172)); + assert_eq!(last.stream_duration_ms, Some(1500)); + assert_eq!(last.ttft_ms, Some(690)); + assert_eq!(last.attempt_count, Some(1)); + } + #[tokio::test] async fn product_event_queue_owner_broadcasts_while_draining_the_legacy_queue() { let queue = Arc::new(EventQueue::new(EventQueueConfig { 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 8bbaa6f161..59555a46de 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -7940,6 +7940,37 @@ describe('FlowChatStore reconcile snapshot content safety', () => { ).toContainEqual(expect.objectContaining({ id: 'plan-display-test' })); }); + it('keeps live round timing when the settled host record lost it', async () => { + // Older hosts rebuild the last round at Turn completion before this + // window's checkpoint of `ModelRoundCompleted`, persisting duration 0 and + // no TTFT. Adopting that would hide the turn's TTFT and output rate. + await hydrateSessionWithContent(); + flowChatStore.updateModelRound('history-1', 'turn-0', 'round-0', round => ({ + ...round, + durationMs: 2172, + streamDurationMs: 1500, + ttftMs: 690, + attemptCount: 1, + })); + + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: hostSession(), + turns: [{ + ...createPersistedTurn(0), + modelRounds: [{ ...HYDRATED_ROUND, durationMs: 0 }], + endTime: 3, + }], + contextRestoreState: 'ready', + }); + + await expect( + flowChatStore.reconcileSettledDialogTurn('history-1', 'turn-0'), + ).resolves.toBe(true); + expect( + flowChatStore.getState().sessions.get('history-1')?.dialogTurns[0].modelRounds[0], + ).toMatchObject({ durationMs: 2172, streamDurationMs: 1500, ttftMs: 690, attemptCount: 1 }); + }); + it('still adopts the host copy when the snapshot carries the projected work', async () => { // The guard must not disable wholesale replacement, which is how a settled // turn picks up the host's authoritative copy. @@ -7971,6 +8002,41 @@ describe('FlowChatStore reconcile snapshot content safety', () => { ).toHaveLength(2); }); + it('keeps live round timing when a Peer snapshot adopts a settled Turn', async () => { + await hydrateSessionWithContent(); + flowChatStore.updateModelRound('history-1', 'turn-0', 'round-0', round => ({ + ...round, + durationMs: 2172, + ttftMs: 690, + })); + + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: hostSession(), + turns: [{ + ...createPersistedTurn(0), + modelRounds: [{ + ...HYDRATED_ROUND, + durationMs: 0, + textItems: [ + { id: 'text-0', content: 'OpenBitFun is an agentic IDE…', timestamp: 2 }, + { id: 'text-1', content: '…with multi-device control.', timestamp: 3 }, + ], + }], + }], + contextRestoreState: 'ready', + }); + + const result = await flowChatStore.refreshPeerSessionSnapshot( + 'history-1', + { requireActiveSession: true }, + ); + + expect(result.applied).toBe(true); + const round = flowChatStore.getState().sessions.get('history-1')?.dialogTurns[0].modelRounds[0]; + expect(round?.items).toHaveLength(2); + expect(round).toMatchObject({ durationMs: 2172, ttftMs: 690 }); + }); + describe('a Turn whose terminal event this window missed', () => { // Regression 2026-11-02: a Turn kept running locally while the window // rendered a Peer device. Its later chunks and terminal event were dropped diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index e6eb7def73..466dfbaa0b 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -858,6 +858,49 @@ function preserveClientDerivedDisplayItems( return changed ? { ...persisted, modelRounds } : persisted; } +const ROUND_TIMING_KEYS = [ + 'firstChunkMs', + 'firstVisibleOutputMs', + 'streamDurationMs', + 'ttftMs', + 'attemptCount', +] as const; + +/** + * Keep live `ModelRoundCompleted` timing that a settled record lacks. + * + * Hosts that predate journal-carried round timing rebuild the last round of a + * Turn without it (duration persisted as 0), because their completion write + * usually lands before this client's checkpoint of that event. Adopting such a + * record would erase the TTFT and output rate this window already measured. + */ +function preserveLiveRoundTiming(current: DialogTurn, persisted: DialogTurn): DialogTurn { + let changed = false; + const modelRounds = persisted.modelRounds.map(persistedRound => { + const currentRound = current.modelRounds.find(round => round.id === persistedRound.id); + if (!currentRound) { + return persistedRound; + } + const patch: Partial = {}; + const isMeasured = (durationMs?: number) => typeof durationMs === 'number' && durationMs > 0; + if (!isMeasured(persistedRound.durationMs) && isMeasured(currentRound.durationMs)) { + patch.durationMs = currentRound.durationMs; + } + for (const key of ROUND_TIMING_KEYS) { + if (persistedRound[key] === undefined && currentRound[key] !== undefined) { + patch[key] = currentRound[key]; + } + } + if (Object.keys(patch).length === 0) { + return persistedRound; + } + changed = true; + return { ...persistedRound, ...patch }; + }); + + return changed ? { ...persisted, modelRounds } : persisted; +} + /** * Whether a persisted-record read may replace the Turn already projected. * @@ -8386,7 +8429,7 @@ export class FlowChatStore { if (adopted === turns) { adopted = [...turns]; } - adopted[index] = snapshotTurn; + adopted[index] = preserveLiveRoundTiming(adopted[index], snapshotTurn); } return adopted; }; @@ -8443,24 +8486,27 @@ export class FlowChatStore { let turnsChanged = false; for (const snapshotTurn of snapshotTurns) { const existingIndex = mergedTurns.findIndex(turn => turn.id === snapshotTurn.id); + // The Runtime journal replay *is* the runtime writer, so it always + // establishes its own active Turn. + const isRuntimeReplayTurn = Boolean(runtimeReplaySnapshot) + && snapshotTurn.id === runtimeReplaySnapshot?.activeTurnId; if (existingIndex === -1) { mergedTurns.push(snapshotTurn); turnsChanged = true; } else if ( - // The Runtime journal replay *is* the runtime writer, so it always - // establishes its own active Turn. - runtimeReplaySnapshot && snapshotTurn.id === runtimeReplaySnapshot.activeTurnId - ? true - : persistedReadMayReplaceTurn( - sessionId, - mergedTurns[existingIndex], - snapshotTurn, - activeTurnId, - Boolean(runtimeEventSnapshot), - true, - ) + isRuntimeReplayTurn + || persistedReadMayReplaceTurn( + sessionId, + mergedTurns[existingIndex], + snapshotTurn, + activeTurnId, + Boolean(runtimeEventSnapshot), + true, + ) ) { - mergedTurns[existingIndex] = snapshotTurn; + mergedTurns[existingIndex] = isRuntimeReplayTurn + ? snapshotTurn + : preserveLiveRoundTiming(mergedTurns[existingIndex], snapshotTurn); turnsChanged = true; } } @@ -8646,7 +8692,10 @@ export class FlowChatStore { return prev; } const current = session.dialogTurns[turnIndex]; - const reconciled = preserveClientDerivedDisplayItems(current, incoming); + const reconciled = preserveLiveRoundTiming( + current, + preserveClientDerivedDisplayItems(current, incoming), + ); if ( !['completed', 'cancelled', 'error'].includes(current.status) || !persistedReadMayReplaceTurn(