From 5aaf080859a3a5e820aecf95e550e9dcff61890e Mon Sep 17 00:00:00 2001 From: egor Date: Fri, 4 Dec 2026 20:21:27 +0500 Subject: [PATCH 1/3] fix(agent): explain Codex MCP approval conflicts --- crates/agent/src/panel/composer_renderer.rs | 31 +++++++++++ crates/agent/src/panel/entries/tool_output.rs | 15 +++++- crates/agent/src/panel/tests/tool_sections.rs | 44 +++++++++++++++- crates/agent/src/panel/tests/warm_start.rs | 52 +++++++++++++++++++ crates/ai/src/mcp.rs | 2 +- crates/ai/src/tools/catalog.rs | 41 ++++++++------- crates/ai/src/tools/catalog/tests.rs | 26 ++++++++++ crates/ai/src/tools/fixtures/tools-list.json | 33 ++++++++++++ docs/AI_AGENTS.md | 7 +++ docs/architecture/domain.md | 3 ++ 10 files changed, 232 insertions(+), 22 deletions(-) diff --git a/crates/agent/src/panel/composer_renderer.rs b/crates/agent/src/panel/composer_renderer.rs index f1c1b22f..241569ea 100644 --- a/crates/agent/src/panel/composer_renderer.rs +++ b/crates/agent/src/panel/composer_renderer.rs @@ -13,6 +13,7 @@ use gpui_kit::{ px, rems, }; use nocterm_ai::model::auth::AuthFlow; +use nocterm_ai::model::controls::{ConfigCategory, ConfigKind}; use nocterm_ui::IconName; use super::{ @@ -21,6 +22,25 @@ use super::{ }; use crate::thread::{AgentThread, config_label}; +fn codex_mcp_approval_warning(thread: &AgentThread) -> bool { + if thread.document().agent_id() != "codex" || thread.composer().attachments().is_empty() { + return false; + } + let config = thread.configuration(); + match config + .options() + .iter() + .find(|option| option.category == Some(ConfigCategory::Mode)) + { + Some(option) => { + matches!(&option.kind, ConfigKind::Select(select) if select.current.as_str() == "agent-full-access") + } + None => config + .current_mode() + .is_some_and(|mode| mode.as_str() == "agent-full-access"), + } +} + fn remove_image(origin: gpui_kit::EntityId, index: usize, cx: &mut Context) -> Button { Button::new(("remove-image", index)) .ghost() @@ -389,6 +409,17 @@ impl ComposerRenderer { .into_any_element(), ); } + if codex_mcp_approval_warning(thread.read(cx)) { + notices.push( + div() + .id("codex-mcp-approval-warning") + .test_support() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child("Full access blocks approval-required Codex MCP tools. Select Workspace access to allow approval requests.") + .into_any_element(), + ); + } if thread.read(cx).ended() && !thread.read(cx).session_generating() { notices.push( Button::new("agent-restart") diff --git a/crates/agent/src/panel/entries/tool_output.rs b/crates/agent/src/panel/entries/tool_output.rs index 4f7e3dd4..47200783 100644 --- a/crates/agent/src/panel/entries/tool_output.rs +++ b/crates/agent/src/panel/entries/tool_output.rs @@ -6,7 +6,7 @@ use gpui_kit::{ px, }; use nocterm_ai::model::content::Content; -use nocterm_ai::model::tools::{ToolContent, ToolRecord}; +use nocterm_ai::model::tools::{ToolContent, ToolRecord, ToolStatus}; use nocterm_ai::tool_display::{self, ToolDisplay, ToolOutcome}; use serde_json::Value; @@ -91,6 +91,19 @@ pub(in crate::panel) fn source(call: &ToolRecord, redact: bool) -> Option, cx: &mut TestAppContext) -> Strin cx.update(|cx| crate::thread::config_label(&thread.read(cx).config_options()[0])) } +#[gpui_kit::test] +fn codex_full_access_with_terminals_warns_until_user_changes_mode(cx: &mut TestAppContext) { + let f = fixture(cx); + f.commands.config.set_options(vec![ + ConfigOption::select( + "mode", + "Mode", + "agent-full-access", + vec![ + ConfigChoice::new("agent-full-access", "Full access"), + ConfigChoice::new("workspace-write", "Workspace access"), + ], + ) + .category(ConfigCategory::Mode), + ]); + let thread = chat(&f, cx); + cx.run_until_parked(); + thread.update(cx, |thread, cx| { + thread.replace_composer_context(Vec::new(), cx) + }); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("codex-mcp-approval-warning").is_none()); + }) + .unwrap(); + thread.update(cx, |thread, cx| { + thread.attach(Attachment::Terminal(f.terminal), cx); + }); + cx.run_until_parked(); + assert!(f.commands.config.requests().is_empty()); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("codex-mcp-approval-warning").is_some()); + window.click("config-picker-mode", cx); + window.render_frame(cx); + window.click("config-mode-workspace-write", cx); + }) + .unwrap(); + cx.run_until_parked(); + let requests = f.commands.config.requests(); + assert_eq!(requests.len(), 1); + assert_eq!( + requests[0].setting, + ConfigSetting::Choice("workspace-write".into()) + ); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("codex-mcp-approval-warning").is_none()); + }) + .unwrap(); +} + #[gpui_kit::test] fn a_new_chat_connects_at_once_so_its_model_is_chosen_before_the_first_message( cx: &mut TestAppContext, diff --git a/crates/ai/src/mcp.rs b/crates/ai/src/mcp.rs index 91b440ed..c996eabd 100644 --- a/crates/ai/src/mcp.rs +++ b/crates/ai/src/mcp.rs @@ -69,7 +69,7 @@ impl McpSession { _ if !self.initialized => error(id, -32002, "Initialize first"), "tools/list" => { let tools: Vec<_> = offer.tools().map(|spec| { - json!({"name":spec.name,"description":spec.description,"inputSchema":(spec.schema)()}) + json!({"name":spec.name,"description":spec.description,"inputSchema":(spec.schema)(),"annotations":{"readOnlyHint":spec.read_only}}) }).collect(); McpStep::Reply(json!({"jsonrpc":"2.0","id":id,"result":{"tools":tools}})) } diff --git a/crates/ai/src/tools/catalog.rs b/crates/ai/src/tools/catalog.rs index 9c1c1db8..617b99f5 100644 --- a/crates/ai/src/tools/catalog.rs +++ b/crates/ai/src/tools/catalog.rs @@ -8,6 +8,8 @@ pub struct ToolSpec { /// Terminal tools are always listed; file tools only while a chat offers them. pub group: ToolGroup, pub description: &'static str, + /// MCP metadata only; never an authorization decision. + pub read_only: bool, pub schema: fn() -> Value, /// Shape only: execution limits are checked separately by `validate`. pub parse: fn(Value) -> Option, @@ -50,7 +52,7 @@ impl ToolOffer { // The exhaustive name match makes each TerminalCall variant require a row here. macro_rules! catalog { - ($($variant:ident $(($arguments:ty))? => $name:literal, $label:literal, $group:ident, $description:literal;)*) => { + ($($variant:ident $(($arguments:ty))? => $name:literal, $label:literal, $group:ident, $read_only:literal, $description:literal;)*) => { enum Index { $($variant,)* } pub static TOOLS: &[ToolSpec] = &[$(ToolSpec { @@ -58,6 +60,7 @@ macro_rules! catalog { label: $label, group: ToolGroup::$group, description: $description, + read_only: $read_only, schema: catalog!(@schema $($arguments)?), parse: catalog!(@parse $variant $($arguments)?), },)*]; @@ -86,41 +89,41 @@ macro_rules! catalog { } catalog! { - ListTerminals => "list_terminals", "List terminals", Terminals, + ListTerminals => "list_terminals", "List terminals", Terminals, true, "List terminals attached to this chat, and attached servers that have no session yet (offline_servers). These are the only servers you can reach: nocterm holds their credentials, so never connect on your own with ssh. When the list is empty, tell the user to attach a terminal or server to the chat"; - OpenTerminal(OpenTerminal) => "open_terminal", "Connect", Terminals, + OpenTerminal(OpenTerminal) => "open_terminal", "Connect", Terminals, false, "Connect to an attached offline server in the background, without disturbing the user; returns its terminal_id once connected. If it fails, tell the user in one short sentence why and stop"; - ReadTerminal(ReadTerminal) => "read_terminal", "Read terminal", Terminals, + ReadTerminal(ReadTerminal) => "read_terminal", "Read terminal", Terminals, true, "Read bounded output of an attached terminal"; - SendInput(SendInput) => "send_input", "Send input", Terminals, + SendInput(SendInput) => "send_input", "Send input", Terminals, false, "Send text to an attached terminal with user approval"; - RunCommand(RunCommand) => "run_command", "Run command", Terminals, + RunCommand(RunCommand) => "run_command", "Run command", Terminals, false, "Type one command into a known empty live shell prompt. Requires shell integration; an output pause never proves completion. Prefer exec_command for a reliable exit status"; - ExecCommand(ExecCommand) => "exec_command", "Execute program", Terminals, + ExecCommand(ExecCommand) => "exec_command", "Execute program", Terminals, false, "Run program with separate args and optional stdin on the attached terminal host over its current connection. Local execution passes args directly; SSH renders a POSIX command line, so arbitrary args require a POSIX-compatible remote command shell and are not guaranteed on Windows SSH. Fresh process: no inherited terminal cwd, environment, aliases or functions. Use an explicit shell for shell syntax. Returns actual exit status or an owned command_id for read_command/cancel_command. Output is bounded and continuously drained"; - ReadCommand(ReadCommand) => "read_command", "Read command", Terminals, + ReadCommand(ReadCommand) => "read_command", "Read command", Terminals, true, "Read a bounded full snapshot of a command owned by this chat. Does not start or cancel a command; optional yield_ms waits briefly"; - CancelCommand(CancelCommand) => "cancel_command", "Cancel command", Terminals, + CancelCommand(CancelCommand) => "cancel_command", "Cancel command", Terminals, false, "Cancel a command owned by this chat. SSH sends TERM and closes its channel; remote descendant termination is best effort"; - TransferFiles(TransferFiles) => "transfer_files", "Transfer files", Terminals, + TransferFiles(TransferFiles) => "transfer_files", "Transfer files", Terminals, false, "Copy files and folders between the hosts of two attached terminals: this computer (a local terminal) to a server, a server to this computer, or a server to another server. nocterm relays the data over the connections it already holds, so servers need no credentials for each other and you must never use scp, rsync or ssh between them. Every path is absolute (no ~, no .. components). sources are files or folders on the source host; folders copy recursively, and each source is copied into destination under its own name. destination must be an existing folder; it is never created. Existing files are skipped and counted as skipped unless overwrite is true. Symbolic links and special files are skipped. At most 64 sources per call. Two local terminals are refused: use exec_command. Some environments only allow copies within one server. The copy runs in the background: after optional yield_ms (default 1000) it returns the current state and a transfer_id for read_transfer/cancel_transfer. Poll read_transfer until the state is completed, failed or cancelled. Whole files are published atomically; a cancelled or failed file leaves no partial file"; - ReadTransfer(ReadTransfer) => "read_transfer", "Read transfer", Terminals, + ReadTransfer(ReadTransfer) => "read_transfer", "Read transfer", Terminals, true, "Read a snapshot of a transfer started by this chat: state, file and byte counts and up to 16 failures. Does not start or cancel a transfer; optional yield_ms waits briefly while it is active"; - CancelTransfer(CancelTransfer) => "cancel_transfer", "Cancel transfer", Terminals, + CancelTransfer(CancelTransfer) => "cancel_transfer", "Cancel transfer", Terminals, false, "Cancel a transfer started by this chat. Files already published stay in place; files being copied are discarded"; - ListFiles(ListFiles) => "list_files", "List files", Files, + ListFiles(ListFiles) => "list_files", "List files", Files, true, "List a folder of an attached terminal whose list_terminals entry has file_tools: true. Such a terminal serves files but runs no programs (for example a console tab a plugin opened for a game server panel): exec_command and run_command cannot reach its files, so use the file tools for them. Paths are absolute from / with no ~, . or .. parts. Folders come first; at most 1000 entries. The file tools act only on terminals with file_tools: true, never on other terminals or this computer"; - ReadFile(ReadFile) => "read_file", "Read file", Files, + ReadFile(ReadFile) => "read_file", "Read file", Files, true, "Read a UTF-8 text file of an attached terminal with file_tools: true, up to 1 MiB, a range of lines at a time (start_line from 1, max_lines up to 2000, at most 64 KiB per answer; next_start_line says where to continue). The content is exactly the file's text, except where it is shown as [REDACTED]: such text is hidden from you, so change other parts with edit_file and never write the marker back"; - WriteFile(WriteFile) => "write_file", "Write file", Files, + WriteFile(WriteFile) => "write_file", "Write file", Files, false, "Write a whole UTF-8 text file (at most 512 KiB) on an attached terminal with file_tools: true, with user approval. An existing file is refused unless overwrite is true; prefer edit_file to change part of a file. The parent folder must exist"; - EditFile(EditFile) => "edit_file", "Edit file", Files, + EditFile(EditFile) => "edit_file", "Edit file", Files, false, "Replace exact text in a file of an attached terminal with file_tools: true, with user approval. old_text must occur exactly once, copied exactly from read_file with its whitespace, unless replace_all is true. Send only the part that changes; the file is changed on its host"; - MakeDirectory(MakeDirectory) => "make_directory", "Create folder", Files, + MakeDirectory(MakeDirectory) => "make_directory", "Create folder", Files, false, "Create a folder on an attached terminal with file_tools: true, with user approval. Its parent must exist; an existing folder is accepted"; - DeletePath(DeletePath) => "delete_path", "Delete", Files, + DeletePath(DeletePath) => "delete_path", "Delete", Files, false, "Delete a file or folder on an attached terminal with file_tools: true, with user approval. A folder is removed as the terminal's host removes folders, which may include its contents; it cannot be undone"; - MovePath(MovePath) => "move_path", "Move", Files, + MovePath(MovePath) => "move_path", "Move", Files, false, "Move or rename a file or folder within one attached terminal with file_tools: true, with user approval. Both paths are absolute"; } diff --git a/crates/ai/src/tools/catalog/tests.rs b/crates/ai/src/tools/catalog/tests.rs index 18057d9e..2db067f8 100644 --- a/crates/ai/src/tools/catalog/tests.rs +++ b/crates/ai/src/tools/catalog/tests.rs @@ -82,6 +82,32 @@ fn tools_list_preserves_original_order_descriptions_and_schemas() { ); } +#[test] +fn only_observation_tools_are_advertised_as_read_only() { + let McpStep::Reply(reply) = + session().handle(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#, ALL) + else { + panic!("expected tools/list reply"); + }; + for tool in reply["result"]["tools"].as_array().unwrap() { + let name = tool["name"].as_str().unwrap(); + let observation = matches!( + name, + "list_terminals" + | "read_terminal" + | "read_command" + | "read_transfer" + | "list_files" + | "read_file" + ); + assert_eq!( + tool["annotations"]["readOnlyHint"], + json!(observation), + "{name}" + ); + } +} + #[test] fn file_tools_are_listed_and_admitted_only_while_offered() { let listed = |offer| { diff --git a/crates/ai/src/tools/fixtures/tools-list.json b/crates/ai/src/tools/fixtures/tools-list.json index bb5550c2..7cb84c08 100644 --- a/crates/ai/src/tools/fixtures/tools-list.json +++ b/crates/ai/src/tools/fixtures/tools-list.json @@ -5,6 +5,9 @@ "tools": [ { "name": "list_terminals", + "annotations": { + "readOnlyHint": true + }, "description": "List terminals attached to this chat, and attached servers that have no session yet (offline_servers). These are the only servers you can reach: nocterm holds their credentials, so never connect on your own with ssh. When the list is empty, tell the user to attach a terminal or server to the chat", "inputSchema": { "type": "object", @@ -14,6 +17,9 @@ }, { "name": "open_terminal", + "annotations": { + "readOnlyHint": false + }, "description": "Connect to an attached offline server in the background, without disturbing the user; returns its terminal_id once connected. If it fails, tell the user in one short sentence why and stop", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -34,6 +40,9 @@ }, { "name": "read_terminal", + "annotations": { + "readOnlyHint": true + }, "description": "Read bounded output of an attached terminal", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -68,6 +77,9 @@ }, { "name": "send_input", + "annotations": { + "readOnlyHint": false + }, "description": "Send text to an attached terminal with user approval", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -94,6 +106,9 @@ }, { "name": "run_command", + "annotations": { + "readOnlyHint": false + }, "description": "Type one command into a known empty live shell prompt. Requires shell integration; an output pause never proves completion. Prefer exec_command for a reliable exit status", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -132,6 +147,9 @@ }, { "name": "exec_command", + "annotations": { + "readOnlyHint": false + }, "description": "Run program with separate args and optional stdin on the attached terminal host over its current connection. Local execution passes args directly; SSH renders a POSIX command line, so arbitrary args require a POSIX-compatible remote command shell and are not guaranteed on Windows SSH. Fresh process: no inherited terminal cwd, environment, aliases or functions. Use an explicit shell for shell syntax. Returns actual exit status or an owned command_id for read_command/cancel_command. Output is bounded and continuously drained", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -184,6 +202,9 @@ }, { "name": "read_command", + "annotations": { + "readOnlyHint": true + }, "description": "Read a bounded full snapshot of a command owned by this chat. Does not start or cancel a command; optional yield_ms waits briefly", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -214,6 +235,9 @@ }, { "name": "cancel_command", + "annotations": { + "readOnlyHint": false + }, "description": "Cancel a command owned by this chat. SSH sends TERM and closes its channel; remote descendant termination is best effort", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -236,6 +260,9 @@ }, { "name": "transfer_files", + "annotations": { + "readOnlyHint": false + }, "description": "Copy files and folders between the hosts of two attached terminals: this computer (a local terminal) to a server, a server to this computer, or a server to another server. nocterm relays the data over the connections it already holds, so servers need no credentials for each other and you must never use scp, rsync or ssh between them. Every path is absolute (no ~, no .. components). sources are files or folders on the source host; folders copy recursively, and each source is copied into destination under its own name. destination must be an existing folder; it is never created. Existing files are skipped and counted as skipped unless overwrite is true. Symbolic links and special files are skipped. At most 64 sources per call. Two local terminals are refused: use exec_command. Some environments only allow copies within one server. The copy runs in the background: after optional yield_ms (default 1000) it returns the current state and a transfer_id for read_transfer/cancel_transfer. Poll read_transfer until the state is completed, failed or cancelled. Whole files are published atomically; a cancelled or failed file leaves no partial file", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -287,6 +314,9 @@ }, { "name": "read_transfer", + "annotations": { + "readOnlyHint": true + }, "description": "Read a snapshot of a transfer started by this chat: state, file and byte counts and up to 16 failures. Does not start or cancel a transfer; optional yield_ms waits briefly while it is active", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -313,6 +343,9 @@ }, { "name": "cancel_transfer", + "annotations": { + "readOnlyHint": false + }, "description": "Cancel a transfer started by this chat. Files already published stay in place; files being copied are discarded", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", diff --git a/docs/AI_AGENTS.md b/docs/AI_AGENTS.md index 3ed77b20..17ed37d6 100644 --- a/docs/AI_AGENTS.md +++ b/docs/AI_AGENTS.md @@ -478,6 +478,13 @@ If the provider supplies no valid one-time choice, the request remains as a card with an explanation and the provider's options for manual review. Stop, disabled AI and requests from an obsolete or different session cancel instead of approving. +Codex's **Full access** mode uses the provider's `never` approval policy. Codex +can refuse MCP tools that require approval before their requests reach Nocterm, +even when the vault is unlocked and the terminal is attached and connected. +If this happens, select **Workspace access** in the chat's mode picker, then +retry and review any permission requests. Nocterm's attachment and terminal +approval rules still apply independently. + The terminal read cursor is inclusive: a resumed read may replace the previous last logical line after more text is appended. It is not an exact byte-stream cursor. Alternate screens expose the visible page only. A local OSC 133 prompt diff --git a/docs/architecture/domain.md b/docs/architecture/domain.md index 9664b398..5d6fd39b 100644 --- a/docs/architecture/domain.md +++ b/docs/architecture/domain.md @@ -363,6 +363,9 @@ that format; command reports share explicit redaction policy and retain the actu exit, byte count and truncation. The panel decodes the same DTOs while retaining its labels, unknown-field display and historical provider-envelope fallbacks. These reports are observations, never execution or cancellation capabilities. +The tool catalog advertises MCP read-only hints for observation tools only. +Hints describe side effects, not grants; attachment scope and approvals are +enforced independently of the advertised metadata. `nocterm-ai::agents` describes how a known agent deviates from plain ACP as an `AgentProfile`: its pinned launch, the home directories it writes, how it reports From 1b8b411e6f8e48fae3fcf43155f1b1c8d57bf05a Mon Sep 17 00:00:00 2001 From: egor Date: Fri, 4 Dec 2026 23:23:04 +0500 Subject: [PATCH 2/3] fix(agent): clarify effective Codex goal permissions --- crates/agent/src/panel/composer_renderer.rs | 30 ++++------- crates/agent/src/panel/entries/tool_output.rs | 2 +- crates/agent/src/panel/tests/commands.rs | 52 +++++++++++++++++++ crates/agent/src/panel/tests/tool_sections.rs | 3 ++ crates/agent/src/panel/tests/warm_start.rs | 52 ------------------- docs/AI_AGENTS.md | 16 +++--- 6 files changed, 75 insertions(+), 80 deletions(-) diff --git a/crates/agent/src/panel/composer_renderer.rs b/crates/agent/src/panel/composer_renderer.rs index 241569ea..89ec0515 100644 --- a/crates/agent/src/panel/composer_renderer.rs +++ b/crates/agent/src/panel/composer_renderer.rs @@ -13,7 +13,6 @@ use gpui_kit::{ px, rems, }; use nocterm_ai::model::auth::AuthFlow; -use nocterm_ai::model::controls::{ConfigCategory, ConfigKind}; use nocterm_ui::IconName; use super::{ @@ -22,23 +21,12 @@ use super::{ }; use crate::thread::{AgentThread, config_label}; -fn codex_mcp_approval_warning(thread: &AgentThread) -> bool { - if thread.document().agent_id() != "codex" || thread.composer().attachments().is_empty() { - return false; - } - let config = thread.configuration(); - match config - .options() - .iter() - .find(|option| option.category == Some(ConfigCategory::Mode)) - { - Some(option) => { - matches!(&option.kind, ConfigKind::Select(select) if select.current.as_str() == "agent-full-access") - } - None => config - .current_mode() - .is_some_and(|mode| mode.as_str() == "agent-full-access"), - } +fn codex_goal_mode_notice(thread: &AgentThread) -> bool { + thread.document().agent_id() == "codex" + && thread.draft_text().is_some_and(|draft| { + nocterm_ai::commands::invocation(draft, thread.configuration().commands()) + .is_some_and(|command| command.name == "goal") + }) } fn remove_image(origin: gpui_kit::EntityId, index: usize, cx: &mut Context) -> Button { @@ -409,14 +397,14 @@ impl ComposerRenderer { .into_any_element(), ); } - if codex_mcp_approval_warning(thread.read(cx)) { + if codex_goal_mode_notice(thread.read(cx)) { notices.push( div() - .id("codex-mcp-approval-warning") + .id("codex-goal-mode-notice") .test_support() .text_xs() .text_color(cx.theme().muted_foreground) - .child("Full access blocks approval-required Codex MCP tools. Select Workspace access to allow approval requests.") + .child("Codex goal commands may retain the last applied permission mode. After changing mode, send a regular message before starting or resuming a goal.") .into_any_element(), ); } diff --git a/crates/agent/src/panel/entries/tool_output.rs b/crates/agent/src/panel/entries/tool_output.rs index 47200783..75cf4f18 100644 --- a/crates/agent/src/panel/entries/tool_output.rs +++ b/crates/agent/src/panel/entries/tool_output.rs @@ -101,7 +101,7 @@ pub(in crate::panel) fn source(call: &ToolRecord, redact: bool) -> Option, text: &str, cx: &mut Tes } } +#[gpui_kit::test] +fn codex_goal_warns_about_the_effective_mode_instead_of_assuming_full_access( + cx: &mut TestAppContext, +) { + let f = fixture(cx); + f.commands.config.set_options(vec![ + ConfigOption::select( + "mode", + "Mode", + "agent-full-access", + vec![ + ConfigChoice::new("agent-full-access", "Full access"), + ConfigChoice::new("workspace-write", "Workspace access"), + ], + ) + .category(ConfigCategory::Mode), + ]); + new_chat(&f, cx); + let goals = || vec![AvailableCommand::new("goal", "Work towards an objective")]; + commands(&f, goals(), "Ordinary message", cx); + cx.update_window(f.handle, |_, window, _cx| { + assert!(window.try_find("codex-goal-mode-notice").is_none()); + }) + .unwrap(); + + commands(&f, goals(), "/goal resume", cx); + cx.update_window(f.handle, |_, window, cx| { + assert!(window.try_find("codex-goal-mode-notice").is_some()); + window.click("config-picker-mode", cx); + window.render_frame(cx); + window.click("config-mode-workspace-write", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("codex-goal-mode-notice").is_some()); + }) + .unwrap(); + assert_eq!(f.commands.config.requests().len(), 1); + assert!( + f.commands.prompts.lock().unwrap().is_empty(), + "the notice must not send an implicit prompt" + ); + + commands(&f, goals(), "/goals", cx); + cx.update_window(f.handle, |_, window, _cx| { + assert!(window.try_find("codex-goal-mode-notice").is_none()); + }) + .unwrap(); +} + #[gpui_kit::test] fn clicked_unicode_command_keeps_focus_and_appends_at_end(cx: &mut TestAppContext) { let f = fixture(cx); diff --git a/crates/agent/src/panel/tests/tool_sections.rs b/crates/agent/src/panel/tests/tool_sections.rs index 9121d4d9..42e3537e 100644 --- a/crates/agent/src/panel/tests/tool_sections.rs +++ b/crates/agent/src/panel/tests/tool_sections.rs @@ -99,6 +99,9 @@ fn codex_approval_policy_failure_explains_the_provider_gate() { .find(|section| section.label == "Codex approval mode") .unwrap(); assert!(help.text.contains("Workspace access")); + assert!(help.text.contains("displayed mode can differ")); + assert!(help.text.contains("/goal")); + assert!(help.text.contains("send a regular message")); assert!( help.text .contains("Nocterm terminal permissions still apply") diff --git a/crates/agent/src/panel/tests/warm_start.rs b/crates/agent/src/panel/tests/warm_start.rs index 5b899987..afdf3876 100644 --- a/crates/agent/src/panel/tests/warm_start.rs +++ b/crates/agent/src/panel/tests/warm_start.rs @@ -42,58 +42,6 @@ fn current_model(thread: &Entity, cx: &mut TestAppContext) -> Strin cx.update(|cx| crate::thread::config_label(&thread.read(cx).config_options()[0])) } -#[gpui_kit::test] -fn codex_full_access_with_terminals_warns_until_user_changes_mode(cx: &mut TestAppContext) { - let f = fixture(cx); - f.commands.config.set_options(vec![ - ConfigOption::select( - "mode", - "Mode", - "agent-full-access", - vec![ - ConfigChoice::new("agent-full-access", "Full access"), - ConfigChoice::new("workspace-write", "Workspace access"), - ], - ) - .category(ConfigCategory::Mode), - ]); - let thread = chat(&f, cx); - cx.run_until_parked(); - thread.update(cx, |thread, cx| { - thread.replace_composer_context(Vec::new(), cx) - }); - cx.update_window(f.handle, |_, window, cx| { - window.render_frame(cx); - assert!(window.try_find("codex-mcp-approval-warning").is_none()); - }) - .unwrap(); - thread.update(cx, |thread, cx| { - thread.attach(Attachment::Terminal(f.terminal), cx); - }); - cx.run_until_parked(); - assert!(f.commands.config.requests().is_empty()); - cx.update_window(f.handle, |_, window, cx| { - window.render_frame(cx); - assert!(window.try_find("codex-mcp-approval-warning").is_some()); - window.click("config-picker-mode", cx); - window.render_frame(cx); - window.click("config-mode-workspace-write", cx); - }) - .unwrap(); - cx.run_until_parked(); - let requests = f.commands.config.requests(); - assert_eq!(requests.len(), 1); - assert_eq!( - requests[0].setting, - ConfigSetting::Choice("workspace-write".into()) - ); - cx.update_window(f.handle, |_, window, cx| { - window.render_frame(cx); - assert!(window.try_find("codex-mcp-approval-warning").is_none()); - }) - .unwrap(); -} - #[gpui_kit::test] fn a_new_chat_connects_at_once_so_its_model_is_chosen_before_the_first_message( cx: &mut TestAppContext, diff --git a/docs/AI_AGENTS.md b/docs/AI_AGENTS.md index 17ed37d6..4d4893f5 100644 --- a/docs/AI_AGENTS.md +++ b/docs/AI_AGENTS.md @@ -478,12 +478,16 @@ If the provider supplies no valid one-time choice, the request remains as a card with an explanation and the provider's options for manual review. Stop, disabled AI and requests from an obsolete or different session cancel instead of approving. -Codex's **Full access** mode uses the provider's `never` approval policy. Codex -can refuse MCP tools that require approval before their requests reach Nocterm, -even when the vault is unlocked and the terminal is attached and connected. -If this happens, select **Workspace access** in the chat's mode picker, then -retry and review any permission requests. Nocterm's attachment and terminal -approval rules still apply independently. +Codex can refuse MCP tools before their requests reach Nocterm when its +effective approval policy is `never`, even with an unlocked vault and an +attached, connected terminal. In codex-acp 2.13.0 the mode picker changes the +adapter's selection, but regular prompts apply that selection to the Codex +thread. The `/goal` command starts or resumes a goal directly and can retain +the thread's previous policy instead. The displayed selection is therefore +not proof of the effective policy for a running goal. If this error occurs, +stop the goal, select **Workspace access**, send a regular message and wait for +it to finish before resuming the goal. Review any permission requests. +Nocterm's attachment and terminal approval rules still apply independently. The terminal read cursor is inclusive: a resumed read may replace the previous last logical line after more text is appended. It is not an exact byte-stream From ad3f604e5d61d4203bed9a7019a495d79b330c00 Mon Sep 17 00:00:00 2001 From: egor Date: Fri, 4 Dec 2026 23:11:01 +0500 Subject: [PATCH 3/3] fix(agent): smooth and isolate thinking animation --- Cargo.lock | 1 - THIRD_PARTY_NOTICES.txt | 6 +- crates/agent/src/panel.rs | 12 +- crates/agent/src/panel/chat.rs | 6 +- crates/agent/src/panel/layout.rs | 6 +- crates/agent/src/panel/lifecycle.rs | 2 +- crates/agent/src/panel/parts.rs | 44 +++- crates/agent/src/panel/tests/approvals.rs | 2 +- crates/agent/src/panel/tests/composer.rs | 2 +- .../panel/tests/composer/menu_stability.rs | 2 +- crates/agent/src/panel/tests/invalidation.rs | 100 ++++++++ crates/agent/src/panel/tests/mod.rs | 14 +- crates/agent/src/panel/tests/servers/menu.rs | 2 +- crates/agent/src/panel/tests/tool_input.rs | 2 +- crates/agent/src/panel/transcript.rs | 14 +- crates/ui/Cargo.toml | 1 - crates/ui/assets/animations/thinking.webp | Bin 9630 -> 0 bytes crates/ui/src/animations.rs | 231 ++++++++++++------ docs/architecture/feature.md | 10 +- 19 files changed, 347 insertions(+), 110 deletions(-) delete mode 100644 crates/ui/assets/animations/thinking.webp diff --git a/Cargo.lock b/Cargo.lock index 4e45c35b..8583e6cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6456,7 +6456,6 @@ version = "0.0.0" dependencies = [ "futures", "gpui-kit", - "image", "nocterm-core", "nocterm-design", "nocterm-explorer", diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt index cd0007aa..8a3e63d7 100644 --- a/THIRD_PARTY_NOTICES.txt +++ b/THIRD_PARTY_NOTICES.txt @@ -2,9 +2,9 @@ Nocterm third-party licenses and notices ======================================== Generated by scripts/generate-license-notices.py using cargo-about 0.9.2. -Content SHA-256: 23f38964a59e4349ce78c3623d881bd996f343a217ad640e1f91906a7ef379de -Input fingerprint: 76076c89e8bd371a415fe064f1b773b52fb9e84437c9c85598cceb5abbb3f1e2 -Cargo.lock SHA-256 (release version masked): b33eec8e734dbb668401cb696d4cc21b59b8aeed795c149ed508e484bf5c34a7 +Content SHA-256: b533cd5e2e46230eb61c730ffdc816522be1c0cb727a17d2724167db73b8c667 +Input fingerprint: a5630f1f5613afb41b26855a566b5a838c0a83907151aee0db585a7f8c263aa1 +Cargo.lock SHA-256 (release version masked): d5ced87c994bda2f73b2114fe52f5466b93668a1325723121ec64e4323b06e5f Scope: runtime and build dependencies of Nocterm and its optional vault broker for Linux x86_64, Windows x86_64, macOS x86_64 and macOS arm64. diff --git a/crates/agent/src/panel.rs b/crates/agent/src/panel.rs index 75d79ae4..bd8ce2d3 100644 --- a/crates/agent/src/panel.rs +++ b/crates/agent/src/panel.rs @@ -95,7 +95,7 @@ impl AgentPanel { let composer = composer_view::ComposerView::new(window, cx); let menus = menu_view::MenuView::new(composer.focus(cx), window, cx); let history = history_column::HistoryColumn::new(window, cx); - let layout = layout::PanelLayout::new(layout, cx); + let layout = layout::PanelLayout::new(layout, window, cx); let messages = message_list::MessageList::new(images, cx); let subscriptions = Self::bind_panel(&host, &settings, window, cx); // Whatever the panel redraws for, its cached regions redraw too; thread changes @@ -455,6 +455,14 @@ impl AgentPanel { ) -> AnyElement { match kind { parts::PartKind::Transcript => self.render_transcript_part(cx), + parts::PartKind::Approvals => self + .current() + .and_then(|thread| self.render_approvals(&thread, window, cx)) + .unwrap_or_else(|| div().into_any_element()), + parts::PartKind::Status => self + .current() + .and_then(|thread| self.chat_status(&thread, cx)) + .unwrap_or_else(|| div().into_any_element()), parts::PartKind::Footer => self.render_footer(window, cx), parts::PartKind::Queue => self.render_queue_part(cx), } @@ -629,6 +637,8 @@ impl Render for AgentPanel { .min_w_0() .min_h_0() .child(self.layout.parts().transcript()) + .child(self.layout.parts().approvals()) + .child(self.layout.parts().status()) .child(self.layout.parts().footer(self.menus.current().is_some())) .into_any_element(); if self.layout.history() { diff --git a/crates/agent/src/panel/chat.rs b/crates/agent/src/panel/chat.rs index 7c06c137..ca03f3b7 100644 --- a/crates/agent/src/panel/chat.rs +++ b/crates/agent/src/panel/chat.rs @@ -10,7 +10,7 @@ use nocterm_ai::usage::{Breakdown, RateLimit}; use std::time::Duration; impl AgentPanel { - /// The open chat's footer: approvals, status, queue, commands and the composer. + /// The open chat's footer: queue, commands and the composer. pub(super) fn render_footer( &mut self, window: &mut Window, @@ -20,8 +20,6 @@ impl AgentPanel { return div().into_any_element(); }; let frame = super::composer_frame::ComposerFrame::read(&thread, cx); - let approvals = self.render_approvals(&thread, window, cx); - let status = self.chat_status(&thread, cx); let labels = attachments::AttachmentLabels::new(thread.read(cx).workspace_seat(), cx); let queue = (!thread.read(cx).composer().queue().is_empty()).then(|| self.layout.parts().queue()); @@ -30,8 +28,6 @@ impl AgentPanel { v_flex() .w_full() .min_w_0() - .children(approvals) - .children(status) .children(queue) .children(commands) .child(composer) diff --git a/crates/agent/src/panel/layout.rs b/crates/agent/src/panel/layout.rs index cb33a11f..9317ec48 100644 --- a/crates/agent/src/panel/layout.rs +++ b/crates/agent/src/panel/layout.rs @@ -91,7 +91,7 @@ pub(super) struct PanelLayout { parts: super::parts::PanelParts, } impl PanelLayout { - pub(super) fn new(layout: LayoutHandle, cx: &mut Context) -> Self { + pub(super) fn new(layout: LayoutHandle, window: &Window, cx: &mut Context) -> Self { let mut bindings = Vec::new(); let splits = [1, 0].map(|index| { let split = cx.new(|_| ResizableState::default()); @@ -112,6 +112,8 @@ impl PanelLayout { panel.on_shared_history_width_changed(value, cx) }); })); + let parts = super::parts::PanelParts::new(cx); + bindings.push(parts.observe_status_visibility(window)); Self { history: true, widened: None, @@ -121,7 +123,7 @@ impl PanelLayout { layout, _bindings: bindings, refresh: std::array::from_fn(|_| SplitRefresh::Idle), - parts: super::parts::PanelParts::new(cx), + parts, } } pub(super) fn history(&self) -> bool { diff --git a/crates/agent/src/panel/lifecycle.rs b/crates/agent/src/panel/lifecycle.rs index 7946f9ed..8f38b016 100644 --- a/crates/agent/src/panel/lifecycle.rs +++ b/crates/agent/src/panel/lifecycle.rs @@ -507,7 +507,7 @@ impl AgentPanel { let stamp = super::parts::transcript_stamp(loaded.read(cx)); let parts = self.layout.parts(); parts.transcript_changed(rows, stamp, cx); - parts.notify(super::parts::PartKind::Footer, cx); + parts.notify_chat_footer(cx); } self.schedule_history_redraw(cx); } diff --git a/crates/agent/src/panel/parts.rs b/crates/agent/src/panel/parts.rs index 01cbf57c..9f7b2549 100644 --- a/crates/agent/src/panel/parts.rs +++ b/crates/agent/src/panel/parts.rs @@ -3,19 +3,22 @@ //! Cached regions are reused unless they are notified. Any notify of the panel //! invalidates all of them, so state the panel changes stays correct by default; //! thread changes, typing and queue disclosure can target a single region. -//! The footer (approvals, status, queue, commands and composer) is cached to its +//! Approvals and animated status are independent siblings of the footer. +//! The footer (queue, commands and composer) is cached to its //! content while its pickers are closed. Open pickers keep their interaction state //! live instead of reusing a content-sized cache's deferred popup. use super::{AgentPanel, history::HistoryViewport}; use gpui_kit::{ App, AppContext as _, Context, Entity, IntoElement, Render, StyleRefinement, Styled, - WeakEntity, Window, div, + Subscription, WeakEntity, Window, div, }; use std::hash::{Hash, Hasher}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum PartKind { Transcript, + Approvals, + Status, Footer, Queue, } @@ -48,6 +51,8 @@ impl Render for HistoryPart { pub(super) struct PanelParts { transcript: Entity, history: Entity, + approvals: Entity, + status: Entity, footer: Entity, queue: Entity, transcript_seen: Option, @@ -61,6 +66,8 @@ impl PanelParts { cx.new(|_| PanelPart { panel, kind }) }; let transcript = part(PartKind::Transcript); + let approvals = part(PartKind::Approvals); + let status = part(PartKind::Status); let footer = part(PartKind::Footer); let queue = part(PartKind::Queue); let history = cx.new(|_| HistoryPart { @@ -70,6 +77,8 @@ impl PanelParts { Self { transcript, history, + approvals, + status, footer, queue, transcript_seen: None, @@ -96,6 +105,27 @@ impl PanelParts { .min_w_0(), ) } + /// Approvals stay above the status and composer without being rebuilt by animation. + pub(super) fn approvals(&self) -> impl IntoElement + use<> { + self.approvals + .clone() + .cached_to_content(StyleRefinement::default().w_full()) + } + /// The animation owns layout-time element state (including its paced wake). + /// Do not use a content-sized replay cache here: its replay only preserves + /// prepaint/paint state, not an animation's layout-time state. The surrounding + /// panel remains cached and the expensive sibling regions are independent. + pub(super) fn status(&self) -> impl IntoElement + use<> { + self.status.clone() + } + /// Visibility is not focus. Repaint the status when a hidden window is + /// presented again, even if its cached last draw had no animation wake. + pub(super) fn observe_status_visibility(&self, window: &Window) -> Subscription { + let status = self.status.downgrade(); + window.observe_window_visibility(move |_, _, cx| { + let _ = status.update(cx, |_, cx| cx.notify()); + }) + } /// Open pickers must retain their keyed popup, hover and scroll state across frames. pub(super) fn footer(&self, picker_open: bool) -> impl IntoElement + use<> { if picker_open { @@ -107,7 +137,7 @@ impl PanelParts { .into_any_element() } } - /// Keep a static queue available to the status animation's footer redraws. + /// Keep a static queue available to composer redraws. pub(super) fn queue(&self) -> impl IntoElement + use<> { self.queue .clone() @@ -117,11 +147,19 @@ impl PanelParts { pub(super) fn invalidate(&self, cx: &mut App) { self.transcript.update(cx, |_, cx| cx.notify()); self.invalidate_history(cx); + self.notify_chat_footer(cx); + } + /// A chat semantic update may change all of its lower regions. + pub(super) fn notify_chat_footer(&self, cx: &mut App) { + self.notify(PartKind::Approvals, cx); + self.notify(PartKind::Status, cx); self.notify(PartKind::Footer, cx); } pub(super) fn notify(&self, kind: PartKind, cx: &mut App) { let part = match kind { PartKind::Transcript => &self.transcript, + PartKind::Approvals => &self.approvals, + PartKind::Status => &self.status, PartKind::Footer => { self.queue.update(cx, |_, cx| cx.notify()); &self.footer diff --git a/crates/agent/src/panel/tests/approvals.rs b/crates/agent/src/panel/tests/approvals.rs index bb28b0d1..9f0910f2 100644 --- a/crates/agent/src/panel/tests/approvals.rs +++ b/crates/agent/src/panel/tests/approvals.rs @@ -100,7 +100,7 @@ fn live_group_membership_and_revoked_registration_reject_stale_terminal_ids( icon: None, flag: None, }; - let directory = Rc::new(Directory(std::cell::RefCell::new(vec![summary]))); + let directory = Rc::new(Directory::new(std::cell::RefCell::new(vec![summary]))); cx.update(|cx| { f.workspace.update(cx, |workspace, _| { workspace.set_connection_directory(directory.clone()) diff --git a/crates/agent/src/panel/tests/composer.rs b/crates/agent/src/panel/tests/composer.rs index 1c2b1fff..5d6377cf 100644 --- a/crates/agent/src/panel/tests/composer.rs +++ b/crates/agent/src/panel/tests/composer.rs @@ -23,7 +23,7 @@ fn attach_menu_lists_servers_under_their_folders(cx: &mut TestAppContext) { icon: None, flag: None, }; - let directory = Rc::new(Directory(std::cell::RefCell::new(vec![ + let directory = Rc::new(Directory::new(std::cell::RefCell::new(vec![ server("proxmox", Some("homelab")), server("backup", None), server("ai-server", Some("homelab")), diff --git a/crates/agent/src/panel/tests/composer/menu_stability.rs b/crates/agent/src/panel/tests/composer/menu_stability.rs index 56ae4c74..c1cda638 100644 --- a/crates/agent/src/panel/tests/composer/menu_stability.rs +++ b/crates/agent/src/panel/tests/composer/menu_stability.rs @@ -13,7 +13,7 @@ impl gpui_kit::Render for PanelHost { } fn many_servers(f: &Fixture, cx: &mut TestAppContext) -> Rc { - let directory = Rc::new(Directory(std::cell::RefCell::new( + let directory = Rc::new(Directory::new(std::cell::RefCell::new( (0..35) .map(|index| super::super::servers::summary(&format!("server-{index:02}"), None)) .collect(), diff --git a/crates/agent/src/panel/tests/invalidation.rs b/crates/agent/src/panel/tests/invalidation.rs index 1a067b00..3eec3b02 100644 --- a/crates/agent/src/panel/tests/invalidation.rs +++ b/crates/agent/src/panel/tests/invalidation.rs @@ -563,3 +563,103 @@ fn a_growing_draft_grows_the_cached_composer_below_the_transcript(cx: &mut TestA "the transcript gives way: {transcript:?} above {after:?}" ); } + +fn painted_thinking_tiles(f: &Fixture, cx: &mut TestAppContext) -> Vec { + cx.update_window(f.handle, |_, window, _| { + let scale = window.scale_factor(); + let indicator = window.find("agent-thinking").bounds(); + window + .painted_quads() + .into_iter() + .filter(|quad| { + let x = gpui_kit::px(quad.bounds.origin.x.0 / scale); + let y = gpui_kit::px(quad.bounds.origin.y.0 / scale); + indicator.contains(&gpui_kit::point(x, y)) + && (quad.bounds.size.width.0 / scale - 6.).abs() < 0.1 + && (quad.bounds.size.height.0 / scale - 6.).abs() < 0.1 + }) + .collect::>() + }) + .unwrap() +} + +fn advance_thinking_frame(f: &Fixture, cx: &mut TestAppContext, millis: u64) { + cx.executor() + .advance_clock(std::time::Duration::from_millis(millis)); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.draw(cx).clear(cx)) + .unwrap(); +} + +#[gpui_kit::test] +fn thinking_animation_does_not_rebuild_attachment_labels(cx: &mut TestAppContext) { + let f = fixture(cx); + let directory = Rc::new(Directory::new(Default::default())); + cx.update(|cx| { + f.workspace.update(cx, |workspace, _| { + workspace.set_connection_directory(directory.clone()); + }); + }); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| thread.send("Think".into(), cx)); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.activate_window(); + // Exclude the composer's independent 500ms cursor blink from the + // measurement; the visible thinking indicator does not require focus. + window.blur(cx); + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + }) + .unwrap(); + cx.run_until_parked(); + // Let the initial chat notifications and coalesced history update settle + // before counting steady-state animation work. + for _ in 0..4 { + advance_thinking_frame(&f, cx, 25); + } + let start = painted_thinking_tiles(&f, cx); + let before = directory.reads(); + for _ in 0..20 { + advance_thinking_frame(&f, cx, 25); + } + let reads = directory.reads() - before; + assert_eq!( + reads, 0, + "thinking animation must not rebuild attachment labels" + ); + let end = painted_thinking_tiles(&f, cx); + assert_eq!(start.len(), 3); + assert_eq!(end.len(), 3); + assert_ne!(start, end, "timed redraws must actually move the indicator"); + + cx.simulate_window_visibility_change(f.handle, gpui_kit::WindowVisibility::Hidden); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.draw(cx).clear(cx)) + .unwrap(); + let hidden = painted_thinking_tiles(&f, cx); + advance_thinking_frame(&f, cx, 200); + assert_eq!( + hidden, + painted_thinking_tiles(&f, cx), + "hidden animation rests" + ); + cx.simulate_window_visibility_change(f.handle, gpui_kit::WindowVisibility::Visible); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.draw(cx).clear(cx)) + .unwrap(); + let restored = painted_thinking_tiles(&f, cx); + advance_thinking_frame(&f, cx, 200); + assert_ne!( + restored, + painted_thinking_tiles(&f, cx), + "visible window must resume the loop" + ); + complete_active(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.draw(cx).clear(cx); + assert!(window.try_find("agent-thinking").is_none()); + }) + .unwrap(); +} diff --git a/crates/agent/src/panel/tests/mod.rs b/crates/agent/src/panel/tests/mod.rs index f64affe1..97095ce5 100644 --- a/crates/agent/src/panel/tests/mod.rs +++ b/crates/agent/src/panel/tests/mod.rs @@ -465,9 +465,21 @@ fn exchange(f: &Fixture, text: &str, answer: &str, cx: &mut TestAppContext) -> S session } -struct Directory(std::cell::RefCell>); +struct Directory( + std::cell::RefCell>, + std::cell::Cell, +); +impl Directory { + fn new(entries: std::cell::RefCell>) -> Self { + Self(entries, std::cell::Cell::new(0)) + } + fn reads(&self) -> usize { + self.1.get() + } +} impl nocterm_workspace::ConnectionDirectory for Directory { fn connections(&self, _: &App) -> Vec { + self.1.set(self.1.get() + 1); self.0.borrow().clone() } fn open( diff --git a/crates/agent/src/panel/tests/servers/menu.rs b/crates/agent/src/panel/tests/servers/menu.rs index 4104e52b..a30db28a 100644 --- a/crates/agent/src/panel/tests/servers/menu.rs +++ b/crates/agent/src/panel/tests/servers/menu.rs @@ -62,7 +62,7 @@ fn servers_with_the_same_display_name_keep_independent_attachment_choices(cx: &m db.name = "Same name".into(); cx.update(|cx| { f.workspace.update(cx, |workspace, _| { - workspace.set_connection_directory(Rc::new(Directory(RefCell::new(vec![web, db])))) + workspace.set_connection_directory(Rc::new(Directory::new(RefCell::new(vec![web, db])))) }) }); new_chat(&f, cx); diff --git a/crates/agent/src/panel/tests/tool_input.rs b/crates/agent/src/panel/tests/tool_input.rs index 119d46f0..ddab9146 100644 --- a/crates/agent/src/panel/tests/tool_input.rs +++ b/crates/agent/src/panel/tests/tool_input.rs @@ -594,7 +594,7 @@ fn verified_destination_uses_the_connected_host_and_survives_rename_detach_and_r icon: None, flag: None, }; - let directory = Rc::new(Directory(std::cell::RefCell::new(vec![summary]))); + let directory = Rc::new(Directory::new(std::cell::RefCell::new(vec![summary]))); cx.update(|cx| { f.workspace.update(cx, |workspace, _| { workspace.set_connection_directory(directory.clone()) diff --git a/crates/agent/src/panel/transcript.rs b/crates/agent/src/panel/transcript.rs index d5c6387f..58af3ab4 100644 --- a/crates/agent/src/panel/transcript.rs +++ b/crates/agent/src/panel/transcript.rs @@ -1,7 +1,7 @@ //! An open chat: the transcript, the plan, pending approvals, the status //! line and the composer. use gpui_kit::{ - AnyElement, SharedString, TestSupportExt as _, + AnyElement, TestSupportExt as _, component::{ActiveTheme as _, h_flex, v_flex}, div, prelude::*, @@ -70,18 +70,10 @@ impl TranscriptView { .text_color(cx.theme().muted_foreground) .when(live, |row| { row.child(div().id("agent-thinking").test_support().child( - nocterm_ui::thinking_indicator( - SharedString::from(format!("agent-thinking-{id}")), - cx.theme().foreground, - ), + nocterm_ui::thinking_indicator(("agent-thinking", id), cx.theme().foreground), )) }) - .child(activity_text( - SharedString::from(format!("agent-live-status-{id}")), - text, - live, - cx, - )) + .child(activity_text("agent-status-label", text, false, cx)) .into_any_element() } } diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index a46ff87a..c3e43bea 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -26,7 +26,6 @@ nocterm-design.workspace = true nocterm-settings.workspace = true gpui-kit.workspace = true -image = { version = "0.25", default-features = false, features = ["webp"] } schemars.workspace = true serde_json.workspace = true serde.workspace = true diff --git a/crates/ui/assets/animations/thinking.webp b/crates/ui/assets/animations/thinking.webp deleted file mode 100644 index cc3b9d0f00a90c279d6a8d10c423515928704ad1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9630 zcmd^_cTkhvw#Jjti}YTkH<6}vkPZ^*NCyFFiV~_6MI>|tq&MlkNL3_s2u(nwC?H)x zk)qO(ZgSs*!*`Eo?wz^+-*hp&A;gJRp#%x{AJuzO)%J2n3=6 zenqf9%DPY;eBjmjqpYi=K?uHhb^Z=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*y}IWC92Q z$#g-8=_Y`OOhjRf&EPIt@2CEa@|-`fqPXThBdXL6pOu50qghm7?;pe`L;88LUXqEQ z$%4PUIBT-4ld2sJ9aG|OHWz&`uG!le!dEkRoh2DBv@2NCIWlvc)7XrCHLhy{Gi3#wHFeLkfeBMpc-w>W9 z9pqwW`nJNTfV3f%6qjKrlfaZrQ=xPXOJ&)n^Nq z?%&;?Xe|;BEhmYJyPOP@pI7WqM4ncL^bey9LNAwq%^43q7@FxJas8y0e>IvKqe6Q%U{vBP+*O$Z{CfKM z_?_R+V-hv0VZl3Daf<+3(7vQqj|5p3o-*#>`)J0@yRX6dhI?Gc;kgB#uNDWa=>3C@ zxi~fkhxWwWn%Ea@lhd;*bz4wOwAjq`oM#RYQUKe(Ip>w#Kw&YStJaN;FhT#3bJ`a5+UC#JmDUf=+Rl z9o+Zm8s9XXXz}2FeJ5Am5Zq-noh_wdOhTHjy^Lz9(T*3L8SHc0ODPe7BMnZToNl#h zQHsY`2OJtbycf(6CyMOAsV&%cFUPq` zP+kWzQ}#29CQTA0B5YRvbqfO|=U4CrNePC80qbR9^dZJ?6kPmc0drOht(ZZi5c@_j zF-2aRfiP(j;^$HYbvB&t`SK#^@kB;9U&(pcRTuaJA0xoZ%mG yIurU;h3S%zj=7K+ad9e0um+U&g-^woX@rGr$&Z&|`ucx, color: Hsla) -> impl IntoElement { - let tint = Tint::from(color); - let source = ImageSource::Custom(Arc::new(move |window, cx: &mut App| { - window.use_asset::(&tint, cx) - })); - gpui_kit::img(source).id(id).flex_shrink_0().size(px(16.)) + ThinkingIndicator { + id: id.into(), + color, + } } -/// A colour as straight 8-bit BGRA, the image cache's pixel layout. -#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] -struct Tint([u8; 4]); +#[derive(IntoElement)] +struct ThinkingIndicator { + id: ElementId, + color: Hsla, +} -impl From for Tint { - fn from(color: Hsla) -> Self { - let rgba = color.to_rgb(); - let byte = |channel: f32| (channel.clamp(0., 1.) * 255.).round() as u8; - Self([byte(rgba.b), byte(rgba.g), byte(rgba.r), byte(rgba.a)]) +impl RenderOnce for ThinkingIndicator { + fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement { + let frame = ThinkingFrame { + phase: 0., + color: self.color, + }; + // An unfocused but visible window still plays. The toolkit respects the + // OS reduce-motion preference, and its timed wake belongs to the drawn view. + if window.is_visible() { + frame + .with_animation( + self.id, + Animation::new(CYCLE) + .repeat_synced() + .with_max_fps(UPDATES_PER_SECOND), + |mut frame, phase| { + frame.phase = phase; + frame + }, + ) + .into_any_element() + } else { + frame.into_any_element() + } } } -/// The thinking animation tinted to one colour. -enum ThinkingAnimation {} - -impl Asset for ThinkingAnimation { - type Source = Tint; - type Output = Result, ImageCacheError>; - - #[expect( - clippy::manual_async_fn, - reason = "an `async fn` future would borrow `App`, which is neither `Send` nor `'static`" - )] - fn load( - tint: Self::Source, - _: &mut App, - ) -> impl Future + Send + 'static { - async move { tinted(THINKING, tint).map(Arc::new) } - } +#[derive(IntoElement)] +struct ThinkingFrame { + phase: f32, + color: Hsla, } -/// Decodes the animated mask `bytes` with every pixel painted `tint`, -/// keeping the mask's coverage as alpha. -fn tinted(bytes: &[u8], tint: Tint) -> Result { - let mut decoder = WebPDecoder::new(Cursor::new(bytes)).map_err(image_error)?; - decoder - .set_background_color(Rgba([0, 0, 0, 0])) - .map_err(image_error)?; - let [b, g, r, a] = tint.0; - let mut frames = Vec::new(); - for frame in decoder.into_frames() { - let mut frame = frame.map_err(image_error)?; - for pixel in frame.buffer_mut().as_chunks_mut::<4>().0 { - let coverage = u16::from(pixel[3]) * u16::from(a) / 255; - *pixel = [b, g, r, coverage as u8]; - } - frames.push(frame); +impl RenderOnce for ThinkingFrame { + fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, (), window, _| { + for [x, y] in tiles(self.phase) { + window.paint_quad(quad( + Bounds::new(bounds.origin + point(px(x), px(y)), size(px(6.), px(6.))), + px(1.25), + self.color, + Edges::default(), + transparent_black(), + BorderStyle::default(), + )); + } + }, + ) + .size(px(16.)) + .flex_shrink_0() } - Ok(RenderImage::new(frames)) } -fn image_error(error: image::ImageError) -> ImageCacheError { - ImageCacheError::Image(Arc::new(error)) +/// A smoothstep gives each tile zero velocity at its endpoints. Consecutive +/// segments describe exactly the same occupied corners at the seam. +fn tiles(phase: f32) -> [[f32; 2]; 3] { + let step = phase.rem_euclid(1.) * 4.; + let gap = step.floor() as usize; + let next = (gap + 1) % 4; + let t = step.fract(); + let t = t * t * (3. - 2. * t); + let moving = std::array::from_fn(|axis| { + POSITIONS[next][axis] + (POSITIONS[gap][axis] - POSITIONS[next][axis]) * t + }); + [moving, POSITIONS[(gap + 2) % 4], POSITIONS[(gap + 3) % 4]] } #[cfg(test)] mod tests { - use super::{THINKING, Tint, tinted}; + use super::*; + use gpui_kit::{AppContext as _, Context, Render, TestAppContext, WindowHandle, div}; + + fn same_tiles(left: [[f32; 2]; 3], right: [[f32; 2]; 3]) -> bool { + left.iter().all(|a| { + right + .iter() + .any(|b| (a[0] - b[0]).abs() < 0.001 && (a[1] - b[1]).abs() < 0.001) + }) + } #[test] - fn thinking_indicator_animates_in_the_requested_colour() { - let black = tinted(THINKING, Tint::from(gpui_kit::black())).unwrap(); - assert!(black.frame_count() > 1); - let pixels = black.as_bytes(0).unwrap().as_chunks::<4>().0.iter(); - assert!(pixels.clone().any(|pixel| pixel[3] > 0)); - assert!(pixels.clone().any(|pixel| pixel[3] == 0)); - assert!(pixels.clone().all(|pixel| pixel[..3] == [0, 0, 0])); + fn thinking_tiles_are_continuous_at_every_corner_and_loop_seam() { + for boundary in [0.25, 0.5, 0.75, 1.] { + assert!(same_tiles(tiles(boundary - 0.0001), tiles(boundary))); + assert!(same_tiles(tiles(boundary), tiles(boundary + 0.0001))); + } + assert!(same_tiles(tiles(0.), tiles(1.))); + assert!(!same_tiles(tiles(0.), tiles(0.125))); + for index in 0..1600 { + let positions = tiles(index as f32 / 1600.); + for [x, y] in positions { + assert!((1.5..=8.5).contains(&x)); + assert!((1.5..=8.5).contains(&y)); + } + } + } + + struct Preview(bool); + impl Render for Preview { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + use gpui_kit::ParentElement as _; + div().children( + self.0 + .then(|| thinking_indicator("thinking", gpui_kit::white())), + ) + } + } + + fn painted(window: WindowHandle, cx: &mut TestAppContext) -> Vec { + cx.update_window(window.into(), |_, window, cx| { + window.draw(cx).clear(cx); + window.painted_quads() + }) + .unwrap() + } - let white = tinted(THINKING, Tint::from(gpui_kit::white())).unwrap(); - let pixels = white.as_bytes(0).unwrap().as_chunks::<4>().0.iter(); - assert!(pixels.clone().all(|pixel| pixel[..3] == [255, 255, 255])); + #[gpui_kit::test] + fn thinking_indicator_paints_three_quads_and_loops_without_focus(cx: &mut TestAppContext) { + let window = cx.open_window(size(px(100.), px(100.)), |_, _| Preview(true)); + cx.run_until_parked(); + window + .update(cx, |_, window, _| assert!(!window.is_window_active())) + .unwrap(); + let start = painted(window, cx); + assert_eq!(start.len(), 3); + cx.executor().advance_clock(Duration::from_millis(200)); + cx.run_until_parked(); + let middle = painted(window, cx); + assert_eq!(middle.len(), 3); + assert_ne!( + start, middle, + "visible window must animate without relying on OS focus" + ); + // A delayed draw is immediately back at the matching cycle phase. + cx.executor().advance_clock(CYCLE); + cx.run_until_parked(); + assert_eq!(painted(window, cx), middle); + cx.update(|cx| cx.set_reduce_motion(true)); + cx.run_until_parked(); + let static_frame = painted(window, cx); + cx.executor().advance_clock(Duration::from_millis(200)); + cx.run_until_parked(); + assert_eq!(painted(window, cx), static_frame); + window + .update(cx, |view, _, cx| { + view.0 = false; + cx.notify(); + }) + .unwrap(); + cx.run_until_parked(); + assert!(painted(window, cx).is_empty()); } } diff --git a/docs/architecture/feature.md b/docs/architecture/feature.md index 40293fcb..1acf80f4 100644 --- a/docs/architecture/feature.md +++ b/docs/architecture/feature.md @@ -741,9 +741,13 @@ each agent message's and expanded reasoning's parsed Markdown per row, so a row scrolled back into view keeps its parse. The chat document's transcript generation marks replacements. Within one generation, stream updates and reveal ticks let the row sanitize and parse just the appended text, unless an image marker crosses the -chunk boundary. PanelLayout keeps the panel's regions as cached views: the transcript, the -history and the footer (approvals, status, queue, commands and composer), which is -cached to its content and keeps its last height while reused. Any panel notify +chunk boundary. PanelLayout keeps separate views for the transcript, history, +approvals, status and footer (queue, commands and composer). The approval and +footer regions are cached to their content and retain their last +height while reused. The status stays live so its layout-time animation wake is +not discarded by content-sized replay. The thinking indicator paints three +time-based rounded quads; its paced redraw invalidates only the status region, +without rebuilding the composer or its attachment index. Any panel notify redraws every region; a change of the open chat redraws the transcript only when its rows or what they show changed, typing redraws the footer, and the coalesced redraw of other chats redraws the history only