timestamps

This commit is contained in:
Roy Han
2026-03-31 14:15:33 -07:00
parent a85835dd0b
commit 81b4ff7937
17 changed files with 136 additions and 54 deletions
+16 -34
View File
@@ -30,8 +30,6 @@ use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tokio::sync::mpsc;
#[derive(Clone)]
@@ -217,7 +215,7 @@ struct PendingTurnStartState {
struct CompletedTurnState {
status: Option<TurnStatus>,
turn_error: Option<CodexErrorInfo>,
completed_at_secs: u64,
completed_at: u64,
duration_ms: Option<u64>,
}
@@ -226,7 +224,7 @@ struct TurnState {
thread_id: Option<String>,
num_input_images: Option<usize>,
resolved_config: Option<TurnResolvedConfigFact>,
started_at_ms: Option<u64>,
created_at: Option<u64>,
completed: Option<CompletedTurnState>,
}
@@ -552,7 +550,7 @@ struct CodexTurnEventParams {
reasoning_output_tokens: Option<i64>,
total_tokens: Option<i64>,
duration_ms: Option<u64>,
started_at: Option<u64>,
created_at: Option<u64>,
completed_at: Option<u64>,
}
@@ -728,7 +726,7 @@ impl AnalyticsReducer {
thread_id: None,
num_input_images: None,
resolved_config: None,
started_at_ms: None,
created_at: None,
completed: None,
});
turn_state.thread_id = Some(thread_id);
@@ -804,7 +802,7 @@ impl AnalyticsReducer {
thread_id: None,
num_input_images: None,
resolved_config: None,
started_at_ms: None,
created_at: None,
completed: None,
});
turn_state.connection_id = Some(connection_id);
@@ -828,10 +826,10 @@ impl AnalyticsReducer {
thread_id: None,
num_input_images: None,
resolved_config: None,
started_at_ms: None,
created_at: None,
completed: None,
});
turn_state.started_at_ms = Some(now_unix_timestamp_millis());
turn_state.created_at = u64::try_from(notification.created_at).ok();
}
ServerNotification::TurnCompleted(notification) => {
let turn_state =
@@ -842,11 +840,9 @@ impl AnalyticsReducer {
thread_id: None,
num_input_images: None,
resolved_config: None,
started_at_ms: None,
created_at: None,
completed: None,
});
let completed_at_secs = now_unix_timestamp_secs();
let completed_at_ms = completed_at_secs.saturating_mul(1000);
turn_state.completed = Some(CompletedTurnState {
status: analytics_turn_status(notification.turn.status),
turn_error: notification.turn.error.and_then(|error| {
@@ -854,10 +850,10 @@ impl AnalyticsReducer {
.codex_error_info
.map(app_server_codex_error_info_to_core)
}),
completed_at_secs,
duration_ms: turn_state
.started_at_ms
.map(|started_at_ms| completed_at_ms.saturating_sub(started_at_ms)),
completed_at: u64::try_from(notification.completed_at).unwrap_or_default(),
duration_ms: notification
.duration_ms
.and_then(|duration_ms| u64::try_from(duration_ms).ok()),
});
let turn_id = notification.turn.id;
self.maybe_emit_turn_event(&turn_id, out);
@@ -896,7 +892,7 @@ impl AnalyticsReducer {
num_input_images,
resolved_config,
completed,
turn_state.started_at_ms.map(|value| value / 1000),
turn_state.created_at,
),
},
)));
@@ -1025,7 +1021,7 @@ fn codex_turn_event_params(
num_input_images: usize,
resolved_config: TurnResolvedConfigFact,
completed: CompletedTurnState,
started_at: Option<u64>,
created_at: Option<u64>,
) -> CodexTurnEventParams {
let TurnResolvedConfigFact {
turn_id: _resolved_turn_id,
@@ -1082,8 +1078,8 @@ fn codex_turn_event_params(
reasoning_output_tokens: None,
total_tokens: None,
duration_ms: completed.duration_ms,
started_at,
completed_at: Some(completed.completed_at_secs),
created_at,
completed_at: Some(completed.completed_at),
}
}
@@ -1192,20 +1188,6 @@ fn session_source_name(session_source: &SessionSource) -> Option<&'static str> {
}
}
fn now_unix_timestamp_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn now_unix_timestamp_millis() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
fn analytics_turn_status(status: codex_app_server_protocol::TurnStatus) -> Option<TurnStatus> {
match status {
codex_app_server_protocol::TurnStatus::Completed => Some(TurnStatus::Completed),
@@ -162,6 +162,7 @@ fn sample_turn_started_notification(thread_id: &str, turn_id: &str) -> ServerNot
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 455,
})
}
@@ -183,6 +184,8 @@ fn sample_turn_completed_notification(
additional_details: None,
}),
},
completed_at: 456,
duration_ms: Some(1234),
})
}
@@ -468,7 +471,7 @@ fn turn_event_serializes_expected_shape() {
CompletedTurnState {
status: Some(TurnStatus::Completed),
turn_error: None,
completed_at_secs: 456,
completed_at: 456,
duration_ms: Some(1234),
},
Some(455),
@@ -516,7 +519,7 @@ fn turn_event_serializes_expected_shape() {
"reasoning_output_tokens": null,
"total_tokens": null,
"duration_ms": 1234,
"started_at": 455,
"created_at": 455,
"completed_at": 456
}
})
@@ -572,7 +575,7 @@ async fn turn_lifecycle_emits_turn_event() {
TurnResolvedConfigFact {
turn_id: "turn-2".to_string(),
thread_id: "thread-2".to_string(),
num_input_images: 2,
num_input_images: 1,
submission_type: None,
model: "gpt-5".to_string(),
model_provider: "openai".to_string(),
@@ -622,7 +625,7 @@ async fn turn_lifecycle_emits_turn_event() {
);
assert_eq!(payload["event_params"]["num_input_images"], json!(1));
assert_eq!(payload["event_params"]["status"], json!("completed"));
assert!(payload["event_params"]["started_at"].as_u64().is_some());
assert!(payload["event_params"]["created_at"].as_u64().is_some());
assert!(payload["event_params"]["completed_at"].as_u64().is_some());
}
@@ -643,7 +646,12 @@ async fn turn_does_not_emit_without_required_prerequisites() {
&mut out,
)
.await;
assert!(out.is_empty());
assert_eq!(out.len(), 1);
let payload = serde_json::to_value(&out[0]).expect("serialize turn event");
assert_eq!(
payload["event_params"]["product_client_id"],
json!(originator().value)
);
let mut reducer = AnalyticsReducer::default();
let mut out = Vec::new();
@@ -664,7 +672,7 @@ async fn turn_does_not_emit_without_required_prerequisites() {
}
#[tokio::test]
async fn turn_completed_without_started_notification_emits_null_started_at() {
async fn turn_completed_without_started_notification_emits_null_created_at() {
let mut reducer = AnalyticsReducer::default();
let mut out = Vec::new();
@@ -682,8 +690,8 @@ async fn turn_completed_without_started_notification_emits_null_started_at() {
.await;
let payload = serde_json::to_value(&out[0]).expect("serialize turn event");
assert_eq!(payload["event_params"]["started_at"], json!(null));
assert_eq!(payload["event_params"]["duration_ms"], json!(null));
assert_eq!(payload["event_params"]["created_at"], json!(null));
assert_eq!(payload["event_params"]["duration_ms"], json!(1234));
}
#[tokio::test]
+4
View File
@@ -1061,6 +1061,8 @@ mod tests {
status: codex_app_server_protocol::TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
})
}
@@ -1834,6 +1836,8 @@ mod tests {
status: codex_app_server_protocol::TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
}
)
)
@@ -4776,6 +4776,9 @@ pub struct ThreadNameUpdatedNotification {
pub struct TurnStartedNotification {
pub thread_id: String,
pub turn: Turn,
/// Unix timestamp (in seconds) when the turn started.
#[ts(type = "number")]
pub created_at: i64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
@@ -4802,6 +4805,12 @@ pub struct Usage {
pub struct TurnCompletedNotification {
pub thread_id: String,
pub turn: Turn,
/// Unix timestamp (in seconds) when the turn completed.
#[ts(type = "number")]
pub completed_at: i64,
/// Duration between turn start and completion in milliseconds, if known.
#[ts(type = "number | null")]
pub duration_ms: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
@@ -142,6 +142,8 @@ use std::convert::TryFrom;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tokio::sync::Mutex;
use tokio::sync::oneshot;
use tracing::error;
@@ -290,6 +292,7 @@ pub(crate) async fn apply_bespoke_event_handling(
let notification = TurnStartedNotification {
thread_id: conversation_id.to_string(),
turn,
created_at: set_turn_started_at(&thread_state).await,
};
analytics_events_client
.track_notification(ServerNotification::TurnStarted(notification.clone()));
@@ -1957,9 +1960,11 @@ async fn emit_turn_completed_with_status(
event_turn_id: String,
status: TurnStatus,
error: Option<TurnError>,
started_at_ms: Option<i64>,
analytics_events_client: Option<&AnalyticsEventsClient>,
outgoing: &ThreadScopedOutgoingMessageSender,
) {
let completed_at_ms = now_unix_timestamp_millis();
let notification = TurnCompletedNotification {
thread_id: conversation_id.to_string(),
turn: Turn {
@@ -1968,6 +1973,9 @@ async fn emit_turn_completed_with_status(
error,
status,
},
completed_at: completed_at_ms / 1000,
duration_ms: started_at_ms
.map(|started_at_ms| completed_at_ms.saturating_sub(started_at_ms)),
};
if let Some(analytics_events_client) = analytics_events_client {
analytics_events_client
@@ -2121,6 +2129,7 @@ async fn handle_turn_complete(
thread_state: &Arc<Mutex<ThreadState>>,
) {
let turn_summary = find_and_remove_turn_summary(conversation_id, thread_state).await;
let started_at_ms = turn_summary.started_at_ms;
let (status, error) = match turn_summary.last_error {
Some(error) => (TurnStatus::Failed, Some(error)),
@@ -2132,6 +2141,7 @@ async fn handle_turn_complete(
event_turn_id,
status,
error,
started_at_ms,
analytics_events_client,
outgoing,
)
@@ -2144,19 +2154,34 @@ async fn handle_turn_interrupted(
outgoing: &ThreadScopedOutgoingMessageSender,
thread_state: &Arc<Mutex<ThreadState>>,
) {
find_and_remove_turn_summary(conversation_id, thread_state).await;
let turn_summary = find_and_remove_turn_summary(conversation_id, thread_state).await;
emit_turn_completed_with_status(
conversation_id,
event_turn_id,
TurnStatus::Interrupted,
/*error*/ None,
turn_summary.started_at_ms,
/*analytics_events_client*/ None,
outgoing,
)
.await;
}
async fn set_turn_started_at(thread_state: &Arc<Mutex<ThreadState>>) -> i64 {
let started_at_ms = now_unix_timestamp_millis();
let mut state = thread_state.lock().await;
state.turn_summary.started_at_ms = Some(started_at_ms);
started_at_ms / 1000
}
fn now_unix_timestamp_millis() -> i64 {
let duration = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
}
async fn handle_thread_rollback_failed(
_conversation_id: ThreadId,
message: String,
+2
View File
@@ -821,6 +821,8 @@ mod tests {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
})
));
}
+2 -11
View File
@@ -61,7 +61,6 @@ use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_core::config_loader::CloudRequirementsLoader;
use codex_core::config_loader::LoaderOverrides;
use codex_core::default_client::DEFAULT_ORIGINATOR;
use codex_core::default_client::SetOriginatorError;
use codex_core::default_client::USER_AGENT_SUFFIX;
use codex_core::default_client::get_codex_user_agent;
@@ -88,8 +87,6 @@ use toml::Value as TomlValue;
use tracing::Instrument;
const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10);
const TUI_APP_SERVER_CLIENT_NAME: &str = "codex-tui";
#[derive(Clone)]
struct ExternalAuthRefreshBridge {
outgoing: Arc<OutgoingMessageSender>,
@@ -573,14 +570,8 @@ impl MessageProcessor {
} = params.client_info;
session.app_server_client_name = Some(name.clone());
session.client_version = Some(version.clone());
let originator = if name == TUI_APP_SERVER_CLIENT_NAME {
// TODO: Remove this temporary workaround once app-server clients no longer
// need to retain the legacy TUI `codex_cli_rs` originator behavior.
DEFAULT_ORIGINATOR.to_string()
} else {
name.clone()
};
if let Err(error) = set_default_originator(originator.clone()) {
let originator = name.clone();
if let Err(error) = set_default_originator(originator) {
match error {
SetOriginatorError::InvalidHeaderValue => {
let error = JSONRPCErrorError {
+1
View File
@@ -44,6 +44,7 @@ pub(crate) enum ThreadListenerCommand {
/// Per-conversation accumulation of the latest states e.g. error message while a turn runs.
#[derive(Default, Clone)]
pub(crate) struct TurnSummary {
pub(crate) started_at_ms: Option<i64>,
pub(crate) file_change_started: HashSet<String>,
pub(crate) command_execution_started: HashSet<String>,
pub(crate) last_error: Option<TurnError>,
@@ -731,6 +731,8 @@ mod tests {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -775,6 +777,8 @@ mod tests {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -815,6 +819,8 @@ mod tests {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -855,6 +861,8 @@ mod tests {
status: TurnStatus::Failed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -896,6 +904,8 @@ mod tests {
status: TurnStatus::Interrupted,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -663,6 +663,8 @@ mod tests {
codex_error_info: None,
}),
},
completed_at: 0,
duration_ms: None,
},
));
+1
View File
@@ -705,6 +705,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
TurnStartedNotification {
thread_id: response.review_thread_id.clone(),
turn: response.turn.clone(),
created_at: 0,
},
));
let task_id = response.turn.id;
@@ -145,6 +145,7 @@ fn turn_started_emits_turn_started_event() {
status: TurnStatus::InProgress,
error: None,
},
created_at: 0,
}));
assert_eq!(
@@ -1067,6 +1068,8 @@ fn plan_update_emits_started_then_updated_then_completed() {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
assert_eq!(
@@ -1123,6 +1126,8 @@ fn plan_update_after_completion_starts_new_todo_list_with_new_id() {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -1202,6 +1207,8 @@ fn token_usage_update_is_emitted_on_turn_completion() {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
assert_eq!(
@@ -1237,6 +1244,8 @@ fn turn_completion_recovers_final_message_from_turn_items() {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -1311,6 +1320,8 @@ fn turn_completion_reconciles_started_items_from_turn_items() {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -1368,6 +1379,8 @@ fn turn_completion_overwrites_stale_final_message_from_turn_items() {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -1408,6 +1421,8 @@ fn turn_completion_preserves_streamed_final_message_when_turn_items_are_empty()
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -1456,6 +1471,8 @@ fn failed_turn_clears_stale_final_message() {
codex_error_info: None,
}),
},
completed_at: 0,
duration_ms: None,
},
));
@@ -1479,6 +1496,8 @@ fn turn_completion_falls_back_to_final_plan_text() {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
@@ -1527,6 +1546,8 @@ fn turn_failure_prefers_structured_error_message() {
status: TurnStatus::Failed,
error: None,
},
completed_at: 0,
duration_ms: None,
},
));
assert_eq!(
+3
View File
@@ -8288,6 +8288,7 @@ guardian_approval = true
ServerNotification::TurnStarted(TurnStartedNotification {
thread_id: thread_id.to_string(),
turn: test_turn(turn_id, TurnStatus::InProgress, Vec::new()),
created_at: 0,
})
}
@@ -8299,6 +8300,8 @@ guardian_approval = true
ServerNotification::TurnCompleted(TurnCompletedNotification {
thread_id: thread_id.to_string(),
turn: test_turn(turn_id, status, Vec::new()),
completed_at: 0,
duration_ms: None,
})
}
@@ -1086,6 +1086,8 @@ mod tests {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
}),
)
.expect("notification should bridge");
@@ -1297,6 +1299,8 @@ mod tests {
status: TurnStatus::Interrupted,
error: None,
},
completed_at: 0,
duration_ms: None,
}),
)
.expect("notification should bridge");
@@ -1333,6 +1337,8 @@ mod tests {
additional_details: None,
}),
},
completed_at: 0,
duration_ms: None,
}),
)
.expect("notification should bridge");
@@ -677,6 +677,8 @@ mod tests {
status: TurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
})
}
@@ -5736,6 +5736,8 @@ impl ChatWidget {
status,
error,
},
completed_at: 0,
duration_ms: None,
},
Some(replay_kind),
);
@@ -4363,6 +4363,7 @@ async fn submit_user_message_queues_while_compaction_turn_is_running() {
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 0,
}),
None,
);
@@ -4406,6 +4407,8 @@ async fn submit_user_message_queues_while_compaction_turn_is_running() {
status: AppServerTurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
}),
None,
);
@@ -4610,6 +4613,7 @@ async fn live_app_server_turn_completed_clears_working_status_after_answer_item(
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 0,
}),
None,
);
@@ -4649,6 +4653,8 @@ async fn live_app_server_turn_completed_clears_working_status_after_answer_item(
status: AppServerTurnStatus::Completed,
error: None,
},
completed_at: 0,
duration_ms: None,
}),
None,
);
@@ -4932,6 +4938,7 @@ async fn live_app_server_failed_turn_does_not_duplicate_error_history() {
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 0,
}),
None,
);
@@ -4967,6 +4974,8 @@ async fn live_app_server_failed_turn_does_not_duplicate_error_history() {
additional_details: None,
}),
},
completed_at: 0,
duration_ms: None,
}),
None,
);
@@ -4988,6 +4997,7 @@ async fn replayed_retryable_app_server_error_keeps_turn_running() {
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 0,
}),
Some(ReplayKind::ThreadSnapshot),
);
@@ -5030,6 +5040,7 @@ async fn live_app_server_stream_recovery_restores_previous_status_header() {
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 0,
}),
None,
);
@@ -5084,6 +5095,7 @@ async fn live_app_server_server_overloaded_error_renders_warning() {
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 0,
}),
None,
);
@@ -5261,6 +5273,7 @@ async fn live_reasoning_summary_is_not_rendered_twice_when_item_completes() {
status: AppServerTurnStatus::InProgress,
error: None,
},
created_at: 0,
}),
None,
);