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.

fix(macrod): wait for a herdr tab's shell before starting its agent (#7632)

Wolf Mermelsteind5dcd9c741c4
diff --git a/crates/channels/src/domain/reference_sharing.rs b/crates/channels/src/domain/reference_sharing.rs
index b830ae8b7c..9b386547e3 100644
--- a/crates/channels/src/domain/reference_sharing.rs
+++ b/crates/channels/src/domain/reference_sharing.rs
@@ -13,6 +13,10 @@ use model_file_type::FileType;
///
/// A PDF grants comment access so channel members can annotate it, capped at
/// the sharer's own access. `file_type` is the referenced document's file type.
+#[cfg_attr(
+ not(feature = "outbound"),
+ allow(dead_code, reason = "only the outbound share adapter grants access")
+)]
pub(crate) fn grant_level(
item_type: ReferencedShareItemType,
file_type: Option<FileType>,
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rs
index b79c71e9eb..cf54f6a426 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs
@@ -63,6 +63,8 @@ const STATUS_EVERY: u32 = 4;
/// Consecutive ready status checks, with no transcript ending, that end a
/// turn anyway (slash commands and interrupted turns write no final message).
const SETTLED_CHECKS: u32 = 3;
+/// How long a new tab's shell may take to reach its prompt.
+const SHELL_READY_TIMEOUT: Duration = Duration::from_secs(10);
const QUIET_START: Duration = Duration::from_secs(20);
const MISSING_AGENT_CHECKS: u32 = 5;
/// Which coding-agent TUI each session runs.
@@ -754,8 +756,6 @@ impl Adapter {
.open_window(&session.cwd, &label, !self.options.no_focus)
.await?
};
- // The tab's shell must reach its prompt before an agent can start.
- tokio::time::sleep(Duration::from_millis(800)).await;
let model = lock(&session.model).clone();
let mut args = Vec::new();
@@ -808,9 +808,20 @@ impl Adapter {
args.extend(self.options.agent_args.iter().cloned());
let name = agent_name(&session.id);
let started = std::time::SystemTime::now();
- herdr
- .start_agent(&name, kind.herdr_kind(), &window.pane_id, &args)
- .await?;
+ // The tab's shell must reach its prompt before an agent can start,
+ // and a worktree's direnv can hold it for seconds.
+ let deadline = tokio::time::Instant::now() + SHELL_READY_TIMEOUT;
+ loop {
+ match herdr
+ .start_agent(&name, kind.herdr_kind(), &window.pane_id, &args)
+ .await
+ {
+ Err(error) if error.pane_busy() && tokio::time::Instant::now() < deadline => {
+ tokio::time::sleep(POLL).await;
+ }
+ result => break result?,
+ }
+ }
tracing::info!(
session = %session.id,
pane = %window.pane_id,
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 bce8712b07..3efaa0aa23 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
@@ -501,3 +501,46 @@ async fn check_control_delivery(kind: TuiAgent, command: &str, reject: bool) {
assert_eq!(adapter.store.load(&id).unwrap().native_id, Some(id));
adapter.shutdown.cancel();
}
+
+#[tokio::test]
+async fn an_agent_waits_for_a_shell_still_loading_its_environment() {
+ use std::os::unix::fs::PermissionsExt as _;
+ let root = tempfile::tempdir().unwrap();
+ let script = root.path().join("herdr");
+ std::fs::write(
+ &script,
+ format!(
+ r#"#!/bin/sh
+cd {}
+case "$1:$2" in
+ tab:create) printf '{{"result":{{"root_pane":{{"tab_id":"w1:t1","pane_id":"w1:p1"}}}}}}\n' ;;
+ agent:start)
+ printf x >> starts
+ [ "$(wc -c < starts)" -ge 3 ] && exit 0
+ printf '{{"error":{{"code":"agent_pane_busy","message":"agent target pane w1:p1 is not an available shell"}}}}\n' >&2
+ exit 1 ;;
+ *) exit 1 ;;
+esac
+"#,
+ shell_words::quote(&root.path().to_string_lossy())
+ ),
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let (adapter, _) = test_adapter(root.path());
+ let created = adapter.new_session(&json!({"cwd":root.path()})).unwrap();
+ let session = adapter
+ .session(&json!({"sessionId":created["sessionId"]}))
+ .unwrap();
+
+ adapter
+ .launch(&HerdrCli::new(script, None), &session, "hello")
+ .await
+ .unwrap();
+
+ assert_eq!(
+ std::fs::read_to_string(root.path().join("starts")).unwrap(),
+ "xxx"
+ );
+ adapter.shutdown.cancel();
+}
diff --git a/crates/coding_agent_worker/src/herdr/cli.rs b/crates/coding_agent_worker/src/herdr/cli.rs
index 3d0187e854..8809c7633c 100644
--- a/crates/coding_agent_worker/src/herdr/cli.rs
+++ b/crates/coding_agent_worker/src/herdr/cli.rs
@@ -45,14 +45,21 @@ pub(crate) enum HerdrError {
impl HerdrError {
/// Only an explicit missing-agent response permits a native session restart.
pub(crate) fn missing_agent(&self) -> bool {
+ self.has_code("agent_not_found")
+ }
+
+ /// The pane is not yet at its shell prompt, e.g. while direnv loads.
+ pub(crate) fn pane_busy(&self) -> bool {
+ self.has_code("agent_pane_busy")
+ }
+
+ fn has_code(&self, code: &str) -> bool {
let Self::Refused { stderr, .. } = self else {
return false;
};
serde_json::from_str::<Value>(stderr)
.ok()
- .is_some_and(|value| {
- value.pointer("/error/code").and_then(Value::as_str) == Some("agent_not_found")
- })
+ .is_some_and(|value| value.pointer("/error/code").and_then(Value::as_str) == Some(code))
}
}
diff --git a/crates/coding_agent_worker/src/tui/agent_catalog.rs b/crates/coding_agent_worker/src/tui/agent_catalog.rs
index d7dc70e072..3163f0a243 100644
--- a/crates/coding_agent_worker/src/tui/agent_catalog.rs
+++ b/crates/coding_agent_worker/src/tui/agent_catalog.rs
@@ -83,6 +83,15 @@ pub struct DetectedAgent {
}
impl DetectedAgent {
+ /// The name inside its group, where "in herdr" goes without saying.
+ pub fn short_name(&self) -> &'static str {
+ match self.kind {
+ AgentKind::HerdrClaude => "Claude Code",
+ AgentKind::HerdrCodex => "Codex",
+ _ => self.name,
+ }
+ }
+
/// The installation still to run before `launch` works, if any.
pub fn pending_install(&self) -> Option<&AdapterInstall> {
self.install
@@ -104,6 +113,13 @@ pub enum AgentKind {
Custom,
}
+impl AgentKind {
+ /// Whether the agent runs as its own TUI in a herdr tab.
+ pub fn is_herdr(self) -> bool {
+ matches!(self, Self::HerdrClaude | Self::HerdrCodex)
+ }
+}
+
/// Result of checking one preset against the local machine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Availability {
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 0e2045f1ab..fb5fa08be5 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
@@ -52,10 +52,7 @@ impl AgentPreset for HerdrTui {
args,
env: std::collections::BTreeMap::new(),
},
- note: Some(match self.0 {
- TuiAgent::Claude => "a live Claude Code tab per session",
- TuiAgent::Codex => "a live Codex tab per session",
- }),
+ note: None,
install: None,
})
}
diff --git a/crates/coding_agent_worker/src/tui/config_form.rs b/crates/coding_agent_worker/src/tui/config_form.rs
index 6afee56397..3abb5b0308 100644
--- a/crates/coding_agent_worker/src/tui/config_form.rs
+++ b/crates/coding_agent_worker/src/tui/config_form.rs
@@ -66,6 +66,14 @@ impl Setting {
Self::HerdrFocus => "Open sessions",
}
}
+
+ /// Whether the setting only applies to an agent running in herdr.
+ pub fn is_herdr(self) -> bool {
+ matches!(
+ self,
+ Self::HerdrModel | Self::HerdrArguments | Self::HerdrStorage | Self::HerdrFocus
+ )
+ }
}
/// Settings in keyboard navigation order.
@@ -88,13 +96,13 @@ pub fn settings(config: &Config) -> &'static [Setting] {
&[
Setting::Agent,
Setting::Workspace,
+ Setting::Name,
+ Setting::Scope,
+ Setting::PermissionBypass,
Setting::HerdrModel,
Setting::HerdrArguments,
Setting::HerdrStorage,
Setting::HerdrFocus,
- Setting::Name,
- Setting::Scope,
- Setting::PermissionBypass,
]
} else {
SETTINGS
diff --git a/crates/coding_agent_worker/src/tui/quickstart/test.rs b/crates/coding_agent_worker/src/tui/quickstart/test.rs
index 029b4b2197..126e72cce9 100644
--- a/crates/coding_agent_worker/src/tui/quickstart/test.rs
+++ b/crates/coding_agent_worker/src/tui/quickstart/test.rs
@@ -224,3 +224,63 @@ fn quickstart_renders_permission_consent_and_warning() {
assert_eq!(workspace.find("/existing/workspace"), full_access.find('['));
}
}
+
+#[test]
+fn quickstart_groups_herdr_agents_apart_from_headless_ones() {
+ use crate::tui::agent_catalog::LaunchSpec;
+ use ratatui::{Terminal, backend::TestBackend};
+ let agent = |kind, name| DetectedAgent {
+ kind,
+ name,
+ launch: LaunchSpec {
+ command: "agent".to_owned(),
+ args: Vec::new(),
+ env: Default::default(),
+ },
+ note: None,
+ install: None,
+ };
+ let setup = Quickstart {
+ agents: vec![
+ agent(AgentKind::HerdrClaude, "Claude Code in herdr"),
+ agent(AgentKind::HerdrCodex, "Codex in herdr"),
+ agent(AgentKind::ClaudeCode, "Claude Code"),
+ ],
+ selected_agent: None,
+ focus: QuickstartFocus::Agent(1),
+ workspace: "/tmp".to_owned(),
+ scope: IdentityScope::Private,
+ allow_permission_bypass: false,
+ mode: QuickstartMode::Normal,
+ status: None,
+ };
+ let mut terminal = Terminal::new(TestBackend::new(100, 40)).unwrap();
+ terminal
+ .draw(|frame| {
+ crate::tui::ui::render_quickstart(frame, &setup, std::path::Path::new("macrod.toml"))
+ })
+ .unwrap();
+ let rows = terminal
+ .backend()
+ .buffer()
+ .content()
+ .chunks(100)
+ .map(|row| {
+ row.iter()
+ .map(|cell| cell.symbol())
+ .collect::<String>()
+ .trim_end()
+ .to_owned()
+ })
+ .collect::<Vec<_>>();
+ let position = |text: &str| rows.iter().position(|row| row.contains(text)).unwrap();
+ assert!(position("Herdr") < position("▸ ○ Codex"));
+ assert!(position("▸ ○ Codex") < position("ACP"));
+ let headless = rows
+ .iter()
+ .rposition(|row| row.contains("○ Claude Code"))
+ .unwrap();
+ assert!(position("○ Claude Code") < position("ACP"));
+ assert!(position("ACP") < headless);
+ assert!(!rows.iter().any(|row| row.contains("in herdr")));
+}
diff --git a/crates/coding_agent_worker/src/tui/ui/modals.rs b/crates/coding_agent_worker/src/tui/ui/modals.rs
index 4147f71e2a..005758e03e 100644
--- a/crates/coding_agent_worker/src/tui/ui/modals.rs
+++ b/crates/coding_agent_worker/src/tui/ui/modals.rs
@@ -7,12 +7,40 @@ use ratatui::widgets::{Clear, Paragraph};
use tui_input::Input;
use super::layout::{centered, render_input};
-use super::theme::{ACCENT, DIM, ERR, SPINNER, THEME, WARN, modal};
+use super::theme::{ACCENT, DIM, ERR, SPINNER, THEME, WARN, modal, section};
use crate::tui::agent_catalog::DetectedAgent;
use crate::tui::app::App;
+/// Agent rows in catalog order, with herdr agents headed apart from
+/// headless ACP agents when both kinds are present.
+pub(super) fn agent_groups<'a>(
+ agents: &'a [DetectedAgent],
+ width: u16,
+ row: impl Fn(usize, &'a DetectedAgent) -> Line<'a>,
+) -> Vec<Line<'a>> {
+ let grouped = agents.iter().any(|agent| agent.kind.is_herdr());
+ let mut lines = Vec::new();
+ let mut previous = None;
+ for (index, agent) in agents.iter().enumerate() {
+ let herdr = agent.kind.is_herdr();
+ if grouped && previous != Some(herdr) {
+ if previous.is_some() {
+ lines.push(Line::raw(""));
+ }
+ lines.push(if herdr {
+ section("Herdr", "each session in its own tab", width)
+ } else {
+ section("ACP", "headless, driven by macrod", width)
+ });
+ previous = Some(herdr);
+ }
+ lines.push(row(index, agent));
+ }
+ lines
+}
+
pub(super) fn render_agent_picker(frame: &mut Frame, agents: &[DetectedAgent], selected: usize) {
- let height = (agents.len() as u16 + 11).clamp(11, 20);
+ let height = (agents.len() as u16 + 14).clamp(11, 24);
let area = centered(62, height, frame.area());
frame.render_widget(Clear, area);
let mut lines = vec![
@@ -25,19 +53,24 @@ pub(super) fn render_agent_picker(frame: &mut Frame, agents: &[DetectedAgent], s
Style::new().fg(WARN),
));
} else {
- lines.extend(agents.iter().enumerate().map(|(index, agent)| {
- let marker = if index == selected { "▸ " } else { " " };
- let style = if index == selected {
- Style::new().fg(ACCENT).bold()
- } else {
- Style::new()
- };
- let detail = agent.note.unwrap_or("");
- Line::from(vec![
- Span::styled(format!("{marker}{:<20}", agent.name), style),
- Span::styled(detail, Style::new().fg(DIM)),
- ])
- }));
+ lines.extend(agent_groups(
+ agents,
+ area.width.saturating_sub(4),
+ |index, agent| {
+ let marker = if index == selected { "▸ " } else { " " };
+ let style = if index == selected {
+ Style::new().fg(ACCENT).bold()
+ } else {
+ Style::new()
+ };
+ let detail = agent.note.unwrap_or("");
+ Line::from(vec![
+ Span::styled(format!("{marker}{:<20}", agent.short_name()), style),
+ Span::styled(detail, Style::new().fg(DIM)),
+ ])
+ },
+ ));
+ lines.push(Line::raw(""));
}
let custom_style = if selected == agents.len() {
Style::new().fg(ACCENT).bold()
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 7baef42ec8..1fc89af910 100644
--- a/crates/coding_agent_worker/src/tui/ui/pages/config.rs
+++ b/crates/coding_agent_worker/src/tui/ui/pages/config.rs
@@ -4,7 +4,7 @@ use ratatui::style::{Style, Stylize as _};
use ratatui::widgets::Paragraph;
use super::super::layout::render_input;
-use super::super::theme::{ACCENT, DIM, WARN, card, focus_marker, focus_style};
+use super::super::theme::{ACCENT, DIM, WARN, card, focus_marker, focus_style, section};
use crate::config::IdentityScope;
use crate::tui::app::{App, Mode};
use crate::tui::config_form::settings;
@@ -14,10 +14,30 @@ pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {
let inner = block.inner(area);
frame.render_widget(block, area);
let settings = settings(&app.config);
+ let herdr_start = settings.iter().position(|setting| setting.is_herdr());
+ // A blank line and a header sit above the herdr group.
+ let row_of = |index: usize| -> u16 {
+ index as u16
+ + if herdr_start.is_some_and(|start| index >= start) {
+ 2
+ } else {
+ 0
+ }
+ };
+ if let Some(start) = herdr_start {
+ frame.render_widget(
+ Paragraph::new(section("Herdr", "each session in its own tab", inner.width)),
+ Rect {
+ y: inner.y + row_of(start) - 1,
+ height: 1,
+ ..inner
+ },
+ );
+ }
for (index, setting) in settings.iter().enumerate() {
let selected = index == app.selected_setting;
let row = Rect {
- y: inner.y + index as u16,
+ y: inner.y + row_of(index),
height: 1,
..inner
};
@@ -56,13 +76,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 + row_of(settings.len()) + 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 + row_of(settings.len()) + 1,
width: inner.width,
height: 1,
};
diff --git a/crates/coding_agent_worker/src/tui/ui/quickstart.rs b/crates/coding_agent_worker/src/tui/ui/quickstart.rs
index d924912328..69a8ab08d9 100644
--- a/crates/coding_agent_worker/src/tui/ui/quickstart.rs
+++ b/crates/coding_agent_worker/src/tui/ui/quickstart.rs
@@ -5,6 +5,7 @@ use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Padding, Paragraph};
use super::layout::{centered, render_input};
+use super::modals::agent_groups;
use super::theme::{ACCENT, DIM, ERR, OK, THEME, WARN, focus_marker, focus_style, modal};
use crate::config::IdentityScope;
use crate::tui::agent_catalog::AgentKind;
@@ -16,10 +17,10 @@ pub(crate) fn render_quickstart(
config_path: &std::path::Path,
) {
super::theme::render_background(frame);
- let discovered_height = (setup.agents.len() as u16 + 2).clamp(3, 9);
+ let discovered_height = (discovered_lines(setup, 0).len() as u16 + 2).clamp(3, 12);
let area = centered(
84,
- frame.area().height.saturating_sub(2).min(33),
+ frame.area().height.saturating_sub(2).min(36),
frame.area(),
);
frame.render_widget(Clear, area);
@@ -224,27 +225,23 @@ fn render_discovered_agents(frame: &mut Frame, setup: &Quickstart, area: Rect) {
return;
}
- for (index, agent) in setup.agents.iter().enumerate() {
+ frame.render_widget(Paragraph::new(discovered_lines(setup, inner.width)), inner);
+}
+
+fn discovered_lines(setup: &Quickstart, width: u16) -> Vec<Line<'_>> {
+ agent_groups(&setup.agents, width, |index, agent| {
let focused = setup.focus == QuickstartFocus::Agent(index);
let chosen = setup
.selected_agent
.as_ref()
.is_some_and(|selected| selected.kind == agent.kind);
- let row = Rect {
- y: inner.y + index as u16,
- height: 1,
- ..inner
- };
- frame.render_widget(
- Paragraph::new(Line::from(vec![
- Span::styled(focus_marker(focused), Style::new().fg(ACCENT)),
- Span::styled(if chosen { "● " } else { "○ " }, Style::new().fg(ACCENT)),
- Span::styled(format!("{:<22}", agent.name), focus_style(focused)),
- Span::styled(agent.note.unwrap_or(""), Style::new().fg(DIM)),
- ])),
- row,
- );
- }
+ Line::from(vec![
+ Span::styled(focus_marker(focused), Style::new().fg(ACCENT)),
+ Span::styled(if chosen { "● " } else { "○ " }, Style::new().fg(ACCENT)),
+ Span::styled(format!("{:<22}", agent.short_name()), focus_style(focused)),
+ Span::styled(agent.note.unwrap_or(""), Style::new().fg(DIM)),
+ ])
+ })
}
fn render_quickstart_custom(frame: &mut Frame, setup: &Quickstart, area: Rect) {
diff --git a/crates/coding_agent_worker/src/tui/ui/theme.rs b/crates/coding_agent_worker/src/tui/ui/theme.rs
index 511bce8099..c341f3a594 100644
--- a/crates/coding_agent_worker/src/tui/ui/theme.rs
+++ b/crates/coding_agent_worker/src/tui/ui/theme.rs
@@ -1,5 +1,6 @@
use ratatui::Frame;
use ratatui::style::{Color, Style, Stylize as _};
+use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Padding};
pub(super) struct Theme {
@@ -77,3 +78,16 @@ pub(super) fn focus_style(focused: bool) -> Style {
Style::new()
}
}
+
+/// A titled rule that groups the rows below it.
+pub(super) fn section(title: &str, note: &str, width: u16) -> Line<'static> {
+ let used = title.chars().count() + note.chars().count() + 2;
+ Line::from(vec![
+ Span::styled(title.to_owned(), Style::new().fg(ACCENT).bold()),
+ Span::styled(format!(" {note} "), Style::new().fg(DIM)),
+ Span::styled(
+ "─".repeat(usize::from(width).saturating_sub(used)),
+ Style::new().fg(THEME.border),
+ ),
+ ])
+}