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): configure native Herdr sessions in the TUI (#7366)

Eric Hayesceedb597f277
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
index eb4a8c08c4..3fc5f8ef0c 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
@@ -11,7 +11,11 @@ import {
} from '@solidjs/testing-library';
import type { JSX } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { buildAgentRoster, type PersistedAgentLike } from '../core/roster';
+import {
+ buildAgentRoster,
+ type PersistedAgentLike,
+ type RuntimeLike,
+} from '../core/roster';
import { AgentPicker } from './AgentPicker';
import { NewChatPage } from './NewChatPage';
@@ -198,7 +202,8 @@ beforeEach(() => {
function page(
connected = true,
agents: PersistedAgentLike[] = [],
- availabilityLoading = false
+ availabilityLoading = false,
+ runtimes: RuntimeLike[] = []
) {
const onStart = vi.fn();
render(() => (
@@ -206,7 +211,7 @@ function page(
compact={mocks.touch}
roster={buildAgentRoster({
agents,
- runtimes: [],
+ runtimes,
cursorConnected: connected,
cursorNeedsConnection: !connected,
macroDefaultModel: 'chat-default',
@@ -503,6 +508,39 @@ describe('agent-led new conversation', () => {
}
);
+ it('dispatches the chosen repository from main to a paired local runtime', async () => {
+ const send = page(
+ true,
+ [
+ {
+ bot: { id: 'local-agent', name: 'Laptop agent', handle: 'laptop' },
+ harness: 'macrod',
+ harness_id: 'laptop',
+ default_model: 'default',
+ },
+ ],
+ false,
+ [{ id: 'laptop', name: 'Laptop', connected: true }]
+ );
+ await selectAgent(/Cursor/);
+ fireEvent.click(screen.getByRole('button', { name: 'Repository' }));
+ fireEvent.click(screen.getByRole('option', { name: 'macro-inc/macro' }));
+ expect(
+ screen.getByRole('button', { name: 'Branch' }).textContent
+ ).toContain('develop');
+ await selectAgent(/Laptop agent/);
+ const branch = screen.getByRole('button', { name: 'Branch' });
+ expect(branch.textContent).toContain('main');
+ expect(branch.hasAttribute('disabled')).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));
+ expect(send).toHaveBeenCalledWith({
+ prompt: 'Prompt',
+ botId: 'local-agent',
+ repoUrl: 'https://github.com/macro-inc/macro',
+ repoBranch: 'main',
+ });
+ });
+
it('keeps a disconnected paired agent visible with its availability reason', () => {
page(true, [
{
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.tsx b/apps/web/src/features/agents-view/views/NewChatPage.tsx
index f19738fb2d..7810046ad4 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.tsx
@@ -154,8 +154,9 @@ export function NewChatPage(props: {
: undefined;
};
const coding = () => selected()?.kind === 'coder';
- // The create-session API accepts explicit repositories only for Cursor.
- const canSelectRepository = () => selected()?.harness === 'cursor';
+ const localRuntime = () => selected()?.harness === 'macrod';
+ const canSelectRepository = () =>
+ selected()?.harness === 'cursor' || localRuntime();
const blocked = () => {
const agent = selected();
return agent ? agent.unavailableReason : 'Choose an agent to start';
@@ -164,11 +165,14 @@ export function NewChatPage(props: {
const reachable = createReachableRepositories(coding);
// Listed only while a repository is chosen: listing costs a GitHub call.
const reachableBranches = createRepositoryBranches(() =>
- coding() ? repoUrl() : undefined
+ coding() && !localRuntime() ? repoUrl() : undefined
);
// A chosen branch, or where the selected repository's own clones start.
const repoBranch = () =>
- branchOverride() ?? defaultBranchFor(reachable.repositories(), repoUrl());
+ localRuntime()
+ ? 'main'
+ : (branchOverride() ??
+ defaultBranchFor(reachable.repositories(), repoUrl()));
const selectRepository = (url: string | undefined) => {
// Another repository starts on its own default branch, not the last one's.
if (url !== repoUrl()) setBranchOverride(undefined);
@@ -275,6 +279,7 @@ export function NewChatPage(props: {
onOpenChange={setRepositoryPickerOpen}
repoUrl={repoUrl()}
branch={repoBranch()}
+ branchLocked={localRuntime()}
repositories={reachable.repositories()}
repositoriesLoading={reachable.loading()}
repositoriesError={reachable.error()}
diff --git a/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx b/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
index 7083b4f466..df8567446e 100644
--- a/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
+++ b/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
@@ -54,6 +54,18 @@ describe('RepositoryPicker', () => {
vi.unstubAllGlobals();
});
+ it('keeps a runtime-enforced branch visible without opening the branch menu', () => {
+ const handlers = picker({ repoUrl: macro.url, branchLocked: true });
+ const branch = screen.getByRole('button', { name: 'Branch' });
+ expect(branch.textContent).toContain('main');
+ expect(branch.hasAttribute('disabled')).toBe(true);
+ fireEvent.click(branch);
+ expect(
+ screen.queryByRole('combobox', { name: 'Search branches' })
+ ).toBeNull();
+ expect(handlers.onSelectBranch).not.toHaveBeenCalled();
+ });
+
it('lists automatic first, then recents, then the rest, marking the selection', () => {
picker({ repoUrl: infra.url, recentRepositories: [infra.url] });
expect(
diff --git a/apps/web/src/features/agents-view/views/RepositoryPicker.tsx b/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
index c251cf72e3..e247ee3bb3 100644
--- a/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
+++ b/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
@@ -40,6 +40,8 @@ export function RepositoryPicker(props: {
repoUrl?: string;
onOpenChange?: (open: boolean) => void;
branch: string;
+ /** This runtime always starts new worktrees from main. */
+ branchLocked?: boolean;
/** Repositories the signed-in user can hand a coder through Macro's GitHub App. */
repositories: ReachableRepository[];
repositoriesLoading: boolean;
@@ -329,7 +331,7 @@ export function RepositoryPicker(props: {
<Popover
open={branchOpen()}
onOpenChange={(open) => {
- setBranchOpen(open);
+ setBranchOpen(open && !props.branchLocked);
setError('');
if (open) {
setBranchSearch('');
@@ -343,10 +345,18 @@ export function RepositoryPicker(props: {
<Popover.Trigger
class="pill min-w-0 max-w-[45%] text-ink"
aria-label="Branch"
+ disabled={props.branchLocked}
+ title={
+ props.branchLocked
+ ? 'New local sessions start from main'
+ : undefined
+ }
>
<GitBranchIcon class="size-4 shrink-0" />
<span class="truncate">{props.branch}</span>
- <CaretDownIcon class="size-3 shrink-0" />
+ <Show when={!props.branchLocked}>
+ <CaretDownIcon class="size-3 shrink-0" />
+ </Show>
</Popover.Trigger>
<Popover.Portal>
<Popover.Content class="z-action-menu w-80 max-w-[calc(100vw-1rem)] rounded-xl border border-edge-muted bg-menu p-3 text-sm text-ink shadow-menu">
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.md
index c856a42004..d0f81abe6c 100644
--- a/crates/coding_agent_worker/README.md
+++ b/crates/coding_agent_worker/README.md
@@ -49,3 +49,17 @@ native launch/resume, not injected into an already-running process.
Codex's documented [MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
and [configuration reference](https://learn.chatgpt.com/docs/config-file/config-reference)
describe `env_http_headers` and per-server configuration.
+
+### Setup
+
+Start macrod inside Herdr and choose **Claude Code in herdr** or **Codex in
+herdr** in Quickstart. Select a workspace directory containing your existing
+clones and pair with Macro. Native CLI authentication and Git credentials are
+reused. Each instance has one configuration, with no profiles to choose per run.
+
+The Config tab adds **Model** (empty uses the native default), **Extra args**
+(shell-style quoting), **Storage** (empty uses automatic instance storage), and
+**Open sessions** (foreground or background). Switching agents clears the
+previous agent's model and extra arguments. Storage and focus preferences remain.
+Session metadata stays in the instance directory even with custom worktree storage.
+Choose a repository in Macro's composer; local sessions always start from `main`.
diff --git a/crates/coding_agent_worker/config.example.toml b/crates/coding_agent_worker/config.example.toml
index f6f02a822c..3fbe92537b 100644
--- a/crates/coding_agent_worker/config.example.toml
+++ b/crates/coding_agent_worker/config.example.toml
@@ -39,3 +39,10 @@ args = ["acp"]
path = "/workspace"
# Informational: having the repo cloned at `path` is the operator's job.
repo_url = "https://github.com/macro-inc/macro"
+
+# Optional defaults for the one native Herdr configuration (also editable in the TUI).
+# [herdr]
+# model = "sonnet" # Omit to use the installed agent's default.
+# arguments = [] # Native CLI arguments, one word per element.
+# storage_path = "/path/to/agents" # Omit for ~/.macrod/herdr/<harness-id>.
+# focus = true # false opens new sessions in the background.
diff --git a/crates/coding_agent_worker/src/config.rs b/crates/coding_agent_worker/src/config.rs
index 16622f0368..aebb55bfad 100644
--- a/crates/coding_agent_worker/src/config.rs
+++ b/crates/coding_agent_worker/src/config.rs
@@ -35,6 +35,34 @@ pub struct Config {
pub harness: Harness,
/// The workspace every session runs against.
pub workspace: Workspace,
+ /// Native Herdr defaults shared by this macrod instance.
+ #[serde(default)]
+ pub herdr: HerdrSettings,
+}
+
+/// One native launch configuration, shared by all new sessions.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct HerdrSettings {
+ /// Native model ID; absent uses the CLI's configured default.
+ pub model: Option<String>,
+ /// Extra native CLI arguments, already split into words.
+ pub arguments: Vec<String>,
+ /// Repository cache and worktree location; absent uses instance storage.
+ pub storage_path: Option<PathBuf>,
+ /// Switch Herdr to newly launched sessions.
+ pub focus: bool,
+}
+
+impl Default for HerdrSettings {
+ fn default() -> Self {
+ Self {
+ model: None,
+ arguments: Vec::new(),
+ storage_path: None,
+ focus: true,
+ }
+ }
}
/// Whether the approved harness is private to its owner or shared with a team.
@@ -176,12 +204,11 @@ pub struct Harness {
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Workspace {
- /// Absolute directory harnesses run in; sent as each session's
- /// workspace at creation.
+ /// Absolute directory generic harnesses run in. Native Herdr searches
+ /// this directory for existing clones and creates a worktree per session.
pub path: PathBuf,
- /// Repository nominally checked out at `path`, recorded on each
- /// session it serves. Informational: having the repo cloned there is
- /// the operator's job.
+ /// Default repository when dispatch does not specify one. Generic
+ /// harnesses expect it at `path`; native Herdr can find or clone it.
#[serde(default)]
pub repo_url: Option<String>,
}
diff --git a/crates/coding_agent_worker/src/daemon.rs b/crates/coding_agent_worker/src/daemon.rs
index 16ebafca2b..79edd5aa2b 100644
--- a/crates/coding_agent_worker/src/daemon.rs
+++ b/crates/coding_agent_worker/src/daemon.rs
@@ -59,22 +59,10 @@ impl Daemon {
let root = crate::herdr::instance_directory(credentials.harness_id)?;
let herdr = crate::herdr::HerdrSession::detect()
.ok_or_else(|| rootcause::report!("start macrod inside a Herdr pane"))?;
- let index = config
- .harness
- .args
- .iter()
- .position(|arg| arg == "--")
- .unwrap_or(config.harness.args.len());
- config.harness.args.splice(
- index..index,
- [
- "--state-dir".to_owned(),
- root.to_string_lossy().into_owned(),
- ],
- );
+ crate::herdr::configure_launch(&mut config.harness, &config.herdr, &root);
Some(crate::herdr::repositories::Workspaces::new(
config.workspace.path.clone(),
- root,
+ config.herdr.storage_path.clone().unwrap_or(root),
crate::herdr::cli::HerdrCli::new(herdr.bin, herdr.workspace_id),
))
} else {
diff --git a/crates/coding_agent_worker/src/herdr.rs b/crates/coding_agent_worker/src/herdr.rs
index 730f5982a9..a9cd062ed4 100644
--- a/crates/coding_agent_worker/src/herdr.rs
+++ b/crates/coding_agent_worker/src/herdr.rs
@@ -108,3 +108,34 @@ impl HerdrSession {
Some(Self { bin, workspace_id })
}
}
+
+/// Apply the instance defaults without mixing adapter flags with native arguments.
+pub(crate) fn configure_launch(
+ harness: &mut crate::config::Harness,
+ settings: &crate::config::HerdrSettings,
+ state_dir: &std::path::Path,
+) {
+ let index = harness
+ .args
+ .iter()
+ .position(|arg| arg == "--")
+ .unwrap_or(harness.args.len());
+ let mut flags = vec![
+ "--state-dir".to_owned(),
+ state_dir.to_string_lossy().into_owned(),
+ "--managed-worktrees".to_owned(),
+ ];
+ if let Some(model) = &settings.model {
+ flags.push(format!("--model={model}"));
+ }
+ if !settings.focus {
+ flags.push("--no-focus".to_owned());
+ }
+ harness.args.splice(index..index, flags);
+ if !settings.arguments.is_empty() {
+ if !harness.args.iter().any(|arg| arg == "--") {
+ harness.args.push("--".to_owned());
+ }
+ harness.args.extend(settings.arguments.iter().cloned());
+ }
+}
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rs
index 41f1cd454e..d9b773bcdd 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs
@@ -7,8 +7,7 @@
//! `codex` in its own herdr tab, rooted at the session's working directory:
//!
//! - the first `session/prompt` opens the tab and starts the agent there
-//! with the session's model (and, for Claude Code, its id and Macro MCP
-//! servers);
+//! with the session's model and Macro MCP servers;
//! - prompts are typed into the TUI with `herdr agent prompt`;
//! - the agent's own session transcript is tailed and streamed back as
//! `session/update`s, and its end-of-turn record ends the turn;
@@ -126,6 +125,10 @@ impl Transcript {
pub(crate) struct AdapterOptions {
/// Private storage shared with the dispatcher's repository preparation.
pub state_dir: Option<PathBuf>,
+ /// Native model ID for new sessions.
+ pub model: Option<String>,
+ /// Sessions use dispatcher-managed worktrees.
+ pub managed_worktrees: bool,
/// The agent TUI sessions run.
pub kind: TuiAgent,
/// Passed to Claude Code as `--permission-mode`.
@@ -213,6 +216,7 @@ pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {
let mut requests = tokio::task::JoinSet::new();
let mut lines = BufReader::new(tokio::io::stdin()).lines();
while let Some(line) = lines.next_line().await? {
+ while requests.try_join_next().is_some() {}
let Ok(message) = serde_json::from_str::<Value>(&line) else {
continue;
};
@@ -428,7 +432,8 @@ impl Adapter {
.kind
.models()
.iter()
- .any(|(id, _)| *id == model) =>
+ .any(|(id, _)| *id == model)
+ || self.options.model.as_deref() == Some(model) =>
{
let live = session
.live
@@ -475,7 +480,12 @@ impl Adapter {
.and_then(Value::as_array)
.cloned()
.unwrap_or_default(),
- model: Mutex::new(DEFAULT_MODEL.to_owned()),
+ model: Mutex::new(
+ self.options
+ .model
+ .clone()
+ .unwrap_or_else(|| DEFAULT_MODEL.to_owned()),
+ ),
native_id: Mutex::new(None),
prompt_pending: AtomicBool::new(false),
live: tokio::sync::Mutex::new(None),
@@ -485,7 +495,7 @@ impl Adapter {
lock(&self.sessions).insert(id.clone(), session.clone());
self.observe(&session);
Ok(
- json!({"sessionId": id, "configOptions": config_options(self.options.kind, DEFAULT_MODEL)}),
+ json!({"sessionId": id, "configOptions": config_options(self.options.kind, &lock(&session.model))}),
)
}
@@ -699,12 +709,7 @@ impl Adapter {
) -> Result<Live, RpcError> {
let kind = self.options.kind;
let label = title_from(first_prompt).unwrap_or_else(|| kind.herdr_kind().to_owned());
- let window = if self
- .options
- .state_dir
- .as_ref()
- .is_some_and(|root| session.cwd.starts_with(root.join("worktrees")))
- {
+ let window = if self.options.managed_worktrees {
let source = crate::outbound::git::primary_worktree(&session.cwd)
.await
.map_err(|error| RpcError::internal(error.to_string()))?;
@@ -1137,17 +1142,21 @@ pub(crate) fn agent_name(session: &str) -> String {
}
fn config_options(kind: TuiAgent, current: &str) -> Value {
+ let mut options = kind
+ .models()
+ .iter()
+ .map(|(value, name)| json!({"value": value, "name": name}))
+ .collect::<Vec<_>>();
+ if !kind.models().iter().any(|(value, _)| *value == current) {
+ options.push(json!({"value": current, "name": current}));
+ }
json!([{
"id": MODEL_CONFIG_ID,
"name": "Model",
"category": "model",
"type": "select",
"currentValue": current,
- "options": kind
- .models()
- .iter()
- .map(|(value, name)| json!({"value": value, "name": name}))
- .collect::<Vec<_>>(),
+ "options": options,
}])
}
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 3b09024d35..96382dcb51 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
@@ -361,3 +361,16 @@ async fn an_unconfirmed_submission_never_sends_an_extra_enter_or_reports_success
);
adapter.shutdown.cancel();
}
+
+#[test]
+fn configured_models_are_advertised_even_when_not_in_the_builtin_catalog() {
+ let options = config_options(TuiAgent::Codex, "custom-model");
+ assert_eq!(options[0]["currentValue"], "custom-model");
+ assert!(
+ options[0]["options"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|option| option["value"] == "custom-model")
+ );
+}
diff --git a/crates/coding_agent_worker/src/herdr/test.rs b/crates/coding_agent_worker/src/herdr/test.rs
index 03ae1eb3c8..1c2b331bdb 100644
--- a/crates/coding_agent_worker/src/herdr/test.rs
+++ b/crates/coding_agent_worker/src/herdr/test.rs
@@ -36,3 +36,47 @@ fn herdr_harnesses_name_their_agent() {
assert_eq!(herdr_agent(&harness(&["acp"])), None);
assert!(!drives_herdr(&harness(&["acp"])));
}
+
+#[test]
+fn instance_settings_keep_native_arguments_after_the_separator() {
+ let mut launch = harness(&[
+ "herdr-acp",
+ "--kind",
+ "codex",
+ "--",
+ "--sandbox",
+ "workspace-write",
+ ]);
+ let settings = crate::config::HerdrSettings {
+ model: Some("custom-model".to_owned()),
+ arguments: vec![
+ "--config".to_owned(),
+ "model_reasoning_effort=\"high\"".to_owned(),
+ ],
+ focus: false,
+ ..Default::default()
+ };
+ configure_launch(
+ &mut launch,
+ &settings,
+ std::path::Path::new("/private state"),
+ );
+ assert_eq!(
+ launch.args,
+ [
+ "herdr-acp",
+ "--kind",
+ "codex",
+ "--state-dir",
+ "/private state",
+ "--managed-worktrees",
+ "--model=custom-model",
+ "--no-focus",
+ "--",
+ "--sandbox",
+ "workspace-write",
+ "--config",
+ "model_reasoning_effort=\"high\"",
+ ]
+ );
+}
diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rs
index 965fe8073b..779d8176c8 100644
--- a/crates/coding_agent_worker/src/main.rs
+++ b/crates/coding_agent_worker/src/main.rs
@@ -64,6 +64,12 @@ enum Command {
/// Private storage for this paired macrod instance.
#[arg(long)]
state_dir: Option<std::path::PathBuf>,
+ /// Native model ID for new sessions.
+ #[arg(long)]
+ model: Option<String>,
+ /// Open sessions in dispatcher-managed worktrees.
+ #[arg(long, hide = true)]
+ managed_worktrees: bool,
/// Which agent TUI each session runs.
#[arg(long, value_enum, default_value_t)]
kind: herdr::acp_agent::TuiAgent,
@@ -111,6 +117,8 @@ async fn main() -> ExitCode {
}
Some(Command::HerdrAcp {
state_dir,
+ model,
+ managed_worktrees,
kind,
permission_mode,
no_focus,
@@ -122,6 +130,8 @@ async fn main() -> ExitCode {
.init();
return match herdr::acp_agent::run(herdr::acp_agent::AdapterOptions {
state_dir,
+ model,
+ managed_worktrees,
kind,
permission_mode,
no_focus,
diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs b/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs
index 7f2a78b8c9..0e2045f1ab 100644
--- a/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs
+++ b/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs
@@ -39,14 +39,11 @@ impl AgentPreset for HerdrTui {
missing: vec!["macrod"],
};
};
- let mut args = vec![
+ let args = vec![
crate::herdr::acp_agent::SUBCOMMAND.to_owned(),
"--kind".to_owned(),
self.0.herdr_kind().to_owned(),
];
- if self.0 == TuiAgent::Claude {
- args.extend(["--permission-mode".to_owned(), "acceptEdits".to_owned()]);
- }
Availability::Available(DetectedAgent {
kind: self.kind(),
name: self.name(),
diff --git a/crates/coding_agent_worker/src/tui/app.rs b/crates/coding_agent_worker/src/tui/app.rs
index 40d2108f79..39a7b49f25 100644
--- a/crates/coding_agent_worker/src/tui/app.rs
+++ b/crates/coding_agent_worker/src/tui/app.rs
@@ -10,7 +10,7 @@ use tui_input::Input;
use super::agent_catalog::{self, DetectedAgent, PathCommands};
use super::api::{HarnessSelfApi, Snapshot};
-use super::config_form::{ConfigForm, SETTINGS, Setting};
+use super::config_form::{ConfigForm, Setting, settings};
use super::input::handle_text_input;
use super::logging::LogBuffer;
use super::platform::{BrowserTarget, copy_to_clipboard};
@@ -68,7 +68,7 @@ pub(crate) enum Mode {
Normal,
/// Editing one config setting's value.
EditSetting {
- /// Index into [`SETTINGS`].
+ /// Index into the current settings.
index: usize,
/// The text being typed.
buffer: Input,
@@ -471,14 +471,17 @@ impl App {
}
async fn commit_edit(&mut self, index: usize, input: String) {
- let setting = SETTINGS[index];
+ let setting = settings(&self.config)[index];
if let Err(message) = self.form.apply_text(setting, &input) {
return self.fail(message);
}
let apply = match setting {
- Setting::Workspace => ApplyConfig::Now,
+ Setting::Workspace
+ | Setting::HerdrModel
+ | Setting::HerdrArguments
+ | Setting::HerdrStorage => ApplyConfig::Now,
Setting::Name => ApplyConfig::NextPairing,
- Setting::Agent | Setting::Scope | Setting::PermissionBypass => {
+ Setting::Agent | Setting::Scope | Setting::PermissionBypass | Setting::HerdrFocus => {
unreachable!("not edited as text")
}
};
@@ -545,6 +548,8 @@ impl App {
self.config = config;
// The core reads config at start, so a save while serving
// means a restart to apply it.
+ self.selected_setting =
+ self.selected_setting.min(settings(&self.config).len() - 1);
if apply == ApplyConfig::Now && self.paired() {
if self.restart_daemon().await {
self.ok("saved and applied");
@@ -588,36 +593,47 @@ impl App {
self.selected_setting = self.selected_setting.saturating_sub(1);
}
KeyCode::Down | KeyCode::Char('j') if self.tab == Tab::Config => {
- self.selected_setting = (self.selected_setting + 1).min(SETTINGS.len() - 1);
+ self.selected_setting =
+ (self.selected_setting + 1).min(settings(&self.config).len() - 1);
}
- KeyCode::Enter if self.tab == Tab::Config => match SETTINGS[self.selected_setting] {
- Setting::Agent => {
- let selected = self
- .agents
- .iter()
- .position(|agent| {
- agent.launch.command == self.config.harness.command
- && agent.launch.args == self.config.harness.args
- })
- .unwrap_or(self.agents.len());
- self.mode = Mode::AgentPicker { selected };
- }
- Setting::Scope => {
- self.form.toggle_scope(&self.config);
- self.save_config(ApplyConfig::NextPairing).await;
- }
- Setting::PermissionBypass => {
- self.form
- .set_permission_bypass(!self.config.identity.allow_permission_bypass);
- self.save_config(ApplyConfig::NextPairing).await;
- }
- setting @ (Setting::Workspace | Setting::Name) => {
- self.mode = Mode::EditSetting {
- index: self.selected_setting,
- buffer: self.form.edit_value(setting).into(),
- };
+ KeyCode::Enter if self.tab == Tab::Config => {
+ match settings(&self.config)[self.selected_setting] {
+ Setting::Agent => {
+ let selected = self
+ .agents
+ .iter()
+ .position(|agent| {
+ agent.launch.command == self.config.harness.command
+ && agent.launch.args == self.config.harness.args
+ })
+ .unwrap_or(self.agents.len());
+ self.mode = Mode::AgentPicker { selected };
+ }
+ Setting::Scope => {
+ self.form.toggle_scope(&self.config);
+ self.save_config(ApplyConfig::NextPairing).await;
+ }
+ Setting::PermissionBypass => {
+ self.form
+ .set_permission_bypass(!self.config.identity.allow_permission_bypass);
+ self.save_config(ApplyConfig::NextPairing).await;
+ }
+ Setting::HerdrFocus => {
+ self.form.toggle_herdr_focus(&self.config);
+ self.save_config(ApplyConfig::Now).await;
+ }
+ setting @ (Setting::Workspace
+ | Setting::Name
+ | Setting::HerdrModel
+ | Setting::HerdrArguments
+ | Setting::HerdrStorage) => {
+ self.mode = Mode::EditSetting {
+ index: self.selected_setting,
+ buffer: self.form.edit_value(setting).into(),
+ };
+ }
}
- },
+ }
_ => {}
}
}
diff --git a/crates/coding_agent_worker/src/tui/config_form.rs b/crates/coding_agent_worker/src/tui/config_form.rs
index ffb1e1c193..6afee56397 100644
--- a/crates/coding_agent_worker/src/tui/config_form.rs
+++ b/crates/coding_agent_worker/src/tui/config_form.rs
@@ -41,6 +41,14 @@ pub enum Setting {
Scope,
/// Whether the next pairing may enable permission bypass.
PermissionBypass,
+ /// Native model override; empty uses the installed agent's default.
+ HerdrModel,
+ /// Optional arguments passed to the native agent.
+ HerdrArguments,
+ /// Location of managed clones and worktrees.
+ HerdrStorage,
+ /// Whether newly launched sessions take focus.
+ HerdrFocus,
}
impl Setting {
@@ -52,6 +60,10 @@ impl Setting {
Self::Name => "Name",
Self::Scope => "Access",
Self::PermissionBypass => "Full Access",
+ Self::HerdrModel => "Model",
+ Self::HerdrArguments => "Extra args",
+ Self::HerdrStorage => "Storage",
+ Self::HerdrFocus => "Open sessions",
}
}
}
@@ -65,6 +77,30 @@ pub const SETTINGS: &[Setting] = &[
Setting::PermissionBypass,
];
+/// Settings relevant to the currently selected agent.
+pub fn settings(config: &Config) -> &'static [Setting] {
+ if config
+ .harness
+ .args
+ .first()
+ .is_some_and(|arg| arg == "herdr-acp")
+ {
+ &[
+ Setting::Agent,
+ Setting::Workspace,
+ Setting::HerdrModel,
+ Setting::HerdrArguments,
+ Setting::HerdrStorage,
+ Setting::HerdrFocus,
+ Setting::Name,
+ Setting::Scope,
+ Setting::PermissionBypass,
+ ]
+ } else {
+ SETTINGS
+ }
+}
+
/// The config document being viewed and edited.
pub struct ConfigForm {
path: PathBuf,
@@ -128,6 +164,24 @@ impl ConfigForm {
.map(str::to_owned)
.unwrap_or_else(|| format!("Custom ({})", config.harness.command)),
Setting::Workspace => config.workspace.path.display().to_string(),
+ Setting::HerdrModel => config
+ .herdr
+ .model
+ .clone()
+ .unwrap_or_else(|| "Agent default".to_owned()),
+ Setting::HerdrArguments => shell_words::join(&config.herdr.arguments),
+ Setting::HerdrStorage => config
+ .herdr
+ .storage_path
+ .as_ref()
+ .map(|path| path.display().to_string())
+ .unwrap_or_else(|| "Automatic (~/.macrod/herdr)".to_owned()),
+ Setting::HerdrFocus => if config.herdr.focus {
+ "Foreground"
+ } else {
+ "Background"
+ }
+ .to_owned(),
Setting::Name => config
.identity
.name
@@ -152,7 +206,20 @@ impl ConfigForm {
match setting {
Setting::Workspace => self.string("workspace", "path").unwrap_or_default(),
Setting::Name => self.string("identity", "name").unwrap_or_default(),
- Setting::Agent | Setting::Scope | Setting::PermissionBypass => String::new(),
+ Setting::HerdrModel => self.string("herdr", "model").unwrap_or_default(),
+ Setting::HerdrStorage => self.string("herdr", "storage_path").unwrap_or_default(),
+ Setting::HerdrArguments => shell_words::join(
+ self.doc
+ .get("herdr")
+ .and_then(|section| section.get("arguments"))
+ .and_then(Item::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(toml_edit::Value::as_str),
+ ),
+ Setting::Agent | Setting::Scope | Setting::PermissionBypass | Setting::HerdrFocus => {
+ String::new()
+ }
}
}
@@ -179,7 +246,32 @@ impl ConfigForm {
self.set_string("identity", "name", input);
}
}
- Setting::Agent | Setting::Scope | Setting::PermissionBypass => {
+ Setting::HerdrModel | Setting::HerdrStorage => {
+ let key = if setting == Setting::HerdrModel {
+ "model"
+ } else {
+ "storage_path"
+ };
+ if input.is_empty() {
+ self.remove("herdr", key);
+ } else {
+ if setting == Setting::HerdrStorage && !Path::new(input).is_absolute() {
+ return Err(
+ "Storage must be an absolute path, or empty for automatic".to_owned()
+ );
+ }
+ self.set_string("herdr", key, input);
+ }
+ }
+ Setting::HerdrArguments => {
+ let words = shell_words::split(input).map_err(|error| error.to_string())?;
+ let mut args = toml_edit::Array::new();
+ for word in words {
+ args.push(word);
+ }
+ self.doc["herdr"].or_insert(toml_edit::table())["arguments"] = value(args);
+ }
+ Setting::Agent | Setting::Scope | Setting::PermissionBypass | Setting::HerdrFocus => {
return Err(format!("{} is selected rather than typed", setting.label()));
}
}
@@ -188,6 +280,30 @@ impl ConfigForm {
/// Apply a detected agent's concrete launch specification.
pub fn apply_agent(&mut self, agent: &DetectedAgent) {
+ let current = self
+ .doc
+ .get("harness")
+ .and_then(|section| section.get("args"))
+ .and_then(Item::as_array)
+ .map(|args| {
+ args.iter()
+ .filter_map(toml_edit::Value::as_str)
+ .collect::<Vec<_>>()
+ });
+ if current.as_deref()
+ != Some(
+ agent
+ .launch
+ .args
+ .iter()
+ .map(String::as_str)
+ .collect::<Vec<_>>()
+ .as_slice(),
+ )
+ {
+ self.remove("herdr", "model");
+ self.remove("herdr", "arguments");
+ }
self.set_string("harness", "command", &agent.launch.command);
let mut args = toml_edit::Array::new();
for arg in &agent.launch.args {
@@ -231,6 +347,11 @@ impl ConfigForm {
self.set_string("identity", "scope", next);
}
+ /// Toggle whether a new native session takes focus.
+ pub fn toggle_herdr_focus(&mut self, config: &Config) {
+ self.doc["herdr"].or_insert(toml_edit::table())["focus"] = value(!config.herdr.focus);
+ }
+
/// Set the requested scope without changing any approved credential scope.
pub fn set_scope(&mut self, scope: IdentityScope) {
let scope = match scope {
@@ -295,7 +416,7 @@ impl ConfigForm {
}
fn remove(&mut self, section: &str, key: &str) {
- if let Some(table) = self.doc[section].as_table_like_mut() {
+ if let Some(table) = self.doc.get_mut(section).and_then(Item::as_table_like_mut) {
table.remove(key);
}
}
diff --git a/crates/coding_agent_worker/src/tui/config_form/test.rs b/crates/coding_agent_worker/src/tui/config_form/test.rs
index 070f4201b5..deccddd605 100644
--- a/crates/coding_agent_worker/src/tui/config_form/test.rs
+++ b/crates/coding_agent_worker/src/tui/config_form/test.rs
@@ -290,3 +290,56 @@ fn permission_bypass_edits_preserve_credentials_and_comments() {
);
}
}
+
+#[test]
+fn native_settings_round_trip_and_agent_switch_resets_provider_defaults() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("macrod.toml");
+ let agent = discover(&HermesOnly).remove(0);
+ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Production)
+ .unwrap();
+ let mut form = ConfigForm::load(&path).unwrap();
+ form.apply_text(Setting::HerdrModel, "custom-model")
+ .unwrap();
+ form.apply_text(
+ Setting::HerdrArguments,
+ "--config 'model_reasoning_effort=\"high\"'",
+ )
+ .unwrap();
+ assert!(
+ form.apply_text(Setting::HerdrArguments, "'unclosed")
+ .is_err()
+ );
+ assert!(form.apply_text(Setting::HerdrStorage, "relative").is_err());
+ let storage = directory.path().join("new-storage");
+ form.apply_text(Setting::HerdrStorage, storage.to_str().unwrap())
+ .unwrap();
+ form.toggle_herdr_focus(&Config::load(&path).unwrap());
+ form.save().unwrap();
+ let config = Config::load(&path).unwrap();
+ assert_eq!(config.herdr.model.as_deref(), Some("custom-model"));
+ assert_eq!(
+ config.herdr.arguments,
+ ["--config", "model_reasoning_effort=\"high\""]
+ );
+ assert_eq!(config.herdr.storage_path.as_ref(), Some(&storage));
+ assert!(!config.herdr.focus);
+ assert!(!settings(&config).contains(&Setting::HerdrModel));
+ let mut native = agent;
+ native.launch.args = vec![
+ "herdr-acp".to_owned(),
+ "--kind".to_owned(),
+ "codex".to_owned(),
+ ];
+ form.apply_agent(&native);
+ form.save().unwrap();
+ let config = Config::load(&path).unwrap();
+ assert!(config.herdr.model.is_none());
+ assert!(config.herdr.arguments.is_empty());
+ assert_eq!(config.herdr.storage_path, Some(storage));
+ assert!(settings(&config).contains(&Setting::HerdrModel));
+ form.apply_text(Setting::HerdrModel, "").unwrap();
+ form.apply_text(Setting::HerdrStorage, "").unwrap();
+ form.save().unwrap();
+ assert!(Config::load(&path).unwrap().herdr.storage_path.is_none());
+}
diff --git a/crates/coding_agent_worker/src/tui/ui/pages/config.rs b/crates/coding_agent_worker/src/tui/ui/pages/config.rs
index 55e5dc7155..7baef42ec8 100644
--- a/crates/coding_agent_worker/src/tui/ui/pages/config.rs
+++ b/crates/coding_agent_worker/src/tui/ui/pages/config.rs
@@ -7,13 +7,14 @@ use super::super::layout::render_input;
use super::super::theme::{ACCENT, DIM, WARN, card, focus_marker, focus_style};
use crate::config::IdentityScope;
use crate::tui::app::{App, Mode};
-use crate::tui::config_form::SETTINGS;
+use crate::tui::config_form::settings;
pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {
let block = card(format!("macrod.toml · {}", app.config_path.display()));
let inner = block.inner(area);
frame.render_widget(block, area);
- for (index, setting) in SETTINGS.iter().enumerate() {
+ let settings = settings(&app.config);
+ for (index, setting) in settings.iter().enumerate() {
let selected = index == app.selected_setting;
let row = Rect {
y: inner.y + index as u16,
@@ -55,13 +56,13 @@ pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {
frame.render_widget(
Paragraph::new("Warning: agents can run commands and edit files without approval.\nApplies at next pairing.")
.style(Style::new().fg(WARN)),
- Rect { y: inner.y + SETTINGS.len() as u16 + 2, height: 2, ..inner },
+ Rect { y: inner.y + settings.len() as u16 + 2, height: 2, ..inner },
);
}
if app.config.identity.scope == IdentityScope::Team {
let warning = Rect {
x: inner.x,
- y: inner.y + SETTINGS.len() as u16 + 1,
+ y: inner.y + settings.len() as u16 + 1,
width: inner.width,
height: 1,
};
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 634ad8e194..9ef3bec8fa 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -312,6 +312,11 @@ the shimmer.
agent changes and are sent only to coding agents. Cursor honors the explicit
repository and branch instead of choosing a repository from the prompt;
the owner must have access through the connected GitHub App.
+ Paired macrod agents also receive the repository choice. With native Herdr,
+ macrod finds an existing clone or clones it using local Git credentials, then
+ creates a managed worktree from a fresh `origin/main`. **Branch** shows `main`
+ and cannot be changed for local sessions. The native Claude/Codex TUI remains
+ interactive in Herdr, and local turns appear in the Macro transcript.
- Sending starts a session with the chosen agent's configured default model;
a model selected from its submenu overrides that default for the next send
only. Sending or choosing another agent clears the override. This does not