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): recover native sessions and observe local Herdr turns (#7364)

Eric Hayes29bcb8afb415
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.md
index e417363506..0e4b4e5ec7 100644
--- a/crates/coding_agent_worker/README.md
+++ b/crates/coding_agent_worker/README.md
@@ -12,3 +12,17 @@ Herdr creates and registers the worktree. The session ID determines its path
and branch, so redelivery reuses existing work without resetting edits. Cached
repositories and worktrees live under `~/.macrod/herdr/<harness-id>/`. Each
paired macrod instance has one configuration and its own storage directory.
+
+### Reconnecting native sessions
+
+macrod records native session IDs and transcript locations in private files in
+its instance directory. ACP `session/load` replays the native transcript before
+acknowledging the load. A running Herdr agent is reattached; an explicitly missing
+agent resumes its native session on the next prompt. Socket errors do not create
+replacement agents. Changing the configured provider does not convert existing
+sessions into sessions for the other provider.
+
+A background reader forwards local TUI turns even without a Macro prompt.
+Complete JSONL records are read in bounded batches. Partial lines wait for the
+next append; truncation or replacement requires a reload. Turn boundaries are
+forwarded in order, including multiple local turns between polls.
diff --git a/crates/coding_agent_worker/src/herdr.rs b/crates/coding_agent_worker/src/herdr.rs
index 19a70be741..0dd47401b9 100644
--- a/crates/coding_agent_worker/src/herdr.rs
+++ b/crates/coding_agent_worker/src/herdr.rs
@@ -19,6 +19,8 @@ pub(crate) mod acp_agent;
pub(crate) mod cli;
mod hub;
pub(crate) mod repositories;
+mod store;
+mod tail;
mod tap;
pub(crate) mod wire;
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rs
index b5a4da3913..8b79cabe4a 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs
@@ -17,10 +17,9 @@
//!
//! Anyone watching the herdr window can also type into the TUI directly.
-use std::collections::HashMap;
-use std::io::{Read as _, Seek as _};
+use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -32,6 +31,8 @@ use tokio_util::sync::CancellationToken;
use super::HerdrSession;
use super::cli::{HerdrCli, HerdrError};
use super::hub::title_from;
+use super::store::{Record, Store, write_private};
+use super::tail::Cursor;
use agent_fold::domain::transcript::{Fold, LogEvent};
use claude_fold::ClaudeLog;
use codex_fold::CodexLog;
@@ -67,7 +68,17 @@ const MISSING_AGENT_CHECKS: u32 = 5;
const SUBMIT_GRACE: Duration = Duration::from_secs(5);
/// Which coding-agent TUI each session runs.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Default,
+ PartialEq,
+ Eq,
+ clap::ValueEnum,
+ serde::Serialize,
+ serde::Deserialize,
+)]
pub(crate) enum TuiAgent {
/// Claude Code (`claude`).
#[default]
@@ -179,6 +190,16 @@ pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {
});
let herdr = HerdrSession::detect();
+ let home = environment::Home::new().and_then(|home| home.value().map(PathBuf::from));
+ let state_dir = options
+ .state_dir
+ .clone()
+ .or_else(|| {
+ home.as_ref()
+ .map(|home| home.join(".macrod/herdr/standalone"))
+ })
+ .ok_or_else(|| rootcause::report!("HOME or --state-dir is required"))?;
+ let shutdown = CancellationToken::new();
let adapter = Arc::new(Adapter {
out: out_tx,
pending: Mutex::new(HashMap::new()),
@@ -188,10 +209,13 @@ pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {
.as_ref()
.map(|herdr| HerdrCli::new(&herdr.bin, herdr.workspace_id.clone())),
options,
- home: environment::Home::new().and_then(|home| home.value().map(PathBuf::from)),
+ home,
+ store: Store(state_dir),
+ shutdown: shutdown.clone(),
claimed: Mutex::new(std::collections::HashSet::new()),
});
+ let mut requests = tokio::task::JoinSet::new();
let mut lines = BufReader::new(tokio::io::stdin()).lines();
while let Some(line) = lines.next_line().await? {
let Ok(message) = serde_json::from_str::<Value>(&line) else {
@@ -203,9 +227,27 @@ pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {
(Some(method), Some(id)) => {
let adapter = adapter.clone();
let method = method.to_owned();
- tokio::spawn(async move {
+ requests.spawn(async move {
+ let prompt_session = if method == "session/prompt" {
+ adapter.session(&params).ok()
+ } else {
+ None
+ };
+ if prompt_session
+ .as_ref()
+ .is_some_and(|session| session.prompt_pending.swap(true, Ordering::SeqCst))
+ {
+ adapter.respond(
+ id,
+ Err(RpcError::invalid("a prompt is already in progress")),
+ );
+ return;
+ }
let result = adapter.request(&method, params).await;
adapter.respond(id, result);
+ if let Some(session) = prompt_session {
+ session.prompt_pending.store(false, Ordering::SeqCst);
+ }
});
}
(Some("session/cancel"), None) => adapter.cancel(&params),
@@ -214,12 +256,18 @@ pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {
(None, None) => {}
}
}
+ shutdown.cancel();
+ requests.abort_all();
+ while requests.join_next().await.is_some() {}
+ lock(&adapter.pending).clear();
drop(adapter);
let _ = writer.await;
Ok(())
}
struct Adapter {
+ store: Store,
+ shutdown: CancellationToken,
out: mpsc::UnboundedSender<Value>,
pending: Mutex<HashMap<String, oneshot::Sender<Value>>>,
next_id: AtomicU64,
@@ -237,10 +285,20 @@ struct Session {
cwd: PathBuf,
mcp_servers: Vec<Value>,
model: Mutex<String>,
+ native_id: Mutex<Option<String>>,
+ prompt_pending: AtomicBool,
live: tokio::sync::Mutex<Option<Live>>,
cancel: Mutex<Option<CancellationToken>>,
}
+struct PromptCancellation<'a>(&'a Mutex<Option<CancellationToken>>);
+
+impl Drop for PromptCancellation<'_> {
+ fn drop(&mut self) {
+ lock(self.0).take();
+ }
+}
+
/// A session's running TUI.
struct Live {
session: String,
@@ -250,7 +308,8 @@ struct Live {
model: String,
log: Transcript,
path: Option<PathBuf>,
- offset: u64,
+ cursor: Cursor,
+ pending: VecDeque<LogEvent>,
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
@@ -292,7 +351,12 @@ impl Adapter {
let (tx, rx) = oneshot::channel();
lock(&self.pending).insert(Value::String(id.clone()).to_string(), tx);
self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
- rx.await.ok()
+ let answer = tokio::select! {
+ answer = rx => answer.ok(),
+ () = self.shutdown.cancelled() => None,
+ };
+ lock(&self.pending).remove(&Value::String(id).to_string());
+ answer
}
fn answered(&self, id: &Value, message: Value) {
@@ -325,13 +389,14 @@ impl Adapter {
"initialize" => Ok(json!({
"protocolVersion": 1,
"agentCapabilities": {
- "loadSession": false,
+ "loadSession": true,
"promptCapabilities": {"image": false, "audio": false, "embeddedContext": false},
},
"authMethods": [],
"agentInfo": {"name": "macrod-herdr", "version": env!("CARGO_PKG_VERSION")},
})),
- "session/new" => Ok(self.new_session(&params)),
+ "session/new" => self.new_session(&params),
+ "session/load" => self.load_session(&params).await,
"session/set_config_option" => {
let session = self.session(&params)?;
let config = params.get("configId").and_then(Value::as_str);
@@ -365,29 +430,166 @@ impl Adapter {
}
}
- fn new_session(&self, params: &Value) -> Value {
+ fn new_session(self: &Arc<Self>, params: &Value) -> Result<Value, RpcError> {
let id = uuid::Uuid::new_v4().to_string();
let cwd = params
.get("cwd")
.and_then(Value::as_str)
- .map_or_else(|| PathBuf::from("."), PathBuf::from);
- let mcp_servers = params
- .get("mcpServers")
- .and_then(Value::as_array)
- .cloned()
- .unwrap_or_default();
- lock(&self.sessions).insert(
- id.clone(),
- Arc::new(Session {
- id: id.clone(),
- cwd,
- mcp_servers,
- model: Mutex::new(DEFAULT_MODEL.to_owned()),
- live: tokio::sync::Mutex::new(None),
- cancel: Mutex::new(None),
- }),
- );
- json!({"sessionId": id, "configOptions": config_options(self.options.kind, DEFAULT_MODEL)})
+ .map(PathBuf::from)
+ .ok_or_else(|| RpcError::invalid("missing cwd"))?;
+ let session = Arc::new(Session {
+ id: id.clone(),
+ cwd,
+ mcp_servers: params
+ .get("mcpServers")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default(),
+ model: Mutex::new(DEFAULT_MODEL.to_owned()),
+ native_id: Mutex::new(None),
+ prompt_pending: AtomicBool::new(false),
+ live: tokio::sync::Mutex::new(None),
+ cancel: Mutex::new(None),
+ });
+ self.save(&session, None)?;
+ lock(&self.sessions).insert(id.clone(), session.clone());
+ self.observe(&session);
+ Ok(
+ json!({"sessionId": id, "configOptions": config_options(self.options.kind, DEFAULT_MODEL)}),
+ )
+ }
+
+ fn save(&self, session: &Session, live: Option<&Live>) -> Result<(), RpcError> {
+ self.store
+ .save(&Record {
+ version: 1,
+ id: session.id.clone(),
+ kind: self.options.kind,
+ cwd: session.cwd.clone(),
+ model: lock(&session.model).clone(),
+ native_id: lock(&session.native_id).clone(),
+ transcript: live.and_then(|live| live.path.clone()),
+ started: live
+ .map(|live| live.started)
+ .unwrap_or_else(std::time::SystemTime::now)
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ })
+ .map_err(|error| RpcError::internal(format!("could not save native session: {error}")))
+ }
+
+ async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, RpcError> {
+ let id = params
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| RpcError::invalid("missing sessionId"))?;
+ let existing = lock(&self.sessions).get(id).cloned();
+ if let Some(existing) = &existing {
+ let mut live = existing
+ .live
+ .try_lock()
+ .map_err(|_| RpcError::invalid("cannot reload during a Macro prompt"))?;
+ if existing.prompt_pending.load(Ordering::SeqCst) {
+ return Err(RpcError::invalid("cannot reload during a Macro prompt"));
+ }
+ *live = None;
+ lock(&self.sessions).remove(id);
+ }
+ let record = self.store.load(id).map_err(|error| {
+ RpcError::internal(format!("could not restore native session: {error}"))
+ })?;
+ if record.kind != self.options.kind
+ || params.get("cwd").and_then(Value::as_str).map(Path::new)
+ != Some(record.cwd.as_path())
+ {
+ return Err(RpcError::invalid(
+ "saved session belongs to a different agent or workspace",
+ ));
+ }
+ let mut live = Live {
+ session: id.to_owned(),
+ cwd: record.cwd.clone(),
+ started: std::time::UNIX_EPOCH + Duration::from_secs(record.started),
+ name: agent_name(id),
+ model: record.model.clone(),
+ log: self.options.kind.log(),
+ path: record.transcript,
+ cursor: Cursor::default(),
+ pending: VecDeque::new(),
+ };
+ if live.path.is_none() {
+ live.path = self.locate(&live, record.native_id.as_deref());
+ }
+ let session = Arc::new(Session {
+ id: id.to_owned(),
+ cwd: record.cwd,
+ mcp_servers: params
+ .get("mcpServers")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default(),
+ model: Mutex::new(record.model.clone()),
+ native_id: Mutex::new(record.native_id),
+ prompt_pending: AtomicBool::new(false),
+ live: tokio::sync::Mutex::new(None),
+ cancel: Mutex::new(None),
+ });
+ // ACP load stages this complete history until our successful response.
+ loop {
+ let offset = live.cursor.offset;
+ self.forward(&session, &mut live, &mut None)?;
+ if offset == live.cursor.offset && live.pending.is_empty() {
+ break;
+ }
+ }
+ *session.live.lock().await = Some(live);
+ lock(&self.sessions).insert(id.to_owned(), session.clone());
+ self.observe(&session);
+ Ok(json!({"configOptions": config_options(self.options.kind, &record.model)}))
+ }
+
+ fn observe(self: &Arc<Self>, session: &Arc<Session>) {
+ let adapter = Arc::downgrade(self);
+ let session = Arc::downgrade(session);
+ let shutdown = self.shutdown.clone();
+ tokio::spawn(async move {
+ loop {
+ tokio::select! {
+ () = shutdown.cancelled() => break,
+ () = tokio::time::sleep(POLL) => {}
+ }
+ let (Some(adapter), Some(session)) = (adapter.upgrade(), session.upgrade()) else {
+ break;
+ };
+ if session.prompt_pending.load(Ordering::SeqCst) {
+ continue;
+ }
+ // A Macro prompt owns the reader until its response is sent.
+ let Ok(mut guard) = session.live.try_lock() else {
+ continue;
+ };
+ let Some(live) = guard.as_mut() else {
+ continue;
+ };
+ if let Err(error) = adapter.forward(&session, live, &mut None) {
+ tracing::warn!(session = %session.id, error = %error.message, "native transcript observation stopped");
+ adapter.turn_complete(&session.id, "failed");
+ break;
+ }
+ }
+ });
+ }
+
+ fn turn_complete(&self, session: &str, stop: &str) {
+ let outcome = match stop {
+ "cancelled" => json!({"kind":"cancelled"}),
+ "failed" => {
+ json!({"kind":"failed", "message":"native transcript could not be read; reload the session"})
+ }
+ _ => json!({"kind":"finished"}),
+ };
+ self.send(json!({"jsonrpc":"2.0", "method":"_session/turn_complete", "params":{"sessionId":session, "outcome":outcome}}));
}
async fn prompt(
@@ -400,10 +602,45 @@ impl Adapter {
})?;
let cancel = CancellationToken::new();
*lock(&session.cancel) = Some(cancel.clone());
+ let _cancellation = PromptCancellation(&session.cancel);
let mut guard = session.live.lock().await;
+ if let Some(live) = guard.as_ref() {
+ match herdr.agent_info(&live.name).await {
+ Ok(info) if matches!(info.status.as_str(), "working" | "blocked") => {
+ return Err(RpcError::invalid(
+ "the native session is busy; finish its current turn in Herdr first",
+ ));
+ }
+ Ok(info) => {
+ if info.cwd.as_ref().is_some_and(|cwd| cwd != &session.cwd)
+ || info
+ .session_id
+ .as_ref()
+ .zip(lock(&session.native_id).as_ref())
+ .is_some_and(|(actual, expected)| actual != expected)
+ {
+ return Err(RpcError::invalid(
+ "Herdr agent identity no longer matches this session",
+ ));
+ }
+ }
+ Err(error) if error.missing_agent() => {
+ let old = guard.take().expect("live session was checked above");
+ let mut restarted = self.launch(herdr, session, text).await?;
+ restarted.path = old.path;
+ restarted.cursor = old.cursor;
+ restarted.log = old.log;
+ restarted.pending = old.pending;
+ *guard = Some(restarted);
+ self.save(session, guard.as_ref())?;
+ }
+ Err(error) => return Err(error.into()),
+ }
+ }
if guard.is_none() {
*guard = Some(self.launch(herdr, session, text).await?);
+ self.save(session, guard.as_ref())?;
}
let Some(live) = guard.as_mut() else {
return Err(RpcError::internal("the Claude Code window did not start"));
@@ -417,17 +654,18 @@ impl Adapter {
live.model = model;
tokio::time::sleep(Duration::from_secs(1)).await;
}
- // Anything already in the transcript belongs to earlier turns.
- for event in self.drain(live) {
- if let LogEvent::Update(update) = event {
- self.notify_update(&session.id, update);
- }
+ if live.pending.is_empty() {
+ live.pending = self.drain(live)?.into();
+ }
+ if !live.pending.is_empty() {
+ return Err(RpcError::invalid(
+ "the native transcript has new activity; retry once it has synchronized",
+ ));
}
herdr.prompt_agent(&live.name, text).await?;
let outcome = self.follow(herdr, session, live, &cancel).await;
- if outcome.is_err() {
- *guard = None;
- }
+ *lock(&session.cancel) = None;
+ self.save(session, guard.as_ref())?;
outcome
}
@@ -462,11 +700,25 @@ impl Adapter {
let model = lock(&session.model).clone();
let mut args = Vec::new();
- if model != DEFAULT_MODEL {
+ let resume = lock(&session.native_id).clone();
+ if let Some(id) = &resume {
+ args.extend([
+ if kind == TuiAgent::Claude {
+ "--resume"
+ } else {
+ "resume"
+ }
+ .to_owned(),
+ id.clone(),
+ ]);
+ }
+ if model != DEFAULT_MODEL && resume.is_none() {
args.extend(["--model".to_owned(), model.clone()]);
}
if kind == TuiAgent::Claude {
- args.extend(["--session-id".to_owned(), session.id.clone()]);
+ if resume.is_none() {
+ args.extend(["--session-id".to_owned(), session.id.clone()]);
+ }
if let Some(mode) = &self.options.permission_mode {
args.extend(["--permission-mode".to_owned(), mode.clone()]);
}
@@ -489,6 +741,9 @@ impl Adapter {
agent = kind.herdr_kind(),
"agent started in herdr"
);
+ if kind == TuiAgent::Claude {
+ *lock(&session.native_id) = Some(session.id.clone());
+ }
Ok(Live {
session: session.id.clone(),
cwd: session.cwd.clone(),
@@ -497,7 +752,8 @@ impl Adapter {
model,
log: self.options.kind.log(),
path: None,
- offset: 0,
+ cursor: Cursor::default(),
+ pending: VecDeque::new(),
})
}
@@ -547,12 +803,12 @@ impl Adapter {
// to it. One Ctrl+C clears the box (two would quit).
herdr.send_keys(&live.name, &["ctrl+c"]).await?;
}
- self.forward(session, live, &mut open_tool);
+ self.forward(session, live, &mut open_tool)?;
return Ok("cancelled");
}
() = tokio::time::sleep(POLL) => {}
}
- let (moved, ended) = self.forward(session, live, &mut open_tool);
+ let (moved, ended) = self.forward(session, live, &mut open_tool)?;
active |= moved;
if let Some(stop) = ended {
return Ok(stop);
@@ -565,9 +821,13 @@ impl Adapter {
let status = match herdr.agent_info(&live.name).await {
Ok(info) => {
missing = 0;
+ if info.session_id.is_some() {
+ *lock(&session.native_id) = info.session_id.clone();
+ }
if live.path.is_none() {
live.path = self.locate(live, info.session_id.as_deref());
}
+ self.save(session, Some(live))?;
info.status
}
Err(error) => {
@@ -603,7 +863,7 @@ impl Adapter {
"idle" | "done" => {
settled += 1;
if settled >= SETTLED_CHECKS && (active || started.elapsed() > QUIET_START) {
- self.forward(session, live, &mut open_tool);
+ self.forward(session, live, &mut open_tool)?;
return Ok("end_turn");
}
}
@@ -619,10 +879,13 @@ impl Adapter {
session: &Session,
live: &mut Live,
open_tool: &mut Option<(String, String)>,
- ) -> (bool, Option<&'static str>) {
+ ) -> Result<(bool, Option<&'static str>), RpcError> {
let mut moved = false;
let mut ended = None;
- for event in self.drain(live) {
+ if live.pending.is_empty() {
+ live.pending = self.drain(live)?.into();
+ }
+ while let Some(event) = live.pending.pop_front() {
match event {
LogEvent::Update(update) => {
moved = true;
@@ -633,10 +896,14 @@ impl Adapter {
}
self.notify_update(&session.id, update);
}
- LogEvent::TurnEnded(stop) => ended = Some(stop),
+ LogEvent::TurnEnded(stop) => {
+ self.turn_complete(&session.id, stop);
+ ended = Some(stop);
+ break;
+ }
}
}
- (moved, ended)
+ Ok((moved, ended))
}
/// Ask Macro about the TUI's permission dialog, then press the key for
@@ -716,31 +983,20 @@ impl Adapter {
}
/// Read whole new lines from the session's transcript.
- fn drain(&self, live: &mut Live) -> Vec<LogEvent> {
+ fn drain(&self, live: &mut Live) -> Result<Vec<LogEvent>, RpcError> {
if live.path.is_none() {
live.path = self.locate(live, None);
}
let Some(path) = &live.path else {
- return Vec::new();
+ return Ok(Vec::new());
};
- let Ok(mut file) = std::fs::File::open(path) else {
- return Vec::new();
- };
- if file.seek(std::io::SeekFrom::Start(live.offset)).is_err() {
- return Vec::new();
- }
- let mut bytes = Vec::new();
- if file.read_to_end(&mut bytes).is_err() {
- return Vec::new();
- }
- let Some(end) = bytes.iter().rposition(|byte| *byte == b'\n') else {
- return Vec::new();
- };
- live.offset += end as u64 + 1;
- String::from_utf8_lossy(&bytes[..end])
- .lines()
- .flat_map(|line| live.log.entry(line))
- .collect()
+ let lines = live.cursor.read(path).map_err(|error| {
+ RpcError::internal(format!("could not read native transcript: {error}"))
+ })?;
+ Ok(lines
+ .into_iter()
+ .flat_map(|line| live.log.entry(&line))
+ .collect())
}
}
@@ -957,17 +1213,5 @@ fn find_claude_transcript(claude_home: &Path, session: &str) -> Option<PathBuf>
.find(|path| path.is_file())
}
-fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
- use std::io::Write as _;
- use std::os::unix::fs::OpenOptionsExt as _;
- std::fs::OpenOptions::new()
- .write(true)
- .create(true)
- .truncate(true)
- .mode(0o600)
- .open(path)?
- .write_all(bytes)
-}
-
#[cfg(test)]
mod test;
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 cecf3ff2fb..efc7a85301 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
@@ -153,3 +153,153 @@ fn codex_permission_dialogs_are_titled_from_the_screen() {
"Codex is asking for permission"
);
}
+
+fn test_adapter(root: &Path) -> (Arc<Adapter>, mpsc::UnboundedReceiver<Value>) {
+ let (out, receiver) = mpsc::unbounded_channel();
+ (
+ Arc::new(Adapter {
+ store: Store(root.to_owned()),
+ shutdown: CancellationToken::new(),
+ out,
+ pending: Mutex::new(HashMap::new()),
+ next_id: AtomicU64::new(0),
+ sessions: Mutex::new(HashMap::new()),
+ herdr: None,
+ options: AdapterOptions::default(),
+ home: None,
+ claimed: Mutex::new(std::collections::HashSet::new()),
+ }),
+ receiver,
+ )
+}
+
+fn save_transcript(root: &Path, id: &str) -> PathBuf {
+ let transcript = root.join(format!("{id}.jsonl"));
+ std::fs::write(&transcript, "").unwrap();
+ Store(root.to_owned())
+ .save(&Record {
+ version: 1,
+ id: id.to_owned(),
+ kind: TuiAgent::Claude,
+ cwd: root.to_owned(),
+ model: "sonnet".into(),
+ native_id: Some(id.to_owned()),
+ transcript: Some(transcript.clone()),
+ started: 1,
+ })
+ .unwrap();
+ transcript
+}
+
+fn append_turn(path: &Path, id: &str, prompt: &str) {
+ use std::io::Write as _;
+ let mut file = std::fs::OpenOptions::new().append(true).open(path).unwrap();
+ writeln!(
+ file,
+ "{}",
+ json!({"type":"user", "uuid":format!("{id}-user"), "message":{"content":prompt}})
+ )
+ .unwrap();
+ writeln!(file, "{}", json!({"type":"assistant", "uuid":format!("{id}-agent"), "message":{"content":[{"type":"text", "text":"done"}], "stop_reason":"end_turn"}})).unwrap();
+}
+
+#[tokio::test]
+async fn restore_replays_history_and_observes_local_turns_without_a_macro_prompt() {
+ let root = tempfile::tempdir().unwrap();
+ let id = uuid::Uuid::new_v4().to_string();
+ let transcript = save_transcript(root.path(), &id);
+ append_turn(&transcript, "first", "historical prompt");
+ let (adapter, mut output) = test_adapter(root.path());
+ adapter
+ .load_session(&json!({"sessionId":id, "cwd":root.path(), "mcpServers":[]}))
+ .await
+ .unwrap();
+ let history: Vec<_> = std::iter::from_fn(|| output.try_recv().ok()).collect();
+ assert_eq!(history.len(), 3);
+ assert_eq!(
+ history[0]["params"]["update"]["content"]["text"],
+ "historical prompt"
+ );
+ assert_eq!(history[2]["method"], "_session/turn_complete");
+ append_turn(&transcript, "second", "local prompt");
+ append_turn(&transcript, "third", "another local prompt");
+ let mut live = Vec::new();
+ for _ in 0..6 {
+ live.push(
+ tokio::time::timeout(Duration::from_secs(2), output.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ );
+ }
+ assert_eq!(
+ live[0]["params"]["update"]["content"]["text"],
+ "local prompt"
+ );
+ assert_eq!(live[2]["method"], "_session/turn_complete");
+ assert_eq!(
+ live[3]["params"]["update"]["content"]["text"],
+ "another local prompt"
+ );
+ assert_eq!(live[5]["method"], "_session/turn_complete");
+ assert!(
+ tokio::time::timeout(Duration::from_millis(400), output.recv())
+ .await
+ .is_err()
+ );
+ adapter.shutdown.cancel();
+}
+
+#[tokio::test]
+async fn restore_rejects_a_different_workspace_or_agent() {
+ let root = tempfile::tempdir().unwrap();
+ let id = uuid::Uuid::new_v4().to_string();
+ save_transcript(root.path(), &id);
+ let (adapter, mut output) = test_adapter(root.path());
+ assert!(
+ adapter
+ .load_session(&json!({"sessionId":id,"cwd":"/other"}))
+ .await
+ .is_err()
+ );
+ assert!(output.try_recv().is_err());
+ let mut record = adapter.store.load(&id).unwrap();
+ record.kind = TuiAgent::Codex;
+ adapter.store.save(&record).unwrap();
+ assert!(
+ adapter
+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))
+ .await
+ .is_err()
+ );
+}
+
+#[tokio::test]
+async fn observer_waits_until_the_macro_prompt_response_has_been_sent() {
+ let root = tempfile::tempdir().unwrap();
+ let id = uuid::Uuid::new_v4().to_string();
+ let transcript = save_transcript(root.path(), &id);
+ let (adapter, mut output) = test_adapter(root.path());
+ adapter
+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))
+ .await
+ .unwrap();
+ let session = adapter.session(&json!({"sessionId":id})).unwrap();
+ session.prompt_pending.store(true, Ordering::SeqCst);
+ append_turn(&transcript, "first", "local prompt");
+ assert!(
+ tokio::time::timeout(Duration::from_millis(400), output.recv())
+ .await
+ .is_err()
+ );
+ session.prompt_pending.store(false, Ordering::SeqCst);
+ let update = tokio::time::timeout(Duration::from_secs(2), output.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ update["params"]["update"]["content"]["text"],
+ "local prompt"
+ );
+ adapter.shutdown.cancel();
+}
diff --git a/crates/coding_agent_worker/src/herdr/cli.rs b/crates/coding_agent_worker/src/herdr/cli.rs
index 69920a7e09..ac7ecf274f 100644
--- a/crates/coding_agent_worker/src/herdr/cli.rs
+++ b/crates/coding_agent_worker/src/herdr/cli.rs
@@ -39,6 +39,20 @@ pub(crate) enum HerdrError {
},
}
+impl HerdrError {
+ /// Only an explicit missing-agent response permits a native session restart.
+ pub(crate) fn missing_agent(&self) -> 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")
+ })
+ }
+}
+
/// The tab and root pane a new herdr window opened with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Window {
@@ -55,6 +69,10 @@ pub(crate) struct AgentInfo {
pub status: String,
/// The agent's own session id, when its integration reports one.
pub session_id: Option<String>,
+ /// Native pane working directory, for reconnect validation.
+ pub cwd: Option<PathBuf>,
+ /// Monotonic native state generation, used to reject stale permissions.
+ pub state_change_seq: u64,
}
/// Drives the herdr session through its CLI.
@@ -246,6 +264,14 @@ impl HerdrCli {
source,
})?;
Ok(AgentInfo {
+ cwd: answer
+ .pointer("/result/agent/cwd")
+ .and_then(Value::as_str)
+ .map(PathBuf::from),
+ state_change_seq: answer
+ .pointer("/result/agent/state_change_seq")
+ .and_then(Value::as_u64)
+ .unwrap_or_default(),
status: answer
.pointer("/result/agent/agent_status")
.and_then(Value::as_str)
diff --git a/crates/coding_agent_worker/src/herdr/store.rs b/crates/coding_agent_worker/src/herdr/store.rs
new file mode 100644
index 0000000000..013e14320a
--- /dev/null
+++ b/crates/coding_agent_worker/src/herdr/store.rs
@@ -0,0 +1,69 @@
+//! Durable native-session identities. No prompts or MCP credentials are stored here.
+
+use super::acp_agent::TuiAgent;
+use serde::{Deserialize, Serialize};
+use std::path::{Path, PathBuf};
+
+#[cfg(test)]
+mod test;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub(crate) struct Record {
+ pub version: u32,
+ pub id: String,
+ pub kind: TuiAgent,
+ pub cwd: PathBuf,
+ pub model: String,
+ pub native_id: Option<String>,
+ pub transcript: Option<PathBuf>,
+ pub started: u64,
+}
+
+pub(crate) struct Store(pub PathBuf);
+
+impl Store {
+ fn path(&self, id: &str) -> std::io::Result<PathBuf> {
+ let id = uuid::Uuid::parse_str(id).map_err(std::io::Error::other)?;
+ Ok(self.0.join("sessions").join(format!("{id}.json")))
+ }
+
+ pub fn save(&self, record: &Record) -> std::io::Result<()> {
+ use std::os::unix::fs::DirBuilderExt as _;
+ let path = self.path(&record.id)?;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(path.parent().unwrap_or(&self.0))?;
+ write_private(&path, &serde_json::to_vec(record)?)
+ }
+
+ pub fn load(&self, id: &str) -> std::io::Result<Record> {
+ let record: Record = serde_json::from_slice(&std::fs::read(self.path(id)?)?)?;
+ if record.version != 1 || record.id != id {
+ return Err(std::io::Error::other(
+ "unsupported or mismatched native session record",
+ ));
+ }
+ Ok(record)
+ }
+}
+
+pub(crate) fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ use std::io::Write as _;
+ use std::os::unix::fs::OpenOptionsExt as _;
+ let pending = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
+ let result = (|| {
+ let mut file = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&pending)?;
+ file.write_all(bytes)?;
+ file.sync_all()?;
+ std::fs::rename(&pending, path)
+ })();
+ if result.is_err() {
+ let _ = std::fs::remove_file(&pending);
+ }
+ result
+}
diff --git a/crates/coding_agent_worker/src/herdr/store/test.rs b/crates/coding_agent_worker/src/herdr/store/test.rs
new file mode 100644
index 0000000000..4fb24792cb
--- /dev/null
+++ b/crates/coding_agent_worker/src/herdr/store/test.rs
@@ -0,0 +1,30 @@
+use super::*;
+
+#[test]
+fn records_survive_a_new_store_without_exposing_credentials() {
+ use std::os::unix::fs::PermissionsExt as _;
+ let root = tempfile::tempdir().unwrap();
+ let id = uuid::Uuid::new_v4().to_string();
+ let record = Record {
+ version: 1,
+ id: id.clone(),
+ kind: TuiAgent::Claude,
+ cwd: PathBuf::from("/repo"),
+ model: "sonnet".into(),
+ native_id: Some(id.clone()),
+ transcript: Some(PathBuf::from("/log.jsonl")),
+ started: 1,
+ };
+ Store(root.path().to_owned()).save(&record).unwrap();
+ let reopened = Store(root.path().to_owned());
+ assert_eq!(reopened.load(&id).unwrap().native_id, Some(id.clone()));
+ assert_eq!(
+ std::fs::metadata(reopened.path(&id).unwrap())
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o600
+ );
+ assert!(reopened.load("../other").is_err());
+}
diff --git a/crates/coding_agent_worker/src/herdr/tail.rs b/crates/coding_agent_worker/src/herdr/tail.rs
new file mode 100644
index 0000000000..a3d7432176
--- /dev/null
+++ b/crates/coding_agent_worker/src/herdr/tail.rs
@@ -0,0 +1,49 @@
+//! Bounded JSONL framing. Provider folds never open files or own byte offsets.
+
+use std::io::{Read as _, Seek as _};
+use std::os::unix::fs::MetadataExt as _;
+use std::path::Path;
+
+#[cfg(test)]
+mod test;
+
+const MAX_BATCH: u64 = 16 * 1024 * 1024;
+
+#[derive(Default)]
+pub(crate) struct Cursor {
+ pub offset: u64,
+ identity: Option<(u64, u64)>,
+}
+
+impl Cursor {
+ /// Advance only over complete UTF-8 lines. A replaced/truncated log needs
+ /// an explicit history reload, never an implicit replay into live output.
+ pub fn read(&mut self, path: &Path) -> std::io::Result<Vec<String>> {
+ let mut file = std::fs::File::open(path)?;
+ let metadata = file.metadata()?;
+ let identity = (metadata.dev(), metadata.ino());
+ if metadata.len() < self.offset || self.identity.is_some_and(|old| old != identity) {
+ return Err(std::io::Error::other(
+ "native transcript was replaced or truncated; reload the session",
+ ));
+ }
+ self.identity = Some(identity);
+ file.seek(std::io::SeekFrom::Start(self.offset))?;
+ let mut bytes = Vec::new();
+ file.take(MAX_BATCH).read_to_end(&mut bytes)?;
+ let Some(end) = bytes.iter().rposition(|byte| *byte == b'\n') else {
+ return if bytes.len() as u64 == MAX_BATCH {
+ Err(std::io::Error::other(
+ "native transcript record exceeds 16 MiB",
+ ))
+ } else {
+ Ok(Vec::new())
+ };
+ };
+ let text = std::str::from_utf8(&bytes[..end])
+ .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
+ let lines = text.lines().map(str::to_owned).collect();
+ self.offset += end as u64 + 1;
+ Ok(lines)
+ }
+}
diff --git a/crates/coding_agent_worker/src/herdr/tail/test.rs b/crates/coding_agent_worker/src/herdr/tail/test.rs
new file mode 100644
index 0000000000..3fa354d913
--- /dev/null
+++ b/crates/coding_agent_worker/src/herdr/tail/test.rs
@@ -0,0 +1,33 @@
+use super::*;
+use std::io::Write as _;
+
+#[test]
+fn partial_utf8_and_missing_newlines_are_not_consumed() {
+ let mut file = tempfile::NamedTempFile::new().unwrap();
+ file.write_all(b"first\n\xc3").unwrap();
+ let mut cursor = Cursor::default();
+ assert_eq!(cursor.read(file.path()).unwrap(), ["first"]);
+ assert_eq!(cursor.offset, 6);
+ assert!(cursor.read(file.path()).unwrap().is_empty());
+ file.write_all(b"\xa9\nlast").unwrap();
+ assert_eq!(cursor.read(file.path()).unwrap(), ["é"]);
+ file.write_all(b"\n").unwrap();
+ assert_eq!(cursor.read(file.path()).unwrap(), ["last"]);
+ assert!(cursor.read(file.path()).unwrap().is_empty());
+}
+
+#[test]
+fn truncation_and_replacement_require_explicit_replay() {
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("log");
+ std::fs::write(&path, "one\n").unwrap();
+ let mut cursor = Cursor::default();
+ cursor.read(&path).unwrap();
+ std::fs::write(&path, "").unwrap();
+ assert!(cursor.read(&path).is_err());
+ std::fs::write(&path, "one\n").unwrap();
+ let replacement = root.path().join("replacement");
+ std::fs::write(&replacement, "two\n").unwrap();
+ std::fs::rename(replacement, &path).unwrap();
+ assert!(cursor.read(&path).is_err());
+}