diff --git a/FORK.md b/FORK.md index 131b5606a374..9a055821548a 100644 --- a/FORK.md +++ b/FORK.md @@ -84,6 +84,9 @@ passing on its own is enough: a cherry-pick does not move the base. | — | `wire_api = "chat"`: Chat Completions client restored for providers whose Responses path drops tool calls (grok via theclawbay/LiteLLM, WI-1139). New files only, plus one dispatch arm: `core/src/chat_request.rs` (request conversion; namespaced tools flattened to `ns__name`, freeform tools such as apply_patch exposed as a function taking one `input` string, calls restored by `ChatToolMap`), `codex-api/src/{endpoint,sse}/chat.rs` (client and SSE parser, fixture tests in `sse/chat_tests.rs`). Reasoning, web search and tool search are not sent over chat. Branch `fork/wi-1286-chat-wire`. | fork-only; upstream removed the chat client | | — | Headless MCP startup (issue #26, WI-1514): `codex exec` defaults `mcp_optional_startup_grace_ms` to 0 unless set, so every enabled server's startup is awaited (each bounded by its `startup_timeout_sec`) before the first request; a failed or timed-out server is printed as a warning and the run continues. Tool dispatch resolves un-namespaced `mcp____` names and bare names unique across MCP servers, and answers a call to a server still handshaking with "MCP server `x` is still starting" instead of "unsupported call". `exec/src/lib.rs`, `core/src/tools/registry.rs`, `codex-mcp` `pending_startup_servers`. Branch `fix/issue-26-mcp-startup`. | fork-only | | — | Auto-compaction loop guard (WI-2832): after a context-limit compaction (pre-turn or mid-turn), if the first request's prompt alone is still at or over `model_auto_compact_token_limit` (body after prefix for that scope) or the usable window, the turn ends with a warning and a `ContextWindowExceeded` error instead of compacting again. Before this, a fixed prefix (tool specs) over the limit looped compaction -> one tool call -> compaction (235 compactions in one turn). `core/src/session/turn.rs`; tests `turn_tests.rs` `prompt_over_limit_*`, `suite::compact::auto_compact_stops_when_compaction_cannot_get_below_limit`. Branch `wi-2832-compaction-thrash-guard`. | fork-only; upstream has the same loop | +| — | Auto-review audit trail (issue #34, WI-4410): `codex-rollout` `policy.rs` now persists terminal `GuardianAssessment` events (approved, denied, timed out, aborted) in the rollout; the in-progress marker stays transient. Before, no verdict was recorded in the parent rollout. Pinned by `policy_tests.rs::guardian_assessment_verdicts_are_persisted_but_in_progress_is_not`. Findings: the reviewer runs on the parent's own model provider (`guardian_session_inherits_parent_http_fallback` has a custom-provider case; not exercised against a live LiteLLM here). Under `approvals_reviewer=auto_review` an action is decided by the reviewer, not escalated as a user prompt: a denial reaches the model as a rejection and the client as a `GuardianAssessment` (Denied) event, and only `approvals_reviewer=user` raises `ExecApprovalRequest`. Pinned end to end by `core/tests/suite/auto_review.rs` `auto_review_denial_surfaces_as_guardian_assessment_and_is_persisted`: the client sees `GuardianAssessment` `InProgress` then `Denied` with no `ExecApprovalRequest`, and the `Denied` verdict is in the rollout. Vogt's detector must watch `GuardianAssessment` `Denied` (Vogt-side follow-up; not a fork change). Branch `fix/issue-34-auto-review`. | fork-only | +| — | Per-session provider (issue #39, WI-4409): no code change. `-c model_provider= -c model_context_window= -c model_auto_compact_token_limit=` already override the global `config.toml` for one session; pinned by `cli_overrides_select_session_provider_and_context_limits` in `core/src/config/config_loader_tests.rs`. Branch `fix/issue-39-session-provider`. | fork-only (test + note) | +| — | TUI mouse (issues #43, #44, WI-4408): wheel events scroll the transcript wherever the pointer is on screen (`tui/src/transcript_view/input.rs`; selection still respects the rect), and `tui.mouse_capture = false` (or `-c tui.mouse_capture=false`, or env `CODEX_TUI_MOUSE_CAPTURE=0`; env wins) stops the TUI requesting mouse reporting in the alternate screen so browser/mobile/multi-viewer front ends keep text selection while the fullscreen transcript stays. For append-only output use `tui.alternate_screen = "never"` / `--no-alt-screen`. `config/src/types.rs`, `tui/src/tui.rs` `MouseCapture::captures_mouse`. Branch `fix/wi-tui-43-44`. | fork-only | ## External adapters diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 177faa086cf8..9d81cd0c5f79 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -953,6 +953,11 @@ pub struct Tui { #[schemars(schema_with = "crate::tui_mouse_scroll::schema")] pub mouse_scroll_speed: Option, + /// Let the TUI capture mouse events in the alternate screen. Defaults to `true`. + /// Set `false` for browser, mobile or multi-viewer terminals whose front end owns text + /// selection. Overridden by the `CODEX_TUI_MOUSE_CAPTURE` environment variable. + pub mouse_capture: Option, + /// Copy selected transcript, footer, or composer text when the mouse button is released. /// Defaults to `auto`: enabled except in direct terminals known to forward their native /// copy shortcut (Ghostty 1.2+, Kitty on macOS, Windows Terminal, and VS Code on Windows). diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 16100ee79170..971b9b27b058 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -5537,6 +5537,10 @@ "default": {}, "description": "Startup tooltip availability NUX state persisted by the TUI." }, + "mouse_capture": { + "description": "Let the TUI capture mouse events in the alternate screen. Defaults to `true`. Set `false` for browser, mobile or multi-viewer terminals whose front end owns text selection. Overridden by the `CODEX_TUI_MOUSE_CAPTURE` environment variable.", + "type": "boolean" + }, "mouse_scroll_speed": { "default": null, "description": "Mouse wheel speed multiplier for transcript scrolling, based on one row per event. Defaults to `1.0`. Positive fractional values slow scrolling; values above `1.0` speed it up.", diff --git a/codex-rs/core/src/config/config_loader_tests.rs b/codex-rs/core/src/config/config_loader_tests.rs index 23612f7dc938..9bfdee962504 100644 --- a/codex-rs/core/src/config/config_loader_tests.rs +++ b/codex-rs/core/src/config/config_loader_tests.rs @@ -4940,3 +4940,54 @@ async fn async_compaction_config() { assert_eq!(actual, expected, "{settings}"); } } + +/// Fork issue #39: a session picks its provider and context limits with `-c` +/// overrides, without touching the global default in config.toml. +#[tokio::test] +async fn cli_overrides_select_session_provider_and_context_limits() { + let tmp = tempdir().expect("tempdir"); + std::fs::write( + tmp.path().join(CONFIG_TOML_FILE), + r#" +model_provider = "global" +model_context_window = 850000 +model_auto_compact_token_limit = 800000 + +[model_providers.global] +name = "global" +base_url = "http://localhost:1/v1" + +[model_providers.session] +name = "session" +base_url = "http://localhost:2/v1" +"#, + ) + .expect("write config"); + + let config = ConfigBuilder::default() + .codex_home(tmp.path().to_path_buf()) + .fallback_cwd(Some(tmp.path().to_path_buf())) + .loader_overrides(LoaderOverrides::without_managed_config_for_tests()) + .cli_overrides(vec![ + ( + "model_provider".to_string(), + TomlValue::String("session".to_string()), + ), + ( + "model_context_window".to_string(), + TomlValue::Integer(128000), + ), + ( + "model_auto_compact_token_limit".to_string(), + TomlValue::Integer(100000), + ), + ]) + .build() + .await + .expect("config with provider override"); + + assert_eq!(config.model_provider_id, "session"); + assert_eq!(config.model_provider.name, "session"); + assert_eq!(config.model_context_window, Some(128000)); + assert_eq!(config.model_auto_compact_token_limit, Some(100000)); +} diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 0e625bb15668..5056c4b117ba 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -1409,6 +1409,7 @@ fn config_toml_deserializes_model_availability_nux() { collapse_turn_details: false, sidebar_width_percent: None, mouse_scroll_speed: None, + mouse_capture: None, copy_on_select: Default::default(), copy_on_select_clear_selection: false, right_click_paste: Default::default(), @@ -4778,6 +4779,7 @@ fn tui_config_missing_notifications_field_defaults_to_enabled() { collapse_turn_details: false, sidebar_width_percent: None, mouse_scroll_speed: None, + mouse_capture: None, copy_on_select: Default::default(), copy_on_select_clear_selection: false, right_click_paste: Default::default(), diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 0a0446062017..ee3dc4d9a8b6 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -857,6 +857,9 @@ pub struct Config { /// Mouse wheel speed multiplier for transcript scrolling; defaults to one row per event. pub tui_mouse_scroll_speed: Option, + /// Whether the TUI may capture the mouse in the alternate screen (`tui.mouse_capture`). + pub tui_mouse_capture: Option, + /// Override the terminal default for copying transcript, footer, and composer selections. pub tui_copy_on_select: codex_config::types::CopyOnSelect, @@ -4896,6 +4899,7 @@ impl Config { .is_none_or(|tui| tui.fullscreen_transcript), tui_sidebar_width_percent: cfg.tui.as_ref().and_then(|tui| tui.sidebar_width_percent), tui_mouse_scroll_speed: cfg.tui.as_ref().and_then(|tui| tui.mouse_scroll_speed), + tui_mouse_capture: cfg.tui.as_ref().and_then(|tui| tui.mouse_capture), tui_copy_on_select: cfg .tui .as_ref() diff --git a/codex-rs/core/tests/suite/auto_review.rs b/codex-rs/core/tests/suite/auto_review.rs index 470a81579b18..62b7b013c0f2 100644 --- a/codex-rs/core/tests/suite/auto_review.rs +++ b/codex-rs/core/tests/suite/auto_review.rs @@ -12,6 +12,8 @@ use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; use codex_features::Feature; use codex_login::CodexAuth; +use codex_model_provider_info::ModelProviderInfo; +use codex_model_provider_info::WireApi; use codex_models_manager::manager::RefreshStrategy; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::ReasoningSummary; @@ -33,6 +35,8 @@ use codex_protocol::request_permissions::PermissionGrantScope; use codex_protocol::request_permissions::RequestPermissionProfile; use codex_protocol::request_permissions::RequestPermissionsResponse; use codex_protocol::user_input::UserInput; +use codex_rollout::RolloutItem; +use codex_rollout::RolloutRecorder; use core_test_support::TempDirExt; use core_test_support::responses::ev_apply_patch_custom_tool_call; use core_test_support::responses::ev_assistant_message; @@ -298,6 +302,276 @@ async fn require_escalated_bypasses_extension_approval_and_runs_guardian() -> Re Ok(()) } +/// Fork issue #34 (WI-4410): under `approvals_reviewer=auto_review` a blocked escalation is +/// decided by the reviewer and never raised as a user approval prompt. The client-visible shape +/// Vogt must watch is a `GuardianAssessment` event: `InProgress`, then `Denied`. The terminal +/// verdict is also persisted in the rollout, so the decision is auditable after the turn. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn auto_review_denial_surfaces_as_guardian_assessment_and_is_persisted() -> Result<()> { + skip_if_no_network!(Ok(())); + skip_if_wine_exec!(Ok(()), "exec_command requires host-native paths"); + + let server = MockServer::start().await; + let call_id = "auto-review-denied-command"; + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-parent-1"), + ev_function_call( + call_id, + "exec_command", + &json!({ + "cmd": "pwd", + "sandbox_permissions": "require_escalated", + "justification": "run outside the sandbox after a blocked attempt", + }) + .to_string(), + ), + ev_completed("resp-parent-1"), + ]), + sse(vec![ + ev_response_created("resp-guardian"), + ev_assistant_message( + "msg-guardian", + &json!({ + "risk_level": "high", + "user_authorization": "low", + "outcome": "deny", + "rationale": "The unsandboxed command is not authorized.", + }) + .to_string(), + ), + ev_completed("resp-guardian"), + ]), + sse(vec![ + ev_response_created("resp-parent-2"), + ev_assistant_message("msg-parent", "done"), + ev_completed("resp-parent-2"), + ]), + ], + ) + .await; + + let mut extensions = ExtensionRegistryBuilder::new(); + extensions.approval_review_contributor(Arc::new(EscalationApprovingReviewContributor)); + let mut builder = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_config(|config| { + config.approvals_reviewer = ApprovalsReviewer::AutoReview; + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config + .permissions + .set_permission_profile(PermissionProfile::read_only()) + .expect("set read-only permission profile"); + }); + let test = builder.build_with_auto_env(&server).await?; + test.codex + .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { + text: "retry the blocked command outside the sandbox".into(), + text_elements: Vec::new(), + }])) + .await?; + + let mut assessments = Vec::new(); + loop { + match wait_for_event(&test.codex, |_| true).await { + EventMsg::ExecApprovalRequest(event) => { + panic!("auto_review must not raise a user approval prompt: {event:?}") + } + EventMsg::GuardianAssessment(event) => assessments.push(event), + EventMsg::TurnComplete(_) => break, + _ => {} + } + } + + // The client watches the in-progress review, then the terminal Denied verdict. + let statuses = assessments + .iter() + .map(|event| event.status) + .collect::>(); + assert_eq!( + statuses, + vec![ + codex_protocol::protocol::GuardianAssessmentStatus::InProgress, + codex_protocol::protocol::GuardianAssessmentStatus::Denied, + ] + ); + assert_eq!(assessments[0].id, assessments[1].id); + // The reviewed action is the shell-wrapped command, so match the command text, not equality. + let reviewed_action = format!("{:?}", assessments[1].action); + assert!(reviewed_action.contains("pwd"), "{reviewed_action}"); + assert!( + responses + .function_call_output_text(call_id) + .context("expected exec_command output")? + .contains("not authorized") + ); + + // The terminal verdict is durable; the in-progress marker is not (fork #34). + test.codex.shutdown_and_wait().await?; + let rollout_path = test.codex.rollout_path().context("local rollout path")?; + let (items, _, parse_errors) = RolloutRecorder::load_rollout_items(&rollout_path).await?; + let persisted = items + .iter() + .filter_map(|item| match item { + RolloutItem::EventMsg(EventMsg::GuardianAssessment(event)) => Some(event.status), + _ => None, + }) + .collect::>(); + assert_eq!( + (parse_errors, persisted), + ( + 0, + vec![codex_protocol::protocol::GuardianAssessmentStatus::Denied] + ) + ); + + Ok(()) +} + +/// Fork issue #34 item (1): `approvals_reviewer=auto_review` works with a custom, non-OpenAI +/// model provider. The default `openai` provider points at `default_server`, which must receive +/// nothing, while the custom `litellm` provider serves the parent turn and the Guardian review. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn auto_review_routes_reviewer_to_custom_provider() -> Result<()> { + skip_if_no_network!(Ok(())); + skip_if_wine_exec!(Ok(()), "exec_command requires host-native paths"); + + let default_server = MockServer::start().await; + let custom_server = MockServer::start().await; + let call_id = "custom-provider-denied-command"; + let responses = mount_sse_sequence( + &custom_server, + vec![ + sse(vec![ + ev_response_created("resp-parent-1"), + ev_function_call( + call_id, + "exec_command", + &json!({ + "cmd": "pwd", + "sandbox_permissions": "require_escalated", + "justification": "run outside the sandbox after a blocked attempt", + }) + .to_string(), + ), + ev_completed("resp-parent-1"), + ]), + sse(vec![ + ev_response_created("resp-guardian"), + ev_assistant_message( + "msg-guardian", + &json!({ + "risk_level": "high", + "user_authorization": "low", + "outcome": "deny", + "rationale": "The unsandboxed command is not authorized.", + }) + .to_string(), + ), + ev_completed("resp-guardian"), + ]), + sse(vec![ + ev_response_created("resp-parent-2"), + ev_assistant_message("msg-parent", "done"), + ev_completed("resp-parent-2"), + ]), + ], + ) + .await; + + let custom_base_url = format!("{}/v1", custom_server.uri()); + let mut extensions = ExtensionRegistryBuilder::new(); + extensions.approval_review_contributor(Arc::new(EscalationApprovingReviewContributor)); + let mut builder = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_config(move |config| { + config.model_provider_id = "litellm".to_string(); + config.model_provider = ModelProviderInfo { + name: "LiteLLM".into(), + base_url: Some(custom_base_url), + model_catalog_url: None, + env_key: None, + env_key_instructions: None, + experimental_bearer_token: None, + auth: None, + gateway_oauth: None, + aws: None, + wire_api: WireApi::Responses, + query_params: None, + http_headers: None, + env_http_headers: None, + request_max_retries: Some(0), + stream_max_retries: Some(0), + stream_idle_timeout_ms: Some(5_000), + websocket_connect_timeout_ms: None, + requires_openai_auth: false, + supports_websockets: false, + supports_standalone_web_search: false, + capabilities: None, + project_id: None, + location: None, + credential_file: None, + include_internal_metadata: false, + }; + config.approvals_reviewer = ApprovalsReviewer::AutoReview; + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config + .permissions + .set_permission_profile(PermissionProfile::read_only()) + .expect("set read-only permission profile"); + }); + let test = builder.build_with_auto_env(&default_server).await?; + test.codex + .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { + text: "retry the blocked command outside the sandbox".into(), + text_elements: Vec::new(), + }])) + .await?; + + loop { + match wait_for_event(&test.codex, |_| true).await { + EventMsg::ExecApprovalRequest(event) => { + panic!("auto_review must not raise a user approval prompt: {event:?}") + } + EventMsg::TurnComplete(_) => break, + _ => {} + } + } + + // Nothing reached the default provider's server. + let default_responses = default_server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|request| request.url.path().ends_with("/responses")) + .count(); + assert_eq!(default_responses, 0); + + // The parent turn and the Guardian review both went to the custom provider. + let requests = responses.requests(); + assert_eq!(requests.len(), 3); + let guardian_request = requests + .iter() + .find(|request| { + request.body_json()["client_metadata"]["x-openai-subagent"].as_str() == Some("guardian") + }) + .context("expected Guardian review on the custom provider")?; + assert!(guardian_request.body_contains_text("run outside the sandbox")); + + // The reviewer's Deny verdict is applied to the command. + assert!( + responses + .function_call_output_text(call_id) + .context("expected exec_command output")? + .contains("not authorized") + ); + + Ok(()) +} + #[derive(Clone, Copy)] enum GuardianV2DisableSource { Config, diff --git a/codex-rs/rollout/src/policy.rs b/codex-rs/rollout/src/policy.rs index e62c42320456..f40e2dc6aa7d 100644 --- a/codex-rs/rollout/src/policy.rs +++ b/codex-rs/rollout/src/policy.rs @@ -158,10 +158,16 @@ fn persisted_event_msg( && event.kind != SubAgentActivityKind::Completed) .then_some(Cow::Borrowed(ev)), + // Auto-review verdicts are the audit trail of what was auto-approved or + // denied (fork issue #34). Only the terminal status is durable; the + // in-progress marker is transient. + EventMsg::GuardianAssessment(event) => (event.status + != codex_protocol::protocol::GuardianAssessmentStatus::InProgress) + .then_some(Cow::Borrowed(ev)), + // Transient, non-durable events. EventMsg::Error(_) | EventMsg::ThreadQueueChanged(_) - | EventMsg::GuardianAssessment(_) | EventMsg::ExecCommandEnd(_) | EventMsg::ViewImageToolCall(_) | EventMsg::CollabAgentSpawnEnd(_) diff --git a/codex-rs/rollout/src/policy_tests.rs b/codex-rs/rollout/src/policy_tests.rs index fee292f15e13..a63408fc987d 100644 --- a/codex-rs/rollout/src/policy_tests.rs +++ b/codex-rs/rollout/src/policy_tests.rs @@ -118,3 +118,49 @@ fn inline_image_generation_result_is_preserved() { }) ); } + +fn guardian_assessment(status: codex_protocol::protocol::GuardianAssessmentStatus) -> EventMsg { + EventMsg::GuardianAssessment(codex_protocol::protocol::GuardianAssessmentEvent { + review_reason: None, + model_context: None, + id: "review-1".into(), + target_item_id: None, + plugin_id: None, + script_path: None, + turn_id: "turn-1".into(), + started_at_ms: 1, + completed_at_ms: None, + status, + risk_level: None, + user_authorization: None, + rationale: None, + decision_source: None, + action: codex_protocol::protocol::GuardianAssessmentAction::Command { + source: codex_protocol::protocol::GuardianCommandSource::Shell, + command: "true".into(), + cwd: codex_utils_absolute_path::AbsolutePathBuf::current_dir() + .expect("current dir") + .into(), + }, + }) +} + +/// Fork issue #34: auto-review verdicts must be auditable from the rollout. +#[test] +fn guardian_assessment_verdicts_are_persisted_but_in_progress_is_not() { + use codex_protocol::protocol::GuardianAssessmentStatus as S; + for status in [S::Approved, S::Denied, S::TimedOut, S::Aborted] { + let event = guardian_assessment(status); + assert!( + persisted_event_msg(&event, ThreadHistoryMode::Legacy).is_some(), + "{status:?} must be persisted" + ); + } + assert!( + persisted_event_msg( + &guardian_assessment(S::InProgress), + ThreadHistoryMode::Legacy + ) + .is_none() + ); +} diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs index 63e9c7c9fa11..597d5a40e410 100644 --- a/codex-rs/thread-manager-sample/src/main.rs +++ b/codex-rs/thread-manager-sample/src/main.rs @@ -305,6 +305,7 @@ async fn new_config( tui_collapse_turn_details: false, tui_sidebar_width_percent: None, tui_mouse_scroll_speed: None, + tui_mouse_capture: None, tui_copy_on_select: Default::default(), tui_copy_on_select_clear_selection: false, tui_right_click_paste: Default::default(), diff --git a/codex-rs/tui/src/app/owned_transcript_input_tests.rs b/codex-rs/tui/src/app/owned_transcript_input_tests.rs index e622c90c9b1a..479e6b36ef0f 100644 --- a/codex-rs/tui/src/app/owned_transcript_input_tests.rs +++ b/codex-rs/tui/src/app/owned_transcript_input_tests.rs @@ -342,7 +342,10 @@ async fn plan_menu_allows_transcript_selection_and_copy_but_respects_popup_bound } } let bottom = app.render_owned_transcript(&mut tui, size)?; - let before = screen(&tui); + let latest = screen(&tui); + // Wheel scrolls the transcript from anywhere on screen, including over the plan popup + // (#43); the popup still owns clicks and drags, checked below. + let mut scrolled = false; for (kind, column, row) in [ (MouseEventKind::ScrollUp, 1, bottom.y), (MouseEventKind::ScrollDown, 1, bottom.y), @@ -351,9 +354,17 @@ async fn plan_menu_allows_transcript_selection_and_copy_but_respects_popup_bound app.handle_tui_event(&mut tui, &mut server, pointer_event(kind, column, row)) .await?; app.render_owned_transcript(&mut tui, size)?; - assert_eq!(screen(&tui), before); + scrolled |= screen(&tui) != latest; assert!(!app.transcript_view.has_active_interaction()); } + assert!( + scrolled, + "wheel over the plan popup should scroll the transcript" + ); + app.transcript_view.jump_to_latest(); + app.render_owned_transcript(&mut tui, size)?; + let before = screen(&tui); + assert_eq!(before, latest); let (plan_row, plan_column) = before .lines() .enumerate() diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index ac3dc15ef262..a222ded5cb8c 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -2169,6 +2169,7 @@ async fn run_ratatui_app( ); } + crate::tui::configure_mouse_capture(config.tui_mouse_capture); // Cloud configuration and session selection can change screen policy after first paint. let use_alt_screen = determine_alt_screen_mode( cli.no_alt_screen, diff --git a/codex-rs/tui/src/local_settings.rs b/codex-rs/tui/src/local_settings.rs index 0d8477b2713b..38c5a34b2d1f 100644 --- a/codex-rs/tui/src/local_settings.rs +++ b/codex-rs/tui/src/local_settings.rs @@ -80,6 +80,7 @@ impl LocalSettings { collapse_turn_details: config.tui_collapse_turn_details, sidebar_width_percent: config.tui_sidebar_width_percent, mouse_scroll_speed: config.tui_mouse_scroll_speed, + mouse_capture: config.tui_mouse_capture, copy_on_select: config.tui_copy_on_select, copy_on_select_clear_selection: config.tui_copy_on_select_clear_selection, right_click_paste: config.tui_right_click_paste, diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index 59183c42acf7..59269eacb941 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -337,7 +337,13 @@ impl TranscriptView { .selection .as_ref() .is_some_and(|selection| selection.dragging); - if !inside && !dragging { + // Wheel scrolling applies anywhere on screen: front ends that synthesize wheel reports + // (browser or mobile terminals) cannot be relied on to aim them at the transcript. + let wheel = matches!( + event.kind, + MouseEventKind::ScrollUp | MouseEventKind::ScrollDown + ); + if !inside && !dragging && !wheel { return None; } // Wheel navigation supersedes the last drag position. A real drag event can resume it. @@ -364,8 +370,14 @@ impl TranscriptView { if rounded != 0.0 && (self.pending_mouse_scroll - rounded).abs() < 1e-9 { self.pending_mouse_scroll = rounded; } - let rows = self.pending_mouse_scroll as isize; + let mut rows = self.pending_mouse_scroll as isize; self.pending_mouse_scroll = self.pending_mouse_scroll.fract(); + // Any upward wheel movement leaves the bottom, even before a whole row has + // accumulated, so streaming output cannot re-pin a reader who began scrolling up. + if direction < 0.0 && rows == 0 && self.is_following() { + rows = -1; + self.pending_mouse_scroll += 1.0; + } if rows != 0 { self.scroll(cells, rows); } diff --git a/codex-rs/tui/src/transcript_view/input_tests.rs b/codex-rs/tui/src/transcript_view/input_tests.rs index 802f45d96285..fcf30378dcf7 100644 --- a/codex-rs/tui/src/transcript_view/input_tests.rs +++ b/codex-rs/tui/src/transcript_view/input_tests.rs @@ -92,8 +92,8 @@ fn decimal_mouse_scroll_speeds_preserve_whole_rows() { } #[test] -fn fractional_mouse_scroll_does_not_pause_following_until_a_row_moves() { - let (mut view, cells) = transcript( +fn upward_fractional_wheel_unpins_before_a_row_moves_and_streaming_cannot_repin() { + let (mut view, mut cells) = transcript( "one\n\ntwo\n\nthree\n\nfour\n\nfive\n\nsix", /*width*/ 12, ); @@ -102,9 +102,49 @@ fn fractional_mouse_scroll_does_not_pause_following_until_a_row_moves() { mouse(MouseEventKind::ScrollUp, /*column*/ 4, /*row*/ 1), &cells, ); + assert!(!view.is_following()); + cells.push(Arc::new(AgentMarkdownCell::new( + "seven\n\neight".into(), + std::path::Path::new("/"), + ))); + let area = Rect::new( + /*x*/ 2, /*y*/ 1, /*width*/ 12, /*height*/ 8, + ); + view.render(area, &mut Buffer::empty(area), &cells); + assert!(!view.is_following()); +} + +#[test] +fn downward_fractional_wheel_does_not_unpin_until_a_row_moves() { + let (mut view, cells) = transcript( + "one\n\ntwo\n\nthree\n\nfour\n\nfive\n\nsix", + /*width*/ 12, + ); + view.mouse_scroll_speed = 0.5; + view.handle_mouse( + mouse( + MouseEventKind::ScrollDown, + /*column*/ 4, + /*row*/ 1, + ), + &cells, + ); + assert!(view.is_following()); +} + +#[test] +fn wheel_scrolls_transcript_when_pointer_is_outside_its_area() { + let (mut view, cells) = transcript( + "one\n\ntwo\n\nthree\n\nfour\n\nfive\n\nsix", + /*width*/ 12, + ); assert!(view.is_following()); view.handle_mouse( - mouse(MouseEventKind::ScrollUp, /*column*/ 4, /*row*/ 1), + mouse( + MouseEventKind::ScrollUp, + /*column*/ 60, + /*row*/ 40, + ), &cells, ); assert!(!view.is_following()); diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 30002e854012..8f7c04224f47 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -688,8 +688,31 @@ pub(crate) enum MouseCapture { Disabled, } +/// Process-wide veto from `tui.mouse_capture = false` or `CODEX_TUI_MOUSE_CAPTURE=0`. +static MOUSE_CAPTURE_VETOED: AtomicBool = AtomicBool::new(false); + +/// Resolve the mouse-capture policy: the environment variable wins over the config value. +pub(crate) fn mouse_capture_allowed(config: Option, env: Option<&str>) -> bool { + match env.map(|value| value.trim().to_ascii_lowercase()) { + Some(value) if matches!(value.as_str(), "0" | "false" | "off" | "no" | "never") => false, + Some(value) if matches!(value.as_str(), "1" | "true" | "on" | "yes" | "always") => true, + _ => config.unwrap_or(true), + } +} + +pub(crate) fn configure_mouse_capture(config: Option) { + let env = std::env::var("CODEX_TUI_MOUSE_CAPTURE").ok(); + MOUSE_CAPTURE_VETOED.store( + !mouse_capture_allowed(config, env.as_deref()), + Ordering::Relaxed, + ); +} + impl MouseCapture { fn captures_mouse(self, owned_screen: bool) -> bool { + if MOUSE_CAPTURE_VETOED.load(Ordering::Relaxed) { + return false; + } match self { Self::Inherit => owned_screen, Self::Enabled => true, @@ -859,8 +882,10 @@ impl Tui { let transition = if owned { self.owned_screen = true; if self.is_alt_screen_active() { - ALTERNATE_SCREEN - .configure_input(self.terminal.backend_mut(), /*capture_mouse*/ true) + ALTERNATE_SCREEN.configure_input( + self.terminal.backend_mut(), + MouseCapture::Enabled.captures_mouse(self.owned_screen), + ) } else { self.enter_alt_screen() } @@ -1649,3 +1674,18 @@ fn ensure_virtual_terminal_processing() -> Result<()> { fn ensure_virtual_terminal_processing() -> Result<()> { Ok(()) } + +#[cfg(test)] +mod mouse_capture_policy_tests { + use super::mouse_capture_allowed; + + #[test] + fn config_and_env_resolve_mouse_capture() { + assert!(mouse_capture_allowed(None, None)); + assert!(!mouse_capture_allowed(Some(false), None)); + assert!(!mouse_capture_allowed(None, Some("0"))); + assert!(!mouse_capture_allowed(Some(true), Some("off"))); + assert!(mouse_capture_allowed(Some(false), Some("1"))); + assert!(!mouse_capture_allowed(Some(false), Some("garbage"))); + } +} diff --git a/codex-rs/tui/src/tui/alternate_screen.rs b/codex-rs/tui/src/tui/alternate_screen.rs index 692d6ae8c24b..c2482e880c04 100644 --- a/codex-rs/tui/src/tui/alternate_screen.rs +++ b/codex-rs/tui/src/tui/alternate_screen.rs @@ -247,7 +247,9 @@ impl super::MouseCapture { *self = next; if let Err(error) = screen.configure_input(writer, next.captures_mouse(owned)) { *self = Self::Inherit; - let _ = screen.configure_input(writer, owned); + // The fallback applies the same veto (tui.mouse_capture=false) as the requested policy. + // The fallback applies the same veto (tui.mouse_capture=false) as the requested policy. + let _ = screen.configure_input(writer, Self::Inherit.captures_mouse(owned)); return Err(error); } Ok(()) diff --git a/codex-rs/tui/src/tui/alternate_screen_tests.rs b/codex-rs/tui/src/tui/alternate_screen_tests.rs index beeab25478ff..158ad4a65ef6 100644 --- a/codex-rs/tui/src/tui/alternate_screen_tests.rs +++ b/codex-rs/tui/src/tui/alternate_screen_tests.rs @@ -366,6 +366,36 @@ fn failed_mouse_encoding_setup_is_cleaned_up() { ); } +#[test] +fn failed_mouse_fallback_respects_the_mouse_capture_veto() { + let screen = AlternateScreen::default(); + let mut output = Vec::new(); + enter_with_mouse_enabled(&screen, &mut output, /*capture_mouse*/ true).unwrap(); + let mut writer = FailOnce { + output, + sequence: b"\x1b[?1006l\x1b[?1015l\x1b[?1003l\x1b[?1002l\x1b[?1000l", + failed: false, + }; + crate::tui::configure_mouse_capture(Some(false)); + let mut state = MouseCapture::Enabled; + let result = state.apply( + &screen, + &mut writer, + MouseCapture::Inherit, + /*owned*/ true, + ); + crate::tui::configure_mouse_capture(None); + assert!(result.is_err()); + let mut terminal = vt100::Parser::new( + /*rows*/ 24, /*cols*/ 80, /*scrollback_len*/ 0, + ); + terminal.process(&writer.output); + assert_eq!( + terminal.screen().mouse_protocol_mode(), + vt100::MouseProtocolMode::None, + ); +} + #[test] fn failed_mouse_cleanup_still_leaves_owned_screen_and_remains_retryable() { let screen = AlternateScreen::default();