diff --git a/codex-rs/app-server/src/request_processors/token_usage_replay.rs b/codex-rs/app-server/src/request_processors/token_usage_replay.rs index 9c224b4861..537a9e9644 100644 --- a/codex-rs/app-server/src/request_processors/token_usage_replay.rs +++ b/codex-rs/app-server/src/request_processors/token_usage_replay.rs @@ -89,7 +89,20 @@ fn latest_token_usage_turn_id_from_rollout_items( } if turns.is_empty() { - return builder.active_turn_id_if_explicit(); + return builder.active_turn_id_if_explicit().or_else(|| { + // A compaction checkpoint can cut off TurnStarted. Only trust a + // saved context from the turn that owns this count. + let start = builder.active_turn_start_index()?; + let [RolloutItem::Compacted(_), rest @ ..] = &rollout_items[start..token_count_index] + else { + return None; + }; + let context = rest.iter().rev().find_map(|item| match item { + RolloutItem::TurnContext(context) => Some(context), + _ => None, + })?; + context.turn_id.clone() + }); } let active_turn_id = builder.active_turn_id()?; diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 6e8fc397f4..e42aeb0e99 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -115,6 +115,7 @@ use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource as RolloutSessionSource; use codex_protocol::protocol::SubAgentSource; +use codex_protocol::protocol::ThreadRolledBackEvent; use codex_protocol::protocol::ThreadSettingsAppliedEvent; use codex_protocol::protocol::TokenCountEvent; use codex_protocol::protocol::TokenUsage; @@ -4711,8 +4712,27 @@ async fn thread_resume_emits_restored_token_usage_before_next_turn() -> Result<( Ok(()) } +async fn append_compaction_with_context(path: &Path, cwd: &Path, turn_id: &str) -> Result<()> { + let checkpoint = serde_json::from_value(json!({ + "message": "summary", "replacement_history": [], "window_number": 1, + }))?; + append_rollout_item_to_path(path, &RolloutItem::Compacted(checkpoint)).await?; + let context = serde_json::from_value(json!({ + "turn_id": turn_id, + "cwd": cwd, + "approval_policy": "never", + "sandbox_policy": {"type": "read-only"}, + "model": "gpt-5.4", + "summary": "auto", + }))?; + append_rollout_item_to_path(path, &RolloutItem::TurnContext(context)).await?; + Ok(()) +} + +#[test_case(false; "explicit turn start")] +#[test_case(true; "compaction inside the last turn")] #[tokio::test] -async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result<()> { +async fn cold_paginated_resume_restores_usage_without_loading_turns(compacted: bool) -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; mock_responses_config(&server.uri()).write(codex_home.path())?; @@ -4739,6 +4759,9 @@ async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result< })), ) .await?; + if compacted { + append_compaction_with_context(&path, codex_home.path(), canonical_turn_id).await?; + } append_rollout_item_to_path( &path, &RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent { @@ -4789,6 +4812,8 @@ async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result< assert_eq!(notification.thread_id, thread.id); assert_eq!(notification.turn_id, canonical_turn_id); assert_eq!(notification.token_usage.total.total_tokens, 150); + assert_eq!(notification.token_usage.last.total_tokens, 90); + assert_eq!(notification.token_usage.model_context_window, Some(200_000)); let turns_id = app_server .send_thread_turns_list_request(ThreadTurnsListParams { @@ -4838,8 +4863,12 @@ async fn cold_paginated_resume_restores_usage_without_loading_turns() -> Result< Ok(()) } +#[test_case(false; "implicit turn")] +#[test_case(true; "rolled back compacted turn")] #[tokio::test] -async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous() -> Result<()> { +async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous( + rolled_back: bool, +) -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; mock_responses_config(&server.uri()).write(codex_home.path())?; @@ -4853,6 +4882,16 @@ async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous() -> Resul /*git_info*/ None, )?; let path = rollout_path(codex_home.path(), filename_ts, &conversation_id); + if rolled_back { + append_compaction_with_context(&path, codex_home.path(), "rolled-back-turn").await?; + append_rollout_item_to_path( + &path, + &RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent { + num_turns: 1, + })), + ) + .await?; + } append_rollout_item_to_path( &path, &RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent { @@ -4920,7 +4959,7 @@ async fn cold_paginated_resume_omits_usage_when_its_turn_is_ambiguous() -> Resul ) .await .is_err(), - "usage owned by an implicit turn must not be attributed to {interrupted_turn_id}" + "usage with no known owner must not be replayed" ); Ok(())