Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(macrod): offer Always allow on native Herdr permission prompts (#9022)

Wolf Mermelstein17c83198e3d4
diff --git a/Cargo.lock b/Cargo.lock
index 81a50ebf9b..26da356b26 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4585,6 +4585,7 @@ dependencies = [
"futures",
"harness_id",
"harnesses",
+ "lazy-regex",
"macro_env_var",
"macro_event_broker",
"macro_user_id",
diff --git a/apps/web/src/features/agent-interactions/components/PermissionOptions.tsx b/apps/web/src/features/agent-interactions/components/PermissionOptions.tsx
index 98081c5c07..56015d39a2 100644
--- a/apps/web/src/features/agent-interactions/components/PermissionOptions.tsx
+++ b/apps/web/src/features/agent-interactions/components/PermissionOptions.tsx
@@ -1,6 +1,7 @@
/**
- * One-time decisions stay close at hand. Additional choices retain the
- * agent's full wording in a menu so remembered rules can be read before use.
+ * Deny, Always allow, and Allow once stay close at hand. Additional choices
+ * retain the agent's full wording in a menu so remembered rules can be read
+ * before use; Always allow shows its wording as a tooltip.
*/
import CaretDown from '@icon/system/regular/caret-down.svg';
@@ -35,10 +36,14 @@ export function PermissionOptions(props: PermissionOptionsProps) {
return options.length === 1 ? options[0] : undefined;
};
const allow = () => unique('allow_once');
+ const always = () => unique('allow_always');
const deny = () => unique('reject_once');
const more = () =>
props.options.filter(
- (option) => option.id !== allow()?.id && option.id !== deny()?.id
+ (option) =>
+ option.id !== allow()?.id &&
+ option.id !== always()?.id &&
+ option.id !== deny()?.id
);
return (
@@ -91,6 +96,20 @@ export function PermissionOptions(props: PermissionOptionsProps) {
</Dropdown.Content>
</Dropdown>
</Show>
+ <Show when={always()}>
+ {(option) => (
+ <Button
+ type="button"
+ size="md"
+ variant="outline"
+ tooltip={option().name}
+ disabled={props.disabled}
+ onClick={() => props.onSelect(option().id)}
+ >
+ Always allow
+ </Button>
+ )}
+ </Show>
<Show when={allow()}>
{(option) => (
<Button
@@ -112,7 +131,7 @@ export function PermissionOptions(props: PermissionOptionsProps) {
function permissionOptionLabel(kind: PermissionOptionKind): string {
return match(kind)
.with('allow_once', () => 'Allow once')
- .with('allow_always', () => 'Remember approval')
+ .with('allow_always', () => 'Always allow')
.with('reject_once', () => 'Deny')
.with('reject_always', () => 'Remember denial')
.exhaustive();
diff --git a/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx b/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx
index 5545d89808..992fcef835 100644
--- a/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx
@@ -25,7 +25,7 @@ export function PermissionPart(props: {
if (!chosen) return 'Answered';
return match(chosen.kind)
.with('allow_once', () => 'Allowed once')
- .with('allow_always', () => 'Approval remembered')
+ .with('allow_always', () => 'Always allowed')
.with('reject_once', () => 'Denied')
.with('reject_always', () => 'Denial remembered')
.exhaustive();
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 07d7a22bd4..d4dc9c5095 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -4,6 +4,7 @@
* `/component/agent-ui`.
*/
+import { PermissionCard } from '@app/features/agent-interactions/components/PermissionCard';
import {
initialValues,
validate,
@@ -1162,6 +1163,24 @@ export default function AgentUiGallery() {
/>
</Item>
+ <Item label="PermissionCard (native Herdr session)">
+ <PermissionCard
+ action="Run command"
+ detail="cargo test -p coding_agent_worker"
+ options={[
+ { id: 'allow', name: 'Allow once', kind: 'allow_once' },
+ {
+ id: 'always',
+ name: 'Always allow `cargo test -p coding_agent_worker` in this session',
+ kind: 'allow_always',
+ },
+ { id: 'reject', name: 'Reject', kind: 'reject_once' },
+ ]}
+ canAnswer
+ onSelect={() => {}}
+ />
+ </Item>
+
<Item label="ComposerNotice">
<ComposerNotice text="Waking the agent's sandbox…" active />
</Item>
diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.toml
index 1e40312f67..34b33d1474 100644
--- a/crates/coding_agent_worker/Cargo.toml
+++ b/crates/coding_agent_worker/Cargo.toml
@@ -31,6 +31,7 @@ eventsource-stream = { workspace = true }
futures = { workspace = true }
harness_id = { path = "../harness_id" }
harnesses = { path = "../harnesses", default-features = false }
+lazy-regex = { workspace = true }
macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_env_var = { path = "../macro_env_var" }
macro_user_id = { path = "../macro_user_id" }
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.md
index 78de9c1205..2df084af7e 100644
--- a/crates/coding_agent_worker/README.md
+++ b/crates/coding_agent_worker/README.md
@@ -79,6 +79,14 @@ visible dialog, and the same Herdr state generation. Sign-in prompts and other
unknown dialogs require native interaction. Herdr does not offer an atomic
compare-and-send-key operation, so native interaction remains the authority.
+Macro offers **Always allow** next to **Allow once**. When the dialog shows its
+own "Yes, and don't ask again ..." answer with a known shortcut, Always allow
+presses it and the native agent keeps the rule. Otherwise macrod approves the
+dialog and remembers the tool for the rest of the session: Claude Code's tool
+name (such as `Bash`) or Codex's exact command. Later dialogs for it are
+approved without asking Macro. These standing approvals live in macrod's memory
+and end when macrod restarts.
+
Macro supplies the session's configured MCP connections when macrod binds it:
owner-connection sessions include enabled connected apps and custom MCP servers;
explicit agent selections retain their selected apps. All connections use the
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rs
index cf54f6a426..479850d44e 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs
@@ -12,7 +12,8 @@
//! - the agent's own session transcript is tailed and streamed back as
//! `session/update`s, and its end-of-turn record ends the turn;
//! - a permission dialog in the TUI becomes a `session/request_permission`,
-//! answered by pressing the matching key; `session/cancel` presses Esc.
+//! answered by pressing the matching key (see `permission`);
+//! `session/cancel` presses Esc.
//!
//! Anyone watching the herdr window can also type into the TUI directly.
@@ -39,6 +40,11 @@ use codex_fold::CodexLog;
mod commands;
mod effort;
mod models;
+mod permission;
+
+#[cfg(test)]
+use permission::permission_title;
+use permission::{OpenTool, track_open_tool};
/// The subcommand macrod's harness config names to run this adapter.
pub(crate) const SUBCOMMAND: &str = "herdr-acp";
@@ -294,6 +300,9 @@ struct Session {
prompt_pending: AtomicBool,
live: tokio::sync::Mutex<Option<Live>>,
cancel: Mutex<Option<CancellationToken>>,
+ /// Tools a user in Macro chose to always allow for this session, where
+ /// the native dialog had no "don't ask again" answer of its own.
+ always_allowed: Mutex<std::collections::HashSet<String>>,
}
struct PermissionEpoch(Arc<AtomicU64>);
@@ -481,6 +490,7 @@ impl Adapter {
prompt_pending: AtomicBool::new(false),
live: tokio::sync::Mutex::new(None),
cancel: Mutex::new(None),
+ always_allowed: Mutex::new(std::collections::HashSet::new()),
});
self.save(&session, None)?;
lock(&self.sessions).insert(id.clone(), session.clone());
@@ -563,6 +573,7 @@ impl Adapter {
prompt_pending: AtomicBool::new(false),
live: tokio::sync::Mutex::new(None),
cancel: Mutex::new(None),
+ always_allowed: Mutex::new(std::collections::HashSet::new()),
});
// ACP load stages this complete history until our successful response.
loop {
@@ -872,7 +883,7 @@ impl Adapter {
let mut settled = 0u32;
let mut missing = 0u32;
let mut active = false;
- let mut open_tool: Option<(String, String)> = None;
+ let mut open_tool: Option<OpenTool> = None;
// Bumped whenever a dialog is asked about or goes away, so a late
// answer from Macro never presses keys into a different dialog.
let generation = Arc::new(AtomicU64::new(0));
@@ -977,7 +988,7 @@ impl Adapter {
&self,
session: &Session,
live: &mut Live,
- open_tool: &mut Option<(String, String)>,
+ open_tool: &mut Option<OpenTool>,
) -> Result<(bool, Option<&'static str>), RpcError> {
let mut moved = false;
let mut ended = None;
@@ -1008,94 +1019,6 @@ impl Adapter {
Ok((moved, ended))
}
- /// Ask Macro about the TUI's permission dialog, then press the key for
- /// the answer - unless the dialog was already answered in the window.
- fn ask_permission(
- self: &Arc<Self>,
- session: &Arc<Session>,
- live: &Live,
- tool: Option<(String, String)>,
- generation: u64,
- blocked: &Arc<AtomicU64>,
- ) {
- let Some(herdr) = self.herdr.clone() else {
- return;
- };
- let adapter = self.clone();
- let session_id = session.id.clone();
- let name = live.name.clone();
- let blocked = blocked.clone();
- let kind = self.options.kind;
- tokio::spawn(async move {
- let Ok(before) = herdr.agent_info(&name).await else {
- return;
- };
- let Ok(screen) = herdr.read_agent(&name).await else {
- return;
- };
- let Some(approve_key) = super::controls::approve_key(kind, &screen) else {
- adapter.notify_update(&session_id, json!({"sessionUpdate":"agent_message_chunk", "content":{"type":"text", "text":"The native agent needs input in Herdr."}}));
- return;
- };
- if before.status != "blocked" {
- return;
- }
- let (tool_id, title) = match tool {
- Some(tool) => tool,
- None => (
- format!("herdr-permission-{generation}"),
- permission_title(kind, &screen),
- ),
- };
- let answer = adapter
- .call(
- "session/request_permission",
- json!({
- "sessionId": session_id,
- "toolCall": {"toolCallId": tool_id, "title": title, "status": "pending"},
- "options": [
- {"optionId": "allow", "name": "Allow", "kind": "allow_once"},
- {"optionId": "reject", "name": "Reject", "kind": "reject_once"},
- ],
- }),
- )
- .await;
- if blocked.load(Ordering::SeqCst) != generation {
- return;
- }
- let Ok(after) = herdr.agent_info(&name).await else {
- return;
- };
- let Ok(current_screen) = herdr.read_agent(&name).await else {
- return;
- };
- if !super::controls::same_dialog(
- &screen,
- &current_screen,
- before.state_change_seq,
- after.state_change_seq,
- &after.status,
- ) {
- return;
- }
- let key = match answer
- .as_ref()
- .and_then(|answer| answer.pointer("/result/outcome/optionId"))
- .and_then(Value::as_str)
- {
- Some("allow") => approve_key,
- Some("reject") => "esc",
- _ => return,
- };
- if blocked.load(Ordering::SeqCst) != generation {
- return;
- }
- if let Err(error) = herdr.send_keys(&name, &[key]).await {
- tracing::warn!(error = %error, "could not answer the agent's permission dialog");
- }
- });
- }
-
/// Where the agent writes the session's transcript, once it exists.
/// Claude Code names it after the id this adapter gave it; Codex mints
/// its own id, which herdr reports once the session is live.
@@ -1133,56 +1056,6 @@ impl Adapter {
}
}
-/// What a permission dialog on the agent's screen is asking about.
-pub(crate) fn permission_title(kind: TuiAgent, screen: &str) -> String {
- let lines: Vec<&str> = screen.lines().map(str::trim).collect();
- let asked = lines
- .iter()
- .rposition(|line| line.starts_with("Would you like to"))
- .map(|index| (lines[index], &lines[index + 1..]));
- if let Some((question, rest)) = asked {
- if let Some(command) = rest.iter().find_map(|line| line.strip_prefix("$ ")) {
- return format!("Run {}", clip_title(command));
- }
- if question.contains("edit") {
- return "Edit files".to_owned();
- }
- if let Some(reason) = rest.iter().find_map(|line| line.strip_prefix("Reason: ")) {
- return clip_title(reason);
- }
- }
- match kind {
- TuiAgent::Claude => "Claude Code is asking for permission".to_owned(),
- TuiAgent::Codex => "Codex is asking for permission".to_owned(),
- }
-}
-
-fn clip_title(text: &str) -> String {
- const LIMIT: usize = 80;
- let mut clipped: String = text.chars().take(LIMIT).collect();
- if text.chars().count() > LIMIT {
- clipped.push('…');
- }
- clipped
-}
-
-fn track_open_tool(open_tool: &mut Option<(String, String)>, update: &Value) {
- let id = update.get("toolCallId").and_then(Value::as_str);
- match update.get("sessionUpdate").and_then(Value::as_str) {
- Some("tool_call") => {
- let title = update
- .get("title")
- .and_then(Value::as_str)
- .unwrap_or_default();
- *open_tool = id.map(|id| (id.to_owned(), title.to_owned()));
- }
- Some("tool_call_update") if open_tool.as_ref().map(|(open, _)| open.as_str()) == id => {
- *open_tool = None;
- }
- _ => {}
- }
-}
-
/// A herdr agent name for the session: `[a-z][a-z0-9_-]{0,31}`.
pub(crate) fn agent_name(session: &str) -> String {
let short: String = session
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/permission.rs b/crates/coding_agent_worker/src/herdr/acp_agent/permission.rs
new file mode 100644
index 0000000000..71a48a7f04
--- /dev/null
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/permission.rs
@@ -0,0 +1,263 @@
+//! Native permission dialogs answered from Macro. "Always allow" presses the
+//! dialog's own "don't ask again" answer when it shows one; otherwise this
+//! session remembers the tool and answers its later dialogs itself.
+
+use super::super::controls::{self, NativeAlways};
+use super::*;
+
+const ALLOW: &str = "allow";
+const ALWAYS: &str = "always";
+const REJECT: &str = "reject";
+
+/// The tool call the agent's transcript shows running, which a permission
+/// dialog is about.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) struct OpenTool {
+ pub id: String,
+ pub title: String,
+ /// The agent's own tool name, such as `Bash`.
+ pub name: Option<String>,
+}
+
+/// How "Always allow" is carried out for one dialog.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Always {
+ /// Press the dialog's own answer; the agent remembers it.
+ Native(NativeAlways),
+ /// Approve, and auto-approve this tool's later dialogs in the session.
+ Standing { tool: String, name: String },
+}
+
+impl Always {
+ fn for_dialog(kind: TuiAgent, tool: Option<&OpenTool>, screen: &str) -> Option<Self> {
+ if let Some(native) = controls::always_choice(kind, screen) {
+ return Some(Self::Native(native));
+ }
+ standing_tool(kind, tool, screen).map(|(tool, shown)| Self::Standing {
+ tool,
+ name: format!("Always allow {shown} in this session"),
+ })
+ }
+
+ fn name(&self) -> &str {
+ match self {
+ Self::Native(native) => &native.name,
+ Self::Standing { name, .. } => name,
+ }
+ }
+}
+
+/// What a standing approval covers, and how to show it: Claude Code names
+/// the tool in its transcript; Codex shows the command on screen.
+fn standing_tool(
+ kind: TuiAgent,
+ tool: Option<&OpenTool>,
+ screen: &str,
+) -> Option<(String, String)> {
+ match kind {
+ TuiAgent::Claude => tool
+ .and_then(|tool| tool.name.clone())
+ .map(|name| (name.clone(), name)),
+ TuiAgent::Codex => dialog_command(screen)
+ .map(|command| (command.to_owned(), format!("`{}`", clip_title(command)))),
+ }
+}
+
+/// The options Macro offers for one dialog.
+fn permission_options(always: Option<&Always>) -> Value {
+ let mut options = vec![json!({"optionId": ALLOW, "name": "Allow once", "kind": "allow_once"})];
+ if let Some(always) = always {
+ options.push(json!({"optionId": ALWAYS, "name": always.name(), "kind": "allow_always"}));
+ }
+ options.push(json!({"optionId": REJECT, "name": "Reject", "kind": "reject_once"}));
+ Value::Array(options)
+}
+
+impl Adapter {
+ /// Ask Macro about the TUI's permission dialog, then press the key for
+ /// the answer - unless the dialog was already answered in the window.
+ /// A tool the session always allows is approved without asking.
+ pub(super) fn ask_permission(
+ self: &Arc<Self>,
+ session: &Arc<Session>,
+ live: &Live,
+ tool: Option<OpenTool>,
+ generation: u64,
+ blocked: &Arc<AtomicU64>,
+ ) {
+ let adapter = self.clone();
+ let session = session.clone();
+ let name = live.name.clone();
+ let blocked = blocked.clone();
+ tokio::spawn(async move {
+ adapter
+ .answer_permission(&session, &name, tool, generation, &blocked)
+ .await;
+ });
+ }
+
+ async fn answer_permission(
+ &self,
+ session: &Session,
+ name: &str,
+ tool: Option<OpenTool>,
+ generation: u64,
+ blocked: &AtomicU64,
+ ) {
+ let Some(herdr) = &self.herdr else {
+ return;
+ };
+ let kind = self.options.kind;
+ let Ok(before) = herdr.agent_info(name).await else {
+ return;
+ };
+ let Ok(screen) = herdr.read_agent(name).await else {
+ return;
+ };
+ let Some(approve_key) = controls::approve_key(kind, &screen) else {
+ self.notify_update(&session.id, json!({"sessionUpdate":"agent_message_chunk", "content":{"type":"text", "text":"The native agent needs input in Herdr."}}));
+ return;
+ };
+ if before.status != "blocked" {
+ return;
+ }
+ let always = Always::for_dialog(kind, tool.as_ref(), &screen);
+ let standing = match &always {
+ Some(Always::Standing { tool, .. }) => lock(&session.always_allowed).contains(tool),
+ _ => false,
+ };
+ let choice = if standing {
+ tracing::info!(session_id = %session.id, "native permission dialog approved by a standing approval");
+ Some(ALLOW.to_owned())
+ } else {
+ let (tool_id, title) = match &tool {
+ Some(tool) => (tool.id.clone(), tool.title.clone()),
+ None => (
+ format!("herdr-permission-{generation}"),
+ permission_title(kind, &screen),
+ ),
+ };
+ self.call(
+ "session/request_permission",
+ json!({
+ "sessionId": session.id,
+ "toolCall": {"toolCallId": tool_id, "title": title, "status": "pending"},
+ "options": permission_options(always.as_ref()),
+ }),
+ )
+ .await
+ .as_ref()
+ .and_then(|answer| answer.pointer("/result/outcome/optionId"))
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ };
+ if blocked.load(Ordering::SeqCst) != generation {
+ return;
+ }
+ let Ok(after) = herdr.agent_info(name).await else {
+ return;
+ };
+ let Ok(current_screen) = herdr.read_agent(name).await else {
+ return;
+ };
+ if !controls::same_dialog(
+ &screen,
+ &current_screen,
+ before.state_change_seq,
+ after.state_change_seq,
+ &after.status,
+ ) {
+ return;
+ }
+ let (key, remember) = match (choice.as_deref(), always) {
+ (Some(ALLOW), _) => (approve_key.to_owned(), None),
+ (Some(ALWAYS), Some(Always::Native(native))) => (native.key, None),
+ (Some(ALWAYS), Some(Always::Standing { tool, .. })) => {
+ (approve_key.to_owned(), Some(tool))
+ }
+ (Some(REJECT), _) => ("esc".to_owned(), None),
+ _ => return,
+ };
+ if blocked.load(Ordering::SeqCst) != generation {
+ return;
+ }
+ if let Err(error) = herdr.send_keys(name, &[&key]).await {
+ tracing::warn!(error = %error, "could not answer the agent's permission dialog");
+ return;
+ }
+ if let Some(tool) = remember {
+ lock(&session.always_allowed).insert(tool);
+ }
+ }
+}
+
+/// The command a Codex dialog asks to run.
+fn dialog_command(screen: &str) -> Option<&str> {
+ let lines: Vec<&str> = screen.lines().map(str::trim).collect();
+ let question = lines
+ .iter()
+ .rposition(|line| line.starts_with("Would you like to"))?;
+ lines[question + 1..]
+ .iter()
+ .find_map(|line| line.strip_prefix("$ "))
+}
+
+/// What a permission dialog on the agent's screen is asking about.
+pub(super) fn permission_title(kind: TuiAgent, screen: &str) -> String {
+ let lines: Vec<&str> = screen.lines().map(str::trim).collect();
+ let asked = lines
+ .iter()
+ .rposition(|line| line.starts_with("Would you like to"))
+ .map(|index| (lines[index], &lines[index + 1..]));
+ if let Some((question, rest)) = asked {
+ if let Some(command) = dialog_command(screen) {
+ return format!("Run {}", clip_title(command));
+ }
+ if question.contains("edit") {
+ return "Edit files".to_owned();
+ }
+ if let Some(reason) = rest.iter().find_map(|line| line.strip_prefix("Reason: ")) {
+ return clip_title(reason);
+ }
+ }
+ match kind {
+ TuiAgent::Claude => "Claude Code is asking for permission".to_owned(),
+ TuiAgent::Codex => "Codex is asking for permission".to_owned(),
+ }
+}
+
+fn clip_title(text: &str) -> String {
+ const LIMIT: usize = 80;
+ let mut clipped: String = text.chars().take(LIMIT).collect();
+ if text.chars().count() > LIMIT {
+ clipped.push('…');
+ }
+ clipped
+}
+
+pub(super) fn track_open_tool(open_tool: &mut Option<OpenTool>, update: &Value) {
+ let id = update.get("toolCallId").and_then(Value::as_str);
+ match update.get("sessionUpdate").and_then(Value::as_str) {
+ Some("tool_call") => {
+ *open_tool = id.map(|id| OpenTool {
+ id: id.to_owned(),
+ title: update
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_owned(),
+ name: update
+ .pointer("/_meta/claudeCode/toolName")
+ .and_then(Value::as_str)
+ .map(str::to_owned),
+ });
+ }
+ Some("tool_call_update") if open_tool.as_ref().map(|open| open.id.as_str()) == id => {
+ *open_tool = None;
+ }
+ _ => {}
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/permission/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/permission/test.rs
new file mode 100644
index 0000000000..5419472b7d
--- /dev/null
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/permission/test.rs
@@ -0,0 +1,184 @@
+use std::os::unix::fs::PermissionsExt as _;
+
+use super::super::test::test_adapter;
+use super::*;
+
+const CODEX_RUN: &str = " Would you like to run the following command?\n\n $ cargo test -p macrod\n\n› 1. Yes, proceed (y)\n 2. No, and tell Codex what to do differently (esc)\n";
+const CODEX_RUN_REMEMBERABLE: &str = " Would you like to run the following command?\n\n $ cargo test -p macrod\n\n› 1. Yes, proceed (y)\n 2. Yes, and don't ask again for commands that start with `cargo test` (p)\n 3. No, and tell Codex what to do differently (esc)\n";
+
+/// A herdr whose agent is blocked on the dialog in `screen`, logging keys.
+fn fake_herdr(root: &Path) -> (HerdrCli, PathBuf, PathBuf) {
+ let screen = root.join("screen");
+ let keys = root.join("keys");
+ let script = root.join("herdr");
+ std::fs::write(
+ &script,
+ format!(
+ "#!/bin/sh\ncase \"$2\" in\n get) printf '%s\\n' '{{\"result\":{{\"agent\":{{\"agent_status\":\"blocked\",\"state_change_seq\":1}}}}}}';;\n read) cat {screen};;\n send-keys) printf '%s\\n' \"$4\" >> {keys};;\n *) exit 2;;\nesac\n",
+ screen = shell_words::quote(&screen.to_string_lossy()),
+ keys = shell_words::quote(&keys.to_string_lossy()),
+ ),
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
+ std::fs::write(&keys, "").unwrap();
+ (HerdrCli::new(script, None), screen, keys)
+}
+
+fn codex_adapter(
+ root: &Path,
+) -> (
+ Arc<Adapter>,
+ mpsc::UnboundedReceiver<Value>,
+ PathBuf,
+ PathBuf,
+) {
+ let (herdr, screen, keys) = fake_herdr(root);
+ let (mut adapter, output) = test_adapter(root);
+ let adapter_mut = Arc::get_mut(&mut adapter).unwrap();
+ adapter_mut.herdr = Some(herdr);
+ adapter_mut.options.kind = TuiAgent::Codex;
+ (adapter, output, screen, keys)
+}
+
+fn session(root: &Path) -> Session {
+ Session {
+ id: "s1".to_owned(),
+ cwd: root.to_owned(),
+ mcp_servers: Vec::new(),
+ model: Mutex::new(DEFAULT_MODEL.to_owned()),
+ effort: Mutex::new(None),
+ native_id: Mutex::new(None),
+ prompt_pending: AtomicBool::new(false),
+ live: tokio::sync::Mutex::new(None),
+ cancel: Mutex::new(None),
+ always_allowed: Mutex::new(std::collections::HashSet::new()),
+ }
+}
+
+/// Answer the next permission request with `option`, returning the request.
+async fn answer_next(
+ adapter: &Adapter,
+ output: &mut mpsc::UnboundedReceiver<Value>,
+ option: &str,
+) -> Value {
+ let request = output.recv().await.unwrap();
+ adapter.answered(
+ &request["id"],
+ json!({"jsonrpc": "2.0", "id": request["id"], "result": {"outcome": {"outcome": "selected", "optionId": option}}}),
+ );
+ request
+}
+
+#[tokio::test]
+async fn always_allowing_a_command_without_a_native_answer_approves_it_for_the_rest_of_the_session()
+{
+ let root = tempfile::tempdir().unwrap();
+ let (adapter, mut output, screen, keys) = codex_adapter(root.path());
+ let session = session(root.path());
+ let blocked = AtomicU64::new(1);
+ std::fs::write(&screen, CODEX_RUN).unwrap();
+
+ let ((), request) = tokio::join!(
+ adapter.answer_permission(&session, "macro-s1", None, 1, &blocked),
+ answer_next(&adapter, &mut output, "always"),
+ );
+ assert_eq!(request["method"], "session/request_permission");
+ assert_eq!(
+ request["params"]["options"],
+ json!([
+ {"optionId": "allow", "name": "Allow once", "kind": "allow_once"},
+ {"optionId": "always", "name": "Always allow `cargo test -p macrod` in this session", "kind": "allow_always"},
+ {"optionId": "reject", "name": "Reject", "kind": "reject_once"},
+ ])
+ );
+ assert_eq!(std::fs::read_to_string(&keys).unwrap(), "y\n");
+
+ // The same command again is approved without asking Macro.
+ adapter
+ .answer_permission(&session, "macro-s1", None, 1, &blocked)
+ .await;
+ assert!(output.try_recv().is_err());
+ assert_eq!(std::fs::read_to_string(&keys).unwrap(), "y\ny\n");
+
+ // A different command still asks.
+ std::fs::write(
+ &screen,
+ CODEX_RUN.replace("cargo test -p macrod", "rm -rf target"),
+ )
+ .unwrap();
+ let ((), request) = tokio::join!(
+ adapter.answer_permission(&session, "macro-s1", None, 1, &blocked),
+ answer_next(&adapter, &mut output, "reject"),
+ );
+ assert_eq!(
+ request["params"]["options"][1]["name"],
+ "Always allow `rm -rf target` in this session"
+ );
+ assert_eq!(std::fs::read_to_string(&keys).unwrap(), "y\ny\nesc\n");
+ adapter.shutdown.cancel();
+}
+
+#[tokio::test]
+async fn always_allow_presses_the_dialogs_own_dont_ask_again_answer() {
+ let root = tempfile::tempdir().unwrap();
+ let (adapter, mut output, screen, keys) = codex_adapter(root.path());
+ let session = session(root.path());
+ let blocked = AtomicU64::new(1);
+ std::fs::write(&screen, CODEX_RUN_REMEMBERABLE).unwrap();
+
+ let ((), request) = tokio::join!(
+ adapter.answer_permission(&session, "macro-s1", None, 1, &blocked),
+ answer_next(&adapter, &mut output, "always"),
+ );
+ assert_eq!(
+ request["params"]["options"][1],
+ json!({"optionId": "always", "name": "Yes, and don't ask again for commands that start with `cargo test`", "kind": "allow_always"})
+ );
+ assert_eq!(std::fs::read_to_string(&keys).unwrap(), "p\n");
+ // The native agent remembers it; Macro keeps no standing approval.
+ assert!(lock(&session.always_allowed).is_empty());
+ adapter.shutdown.cancel();
+}
+
+#[tokio::test]
+async fn a_dialog_answered_in_the_window_meanwhile_records_no_standing_approval() {
+ let root = tempfile::tempdir().unwrap();
+ let (adapter, mut output, screen, keys) = codex_adapter(root.path());
+ let session = session(root.path());
+ let blocked = AtomicU64::new(1);
+ std::fs::write(&screen, CODEX_RUN).unwrap();
+
+ let ((), _) = tokio::join!(
+ adapter.answer_permission(&session, "macro-s1", None, 1, &blocked),
+ async {
+ let request = output.recv().await.unwrap();
+ std::fs::write(&screen, "a different dialog").unwrap();
+ adapter.answered(
+ &request["id"],
+ json!({"result": {"outcome": {"outcome": "selected", "optionId": "always"}}}),
+ );
+ },
+ );
+ assert_eq!(std::fs::read_to_string(&keys).unwrap(), "");
+ assert!(lock(&session.always_allowed).is_empty());
+ adapter.shutdown.cancel();
+}
+
+#[test]
+fn claude_code_dialogs_remember_by_the_tool_its_transcript_names() {
+ let bash = OpenTool {
+ id: "toolu_1".to_owned(),
+ title: "ls -la".to_owned(),
+ name: Some("Bash".to_owned()),
+ };
+ let screen = " Bash command\n ls -la\n\n Do you want to proceed?\n ❯ 1. Yes\n 2. No, and tell Claude what to do differently (esc)\n";
+ assert_eq!(
+ Always::for_dialog(TuiAgent::Claude, Some(&bash), screen),
+ Some(Always::Standing {
+ tool: "Bash".to_owned(),
+ name: "Always allow Bash in this session".to_owned(),
+ })
+ );
+ assert_eq!(Always::for_dialog(TuiAgent::Claude, None, screen), None);
+}
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
index 3efaa0aa23..1519507ee0 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
@@ -53,9 +53,16 @@ fn an_open_tool_is_forgotten_once_it_reports() {
let mut open = None;
track_open_tool(
&mut open,
- &json!({"sessionUpdate": "tool_call", "toolCallId": "t", "title": "Bash ls"}),
+ &json!({"sessionUpdate": "tool_call", "toolCallId": "t", "title": "Bash ls", "_meta": {"claudeCode": {"toolName": "Bash"}}}),
+ );
+ assert_eq!(
+ open,
+ Some(OpenTool {
+ id: "t".to_owned(),
+ title: "Bash ls".to_owned(),
+ name: Some("Bash".to_owned()),
+ })
);
- assert_eq!(open, Some(("t".to_owned(), "Bash ls".to_owned())));
track_open_tool(
&mut open,
&json!({"sessionUpdate": "tool_call_update", "toolCallId": "other"}),
diff --git a/crates/coding_agent_worker/src/herdr/controls.rs b/crates/coding_agent_worker/src/herdr/controls.rs
index ed595f5b4b..27e0e9eb99 100644
--- a/crates/coding_agent_worker/src/herdr/controls.rs
+++ b/crates/coding_agent_worker/src/herdr/controls.rs
@@ -23,6 +23,35 @@ pub(crate) fn approve_key(kind: TuiAgent, screen: &str) -> Option<&'static str>
}
}
+/// A dialog's own "don't ask again" answer.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct NativeAlways {
+ /// The key that picks it.
+ pub key: String,
+ /// The dialog's wording, which says what it will remember.
+ pub name: String,
+}
+
+/// The dialog's own "don't ask again" answer, when it shows one with a known
+/// shortcut: Codex labels each answer `(key)`, Claude Code takes its number.
+pub(crate) fn always_choice(kind: TuiAgent, screen: &str) -> Option<NativeAlways> {
+ screen.lines().find_map(|line| {
+ let (_, number, name, shortcut) = lazy_regex::regex_captures!(
+ r"^\s*[›❯>]?\s*(\d+)\. (Yes, (?:and don't ask again|allow all).*?)(?: \(([^()]+)\))?\s*$",
+ line
+ )?;
+ let key = match kind {
+ TuiAgent::Codex if shortcut.chars().count() == 1 => shortcut,
+ TuiAgent::Codex => return None,
+ TuiAgent::Claude => number,
+ };
+ Some(NativeAlways {
+ key: key.to_owned(),
+ name: name.to_owned(),
+ })
+ })
+}
+
/// A reply may affect only the same visible dialog and native state generation.
pub(crate) fn same_dialog(
before: &str,
diff --git a/crates/coding_agent_worker/src/herdr/controls/test.rs b/crates/coding_agent_worker/src/herdr/controls/test.rs
index 671db10e8f..5952c087d8 100644
--- a/crates/coding_agent_worker/src/herdr/controls/test.rs
+++ b/crates/coding_agent_worker/src/herdr/controls/test.rs
@@ -23,3 +23,43 @@ fn local_answers_and_replaced_dialogs_invalidate_remote_replies() {
assert!(!same_dialog("approve A", "approve B", 3, 3, "blocked"));
assert!(!same_dialog("approve A", "approve A", 3, 3, "working"));
}
+
+#[test]
+fn dont_ask_again_answers_are_found_with_the_key_that_picks_them() {
+ let codex = "Would you like to run the following command?\n\n $ cargo test\n\n› 1. Yes, proceed (y)\n 2. Yes, and don't ask again for commands that start with `cargo test` (p)\n 3. No, and tell Codex what to do differently (esc)\n";
+ assert_eq!(
+ always_choice(TuiAgent::Codex, codex),
+ Some(NativeAlways {
+ key: "p".to_owned(),
+ name: "Yes, and don't ask again for commands that start with `cargo test`".to_owned(),
+ })
+ );
+ let claude = " Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and don't ask again for ls commands in /repo\n 3. No, and tell Claude what to do differently (esc)\n";
+ assert_eq!(
+ always_choice(TuiAgent::Claude, claude),
+ Some(NativeAlways {
+ key: "2".to_owned(),
+ name: "Yes, and don't ask again for ls commands in /repo".to_owned(),
+ })
+ );
+ let claude_edits = " Do you want to make this edit to a.rs?\n ❯ 1. Yes\n 2. Yes, allow all edits during this session (shift+tab)\n 3. No\n";
+ assert_eq!(
+ always_choice(TuiAgent::Claude, claude_edits),
+ Some(NativeAlways {
+ key: "2".to_owned(),
+ name: "Yes, allow all edits during this session".to_owned(),
+ })
+ );
+ // Without a one-key shortcut (a wrapped line), Codex's answer can't be pressed.
+ assert_eq!(
+ always_choice(
+ TuiAgent::Codex,
+ "› 1. Yes, proceed (y)\n 2. Yes, and don't ask again for commands that start with\n"
+ ),
+ None
+ );
+ assert_eq!(
+ always_choice(TuiAgent::Codex, "› 1. Yes, proceed (y)\n 2. No (esc)\n"),
+ None
+ );
+}
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index e16767b0d3..fd34dd1cd7 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -1817,8 +1817,11 @@ must stay hidden; subsequent live messages must still appear.
A pending request shows one `Approval needed` card above the composer, with
the command or affected file separate from the actions. The transcript does
not repeat the pending request.
- `Allow once` and `Deny` answer immediately; `More options` contains remembered
- choices with the agent's full rule text. Channel Magic Chips expose the same
+ `Allow once`, `Always allow`, and `Deny` answer immediately; `Always allow`
+ shows the agent's rule text as its tooltip. `More options` holds any further
+ remembered choices with their full rule text. Native Herdr sessions (Claude
+ Code or Codex in herdr) offer `Always allow` for recognized approval
+ dialogs; see `crates/coding_agent_worker/README.md`. Channel Magic Chips expose the same
approval card in place of their loading state, alongside existing questions.
Only authenticated users with **Edit** or **Owner** session access may answer;
bot, harness, and internal-service credentials cannot approve on their behalf.