Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(tui): a shared machine's models, and a close that succeeded (#1454)

lingrd94c7f158220b
diff --git a/cli/src/core/agents/close.spec.ts b/cli/src/core/agents/close.spec.ts
index eef5e537f..d5e8c901c 100644
--- a/cli/src/core/agents/close.spec.ts
+++ b/cli/src/core/agents/close.spec.ts
@@ -190,6 +190,23 @@ describe('closing agents no window shows', () => {
expect(request).toHaveBeenCalledTimes(3)
})
+ it('leaves out an agent closed while the preview was reading the others', async () => {
+ // An inspect of an agent already closed answers { closed: true }: it has nothing left to close, and once
+ // entered the reviewed batch as activity 'unknown'.
+ const stopped = row({ agentId: 'stopped' })
+ const quiet = row({ agentId: 'quiet', sessionId: 's2' })
+ const { deps, closing } = setup({}, [stopped, quiet])
+ vi.mocked(deps.cleanupTabs.isHidden).mockReturnValue(true)
+ vi.spyOn(closing.closeAgentService, 'request')
+ .mockResolvedValueOnce({ closed: true })
+ .mockResolvedValueOnce({ activity: 'idle' })
+ expect(await closing.cleanupPreview()).toEqual({
+ version: 1,
+ agents: [{ agentId: 'quiet', sessionId: 's2', createdAt: new Date(0).toISOString(), name: projectDisplayName(quiet), engine: 'claude', activity: 'idle' }],
+ kept: 1,
+ })
+ })
+
it('a close asked for while the preview is reading the agent is carried out, not answered with the reading', async () => {
// The preview inspects every hidden agent; a window's close of one of them arriving meanwhile was
// once answered with that inspect's `{ activity }`, and the agent left running (e2e/windows.e2e.ts).
diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.ts
index d2c38e5d4..9ac1031ac 100644
--- a/cli/src/core/agents/close.ts
+++ b/cli/src/core/agents/close.ts
@@ -116,7 +116,9 @@ export function createAgentClosing({
if (!cleanupTabs.isHidden(s)) continue
const target = { agentId: s.agentId, sessionId: s.sessionId, createdAt: new Date(s.registeredAt).toISOString() }
const inspected = await closeAgentService.request({ ...target, mode: 'inspect' })
- if (inspected.error) continue // A changing session is never added to a reviewed batch.
+ // A changing session is never added to a reviewed batch, nor one that stopped while the others were read: it
+ // has nothing left to close.
+ if (inspected.error || inspected.closed) continue
agents.push({ ...target, name: projectDisplayName(s), engine: s.engine, activity: inspected.activity ?? 'unknown' })
}
return { version: 1, agents, kept: sessions.length - agents.length }
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index b38dc567f..e2d599b00 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -202,12 +202,24 @@ it('a close of one already closed, the same conversation, is closed: asked after
expect(await window).toEqual({ closed: true })
expect(await service.request(request('now'))).toEqual({ closed: true })
expect(deps.stop).toHaveBeenCalledOnce()
- // Asking what it is doing, or to close it after its task, is about a live one: it changed.
- expect(await service.request(request('inspect'))).toEqual({ error: 'AGENT_CHANGED' })
+ // A close after its task is about a live one: it changed.
expect(await service.request(request('after_task'))).toEqual({ error: 'AGENT_CHANGED' })
// Another conversation by that id was not closed.
expect(await service.request({ ...request('now'), sessionId: 'other' })).toEqual({ error: 'AGENT_CHANGED' })
})
+it('an inspect of one already closed, the same conversation, is closed', async () => {
+ // The terminal client inspects before every close: one asked again after a close it shows as unconfirmed (its
+ // answer lost, or the harness bound a conversation meanwhile) was answered AGENT_CHANGED, "Stop not confirmed".
+ const asked = request()
+ const closedAlready = vi.fn((r: AgentCloseRequest) => r.agentId === asked.agentId && r.sessionId === asked.sessionId && !registry.byAgent(r.agentId))
+ service.dispose()
+ service = new CloseAgentService({ ...deps, closedAlready })
+ expect(await service.request(request('now'))).toEqual({ closed: true })
+ expect(await service.request(request('inspect'))).toEqual({ closed: true })
+ expect(await service.request({ ...request('inspect'), sessionId: 'other' })).toEqual({ error: 'AGENT_CHANGED' })
+ expect(deps.stop).toHaveBeenCalledOnce()
+ expect(deps.activity).toHaveBeenCalledOnce()
+})
it('a close now asked for while a close after the task is being planned closes now', async () => {
let read!: (activity: CloseActivity) => void
vi.mocked(deps.activity).mockImplementationOnce(() => new Promise(resolve => { read = resolve }))
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index 9565843d8..d30a5027f 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -182,10 +182,13 @@ export class CloseAgentService {
* The answer to a close of an agent that is not the one asked about. One already closed, the same conversation, is
* closed: a window closing a tab after a pane in it, its starter, was closed takes the harnesses that starter started
* with it (services/agentCleanup.ts), and the window's own close of them, asked a moment later, was answered
- * AGENT_CHANGED and shown as "Could not confirm that it stopped". Anything else is AGENT_CHANGED.
+ * AGENT_CHANGED and shown as "Could not confirm that it stopped". An inspect of one is closed too: the terminal client
+ * inspects before every close, and its close again of one it had closed was answered "Stop not confirmed:
+ * AGENT_CHANGED". Anything else is AGENT_CHANGED.
*/
private changed(request: AgentCloseRequest): AgentCloseResult {
- return (request.mode === 'idle' || request.mode === 'now') && this.deps.closedAlready?.(request) ? { closed: true } : { error: 'AGENT_CHANGED' }
+ return (request.mode === 'idle' || request.mode === 'now' || request.mode === 'inspect') && this.deps.closedAlready?.(request)
+ ? { closed: true } : { error: 'AGENT_CHANGED' }
}
private async execute(request: AgentCloseRequest, target: string, revision: number): Promise<AgentCloseResult> {
diff --git a/tui/src/account_scope.rs b/tui/src/account_scope.rs
index 395700cfa..07d036355 100644
--- a/tui/src/account_scope.rs
+++ b/tui/src/account_scope.rs
@@ -70,7 +70,7 @@ impl App {
self.fleet.machines.retain(|m| m.id != machine);
self.fleet.agents.retain(|(m, _), _| m != machine);
self.shells.retain(|(m, _)| m != machine);
- self.homes.remove(machine); self.usage.remove(machine); self.rtt.remove(machine);
+ self.homes.remove(machine); self.usage.remove(machine); self.usage_asked.remove(machine); self.rtt.remove(machine);
self.pending_questions.retain(|(m, _, _)| m != machine);
self.home_order.borrow_mut().clear(); self.fleet_marked = false;
self.fit_panes(); self.redraw_all = true; self.server_dirty = true;
@@ -231,7 +231,7 @@ impl App {
self.recent.clear(); self.home_external.clear(); self.said.clear(); self.said_for.clear(); self.said_want.clear();
self.said_generation = self.said_generation.wrapping_add(1); self.said_pending = 0; self.said_due = None;
self.tails.clear(); self.tails_asked.clear(); self.pending_questions.clear();
- self.dsh.clear(); self.rtt.clear(); self.homes.clear(); self.usage.clear(); self.usage_checked = None;
+ self.dsh.clear(); self.rtt.clear(); self.homes.clear(); self.usage.clear(); self.usage_checked = None; self.usage_asked.clear();
self.prs.clear(); self.pr_asking.clear(); self.prs_read = None; self.seen_rostered.clear(); self.enriching = 0;
self.home_order.borrow_mut().clear(); self.fleet_marked = false;
self.agent_errors.clear(); self.launch_failed = None; self.away = None;
diff --git a/tui/src/agent_switch.rs b/tui/src/agent_switch.rs
index 1134de2a1..8fd9825b1 100644
--- a/tui/src/agent_switch.rs
+++ b/tui/src/agent_switch.rs
@@ -285,7 +285,7 @@ fn source_for(app: &App, pane: u64) -> Option<Agent> {
pub fn pane_supports(app: &App, pane: u64) -> bool {
source_for(app, pane).is_some_and(|a| a.engine != "terminal" && a.dsh_id != "autonomous/pair"
- && app.fleet.machine(&a.machine_id).is_some_and(|m| !m.shared))
+ && app.fleet.machine(&a.machine_id).is_some() && !app.fleet.belongs_to_other_account(&a.machine_id))
}
pub fn pane_label(app: &App, pane: u64) -> String {
@@ -1030,6 +1030,11 @@ mod tests {
assert!(!pane_supports(&app, 1));
app.modal = None; open(&mut app, 1);
assert!(app.modal.is_none());
+ // A machine shared with this account by email (guest sharing) is its owner's too.
+ app.fleet.machines[0].shared = false;
+ assert!(pane_supports(&app, 1));
+ app.fleet.shares.insert("local".into(), crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false });
+ assert!(!pane_supports(&app, 1));
}
#[tokio::test]
diff --git a/tui/src/app.rs b/tui/src/app.rs
index bccb040d9..4b07d77ca 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -755,6 +755,9 @@ pub struct App {
/// Each machine's agent accounts' rate limits (usage_read), and when they were last asked.
pub usage: HashMap<String, Vec<fleet::Usage>>,
pub usage_checked: Option<Instant>,
+ /// When each machine was last asked its usage, and on which connection (read_usage: at most once a
+ /// minute per connection; a reconnect is asked its own).
+ pub usage_asked: HashMap<String, (u64, Instant)>,
pub key_name: Option<String>,
pub key_run: Option<String>,
pub cfg_finished: bool,
@@ -997,6 +1000,7 @@ impl App {
enriching: 0,
usage: HashMap::new(),
usage_checked: None,
+ usage_asked: HashMap::new(),
key_name: None,
key_run: None,
cfg_finished: false,
@@ -1512,6 +1516,9 @@ impl App {
if machine_id == self.fleet.local_id && !crate::local::is_local(&machine_id) { self.daemon_down = false; crate::dial::reconnected(self) }
self.relist(&machine_id);
self.push_theme();
+ // Its plans now, not at the next five-minute read: on a machine shared with this account
+ // they are the owner's, which a harness there runs on.
+ if !crate::local::is_local(&machine_id) { self.read_usage(&machine_id); }
// A guest there has no home of the owner's to read: its workspace stands for it, beside the
// folders the owner shares (docs/plans/2026-10-19-guest-machine-sharing-plan.md).
if self.fleet.shares.contains_key(&machine_id) {
@@ -6314,6 +6321,37 @@ impl App {
// ── the loop's slow tick ─────────────────────────────────────────────────
+ /// Ask [machine] its agent accounts' rate limits (usage_read), unless it was asked in the last
+ /// minute: when it connects, when Models opens, and on enrich's five-minute timer. On a machine
+ /// shared with this account they are its owner's, the plans a harness there runs on. False when
+ /// it has no link to ask.
+ ///
+ /// The minute is the connection's: a read's reply is dropped once its connection is gone, so a
+ /// machine that drops and connects again is asked again rather than waiting for the timer.
+ pub fn read_usage(&mut self, machine: &str) -> bool {
+ let Some(link) = self.link(machine) else { return false };
+ let generation = link.generation;
+ if self.usage_asked.get(machine).is_some_and(|&(asked_on, at)| asked_on == generation && at.elapsed() < Duration::from_secs(60)) { return true }
+ self.usage_asked.insert(machine.to_string(), (generation, Instant::now()));
+ let id = machine.to_string();
+ self.spawn(async move { link.rpc("usage_read", json!({}), Duration::from_secs(30)).await }, move |app, reply| app.usage_replied(id, generation, reply));
+ true
+ }
+
+ /// A usage_read's answer from [machine]'s connection [generation]: nothing once that connection
+ /// is gone (the next one asks its own).
+ fn usage_replied(&mut self, machine: String, generation: u64, reply: Result<Value, RpcError>) {
+ if self.connection_generation(&machine) != Some(generation) { return }
+ // A first read that failed is asked again on the timer's half-minute retry (enrich).
+ let Ok(reply) = reply else {
+ self.usage_asked.remove(&machine);
+ if !self.usage.contains_key(&machine) { self.usage_checked = Instant::now().checked_sub(Duration::from_secs(270)) }
+ return;
+ };
+ let readings: Vec<fleet::Usage> = reply.get("providers").and_then(Value::as_array).map(|p| p.iter().filter_map(fleet::usage_from).collect()).unwrap_or_default();
+ self.usage.insert(machine, readings);
+ }
+
/// What the daemons know of each harness beyond its row, asked a few at a time, the focused
/// pane's first, then in the order they need you: its last recap (agent_recent — so what it did
/// is there after hn starts again), and the pull request for its branch (git_pull_request, at
@@ -6330,14 +6368,7 @@ impl App {
let ids: Vec<String> = self.fleet.machines.iter().filter(|m| m.usable()).map(|m| m.id.clone()).collect();
if ids.is_empty() { self.usage_checked = soon() }
for id in ids {
- let Some(link) = self.link(&id) else { self.usage_checked = soon(); continue };
- let generation = link.generation;
- self.spawn(async move { link.rpc("usage_read", json!({}), Duration::from_secs(30)).await }, move |app, reply| {
- if app.connection_generation(&id) != Some(generation) { return }
- let Ok(reply) = reply else { if !app.usage.contains_key(&id) { app.usage_checked = soon() } return };
- let readings: Vec<fleet::Usage> = reply.get("providers").and_then(Value::as_array).map(|p| p.iter().filter_map(fleet::usage_from).collect()).unwrap_or_default();
- app.usage.insert(id, readings);
- });
+ if !self.read_usage(&id) { self.usage_checked = soon() }
}
}
if self.enriching >= AT_ONCE { return }
@@ -7387,6 +7418,36 @@ mod recovery_tests {
assert!(matches!(&app.panes[&1].phase, Phase::Card { title, .. } if title == "This machine is not linked here"));
}
+ // A machine shared with this account showed the guest's own plans for up to five minutes after it
+ // connected: its usage (the owner's plans, which a harness there runs on) waited for the timer.
+ #[tokio::test]
+ async fn a_shared_machine_is_asked_its_usage_when_it_connects_and_at_most_once_a_minute() {
+ let mut app = fixture();
+ app.fleet.shares.insert("test-peer".into(), crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false });
+ app.on_machine("test-peer".into(), 1, MachineEvent::Connected);
+ let asked = *app.usage_asked.get("test-peer").expect("usage_read sent on connect");
+ app.read_usage("test-peer");
+ assert_eq!(app.usage_asked["test-peer"], asked, "not again within the minute");
+
+ // It dropped and connected again within the minute: the first connection's read is never
+ // answered here (its reply is that connection's), so the new one is asked its own.
+ app.links["test-peer"].link.as_ref().unwrap().close();
+ app.links.insert("test-peer".into(), LinkState { link: Some(Link::spawn(app.port, "test-peer", 2, app.sink.clone())), generation: 2, attempts: 0, retry_at: None });
+ app.on_machine("test-peer".into(), 2, MachineEvent::Connected);
+ assert_ne!(app.usage_asked["test-peer"], asked, "asked again on the new connection");
+ let again = app.usage_asked["test-peer"];
+
+ // The first connection's answer, arriving now, is not this one's: neither a failure nor plans.
+ app.usage_replied("test-peer".into(), 1, Err(RpcError::new("DISCONNECTED", "")));
+ app.usage_replied("test-peer".into(), 1, Ok(json!({ "providers": [] })));
+ assert_eq!(app.usage_asked["test-peer"], again);
+ assert!(!app.usage.contains_key("test-peer"));
+ // This connection's read failed: it may be asked again at once.
+ app.usage_replied("test-peer".into(), 2, Err(RpcError::new("TIMEOUT", "")));
+ assert!(!app.usage_asked.contains_key("test-peer"));
+ app.links["test-peer"].link.as_ref().unwrap().close();
+ }
+
// ── connections as measured (measure.rs): one per connection, not one per dial ──
/// Signed in, with this computer listed and connected so what is measured is sent.
diff --git a/tui/src/fleet.rs b/tui/src/fleet.rs
index 54721975b..dfd0be856 100644
--- a/tui/src/fleet.rs
+++ b/tui/src/fleet.rs
@@ -553,6 +553,10 @@ impl Fleet {
}
pub fn machine(&self, id: &str) -> Option<&Machine> { self.machines.iter().find(|m| m.id == id) }
+ /// Another account's machine, shared view-only ([Machine::shared]) or whole ([shares]): its daemon
+ /// answers as its owner, so a harness there is never this account's to move (desktop's
+ /// `belongsToOtherAccount`).
+ pub fn belongs_to_other_account(&self, id: &str) -> bool { self.shares.contains_key(id) || self.machine(id).is_some_and(|m| m.shared) }
pub fn machine_mut(&mut self, id: &str) -> Option<&mut Machine> { self.machines.iter_mut().find(|m| m.id == id) }
/// The account's record for this computer; the local PTY transport is not another machine.
pub fn registered_local_machine(&self) -> Option<&Machine> {
diff --git a/tui/src/models.rs b/tui/src/models.rs
index 742510667..f8d0c7230 100644
--- a/tui/src/models.rs
+++ b/tui/src/models.rs
@@ -565,7 +565,7 @@ pub struct Target { pub machine: String, pub agent: String, pub engine: String,
/// still manages local models.
pub fn pane_supports(app: &App, pane: u64) -> bool {
let Some(p) = app.panes.get(&pane) else { return false };
- app.fleet.machine(&p.machine_id).is_some_and(|m| !m.shared)
+ app.fleet.machine(&p.machine_id).is_some() && !app.fleet.belongs_to_other_account(&p.machine_id)
&& app.fleet.agent(&p.machine_id, &p.agent_id).is_some_and(|a| a.status != "stopped" && ["codex", "claude", "opencode", "pi"].contains(&a.engine.as_str()))
}
@@ -581,7 +581,7 @@ pub fn pane_label(app: &App, pane: u64) -> String {
pub fn target(app: &App) -> Option<Target> {
let of = |machine: String, agent: String| -> Option<Target> {
- if app.fleet.machine(&machine).is_some_and(|m| m.shared) { return None }
+ if app.fleet.belongs_to_other_account(&machine) { return None }
let a = app.fleet.agent(&machine, &agent)?;
let a = if app.models_view.selection_fixed { if a.status == "stopped" { return None } a } else { live_in_pane(app, a) };
(a.engine != "terminal").then(|| Target { engine: a.engine.clone(), grid_model: a.grid_model.clone(), base_url: a.grid_base_url.clone(), machine, agent: a.id.clone() })
@@ -2071,6 +2071,9 @@ pub fn open(app: &mut App) {
app.models_view.selection_pane = app.focused();
select(app);
app.models_view.panel_generation = app.models_view.panel_generation.wrapping_add(1);
+ // Each machine's subscriptions as it says them now (at most once a minute each, read_usage).
+ let usable: Vec<String> = app.fleet.machines.iter().filter(|m| m.usable() && !crate::local::is_local(&m.id)).map(|m| m.id.clone()).collect();
+ for id in usable { app.read_usage(&id); }
let machine = app.fleet.local_id.clone();
if machine.is_empty() || app.link(&machine).is_none() { return }
if !app.models_view.reading.contains(&machine) { read_local(app, &machine) }
@@ -2716,6 +2719,20 @@ mod tests {
}
}
+ /// A harness on a machine shared with this account by email runs on its owner's plans, which its
+ /// daemon alone moves: no "Change model…", and no Use moves it (desktop's isSharedMachine).
+ #[test]
+ fn a_harness_on_a_machine_shared_with_you_is_not_moved_from_here() {
+ let mut app = app();
+ app.fleet.machines.push(Machine { shared: false, id: "dee".into(), name: "Dee's Mac".into(), local: false, status: "online".into(), reach: Reach::Ready });
+ app.fleet.agents.insert(("dee".into(), "g1".into()), crate::fleet::agent_from("dee", &json!({ "id": "g1", "name": "guest", "engine": "claude" }), None));
+ app.panes.insert(1, crate::pane::Pane::new(1, "dee", "g1", 150, 40));
+ assert!(pane_supports(&app, 1) && target(&app).is_some(), "an own machine's harness moves");
+ app.fleet.shares.insert("dee".into(), crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false });
+ assert!(!pane_supports(&app, 1));
+ assert!(target(&app).is_none());
+ }
+
#[test]
fn models_opened_while_a_harness_starts_takes_it_once_its_engine_is_seen() {
let mut app = app();
diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rs
index 2de64804c..8d1fb39b2 100644
--- a/tui/src/new_harness.rs
+++ b/tui/src/new_harness.rs
@@ -116,6 +116,9 @@ pub struct Form {
launch_target: Option<crate::input::LaunchTarget>,
remember_choices: bool,
local_only: bool,
+ /// On a machine shared with this account (guest sharing): its harness runs on the owner's plans,
+ /// and the owner's daemon lists a guest no models or profiles.
+ guest: bool,
prepared_folder: Option<String>,
focus: Field,
child: Option<Child>,
@@ -170,13 +173,13 @@ impl Form {
// The machine is its own row, here and on the page: not "project @ machine" in one.
let mut fields = vec![Field::Task, Field::Agent, Field::Machine, Field::Project];
if !page && git_controls { fields.extend([Field::Branch, Field::Worktree]); }
- if self.draft.what.engine != "terminal" {
+ if self.draft.what.engine != "terminal" && !self.guest {
fields.push(Field::Model);
}
if !data::modes(&self.draft.what.engine).is_empty() {
fields.push(Field::Approvals);
}
- if self.draft.what.engine == "codex" && self.draft.model.is_none() {
+ if self.draft.what.engine == "codex" && self.draft.model.is_none() && !self.guest {
fields.push(Field::Profile);
}
if page && git_controls { fields.extend([Field::Worktree, Field::Branch]); }
@@ -551,6 +554,7 @@ fn make_form(app: &mut App, machine: Option<String>, cwd: Option<String>, surfac
launch_target: None,
remember_choices: true,
local_only: false,
+ guest: false,
prepared_folder: None,
focus: if task::supported(&engine) { Field::Task } else { Field::Create },
child: None,
@@ -583,6 +587,7 @@ fn make_form(app: &mut App, machine: Option<String>, cwd: Option<String>, surfac
fn refresh_form(app: &App, form: &mut Form) {
form.machine_label = machine_label(app, &form.draft.machine);
form.local_only = crate::local::is_local(&form.draft.machine) && app.daemon_down;
+ form.guest = app.fleet.shares.contains_key(&form.draft.machine);
// Git discovery can finish while its controls have keyboard focus.
if matches!(form.focus, Field::Branch | Field::Worktree) && !form.fields().contains(&form.focus) {
form.focus = Field::Project;
@@ -1200,6 +1205,8 @@ fn set_machine(app: &mut App, form: &mut Form, machine: &str) {
form.models = Value::Null;
form.profiles = Value::Null;
form.draft.profile = None;
+ // A guest's harness runs on the owner's plans: a model chosen for another machine stays behind.
+ if app.fleet.shares.contains_key(machine) { form.draft.model = None }
form.resource_generation.clear();
crate::input::load_dsh(app, machine.into(), false);
refresh_form(app, form);
@@ -2052,6 +2059,24 @@ mod tests {
assert!(agent_rows(&app, "local").len() > 2);
}
+ /// A guest's harness runs on the owner's plans, and the owner's daemon lists a guest no models or
+ /// profiles (GUEST_NOT_ALLOWED): no Model or Profile is offered there, and none chosen goes along.
+ #[tokio::test]
+ async fn a_guest_is_offered_no_model_or_profile_on_a_machine_shared_with_it() {
+ let mut app = app();
+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "dee".into(), name: "Dee's Mac".into(), local: false, status: "online".into(), reach: crate::fleet::Reach::Ready });
+ app.fleet.shares.insert("dee".into(), crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false });
+ open(&mut app, None, Some("/home/dev/repo".into()));
+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };
+ set_engine(&mut form, "codex");
+ assert!(form.fields().contains(&Field::Model) && form.fields().contains(&Field::Profile), "this computer's own");
+ form.draft.model = Some(("own-grid".into(), "qwen-35b".into(), "studio".into()));
+ set_machine(&mut app, &mut form, "dee");
+ assert!(!form.fields().contains(&Field::Model));
+ assert!(!form.fields().contains(&Field::Profile));
+ assert_eq!((form.draft.model.clone(), form.draft.profile.clone()), (None, None));
+ }
+
fn app() -> App {
let (sink, _) = tokio::sync::mpsc::unbounded_channel();
let mut app = App::new(19789, sink, (150, 42));
diff --git a/tui/src/session_close.rs b/tui/src/session_close.rs
index ea03c69bd..27dfe7f41 100644
--- a/tui/src/session_close.rs
+++ b/tui/src/session_close.rs
@@ -33,6 +33,14 @@ impl Identity {
&& app.fleet.agent(&self.machine, &self.agent).is_some_and(|a| a.session_id == self.session && a.created_at_wire == self.created)
}
+ /// The reviewed harness, as it is now: the same agent, and the reviewed conversation or, reviewed before its
+ /// engine bound one (Codex's first seconds), the one it bound since. The row may now be stopped. Desktop's
+ /// `Agent.continuesSession`; a Stop still names the reviewed identity and the daemon decides (cli `matches`).
+ pub fn continues(&self, app: &App) -> bool {
+ self.connection_matches(app) && app.fleet.agent(&self.machine, &self.agent)
+ .is_some_and(|a| a.created_at_wire == self.created && (a.session_id == self.session || self.session.is_empty()))
+ }
+
pub fn connection_matches(&self, app: &App) -> bool {
self.owner_matches(app) && self.generation == app.connection_generation(&self.machine)
}
@@ -61,7 +69,11 @@ impl View {
fn matches(&self, app: &App) -> bool {
self.owner == app.fleet.local_id && app.panes.get(&self.pane).is_some_and(|p| p.machine_id == self.machine && p.agent_id == self.agent)
- && self.epoch == app.fleet.agent(&self.machine, &self.agent).map(|a| (a.session_id.clone(), a.created_at_wire.clone()))
+ && match (&self.epoch, app.fleet.agent(&self.machine, &self.agent)) {
+ // (Captured before its first conversation bound: the same view of it once one has.)
+ (Some((session, created)), Some(a)) => *created == a.created_at_wire && (session.is_empty() || *session == a.session_id),
+ (epoch, agent) => epoch.is_none() && agent.is_none(),
+ }
}
}
@@ -200,7 +212,7 @@ fn advance(app: &mut App, id: &str) {
let Some(op) = &app.session_close.operation else { return };
if op.id != id { return }
if op.stage == Stage::Inspect && !showing(app, id) { app.session_close.operation = None; return }
- if !op.targets.iter().filter(|t| !t.closed).all(|t| t.identity.matches(app)) {
+ if !op.targets.iter().filter(|t| !t.closed).all(|t| t.identity.continues(app)) {
fail(app, "The session or connection changed. Check it before trying again.".into()); return;
}
if op.at >= op.targets.len() {
@@ -244,10 +256,13 @@ fn received(app: &mut App, id: &str, index: usize, mode: &str, reply: Result<Val
let Some(op) = &app.session_close.operation else { return };
if op.id != id || op.at != index { return }
if mode == "inspect" && !showing(app, id) { app.session_close.operation = None; return }
- let identity = op.targets[index].identity.clone();
- let removed_before_ack = mode != "inspect" && identity.connection_matches(app)
+ let mut identity = op.targets[index].identity.clone();
+ // Closed and its row already gone: an inspect can answer that too, when it was closed elsewhere first.
+ let removed_before_ack = identity.connection_matches(app)
&& app.fleet.agent(&identity.machine, &identity.agent).is_none() && reply.as_ref().is_ok_and(|r| r["closed"] == true);
- if !identity.matches(app) && !removed_before_ack { fail(app, "The session or connection changed. No replacement was stopped.".into()); return }
+ if !identity.continues(app) && !removed_before_ack { fail(app, "The session or connection changed. No replacement was stopped.".into()); return }
+ // From here on, the conversation it bound since the review (if it did): the views and other clients know that one.
+ if let Some(a) = app.fleet.agent(&identity.machine, &identity.agent) { identity.session = a.session_id.clone(); }
let reply = match reply {
Ok(reply) => reply,
Err(error) => {
@@ -272,14 +287,16 @@ fn received(app: &mut App, id: &str, index: usize, mode: &str, reply: Result<Val
fail(app, format!("Stop not confirmed: {}", reply["detail"].as_str().filter(|s| !s.is_empty()).unwrap_or(error)));
return;
}
- if mode != "inspect" && reply["closed"] != true {
+ // An inspect can answer closed too: stopped already (by another window, or a close whose answer was lost).
+ let closed = reply["closed"] == true;
+ if mode != "inspect" && !closed {
fail(app, "Stop not confirmed. The pane is still here.".into()); return;
}
let op = app.session_close.operation.as_mut().unwrap();
let target = &mut op.targets[index];
- if mode == "inspect" { target.activity = activity; } else { target.closed = true; }
+ if closed { target.closed = true; target.identity = identity.clone(); } else { target.activity = activity; }
op.at += 1;
- if mode != "inspect" {
+ if closed {
crate::workspace_events::publish(app, &identity, None);
remove_confirmed(app, &identity);
}
@@ -590,6 +607,68 @@ mod tests {
assert!(!app.panes.contains_key(&1)); assert!(app.panes.contains_key(&2));
}
+ #[tokio::test]
+ async fn a_harness_that_bound_its_first_conversation_while_stopping_is_stopped() {
+ // Codex's first seconds: reviewed with no conversation; the daemon waits for the bind (agent_synced),
+ // stops it (agent_deleted marks the row stopped), then answers closed.
+ let mut app = app();
+ app.fleet.agents.get_mut(&("local".into(), "a1".into())).unwrap().session_id.clear();
+ pane(&mut app, 1);
+ answer(&mut app, "inspect", json!({"activity":"idle"}));
+ assert_eq!(app.session_close.sent[1].1["sessionId"], "");
+ let row = app.fleet.agents.get_mut(&("local".into(), "a1".into())).unwrap();
+ row.session_id = "codex-bound".into();
+ row.status = "stopped".into();
+ answer(&mut app, "idle", json!({"closed":true}));
+ assert!(app.session_close.operation.is_none(), "the stop is done");
+ assert!(!app.panes.contains_key(&1)); assert!(app.panes.contains_key(&2));
+ assert!(app.modal.is_none());
+ assert!(app.toast.as_ref().is_none_or(|t| !t.0.contains("changed")));
+ }
+
+ #[tokio::test]
+ async fn another_conversation_after_a_bound_one_is_still_a_change() {
+ let mut app = app();
+ pane(&mut app, 1);
+ answer(&mut app, "inspect", json!({"activity":"idle"}));
+ app.fleet.agents.get_mut(&("local".into(), "a1".into())).unwrap().session_id = "replacement".into();
+ answer(&mut app, "idle", json!({"closed":true}));
+ assert!(app.panes.contains_key(&1));
+ assert!(app.session_close.operation.as_ref().is_some_and(|op| op.stage == Stage::Failed));
+ }
+
+ #[tokio::test]
+ async fn inspecting_an_already_closed_harness_finishes_the_close() {
+ let mut app = app();
+ pane(&mut app, 1);
+ answer(&mut app, "inspect", json!({"closed":true}));
+ assert_eq!(modes(&app), ["inspect"], "nothing left to stop");
+ assert!(app.session_close.operation.is_none());
+ assert!(!app.panes.contains_key(&1)); assert!(app.panes.contains_key(&2));
+ assert_eq!(app.fleet.agent("local", "a1").unwrap().status, "stopped");
+ assert!(app.modal.is_none());
+ }
+
+ #[tokio::test]
+ async fn inspecting_a_harness_already_closed_and_gone_from_the_list_finishes_the_close() {
+ // Closed elsewhere, and its row removed before the inspect's answer: closed, not "changed".
+ let mut app = app();
+ pane(&mut app, 1);
+ app.fleet.agents.remove(&("local".into(), "a1".into()));
+ answer(&mut app, "inspect", json!({"closed":true}));
+ assert_eq!(modes(&app), ["inspect"], "nothing left to stop");
+ assert!(app.session_close.operation.is_none());
+ assert!(!app.panes.contains_key(&1)); assert!(app.panes.contains_key(&2));
+ assert!(app.toast.as_ref().is_none_or(|t| !t.0.contains("changed")));
+ // A row gone with an inspect answering what it is doing is still a change.
+ let mut app = self::app();
+ pane(&mut app, 1);
+ app.fleet.agents.remove(&("local".into(), "a1".into()));
+ answer(&mut app, "inspect", json!({"activity":"idle"}));
+ assert!(app.panes.contains_key(&1));
+ assert!(app.session_close.operation.as_ref().is_some_and(|op| op.stage == Stage::Failed));
+ }
+
#[tokio::test]
async fn partial_tab_stop_keeps_failed_sessions_and_other_tabs() {
let mut app = app();