Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions crates/agent/src/panel/composer_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ use super::{
};
use crate::thread::{AgentThread, config_label};

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<AgentPanel>) -> Button {
Button::new(("remove-image", index))
.ghost()
Expand Down Expand Up @@ -389,6 +397,17 @@ impl ComposerRenderer {
.into_any_element(),
);
}
if codex_goal_mode_notice(thread.read(cx)) {
notices.push(
div()
.id("codex-goal-mode-notice")
.test_support()
.text_xs()
.text_color(cx.theme().muted_foreground)
.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(),
);
}
if thread.read(cx).ended() && !thread.read(cx).session_generating() {
notices.push(
Button::new("agent-restart")
Expand Down
15 changes: 14 additions & 1 deletion crates/agent/src/panel/entries/tool_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -91,6 +91,19 @@ pub(in crate::panel) fn source(call: &ToolRecord, redact: bool) -> Option<Output
.map(|display| display.tool.as_ref())
.or_else(|| tool_display::fallback_tool(call));
let mut output = provider_output(call, tool);
if tool.is_some()
&& call.status == ToolStatus::Failed
&& call
.raw_output
.as_ref()
.and_then(|raw| raw["error"]["message"].as_str())
== Some("MCP tool call requires approval, but approval policy is never")
{
output.append(Output::plain(
"Codex approval mode",
"Codex refused this request before it reached Nocterm because its effective approval policy is never. The displayed mode can differ from the effective mode, especially with /goal. Stop the goal, select Workspace access and send a regular message before resuming. Nocterm terminal permissions still apply.".into(),
));
}
if output.sections.is_empty() {
return None;
}
Expand Down
52 changes: 52 additions & 0 deletions crates/agent/src/panel/tests/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,58 @@ fn commands(f: &Fixture, values: Vec<AvailableCommand>, 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);
Expand Down
47 changes: 46 additions & 1 deletion crates/agent/src/panel/tests/tool_sections.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::tool_output::exec_result;
use crate::panel::entries::{tool_input, tool_output};
use nocterm_ai::model::tools::ToolRecord;
use nocterm_ai::model::tools::{ToolRecord, ToolStatus};
use nocterm_ai::tool_display;
use serde_json::json;

Expand Down Expand Up @@ -78,3 +78,48 @@ fn explicit_registered_envelopes_work_without_a_provider_name() {
assert!(tool_display::requested_arguments(&foreign).is_none());
assert!(tool_display::header(&foreign).starts_with("Tool call"));
}

#[test]
fn codex_approval_policy_failure_explains_the_provider_gate() {
let error = "MCP tool call requires approval, but approval policy is never";
let call = ToolRecord::new("denied", "nocterm-26: exec_command")
.status(ToolStatus::Failed)
.raw_input(json!({"server":"nocterm-26","tool":"exec_command","arguments":{"terminal_id":"t5","program":"pwd","args":[],"yield_ms":1000}}))
.raw_output(json!({"result":null,"error":{"message":error}}));
let output = tool_output::source(&call, false).unwrap();
assert!(
output
.sections
.iter()
.any(|section| section.text.contains(error))
);
let help = output
.sections
.iter()
.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")
);

for unrelated in [
call.clone()
.raw_input(json!({"server":"external","tool":"exec_command","arguments":{}})),
call.clone()
.raw_output(json!({"error":{"message":"Vault is locked"}})),
call.status(ToolStatus::Succeeded),
] {
assert!(
!tool_output::source(&unrelated, false)
.unwrap()
.sections
.iter()
.any(|section| section.label == "Codex approval mode")
);
}
}
2 changes: 1 addition & 1 deletion crates/ai/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}}))
}
Expand Down
41 changes: 22 additions & 19 deletions crates/ai/src/tools/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TerminalCall>,
Expand Down Expand Up @@ -50,14 +52,15 @@ 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 {
name: $name,
label: $label,
group: ToolGroup::$group,
description: $description,
read_only: $read_only,
schema: catalog!(@schema $($arguments)?),
parse: catalog!(@parse $variant $($arguments)?),
},)*];
Expand Down Expand Up @@ -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";
}

Expand Down
26 changes: 26 additions & 0 deletions crates/ai/src/tools/catalog/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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| {
Expand Down
Loading
Loading