From fcc2a92743e1346d35de6a096240d4335be26048 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 14:19:57 +0200 Subject: [PATCH 01/13] fix: emit thread stop lifecycle on implicit shutdown (#22482) ## Why The thread lifecycle contributor hooks from #22476 should observe every session teardown. The explicit `Op::Shutdown` path already emitted `on_thread_stop`, but when `submission_loop` exited because its submission channel closed, it only tore down runtime services. That meant extensions could miss the thread-stop lifecycle signal on implicit runtime shutdown. ## What Changed - Split shared runtime teardown into `shutdown_runtime_services(...)`. - Split thread-stop lifecycle emission into `emit_thread_stop_lifecycle(...)`. - Reused those helpers from both explicit shutdown and the channel-close shutdown path. - Tracked whether `Op::Shutdown` was received so the explicit path does not double-emit lifecycle events after it exits the loop. - Added a regression test that closes the submission channel and asserts `ThreadLifecycleContributor::on_thread_stop` runs once with the expected thread/session stores. ## Testing - `cargo test -p codex-core submission_loop_channel_close_emits_thread_stop_lifecycle` --- codex-rs/core/src/session/handlers.rs | 44 ++++++----- codex-rs/core/src/session/tests.rs | 110 ++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 21 deletions(-) diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index a3de362d61..d4d7bea3b4 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -617,7 +617,7 @@ pub async fn set_thread_memory_mode(sess: &Arc, sub_id: String, mode: T } } -pub async fn shutdown(sess: &Arc, sub_id: String) -> bool { +async fn shutdown_session_runtime(sess: &Arc) { sess.abort_all_tasks(TurnAbortReason::Interrupted).await; let _ = sess.conversation.shutdown().await; sess.services @@ -630,6 +630,20 @@ pub async fn shutdown(sess: &Arc, sub_id: String) -> bool { }; mcp_shutdown.await; sess.guardian_review_session.shutdown().await; +} + +fn emit_thread_stop_lifecycle(sess: &Session) { + for contributor in sess.services.extensions.thread_lifecycle_contributors() { + contributor.on_thread_stop(codex_extension_api::ThreadStopInput { + thread_id: sess.conversation_id, + session_store: &sess.services.session_extension_data, + thread_store: &sess.services.thread_extension_data, + }); + } +} + +pub async fn shutdown(sess: &Arc, sub_id: String) -> bool { + shutdown_session_runtime(sess).await; info!("Shutting down Codex instance"); let history = sess.clone_history().await; let turn_count = history @@ -643,13 +657,7 @@ pub async fn shutdown(sess: &Arc, sub_id: String) -> bool { &[], ); - for contributor in sess.services.extensions.thread_lifecycle_contributors() { - contributor.on_thread_stop(codex_extension_api::ThreadStopInput { - thread_id: sess.conversation_id, - session_store: &sess.services.session_extension_data, - thread_store: &sess.services.thread_extension_data, - }); - } + emit_thread_stop_lifecycle(sess.as_ref()); // Gracefully flush and shutdown thread persistence on session end so tests // that inspect durable state do not race with the background writer. @@ -722,6 +730,7 @@ pub(super) async fn submission_loop( rx_sub: Receiver, ) { // To break out of this loop, send Op::Shutdown. + let mut shutdown_received = false; while let Ok(sub) = rx_sub.recv().await { debug!(?sub, "Submission"); let dispatch_span = submission_dispatch_span(&sub); @@ -894,23 +903,16 @@ pub(super) async fn submission_loop( .instrument(dispatch_span) .await; if should_exit { + shutdown_received = true; break; } } // If the submission loop exits because the channel closed without an - // explicit shutdown op, still run process teardown for child processes - // owned by this session. - sess.services - .unified_exec_manager - .terminate_all_processes() - .await; - let mcp_shutdown = { - let mut manager = sess.services.mcp_connection_manager.write().await; - manager.begin_shutdown() - }; - mcp_shutdown.await; - // Also drain cached guardian state on this implicit shutdown path. - sess.guardian_review_session.shutdown().await; + // explicit shutdown op, still run session teardown. + if !shutdown_received { + shutdown_session_runtime(&sess).await; + emit_thread_stop_lifecycle(sess.as_ref()); + } debug!("Agent loop exited"); } diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index c5602ddaae..5fcb652f8c 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -5196,6 +5196,116 @@ async fn shutdown_complete_does_not_append_to_thread_store_after_shutdown() { ); } +#[tokio::test] +async fn submission_loop_channel_close_emits_thread_stop_lifecycle() { + struct SessionStopMarker; + struct ThreadStopMarker; + + struct ThreadStopRecorder { + calls: Arc, + expected_thread_id: ThreadId, + } + + impl codex_extension_api::ThreadLifecycleContributor for ThreadStopRecorder { + fn on_thread_stop(&self, input: codex_extension_api::ThreadStopInput<'_>) { + assert_eq!(self.expected_thread_id, input.thread_id); + assert!(input.session_store.get::().is_some()); + assert!(input.thread_store.get::().is_some()); + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + } + + let (mut session, turn_context) = make_session_and_context().await; + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.thread_lifecycle_contributor(Arc::new(ThreadStopRecorder { + calls: Arc::clone(&calls), + expected_thread_id: session.conversation_id, + })); + session.services.extensions = Arc::new(builder.build()); + session + .services + .session_extension_data + .insert(SessionStopMarker); + session + .services + .thread_extension_data + .insert(ThreadStopMarker); + + let (tx_sub, rx_sub) = async_channel::bounded(1); + drop(tx_sub); + let session = Arc::new(session); + submission_loop(session, Arc::clone(&turn_context.config), rx_sub).await; + + assert_eq!(1, calls.load(std::sync::atomic::Ordering::SeqCst)); +} + +#[tokio::test] +async fn submission_loop_channel_close_aborts_active_turn_before_thread_stop_lifecycle() { + struct LifecycleRecorder { + calls: Arc>>, + expected_thread_id: ThreadId, + expected_turn_id: String, + } + + impl codex_extension_api::ThreadLifecycleContributor for LifecycleRecorder { + fn on_thread_stop(&self, input: codex_extension_api::ThreadStopInput<'_>) { + assert_eq!(self.expected_thread_id, input.thread_id); + self.calls + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push("thread_stop"); + } + } + + impl codex_extension_api::TurnLifecycleContributor for LifecycleRecorder { + fn on_turn_abort(&self, input: codex_extension_api::TurnAbortInput<'_>) { + assert_eq!(self.expected_thread_id, input.thread_id); + assert_eq!(self.expected_turn_id, input.turn_id); + assert_eq!(TurnAbortReason::Interrupted, input.reason); + self.calls + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push("turn_abort"); + } + } + + let (mut session, turn_context) = make_session_and_context().await; + let calls = Arc::new(std::sync::Mutex::new(Vec::new())); + let recorder = Arc::new(LifecycleRecorder { + calls: Arc::clone(&calls), + expected_thread_id: session.conversation_id, + expected_turn_id: turn_context.sub_id.clone(), + }); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.thread_lifecycle_contributor(recorder.clone()); + builder.turn_lifecycle_contributor(recorder); + session.services.extensions = Arc::new(builder.build()); + + let session = Arc::new(session); + session + .spawn_task( + Arc::new(turn_context), + Vec::new(), + NeverEndingTask { + kind: TaskKind::Regular, + listen_to_cancellation_token: true, + }, + ) + .await; + + let (tx_sub, rx_sub) = async_channel::bounded(1); + drop(tx_sub); + submission_loop(Arc::clone(&session), session.get_config().await, rx_sub).await; + + assert_eq!( + vec!["turn_abort", "thread_stop"], + *calls + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + ); +} + #[tokio::test] async fn shutdown_and_wait_allows_multiple_waiters() { let (session, _turn_context) = make_session_and_context().await; From 083c1962f918b38d7d74f6c1ffec93483bf22062 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 14:32:23 +0200 Subject: [PATCH 02/13] feat: add token usage contributor hook (#22485) ## Why Extensions need a stable place to observe token accounting after Codex folds model-provider usage into the session's cached `TokenUsageInfo`. Without a contributor hook, extension-owned features that need last-turn or cumulative token usage have to duplicate session plumbing or infer state from client-facing `TokenCount` notifications. ## What changed - Added `TokenUsageContributor` to `codex-extension-api`, passing session/thread `ExtensionData`, `ThreadId`, turn id, and the current `TokenUsageInfo`. - Added registry builder/storage support for token-usage contributors. - Invoked registered contributors from `Session::record_token_usage_info` after the session token cache is updated and before the client `TokenCount` notification is emitted. ## Testing - Added `record_token_usage_info_notifies_extension_contributors`, covering cumulative token usage updates and access to both extension stores. --- codex-rs/core/src/session/mod.rs | 19 ++- codex-rs/core/src/session/tests.rs | 112 ++++++++++++++++++ .../ext/extension-api/src/contributors.rs | 20 ++++ codex-rs/ext/extension-api/src/lib.rs | 1 + codex-rs/ext/extension-api/src/registry.rs | 15 +++ 5 files changed, 165 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index fa63715272..770d356ef1 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -2858,8 +2858,23 @@ impl Session { token_usage: Option<&TokenUsage>, ) { if let Some(token_usage) = token_usage { - let mut state = self.state.lock().await; - state.update_token_info_from_usage(token_usage, turn_context.model_context_window()); + let token_info = { + let mut state = self.state.lock().await; + state + .update_token_info_from_usage(token_usage, turn_context.model_context_window()); + state.token_info() + }; + if let Some(token_info) = token_info.as_ref() { + for contributor in self.services.extensions.token_usage_contributors() { + contributor.on_token_usage( + &self.services.session_extension_data, + &self.services.thread_extension_data, + self.conversation_id, + &turn_context.sub_id, + token_info, + ); + } + } } } diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 5fcb652f8c..2964b0ad5f 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1800,6 +1800,118 @@ async fn recompute_token_usage_updates_model_context_window() { assert_eq!(actual.model_context_window, Some(128_000)); } +#[tokio::test] +async fn record_token_usage_info_notifies_extension_contributors() { + struct SessionTokenUsageMarker; + struct ThreadTokenUsageMarker; + + #[derive(Debug, PartialEq, Eq)] + struct RecordedTokenUsage { + thread_id: ThreadId, + turn_id: String, + token_usage: TokenUsageInfo, + saw_session_store: bool, + saw_thread_store: bool, + } + + struct TokenUsageRecorder { + records: Arc>>, + } + + impl codex_extension_api::TokenUsageContributor for TokenUsageRecorder { + fn on_token_usage( + &self, + session_store: &codex_extension_api::ExtensionData, + thread_store: &codex_extension_api::ExtensionData, + thread_id: ThreadId, + turn_id: &str, + token_usage: &TokenUsageInfo, + ) { + self.records + .lock() + .expect("token usage records lock") + .push(RecordedTokenUsage { + thread_id, + turn_id: turn_id.to_string(), + token_usage: token_usage.clone(), + saw_session_store: session_store.get::().is_some(), + saw_thread_store: thread_store.get::().is_some(), + }); + } + } + + let (mut session, turn_context) = make_session_and_context().await; + let records = Arc::new(std::sync::Mutex::new(Vec::new())); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.token_usage_contributor(Arc::new(TokenUsageRecorder { + records: Arc::clone(&records), + })); + session.services.extensions = Arc::new(builder.build()); + session + .services + .session_extension_data + .insert(SessionTokenUsageMarker); + session + .services + .thread_extension_data + .insert(ThreadTokenUsageMarker); + + let first_usage = TokenUsage { + input_tokens: 10, + cached_input_tokens: 2, + output_tokens: 20, + reasoning_output_tokens: 3, + total_tokens: 33, + }; + let second_usage = TokenUsage { + input_tokens: 7, + cached_input_tokens: 1, + output_tokens: 8, + reasoning_output_tokens: 5, + total_tokens: 20, + }; + + session + .record_token_usage_info(&turn_context, Some(&first_usage)) + .await; + session + .record_token_usage_info(&turn_context, Some(&second_usage)) + .await; + + let mut expected_total_usage = first_usage.clone(); + expected_total_usage.add_assign(&second_usage); + let expected = vec![ + RecordedTokenUsage { + thread_id: session.conversation_id, + turn_id: turn_context.sub_id.clone(), + token_usage: TokenUsageInfo { + total_token_usage: first_usage.clone(), + last_token_usage: first_usage, + model_context_window: turn_context.model_context_window(), + }, + saw_session_store: true, + saw_thread_store: true, + }, + RecordedTokenUsage { + thread_id: session.conversation_id, + turn_id: turn_context.sub_id.clone(), + token_usage: TokenUsageInfo { + total_token_usage: expected_total_usage, + last_token_usage: second_usage, + model_context_window: turn_context.model_context_window(), + }, + saw_session_store: true, + saw_thread_store: true, + }, + ]; + let actual = records + .lock() + .expect("token usage records lock") + .drain(..) + .collect::>(); + assert_eq!(expected, actual); +} + #[tokio::test] async fn record_initial_history_reconstructs_forked_transcript() { let (session, turn_context) = make_session_and_context().await; diff --git a/codex-rs/ext/extension-api/src/contributors.rs b/codex-rs/ext/extension-api/src/contributors.rs index 0aee629a43..961b294263 100644 --- a/codex-rs/ext/extension-api/src/contributors.rs +++ b/codex-rs/ext/extension-api/src/contributors.rs @@ -1,8 +1,10 @@ use std::future::Future; use std::sync::Arc; +use codex_protocol::ThreadId; use codex_protocol::items::TurnItem; use codex_protocol::protocol::ReviewDecision; +use codex_protocol::protocol::TokenUsageInfo; use crate::ExtensionData; @@ -66,6 +68,24 @@ pub trait TurnLifecycleContributor: Send + Sync { fn on_turn_abort(&self, _input: TurnAbortInput<'_>) {} } +/// Contributor for token usage checkpoints reported by the model provider. +/// +/// Implementations should keep this callback cheap. The host calls it after +/// updating cached token usage and before emitting the corresponding client +/// token-count notification. +pub trait TokenUsageContributor: Send + Sync { + /// Called each time the host records token usage from a model response. + fn on_token_usage( + &self, + _session_store: &ExtensionData, + _thread_store: &ExtensionData, + _thread_id: ThreadId, + _turn_id: &str, + _token_usage: &TokenUsageInfo, + ) { + } +} + /// Extension contribution that exposes native tools owned by a feature. pub trait ToolContributor: Send + Sync { /// Returns the native tools visible for the supplied extension stores. diff --git a/codex-rs/ext/extension-api/src/lib.rs b/codex-rs/ext/extension-api/src/lib.rs index 57ecefd964..65e167c771 100644 --- a/codex-rs/ext/extension-api/src/lib.rs +++ b/codex-rs/ext/extension-api/src/lib.rs @@ -25,6 +25,7 @@ pub use contributors::ThreadLifecycleContributor; pub use contributors::ThreadResumeInput; pub use contributors::ThreadStartInput; pub use contributors::ThreadStopInput; +pub use contributors::TokenUsageContributor; pub use contributors::ToolContributor; pub use contributors::TurnAbortInput; pub use contributors::TurnItemContributionFuture; diff --git a/codex-rs/ext/extension-api/src/registry.rs b/codex-rs/ext/extension-api/src/registry.rs index f6a4dd6667..f2818cacaa 100644 --- a/codex-rs/ext/extension-api/src/registry.rs +++ b/codex-rs/ext/extension-api/src/registry.rs @@ -5,6 +5,7 @@ use crate::ApprovalReviewFuture; use crate::ContextContributor; use crate::ExtensionData; use crate::ThreadLifecycleContributor; +use crate::TokenUsageContributor; use crate::ToolContributor; use crate::TurnItemContributor; use crate::TurnLifecycleContributor; @@ -13,6 +14,7 @@ use crate::TurnLifecycleContributor; pub struct ExtensionRegistryBuilder { thread_lifecycle_contributors: Vec>>, turn_lifecycle_contributors: Vec>, + token_usage_contributors: Vec>, context_contributors: Vec>, tool_contributors: Vec>, turn_item_contributors: Vec>, @@ -24,6 +26,7 @@ impl Default for ExtensionRegistryBuilder { Self { thread_lifecycle_contributors: Vec::new(), turn_lifecycle_contributors: Vec::new(), + token_usage_contributors: Vec::new(), approval_review_contributors: Vec::new(), context_contributors: Vec::new(), tool_contributors: Vec::new(), @@ -56,6 +59,11 @@ impl ExtensionRegistryBuilder { self.turn_lifecycle_contributors.push(contributor); } + /// Registers one token-usage contributor. + pub fn token_usage_contributor(&mut self, contributor: Arc) { + self.token_usage_contributors.push(contributor); + } + /// Registers one prompt contributor. pub fn prompt_contributor(&mut self, contributor: Arc) { self.context_contributors.push(contributor); @@ -76,6 +84,7 @@ impl ExtensionRegistryBuilder { ExtensionRegistry { thread_lifecycle_contributors: self.thread_lifecycle_contributors, turn_lifecycle_contributors: self.turn_lifecycle_contributors, + token_usage_contributors: self.token_usage_contributors, approval_review_contributors: self.approval_review_contributors, context_contributors: self.context_contributors, tool_contributors: self.tool_contributors, @@ -88,6 +97,7 @@ impl ExtensionRegistryBuilder { pub struct ExtensionRegistry { thread_lifecycle_contributors: Vec>>, turn_lifecycle_contributors: Vec>, + token_usage_contributors: Vec>, context_contributors: Vec>, tool_contributors: Vec>, turn_item_contributors: Vec>, @@ -105,6 +115,11 @@ impl ExtensionRegistry { &self.turn_lifecycle_contributors } + /// Returns the registered token-usage contributors. + pub fn token_usage_contributors(&self) -> &[Arc] { + &self.token_usage_contributors + } + /// Claims the first rendered approval-review prompt accepted by an /// installed contributor. pub fn approval_review<'a>( From 99157f37977b251670b267734a1ac640e20acc95 Mon Sep 17 00:00:00 2001 From: Shijie Rao Date: Wed, 13 May 2026 06:31:08 -0700 Subject: [PATCH 03/13] Scope macOS signing secrets to release environment (#22443) ## Summary - Split macOS Rust release builds into a dedicated `build-macos` job - Attach the `macos-signing` environment only to the macOS signing/build job - Keep Linux release builds outside the Apple signing environment while preserving the existing shared release build steps --- .github/workflows/rust-release.yml | 76 ++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 25 deletions(-) diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 6dd751b7f6..f9c4b4655c 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -69,30 +69,6 @@ jobs: fail-fast: false matrix: include: - - runner: macos-15-xlarge - target: aarch64-apple-darwin - bundle: primary - artifact_name: aarch64-apple-darwin - binaries: "codex codex-responses-api-proxy" - build_dmg: "true" - - runner: macos-15-xlarge - target: aarch64-apple-darwin - bundle: app-server - artifact_name: aarch64-apple-darwin-app-server - binaries: "codex-app-server" - build_dmg: "false" - - runner: macos-15-xlarge - target: x86_64-apple-darwin - bundle: primary - artifact_name: x86_64-apple-darwin - binaries: "codex codex-responses-api-proxy" - build_dmg: "true" - - runner: macos-15-xlarge - target: x86_64-apple-darwin - bundle: app-server - artifact_name: x86_64-apple-darwin-app-server - binaries: "codex-app-server" - build_dmg: "false" # Release artifacts intentionally ship MUSL-linked Linux binaries. - runner: ubuntu-24.04 target: x86_64-unknown-linux-musl @@ -119,7 +95,7 @@ jobs: binaries: "codex-app-server" build_dmg: "false" - steps: + steps: &rust_release_build_steps - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false @@ -502,6 +478,55 @@ jobs: path: | codex-rs/dist/${{ matrix.target }}/* + build-macos: + needs: tag-check + name: Build - ${{ matrix.runner }} - ${{ matrix.target }} - ${{ matrix.bundle }} + runs-on: ${{ matrix.runs_on || matrix.runner }} + # Release builds can take a long time, so leave some headroom to avoid + # having to restart the full workflow due to a timeout. + timeout-minutes: 90 + environment: macos-signing + permissions: + contents: read + defaults: + run: + working-directory: codex-rs + env: + # Preserve the LTO setting from the original combined release build matrix. + # Linux ARM is why this currently resolves to thin for every target. + CARGO_PROFILE_RELEASE_LTO: ${{ contains(github.ref_name, '-alpha') && 'thin' || 'thin' }} + + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15-xlarge + target: aarch64-apple-darwin + bundle: primary + artifact_name: aarch64-apple-darwin + binaries: "codex codex-responses-api-proxy" + build_dmg: "true" + - runner: macos-15-xlarge + target: aarch64-apple-darwin + bundle: app-server + artifact_name: aarch64-apple-darwin-app-server + binaries: "codex-app-server" + build_dmg: "false" + - runner: macos-15-xlarge + target: x86_64-apple-darwin + bundle: primary + artifact_name: x86_64-apple-darwin + binaries: "codex codex-responses-api-proxy" + build_dmg: "true" + - runner: macos-15-xlarge + target: x86_64-apple-darwin + bundle: app-server + artifact_name: x86_64-apple-darwin-app-server + binaries: "codex-app-server" + build_dmg: "false" + + steps: *rust_release_build_steps + build-windows: needs: tag-check uses: ./.github/workflows/rust-release-windows.yml @@ -524,6 +549,7 @@ jobs: release: needs: - build + - build-macos - build-windows - argument-comment-lint-release-assets - zsh-release-assets From 1dcc89f1d4580c3c579a8b8a5fe2f42c1303785e Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 16:13:16 +0200 Subject: [PATCH 04/13] feat: move extension scope ids into ExtensionData (#22490) ## Summary - add a scoped level_id to ExtensionData and expose it through level_id() - remove thread_id/turn_id parameters from extension contributor inputs where the scoped ExtensionData already carries that identity - move turn-scoped extension data onto TurnContext so token usage and lifecycle contributors can share the same turn store ## Testing - cargo check -p codex-extension-api -p codex-core --tests - cargo test -p codex-extension-api - cargo test -p codex-guardian - cargo test -p codex-core --lib record_token_usage_info_notifies_extension_contributors - cargo test -p codex-core --lib submission_loop_channel_close_emits_thread_stop_lifecycle - cargo test -p codex-core --lib submission_loop_channel_close_aborts_active_turn_before_thread_stop_lifecycle - just fix -p codex-extension-api - just fix -p codex-guardian - just fix -p codex-core - just fmt ## Note - Attempted cargo test -p codex-core; it aborted in agent::control::tests::spawn_agent_fork_last_n_turns_keeps_only_recent_turns with the existing stack overflow before the full suite completed. --- codex-rs/core/src/codex_thread.rs | 1 - codex-rs/core/src/session/handlers.rs | 1 - codex-rs/core/src/session/mod.rs | 3 +- codex-rs/core/src/session/review.rs | 3 +- codex-rs/core/src/session/session.rs | 7 +-- codex-rs/core/src/session/tests.rs | 52 ++++++++++++------- codex-rs/core/src/session/turn_context.rs | 4 ++ codex-rs/core/src/state/turn.rs | 5 -- codex-rs/core/src/tasks/lifecycle.rs | 20 +------ codex-rs/core/src/tasks/mod.rs | 35 ++++--------- .../examples/enabled_extensions.rs | 6 +-- .../ext/extension-api/src/contributors.rs | 4 +- .../src/contributors/thread_lifecycle.rs | 8 --- .../src/contributors/turn_lifecycle.rs | 13 ----- codex-rs/ext/extension-api/src/state.rs | 17 ++++-- codex-rs/ext/guardian/src/lib.rs | 5 +- 16 files changed, 77 insertions(+), 107 deletions(-) diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 60b77067a6..be5b0ccb88 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -149,7 +149,6 @@ impl CodexThread { .thread_lifecycle_contributors() { contributor.on_thread_resume(codex_extension_api::ThreadResumeInput { - thread_id: self.codex.session.conversation_id, session_store: &self.codex.session.services.session_extension_data, thread_store: &self.codex.session.services.thread_extension_data, }); diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index d4d7bea3b4..ab40cb8eed 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -635,7 +635,6 @@ async fn shutdown_session_runtime(sess: &Arc) { fn emit_thread_stop_lifecycle(sess: &Session) { for contributor in sess.services.extensions.thread_lifecycle_contributors() { contributor.on_thread_stop(codex_extension_api::ThreadStopInput { - thread_id: sess.conversation_id, session_store: &sess.services.session_extension_data, thread_store: &sess.services.thread_extension_data, }); diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 770d356ef1..3b8939ec5e 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -2869,8 +2869,7 @@ impl Session { contributor.on_token_usage( &self.services.session_extension_data, &self.services.thread_extension_data, - self.conversation_id, - &turn_context.sub_id, + turn_context.extension_data.as_ref(), token_info, ); } diff --git a/codex-rs/core/src/session/review.rs b/codex-rs/core/src/session/review.rs index b0113cbdb7..f884a95a27 100644 --- a/codex-rs/core/src/session/review.rs +++ b/codex-rs/core/src/session/review.rs @@ -113,7 +113,7 @@ pub(super) async fn spawn_review_thread( )); let review_turn_context = TurnContext { - sub_id: review_turn_id, + sub_id: review_turn_id.clone(), trace_id: current_span_trace_id(), realtime_active: parent_turn_context.realtime_active, config: per_turn_config, @@ -149,6 +149,7 @@ pub(super) async fn spawn_review_thread( dynamic_tools: parent_turn_context.dynamic_tools.clone(), truncation_policy: model_info.truncation_policy.into(), turn_metadata_state, + extension_data: Arc::new(codex_extension_api::ExtensionData::new(review_turn_id)), turn_skills: TurnSkillsContext::new(parent_turn_context.turn_skills.outcome.clone()), turn_timing_state: Arc::new(TurnTimingState::default()), server_model_warning_emitted: AtomicBool::new(false), diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 6ca8ac1bf1..5b1b8c83e4 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -811,11 +811,12 @@ impl Session { SessionId::from(thread_id) }; let agent_control = agent_control.with_session_id(session_id); - let session_extension_data = codex_extension_api::ExtensionData::new(); - let thread_extension_data = codex_extension_api::ExtensionData::new(); + let session_extension_data = + codex_extension_api::ExtensionData::new(session_id.to_string()); + let thread_extension_data = + codex_extension_api::ExtensionData::new(thread_id.to_string()); for contributor in extensions.thread_lifecycle_contributors() { contributor.on_thread_start(codex_extension_api::ThreadStartInput { - thread_id, config: config.as_ref(), session_store: &session_extension_data, thread_store: &thread_extension_data, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 2964b0ad5f..45ac5ab9c5 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1807,8 +1807,9 @@ async fn record_token_usage_info_notifies_extension_contributors() { #[derive(Debug, PartialEq, Eq)] struct RecordedTokenUsage { - thread_id: ThreadId, - turn_id: String, + session_level_id: String, + thread_level_id: String, + turn_level_id: String, token_usage: TokenUsageInfo, saw_session_store: bool, saw_thread_store: bool, @@ -1823,16 +1824,16 @@ async fn record_token_usage_info_notifies_extension_contributors() { &self, session_store: &codex_extension_api::ExtensionData, thread_store: &codex_extension_api::ExtensionData, - thread_id: ThreadId, - turn_id: &str, + turn_store: &codex_extension_api::ExtensionData, token_usage: &TokenUsageInfo, ) { self.records .lock() .expect("token usage records lock") .push(RecordedTokenUsage { - thread_id, - turn_id: turn_id.to_string(), + session_level_id: session_store.level_id().to_string(), + thread_level_id: thread_store.level_id().to_string(), + turn_level_id: turn_store.level_id().to_string(), token_usage: token_usage.clone(), saw_session_store: session_store.get::().is_some(), saw_thread_store: thread_store.get::().is_some(), @@ -1882,8 +1883,9 @@ async fn record_token_usage_info_notifies_extension_contributors() { expected_total_usage.add_assign(&second_usage); let expected = vec![ RecordedTokenUsage { - thread_id: session.conversation_id, - turn_id: turn_context.sub_id.clone(), + session_level_id: session.session_id().to_string(), + thread_level_id: session.conversation_id.to_string(), + turn_level_id: turn_context.sub_id.clone(), token_usage: TokenUsageInfo { total_token_usage: first_usage.clone(), last_token_usage: first_usage, @@ -1893,8 +1895,9 @@ async fn record_token_usage_info_notifies_extension_contributors() { saw_thread_store: true, }, RecordedTokenUsage { - thread_id: session.conversation_id, - turn_id: turn_context.sub_id.clone(), + session_level_id: session.session_id().to_string(), + thread_level_id: session.conversation_id.to_string(), + turn_level_id: turn_context.sub_id.clone(), token_usage: TokenUsageInfo { total_token_usage: expected_total_usage, last_token_usage: second_usage, @@ -3981,8 +3984,10 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { plugins_manager, mcp_manager, extensions: Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()), - session_extension_data: codex_extension_api::ExtensionData::new(), - thread_extension_data: codex_extension_api::ExtensionData::new(), + session_extension_data: codex_extension_api::ExtensionData::new( + agent_control.session_id().to_string(), + ), + thread_extension_data: codex_extension_api::ExtensionData::new(thread_id.to_string()), agent_control, network_proxy: None, network_approval: Arc::clone(&network_approval), @@ -5320,7 +5325,10 @@ async fn submission_loop_channel_close_emits_thread_stop_lifecycle() { impl codex_extension_api::ThreadLifecycleContributor for ThreadStopRecorder { fn on_thread_stop(&self, input: codex_extension_api::ThreadStopInput<'_>) { - assert_eq!(self.expected_thread_id, input.thread_id); + assert_eq!( + self.expected_thread_id.to_string(), + input.thread_store.level_id() + ); assert!(input.session_store.get::().is_some()); assert!(input.thread_store.get::().is_some()); self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -5362,7 +5370,10 @@ async fn submission_loop_channel_close_aborts_active_turn_before_thread_stop_lif impl codex_extension_api::ThreadLifecycleContributor for LifecycleRecorder { fn on_thread_stop(&self, input: codex_extension_api::ThreadStopInput<'_>) { - assert_eq!(self.expected_thread_id, input.thread_id); + assert_eq!( + self.expected_thread_id.to_string(), + input.thread_store.level_id() + ); self.calls .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) @@ -5372,8 +5383,11 @@ async fn submission_loop_channel_close_aborts_active_turn_before_thread_stop_lif impl codex_extension_api::TurnLifecycleContributor for LifecycleRecorder { fn on_turn_abort(&self, input: codex_extension_api::TurnAbortInput<'_>) { - assert_eq!(self.expected_thread_id, input.thread_id); - assert_eq!(self.expected_turn_id, input.turn_id); + assert_eq!( + self.expected_thread_id.to_string(), + input.thread_store.level_id() + ); + assert_eq!(self.expected_turn_id, input.turn_store.level_id()); assert_eq!(TurnAbortReason::Interrupted, input.reason); self.calls .lock() @@ -5811,8 +5825,10 @@ where plugins_manager, mcp_manager, extensions: Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()), - session_extension_data: codex_extension_api::ExtensionData::new(), - thread_extension_data: codex_extension_api::ExtensionData::new(), + session_extension_data: codex_extension_api::ExtensionData::new( + agent_control.session_id().to_string(), + ), + thread_extension_data: codex_extension_api::ExtensionData::new(thread_id.to_string()), agent_control, network_proxy: None, network_approval: Arc::clone(&network_approval), diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index 79d07ede01..aa8e08119a 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -92,6 +92,7 @@ pub struct TurnContext { pub(crate) truncation_policy: TruncationPolicy, pub(crate) dynamic_tools: Vec, pub(crate) turn_metadata_state: Arc, + pub(crate) extension_data: Arc, pub(crate) turn_skills: TurnSkillsContext, pub(crate) turn_timing_state: Arc, pub(crate) server_model_warning_emitted: AtomicBool, @@ -274,6 +275,7 @@ impl TurnContext { truncation_policy, dynamic_tools: self.dynamic_tools.clone(), turn_metadata_state: self.turn_metadata_state.clone(), + extension_data: Arc::clone(&self.extension_data), turn_skills: self.turn_skills.clone(), turn_timing_state: Arc::clone(&self.turn_timing_state), server_model_warning_emitted: AtomicBool::new( @@ -535,6 +537,7 @@ impl Session { network.is_some(), )); let (current_date, timezone) = local_time_context(); + let extension_data = Arc::new(codex_extension_api::ExtensionData::new(sub_id.clone())); TurnContext { sub_id, trace_id: current_span_trace_id(), @@ -572,6 +575,7 @@ impl Session { truncation_policy: model_info.truncation_policy.into(), dynamic_tools: session_configuration.dynamic_tools.clone(), turn_metadata_state, + extension_data, turn_skills: TurnSkillsContext::new(skills_outcome), turn_timing_state: Arc::new(TurnTimingState::default()), server_model_warning_emitted: AtomicBool::new(false), diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index d9b1c31569..0dd0c09379 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -1,6 +1,5 @@ //! Turn-scoped state and active turn metadata scaffolding. -use codex_extension_api::ExtensionData; use codex_sandboxing::policy_transforms::merge_permission_profiles; use indexmap::IndexMap; use std::collections::HashMap; @@ -76,7 +75,6 @@ pub(crate) struct RunningTask { pub(crate) cancellation_token: CancellationToken, pub(crate) handle: AbortOnDropHandle<()>, pub(crate) turn_context: Arc, - pub(crate) turn_extension_data: Arc, // Timer recorded when the task drops to capture the full turn duration. pub(crate) _timer: Option, } @@ -84,7 +82,6 @@ pub(crate) struct RunningTask { pub(crate) struct RemovedTask { pub(crate) records_turn_token_usage_on_span: bool, pub(crate) active_turn_is_empty: bool, - pub(crate) turn_extension_data: Arc, } impl ActiveTurn { @@ -100,7 +97,6 @@ impl ActiveTurn { Some(RemovedTask { records_turn_token_usage_on_span, active_turn_is_empty: self.tasks.is_empty(), - turn_extension_data: task.turn_extension_data, }) } @@ -124,7 +120,6 @@ pub(crate) struct TurnState { pub(crate) tool_calls: u64, pub(crate) has_memory_citation: bool, pub(crate) token_usage_at_turn_start: TokenUsage, - pub(crate) extension_data: Arc, } pub(crate) struct PendingRequestPermissions { diff --git a/codex-rs/core/src/tasks/lifecycle.rs b/codex-rs/core/src/tasks/lifecycle.rs index 570e3953c0..2fb9017df2 100644 --- a/codex-rs/core/src/tasks/lifecycle.rs +++ b/codex-rs/core/src/tasks/lifecycle.rs @@ -2,18 +2,11 @@ use codex_extension_api::ExtensionData; use codex_protocol::protocol::TurnAbortReason; use crate::session::session::Session; -use crate::session::turn_context::TurnContext; impl Session { - pub(super) fn emit_turn_start_lifecycle( - &self, - turn_context: &TurnContext, - turn_store: &ExtensionData, - ) { + pub(super) fn emit_turn_start_lifecycle(&self, turn_store: &ExtensionData) { for contributor in self.services.extensions.turn_lifecycle_contributors() { contributor.on_turn_start(codex_extension_api::TurnStartInput { - thread_id: self.conversation_id, - turn_id: &turn_context.sub_id, session_store: &self.services.session_extension_data, thread_store: &self.services.thread_extension_data, turn_store, @@ -21,15 +14,9 @@ impl Session { } } - pub(super) fn emit_turn_stop_lifecycle( - &self, - turn_context: &TurnContext, - turn_store: &ExtensionData, - ) { + pub(super) fn emit_turn_stop_lifecycle(&self, turn_store: &ExtensionData) { for contributor in self.services.extensions.turn_lifecycle_contributors() { contributor.on_turn_stop(codex_extension_api::TurnStopInput { - thread_id: self.conversation_id, - turn_id: &turn_context.sub_id, session_store: &self.services.session_extension_data, thread_store: &self.services.thread_extension_data, turn_store, @@ -39,14 +26,11 @@ impl Session { pub(super) fn emit_turn_abort_lifecycle( &self, - turn_context: &TurnContext, reason: TurnAbortReason, turn_store: &ExtensionData, ) { for contributor in self.services.extensions.turn_lifecycle_contributors() { contributor.on_turn_abort(codex_extension_api::TurnAbortInput { - thread_id: self.conversation_id, - turn_id: &turn_context.sub_id, reason: reason.clone(), session_store: &self.services.session_extension_data, thread_store: &self.services.thread_extension_data, diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index ab2594d470..6da6d9ad9b 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -346,7 +346,7 @@ impl Session { debug_assert!(turn.tasks.is_empty()); Arc::clone(&turn.turn_state) }; - let turn_extension_data = { + { let mut turn_state = turn_state.lock().await; turn_state.token_usage_at_turn_start = token_usage_at_turn_start; for item in queued_response_items { @@ -355,9 +355,8 @@ impl Session { for item in mailbox_items { turn_state.push_pending_input(item); } - Arc::clone(&turn_state.extension_data) - }; - self.emit_turn_start_lifecycle(turn_context.as_ref(), turn_extension_data.as_ref()); + } + self.emit_turn_start_lifecycle(turn_context.extension_data.as_ref()); let mut active = self.active_turn.lock().await; let turn = active.get_or_insert_with(ActiveTurn::default); @@ -428,7 +427,6 @@ impl Session { task, cancellation_token, turn_context: Arc::clone(&turn_context), - turn_extension_data, _timer: timer, }; turn.add_task(running_task); @@ -480,14 +478,10 @@ impl Session { let mut aborted_turn = false; let mut active_turn_to_clear = None; let mut turn_context = None; - let mut turn_extension_data = None; if let Some(mut active_turn) = self.take_active_turn().await { let tasks = active_turn.drain_tasks(); aborted_turn = !tasks.is_empty(); turn_context = tasks.first().map(|task| Arc::clone(&task.turn_context)); - turn_extension_data = tasks - .first() - .map(|task| Arc::clone(&task.turn_extension_data)); for task in tasks { self.handle_task_abort(task, reason.clone()).await; } @@ -496,10 +490,8 @@ impl Session { } } - if let Some(turn_context) = turn_context.as_deref() - && let Some(turn_extension_data) = turn_extension_data.as_deref() - { - self.emit_turn_abort_lifecycle(turn_context, reason.clone(), turn_extension_data); + if let Some(turn_context) = turn_context.as_deref() { + self.emit_turn_abort_lifecycle(reason.clone(), turn_context.extension_data.as_ref()); } if (aborted_turn || reason == TurnAbortReason::Interrupted) && let Err(err) = self @@ -543,16 +535,11 @@ impl Session { let tasks = active_turn.drain_tasks(); let turn_context = tasks.first().map(|task| Arc::clone(&task.turn_context)); - let turn_extension_data = tasks - .first() - .map(|task| Arc::clone(&task.turn_extension_data)); for task in tasks { self.handle_task_abort(task, reason.clone()).await; } - if let Some(turn_context) = turn_context.as_deref() - && let Some(turn_extension_data) = turn_extension_data.as_deref() - { - self.emit_turn_abort_lifecycle(turn_context, reason.clone(), turn_extension_data); + if let Some(turn_context) = turn_context.as_deref() { + self.emit_turn_abort_lifecycle(reason.clone(), turn_context.extension_data.as_ref()); } if let Err(err) = self .goal_runtime_apply(GoalRuntimeEvent::TaskAborted { @@ -589,7 +576,6 @@ impl Session { let mut turn_had_memory_citation = false; let mut turn_tool_calls = 0_u64; let mut records_turn_token_usage_on_span = false; - let mut turn_extension_data = None; let turn_state = { let mut active = self.active_turn.lock().await; if let Some(at) = active.as_mut() @@ -598,7 +584,6 @@ impl Session { records_turn_token_usage_on_span = removed_task.records_turn_token_usage_on_span; if removed_task.active_turn_is_empty { should_clear_active_turn = true; - turn_extension_data = Some(removed_task.turn_extension_data); let turn_state = Arc::clone(&at.turn_state); Some(turn_state) } else { @@ -756,10 +741,8 @@ impl Session { .turn_timing_state .time_to_first_token_ms() .await; - if should_clear_active_turn - && let Some(turn_extension_data) = turn_extension_data.as_deref() - { - self.emit_turn_stop_lifecycle(turn_context.as_ref(), turn_extension_data); + if should_clear_active_turn { + self.emit_turn_stop_lifecycle(turn_context.extension_data.as_ref()); } if let Err(err) = self .goal_runtime_apply(GoalRuntimeEvent::TurnFinished { diff --git a/codex-rs/ext/extension-api/examples/enabled_extensions.rs b/codex-rs/ext/extension-api/examples/enabled_extensions.rs index 9a267d6919..f32af97c1a 100644 --- a/codex-rs/ext/extension-api/examples/enabled_extensions.rs +++ b/codex-rs/ext/extension-api/examples/enabled_extensions.rs @@ -13,9 +13,9 @@ fn main() { let registry = builder.build(); // 2. The host decides which stores are shared. - let session_store = ExtensionData::new(); - let first_thread_store = ExtensionData::new(); - let second_thread_store = ExtensionData::new(); + let session_store = ExtensionData::new("session"); + let first_thread_store = ExtensionData::new("thread-1"); + let second_thread_store = ExtensionData::new("thread-2"); // 3. Reusing the same session store shares session state across threads. let first_thread_fragments = contribute_prompt(®istry, &session_store, &first_thread_store); diff --git a/codex-rs/ext/extension-api/src/contributors.rs b/codex-rs/ext/extension-api/src/contributors.rs index 961b294263..7393f0b3db 100644 --- a/codex-rs/ext/extension-api/src/contributors.rs +++ b/codex-rs/ext/extension-api/src/contributors.rs @@ -1,7 +1,6 @@ use std::future::Future; use std::sync::Arc; -use codex_protocol::ThreadId; use codex_protocol::items::TurnItem; use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::TokenUsageInfo; @@ -79,8 +78,7 @@ pub trait TokenUsageContributor: Send + Sync { &self, _session_store: &ExtensionData, _thread_store: &ExtensionData, - _thread_id: ThreadId, - _turn_id: &str, + _turn_store: &ExtensionData, _token_usage: &TokenUsageInfo, ) { } diff --git a/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs b/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs index 41da56c030..d50f5a1e2f 100644 --- a/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs +++ b/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs @@ -1,11 +1,7 @@ -use codex_protocol::ThreadId; - use crate::ExtensionData; /// Input supplied when the host starts a runtime for a thread. pub struct ThreadStartInput<'a, C> { - /// Identifier for the thread whose runtime is starting. - pub thread_id: ThreadId, /// Host configuration visible at thread start. pub config: &'a C, /// Store scoped to the host session runtime. @@ -16,8 +12,6 @@ pub struct ThreadStartInput<'a, C> { /// Input supplied when the host resumes an existing thread. pub struct ThreadResumeInput<'a> { - /// Identifier for the thread being resumed. - pub thread_id: ThreadId, /// Store scoped to the host session runtime. pub session_store: &'a ExtensionData, /// Store scoped to this thread runtime. @@ -26,8 +20,6 @@ pub struct ThreadResumeInput<'a> { /// Input supplied when the host stops a thread runtime. pub struct ThreadStopInput<'a> { - /// Identifier for the thread whose runtime is stopping. - pub thread_id: ThreadId, /// Store scoped to the host session runtime. pub session_store: &'a ExtensionData, /// Store scoped to this thread runtime. diff --git a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs index 8e6f2fb7f0..0b53183e28 100644 --- a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs +++ b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs @@ -1,14 +1,9 @@ -use codex_protocol::ThreadId; use codex_protocol::protocol::TurnAbortReason; use crate::ExtensionData; /// Input supplied when the host starts a turn. pub struct TurnStartInput<'a> { - /// Identifier for the thread containing this turn. - pub thread_id: ThreadId, - /// Identifier for the turn that is starting. - pub turn_id: &'a str, /// Store scoped to the host session runtime. pub session_store: &'a ExtensionData, /// Store scoped to this thread runtime. @@ -19,10 +14,6 @@ pub struct TurnStartInput<'a> { /// Input supplied when the host completes a turn. pub struct TurnStopInput<'a> { - /// Identifier for the thread containing this turn. - pub thread_id: ThreadId, - /// Identifier for the turn that is stopping. - pub turn_id: &'a str, /// Store scoped to the host session runtime. pub session_store: &'a ExtensionData, /// Store scoped to this thread runtime. @@ -33,10 +24,6 @@ pub struct TurnStopInput<'a> { /// Input supplied when the host aborts a turn. pub struct TurnAbortInput<'a> { - /// Identifier for the thread containing this turn. - pub thread_id: ThreadId, - /// Identifier for the turn that is aborting. - pub turn_id: &'a str, /// Reason the host aborted the turn. pub reason: TurnAbortReason, /// Store scoped to the host session runtime. diff --git a/codex-rs/ext/extension-api/src/state.rs b/codex-rs/ext/extension-api/src/state.rs index 2fc9a8725f..aab37f5059 100644 --- a/codex-rs/ext/extension-api/src/state.rs +++ b/codex-rs/ext/extension-api/src/state.rs @@ -8,15 +8,24 @@ use std::sync::PoisonError; type ErasedData = Arc; /// Typed extension-owned data attached to one host object. -#[derive(Default, Debug)] +#[derive(Debug)] pub struct ExtensionData { + level_id: String, entries: Mutex>, } impl ExtensionData { - /// Creates an empty attachment map. - pub fn new() -> Self { - Self::default() + /// Creates an empty attachment map for one host-owned scope. + pub fn new(level_id: impl Into) -> Self { + Self { + level_id: level_id.into(), + entries: Mutex::new(HashMap::new()), + } + } + + /// Returns the host identity for the scope this data is attached to. + pub fn level_id(&self) -> &str { + &self.level_id } /// Returns the attached value of type `T`, if one exists. diff --git a/codex-rs/ext/guardian/src/lib.rs b/codex-rs/ext/guardian/src/lib.rs index 1754f6e642..809a381471 100644 --- a/codex-rs/ext/guardian/src/lib.rs +++ b/codex-rs/ext/guardian/src/lib.rs @@ -52,8 +52,11 @@ where S: Send + Sync, { fn on_thread_start(&self, input: ThreadStartInput<'_, Config>) { + let Ok(forked_from_thread_id) = ThreadId::from_string(input.thread_store.level_id()) else { + return; + }; input.thread_store.insert(GuardianThreadContext { - forked_from_thread_id: input.thread_id, + forked_from_thread_id, }); } } From 68e045a631e108ae069660bc2ce1148f46d29130 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 16:43:28 +0200 Subject: [PATCH 05/13] Make context contributors async (#22491) ## Summary - make ContextContributor return a boxed Send future - await context contributors during initial context assembly - update existing contributors and extension-api examples for the async contract ## Testing - cargo test -p codex-extension-api --examples - cargo test -p codex-git-attribution - cargo test -p codex-core build_initial_context_includes_git_attribution_from_extensions -- --nocapture - cargo test -p codex-core build_initial_context_omits_git_attribution_when_feature_is_disabled -- --nocapture - cargo test -p codex-core (fails in unrelated agent::control::tests::spawn_agent_fork_last_n_turns_keeps_only_recent_turns stack overflow) - just fix -p codex-extension-api - just fix -p codex-git-attribution - just fix -p codex-core - cargo clippy -p codex-extension-api --examples --- codex-rs/core/src/session/mod.rs | 14 ++++-- codex-rs/core/src/session/tests.rs | 34 +++++++------ .../examples/enabled_extensions.rs | 49 +++++++++++++++---- .../shared_state_extension.rs | 44 +++++++++-------- .../ext/extension-api/src/contributors.rs | 10 ++-- codex-rs/ext/git-attribution/src/lib.rs | 32 ++++++------ 6 files changed, 114 insertions(+), 69 deletions(-) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 3b8939ec5e..a1d598bff7 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -2694,11 +2694,15 @@ impl Session { { developer_sections.push(plugin_instructions.render()); } - for contributor in self.services.extensions.context_contributors() { - for fragment in contributor.contribute( - &self.services.session_extension_data, - &self.services.thread_extension_data, - ) { + let context_contributors = self.services.extensions.context_contributors().to_vec(); + for contributor in context_contributors { + for fragment in contributor + .contribute( + &self.services.session_extension_data, + &self.services.thread_extension_data, + ) + .await + { match fragment.slot() { PromptSlot::DeveloperPolicy | PromptSlot::DeveloperCapabilities => { developer_sections.push(fragment.text().to_string()); diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 45ac5ab9c5..5a4bc2d0e7 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -6352,21 +6352,25 @@ struct GitAttributionTestContributor; struct GitAttributionTestState; impl codex_extension_api::ContextContributor for GitAttributionTestContributor { - fn contribute( - &self, - _session_store: &codex_extension_api::ExtensionData, - thread_store: &codex_extension_api::ExtensionData, - ) -> Vec { - thread_store - .get::() - .is_some() - .then(|| { - codex_extension_api::PromptFragment::developer_policy( - "git attribution extension enabled", - ) - }) - .into_iter() - .collect() + fn contribute<'a>( + &'a self, + _session_store: &'a codex_extension_api::ExtensionData, + thread_store: &'a codex_extension_api::ExtensionData, + ) -> std::pin::Pin< + Box> + Send + 'a>, + > { + Box::pin(async move { + thread_store + .get::() + .is_some() + .then(|| { + codex_extension_api::PromptFragment::developer_policy( + "git attribution extension enabled", + ) + }) + .into_iter() + .collect() + }) } } diff --git a/codex-rs/ext/extension-api/examples/enabled_extensions.rs b/codex-rs/ext/extension-api/examples/enabled_extensions.rs index f32af97c1a..9027c28241 100644 --- a/codex-rs/ext/extension-api/examples/enabled_extensions.rs +++ b/codex-rs/ext/extension-api/examples/enabled_extensions.rs @@ -1,6 +1,12 @@ #[path = "enabled_extensions/shared_state_extension.rs"] mod shared_state_extension; +use std::future::Future; +use std::pin::pin; +use std::task::Context; +use std::task::Poll; +use std::task::Waker; + use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionRegistryBuilder; use shared_state_extension::recorded_style_contributions; @@ -18,9 +24,21 @@ fn main() { let second_thread_store = ExtensionData::new("thread-2"); // 3. Reusing the same session store shares session state across threads. - let first_thread_fragments = contribute_prompt(®istry, &session_store, &first_thread_store); - contribute_prompt(®istry, &session_store, &first_thread_store); - contribute_prompt(®istry, &session_store, &second_thread_store); + let first_thread_fragments = block_on_ready(contribute_prompt( + ®istry, + &session_store, + &first_thread_store, + )); + block_on_ready(contribute_prompt( + ®istry, + &session_store, + &first_thread_store, + )); + block_on_ready(contribute_prompt( + ®istry, + &session_store, + &second_thread_store, + )); println!("first prompt fragments: {}", first_thread_fragments.len()); println!( @@ -49,14 +67,27 @@ fn main() { ); } -fn contribute_prompt( +async fn contribute_prompt( registry: &codex_extension_api::ExtensionRegistry<()>, session_store: &ExtensionData, thread_store: &ExtensionData, ) -> Vec { - registry - .context_contributors() - .iter() - .flat_map(|contributor| contributor.contribute(session_store, thread_store)) - .collect() + let mut fragments = Vec::new(); + for contributor in registry.context_contributors() { + fragments.extend(contributor.contribute(session_store, thread_store).await); + } + fragments +} + +fn block_on_ready(future: F) -> F::Output +where + F: Future, +{ + let waker = Waker::noop(); + let mut context = Context::from_waker(waker); + let mut future = pin!(future); + match future.as_mut().poll(&mut context) { + Poll::Ready(output) => output, + Poll::Pending => panic!("example context contributors should complete immediately"), + } } diff --git a/codex-rs/ext/extension-api/examples/enabled_extensions/shared_state_extension.rs b/codex-rs/ext/extension-api/examples/enabled_extensions/shared_state_extension.rs index 25ab027c88..531f65b99e 100644 --- a/codex-rs/ext/extension-api/examples/enabled_extensions/shared_state_extension.rs +++ b/codex-rs/ext/extension-api/examples/enabled_extensions/shared_state_extension.rs @@ -17,17 +17,19 @@ pub fn install(registry: &mut ExtensionRegistryBuilder<()>) { struct StyleContributor; impl ContextContributor for StyleContributor { - fn contribute( - &self, - session_store: &ExtensionData, - thread_store: &ExtensionData, - ) -> Vec { - contribution_counts(session_store).record_style(); - contribution_counts(thread_store).record_style(); + fn contribute<'a>( + &'a self, + session_store: &'a ExtensionData, + thread_store: &'a ExtensionData, + ) -> std::pin::Pin> + Send + 'a>> { + Box::pin(async move { + contribution_counts(session_store).record_style(); + contribution_counts(thread_store).record_style(); - vec![PromptFragment::developer_policy( - "Prefer short answers unless the user asks for detail.", - )] + vec![PromptFragment::developer_policy( + "Prefer short answers unless the user asks for detail.", + )] + }) } } @@ -35,17 +37,19 @@ impl ContextContributor for StyleContributor { struct UsageContributor; impl ContextContributor for UsageContributor { - fn contribute( - &self, - session_store: &ExtensionData, - thread_store: &ExtensionData, - ) -> Vec { - contribution_counts(session_store).record_usage(); - contribution_counts(thread_store).record_usage(); + fn contribute<'a>( + &'a self, + session_store: &'a ExtensionData, + thread_store: &'a ExtensionData, + ) -> std::pin::Pin> + Send + 'a>> { + Box::pin(async move { + contribution_counts(session_store).record_usage(); + contribution_counts(thread_store).record_usage(); - vec![PromptFragment::developer_capability( - "This extension can contribute more than one prompt fragment.", - )] + vec![PromptFragment::developer_capability( + "This extension can contribute more than one prompt fragment.", + )] + }) } } diff --git a/codex-rs/ext/extension-api/src/contributors.rs b/codex-rs/ext/extension-api/src/contributors.rs index 7393f0b3db..aea59c8a50 100644 --- a/codex-rs/ext/extension-api/src/contributors.rs +++ b/codex-rs/ext/extension-api/src/contributors.rs @@ -26,11 +26,11 @@ pub use turn_lifecycle::TurnStopInput; /// Extension contribution that adds prompt fragments during prompt assembly. pub trait ContextContributor: Send + Sync { - fn contribute( - &self, - session_store: &ExtensionData, - thread_store: &ExtensionData, - ) -> Vec; + fn contribute<'a>( + &'a self, + session_store: &'a ExtensionData, + thread_store: &'a ExtensionData, + ) -> std::pin::Pin> + Send + 'a>>; } /// Contributor for host-owned thread lifecycle gates. diff --git a/codex-rs/ext/git-attribution/src/lib.rs b/codex-rs/ext/git-attribution/src/lib.rs index 1df7815d6e..03655296da 100644 --- a/codex-rs/ext/git-attribution/src/lib.rs +++ b/codex-rs/ext/git-attribution/src/lib.rs @@ -16,21 +16,23 @@ const DEFAULT_ATTRIBUTION_VALUE: &str = "Codex "; pub struct GitAttributionExtension; impl ContextContributor for GitAttributionExtension { - fn contribute( - &self, - _session_store: &ExtensionData, - thread_store: &ExtensionData, - ) -> Vec { - let Some(config_store) = thread_store.get::() else { - return Vec::new(); - }; - if !config_store.enabled { - return Vec::new(); - } - build_instruction(config_store.prompt.as_deref()) - .map(PromptFragment::developer_policy) - .into_iter() - .collect() + fn contribute<'a>( + &'a self, + _session_store: &'a ExtensionData, + thread_store: &'a ExtensionData, + ) -> std::pin::Pin> + Send + 'a>> { + Box::pin(async move { + let Some(config_store) = thread_store.get::() else { + return Vec::new(); + }; + if !config_store.enabled { + return Vec::new(); + } + build_instruction(config_store.prompt.as_deref()) + .map(PromptFragment::developer_policy) + .into_iter() + .collect() + }) } } From 6f77b70ff3d9995fa7e0dd7b88f11af3bef05d0d Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Wed, 13 May 2026 12:11:15 -0300 Subject: [PATCH 06/13] feat(tui): remove Zellij TUI workarounds (#22214) ## Why We added Zellij-specific TUI workarounds because older Zellij behavior did not work with Codex's normal terminal model: - #8555 made `tui.alternate_screen = "auto"` disable alternate screen in Zellij so transcript history stayed available. - #16578 avoided scroll-region operations in Zellij by emitting raw newlines and using a separate composer styling path. This PR removes both workarounds because the latest Zellij release tested locally (`zellij 0.44.1`) works correctly with Codex's standard TUI behavior: normal alternate-screen handling, redraw, and history insertion. ## What Changed - Removed the `InsertHistoryMode::Zellij` path and the Zellij-only newline scrollback insertion behavior. - Removed cached `is_zellij` state from the TUI and composer. - Removed Zellij-specific composer styling, the helper snapshot, and the `TerminalInfo::is_zellij()` convenience method that only served this workaround. - Changed `tui.alternate_screen = "auto"` to use alternate screen for Zellij too; `--no-alt-screen` and `tui.alternate_screen = "never"` still preserve the inline mode escape hatch. - Updated the generated config schema description for `tui.alternate_screen`. ## How to Test Manual smoke path used with `zellij 0.44.1`: 1. Build and run this branch inside a Zellij `0.44.1` session with default config. 2. Start Codex normally and produce enough assistant/tool output to create scrollback. 3. Confirm the transcript remains readable, the composer renders normally, and scrolling through terminal history works. 4. Resize the Zellij pane while output exists and confirm the TUI redraws without duplicated, missing, or stale rows. 5. Compare with `--no-alt-screen` or `-c tui.alternate_screen=never` if you want to verify the inline fallback still works. Targeted tests: - `just write-config-schema` - `just fmt` - `just fix -p codex-tui` - `cargo test -p codex-terminal-detection` - `cargo test -p codex-tui alternate_screen_auto_uses_alt_screen` Attempted but did not complete locally: - `cargo test -p codex-tui` built and ran the new test successfully, then failed later on unrelated local failures in `status_permissions_full_disk_managed_*` and a stack overflow in `tests::fork_last_filters_latest_session_by_cwd_unless_show_all`. ## Documentation No developers.openai.com Codex documentation update is needed for this revert. --- codex-rs/config/src/types.rs | 7 +- codex-rs/core/config.schema.json | 8 +- codex-rs/core/src/config/mod.rs | 4 +- codex-rs/protocol/src/config_types.rs | 23 +- codex-rs/tui/src/bottom_pane/chat_composer.rs | 127 +---------- ...omposer__tests__zellij_empty_composer.snap | 14 -- codex-rs/tui/src/bottom_pane/textarea.rs | 28 +-- codex-rs/tui/src/cli.rs | 4 +- codex-rs/tui/src/custom_terminal.rs | 5 +- codex-rs/tui/src/insert_history.rs | 204 ++++-------------- codex-rs/tui/src/lib.rs | 50 ++--- codex-rs/tui/src/tui.rs | 126 +++-------- 12 files changed, 126 insertions(+), 474 deletions(-) delete mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__zellij_empty_composer.snap diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index dfc81852ea..21d9b44752 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -668,12 +668,9 @@ pub struct Tui { /// Controls whether the TUI uses the terminal's alternate screen buffer. /// - /// - `auto` (default): Disable alternate screen in Zellij, enable elsewhere. - /// - `always`: Always use alternate screen (original behavior). + /// - `auto` (default): Use alternate screen. + /// - `always`: Always use alternate screen. /// - `never`: Never use alternate screen (inline mode only, preserves scrollback). - /// - /// Using alternate screen provides a cleaner fullscreen experience but prevents - /// scrollback in terminal multiplexers like Zellij that follow the xterm spec. #[serde(default)] pub alternate_screen: AltScreenMode, diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 7601f01377..1d3ca3210b 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -62,17 +62,17 @@ "type": "object" }, "AltScreenMode": { - "description": "Controls whether the TUI uses the terminal's alternate screen buffer.\n\n**Background:** The alternate screen buffer provides a cleaner fullscreen experience without polluting the terminal's scrollback history. However, it conflicts with terminal multiplexers like Zellij that strictly follow the xterm specification, which defines that alternate screen buffers should not have scrollback.\n\n**Zellij's behavior:** Zellij intentionally disables scrollback in alternate screen mode (see https://github.com/zellij-org/zellij/pull/1032) to comply with the xterm spec. This is by design and not configurable in Zellij—there is no option to enable scrollback in alternate screen mode.\n\n**Solution:** This setting provides a pragmatic workaround: - `auto` (default): Automatically detect the terminal multiplexer. If running in Zellij, disable alternate screen to preserve scrollback. Enable it everywhere else. - `always`: Always use alternate screen mode (original behavior before this fix). - `never`: Never use alternate screen mode. Runs in inline mode, preserving scrollback in all multiplexers.\n\nThe CLI flag `--no-alt-screen` can override this setting at runtime.", + "description": "Controls whether the TUI uses the terminal's alternate screen buffer.\n\n- `auto` (default): Use alternate screen mode. - `always`: Always use alternate screen mode. - `never`: Never use alternate screen mode. Runs in inline mode, preserving scrollback.\n\nThe CLI flag `--no-alt-screen` can override this setting at runtime.", "oneOf": [ { - "description": "Auto-detect: disable alternate screen in Zellij, enable elsewhere.", + "description": "Use alternate screen mode.", "enum": [ "auto" ], "type": "string" }, { - "description": "Always use alternate screen (original behavior).", + "description": "Always use alternate screen mode.", "enum": [ "always" ], @@ -2536,7 +2536,7 @@ } ], "default": "auto", - "description": "Controls whether the TUI uses the terminal's alternate screen buffer.\n\n- `auto` (default): Disable alternate screen in Zellij, enable elsewhere. - `always`: Always use alternate screen (original behavior). - `never`: Never use alternate screen (inline mode only, preserves scrollback).\n\nUsing alternate screen provides a cleaner fullscreen experience but prevents scrollback in terminal multiplexers like Zellij that follow the xterm spec." + "description": "Controls whether the TUI uses the terminal's alternate screen buffer.\n\n- `auto` (default): Use alternate screen. - `always`: Always use alternate screen. - `never`: Never use alternate screen (inline mode only, preserves scrollback)." }, "animations": { "default": true, diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index f5f95f9e87..d74f83102c 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -531,8 +531,8 @@ pub struct Config { /// Controls whether the TUI uses the terminal's alternate screen buffer. /// /// This is the same `tui.alternate_screen` value from `config.toml`. - /// - `auto` (default): Disable alternate screen in Zellij, enable elsewhere. - /// - `always`: Always use alternate screen (original behavior). + /// - `auto` (default): Use alternate screen. + /// - `always`: Always use alternate screen. /// - `never`: Never use alternate screen (inline mode, preserves scrollback). pub tui_alternate_screen: AltScreenMode, /// Ordered list of status line item identifiers for the TUI. diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs index 47dc15f183..37e8d95e25 100644 --- a/codex-rs/protocol/src/config_types.rs +++ b/codex-rs/protocol/src/config_types.rs @@ -465,22 +465,9 @@ pub enum TrustLevel { /// Controls whether the TUI uses the terminal's alternate screen buffer. /// -/// **Background:** The alternate screen buffer provides a cleaner fullscreen experience -/// without polluting the terminal's scrollback history. However, it conflicts with terminal -/// multiplexers like Zellij that strictly follow the xterm specification, which defines -/// that alternate screen buffers should not have scrollback. -/// -/// **Zellij's behavior:** Zellij intentionally disables scrollback in alternate screen mode -/// (see https://github.com/zellij-org/zellij/pull/1032) to comply with the xterm spec. This -/// is by design and not configurable in Zellij—there is no option to enable scrollback in -/// alternate screen mode. -/// -/// **Solution:** This setting provides a pragmatic workaround: -/// - `auto` (default): Automatically detect the terminal multiplexer. If running in Zellij, -/// disable alternate screen to preserve scrollback. Enable it everywhere else. -/// - `always`: Always use alternate screen mode (original behavior before this fix). -/// - `never`: Never use alternate screen mode. Runs in inline mode, preserving scrollback -/// in all multiplexers. +/// - `auto` (default): Use alternate screen mode. +/// - `always`: Always use alternate screen mode. +/// - `never`: Never use alternate screen mode. Runs in inline mode, preserving scrollback. /// /// The CLI flag `--no-alt-screen` can override this setting at runtime. #[derive( @@ -489,10 +476,10 @@ pub enum TrustLevel { #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum AltScreenMode { - /// Auto-detect: disable alternate screen in Zellij, enable elsewhere. + /// Use alternate screen mode. #[default] Auto, - /// Always use alternate screen (original behavior). + /// Always use alternate screen mode. Always, /// Never use alternate screen (inline mode only). Never, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 5f93febfa7..0f97b7f6c9 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -415,7 +415,6 @@ pub(crate) struct ChatComposer { audio_device_selection_enabled: bool, windows_degraded_sandbox_active: bool, side_conversation_active: bool, - is_zellij: bool, status_line_value: Option>, status_line_hyperlink_url: Option, status_line_enabled: bool, @@ -599,10 +598,6 @@ impl ChatComposer { audio_device_selection_enabled: false, windows_degraded_sandbox_active: false, side_conversation_active: false, - is_zellij: matches!( - codex_terminal_detection::terminal_info().multiplexer, - Some(codex_terminal_detection::Multiplexer::Zellij {}) - ), status_line_value: None, status_line_hyperlink_url: None, status_line_enabled: false, @@ -4788,56 +4783,20 @@ impl ChatComposer { } } } - self.render_textarea( - composer_rect, - remote_images_rect, - textarea_rect, - buf, - mask_char, - ); - } - - /// Paint the composer's text input area, prompt chevron, and placeholder text. - /// - /// In Zellij sessions the textarea uses explicit `Color::Reset` foreground styling - /// to prevent the multiplexer's pane chrome from bleeding into cell styles, and - /// substitutes hardcoded colors for `.bold()` / `.dim()` modifiers that Zellij - /// renders inconsistently. The standard path is unchanged. - fn render_textarea( - &self, - composer_rect: Rect, - remote_images_rect: Rect, - textarea_rect: Rect, - buf: &mut Buffer, - mask_char: Option, - ) { - let is_zellij = self.is_zellij; let style = user_message_style(); - let textarea_style = style.fg(ratatui::style::Color::Reset); Block::default().style(style).render_ref(composer_rect, buf); if !remote_images_rect.is_empty() { Paragraph::new(self.remote_images_lines(remote_images_rect.width)) .style(style) .render_ref(remote_images_rect, buf); } - if is_zellij && !textarea_rect.is_empty() { - buf.set_style(textarea_rect, textarea_style); - } if !textarea_rect.is_empty() { let prompt = if self.input_enabled { if self.is_bash_mode { - if is_zellij { - Span::from("!").light_red() - } else { - Span::from("!").light_red().bold() - } - } else if is_zellij { - Span::styled("›", style.fg(ratatui::style::Color::Cyan)) + Span::from("!").light_red().bold() } else { "›".bold() } - } else if is_zellij { - Span::styled("›", style.fg(ratatui::style::Color::DarkGray)) } else { "›".dim() }; @@ -4852,39 +4811,8 @@ impl ChatComposer { let mut state = self.textarea_state.borrow_mut(); let textarea_is_empty = self.textarea.text().is_empty() && !self.is_bash_mode; if let Some(mask_char) = mask_char { - self.textarea.render_ref_masked( - textarea_rect, - buf, - &mut state, - mask_char, - if is_zellij { - textarea_style - } else { - ratatui::style::Style::default() - }, - ); - } else if is_zellij && textarea_is_empty { - buf.set_style(textarea_rect, textarea_style); - } else if is_zellij { - let highlight_ranges = self.history_search_highlight_ranges(); - if highlight_ranges.is_empty() { - self.textarea - .render_ref_styled(textarea_rect, buf, &mut state, textarea_style); - } else { - let highlight_style = - textarea_style.add_modifier(Modifier::REVERSED | Modifier::BOLD); - let highlights = highlight_ranges - .into_iter() - .map(|range| (range, highlight_style)) - .collect::>(); - self.textarea.render_ref_styled_with_highlights( - textarea_rect, - buf, - &mut state, - textarea_style, - &highlights, - ); - } + self.textarea + .render_ref_masked(textarea_rect, buf, &mut state, mask_char); } else { let highlight_ranges = self.history_search_highlight_ranges(); if highlight_ranges.is_empty() { @@ -4915,18 +4843,9 @@ impl ChatComposer { .to_string() }; if !textarea_rect.is_empty() { - if is_zellij { - buf.set_string( - textarea_rect.x, - textarea_rect.y, - text, - textarea_style.fg(ratatui::style::Color::White).italic(), - ); - } else { - let placeholder = Span::from(text).dim(); - let line = Line::from(vec![placeholder]); - line.render_ref(textarea_rect.inner(Margin::new(0, 0)), buf); - } + let placeholder = Span::from(text).dim(); + Line::from(vec![placeholder]) + .render_ref(textarea_rect.inner(Margin::new(0, 0)), buf); } } } @@ -5149,35 +5068,6 @@ mod tests { ); } - fn snapshot_zellij_composer_state(name: &str, setup: F) - where - F: FnOnce(&mut ChatComposer), - { - use ratatui::Terminal; - use ratatui::backend::TestBackend; - - let (tx, _rx) = unbounded_channel::(); - let sender = AppEventSender::new(tx); - let mut composer = ChatComposer::new( - /*has_input_focus*/ true, - sender, - /*enhanced_keys_supported*/ true, - "Ask Codex to do anything".to_string(), - /*disable_paste_burst*/ false, - ); - composer.is_zellij = true; - setup(&mut composer); - let footer_props = composer.footer_props(); - let footer_lines = footer_height(&footer_props); - let footer_spacing = ChatComposer::footer_spacing(footer_lines); - let height = footer_lines + footer_spacing + 8; - let mut terminal = Terminal::new(TestBackend::new(100, height)).unwrap(); - terminal - .draw(|f| composer.render(f.area(), f.buffer_mut())) - .unwrap(); - insta::assert_snapshot!(name, terminal.backend()); - } - #[test] fn footer_mode_snapshots() { use crossterm::event::KeyCode; @@ -5697,11 +5587,6 @@ mod tests { ); } - #[test] - fn zellij_empty_composer_snapshot() { - snapshot_zellij_composer_state("zellij_empty_composer", |_composer| {}); - } - #[test] fn esc_hint_stays_hidden_with_draft_content() { use crossterm::event::KeyCode; diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__zellij_empty_composer.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__zellij_empty_composer.snap deleted file mode 100644 index 15496a4539..0000000000 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__zellij_empty_composer.snap +++ /dev/null @@ -1,14 +0,0 @@ ---- -source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 4001 -expression: terminal.backend() ---- -" " -"› Ask Codex to do anything " -" " -" " -" " -" " -" " -" " -" ? for shortcuts 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index 0638412110..96f6cf8cbb 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -24,6 +24,7 @@ use crossterm::event::KeyEventKind; use crossterm::event::KeyModifiers; use ratatui::buffer::Buffer; use ratatui::layout::Rect; +use ratatui::style::Color; use ratatui::style::Style; use ratatui::widgets::StatefulWidgetRef; use ratatui::widgets::WidgetRef; @@ -1893,7 +1894,6 @@ impl TextArea { buf: &mut Buffer, state: &mut TextAreaState, mask_char: char, - base_style: Style, ) { let lines = self.wrapped_lines(area.width); let scroll = self.effective_scroll(area.height, &lines, state.scroll); @@ -1901,25 +1901,7 @@ impl TextArea { let start = scroll as usize; let end = (scroll + area.height).min(lines.len() as u16) as usize; - self.render_lines_masked(area, buf, &lines, start..end, mask_char, base_style); - } - - /// Render the textarea with an explicit `base_style` applied to every cell, - /// used by the Zellij code path to override inherited terminal styles. - pub(crate) fn render_ref_styled( - &self, - area: Rect, - buf: &mut Buffer, - state: &mut TextAreaState, - base_style: Style, - ) { - let lines = self.wrapped_lines(area.width); - let scroll = self.effective_scroll(area.height, &lines, state.scroll); - state.scroll = scroll; - - let start = scroll as usize; - let end = (scroll + area.height).min(lines.len() as u16) as usize; - self.render_lines(area, buf, &lines, start..end, base_style, &[]); + self.render_lines_masked(area, buf, &lines, start..end, mask_char); } /// Render the textarea with `base_style` plus additional render-only highlight ranges. @@ -1970,7 +1952,7 @@ impl TextArea { } let styled = &self.text[overlap_start..overlap_end]; let x_off = self.text[line_range.start..overlap_start].width() as u16; - let style = base_style.fg(ratatui::style::Color::Cyan); + let style = base_style.fg(Color::Cyan); buf.set_string(area.x + x_off, y, styled, style); } @@ -1996,18 +1978,16 @@ impl TextArea { lines: &[Range], range: std::ops::Range, mask_char: char, - base_style: Style, ) { for (row, idx) in range.enumerate() { let r = &lines[idx]; let y = area.y + row as u16; let line_range = r.start..r.end - 1; - buf.set_style(Rect::new(area.x, y, area.width, 1), base_style); let masked = self.text[line_range.clone()] .chars() .map(|_| mask_char) .collect::(); - buf.set_string(area.x, y, &masked, base_style); + buf.set_string(area.x, y, &masked, Style::default()); } } } diff --git a/codex-rs/tui/src/cli.rs b/codex-rs/tui/src/cli.rs index 3d47442c90..d6001c60d8 100644 --- a/codex-rs/tui/src/cli.rs +++ b/codex-rs/tui/src/cli.rs @@ -63,9 +63,7 @@ pub struct Cli { /// Disable alternate screen mode /// - /// Runs the TUI in inline mode, preserving terminal scrollback history. This is useful - /// in terminal multiplexers like Zellij that follow the xterm spec strictly and disable - /// scrollback in alternate screen buffers. + /// Runs the TUI in inline mode, preserving terminal scrollback history. #[arg(long = "no-alt-screen", default_value_t = false)] pub no_alt_screen: bool, diff --git a/codex-rs/tui/src/custom_terminal.rs b/codex-rs/tui/src/custom_terminal.rs index 3d0519080e..995a0358f6 100644 --- a/codex-rs/tui/src/custom_terminal.rs +++ b/codex-rs/tui/src/custom_terminal.rs @@ -486,9 +486,8 @@ where } /// Force the next draw pass to repaint the entire viewport by resetting the - /// diff buffer. Call this after operations that move screen content outside of - /// ratatui's knowledge (e.g., Zellij-mode scrolling via raw newlines), since - /// the diff buffer's assumptions about what is currently displayed are invalid. + /// diff buffer. Call this after raw terminal operations that move screen + /// content outside ratatui's knowledge. pub fn invalidate_viewport(&mut self) { self.previous_buffer_mut().reset(); } diff --git a/codex-rs/tui/src/insert_history.rs b/codex-rs/tui/src/insert_history.rs index 6a83594e1f..f2c64a1098 100644 --- a/codex-rs/tui/src/insert_history.rs +++ b/codex-rs/tui/src/insert_history.rs @@ -1,8 +1,7 @@ //! Inserts finalized history rows into terminal scrollback. //! //! Codex uses the terminal scrollback itself for finalized chat history, so inserting a history -//! cell is an escape-sequence operation rather than a normal ratatui render. The mode determines -//! how to create room for new history above the inline viewport. +//! cell is an escape-sequence operation rather than a normal ratatui render. use std::fmt; use std::io; @@ -35,28 +34,6 @@ use ratatui::style::Modifier; use ratatui::text::Line; use ratatui::text::Span; -/// Selects the terminal escape strategy for inserting history lines above the viewport. -/// -/// Standard terminals support `DECSTBM` scroll regions and Reverse Index (`ESC M`), -/// which let us slide existing content down without redrawing it. Zellij silently -/// drops or mishandles those sequences, so `Zellij` mode falls back to emitting -/// newlines at the bottom of the screen and writing lines at absolute positions. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum InsertHistoryMode { - Standard, - Zellij, -} - -impl InsertHistoryMode { - pub fn new(is_zellij: bool) -> Self { - if is_zellij { - Self::Zellij - } else { - Self::Standard - } - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HistoryLineWrapPolicy { PreWrap, @@ -72,38 +49,12 @@ pub fn insert_history_lines( where B: Backend + Write, { - insert_history_lines_with_mode(terminal, lines, InsertHistoryMode::Standard) + insert_history_lines_with_wrap_policy(terminal, lines, HistoryLineWrapPolicy::PreWrap) } -/// Insert `lines` above the viewport, using the escape strategy selected by `mode`. -/// -/// In `Standard` mode this manipulates DECSTBM scroll regions to slide existing -/// scrollback down and writes new lines into the freed space. In `Zellij` mode it -/// emits newlines at the screen bottom to create space (since Zellij ignores scroll -/// region escapes) and writes lines at computed absolute positions. Both modes -/// update `terminal.viewport_area` so subsequent draw passes know where the -/// viewport moved to. Resize reflow uses the same viewport-aware path after -/// clearing old scrollback. -pub fn insert_history_lines_with_mode( +pub fn insert_history_lines_with_wrap_policy( terminal: &mut crate::custom_terminal::Terminal, lines: Vec, - mode: InsertHistoryMode, -) -> io::Result<()> -where - B: Backend + Write, -{ - insert_history_lines_with_mode_and_wrap_policy( - terminal, - lines, - mode, - HistoryLineWrapPolicy::PreWrap, - ) -} - -pub fn insert_history_lines_with_mode_and_wrap_policy( - terminal: &mut crate::custom_terminal::Terminal, - lines: Vec, - mode: InsertHistoryMode, wrap_policy: HistoryLineWrapPolicy, ) -> io::Result<()> where @@ -151,90 +102,56 @@ where wrapped.extend(line_wrapped); } let wrapped_lines = wrapped_rows as u16; + let cursor_top = if area.bottom() < screen_size.height { + // If the viewport is not at the bottom of the screen, scroll it down to make room. + // Don't scroll it past the bottom of the screen. + let scroll_amount = wrapped_lines.min(screen_size.height - area.bottom()); - match mode { - InsertHistoryMode::Zellij => { - let space_below = screen_size.height.saturating_sub(area.bottom()); - let shift_down = wrapped_lines.min(space_below); - let scroll_up_amount = wrapped_lines.saturating_sub(shift_down); - - if scroll_up_amount > 0 { - // Scroll the entire screen up by emitting \n at the bottom - queue!( - writer, - MoveTo(/*x*/ 0, screen_size.height.saturating_sub(1)) - )?; - for _ in 0..scroll_up_amount { - queue!(writer, Print("\n"))?; - } - } - - if shift_down > 0 { - area.y += shift_down; - should_update_area = true; - } - - let cursor_top = area.top().saturating_sub(scroll_up_amount + shift_down); - queue!(writer, MoveTo(/*x*/ 0, cursor_top))?; - - for (i, line) in wrapped.iter().enumerate() { - if i > 0 { - queue!(writer, Print("\r\n"))?; - } - write_history_line(writer, line, wrap_width)?; - } + let top_1based = area.top() + 1; + queue!(writer, SetScrollRegion(top_1based..screen_size.height))?; + queue!(writer, MoveTo(/*x*/ 0, area.top()))?; + for _ in 0..scroll_amount { + queue!(writer, Print("\x1bM"))?; } - InsertHistoryMode::Standard => { - let cursor_top = if area.bottom() < screen_size.height { - let scroll_amount = wrapped_lines.min(screen_size.height - area.bottom()); + queue!(writer, ResetScrollRegion)?; - let top_1based = area.top() + 1; - queue!(writer, SetScrollRegion(top_1based..screen_size.height))?; - queue!(writer, MoveTo(/*x*/ 0, area.top()))?; - for _ in 0..scroll_amount { - queue!(writer, Print("\x1bM"))?; - } - queue!(writer, ResetScrollRegion)?; + let cursor_top = area.top().saturating_sub(1); + area.y += scroll_amount; + should_update_area = true; + cursor_top + } else { + area.top().saturating_sub(1) + }; - let cursor_top = area.top().saturating_sub(1); - area.y += scroll_amount; - should_update_area = true; - cursor_top - } else { - area.top().saturating_sub(1) - }; + // Limit the scroll region to the lines from the top of the screen to the + // top of the viewport. With this in place, when we add lines inside this + // area, only the lines in this area will be scrolled. We place the cursor + // at the end of the scroll region, and add lines starting there. + // + // ┌─Screen───────────────────────┐ + // │┌╌Scroll region╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐│ + // │┆ ┆│ + // │┆ ┆│ + // │┆ ┆│ + // │█╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘│ + // │╭─Viewport───────────────────╮│ + // ││ ││ + // │╰────────────────────────────╯│ + // └──────────────────────────────┘ + queue!(writer, SetScrollRegion(1..area.top()))?; - // Limit the scroll region to the lines from the top of the screen to the - // top of the viewport. With this in place, when we add lines inside this - // area, only the lines in this area will be scrolled. We place the cursor - // at the end of the scroll region, and add lines starting there. - // - // ┌─Screen───────────────────────┐ - // │┌╌Scroll region╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐│ - // │┆ ┆│ - // │┆ ┆│ - // │┆ ┆│ - // │█╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘│ - // │╭─Viewport───────────────────╮│ - // ││ ││ - // │╰────────────────────────────╯│ - // └──────────────────────────────┘ - queue!(writer, SetScrollRegion(1..area.top()))?; + // NB: we are using MoveTo instead of set_cursor_position here to avoid messing with the + // terminal's last_known_cursor_position, which hopefully will still be accurate after we + // fetch/restore the cursor position. insert_history_lines should be cursor-position-neutral :) + queue!(writer, MoveTo(/*x*/ 0, cursor_top))?; - // NB: we are using MoveTo instead of set_cursor_position here to avoid messing with the - // terminal's last_known_cursor_position, which hopefully will still be accurate after we - // fetch/restore the cursor position. insert_history_lines should be cursor-position-neutral :) - queue!(writer, MoveTo(/*x*/ 0, cursor_top))?; - - for line in &wrapped { - queue!(writer, Print("\r\n"))?; - write_history_line(writer, line, wrap_width)?; - } - - queue!(writer, ResetScrollRegion)?; - } + for line in &wrapped { + queue!(writer, Print("\r\n"))?; + write_history_line(writer, line, wrap_width)?; } + queue!(writer, ResetScrollRegion)?; + // Restore the cursor position to where it was before we started. queue!(writer, MoveTo(last_cursor_pos.x, last_cursor_pos.y))?; @@ -864,10 +781,9 @@ mod tests { let line = Line::from("alpha beta gamma delta epsilon zeta"); - insert_history_lines_with_mode_and_wrap_policy( + insert_history_lines_with_wrap_policy( &mut term, vec![line], - InsertHistoryMode::Standard, HistoryLineWrapPolicy::Terminal, ) .expect("insert raw history"); @@ -954,32 +870,4 @@ mod tests { "expected URL content to appear immediately after prompt (allowing at most one spacer row), got prompt_row={prompt_row}, url_row={url_row}, rows={rows:?}", ); } - - #[test] - fn vt100_zellij_mode_inserts_history_and_updates_viewport() { - let width: u16 = 32; - let height: u16 = 8; - let backend = VT100Backend::new(width, height); - let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); - let viewport = Rect::new(/*x*/ 0, /*y*/ 4, width, /*height*/ 2); - term.set_viewport_area(viewport); - - let line: Line<'static> = Line::from("zellij history"); - insert_history_lines_with_mode(&mut term, vec![line], InsertHistoryMode::Zellij) - .expect("insert zellij history"); - - let start_row = 0; - let rows: Vec = term - .backend() - .vt100() - .screen() - .rows(start_row, width) - .collect(); - assert!( - rows.iter().any(|row| row.contains("zellij history")), - "expected zellij history row in screen output, rows: {rows:?}" - ); - assert_eq!(term.viewport_area, Rect::new(0, 5, width, 2)); - assert_eq!(term.visible_history_rows(), 1); - } } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index b86c92dfa4..97c7d023f5 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -53,7 +53,6 @@ use codex_protocol::config_types::WindowsSandboxLevel; use codex_rollout::StateDbHandle; use codex_rollout::state_db; use codex_state::log_db; -use codex_terminal_detection::terminal_info; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_absolute_path::canonicalize_existing_preserving_symlinks; use codex_utils_oss::ensure_oss_provider_ready; @@ -1655,36 +1654,17 @@ impl Drop for TerminalRestoreGuard { /// Determine whether to use the terminal's alternate screen buffer. /// -/// The alternate screen buffer provides a cleaner fullscreen experience without polluting -/// the terminal's scrollback history. However, it conflicts with terminal multiplexers like -/// Zellij that strictly follow the xterm spec, which disallows scrollback in alternate screen -/// buffers. Zellij intentionally disables scrollback in alternate screen mode (see -/// https://github.com/zellij-org/zellij/pull/1032) and offers no configuration option to -/// change this behavior. -/// -/// This function implements a pragmatic workaround: /// - If `--no-alt-screen` is explicitly passed, always disable alternate screen /// - Otherwise, respect the `tui.alternate_screen` config setting: -/// - `always`: Use alternate screen everywhere (original behavior) +/// - `always`: Use alternate screen /// - `never`: Inline mode only, preserves scrollback -/// - `auto` (default): Auto-detect the terminal multiplexer and disable alternate screen -/// only in Zellij, enabling it everywhere else +/// - `auto` (default): Use alternate screen fn determine_alt_screen_mode(no_alt_screen: bool, tui_alternate_screen: AltScreenMode) -> bool { if no_alt_screen { - false - } else { - match tui_alternate_screen { - AltScreenMode::Always => true, - AltScreenMode::Never => false, - AltScreenMode::Auto => { - let terminal_info = terminal_info(); - !matches!( - terminal_info.multiplexer, - Some(codex_terminal_detection::Multiplexer::Zellij {}) - ) - } - } + return false; } + + tui_alternate_screen != AltScreenMode::Never } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1817,6 +1797,26 @@ mod tests { .await } + #[test] + fn alternate_screen_auto_uses_alt_screen() { + assert!(determine_alt_screen_mode( + /*no_alt_screen*/ false, + AltScreenMode::Auto, + )); + assert!(determine_alt_screen_mode( + /*no_alt_screen*/ false, + AltScreenMode::Always, + )); + assert!(!determine_alt_screen_mode( + /*no_alt_screen*/ false, + AltScreenMode::Never, + )); + assert!(!determine_alt_screen_mode( + /*no_alt_screen*/ true, + AltScreenMode::Auto, + )); + } + #[test] fn session_target_display_label_falls_back_to_thread_id() { let thread_id = ThreadId::new(); diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 9255d188c4..2d22e161fa 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -33,7 +33,6 @@ use ratatui::crossterm::terminal::enable_raw_mode; use ratatui::layout::Offset; use ratatui::layout::Position; use ratatui::layout::Rect; -use ratatui::layout::Size; use ratatui::text::Line; use tokio::sync::broadcast; use tokio_stream::Stream; @@ -440,8 +439,7 @@ pub struct Tui { enhanced_keys_supported: bool, notification_backend: Option, notification_condition: NotificationCondition, - is_zellij: bool, - // When false, enter_alt_screen() becomes a no-op (for Zellij scrollback support) + // When false, enter_alt_screen() becomes a no-op. alt_screen_enabled: bool, } @@ -474,10 +472,6 @@ impl Tui { // Cache this to avoid contention with the event reader. supports_color::on_cached(supports_color::Stream::Stdout); let _ = crate::terminal_palette::default_colors(); - let is_zellij = matches!( - codex_terminal_detection::terminal_info().multiplexer, - Some(codex_terminal_detection::Multiplexer::Zellij {}) - ); Self { frame_requester, @@ -495,7 +489,6 @@ impl Tui { enhanced_keys_supported, notification_backend: Some(detect_backend(NotificationMethod::default())), notification_condition: NotificationCondition::default(), - is_zellij, alt_screen_enabled: true, } } @@ -687,62 +680,6 @@ impl Tui { self.pending_history_lines.clear(); } - /// Resize the inline viewport to `height` rows, scrolling content above it if - /// the viewport would extend past the bottom of the screen. Returns `true` when - /// the caller must invalidate the diff buffer (Zellij mode), because the scroll - /// was performed with raw newlines that ratatui cannot track. - fn update_inline_viewport( - terminal: &mut Terminal, - height: u16, - is_zellij: bool, - ) -> Result { - let size = terminal.size()?; - let mut needs_full_repaint = false; - - let mut area = terminal.viewport_area; - area.height = height.min(size.height); - area.width = size.width; - if area.bottom() > size.height { - let scroll_by = area.bottom() - size.height; - if is_zellij { - Self::scroll_zellij_expanded_viewport(terminal, size, scroll_by)?; - needs_full_repaint = true; - } else { - terminal - .backend_mut() - .scroll_region_up(0..area.top(), scroll_by)?; - } - area.y = size.height - area.height; - } - if area != terminal.viewport_area { - // On startup, the old viewport can still be empty. Clear from the - // new viewport top so stale shell cells do not show through spaces. - clear_for_viewport_change(terminal, area)?; - terminal.set_viewport_area(area); - } - - Ok(needs_full_repaint) - } - - /// Push content above the viewport upward by `scroll_by` rows using raw - /// newlines at the screen bottom. This is the Zellij-safe alternative to - /// `scroll_region_up`, which relies on DECSTBM sequences Zellij does not - /// support. - fn scroll_zellij_expanded_viewport( - terminal: &mut Terminal, - size: Size, - scroll_by: u16, - ) -> Result<()> { - crossterm::queue!( - terminal.backend_mut(), - crossterm::cursor::MoveTo(0, size.height.saturating_sub(1)) - )?; - for _ in 0..scroll_by { - crossterm::queue!(terminal.backend_mut(), crossterm::style::Print("\n"))?; - } - Ok(()) - } - /// Resize the inline viewport for the resize-reflow path. /// /// Unlike the legacy draw path, this path does not scroll rows above the viewport when the @@ -751,7 +688,6 @@ impl Tui { fn update_inline_viewport_for_resize_reflow( terminal: &mut Terminal, height: u16, - is_zellij: bool, ) -> Result { let size = terminal.size()?; let terminal_height_shrank = size.height < terminal.last_known_screen_size.height; @@ -768,13 +704,9 @@ impl Tui { if area.bottom() > size.height { let scroll_by = area.bottom() - size.height; if !terminal_height_shrank { - if is_zellij { - Self::scroll_zellij_expanded_viewport(terminal, size, scroll_by)?; - } else { - terminal - .backend_mut() - .scroll_region_up(0..area.top(), scroll_by)?; - } + terminal + .backend_mut() + .scroll_region_up(0..area.top(), scroll_by)?; } area.y = size.height - area.height; } else if terminal_height_grew && viewport_was_bottom_aligned { @@ -792,27 +724,23 @@ impl Tui { } /// Write any buffered history lines above the viewport and clear the buffer. - /// Returns `true` when Zellij mode was used, signaling that the caller must - /// invalidate the diff buffer for a full repaint. fn flush_pending_history_lines( terminal: &mut Terminal, pending_history_lines: &mut Vec, - is_zellij: bool, - ) -> Result { + ) -> Result<()> { if pending_history_lines.is_empty() { - return Ok(false); + return Ok(()); } for batch in pending_history_lines.iter() { - crate::insert_history::insert_history_lines_with_mode_and_wrap_policy( + crate::insert_history::insert_history_lines_with_wrap_policy( terminal, batch.lines.clone(), - crate::insert_history::InsertHistoryMode::new(is_zellij), batch.wrap_policy, )?; } pending_history_lines.clear(); - Ok(is_zellij) + Ok(()) } pub fn draw( @@ -843,17 +771,26 @@ impl Tui { terminal.clear()?; } - let mut needs_full_repaint = - Self::update_inline_viewport(terminal, height, self.is_zellij)?; - needs_full_repaint |= Self::flush_pending_history_lines( - terminal, - &mut self.pending_history_lines, - self.is_zellij, - )?; + let size = terminal.size()?; - if needs_full_repaint { - terminal.invalidate_viewport(); + let mut area = terminal.viewport_area; + area.height = height.min(size.height); + area.width = size.width; + // If the viewport has expanded, scroll everything else up to make room. + if area.bottom() > size.height { + terminal + .backend_mut() + .scroll_region_up(0..area.top(), area.bottom() - size.height)?; + area.y = size.height - area.height; } + if area != terminal.viewport_area { + // On startup, the old viewport can still be empty. Clear from the + // new viewport top so stale shell cells do not show through spaces. + clear_for_viewport_change(terminal, area)?; + terminal.set_viewport_area(area); + } + + Self::flush_pending_history_lines(terminal, &mut self.pending_history_lines)?; // Update the y position for suspending so Ctrl-Z can place the cursor correctly. #[cfg(unix)] @@ -943,14 +880,9 @@ impl Tui { } let terminal = &mut self.terminal; - let mut needs_full_repaint = - Self::update_inline_viewport_for_resize_reflow(terminal, height, self.is_zellij)?; - let flushed_history = Self::flush_pending_history_lines( - terminal, - &mut self.pending_history_lines, - self.is_zellij, - )?; - needs_full_repaint |= flushed_history; + let needs_full_repaint = + Self::update_inline_viewport_for_resize_reflow(terminal, height)?; + Self::flush_pending_history_lines(terminal, &mut self.pending_history_lines)?; if needs_full_repaint { terminal.invalidate_viewport(); From 87de4e32903610b8ab66d1bda1d491936b8b0973 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 13 May 2026 18:11:50 +0300 Subject: [PATCH 07/13] Add service tier overrides to spawned agents (#22139) ## Why Spawned agents can already override `model` and `reasoning_effort`, but they have no equivalent way to opt into a model-supported service tier. That makes it impossible to preserve or intentionally select tiered execution behavior when delegating work to a sub-agent, even though the model catalog already advertises supported `service_tiers`. ## What changed - Add optional `service_tier` to both legacy and `MultiAgentV2` `spawn_agent` tool inputs. - Show each picker-visible model's supported service tier ids and descriptions in the `spawn_agent` tool guidance. - Resolve service tier selection after the child agent's effective model is known. - Inherit the parent tier when omitted and still supported by the final child model; otherwise clear it. - Reject explicit unsupported tier requests with a model-facing error. - Keep explicit `service_tier` usable on full-history forks, while still honoring the existing model/reasoning fork restrictions. - Hide `service_tier` alongside other spawn metadata when `hide_spawn_agent_metadata` is enabled. ## Verification Added focused coverage for: - v1/v2 `spawn_agent` schema exposure for `service_tier` - tier descriptions in spawn guidance - hidden-metadata suppression - explicit supported tier selection - explicit unknown and unsupported tier rejection - inherited tier preservation or clearing based on child-model support - full-history fork acceptance for explicit service tiers in both v1 and v2 Local Rust tests were not run in this workspace per repo guidance; the new coverage is included for CI. --- .../src/tools/handlers/multi_agents/spawn.rs | 8 + .../src/tools/handlers/multi_agents_common.rs | 45 +++ .../src/tools/handlers/multi_agents_spec.rs | 29 +- .../tools/handlers/multi_agents_spec_tests.rs | 48 ++- .../src/tools/handlers/multi_agents_tests.rs | 368 ++++++++++++++++++ .../tools/handlers/multi_agents_v2/spawn.rs | 8 + .../tests/suite/spawn_agent_description.rs | 15 +- 7 files changed, 517 insertions(+), 4 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs index 8f9c93edb7..395e74f137 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs @@ -99,6 +99,13 @@ async fn handle_spawn_agent( .await .map_err(FunctionCallError::RespondToModel)?; } + apply_spawn_agent_service_tier( + &session, + &mut config, + turn.config.service_tier.as_deref(), + args.service_tier.as_deref(), + ) + .await?; apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?; apply_spawn_agent_overrides(&mut config, child_depth); @@ -206,6 +213,7 @@ struct SpawnAgentArgs { agent_type: Option, model: Option, reasoning_effort: Option, + service_tier: Option, #[serde(default)] fork_context: bool, } diff --git a/codex-rs/core/src/tools/handlers/multi_agents_common.rs b/codex-rs/core/src/tools/handlers/multi_agents_common.rs index c01755cb2b..cc4e9ebfca 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_common.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_common.rs @@ -336,6 +336,51 @@ pub(crate) async fn apply_requested_spawn_agent_model_overrides( Ok(()) } +pub(crate) async fn apply_spawn_agent_service_tier( + session: &Session, + config: &mut Config, + parent_service_tier: Option<&str>, + requested_service_tier: Option<&str>, +) -> Result<(), FunctionCallError> { + let Some(candidate_service_tier) = requested_service_tier.or(parent_service_tier) else { + return Ok(()); + }; + let model = config.model.clone().ok_or_else(|| { + FunctionCallError::RespondToModel( + "spawn_agent could not resolve the child model for service tier validation".to_string(), + ) + })?; + let model_info = session + .services + .models_manager + .get_model_info(model.as_str(), &config.to_models_manager_config()) + .await; + + if model_info.supports_service_tier(candidate_service_tier) { + config.service_tier = Some(candidate_service_tier.to_string()); + return Ok(()); + } + + if requested_service_tier.is_none() { + config.service_tier = None; + return Ok(()); + } + + let supported_service_tiers = if model_info.service_tiers.is_empty() { + "none".to_string() + } else { + model_info + .service_tiers + .iter() + .map(|tier| tier.id.as_str()) + .collect::>() + .join(", ") + }; + Err(FunctionCallError::RespondToModel(format!( + "Service tier `{candidate_service_tier}` is not supported for model `{model}`. Supported service tiers: {supported_service_tiers}" + ))) +} + fn find_spawn_agent_model_name( available_models: &[codex_protocol::openai_models::ModelPreset], requested_model: &str, diff --git a/codex-rs/core/src/tools/handlers/multi_agents_spec.rs b/codex-rs/core/src/tools/handlers/multi_agents_spec.rs index 233491efa4..111ab67798 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_spec.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_spec.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; const SPAWN_AGENT_INHERITED_MODEL_GUIDANCE: &str = "Spawned agents inherit your current model by default. Omit `model` to use that preferred default; set `model` only when an explicit override is needed."; const SPAWN_AGENT_MODEL_OVERRIDE_DESCRIPTION: &str = "Optional model override for the new agent. Leave unset to inherit the same model as the parent, which is the preferred default. Only set this when the user explicitly asks for a different model or the task clearly requires one."; +const SPAWN_AGENT_SERVICE_TIER_OVERRIDE_DESCRIPTION: &str = "Optional service tier override for the new agent. Leave unset unless the user explicitly asks for one."; #[derive(Debug, Clone, Default)] pub struct SpawnAgentToolOptions { @@ -545,6 +546,12 @@ fn spawn_agent_common_properties_v1(agent_type_description: &str) -> BTreeMap BTreeMap String { .map(|preset| format!("{} ({})", preset.effort, preset.description)) .collect::>() .join(", "); + let service_tiers = if model.service_tiers.is_empty() { + "none".to_string() + } else { + model + .service_tiers + .iter() + .map(|tier| format!("{} ({}: {})", tier.id, tier.name, tier.description)) + .collect::>() + .join(", ") + }; format!( - "- {} (`{}`): {} Default reasoning effort: {}. Supported reasoning efforts: {}.", + "- {} (`{}`): {} Default reasoning effort: {}. Supported reasoning efforts: {}. Supported service tiers: {}.", model.display_name, model.model, model.description, model.default_reasoning_effort, - efforts + efforts, + service_tiers ) }) .collect::>() diff --git a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs index c8fa1a0f90..aaa29d6d4c 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs @@ -1,5 +1,6 @@ use super::*; use codex_protocol::openai_models::ModelPreset; +use codex_protocol::openai_models::ModelServiceTier; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_tools::JsonSchemaPrimitiveType; @@ -20,7 +21,11 @@ fn model_preset(id: &str, show_in_picker: bool) -> ModelPreset { }], supports_personality: false, additional_speed_tiers: Vec::new(), - service_tiers: Vec::new(), + service_tiers: vec![ModelServiceTier { + id: "priority".to_string(), + name: "Fast".to_string(), + description: "1.5x speed, increased usage".to_string(), + }], is_default: false, upgrade: None, show_in_picker, @@ -70,6 +75,10 @@ fn spawn_agent_tool_v2_requires_task_name_and_lists_visible_models() { .contains("Available model overrides (optional; inherited parent model is preferred):") ); assert!(description.contains("visible display (`visible-model`)")); + assert!( + description + .contains("Supported service tiers: priority (Fast: 1.5x speed, increased usage).") + ); assert!(!description.contains("hidden display (`hidden-model`)")); assert!(properties.contains_key("task_name")); assert!(properties.contains_key("message")); @@ -86,6 +95,12 @@ fn spawn_agent_tool_v2_requires_task_name_and_lists_visible_models() { .and_then(|schema| schema.description.as_deref()), Some(SPAWN_AGENT_MODEL_OVERRIDE_DESCRIPTION) ); + assert_eq!( + properties + .get("service_tier") + .and_then(|schema| schema.description.as_deref()), + Some(SPAWN_AGENT_SERVICE_TIER_OVERRIDE_DESCRIPTION) + ); assert_eq!( parameters.required.as_ref(), Some(&vec!["task_name".to_string(), "message".to_string()]) @@ -127,6 +142,37 @@ fn spawn_agent_tool_v1_keeps_legacy_fork_context_field() { .and_then(|schema| schema.description.as_deref()), Some(SPAWN_AGENT_MODEL_OVERRIDE_DESCRIPTION) ); + assert_eq!( + properties + .get("service_tier") + .and_then(|schema| schema.description.as_deref()), + Some(SPAWN_AGENT_SERVICE_TIER_OVERRIDE_DESCRIPTION) + ); +} + +#[test] +fn spawn_agent_tool_hides_service_tier_with_spawn_metadata() { + let tool = create_spawn_agent_tool_v2(SpawnAgentToolOptions { + available_models: vec![model_preset("visible", /*show_in_picker*/ true)], + agent_type_description: "role help".to_string(), + hide_agent_type_model_reasoning: true, + include_usage_hint: true, + usage_hint_text: None, + max_concurrent_threads_per_session: Some(4), + }); + + let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = tool else { + panic!("spawn_agent should be a function tool"); + }; + let properties = parameters + .properties + .as_ref() + .expect("spawn_agent should use object params"); + + assert!(!properties.contains_key("agent_type")); + assert!(!properties.contains_key("model")); + assert!(!properties.contains_key("reasoning_effort")); + assert!(!properties.contains_key("service_tier")); } #[test] diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index d1360186a0..f051fb0f70 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -23,6 +23,7 @@ use codex_model_provider::create_model_provider; use codex_model_provider_info::built_in_model_providers; use codex_protocol::AgentPath; use codex_protocol::ThreadId; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::ShellEnvironmentPolicy; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; @@ -444,6 +445,373 @@ async fn multi_agent_v2_spawn_defaults_to_full_fork_and_rejects_child_model_over ); } +#[tokio::test] +async fn spawn_agent_service_tier_override_validates_the_effective_child_model() { + #[derive(Debug, Deserialize)] + struct SpawnAgentResult { + agent_id: String, + } + + { + let (mut session, turn) = make_session_and_context().await; + let manager = thread_manager(); + let root = manager + .start_thread((*turn.config).clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.conversation_id = root.thread_id; + + let output = SpawnAgentHandler::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "model": "gpt-5.4", + "service_tier": ServiceTier::Fast.request_value() + })), + )) + .await + .expect("spawn_agent should accept a supported explicit service tier"); + let (content, _) = expect_text_output(output); + let result: SpawnAgentResult = + serde_json::from_str(&content).expect("spawn_agent result should be json"); + let snapshot = manager + .get_thread(parse_agent_id(&result.agent_id)) + .await + .expect("spawned agent thread should exist") + .config_snapshot() + .await; + + assert_eq!( + snapshot.service_tier, + Some(ServiceTier::Fast.request_value().to_string()) + ); + } + + { + let (session, turn) = make_session_and_context().await; + let err = SpawnAgentHandler::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "model": "gpt-5.4", + "service_tier": "turbo" + })), + )) + .await + .expect_err("unknown service tier should be rejected"); + + assert_eq!( + err, + FunctionCallError::RespondToModel( + "Service tier `turbo` is not supported for model `gpt-5.4`. Supported service tiers: priority" + .to_string() + ) + ); + } + + { + let (session, turn) = make_session_and_context().await; + let err = SpawnAgentHandler::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "model": "gpt-5.3-codex", + "service_tier": ServiceTier::Fast.request_value() + })), + )) + .await + .expect_err("tier unsupported by the final child model should be rejected"); + + assert_eq!( + err, + FunctionCallError::RespondToModel( + "Service tier `priority` is not supported for model `gpt-5.3-codex`. Supported service tiers: none" + .to_string() + ) + ); + } +} + +#[tokio::test] +async fn spawn_agent_service_tier_inheritance_preserves_supported_or_configured_tiers() { + #[derive(Debug, Deserialize)] + struct SpawnAgentResult { + agent_id: String, + } + + { + let (mut session, turn) = make_session_and_context().await; + let mut turn = turn + .with_model("gpt-5.4".to_string(), &session.services.models_manager) + .await; + let mut config = (*turn.config).clone(); + config.service_tier = Some(ServiceTier::Fast.request_value().to_string()); + turn.config = Arc::new(config); + let manager = thread_manager(); + let root = manager + .start_thread((*turn.config).clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.conversation_id = root.thread_id; + + let output = SpawnAgentHandler::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({"message": "inspect this repo"})), + )) + .await + .expect("spawn_agent should inherit a supported parent service tier"); + let (content, _) = expect_text_output(output); + let result: SpawnAgentResult = + serde_json::from_str(&content).expect("spawn_agent result should be json"); + let snapshot = manager + .get_thread(parse_agent_id(&result.agent_id)) + .await + .expect("spawned agent thread should exist") + .config_snapshot() + .await; + + assert_eq!( + snapshot.service_tier, + Some(ServiceTier::Fast.request_value().to_string()) + ); + } + + { + let (mut session, turn) = make_session_and_context().await; + let mut turn = turn + .with_model("gpt-5.4".to_string(), &session.services.models_manager) + .await; + let mut config = (*turn.config).clone(); + config.service_tier = Some(ServiceTier::Fast.request_value().to_string()); + turn.config = Arc::new(config); + let manager = thread_manager(); + let root = manager + .start_thread((*turn.config).clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.conversation_id = root.thread_id; + + let output = SpawnAgentHandler::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "model": "gpt-5.3-codex" + })), + )) + .await + .expect("spawn_agent should clear unsupported inherited service tier"); + let (content, _) = expect_text_output(output); + let result: SpawnAgentResult = + serde_json::from_str(&content).expect("spawn_agent result should be json"); + let snapshot = manager + .get_thread(parse_agent_id(&result.agent_id)) + .await + .expect("spawned agent thread should exist") + .config_snapshot() + .await; + + assert_eq!(snapshot.service_tier, None); + } + + { + let (mut session, mut turn) = make_session_and_context().await; + tokio::fs::create_dir_all(&turn.config.codex_home) + .await + .expect("codex home should be created"); + let role_config_path = turn + .config + .codex_home + .as_path() + .join("service-tier-role.toml"); + tokio::fs::write( + &role_config_path, + r#"model = "gpt-5.4" +service_tier = "priority" +"#, + ) + .await + .expect("role config should be written"); + + let role_name = "service-tier-role".to_string(); + let mut config = (*turn.config).clone(); + config.agent_roles.insert( + role_name.clone(), + AgentRoleConfig { + description: Some("Role with a child service tier".to_string()), + config_file: Some(role_config_path), + nickname_candidates: None, + }, + ); + turn.config = Arc::new(config); + let manager = thread_manager(); + let root = manager + .start_thread((*turn.config).clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.conversation_id = root.thread_id; + + let output = SpawnAgentHandler::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "agent_type": role_name + })), + )) + .await + .expect("spawn_agent should preserve the child role service tier"); + let (content, _) = expect_text_output(output); + let result: SpawnAgentResult = + serde_json::from_str(&content).expect("spawn_agent result should be json"); + let snapshot = manager + .get_thread(parse_agent_id(&result.agent_id)) + .await + .expect("spawned agent thread should exist") + .config_snapshot() + .await; + + assert_eq!( + snapshot.service_tier, + Some(ServiceTier::Fast.request_value().to_string()) + ); + } +} + +#[tokio::test] +async fn spawn_agent_full_history_fork_accepts_explicit_service_tier() { + #[derive(Debug, Deserialize)] + struct SpawnAgentResult { + agent_id: String, + } + + let (mut session, turn) = make_session_and_context().await; + let turn = turn + .with_model("gpt-5.4".to_string(), &session.services.models_manager) + .await; + let manager = thread_manager(); + let root = manager + .start_thread((*turn.config).clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.conversation_id = root.thread_id; + + let output = SpawnAgentHandler::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "fork_context": true, + "service_tier": ServiceTier::Fast.request_value() + })), + )) + .await + .expect("full-history fork should accept explicit service tier"); + let (content, _) = expect_text_output(output); + let result: SpawnAgentResult = + serde_json::from_str(&content).expect("spawn_agent result should be json"); + let snapshot = manager + .get_thread(parse_agent_id(&result.agent_id)) + .await + .expect("spawned agent thread should exist") + .config_snapshot() + .await; + + assert_eq!( + snapshot.service_tier, + Some(ServiceTier::Fast.request_value().to_string()) + ); +} + +#[tokio::test] +async fn multi_agent_v2_full_history_fork_accepts_explicit_service_tier() { + #[derive(Debug, Deserialize)] + struct SpawnAgentResult { + task_name: String, + } + + let (mut session, turn) = make_session_and_context().await; + let mut turn = turn + .with_model("gpt-5.4".to_string(), &session.services.models_manager) + .await; + let mut config = (*turn.config).clone(); + config + .features + .enable(Feature::MultiAgentV2) + .expect("test config should allow feature update"); + turn.config = Arc::new(config); + let manager = thread_manager(); + let root = manager + .start_thread((*turn.config).clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.conversation_id = root.thread_id; + let session = Arc::new(session); + let turn = Arc::new(turn); + + let output = SpawnAgentHandlerV2::default() + .handle(invocation( + session.clone(), + turn.clone(), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "task_name": "fork_with_tier", + "service_tier": ServiceTier::Fast.request_value() + })), + )) + .await + .expect("multi-agent v2 full-history fork should accept explicit service tier"); + let (content, _) = expect_text_output(output); + let result: SpawnAgentResult = + serde_json::from_str(&content).expect("spawn_agent result should be json"); + let child_thread_id = session + .services + .agent_control + .resolve_agent_reference( + session.conversation_id, + &turn.session_source, + result.task_name.as_str(), + ) + .await + .expect("spawned task name should resolve"); + let snapshot = manager + .get_thread(child_thread_id) + .await + .expect("spawned agent thread should exist") + .config_snapshot() + .await; + + assert_eq!( + snapshot.service_tier, + Some(ServiceTier::Fast.request_value().to_string()) + ); +} + #[tokio::test] async fn multi_agent_v2_spawn_partial_fork_turns_allows_agent_type_override() { let (mut session, mut turn) = make_session_and_context().await; diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index a849bcd971..1ab59cc3fe 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -98,6 +98,13 @@ async fn handle_spawn_agent( .await .map_err(FunctionCallError::RespondToModel)?; } + apply_spawn_agent_service_tier( + &session, + &mut config, + turn.config.service_tier.as_deref(), + args.service_tier.as_deref(), + ) + .await?; apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?; apply_spawn_agent_overrides(&mut config, child_depth); @@ -238,6 +245,7 @@ struct SpawnAgentArgs { agent_type: Option, model: Option, reasoning_effort: Option, + service_tier: Option, fork_turns: Option, fork_context: Option, } diff --git a/codex-rs/core/tests/suite/spawn_agent_description.rs b/codex-rs/core/tests/suite/spawn_agent_description.rs index cc5a9952e3..5aab77cd7d 100644 --- a/codex-rs/core/tests/suite/spawn_agent_description.rs +++ b/codex-rs/core/tests/suite/spawn_agent_description.rs @@ -9,6 +9,7 @@ use codex_models_manager::manager::SharedModelsManager; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; +use codex_protocol::openai_models::ModelServiceTier; use codex_protocol::openai_models::ModelVisibility; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; @@ -52,6 +53,7 @@ fn test_model_info( visibility: ModelVisibility, default_reasoning_level: ReasoningEffort, supported_reasoning_levels: Vec, + service_tiers: Vec, ) -> ModelInfo { ModelInfo { slug: slug.to_string(), @@ -67,7 +69,7 @@ fn test_model_info( supports_search_tool: false, priority: 1, additional_speed_tiers: Vec::new(), - service_tiers: Vec::new(), + service_tiers, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, @@ -126,6 +128,11 @@ async fn spawn_agent_description_lists_visible_models_and_reasoning_efforts() -> description: "Deep dive".to_string(), }, ], + vec![ModelServiceTier { + id: "priority".to_string(), + name: "Fast".to_string(), + description: "1.5x speed, increased usage".to_string(), + }], ), test_model_info( "hidden-model", @@ -137,6 +144,7 @@ async fn spawn_agent_description_lists_visible_models_and_reasoning_efforts() -> effort: ReasoningEffort::Low, description: "Not visible".to_string(), }], + Vec::new(), ), ], }, @@ -195,6 +203,11 @@ async fn spawn_agent_description_lists_visible_models_and_reasoning_efforts() -> description.contains("low (Quick scan), high (Deep dive)."), "expected reasoning efforts in spawn_agent description: {description:?}" ); + assert!( + description + .contains("Supported service tiers: priority (Fast: 1.5x speed, increased usage)."), + "expected service tier guidance in spawn_agent description: {description:?}" + ); assert!( !description.contains("Hidden Model"), "hidden picker model should be omitted from spawn_agent description: {description:?}" From 34bb85519fee54faef578e0d4eb26a332f564701 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 17:13:34 +0200 Subject: [PATCH 08/13] feat: add config-change extension contributor (#22488) ## Why Extensions can observe thread and turn lifecycle events today, but there was no single host-owned hook for changes to the effective thread configuration. That makes features that need to react to model, permission, or tool-suggest updates either depend on individual mutation paths or risk going stale after runtime config refreshes. This adds a typed config-change contributor so extension-owned state can stay synchronized with the effective thread config while the host remains responsible for deciding when config changed. ## What Changed - Added `ConfigContributor` to `codex_extension_api`, with before/after immutable snapshots of the effective config plus session/thread extension stores. - Added registry builder/accessor support through `config_contributor` and `config_contributors`. - Emits config-change callbacks after committed updates from session settings, per-turn setting updates, and `refresh_runtime_config`. - Builds effective config snapshots only when config contributors are registered, and suppresses no-op callbacks when the before/after snapshots are equal. - Added a core session regression test that verifies contributors observe both model changes and user-layer runtime config changes, including access to session and thread extension stores. ## Validation Added `config_change_contributor_observes_effective_config_changes` in `codex-rs/core/src/session/tests.rs` to cover the new contributor path. --- codex-rs/core/src/session/mod.rs | 50 ++++++- codex-rs/core/src/session/tests.rs | 132 ++++++++++++++++++ codex-rs/core/src/session/turn_context.rs | 23 +++ .../ext/extension-api/src/contributors.rs | 17 +++ codex-rs/ext/extension-api/src/lib.rs | 1 + codex-rs/ext/extension-api/src/registry.rs | 15 ++ 6 files changed, 235 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index a1d598bff7..b40f289dc0 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -1317,7 +1317,16 @@ impl Session { &self, updates: SessionSettingsUpdate, ) -> ConstraintResult<()> { - let (previous_cwd, permission_profile_changed, next_cwd, codex_home, session_source) = { + let notify_config_contributors = !self.services.extensions.config_contributors().is_empty(); + let ( + previous_config, + new_config, + previous_cwd, + permission_profile_changed, + next_cwd, + codex_home, + session_source, + ) = { let mut state = self.state.lock().await; let updated = match state.session_configuration.apply(&updates) { Ok(updated) => updated, @@ -1327,6 +1336,10 @@ impl Session { } }; + let previous_config = notify_config_contributors + .then(|| Self::build_effective_session_config(&state.session_configuration)); + let new_config = + notify_config_contributors.then(|| Self::build_effective_session_config(&updated)); let previous_cwd = state.session_configuration.cwd.clone(); let previous_permission_profile = state.session_configuration.permission_profile(); let updated_permission_profile = updated.permission_profile(); @@ -1337,6 +1350,8 @@ impl Session { let session_source = updated.session_source.clone(); state.session_configuration = updated; ( + previous_config, + new_config, previous_cwd, permission_profile_changed, next_cwd, @@ -1345,6 +1360,7 @@ impl Session { ) }; + self.emit_config_changed_contributors(previous_config.as_ref(), new_config.as_ref()); self.maybe_refresh_shell_snapshot_for_cwd( &previous_cwd, &next_cwd, @@ -1397,8 +1413,11 @@ impl Session { // Refresh only the user layer from the incoming snapshot. Preserve thread-local // layers such as request/session overrides that were present when this session // was created. - let config = { + let notify_config_contributors = !self.services.extensions.config_contributors().is_empty(); + let (previous_config, new_config, config) = { let mut state = self.state.lock().await; + let previous_config = notify_config_contributors + .then(|| Self::build_effective_session_config(&state.session_configuration)); let mut config = (*state.session_configuration.original_config_do_not_use).clone(); config.config_layer_stack = config .config_layer_stack @@ -1407,8 +1426,11 @@ impl Session { resolve_tool_suggest_config_from_layer_stack(&config.config_layer_stack); let config = Arc::new(config); state.session_configuration.original_config_do_not_use = Arc::clone(&config); - config + let new_config = notify_config_contributors + .then(|| Self::build_effective_session_config(&state.session_configuration)); + (previous_config, new_config, config) }; + self.emit_config_changed_contributors(previous_config.as_ref(), new_config.as_ref()); self.services.skills_manager.clear_cache(); self.services.plugins_manager.clear_cache(); let hooks = build_hooks_for_config( @@ -1429,6 +1451,28 @@ impl Session { } } + fn emit_config_changed_contributors( + &self, + previous_config: Option<&Config>, + new_config: Option<&Config>, + ) { + let (Some(previous_config), Some(new_config)) = (previous_config, new_config) else { + return; + }; + if previous_config == new_config { + return; + } + for contributor in self.services.extensions.config_contributors() { + contributor.on_config_changed( + &self.services.session_extension_data, + &self.services.thread_extension_data, + self.conversation_id, + previous_config, + new_config, + ); + } + } + pub(crate) async fn reload_user_config_layer(&self) { // Refresh layer-backed runtime state for an existing session, including enabled plugin, // skill, and hook state. Derived config fields such as feature gates and legacy notify diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 5a4bc2d0e7..2e9907e952 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1915,6 +1915,138 @@ async fn record_token_usage_info_notifies_extension_contributors() { assert_eq!(expected, actual); } +#[tokio::test] +async fn config_change_contributor_observes_effective_config_changes() { + struct SessionConfigMarker; + struct ThreadConfigMarker; + + #[derive(Debug, PartialEq)] + struct RecordedConfigChange { + thread_id: ThreadId, + previous_model: Option, + new_model: Option, + previous_disabled_tools: Vec, + new_disabled_tools: Vec, + saw_session_store: bool, + saw_thread_store: bool, + } + + struct ConfigRecorder { + records: Arc>>, + } + + impl codex_extension_api::ConfigContributor for ConfigRecorder { + fn on_config_changed( + &self, + session_store: &codex_extension_api::ExtensionData, + thread_store: &codex_extension_api::ExtensionData, + thread_id: ThreadId, + previous_config: &crate::config::Config, + new_config: &crate::config::Config, + ) { + self.records + .lock() + .expect("config change records lock") + .push(RecordedConfigChange { + thread_id, + previous_model: previous_config.model.clone(), + new_model: new_config.model.clone(), + previous_disabled_tools: previous_config.tool_suggest.disabled_tools.clone(), + new_disabled_tools: new_config.tool_suggest.disabled_tools.clone(), + saw_session_store: session_store.get::().is_some(), + saw_thread_store: thread_store.get::().is_some(), + }); + } + } + + let (mut session, _turn_context) = make_session_and_context().await; + let records = Arc::new(std::sync::Mutex::new(Vec::new())); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.config_contributor(Arc::new(ConfigRecorder { + records: Arc::clone(&records), + })); + session.services.extensions = Arc::new(builder.build()); + session + .services + .session_extension_data + .insert(SessionConfigMarker); + session + .services + .thread_extension_data + .insert(ThreadConfigMarker); + + let original_model = session.collaboration_mode().await.model().to_string(); + let original_disabled_tools = session + .get_config() + .await + .tool_suggest + .disabled_tools + .clone(); + let next_model = if original_model == "gpt-5.4" { + "gpt-5.2" + } else { + "gpt-5.4" + }; + let collaboration_mode = session.collaboration_mode().await.with_updates( + Some(next_model.to_string()), + /*effort*/ None, + /*developer_instructions*/ None, + ); + session + .update_settings(SessionSettingsUpdate { + collaboration_mode: Some(collaboration_mode), + ..Default::default() + }) + .await + .expect("update settings"); + + let codex_home = session.codex_home().await; + std::fs::create_dir_all(&codex_home).expect("create codex home"); + std::fs::write( + codex_home.join(CONFIG_TOML_FILE), + r#"[tool_suggest] +disabled_tools = [ + { type = "connector", id = " calendar " }, + { type = "plugin", id = "slack@openai-curated" }, +] +"#, + ) + .expect("write user config"); + let next_config = load_latest_config_for_session(&session).await; + session.refresh_runtime_config(next_config).await; + + let expected_disabled_tools = vec![ + ToolSuggestDisabledTool::connector("calendar"), + ToolSuggestDisabledTool::plugin("slack@openai-curated"), + ]; + let expected = vec![ + RecordedConfigChange { + thread_id: session.conversation_id, + previous_model: Some(original_model), + new_model: Some(next_model.to_string()), + previous_disabled_tools: original_disabled_tools.clone(), + new_disabled_tools: original_disabled_tools.clone(), + saw_session_store: true, + saw_thread_store: true, + }, + RecordedConfigChange { + thread_id: session.conversation_id, + previous_model: Some(next_model.to_string()), + new_model: Some(next_model.to_string()), + previous_disabled_tools: original_disabled_tools, + new_disabled_tools: expected_disabled_tools, + saw_session_store: true, + saw_thread_store: true, + }, + ]; + let actual = records + .lock() + .expect("config change records lock") + .drain(..) + .collect::>(); + assert_eq!(expected, actual); +} + #[tokio::test] async fn record_initial_history_reconstructs_forked_transcript() { let (session, turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index aa8e08119a..12a1ccb79d 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -438,6 +438,18 @@ impl Session { per_turn_config } + pub(crate) fn build_effective_session_config( + session_configuration: &SessionConfiguration, + ) -> Config { + let mut config = + Self::build_per_turn_config(session_configuration, session_configuration.cwd.clone()); + config.model = Some(session_configuration.collaboration_mode.model().to_string()); + config.permissions.approval_policy = session_configuration.approval_policy.clone(); + config.permissions.active_permission_profile = + session_configuration.active_permission_profile.clone(); + config + } + #[allow(clippy::too_many_arguments)] pub(crate) fn make_turn_context( thread_id: ThreadId, @@ -588,6 +600,7 @@ impl Session { sub_id: String, updates: SessionSettingsUpdate, ) -> CodexResult> { + let notify_config_contributors = !self.services.extensions.config_contributors().is_empty(); let update_result: CodexResult<_> = { let mut state = self.state.lock().await; match state.session_configuration.clone().apply(&updates) { @@ -612,6 +625,11 @@ impl Session { previous_permission_profile != next_permission_profile; let codex_home = next.codex_home.clone(); let session_source = next.session_source.clone(); + let previous_config = notify_config_contributors.then(|| { + Self::build_effective_session_config(&state.session_configuration) + }); + let new_config = notify_config_contributors + .then(|| Self::build_effective_session_config(&next)); state.session_configuration = next.clone(); Ok(( next, @@ -620,6 +638,8 @@ impl Session { previous_cwd, codex_home, session_source, + previous_config, + new_config, )) } Err(err) => Err(CodexErr::InvalidRequest(err.to_string())), @@ -633,6 +653,8 @@ impl Session { previous_cwd, codex_home, session_source, + previous_config, + new_config, ) = match update_result { Ok(update) => update, Err(err) => { @@ -649,6 +671,7 @@ impl Session { } }; + self.emit_config_changed_contributors(previous_config.as_ref(), new_config.as_ref()); self.maybe_refresh_shell_snapshot_for_cwd( &previous_cwd, &session_configuration.cwd, diff --git a/codex-rs/ext/extension-api/src/contributors.rs b/codex-rs/ext/extension-api/src/contributors.rs index aea59c8a50..c3297c5402 100644 --- a/codex-rs/ext/extension-api/src/contributors.rs +++ b/codex-rs/ext/extension-api/src/contributors.rs @@ -67,6 +67,23 @@ pub trait TurnLifecycleContributor: Send + Sync { fn on_turn_abort(&self, _input: TurnAbortInput<'_>) {} } +/// Contributor for host-owned configuration changes. +/// +/// Implementations should treat the supplied values as immutable before/after +/// snapshots of the effective thread configuration. +pub trait ConfigContributor: Send + Sync { + /// Called after the host commits a changed thread configuration. + fn on_config_changed( + &self, + _session_store: &ExtensionData, + _thread_store: &ExtensionData, + _thread_id: ThreadId, + _previous_config: &C, + _new_config: &C, + ) { + } +} + /// Contributor for token usage checkpoints reported by the model provider. /// /// Implementations should keep this callback cheap. The host calls it after diff --git a/codex-rs/ext/extension-api/src/lib.rs b/codex-rs/ext/extension-api/src/lib.rs index 65e167c771..ccfa2520e4 100644 --- a/codex-rs/ext/extension-api/src/lib.rs +++ b/codex-rs/ext/extension-api/src/lib.rs @@ -15,6 +15,7 @@ pub use codex_tools::ToolSpec; pub use codex_tools::parse_tool_input_schema; pub use contributors::ApprovalReviewContributor; pub use contributors::ApprovalReviewFuture; +pub use contributors::ConfigContributor; pub use contributors::ContextContributor; pub use contributors::ExtensionToolExecutor; pub use contributors::ExtensionToolFuture; diff --git a/codex-rs/ext/extension-api/src/registry.rs b/codex-rs/ext/extension-api/src/registry.rs index f2818cacaa..8193f5c1d1 100644 --- a/codex-rs/ext/extension-api/src/registry.rs +++ b/codex-rs/ext/extension-api/src/registry.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use crate::ApprovalReviewContributor; use crate::ApprovalReviewFuture; +use crate::ConfigContributor; use crate::ContextContributor; use crate::ExtensionData; use crate::ThreadLifecycleContributor; @@ -14,6 +15,7 @@ use crate::TurnLifecycleContributor; pub struct ExtensionRegistryBuilder { thread_lifecycle_contributors: Vec>>, turn_lifecycle_contributors: Vec>, + config_contributors: Vec>>, token_usage_contributors: Vec>, context_contributors: Vec>, tool_contributors: Vec>, @@ -26,6 +28,7 @@ impl Default for ExtensionRegistryBuilder { Self { thread_lifecycle_contributors: Vec::new(), turn_lifecycle_contributors: Vec::new(), + config_contributors: Vec::new(), token_usage_contributors: Vec::new(), approval_review_contributors: Vec::new(), context_contributors: Vec::new(), @@ -59,6 +62,11 @@ impl ExtensionRegistryBuilder { self.turn_lifecycle_contributors.push(contributor); } + /// Registers one config contributor. + pub fn config_contributor(&mut self, contributor: Arc>) { + self.config_contributors.push(contributor); + } + /// Registers one token-usage contributor. pub fn token_usage_contributor(&mut self, contributor: Arc) { self.token_usage_contributors.push(contributor); @@ -84,6 +92,7 @@ impl ExtensionRegistryBuilder { ExtensionRegistry { thread_lifecycle_contributors: self.thread_lifecycle_contributors, turn_lifecycle_contributors: self.turn_lifecycle_contributors, + config_contributors: self.config_contributors, token_usage_contributors: self.token_usage_contributors, approval_review_contributors: self.approval_review_contributors, context_contributors: self.context_contributors, @@ -97,6 +106,7 @@ impl ExtensionRegistryBuilder { pub struct ExtensionRegistry { thread_lifecycle_contributors: Vec>>, turn_lifecycle_contributors: Vec>, + config_contributors: Vec>>, token_usage_contributors: Vec>, context_contributors: Vec>, tool_contributors: Vec>, @@ -115,6 +125,11 @@ impl ExtensionRegistry { &self.turn_lifecycle_contributors } + /// Returns the registered config contributors. + pub fn config_contributors(&self) -> &[Arc>] { + &self.config_contributors + } + /// Returns the registered token-usage contributors. pub fn token_usage_contributors(&self) -> &[Arc] { &self.token_usage_contributors From 8ba67499326617525ea85c7c3bd0d560cf073005 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 17:14:31 +0200 Subject: [PATCH 09/13] feat: memories ext (#22498) First memories extension implementation Based on memories-mcp tools --- codex-rs/Cargo.lock | 20 + codex-rs/Cargo.toml | 3 + codex-rs/ext/memories/BUILD.bazel | 6 + codex-rs/ext/memories/Cargo.toml | 32 ++ codex-rs/ext/memories/src/backend.rs | 164 ++++++ codex-rs/ext/memories/src/lib.rs | 192 +++++++ codex-rs/ext/memories/src/local.rs | 616 ++++++++++++++++++++++ codex-rs/ext/memories/src/schema.rs | 42 ++ codex-rs/ext/memories/src/tools/list.rs | 69 +++ codex-rs/ext/memories/src/tools/mod.rs | 79 +++ codex-rs/ext/memories/src/tools/read.rs | 120 +++++ codex-rs/ext/memories/src/tools/search.rs | 160 ++++++ 12 files changed, 1503 insertions(+) create mode 100644 codex-rs/ext/memories/BUILD.bazel create mode 100644 codex-rs/ext/memories/Cargo.toml create mode 100644 codex-rs/ext/memories/src/backend.rs create mode 100644 codex-rs/ext/memories/src/lib.rs create mode 100644 codex-rs/ext/memories/src/local.rs create mode 100644 codex-rs/ext/memories/src/schema.rs create mode 100644 codex-rs/ext/memories/src/tools/list.rs create mode 100644 codex-rs/ext/memories/src/tools/mod.rs create mode 100644 codex-rs/ext/memories/src/tools/read.rs create mode 100644 codex-rs/ext/memories/src/tools/search.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index cd045e1f94..4a23797cc3 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3137,6 +3137,26 @@ dependencies = [ "wiremock", ] +[[package]] +name = "codex-memories-extension" +version = "0.0.0" +dependencies = [ + "codex-core", + "codex-extension-api", + "codex-features", + "codex-memories-read", + "codex-tools", + "codex-utils-absolute-path", + "codex-utils-output-truncation", + "pretty_assertions", + "schemars 0.8.22", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.18", + "tokio", +] + [[package]] name = "codex-memories-mcp" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 233edcdee8..bd0bcec66a 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -47,6 +47,7 @@ members = [ "ext/extension-api", "ext/guardian", "ext/git-attribution", + "ext/memories", "external-agent-migration", "external-agent-sessions", "keyring-store", @@ -179,6 +180,7 @@ codex-linux-sandbox = { path = "linux-sandbox" } codex-lmstudio = { path = "lmstudio" } codex-login = { path = "login" } codex-message-history = { path = "message-history" } +codex-memories-extension = { path = "ext/memories" } codex-memories-read = { path = "memories/read" } codex-memories-write = { path = "memories/write" } codex-mcp = { path = "codex-mcp" } @@ -469,6 +471,7 @@ unwrap_used = "deny" [workspace.metadata.cargo-shear] ignored = [ "codex-agent-graph-store", + "codex-memories-extension", "icu_provider", "openssl-sys", "codex-v8-poc", diff --git a/codex-rs/ext/memories/BUILD.bazel b/codex-rs/ext/memories/BUILD.bazel new file mode 100644 index 0000000000..5da7a952ab --- /dev/null +++ b/codex-rs/ext/memories/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "memories", + crate_name = "codex_memories_extension", +) diff --git a/codex-rs/ext/memories/Cargo.toml b/codex-rs/ext/memories/Cargo.toml new file mode 100644 index 0000000000..542eaa6bc5 --- /dev/null +++ b/codex-rs/ext/memories/Cargo.toml @@ -0,0 +1,32 @@ +[package] +edition.workspace = true +license.workspace = true +name = "codex-memories-extension" +version.workspace = true + +[lib] +name = "codex_memories_extension" +path = "src/lib.rs" +doctest = false + +[lints] +workspace = true + +[dependencies] +codex-core = { workspace = true } +codex-extension-api = { workspace = true } +codex-features = { workspace = true } +codex-memories-read = { workspace = true } +codex-utils-absolute-path = { workspace = true } +codex-utils-output-truncation = { workspace = true } +schemars = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = ["fs"] } + +[dev-dependencies] +codex-tools = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["fs", "macros"] } diff --git a/codex-rs/ext/memories/src/backend.rs b/codex-rs/ext/memories/src/backend.rs new file mode 100644 index 0000000000..929852f1b1 --- /dev/null +++ b/codex-rs/ext/memories/src/backend.rs @@ -0,0 +1,164 @@ +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; +use std::future::Future; + +pub const DEFAULT_LIST_MAX_RESULTS: usize = 2_000; +pub const MAX_LIST_RESULTS: usize = 2_000; +pub const DEFAULT_SEARCH_MAX_RESULTS: usize = 200; +pub const MAX_SEARCH_RESULTS: usize = 200; +pub const DEFAULT_READ_MAX_TOKENS: usize = 20_000; + +/// Storage interface behind the memories MCP tools. +/// +/// Implementations should return paths relative to the memory store and enforce +/// their own storage-specific access rules. The local implementation uses the +/// filesystem today; a later implementation can satisfy the same contract from a +/// remote backend. +pub trait MemoriesBackend: Clone + Send + Sync + 'static { + fn list( + &self, + request: ListMemoriesRequest, + ) -> impl Future> + Send; + + fn read( + &self, + request: ReadMemoryRequest, + ) -> impl Future> + Send; + + fn search( + &self, + request: SearchMemoriesRequest, + ) -> impl Future> + Send; +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ListMemoriesRequest { + pub path: Option, + pub cursor: Option, + pub max_results: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ListMemoriesResponse { + pub path: Option, + pub entries: Vec, + pub next_cursor: Option, + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReadMemoryRequest { + pub path: String, + pub line_offset: usize, + pub max_lines: Option, + pub max_tokens: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ReadMemoryResponse { + pub path: String, + pub start_line_number: usize, + pub content: String, + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SearchMemoriesRequest { + pub queries: Vec, + pub match_mode: SearchMatchMode, + pub path: Option, + pub cursor: Option, + pub context_lines: usize, + pub case_sensitive: bool, + pub normalized: bool, + pub max_results: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SearchMemoriesResponse { + pub queries: Vec, + pub match_mode: SearchMatchMode, + pub path: Option, + pub matches: Vec, + pub next_cursor: Option, + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum SearchMatchMode { + Any, + AllOnSameLine, + AllWithinLines { + #[schemars(range(min = 1))] + line_count: usize, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MemoryEntry { + pub path: String, + pub entry_type: MemoryEntryType, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum MemoryEntryType { + File, + Directory, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MemorySearchMatch { + pub path: String, + pub match_line_number: usize, + pub content_start_line_number: usize, + pub content: String, + pub matched_queries: Vec, +} + +#[derive(Debug, thiserror::Error)] +pub enum MemoriesBackendError { + #[error("path '{path}' {reason}")] + InvalidPath { path: String, reason: String }, + #[error("cursor '{cursor}' {reason}")] + InvalidCursor { cursor: String, reason: String }, + #[error("path '{path}' was not found")] + NotFound { path: String }, + #[error("line_offset must be a 1-indexed line number")] + InvalidLineOffset, + #[error("max_lines must be a positive integer")] + InvalidMaxLines, + #[error("line_offset exceeds file length")] + LineOffsetExceedsFileLength, + #[error("path '{path}' is not a file")] + NotFile { path: String }, + #[error("queries must not be empty or contain empty strings")] + EmptyQuery, + #[error("all_within_lines.line_count must be a positive integer")] + InvalidMatchWindow, + #[error("I/O error while reading memories: {0}")] + Io(#[from] std::io::Error), +} + +impl MemoriesBackendError { + pub fn invalid_path(path: impl Into, reason: impl Into) -> Self { + Self::InvalidPath { + path: path.into(), + reason: reason.into(), + } + } + + pub fn invalid_cursor(cursor: impl Into, reason: impl Into) -> Self { + Self::InvalidCursor { + cursor: cursor.into(), + reason: reason.into(), + } + } +} diff --git a/codex-rs/ext/memories/src/lib.rs b/codex-rs/ext/memories/src/lib.rs new file mode 100644 index 0000000000..41143bef0f --- /dev/null +++ b/codex-rs/ext/memories/src/lib.rs @@ -0,0 +1,192 @@ +use std::sync::Arc; + +use codex_core::config::Config; +use codex_extension_api::ContextContributor; +use codex_extension_api::ExtensionData; +use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::PromptFragment; +use codex_extension_api::ThreadLifecycleContributor; +use codex_extension_api::ThreadStartInput; +use codex_extension_api::ToolContributor; +use codex_features::Feature; +use codex_memories_read::build_memory_tool_developer_instructions; +use codex_utils_absolute_path::AbsolutePathBuf; + +mod backend; +mod local; +mod schema; +mod tools; + +use local::LocalMemoriesBackend; + +/// Contributes Codex memory read-path prompt context and memory read tools. +#[derive(Clone, Copy, Debug, Default)] +pub struct MemoriesExtension; + +#[derive(Clone, Debug)] +struct MemoriesExtensionConfig { + enabled: bool, + codex_home: AbsolutePathBuf, +} + +impl ContextContributor for MemoriesExtension { + fn contribute<'a>( + &'a self, + _session_store: &'a ExtensionData, + thread_store: &'a ExtensionData, + ) -> std::pin::Pin> + Send + 'a>> { + Box::pin(async move { + let Some(config) = thread_store.get::() else { + return Vec::new(); + }; + if !config.enabled { + return Vec::new(); + } + + build_memory_tool_developer_instructions(&config.codex_home) + .await + .map(PromptFragment::developer_policy) + .into_iter() + .collect() + }) + } +} + +impl ThreadLifecycleContributor for MemoriesExtension { + fn on_thread_start(&self, input: ThreadStartInput<'_, Config>) { + input.thread_store.insert(MemoriesExtensionConfig { + enabled: input.config.features.enabled(Feature::MemoryTool) + && input.config.memories.use_memories, + codex_home: input.config.codex_home.clone(), + }); + } +} + +impl ToolContributor for MemoriesExtension { + fn tools( + &self, + _session_store: &ExtensionData, + thread_store: &ExtensionData, + ) -> Vec> { + let Some(config) = thread_store.get::() else { + return Vec::new(); + }; + if !config.enabled { + return Vec::new(); + } + + tools::memory_tools(LocalMemoriesBackend::from_codex_home(&config.codex_home)) + } +} + +/// Installs the memories extension contributors into the extension registry. +pub fn install(registry: &mut ExtensionRegistryBuilder) { + let extension = Arc::new(MemoriesExtension); + registry.thread_lifecycle_contributor(extension.clone()); + registry.prompt_contributor(extension.clone()); + registry.tool_contributor(extension); +} + +#[cfg(test)] +mod tests { + use codex_extension_api::ContextContributor; + use codex_extension_api::ExtensionData; + use codex_extension_api::PromptSlot; + use codex_extension_api::ToolContributor; + use codex_utils_absolute_path::test_support::PathBufExt; + use codex_utils_absolute_path::test_support::PathExt; + use codex_utils_absolute_path::test_support::test_path_buf; + use pretty_assertions::assert_eq; + + use super::MemoriesExtension; + use super::MemoriesExtensionConfig; + + #[test] + fn tools_are_not_contributed_without_thread_config() { + let extension = MemoriesExtension; + + assert!( + extension + .tools( + &ExtensionData::new("session"), + &ExtensionData::new("thread") + ) + .is_empty() + ); + } + + #[test] + fn tools_are_not_contributed_when_disabled() { + let extension = MemoriesExtension; + let thread_store = ExtensionData::new("thread"); + thread_store.insert(MemoriesExtensionConfig { + enabled: false, + codex_home: test_path_buf("/tmp/codex-home").abs(), + }); + + assert!( + extension + .tools(&ExtensionData::new("session"), &thread_store) + .is_empty() + ); + } + + #[test] + fn tools_are_contributed_when_enabled() { + let extension = MemoriesExtension; + let thread_store = ExtensionData::new("thread"); + thread_store.insert(MemoriesExtensionConfig { + enabled: true, + codex_home: test_path_buf("/tmp/codex-home").abs(), + }); + + let tool_names = extension + .tools(&ExtensionData::new("session"), &thread_store) + .into_iter() + .map(|tool| tool.tool_name().to_string()) + .collect::>(); + + assert_eq!( + tool_names, + vec![ + "memory_list".to_string(), + "memory_read".to_string(), + "memory_search".to_string() + ] + ); + } + + #[tokio::test] + async fn prompt_contribution_uses_memory_summary_when_enabled() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let memories_dir = tempdir.path().join("memories"); + tokio::fs::create_dir_all(&memories_dir) + .await + .expect("create memories dir"); + tokio::fs::write( + memories_dir.join("memory_summary.md"), + "Remember repository-specific implementation preferences.", + ) + .await + .expect("write memory summary"); + + let extension = MemoriesExtension; + let thread_store = ExtensionData::new("thread"); + thread_store.insert(MemoriesExtensionConfig { + enabled: true, + codex_home: tempdir.path().abs(), + }); + + let fragments = extension + .contribute(&ExtensionData::new("session"), &thread_store) + .await; + + assert_eq!(fragments.len(), 1); + assert_eq!(fragments[0].slot(), PromptSlot::DeveloperPolicy); + assert!( + fragments[0] + .text() + .contains("Remember repository-specific implementation preferences.") + ); + } +} diff --git a/codex-rs/ext/memories/src/local.rs b/codex-rs/ext/memories/src/local.rs new file mode 100644 index 0000000000..47c09b60d9 --- /dev/null +++ b/codex-rs/ext/memories/src/local.rs @@ -0,0 +1,616 @@ +use crate::backend::DEFAULT_READ_MAX_TOKENS; +use crate::backend::ListMemoriesRequest; +use crate::backend::ListMemoriesResponse; +use crate::backend::MAX_LIST_RESULTS; +use crate::backend::MAX_SEARCH_RESULTS; +use crate::backend::MemoriesBackend; +use crate::backend::MemoriesBackendError; +use crate::backend::MemoryEntry; +use crate::backend::MemoryEntryType; +use crate::backend::MemorySearchMatch; +use crate::backend::ReadMemoryRequest; +use crate::backend::ReadMemoryResponse; +use crate::backend::SearchMatchMode; +use crate::backend::SearchMemoriesRequest; +use crate::backend::SearchMemoriesResponse; +use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_output_truncation::TruncationPolicy; +use codex_utils_output_truncation::truncate_text; +use std::borrow::Cow; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +#[derive(Debug, Clone)] +pub struct LocalMemoriesBackend { + root: PathBuf, +} + +impl LocalMemoriesBackend { + pub fn from_codex_home(codex_home: &AbsolutePathBuf) -> Self { + Self::from_memory_root(codex_home.join("memories").to_path_buf()) + } + + pub fn from_memory_root(root: impl Into) -> Self { + Self { root: root.into() } + } + + async fn resolve_scoped_path( + &self, + relative_path: Option<&str>, + ) -> Result { + let Some(relative_path) = relative_path else { + return Ok(self.root.clone()); + }; + let relative = Path::new(relative_path); + if relative.components().any(|component| { + matches!( + component, + Component::ParentDir | Component::RootDir | Component::Prefix(_) + ) + }) { + return Err(MemoriesBackendError::invalid_path( + relative_path, + "must stay within the memories root", + )); + } + if relative.components().any(is_hidden_component) { + return Err(MemoriesBackendError::NotFound { + path: relative_path.to_string(), + }); + } + + let components = relative.components().collect::>(); + let mut scoped_path = self.root.clone(); + for (idx, component) in components.iter().enumerate() { + scoped_path.push(component.as_os_str()); + + let Some(metadata) = Self::metadata_or_none(&scoped_path).await? else { + for remaining_component in components.iter().skip(idx + 1) { + scoped_path.push(remaining_component.as_os_str()); + } + return Ok(scoped_path); + }; + + reject_symlink(&display_relative_path(&self.root, &scoped_path), &metadata)?; + if idx + 1 < components.len() && !metadata.is_dir() { + return Err(MemoriesBackendError::invalid_path( + relative_path, + "traverses through a non-directory path component", + )); + } + } + + Ok(scoped_path) + } + + async fn metadata_or_none( + path: &Path, + ) -> Result, MemoriesBackendError> { + match tokio::fs::symlink_metadata(path).await { + Ok(metadata) => Ok(Some(metadata)), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(err) => Err(err.into()), + } + } +} + +impl MemoriesBackend for LocalMemoriesBackend { + async fn list( + &self, + request: ListMemoriesRequest, + ) -> Result { + let max_results = request.max_results.min(MAX_LIST_RESULTS); + let start = self.resolve_scoped_path(request.path.as_deref()).await?; + let start_index = match request.cursor.as_deref() { + Some(cursor) => cursor.parse::().map_err(|_| { + MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer") + })?, + None => 0, + }; + let Some(metadata) = Self::metadata_or_none(&start).await? else { + return Err(MemoriesBackendError::NotFound { + path: request.path.unwrap_or_default(), + }); + }; + reject_symlink(&display_relative_path(&self.root, &start), &metadata)?; + + let mut entries = if metadata.is_file() { + vec![MemoryEntry { + path: display_relative_path(&self.root, &start), + entry_type: MemoryEntryType::File, + }] + } else if metadata.is_dir() { + let mut entries = Vec::new(); + for path in read_sorted_dir_paths(&start).await? { + if is_hidden_path(&path) { + continue; + } + let Some(metadata) = Self::metadata_or_none(&path).await? else { + continue; + }; + if metadata.file_type().is_symlink() { + continue; + } + + let entry_type = if metadata.is_dir() { + MemoryEntryType::Directory + } else if metadata.is_file() { + MemoryEntryType::File + } else { + continue; + }; + entries.push(MemoryEntry { + path: display_relative_path(&self.root, &path), + entry_type, + }); + } + entries + } else { + Vec::new() + }; + if start_index > entries.len() { + return Err(MemoriesBackendError::invalid_cursor( + start_index.to_string(), + "exceeds result count", + )); + } + + let end_index = start_index.saturating_add(max_results).min(entries.len()); + let next_cursor = (end_index < entries.len()).then(|| end_index.to_string()); + let truncated = next_cursor.is_some(); + Ok(ListMemoriesResponse { + path: request.path, + entries: entries.drain(start_index..end_index).collect(), + next_cursor, + truncated, + }) + } + + async fn read( + &self, + request: ReadMemoryRequest, + ) -> Result { + if request.line_offset == 0 { + return Err(MemoriesBackendError::InvalidLineOffset); + } + if request.max_lines == Some(0) { + return Err(MemoriesBackendError::InvalidMaxLines); + } + + let path = self + .resolve_scoped_path(Some(request.path.as_str())) + .await?; + let Some(metadata) = Self::metadata_or_none(&path).await? else { + return Err(MemoriesBackendError::NotFound { path: request.path }); + }; + reject_symlink(&request.path, &metadata)?; + if !metadata.is_file() { + return Err(MemoriesBackendError::NotFile { path: request.path }); + } + + let original_content = tokio::fs::read_to_string(&path).await?; + let start_byte = line_start_byte_offset(&original_content, request.line_offset)?; + let end_byte = line_end_byte_offset(&original_content, start_byte, request.max_lines); + let content_from_offset = &original_content[start_byte..end_byte]; + let max_tokens = if request.max_tokens == 0 { + DEFAULT_READ_MAX_TOKENS + } else { + request.max_tokens + }; + let content = truncate_text(content_from_offset, TruncationPolicy::Tokens(max_tokens)); + let truncated = end_byte < original_content.len() || content != content_from_offset; + Ok(ReadMemoryResponse { + path: request.path, + start_line_number: request.line_offset, + content, + truncated, + }) + } + + async fn search( + &self, + request: SearchMemoriesRequest, + ) -> Result { + let queries = request + .queries + .iter() + .map(|query| query.trim().to_string()) + .collect::>(); + if queries.is_empty() || queries.iter().any(std::string::String::is_empty) { + return Err(MemoriesBackendError::EmptyQuery); + } + if matches!( + request.match_mode, + SearchMatchMode::AllWithinLines { line_count: 0 } + ) { + return Err(MemoriesBackendError::InvalidMatchWindow); + } + + let max_results = request.max_results.min(MAX_SEARCH_RESULTS); + let start = self.resolve_scoped_path(request.path.as_deref()).await?; + let start_index = match request.cursor.as_deref() { + Some(cursor) => cursor.parse::().map_err(|_| { + MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer") + })?, + None => 0, + }; + let Some(metadata) = Self::metadata_or_none(&start).await? else { + return Err(MemoriesBackendError::NotFound { + path: request.path.unwrap_or_default(), + }); + }; + reject_symlink(&display_relative_path(&self.root, &start), &metadata)?; + + let matcher = SearchMatcher::new( + queries.clone(), + request.match_mode.clone(), + request.case_sensitive, + request.normalized, + )?; + let mut matches = Vec::new(); + search_entries( + &self.root, + &start, + &metadata, + &matcher, + request.context_lines, + &mut matches, + ) + .await?; + matches.sort_by(|left, right| { + left.path + .cmp(&right.path) + .then(left.match_line_number.cmp(&right.match_line_number)) + }); + if start_index > matches.len() { + return Err(MemoriesBackendError::invalid_cursor( + start_index.to_string(), + "exceeds result count", + )); + } + let end_index = start_index.saturating_add(max_results).min(matches.len()); + let next_cursor = (end_index < matches.len()).then(|| end_index.to_string()); + let truncated = next_cursor.is_some(); + Ok(SearchMemoriesResponse { + queries, + match_mode: request.match_mode, + path: request.path, + matches: matches.drain(start_index..end_index).collect(), + next_cursor, + truncated, + }) + } +} + +async fn search_entries( + root: &Path, + current: &Path, + current_metadata: &std::fs::Metadata, + matcher: &SearchMatcher, + context_lines: usize, + matches: &mut Vec, +) -> Result<(), MemoriesBackendError> { + if current_metadata.is_file() { + search_file(root, current, matcher, context_lines, matches).await?; + return Ok(()); + } + if !current_metadata.is_dir() { + return Ok(()); + } + + let mut pending = vec![current.to_path_buf()]; + while let Some(dir_path) = pending.pop() { + for path in read_sorted_dir_paths(&dir_path).await? { + if is_hidden_path(&path) { + continue; + } + let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else { + continue; + }; + if metadata.file_type().is_symlink() { + continue; + } + if metadata.is_dir() { + pending.push(path); + } else if metadata.is_file() { + search_file(root, &path, matcher, context_lines, matches).await?; + } + } + } + + Ok(()) +} + +async fn search_file( + root: &Path, + path: &Path, + matcher: &SearchMatcher, + context_lines: usize, + matches: &mut Vec, +) -> Result<(), MemoriesBackendError> { + let content = match tokio::fs::read_to_string(path).await { + Ok(content) => content, + Err(err) if err.kind() == std::io::ErrorKind::InvalidData => return Ok(()), + Err(err) => return Err(err.into()), + }; + let lines = content.lines().collect::>(); + let line_matches = lines + .iter() + .map(|line| matcher.matched_query_flags(line)) + .collect::>(); + match &matcher.match_mode { + SearchMatchMode::Any => { + for (idx, matched_query_flags) in line_matches.iter().enumerate() { + if matched_query_flags.iter().any(|matched| *matched) { + matches.push(build_search_match( + root, + path, + &lines, + idx, + idx, + context_lines, + matcher.matched_queries(matched_query_flags), + )); + } + } + } + SearchMatchMode::AllOnSameLine => { + for (idx, matched_query_flags) in line_matches.iter().enumerate() { + if matched_query_flags.iter().all(|matched| *matched) { + matches.push(build_search_match( + root, + path, + &lines, + idx, + idx, + context_lines, + matcher.matched_queries(matched_query_flags), + )); + } + } + } + SearchMatchMode::AllWithinLines { line_count } => { + let mut windows = Vec::new(); + for start_index in 0..lines.len() { + if !line_matches[start_index].iter().any(|matched| *matched) { + continue; + } + let last_allowed_index = start_index + .saturating_add(line_count.saturating_sub(1)) + .min(lines.len().saturating_sub(1)); + let mut matched_query_flags = vec![false; matcher.queries.len()]; + for (end_index, line_match_flags) in line_matches + .iter() + .enumerate() + .take(last_allowed_index + 1) + .skip(start_index) + { + for (idx, matched) in line_match_flags.iter().enumerate() { + matched_query_flags[idx] |= matched; + } + if matched_query_flags.iter().all(|matched| *matched) { + windows.push((start_index, end_index, matched_query_flags)); + break; + } + } + } + for (idx, (start_index, end_index, matched_query_flags)) in windows.iter().enumerate() { + let strictly_contains_another_window = windows.iter().enumerate().any( + |(other_idx, (other_start_index, other_end_index, _))| { + idx != other_idx + && start_index <= other_start_index + && end_index >= other_end_index + && (start_index != other_start_index || end_index != other_end_index) + }, + ); + if strictly_contains_another_window { + continue; + } + matches.push(build_search_match( + root, + path, + &lines, + *start_index, + *end_index, + context_lines, + matcher.matched_queries(matched_query_flags), + )); + } + } + } + Ok(()) +} + +fn build_search_match( + root: &Path, + path: &Path, + lines: &[&str], + match_start_index: usize, + match_end_index: usize, + context_lines: usize, + matched_queries: Vec, +) -> MemorySearchMatch { + let content_start_index = match_start_index.saturating_sub(context_lines); + let content_end_index = match_end_index + .saturating_add(context_lines) + .saturating_add(1) + .min(lines.len()); + MemorySearchMatch { + path: display_relative_path(root, path), + match_line_number: match_start_index + 1, + content_start_line_number: content_start_index + 1, + content: lines[content_start_index..content_end_index].join("\n"), + matched_queries, + } +} + +struct SearchMatcher { + queries: Vec, + prepared_queries: Vec, + comparison: SearchComparison, + match_mode: SearchMatchMode, +} + +impl SearchMatcher { + fn new( + queries: Vec, + match_mode: SearchMatchMode, + case_sensitive: bool, + normalized: bool, + ) -> Result { + let comparison = SearchComparison::new(case_sensitive, normalized); + let prepared_queries = queries + .iter() + .map(|query| comparison.prepare(query)) + .map(Cow::into_owned) + .collect::>(); + if prepared_queries.iter().any(std::string::String::is_empty) { + return Err(MemoriesBackendError::EmptyQuery); + } + Ok(Self { + queries, + prepared_queries, + comparison, + match_mode, + }) + } + + fn matched_query_flags(&self, line: &str) -> Vec { + let line = self.comparison.prepare(line); + self.prepared_queries + .iter() + .map(|query| line.as_ref().contains(query)) + .collect() + } + + fn matched_queries(&self, matched_query_flags: &[bool]) -> Vec { + self.queries + .iter() + .zip(matched_query_flags) + .filter_map(|(query, matched)| matched.then_some(query.clone())) + .collect() + } +} + +#[derive(Clone, Copy)] +struct SearchComparison { + case_sensitive: bool, + normalized: bool, +} + +impl SearchComparison { + fn new(case_sensitive: bool, normalized: bool) -> Self { + Self { + case_sensitive, + normalized, + } + } + + fn prepare<'a>(self, value: &'a str) -> Cow<'a, str> { + if self.case_sensitive && !self.normalized { + return Cow::Borrowed(value); + } + + let value = if self.case_sensitive { + Cow::Borrowed(value) + } else { + Cow::Owned(value.to_lowercase()) + }; + if !self.normalized { + return value; + } + + Cow::Owned( + value + .chars() + .filter(|ch| ch.is_alphanumeric()) + .collect::(), + ) + } +} + +async fn read_sorted_dir_paths(dir_path: &Path) -> Result, MemoriesBackendError> { + let mut dir = match tokio::fs::read_dir(dir_path).await { + Ok(dir) => dir, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(err) => return Err(err.into()), + }; + let mut paths = Vec::new(); + while let Some(entry) = dir.next_entry().await? { + paths.push(entry.path()); + } + paths.sort(); + Ok(paths) +} + +fn reject_symlink(path: &str, metadata: &std::fs::Metadata) -> Result<(), MemoriesBackendError> { + if metadata.file_type().is_symlink() { + return Err(MemoriesBackendError::invalid_path( + path, + "must not be a symlink", + )); + } + Ok(()) +} + +fn is_hidden_component(component: Component<'_>) -> bool { + matches!( + component, + Component::Normal(name) if name.to_string_lossy().starts_with('.') + ) +} + +fn is_hidden_path(path: &Path) -> bool { + path.file_name() + .is_some_and(|name| name.to_string_lossy().starts_with('.')) +} + +fn display_relative_path(root: &Path, path: &Path) -> String { + path.strip_prefix(root) + .unwrap_or(path) + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .filter(|component| !component.is_empty()) + .collect::>() + .join("/") +} + +fn line_start_byte_offset( + content: &str, + line_offset: usize, +) -> Result { + if line_offset == 1 { + return Ok(0); + } + + let mut current_line = 1; + for (idx, ch) in content.char_indices() { + if ch == '\n' { + current_line += 1; + if current_line == line_offset { + return Ok(idx + 1); + } + } + } + + Err(MemoriesBackendError::LineOffsetExceedsFileLength) +} + +fn line_end_byte_offset(content: &str, start_byte: usize, max_lines: Option) -> usize { + let Some(max_lines) = max_lines else { + return content.len(); + }; + + let mut lines_seen = 1; + for (relative_idx, ch) in content[start_byte..].char_indices() { + if ch == '\n' { + if lines_seen == max_lines { + return start_byte + relative_idx + 1; + } + lines_seen += 1; + } + } + + content.len() +} diff --git a/codex-rs/ext/memories/src/schema.rs b/codex-rs/ext/memories/src/schema.rs new file mode 100644 index 0000000000..977cd5679a --- /dev/null +++ b/codex-rs/ext/memories/src/schema.rs @@ -0,0 +1,42 @@ +use schemars::JsonSchema; +use schemars::r#gen::SchemaSettings; +use serde_json::Map; +use serde_json::Value; + +pub(crate) fn input_schema_for() -> Value { + schema_for::(/*option_add_null_type*/ false) +} + +pub(crate) fn output_schema_for() -> Value { + schema_for::(/*option_add_null_type*/ true) +} + +fn schema_for(option_add_null_type: bool) -> Value { + let schema = SchemaSettings::draft2019_09() + .with(|settings| { + settings.inline_subschemas = true; + settings.option_add_null_type = option_add_null_type; + }) + .into_generator() + .into_root_schema_for::(); + let schema_value = serde_json::to_value(schema) + .unwrap_or_else(|err| panic!("generated tool schema should serialize: {err}")); + let Value::Object(mut schema_object) = schema_value else { + unreachable!("root tool schema must be an object"); + }; + + let mut tool_schema = Map::new(); + for key in [ + "properties", + "required", + "type", + "additionalProperties", + "$defs", + "definitions", + ] { + if let Some(value) = schema_object.remove(key) { + tool_schema.insert(key.to_string(), value); + } + } + Value::Object(tool_schema) +} diff --git a/codex-rs/ext/memories/src/tools/list.rs b/codex-rs/ext/memories/src/tools/list.rs new file mode 100644 index 0000000000..e9674f704b --- /dev/null +++ b/codex-rs/ext/memories/src/tools/list.rs @@ -0,0 +1,69 @@ +use codex_extension_api::ExtensionToolExecutor; +use codex_extension_api::ExtensionToolFuture; +use codex_extension_api::JsonToolOutput; +use codex_extension_api::ToolCall; +use codex_extension_api::ToolName; +use codex_extension_api::ToolSpec; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::json; + +use crate::backend::DEFAULT_LIST_MAX_RESULTS; +use crate::backend::ListMemoriesRequest; +use crate::backend::ListMemoriesResponse; +use crate::backend::MAX_LIST_RESULTS; +use crate::backend::MemoriesBackend; +use crate::local::LocalMemoriesBackend; + +use super::LIST_TOOL_NAME; +use super::backend_error_to_function_call; +use super::clamp_max_results; +use super::function_tool; +use super::parse_args; + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct ListArgs { + path: Option, + cursor: Option, + #[schemars(range(min = 1))] + max_results: Option, +} + +#[derive(Clone)] +pub(super) struct ListTool { + pub(super) backend: LocalMemoriesBackend, +} + +impl ExtensionToolExecutor for ListTool { + fn tool_name(&self) -> ToolName { + ToolName::plain(LIST_TOOL_NAME) + } + + fn spec(&self) -> Option { + Some(function_tool::( + LIST_TOOL_NAME, + "List immediate files and directories under a path in the Codex memories store.", + )) + } + + fn handle(&self, call: ToolCall) -> ExtensionToolFuture<'_> { + let backend = self.backend.clone(); + Box::pin(async move { + let args: ListArgs = parse_args(&call)?; + let response = backend + .list(ListMemoriesRequest { + path: args.path, + cursor: args.cursor, + max_results: clamp_max_results( + args.max_results, + DEFAULT_LIST_MAX_RESULTS, + MAX_LIST_RESULTS, + ), + }) + .await + .map_err(backend_error_to_function_call)?; + Ok(JsonToolOutput::new(json!(response))) + }) + } +} diff --git a/codex-rs/ext/memories/src/tools/mod.rs b/codex-rs/ext/memories/src/tools/mod.rs new file mode 100644 index 0000000000..735126349e --- /dev/null +++ b/codex-rs/ext/memories/src/tools/mod.rs @@ -0,0 +1,79 @@ +use std::sync::Arc; + +use codex_extension_api::ExtensionToolExecutor; +use codex_extension_api::FunctionCallError; +use codex_extension_api::ResponsesApiTool; +use codex_extension_api::ToolCall; +use codex_extension_api::ToolSpec; +use codex_extension_api::parse_tool_input_schema; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::Value; + +use crate::backend::MemoriesBackendError; +use crate::local::LocalMemoriesBackend; +use crate::schema; + +mod list; +mod read; +mod search; + +const LIST_TOOL_NAME: &str = "memory_list"; +const READ_TOOL_NAME: &str = "memory_read"; +const SEARCH_TOOL_NAME: &str = "memory_search"; + +pub(crate) fn memory_tools(backend: LocalMemoriesBackend) -> Vec> { + vec![ + Arc::new(list::ListTool { + backend: backend.clone(), + }), + Arc::new(read::ReadTool { + backend: backend.clone(), + }), + Arc::new(search::SearchTool { backend }), + ] +} + +fn function_tool(name: &str, description: &str) -> ToolSpec { + ToolSpec::Function(ResponsesApiTool { + name: name.to_string(), + description: description.to_string(), + strict: false, + defer_loading: None, + parameters: parse_tool_input_schema(&schema::input_schema_for::()) + .unwrap_or_else(|err| panic!("generated input schema for {name} should parse: {err}")), + output_schema: Some(schema::output_schema_for::()), + }) +} + +fn parse_args Deserialize<'de>>(call: &ToolCall) -> Result { + let arguments = call.function_arguments()?; + let value = if arguments.trim().is_empty() { + Value::Object(serde_json::Map::new()) + } else { + serde_json::from_str(arguments) + .map_err(|err| FunctionCallError::RespondToModel(err.to_string()))? + }; + serde_json::from_value(value).map_err(|err| FunctionCallError::RespondToModel(err.to_string())) +} + +fn clamp_max_results(requested: Option, default: usize, max: usize) -> usize { + requested.unwrap_or(default).clamp(1, max) +} + +fn backend_error_to_function_call(err: MemoriesBackendError) -> FunctionCallError { + match err { + MemoriesBackendError::InvalidPath { .. } + | MemoriesBackendError::InvalidCursor { .. } + | MemoriesBackendError::NotFound { .. } + | MemoriesBackendError::InvalidLineOffset + | MemoriesBackendError::InvalidMaxLines + | MemoriesBackendError::LineOffsetExceedsFileLength + | MemoriesBackendError::NotFile { .. } + | MemoriesBackendError::EmptyQuery + | MemoriesBackendError::InvalidMatchWindow => { + FunctionCallError::RespondToModel(err.to_string()) + } + MemoriesBackendError::Io(_) => FunctionCallError::Fatal(err.to_string()), + } +} diff --git a/codex-rs/ext/memories/src/tools/read.rs b/codex-rs/ext/memories/src/tools/read.rs new file mode 100644 index 0000000000..96129ec0f9 --- /dev/null +++ b/codex-rs/ext/memories/src/tools/read.rs @@ -0,0 +1,120 @@ +use codex_extension_api::ExtensionToolExecutor; +use codex_extension_api::ExtensionToolFuture; +use codex_extension_api::JsonToolOutput; +use codex_extension_api::ToolCall; +use codex_extension_api::ToolName; +use codex_extension_api::ToolSpec; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::json; + +use crate::backend::DEFAULT_READ_MAX_TOKENS; +use crate::backend::MemoriesBackend; +use crate::backend::ReadMemoryRequest; +use crate::backend::ReadMemoryResponse; +use crate::local::LocalMemoriesBackend; + +use super::READ_TOOL_NAME; +use super::backend_error_to_function_call; +use super::function_tool; +use super::parse_args; + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct ReadArgs { + path: String, + #[schemars(range(min = 1))] + line_offset: Option, + #[schemars(range(min = 1))] + max_lines: Option, +} + +#[derive(Clone)] +pub(super) struct ReadTool { + pub(super) backend: LocalMemoriesBackend, +} + +impl ExtensionToolExecutor for ReadTool { + fn tool_name(&self) -> ToolName { + ToolName::plain(READ_TOOL_NAME) + } + + fn spec(&self) -> Option { + Some(function_tool::( + READ_TOOL_NAME, + "Read a Codex memory file by relative path, optionally starting at a 1-indexed line offset and limiting the number of lines returned.", + )) + } + + fn handle(&self, call: ToolCall) -> ExtensionToolFuture<'_> { + let backend = self.backend.clone(); + Box::pin(async move { + let args: ReadArgs = parse_args(&call)?; + let response = backend + .read(ReadMemoryRequest { + path: args.path, + line_offset: args.line_offset.unwrap_or(1), + max_lines: args.max_lines, + max_tokens: DEFAULT_READ_MAX_TOKENS, + }) + .await + .map_err(backend_error_to_function_call)?; + Ok(JsonToolOutput::new(json!(response))) + }) + } +} + +#[cfg(test)] +mod tests { + use codex_extension_api::ToolPayload; + use codex_tools::ToolOutput; + use pretty_assertions::assert_eq; + use serde_json::json; + + use super::*; + + #[tokio::test] + async fn read_tool_reads_memory_file() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let memory_root = tempdir.path().join("memories"); + tokio::fs::create_dir_all(&memory_root) + .await + .expect("create memories dir"); + tokio::fs::write( + memory_root.join("MEMORY.md"), + "first line\nsecond needle line\nthird line\n", + ) + .await + .expect("write memory"); + let tool = ReadTool { + backend: LocalMemoriesBackend::from_memory_root(&memory_root), + }; + let payload = ToolPayload::Function { + arguments: json!({ + "path": "MEMORY.md", + "line_offset": 2, + "max_lines": 1 + }) + .to_string(), + }; + + let output = tool + .handle(ToolCall { + call_id: "call-1".to_string(), + tool_name: ToolName::plain(READ_TOOL_NAME), + payload: payload.clone(), + }) + .await + .expect("read should succeed"); + + assert_eq!( + output.post_tool_use_response("call-1", &payload), + Some(json!({ + "path": "MEMORY.md", + "content": "second needle line\n", + "start_line_number": 2, + "truncated": true + })) + ); + } +} diff --git a/codex-rs/ext/memories/src/tools/search.rs b/codex-rs/ext/memories/src/tools/search.rs new file mode 100644 index 0000000000..f437df0040 --- /dev/null +++ b/codex-rs/ext/memories/src/tools/search.rs @@ -0,0 +1,160 @@ +use codex_extension_api::ExtensionToolExecutor; +use codex_extension_api::ExtensionToolFuture; +use codex_extension_api::JsonToolOutput; +use codex_extension_api::ToolCall; +use codex_extension_api::ToolName; +use codex_extension_api::ToolSpec; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::json; + +use crate::backend::DEFAULT_SEARCH_MAX_RESULTS; +use crate::backend::MAX_SEARCH_RESULTS; +use crate::backend::MemoriesBackend; +use crate::backend::SearchMatchMode; +use crate::backend::SearchMemoriesRequest; +use crate::backend::SearchMemoriesResponse; +use crate::local::LocalMemoriesBackend; + +use super::SEARCH_TOOL_NAME; +use super::backend_error_to_function_call; +use super::clamp_max_results; +use super::function_tool; +use super::parse_args; + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct SearchArgs { + #[schemars(length(min = 1))] + queries: Vec, + match_mode: Option, + path: Option, + cursor: Option, + #[schemars(range(min = 0))] + context_lines: Option, + case_sensitive: Option, + normalized: Option, + #[schemars(range(min = 1))] + max_results: Option, +} + +#[derive(Clone)] +pub(super) struct SearchTool { + pub(super) backend: LocalMemoriesBackend, +} + +impl ExtensionToolExecutor for SearchTool { + fn tool_name(&self) -> ToolName { + ToolName::plain(SEARCH_TOOL_NAME) + } + + fn spec(&self) -> Option { + Some(function_tool::( + SEARCH_TOOL_NAME, + "Search Codex memory files for substring matches, optionally normalizing separators or requiring all query substrings on the same line or within a line window.", + )) + } + + fn handle(&self, call: ToolCall) -> ExtensionToolFuture<'_> { + let backend = self.backend.clone(); + Box::pin(async move { + let args: SearchArgs = parse_args(&call)?; + let response = backend + .search(args.into_request()) + .await + .map_err(backend_error_to_function_call)?; + Ok(JsonToolOutput::new(json!(response))) + }) + } +} + +impl SearchArgs { + fn into_request(self) -> SearchMemoriesRequest { + SearchMemoriesRequest { + queries: self.queries, + match_mode: self.match_mode.unwrap_or(SearchMatchMode::Any), + path: self.path, + cursor: self.cursor, + context_lines: self.context_lines.unwrap_or(0), + case_sensitive: self.case_sensitive.unwrap_or(true), + normalized: self.normalized.unwrap_or(false), + max_results: clamp_max_results( + self.max_results, + DEFAULT_SEARCH_MAX_RESULTS, + MAX_SEARCH_RESULTS, + ), + } + } +} + +#[cfg(test)] +mod tests { + use pretty_assertions::assert_eq; + use serde_json::json; + + use super::*; + + #[test] + fn search_args_accept_multiple_queries() { + let args: SearchArgs = serde_json::from_value(json!({ + "queries": ["alpha", "needle"], + "case_sensitive": false + })) + .expect("multi-query args should parse"); + + let request = args.into_request(); + + assert_eq!( + request, + SearchMemoriesRequest { + queries: vec!["alpha".to_string(), "needle".to_string()], + match_mode: SearchMatchMode::Any, + path: None, + cursor: None, + context_lines: 0, + case_sensitive: false, + normalized: false, + max_results: DEFAULT_SEARCH_MAX_RESULTS, + } + ); + } + + #[test] + fn search_args_accept_windowed_all_match_mode() { + let args: SearchArgs = serde_json::from_value(json!({ + "queries": ["alpha", "needle"], + "match_mode": { + "type": "all_within_lines", + "line_count": 3 + } + })) + .expect("windowed all args should parse"); + + let request = args.into_request(); + + assert_eq!( + request, + SearchMemoriesRequest { + queries: vec!["alpha".to_string(), "needle".to_string()], + match_mode: SearchMatchMode::AllWithinLines { line_count: 3 }, + path: None, + cursor: None, + context_lines: 0, + case_sensitive: true, + normalized: false, + max_results: DEFAULT_SEARCH_MAX_RESULTS, + } + ); + } + + #[test] + fn search_args_reject_legacy_single_query() { + let err = serde_json::from_value::(json!({ + "query": "needle", + })) + .expect_err("legacy query field should be rejected"); + + assert!(err.to_string().contains("unknown field")); + assert!(err.to_string().contains("query")); + } +} From 441c2f818f26708d79a3d438c59048eb8a33a558 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 17:28:37 +0200 Subject: [PATCH 10/13] fix: main (#22503) Fix main due to conflicting merge --- codex-rs/core/src/session/mod.rs | 1 - codex-rs/core/src/session/tests.rs | 5 ----- codex-rs/ext/extension-api/src/contributors.rs | 1 - 3 files changed, 7 deletions(-) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index b40f289dc0..3ef9466812 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -1466,7 +1466,6 @@ impl Session { contributor.on_config_changed( &self.services.session_extension_data, &self.services.thread_extension_data, - self.conversation_id, previous_config, new_config, ); diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 2e9907e952..b4ba561873 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1922,7 +1922,6 @@ async fn config_change_contributor_observes_effective_config_changes() { #[derive(Debug, PartialEq)] struct RecordedConfigChange { - thread_id: ThreadId, previous_model: Option, new_model: Option, previous_disabled_tools: Vec, @@ -1940,7 +1939,6 @@ async fn config_change_contributor_observes_effective_config_changes() { &self, session_store: &codex_extension_api::ExtensionData, thread_store: &codex_extension_api::ExtensionData, - thread_id: ThreadId, previous_config: &crate::config::Config, new_config: &crate::config::Config, ) { @@ -1948,7 +1946,6 @@ async fn config_change_contributor_observes_effective_config_changes() { .lock() .expect("config change records lock") .push(RecordedConfigChange { - thread_id, previous_model: previous_config.model.clone(), new_model: new_config.model.clone(), previous_disabled_tools: previous_config.tool_suggest.disabled_tools.clone(), @@ -2021,7 +2018,6 @@ disabled_tools = [ ]; let expected = vec![ RecordedConfigChange { - thread_id: session.conversation_id, previous_model: Some(original_model), new_model: Some(next_model.to_string()), previous_disabled_tools: original_disabled_tools.clone(), @@ -2030,7 +2026,6 @@ disabled_tools = [ saw_thread_store: true, }, RecordedConfigChange { - thread_id: session.conversation_id, previous_model: Some(next_model.to_string()), new_model: Some(next_model.to_string()), previous_disabled_tools: original_disabled_tools, diff --git a/codex-rs/ext/extension-api/src/contributors.rs b/codex-rs/ext/extension-api/src/contributors.rs index c3297c5402..f3d1375ac8 100644 --- a/codex-rs/ext/extension-api/src/contributors.rs +++ b/codex-rs/ext/extension-api/src/contributors.rs @@ -77,7 +77,6 @@ pub trait ConfigContributor: Send + Sync { &self, _session_store: &ExtensionData, _thread_store: &ExtensionData, - _thread_id: ThreadId, _previous_config: &C, _new_config: &C, ) { From 3d517fbd00ed357572f473b8fef6a00cdabfbd2e Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Wed, 13 May 2026 12:33:27 -0300 Subject: [PATCH 11/13] feat(tui): standardize picker navigation keys (#22347) ## Why Picker-style UI in the TUI has accumulated a mix of hardcoded navigation keys. Some lists supported page movement, some did not; some accepted Vim-like keys, while others only accepted arrows; and tabbed or horizontally adjustable pickers had no shared keymap action for left/right movement. This PR makes picker/list navigation consistent and configurable so users can rely on the same defaults across the TUI. ## What Changed - Adds shared list keymap actions for: - vertical movement: `move_up`, `move_down` - horizontal movement: `move_left`, `move_right` - paging and jumps: `page_up`, `page_down`, `jump_top`, `jump_bottom` - Adds defaults: - Up/down: arrows, `Ctrl+P/N`, `Ctrl+K/J`, and plain `k/j` where text input is not active - Page up/down: `PageUp/PageDown` and `Ctrl+B/F` - First/last: `Home/End` - Left/right: `Left/Right` and `Ctrl+H/L` - Wires the shared list keymap through picker and list surfaces including session resume, multi-select, tabbed selection lists, settings-style lists, app-link selection, MCP elicitation, request-user-input, and the OSS selection wizard. - Keeps search behavior intact by reserving printable characters for query text in searchable pickers. - Updates keymap setup actions, config schema, snapshots, and focused coverage for the new list actions. ## How to Test 1. Start Codex from this branch and open the session picker, for example with an existing session history. 2. In the session list, verify that `Ctrl+J/K` moves the selection down/up. 3. Verify that `Ctrl+F/B` pages down/up and `Home/End` jumps to the first/last visible session. 4. Type printable search text such as `j` or `k` and confirm it updates the query instead of navigating. 5. Focus a picker control that changes values horizontally, such as a session picker toolbar control, and verify `Ctrl+H/L` changes the focused value like left/right arrows. Targeted tests run: - `cargo test -p codex-tui keymap::tests::` - `cargo test -p codex-tui keymap_setup::tests::` - `cargo test -p codex-tui horizontal_list_keys` - `cargo test -p codex-tui page_and_jump_navigation_use_list_keymap` - `cargo test -p codex-tui ctrl_h_l_move_provider_selection` - `cargo test -p codex-tui scroll_state::tests` - `cargo test -p codex-tui switching_tabs_changes_visible_items_and_clears_search` - `cargo test -p codex-tui toggle_sort_key_reloads_with_new_sort` Also ran `just write-config-schema`, `just fmt`, `just fix -p codex-tui`, `just argument-comment-lint`, and `git diff --check`. Note: `cargo test -p codex-tui` was attempted and still aborts in the pre-existing `tests::fork_last_filters_latest_session_by_cwd_unless_show_all` stack overflow, which is unrelated to this branch. --- codex-rs/config/src/tui_keymap.rs | 12 + codex-rs/core/config.schema.json | 64 +++- codex-rs/tui/src/bottom_pane/app_link_view.rs | 105 +++++- .../bottom_pane/experimental_features_view.rs | 83 ++-- .../tui/src/bottom_pane/hooks_browser_view.rs | 72 ++-- .../src/bottom_pane/list_selection_view.rs | 240 ++++++++++-- .../src/bottom_pane/mcp_server_elicitation.rs | 82 ++++ .../src/bottom_pane/memories_settings_view.rs | 82 ++-- codex-rs/tui/src/bottom_pane/mod.rs | 13 +- .../src/bottom_pane/multi_select_picker.rs | 244 +++++++++--- .../src/bottom_pane/request_user_input/mod.rs | 73 +++- codex-rs/tui/src/bottom_pane/scroll_state.rs | 113 +++++- .../tui/src/bottom_pane/skills_toggle_view.rs | 148 +++++--- ..._snapshot_uses_runtime_preview_values.snap | 2 +- ...up__tests__terminal_title_setup_basic.snap | 2 +- .../tui/src/bottom_pane/status_line_setup.rs | 8 +- codex-rs/tui/src/bottom_pane/title_setup.rs | 15 +- codex-rs/tui/src/chatwidget.rs | 15 +- codex-rs/tui/src/chatwidget/hooks.rs | 1 + codex-rs/tui/src/chatwidget/skills.rs | 6 +- ...tatus_line_setup_popup_hardcoded_only.snap | 2 +- ...ts__status_line_setup_popup_live_only.snap | 2 +- ..._tests__status_line_setup_popup_mixed.snap | 2 +- ...inal_title_setup_popup_hardcoded_only.snap | 2 +- ..._terminal_title_setup_popup_live_only.snap | 2 +- ...sts__terminal_title_setup_popup_mixed.snap | 2 +- .../chatwidget/tests/popups_and_settings.rs | 7 +- codex-rs/tui/src/key_hint.rs | 27 ++ codex-rs/tui/src/keymap.rs | 354 +++++++++++++++++- codex-rs/tui/src/keymap_setup/actions.rs | 18 + codex-rs/tui/src/oss_selection.rs | 61 ++- codex-rs/tui/src/resume_picker.rs | 190 ++++++---- ...ap_setup__tests__keymap_picker_custom.snap | 2 +- ...ests__keymap_picker_fast_mode_enabled.snap | 2 +- ...p__tests__keymap_picker_first_actions.snap | 4 +- ...ap_setup__tests__keymap_picker_narrow.snap | 2 +- ...ymap_setup__tests__keymap_picker_wide.snap | 2 +- 37 files changed, 1635 insertions(+), 426 deletions(-) diff --git a/codex-rs/config/src/tui_keymap.rs b/codex-rs/config/src/tui_keymap.rs index 90d82da933..5b1e7d4cc8 100644 --- a/codex-rs/config/src/tui_keymap.rs +++ b/codex-rs/config/src/tui_keymap.rs @@ -306,6 +306,18 @@ pub struct TuiListKeymap { pub move_up: Option, /// Move list selection down. pub move_down: Option, + /// Move horizontally left in list pickers that support horizontal actions. + pub move_left: Option, + /// Move horizontally right in list pickers that support horizontal actions. + pub move_right: Option, + /// Move list selection up by one page. + pub page_up: Option, + /// Move list selection down by one page. + pub page_down: Option, + /// Jump to the first list item. + pub jump_top: Option, + /// Jump to the last list item. + pub jump_bottom: Option, /// Accept current selection. pub accept: Option, /// Cancel and close selection view. diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 1d3ca3210b..8a7cb01b5f 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2606,8 +2606,14 @@ "list": { "accept": null, "cancel": null, + "jump_bottom": null, + "jump_top": null, "move_down": null, - "move_up": null + "move_left": null, + "move_right": null, + "move_up": null, + "page_down": null, + "page_up": null }, "pager": { "close": null, @@ -3252,8 +3258,14 @@ "default": { "accept": null, "cancel": null, + "jump_bottom": null, + "jump_top": null, "move_down": null, - "move_up": null + "move_left": null, + "move_right": null, + "move_up": null, + "page_down": null, + "page_up": null } }, "pager": { @@ -3350,6 +3362,22 @@ ], "description": "Cancel and close selection view." }, + "jump_bottom": { + "allOf": [ + { + "$ref": "#/definitions/KeybindingsSpec" + } + ], + "description": "Jump to the last list item." + }, + "jump_top": { + "allOf": [ + { + "$ref": "#/definitions/KeybindingsSpec" + } + ], + "description": "Jump to the first list item." + }, "move_down": { "allOf": [ { @@ -3358,6 +3386,22 @@ ], "description": "Move list selection down." }, + "move_left": { + "allOf": [ + { + "$ref": "#/definitions/KeybindingsSpec" + } + ], + "description": "Move horizontally left in list pickers that support horizontal actions." + }, + "move_right": { + "allOf": [ + { + "$ref": "#/definitions/KeybindingsSpec" + } + ], + "description": "Move horizontally right in list pickers that support horizontal actions." + }, "move_up": { "allOf": [ { @@ -3365,6 +3409,22 @@ } ], "description": "Move list selection up." + }, + "page_down": { + "allOf": [ + { + "$ref": "#/definitions/KeybindingsSpec" + } + ], + "description": "Move list selection down by one page." + }, + "page_up": { + "allOf": [ + { + "$ref": "#/definitions/KeybindingsSpec" + } + ], + "description": "Move list selection up by one page." } }, "type": "object" diff --git a/codex-rs/tui/src/bottom_pane/app_link_view.rs b/codex-rs/tui/src/bottom_pane/app_link_view.rs index 3702849fce..7fe180a16f 100644 --- a/codex-rs/tui/src/bottom_pane/app_link_view.rs +++ b/codex-rs/tui/src/bottom_pane/app_link_view.rs @@ -29,6 +29,8 @@ use crate::app::app_server_requests::ResolvedAppServerRequest; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use crate::key_hint; +use crate::key_hint::KeyBindingListExt; +use crate::keymap::ListKeymap; use crate::render::Insets; use crate::render::RectExt as _; use crate::style::user_message_style; @@ -238,10 +240,24 @@ pub(crate) struct AppLinkView { screen: AppLinkScreen, selected_action: usize, complete: bool, + list_keymap: ListKeymap, } impl AppLinkView { + #[cfg(test)] pub(crate) fn new(params: AppLinkViewParams, app_event_tx: AppEventSender) -> Self { + Self::new_with_keymap( + params, + app_event_tx, + crate::keymap::RuntimeKeymap::defaults().list, + ) + } + + pub(crate) fn new_with_keymap( + params: AppLinkViewParams, + app_event_tx: AppEventSender, + list_keymap: ListKeymap, + ) -> Self { let AppLinkViewParams { app_id, title, @@ -269,6 +285,7 @@ impl AppLinkView { screen: AppLinkScreen::Link, selected_action: 0, complete: false, + list_keymap, } } @@ -679,10 +696,6 @@ impl BottomPaneView for AppLinkView { KeyEvent { code: KeyCode::Up, .. } - | KeyEvent { - code: KeyCode::Left, - .. - } | KeyEvent { code: KeyCode::BackTab, .. @@ -691,20 +704,12 @@ impl BottomPaneView for AppLinkView { code: KeyCode::Char('k'), modifiers: KeyModifiers::NONE, .. - } - | KeyEvent { - code: KeyCode::Char('h'), - modifiers: KeyModifiers::NONE, - .. } => self.move_selection_prev(), + _ if self.list_keymap.move_left.is_pressed(key_event) => self.move_selection_prev(), KeyEvent { code: KeyCode::Down, .. } - | KeyEvent { - code: KeyCode::Right, - .. - } | KeyEvent { code: KeyCode::Tab, .. } @@ -712,12 +717,8 @@ impl BottomPaneView for AppLinkView { code: KeyCode::Char('j'), modifiers: KeyModifiers::NONE, .. - } - | KeyEvent { - code: KeyCode::Char('l'), - modifiers: KeyModifiers::NONE, - .. } => self.move_selection_next(), + _ if self.list_keymap.move_right.is_pressed(key_event) => self.move_selection_next(), KeyEvent { code: KeyCode::Char(c), modifiers: KeyModifiers::NONE, @@ -1087,6 +1088,74 @@ mod tests { assert!(view.terminal_title_requires_action()); } + #[test] + fn horizontal_list_keys_move_action_selection() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut view = AppLinkView::new( + AppLinkViewParams { + app_id: "connector_1".to_string(), + title: "Notion".to_string(), + description: None, + instructions: "Manage app".to_string(), + url: "https://example.test/notion".to_string(), + is_installed: true, + is_enabled: true, + suggest_reason: None, + suggestion_type: None, + elicitation_target: None, + }, + tx, + ); + + assert_eq!(view.selected_action, 0); + view.handle_key_event(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)); + assert_eq!(view.selected_action, 1); + view.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL)); + assert_eq!(view.selected_action, 0); + } + + #[test] + fn remapped_horizontal_list_keys_control_action_selection() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut list_keymap = crate::keymap::RuntimeKeymap::defaults().list; + list_keymap.move_left = vec![key_hint::plain(KeyCode::Char('x'))]; + list_keymap.move_right = vec![key_hint::plain(KeyCode::Char('z'))]; + let mut view = AppLinkView::new_with_keymap( + AppLinkViewParams { + app_id: "connector_1".to_string(), + title: "Notion".to_string(), + description: None, + instructions: "Manage app".to_string(), + url: "https://example.test/notion".to_string(), + is_installed: true, + is_enabled: true, + suggest_reason: None, + suggestion_type: None, + elicitation_target: None, + }, + tx, + list_keymap, + ); + + assert_eq!(view.selected_action, 0); + view.handle_key_event(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::NONE)); + assert_eq!(view.selected_action, 0); + view.handle_key_event(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(view.selected_action, 0); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE)); + assert_eq!(view.selected_action, 1); + view.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE)); + assert_eq!(view.selected_action, 1); + view.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert_eq!(view.selected_action, 1); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)); + assert_eq!(view.selected_action, 0); + } + #[test] fn toggle_action_sends_set_app_enabled_and_updates_label() { let (tx_raw, mut rx) = unbounded_channel::(); diff --git a/codex-rs/tui/src/bottom_pane/experimental_features_view.rs b/codex-rs/tui/src/bottom_pane/experimental_features_view.rs index c36d70c9fb..6d57e58b6c 100644 --- a/codex-rs/tui/src/bottom_pane/experimental_features_view.rs +++ b/codex-rs/tui/src/bottom_pane/experimental_features_view.rs @@ -13,6 +13,8 @@ use ratatui::widgets::Widget; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use crate::key_hint; +use crate::key_hint::KeyBindingListExt; +use crate::keymap::ListKeymap; use crate::render::Insets; use crate::render::RectExt as _; use crate::render::renderable::ColumnRenderable; @@ -43,12 +45,14 @@ pub(crate) struct ExperimentalFeaturesView { app_event_tx: AppEventSender, header: Box, footer_hint: Line<'static>, + keymap: ListKeymap, } impl ExperimentalFeaturesView { pub(crate) fn new( features: Vec, app_event_tx: AppEventSender, + keymap: ListKeymap, ) -> Self { let mut header = ColumnRenderable::new(); header.push(Line::from("Experimental features".bold())); @@ -63,6 +67,7 @@ impl ExperimentalFeaturesView { app_event_tx, header: Box::new(header), footer_hint: experimental_popup_hint_line(), + keymap, }; view.initialize_selection(); view @@ -119,6 +124,30 @@ impl ExperimentalFeaturesView { self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len)); } + fn page_up(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.state.page_up_clamped(len, visible); + } + + fn page_down(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.state.page_down_clamped(len, visible); + } + + fn jump_top(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.state.jump_top(len, visible); + } + + fn jump_bottom(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.state.jump_bottom(len, visible); + } + fn toggle_selected(&mut self) { let Some(selected_idx) = self.state.selected_idx else { return; @@ -137,56 +166,20 @@ impl ExperimentalFeaturesView { impl BottomPaneView for ExperimentalFeaturesView { fn handle_key_event(&mut self, key_event: KeyEvent) { match key_event { - KeyEvent { - code: KeyCode::Up, .. - } - | KeyEvent { - code: KeyCode::Char('p'), - modifiers: KeyModifiers::CONTROL, - .. - } - | KeyEvent { - code: KeyCode::Char('\u{0010}'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_up(), - KeyEvent { - code: KeyCode::Char('k'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_up(), - KeyEvent { - code: KeyCode::Down, - .. - } - | KeyEvent { - code: KeyCode::Char('n'), - modifiers: KeyModifiers::CONTROL, - .. - } - | KeyEvent { - code: KeyCode::Char('\u{000e}'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_down(), - KeyEvent { - code: KeyCode::Char('j'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_down(), + _ if self.keymap.move_up.is_pressed(key_event) => self.move_up(), + _ if self.keymap.move_down.is_pressed(key_event) => self.move_down(), + _ if self.keymap.page_up.is_pressed(key_event) => self.page_up(), + _ if self.keymap.page_down.is_pressed(key_event) => self.page_down(), + _ if self.keymap.jump_top.is_pressed(key_event) => self.jump_top(), + _ if self.keymap.jump_bottom.is_pressed(key_event) => self.jump_bottom(), KeyEvent { code: KeyCode::Char(' '), modifiers: KeyModifiers::NONE, .. } => self.toggle_selected(), - KeyEvent { - code: KeyCode::Enter, - modifiers: KeyModifiers::NONE, - .. - } - | KeyEvent { - code: KeyCode::Esc, .. - } => { + _ if self.keymap.accept.is_pressed(key_event) + || self.keymap.cancel.is_pressed(key_event) => + { self.on_ctrl_c(); } _ => {} diff --git a/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs b/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs index c9c7a8c617..462e9b286e 100644 --- a/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs +++ b/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs @@ -29,6 +29,8 @@ use crate::app_event_sender::AppEventSender; use crate::hooks_rpc::HookTrustUpdate; use crate::hooks_rpc::hook_needs_review; use crate::key_hint; +use crate::key_hint::KeyBindingListExt; +use crate::keymap::ListKeymap; use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; use crate::render::renderable::Renderable; use crate::status::format_directory_display; @@ -50,6 +52,7 @@ pub(crate) struct HooksBrowserView { state: ScrollState, complete: bool, app_event_tx: AppEventSender, + keymap: ListKeymap, } impl HooksBrowserView { @@ -68,10 +71,15 @@ impl HooksBrowserView { errors, }, app_event_tx, + crate::keymap::RuntimeKeymap::defaults().list, ) } - pub(crate) fn from_entry(mut entry: HooksListEntry, app_event_tx: AppEventSender) -> Self { + pub(crate) fn from_entry( + mut entry: HooksListEntry, + app_event_tx: AppEventSender, + keymap: ListKeymap, + ) -> Self { entry.hooks.sort_by_key(|hook| hook.display_order); let mut view = Self { entry, @@ -79,6 +87,7 @@ impl HooksBrowserView { state: ScrollState::new(), complete: false, app_event_tx, + keymap, }; if view.page_len() > 0 { view.state.selected_idx = Some( @@ -165,6 +174,26 @@ impl HooksBrowserView { self.state.ensure_visible(len, self.max_visible_rows()); } + fn page_up(&mut self) { + let len = self.page_len(); + self.state.page_up_clamped(len, self.max_visible_rows()); + } + + fn page_down(&mut self) { + let len = self.page_len(); + self.state.page_down_clamped(len, self.max_visible_rows()); + } + + fn jump_top(&mut self) { + let len = self.page_len(); + self.state.jump_top(len, self.max_visible_rows()); + } + + fn jump_bottom(&mut self) { + let len = self.page_len(); + self.state.jump_bottom(len, self.max_visible_rows()); + } + fn page_len(&self) -> usize { match self.page { HooksBrowserPage::Events => codex_protocol::protocol::HookEventName::iter().count(), @@ -533,33 +562,18 @@ impl HooksBrowserView { impl BottomPaneView for HooksBrowserView { fn handle_key_event(&mut self, key_event: KeyEvent) { match key_event { - KeyEvent { - code: KeyCode::Up, .. + _ if self.keymap.move_up.is_pressed(key_event) => self.move_up(), + _ if self.keymap.move_down.is_pressed(key_event) => self.move_down(), + _ if self.keymap.page_up.is_pressed(key_event) => self.page_up(), + _ if self.keymap.page_down.is_pressed(key_event) => self.page_down(), + _ if self.keymap.jump_top.is_pressed(key_event) => self.jump_top(), + _ if self.keymap.jump_bottom.is_pressed(key_event) => self.jump_bottom(), + _ if self.keymap.accept.is_pressed(key_event) + && self.page == HooksBrowserPage::Events => + { + self.open_selected_event() } - | KeyEvent { - code: KeyCode::Char('p'), - modifiers: KeyModifiers::CONTROL, - .. - } => self.move_up(), - KeyEvent { - code: KeyCode::Down, - .. - } - | KeyEvent { - code: KeyCode::Char('n'), - modifiers: KeyModifiers::CONTROL, - .. - } => self.move_down(), - KeyEvent { - code: KeyCode::Enter, - modifiers: KeyModifiers::NONE, - .. - } if self.page == HooksBrowserPage::Events => self.open_selected_event(), - KeyEvent { - code: KeyCode::Enter, - modifiers: KeyModifiers::NONE, - .. - } => { + _ if self.keymap.accept.is_pressed(key_event) => { if let HooksBrowserPage::Handlers(event_name) = self.page { self.toggle_selected_hook(event_name); } @@ -581,9 +595,7 @@ impl BottomPaneView for HooksBrowserView { HooksBrowserPage::Events => self.trust_all_hooks(), HooksBrowserPage::Handlers(event_name) => self.trust_selected_hook(event_name), }, - KeyEvent { - code: KeyCode::Esc, .. - } => match self.page { + _ if self.keymap.cancel.is_pressed(key_event) => match self.page { HooksBrowserPage::Events => self.close(), HooksBrowserPage::Handlers(_) => self.return_to_events(), }, diff --git a/codex-rs/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rs index 2d0ac3717b..94ef15cde5 100644 --- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs @@ -17,6 +17,7 @@ use super::selection_popup_common::wrap_styled_line; use crate::app_event_sender::AppEventSender; use crate::key_hint::KeyBinding; use crate::key_hint::KeyBindingListExt; +use crate::key_hint::is_plain_text_key_event; use crate::keymap::ListKeymap; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::Renderable; @@ -655,8 +656,8 @@ impl ListSelectionView { let len = self.visible_len(); self.state.move_up_wrap(len); let visible = Self::max_visible_rows(len); - self.state.ensure_visible(len, visible); self.skip_disabled_up(); + self.state.ensure_visible(len, visible); if self.selected_actual_idx() != before { self.fire_selection_changed(); } @@ -667,8 +668,56 @@ impl ListSelectionView { let len = self.visible_len(); self.state.move_down_wrap(len); let visible = Self::max_visible_rows(len); - self.state.ensure_visible(len, visible); self.skip_disabled_down(); + self.state.ensure_visible(len, visible); + if self.selected_actual_idx() != before { + self.fire_selection_changed(); + } + } + + fn page_up(&mut self) { + let before = self.selected_actual_idx(); + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.page_up_clamped(len, visible); + self.skip_disabled_up_clamped(); + self.state.ensure_visible(len, visible); + if self.selected_actual_idx() != before { + self.fire_selection_changed(); + } + } + + fn page_down(&mut self) { + let before = self.selected_actual_idx(); + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.page_down_clamped(len, visible); + self.skip_disabled_down_clamped(); + self.state.ensure_visible(len, visible); + if self.selected_actual_idx() != before { + self.fire_selection_changed(); + } + } + + fn jump_top(&mut self) { + let before = self.selected_actual_idx(); + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.jump_top(len, visible); + self.skip_disabled_down_clamped(); + self.state.ensure_visible(len, visible); + if self.selected_actual_idx() != before { + self.fire_selection_changed(); + } + } + + fn jump_bottom(&mut self) { + let before = self.selected_actual_idx(); + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.jump_bottom(len, visible); + self.skip_disabled_up_clamped(); + self.state.ensure_visible(len, visible); if self.selected_actual_idx() != before { self.fire_selection_changed(); } @@ -788,13 +837,7 @@ impl ListSelectionView { fn skip_disabled_down(&mut self) { let len = self.visible_len(); for _ in 0..len { - if let Some(idx) = self.state.selected_idx - && let Some(actual_idx) = self.filtered_indices.get(idx) - && self - .active_items() - .get(*actual_idx) - .is_some_and(|item| item.disabled_reason.is_some() || item.is_disabled) - { + if self.selected_visible_idx_is_disabled() { self.state.move_down_wrap(len); } else { break; @@ -805,34 +848,70 @@ impl ListSelectionView { fn skip_disabled_up(&mut self) { let len = self.visible_len(); for _ in 0..len { - if let Some(idx) = self.state.selected_idx - && let Some(actual_idx) = self.filtered_indices.get(idx) - && self - .active_items() - .get(*actual_idx) - .is_some_and(|item| item.disabled_reason.is_some() || item.is_disabled) - { + if self.selected_visible_idx_is_disabled() { self.state.move_up_wrap(len); } else { break; } } } + + fn skip_disabled_down_clamped(&mut self) { + let Some(start) = self.state.selected_idx else { + return; + }; + if !self.visible_idx_is_disabled(start) { + return; + } + + let len = self.visible_len(); + self.state.selected_idx = ((start + 1)..len) + .find(|idx| !self.visible_idx_is_disabled(*idx)) + .or_else(|| { + (0..start) + .rev() + .find(|idx| !self.visible_idx_is_disabled(*idx)) + }) + .or(Some(start)); + } + + fn skip_disabled_up_clamped(&mut self) { + let Some(start) = self.state.selected_idx else { + return; + }; + if !self.visible_idx_is_disabled(start) { + return; + } + + let len = self.visible_len(); + self.state.selected_idx = (0..start) + .rev() + .find(|idx| !self.visible_idx_is_disabled(*idx)) + .or_else(|| ((start + 1)..len).find(|idx| !self.visible_idx_is_disabled(*idx))) + .or(Some(start)); + } + + fn selected_visible_idx_is_disabled(&self) -> bool { + self.state + .selected_idx + .is_some_and(|idx| self.visible_idx_is_disabled(idx)) + } + + fn visible_idx_is_disabled(&self, idx: usize) -> bool { + self.filtered_indices + .get(idx) + .and_then(|actual_idx| self.active_items().get(*actual_idx)) + .is_some_and(|item| item.disabled_reason.is_some() || item.is_disabled) + } } impl BottomPaneView for ListSelectionView { fn handle_key_event(&mut self, key_event: KeyEvent) { - let is_plain_text_char = matches!( - key_event, - KeyEvent { - code: KeyCode::Char(ch), - modifiers, - .. - } if !ch.is_ascii_control() - && !modifiers.contains(KeyModifiers::CONTROL) - && !modifiers.contains(KeyModifiers::ALT) - ); - let allow_plain_char_navigation = !self.is_searchable || !is_plain_text_char; + // Searchable lists reserve printable characters for query input. This + // keeps vim-style plain j/k/h/l useful in non-search lists without + // making those letters impossible to type into a filter. + let allow_plain_char_navigation = + !self.is_searchable || !is_plain_text_key_event(key_event); match key_event { _ if allow_plain_char_navigation && self.keymap.move_up.is_pressed(key_event) => { @@ -841,14 +920,30 @@ impl BottomPaneView for ListSelectionView { _ if allow_plain_char_navigation && self.keymap.move_down.is_pressed(key_event) => { self.move_down() } - KeyEvent { - code: KeyCode::Left, - .. - } if self.tabs_enabled() => self.switch_tab(/*step*/ -1), - KeyEvent { - code: KeyCode::Right, - .. - } if self.tabs_enabled() => self.switch_tab(/*step*/ 1), + _ if allow_plain_char_navigation && self.keymap.page_up.is_pressed(key_event) => { + self.page_up() + } + _ if allow_plain_char_navigation && self.keymap.page_down.is_pressed(key_event) => { + self.page_down() + } + _ if allow_plain_char_navigation && self.keymap.jump_top.is_pressed(key_event) => { + self.jump_top() + } + _ if allow_plain_char_navigation && self.keymap.jump_bottom.is_pressed(key_event) => { + self.jump_bottom() + } + _ if allow_plain_char_navigation + && self.tabs_enabled() + && self.keymap.move_left.is_pressed(key_event) => + { + self.switch_tab(/*step*/ -1) + } + _ if allow_plain_char_navigation + && self.tabs_enabled() + && self.keymap.move_right.is_pressed(key_event) => + { + self.switch_tab(/*step*/ 1) + } KeyEvent { code: KeyCode::Backspace, .. @@ -1618,6 +1713,10 @@ mod tests { assert_eq!(view.active_tab_id(), Some("alpha")); assert_eq!(view.search_query, ""); + view.handle_key_event(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)); + assert_eq!(view.active_tab_id(), Some("beta")); + view.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL)); + assert_eq!(view.active_tab_id(), Some("alpha")); let rendered = render_lines(&view); assert!( rendered.contains("Alpha Item") && !rendered.contains("Beta Item"), @@ -2059,6 +2158,77 @@ mod tests { assert_eq!(view.selected_actual_idx(), Some(1)); } + #[test] + fn page_and_jump_navigation_use_list_keymap() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut keymap = crate::keymap::RuntimeKeymap::defaults().list; + keymap.page_down = vec![crate::key_hint::ctrl(KeyCode::Char('d'))]; + keymap.page_up = vec![crate::key_hint::ctrl(KeyCode::Char('u'))]; + keymap.jump_bottom = vec![crate::key_hint::ctrl(KeyCode::Char('e'))]; + keymap.jump_top = vec![crate::key_hint::ctrl(KeyCode::Char('a'))]; + let mut view = ListSelectionView::new( + SelectionViewParams { + items: (0..12) + .map(|idx| SelectionItem { + name: format!("Item {idx}"), + ..Default::default() + }) + .collect(), + ..Default::default() + }, + tx, + keymap, + ); + + view.handle_key_event(KeyEvent::from(KeyCode::PageDown)); + assert_eq!(view.selected_actual_idx(), Some(0)); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); + assert_eq!(view.selected_actual_idx(), Some(8)); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)); + assert_eq!(view.selected_actual_idx(), Some(0)); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::CONTROL)); + assert_eq!(view.selected_actual_idx(), Some(11)); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL)); + assert_eq!(view.selected_actual_idx(), Some(0)); + } + + #[test] + fn page_and_jump_navigation_skip_trailing_disabled_rows_without_wrapping() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut view = ListSelectionView::new( + SelectionViewParams { + items: (0..12) + .map(|idx| SelectionItem { + name: format!("Item {idx}"), + is_disabled: idx >= 8, + ..Default::default() + }) + .collect(), + ..Default::default() + }, + tx, + crate::keymap::RuntimeKeymap::defaults().list, + ); + + view.handle_key_event(KeyEvent::from(KeyCode::PageDown)); + assert_eq!(view.selected_actual_idx(), Some(7)); + let selected = view.state.selected_idx.expect("selection should be set"); + assert!(view.state.scroll_top <= selected); + assert!(selected < view.state.scroll_top + ListSelectionView::max_visible_rows(/*len*/ 12)); + + view.handle_key_event(KeyEvent::from(KeyCode::End)); + assert_eq!(view.selected_actual_idx(), Some(7)); + let selected = view.state.selected_idx.expect("selection should be set"); + assert!(view.state.scroll_top <= selected); + assert!(selected < view.state.scroll_top + ListSelectionView::max_visible_rows(/*len*/ 12)); + } + #[test] fn wraps_long_option_without_overflowing_columns() { let (tx_raw, _rx) = unbounded_channel::(); diff --git a/codex-rs/tui/src/bottom_pane/mcp_server_elicitation.rs b/codex-rs/tui/src/bottom_pane/mcp_server_elicitation.rs index 95e8e8ca1e..447ab8e6c3 100644 --- a/codex-rs/tui/src/bottom_pane/mcp_server_elicitation.rs +++ b/codex-rs/tui/src/bottom_pane/mcp_server_elicitation.rs @@ -49,6 +49,8 @@ use crate::bottom_pane::selection_popup_common::menu_surface_inset; use crate::bottom_pane::selection_popup_common::menu_surface_padding_height; use crate::bottom_pane::selection_popup_common::render_menu_surface; use crate::bottom_pane::selection_popup_common::render_rows; +use crate::key_hint::KeyBindingListExt; +use crate::keymap::ListKeymap; use crate::render::renderable::Renderable; use crate::text_formatting::format_json_compact; use crate::text_formatting::truncate_text; @@ -711,15 +713,35 @@ pub(crate) struct McpServerElicitationOverlay { current_idx: usize, done: bool, validation_error: Option, + list_keymap: ListKeymap, } impl McpServerElicitationOverlay { + #[cfg(test)] pub(crate) fn new( request: McpServerElicitationFormRequest, app_event_tx: AppEventSender, has_input_focus: bool, enhanced_keys_supported: bool, disable_paste_burst: bool, + ) -> Self { + Self::new_with_keymap( + request, + app_event_tx, + has_input_focus, + enhanced_keys_supported, + disable_paste_burst, + crate::keymap::RuntimeKeymap::defaults().list, + ) + } + + pub(crate) fn new_with_keymap( + request: McpServerElicitationFormRequest, + app_event_tx: AppEventSender, + has_input_focus: bool, + enhanced_keys_supported: bool, + disable_paste_burst: bool, + list_keymap: ListKeymap, ) -> Self { let mut composer = ChatComposer::new_with_config( has_input_focus, @@ -739,6 +761,7 @@ impl McpServerElicitationOverlay { current_idx: 0, done: false, validation_error: None, + list_keymap, }; overlay.reset_for_request(); overlay.restore_current_draft(); @@ -1529,18 +1552,40 @@ impl BottomPaneView for McpServerElicitationOverlay { code: KeyCode::Left, modifiers: KeyModifiers::NONE, .. + } + | KeyEvent { + code: KeyCode::Char('h'), + modifiers: KeyModifiers::NONE, + .. } if self.current_field_is_select() => { self.move_field(/*next*/ false); return; } + _ if self.current_field_is_select() + && self.list_keymap.move_left.is_pressed(key_event) => + { + self.move_field(/*next*/ false); + return; + } KeyEvent { code: KeyCode::Right, modifiers: KeyModifiers::NONE, .. + } + | KeyEvent { + code: KeyCode::Char('l'), + modifiers: KeyModifiers::NONE, + .. } if self.current_field_is_select() => { self.move_field(/*next*/ true); return; } + _ if self.current_field_is_select() + && self.list_keymap.move_right.is_pressed(key_event) => + { + self.move_field(/*next*/ true); + return; + } _ => {} } @@ -2155,6 +2200,43 @@ mod tests { ); } + #[test] + fn horizontal_list_keys_move_between_select_fields() { + let (tx, _rx) = test_sender(); + let request = from_form_request( + ThreadId::default(), + form_request( + "Choose values", + serde_json::json!({ + "type": "object", + "properties": { + "first": { + "type": "boolean", + "title": "First", + }, + "second": { + "type": "boolean", + "title": "Second", + } + }, + "required": ["first", "second"], + }), + /*meta*/ None, + ), + ) + .expect("expected supported form"); + let mut overlay = McpServerElicitationOverlay::new( + request, tx, /*has_input_focus*/ true, /*enhanced_keys_supported*/ false, + /*disable_paste_burst*/ false, + ); + + assert_eq!(overlay.current_idx, 0); + overlay.handle_key_event(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)); + assert_eq!(overlay.current_idx, 1); + overlay.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL)); + assert_eq!(overlay.current_idx, 0); + } + #[test] fn empty_tool_approval_schema_session_choice_sets_persist_meta() { let (tx, mut rx) = test_sender(); diff --git a/codex-rs/tui/src/bottom_pane/memories_settings_view.rs b/codex-rs/tui/src/bottom_pane/memories_settings_view.rs index d2d3c00ce3..06e9b31eb8 100644 --- a/codex-rs/tui/src/bottom_pane/memories_settings_view.rs +++ b/codex-rs/tui/src/bottom_pane/memories_settings_view.rs @@ -14,6 +14,8 @@ use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::popup_consts::standard_popup_hint_line; use crate::key_hint; +use crate::key_hint::KeyBindingListExt; +use crate::keymap::ListKeymap; use crate::render::Insets; use crate::render::RectExt as _; use crate::render::renderable::ColumnRenderable; @@ -62,6 +64,7 @@ pub(crate) struct MemoriesSettingsView { complete: bool, app_event_tx: AppEventSender, docs_link: Line<'static>, + keymap: ListKeymap, } impl MemoriesSettingsView { @@ -69,6 +72,7 @@ impl MemoriesSettingsView { use_memories: bool, generate_memories: bool, app_event_tx: AppEventSender, + keymap: ListKeymap, ) -> Self { let mut view = Self { items: vec![ @@ -98,6 +102,7 @@ impl MemoriesSettingsView { "Learn more: ".dim(), MEMORIES_DOC_URL.cyan().underlined(), ]), + keymap, }; view.initialize_selection(); view @@ -216,6 +221,30 @@ impl MemoriesSettingsView { state.ensure_visible(len, MAX_POPUP_ROWS.min(len)); } + fn page_up(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.active_state_mut().page_up_clamped(len, visible); + } + + fn page_down(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.active_state_mut().page_down_clamped(len, visible); + } + + fn jump_top(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.active_state_mut().jump_top(len, visible); + } + + fn jump_bottom(&mut self) { + let len = self.visible_len(); + let visible = MAX_POPUP_ROWS.min(len); + self.active_state_mut().jump_bottom(len, visible); + } + fn toggle_selected(&mut self) { if self.reset_confirmation.is_some() { return; @@ -271,56 +300,19 @@ impl MemoriesSettingsView { impl BottomPaneView for MemoriesSettingsView { fn handle_key_event(&mut self, key_event: KeyEvent) { match key_event { - KeyEvent { - code: KeyCode::Up, .. - } - | KeyEvent { - code: KeyCode::Char('p'), - modifiers: KeyModifiers::CONTROL, - .. - } - | KeyEvent { - code: KeyCode::Char('\u{0010}'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_up(), - KeyEvent { - code: KeyCode::Char('k'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_up(), - KeyEvent { - code: KeyCode::Down, - .. - } - | KeyEvent { - code: KeyCode::Char('n'), - modifiers: KeyModifiers::CONTROL, - .. - } - | KeyEvent { - code: KeyCode::Char('\u{000e}'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_down(), - KeyEvent { - code: KeyCode::Char('j'), - modifiers: KeyModifiers::NONE, - .. - } => self.move_down(), + _ if self.keymap.move_up.is_pressed(key_event) => self.move_up(), + _ if self.keymap.move_down.is_pressed(key_event) => self.move_down(), + _ if self.keymap.page_up.is_pressed(key_event) => self.page_up(), + _ if self.keymap.page_down.is_pressed(key_event) => self.page_down(), + _ if self.keymap.jump_top.is_pressed(key_event) => self.jump_top(), + _ if self.keymap.jump_bottom.is_pressed(key_event) => self.jump_bottom(), KeyEvent { code: KeyCode::Char(' '), modifiers: KeyModifiers::NONE, .. } => self.toggle_selected(), - KeyEvent { - code: KeyCode::Enter, - modifiers: KeyModifiers::NONE, - .. - } => self.save(), - KeyEvent { - code: KeyCode::Esc, .. - } => self.cancel(), + _ if self.keymap.accept.is_pressed(key_event) => self.save(), + _ if self.keymap.cancel.is_pressed(key_event) => self.cancel(), _ => {} } } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 5a0f967ee2..3faea3f81c 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -1082,6 +1082,10 @@ impl BottomPane { popup_consts::standard_popup_hint_line_for_keymap(&self.keymap.list) } + pub(crate) fn list_keymap(&self) -> crate::keymap::ListKeymap { + self.keymap.list.clone() + } + /// Replace one or more active views whose IDs are in `view_ids` with a /// generic list selection view. pub(crate) fn replace_active_views_with_selection_view( @@ -1298,12 +1302,13 @@ impl BottomPane { request }; - let modal = RequestUserInputOverlay::new( + let modal = RequestUserInputOverlay::new_with_keymap( request, self.app_event_tx.clone(), self.has_input_focus, self.enhanced_keys_supported, self.disable_paste_burst, + self.keymap.list.clone(), ); self.pause_status_timer_for_modal(); self.set_composer_input_enabled( @@ -1342,7 +1347,7 @@ impl BottomPane { tool_suggestion.suggest_type, mcp_server_elicitation::ToolSuggestionType::Enable ); - let view = AppLinkView::new( + let view = AppLinkView::new_with_keymap( AppLinkViewParams { app_id: tool_suggestion.tool_id.clone(), title: tool_suggestion.tool_name.clone(), @@ -1373,6 +1378,7 @@ impl BottomPane { }), }, self.app_event_tx.clone(), + self.keymap.list.clone(), ); self.pause_status_timer_for_modal(); self.set_composer_input_enabled( @@ -1383,12 +1389,13 @@ impl BottomPane { return; } - let modal = McpServerElicitationOverlay::new( + let modal = McpServerElicitationOverlay::new_with_keymap( request, self.app_event_tx.clone(), self.has_input_focus, self.enhanced_keys_supported, self.disable_paste_burst, + self.keymap.list.clone(), ); self.pause_status_timer_for_modal(); self.set_composer_input_enabled( diff --git a/codex-rs/tui/src/bottom_pane/multi_select_picker.rs b/codex-rs/tui/src/bottom_pane/multi_select_picker.rs index 6b046e7ea0..619ff31b5d 100644 --- a/codex-rs/tui/src/bottom_pane/multi_select_picker.rs +++ b/codex-rs/tui/src/bottom_pane/multi_select_picker.rs @@ -61,6 +61,11 @@ use crate::bottom_pane::popup_consts::MAX_POPUP_ROWS; use crate::bottom_pane::scroll_state::ScrollState; use crate::bottom_pane::selection_popup_common::render_rows_single_line; use crate::key_hint; +use crate::key_hint::KeyBindingListExt; +use crate::key_hint::is_plain_text_key_event; +use crate::keymap::ListKeymap; +use crate::keymap::RuntimeKeymap; +use crate::keymap::primary_binding; use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; use crate::render::Insets; use crate::render::RectExt; @@ -182,6 +187,9 @@ pub(crate) struct MultiSelectPicker { /// Whether left/right arrow reordering is enabled. ordering_enabled: bool, + /// Shared list keybindings for navigation and completion. + keymap: ListKeymap, + /// Optional callback to generate a preview line from current item states. preview_builder: Option, @@ -352,6 +360,30 @@ impl MultiSelectPicker { self.state.ensure_visible(len, visible); } + fn page_up(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.page_up_clamped(len, visible); + } + + fn page_down(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.page_down_clamped(len, visible); + } + + fn jump_top(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.jump_top(len, visible); + } + + fn jump_bottom(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.jump_bottom(len, visible); + } + /// Toggles the enabled state of the currently selected item. /// /// Updates the preview line and invokes the `on_change` callback if set. @@ -493,50 +525,41 @@ impl BottomPaneView for MultiSelectPicker { } fn handle_key_event(&mut self, key_event: KeyEvent) { + // Printable characters always feed search. Movement aliases such as + // plain j/k only apply through non-text events or modified bindings. + let allow_plain_char_navigation = !is_plain_text_key_event(key_event); + match key_event { - KeyEvent { code: KeyCode::Left, .. } if self.ordering_enabled => { + _ if allow_plain_char_navigation + && self.ordering_enabled + && self.keymap.move_left.is_pressed(key_event) => + { self.move_selected_item(Direction::Up); } - KeyEvent { code: KeyCode::Right, .. } if self.ordering_enabled => { + _ if allow_plain_char_navigation + && self.ordering_enabled + && self.keymap.move_right.is_pressed(key_event) => + { self.move_selected_item(Direction::Down); } - KeyEvent { - code: KeyCode::Up, .. + _ if allow_plain_char_navigation && self.keymap.move_up.is_pressed(key_event) => { + self.move_up() } - | KeyEvent { - code: KeyCode::Char('p'), - modifiers: KeyModifiers::CONTROL, - .. + _ if allow_plain_char_navigation && self.keymap.move_down.is_pressed(key_event) => { + self.move_down() } - | KeyEvent { - code: KeyCode::Char('k'), - modifiers: KeyModifiers::CONTROL, - .. + _ if allow_plain_char_navigation && self.keymap.page_up.is_pressed(key_event) => { + self.page_up() } - | KeyEvent { - code: KeyCode::Char('\u{0010}'), - modifiers: KeyModifiers::NONE, - .. - } /* ^P */ => self.move_up(), - KeyEvent { - code: KeyCode::Down, - .. + _ if allow_plain_char_navigation && self.keymap.page_down.is_pressed(key_event) => { + self.page_down() } - | KeyEvent { - code: KeyCode::Char('j'), - modifiers: KeyModifiers::CONTROL, - .. + _ if allow_plain_char_navigation && self.keymap.jump_top.is_pressed(key_event) => { + self.jump_top() } - | KeyEvent { - code: KeyCode::Char('n'), - modifiers: KeyModifiers::CONTROL, - .. + _ if allow_plain_char_navigation && self.keymap.jump_bottom.is_pressed(key_event) => { + self.jump_bottom() } - | KeyEvent { - code: KeyCode::Char('\u{000e}'), - modifiers: KeyModifiers::NONE, - .. - } /* ^N */ => self.move_down(), KeyEvent { code: KeyCode::Backspace, .. @@ -549,15 +572,8 @@ impl BottomPaneView for MultiSelectPicker { modifiers: KeyModifiers::NONE, .. } => self.toggle_selected(), - KeyEvent { - code: KeyCode::Enter, - .. - } => self.confirm_selection(), - KeyEvent { - code: KeyCode::Esc, .. - } => { - self.close(); - } + _ if self.keymap.accept.is_pressed(key_event) => self.confirm_selection(), + _ if self.keymap.cancel.is_pressed(key_event) => self.close(), KeyEvent { code: KeyCode::Char(c), modifiers, @@ -703,6 +719,7 @@ pub(crate) struct MultiSelectPickerBuilder { items: Vec, ordering_enabled: bool, app_event_tx: AppEventSender, + keymap: ListKeymap, preview_builder: Option, on_change: Option, on_confirm: Option, @@ -719,6 +736,7 @@ impl MultiSelectPickerBuilder { items: Vec::new(), ordering_enabled: false, app_event_tx, + keymap: RuntimeKeymap::defaults().list, preview_builder: None, on_change: None, on_confirm: None, @@ -732,15 +750,6 @@ impl MultiSelectPickerBuilder { self } - /// Sets custom instruction spans for the footer hint line. - /// - /// If not set, default instructions are shown (Space to toggle, Enter to - /// confirm, Escape to close). - pub fn instructions(mut self, instructions: Vec>) -> Self { - self.instructions = instructions; - self - } - /// Enables left/right arrow keys for reordering items. /// /// Reordering is only active when the search query is empty. @@ -749,6 +758,12 @@ impl MultiSelectPickerBuilder { self } + /// Sets the shared list keymap used for navigation and completion. + pub fn list_keymap(mut self, keymap: ListKeymap) -> Self { + self.keymap = keymap; + self + } + /// Sets a callback to generate a preview line from the current item states. /// /// The callback receives all items and should return a [`Line`] to display, @@ -806,15 +821,34 @@ impl MultiSelectPickerBuilder { } let instructions = if self.instructions.is_empty() { - vec![ + let mut spans = vec![ "Press ".into(), key_hint::plain(KeyCode::Char(' ')).into(), - " to toggle; ".into(), - key_hint::plain(KeyCode::Enter).into(), - " to confirm and close; ".into(), - key_hint::plain(KeyCode::Esc).into(), - " to close".into(), - ] + " to toggle".into(), + ]; + if self.ordering_enabled + && let (Some(move_left), Some(move_right)) = ( + primary_binding(&self.keymap.move_left), + primary_binding(&self.keymap.move_right), + ) + { + spans.push("; ".into()); + spans.push(move_left.into()); + spans.push("/".into()); + spans.push(move_right.into()); + spans.push(" to move".into()); + } + if let Some(accept) = primary_binding(&self.keymap.accept) { + spans.push("; ".into()); + spans.push(accept.into()); + spans.push(" to confirm and close".into()); + } + if let Some(cancel) = primary_binding(&self.keymap.cancel) { + spans.push("; ".into()); + spans.push(cancel.into()); + spans.push(" to close".into()); + } + spans } else { self.instructions }; @@ -827,6 +861,7 @@ impl MultiSelectPickerBuilder { header: Box::new(header), footer_hint: Line::from(instructions), ordering_enabled: self.ordering_enabled, + keymap: self.keymap, search_query: String::new(), filtered_indices: Vec::new(), preview_builder: self.preview_builder, @@ -940,6 +975,38 @@ mod tests { ); } + #[test] + fn horizontal_list_keys_reorder_orderable_items() { + let mut picker = test_picker(vec![ + item( + "model", /*orderable*/ true, /*section_break_after*/ false, + ), + item( + "branch", /*orderable*/ true, /*section_break_after*/ false, + ), + ]); + + picker.handle_key_event(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)); + assert_eq!( + picker + .items + .iter() + .map(|item| item.id.as_str()) + .collect::>(), + vec!["branch", "model"] + ); + + picker.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL)); + assert_eq!( + picker + .items + .iter() + .map(|item| item.id.as_str()) + .collect::>(), + vec!["model", "branch"] + ); + } + #[test] fn section_break_after_item_renders_separator_row() { let picker = test_picker(vec![ @@ -964,4 +1031,65 @@ mod tests { ); assert_eq!(rows.state.selected_idx, Some(0)); } + + #[test] + fn searchable_plain_j_updates_query_instead_of_navigating() { + let mut picker = test_picker(vec![ + item( + "alpha", /*orderable*/ true, /*section_break_after*/ false, + ), + item( + "jupiter", /*orderable*/ true, /*section_break_after*/ false, + ), + ]); + + picker.handle_key_event(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE)); + + assert_eq!(picker.search_query, "j"); + assert_eq!(picker.filtered_indices, vec![1]); + assert_eq!(picker.state.selected_idx, Some(0)); + } + + #[test] + fn page_and_jump_navigation_use_list_keymap() { + let (tx, _rx) = unbounded_channel::(); + let mut keymap = RuntimeKeymap::defaults().list; + keymap.page_down = vec![key_hint::ctrl(KeyCode::Char('d'))]; + keymap.page_up = vec![key_hint::ctrl(KeyCode::Char('u'))]; + keymap.jump_bottom = vec![key_hint::ctrl(KeyCode::Char('e'))]; + keymap.jump_top = vec![key_hint::ctrl(KeyCode::Char('a'))]; + let mut picker = MultiSelectPicker::builder( + "Test".to_string(), + /*subtitle*/ None, + AppEventSender::new(tx), + ) + .items( + (0..12) + .map(|idx| { + item( + &format!("item-{idx}"), + /*orderable*/ true, + /*section_break_after*/ false, + ) + }) + .collect(), + ) + .list_keymap(keymap) + .build(); + + picker.handle_key_event(KeyEvent::from(KeyCode::PageDown)); + assert_eq!(picker.state.selected_idx, Some(0)); + + picker.handle_key_event(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); + assert_eq!(picker.state.selected_idx, Some(8)); + + picker.handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)); + assert_eq!(picker.state.selected_idx, Some(0)); + + picker.handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::CONTROL)); + assert_eq!(picker.state.selected_idx, Some(11)); + + picker.handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL)); + assert_eq!(picker.state.selected_idx, Some(0)); + } } diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs b/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs index 1b9e8c975b..68c6755e45 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs @@ -29,6 +29,8 @@ use crate::bottom_pane::scroll_state::ScrollState; use crate::bottom_pane::selection_popup_common::GenericDisplayRow; use crate::bottom_pane::selection_popup_common::measure_rows_height; use crate::history_cell; +use crate::key_hint::KeyBindingListExt; +use crate::keymap::ListKeymap; use crate::render::renderable::Renderable; #[cfg(test)] @@ -138,15 +140,35 @@ pub(crate) struct RequestUserInputOverlay { done: bool, pending_submission_draft: Option, confirm_unanswered: Option, + list_keymap: ListKeymap, } impl RequestUserInputOverlay { + #[cfg(test)] pub(crate) fn new( request: ToolRequestUserInputParams, app_event_tx: AppEventSender, has_input_focus: bool, enhanced_keys_supported: bool, disable_paste_burst: bool, + ) -> Self { + Self::new_with_keymap( + request, + app_event_tx, + has_input_focus, + enhanced_keys_supported, + disable_paste_burst, + crate::keymap::RuntimeKeymap::defaults().list, + ) + } + + pub(crate) fn new_with_keymap( + request: ToolRequestUserInputParams, + app_event_tx: AppEventSender, + has_input_focus: bool, + enhanced_keys_supported: bool, + disable_paste_burst: bool, + list_keymap: ListKeymap, ) -> Self { // Use the same composer widget, but disable popups/slash-commands and // image-path attachment so it behaves like a focused notes field. @@ -171,6 +193,7 @@ impl RequestUserInputOverlay { done: false, pending_submission_draft: None, confirm_unanswered: None, + list_keymap, }; overlay.reset_for_request(); overlay.ensure_focus_available(); @@ -1063,11 +1086,8 @@ impl BottomPaneView for RequestUserInputOverlay { code: KeyCode::Char('h'), modifiers: KeyModifiers::NONE, .. - } if self.has_options() && matches!(self.focus, Focus::Options) => { - self.move_question(/*next*/ false); - return; } - KeyEvent { + | KeyEvent { code: KeyCode::Left, modifiers: KeyModifiers::NONE, .. @@ -1075,19 +1095,30 @@ impl BottomPaneView for RequestUserInputOverlay { self.move_question(/*next*/ false); return; } + _ if self.has_options() + && matches!(self.focus, Focus::Options) + && self.list_keymap.move_left.is_pressed(key_event) => + { + self.move_question(/*next*/ false); + return; + } KeyEvent { code: KeyCode::Char('l'), modifiers: KeyModifiers::NONE, .. + } + | KeyEvent { + code: KeyCode::Right, + modifiers: KeyModifiers::NONE, + .. } if self.has_options() && matches!(self.focus, Focus::Options) => { self.move_question(/*next*/ true); return; } - KeyEvent { - code: KeyCode::Right, - modifiers: KeyModifiers::NONE, - .. - } if self.has_options() && matches!(self.focus, Focus::Options) => { + _ if self.has_options() + && matches!(self.focus, Focus::Options) + && self.list_keymap.move_right.is_pressed(key_event) => + { self.move_question(/*next*/ true); return; } @@ -1886,6 +1917,30 @@ mod tests { assert_eq!(overlay.current_index(), 0); } + #[test] + fn horizontal_list_keys_move_between_questions_in_options() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Pick one"), + question_with_options("q2", "Pick two"), + ], + ), + tx, + /*has_input_focus*/ true, + /*enhanced_keys_supported*/ false, + /*disable_paste_burst*/ false, + ); + + assert_eq!(overlay.current_index(), 0); + overlay.handle_key_event(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)); + assert_eq!(overlay.current_index(), 1); + overlay.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL)); + assert_eq!(overlay.current_index(), 0); + } + #[test] fn options_notes_focus_hides_question_navigation_tip() { let (tx, _rx) = test_sender(); diff --git a/codex-rs/tui/src/bottom_pane/scroll_state.rs b/codex-rs/tui/src/bottom_pane/scroll_state.rs index a9728d1a0d..a76f3821b1 100644 --- a/codex-rs/tui/src/bottom_pane/scroll_state.rs +++ b/codex-rs/tui/src/bottom_pane/scroll_state.rs @@ -4,6 +4,13 @@ /// - Optional selection (None when list is empty) /// - Wrap-around navigation on Up/Down /// - Maintaining a scroll window (`scroll_top`) so the selected row stays visible +/// +/// Callers own the filtered row count and the visible window size. Every +/// mutation method takes those values instead of caching them here, so list +/// views can apply filters, pagination, or density changes without this helper +/// knowing about their data model. Passing a stale length after filtering would +/// leave selection pointing at the wrong row, so callers should clamp or move +/// through this type immediately after changing their visible row set. #[derive(Debug, Default, Clone, Copy)] pub(crate) struct ScrollState { pub selected_idx: Option, @@ -26,20 +33,15 @@ impl ScrollState { /// Clamp selection to be within the [0, len-1] range, or None when empty. pub fn clamp_selection(&mut self, len: usize) { - self.selected_idx = match len { - 0 => None, - _ => Some(self.selected_idx.unwrap_or(0).min(len - 1)), - }; - if len == 0 { - self.scroll_top = 0; + if self.clear_if_empty(len) { + return; } + self.selected_idx = Some(self.selected_idx.unwrap_or(0).min(len - 1)); } /// Move selection up by one, wrapping to the bottom when necessary. pub fn move_up_wrap(&mut self, len: usize) { - if len == 0 { - self.selected_idx = None; - self.scroll_top = 0; + if self.clear_if_empty(len) { return; } self.selected_idx = Some(match self.selected_idx { @@ -51,9 +53,7 @@ impl ScrollState { /// Move selection down by one, wrapping to the top when necessary. pub fn move_down_wrap(&mut self, len: usize) { - if len == 0 { - self.selected_idx = None; - self.scroll_top = 0; + if self.clear_if_empty(len) { return; } self.selected_idx = Some(match self.selected_idx { @@ -62,6 +62,63 @@ impl ScrollState { }); } + /// Move selection up by one visible page, clamping at the first row. + /// + /// Page movement intentionally does not wrap. It mirrors terminal list + /// behavior where repeated page-up/page-down converges at the nearest edge + /// while still keeping the selected row visible. + pub fn page_up_clamped(&mut self, len: usize, visible_rows: usize) { + if self.clear_if_empty(len) { + return; + } + let step = visible_rows.max(1); + let current = self.selected_idx.unwrap_or(0).min(len - 1); + self.selected_idx = Some(current.saturating_sub(step)); + self.ensure_visible(len, visible_rows); + } + + /// Move selection down by one visible page, clamping at the last row. + /// + /// Page movement intentionally does not wrap. It mirrors terminal list + /// behavior where repeated page-up/page-down converges at the nearest edge + /// while still keeping the selected row visible. + pub fn page_down_clamped(&mut self, len: usize, visible_rows: usize) { + if self.clear_if_empty(len) { + return; + } + let step = visible_rows.max(1); + let current = self.selected_idx.unwrap_or(0).min(len - 1); + self.selected_idx = Some(current.saturating_add(step).min(len - 1)); + self.ensure_visible(len, visible_rows); + } + + /// Jump selection to the first row. + pub fn jump_top(&mut self, len: usize, visible_rows: usize) { + if self.clear_if_empty(len) { + return; + } + self.selected_idx = Some(0); + self.ensure_visible(len, visible_rows); + } + + /// Jump selection to the last row. + pub fn jump_bottom(&mut self, len: usize, visible_rows: usize) { + if self.clear_if_empty(len) { + return; + } + self.selected_idx = Some(len - 1); + self.ensure_visible(len, visible_rows); + } + + fn clear_if_empty(&mut self, len: usize) -> bool { + if len != 0 { + return false; + } + self.selected_idx = None; + self.scroll_top = 0; + true + } + /// Adjust `scroll_top` so that the current `selected_idx` is visible within /// the window of `visible_rows`. pub fn ensure_visible(&mut self, len: usize, visible_rows: usize) { @@ -112,4 +169,36 @@ mod tests { assert_eq!(s.selected_idx, Some(0)); assert_eq!(s.scroll_top, 0); } + + #[test] + fn page_and_jump_navigation_clamps() { + let mut s = ScrollState::new(); + let len = 10; + let vis = 4; + + s.clamp_selection(len); + s.page_down_clamped(len, vis); + assert_eq!(s.selected_idx, Some(4)); + assert_eq!(s.scroll_top, 1); + + s.page_down_clamped(len, vis); + assert_eq!(s.selected_idx, Some(8)); + assert_eq!(s.scroll_top, 5); + + s.page_down_clamped(len, vis); + assert_eq!(s.selected_idx, Some(9)); + assert_eq!(s.scroll_top, 6); + + s.page_up_clamped(len, vis); + assert_eq!(s.selected_idx, Some(5)); + assert_eq!(s.scroll_top, 5); + + s.jump_top(len, vis); + assert_eq!(s.selected_idx, Some(0)); + assert_eq!(s.scroll_top, 0); + + s.jump_bottom(len, vis); + assert_eq!(s.selected_idx, Some(9)); + assert_eq!(s.scroll_top, 6); + } } diff --git a/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs b/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs index 85c014f66b..5a5414ed49 100644 --- a/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs +++ b/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs @@ -14,6 +14,10 @@ use ratatui::widgets::Widget; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use crate::key_hint; +use crate::key_hint::KeyBindingListExt; +use crate::key_hint::is_plain_text_key_event; +use crate::keymap::ListKeymap; +use crate::keymap::primary_binding; use crate::render::Insets; use crate::render::RectExt as _; use crate::render::renderable::ColumnRenderable; @@ -49,10 +53,15 @@ pub(crate) struct SkillsToggleView { footer_hint: Line<'static>, search_query: String, filtered_indices: Vec, + keymap: ListKeymap, } impl SkillsToggleView { - pub(crate) fn new(items: Vec, app_event_tx: AppEventSender) -> Self { + pub(crate) fn new( + items: Vec, + app_event_tx: AppEventSender, + keymap: ListKeymap, + ) -> Self { let mut header = ColumnRenderable::new(); header.push(Line::from("Enable/Disable Skills".bold())); header.push(Line::from( @@ -65,9 +74,10 @@ impl SkillsToggleView { complete: false, app_event_tx, header: Box::new(header), - footer_hint: skills_toggle_hint_line(), + footer_hint: skills_toggle_hint_line(&keymap), search_query: String::new(), filtered_indices: Vec::new(), + keymap, }; view.apply_filter(); view @@ -161,6 +171,30 @@ impl SkillsToggleView { self.state.ensure_visible(len, visible); } + fn page_up(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.page_up_clamped(len, visible); + } + + fn page_down(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.page_down_clamped(len, visible); + } + + fn jump_top(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.jump_top(len, visible); + } + + fn jump_bottom(&mut self) { + let len = self.visible_len(); + let visible = Self::max_visible_rows(len); + self.state.jump_bottom(len, visible); + } + fn toggle_selected(&mut self) { let Some(idx) = self.state.selected_idx else { return; @@ -200,34 +234,29 @@ impl SkillsToggleView { impl BottomPaneView for SkillsToggleView { fn handle_key_event(&mut self, key_event: KeyEvent) { + // Printable characters always feed search. Movement aliases such as + // plain j/k only apply through non-text events or modified bindings. + let allow_plain_char_navigation = !is_plain_text_key_event(key_event); + match key_event { - KeyEvent { - code: KeyCode::Up, .. + _ if allow_plain_char_navigation && self.keymap.move_up.is_pressed(key_event) => { + self.move_up() } - | KeyEvent { - code: KeyCode::Char('p'), - modifiers: KeyModifiers::CONTROL, - .. + _ if allow_plain_char_navigation && self.keymap.move_down.is_pressed(key_event) => { + self.move_down() } - | KeyEvent { - code: KeyCode::Char('\u{0010}'), - modifiers: KeyModifiers::NONE, - .. - } /* ^P */ => self.move_up(), - KeyEvent { - code: KeyCode::Down, - .. + _ if allow_plain_char_navigation && self.keymap.page_up.is_pressed(key_event) => { + self.page_up() } - | KeyEvent { - code: KeyCode::Char('n'), - modifiers: KeyModifiers::CONTROL, - .. + _ if allow_plain_char_navigation && self.keymap.page_down.is_pressed(key_event) => { + self.page_down() + } + _ if allow_plain_char_navigation && self.keymap.jump_top.is_pressed(key_event) => { + self.jump_top() + } + _ if allow_plain_char_navigation && self.keymap.jump_bottom.is_pressed(key_event) => { + self.jump_bottom() } - | KeyEvent { - code: KeyCode::Char('\u{000e}'), - modifiers: KeyModifiers::NONE, - .. - } /* ^N */ => self.move_down(), KeyEvent { code: KeyCode::Backspace, .. @@ -239,15 +268,9 @@ impl BottomPaneView for SkillsToggleView { code: KeyCode::Char(' '), modifiers: KeyModifiers::NONE, .. - } - | KeyEvent { - code: KeyCode::Enter, - modifiers: KeyModifiers::NONE, - .. } => self.toggle_selected(), - KeyEvent { - code: KeyCode::Esc, .. - } => { + _ if self.keymap.accept.is_pressed(key_event) => self.toggle_selected(), + _ if self.keymap.cancel.is_pressed(key_event) => { self.on_ctrl_c(); } KeyEvent { @@ -364,16 +387,37 @@ impl Renderable for SkillsToggleView { } } -fn skills_toggle_hint_line() -> Line<'static> { - Line::from(vec![ - "Press ".into(), - key_hint::plain(KeyCode::Char(' ')).into(), - " or ".into(), - key_hint::plain(KeyCode::Enter).into(), - " to toggle; ".into(), - key_hint::plain(KeyCode::Esc).into(), - " to close".into(), - ]) +fn skills_toggle_hint_line(keymap: &ListKeymap) -> Line<'static> { + let space = key_hint::plain(KeyCode::Char(' ')); + let accept = primary_binding(&keymap.accept).filter(|binding| *binding != space); + let cancel = primary_binding(&keymap.cancel); + + match (accept, cancel) { + (Some(accept), Some(cancel)) => Line::from(vec![ + "Press ".into(), + space.into(), + " or ".into(), + accept.into(), + " to toggle; ".into(), + cancel.into(), + " to close".into(), + ]), + (Some(accept), None) => Line::from(vec![ + "Press ".into(), + space.into(), + " or ".into(), + accept.into(), + " to toggle".into(), + ]), + (None, Some(cancel)) => Line::from(vec![ + "Press ".into(), + space.into(), + " to toggle; ".into(), + cancel.into(), + " to close".into(), + ]), + (None, None) => Line::from(vec!["Press ".into(), space.into(), " to toggle".into()]), + } } #[cfg(test)] @@ -429,7 +473,23 @@ mod tests { path: test_path_buf("/tmp/skills/changelog_writer.toml").abs(), }, ]; - let view = SkillsToggleView::new(items, tx); + let view = SkillsToggleView::new(items, tx, crate::keymap::RuntimeKeymap::defaults().list); assert_snapshot!("skills_toggle_basic", render_lines(&view, /*width*/ 72)); } + + #[test] + fn footer_hint_uses_list_keymap_accept_and_cancel() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut keymap = crate::keymap::RuntimeKeymap::defaults().list; + keymap.accept = vec![key_hint::ctrl(KeyCode::Char('t'))]; + keymap.cancel = vec![key_hint::ctrl(KeyCode::Char('x'))]; + let view = SkillsToggleView::new(Vec::new(), tx, keymap); + let rendered = render_lines(&view, /*width*/ 72); + + assert!(rendered.contains("ctrl + t")); + assert!(rendered.contains("ctrl + x")); + assert!(!rendered.contains("enter")); + assert!(!rendered.contains("esc")); + } } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap index db86cf8a78..50eb41ed4a 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_uses_runtime_preview_values.snap @@ -18,4 +18,4 @@ expression: "render_lines(&view, 72)" [ ] pull-request-number Open pull request number for the current … gpt-5-codex · ~/codex-rs · jif/statusline-preview - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc + Press space to toggle; ←/→ to move; enter to confirm and close; esc to diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap index 598fa418a1..be5cecebf1 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap @@ -18,4 +18,4 @@ expression: "render_lines(&view, 84)" [ ] context-remaining Percentage of context window remaining (omitted when unk… [ ! ] Action Required | my-project | Working | thread title - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel. + Press space to toggle; ←/→ to move; enter to confirm and close; esc to close diff --git a/codex-rs/tui/src/bottom_pane/status_line_setup.rs b/codex-rs/tui/src/bottom_pane/status_line_setup.rs index d96bc286a3..5ce13cd214 100644 --- a/codex-rs/tui/src/bottom_pane/status_line_setup.rs +++ b/codex-rs/tui/src/bottom_pane/status_line_setup.rs @@ -35,6 +35,7 @@ use crate::bottom_pane::multi_select_picker::MultiSelectItem; use crate::bottom_pane::multi_select_picker::MultiSelectPicker; use crate::bottom_pane::status_surface_preview::StatusSurfacePreviewData; use crate::bottom_pane::status_surface_preview::StatusSurfacePreviewItem; +use crate::keymap::ListKeymap; use crate::render::renderable::Renderable; const STATUS_LINE_USE_THEME_COLORS_ITEM_ID: &str = "status-line-use-theme-colors"; @@ -246,6 +247,7 @@ impl StatusLineSetupView { use_theme_colors: bool, preview_data: StatusSurfacePreviewData, app_event_tx: AppEventSender, + list_keymap: ListKeymap, ) -> Self { let mut used_ids = HashSet::new(); let mut items = vec![MultiSelectItem { @@ -284,10 +286,7 @@ impl StatusLineSetupView { Some("Select which items to display in the status line.".to_string()), app_event_tx, ) - .instructions(vec![ - "Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel." - .into(), - ]) + .list_keymap(list_keymap) .items(items) .enable_ordering() .on_preview(move |items| { @@ -621,6 +620,7 @@ mod tests { ), ]), AppEventSender::new(tx_raw), + crate::keymap::RuntimeKeymap::defaults().list, ); assert_snapshot!(render_lines(&view, /*width*/ 72)); diff --git a/codex-rs/tui/src/bottom_pane/title_setup.rs b/codex-rs/tui/src/bottom_pane/title_setup.rs index ae3c56ca3b..f37991bc00 100644 --- a/codex-rs/tui/src/bottom_pane/title_setup.rs +++ b/codex-rs/tui/src/bottom_pane/title_setup.rs @@ -26,6 +26,7 @@ use crate::bottom_pane::multi_select_picker::MultiSelectItem; use crate::bottom_pane::multi_select_picker::MultiSelectPicker; use crate::bottom_pane::status_surface_preview::StatusSurfacePreviewData; use crate::bottom_pane::status_surface_preview::StatusSurfacePreviewItem; +use crate::keymap::ListKeymap; use crate::render::renderable::Renderable; /// Available items that can be displayed in the terminal title. @@ -244,6 +245,7 @@ impl TerminalTitleSetupView { title_items: Option<&[String]>, preview_data: StatusSurfacePreviewData, app_event_tx: AppEventSender, + list_keymap: ListKeymap, ) -> Self { let selected_items = title_items .into_iter() @@ -271,10 +273,7 @@ impl TerminalTitleSetupView { Some("Select which items to display in the terminal title.".to_string()), app_event_tx, ) - .instructions(vec![ - "Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel." - .into(), - ]) + .list_keymap(list_keymap) .items(items) .enable_ordering() .on_preview(move |items| { @@ -387,8 +386,12 @@ mod tests { "run-state".to_string(), "thread-title".to_string(), ]; - let view = - TerminalTitleSetupView::new(Some(&selected), StatusSurfacePreviewData::default(), tx); + let view = TerminalTitleSetupView::new( + Some(&selected), + StatusSurfacePreviewData::default(), + tx, + crate::keymap::RuntimeKeymap::defaults().list, + ); assert_snapshot!( "terminal_title_setup_basic", render_lines(&view, /*width*/ 84) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index b73459c6ff..2894e79c88 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1441,7 +1441,11 @@ impl ChatWidget { } pub(crate) fn open_app_link_view(&mut self, params: crate::bottom_pane::AppLinkViewParams) { - let view = crate::bottom_pane::AppLinkView::new(params, self.app_event_tx.clone()); + let view = crate::bottom_pane::AppLinkView::new_with_keymap( + params, + self.app_event_tx.clone(), + self.bottom_pane.list_keymap(), + ); self.bottom_pane.show_view(Box::new(view)); self.request_redraw(); } @@ -1899,6 +1903,7 @@ impl ChatWidget { self.config.memories.use_memories, self.config.memories.generate_memories, self.app_event_tx.clone(), + self.bottom_pane.list_keymap(), ); self.bottom_pane.show_view(Box::new(view)); } @@ -4981,6 +4986,7 @@ impl ChatWidget { self.config.tui_status_line_use_colors, self.status_surface_preview_data(), self.app_event_tx.clone(), + self.bottom_pane.list_keymap(), ); self.bottom_pane.show_view(Box::new(view)); } @@ -4992,6 +4998,7 @@ impl ChatWidget { Some(configured_terminal_title_items.as_slice()), self.terminal_title_preview_data(), self.app_event_tx.clone(), + self.bottom_pane.list_keymap(), ); self.bottom_pane.show_view(Box::new(view)); } @@ -6517,7 +6524,11 @@ impl ChatWidget { }) .collect(); - let view = ExperimentalFeaturesView::new(features, self.app_event_tx.clone()); + let view = ExperimentalFeaturesView::new( + features, + self.app_event_tx.clone(), + self.bottom_pane.list_keymap(), + ); self.bottom_pane.show_view(Box::new(view)); } diff --git a/codex-rs/tui/src/chatwidget/hooks.rs b/codex-rs/tui/src/chatwidget/hooks.rs index f8c52f74ea..3cc638a8d7 100644 --- a/codex-rs/tui/src/chatwidget/hooks.rs +++ b/codex-rs/tui/src/chatwidget/hooks.rs @@ -36,6 +36,7 @@ impl ChatWidget { .show_view(Box::new(HooksBrowserView::from_entry( entry, self.app_event_tx.clone(), + self.bottom_pane.list_keymap(), ))); self.request_redraw(); } diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index bc431d0db7..356e191b8e 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -94,7 +94,11 @@ impl ChatWidget { }) .collect(); - let view = SkillsToggleView::new(items, self.app_event_tx.clone()); + let view = SkillsToggleView::new( + items, + self.app_event_tx.clone(), + self.bottom_pane.list_keymap(), + ); self.bottom_pane.show_view(Box::new(view)); } diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap index 652c914adf..10c1132c3f 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap @@ -17,4 +17,4 @@ expression: status_line_popup_snapshot(&mut chat) [ ] current-dir Current working directory my-project · feat/awesome-feature · thread title - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel. + Press space to toggle; ←/→ to move; enter to confirm and close; esc to close diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap index fc713c4cdc..3106adea2a 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap @@ -17,4 +17,4 @@ expression: status_line_popup_snapshot(&mut chat) [ ] current-dir Current working directory preview-live-root · feature/live-preview-branch · Live preview thread - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel. + Press space to toggle; ←/→ to move; enter to confirm and close; esc to close diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap index 547f70daa8..1cb2dcb5af 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap @@ -17,4 +17,4 @@ expression: status_line_popup_snapshot(&mut chat) [ ] current-dir Current working directory my-project · feature/mixed-preview · Mixed preview thread - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel. + Press space to toggle; ←/→ to move; enter to confirm and close; esc to close diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap index cf2248ffdd..8ff4227504 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap @@ -17,4 +17,4 @@ expression: terminal_title_popup_snapshot(&mut chat) [ ] run-state Compact session run-state text (Ready, Working, Thinking) thread title | feat/awesome-feature | Tasks 0/0 - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel. + Press space to toggle; ←/→ to move; enter to confirm and close; esc to close diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap index c22a70f714..8c149b8cc9 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap @@ -17,4 +17,4 @@ expression: terminal_title_popup_snapshot(&mut chat) [ ] run-state Compact session run-state text (Ready, Working, Thinking) preview-live-root | Live preview thread | feature/live-preview-branch | Tasks 2/5 - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel. + Press space to toggle; ←/→ to move; enter to confirm and close; esc to close diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap index 06b988811e..b04e07bd9b 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap @@ -17,4 +17,4 @@ expression: terminal_title_popup_snapshot(&mut chat) [ ] git-branch Current Git branch (omitted when unavailable) project | Mixed preview thread | Tasks 0/0 - Use ↑↓ to navigate, ←→ to move, space to select, enter to confirm, esc to cancel. + Press space to toggle; ←/→ to move; enter to confirm and close; esc to close diff --git a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs index a2dd3b9955..4f4398d349 100644 --- a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs +++ b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs @@ -2181,7 +2181,11 @@ async fn experimental_features_popup_snapshot() { enabled: true, }, ]; - let view = ExperimentalFeaturesView::new(features, chat.app_event_tx.clone()); + let view = ExperimentalFeaturesView::new( + features, + chat.app_event_tx.clone(), + crate::keymap::RuntimeKeymap::defaults().list, + ); chat.bottom_pane.show_view(Box::new(view)); let popup = render_bottom_popup(&chat, /*width*/ 80); @@ -2201,6 +2205,7 @@ async fn experimental_features_toggle_saves_on_exit() { enabled: false, }], chat.app_event_tx.clone(), + crate::keymap::RuntimeKeymap::defaults().list, ); chat.bottom_pane.show_view(Box::new(view)); diff --git a/codex-rs/tui/src/key_hint.rs b/codex-rs/tui/src/key_hint.rs index 1008a00aa5..da5a332360 100644 --- a/codex-rs/tui/src/key_hint.rs +++ b/codex-rs/tui/src/key_hint.rs @@ -5,6 +5,12 @@ //! cross-terminal inconsistencies in how shifted letters and raw C0 control //! characters are reported. //! +//! List and picker code should match navigation through these helpers instead +//! of comparing `KeyEvent` values directly. The matcher owns compatibility for +//! terminals that report control chords as C0 characters, while +//! `is_plain_text_key_event` gives searchable pickers a shared boundary between +//! text input and navigation commands. +//! //! It also supplies rendering helpers that convert bindings into styled //! `ratatui::text::Span` values for UI hint display. @@ -122,6 +128,27 @@ impl KeyBindingListExt for [KeyBinding] { } } +/// Returns whether an event should be treated as literal text input. +/// +/// Searchable pickers use this to avoid stealing plain printable characters for +/// navigation when the same character might be a valid query. For example, a +/// list may bind `j` and `k` for movement, but a searchable list must let +/// plain `j` update the query while still allowing `Ctrl+J` to move. Calling +/// this after normalizing keybindings would blur that distinction and cause +/// printable search input to disappear. +pub(crate) fn is_plain_text_key_event(event: KeyEvent) -> bool { + matches!( + event, + KeyEvent { + code: KeyCode::Char(ch), + modifiers, + .. + } if !ch.is_ascii_control() + && !modifiers.contains(KeyModifiers::CONTROL) + && !modifiers.contains(KeyModifiers::ALT) + ) +} + pub(crate) const fn plain(key: KeyCode) -> KeyBinding { KeyBinding::new(key, KeyModifiers::NONE) } diff --git a/codex-rs/tui/src/keymap.rs b/codex-rs/tui/src/keymap.rs index c12d24ca22..fbac160967 100644 --- a/codex-rs/tui/src/keymap.rs +++ b/codex-rs/tui/src/keymap.rs @@ -201,10 +201,24 @@ pub(crate) struct PagerKeymap { } /// Generic list picker keybindings shared across popup list views. +/// +/// These actions describe list intent rather than a specific widget layout. +/// Vertical actions move the highlighted row, page and jump actions move within +/// the current filtered row set, and horizontal actions are available to views +/// that expose adjacent choices such as tabs, toolbar values, or ordered item +/// movement. Views that also accept search text are responsible for checking +/// `is_plain_text_key_event` before dispatching plain-character bindings so a +/// configured `j`, `k`, `h`, or `l` does not steal query input. #[derive(Clone, Debug)] pub(crate) struct ListKeymap { pub(crate) move_up: Vec, pub(crate) move_down: Vec, + pub(crate) move_left: Vec, + pub(crate) move_right: Vec, + pub(crate) page_up: Vec, + pub(crate) page_down: Vec, + pub(crate) jump_top: Vec, + pub(crate) jump_bottom: Vec, pub(crate) accept: Vec, pub(crate) cancel: Vec, } @@ -505,13 +519,6 @@ impl RuntimeKeymap { close_transcript: resolve_local!(keymap, defaults, pager, close_transcript), }; - let list = ListKeymap { - move_up: resolve_local!(keymap, defaults, list, move_up), - move_down: resolve_local!(keymap, defaults, list, move_down), - accept: resolve_local!(keymap, defaults, list, accept), - cancel: resolve_local!(keymap, defaults, list, cancel), - }; - let approval = ApprovalKeymap { open_fullscreen: resolve_local!(keymap, defaults, approval, open_fullscreen), open_thread: resolve_local!(keymap, defaults, approval, open_thread), @@ -523,6 +530,121 @@ impl RuntimeKeymap { cancel: resolve_local!(keymap, defaults, approval, cancel), }; + let list_move_up = resolve_local!(keymap, defaults, list, move_up); + let list_move_down = resolve_local!(keymap, defaults, list, move_down); + let list_accept = resolve_local!(keymap, defaults, list, accept); + let list_cancel = resolve_local!(keymap, defaults, list, cancel); + let mut configured_bindings_to_preserve = Vec::new(); + for (configured, resolved) in [ + ( + keymap.global.open_transcript.as_ref(), + app.open_transcript.as_slice(), + ), + ( + keymap.global.open_external_editor.as_ref(), + app.open_external_editor.as_slice(), + ), + (keymap.global.copy.as_ref(), app.copy.as_slice()), + ( + keymap.global.clear_terminal.as_ref(), + app.clear_terminal.as_slice(), + ), + ( + keymap.global.toggle_vim_mode.as_ref(), + app.toggle_vim_mode.as_slice(), + ), + ( + keymap.global.toggle_fast_mode.as_ref(), + app.toggle_fast_mode.as_slice(), + ), + ( + keymap.global.toggle_raw_output.as_ref(), + app.toggle_raw_output.as_slice(), + ), + (keymap.list.move_up.as_ref(), list_move_up.as_slice()), + (keymap.list.move_down.as_ref(), list_move_down.as_slice()), + (keymap.list.accept.as_ref(), list_accept.as_slice()), + (keymap.list.cancel.as_ref(), list_cancel.as_slice()), + ( + keymap.approval.open_fullscreen.as_ref(), + approval.open_fullscreen.as_slice(), + ), + ( + keymap.approval.open_thread.as_ref(), + approval.open_thread.as_slice(), + ), + ( + keymap.approval.approve.as_ref(), + approval.approve.as_slice(), + ), + ( + keymap.approval.approve_for_session.as_ref(), + approval.approve_for_session.as_slice(), + ), + ( + keymap.approval.approve_for_prefix.as_ref(), + approval.approve_for_prefix.as_slice(), + ), + (keymap.approval.deny.as_ref(), approval.deny.as_slice()), + ( + keymap.approval.decline.as_ref(), + approval.decline.as_slice(), + ), + (keymap.approval.cancel.as_ref(), approval.cancel.as_slice()), + ] { + if configured.is_none() { + continue; + } + for binding in resolved { + if !configured_bindings_to_preserve.contains(binding) { + configured_bindings_to_preserve.push(*binding); + } + } + } + + let list = ListKeymap { + move_up: list_move_up, + move_down: list_move_down, + move_left: resolve_new_list_bindings( + keymap.list.move_left.as_ref(), + &defaults.list.move_left, + &configured_bindings_to_preserve, + "tui.keymap.list.move_left", + )?, + move_right: resolve_new_list_bindings( + keymap.list.move_right.as_ref(), + &defaults.list.move_right, + &configured_bindings_to_preserve, + "tui.keymap.list.move_right", + )?, + page_up: resolve_new_list_bindings( + keymap.list.page_up.as_ref(), + &defaults.list.page_up, + &configured_bindings_to_preserve, + "tui.keymap.list.page_up", + )?, + page_down: resolve_new_list_bindings( + keymap.list.page_down.as_ref(), + &defaults.list.page_down, + &configured_bindings_to_preserve, + "tui.keymap.list.page_down", + )?, + jump_top: resolve_new_list_bindings( + keymap.list.jump_top.as_ref(), + &defaults.list.jump_top, + &configured_bindings_to_preserve, + "tui.keymap.list.jump_top", + )?, + jump_bottom: resolve_new_list_bindings( + keymap.list.jump_bottom.as_ref(), + &defaults.list.jump_bottom, + &configured_bindings_to_preserve, + "tui.keymap.list.jump_bottom", + )?, + accept: list_accept, + cancel: list_cancel, + }; + let resolved = Self { app, chat, @@ -711,13 +833,21 @@ impl RuntimeKeymap { move_up: default_bindings![ plain(KeyCode::Up), ctrl(KeyCode::Char('p')), + ctrl(KeyCode::Char('k')), plain(KeyCode::Char('k')) ], move_down: default_bindings![ plain(KeyCode::Down), ctrl(KeyCode::Char('n')), + ctrl(KeyCode::Char('j')), plain(KeyCode::Char('j')) ], + move_left: default_bindings![plain(KeyCode::Left), ctrl(KeyCode::Char('h'))], + move_right: default_bindings![plain(KeyCode::Right), ctrl(KeyCode::Char('l'))], + page_up: default_bindings![plain(KeyCode::PageUp), ctrl(KeyCode::Char('b'))], + page_down: default_bindings![plain(KeyCode::PageDown), ctrl(KeyCode::Char('f'))], + jump_top: default_bindings![plain(KeyCode::Home)], + jump_bottom: default_bindings![plain(KeyCode::End)], accept: default_bindings![plain(KeyCode::Enter)], cancel: default_bindings![plain(KeyCode::Esc)], }, @@ -835,7 +965,7 @@ impl RuntimeKeymap { MAIN_RESERVED_BINDINGS, )?; - validate_no_shadow( + validate_no_shadow_with_allowed_overlaps( "app", [ ("open_transcript", self.app.open_transcript.as_slice()), @@ -852,6 +982,12 @@ impl RuntimeKeymap { [ ("list.move_up", self.list.move_up.as_slice()), ("list.move_down", self.list.move_down.as_slice()), + ("list.move_left", self.list.move_left.as_slice()), + ("list.move_right", self.list.move_right.as_slice()), + ("list.page_up", self.list.page_up.as_slice()), + ("list.page_down", self.list.page_down.as_slice()), + ("list.jump_top", self.list.jump_top.as_slice()), + ("list.jump_bottom", self.list.jump_bottom.as_slice()), ("list.accept", self.list.accept.as_slice()), ("list.cancel", self.list.cancel.as_slice()), ( @@ -872,6 +1008,11 @@ impl RuntimeKeymap { ("approval.decline", self.approval.decline.as_slice()), ("approval.cancel", self.approval.cancel.as_slice()), ], + [( + "clear_terminal", + "list.move_right", + key_hint::ctrl(KeyCode::Char('l')), + )], )?; // While the composer is focused, these main-surface handlers always @@ -1123,6 +1264,12 @@ impl RuntimeKeymap { [ ("move_up", self.list.move_up.as_slice()), ("move_down", self.list.move_down.as_slice()), + ("move_left", self.list.move_left.as_slice()), + ("move_right", self.list.move_right.as_slice()), + ("page_up", self.list.page_up.as_slice()), + ("page_down", self.list.page_down.as_slice()), + ("jump_top", self.list.jump_top.as_slice()), + ("jump_bottom", self.list.jump_bottom.as_slice()), ("accept", self.list.accept.as_slice()), ("cancel", self.list.cancel.as_slice()), ], @@ -1152,6 +1299,12 @@ impl RuntimeKeymap { for (action, bindings) in [ ("list.move_up", self.list.move_up.as_slice()), ("list.move_down", self.list.move_down.as_slice()), + ("list.move_left", self.list.move_left.as_slice()), + ("list.move_right", self.list.move_right.as_slice()), + ("list.page_up", self.list.page_up.as_slice()), + ("list.page_down", self.list.page_down.as_slice()), + ("list.jump_top", self.list.jump_top.as_slice()), + ("list.jump_bottom", self.list.jump_bottom.as_slice()), ("list.accept", self.list.accept.as_slice()), ("list.cancel", self.list.cancel.as_slice()), ( @@ -1221,14 +1374,6 @@ See the Codex keymap documentation for supported actions and examples." Ok(()) } -fn validate_no_shadow( - context: &str, - primary: [(&'static str, &[KeyBinding]); N], - shadowed: [(&'static str, &[KeyBinding]); M], -) -> Result<(), String> { - validate_no_shadow_with_allowed_overlaps(context, primary, shadowed, []) -} - fn validate_no_shadow_with_allowed_overlaps( context: &str, primary: [(&'static str, &[KeyBinding]); N], @@ -1372,6 +1517,22 @@ fn resolve_bindings( parse_bindings(spec, path) } +fn resolve_new_list_bindings( + configured: Option<&KeybindingsSpec>, + fallback: &[KeyBinding], + configured_bindings_to_preserve: &[KeyBinding], + path: &str, +) -> Result, String> { + let Some(spec) = configured else { + return Ok(fallback + .iter() + .copied() + .filter(|binding| !configured_bindings_to_preserve.contains(binding)) + .collect()); + }; + parse_bindings(spec, path) +} + /// Parse one keybinding value (`string` or `list[string]`) into concrete bindings. /// /// Duplicate entries are de-duplicated while preserving first-seen order so the @@ -1659,6 +1820,152 @@ mod tests { assert_eq!(runtime.editor.kill_whole_line, Vec::new()); } + #[test] + fn defaults_include_list_page_and_jump_actions() { + let runtime = RuntimeKeymap::defaults(); + + assert_eq!( + runtime.list.move_up, + vec![ + key_hint::plain(KeyCode::Up), + key_hint::ctrl(KeyCode::Char('p')), + key_hint::ctrl(KeyCode::Char('k')), + key_hint::plain(KeyCode::Char('k')), + ] + ); + assert_eq!( + runtime.list.move_down, + vec![ + key_hint::plain(KeyCode::Down), + key_hint::ctrl(KeyCode::Char('n')), + key_hint::ctrl(KeyCode::Char('j')), + key_hint::plain(KeyCode::Char('j')), + ] + ); + assert_eq!( + runtime.list.move_left, + vec![ + key_hint::plain(KeyCode::Left), + key_hint::ctrl(KeyCode::Char('h')), + ] + ); + assert_eq!( + runtime.list.move_right, + vec![ + key_hint::plain(KeyCode::Right), + key_hint::ctrl(KeyCode::Char('l')), + ] + ); + assert_eq!( + runtime.list.page_up, + vec![ + key_hint::plain(KeyCode::PageUp), + key_hint::ctrl(KeyCode::Char('b')), + ] + ); + assert_eq!( + runtime.list.page_down, + vec![ + key_hint::plain(KeyCode::PageDown), + key_hint::ctrl(KeyCode::Char('f')), + ] + ); + assert_eq!(runtime.list.jump_top, vec![key_hint::plain(KeyCode::Home)]); + assert_eq!( + runtime.list.jump_bottom, + vec![key_hint::plain(KeyCode::End)] + ); + } + + #[test] + fn configured_legacy_list_bindings_prune_new_default_overlaps() { + let mut keymap = TuiKeymap::default(); + keymap.list.move_up = Some(one("page-up")); + keymap.list.move_down = Some(one("page-down")); + + let runtime = RuntimeKeymap::from_config(&keymap).expect("config should parse"); + + assert_eq!(runtime.list.move_up, vec![key_hint::plain(KeyCode::PageUp)]); + assert_eq!( + runtime.list.move_down, + vec![key_hint::plain(KeyCode::PageDown)] + ); + assert_eq!( + runtime.list.page_up, + vec![key_hint::ctrl(KeyCode::Char('b'))] + ); + assert_eq!( + runtime.list.page_down, + vec![key_hint::ctrl(KeyCode::Char('f'))] + ); + } + + #[test] + fn configured_legacy_list_bindings_can_prune_all_new_default_keys() { + let mut keymap = TuiKeymap::default(); + keymap.list.move_up = Some(KeybindingsSpec::Many(vec![ + KeybindingSpec("page-up".to_string()), + KeybindingSpec("ctrl-b".to_string()), + ])); + + let runtime = RuntimeKeymap::from_config(&keymap).expect("config should parse"); + + assert_eq!( + runtime.list.move_up, + vec![ + key_hint::plain(KeyCode::PageUp), + key_hint::ctrl(KeyCode::Char('b')), + ] + ); + assert_eq!(runtime.list.page_up, Vec::new()); + } + + #[test] + fn explicit_new_list_bindings_still_conflict_with_legacy_bindings() { + let mut keymap = TuiKeymap::default(); + keymap.list.move_up = Some(one("page-up")); + keymap.list.page_up = Some(one("page-up")); + + expect_conflict(&keymap, "move_up", "page_up"); + } + + #[test] + fn configured_app_bindings_prune_new_list_default_overlaps() { + let mut keymap = TuiKeymap::default(); + keymap.global.copy = Some(one("page-down")); + + let runtime = RuntimeKeymap::from_config(&keymap).expect("config should parse"); + + assert_eq!(runtime.app.copy, vec![key_hint::plain(KeyCode::PageDown)]); + assert_eq!( + runtime.list.page_down, + vec![key_hint::ctrl(KeyCode::Char('f'))] + ); + } + + #[test] + fn configured_approval_bindings_prune_new_list_default_overlaps() { + let mut keymap = TuiKeymap::default(); + keymap.approval.approve = Some(one("home")); + + let runtime = RuntimeKeymap::from_config(&keymap).expect("config should parse"); + + assert_eq!( + runtime.approval.approve, + vec![key_hint::plain(KeyCode::Home)] + ); + assert_eq!(runtime.list.jump_top, Vec::new()); + } + + #[test] + fn explicit_new_list_bindings_still_conflict_with_configured_approval_bindings() { + let mut keymap = TuiKeymap::default(); + keymap.approval.approve = Some(one("home")); + keymap.list.jump_top = Some(one("home")); + + expect_conflict(&keymap, "list.jump_top", "approval.approve"); + } + #[test] fn vim_normal_defaults_include_insert_and_arrow_aliases() { let runtime = RuntimeKeymap::defaults(); @@ -1734,6 +2041,21 @@ mod tests { keymap.list.move_down = Some(one("up")); expect_conflict(&keymap, "move_up", "move_down"); + + let mut keymap = TuiKeymap::default(); + keymap.list.move_left = Some(one("left")); + keymap.list.move_right = Some(one("left")); + + expect_conflict(&keymap, "move_left", "move_right"); + } + + #[test] + fn rejects_conflicting_list_page_and_jump_bindings() { + let mut keymap = TuiKeymap::default(); + keymap.list.page_up = Some(one("home")); + keymap.list.jump_top = Some(one("home")); + + expect_conflict(&keymap, "page_up", "jump_top"); } #[test] diff --git a/codex-rs/tui/src/keymap_setup/actions.rs b/codex-rs/tui/src/keymap_setup/actions.rs index 8e11c55377..9ce827b8a9 100644 --- a/codex-rs/tui/src/keymap_setup/actions.rs +++ b/codex-rs/tui/src/keymap_setup/actions.rs @@ -164,6 +164,12 @@ pub(super) const KEYMAP_ACTIONS: &[KeymapActionDescriptor] = &[ action("pager", "Pager", "close_transcript", "Close the transcript overlay."), action("list", "List", "move_up", "Move list selection up."), action("list", "List", "move_down", "Move list selection down."), + action("list", "List", "move_left", "Move horizontally left in list pickers."), + action("list", "List", "move_right", "Move horizontally right in list pickers."), + action("list", "List", "page_up", "Move list selection up by one page."), + action("list", "List", "page_down", "Move list selection down by one page."), + action("list", "List", "jump_top", "Jump to the first list item."), + action("list", "List", "jump_bottom", "Jump to the last list item."), action("list", "List", "accept", "Accept the current list selection."), action("list", "List", "cancel", "Cancel and close selection views."), action("approval", "Approval", "open_fullscreen", "Open approval details fullscreen."), @@ -286,6 +292,12 @@ pub(super) fn binding_slot<'a>( ("pager", "close_transcript") => Some(&mut keymap.pager.close_transcript), ("list", "move_up") => Some(&mut keymap.list.move_up), ("list", "move_down") => Some(&mut keymap.list.move_down), + ("list", "move_left") => Some(&mut keymap.list.move_left), + ("list", "move_right") => Some(&mut keymap.list.move_right), + ("list", "page_up") => Some(&mut keymap.list.page_up), + ("list", "page_down") => Some(&mut keymap.list.page_down), + ("list", "jump_top") => Some(&mut keymap.list.jump_top), + ("list", "jump_bottom") => Some(&mut keymap.list.jump_bottom), ("list", "accept") => Some(&mut keymap.list.accept), ("list", "cancel") => Some(&mut keymap.list.cancel), ("approval", "open_fullscreen") => Some(&mut keymap.approval.open_fullscreen), @@ -390,6 +402,12 @@ pub(super) fn bindings_for_action<'a>( ("pager", "close_transcript") => Some(runtime_keymap.pager.close_transcript.as_slice()), ("list", "move_up") => Some(runtime_keymap.list.move_up.as_slice()), ("list", "move_down") => Some(runtime_keymap.list.move_down.as_slice()), + ("list", "move_left") => Some(runtime_keymap.list.move_left.as_slice()), + ("list", "move_right") => Some(runtime_keymap.list.move_right.as_slice()), + ("list", "page_up") => Some(runtime_keymap.list.page_up.as_slice()), + ("list", "page_down") => Some(runtime_keymap.list.page_down.as_slice()), + ("list", "jump_top") => Some(runtime_keymap.list.jump_top.as_slice()), + ("list", "jump_bottom") => Some(runtime_keymap.list.jump_bottom.as_slice()), ("list", "accept") => Some(runtime_keymap.list.accept.as_slice()), ("list", "cancel") => Some(runtime_keymap.list.cancel.as_slice()), ("approval", "open_fullscreen") => Some(runtime_keymap.approval.open_fullscreen.as_slice()), diff --git a/codex-rs/tui/src/oss_selection.rs b/codex-rs/tui/src/oss_selection.rs index 5396f061c6..ab9176ffbe 100644 --- a/codex-rs/tui/src/oss_selection.rs +++ b/codex-rs/tui/src/oss_selection.rs @@ -1,6 +1,9 @@ use std::io; use std::sync::LazyLock; +use crate::key_hint; +use crate::key_hint::KeyBinding; +use crate::key_hint::KeyBindingListExt; use crate::legacy_core::config::set_default_oss_provider; use codex_model_provider_info::DEFAULT_LMSTUDIO_PORT; use codex_model_provider_info::DEFAULT_OLLAMA_PORT; @@ -10,6 +13,7 @@ use crossterm::event::Event; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; +use crossterm::event::KeyModifiers; use crossterm::event::{self}; use crossterm::execute; use crossterm::terminal::EnterAlternateScreen; @@ -77,6 +81,18 @@ static OSS_SELECT_OPTIONS: LazyLock> = LazyLock::new(|| { ] }); +// This startup wizard runs before the main TUI runtime keymap is available, so +// it mirrors the built-in horizontal list defaults instead of reading config. +// The shared matcher still covers raw C0 Ctrl-H/Ctrl-L terminal reports. +const MOVE_LEFT_KEYS: [KeyBinding; 2] = [ + key_hint::plain(KeyCode::Left), + key_hint::ctrl(KeyCode::Char('h')), +]; +const MOVE_RIGHT_KEYS: [KeyBinding; 2] = [ + key_hint::plain(KeyCode::Right), + key_hint::ctrl(KeyCode::Char('l')), +]; + pub struct OssSelectionWidget<'a> { select_options: &'a Vec, confirmation_prompt: Paragraph<'a>, @@ -178,29 +194,35 @@ impl OssSelectionWidget<'_> { } fn handle_select_key(&mut self, key_event: KeyEvent) { - match key_event.code { - KeyCode::Char('c') - if key_event - .modifiers - .contains(crossterm::event::KeyModifiers::CONTROL) => - { + match key_event { + KeyEvent { + code: KeyCode::Char('c'), + modifiers, + .. + } if modifiers.contains(KeyModifiers::CONTROL) => { self.send_decision("__CANCELLED__".to_string()); } - KeyCode::Left => { + _ if MOVE_LEFT_KEYS.is_pressed(key_event) => { self.selected_option = (self.selected_option + self.select_options.len() - 1) % self.select_options.len(); } - KeyCode::Right => { + _ if MOVE_RIGHT_KEYS.is_pressed(key_event) => { self.selected_option = (self.selected_option + 1) % self.select_options.len(); } - KeyCode::Enter => { + KeyEvent { + code: KeyCode::Enter, + .. + } => { let opt = &self.select_options[self.selected_option]; self.send_decision(opt.provider_id.to_string()); } - KeyCode::Esc => { + KeyEvent { + code: KeyCode::Esc, .. + } => { self.send_decision(LMSTUDIO_OSS_PROVIDER_ID.to_string()); } - other => { + KeyEvent { code, .. } => { + let other = code; let normalized = Self::normalize_keycode(other); if let Some(opt) = self .select_options @@ -371,3 +393,20 @@ async fn check_port_status(port: u16) -> io::Result { Err(_) => Ok(false), // Connection failed = not running } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ctrl_h_l_move_provider_selection() { + let mut widget = OssSelectionWidget::new(ProviderStatus::Unknown, ProviderStatus::Unknown) + .expect("widget should initialize"); + + assert_eq!(widget.selected_option, 0); + widget.handle_key_event(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)); + assert_eq!(widget.selected_option, 1); + widget.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL)); + assert_eq!(widget.selected_option, 0); + } +} diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 5d5e888390..527c84a8e2 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -10,6 +10,9 @@ use crate::app_server_session::AppServerSession; use crate::color::blend; use crate::color::is_light; use crate::git_action_directives::parse_assistant_markdown; +use crate::key_hint::KeyBindingListExt; +use crate::key_hint::is_plain_text_key_event; +use crate::keymap::ListKeymap; use crate::keymap::PagerKeymap; use crate::keymap::RuntimeKeymap; use crate::legacy_core::config::Config; @@ -282,6 +285,7 @@ struct SessionPickerRunOptions { initial_density: SessionListDensity, view_persistence: Option, pager_keymap: PagerKeymap, + list_keymap: ListKeymap, } /// Interactive session picker that lists app-server threads with simple search, @@ -354,7 +358,7 @@ async fn run_resume_picker_with_launch_context( ); let local_filter_cwd = local_picker_cwd_filter(&cwd_filter, is_remote); let provider_filter = picker_provider_filter(config, is_remote); - let pager_keymap = picker_pager_keymap(config)?; + let runtime_keymap = picker_runtime_keymap(config)?; let options = SessionPickerRunOptions { show_all, filter_cwd: cwd_filter, @@ -367,7 +371,8 @@ async fn run_resume_picker_with_launch_context( codex_home: config.codex_home.to_path_buf(), active_profile: config.active_profile.clone(), }), - pager_keymap, + pager_keymap: runtime_keymap.pager, + list_keymap: runtime_keymap.list, }; run_session_picker_with_loader( tui, @@ -399,7 +404,7 @@ pub async fn run_fork_picker_with_app_server( ); let local_filter_cwd = local_picker_cwd_filter(&cwd_filter, is_remote); let provider_filter = picker_provider_filter(config, is_remote); - let pager_keymap = picker_pager_keymap(config)?; + let runtime_keymap = picker_runtime_keymap(config)?; let options = SessionPickerRunOptions { show_all, filter_cwd: cwd_filter, @@ -412,7 +417,8 @@ pub async fn run_fork_picker_with_app_server( codex_home: config.codex_home.to_path_buf(), active_profile: config.active_profile.clone(), }), - pager_keymap, + pager_keymap: runtime_keymap.pager, + list_keymap: runtime_keymap.list, }; run_session_picker_with_loader( tui, @@ -447,6 +453,7 @@ async fn run_session_picker_with_loader( state.density = options.initial_density; state.view_persistence = options.view_persistence; state.pager_keymap = options.pager_keymap; + state.list_keymap = options.list_keymap; state.launch_context = options.launch_context; state.start_initial_load(); state.request_frame(); @@ -516,9 +523,8 @@ fn picker_provider_filter(config: &Config, is_remote: bool) -> ProviderFilter { } } -fn picker_pager_keymap(config: &Config) -> Result { +fn picker_runtime_keymap(config: &Config) -> Result { RuntimeKeymap::from_config(&config.tui_keymap) - .map(|keymap| keymap.pager) .map_err(|err| color_eyre::eyre::eyre!("invalid keymap configuration: {err}")) } @@ -656,6 +662,7 @@ struct PickerState { transcript_loading_frame_shown: bool, overlay: Option, pager_keymap: PagerKeymap, + list_keymap: ListKeymap, } struct PaginationState { @@ -928,6 +935,7 @@ impl PickerState { transcript_loading_frame_shown: false, overlay: None, pager_keymap: RuntimeKeymap::defaults().pager, + list_keymap: RuntimeKeymap::defaults().list, } } @@ -1028,18 +1036,14 @@ impl PickerState { if self.is_transcript_loading() { return Ok(self.handle_transcript_loading_key(key)); } - if !matches!(key.code, KeyCode::PageDown) { + if !self.list_keymap.page_down.is_pressed(key) { self.pending_page_down_target = None; } + // The session picker is always searchable, so plain text belongs to + // the query first. Modified list bindings still route through the + // runtime keymap below. + let allow_plain_char_navigation = !is_plain_text_key_event(key); match key { - KeyEvent { - code: KeyCode::Esc, .. - } => { - if self.query.is_empty() { - return Ok(Some(SessionSelection::StartFresh)); - } - self.clear_query_preserving_selection(); - } KeyEvent { code: KeyCode::Char('c'), modifiers, @@ -1047,6 +1051,12 @@ impl PickerState { } if modifiers.contains(KeyModifiers::CONTROL) => { return Ok(Some(SessionSelection::Exit)); } + _ if self.list_keymap.cancel.is_pressed(key) => { + if self.query.is_empty() { + return Ok(Some(SessionSelection::StartFresh)); + } + self.clear_query_preserving_selection(); + } KeyEvent { code: KeyCode::Char('t'), modifiers, @@ -1089,10 +1099,7 @@ impl PickerState { } /* ^O */ => { self.toggle_density().await; } - KeyEvent { - code: KeyCode::Enter, - .. - } => { + _ if self.list_keymap.accept.is_pressed(key) => { if let Some(row) = self.filtered_rows.get(self.selected) { let path = row.path.clone(); let thread_id = match row.thread_id { @@ -1119,39 +1126,14 @@ impl PickerState { self.request_frame(); } } - KeyEvent { - code: KeyCode::Up, .. - } - | KeyEvent { - code: KeyCode::Char('p'), - modifiers: KeyModifiers::CONTROL, - .. - } - | KeyEvent { - code: KeyCode::Char('\u{0010}'), - modifiers: KeyModifiers::NONE, - .. - } /* ^P */ => { + _ if allow_plain_char_navigation && self.list_keymap.move_up.is_pressed(key) => { if self.selected > 0 { self.selected -= 1; self.ensure_selected_visible(); } self.request_frame(); } - KeyEvent { - code: KeyCode::Down, - .. - } - | KeyEvent { - code: KeyCode::Char('n'), - modifiers: KeyModifiers::CONTROL, - .. - } - | KeyEvent { - code: KeyCode::Char('\u{000e}'), - modifiers: KeyModifiers::NONE, - .. - } /* ^N */ => { + _ if allow_plain_char_navigation && self.list_keymap.move_down.is_pressed(key) => { if self.selected + 1 < self.filtered_rows.len() { self.selected += 1; self.ensure_selected_visible(); @@ -1159,10 +1141,7 @@ impl PickerState { self.maybe_load_more_for_scroll(); self.request_frame(); } - KeyEvent { - code: KeyCode::PageUp, - .. - } => { + _ if allow_plain_char_navigation && self.list_keymap.page_up.is_pressed(key) => { let step = self.view_rows.unwrap_or(10).max(1); if self.selected > 0 { self.selected = self.selected.saturating_sub(step); @@ -1170,19 +1149,14 @@ impl PickerState { self.request_frame(); } } - KeyEvent { - code: KeyCode::Home, - .. - } => { + _ if allow_plain_char_navigation && self.list_keymap.jump_top.is_pressed(key) => { if !self.filtered_rows.is_empty() { self.selected = 0; self.ensure_selected_visible(); self.request_frame(); } } - KeyEvent { - code: KeyCode::End, .. - } => { + _ if allow_plain_char_navigation && self.list_keymap.jump_bottom.is_pressed(key) => { if !self.filtered_rows.is_empty() { self.selected = self.filtered_rows.len().saturating_sub(1); self.ensure_selected_visible(); @@ -1190,10 +1164,7 @@ impl PickerState { self.request_frame(); } } - KeyEvent { - code: KeyCode::PageDown, - .. - } => { + _ if allow_plain_char_navigation && self.list_keymap.page_down.is_pressed(key) => { if !self.filtered_rows.is_empty() { let step = self.view_rows.unwrap_or(10).max(1); let target = self.selected.saturating_add(step); @@ -1222,14 +1193,10 @@ impl PickerState { self.focus_previous_toolbar_control(); self.request_frame(); } - KeyEvent { - code: KeyCode::Left, - .. - } - | KeyEvent { - code: KeyCode::Right, - .. - } => { + _ if allow_plain_char_navigation + && (self.list_keymap.move_left.is_pressed(key) + || self.list_keymap.move_right.is_pressed(key)) => + { self.change_focused_toolbar_value(); self.request_frame(); } @@ -5382,7 +5349,7 @@ session_picker_view = "dense" .await .unwrap(); state - .handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)) + .handle_key(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)) .await .unwrap(); @@ -5554,6 +5521,89 @@ session_picker_view = "dense" assert_eq!(state.selected, 0); } + #[tokio::test] + async fn page_and_jump_navigation_use_list_keymap() { + let loader = page_only_loader(|_| {}); + let mut state = PickerState::new( + FrameRequester::test_dummy(), + loader, + ProviderFilter::MatchDefault(String::from("openai")), + /*show_all*/ true, + /*filter_cwd*/ None, + SessionPickerAction::Resume, + ); + state.list_keymap.page_down = vec![crate::key_hint::ctrl(KeyCode::Char('d'))]; + state.list_keymap.page_up = vec![crate::key_hint::ctrl(KeyCode::Char('u'))]; + state.list_keymap.jump_bottom = vec![crate::key_hint::ctrl(KeyCode::Char('y'))]; + state.list_keymap.jump_top = vec![crate::key_hint::ctrl(KeyCode::Char('a'))]; + + let mut items = Vec::new(); + for idx in 0..20 { + let ts = format!("2025-01-{:02}T00:00:00Z", idx + 1); + let preview = format!("item-{idx}"); + let path = format!("/tmp/item-{idx}.jsonl"); + items.push(make_row(&path, &ts, &preview)); + } + + state.reset_pagination(); + state.ingest_page(page( + items, /*next_cursor*/ None, /*num_scanned_files*/ 20, + /*reached_scan_cap*/ false, + )); + state.update_viewport(/*rows*/ 5, /*width*/ 80); + + state + .handle_key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE)) + .await + .unwrap(); + assert_eq!(state.selected, 0); + + state + .handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)) + .await + .unwrap(); + assert_eq!(state.selected, 5); + + state + .handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)) + .await + .unwrap(); + assert_eq!(state.selected, 0); + + state + .handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)) + .await + .unwrap(); + assert_eq!(state.selected, 19); + + state + .handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL)) + .await + .unwrap(); + assert_eq!(state.selected, 0); + } + + #[tokio::test] + async fn ctrl_c_exits_even_when_cancel_is_remapped_to_ctrl_c() { + let loader = page_only_loader(|_| {}); + let mut state = PickerState::new( + FrameRequester::test_dummy(), + loader, + ProviderFilter::MatchDefault(String::from("openai")), + /*show_all*/ true, + /*filter_cwd*/ None, + SessionPickerAction::Resume, + ); + state.list_keymap.cancel = vec![crate::key_hint::ctrl(KeyCode::Char('c'))]; + + let selection = state + .handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)) + .await + .unwrap(); + + assert!(matches!(selection, Some(SessionSelection::Exit))); + } + #[tokio::test] async fn end_jumps_to_last_known_row_and_starts_loading_more() { let recorded_requests: Arc>> = Arc::new(Mutex::new(Vec::new())); diff --git a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_custom.snap b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_custom.snap index f58386a8d5..898108c755 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_custom.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_custom.snap @@ -5,7 +5,7 @@ expression: "render_picker(params, 120)" Keymap All configurable shortcuts. - 87 actions, 1 customized, 2 unbound. + 93 actions, 1 customized, 2 unbound. [All] Common Customized (1) Unbound (2) App Composer Editor Vim Navigation Approval Debug diff --git a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_fast_mode_enabled.snap b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_fast_mode_enabled.snap index 1c247951fd..4d9440cb4e 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_fast_mode_enabled.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_fast_mode_enabled.snap @@ -5,7 +5,7 @@ expression: "render_picker(params, 120)" Keymap All configurable shortcuts. - 88 actions, 0 customized, 3 unbound. + 94 actions, 0 customized, 3 unbound. [All] Common Customized (0) Unbound (3) App Composer Editor Vim Navigation Approval Debug diff --git a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_first_actions.snap b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_first_actions.snap index e094edad97..58b1b80803 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_first_actions.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_first_actions.snap @@ -2,7 +2,7 @@ source: tui/src/keymap_setup.rs expression: snapshot --- -tab: All (87 selectable) +tab: All (93 selectable) tab: Common (19 selectable) tab: Customized (0) (0 selectable) tab: Unbound (2) (2 selectable) @@ -10,7 +10,7 @@ tab: App (9 selectable) tab: Composer (5 selectable) tab: Editor (17 selectable) tab: Vim (34 selectable) -tab: Navigation (14 selectable) +tab: Navigation (20 selectable) tab: Approval (8 selectable) tab: Debug (1 selectable) Open Transcript | ctrl-t | Global open_transcript Open Transcript Open the transcript overlay. ctrl-t Default diff --git a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_narrow.snap b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_narrow.snap index f146c7eed1..6a98da9238 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_narrow.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_narrow.snap @@ -5,7 +5,7 @@ expression: "render_picker(params, 78)" Keymap All configurable shortcuts. - 87 actions, 0 customized, 2 unbound. + 93 actions, 0 customized, 2 unbound. [All] Common Customized (0) Unbound (2) App Composer Editor Vim Navigation Approval Debug diff --git a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_wide.snap b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_wide.snap index c9b8be80fd..9d651ee4f0 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_wide.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__keymap_setup__tests__keymap_picker_wide.snap @@ -5,7 +5,7 @@ expression: "render_picker(params, 120)" Keymap All configurable shortcuts. - 87 actions, 0 customized, 2 unbound. + 93 actions, 0 customized, 2 unbound. [All] Common Customized (0) Unbound (2) App Composer Editor Vim Navigation Approval Debug From 2edae8d858509bdf82930335e27877c7b04aa492 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 13 May 2026 17:39:50 +0200 Subject: [PATCH 12/13] refactor: split memories extension crate modules (#22500) ## Why The memories extension has several distinct responsibilities: registering its prompt and tool contributors, enforcing local-memory filesystem boundaries, implementing list/read/search behavior, and wrapping that backend as extension tools. Those responsibilities were concentrated in `lib.rs`, `local.rs`, and the tool modules, which made follow-up work harder to review and risked growing files through unrelated edits. This PR reorganizes the crate so each responsibility has a narrower owner while preserving the same extension entrypoint and memory tool behavior. ## What Changed - Moved extension lifecycle, prompt, and tool registration into `src/extension.rs`, leaving `src/lib.rs` as the small crate entrypoint. - Split `LocalMemoriesBackend` helpers into `local/list.rs`, `local/path.rs`, `local/read.rs`, and `local/search.rs`. - Centralized tool names and limits at the crate level, and kept the backend and extension implementation crate-private. - Made `memory_list`, `memory_read`, and `memory_search` tool executors generic over `MemoriesBackend`, so tests can exercise the full executor path without depending on tool internals. - Consolidated and expanded memory extension tests in `src/tests.rs`, including read/search tool output coverage, multi-query search, windowed `all_within_lines`, and legacy `query` rejection. ## Testing - Not run locally. --- codex-rs/ext/memories/src/backend.rs | 6 - codex-rs/ext/memories/src/extension.rs | 84 ++++ codex-rs/ext/memories/src/lib.rs | 194 +------- codex-rs/ext/memories/src/local.rs | 551 ++-------------------- codex-rs/ext/memories/src/local/list.rs | 83 ++++ codex-rs/ext/memories/src/local/path.rs | 56 +++ codex-rs/ext/memories/src/local/read.rs | 90 ++++ codex-rs/ext/memories/src/local/search.rs | 336 +++++++++++++ codex-rs/ext/memories/src/tests.rs | 311 ++++++++++++ codex-rs/ext/memories/src/tools/list.rs | 16 +- codex-rs/ext/memories/src/tools/mod.rs | 11 +- codex-rs/ext/memories/src/tools/read.rs | 69 +-- codex-rs/ext/memories/src/tools/search.rs | 88 +--- 13 files changed, 1029 insertions(+), 866 deletions(-) create mode 100644 codex-rs/ext/memories/src/extension.rs create mode 100644 codex-rs/ext/memories/src/local/list.rs create mode 100644 codex-rs/ext/memories/src/local/path.rs create mode 100644 codex-rs/ext/memories/src/local/read.rs create mode 100644 codex-rs/ext/memories/src/local/search.rs create mode 100644 codex-rs/ext/memories/src/tests.rs diff --git a/codex-rs/ext/memories/src/backend.rs b/codex-rs/ext/memories/src/backend.rs index 929852f1b1..fa635c8302 100644 --- a/codex-rs/ext/memories/src/backend.rs +++ b/codex-rs/ext/memories/src/backend.rs @@ -3,12 +3,6 @@ use serde::Deserialize; use serde::Serialize; use std::future::Future; -pub const DEFAULT_LIST_MAX_RESULTS: usize = 2_000; -pub const MAX_LIST_RESULTS: usize = 2_000; -pub const DEFAULT_SEARCH_MAX_RESULTS: usize = 200; -pub const MAX_SEARCH_RESULTS: usize = 200; -pub const DEFAULT_READ_MAX_TOKENS: usize = 20_000; - /// Storage interface behind the memories MCP tools. /// /// Implementations should return paths relative to the memory store and enforce diff --git a/codex-rs/ext/memories/src/extension.rs b/codex-rs/ext/memories/src/extension.rs new file mode 100644 index 0000000000..2b49559183 --- /dev/null +++ b/codex-rs/ext/memories/src/extension.rs @@ -0,0 +1,84 @@ +use std::sync::Arc; + +use codex_core::config::Config; +use codex_extension_api::ContextContributor; +use codex_extension_api::ExtensionData; +use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::PromptFragment; +use codex_extension_api::ThreadLifecycleContributor; +use codex_extension_api::ThreadStartInput; +use codex_extension_api::ToolContributor; +use codex_features::Feature; +use codex_memories_read::build_memory_tool_developer_instructions; +use codex_utils_absolute_path::AbsolutePathBuf; + +use crate::local::LocalMemoriesBackend; +use crate::tools; + +/// Contributes Codex memory read-path prompt context and memory read tools. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct MemoriesExtension; + +#[derive(Clone, Debug)] +pub(crate) struct MemoriesExtensionConfig { + pub(crate) enabled: bool, + pub(crate) codex_home: AbsolutePathBuf, +} + +impl ContextContributor for MemoriesExtension { + fn contribute<'a>( + &'a self, + _session_store: &'a ExtensionData, + thread_store: &'a ExtensionData, + ) -> std::pin::Pin> + Send + 'a>> { + Box::pin(async move { + let Some(config) = thread_store.get::() else { + return Vec::new(); + }; + if !config.enabled { + return Vec::new(); + } + + build_memory_tool_developer_instructions(&config.codex_home) + .await + .map(PromptFragment::developer_policy) + .into_iter() + .collect() + }) + } +} + +impl ThreadLifecycleContributor for MemoriesExtension { + fn on_thread_start(&self, input: ThreadStartInput<'_, Config>) { + input.thread_store.insert(MemoriesExtensionConfig { + enabled: input.config.features.enabled(Feature::MemoryTool) + && input.config.memories.use_memories, + codex_home: input.config.codex_home.clone(), + }); + } +} + +impl ToolContributor for MemoriesExtension { + fn tools( + &self, + _session_store: &ExtensionData, + thread_store: &ExtensionData, + ) -> Vec> { + let Some(config) = thread_store.get::() else { + return Vec::new(); + }; + if !config.enabled { + return Vec::new(); + } + + tools::memory_tools(LocalMemoriesBackend::from_codex_home(&config.codex_home)) + } +} + +/// Installs the memories extension contributors into the extension registry. +pub fn install(registry: &mut ExtensionRegistryBuilder) { + let extension = Arc::new(MemoriesExtension); + registry.thread_lifecycle_contributor(extension.clone()); + registry.prompt_contributor(extension.clone()); + registry.tool_contributor(extension); +} diff --git a/codex-rs/ext/memories/src/lib.rs b/codex-rs/ext/memories/src/lib.rs index 41143bef0f..4b6f74c571 100644 --- a/codex-rs/ext/memories/src/lib.rs +++ b/codex-rs/ext/memories/src/lib.rs @@ -1,192 +1,20 @@ -use std::sync::Arc; - -use codex_core::config::Config; -use codex_extension_api::ContextContributor; -use codex_extension_api::ExtensionData; -use codex_extension_api::ExtensionRegistryBuilder; -use codex_extension_api::PromptFragment; -use codex_extension_api::ThreadLifecycleContributor; -use codex_extension_api::ThreadStartInput; -use codex_extension_api::ToolContributor; -use codex_features::Feature; -use codex_memories_read::build_memory_tool_developer_instructions; -use codex_utils_absolute_path::AbsolutePathBuf; - mod backend; +mod extension; mod local; mod schema; mod tools; -use local::LocalMemoriesBackend; +pub use extension::install; -/// Contributes Codex memory read-path prompt context and memory read tools. -#[derive(Clone, Copy, Debug, Default)] -pub struct MemoriesExtension; +pub(crate) const DEFAULT_LIST_MAX_RESULTS: usize = 2_000; +pub(crate) const MAX_LIST_RESULTS: usize = 2_000; +pub(crate) const DEFAULT_SEARCH_MAX_RESULTS: usize = 200; +pub(crate) const MAX_SEARCH_RESULTS: usize = 200; +pub(crate) const DEFAULT_READ_MAX_TOKENS: usize = 20_000; -#[derive(Clone, Debug)] -struct MemoriesExtensionConfig { - enabled: bool, - codex_home: AbsolutePathBuf, -} - -impl ContextContributor for MemoriesExtension { - fn contribute<'a>( - &'a self, - _session_store: &'a ExtensionData, - thread_store: &'a ExtensionData, - ) -> std::pin::Pin> + Send + 'a>> { - Box::pin(async move { - let Some(config) = thread_store.get::() else { - return Vec::new(); - }; - if !config.enabled { - return Vec::new(); - } - - build_memory_tool_developer_instructions(&config.codex_home) - .await - .map(PromptFragment::developer_policy) - .into_iter() - .collect() - }) - } -} - -impl ThreadLifecycleContributor for MemoriesExtension { - fn on_thread_start(&self, input: ThreadStartInput<'_, Config>) { - input.thread_store.insert(MemoriesExtensionConfig { - enabled: input.config.features.enabled(Feature::MemoryTool) - && input.config.memories.use_memories, - codex_home: input.config.codex_home.clone(), - }); - } -} - -impl ToolContributor for MemoriesExtension { - fn tools( - &self, - _session_store: &ExtensionData, - thread_store: &ExtensionData, - ) -> Vec> { - let Some(config) = thread_store.get::() else { - return Vec::new(); - }; - if !config.enabled { - return Vec::new(); - } - - tools::memory_tools(LocalMemoriesBackend::from_codex_home(&config.codex_home)) - } -} - -/// Installs the memories extension contributors into the extension registry. -pub fn install(registry: &mut ExtensionRegistryBuilder) { - let extension = Arc::new(MemoriesExtension); - registry.thread_lifecycle_contributor(extension.clone()); - registry.prompt_contributor(extension.clone()); - registry.tool_contributor(extension); -} +pub(crate) const LIST_TOOL_NAME: &str = "memory_list"; +pub(crate) const READ_TOOL_NAME: &str = "memory_read"; +pub(crate) const SEARCH_TOOL_NAME: &str = "memory_search"; #[cfg(test)] -mod tests { - use codex_extension_api::ContextContributor; - use codex_extension_api::ExtensionData; - use codex_extension_api::PromptSlot; - use codex_extension_api::ToolContributor; - use codex_utils_absolute_path::test_support::PathBufExt; - use codex_utils_absolute_path::test_support::PathExt; - use codex_utils_absolute_path::test_support::test_path_buf; - use pretty_assertions::assert_eq; - - use super::MemoriesExtension; - use super::MemoriesExtensionConfig; - - #[test] - fn tools_are_not_contributed_without_thread_config() { - let extension = MemoriesExtension; - - assert!( - extension - .tools( - &ExtensionData::new("session"), - &ExtensionData::new("thread") - ) - .is_empty() - ); - } - - #[test] - fn tools_are_not_contributed_when_disabled() { - let extension = MemoriesExtension; - let thread_store = ExtensionData::new("thread"); - thread_store.insert(MemoriesExtensionConfig { - enabled: false, - codex_home: test_path_buf("/tmp/codex-home").abs(), - }); - - assert!( - extension - .tools(&ExtensionData::new("session"), &thread_store) - .is_empty() - ); - } - - #[test] - fn tools_are_contributed_when_enabled() { - let extension = MemoriesExtension; - let thread_store = ExtensionData::new("thread"); - thread_store.insert(MemoriesExtensionConfig { - enabled: true, - codex_home: test_path_buf("/tmp/codex-home").abs(), - }); - - let tool_names = extension - .tools(&ExtensionData::new("session"), &thread_store) - .into_iter() - .map(|tool| tool.tool_name().to_string()) - .collect::>(); - - assert_eq!( - tool_names, - vec![ - "memory_list".to_string(), - "memory_read".to_string(), - "memory_search".to_string() - ] - ); - } - - #[tokio::test] - async fn prompt_contribution_uses_memory_summary_when_enabled() { - let tempdir = tempfile::tempdir().expect("tempdir"); - let memories_dir = tempdir.path().join("memories"); - tokio::fs::create_dir_all(&memories_dir) - .await - .expect("create memories dir"); - tokio::fs::write( - memories_dir.join("memory_summary.md"), - "Remember repository-specific implementation preferences.", - ) - .await - .expect("write memory summary"); - - let extension = MemoriesExtension; - let thread_store = ExtensionData::new("thread"); - thread_store.insert(MemoriesExtensionConfig { - enabled: true, - codex_home: tempdir.path().abs(), - }); - - let fragments = extension - .contribute(&ExtensionData::new("session"), &thread_store) - .await; - - assert_eq!(fragments.len(), 1); - assert_eq!(fragments[0].slot(), PromptSlot::DeveloperPolicy); - assert!( - fragments[0] - .text() - .contains("Remember repository-specific implementation preferences.") - ); - } -} +mod tests; diff --git a/codex-rs/ext/memories/src/local.rs b/codex-rs/ext/memories/src/local.rs index 47c09b60d9..8c663d73fb 100644 --- a/codex-rs/ext/memories/src/local.rs +++ b/codex-rs/ext/memories/src/local.rs @@ -1,37 +1,34 @@ -use crate::backend::DEFAULT_READ_MAX_TOKENS; -use crate::backend::ListMemoriesRequest; -use crate::backend::ListMemoriesResponse; -use crate::backend::MAX_LIST_RESULTS; -use crate::backend::MAX_SEARCH_RESULTS; -use crate::backend::MemoriesBackend; -use crate::backend::MemoriesBackendError; -use crate::backend::MemoryEntry; -use crate::backend::MemoryEntryType; -use crate::backend::MemorySearchMatch; -use crate::backend::ReadMemoryRequest; -use crate::backend::ReadMemoryResponse; -use crate::backend::SearchMatchMode; -use crate::backend::SearchMemoriesRequest; -use crate::backend::SearchMemoriesResponse; -use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_output_truncation::TruncationPolicy; -use codex_utils_output_truncation::truncate_text; -use std::borrow::Cow; use std::path::Component; use std::path::Path; use std::path::PathBuf; +use codex_utils_absolute_path::AbsolutePathBuf; + +use crate::backend::ListMemoriesRequest; +use crate::backend::ListMemoriesResponse; +use crate::backend::MemoriesBackend; +use crate::backend::MemoriesBackendError; +use crate::backend::ReadMemoryRequest; +use crate::backend::ReadMemoryResponse; +use crate::backend::SearchMemoriesRequest; +use crate::backend::SearchMemoriesResponse; + +mod list; +mod path; +mod read; +mod search; + #[derive(Debug, Clone)] -pub struct LocalMemoriesBackend { +pub(crate) struct LocalMemoriesBackend { root: PathBuf, } impl LocalMemoriesBackend { - pub fn from_codex_home(codex_home: &AbsolutePathBuf) -> Self { + pub(crate) fn from_codex_home(codex_home: &AbsolutePathBuf) -> Self { Self::from_memory_root(codex_home.join("memories").to_path_buf()) } - pub fn from_memory_root(root: impl Into) -> Self { + pub(crate) fn from_memory_root(root: impl Into) -> Self { Self { root: root.into() } } @@ -54,7 +51,7 @@ impl LocalMemoriesBackend { "must stay within the memories root", )); } - if relative.components().any(is_hidden_component) { + if relative.components().any(path::is_hidden_component) { return Err(MemoriesBackendError::NotFound { path: relative_path.to_string(), }); @@ -72,7 +69,10 @@ impl LocalMemoriesBackend { return Ok(scoped_path); }; - reject_symlink(&display_relative_path(&self.root, &scoped_path), &metadata)?; + path::reject_symlink( + &path::display_relative_path(&self.root, &scoped_path), + &metadata, + )?; if idx + 1 < components.len() && !metadata.is_dir() { return Err(MemoriesBackendError::invalid_path( relative_path, @@ -100,517 +100,20 @@ impl MemoriesBackend for LocalMemoriesBackend { &self, request: ListMemoriesRequest, ) -> Result { - let max_results = request.max_results.min(MAX_LIST_RESULTS); - let start = self.resolve_scoped_path(request.path.as_deref()).await?; - let start_index = match request.cursor.as_deref() { - Some(cursor) => cursor.parse::().map_err(|_| { - MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer") - })?, - None => 0, - }; - let Some(metadata) = Self::metadata_or_none(&start).await? else { - return Err(MemoriesBackendError::NotFound { - path: request.path.unwrap_or_default(), - }); - }; - reject_symlink(&display_relative_path(&self.root, &start), &metadata)?; - - let mut entries = if metadata.is_file() { - vec![MemoryEntry { - path: display_relative_path(&self.root, &start), - entry_type: MemoryEntryType::File, - }] - } else if metadata.is_dir() { - let mut entries = Vec::new(); - for path in read_sorted_dir_paths(&start).await? { - if is_hidden_path(&path) { - continue; - } - let Some(metadata) = Self::metadata_or_none(&path).await? else { - continue; - }; - if metadata.file_type().is_symlink() { - continue; - } - - let entry_type = if metadata.is_dir() { - MemoryEntryType::Directory - } else if metadata.is_file() { - MemoryEntryType::File - } else { - continue; - }; - entries.push(MemoryEntry { - path: display_relative_path(&self.root, &path), - entry_type, - }); - } - entries - } else { - Vec::new() - }; - if start_index > entries.len() { - return Err(MemoriesBackendError::invalid_cursor( - start_index.to_string(), - "exceeds result count", - )); - } - - let end_index = start_index.saturating_add(max_results).min(entries.len()); - let next_cursor = (end_index < entries.len()).then(|| end_index.to_string()); - let truncated = next_cursor.is_some(); - Ok(ListMemoriesResponse { - path: request.path, - entries: entries.drain(start_index..end_index).collect(), - next_cursor, - truncated, - }) + list::list(self, request).await } async fn read( &self, request: ReadMemoryRequest, ) -> Result { - if request.line_offset == 0 { - return Err(MemoriesBackendError::InvalidLineOffset); - } - if request.max_lines == Some(0) { - return Err(MemoriesBackendError::InvalidMaxLines); - } - - let path = self - .resolve_scoped_path(Some(request.path.as_str())) - .await?; - let Some(metadata) = Self::metadata_or_none(&path).await? else { - return Err(MemoriesBackendError::NotFound { path: request.path }); - }; - reject_symlink(&request.path, &metadata)?; - if !metadata.is_file() { - return Err(MemoriesBackendError::NotFile { path: request.path }); - } - - let original_content = tokio::fs::read_to_string(&path).await?; - let start_byte = line_start_byte_offset(&original_content, request.line_offset)?; - let end_byte = line_end_byte_offset(&original_content, start_byte, request.max_lines); - let content_from_offset = &original_content[start_byte..end_byte]; - let max_tokens = if request.max_tokens == 0 { - DEFAULT_READ_MAX_TOKENS - } else { - request.max_tokens - }; - let content = truncate_text(content_from_offset, TruncationPolicy::Tokens(max_tokens)); - let truncated = end_byte < original_content.len() || content != content_from_offset; - Ok(ReadMemoryResponse { - path: request.path, - start_line_number: request.line_offset, - content, - truncated, - }) + read::read(self, request).await } async fn search( &self, request: SearchMemoriesRequest, ) -> Result { - let queries = request - .queries - .iter() - .map(|query| query.trim().to_string()) - .collect::>(); - if queries.is_empty() || queries.iter().any(std::string::String::is_empty) { - return Err(MemoriesBackendError::EmptyQuery); - } - if matches!( - request.match_mode, - SearchMatchMode::AllWithinLines { line_count: 0 } - ) { - return Err(MemoriesBackendError::InvalidMatchWindow); - } - - let max_results = request.max_results.min(MAX_SEARCH_RESULTS); - let start = self.resolve_scoped_path(request.path.as_deref()).await?; - let start_index = match request.cursor.as_deref() { - Some(cursor) => cursor.parse::().map_err(|_| { - MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer") - })?, - None => 0, - }; - let Some(metadata) = Self::metadata_or_none(&start).await? else { - return Err(MemoriesBackendError::NotFound { - path: request.path.unwrap_or_default(), - }); - }; - reject_symlink(&display_relative_path(&self.root, &start), &metadata)?; - - let matcher = SearchMatcher::new( - queries.clone(), - request.match_mode.clone(), - request.case_sensitive, - request.normalized, - )?; - let mut matches = Vec::new(); - search_entries( - &self.root, - &start, - &metadata, - &matcher, - request.context_lines, - &mut matches, - ) - .await?; - matches.sort_by(|left, right| { - left.path - .cmp(&right.path) - .then(left.match_line_number.cmp(&right.match_line_number)) - }); - if start_index > matches.len() { - return Err(MemoriesBackendError::invalid_cursor( - start_index.to_string(), - "exceeds result count", - )); - } - let end_index = start_index.saturating_add(max_results).min(matches.len()); - let next_cursor = (end_index < matches.len()).then(|| end_index.to_string()); - let truncated = next_cursor.is_some(); - Ok(SearchMemoriesResponse { - queries, - match_mode: request.match_mode, - path: request.path, - matches: matches.drain(start_index..end_index).collect(), - next_cursor, - truncated, - }) + search::search(self, request).await } } - -async fn search_entries( - root: &Path, - current: &Path, - current_metadata: &std::fs::Metadata, - matcher: &SearchMatcher, - context_lines: usize, - matches: &mut Vec, -) -> Result<(), MemoriesBackendError> { - if current_metadata.is_file() { - search_file(root, current, matcher, context_lines, matches).await?; - return Ok(()); - } - if !current_metadata.is_dir() { - return Ok(()); - } - - let mut pending = vec![current.to_path_buf()]; - while let Some(dir_path) = pending.pop() { - for path in read_sorted_dir_paths(&dir_path).await? { - if is_hidden_path(&path) { - continue; - } - let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else { - continue; - }; - if metadata.file_type().is_symlink() { - continue; - } - if metadata.is_dir() { - pending.push(path); - } else if metadata.is_file() { - search_file(root, &path, matcher, context_lines, matches).await?; - } - } - } - - Ok(()) -} - -async fn search_file( - root: &Path, - path: &Path, - matcher: &SearchMatcher, - context_lines: usize, - matches: &mut Vec, -) -> Result<(), MemoriesBackendError> { - let content = match tokio::fs::read_to_string(path).await { - Ok(content) => content, - Err(err) if err.kind() == std::io::ErrorKind::InvalidData => return Ok(()), - Err(err) => return Err(err.into()), - }; - let lines = content.lines().collect::>(); - let line_matches = lines - .iter() - .map(|line| matcher.matched_query_flags(line)) - .collect::>(); - match &matcher.match_mode { - SearchMatchMode::Any => { - for (idx, matched_query_flags) in line_matches.iter().enumerate() { - if matched_query_flags.iter().any(|matched| *matched) { - matches.push(build_search_match( - root, - path, - &lines, - idx, - idx, - context_lines, - matcher.matched_queries(matched_query_flags), - )); - } - } - } - SearchMatchMode::AllOnSameLine => { - for (idx, matched_query_flags) in line_matches.iter().enumerate() { - if matched_query_flags.iter().all(|matched| *matched) { - matches.push(build_search_match( - root, - path, - &lines, - idx, - idx, - context_lines, - matcher.matched_queries(matched_query_flags), - )); - } - } - } - SearchMatchMode::AllWithinLines { line_count } => { - let mut windows = Vec::new(); - for start_index in 0..lines.len() { - if !line_matches[start_index].iter().any(|matched| *matched) { - continue; - } - let last_allowed_index = start_index - .saturating_add(line_count.saturating_sub(1)) - .min(lines.len().saturating_sub(1)); - let mut matched_query_flags = vec![false; matcher.queries.len()]; - for (end_index, line_match_flags) in line_matches - .iter() - .enumerate() - .take(last_allowed_index + 1) - .skip(start_index) - { - for (idx, matched) in line_match_flags.iter().enumerate() { - matched_query_flags[idx] |= matched; - } - if matched_query_flags.iter().all(|matched| *matched) { - windows.push((start_index, end_index, matched_query_flags)); - break; - } - } - } - for (idx, (start_index, end_index, matched_query_flags)) in windows.iter().enumerate() { - let strictly_contains_another_window = windows.iter().enumerate().any( - |(other_idx, (other_start_index, other_end_index, _))| { - idx != other_idx - && start_index <= other_start_index - && end_index >= other_end_index - && (start_index != other_start_index || end_index != other_end_index) - }, - ); - if strictly_contains_another_window { - continue; - } - matches.push(build_search_match( - root, - path, - &lines, - *start_index, - *end_index, - context_lines, - matcher.matched_queries(matched_query_flags), - )); - } - } - } - Ok(()) -} - -fn build_search_match( - root: &Path, - path: &Path, - lines: &[&str], - match_start_index: usize, - match_end_index: usize, - context_lines: usize, - matched_queries: Vec, -) -> MemorySearchMatch { - let content_start_index = match_start_index.saturating_sub(context_lines); - let content_end_index = match_end_index - .saturating_add(context_lines) - .saturating_add(1) - .min(lines.len()); - MemorySearchMatch { - path: display_relative_path(root, path), - match_line_number: match_start_index + 1, - content_start_line_number: content_start_index + 1, - content: lines[content_start_index..content_end_index].join("\n"), - matched_queries, - } -} - -struct SearchMatcher { - queries: Vec, - prepared_queries: Vec, - comparison: SearchComparison, - match_mode: SearchMatchMode, -} - -impl SearchMatcher { - fn new( - queries: Vec, - match_mode: SearchMatchMode, - case_sensitive: bool, - normalized: bool, - ) -> Result { - let comparison = SearchComparison::new(case_sensitive, normalized); - let prepared_queries = queries - .iter() - .map(|query| comparison.prepare(query)) - .map(Cow::into_owned) - .collect::>(); - if prepared_queries.iter().any(std::string::String::is_empty) { - return Err(MemoriesBackendError::EmptyQuery); - } - Ok(Self { - queries, - prepared_queries, - comparison, - match_mode, - }) - } - - fn matched_query_flags(&self, line: &str) -> Vec { - let line = self.comparison.prepare(line); - self.prepared_queries - .iter() - .map(|query| line.as_ref().contains(query)) - .collect() - } - - fn matched_queries(&self, matched_query_flags: &[bool]) -> Vec { - self.queries - .iter() - .zip(matched_query_flags) - .filter_map(|(query, matched)| matched.then_some(query.clone())) - .collect() - } -} - -#[derive(Clone, Copy)] -struct SearchComparison { - case_sensitive: bool, - normalized: bool, -} - -impl SearchComparison { - fn new(case_sensitive: bool, normalized: bool) -> Self { - Self { - case_sensitive, - normalized, - } - } - - fn prepare<'a>(self, value: &'a str) -> Cow<'a, str> { - if self.case_sensitive && !self.normalized { - return Cow::Borrowed(value); - } - - let value = if self.case_sensitive { - Cow::Borrowed(value) - } else { - Cow::Owned(value.to_lowercase()) - }; - if !self.normalized { - return value; - } - - Cow::Owned( - value - .chars() - .filter(|ch| ch.is_alphanumeric()) - .collect::(), - ) - } -} - -async fn read_sorted_dir_paths(dir_path: &Path) -> Result, MemoriesBackendError> { - let mut dir = match tokio::fs::read_dir(dir_path).await { - Ok(dir) => dir, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(err) => return Err(err.into()), - }; - let mut paths = Vec::new(); - while let Some(entry) = dir.next_entry().await? { - paths.push(entry.path()); - } - paths.sort(); - Ok(paths) -} - -fn reject_symlink(path: &str, metadata: &std::fs::Metadata) -> Result<(), MemoriesBackendError> { - if metadata.file_type().is_symlink() { - return Err(MemoriesBackendError::invalid_path( - path, - "must not be a symlink", - )); - } - Ok(()) -} - -fn is_hidden_component(component: Component<'_>) -> bool { - matches!( - component, - Component::Normal(name) if name.to_string_lossy().starts_with('.') - ) -} - -fn is_hidden_path(path: &Path) -> bool { - path.file_name() - .is_some_and(|name| name.to_string_lossy().starts_with('.')) -} - -fn display_relative_path(root: &Path, path: &Path) -> String { - path.strip_prefix(root) - .unwrap_or(path) - .components() - .map(|component| component.as_os_str().to_string_lossy()) - .filter(|component| !component.is_empty()) - .collect::>() - .join("/") -} - -fn line_start_byte_offset( - content: &str, - line_offset: usize, -) -> Result { - if line_offset == 1 { - return Ok(0); - } - - let mut current_line = 1; - for (idx, ch) in content.char_indices() { - if ch == '\n' { - current_line += 1; - if current_line == line_offset { - return Ok(idx + 1); - } - } - } - - Err(MemoriesBackendError::LineOffsetExceedsFileLength) -} - -fn line_end_byte_offset(content: &str, start_byte: usize, max_lines: Option) -> usize { - let Some(max_lines) = max_lines else { - return content.len(); - }; - - let mut lines_seen = 1; - for (relative_idx, ch) in content[start_byte..].char_indices() { - if ch == '\n' { - if lines_seen == max_lines { - return start_byte + relative_idx + 1; - } - lines_seen += 1; - } - } - - content.len() -} diff --git a/codex-rs/ext/memories/src/local/list.rs b/codex-rs/ext/memories/src/local/list.rs new file mode 100644 index 0000000000..60915aa1f9 --- /dev/null +++ b/codex-rs/ext/memories/src/local/list.rs @@ -0,0 +1,83 @@ +use crate::MAX_LIST_RESULTS; +use crate::backend::ListMemoriesRequest; +use crate::backend::ListMemoriesResponse; +use crate::backend::MemoriesBackendError; +use crate::backend::MemoryEntry; +use crate::backend::MemoryEntryType; + +use super::LocalMemoriesBackend; +use super::path::display_relative_path; +use super::path::is_hidden_path; +use super::path::read_sorted_dir_paths; +use super::path::reject_symlink; + +pub(super) async fn list( + backend: &LocalMemoriesBackend, + request: ListMemoriesRequest, +) -> Result { + let max_results = request.max_results.min(MAX_LIST_RESULTS); + let start = backend.resolve_scoped_path(request.path.as_deref()).await?; + let start_index = match request.cursor.as_deref() { + Some(cursor) => cursor.parse::().map_err(|_| { + MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer") + })?, + None => 0, + }; + let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&start).await? else { + return Err(MemoriesBackendError::NotFound { + path: request.path.unwrap_or_default(), + }); + }; + reject_symlink(&display_relative_path(&backend.root, &start), &metadata)?; + + let mut entries = if metadata.is_file() { + vec![MemoryEntry { + path: display_relative_path(&backend.root, &start), + entry_type: MemoryEntryType::File, + }] + } else if metadata.is_dir() { + let mut entries = Vec::new(); + for path in read_sorted_dir_paths(&start).await? { + if is_hidden_path(&path) { + continue; + } + let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else { + continue; + }; + if metadata.file_type().is_symlink() { + continue; + } + + let entry_type = if metadata.is_dir() { + MemoryEntryType::Directory + } else if metadata.is_file() { + MemoryEntryType::File + } else { + continue; + }; + entries.push(MemoryEntry { + path: display_relative_path(&backend.root, &path), + entry_type, + }); + } + entries + } else { + Vec::new() + }; + if start_index > entries.len() { + return Err(MemoriesBackendError::invalid_cursor( + start_index.to_string(), + "exceeds result count", + )); + } + + let end_index = start_index.saturating_add(max_results).min(entries.len()); + let next_cursor = (end_index < entries.len()).then(|| end_index.to_string()); + let truncated = next_cursor.is_some(); + Ok(ListMemoriesResponse { + path: request.path, + entries: entries.drain(start_index..end_index).collect(), + next_cursor, + truncated, + }) +} diff --git a/codex-rs/ext/memories/src/local/path.rs b/codex-rs/ext/memories/src/local/path.rs new file mode 100644 index 0000000000..2052967f68 --- /dev/null +++ b/codex-rs/ext/memories/src/local/path.rs @@ -0,0 +1,56 @@ +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use crate::backend::MemoriesBackendError; + +pub(super) async fn read_sorted_dir_paths( + dir_path: &Path, +) -> Result, MemoriesBackendError> { + let mut dir = match tokio::fs::read_dir(dir_path).await { + Ok(dir) => dir, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(err) => return Err(err.into()), + }; + let mut paths = Vec::new(); + while let Some(entry) = dir.next_entry().await? { + paths.push(entry.path()); + } + paths.sort(); + Ok(paths) +} + +pub(super) fn reject_symlink( + path: &str, + metadata: &std::fs::Metadata, +) -> Result<(), MemoriesBackendError> { + if metadata.file_type().is_symlink() { + return Err(MemoriesBackendError::invalid_path( + path, + "must not be a symlink", + )); + } + Ok(()) +} + +pub(super) fn is_hidden_component(component: Component<'_>) -> bool { + matches!( + component, + Component::Normal(name) if name.to_string_lossy().starts_with('.') + ) +} + +pub(super) fn is_hidden_path(path: &Path) -> bool { + path.file_name() + .is_some_and(|name| name.to_string_lossy().starts_with('.')) +} + +pub(super) fn display_relative_path(root: &Path, path: &Path) -> String { + path.strip_prefix(root) + .unwrap_or(path) + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .filter(|component| !component.is_empty()) + .collect::>() + .join("/") +} diff --git a/codex-rs/ext/memories/src/local/read.rs b/codex-rs/ext/memories/src/local/read.rs new file mode 100644 index 0000000000..d2e22bd1a8 --- /dev/null +++ b/codex-rs/ext/memories/src/local/read.rs @@ -0,0 +1,90 @@ +use codex_utils_output_truncation::TruncationPolicy; +use codex_utils_output_truncation::truncate_text; + +use crate::DEFAULT_READ_MAX_TOKENS; +use crate::backend::MemoriesBackendError; +use crate::backend::ReadMemoryRequest; +use crate::backend::ReadMemoryResponse; + +use super::LocalMemoriesBackend; +use super::path::reject_symlink; + +pub(super) async fn read( + backend: &LocalMemoriesBackend, + request: ReadMemoryRequest, +) -> Result { + if request.line_offset == 0 { + return Err(MemoriesBackendError::InvalidLineOffset); + } + if request.max_lines == Some(0) { + return Err(MemoriesBackendError::InvalidMaxLines); + } + + let path = backend + .resolve_scoped_path(Some(request.path.as_str())) + .await?; + let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else { + return Err(MemoriesBackendError::NotFound { path: request.path }); + }; + reject_symlink(&request.path, &metadata)?; + if !metadata.is_file() { + return Err(MemoriesBackendError::NotFile { path: request.path }); + } + + let original_content = tokio::fs::read_to_string(&path).await?; + let start_byte = line_start_byte_offset(&original_content, request.line_offset)?; + let end_byte = line_end_byte_offset(&original_content, start_byte, request.max_lines); + let content_from_offset = &original_content[start_byte..end_byte]; + let max_tokens = if request.max_tokens == 0 { + DEFAULT_READ_MAX_TOKENS + } else { + request.max_tokens + }; + let content = truncate_text(content_from_offset, TruncationPolicy::Tokens(max_tokens)); + let truncated = end_byte < original_content.len() || content != content_from_offset; + Ok(ReadMemoryResponse { + path: request.path, + start_line_number: request.line_offset, + content, + truncated, + }) +} + +fn line_start_byte_offset( + content: &str, + line_offset: usize, +) -> Result { + if line_offset == 1 { + return Ok(0); + } + + let mut current_line = 1; + for (idx, ch) in content.char_indices() { + if ch == '\n' { + current_line += 1; + if current_line == line_offset { + return Ok(idx + 1); + } + } + } + + Err(MemoriesBackendError::LineOffsetExceedsFileLength) +} + +fn line_end_byte_offset(content: &str, start_byte: usize, max_lines: Option) -> usize { + let Some(max_lines) = max_lines else { + return content.len(); + }; + + let mut lines_seen = 1; + for (relative_idx, ch) in content[start_byte..].char_indices() { + if ch == '\n' { + if lines_seen == max_lines { + return start_byte + relative_idx + 1; + } + lines_seen += 1; + } + } + + content.len() +} diff --git a/codex-rs/ext/memories/src/local/search.rs b/codex-rs/ext/memories/src/local/search.rs new file mode 100644 index 0000000000..85551fd88a --- /dev/null +++ b/codex-rs/ext/memories/src/local/search.rs @@ -0,0 +1,336 @@ +use std::borrow::Cow; +use std::path::Path; + +use crate::MAX_SEARCH_RESULTS; +use crate::backend::MemoriesBackendError; +use crate::backend::MemorySearchMatch; +use crate::backend::SearchMatchMode; +use crate::backend::SearchMemoriesRequest; +use crate::backend::SearchMemoriesResponse; + +use super::LocalMemoriesBackend; +use super::path::display_relative_path; +use super::path::is_hidden_path; +use super::path::read_sorted_dir_paths; +use super::path::reject_symlink; + +pub(super) async fn search( + backend: &LocalMemoriesBackend, + request: SearchMemoriesRequest, +) -> Result { + let queries = request + .queries + .iter() + .map(|query| query.trim().to_string()) + .collect::>(); + if queries.is_empty() || queries.iter().any(std::string::String::is_empty) { + return Err(MemoriesBackendError::EmptyQuery); + } + if matches!( + request.match_mode, + SearchMatchMode::AllWithinLines { line_count: 0 } + ) { + return Err(MemoriesBackendError::InvalidMatchWindow); + } + + let max_results = request.max_results.min(MAX_SEARCH_RESULTS); + let start = backend.resolve_scoped_path(request.path.as_deref()).await?; + let start_index = match request.cursor.as_deref() { + Some(cursor) => cursor.parse::().map_err(|_| { + MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer") + })?, + None => 0, + }; + let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&start).await? else { + return Err(MemoriesBackendError::NotFound { + path: request.path.unwrap_or_default(), + }); + }; + reject_symlink(&display_relative_path(&backend.root, &start), &metadata)?; + + let matcher = SearchMatcher::new( + queries.clone(), + request.match_mode.clone(), + request.case_sensitive, + request.normalized, + )?; + let mut matches = Vec::new(); + search_entries( + &backend.root, + &start, + &metadata, + &matcher, + request.context_lines, + &mut matches, + ) + .await?; + matches.sort_by(|left, right| { + left.path + .cmp(&right.path) + .then(left.match_line_number.cmp(&right.match_line_number)) + }); + if start_index > matches.len() { + return Err(MemoriesBackendError::invalid_cursor( + start_index.to_string(), + "exceeds result count", + )); + } + let end_index = start_index.saturating_add(max_results).min(matches.len()); + let next_cursor = (end_index < matches.len()).then(|| end_index.to_string()); + let truncated = next_cursor.is_some(); + Ok(SearchMemoriesResponse { + queries, + match_mode: request.match_mode, + path: request.path, + matches: matches.drain(start_index..end_index).collect(), + next_cursor, + truncated, + }) +} + +async fn search_entries( + root: &Path, + current: &Path, + current_metadata: &std::fs::Metadata, + matcher: &SearchMatcher, + context_lines: usize, + matches: &mut Vec, +) -> Result<(), MemoriesBackendError> { + if current_metadata.is_file() { + search_file(root, current, matcher, context_lines, matches).await?; + return Ok(()); + } + if !current_metadata.is_dir() { + return Ok(()); + } + + let mut pending = vec![current.to_path_buf()]; + while let Some(dir_path) = pending.pop() { + for path in read_sorted_dir_paths(&dir_path).await? { + if is_hidden_path(&path) { + continue; + } + let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else { + continue; + }; + if metadata.file_type().is_symlink() { + continue; + } + if metadata.is_dir() { + pending.push(path); + } else if metadata.is_file() { + search_file(root, &path, matcher, context_lines, matches).await?; + } + } + } + + Ok(()) +} + +async fn search_file( + root: &Path, + path: &Path, + matcher: &SearchMatcher, + context_lines: usize, + matches: &mut Vec, +) -> Result<(), MemoriesBackendError> { + let content = match tokio::fs::read_to_string(path).await { + Ok(content) => content, + Err(err) if err.kind() == std::io::ErrorKind::InvalidData => return Ok(()), + Err(err) => return Err(err.into()), + }; + let lines = content.lines().collect::>(); + let line_matches = lines + .iter() + .map(|line| matcher.matched_query_flags(line)) + .collect::>(); + match &matcher.match_mode { + SearchMatchMode::Any => { + for (idx, matched_query_flags) in line_matches.iter().enumerate() { + if matched_query_flags.iter().any(|matched| *matched) { + matches.push(build_search_match( + root, + path, + &lines, + idx, + idx, + context_lines, + matcher.matched_queries(matched_query_flags), + )); + } + } + } + SearchMatchMode::AllOnSameLine => { + for (idx, matched_query_flags) in line_matches.iter().enumerate() { + if matched_query_flags.iter().all(|matched| *matched) { + matches.push(build_search_match( + root, + path, + &lines, + idx, + idx, + context_lines, + matcher.matched_queries(matched_query_flags), + )); + } + } + } + SearchMatchMode::AllWithinLines { line_count } => { + let mut windows = Vec::new(); + for start_index in 0..lines.len() { + if !line_matches[start_index].iter().any(|matched| *matched) { + continue; + } + let last_allowed_index = start_index + .saturating_add(line_count.saturating_sub(1)) + .min(lines.len().saturating_sub(1)); + let mut matched_query_flags = vec![false; matcher.queries.len()]; + for (end_index, line_match_flags) in line_matches + .iter() + .enumerate() + .take(last_allowed_index + 1) + .skip(start_index) + { + for (idx, matched) in line_match_flags.iter().enumerate() { + matched_query_flags[idx] |= matched; + } + if matched_query_flags.iter().all(|matched| *matched) { + windows.push((start_index, end_index, matched_query_flags)); + break; + } + } + } + for (idx, (start_index, end_index, matched_query_flags)) in windows.iter().enumerate() { + let strictly_contains_another_window = windows.iter().enumerate().any( + |(other_idx, (other_start_index, other_end_index, _))| { + idx != other_idx + && start_index <= other_start_index + && end_index >= other_end_index + && (start_index != other_start_index || end_index != other_end_index) + }, + ); + if strictly_contains_another_window { + continue; + } + matches.push(build_search_match( + root, + path, + &lines, + *start_index, + *end_index, + context_lines, + matcher.matched_queries(matched_query_flags), + )); + } + } + } + Ok(()) +} + +fn build_search_match( + root: &Path, + path: &Path, + lines: &[&str], + match_start_index: usize, + match_end_index: usize, + context_lines: usize, + matched_queries: Vec, +) -> MemorySearchMatch { + let content_start_index = match_start_index.saturating_sub(context_lines); + let content_end_index = match_end_index + .saturating_add(context_lines) + .saturating_add(1) + .min(lines.len()); + MemorySearchMatch { + path: display_relative_path(root, path), + match_line_number: match_start_index + 1, + content_start_line_number: content_start_index + 1, + content: lines[content_start_index..content_end_index].join("\n"), + matched_queries, + } +} + +struct SearchMatcher { + queries: Vec, + prepared_queries: Vec, + comparison: SearchComparison, + match_mode: SearchMatchMode, +} + +impl SearchMatcher { + fn new( + queries: Vec, + match_mode: SearchMatchMode, + case_sensitive: bool, + normalized: bool, + ) -> Result { + let comparison = SearchComparison::new(case_sensitive, normalized); + let prepared_queries = queries + .iter() + .map(|query| comparison.prepare(query)) + .map(Cow::into_owned) + .collect::>(); + if prepared_queries.iter().any(std::string::String::is_empty) { + return Err(MemoriesBackendError::EmptyQuery); + } + Ok(Self { + queries, + prepared_queries, + comparison, + match_mode, + }) + } + + fn matched_query_flags(&self, line: &str) -> Vec { + let line = self.comparison.prepare(line); + self.prepared_queries + .iter() + .map(|query| line.as_ref().contains(query)) + .collect() + } + + fn matched_queries(&self, matched_query_flags: &[bool]) -> Vec { + self.queries + .iter() + .zip(matched_query_flags) + .filter_map(|(query, matched)| matched.then_some(query.clone())) + .collect() + } +} + +#[derive(Clone, Copy)] +struct SearchComparison { + case_sensitive: bool, + normalized: bool, +} + +impl SearchComparison { + fn new(case_sensitive: bool, normalized: bool) -> Self { + Self { + case_sensitive, + normalized, + } + } + + fn prepare<'a>(self, value: &'a str) -> Cow<'a, str> { + if self.case_sensitive && !self.normalized { + return Cow::Borrowed(value); + } + + let value = if self.case_sensitive { + Cow::Borrowed(value) + } else { + Cow::Owned(value.to_lowercase()) + }; + if !self.normalized { + return value; + } + + Cow::Owned( + value + .chars() + .filter(|ch| ch.is_alphanumeric()) + .collect::(), + ) + } +} diff --git a/codex-rs/ext/memories/src/tests.rs b/codex-rs/ext/memories/src/tests.rs new file mode 100644 index 0000000000..3d9cd9a79b --- /dev/null +++ b/codex-rs/ext/memories/src/tests.rs @@ -0,0 +1,311 @@ +use std::path::Path; +use std::sync::Arc; + +use codex_extension_api::ContextContributor; +use codex_extension_api::ExtensionData; +use codex_extension_api::ExtensionToolExecutor; +use codex_extension_api::PromptSlot; +use codex_extension_api::ToolCall; +use codex_extension_api::ToolContributor; +use codex_extension_api::ToolName; +use codex_extension_api::ToolPayload; +use codex_tools::ToolOutput; +use codex_utils_absolute_path::test_support::PathBufExt; +use codex_utils_absolute_path::test_support::PathExt; +use codex_utils_absolute_path::test_support::test_path_buf; +use pretty_assertions::assert_eq; +use serde_json::json; + +use crate::extension::MemoriesExtension; +use crate::extension::MemoriesExtensionConfig; +use crate::local::LocalMemoriesBackend; + +#[test] +fn tools_are_not_contributed_without_thread_config() { + let extension = MemoriesExtension; + + assert!( + extension + .tools( + &ExtensionData::new("session"), + &ExtensionData::new("thread") + ) + .is_empty() + ); +} + +#[test] +fn tools_are_not_contributed_when_disabled() { + let extension = MemoriesExtension; + let thread_store = ExtensionData::new("thread"); + thread_store.insert(MemoriesExtensionConfig { + enabled: false, + codex_home: test_path_buf("/tmp/codex-home").abs(), + }); + + assert!( + extension + .tools(&ExtensionData::new("session"), &thread_store) + .is_empty() + ); +} + +#[test] +fn tools_are_contributed_when_enabled() { + let extension = MemoriesExtension; + let thread_store = ExtensionData::new("thread"); + thread_store.insert(MemoriesExtensionConfig { + enabled: true, + codex_home: test_path_buf("/tmp/codex-home").abs(), + }); + + let tool_names = extension + .tools(&ExtensionData::new("session"), &thread_store) + .into_iter() + .map(|tool| tool.tool_name().to_string()) + .collect::>(); + + assert_eq!( + tool_names, + vec![ + "memory_list".to_string(), + "memory_read".to_string(), + "memory_search".to_string() + ] + ); +} + +#[tokio::test] +async fn prompt_contribution_uses_memory_summary_when_enabled() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let memories_dir = tempdir.path().join("memories"); + tokio::fs::create_dir_all(&memories_dir) + .await + .expect("create memories dir"); + tokio::fs::write( + memories_dir.join("memory_summary.md"), + "Remember repository-specific implementation preferences.", + ) + .await + .expect("write memory summary"); + + let extension = MemoriesExtension; + let thread_store = ExtensionData::new("thread"); + thread_store.insert(MemoriesExtensionConfig { + enabled: true, + codex_home: tempdir.path().abs(), + }); + + let fragments = extension + .contribute(&ExtensionData::new("session"), &thread_store) + .await; + + assert_eq!(fragments.len(), 1); + assert_eq!(fragments[0].slot(), PromptSlot::DeveloperPolicy); + assert!( + fragments[0] + .text() + .contains("Remember repository-specific implementation preferences.") + ); +} + +#[tokio::test] +async fn read_tool_reads_memory_file() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let memory_root = tempdir.path().join("memories"); + tokio::fs::create_dir_all(&memory_root) + .await + .expect("create memories dir"); + tokio::fs::write( + memory_root.join("MEMORY.md"), + "first line\nsecond needle line\nthird line\n", + ) + .await + .expect("write memory"); + let tool = memory_tool(&memory_root, crate::READ_TOOL_NAME); + let payload = ToolPayload::Function { + arguments: json!({ + "path": "MEMORY.md", + "line_offset": 2, + "max_lines": 1 + }) + .to_string(), + }; + + let output = tool + .handle(ToolCall { + call_id: "call-1".to_string(), + tool_name: ToolName::plain(crate::READ_TOOL_NAME), + payload: payload.clone(), + }) + .await + .expect("read should succeed"); + + assert_eq!( + output.post_tool_use_response("call-1", &payload), + Some(json!({ + "path": "MEMORY.md", + "content": "second needle line\n", + "start_line_number": 2, + "truncated": true + })) + ); +} + +#[tokio::test] +async fn search_tool_accepts_multiple_queries() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let memory_root = tempdir.path().join("memories"); + tokio::fs::create_dir_all(&memory_root) + .await + .expect("create memories dir"); + tokio::fs::write( + memory_root.join("MEMORY.md"), + "alpha only\nneedle only\nalpha needle\n", + ) + .await + .expect("write memory"); + let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME); + let payload = ToolPayload::Function { + arguments: json!({ + "queries": ["alpha", "needle"], + "case_sensitive": false + }) + .to_string(), + }; + + let output = tool + .handle(ToolCall { + call_id: "call-1".to_string(), + tool_name: ToolName::plain(crate::SEARCH_TOOL_NAME), + payload: payload.clone(), + }) + .await + .expect("search should succeed"); + + assert_eq!( + output.post_tool_use_response("call-1", &payload), + Some(json!({ + "queries": ["alpha", "needle"], + "match_mode": { + "type": "any" + }, + "path": null, + "matches": [ + { + "path": "MEMORY.md", + "match_line_number": 1, + "content_start_line_number": 1, + "content": "alpha only", + "matched_queries": ["alpha"] + }, + { + "path": "MEMORY.md", + "match_line_number": 2, + "content_start_line_number": 2, + "content": "needle only", + "matched_queries": ["needle"] + }, + { + "path": "MEMORY.md", + "match_line_number": 3, + "content_start_line_number": 3, + "content": "alpha needle", + "matched_queries": ["alpha", "needle"] + } + ], + "next_cursor": null, + "truncated": false + })) + ); +} + +#[tokio::test] +async fn search_tool_accepts_windowed_all_match_mode() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let memory_root = tempdir.path().join("memories"); + tokio::fs::create_dir_all(&memory_root) + .await + .expect("create memories dir"); + tokio::fs::write(memory_root.join("MEMORY.md"), "alpha\nmiddle\nneedle\n") + .await + .expect("write memory"); + let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME); + let payload = ToolPayload::Function { + arguments: json!({ + "queries": ["alpha", "needle"], + "match_mode": { + "type": "all_within_lines", + "line_count": 3 + } + }) + .to_string(), + }; + + let output = tool + .handle(ToolCall { + call_id: "call-1".to_string(), + tool_name: ToolName::plain(crate::SEARCH_TOOL_NAME), + payload: payload.clone(), + }) + .await + .expect("search should succeed"); + + assert_eq!( + output.post_tool_use_response("call-1", &payload), + Some(json!({ + "queries": ["alpha", "needle"], + "match_mode": { + "type": "all_within_lines", + "line_count": 3 + }, + "path": null, + "matches": [ + { + "path": "MEMORY.md", + "match_line_number": 1, + "content_start_line_number": 1, + "content": "alpha\nmiddle\nneedle", + "matched_queries": ["alpha", "needle"] + } + ], + "next_cursor": null, + "truncated": false + })) + ); +} + +#[tokio::test] +async fn search_tool_rejects_legacy_single_query() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let memory_root = tempdir.path().join("memories"); + tokio::fs::create_dir_all(&memory_root) + .await + .expect("create memories dir"); + let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME); + let payload = ToolPayload::Function { + arguments: json!({ + "query": "needle", + }) + .to_string(), + }; + + let err = tool + .handle(ToolCall { + call_id: "call-1".to_string(), + tool_name: ToolName::plain(crate::SEARCH_TOOL_NAME), + payload, + }) + .await + .expect_err("legacy query field should be rejected"); + + assert!(err.to_string().contains("unknown field")); + assert!(err.to_string().contains("query")); +} + +fn memory_tool(memory_root: &Path, tool_name: &str) -> Arc { + crate::tools::memory_tools(LocalMemoriesBackend::from_memory_root(memory_root)) + .into_iter() + .find(|tool| tool.tool_name().to_string() == tool_name) + .unwrap_or_else(|| panic!("{tool_name} tool should be registered")) +} diff --git a/codex-rs/ext/memories/src/tools/list.rs b/codex-rs/ext/memories/src/tools/list.rs index e9674f704b..bd1599047e 100644 --- a/codex-rs/ext/memories/src/tools/list.rs +++ b/codex-rs/ext/memories/src/tools/list.rs @@ -8,14 +8,13 @@ use schemars::JsonSchema; use serde::Deserialize; use serde_json::json; -use crate::backend::DEFAULT_LIST_MAX_RESULTS; +use crate::DEFAULT_LIST_MAX_RESULTS; +use crate::LIST_TOOL_NAME; +use crate::MAX_LIST_RESULTS; use crate::backend::ListMemoriesRequest; use crate::backend::ListMemoriesResponse; -use crate::backend::MAX_LIST_RESULTS; use crate::backend::MemoriesBackend; -use crate::local::LocalMemoriesBackend; -use super::LIST_TOOL_NAME; use super::backend_error_to_function_call; use super::clamp_max_results; use super::function_tool; @@ -31,11 +30,14 @@ struct ListArgs { } #[derive(Clone)] -pub(super) struct ListTool { - pub(super) backend: LocalMemoriesBackend, +pub(super) struct ListTool { + pub(super) backend: B, } -impl ExtensionToolExecutor for ListTool { +impl ExtensionToolExecutor for ListTool +where + B: MemoriesBackend, +{ fn tool_name(&self) -> ToolName { ToolName::plain(LIST_TOOL_NAME) } diff --git a/codex-rs/ext/memories/src/tools/mod.rs b/codex-rs/ext/memories/src/tools/mod.rs index 735126349e..b488cc5e87 100644 --- a/codex-rs/ext/memories/src/tools/mod.rs +++ b/codex-rs/ext/memories/src/tools/mod.rs @@ -10,19 +10,18 @@ use schemars::JsonSchema; use serde::Deserialize; use serde_json::Value; +use crate::backend::MemoriesBackend; use crate::backend::MemoriesBackendError; -use crate::local::LocalMemoriesBackend; use crate::schema; mod list; mod read; mod search; -const LIST_TOOL_NAME: &str = "memory_list"; -const READ_TOOL_NAME: &str = "memory_read"; -const SEARCH_TOOL_NAME: &str = "memory_search"; - -pub(crate) fn memory_tools(backend: LocalMemoriesBackend) -> Vec> { +pub(crate) fn memory_tools(backend: B) -> Vec> +where + B: MemoriesBackend, +{ vec![ Arc::new(list::ListTool { backend: backend.clone(), diff --git a/codex-rs/ext/memories/src/tools/read.rs b/codex-rs/ext/memories/src/tools/read.rs index 96129ec0f9..ec411a9947 100644 --- a/codex-rs/ext/memories/src/tools/read.rs +++ b/codex-rs/ext/memories/src/tools/read.rs @@ -8,13 +8,12 @@ use schemars::JsonSchema; use serde::Deserialize; use serde_json::json; -use crate::backend::DEFAULT_READ_MAX_TOKENS; +use crate::DEFAULT_READ_MAX_TOKENS; +use crate::READ_TOOL_NAME; use crate::backend::MemoriesBackend; use crate::backend::ReadMemoryRequest; use crate::backend::ReadMemoryResponse; -use crate::local::LocalMemoriesBackend; -use super::READ_TOOL_NAME; use super::backend_error_to_function_call; use super::function_tool; use super::parse_args; @@ -30,11 +29,14 @@ struct ReadArgs { } #[derive(Clone)] -pub(super) struct ReadTool { - pub(super) backend: LocalMemoriesBackend, +pub(super) struct ReadTool { + pub(super) backend: B, } -impl ExtensionToolExecutor for ReadTool { +impl ExtensionToolExecutor for ReadTool +where + B: MemoriesBackend, +{ fn tool_name(&self) -> ToolName { ToolName::plain(READ_TOOL_NAME) } @@ -63,58 +65,3 @@ impl ExtensionToolExecutor for ReadTool { }) } } - -#[cfg(test)] -mod tests { - use codex_extension_api::ToolPayload; - use codex_tools::ToolOutput; - use pretty_assertions::assert_eq; - use serde_json::json; - - use super::*; - - #[tokio::test] - async fn read_tool_reads_memory_file() { - let tempdir = tempfile::tempdir().expect("tempdir"); - let memory_root = tempdir.path().join("memories"); - tokio::fs::create_dir_all(&memory_root) - .await - .expect("create memories dir"); - tokio::fs::write( - memory_root.join("MEMORY.md"), - "first line\nsecond needle line\nthird line\n", - ) - .await - .expect("write memory"); - let tool = ReadTool { - backend: LocalMemoriesBackend::from_memory_root(&memory_root), - }; - let payload = ToolPayload::Function { - arguments: json!({ - "path": "MEMORY.md", - "line_offset": 2, - "max_lines": 1 - }) - .to_string(), - }; - - let output = tool - .handle(ToolCall { - call_id: "call-1".to_string(), - tool_name: ToolName::plain(READ_TOOL_NAME), - payload: payload.clone(), - }) - .await - .expect("read should succeed"); - - assert_eq!( - output.post_tool_use_response("call-1", &payload), - Some(json!({ - "path": "MEMORY.md", - "content": "second needle line\n", - "start_line_number": 2, - "truncated": true - })) - ); - } -} diff --git a/codex-rs/ext/memories/src/tools/search.rs b/codex-rs/ext/memories/src/tools/search.rs index f437df0040..38863bcad5 100644 --- a/codex-rs/ext/memories/src/tools/search.rs +++ b/codex-rs/ext/memories/src/tools/search.rs @@ -8,15 +8,14 @@ use schemars::JsonSchema; use serde::Deserialize; use serde_json::json; -use crate::backend::DEFAULT_SEARCH_MAX_RESULTS; -use crate::backend::MAX_SEARCH_RESULTS; +use crate::DEFAULT_SEARCH_MAX_RESULTS; +use crate::MAX_SEARCH_RESULTS; +use crate::SEARCH_TOOL_NAME; use crate::backend::MemoriesBackend; use crate::backend::SearchMatchMode; use crate::backend::SearchMemoriesRequest; use crate::backend::SearchMemoriesResponse; -use crate::local::LocalMemoriesBackend; -use super::SEARCH_TOOL_NAME; use super::backend_error_to_function_call; use super::clamp_max_results; use super::function_tool; @@ -39,11 +38,14 @@ struct SearchArgs { } #[derive(Clone)] -pub(super) struct SearchTool { - pub(super) backend: LocalMemoriesBackend, +pub(super) struct SearchTool { + pub(super) backend: B, } -impl ExtensionToolExecutor for SearchTool { +impl ExtensionToolExecutor for SearchTool +where + B: MemoriesBackend, +{ fn tool_name(&self) -> ToolName { ToolName::plain(SEARCH_TOOL_NAME) } @@ -86,75 +88,3 @@ impl SearchArgs { } } } - -#[cfg(test)] -mod tests { - use pretty_assertions::assert_eq; - use serde_json::json; - - use super::*; - - #[test] - fn search_args_accept_multiple_queries() { - let args: SearchArgs = serde_json::from_value(json!({ - "queries": ["alpha", "needle"], - "case_sensitive": false - })) - .expect("multi-query args should parse"); - - let request = args.into_request(); - - assert_eq!( - request, - SearchMemoriesRequest { - queries: vec!["alpha".to_string(), "needle".to_string()], - match_mode: SearchMatchMode::Any, - path: None, - cursor: None, - context_lines: 0, - case_sensitive: false, - normalized: false, - max_results: DEFAULT_SEARCH_MAX_RESULTS, - } - ); - } - - #[test] - fn search_args_accept_windowed_all_match_mode() { - let args: SearchArgs = serde_json::from_value(json!({ - "queries": ["alpha", "needle"], - "match_mode": { - "type": "all_within_lines", - "line_count": 3 - } - })) - .expect("windowed all args should parse"); - - let request = args.into_request(); - - assert_eq!( - request, - SearchMemoriesRequest { - queries: vec!["alpha".to_string(), "needle".to_string()], - match_mode: SearchMatchMode::AllWithinLines { line_count: 3 }, - path: None, - cursor: None, - context_lines: 0, - case_sensitive: true, - normalized: false, - max_results: DEFAULT_SEARCH_MAX_RESULTS, - } - ); - } - - #[test] - fn search_args_reject_legacy_single_query() { - let err = serde_json::from_value::(json!({ - "query": "needle", - })) - .expect_err("legacy query field should be rejected"); - - assert!(err.to_string().contains("unknown field")); - assert!(err.to_string().contains("query")); - } -} From 8fe0ecb045462528eabf0c94b25a41aa15e84fa7 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 13 May 2026 08:52:56 -0700 Subject: [PATCH 13/13] Refactor chatwidget protocol flows into modules (phase 3) (#22433) ## Why `chatwidget.rs` is still carrying too many unrelated responsibilities in one file. #22269 started a five-phase cleanup to move coherent behavior domains into focused modules while keeping `chatwidget.rs` as the composition layer. #22407 completed phase 2 by extracting input and submission flow. This PR is phase 3. It keeps moving high-churn event handling out of the central widget by extracting protocol, replay, streaming, and tool lifecycle handling without changing the visible behavior those flows already provide. This is once again just a mechanical movement of existing functions. No functional changes. ## What Changed - Added focused modules for protocol request dispatch, replay rendering, assistant/plan/reasoning streaming, turn runtime bookkeeping, hook lifecycle handling, command lifecycle handling, tool lifecycle rendering, and interactive tool request prompts. - Kept active-cell grouping, transcript invalidation, interrupt deferral, and final-message separator behavior in the same flows, just moved into smaller files. - Added module header comments to the new files so the ownership boundaries are explicit. - Left `codex-rs/tui/src/chatwidget.rs` as the registration and orchestration surface for these extracted behaviors. ## Cleanup Phases The five-phase cleanup plan from #22269 is: 1. Phase 1: mechanical helper and state moves. Completed in #22269. 2. Phase 2: extract input and submission flow, including queued user messages, shell prompt submission, pending steer restoration, and thread input snapshot/restore behavior. Completed in #22407. 3. Phase 3: extract protocol, replay, streaming, and tool lifecycle handling, while preserving active-cell grouping, transcript invalidation, interrupt deferral, and final-message separator behavior. This PR. 4. Phase 4: extract settings, popups, and status surfaces, including model/reasoning/collaboration/personality popups, permission prompts, rate-limit UI, and connectors helpers. 5. Phase 5: clean up the remaining constructor and orchestration code once the larger behavior domains have moved out, leaving `chatwidget.rs` as the composition layer. --- codex-rs/tui/src/chatwidget.rs | 2504 +---------------- .../tui/src/chatwidget/command_lifecycle.rs | 454 +++ codex-rs/tui/src/chatwidget/hook_lifecycle.rs | 132 + .../tui/src/chatwidget/protocol_requests.rs | 148 + codex-rs/tui/src/chatwidget/replay.rs | 196 ++ codex-rs/tui/src/chatwidget/streaming.rs | 459 +++ codex-rs/tui/src/chatwidget/tool_lifecycle.rs | 264 ++ codex-rs/tui/src/chatwidget/tool_requests.rs | 449 +++ codex-rs/tui/src/chatwidget/turn_runtime.rs | 477 ++++ 9 files changed, 2587 insertions(+), 2496 deletions(-) create mode 100644 codex-rs/tui/src/chatwidget/command_lifecycle.rs create mode 100644 codex-rs/tui/src/chatwidget/hook_lifecycle.rs create mode 100644 codex-rs/tui/src/chatwidget/protocol_requests.rs create mode 100644 codex-rs/tui/src/chatwidget/replay.rs create mode 100644 codex-rs/tui/src/chatwidget/streaming.rs create mode 100644 codex-rs/tui/src/chatwidget/tool_lifecycle.rs create mode 100644 codex-rs/tui/src/chatwidget/tool_requests.rs create mode 100644 codex-rs/tui/src/chatwidget/turn_runtime.rs diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 2894e79c88..6723577754 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -316,6 +316,7 @@ use crate::status_indicator_widget::STATUS_DETAILS_DEFAULT_MAX_LINES; use crate::status_indicator_widget::StatusDetailsCapitalization; use crate::text_formatting::truncate_text; use crate::tui::FrameRequester; +mod command_lifecycle; mod connectors; use self::connectors::ConnectorsCacheState; use self::connectors::ConnectorsState; @@ -348,6 +349,7 @@ use self::mcp_startup::McpStartupStatus; mod pets; mod session_header; use self::session_header::SessionHeader; +mod hook_lifecycle; mod hooks; mod skills; mod slash_dispatch; @@ -361,6 +363,7 @@ use self::plugins::PluginsCacheState; mod plan_implementation; use self::plan_implementation::PLAN_IMPLEMENTATION_TITLE; mod protocol; +mod protocol_requests; mod rate_limits; use self::rate_limits::NUDGE_MODEL_SLUG; use self::rate_limits::RATE_LIMIT_SWITCH_PROMPT_THRESHOLD; @@ -371,6 +374,7 @@ use self::rate_limits::app_server_rate_limit_error_kind; pub(crate) use self::rate_limits::get_limits_duration; use self::rate_limits::is_app_server_cyber_policy_error; mod realtime; +mod replay; use self::realtime::RealtimeConversationUiState; mod reasoning_shortcuts; mod review; @@ -382,10 +386,14 @@ use self::status_state::StatusIndicatorState; use self::status_state::StatusState; use self::status_state::TerminalTitleStatusKind; mod status_surfaces; +mod streaming; use self::status_surfaces::CachedProjectRootName; +mod tool_lifecycle; +mod tool_requests; mod transcript; use self::transcript::TranscriptState; mod turn_lifecycle; +mod turn_runtime; use self::turn_lifecycle::TurnLifecycleState; mod user_messages; use self::user_messages::PendingSteer; @@ -888,112 +896,6 @@ impl ChatWidget { self.realtime_conversation_enabled() } - /// Synchronize the bottom-pane "task running" indicator with the current lifecycles. - /// - /// The bottom pane only has one running flag, but this module treats it as a derived state of - /// both the agent turn lifecycle and MCP startup lifecycle. - fn update_task_running_state(&mut self) { - self.bottom_pane.set_task_running( - self.turn_lifecycle.agent_turn_running || self.mcp_startup_status.is_some(), - ); - self.refresh_plan_mode_nudge(); - self.refresh_status_surfaces(); - } - - fn restore_reasoning_status_header(&mut self) { - if let Some(header) = extract_first_bold(&self.reasoning_buffer) { - self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking; - self.set_status_header(header); - } else if self.bottom_pane.is_task_running() { - self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Working; - self.set_status_header(String::from("Working")); - } - } - - fn flush_unified_exec_wait_streak(&mut self) { - let Some(wait) = self.unified_exec_wait_streak.take() else { - return; - }; - self.transcript.needs_final_message_separator = true; - let cell = history_cell::new_unified_exec_interaction(wait.command_display, String::new()); - self.app_event_tx - .send(AppEvent::InsertHistoryCell(Box::new(cell))); - self.restore_reasoning_status_header(); - } - - fn flush_answer_stream_with_separator(&mut self) { - let had_stream_controller = self.stream_controller.is_some(); - if let Some(mut controller) = self.stream_controller.take() { - let scrollback_reflow = if controller.has_live_tail() { - crate::app_event::ConsolidationScrollbackReflow::Required - } else { - crate::app_event::ConsolidationScrollbackReflow::IfResizeReflowRan - }; - self.clear_active_stream_tail(); - let (cell, source) = controller.finalize(); - let deferred_history_cell = - if scrollback_reflow == crate::app_event::ConsolidationScrollbackReflow::Required { - cell - } else { - if let Some(cell) = cell { - self.add_boxed_history(cell); - } - None - }; - // Consolidate the run of streaming AgentMessageCells into a single AgentMarkdownCell - // that can re-render from source on resize. - if let Some(source) = source { - let source = parse_assistant_markdown(&source).visible_markdown; - self.app_event_tx.send(AppEvent::ConsolidateAgentMessage { - source, - cwd: self.config.cwd.to_path_buf(), - scrollback_reflow, - deferred_history_cell, - }); - } - } - self.adaptive_chunking.reset(); - if had_stream_controller && self.stream_controllers_idle() { - self.app_event_tx.send(AppEvent::StopCommitAnimation); - } - } - - fn stream_controllers_idle(&self) -> bool { - self.stream_controller - .as_ref() - .map(|controller| controller.queued_lines() == 0) - .unwrap_or(true) - && self - .plan_stream_controller - .as_ref() - .map(|controller| controller.queued_lines() == 0) - .unwrap_or(true) - } - - /// Restore the status indicator only after commentary completion is pending, - /// the turn is still running, and all stream queues have drained. - /// - /// This gate prevents flicker while normal output is still actively - /// streaming, but still restores a visible "working" affordance when a - /// commentary block ends before the turn itself has completed. - fn maybe_restore_status_indicator_after_stream_idle(&mut self) { - if !self.status_state.pending_status_indicator_restore - || !self.bottom_pane.is_task_running() - || !self.stream_controllers_idle() - { - return; - } - - self.bottom_pane.ensure_status_indicator(); - self.set_status( - self.status_state.current_status.header.clone(), - self.status_state.current_status.details.clone(), - StatusDetailsCapitalization::Preserve, - self.status_state.current_status.details_max_lines, - ); - self.status_state.pending_status_indicator_restore = false; - } - /// Update the status indicator header and details. /// /// Passing `None` clears any existing details. @@ -1175,32 +1077,6 @@ impl ChatWidget { self.refresh_status_surfaces(); } - fn collect_runtime_metrics_delta(&mut self) { - if let Some(delta) = self.session_telemetry.runtime_metrics_summary() { - self.apply_runtime_metrics_delta(delta); - } - } - - fn apply_runtime_metrics_delta(&mut self, delta: RuntimeMetricsSummary) { - let should_log_timing = has_websocket_timing_metrics(delta); - self.turn_runtime_metrics.merge(delta); - if should_log_timing { - self.log_websocket_timing_totals(delta); - } - } - - fn log_websocket_timing_totals(&mut self, delta: RuntimeMetricsSummary) { - if let Some(label) = history_cell::runtime_metrics_label(delta.responses_api_summary()) { - self.add_plain_history_lines(vec![ - vec!["• ".dim(), format!("WebSocket timing: {label}").dark_gray()].into(), - ]); - } - } - - fn refresh_runtime_metrics(&mut self) { - self.collect_runtime_metrics_delta(); - } - fn restore_retry_status_header_if_present(&mut self) { if let Some(header) = self.status_state.take_retry_status_header() { self.set_status_header(header); @@ -1474,390 +1350,6 @@ impl ChatWidget { self.request_redraw(); } - fn finalize_completed_assistant_message(&mut self, message: Option<&str>) { - // If we have a stream_controller, the finalized message payload is redundant because the - // visible content has already been accumulated through deltas. - if self.stream_controller.is_none() - && let Some(message) = message - && !message.is_empty() - { - self.handle_streaming_delta(message.to_string()); - } - self.flush_answer_stream_with_separator(); - self.handle_stream_finished(); - self.request_redraw(); - } - - fn on_agent_message_delta(&mut self, delta: String) { - self.handle_streaming_delta(delta); - } - - fn on_plan_delta(&mut self, delta: String) { - if self.active_mode_kind() != ModeKind::Plan { - return; - } - if !self.transcript.plan_item_active { - self.transcript.plan_item_active = true; - self.transcript.plan_delta_buffer.clear(); - } - self.transcript.plan_delta_buffer.push_str(&delta); - if self.plan_stream_controller.is_none() { - // Before starting a plan stream, flush any active exec cell group. - self.flush_unified_exec_wait_streak(); - self.flush_active_cell(); - self.plan_stream_controller = Some(PlanStreamController::new( - self.current_stream_width(/*reserved_cols*/ 4), - &self.config.cwd, - self.history_render_mode(), - )); - } - if let Some(controller) = self.plan_stream_controller.as_mut() - && controller.push(&delta) - { - self.app_event_tx.send(AppEvent::StartCommitAnimation); - self.run_catch_up_commit_tick(); - } - self.sync_active_stream_tail(); - self.request_redraw(); - } - - fn on_plan_item_completed(&mut self, text: String) { - let streamed_plan = self.transcript.plan_delta_buffer.trim().to_string(); - let plan_text = if text.trim().is_empty() { - streamed_plan - } else { - text - }; - if !plan_text.trim().is_empty() { - self.record_agent_markdown(&plan_text); - self.transcript.latest_proposed_plan_markdown = Some(plan_text.clone()); - } - // Plan commit ticks can hide the status row; remember whether we streamed plan output so - // completion can restore it once stream queues are idle. - let should_restore_after_stream = self.plan_stream_controller.is_some(); - self.transcript.plan_delta_buffer.clear(); - self.transcript.plan_item_active = false; - self.transcript.saw_plan_item_this_turn = true; - let (finalized_streamed_cell, consolidated_plan_source) = - if let Some(mut controller) = self.plan_stream_controller.take() { - let had_live_tail = controller.has_live_tail(); - self.clear_active_stream_tail(); - let (cell, source) = controller.finalize(); - if had_live_tail { - (None, source) - } else { - (cell, source) - } - } else { - (None, None) - }; - if let Some(cell) = finalized_streamed_cell { - self.add_boxed_history(cell); - // TODO: Replace streamed output with the final plan item text if plan streaming is - // removed or if we need to reconcile mismatches between streamed and final content. - if let Some(source) = consolidated_plan_source { - self.app_event_tx - .send(AppEvent::ConsolidateProposedPlan(source)); - } - } else if !plan_text.is_empty() { - self.add_to_history(history_cell::new_proposed_plan(plan_text, &self.config.cwd)); - } else if let Some(source) = consolidated_plan_source { - self.app_event_tx - .send(AppEvent::ConsolidateProposedPlan(source)); - } - if should_restore_after_stream { - self.status_state.pending_status_indicator_restore = true; - self.maybe_restore_status_indicator_after_stream_idle(); - } - } - - fn on_agent_reasoning_delta(&mut self, delta: String) { - // For reasoning deltas, do not stream to history. Accumulate the - // current reasoning block and extract the first bold element - // (between **/**) as the chunk header. Show this header as status. - self.reasoning_buffer.push_str(&delta); - - if self.unified_exec_wait_streak.is_some() { - // Unified exec waiting should take precedence over reasoning-derived status headers. - self.request_redraw(); - return; - } - - if let Some(header) = extract_first_bold(&self.reasoning_buffer) { - // Update the shimmer header to the extracted reasoning chunk header. - self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking; - self.set_status_header(header); - } else { - // Fallback while we don't yet have a bold header: leave existing header as-is. - } - self.request_redraw(); - } - - fn on_agent_reasoning_final(&mut self) { - // At the end of a reasoning block, record transcript-only content. - self.full_reasoning_buffer.push_str(&self.reasoning_buffer); - if !self.full_reasoning_buffer.is_empty() { - let cell = history_cell::new_reasoning_summary_block( - self.full_reasoning_buffer.clone(), - &self.config.cwd, - ); - self.add_boxed_history(cell); - } - self.reasoning_buffer.clear(); - self.full_reasoning_buffer.clear(); - self.request_redraw(); - } - - fn on_reasoning_section_break(&mut self) { - // Start a new reasoning block for header extraction and accumulate transcript. - self.full_reasoning_buffer.push_str(&self.reasoning_buffer); - self.full_reasoning_buffer.push_str("\n\n"); - self.reasoning_buffer.clear(); - } - - // Raw reasoning uses the same flow as summarized reasoning - - fn on_task_started(&mut self) { - self.input_queue.user_turn_pending_start = false; - self.turn_lifecycle.start(Instant::now()); - self.transcript.reset_turn_flags(); - self.adaptive_chunking.reset(); - self.plan_stream_controller = None; - self.turn_runtime_metrics = RuntimeMetricsSummary::default(); - self.session_telemetry.reset_runtime_metrics(); - self.bottom_pane.clear_quit_shortcut_hint(); - self.quit_shortcut_expires_at = None; - self.quit_shortcut_key = None; - self.update_task_running_state(); - self.status_state.retry_status_header = None; - if self.active_hook_cell.take().is_some() { - self.bump_active_cell_revision(); - } - self.status_state.pending_status_indicator_restore = false; - self.bottom_pane - .set_interrupt_hint_visible(/*visible*/ true); - self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Working; - self.set_status_header(String::from("Working")); - self.full_reasoning_buffer.clear(); - self.reasoning_buffer.clear(); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Running, - /*body*/ None, - ); - self.request_redraw(); - } - - fn on_task_complete( - &mut self, - last_agent_message: Option, - duration_ms: Option, - from_replay: bool, - ) { - self.input_queue.submit_pending_steers_after_interrupt = false; - // Use `last_agent_message` from the turn-complete notification as the copy - // source only when no earlier item-level event (AgentMessageItem, plan - // commit, review output) already recorded markdown for this turn. This - // prevents the final summary from overwriting a more specific source. - let sanitized_last_agent_message = last_agent_message - .as_deref() - .map(|message| parse_assistant_markdown(message).visible_markdown); - if let Some(message) = sanitized_last_agent_message - .as_ref() - .filter(|message| !message.is_empty()) - && !self.transcript.saw_copy_source_this_turn - { - self.record_agent_markdown(message); - } - // For desktop notifications: prefer the notification payload, fall back to - // the item-level copy source if present, otherwise send an empty string. - let notification_response = sanitized_last_agent_message - .as_ref() - .filter(|message| !message.is_empty()) - .cloned() - .or_else(|| { - if self.transcript.saw_copy_source_this_turn { - self.transcript.last_agent_markdown.clone() - } else { - None - } - }) - .unwrap_or_default(); - self.transcript.saw_copy_source_this_turn = false; - // If a stream is currently active, finalize it. - self.flush_answer_stream_with_separator(); - if let Some(mut controller) = self.plan_stream_controller.take() { - let had_live_tail = controller.has_live_tail(); - self.clear_active_stream_tail(); - let (cell, source) = controller.finalize(); - if !had_live_tail && let Some(cell) = cell { - self.add_boxed_history(cell); - } - if let Some(source) = source { - self.app_event_tx - .send(AppEvent::ConsolidateProposedPlan(source)); - } - } - self.flush_unified_exec_wait_streak(); - if !from_replay { - self.collect_runtime_metrics_delta(); - let runtime_metrics = - (!self.turn_runtime_metrics.is_empty()).then_some(self.turn_runtime_metrics); - let show_work_separator = self.transcript.had_work_activity - && (self.transcript.needs_final_message_separator || runtime_metrics.is_some()); - if show_work_separator || runtime_metrics.is_some() { - let elapsed_seconds = if show_work_separator { - duration_ms - .and_then(|duration_ms| u64::try_from(duration_ms).ok()) - .map(|duration_ms| duration_ms / 1_000) - .or_else(|| { - self.bottom_pane - .status_widget() - .map(super::status_indicator_widget::StatusIndicatorWidget::elapsed_seconds) - }) - } else { - None - }; - self.add_to_history(history_cell::FinalMessageSeparator::new( - elapsed_seconds, - runtime_metrics, - )); - } - self.turn_runtime_metrics = RuntimeMetricsSummary::default(); - self.transcript.needs_final_message_separator = false; - self.transcript.had_work_activity = false; - self.request_status_line_branch_refresh(); - self.request_status_line_git_summary_refresh(); - } - // Mark task stopped and request redraw now that all content is in history. - self.status_state.pending_status_indicator_restore = false; - self.input_queue.user_turn_pending_start = false; - self.turn_lifecycle.finish(); - self.update_task_running_state(); - self.running_commands.clear(); - self.suppressed_exec_calls.clear(); - self.last_unified_wait = None; - self.unified_exec_wait_streak = None; - if !from_replay { - let body = Notification::agent_turn_preview(¬ification_response); - self.set_ambient_pet_notification(crate::pets::PetNotificationKind::Review, body); - } - self.request_redraw(); - - let had_pending_steers = !self.input_queue.pending_steers.is_empty(); - self.refresh_pending_input_preview(); - - if !from_replay && !self.has_queued_follow_up_messages() && !had_pending_steers { - self.maybe_prompt_plan_implementation(); - } - // Keep this flag for replayed completion events so a subsequent live TurnComplete can - // still show the prompt once after thread switch replay. - if !from_replay { - self.transcript.saw_plan_item_this_turn = false; - } - // If there is a queued user message, send exactly one now to begin the next turn. - let follow_up_started = self.maybe_send_next_queued_input(); - let active_goal_continuing = self - .current_goal_status - .as_ref() - .is_some_and(GoalStatusState::is_active); - // Emit a notification when the agent is truly waiting for the user. - // Queued follow-up input and active goal continuation both start the - // next turn immediately, so notifying at that boundary would feel like - // a false "needs attention". - if !follow_up_started && !active_goal_continuing { - self.notify(Notification::AgentTurnComplete { - response: notification_response, - }); - } - - self.maybe_show_pending_rate_limit_prompt(); - } - - fn maybe_prompt_plan_implementation(&mut self) { - if !self.collaboration_modes_enabled() { - return; - } - if self.has_queued_follow_up_messages() { - return; - } - if self.active_mode_kind() != ModeKind::Plan { - return; - } - if !self.transcript.saw_plan_item_this_turn { - return; - } - if !self.bottom_pane.no_modal_or_popup_active() { - return; - } - - if matches!( - self.rate_limit_switch_prompt, - RateLimitSwitchPromptState::Pending - ) { - return; - } - - self.open_plan_implementation_prompt(); - } - - fn open_plan_implementation_prompt(&mut self) { - let default_mask = collaboration_modes::default_mode_mask(self.model_catalog.as_ref()); - let context_usage_label = self.plan_implementation_context_usage_label(); - - self.bottom_pane - .show_selection_view(plan_implementation::selection_view_params( - default_mask, - self.transcript.latest_proposed_plan_markdown.as_deref(), - context_usage_label.as_deref(), - )); - self.notify(Notification::PlanModePrompt { - title: PLAN_IMPLEMENTATION_TITLE.to_string(), - }); - } - - /// Returns a context-used label for the plan implementation prompt. - /// - /// The footer reports context remaining because it is ambient status, but - /// this prompt is asking whether to discard prior conversation state before - /// implementing a plan. Reporting used context makes the cleanup tradeoff - /// explicit. A fully fresh or unknown context window returns no label so - /// the clear-context option does not imply urgency without evidence. - fn plan_implementation_context_usage_label(&self) -> Option { - let info = self.token_info.as_ref()?; - let percent = self.context_remaining_percent(info); - - let used_tokens = self.context_used_tokens(info, percent.is_some()); - if let Some(percent) = percent { - let used_percent = 100 - percent.clamp(0, 100); - if used_percent <= 0 { - return None; - } - return Some(format!("{used_percent}% used")); - } - - if let Some(tokens) = used_tokens - && tokens > 0 - { - return Some(format!("{} used", format_tokens_compact(tokens))); - } - - None - } - - fn has_queued_follow_up_messages(&self) -> bool { - self.input_queue.has_queued_follow_up_messages() - } - - fn handle_app_server_steer_rejected_error( - &mut self, - codex_error_info: &AppServerCodexErrorInfo, - ) -> bool { - matches!( - codex_error_info, - AppServerCodexErrorInfo::ActiveTurnNotSteerable { .. } - ) && self.enqueue_rejected_steer() - } - pub(crate) fn open_multi_agent_enable_prompt(&mut self) { let items = vec![ SelectionItem { @@ -2095,799 +1587,6 @@ impl ChatWidget { } self.refresh_status_line(); } - /// Finalize any active exec as failed and stop/clear agent-turn UI state. - /// - /// This does not clear MCP startup tracking, because MCP startup can overlap with turn cleanup - /// and should continue to drive the bottom-pane running indicator while it is in progress. - fn finalize_turn(&mut self) { - // Drop preview-only stream tail content on any termination path before - // failed-cell finalization, so transient tail cells are never persisted. - self.clear_active_stream_tail(); - // Ensure any spinner is replaced by a red ✗ and flushed into history. - self.finalize_active_cell_as_failed(); - // Turn-scoped hook rows are transient live state; once the turn is over, - // do not leave an orphaned running row behind if no matching completion - // event arrived before cancellation. - if self.active_hook_cell.take().is_some() { - self.bump_active_cell_revision(); - } - // Reset running state and clear streaming buffers. - self.input_queue.user_turn_pending_start = false; - self.turn_lifecycle.finish(); - self.update_task_running_state(); - self.running_commands.clear(); - self.suppressed_exec_calls.clear(); - self.last_unified_wait = None; - self.unified_exec_wait_streak = None; - self.adaptive_chunking.reset(); - self.stream_controller = None; - self.plan_stream_controller = None; - self.status_state.pending_status_indicator_restore = false; - self.request_status_line_branch_refresh(); - self.request_status_line_git_summary_refresh(); - self.maybe_show_pending_rate_limit_prompt(); - } - - fn on_server_overloaded_error(&mut self, message: String) { - self.input_queue.submit_pending_steers_after_interrupt = false; - self.finalize_turn(); - - let message = if message.trim().is_empty() { - "Codex is currently experiencing high load.".to_string() - } else { - message - }; - - self.add_to_history(history_cell::new_warning_event(message)); - self.request_redraw(); - self.maybe_send_next_queued_input(); - } - - fn on_error(&mut self, message: String) { - self.input_queue.submit_pending_steers_after_interrupt = false; - self.finalize_turn(); - self.add_to_history(history_cell::new_error_event(message)); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Failed, - /*body*/ None, - ); - self.request_redraw(); - - // After an error ends the turn, try sending the next queued input. - self.maybe_send_next_queued_input(); - } - - fn on_cyber_policy_error(&mut self) { - self.input_queue.submit_pending_steers_after_interrupt = false; - self.finalize_turn(); - self.add_to_history(history_cell::new_cyber_policy_error_event()); - self.request_redraw(); - - // After an error ends the turn, try sending the next queued input. - self.maybe_send_next_queued_input(); - } - - fn on_rate_limit_error(&mut self, error_kind: RateLimitErrorKind, message: String) { - let rate_limit_reached_type = self.codex_rate_limit_reached_type.map(|kind| { - if matches!(error_kind, RateLimitErrorKind::UsageLimit) { - match kind { - RateLimitReachedType::WorkspaceOwnerCreditsDepleted => { - RateLimitReachedType::WorkspaceOwnerUsageLimitReached - } - RateLimitReachedType::WorkspaceMemberCreditsDepleted => { - RateLimitReachedType::WorkspaceMemberUsageLimitReached - } - other => other, - } - } else { - kind - } - }); - self.codex_rate_limit_reached_type = rate_limit_reached_type; - - match rate_limit_reached_type { - Some(RateLimitReachedType::WorkspaceOwnerCreditsDepleted) => { - self.on_error( - "You're out of credits. Your workspace is out of credits. Add credits to continue using Codex." - .to_string(), - ); - } - Some(RateLimitReachedType::WorkspaceOwnerUsageLimitReached) => { - self.on_error( - "Usage limit reached. You've reached your usage limit. Increase your limits to continue using codex." - .to_string(), - ); - } - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted) => { - self.on_error(message); - self.open_workspace_owner_nudge_prompt(AddCreditsNudgeCreditType::Credits); - } - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached) => { - self.on_error(message); - self.open_workspace_owner_nudge_prompt(AddCreditsNudgeCreditType::UsageLimit); - } - Some(RateLimitReachedType::RateLimitReached) | None => { - self.on_error(message); - } - } - } - - fn handle_non_retry_error( - &mut self, - message: String, - codex_error_info: Option, - ) { - if codex_error_info - .as_ref() - .is_some_and(|info| self.handle_app_server_steer_rejected_error(info)) - { - } else if codex_error_info - .as_ref() - .is_some_and(is_app_server_cyber_policy_error) - { - self.on_cyber_policy_error(); - } else if let Some(info) = codex_error_info - .as_ref() - .and_then(app_server_rate_limit_error_kind) - { - match info { - RateLimitErrorKind::ServerOverloaded => self.on_server_overloaded_error(message), - RateLimitErrorKind::UsageLimit | RateLimitErrorKind::Generic => { - self.on_rate_limit_error(info, message) - } - } - } else { - self.on_error(message); - } - } - - fn on_warning(&mut self, message: impl Into) { - let message = message.into(); - if !self.warning_display_state.should_display(&message) { - return; - } - self.add_to_history(history_cell::new_warning_event(message)); - self.request_redraw(); - } - - fn on_app_server_model_verification(&mut self, verifications: &[AppServerModelVerification]) { - if verifications.contains(&AppServerModelVerification::TrustedAccessForCyber) { - self.on_warning(TRUSTED_ACCESS_FOR_CYBER_VERIFICATION_WARNING); - } - } - - fn on_plan_update(&mut self, update: UpdatePlanArgs) { - self.transcript.saw_plan_update_this_turn = true; - let total = update.plan.len(); - let completed = update - .plan - .iter() - .filter(|item| match &item.status { - StepStatus::Completed => true, - StepStatus::Pending | StepStatus::InProgress => false, - }) - .count(); - self.transcript.last_plan_progress = (total > 0).then_some((completed, total)); - self.refresh_status_surfaces(); - self.add_to_history(history_cell::new_plan_update(update)); - } - - fn on_exec_approval_request(&mut self, _id: String, ev: ExecApprovalRequestEvent) { - let ev2 = ev.clone(); - self.defer_or_handle( - |q| q.push_exec_approval(ev), - |s| s.handle_exec_approval_now(ev2), - ); - } - - fn on_apply_patch_approval_request(&mut self, _id: String, ev: ApplyPatchApprovalRequestEvent) { - let ev2 = ev.clone(); - self.defer_or_handle( - |q| q.push_apply_patch_approval(ev), - |s| s.handle_apply_patch_approval_now(ev2), - ); - } - - /// Handle guardian review lifecycle events for the current thread. - /// - /// In-progress assessments temporarily own the live status footer so the - /// user can see what is being reviewed, including parallel review - /// aggregation. Terminal assessments clear or update that footer state and - /// render the final approved/denied history cell when guardian returns a - /// decision. - fn on_guardian_assessment(&mut self, ev: GuardianAssessmentEvent) { - let permission_request_summary = |subject: &str, reason: &Option| { - reason - .as_deref() - .map(str::trim) - .filter(|reason| !reason.is_empty()) - .map(|reason| format!("{subject}: {reason}")) - .unwrap_or_else(|| subject.to_string()) - }; - let guardian_action_summary = |action: &GuardianAssessmentAction| match action { - GuardianAssessmentAction::Command { command, .. } => Some(command.clone()), - GuardianAssessmentAction::Execve { program, argv, .. } => { - let command = if argv.is_empty() { - vec![program.clone()] - } else { - argv.clone() - }; - shlex::try_join(command.iter().map(String::as_str)) - .ok() - .or_else(|| Some(command.join(" "))) - } - GuardianAssessmentAction::ApplyPatch { files, .. } => Some(if files.len() == 1 { - format!("apply_patch touching {}", files[0].display()) - } else { - format!("apply_patch touching {} files", files.len()) - }), - GuardianAssessmentAction::NetworkAccess { target, .. } => { - Some(format!("network access to {target}")) - } - GuardianAssessmentAction::McpToolCall { - server, - tool_name, - connector_name, - .. - } => { - let label = connector_name.as_deref().unwrap_or(server.as_str()); - Some(format!("MCP {tool_name} on {label}")) - } - GuardianAssessmentAction::RequestPermissions { reason, .. } => { - Some(permission_request_summary("permission request", reason)) - } - }; - let guardian_command = |action: &GuardianAssessmentAction| match action { - GuardianAssessmentAction::Command { command, .. } => shlex::split(command) - .filter(|command| !command.is_empty()) - .or_else(|| Some(vec![command.clone()])), - GuardianAssessmentAction::Execve { program, argv, .. } => Some(if argv.is_empty() { - vec![program.clone()] - } else { - argv.clone() - }) - .filter(|command| !command.is_empty()), - GuardianAssessmentAction::ApplyPatch { .. } - | GuardianAssessmentAction::NetworkAccess { .. } - | GuardianAssessmentAction::McpToolCall { .. } - | GuardianAssessmentAction::RequestPermissions { .. } => None, - }; - - if ev.status == GuardianAssessmentStatus::InProgress - && let Some(detail) = guardian_action_summary(&ev.action) - { - // In-progress assessments own the live footer state while the - // review is pending. Parallel reviews are aggregated into one - // footer summary by `PendingGuardianReviewStatus`. - self.bottom_pane.ensure_status_indicator(); - self.bottom_pane - .set_interrupt_hint_visible(/*visible*/ true); - self.status_state - .pending_guardian_review_status - .start_or_update(ev.id.clone(), detail); - if let Some(status) = self - .status_state - .pending_guardian_review_status - .status_indicator_state() - { - self.set_status( - status.header, - status.details, - StatusDetailsCapitalization::Preserve, - status.details_max_lines, - ); - } - self.request_redraw(); - return; - } - - // Terminal assessments remove the matching pending footer entry first, - // then render the final approved/denied history cell below. - if self - .status_state - .pending_guardian_review_status - .finish(&ev.id) - { - if let Some(status) = self - .status_state - .pending_guardian_review_status - .status_indicator_state() - { - self.set_status( - status.header, - status.details, - StatusDetailsCapitalization::Preserve, - status.details_max_lines, - ); - } else if self.status_state.current_status.is_guardian_review() { - self.set_status_header(String::from("Working")); - } - } else if self.status_state.pending_guardian_review_status.is_empty() - && self.status_state.current_status.is_guardian_review() - { - self.set_status_header(String::from("Working")); - } - - if ev.status == GuardianAssessmentStatus::Approved { - let cell = if let Some(command) = guardian_command(&ev.action) { - history_cell::new_approval_decision_cell( - command, - crate::history_cell::ReviewDecision::Approved, - history_cell::ApprovalDecisionActor::Guardian, - ) - } else if let Some(summary) = guardian_action_summary(&ev.action) { - history_cell::new_guardian_approved_action_request(summary) - } else { - let summary = serde_json::to_string(&ev.action) - .unwrap_or_else(|_| "".to_string()); - history_cell::new_guardian_approved_action_request(summary) - }; - - self.add_boxed_history(cell); - self.request_redraw(); - return; - } - - if ev.status == GuardianAssessmentStatus::TimedOut { - let cell = if let Some(command) = guardian_command(&ev.action) { - history_cell::new_approval_decision_cell( - command, - crate::history_cell::ReviewDecision::TimedOut, - history_cell::ApprovalDecisionActor::Guardian, - ) - } else { - match &ev.action { - GuardianAssessmentAction::ApplyPatch { files, .. } => { - let files = files - .iter() - .map(|path| path.display().to_string()) - .collect::>(); - history_cell::new_guardian_timed_out_patch_request(files) - } - GuardianAssessmentAction::McpToolCall { - server, tool_name, .. - } => history_cell::new_guardian_timed_out_action_request(format!( - "codex could call MCP tool {server}.{tool_name}" - )), - GuardianAssessmentAction::NetworkAccess { target, .. } => { - history_cell::new_guardian_timed_out_action_request(format!( - "codex could access {target}" - )) - } - GuardianAssessmentAction::RequestPermissions { reason, .. } => { - history_cell::new_guardian_timed_out_action_request( - permission_request_summary("codex could request permissions", reason), - ) - } - GuardianAssessmentAction::Command { .. } => unreachable!(), - GuardianAssessmentAction::Execve { .. } => unreachable!(), - } - }; - - self.add_boxed_history(cell); - self.request_redraw(); - return; - } - - if ev.status != GuardianAssessmentStatus::Denied { - return; - } - self.review.recent_auto_review_denials.push(ev.clone()); - let cell = if let Some(command) = guardian_command(&ev.action) { - history_cell::new_approval_decision_cell( - command, - crate::history_cell::ReviewDecision::Denied, - history_cell::ApprovalDecisionActor::Guardian, - ) - } else { - match &ev.action { - GuardianAssessmentAction::ApplyPatch { files, .. } => { - let files = files - .iter() - .map(|path| path.display().to_string()) - .collect::>(); - history_cell::new_guardian_denied_patch_request(files) - } - GuardianAssessmentAction::McpToolCall { - server, tool_name, .. - } => history_cell::new_guardian_denied_action_request(format!( - "codex to call MCP tool {server}.{tool_name}" - )), - GuardianAssessmentAction::NetworkAccess { target, .. } => { - history_cell::new_guardian_denied_action_request(format!( - "codex to access {target}" - )) - } - GuardianAssessmentAction::RequestPermissions { reason, .. } => { - history_cell::new_guardian_denied_action_request(permission_request_summary( - "codex to request permissions", - reason, - )) - } - GuardianAssessmentAction::Command { .. } => unreachable!(), - GuardianAssessmentAction::Execve { .. } => unreachable!(), - } - }; - - self.add_boxed_history(cell); - self.request_redraw(); - } - - fn on_elicitation_request( - &mut self, - request_id: AppServerRequestId, - params: McpServerElicitationRequestParams, - ) { - let request_id2 = request_id.clone(); - let params2 = params.clone(); - self.defer_or_handle( - |q| q.push_elicitation(request_id, params), - |s| s.handle_elicitation_request_now(request_id2, params2), - ); - } - - fn on_request_user_input(&mut self, ev: ToolRequestUserInputParams) { - let ev2 = ev.clone(); - self.defer_or_handle( - |q| q.push_user_input(ev), - |s| s.handle_request_user_input_now(ev2), - ); - } - - fn on_request_permissions(&mut self, ev: RequestPermissionsEvent) { - let ev2 = ev.clone(); - self.defer_or_handle( - |q| q.push_request_permissions(ev), - |s| s.handle_request_permissions_now(ev2), - ); - } - - fn on_command_execution_started(&mut self, item: ThreadItem) { - let ThreadItem::CommandExecution { - id, - command, - process_id, - source, - command_actions, - .. - } = &item - else { - return; - }; - let (_command, parsed_cmd) = command_execution_command_and_parsed(command, command_actions); - self.flush_answer_stream_with_separator(); - if is_unified_exec_source(*source) { - if *source == ExecCommandSource::UnifiedExecStartup { - self.track_unified_exec_process_begin(id, process_id.as_deref(), command); - } - if !self.bottom_pane.is_task_running() { - return; - } - // Unified exec may be parsed as Unknown; keep the working indicator visible regardless. - self.bottom_pane.ensure_status_indicator(); - if !is_standard_tool_call(&parsed_cmd) { - return; - } - } - let item2 = item.clone(); - self.defer_or_handle( - |q| q.push_item_started(item), - |s| s.handle_command_execution_started_now(item2), - ); - } - - fn on_exec_command_output_delta(&mut self, call_id: &str, delta: &str) { - self.track_unified_exec_output_chunk(call_id, delta.as_bytes()); - if !self.bottom_pane.is_task_running() { - return; - } - - let Some(cell) = self - .transcript - .active_cell - .as_mut() - .and_then(|c| c.as_any_mut().downcast_mut::()) - else { - return; - }; - - if cell.append_output(call_id, delta) { - self.bump_active_cell_revision(); - self.request_redraw(); - } - } - - fn on_terminal_interaction(&mut self, process_id: String, stdin: String) { - if !self.bottom_pane.is_task_running() { - return; - } - self.flush_answer_stream_with_separator(); - let command_display = self - .unified_exec_processes - .iter() - .find(|process| process.key == process_id) - .map(|process| process.command_display.clone()); - if stdin.is_empty() { - // Empty stdin means we are polling for background output. - // Surface this in the status indicator (single "waiting" surface) instead of - // the transcript. Keep the header short so the interrupt hint remains visible. - self.bottom_pane.ensure_status_indicator(); - self.bottom_pane - .set_interrupt_hint_visible(/*visible*/ true); - self.status_state.terminal_title_status_kind = - TerminalTitleStatusKind::WaitingForBackgroundTerminal; - self.set_status( - "Waiting for background terminal".to_string(), - command_display.clone(), - StatusDetailsCapitalization::Preserve, - /*details_max_lines*/ 1, - ); - match &mut self.unified_exec_wait_streak { - Some(wait) if wait.process_id == process_id => { - wait.update_command_display(command_display); - } - Some(_) => { - self.flush_unified_exec_wait_streak(); - self.unified_exec_wait_streak = - Some(UnifiedExecWaitStreak::new(process_id, command_display)); - } - None => { - self.unified_exec_wait_streak = - Some(UnifiedExecWaitStreak::new(process_id, command_display)); - } - } - self.request_redraw(); - } else { - if self - .unified_exec_wait_streak - .as_ref() - .is_some_and(|wait| wait.process_id == process_id) - { - self.flush_unified_exec_wait_streak(); - } - self.add_to_history(history_cell::new_unified_exec_interaction( - command_display, - stdin, - )); - } - } - - fn on_patch_apply_begin(&mut self, changes: HashMap) { - self.add_to_history(history_cell::new_patch_event(changes, &self.config.cwd)); - } - - fn on_view_image_tool_call(&mut self, path: AbsolutePathBuf) { - self.flush_answer_stream_with_separator(); - self.add_to_history(history_cell::new_view_image_tool_call( - path, - &self.config.cwd, - )); - self.request_redraw(); - } - - fn on_image_generation_begin(&mut self) { - self.flush_answer_stream_with_separator(); - } - - fn on_image_generation_end( - &mut self, - call_id: String, - revised_prompt: Option, - saved_path: Option, - ) { - self.flush_answer_stream_with_separator(); - self.add_to_history(history_cell::new_image_generation_call( - call_id, - revised_prompt, - saved_path, - )); - self.request_redraw(); - } - - fn on_file_change_completed(&mut self, item: ThreadItem) { - let item2 = item.clone(); - self.defer_or_handle( - |q| q.push_item_completed(item), - |s| s.handle_file_change_completed_now(item2), - ); - } - - fn on_command_execution_completed(&mut self, item: ThreadItem) { - let ThreadItem::CommandExecution { - id, - process_id, - source, - .. - } = &item - else { - return; - }; - if is_unified_exec_source(*source) { - if let Some(process_id) = process_id.as_deref() - && self - .unified_exec_wait_streak - .as_ref() - .is_some_and(|wait| wait.process_id == process_id) - { - self.flush_unified_exec_wait_streak(); - } - self.track_unified_exec_process_end(id, process_id.as_deref()); - if !self.bottom_pane.is_task_running() { - return; - } - } - let item2 = item.clone(); - self.defer_or_handle( - |q| q.push_item_completed(item), - |s| s.handle_command_execution_completed_now(item2), - ); - } - - fn track_unified_exec_process_begin( - &mut self, - call_id: &str, - process_id: Option<&str>, - command: &str, - ) { - let key = process_id.unwrap_or(call_id).to_string(); - let command = split_command_string(command); - let command_display = strip_bash_lc_and_escape(&command); - if let Some(existing) = self - .unified_exec_processes - .iter_mut() - .find(|process| process.key == key) - { - existing.call_id = call_id.to_string(); - existing.command_display = command_display; - existing.recent_chunks.clear(); - } else { - self.unified_exec_processes.push(UnifiedExecProcessSummary { - key, - call_id: call_id.to_string(), - command_display, - recent_chunks: Vec::new(), - }); - } - self.sync_unified_exec_footer(); - } - - fn track_unified_exec_process_end(&mut self, call_id: &str, process_id: Option<&str>) { - let key = process_id.unwrap_or(call_id); - let before = self.unified_exec_processes.len(); - self.unified_exec_processes - .retain(|process| process.key != key); - if self.unified_exec_processes.len() != before { - self.sync_unified_exec_footer(); - } - } - - fn sync_unified_exec_footer(&mut self) { - let processes = self - .unified_exec_processes - .iter() - .map(|process| process.command_display.clone()) - .collect(); - self.bottom_pane.set_unified_exec_processes(processes); - } - - /// Record recent stdout/stderr lines for the unified exec footer. - fn track_unified_exec_output_chunk(&mut self, call_id: &str, chunk: &[u8]) { - let Some(process) = self - .unified_exec_processes - .iter_mut() - .find(|process| process.call_id == call_id) - else { - return; - }; - - let text = String::from_utf8_lossy(chunk); - for line in text - .lines() - .map(str::trim_end) - .filter(|line| !line.is_empty()) - { - process.recent_chunks.push(line.to_string()); - } - - const MAX_RECENT_CHUNKS: usize = 3; - if process.recent_chunks.len() > MAX_RECENT_CHUNKS { - let drop_count = process.recent_chunks.len() - MAX_RECENT_CHUNKS; - process.recent_chunks.drain(0..drop_count); - } - } - - fn on_mcp_tool_call_started(&mut self, item: ThreadItem) { - let item2 = item.clone(); - self.defer_or_handle( - |q| q.push_item_started(item), - |s| s.handle_mcp_tool_call_started_now(item2), - ); - } - - fn on_mcp_tool_call_completed(&mut self, item: ThreadItem) { - let item2 = item.clone(); - self.defer_or_handle( - |q| q.push_item_completed(item), - |s| s.handle_mcp_tool_call_completed_now(item2), - ); - } - - fn on_web_search_begin(&mut self, call_id: String) { - self.flush_answer_stream_with_separator(); - self.flush_active_cell(); - self.transcript.active_cell = Some(Box::new(history_cell::new_active_web_search_call( - call_id, - String::new(), - self.config.animations, - ))); - self.bump_active_cell_revision(); - self.request_redraw(); - } - - fn on_web_search_end( - &mut self, - call_id: String, - query: String, - action: codex_app_server_protocol::WebSearchAction, - ) { - self.flush_answer_stream_with_separator(); - let mut handled = false; - if let Some(cell) = self - .transcript - .active_cell - .as_mut() - .and_then(|cell| cell.as_any_mut().downcast_mut::()) - && cell.call_id() == call_id - { - cell.update(action.clone(), query.clone()); - cell.complete(); - self.bump_active_cell_revision(); - self.flush_active_cell(); - handled = true; - } - - if !handled { - self.add_to_history(history_cell::new_web_search_call(call_id, query, action)); - } - self.transcript.had_work_activity = true; - } - - fn on_collab_event(&mut self, cell: PlainHistoryCell) { - self.flush_answer_stream_with_separator(); - self.add_to_history(cell); - self.request_redraw(); - } - - fn on_collab_agent_tool_call(&mut self, item: ThreadItem) { - let ThreadItem::CollabAgentToolCall { - id, tool, status, .. - } = &item - else { - return; - }; - if matches!(tool, CollabAgentTool::SpawnAgent) - && let Some(spawn_request) = multi_agents::spawn_request_summary(&item) - { - self.pending_collab_spawn_requests - .insert(id.clone(), spawn_request); - } - - let cached_spawn_request = if matches!(tool, CollabAgentTool::SpawnAgent) - && !matches!(status, CollabAgentToolCallStatus::InProgress) - { - self.pending_collab_spawn_requests.remove(id) - } else { - None - }; - - if let Some(cell) = multi_agents::tool_call_history_cell( - &item, - cached_spawn_request.as_ref(), - |thread_id| self.collab_agent_metadata(thread_id), - ) { - self.on_collab_event(cell); - } - } pub(crate) fn handle_history_entry_response(&mut self, event: HistoryLookupResponse) { let HistoryLookupResponse { @@ -2899,161 +1598,6 @@ impl ChatWidget { .on_history_entry_response(log_id, offset, entry); } - fn on_shutdown_complete(&mut self) { - self.request_immediate_exit(); - } - - fn on_turn_diff(&mut self, unified_diff: String) { - debug!("TurnDiffEvent: {unified_diff}"); - self.refresh_status_line(); - } - - fn interrupted_turn_message(&self, reason: TurnAbortReason) -> String { - if reason == TurnAbortReason::BudgetLimited { - return "Goal budget reached - the turn was stopped.".to_string(); - } - - "Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.".to_string() - } - - fn on_deprecation_notice(&mut self, summary: String, details: Option) { - self.add_to_history(history_cell::new_deprecation_notice(summary, details)); - self.request_redraw(); - } - - fn on_hook_started(&mut self, run: codex_app_server_protocol::HookRunSummary) { - self.flush_answer_stream_with_separator(); - self.flush_completed_hook_output(); - match self.active_hook_cell.as_mut() { - Some(cell) => { - cell.start_run(run); - self.bump_active_cell_revision(); - } - None => { - self.active_hook_cell = Some(history_cell::new_active_hook_cell( - run, - self.config.animations, - )); - self.bump_active_cell_revision(); - } - } - self.request_redraw(); - } - - fn on_hook_completed(&mut self, completed: codex_app_server_protocol::HookRunSummary) { - let completed_existing_run = self - .active_hook_cell - .as_mut() - .map(|cell| cell.complete_run(completed.clone())) - .unwrap_or(false); - if completed_existing_run { - self.bump_active_cell_revision(); - } else { - match self.active_hook_cell.as_mut() { - Some(cell) => { - cell.add_completed_run(completed); - self.bump_active_cell_revision(); - } - None => { - let cell = - history_cell::new_completed_hook_cell(completed, self.config.animations); - if !cell.is_empty() { - self.active_hook_cell = Some(cell); - self.bump_active_cell_revision(); - } - } - } - } - self.flush_completed_hook_output(); - self.finish_active_hook_cell_if_idle(); - self.request_redraw(); - } - - fn flush_completed_hook_output(&mut self) { - let Some(completed_cell) = self - .active_hook_cell - .as_mut() - .and_then(HookCell::take_completed_persistent_runs) - else { - return; - }; - let active_cell_is_empty = self - .active_hook_cell - .as_ref() - .is_some_and(HookCell::is_empty); - if active_cell_is_empty { - self.active_hook_cell = None; - } - self.bump_active_cell_revision(); - self.transcript.needs_final_message_separator = true; - self.app_event_tx - .send(AppEvent::InsertHistoryCell(Box::new(completed_cell))); - } - - fn finish_active_hook_cell_if_idle(&mut self) { - let Some(cell) = self.active_hook_cell.as_ref() else { - return; - }; - if cell.is_empty() { - self.active_hook_cell = None; - self.bump_active_cell_revision(); - return; - } - if cell.should_flush() - && let Some(cell) = self.active_hook_cell.take() - { - self.bump_active_cell_revision(); - self.transcript.needs_final_message_separator = true; - self.app_event_tx - .send(AppEvent::InsertHistoryCell(Box::new(cell))); - } - } - - fn update_due_hook_visibility(&mut self) { - let Some(cell) = self.active_hook_cell.as_mut() else { - return; - }; - let now = Instant::now(); - if cell.advance_time(now) { - self.bump_active_cell_revision(); - } - self.finish_active_hook_cell_if_idle(); - } - - fn schedule_hook_timer_if_needed(&self) { - if self.config.animations - && self - .active_hook_cell - .as_ref() - .is_some_and(HookCell::has_visible_running_run) - { - self.frame_requester - .schedule_frame_in(Duration::from_millis(50)); - } - - let Some(deadline) = self - .active_hook_cell - .as_ref() - .and_then(HookCell::next_timer_deadline) - else { - return; - }; - let delay = deadline.saturating_duration_since(Instant::now()); - self.frame_requester.schedule_frame_in(delay); - } - - fn on_stream_error(&mut self, message: String, additional_details: Option) { - self.status_state.remember_retry_status_header(); - self.bottom_pane.ensure_status_indicator(); - self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking; - self.set_status( - message, - additional_details, - StatusDetailsCapitalization::CapitalizeFirst, - STATUS_DETAILS_DEFAULT_MAX_LINES, - ); - } - pub(crate) fn pre_draw_tick(&mut self) { self.update_due_hook_visibility(); self.schedule_hook_timer_if_needed(); @@ -3073,668 +1617,6 @@ impl ChatWidget { } } - /// Handle completion of an `AgentMessage` turn item. - /// - /// Commentary completion sets a deferred restore flag so the status row - /// returns once stream queues are idle. Final-answer completion (or absent - /// phase for legacy models) clears the flag to preserve historical behavior. - fn on_agent_message_item_completed(&mut self, item: AgentMessageItem, from_replay: bool) { - let mut message = String::new(); - for content in &item.content { - match content { - AgentMessageContent::Text { text } => message.push_str(text), - } - } - let parsed = parse_assistant_markdown(&message); - self.finalize_completed_assistant_message( - (!parsed.visible_markdown.is_empty()).then_some(parsed.visible_markdown.as_str()), - ); - if matches!(item.phase, Some(MessagePhase::FinalAnswer) | None) - && !parsed.visible_markdown.is_empty() - { - self.record_agent_markdown(&parsed.visible_markdown); - } - if !from_replay - && let Some(cwd) = parsed.last_created_branch_cwd() - && let Some(thread_id) = self.thread_id - && let Some(runner) = self.workspace_command_runner.clone() - { - let cwd = PathBuf::from(cwd); - let tx = self.app_event_tx.clone(); - tokio::spawn(async move { - if let Some(branch) = - crate::branch_summary::current_branch_name(runner.as_ref(), &cwd).await - { - tx.send(AppEvent::SyncThreadGitBranch { thread_id, branch }); - } - }); - } - self.status_state.pending_status_indicator_restore = match item.phase { - // Models that don't support preambles only output AgentMessageItems on turn completion. - Some(MessagePhase::FinalAnswer) | None => !self.input_queue.pending_steers.is_empty(), - Some(MessagePhase::Commentary) => true, - }; - self.maybe_restore_status_indicator_after_stream_idle(); - } - - /// Periodic tick for stream commits. In smooth mode this preserves one-line pacing, while - /// catch-up mode drains larger batches to reduce queue lag. - pub(crate) fn on_commit_tick(&mut self) { - self.run_commit_tick(); - } - - /// Runs a regular periodic commit tick. - fn run_commit_tick(&mut self) { - self.run_commit_tick_with_scope(CommitTickScope::AnyMode); - } - - /// Runs an opportunistic commit tick only if catch-up mode is active. - fn run_catch_up_commit_tick(&mut self) { - self.run_commit_tick_with_scope(CommitTickScope::CatchUpOnly); - } - - /// Runs a commit tick for the current stream queue snapshot. - /// - /// `scope` controls whether this call may commit in smooth mode or only when catch-up - /// is currently active. While lines are actively streaming we hide the status row to avoid - /// duplicate "in progress" affordances. Restoration is gated separately so we only re-show - /// the row after commentary completion once stream queues are idle. - fn run_commit_tick_with_scope(&mut self, scope: CommitTickScope) { - let now = Instant::now(); - let outcome = run_commit_tick( - &mut self.adaptive_chunking, - self.stream_controller.as_mut(), - self.plan_stream_controller.as_mut(), - scope, - now, - ); - for cell in outcome.cells { - self.bottom_pane.hide_status_indicator(); - self.add_boxed_history(cell); - } - self.sync_active_stream_tail(); - - if outcome.has_controller && outcome.all_idle { - self.maybe_restore_status_indicator_after_stream_idle(); - self.app_event_tx.send(AppEvent::StopCommitAnimation); - } - - if self.turn_lifecycle.agent_turn_running { - self.refresh_runtime_metrics(); - } - } - - fn flush_interrupt_queue(&mut self) { - let mut mgr = std::mem::take(&mut self.interrupts); - mgr.flush_all(self); - self.interrupts = mgr; - } - - #[inline] - fn defer_or_handle( - &mut self, - push: impl FnOnce(&mut InterruptManager), - handle: impl FnOnce(&mut Self), - ) { - // Preserve deterministic FIFO across queued interrupts: once anything - // is queued due to an active write cycle, continue queueing until the - // queue is flushed to avoid reordering (e.g., ExecEnd before ExecBegin). - if self.stream_controller.is_some() || !self.interrupts.is_empty() { - push(&mut self.interrupts); - } else { - handle(self); - } - } - - fn handle_stream_finished(&mut self) { - if self.task_complete_pending { - self.bottom_pane.hide_status_indicator(); - self.task_complete_pending = false; - } - // A completed stream indicates non-exec content was just inserted. - self.flush_interrupt_queue(); - } - - #[inline] - fn handle_streaming_delta(&mut self, delta: String) { - if self.stream_controller.is_none() { - // Before starting an agent stream, flush any active exec cell group. - self.flush_unified_exec_wait_streak(); - self.flush_active_cell(); - // If the previous turn inserted non-stream history (exec output, patch status, MCP - // calls), render a separator before starting the next streamed assistant message. - if self.transcript.needs_final_message_separator && self.transcript.had_work_activity { - self.add_to_history(history_cell::FinalMessageSeparator::new( - /*elapsed_seconds*/ None, /*runtime_metrics*/ None, - )); - self.transcript.needs_final_message_separator = false; - } else if self.transcript.needs_final_message_separator { - // Reset the flag even if we don't show separator (no work was done) - self.transcript.needs_final_message_separator = false; - } - self.stream_controller = Some(StreamController::new( - self.current_stream_width(/*reserved_cols*/ 2), - &self.config.cwd, - self.history_render_mode(), - )); - } - if let Some(controller) = self.stream_controller.as_mut() - && controller.push(&delta) - { - self.app_event_tx.send(AppEvent::StartCommitAnimation); - self.run_catch_up_commit_tick(); - } - self.sync_active_stream_tail(); - self.request_redraw(); - } - - /// Finalizes an exec call while preserving the active exec cell grouping contract. - /// - /// Exec begin/end events usually pair through `running_commands`, but unified exec can emit an - /// end event for a call that was never materialized as the current active `ExecCell` (for - /// example, when another exploring group is still active). In that case we render the end as a - /// standalone history entry instead of replacing or flushing the unrelated active exploring - /// cell. If this method treated every unknown end as "complete the active cell", the UI could - /// merge unrelated commands and hide still-running exploring work. - pub(crate) fn handle_command_execution_completed_now(&mut self, item: ThreadItem) { - enum ExecEndTarget { - // Normal case: the active exec cell already tracks this call id. - ActiveTracked, - // We have an active exec group, but it does not contain this call id. Render the end - // as a standalone finalized history cell so the active group remains intact. - OrphanHistoryWhileActiveExec, - // No active exec cell can safely own this end; build a new cell from the end payload. - NewCell, - } - - let ThreadItem::CommandExecution { - id, - command, - process_id: _, - source, - command_actions, - aggregated_output, - exit_code, - duration_ms, - .. - } = item - else { - return; - }; - let event_command = split_command_string(&command); - let event_parsed = command_actions - .into_iter() - .map(codex_app_server_protocol::CommandAction::into_core) - .collect(); - let duration = Duration::from_millis(duration_ms.unwrap_or_default().max(0) as u64); - let exit_code = exit_code.unwrap_or_default(); - let aggregated_output = aggregated_output.unwrap_or_default(); - - let running = self.running_commands.remove(&id); - if self.suppressed_exec_calls.remove(&id) { - return; - } - let (command, parsed, source) = match running { - Some(rc) => (rc.command, rc.parsed_cmd, rc.source), - None => (event_command, event_parsed, source), - }; - let parsed = self.annotate_skill_reads_in_parsed_cmd(parsed); - let is_unified_exec_interaction = - matches!(source, ExecCommandSource::UnifiedExecInteraction); - let is_user_shell = source == ExecCommandSource::UserShell; - let end_target = match self.transcript.active_cell.as_ref() { - Some(cell) => match cell.as_any().downcast_ref::() { - Some(exec_cell) if exec_cell.iter_calls().any(|call| call.call_id == id) => { - ExecEndTarget::ActiveTracked - } - Some(exec_cell) if exec_cell.is_active() => { - ExecEndTarget::OrphanHistoryWhileActiveExec - } - Some(_) | None => ExecEndTarget::NewCell, - }, - None => ExecEndTarget::NewCell, - }; - - // Unified exec interaction rows intentionally hide command output text in the exec cell and - // instead render the interaction-specific content elsewhere in the UI. - let output = if is_unified_exec_interaction { - CommandOutput { - exit_code, - formatted_output: String::new(), - aggregated_output: String::new(), - } - } else { - CommandOutput { - exit_code, - formatted_output: aggregated_output.clone(), - aggregated_output, - } - }; - - match end_target { - ExecEndTarget::ActiveTracked => { - if let Some(cell) = self - .transcript - .active_cell - .as_mut() - .and_then(|c| c.as_any_mut().downcast_mut::()) - { - let completed = cell.complete_call(&id, output, duration); - debug_assert!(completed, "active exec cell should contain {id}"); - if cell.should_flush() { - self.flush_active_cell(); - } else { - self.bump_active_cell_revision(); - self.request_redraw(); - } - } - } - ExecEndTarget::OrphanHistoryWhileActiveExec => { - let mut orphan = new_active_exec_command( - id.clone(), - command, - parsed, - source, - /*interaction_input*/ None, - self.config.animations, - ); - let completed = orphan.complete_call(&id, output, duration); - debug_assert!(completed, "new orphan exec cell should contain {id}"); - self.transcript.needs_final_message_separator = true; - self.app_event_tx - .send(AppEvent::InsertHistoryCell(Box::new(orphan))); - self.request_redraw(); - } - ExecEndTarget::NewCell => { - self.flush_active_cell(); - let mut cell = new_active_exec_command( - id.clone(), - command, - parsed, - source, - /*interaction_input*/ None, - self.config.animations, - ); - let completed = cell.complete_call(&id, output, duration); - debug_assert!(completed, "new exec cell should contain {id}"); - if cell.should_flush() { - self.add_to_history(cell); - } else { - self.transcript.active_cell = Some(Box::new(cell)); - self.bump_active_cell_revision(); - self.request_redraw(); - } - } - } - // Mark that actual work was done (command executed) - self.transcript.had_work_activity = true; - if is_user_shell { - self.maybe_send_next_queued_input(); - } - } - - pub(crate) fn handle_file_change_completed_now(&mut self, item: ThreadItem) { - let ThreadItem::FileChange { status, .. } = item else { - return; - }; - // If the patch was successful, just let the "Edited" block stand. - // Otherwise, add a failure block. - if matches!(status, codex_app_server_protocol::PatchApplyStatus::Failed) { - self.add_to_history(history_cell::new_patch_apply_failure(String::new())); - } - // Mark that actual work was done (patch applied) - self.transcript.had_work_activity = true; - } - - pub(crate) fn handle_exec_approval_now(&mut self, ev: ExecApprovalRequestEvent) { - self.flush_answer_stream_with_separator(); - let command = shlex::try_join(ev.command.iter().map(String::as_str)) - .unwrap_or_else(|_| ev.command.join(" ")); - self.notify(Notification::ExecApprovalRequested { command }); - - let available_decisions = ev.effective_available_decisions(); - let request = ApprovalRequest::Exec { - thread_id: self.thread_id.unwrap_or_default(), - thread_label: None, - id: ev.effective_approval_id(), - command: ev.command, - reason: ev.reason, - available_decisions, - network_approval_context: ev.network_approval_context, - additional_permissions: ev.additional_permissions, - }; - self.bottom_pane - .push_approval_request(request, &self.config.features); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Waiting, - /*body*/ None, - ); - self.request_redraw(); - } - - pub(crate) fn handle_apply_patch_approval_now(&mut self, ev: ApplyPatchApprovalRequestEvent) { - self.flush_answer_stream_with_separator(); - - let request = ApprovalRequest::ApplyPatch { - thread_id: self.thread_id.unwrap_or_default(), - thread_label: None, - id: ev.call_id, - reason: ev.reason, - changes: ev.changes.clone(), - cwd: self.config.cwd.clone(), - }; - self.bottom_pane - .push_approval_request(request, &self.config.features); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Waiting, - /*body*/ None, - ); - self.request_redraw(); - self.notify(Notification::EditApprovalRequested { - cwd: self.config.cwd.to_path_buf(), - changes: ev.changes.keys().cloned().collect(), - }); - } - - pub(crate) fn handle_elicitation_request_now( - &mut self, - request_id: AppServerRequestId, - params: McpServerElicitationRequestParams, - ) { - self.flush_answer_stream_with_separator(); - - self.notify(Notification::ElicitationRequested { - server_name: params.server_name.clone(), - }); - - let thread_id = self.thread_id.unwrap_or_default(); - if let Some(params) = crate::bottom_pane::AppLinkViewParams::from_url_app_server_request( - thread_id, - ¶ms.server_name, - request_id.clone(), - ¶ms.request, - ) { - self.open_app_link_view(params); - } else if let Some(request) = McpServerElicitationFormRequest::from_app_server_request( - thread_id, - request_id.clone(), - params.clone(), - ) { - self.bottom_pane - .push_mcp_server_elicitation_request(request); - } else { - match params.request { - McpServerElicitationRequest::Form { message, .. } => { - let request = ApprovalRequest::McpElicitation { - thread_id, - thread_label: None, - server_name: params.server_name, - request_id, - message, - }; - self.bottom_pane - .push_approval_request(request, &self.config.features); - } - McpServerElicitationRequest::Url { .. } => { - self.app_event_tx.resolve_elicitation( - thread_id, - params.server_name, - request_id, - codex_app_server_protocol::McpServerElicitationAction::Decline, - /*content*/ None, - /*meta*/ None, - ); - } - } - } - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Waiting, - /*body*/ None, - ); - self.request_redraw(); - } - - pub(crate) fn push_approval_request(&mut self, request: ApprovalRequest) { - self.bottom_pane - .push_approval_request(request, &self.config.features); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Waiting, - /*body*/ None, - ); - self.request_redraw(); - } - - pub(crate) fn push_mcp_server_elicitation_request( - &mut self, - request: McpServerElicitationFormRequest, - ) { - self.bottom_pane - .push_mcp_server_elicitation_request(request); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Waiting, - /*body*/ None, - ); - self.request_redraw(); - } - - pub(crate) fn handle_request_user_input_now(&mut self, ev: ToolRequestUserInputParams) { - self.flush_answer_stream_with_separator(); - let question_count = ev.questions.len(); - let summary = Notification::user_input_request_summary(&ev.questions); - let title = match (question_count, summary.as_deref()) { - (1, Some(summary)) => summary.to_string(), - (1, None) => "Question requested".to_string(), - (count, _) => format!("{count} questions requested"), - }; - self.notify(Notification::PlanModePrompt { title }); - self.bottom_pane.push_user_input_request(ev); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Waiting, - /*body*/ None, - ); - self.request_redraw(); - } - - pub(crate) fn handle_request_permissions_now(&mut self, ev: RequestPermissionsEvent) { - self.flush_answer_stream_with_separator(); - let request = ApprovalRequest::Permissions { - thread_id: self.thread_id.unwrap_or_default(), - thread_label: None, - call_id: ev.call_id, - reason: ev.reason, - permissions: ev.permissions, - }; - self.bottom_pane - .push_approval_request(request, &self.config.features); - self.set_ambient_pet_notification( - crate::pets::PetNotificationKind::Waiting, - /*body*/ None, - ); - self.request_redraw(); - } - - pub(crate) fn handle_command_execution_started_now(&mut self, item: ThreadItem) { - let ThreadItem::CommandExecution { - id, - command, - source, - command_actions, - .. - } = item - else { - return; - }; - let (command, parsed_cmd) = - command_execution_command_and_parsed(&command, &command_actions); - // Ensure the status indicator is visible while the command runs. - self.bottom_pane.ensure_status_indicator(); - let parsed_cmd = self.annotate_skill_reads_in_parsed_cmd(parsed_cmd); - self.running_commands.insert( - id.clone(), - RunningCommand { - command: command.clone(), - parsed_cmd: parsed_cmd.clone(), - source, - }, - ); - let is_wait_interaction = matches!(source, ExecCommandSource::UnifiedExecInteraction); - let command_display = command.join(" "); - let should_suppress_unified_wait = is_wait_interaction - && self - .last_unified_wait - .as_ref() - .is_some_and(|wait| wait.is_duplicate(&command_display)); - if is_wait_interaction { - self.last_unified_wait = Some(UnifiedExecWaitState::new(command_display)); - } else { - self.last_unified_wait = None; - } - if should_suppress_unified_wait { - self.suppressed_exec_calls.insert(id); - return; - } - if let Some(cell) = self - .transcript - .active_cell - .as_mut() - .and_then(|c| c.as_any_mut().downcast_mut::()) - && let Some(new_exec) = cell.with_added_call( - id.clone(), - command.clone(), - parsed_cmd.clone(), - source, - /*interaction_input*/ None, - ) - { - *cell = new_exec; - self.bump_active_cell_revision(); - } else { - self.flush_active_cell(); - - self.transcript.active_cell = Some(Box::new(new_active_exec_command( - id, - command, - parsed_cmd, - source, - /*interaction_input*/ None, - self.config.animations, - ))); - self.bump_active_cell_revision(); - } - - self.request_redraw(); - } - - pub(crate) fn handle_mcp_tool_call_started_now(&mut self, item: ThreadItem) { - let ThreadItem::McpToolCall { - id, - server, - tool, - arguments, - .. - } = item - else { - return; - }; - self.flush_answer_stream_with_separator(); - self.flush_active_cell(); - self.transcript.active_cell = Some(Box::new(history_cell::new_active_mcp_tool_call( - id, - McpInvocation { - server, - tool, - arguments: Some(arguments), - }, - self.config.animations, - ))); - self.bump_active_cell_revision(); - self.request_redraw(); - } - - pub(crate) fn handle_mcp_tool_call_completed_now(&mut self, item: ThreadItem) { - self.flush_answer_stream_with_separator(); - - let ThreadItem::McpToolCall { - id, - server, - tool, - arguments, - result, - error, - duration_ms, - .. - } = item - else { - return; - }; - let invocation = McpInvocation { - server, - tool, - arguments: Some(arguments), - }; - let duration = Duration::from_millis(duration_ms.unwrap_or_default().max(0) as u64); - let result = match (result, error) { - (_, Some(error)) => Err(error.message), - (Some(result), None) => { - let result = *result; - Ok(codex_protocol::mcp::CallToolResult { - content: result.content, - structured_content: result.structured_content, - is_error: Some(false), - meta: None, - }) - } - (None, None) => Err("MCP tool call completed without a result".to_string()), - }; - - let extra_cell = match self - .transcript - .active_cell - .as_mut() - .and_then(|cell| cell.as_any_mut().downcast_mut::()) - { - Some(cell) if cell.call_id() == id => cell.complete(duration, result), - _ => { - self.flush_active_cell(); - let mut cell = - history_cell::new_active_mcp_tool_call(id, invocation, self.config.animations); - let extra_cell = cell.complete(duration, result); - self.transcript.active_cell = Some(Box::new(cell)); - extra_cell - } - }; - - self.flush_active_cell(); - if let Some(extra) = extra_cell { - self.add_boxed_history(extra); - } - // Mark that actual work was done (MCP tool call) - self.transcript.had_work_activity = true; - } - - pub(crate) fn handle_queued_item_started_now(&mut self, item: ThreadItem) { - match item { - item @ ThreadItem::CommandExecution { .. } => { - self.handle_command_execution_started_now(item); - } - item @ ThreadItem::McpToolCall { .. } => { - self.handle_mcp_tool_call_started_now(item); - } - _ => {} - } - } - - pub(crate) fn handle_queued_item_completed_now(&mut self, item: ThreadItem) { - match item { - item @ ThreadItem::CommandExecution { .. } => { - self.handle_command_execution_completed_now(item); - } - item @ ThreadItem::FileChange { .. } => self.handle_file_change_completed_now(item), - item @ ThreadItem::McpToolCall { .. } => self.handle_mcp_tool_call_completed_now(item), - _ => {} - } - } - pub(crate) fn new_with_app_event(common: ChatWidgetInit) -> Self { Self::new_with_op_target(common, CodexOpTarget::AppEvent) } @@ -4357,376 +2239,6 @@ impl ChatWidget { self.app_event_tx.send(AppEvent::InsertHistoryCell(cell)); } - fn active_cell_is_stream_tail(&self) -> bool { - self.transcript.active_cell.as_ref().is_some_and(|cell| { - cell.as_any().is::() - || cell.as_any().is::() - }) - } - - fn has_active_stream_tail(&self) -> bool { - (self.stream_controller.is_some() || self.plan_stream_controller.is_some()) - && self.active_cell_is_stream_tail() - } - - fn sync_active_stream_tail(&mut self) { - if let Some(controller) = self.stream_controller.as_ref() { - let tail_lines = controller.current_tail_lines(); - if tail_lines.is_empty() { - self.clear_active_stream_tail(); - return; - } - - self.bottom_pane.hide_status_indicator(); - self.transcript.active_cell = - Some(Box::new(history_cell::StreamingAgentTailCell::new( - tail_lines, - controller.tail_starts_stream(), - ))); - self.bump_active_cell_revision(); - return; - } - - if let Some(controller) = self.plan_stream_controller.as_ref() { - let tail_lines = controller.current_tail_display_lines(); - if tail_lines.is_empty() { - self.clear_active_stream_tail(); - return; - } - - self.bottom_pane.hide_status_indicator(); - self.transcript.active_cell = Some(Box::new(history_cell::StreamingPlanTailCell::new( - tail_lines, - !controller.tail_starts_stream(), - ))); - self.bump_active_cell_revision(); - return; - } - - self.clear_active_stream_tail(); - } - - fn clear_active_stream_tail(&mut self) { - if self.active_cell_is_stream_tail() { - self.transcript.active_cell = None; - self.bump_active_cell_revision(); - } - } - - /// Replay a subset of initial events into the UI to seed the transcript when - /// resuming an existing session. This approximates the live event flow and - /// is intentionally conservative: only safe-to-replay items are rendered to - /// avoid triggering side effects. Event ids are passed as `None` to - /// distinguish replayed events from live ones. - pub(crate) fn replay_thread_turns(&mut self, turns: Vec, replay_kind: ReplayKind) { - for turn in turns { - let Turn { - id: turn_id, - items_view: _, - items, - status, - error, - started_at, - completed_at, - duration_ms, - } = turn; - if matches!(status, TurnStatus::InProgress) { - self.last_non_retry_error = None; - self.on_task_started(); - } - for item in items { - self.replay_thread_item(item, turn_id.clone(), replay_kind); - } - if matches!( - status, - TurnStatus::Completed | TurnStatus::Interrupted | TurnStatus::Failed - ) { - self.handle_turn_completed_notification( - TurnCompletedNotification { - thread_id: self.thread_id.map(|id| id.to_string()).unwrap_or_default(), - turn: Turn { - id: turn_id, - items_view: codex_app_server_protocol::TurnItemsView::NotLoaded, - items: Vec::new(), - status, - error, - started_at, - completed_at, - duration_ms, - }, - }, - Some(replay_kind), - ); - } - } - } - - pub(crate) fn replay_thread_item( - &mut self, - item: ThreadItem, - turn_id: String, - replay_kind: ReplayKind, - ) { - self.handle_thread_item(item, turn_id, ThreadItemRenderSource::Replay(replay_kind)); - } - - fn handle_thread_item( - &mut self, - item: ThreadItem, - turn_id: String, - render_source: ThreadItemRenderSource, - ) { - let from_replay = render_source.is_replay(); - let replay_kind = render_source.replay_kind(); - match item { - ThreadItem::UserMessage { content, .. } => { - self.on_committed_user_message(&content, from_replay); - } - ThreadItem::AgentMessage { - id, - text, - phase, - memory_citation, - } => { - self.on_agent_message_item_completed( - AgentMessageItem { - id, - content: vec![AgentMessageContent::Text { text }], - phase, - memory_citation: memory_citation.map(|citation| { - codex_protocol::memory_citation::MemoryCitation { - entries: citation - .entries - .into_iter() - .map(|entry| { - codex_protocol::memory_citation::MemoryCitationEntry { - path: entry.path, - line_start: entry.line_start, - line_end: entry.line_end, - note: entry.note, - } - }) - .collect(), - rollout_ids: citation.thread_ids, - } - }), - }, - from_replay, - ); - } - ThreadItem::Plan { text, .. } => self.on_plan_item_completed(text), - ThreadItem::Reasoning { - summary, content, .. - } => { - if from_replay { - for delta in summary { - self.on_agent_reasoning_delta(delta); - } - if self.config.show_raw_agent_reasoning { - for delta in content { - self.on_agent_reasoning_delta(delta); - } - } - } - self.on_agent_reasoning_final(); - } - item @ ThreadItem::CommandExecution { - status: codex_app_server_protocol::CommandExecutionStatus::InProgress, - .. - } => self.on_command_execution_started(item), - item @ ThreadItem::CommandExecution { .. } => self.on_command_execution_completed(item), - ThreadItem::FileChange { - status: codex_app_server_protocol::PatchApplyStatus::InProgress, - .. - } => {} - item @ ThreadItem::FileChange { .. } => self.on_file_change_completed(item), - item @ ThreadItem::McpToolCall { .. } => self.on_mcp_tool_call_completed(item), - ThreadItem::WebSearch { id, query, action } => { - self.on_web_search_begin(id.clone()); - self.on_web_search_end( - id, - query, - action.unwrap_or(codex_app_server_protocol::WebSearchAction::Other), - ); - } - ThreadItem::ImageView { id: _, path } => { - self.on_view_image_tool_call(path); - } - ThreadItem::ImageGeneration { - id, - revised_prompt, - saved_path, - .. - } => { - self.on_image_generation_end(id, revised_prompt, saved_path); - } - ThreadItem::EnteredReviewMode { review, .. } => { - if from_replay { - self.enter_review_mode_with_hint(review, /*from_replay*/ true); - } - } - ThreadItem::ExitedReviewMode { .. } => { - self.exit_review_mode_after_item(); - } - ThreadItem::ContextCompaction { .. } => { - self.add_info_message("Context compacted".to_string(), /*hint*/ None); - } - ThreadItem::HookPrompt { .. } => {} - ThreadItem::CollabAgentToolCall { - id, - tool, - status, - sender_thread_id, - receiver_thread_ids, - prompt, - model, - reasoning_effort, - agents_states, - } => self.on_collab_agent_tool_call(ThreadItem::CollabAgentToolCall { - id, - tool, - status, - sender_thread_id, - receiver_thread_ids, - prompt, - model, - reasoning_effort, - agents_states, - }), - ThreadItem::DynamicToolCall { .. } => {} - } - - if matches!(replay_kind, Some(ReplayKind::ThreadSnapshot)) && turn_id.is_empty() { - self.request_redraw(); - } - } - - pub(crate) fn handle_server_request( - &mut self, - request: ServerRequest, - replay_kind: Option, - ) { - let id = request.id().to_string(); - match request { - ServerRequest::CommandExecutionRequestApproval { params, .. } => { - let fallback_cwd = self.config.cwd.clone(); - self.on_exec_approval_request( - id, - exec_approval_request_from_params(params, &fallback_cwd), - ); - } - ServerRequest::FileChangeRequestApproval { params, .. } => { - self.on_apply_patch_approval_request( - id, - patch_approval_request_from_params(params), - ); - } - ServerRequest::McpServerElicitationRequest { request_id, params } => { - self.on_elicitation_request(request_id, params); - } - ServerRequest::PermissionsRequestApproval { params, .. } => { - self.on_request_permissions(request_permissions_from_params(params)); - } - ServerRequest::ToolRequestUserInput { params, .. } => { - self.on_request_user_input(params); - } - ServerRequest::DynamicToolCall { .. } - | ServerRequest::AttestationGenerate { .. } - | ServerRequest::ChatgptAuthTokensRefresh { .. } - | ServerRequest::ApplyPatchApproval { .. } - | ServerRequest::ExecCommandApproval { .. } => { - if replay_kind.is_none() { - self.add_error_message(TUI_STUB_MESSAGE.to_string()); - } - } - } - } - - pub(crate) fn handle_skills_list_response(&mut self, response: SkillsListResponse) { - self.on_list_skills(response); - } - - fn on_patch_apply_output_delta(&mut self, _item_id: String, _delta: String) {} - - fn on_guardian_review_notification( - &mut self, - id: String, - turn_id: String, - started_at_ms: i64, - review: codex_app_server_protocol::GuardianApprovalReview, - completion: Option<(i64, codex_app_server_protocol::AutoReviewDecisionSource)>, - action: GuardianApprovalReviewAction, - ) { - let (completed_at_ms, decision_source) = match completion { - Some((completed_at_ms, decision_source)) => { - (Some(completed_at_ms), Some(decision_source)) - } - None => (None, None), - }; - - self.on_guardian_assessment(GuardianAssessmentEvent { - id, - target_item_id: None, - turn_id, - started_at_ms, - completed_at_ms, - status: match review.status { - codex_app_server_protocol::GuardianApprovalReviewStatus::InProgress => { - GuardianAssessmentStatus::InProgress - } - codex_app_server_protocol::GuardianApprovalReviewStatus::Approved => { - GuardianAssessmentStatus::Approved - } - codex_app_server_protocol::GuardianApprovalReviewStatus::Denied => { - GuardianAssessmentStatus::Denied - } - codex_app_server_protocol::GuardianApprovalReviewStatus::TimedOut => { - GuardianAssessmentStatus::TimedOut - } - codex_app_server_protocol::GuardianApprovalReviewStatus::Aborted => { - GuardianAssessmentStatus::Aborted - } - }, - risk_level: review.risk_level.map(|risk_level| match risk_level { - codex_app_server_protocol::GuardianRiskLevel::Low => { - codex_protocol::approvals::GuardianRiskLevel::Low - } - codex_app_server_protocol::GuardianRiskLevel::Medium => { - codex_protocol::approvals::GuardianRiskLevel::Medium - } - codex_app_server_protocol::GuardianRiskLevel::High => { - codex_protocol::approvals::GuardianRiskLevel::High - } - codex_app_server_protocol::GuardianRiskLevel::Critical => { - codex_protocol::approvals::GuardianRiskLevel::Critical - } - }), - user_authorization: review.user_authorization.map(|user_authorization| { - match user_authorization { - codex_app_server_protocol::GuardianUserAuthorization::Unknown => { - codex_protocol::approvals::GuardianUserAuthorization::Unknown - } - codex_app_server_protocol::GuardianUserAuthorization::Low => { - codex_protocol::approvals::GuardianUserAuthorization::Low - } - codex_app_server_protocol::GuardianUserAuthorization::Medium => { - codex_protocol::approvals::GuardianUserAuthorization::Medium - } - codex_app_server_protocol::GuardianUserAuthorization::High => { - codex_protocol::approvals::GuardianUserAuthorization::High - } - } - }), - rationale: review.rationale, - decision_source: decision_source.map(|source| match source { - codex_app_server_protocol::AutoReviewDecisionSource::Agent => { - GuardianAssessmentDecisionSource::Agent - } - }), - action: action.into(), - }); - } - fn enter_review_mode_with_hint(&mut self, hint: String, from_replay: bool) { if self.review.pre_review_token_info.is_none() { self.review.pre_review_token_info = Some(self.token_info.clone()); diff --git a/codex-rs/tui/src/chatwidget/command_lifecycle.rs b/codex-rs/tui/src/chatwidget/command_lifecycle.rs new file mode 100644 index 0000000000..efe7522963 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/command_lifecycle.rs @@ -0,0 +1,454 @@ +//! Command execution lifecycle handlers for `ChatWidget`. +//! +//! This module owns command start/output/completion rendering, including active +//! exec-cell grouping and unified exec wait state. + +use super::*; + +impl ChatWidget { + pub(super) fn flush_unified_exec_wait_streak(&mut self) { + let Some(wait) = self.unified_exec_wait_streak.take() else { + return; + }; + self.transcript.needs_final_message_separator = true; + let cell = history_cell::new_unified_exec_interaction(wait.command_display, String::new()); + self.app_event_tx + .send(AppEvent::InsertHistoryCell(Box::new(cell))); + self.restore_reasoning_status_header(); + } + + pub(super) fn on_command_execution_started(&mut self, item: ThreadItem) { + let ThreadItem::CommandExecution { + id, + command, + process_id, + source, + command_actions, + .. + } = &item + else { + return; + }; + let (_command, parsed_cmd) = command_execution_command_and_parsed(command, command_actions); + self.flush_answer_stream_with_separator(); + if is_unified_exec_source(*source) { + if *source == ExecCommandSource::UnifiedExecStartup { + self.track_unified_exec_process_begin(id, process_id.as_deref(), command); + } + if !self.bottom_pane.is_task_running() { + return; + } + // Unified exec may be parsed as Unknown; keep the working indicator visible regardless. + self.bottom_pane.ensure_status_indicator(); + if !is_standard_tool_call(&parsed_cmd) { + return; + } + } + let item2 = item.clone(); + self.defer_or_handle( + |q| q.push_item_started(item), + |s| s.handle_command_execution_started_now(item2), + ); + } + + pub(super) fn on_exec_command_output_delta(&mut self, call_id: &str, delta: &str) { + self.track_unified_exec_output_chunk(call_id, delta.as_bytes()); + if !self.bottom_pane.is_task_running() { + return; + } + + let Some(cell) = self + .transcript + .active_cell + .as_mut() + .and_then(|c| c.as_any_mut().downcast_mut::()) + else { + return; + }; + + if cell.append_output(call_id, delta) { + self.bump_active_cell_revision(); + self.request_redraw(); + } + } + + pub(super) fn on_terminal_interaction(&mut self, process_id: String, stdin: String) { + if !self.bottom_pane.is_task_running() { + return; + } + self.flush_answer_stream_with_separator(); + let command_display = self + .unified_exec_processes + .iter() + .find(|process| process.key == process_id) + .map(|process| process.command_display.clone()); + if stdin.is_empty() { + // Empty stdin means we are polling for background output. + // Surface this in the status indicator (single "waiting" surface) instead of + // the transcript. Keep the header short so the interrupt hint remains visible. + self.bottom_pane.ensure_status_indicator(); + self.bottom_pane + .set_interrupt_hint_visible(/*visible*/ true); + self.status_state.terminal_title_status_kind = + TerminalTitleStatusKind::WaitingForBackgroundTerminal; + self.set_status( + "Waiting for background terminal".to_string(), + command_display.clone(), + StatusDetailsCapitalization::Preserve, + /*details_max_lines*/ 1, + ); + match &mut self.unified_exec_wait_streak { + Some(wait) if wait.process_id == process_id => { + wait.update_command_display(command_display); + } + Some(_) => { + self.flush_unified_exec_wait_streak(); + self.unified_exec_wait_streak = + Some(UnifiedExecWaitStreak::new(process_id, command_display)); + } + None => { + self.unified_exec_wait_streak = + Some(UnifiedExecWaitStreak::new(process_id, command_display)); + } + } + self.request_redraw(); + } else { + if self + .unified_exec_wait_streak + .as_ref() + .is_some_and(|wait| wait.process_id == process_id) + { + self.flush_unified_exec_wait_streak(); + } + self.add_to_history(history_cell::new_unified_exec_interaction( + command_display, + stdin, + )); + } + } + + pub(super) fn on_command_execution_completed(&mut self, item: ThreadItem) { + let ThreadItem::CommandExecution { + id, + process_id, + source, + .. + } = &item + else { + return; + }; + if is_unified_exec_source(*source) { + if let Some(process_id) = process_id.as_deref() + && self + .unified_exec_wait_streak + .as_ref() + .is_some_and(|wait| wait.process_id == process_id) + { + self.flush_unified_exec_wait_streak(); + } + self.track_unified_exec_process_end(id, process_id.as_deref()); + if !self.bottom_pane.is_task_running() { + return; + } + } + let item2 = item.clone(); + self.defer_or_handle( + |q| q.push_item_completed(item), + |s| s.handle_command_execution_completed_now(item2), + ); + } + + pub(super) fn track_unified_exec_process_begin( + &mut self, + call_id: &str, + process_id: Option<&str>, + command: &str, + ) { + let key = process_id.unwrap_or(call_id).to_string(); + let command = split_command_string(command); + let command_display = strip_bash_lc_and_escape(&command); + if let Some(existing) = self + .unified_exec_processes + .iter_mut() + .find(|process| process.key == key) + { + existing.call_id = call_id.to_string(); + existing.command_display = command_display; + existing.recent_chunks.clear(); + } else { + self.unified_exec_processes.push(UnifiedExecProcessSummary { + key, + call_id: call_id.to_string(), + command_display, + recent_chunks: Vec::new(), + }); + } + self.sync_unified_exec_footer(); + } + + pub(super) fn track_unified_exec_process_end( + &mut self, + call_id: &str, + process_id: Option<&str>, + ) { + let key = process_id.unwrap_or(call_id); + let before = self.unified_exec_processes.len(); + self.unified_exec_processes + .retain(|process| process.key != key); + if self.unified_exec_processes.len() != before { + self.sync_unified_exec_footer(); + } + } + + pub(super) fn sync_unified_exec_footer(&mut self) { + let processes = self + .unified_exec_processes + .iter() + .map(|process| process.command_display.clone()) + .collect(); + self.bottom_pane.set_unified_exec_processes(processes); + } + + /// Record recent stdout/stderr lines for the unified exec footer. + pub(super) fn track_unified_exec_output_chunk(&mut self, call_id: &str, chunk: &[u8]) { + let Some(process) = self + .unified_exec_processes + .iter_mut() + .find(|process| process.call_id == call_id) + else { + return; + }; + + let text = String::from_utf8_lossy(chunk); + for line in text + .lines() + .map(str::trim_end) + .filter(|line| !line.is_empty()) + { + process.recent_chunks.push(line.to_string()); + } + + const MAX_RECENT_CHUNKS: usize = 3; + if process.recent_chunks.len() > MAX_RECENT_CHUNKS { + let drop_count = process.recent_chunks.len() - MAX_RECENT_CHUNKS; + process.recent_chunks.drain(0..drop_count); + } + } + + pub(crate) fn handle_command_execution_started_now(&mut self, item: ThreadItem) { + let ThreadItem::CommandExecution { + id, + command, + source, + command_actions, + .. + } = item + else { + return; + }; + let (command, parsed_cmd) = + command_execution_command_and_parsed(&command, &command_actions); + // Ensure the status indicator is visible while the command runs. + self.bottom_pane.ensure_status_indicator(); + let parsed_cmd = self.annotate_skill_reads_in_parsed_cmd(parsed_cmd); + self.running_commands.insert( + id.clone(), + RunningCommand { + command: command.clone(), + parsed_cmd: parsed_cmd.clone(), + source, + }, + ); + let is_wait_interaction = matches!(source, ExecCommandSource::UnifiedExecInteraction); + let command_display = command.join(" "); + let should_suppress_unified_wait = is_wait_interaction + && self + .last_unified_wait + .as_ref() + .is_some_and(|wait| wait.is_duplicate(&command_display)); + if is_wait_interaction { + self.last_unified_wait = Some(UnifiedExecWaitState::new(command_display)); + } else { + self.last_unified_wait = None; + } + if should_suppress_unified_wait { + self.suppressed_exec_calls.insert(id); + return; + } + if let Some(cell) = self + .transcript + .active_cell + .as_mut() + .and_then(|c| c.as_any_mut().downcast_mut::()) + && let Some(new_exec) = cell.with_added_call( + id.clone(), + command.clone(), + parsed_cmd.clone(), + source, + /*interaction_input*/ None, + ) + { + *cell = new_exec; + self.bump_active_cell_revision(); + } else { + self.flush_active_cell(); + + self.transcript.active_cell = Some(Box::new(new_active_exec_command( + id, + command, + parsed_cmd, + source, + /*interaction_input*/ None, + self.config.animations, + ))); + self.bump_active_cell_revision(); + } + + self.request_redraw(); + } + + /// Finalizes an exec call while preserving the active exec cell grouping contract. + /// + /// Exec begin/end events usually pair through `running_commands`, but unified exec can emit an + /// end event for a call that was never materialized as the current active `ExecCell` (for + /// example, when another exploring group is still active). In that case we render the end as a + /// standalone history entry instead of replacing or flushing the unrelated active exploring + /// cell. If this method treated every unknown end as "complete the active cell", the UI could + /// merge unrelated commands and hide still-running exploring work. + pub(crate) fn handle_command_execution_completed_now(&mut self, item: ThreadItem) { + enum ExecEndTarget { + // Normal case: the active exec cell already tracks this call id. + ActiveTracked, + // We have an active exec group, but it does not contain this call id. Render the end + // as a standalone finalized history cell so the active group remains intact. + OrphanHistoryWhileActiveExec, + // No active exec cell can safely own this end; build a new cell from the end payload. + NewCell, + } + + let ThreadItem::CommandExecution { + id, + command, + process_id: _, + source, + command_actions, + aggregated_output, + exit_code, + duration_ms, + .. + } = item + else { + return; + }; + let event_command = split_command_string(&command); + let event_parsed = command_actions + .into_iter() + .map(codex_app_server_protocol::CommandAction::into_core) + .collect(); + let duration = Duration::from_millis(duration_ms.unwrap_or_default().max(0) as u64); + let exit_code = exit_code.unwrap_or_default(); + let aggregated_output = aggregated_output.unwrap_or_default(); + + let running = self.running_commands.remove(&id); + if self.suppressed_exec_calls.remove(&id) { + return; + } + let (command, parsed, source) = match running { + Some(rc) => (rc.command, rc.parsed_cmd, rc.source), + None => (event_command, event_parsed, source), + }; + let parsed = self.annotate_skill_reads_in_parsed_cmd(parsed); + let is_unified_exec_interaction = + matches!(source, ExecCommandSource::UnifiedExecInteraction); + let is_user_shell = source == ExecCommandSource::UserShell; + let end_target = match self.transcript.active_cell.as_ref() { + Some(cell) => match cell.as_any().downcast_ref::() { + Some(exec_cell) if exec_cell.iter_calls().any(|call| call.call_id == id) => { + ExecEndTarget::ActiveTracked + } + Some(exec_cell) if exec_cell.is_active() => { + ExecEndTarget::OrphanHistoryWhileActiveExec + } + Some(_) | None => ExecEndTarget::NewCell, + }, + None => ExecEndTarget::NewCell, + }; + + // Unified exec interaction rows intentionally hide command output text in the exec cell and + // instead render the interaction-specific content elsewhere in the UI. + let output = if is_unified_exec_interaction { + CommandOutput { + exit_code, + formatted_output: String::new(), + aggregated_output: String::new(), + } + } else { + CommandOutput { + exit_code, + formatted_output: aggregated_output.clone(), + aggregated_output, + } + }; + + match end_target { + ExecEndTarget::ActiveTracked => { + if let Some(cell) = self + .transcript + .active_cell + .as_mut() + .and_then(|c| c.as_any_mut().downcast_mut::()) + { + let completed = cell.complete_call(&id, output, duration); + debug_assert!(completed, "active exec cell should contain {id}"); + if cell.should_flush() { + self.flush_active_cell(); + } else { + self.bump_active_cell_revision(); + self.request_redraw(); + } + } + } + ExecEndTarget::OrphanHistoryWhileActiveExec => { + let mut orphan = new_active_exec_command( + id.clone(), + command, + parsed, + source, + /*interaction_input*/ None, + self.config.animations, + ); + let completed = orphan.complete_call(&id, output, duration); + debug_assert!(completed, "new orphan exec cell should contain {id}"); + self.transcript.needs_final_message_separator = true; + self.app_event_tx + .send(AppEvent::InsertHistoryCell(Box::new(orphan))); + self.request_redraw(); + } + ExecEndTarget::NewCell => { + self.flush_active_cell(); + let mut cell = new_active_exec_command( + id.clone(), + command, + parsed, + source, + /*interaction_input*/ None, + self.config.animations, + ); + let completed = cell.complete_call(&id, output, duration); + debug_assert!(completed, "new exec cell should contain {id}"); + if cell.should_flush() { + self.add_to_history(cell); + } else { + self.transcript.active_cell = Some(Box::new(cell)); + self.bump_active_cell_revision(); + self.request_redraw(); + } + } + } + // Mark that actual work was done (command executed) + self.transcript.had_work_activity = true; + if is_user_shell { + self.maybe_send_next_queued_input(); + } + } +} diff --git a/codex-rs/tui/src/chatwidget/hook_lifecycle.rs b/codex-rs/tui/src/chatwidget/hook_lifecycle.rs new file mode 100644 index 0000000000..db3ac314d2 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/hook_lifecycle.rs @@ -0,0 +1,132 @@ +//! Hook run lifecycle handling for `ChatWidget`. +//! +//! This module keeps active hook cells, hook timers, and hook completion output +//! together. + +use super::*; + +impl ChatWidget { + pub(super) fn on_hook_started(&mut self, run: codex_app_server_protocol::HookRunSummary) { + self.flush_answer_stream_with_separator(); + self.flush_completed_hook_output(); + match self.active_hook_cell.as_mut() { + Some(cell) => { + cell.start_run(run); + self.bump_active_cell_revision(); + } + None => { + self.active_hook_cell = Some(history_cell::new_active_hook_cell( + run, + self.config.animations, + )); + self.bump_active_cell_revision(); + } + } + self.request_redraw(); + } + + pub(super) fn on_hook_completed( + &mut self, + completed: codex_app_server_protocol::HookRunSummary, + ) { + let completed_existing_run = self + .active_hook_cell + .as_mut() + .map(|cell| cell.complete_run(completed.clone())) + .unwrap_or(false); + if completed_existing_run { + self.bump_active_cell_revision(); + } else { + match self.active_hook_cell.as_mut() { + Some(cell) => { + cell.add_completed_run(completed); + self.bump_active_cell_revision(); + } + None => { + let cell = + history_cell::new_completed_hook_cell(completed, self.config.animations); + if !cell.is_empty() { + self.active_hook_cell = Some(cell); + self.bump_active_cell_revision(); + } + } + } + } + self.flush_completed_hook_output(); + self.finish_active_hook_cell_if_idle(); + self.request_redraw(); + } + + pub(super) fn flush_completed_hook_output(&mut self) { + let Some(completed_cell) = self + .active_hook_cell + .as_mut() + .and_then(HookCell::take_completed_persistent_runs) + else { + return; + }; + let active_cell_is_empty = self + .active_hook_cell + .as_ref() + .is_some_and(HookCell::is_empty); + if active_cell_is_empty { + self.active_hook_cell = None; + } + self.bump_active_cell_revision(); + self.transcript.needs_final_message_separator = true; + self.app_event_tx + .send(AppEvent::InsertHistoryCell(Box::new(completed_cell))); + } + + pub(super) fn finish_active_hook_cell_if_idle(&mut self) { + let Some(cell) = self.active_hook_cell.as_ref() else { + return; + }; + if cell.is_empty() { + self.active_hook_cell = None; + self.bump_active_cell_revision(); + return; + } + if cell.should_flush() + && let Some(cell) = self.active_hook_cell.take() + { + self.bump_active_cell_revision(); + self.transcript.needs_final_message_separator = true; + self.app_event_tx + .send(AppEvent::InsertHistoryCell(Box::new(cell))); + } + } + + pub(super) fn update_due_hook_visibility(&mut self) { + let Some(cell) = self.active_hook_cell.as_mut() else { + return; + }; + let now = Instant::now(); + if cell.advance_time(now) { + self.bump_active_cell_revision(); + } + self.finish_active_hook_cell_if_idle(); + } + + pub(super) fn schedule_hook_timer_if_needed(&self) { + if self.config.animations + && self + .active_hook_cell + .as_ref() + .is_some_and(HookCell::has_visible_running_run) + { + self.frame_requester + .schedule_frame_in(Duration::from_millis(50)); + } + + let Some(deadline) = self + .active_hook_cell + .as_ref() + .and_then(HookCell::next_timer_deadline) + else { + return; + }; + let delay = deadline.saturating_duration_since(Instant::now()); + self.frame_requester.schedule_frame_in(delay); + } +} diff --git a/codex-rs/tui/src/chatwidget/protocol_requests.rs b/codex-rs/tui/src/chatwidget/protocol_requests.rs new file mode 100644 index 0000000000..5b53f44fdf --- /dev/null +++ b/codex-rs/tui/src/chatwidget/protocol_requests.rs @@ -0,0 +1,148 @@ +//! App-server request and notification dispatch for `ChatWidget`. +//! +//! This module translates protocol requests into the focused chat-widget flows +//! that render approvals, permissions, tool input, and guardian reviews. + +use super::*; + +impl ChatWidget { + pub(crate) fn handle_server_request( + &mut self, + request: ServerRequest, + replay_kind: Option, + ) { + let id = request.id().to_string(); + match request { + ServerRequest::CommandExecutionRequestApproval { params, .. } => { + let fallback_cwd = self.config.cwd.clone(); + self.on_exec_approval_request( + id, + exec_approval_request_from_params(params, &fallback_cwd), + ); + } + ServerRequest::FileChangeRequestApproval { params, .. } => { + self.on_apply_patch_approval_request( + id, + patch_approval_request_from_params(params), + ); + } + ServerRequest::McpServerElicitationRequest { request_id, params } => { + self.on_elicitation_request(request_id, params); + } + ServerRequest::PermissionsRequestApproval { params, .. } => { + self.on_request_permissions(request_permissions_from_params(params)); + } + ServerRequest::ToolRequestUserInput { params, .. } => { + self.on_request_user_input(params); + } + ServerRequest::DynamicToolCall { .. } + | ServerRequest::AttestationGenerate { .. } + | ServerRequest::ChatgptAuthTokensRefresh { .. } + | ServerRequest::ApplyPatchApproval { .. } + | ServerRequest::ExecCommandApproval { .. } => { + if replay_kind.is_none() { + self.add_error_message(TUI_STUB_MESSAGE.to_string()); + } + } + } + } + + pub(crate) fn handle_skills_list_response(&mut self, response: SkillsListResponse) { + self.on_list_skills(response); + } + + pub(super) fn on_patch_apply_output_delta(&mut self, _item_id: String, _delta: String) {} + + pub(super) fn on_guardian_review_notification( + &mut self, + id: String, + turn_id: String, + started_at_ms: i64, + review: codex_app_server_protocol::GuardianApprovalReview, + completion: Option<(i64, codex_app_server_protocol::AutoReviewDecisionSource)>, + action: GuardianApprovalReviewAction, + ) { + let (completed_at_ms, decision_source) = match completion { + Some((completed_at_ms, decision_source)) => { + (Some(completed_at_ms), Some(decision_source)) + } + None => (None, None), + }; + + self.on_guardian_assessment(GuardianAssessmentEvent { + id, + target_item_id: None, + turn_id, + started_at_ms, + completed_at_ms, + status: match review.status { + codex_app_server_protocol::GuardianApprovalReviewStatus::InProgress => { + GuardianAssessmentStatus::InProgress + } + codex_app_server_protocol::GuardianApprovalReviewStatus::Approved => { + GuardianAssessmentStatus::Approved + } + codex_app_server_protocol::GuardianApprovalReviewStatus::Denied => { + GuardianAssessmentStatus::Denied + } + codex_app_server_protocol::GuardianApprovalReviewStatus::TimedOut => { + GuardianAssessmentStatus::TimedOut + } + codex_app_server_protocol::GuardianApprovalReviewStatus::Aborted => { + GuardianAssessmentStatus::Aborted + } + }, + risk_level: review.risk_level.map(|risk_level| match risk_level { + codex_app_server_protocol::GuardianRiskLevel::Low => { + codex_protocol::approvals::GuardianRiskLevel::Low + } + codex_app_server_protocol::GuardianRiskLevel::Medium => { + codex_protocol::approvals::GuardianRiskLevel::Medium + } + codex_app_server_protocol::GuardianRiskLevel::High => { + codex_protocol::approvals::GuardianRiskLevel::High + } + codex_app_server_protocol::GuardianRiskLevel::Critical => { + codex_protocol::approvals::GuardianRiskLevel::Critical + } + }), + user_authorization: review.user_authorization.map(|user_authorization| { + match user_authorization { + codex_app_server_protocol::GuardianUserAuthorization::Unknown => { + codex_protocol::approvals::GuardianUserAuthorization::Unknown + } + codex_app_server_protocol::GuardianUserAuthorization::Low => { + codex_protocol::approvals::GuardianUserAuthorization::Low + } + codex_app_server_protocol::GuardianUserAuthorization::Medium => { + codex_protocol::approvals::GuardianUserAuthorization::Medium + } + codex_app_server_protocol::GuardianUserAuthorization::High => { + codex_protocol::approvals::GuardianUserAuthorization::High + } + } + }), + rationale: review.rationale, + decision_source: decision_source.map(|source| match source { + codex_app_server_protocol::AutoReviewDecisionSource::Agent => { + GuardianAssessmentDecisionSource::Agent + } + }), + action: action.into(), + }); + } + + pub(super) fn on_shutdown_complete(&mut self) { + self.request_immediate_exit(); + } + + pub(super) fn on_turn_diff(&mut self, unified_diff: String) { + debug!("TurnDiffEvent: {unified_diff}"); + self.refresh_status_line(); + } + + pub(super) fn on_deprecation_notice(&mut self, summary: String, details: Option) { + self.add_to_history(history_cell::new_deprecation_notice(summary, details)); + self.request_redraw(); + } +} diff --git a/codex-rs/tui/src/chatwidget/replay.rs b/codex-rs/tui/src/chatwidget/replay.rs new file mode 100644 index 0000000000..294e07e33a --- /dev/null +++ b/codex-rs/tui/src/chatwidget/replay.rs @@ -0,0 +1,196 @@ +//! Thread replay rendering for `ChatWidget`. +//! +//! This module rehydrates turns and items into transcript state while avoiding +//! live-only side effects. + +use super::*; + +impl ChatWidget { + /// Replay a subset of initial events into the UI to seed the transcript when + /// resuming an existing session. This approximates the live event flow and + /// is intentionally conservative: only safe-to-replay items are rendered to + /// avoid triggering side effects. Event ids are passed as `None` to + /// distinguish replayed events from live ones. + pub(crate) fn replay_thread_turns(&mut self, turns: Vec, replay_kind: ReplayKind) { + for turn in turns { + let Turn { + id: turn_id, + items_view: _, + items, + status, + error, + started_at, + completed_at, + duration_ms, + } = turn; + if matches!(status, TurnStatus::InProgress) { + self.last_non_retry_error = None; + self.on_task_started(); + } + for item in items { + self.replay_thread_item(item, turn_id.clone(), replay_kind); + } + if matches!( + status, + TurnStatus::Completed | TurnStatus::Interrupted | TurnStatus::Failed + ) { + self.handle_turn_completed_notification( + TurnCompletedNotification { + thread_id: self.thread_id.map(|id| id.to_string()).unwrap_or_default(), + turn: Turn { + id: turn_id, + items_view: codex_app_server_protocol::TurnItemsView::NotLoaded, + items: Vec::new(), + status, + error, + started_at, + completed_at, + duration_ms, + }, + }, + Some(replay_kind), + ); + } + } + } + + pub(crate) fn replay_thread_item( + &mut self, + item: ThreadItem, + turn_id: String, + replay_kind: ReplayKind, + ) { + self.handle_thread_item(item, turn_id, ThreadItemRenderSource::Replay(replay_kind)); + } + + pub(super) fn handle_thread_item( + &mut self, + item: ThreadItem, + turn_id: String, + render_source: ThreadItemRenderSource, + ) { + let from_replay = render_source.is_replay(); + let replay_kind = render_source.replay_kind(); + match item { + ThreadItem::UserMessage { content, .. } => { + self.on_committed_user_message(&content, from_replay); + } + ThreadItem::AgentMessage { + id, + text, + phase, + memory_citation, + } => { + self.on_agent_message_item_completed( + AgentMessageItem { + id, + content: vec![AgentMessageContent::Text { text }], + phase, + memory_citation: memory_citation.map(|citation| { + codex_protocol::memory_citation::MemoryCitation { + entries: citation + .entries + .into_iter() + .map(|entry| { + codex_protocol::memory_citation::MemoryCitationEntry { + path: entry.path, + line_start: entry.line_start, + line_end: entry.line_end, + note: entry.note, + } + }) + .collect(), + rollout_ids: citation.thread_ids, + } + }), + }, + from_replay, + ); + } + ThreadItem::Plan { text, .. } => self.on_plan_item_completed(text), + ThreadItem::Reasoning { + summary, content, .. + } => { + if from_replay { + for delta in summary { + self.on_agent_reasoning_delta(delta); + } + if self.config.show_raw_agent_reasoning { + for delta in content { + self.on_agent_reasoning_delta(delta); + } + } + } + self.on_agent_reasoning_final(); + } + item @ ThreadItem::CommandExecution { + status: codex_app_server_protocol::CommandExecutionStatus::InProgress, + .. + } => self.on_command_execution_started(item), + item @ ThreadItem::CommandExecution { .. } => self.on_command_execution_completed(item), + ThreadItem::FileChange { + status: codex_app_server_protocol::PatchApplyStatus::InProgress, + .. + } => {} + item @ ThreadItem::FileChange { .. } => self.on_file_change_completed(item), + item @ ThreadItem::McpToolCall { .. } => self.on_mcp_tool_call_completed(item), + ThreadItem::WebSearch { id, query, action } => { + self.on_web_search_begin(id.clone()); + self.on_web_search_end( + id, + query, + action.unwrap_or(codex_app_server_protocol::WebSearchAction::Other), + ); + } + ThreadItem::ImageView { id: _, path } => { + self.on_view_image_tool_call(path); + } + ThreadItem::ImageGeneration { + id, + revised_prompt, + saved_path, + .. + } => { + self.on_image_generation_end(id, revised_prompt, saved_path); + } + ThreadItem::EnteredReviewMode { review, .. } => { + if from_replay { + self.enter_review_mode_with_hint(review, /*from_replay*/ true); + } + } + ThreadItem::ExitedReviewMode { .. } => { + self.exit_review_mode_after_item(); + } + ThreadItem::ContextCompaction { .. } => { + self.add_info_message("Context compacted".to_string(), /*hint*/ None); + } + ThreadItem::HookPrompt { .. } => {} + ThreadItem::CollabAgentToolCall { + id, + tool, + status, + sender_thread_id, + receiver_thread_ids, + prompt, + model, + reasoning_effort, + agents_states, + } => self.on_collab_agent_tool_call(ThreadItem::CollabAgentToolCall { + id, + tool, + status, + sender_thread_id, + receiver_thread_ids, + prompt, + model, + reasoning_effort, + agents_states, + }), + ThreadItem::DynamicToolCall { .. } => {} + } + + if matches!(replay_kind, Some(ReplayKind::ThreadSnapshot)) && turn_id.is_empty() { + self.request_redraw(); + } + } +} diff --git a/codex-rs/tui/src/chatwidget/streaming.rs b/codex-rs/tui/src/chatwidget/streaming.rs new file mode 100644 index 0000000000..e6f5701d1c --- /dev/null +++ b/codex-rs/tui/src/chatwidget/streaming.rs @@ -0,0 +1,459 @@ +//! Streaming transcript updates for `ChatWidget`. +//! +//! This module owns assistant, plan, and reasoning deltas, including stream-tail +//! cells, commit ticks, and interrupt deferral. + +use super::*; + +impl ChatWidget { + pub(super) fn restore_reasoning_status_header(&mut self) { + if let Some(header) = extract_first_bold(&self.reasoning_buffer) { + self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking; + self.set_status_header(header); + } else if self.bottom_pane.is_task_running() { + self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Working; + self.set_status_header(String::from("Working")); + } + } + + pub(super) fn flush_answer_stream_with_separator(&mut self) { + let had_stream_controller = self.stream_controller.is_some(); + if let Some(mut controller) = self.stream_controller.take() { + let scrollback_reflow = if controller.has_live_tail() { + crate::app_event::ConsolidationScrollbackReflow::Required + } else { + crate::app_event::ConsolidationScrollbackReflow::IfResizeReflowRan + }; + self.clear_active_stream_tail(); + let (cell, source) = controller.finalize(); + let deferred_history_cell = + if scrollback_reflow == crate::app_event::ConsolidationScrollbackReflow::Required { + cell + } else { + if let Some(cell) = cell { + self.add_boxed_history(cell); + } + None + }; + // Consolidate the run of streaming AgentMessageCells into a single AgentMarkdownCell + // that can re-render from source on resize. + if let Some(source) = source { + let source = parse_assistant_markdown(&source).visible_markdown; + self.app_event_tx.send(AppEvent::ConsolidateAgentMessage { + source, + cwd: self.config.cwd.to_path_buf(), + scrollback_reflow, + deferred_history_cell, + }); + } + } + self.adaptive_chunking.reset(); + if had_stream_controller && self.stream_controllers_idle() { + self.app_event_tx.send(AppEvent::StopCommitAnimation); + } + } + + pub(super) fn stream_controllers_idle(&self) -> bool { + self.stream_controller + .as_ref() + .map(|controller| controller.queued_lines() == 0) + .unwrap_or(true) + && self + .plan_stream_controller + .as_ref() + .map(|controller| controller.queued_lines() == 0) + .unwrap_or(true) + } + + /// Restore the status indicator only after commentary completion is pending, + /// the turn is still running, and all stream queues have drained. + /// + /// This gate prevents flicker while normal output is still actively + /// streaming, but still restores a visible "working" affordance when a + /// commentary block ends before the turn itself has completed. + pub(super) fn maybe_restore_status_indicator_after_stream_idle(&mut self) { + if !self.status_state.pending_status_indicator_restore + || !self.bottom_pane.is_task_running() + || !self.stream_controllers_idle() + { + return; + } + + self.bottom_pane.ensure_status_indicator(); + self.set_status( + self.status_state.current_status.header.clone(), + self.status_state.current_status.details.clone(), + StatusDetailsCapitalization::Preserve, + self.status_state.current_status.details_max_lines, + ); + self.status_state.pending_status_indicator_restore = false; + } + + pub(super) fn finalize_completed_assistant_message(&mut self, message: Option<&str>) { + // If we have a stream_controller, the finalized message payload is redundant because the + // visible content has already been accumulated through deltas. + if self.stream_controller.is_none() + && let Some(message) = message + && !message.is_empty() + { + self.handle_streaming_delta(message.to_string()); + } + self.flush_answer_stream_with_separator(); + self.handle_stream_finished(); + self.request_redraw(); + } + + pub(super) fn on_agent_message_delta(&mut self, delta: String) { + self.handle_streaming_delta(delta); + } + + pub(super) fn on_plan_delta(&mut self, delta: String) { + if self.active_mode_kind() != ModeKind::Plan { + return; + } + if !self.transcript.plan_item_active { + self.transcript.plan_item_active = true; + self.transcript.plan_delta_buffer.clear(); + } + self.transcript.plan_delta_buffer.push_str(&delta); + if self.plan_stream_controller.is_none() { + // Before starting a plan stream, flush any active exec cell group. + self.flush_unified_exec_wait_streak(); + self.flush_active_cell(); + self.plan_stream_controller = Some(PlanStreamController::new( + self.current_stream_width(/*reserved_cols*/ 4), + &self.config.cwd, + self.history_render_mode(), + )); + } + if let Some(controller) = self.plan_stream_controller.as_mut() + && controller.push(&delta) + { + self.app_event_tx.send(AppEvent::StartCommitAnimation); + self.run_catch_up_commit_tick(); + } + self.sync_active_stream_tail(); + self.request_redraw(); + } + + pub(super) fn on_plan_item_completed(&mut self, text: String) { + let streamed_plan = self.transcript.plan_delta_buffer.trim().to_string(); + let plan_text = if text.trim().is_empty() { + streamed_plan + } else { + text + }; + if !plan_text.trim().is_empty() { + self.record_agent_markdown(&plan_text); + self.transcript.latest_proposed_plan_markdown = Some(plan_text.clone()); + } + // Plan commit ticks can hide the status row; remember whether we streamed plan output so + // completion can restore it once stream queues are idle. + let should_restore_after_stream = self.plan_stream_controller.is_some(); + self.transcript.plan_delta_buffer.clear(); + self.transcript.plan_item_active = false; + self.transcript.saw_plan_item_this_turn = true; + let (finalized_streamed_cell, consolidated_plan_source) = + if let Some(mut controller) = self.plan_stream_controller.take() { + let had_live_tail = controller.has_live_tail(); + self.clear_active_stream_tail(); + let (cell, source) = controller.finalize(); + if had_live_tail { + (None, source) + } else { + (cell, source) + } + } else { + (None, None) + }; + if let Some(cell) = finalized_streamed_cell { + self.add_boxed_history(cell); + // TODO: Replace streamed output with the final plan item text if plan streaming is + // removed or if we need to reconcile mismatches between streamed and final content. + if let Some(source) = consolidated_plan_source { + self.app_event_tx + .send(AppEvent::ConsolidateProposedPlan(source)); + } + } else if !plan_text.is_empty() { + self.add_to_history(history_cell::new_proposed_plan(plan_text, &self.config.cwd)); + } else if let Some(source) = consolidated_plan_source { + self.app_event_tx + .send(AppEvent::ConsolidateProposedPlan(source)); + } + if should_restore_after_stream { + self.status_state.pending_status_indicator_restore = true; + self.maybe_restore_status_indicator_after_stream_idle(); + } + } + + pub(super) fn on_agent_reasoning_delta(&mut self, delta: String) { + // For reasoning deltas, do not stream to history. Accumulate the + // current reasoning block and extract the first bold element + // (between **/**) as the chunk header. Show this header as status. + self.reasoning_buffer.push_str(&delta); + + if self.unified_exec_wait_streak.is_some() { + // Unified exec waiting should take precedence over reasoning-derived status headers. + self.request_redraw(); + return; + } + + if let Some(header) = extract_first_bold(&self.reasoning_buffer) { + // Update the shimmer header to the extracted reasoning chunk header. + self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking; + self.set_status_header(header); + } else { + // Fallback while we don't yet have a bold header: leave existing header as-is. + } + self.request_redraw(); + } + + pub(super) fn on_agent_reasoning_final(&mut self) { + // At the end of a reasoning block, record transcript-only content. + self.full_reasoning_buffer.push_str(&self.reasoning_buffer); + if !self.full_reasoning_buffer.is_empty() { + let cell = history_cell::new_reasoning_summary_block( + self.full_reasoning_buffer.clone(), + &self.config.cwd, + ); + self.add_boxed_history(cell); + } + self.reasoning_buffer.clear(); + self.full_reasoning_buffer.clear(); + self.request_redraw(); + } + + pub(super) fn on_reasoning_section_break(&mut self) { + // Start a new reasoning block for header extraction and accumulate transcript. + self.full_reasoning_buffer.push_str(&self.reasoning_buffer); + self.full_reasoning_buffer.push_str("\n\n"); + self.reasoning_buffer.clear(); + } + + pub(super) fn on_stream_error(&mut self, message: String, additional_details: Option) { + self.status_state.remember_retry_status_header(); + self.bottom_pane.ensure_status_indicator(); + self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking; + self.set_status( + message, + additional_details, + StatusDetailsCapitalization::CapitalizeFirst, + STATUS_DETAILS_DEFAULT_MAX_LINES, + ); + } + + /// Handle completion of an `AgentMessage` turn item. + /// + /// Commentary completion sets a deferred restore flag so the status row + /// returns once stream queues are idle. Final-answer completion (or absent + /// phase for legacy models) clears the flag to preserve historical behavior. + pub(super) fn on_agent_message_item_completed( + &mut self, + item: AgentMessageItem, + from_replay: bool, + ) { + let mut message = String::new(); + for content in &item.content { + match content { + AgentMessageContent::Text { text } => message.push_str(text), + } + } + let parsed = parse_assistant_markdown(&message); + self.finalize_completed_assistant_message( + (!parsed.visible_markdown.is_empty()).then_some(parsed.visible_markdown.as_str()), + ); + if matches!(item.phase, Some(MessagePhase::FinalAnswer) | None) + && !parsed.visible_markdown.is_empty() + { + self.record_agent_markdown(&parsed.visible_markdown); + } + if !from_replay + && let Some(cwd) = parsed.last_created_branch_cwd() + && let Some(thread_id) = self.thread_id + && let Some(runner) = self.workspace_command_runner.clone() + { + let cwd = PathBuf::from(cwd); + let tx = self.app_event_tx.clone(); + tokio::spawn(async move { + if let Some(branch) = + crate::branch_summary::current_branch_name(runner.as_ref(), &cwd).await + { + tx.send(AppEvent::SyncThreadGitBranch { thread_id, branch }); + } + }); + } + self.status_state.pending_status_indicator_restore = match item.phase { + // Models that don't support preambles only output AgentMessageItems on turn completion. + Some(MessagePhase::FinalAnswer) | None => !self.input_queue.pending_steers.is_empty(), + Some(MessagePhase::Commentary) => true, + }; + self.maybe_restore_status_indicator_after_stream_idle(); + } + + /// Periodic tick for stream commits. In smooth mode this preserves one-line pacing, while + /// catch-up mode drains larger batches to reduce queue lag. + pub(crate) fn on_commit_tick(&mut self) { + self.run_commit_tick(); + } + + /// Runs a regular periodic commit tick. + pub(super) fn run_commit_tick(&mut self) { + self.run_commit_tick_with_scope(CommitTickScope::AnyMode); + } + + /// Runs an opportunistic commit tick only if catch-up mode is active. + pub(super) fn run_catch_up_commit_tick(&mut self) { + self.run_commit_tick_with_scope(CommitTickScope::CatchUpOnly); + } + + /// Runs a commit tick for the current stream queue snapshot. + /// + /// `scope` controls whether this call may commit in smooth mode or only when catch-up + /// is currently active. While lines are actively streaming we hide the status row to avoid + /// duplicate "in progress" affordances. Restoration is gated separately so we only re-show + /// the row after commentary completion once stream queues are idle. + pub(super) fn run_commit_tick_with_scope(&mut self, scope: CommitTickScope) { + let now = Instant::now(); + let outcome = run_commit_tick( + &mut self.adaptive_chunking, + self.stream_controller.as_mut(), + self.plan_stream_controller.as_mut(), + scope, + now, + ); + for cell in outcome.cells { + self.bottom_pane.hide_status_indicator(); + self.add_boxed_history(cell); + } + self.sync_active_stream_tail(); + + if outcome.has_controller && outcome.all_idle { + self.maybe_restore_status_indicator_after_stream_idle(); + self.app_event_tx.send(AppEvent::StopCommitAnimation); + } + + if self.turn_lifecycle.agent_turn_running { + self.refresh_runtime_metrics(); + } + } + + pub(super) fn flush_interrupt_queue(&mut self) { + let mut mgr = std::mem::take(&mut self.interrupts); + mgr.flush_all(self); + self.interrupts = mgr; + } + + #[inline] + pub(super) fn defer_or_handle( + &mut self, + push: impl FnOnce(&mut InterruptManager), + handle: impl FnOnce(&mut Self), + ) { + // Preserve deterministic FIFO across queued interrupts: once anything + // is queued due to an active write cycle, continue queueing until the + // queue is flushed to avoid reordering (e.g., ExecEnd before ExecBegin). + if self.stream_controller.is_some() || !self.interrupts.is_empty() { + push(&mut self.interrupts); + } else { + handle(self); + } + } + + pub(super) fn handle_stream_finished(&mut self) { + if self.task_complete_pending { + self.bottom_pane.hide_status_indicator(); + self.task_complete_pending = false; + } + // A completed stream indicates non-exec content was just inserted. + self.flush_interrupt_queue(); + } + + #[inline] + pub(super) fn handle_streaming_delta(&mut self, delta: String) { + if self.stream_controller.is_none() { + // Before starting an agent stream, flush any active exec cell group. + self.flush_unified_exec_wait_streak(); + self.flush_active_cell(); + // If the previous turn inserted non-stream history (exec output, patch status, MCP + // calls), render a separator before starting the next streamed assistant message. + if self.transcript.needs_final_message_separator && self.transcript.had_work_activity { + self.add_to_history(history_cell::FinalMessageSeparator::new( + /*elapsed_seconds*/ None, /*runtime_metrics*/ None, + )); + self.transcript.needs_final_message_separator = false; + } else if self.transcript.needs_final_message_separator { + // Reset the flag even if we don't show separator (no work was done) + self.transcript.needs_final_message_separator = false; + } + self.stream_controller = Some(StreamController::new( + self.current_stream_width(/*reserved_cols*/ 2), + &self.config.cwd, + self.history_render_mode(), + )); + } + if let Some(controller) = self.stream_controller.as_mut() + && controller.push(&delta) + { + self.app_event_tx.send(AppEvent::StartCommitAnimation); + self.run_catch_up_commit_tick(); + } + self.sync_active_stream_tail(); + self.request_redraw(); + } + + pub(super) fn active_cell_is_stream_tail(&self) -> bool { + self.transcript.active_cell.as_ref().is_some_and(|cell| { + cell.as_any().is::() + || cell.as_any().is::() + }) + } + + pub(super) fn has_active_stream_tail(&self) -> bool { + (self.stream_controller.is_some() || self.plan_stream_controller.is_some()) + && self.active_cell_is_stream_tail() + } + + pub(super) fn sync_active_stream_tail(&mut self) { + if let Some(controller) = self.stream_controller.as_ref() { + let tail_lines = controller.current_tail_lines(); + if tail_lines.is_empty() { + self.clear_active_stream_tail(); + return; + } + + self.bottom_pane.hide_status_indicator(); + self.transcript.active_cell = + Some(Box::new(history_cell::StreamingAgentTailCell::new( + tail_lines, + controller.tail_starts_stream(), + ))); + self.bump_active_cell_revision(); + return; + } + + if let Some(controller) = self.plan_stream_controller.as_ref() { + let tail_lines = controller.current_tail_display_lines(); + if tail_lines.is_empty() { + self.clear_active_stream_tail(); + return; + } + + self.bottom_pane.hide_status_indicator(); + self.transcript.active_cell = Some(Box::new(history_cell::StreamingPlanTailCell::new( + tail_lines, + !controller.tail_starts_stream(), + ))); + self.bump_active_cell_revision(); + return; + } + + self.clear_active_stream_tail(); + } + + pub(super) fn clear_active_stream_tail(&mut self) { + if self.active_cell_is_stream_tail() { + self.transcript.active_cell = None; + self.bump_active_cell_revision(); + } + } +} diff --git a/codex-rs/tui/src/chatwidget/tool_lifecycle.rs b/codex-rs/tui/src/chatwidget/tool_lifecycle.rs new file mode 100644 index 0000000000..456e064caa --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tool_lifecycle.rs @@ -0,0 +1,264 @@ +//! Non-command tool lifecycle rendering for `ChatWidget`. +//! +//! This module handles patch, MCP, web search, image, and collaborator tool +//! events as transcript cells. + +use super::*; + +impl ChatWidget { + pub(super) fn on_patch_apply_begin(&mut self, changes: HashMap) { + self.add_to_history(history_cell::new_patch_event(changes, &self.config.cwd)); + } + + pub(super) fn on_view_image_tool_call(&mut self, path: AbsolutePathBuf) { + self.flush_answer_stream_with_separator(); + self.add_to_history(history_cell::new_view_image_tool_call( + path, + &self.config.cwd, + )); + self.request_redraw(); + } + + pub(super) fn on_image_generation_begin(&mut self) { + self.flush_answer_stream_with_separator(); + } + + pub(super) fn on_image_generation_end( + &mut self, + call_id: String, + revised_prompt: Option, + saved_path: Option, + ) { + self.flush_answer_stream_with_separator(); + self.add_to_history(history_cell::new_image_generation_call( + call_id, + revised_prompt, + saved_path, + )); + self.request_redraw(); + } + + pub(super) fn on_file_change_completed(&mut self, item: ThreadItem) { + let item2 = item.clone(); + self.defer_or_handle( + |q| q.push_item_completed(item), + |s| s.handle_file_change_completed_now(item2), + ); + } + + pub(super) fn on_mcp_tool_call_started(&mut self, item: ThreadItem) { + let item2 = item.clone(); + self.defer_or_handle( + |q| q.push_item_started(item), + |s| s.handle_mcp_tool_call_started_now(item2), + ); + } + + pub(super) fn on_mcp_tool_call_completed(&mut self, item: ThreadItem) { + let item2 = item.clone(); + self.defer_or_handle( + |q| q.push_item_completed(item), + |s| s.handle_mcp_tool_call_completed_now(item2), + ); + } + + pub(super) fn on_web_search_begin(&mut self, call_id: String) { + self.flush_answer_stream_with_separator(); + self.flush_active_cell(); + self.transcript.active_cell = Some(Box::new(history_cell::new_active_web_search_call( + call_id, + String::new(), + self.config.animations, + ))); + self.bump_active_cell_revision(); + self.request_redraw(); + } + + pub(super) fn on_web_search_end( + &mut self, + call_id: String, + query: String, + action: codex_app_server_protocol::WebSearchAction, + ) { + self.flush_answer_stream_with_separator(); + let mut handled = false; + if let Some(cell) = self + .transcript + .active_cell + .as_mut() + .and_then(|cell| cell.as_any_mut().downcast_mut::()) + && cell.call_id() == call_id + { + cell.update(action.clone(), query.clone()); + cell.complete(); + self.bump_active_cell_revision(); + self.flush_active_cell(); + handled = true; + } + + if !handled { + self.add_to_history(history_cell::new_web_search_call(call_id, query, action)); + } + self.transcript.had_work_activity = true; + } + + pub(super) fn on_collab_event(&mut self, cell: PlainHistoryCell) { + self.flush_answer_stream_with_separator(); + self.add_to_history(cell); + self.request_redraw(); + } + + pub(super) fn on_collab_agent_tool_call(&mut self, item: ThreadItem) { + let ThreadItem::CollabAgentToolCall { + id, tool, status, .. + } = &item + else { + return; + }; + if matches!(tool, CollabAgentTool::SpawnAgent) + && let Some(spawn_request) = multi_agents::spawn_request_summary(&item) + { + self.pending_collab_spawn_requests + .insert(id.clone(), spawn_request); + } + + let cached_spawn_request = if matches!(tool, CollabAgentTool::SpawnAgent) + && !matches!(status, CollabAgentToolCallStatus::InProgress) + { + self.pending_collab_spawn_requests.remove(id) + } else { + None + }; + + if let Some(cell) = multi_agents::tool_call_history_cell( + &item, + cached_spawn_request.as_ref(), + |thread_id| self.collab_agent_metadata(thread_id), + ) { + self.on_collab_event(cell); + } + } + + pub(crate) fn handle_file_change_completed_now(&mut self, item: ThreadItem) { + let ThreadItem::FileChange { status, .. } = item else { + return; + }; + // If the patch was successful, just let the "Edited" block stand. + // Otherwise, add a failure block. + if matches!(status, codex_app_server_protocol::PatchApplyStatus::Failed) { + self.add_to_history(history_cell::new_patch_apply_failure(String::new())); + } + // Mark that actual work was done (patch applied) + self.transcript.had_work_activity = true; + } + + pub(crate) fn handle_mcp_tool_call_started_now(&mut self, item: ThreadItem) { + let ThreadItem::McpToolCall { + id, + server, + tool, + arguments, + .. + } = item + else { + return; + }; + self.flush_answer_stream_with_separator(); + self.flush_active_cell(); + self.transcript.active_cell = Some(Box::new(history_cell::new_active_mcp_tool_call( + id, + McpInvocation { + server, + tool, + arguments: Some(arguments), + }, + self.config.animations, + ))); + self.bump_active_cell_revision(); + self.request_redraw(); + } + + pub(crate) fn handle_mcp_tool_call_completed_now(&mut self, item: ThreadItem) { + self.flush_answer_stream_with_separator(); + + let ThreadItem::McpToolCall { + id, + server, + tool, + arguments, + result, + error, + duration_ms, + .. + } = item + else { + return; + }; + let invocation = McpInvocation { + server, + tool, + arguments: Some(arguments), + }; + let duration = Duration::from_millis(duration_ms.unwrap_or_default().max(0) as u64); + let result = match (result, error) { + (_, Some(error)) => Err(error.message), + (Some(result), None) => { + let result = *result; + Ok(codex_protocol::mcp::CallToolResult { + content: result.content, + structured_content: result.structured_content, + is_error: Some(false), + meta: None, + }) + } + (None, None) => Err("MCP tool call completed without a result".to_string()), + }; + + let extra_cell = match self + .transcript + .active_cell + .as_mut() + .and_then(|cell| cell.as_any_mut().downcast_mut::()) + { + Some(cell) if cell.call_id() == id => cell.complete(duration, result), + _ => { + self.flush_active_cell(); + let mut cell = + history_cell::new_active_mcp_tool_call(id, invocation, self.config.animations); + let extra_cell = cell.complete(duration, result); + self.transcript.active_cell = Some(Box::new(cell)); + extra_cell + } + }; + + self.flush_active_cell(); + if let Some(extra) = extra_cell { + self.add_boxed_history(extra); + } + // Mark that actual work was done (MCP tool call) + self.transcript.had_work_activity = true; + } + + pub(crate) fn handle_queued_item_started_now(&mut self, item: ThreadItem) { + match item { + item @ ThreadItem::CommandExecution { .. } => { + self.handle_command_execution_started_now(item); + } + item @ ThreadItem::McpToolCall { .. } => { + self.handle_mcp_tool_call_started_now(item); + } + _ => {} + } + } + + pub(crate) fn handle_queued_item_completed_now(&mut self, item: ThreadItem) { + match item { + item @ ThreadItem::CommandExecution { .. } => { + self.handle_command_execution_completed_now(item); + } + item @ ThreadItem::FileChange { .. } => self.handle_file_change_completed_now(item), + item @ ThreadItem::McpToolCall { .. } => self.handle_mcp_tool_call_completed_now(item), + _ => {} + } + } +} diff --git a/codex-rs/tui/src/chatwidget/tool_requests.rs b/codex-rs/tui/src/chatwidget/tool_requests.rs new file mode 100644 index 0000000000..7ec567325b --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tool_requests.rs @@ -0,0 +1,449 @@ +//! Interactive tool request surfaces for `ChatWidget`. +//! +//! This module owns approval, permission, elicitation, and user-input prompts +//! that block on user decisions. + +use super::*; + +impl ChatWidget { + pub(super) fn on_exec_approval_request(&mut self, _id: String, ev: ExecApprovalRequestEvent) { + let ev2 = ev.clone(); + self.defer_or_handle( + |q| q.push_exec_approval(ev), + |s| s.handle_exec_approval_now(ev2), + ); + } + + pub(super) fn on_apply_patch_approval_request( + &mut self, + _id: String, + ev: ApplyPatchApprovalRequestEvent, + ) { + let ev2 = ev.clone(); + self.defer_or_handle( + |q| q.push_apply_patch_approval(ev), + |s| s.handle_apply_patch_approval_now(ev2), + ); + } + + /// Handle guardian review lifecycle events for the current thread. + /// + /// In-progress assessments temporarily own the live status footer so the + /// user can see what is being reviewed, including parallel review + /// aggregation. Terminal assessments clear or update that footer state and + /// render the final approved/denied history cell when guardian returns a + /// decision. + pub(super) fn on_guardian_assessment(&mut self, ev: GuardianAssessmentEvent) { + let permission_request_summary = |subject: &str, reason: &Option| { + reason + .as_deref() + .map(str::trim) + .filter(|reason| !reason.is_empty()) + .map(|reason| format!("{subject}: {reason}")) + .unwrap_or_else(|| subject.to_string()) + }; + let guardian_action_summary = |action: &GuardianAssessmentAction| match action { + GuardianAssessmentAction::Command { command, .. } => Some(command.clone()), + GuardianAssessmentAction::Execve { program, argv, .. } => { + let command = if argv.is_empty() { + vec![program.clone()] + } else { + argv.clone() + }; + shlex::try_join(command.iter().map(String::as_str)) + .ok() + .or_else(|| Some(command.join(" "))) + } + GuardianAssessmentAction::ApplyPatch { files, .. } => Some(if files.len() == 1 { + format!("apply_patch touching {}", files[0].display()) + } else { + format!("apply_patch touching {} files", files.len()) + }), + GuardianAssessmentAction::NetworkAccess { target, .. } => { + Some(format!("network access to {target}")) + } + GuardianAssessmentAction::McpToolCall { + server, + tool_name, + connector_name, + .. + } => { + let label = connector_name.as_deref().unwrap_or(server.as_str()); + Some(format!("MCP {tool_name} on {label}")) + } + GuardianAssessmentAction::RequestPermissions { reason, .. } => { + Some(permission_request_summary("permission request", reason)) + } + }; + let guardian_command = |action: &GuardianAssessmentAction| match action { + GuardianAssessmentAction::Command { command, .. } => shlex::split(command) + .filter(|command| !command.is_empty()) + .or_else(|| Some(vec![command.clone()])), + GuardianAssessmentAction::Execve { program, argv, .. } => Some(if argv.is_empty() { + vec![program.clone()] + } else { + argv.clone() + }) + .filter(|command| !command.is_empty()), + GuardianAssessmentAction::ApplyPatch { .. } + | GuardianAssessmentAction::NetworkAccess { .. } + | GuardianAssessmentAction::McpToolCall { .. } + | GuardianAssessmentAction::RequestPermissions { .. } => None, + }; + + if ev.status == GuardianAssessmentStatus::InProgress + && let Some(detail) = guardian_action_summary(&ev.action) + { + // In-progress assessments own the live footer state while the + // review is pending. Parallel reviews are aggregated into one + // footer summary by `PendingGuardianReviewStatus`. + self.bottom_pane.ensure_status_indicator(); + self.bottom_pane + .set_interrupt_hint_visible(/*visible*/ true); + self.status_state + .pending_guardian_review_status + .start_or_update(ev.id.clone(), detail); + if let Some(status) = self + .status_state + .pending_guardian_review_status + .status_indicator_state() + { + self.set_status( + status.header, + status.details, + StatusDetailsCapitalization::Preserve, + status.details_max_lines, + ); + } + self.request_redraw(); + return; + } + + // Terminal assessments remove the matching pending footer entry first, + // then render the final approved/denied history cell below. + if self + .status_state + .pending_guardian_review_status + .finish(&ev.id) + { + if let Some(status) = self + .status_state + .pending_guardian_review_status + .status_indicator_state() + { + self.set_status( + status.header, + status.details, + StatusDetailsCapitalization::Preserve, + status.details_max_lines, + ); + } else if self.status_state.current_status.is_guardian_review() { + self.set_status_header(String::from("Working")); + } + } else if self.status_state.pending_guardian_review_status.is_empty() + && self.status_state.current_status.is_guardian_review() + { + self.set_status_header(String::from("Working")); + } + + if ev.status == GuardianAssessmentStatus::Approved { + let cell = if let Some(command) = guardian_command(&ev.action) { + history_cell::new_approval_decision_cell( + command, + crate::history_cell::ReviewDecision::Approved, + history_cell::ApprovalDecisionActor::Guardian, + ) + } else if let Some(summary) = guardian_action_summary(&ev.action) { + history_cell::new_guardian_approved_action_request(summary) + } else { + let summary = serde_json::to_string(&ev.action) + .unwrap_or_else(|_| "".to_string()); + history_cell::new_guardian_approved_action_request(summary) + }; + + self.add_boxed_history(cell); + self.request_redraw(); + return; + } + + if ev.status == GuardianAssessmentStatus::TimedOut { + let cell = if let Some(command) = guardian_command(&ev.action) { + history_cell::new_approval_decision_cell( + command, + crate::history_cell::ReviewDecision::TimedOut, + history_cell::ApprovalDecisionActor::Guardian, + ) + } else { + match &ev.action { + GuardianAssessmentAction::ApplyPatch { files, .. } => { + let files = files + .iter() + .map(|path| path.display().to_string()) + .collect::>(); + history_cell::new_guardian_timed_out_patch_request(files) + } + GuardianAssessmentAction::McpToolCall { + server, tool_name, .. + } => history_cell::new_guardian_timed_out_action_request(format!( + "codex could call MCP tool {server}.{tool_name}" + )), + GuardianAssessmentAction::NetworkAccess { target, .. } => { + history_cell::new_guardian_timed_out_action_request(format!( + "codex could access {target}" + )) + } + GuardianAssessmentAction::RequestPermissions { reason, .. } => { + history_cell::new_guardian_timed_out_action_request( + permission_request_summary("codex could request permissions", reason), + ) + } + GuardianAssessmentAction::Command { .. } => unreachable!(), + GuardianAssessmentAction::Execve { .. } => unreachable!(), + } + }; + + self.add_boxed_history(cell); + self.request_redraw(); + return; + } + + if ev.status != GuardianAssessmentStatus::Denied { + return; + } + self.review.recent_auto_review_denials.push(ev.clone()); + let cell = if let Some(command) = guardian_command(&ev.action) { + history_cell::new_approval_decision_cell( + command, + crate::history_cell::ReviewDecision::Denied, + history_cell::ApprovalDecisionActor::Guardian, + ) + } else { + match &ev.action { + GuardianAssessmentAction::ApplyPatch { files, .. } => { + let files = files + .iter() + .map(|path| path.display().to_string()) + .collect::>(); + history_cell::new_guardian_denied_patch_request(files) + } + GuardianAssessmentAction::McpToolCall { + server, tool_name, .. + } => history_cell::new_guardian_denied_action_request(format!( + "codex to call MCP tool {server}.{tool_name}" + )), + GuardianAssessmentAction::NetworkAccess { target, .. } => { + history_cell::new_guardian_denied_action_request(format!( + "codex to access {target}" + )) + } + GuardianAssessmentAction::RequestPermissions { reason, .. } => { + history_cell::new_guardian_denied_action_request(permission_request_summary( + "codex to request permissions", + reason, + )) + } + GuardianAssessmentAction::Command { .. } => unreachable!(), + GuardianAssessmentAction::Execve { .. } => unreachable!(), + } + }; + + self.add_boxed_history(cell); + self.request_redraw(); + } + + pub(super) fn on_elicitation_request( + &mut self, + request_id: AppServerRequestId, + params: McpServerElicitationRequestParams, + ) { + let request_id2 = request_id.clone(); + let params2 = params.clone(); + self.defer_or_handle( + |q| q.push_elicitation(request_id, params), + |s| s.handle_elicitation_request_now(request_id2, params2), + ); + } + + pub(super) fn on_request_user_input(&mut self, ev: ToolRequestUserInputParams) { + let ev2 = ev.clone(); + self.defer_or_handle( + |q| q.push_user_input(ev), + |s| s.handle_request_user_input_now(ev2), + ); + } + + pub(super) fn on_request_permissions(&mut self, ev: RequestPermissionsEvent) { + let ev2 = ev.clone(); + self.defer_or_handle( + |q| q.push_request_permissions(ev), + |s| s.handle_request_permissions_now(ev2), + ); + } + + pub(crate) fn handle_exec_approval_now(&mut self, ev: ExecApprovalRequestEvent) { + self.flush_answer_stream_with_separator(); + let command = shlex::try_join(ev.command.iter().map(String::as_str)) + .unwrap_or_else(|_| ev.command.join(" ")); + self.notify(Notification::ExecApprovalRequested { command }); + + let available_decisions = ev.effective_available_decisions(); + let request = ApprovalRequest::Exec { + thread_id: self.thread_id.unwrap_or_default(), + thread_label: None, + id: ev.effective_approval_id(), + command: ev.command, + reason: ev.reason, + available_decisions, + network_approval_context: ev.network_approval_context, + additional_permissions: ev.additional_permissions, + }; + self.bottom_pane + .push_approval_request(request, &self.config.features); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + } + + pub(crate) fn handle_apply_patch_approval_now(&mut self, ev: ApplyPatchApprovalRequestEvent) { + self.flush_answer_stream_with_separator(); + + let request = ApprovalRequest::ApplyPatch { + thread_id: self.thread_id.unwrap_or_default(), + thread_label: None, + id: ev.call_id, + reason: ev.reason, + changes: ev.changes.clone(), + cwd: self.config.cwd.clone(), + }; + self.bottom_pane + .push_approval_request(request, &self.config.features); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + self.notify(Notification::EditApprovalRequested { + cwd: self.config.cwd.to_path_buf(), + changes: ev.changes.keys().cloned().collect(), + }); + } + + pub(crate) fn handle_elicitation_request_now( + &mut self, + request_id: AppServerRequestId, + params: McpServerElicitationRequestParams, + ) { + self.flush_answer_stream_with_separator(); + + self.notify(Notification::ElicitationRequested { + server_name: params.server_name.clone(), + }); + + let thread_id = self.thread_id.unwrap_or_default(); + if let Some(params) = crate::bottom_pane::AppLinkViewParams::from_url_app_server_request( + thread_id, + ¶ms.server_name, + request_id.clone(), + ¶ms.request, + ) { + self.open_app_link_view(params); + } else if let Some(request) = McpServerElicitationFormRequest::from_app_server_request( + thread_id, + request_id.clone(), + params.clone(), + ) { + self.bottom_pane + .push_mcp_server_elicitation_request(request); + } else { + match params.request { + McpServerElicitationRequest::Form { message, .. } => { + let request = ApprovalRequest::McpElicitation { + thread_id, + thread_label: None, + server_name: params.server_name, + request_id, + message, + }; + self.bottom_pane + .push_approval_request(request, &self.config.features); + } + McpServerElicitationRequest::Url { .. } => { + self.app_event_tx.resolve_elicitation( + thread_id, + params.server_name, + request_id, + codex_app_server_protocol::McpServerElicitationAction::Decline, + /*content*/ None, + /*meta*/ None, + ); + } + } + } + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + } + + pub(crate) fn push_approval_request(&mut self, request: ApprovalRequest) { + self.bottom_pane + .push_approval_request(request, &self.config.features); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + } + + pub(crate) fn push_mcp_server_elicitation_request( + &mut self, + request: McpServerElicitationFormRequest, + ) { + self.bottom_pane + .push_mcp_server_elicitation_request(request); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + } + + pub(crate) fn handle_request_user_input_now(&mut self, ev: ToolRequestUserInputParams) { + self.flush_answer_stream_with_separator(); + let question_count = ev.questions.len(); + let summary = Notification::user_input_request_summary(&ev.questions); + let title = match (question_count, summary.as_deref()) { + (1, Some(summary)) => summary.to_string(), + (1, None) => "Question requested".to_string(), + (count, _) => format!("{count} questions requested"), + }; + self.notify(Notification::PlanModePrompt { title }); + self.bottom_pane.push_user_input_request(ev); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + } + + pub(crate) fn handle_request_permissions_now(&mut self, ev: RequestPermissionsEvent) { + self.flush_answer_stream_with_separator(); + let request = ApprovalRequest::Permissions { + thread_id: self.thread_id.unwrap_or_default(), + thread_label: None, + call_id: ev.call_id, + reason: ev.reason, + permissions: ev.permissions, + }; + self.bottom_pane + .push_approval_request(request, &self.config.features); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + } +} diff --git a/codex-rs/tui/src/chatwidget/turn_runtime.rs b/codex-rs/tui/src/chatwidget/turn_runtime.rs new file mode 100644 index 0000000000..077c33606d --- /dev/null +++ b/codex-rs/tui/src/chatwidget/turn_runtime.rs @@ -0,0 +1,477 @@ +//! Agent turn lifecycle and runtime bookkeeping for `ChatWidget`. +//! +//! This module owns task start/completion state, runtime metrics, plan updates, +//! and final-message separator handling. + +use super::*; + +impl ChatWidget { + /// Synchronize the bottom-pane "task running" indicator with the current lifecycles. + /// + /// The bottom pane only has one running flag, but this module treats it as a derived state of + /// both the agent turn lifecycle and MCP startup lifecycle. + pub(super) fn update_task_running_state(&mut self) { + self.bottom_pane.set_task_running( + self.turn_lifecycle.agent_turn_running || self.mcp_startup_status.is_some(), + ); + self.refresh_plan_mode_nudge(); + self.refresh_status_surfaces(); + } + + pub(super) fn collect_runtime_metrics_delta(&mut self) { + if let Some(delta) = self.session_telemetry.runtime_metrics_summary() { + self.apply_runtime_metrics_delta(delta); + } + } + + pub(super) fn apply_runtime_metrics_delta(&mut self, delta: RuntimeMetricsSummary) { + let should_log_timing = has_websocket_timing_metrics(delta); + self.turn_runtime_metrics.merge(delta); + if should_log_timing { + self.log_websocket_timing_totals(delta); + } + } + + pub(super) fn log_websocket_timing_totals(&mut self, delta: RuntimeMetricsSummary) { + if let Some(label) = history_cell::runtime_metrics_label(delta.responses_api_summary()) { + self.add_plain_history_lines(vec![ + vec!["• ".dim(), format!("WebSocket timing: {label}").dark_gray()].into(), + ]); + } + } + + pub(super) fn refresh_runtime_metrics(&mut self) { + self.collect_runtime_metrics_delta(); + } + + // Raw reasoning uses the same flow as summarized reasoning + + pub(super) fn on_task_started(&mut self) { + self.input_queue.user_turn_pending_start = false; + self.turn_lifecycle.start(Instant::now()); + self.transcript.reset_turn_flags(); + self.adaptive_chunking.reset(); + self.plan_stream_controller = None; + self.turn_runtime_metrics = RuntimeMetricsSummary::default(); + self.session_telemetry.reset_runtime_metrics(); + self.bottom_pane.clear_quit_shortcut_hint(); + self.quit_shortcut_expires_at = None; + self.quit_shortcut_key = None; + self.update_task_running_state(); + self.status_state.retry_status_header = None; + if self.active_hook_cell.take().is_some() { + self.bump_active_cell_revision(); + } + self.status_state.pending_status_indicator_restore = false; + self.bottom_pane + .set_interrupt_hint_visible(/*visible*/ true); + self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Working; + self.set_status_header(String::from("Working")); + self.full_reasoning_buffer.clear(); + self.reasoning_buffer.clear(); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Running, + /*body*/ None, + ); + self.request_redraw(); + } + + pub(super) fn on_task_complete( + &mut self, + last_agent_message: Option, + duration_ms: Option, + from_replay: bool, + ) { + self.input_queue.submit_pending_steers_after_interrupt = false; + // Use `last_agent_message` from the turn-complete notification as the copy + // source only when no earlier item-level event (AgentMessageItem, plan + // commit, review output) already recorded markdown for this turn. This + // prevents the final summary from overwriting a more specific source. + let sanitized_last_agent_message = last_agent_message + .as_deref() + .map(|message| parse_assistant_markdown(message).visible_markdown); + if let Some(message) = sanitized_last_agent_message + .as_ref() + .filter(|message| !message.is_empty()) + && !self.transcript.saw_copy_source_this_turn + { + self.record_agent_markdown(message); + } + // For desktop notifications: prefer the notification payload, fall back to + // the item-level copy source if present, otherwise send an empty string. + let notification_response = sanitized_last_agent_message + .as_ref() + .filter(|message| !message.is_empty()) + .cloned() + .or_else(|| { + if self.transcript.saw_copy_source_this_turn { + self.transcript.last_agent_markdown.clone() + } else { + None + } + }) + .unwrap_or_default(); + self.transcript.saw_copy_source_this_turn = false; + // If a stream is currently active, finalize it. + self.flush_answer_stream_with_separator(); + if let Some(mut controller) = self.plan_stream_controller.take() { + let had_live_tail = controller.has_live_tail(); + self.clear_active_stream_tail(); + let (cell, source) = controller.finalize(); + if !had_live_tail && let Some(cell) = cell { + self.add_boxed_history(cell); + } + if let Some(source) = source { + self.app_event_tx + .send(AppEvent::ConsolidateProposedPlan(source)); + } + } + self.flush_unified_exec_wait_streak(); + if !from_replay { + self.collect_runtime_metrics_delta(); + let runtime_metrics = + (!self.turn_runtime_metrics.is_empty()).then_some(self.turn_runtime_metrics); + let show_work_separator = self.transcript.had_work_activity + && (self.transcript.needs_final_message_separator || runtime_metrics.is_some()); + if show_work_separator || runtime_metrics.is_some() { + let elapsed_seconds = if show_work_separator { + duration_ms + .and_then(|duration_ms| u64::try_from(duration_ms).ok()) + .map(|duration_ms| duration_ms / 1_000) + .or_else(|| { + self.bottom_pane + .status_widget() + .map(crate::status_indicator_widget::StatusIndicatorWidget::elapsed_seconds) + }) + } else { + None + }; + self.add_to_history(history_cell::FinalMessageSeparator::new( + elapsed_seconds, + runtime_metrics, + )); + } + self.turn_runtime_metrics = RuntimeMetricsSummary::default(); + self.transcript.needs_final_message_separator = false; + self.transcript.had_work_activity = false; + self.request_status_line_branch_refresh(); + self.request_status_line_git_summary_refresh(); + } + // Mark task stopped and request redraw now that all content is in history. + self.status_state.pending_status_indicator_restore = false; + self.input_queue.user_turn_pending_start = false; + self.turn_lifecycle.finish(); + self.update_task_running_state(); + self.running_commands.clear(); + self.suppressed_exec_calls.clear(); + self.last_unified_wait = None; + self.unified_exec_wait_streak = None; + if !from_replay { + let body = Notification::agent_turn_preview(¬ification_response); + self.set_ambient_pet_notification(crate::pets::PetNotificationKind::Review, body); + } + self.request_redraw(); + + let had_pending_steers = !self.input_queue.pending_steers.is_empty(); + self.refresh_pending_input_preview(); + + if !from_replay && !self.has_queued_follow_up_messages() && !had_pending_steers { + self.maybe_prompt_plan_implementation(); + } + // Keep this flag for replayed completion events so a subsequent live TurnComplete can + // still show the prompt once after thread switch replay. + if !from_replay { + self.transcript.saw_plan_item_this_turn = false; + } + // If there is a queued user message, send exactly one now to begin the next turn. + let follow_up_started = self.maybe_send_next_queued_input(); + let active_goal_continuing = self + .current_goal_status + .as_ref() + .is_some_and(GoalStatusState::is_active); + // Emit a notification when the agent is truly waiting for the user. + // Queued follow-up input and active goal continuation both start the + // next turn immediately, so notifying at that boundary would feel like + // a false "needs attention". + if !follow_up_started && !active_goal_continuing { + self.notify(Notification::AgentTurnComplete { + response: notification_response, + }); + } + + self.maybe_show_pending_rate_limit_prompt(); + } + + pub(super) fn maybe_prompt_plan_implementation(&mut self) { + if !self.collaboration_modes_enabled() { + return; + } + if self.has_queued_follow_up_messages() { + return; + } + if self.active_mode_kind() != ModeKind::Plan { + return; + } + if !self.transcript.saw_plan_item_this_turn { + return; + } + if !self.bottom_pane.no_modal_or_popup_active() { + return; + } + + if matches!( + self.rate_limit_switch_prompt, + RateLimitSwitchPromptState::Pending + ) { + return; + } + + self.open_plan_implementation_prompt(); + } + + pub(super) fn open_plan_implementation_prompt(&mut self) { + let default_mask = collaboration_modes::default_mode_mask(self.model_catalog.as_ref()); + let context_usage_label = self.plan_implementation_context_usage_label(); + + self.bottom_pane + .show_selection_view(plan_implementation::selection_view_params( + default_mask, + self.transcript.latest_proposed_plan_markdown.as_deref(), + context_usage_label.as_deref(), + )); + self.notify(Notification::PlanModePrompt { + title: PLAN_IMPLEMENTATION_TITLE.to_string(), + }); + } + + /// Returns a context-used label for the plan implementation prompt. + /// + /// The footer reports context remaining because it is ambient status, but + /// this prompt is asking whether to discard prior conversation state before + /// implementing a plan. Reporting used context makes the cleanup tradeoff + /// explicit. A fully fresh or unknown context window returns no label so + /// the clear-context option does not imply urgency without evidence. + pub(super) fn plan_implementation_context_usage_label(&self) -> Option { + let info = self.token_info.as_ref()?; + let percent = self.context_remaining_percent(info); + + let used_tokens = self.context_used_tokens(info, percent.is_some()); + if let Some(percent) = percent { + let used_percent = 100 - percent.clamp(0, 100); + if used_percent <= 0 { + return None; + } + return Some(format!("{used_percent}% used")); + } + + if let Some(tokens) = used_tokens + && tokens > 0 + { + return Some(format!("{} used", format_tokens_compact(tokens))); + } + + None + } + + pub(super) fn has_queued_follow_up_messages(&self) -> bool { + self.input_queue.has_queued_follow_up_messages() + } + + pub(super) fn handle_app_server_steer_rejected_error( + &mut self, + codex_error_info: &AppServerCodexErrorInfo, + ) -> bool { + matches!( + codex_error_info, + AppServerCodexErrorInfo::ActiveTurnNotSteerable { .. } + ) && self.enqueue_rejected_steer() + } + + /// Finalize any active exec as failed and stop/clear agent-turn UI state. + /// + /// This does not clear MCP startup tracking, because MCP startup can overlap with turn cleanup + /// and should continue to drive the bottom-pane running indicator while it is in progress. + pub(super) fn finalize_turn(&mut self) { + // Drop preview-only stream tail content on any termination path before + // failed-cell finalization, so transient tail cells are never persisted. + self.clear_active_stream_tail(); + // Ensure any spinner is replaced by a red ✗ and flushed into history. + self.finalize_active_cell_as_failed(); + // Turn-scoped hook rows are transient live state; once the turn is over, + // do not leave an orphaned running row behind if no matching completion + // event arrived before cancellation. + if self.active_hook_cell.take().is_some() { + self.bump_active_cell_revision(); + } + // Reset running state and clear streaming buffers. + self.input_queue.user_turn_pending_start = false; + self.turn_lifecycle.finish(); + self.update_task_running_state(); + self.running_commands.clear(); + self.suppressed_exec_calls.clear(); + self.last_unified_wait = None; + self.unified_exec_wait_streak = None; + self.adaptive_chunking.reset(); + self.stream_controller = None; + self.plan_stream_controller = None; + self.status_state.pending_status_indicator_restore = false; + self.request_status_line_branch_refresh(); + self.request_status_line_git_summary_refresh(); + self.maybe_show_pending_rate_limit_prompt(); + } + + pub(super) fn on_server_overloaded_error(&mut self, message: String) { + self.input_queue.submit_pending_steers_after_interrupt = false; + self.finalize_turn(); + + let message = if message.trim().is_empty() { + "Codex is currently experiencing high load.".to_string() + } else { + message + }; + + self.add_to_history(history_cell::new_warning_event(message)); + self.request_redraw(); + self.maybe_send_next_queued_input(); + } + + pub(super) fn on_error(&mut self, message: String) { + self.input_queue.submit_pending_steers_after_interrupt = false; + self.finalize_turn(); + self.add_to_history(history_cell::new_error_event(message)); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Failed, + /*body*/ None, + ); + self.request_redraw(); + + // After an error ends the turn, try sending the next queued input. + self.maybe_send_next_queued_input(); + } + + pub(super) fn on_cyber_policy_error(&mut self) { + self.input_queue.submit_pending_steers_after_interrupt = false; + self.finalize_turn(); + self.add_to_history(history_cell::new_cyber_policy_error_event()); + self.request_redraw(); + + // After an error ends the turn, try sending the next queued input. + self.maybe_send_next_queued_input(); + } + + pub(super) fn on_rate_limit_error(&mut self, error_kind: RateLimitErrorKind, message: String) { + let rate_limit_reached_type = self.codex_rate_limit_reached_type.map(|kind| { + if matches!(error_kind, RateLimitErrorKind::UsageLimit) { + match kind { + RateLimitReachedType::WorkspaceOwnerCreditsDepleted => { + RateLimitReachedType::WorkspaceOwnerUsageLimitReached + } + RateLimitReachedType::WorkspaceMemberCreditsDepleted => { + RateLimitReachedType::WorkspaceMemberUsageLimitReached + } + other => other, + } + } else { + kind + } + }); + self.codex_rate_limit_reached_type = rate_limit_reached_type; + + match rate_limit_reached_type { + Some(RateLimitReachedType::WorkspaceOwnerCreditsDepleted) => { + self.on_error( + "You're out of credits. Your workspace is out of credits. Add credits to continue using Codex." + .to_string(), + ); + } + Some(RateLimitReachedType::WorkspaceOwnerUsageLimitReached) => { + self.on_error( + "Usage limit reached. You've reached your usage limit. Increase your limits to continue using codex." + .to_string(), + ); + } + Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted) => { + self.on_error(message); + self.open_workspace_owner_nudge_prompt(AddCreditsNudgeCreditType::Credits); + } + Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached) => { + self.on_error(message); + self.open_workspace_owner_nudge_prompt(AddCreditsNudgeCreditType::UsageLimit); + } + Some(RateLimitReachedType::RateLimitReached) | None => { + self.on_error(message); + } + } + } + + pub(super) fn handle_non_retry_error( + &mut self, + message: String, + codex_error_info: Option, + ) { + if codex_error_info + .as_ref() + .is_some_and(|info| self.handle_app_server_steer_rejected_error(info)) + { + } else if codex_error_info + .as_ref() + .is_some_and(is_app_server_cyber_policy_error) + { + self.on_cyber_policy_error(); + } else if let Some(info) = codex_error_info + .as_ref() + .and_then(app_server_rate_limit_error_kind) + { + match info { + RateLimitErrorKind::ServerOverloaded => self.on_server_overloaded_error(message), + RateLimitErrorKind::UsageLimit | RateLimitErrorKind::Generic => { + self.on_rate_limit_error(info, message) + } + } + } else { + self.on_error(message); + } + } + + pub(super) fn on_warning(&mut self, message: impl Into) { + let message = message.into(); + if !self.warning_display_state.should_display(&message) { + return; + } + self.add_to_history(history_cell::new_warning_event(message)); + self.request_redraw(); + } + + pub(super) fn on_app_server_model_verification( + &mut self, + verifications: &[AppServerModelVerification], + ) { + if verifications.contains(&AppServerModelVerification::TrustedAccessForCyber) { + self.on_warning(TRUSTED_ACCESS_FOR_CYBER_VERIFICATION_WARNING); + } + } + + pub(super) fn on_plan_update(&mut self, update: UpdatePlanArgs) { + self.transcript.saw_plan_update_this_turn = true; + let total = update.plan.len(); + let completed = update + .plan + .iter() + .filter(|item| match &item.status { + StepStatus::Completed => true, + StepStatus::Pending | StepStatus::InProgress => false, + }) + .count(); + self.transcript.last_plan_progress = (total > 0).then_some((completed, total)); + self.refresh_status_surfaces(); + self.add_to_history(history_cell::new_plan_update(update)); + } + + pub(super) fn interrupted_turn_message(&self, reason: TurnAbortReason) -> String { + if reason == TurnAbortReason::BudgetLimited { + return "Goal budget reached - the turn was stopped.".to_string(); + } + + "Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.".to_string() + } +}