From 8580e0e3e3de22f45c275c172dda7d5bb870eda7 Mon Sep 17 00:00:00 2001 From: Dave Aitel Date: Fri, 10 Apr 2026 08:46:27 -0400 Subject: [PATCH] Include terminal items in turn completion events --- .../schema/json/ServerNotification.json | 2 +- .../codex_app_server_protocol.schemas.json | 2 +- .../codex_app_server_protocol.v2.schemas.json | 2 +- .../schema/json/v2/ReviewStartResponse.json | 2 +- .../schema/json/v2/ThreadForkResponse.json | 2 +- .../schema/json/v2/ThreadListResponse.json | 2 +- .../json/v2/ThreadMetadataUpdateResponse.json | 2 +- .../schema/json/v2/ThreadReadResponse.json | 2 +- .../schema/json/v2/ThreadResumeResponse.json | 2 +- .../json/v2/ThreadRollbackResponse.json | 2 +- .../schema/json/v2/ThreadStartResponse.json | 2 +- .../json/v2/ThreadStartedNotification.json | 2 +- .../json/v2/ThreadUnarchiveResponse.json | 2 +- .../json/v2/TurnCompletedNotification.json | 2 +- .../schema/json/v2/TurnStartResponse.json | 2 +- .../json/v2/TurnStartedNotification.json | 2 +- .../schema/typescript/v2/Turn.ts | 7 +- .../app-server-protocol/src/protocol/v2.rs | 7 +- codex-rs/app-server/README.md | 4 +- .../app-server/src/bespoke_event_handling.rs | 70 +++++++++++++++---- codex-rs/app-server/src/thread_state.rs | 15 ++++ codex-rs/exec/src/lib.rs | 6 +- codex-rs/exec/src/lib_tests.rs | 27 +++++++ 23 files changed, 128 insertions(+), 40 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 4f5410c782..1a93cb3c25 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -3699,7 +3699,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index e4ced5070c..45554864a1 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -14836,7 +14836,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/v2/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index d1f3cbda55..92c817d528 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -12691,7 +12691,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json index a7fe2e8d60..03c1448feb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json @@ -1299,7 +1299,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 9b1870198a..b7dd108209 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -1888,7 +1888,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index 426f34ce35..db786d0397 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -1646,7 +1646,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json index c869a79749..6e3df1457f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json @@ -1646,7 +1646,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index 9569860c38..43a4a08932 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -1646,7 +1646,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 5143545ec1..353ca1c283 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -1888,7 +1888,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index 502dd3961f..2637dbaf31 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -1646,7 +1646,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index c07b4d8258..e93fe272aa 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -1888,7 +1888,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index ff87af2069..5521af3d85 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -1646,7 +1646,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index daf821c374..2aab51a315 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -1646,7 +1646,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json index 82c2b3c76c..d1338231ac 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json @@ -1299,7 +1299,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json index ebb2065cb8..4f7417e5d6 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json @@ -1299,7 +1299,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json index 8b7c2bc410..86444dacd0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json @@ -1299,7 +1299,7 @@ "type": "string" }, "items": { - "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "description": "Populated on history-bearing responses such as `thread/resume` and `thread/fork`. The `turn/completed` notification also includes the terminal turn items when they are still available from the live thread listener. Other responses and notifications may still return an empty list to keep payloads small.", "items": { "$ref": "#/definitions/ThreadItem" }, diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Turn.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Turn.ts index 074ac215fd..6428ed4c0f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Turn.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Turn.ts @@ -7,9 +7,10 @@ import type { TurnStatus } from "./TurnStatus"; export type Turn = { id: string, /** - * Only populated on a `thread/resume` or `thread/fork` response. - * For all other responses and notifications returning a Turn, - * the items field will be an empty list. + * Populated on history-bearing responses such as `thread/resume` and `thread/fork`. + * The `turn/completed` notification also includes the terminal turn items when they are + * still available from the live thread listener. Other responses and notifications may + * still return an empty list to keep payloads small. */ items: Array, status: TurnStatus, /** diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 66ac1a6020..1bd81dfab8 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -3752,9 +3752,10 @@ impl From for TokenUsageBreakdown { #[ts(export_to = "v2/")] pub struct Turn { pub id: String, - /// Only populated on a `thread/resume` or `thread/fork` response. - /// For all other responses and notifications returning a Turn, - /// the items field will be an empty list. + /// Populated on history-bearing responses such as `thread/resume` and `thread/fork`. + /// The `turn/completed` notification also includes the terminal turn items when they are + /// still available from the live thread listener. Other responses and notifications may + /// still return an empty list to keep payloads small. pub items: Vec, pub status: TurnStatus, /// Only populated when the Turn's status is failed. diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index eeaf9ef23e..16bca334aa 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -943,12 +943,12 @@ Because audio is intentionally separate from `ThreadItem`, clients can opt out o The app-server streams JSON-RPC notifications while a turn is running. Each turn emits `turn/started` when it begins running and ends with `turn/completed` (final `turn` status). Token usage events stream separately via `thread/tokenUsage/updated`. Clients subscribe to the events they care about, rendering each item incrementally as updates arrive. The per-item lifecycle is always: `item/started` → zero or more item-specific deltas → `item/completed`. - `turn/started` — `{ turn }` with the turn id, empty `items`, and `status: "inProgress"`. -- `turn/completed` — `{ turn }` where `turn.status` is `completed`, `interrupted`, or `failed`; failures carry `{ error: { message, codexErrorInfo?, additionalDetails? } }`. +- `turn/completed` — `{ turn }` where `turn.status` is `completed`, `interrupted`, or `failed`; failures carry `{ error: { message, codexErrorInfo?, additionalDetails? } }`. When the live listener still has the terminal turn snapshot, `turn.items` includes the completed turn items. - `turn/diff/updated` — `{ threadId, turnId, diff }` represents the up-to-date snapshot of the turn-level unified diff, emitted after every FileChange item. `diff` is the latest aggregated unified diff across every file change in the turn. UIs can render this to show the full "what changed" view without stitching individual `fileChange` items. - `turn/plan/updated` — `{ turnId, explanation?, plan }` whenever the agent shares or changes its plan; each `plan` entry is `{ step, status }` with `status` in `pending`, `inProgress`, or `completed`. - `model/rerouted` — `{ threadId, turnId, fromModel, toModel, reason }` when the backend reroutes a request to a different model (for example, due to high-risk cyber safety checks). -Today both notifications carry an empty `items` array even when item events were streamed; rely on `item/*` notifications for the canonical item list until this is fixed. +`turn/started` still carries an empty `items` array. `turn/completed` includes the terminal turn items when app-server can recover them from the live thread listener, but clients should still treat `item/*` notifications as the canonical incremental stream. #### Items diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index ce71e8974d..f834527521 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -1932,19 +1932,29 @@ struct TurnCompletionMetadata { async fn emit_turn_completed_with_status( conversation_id: ThreadId, event_turn_id: String, + turn_snapshot: Option, turn_completion_metadata: TurnCompletionMetadata, outgoing: &ThreadScopedOutgoingMessageSender, ) { + let turn = turn_snapshot.unwrap_or_else(|| Turn { + id: event_turn_id.clone(), + items: vec![], + error: None, + status: turn_completion_metadata.status.clone(), + started_at: None, + completed_at: None, + duration_ms: None, + }); let notification = TurnCompletedNotification { thread_id: conversation_id.to_string(), turn: Turn { id: event_turn_id, - items: vec![], - error: turn_completion_metadata.error, + items: turn.items, + error: turn_completion_metadata.error.or(turn.error), status: turn_completion_metadata.status, - started_at: turn_completion_metadata.started_at, - completed_at: turn_completion_metadata.completed_at, - duration_ms: turn_completion_metadata.duration_ms, + started_at: turn_completion_metadata.started_at.or(turn.started_at), + completed_at: turn_completion_metadata.completed_at.or(turn.completed_at), + duration_ms: turn_completion_metadata.duration_ms.or(turn.duration_ms), }, }; outgoing @@ -2127,6 +2137,7 @@ pub(crate) async fn maybe_emit_hook_prompt_item_completed( .await; } +#[cfg(test)] async fn find_and_remove_turn_summary( _conversation_id: ThreadId, thread_state: &Arc>, @@ -2135,6 +2146,16 @@ async fn find_and_remove_turn_summary( std::mem::take(&mut state.turn_summary) } +async fn find_turn_completion_state( + event_turn_id: &str, + thread_state: &Arc>, +) -> (TurnSummary, Option) { + let mut state = thread_state.lock().await; + let turn_summary = std::mem::take(&mut state.turn_summary); + let turn_snapshot = state.completion_turn_snapshot(event_turn_id); + (turn_summary, turn_snapshot) +} + async fn handle_turn_complete( conversation_id: ThreadId, event_turn_id: String, @@ -2142,7 +2163,8 @@ async fn handle_turn_complete( outgoing: &ThreadScopedOutgoingMessageSender, thread_state: &Arc>, ) { - let turn_summary = find_and_remove_turn_summary(conversation_id, thread_state).await; + let (turn_summary, turn_snapshot) = + find_turn_completion_state(&event_turn_id, thread_state).await; let (status, error) = match turn_summary.last_error { Some(error) => (TurnStatus::Failed, Some(error)), @@ -2152,6 +2174,7 @@ async fn handle_turn_complete( emit_turn_completed_with_status( conversation_id, event_turn_id, + turn_snapshot, TurnCompletionMetadata { status, error, @@ -2171,11 +2194,13 @@ async fn handle_turn_interrupted( outgoing: &ThreadScopedOutgoingMessageSender, thread_state: &Arc>, ) { - let turn_summary = find_and_remove_turn_summary(conversation_id, thread_state).await; + let (turn_summary, turn_snapshot) = + find_turn_completion_state(&event_turn_id, thread_state).await; emit_turn_completed_with_status( conversation_id, event_turn_id, + turn_snapshot, TurnCompletionMetadata { status: TurnStatus::Interrupted, error: None, @@ -2927,6 +2952,7 @@ mod tests { use codex_protocol::items::build_hook_prompt_message; use codex_protocol::mcp::CallToolResult; use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions; + use codex_protocol::models::MessagePhase; use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; @@ -3767,6 +3793,13 @@ mod tests { collaboration_mode_kind: Default::default(), }, )); + state.track_current_turn_event(&EventMsg::AgentMessage( + codex_protocol::protocol::AgentMessageEvent { + message: "done".to_string(), + phase: Some(MessagePhase::FinalAnswer), + memory_citation: None, + }, + )); state.track_current_turn_event(&EventMsg::TurnComplete(turn_complete_event( &event_turn_id, ))); @@ -3784,12 +3817,23 @@ mod tests { let msg = recv_broadcast_message(&mut rx).await?; match msg { OutgoingMessage::AppServerNotification(ServerNotification::TurnCompleted(n)) => { - assert_eq!(n.turn.id, event_turn_id); - assert_eq!(n.turn.status, TurnStatus::Completed); - assert_eq!(n.turn.error, None); - assert_eq!(n.turn.started_at, Some(42)); - assert_eq!(n.turn.completed_at, Some(TEST_TURN_COMPLETED_AT)); - assert_eq!(n.turn.duration_ms, Some(TEST_TURN_DURATION_MS)); + assert_eq!( + n.turn, + Turn { + id: event_turn_id, + items: vec![ThreadItem::AgentMessage { + id: "item-1".to_string(), + text: "done".to_string(), + phase: Some(MessagePhase::FinalAnswer), + memory_citation: None, + }], + status: TurnStatus::Completed, + error: None, + started_at: Some(42), + completed_at: Some(TEST_TURN_COMPLETED_AT), + duration_ms: Some(TEST_TURN_DURATION_MS), + } + ); } other => bail!("unexpected message: {other:?}"), } diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index 805a64bfb5..f180af7936 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -4,6 +4,7 @@ use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnError; +use codex_app_server_protocol::TurnStatus; use codex_core::CodexThread; use codex_core::ThreadConfigSnapshot; use codex_protocol::ThreadId; @@ -61,6 +62,7 @@ pub(crate) struct ThreadState { pub(crate) listener_generation: u64, listener_command_tx: Option>, current_turn_history: ThreadHistoryBuilder, + last_terminal_turn: Option, listener_thread: Option>, } @@ -93,6 +95,7 @@ impl ThreadState { } self.listener_command_tx = None; self.current_turn_history.reset(); + self.last_terminal_turn = None; self.listener_thread = None; } @@ -110,14 +113,26 @@ impl ThreadState { self.current_turn_history.active_turn_snapshot() } + pub(crate) fn completion_turn_snapshot(&self, turn_id: &str) -> Option { + self.active_turn_snapshot() + .filter(|turn| turn.id == turn_id && !matches!(turn.status, TurnStatus::InProgress)) + .or_else(|| { + self.last_terminal_turn + .clone() + .filter(|turn| turn.id == turn_id) + }) + } + pub(crate) fn track_current_turn_event(&mut self, event: &EventMsg) { if let EventMsg::TurnStarted(payload) = event { self.turn_summary.started_at = payload.started_at; + self.last_terminal_turn = None; } self.current_turn_history.handle_event(event); if matches!(event, EventMsg::TurnAborted(_) | EventMsg::TurnComplete(_)) && !self.current_turn_history.has_active_turn() { + self.last_terminal_turn = self.current_turn_history.active_turn_snapshot(); self.current_turn_history.reset(); } } diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 49220dcecf..130ed7ec99 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -1105,9 +1105,9 @@ async fn maybe_backfill_turn_completed_items( notification: &mut ServerNotification, ) { // In-process delivery may drop non-terminal item notifications under backpressure while still - // guaranteeing `turn/completed`. Because app-server currently emits that completion with an - // empty `turn.items`, exec does one last `thread/read` here so human/json output can recover - // the final message and reconcile any still-running items before shutdown. + // guaranteeing `turn/completed`. App-server now tries to include terminal turn items directly + // on that notification, but exec keeps this bounded `thread/read` fallback for older or + // degraded paths that still arrive with an empty `turn.items`. if !should_backfill_turn_completed_items(thread_ephemeral, notification) { return; } diff --git a/codex-rs/exec/src/lib_tests.rs b/codex-rs/exec/src/lib_tests.rs index f5a4628ec1..6936e18a08 100644 --- a/codex-rs/exec/src/lib_tests.rs +++ b/codex-rs/exec/src/lib_tests.rs @@ -322,6 +322,33 @@ fn should_backfill_turn_completed_items_skips_ephemeral_threads() { )); } +#[test] +fn should_backfill_turn_completed_items_skips_notifications_with_items() { + let notification = + ServerNotification::TurnCompleted(codex_app_server_protocol::TurnCompletedNotification { + thread_id: "thread-1".to_string(), + turn: codex_app_server_protocol::Turn { + id: "turn-1".to_string(), + items: vec![AppServerThreadItem::AgentMessage { + id: "msg-1".to_string(), + text: "finished".to_string(), + phase: None, + memory_citation: None, + }], + status: codex_app_server_protocol::TurnStatus::Completed, + error: None, + started_at: None, + completed_at: None, + duration_ms: None, + }, + }); + + assert!(!should_backfill_turn_completed_items( + /*thread_ephemeral*/ false, + ¬ification + )); +} + #[test] fn canceled_mcp_server_elicitation_response_uses_cancel_action() { let value = canceled_mcp_server_elicitation_response()