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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Refactor agent resume logic and improve UI handling for stopped agents
Dev jacobed166f9b8730
diff --git a/cli/docker/remote-machine/Dockerfile b/cli/docker/remote-machine/Dockerfileindex 521d06e6c..d6ff1b953 100644--- a/cli/docker/remote-machine/Dockerfile+++ b/cli/docker/remote-machine/Dockerfile@@ -50,9 +50,11 @@ ENV LC_ALL=C.UTF-8# from the host can ever reach a loopback bind. socat bridges exactly that gap, on the container# side, for the duration of a sign-in. Doing it here rather than teaching the CLI to bind 0.0.0.0# keeps a real computer's SSO callback on its own loopback, where it belongs.+# tini: pid 1. Every engine a stopped agent leaves behind is orphaned to pid 1, and only a real init+# reaps it — see the ENTRYPOINT below.RUN apt-get update \&& apt-get install -y --no-install-recommends \- tmux procps git curl ca-certificates less socat \+ tmux procps git curl ca-certificates less socat tini \&& rm -rf /var/lib/apt/lists/*# The engine under test. Pinned by the build so a rebuild is reproducible; bump it deliberately.@@ -124,4 +126,10 @@ USER nodeWORKDIR /home/nodeVOLUME ["/home/node/.harness"]-ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]+# ⚠️ **tini is pid 1, not the entrypoint, and a real computer's init is what it stands in for.** The+# entrypoint used to `exec tail -f /dev/null` as pid 1, and tail never calls wait(): every engine+# orphaned when its agent stopped stayed a zombie for the life of the box — with the pid, name and+# start time of the engine it had been. The daemon's identity check read that as the engine still+# running, and refused to resume the agent ("The previous process is still running"). tini reaps+# them, and forwards `docker stop`'s SIGTERM to the entrypoint as tail's pid-1 role did.+ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/entrypoint.sh"]diff --git a/cli/docker/remote-machine/entrypoint.sh b/cli/docker/remote-machine/entrypoint.shindex d8f5e2fd2..b50e9c687 100755--- a/cli/docker/remote-machine/entrypoint.sh+++ b/cli/docker/remote-machine/entrypoint.sh@@ -2,7 +2,7 @@# Keep the box alive, and bring the daemon up when — and only when — it has a session to come up with.## The container is a BOX, not a daemon supervisor. `harness start` self-daemonizes on a real machine-# and does the same here, so pid 1 is this script rather than the adapter: that way a `harness stop`+# and does the same here, so the adapter is not what holds the box open: that way a `harness stop`# from a test, or a daemon that exits on its own, does not take the whole container down and strand# the SSO session and computer id that the next step needs.#@@ -24,6 +24,7 @@ elsefiecho "[entrypoint] ready; holding the container open"-# `exec` so this becomes pid 1 and a `docker stop` reaches it as SIGTERM rather than waiting out the-# 10s grace period on a shell that is ignoring it.+# `exec` so tini's one child is tail itself, and the SIGTERM tini forwards on `docker stop` ends it at+# once rather than waiting out the 10s grace period on a shell that is ignoring it. Reaping is tini's+# job (pid 1, see the Dockerfile's ENTRYPOINT) — tail never waits on anything.exec tail -f /dev/nulldiff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex cc0c40199..52f9e6218 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -11,6 +11,7 @@ import {engineProcessMatch,engineProcessMatchScore,LSTART_MARKER_RE,+ liveProcessRows,parseProcessRow,resumeSessionId,sendLiteralToTmux,@@ -28,6 +29,21 @@ const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwne})describe('tmux process primitives', () => {+ it('drops a zombie from the process table — it keeps the identity of the engine it no longer is', () => {+ // The row the remote-machine rig showed for a stopped agent's Claude, orphaned to a pid 1 that+ // never reaped: same pid, comm and start time as the saved identity, so resume thought it alive.+ const zombie = parseProcessRow('78206 1 claude Tue Sep 22 08:23:44 2026 [claude] <defunct>')!+ const bsdZombie = parseProcessRow('78207 1 (claude) Tue Sep 22 08:23:44 2026 <defunct>')!+ const live = parseProcessRow('3998 3992 node Mon Sep 21 08:15:25 2026 node /home/node/.npm-global/bin/codex')!+ // Only a TRAILING marker is a corpse; an argument that mentions the word is a running process.+ const mentions = parseProcessRow('4000 3992 grep Mon Sep 21 08:15:25 2026 grep <defunct> log.txt')!+ // Pids that do not exist here, so on Linux the /proc check cannot vouch for a live process either.+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')+ expect(liveProcessRows([zombie, live, bsdZombie, mentions])).toEqual([live, mentions])+ vi.restoreAllMocks()+ })++it('parses a process whose comm field contains spaces', () => {expect(parseProcessRow('4242 100 ⌘ Greeting Thu Jul 30 11:00:03 2026 cmd -r abcdef12-3456-7890-abcd-ef1234567890')).toEqual({pid: 4242,diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 9348c6dd8..dfc0f8374 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -179,6 +179,36 @@ function readProcField(pid: number, field: 'cmdline' | 'comm'): string | null {try { return readFileSync(`/proc/${pid}/${field}`, 'utf8') } catch { return null }}+/**+ * The rows that are actually running: a zombie is dropped.+ *+ * ⚠️ **A zombie keeps its pid, its command name and its start time — everything an identity check+ * compares — while being dead.** It stays in the table until its parent reaps it, and an orphan's+ * parent is pid 1, which in a container is often something that never reaps (`tail -f /dev/null` in+ * the remote-machine rig did not). `checkPidRuntime` then called the zombie of a stopped agent's+ * engine "alive", and resume refused that agent for as long as the zombie lasted — forever — with+ * "The previous process is still running". No consumer of the process table wants one: a zombie+ * runs nothing, holds no conversation, and can be neither signalled nor attached to.+ *+ * `ps` renders one as `[comm] <defunct>` (procps) or `<defunct>` (BSD). On Linux the kernel's own+ * state letter settles it, so an argv that merely ENDS in that word is never mistaken for a corpse.+ */+export function liveProcessRows(rows: ProcessRow[]): ProcessRow[] {+ return rows.filter((row) => !isZombie(row))+}++function isZombie(row: ProcessRow): boolean {+ if (!/(^|\s)<defunct>$/.test(row.args)) return false+ if (process.platform !== 'linux') return true+ // `pid (comm) S ...` — comm may hold spaces and parentheses, so the state is read after the LAST `)`.+ const stat = readProcStat(row.pid)+ return stat === null || stat.slice(stat.lastIndexOf(')') + 1).trimStart().startsWith('Z')+}++function readProcStat(pid: number): string | null {+ try { return readFileSync(`/proc/${pid}/stat`, 'utf8') } catch { return null }+}+/*** A `ps` that is already running answers everyone who asks while it runs. The first reconcile pass* after a boot attaches a few agents at once and every attach validates its pane against the table,@@ -208,7 +238,7 @@ async function readProcessRows(): Promise<ProcessRow[] | null> {resolve(rows)})})- return rows ? repairMangledRows(rows) : null+ return rows ? liveProcessRows(repairMangledRows(rows)) : null}function execText(command: string, args: string[], timeout: number): Promise<string | null> {diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex 4db1d722d..1b7acb9c6 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -24,6 +24,7 @@ import {ambiguousAgentProcess,engineProcessMatchScore,enrichProcessRows,+ liveProcessRows,parseProcessRow,processTreePids,resumeSessionId,@@ -304,7 +305,7 @@ export async function probeTmuxAgents(])if (!tmux.ok) return { ok: false, error: `tmux list-panes failed: ${tmux.error}` }if (!ps.ok) return { ok: false, error: `process table failed: ${ps.error}` }- const parsed = ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null)+ const parsed = liveProcessRows(ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null))const rows = await enrichProcessRows(parsed, processTreePids(parsed, tmux.panes.map((pane) => pane.rootPid)))const probe = discoverTmuxAgentsFromSnapshot(tmux.panes,diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dartindex 0789497dc..a3ba4960c 100644--- a/mobile/lib/core/models.dart+++ b/mobile/lib/core/models.dart@@ -272,7 +272,7 @@ class Agent {);/// Saved work the daemon is no longer running, as the desktop's [Agent] reads- /// it. Its conversation is on disk; `agent_restart` brings it back.+ /// it. Its conversation is on disk; `agent_resume` brings it back.////// ⚠️ **Only ever set on a machine the app asked `includeStopped: true` of.**/// The daemon's plain `agents_list` answers with `registry.advertised()` —@@ -280,6 +280,14 @@ class Agent {/// stopped work silently missing, which is exactly what this app did.bool get isStopped => status == 'stopped';+ /// Whether a resume has a conversation to reopen — the desktop's rule, and the daemon's+ /// (`resumeStoppedAgent.ts`): exact resume exists for Claude Code and Codex only, and only once the+ /// engine has saved a session. An agent stopped before its first prompt never got one, and the+ /// machine answers RESUME_UNAVAILABLE for it however many times it is asked.+ bool get canResumeConversation =>+ (engine == 'claude' || engine == 'codex') &&+ sessionId?.isNotEmpty == true;+static String? _safeEngine(Object? raw) {if (raw is! String || raw.isEmpty || raw.length > 64) return null;return RegExp(r'^[a-zA-Z0-9._-]+$').hasMatch(raw) ? raw : null;diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dartindex 572b9103e..b2e36099c 100644--- a/mobile/lib/e2ee/envelope.dart+++ b/mobile/lib/e2ee/envelope.dart@@ -9,9 +9,10 @@ import 'primitives.dart';const int e2eVersion = 1;-/// Frames this client must send as ciphertext — core.ts `ENCRYPTED_DOWN_TYPES`. test/e2ee/ holds it-/// to the CLI's own list, because a type missing here fails nowhere: the frame simply leaves in the-/// clear, and for terminal_* the relay then drops it as TERMINAL_FRAME_REJECTED.+/// Frames this client must send as ciphertext — core.ts `ENCRYPTED_DOWN_TYPES`.+/// `test/encrypted_down_types_test.dart` holds it to the CLI's own list, because a type missing here+/// fails nowhere on the phone: the frame simply leaves in the clear, and the machine refuses it with+/// E2EE_REQUIRED (for terminal_* the relay drops it as TERMINAL_FRAME_REJECTED).const Set<String> encryptedDownTypes = {'message','question_response',@@ -23,6 +24,11 @@ const Set<String> encryptedDownTypes = {'agent_create_status','agent_delete','agent_restart',+ // Reopens stopped work (`AppNotifier.resumeAgent`). Missing here, every tap on a Stopped row came+ // back "Could not open this harness: E2EE_REQUIRED".+ 'agent_resume',+ // Carries the fork's name and first task — what the person typed — like agent_create's prompt.+ 'agent_fork','agent_recent','agent_update','agent_files',diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dartindex 3b6c102f1..16818f685 100644--- a/mobile/lib/phone/agent_home.dart+++ b/mobile/lib/phone/agent_home.dart@@ -157,6 +157,7 @@ class _AgentHomeState extends State<AgentHome> {widget.openAgent?.removeListener(_onAgentRequested);_loadingDeadline?.cancel();_restoreDeadline?.cancel();+ _terminalWait?.cancel();super.dispose();}@@ -266,6 +267,37 @@ class _AgentHomeState extends State<AgentHome> {};}+ /// How long the remembered agent gets to have its terminal verified, once its machine has listed+ /// it — see [_pendingEntryFor].+ ///+ /// 10s: the daemon's reconciler sweeps once as it starts and then every five seconds at its floor+ /// (`TMUX_REAP_INTERVAL_MS`), so a pane that is really there is reported inside two sweeps. Past+ /// that the agent genuinely has no terminal — a pane that was closed, a machine that reaped it —+ /// and the screen stops holding out for one.+ static const _terminalWaitTimeout = Duration(seconds: 10);+ Timer? _terminalWait;+ bool _terminalWaitGaveUp = false;++ /// Whether the remembered agent is listed with its terminal still unverified, and the screen is+ /// still willing to wait for it.+ ///+ /// ⚠️ Arms [_terminalWait] on the first frame that waits, and is called from `build` — a timer,+ /// not a rebuild, so it changes nothing in the frame it is created in. It cannot be armed with+ /// [_restoreDeadline] instead: that one starts when the record is read, while this wait only+ /// begins once a machine has listed the agent, which may be seconds later.+ bool _terminalStillComing(+ List<AgentEntry> entries,+ ({String machineId, String agentId}) agent,+ ) {+ if (_terminalWaitGaveUp) return false;+ if (_pendingEntryFor(entries, agent) == null) return false;+ _terminalWait ??= Timer(_terminalWaitTimeout, () {+ if (!mounted) return;+ setState(() => _terminalWaitGaveUp = true);+ });+ return true;+ }+/// The machine list's own word on whether the machine is up — the REST status, not the socket.static bool _accountSaysOnline(String? status) =>switch (status?.trim().toLowerCase()) {@@ -277,6 +309,20 @@ class _AgentHomeState extends State<AgentHome> {/// build so the wait draws as "Connecting…", never as the empty state.bool _waitingForRestore = false;+ /// Whether that wait is for the agent's own terminal rather than for its machine — see+ /// [_terminalStillComing]. Only the message differs; saying "Connecting to your machine…" over a+ /// machine that has already answered names the wrong thing to be patient with.+ bool _waitingForTerminal = false;++ /// What to tell somebody while the screen holds out for the agent it means to reopen.+ String? _restoreMessage() {+ if (_waitingForTerminal) return 'Reopening your harness…';+ // Every other machine may be up and loaded while the one holding the remembered agent is still+ // dialling — without this the wait would draw as "No agents yet".+ if (_waitingForRestore) return 'Connecting to your machine…';+ return null;+ }+/// The agent to draw, given what the account can currently reach.////// In order:@@ -287,6 +333,7 @@ class _AgentHomeState extends State<AgentHome> {/// - nothing openable at all → null, and the empty state says so.AgentEntry? _target(List<AgentEntry> entries) {_waitingForRestore = false;+ _waitingForTerminal = false;// Picked by hand elsewhere — see [AgentHome.openAgent]. Until it is in the list, the screen keeps// what it has rather than blanking.final requested = _requestedAgent;@@ -316,6 +363,14 @@ class _AgentHomeState extends State<AgentHome> {if (opened != null) {final live = _entryFor(entries, opened);if (live != null) return live;+ // ⚠️ **Unopenable for a moment is not gone — see [_pendingEntryFor].** Returned so `chosen`+ // goes on naming the agent the pager was built for: the key and the snapshot below are left+ // exactly as they are, and the terminal on screen reattaches by itself once the pane is+ // verified (`_attachPendingPanes`). Falling through instead moved somebody off the terminal+ // they were reading, onto an unrelated agent, for a flag that flips back a second later.+ // A real deletion still takes the pager away, through [_dropPagerIfShownAgentWasDeleted].+ final pending = _pendingEntryFor(entries, opened);+ if (pending != null) return pending;}final showing = _showing;if (showing != null) {@@ -327,11 +382,21 @@ class _AgentHomeState extends State<AgentHome> {// later there was no going back to it. Only before any pager is up, only while that machine// is genuinely on its way, and only until [_restoreDeadline] — an agent that was deleted, or a// machine that stays down, still falls through to the first agent below.- if (_neighboursFor == null &&- !_restoreGaveUp &&- _machineStillComing(showing.machineId)) {- _waitingForRestore = true;- return null;+ if (_neighboursFor == null && !_restoreGaveUp) {+ if (_machineStillComing(showing.machineId)) {+ _waitingForRestore = true;+ return null;+ }+ // ⚠️ **And the agent's own terminal is waited for after that, which is a different wait.**+ // Its machine can be answering with a loaded list and the agent on it still be unopenable,+ // for the seconds its pane takes to be verified — see [_terminalStillComing]. Without this+ // the record lost its claim in exactly that window, and the launch settled for the first+ // agent that happened to have been verified already.+ if (_terminalStillComing(entries, showing)) {+ _waitingForRestore = true;+ _waitingForTerminal = true;+ return null;+ }}}return entries.where((entry) => entry.agent.terminalAvailable).firstOrNull;@@ -460,6 +525,30 @@ class _AgentHomeState extends State<AgentHome> {).firstOrNull;+ /// The entry naming [agent] while it is LISTED but not attachable yet — the machine has it, its+ /// terminal has simply not been verified in this instant. Null for an agent that is not there,+ /// and for a stopped one, whose terminal is not coming back on its own.+ ///+ /// ⚠️ **"No terminal" is what an agent looks like while nobody has LOOKED at its pane, not what a+ /// missing agent looks like.** The daemon clears every agent's availability as it loads its+ /// registry (`cli/src/lib/registry.ts`) and fills it back in one agent at a time, as its terminal+ /// reconciler observes each pane — so a restart leaves every agent on the machine reading+ /// unopenable for a moment, and each `agent_synced` frame after it turns one of them back on.+ /// Reading that as "gone" is what sent a launch, and a pager mid-session, to whichever agent+ /// happened to be verified first: the oldest one on the machine.+ AgentEntry? _pendingEntryFor(+ List<AgentEntry> entries,+ ({String machineId, String agentId}) agent,+ ) => entries+ .where(+ (entry) =>+ entry.machineId == agent.machineId &&+ entry.agent.id == agent.agentId &&+ !entry.agent.terminalAvailable &&+ !entry.agent.isStopped,+ )+ .firstOrNull;+@overrideWidget build(BuildContext context) => ListenableBuilder(listenable: widget.notifier,@@ -482,11 +571,7 @@ class _AgentHomeState extends State<AgentHome> {// cards promises the wrong thing and then never delivers it. [_AgentHomeLoading] says what// is happening in words instead, and hands over to the terminal's own "Attaching…" — the// two are built to read as one sequence.- final loading =- _loadingMessage() ??- // Every other machine may be up and loaded while the one holding the remembered agent- // is still dialling — without this the wait would draw as "No agents yet".- (_waitingForRestore ? 'Connecting to your machine…' : null);+ final loading = _loadingMessage() ?? _restoreMessage();_traceLoading(loading);if (loading != null) return _AgentHomeLoading(message: loading);// ⚠️ **No machine is open → this is a MACHINE problem, so the machine screen is what the@@ -533,6 +618,11 @@ class _AgentHomeState extends State<AgentHome> {// where they are, now with every agent of the tab beside them.final snapshot = _neighbours;if (snapshot != null &&+ // ⚠️ **Not while the agent on screen is mid-verification.** Its tab's entries are the+ // openable ones, so an agent whose pane is still being looked at is missing from them —+ // the sets differ for that alone, and the retake would rebuild the pager around a list+ // that no longer holds the agent it is showing, landing it on the list's first page.+ _pendingEntryFor(entries, chosen) == null &&// ⚠️ **Only while the pager is STAYING where it is.** `target` is the// agent the pager opened on for as long as that agent is openable, so// anything else means the screen is being moved on purpose — a tab@@ -658,7 +748,11 @@ class _AgentHomeState extends State<AgentHome> {if (machine == null ||phoneMachineStatusOf(machine) != PhoneMachineStatus.ready ||machine.agentLoadStatus != AgentLoadStatus.loaded ||- machine.agents.any((agent) => agent.id == showing.agentId)) {+ // A STOPPED agent stays on its machine's list (a stop arrives as `agent_synced`, and is+ // kept so it can be resumed) but there is nothing left on screen to show for it.+ machine.agents.any(+ (agent) => agent.id == showing.agentId && !agent.isStopped,+ )) {return;}if (!entries.any((entry) => entry.agent.terminalAvailable)) return;diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dartindex 4345a4c9a..1c4098221 100644--- a/mobile/lib/phone/agent_index.dart+++ b/mobile/lib/phone/agent_index.dart@@ -31,11 +31,18 @@ class AgentEntry {/// Whether a tap can land on this agent — it has a terminal, or it is saved/// work a resume can bring back ([AppNotifier.resumeAgent]).///+ /// ⚠️ **Stopped is not enough: there has to be a conversation to bring back**+ /// ([Agent.canResumeConversation]), the desktop's `canOpen`. Stopped work+ /// with none was offered as a tap that could only ever end in "no supported+ /// saved conversation to resume".+ ////// ⚠️ **Not `terminalAvailable` alone.** A stopped agent has no terminal and/// never will until something restarts it, so the bare flag sorted every one/// of them to the bottom of every list and made them untappable — which,/// before the app asked for them at all, was invisible. It is visible now.- bool get isOpenable => agent.terminalAvailable || agent.isStopped;+ bool get isOpenable =>+ agent.terminalAvailable ||+ (agent.isStopped && agent.canResumeConversation);/// When its conversation last moved: the machine's own [Agent.updatedAt], or/// a turn this app saw since ([MachineState.agentActivityAt]) — whichever isdiff --git a/mobile/lib/phone/agents_list_page.dart b/mobile/lib/phone/agents_list_page.dartindex 117023571..9d673a176 100644--- a/mobile/lib/phone/agents_list_page.dart+++ b/mobile/lib/phone/agents_list_page.dart@@ -217,8 +217,9 @@ class _BodyState extends State<_Body> {row: row,terms: terms,now: now,- openable: (row.entry?.isOpenable ?? false) && _resuming == null,+ openable: row.entry?.isOpenable ?? false,resuming: _resuming == row.id,+ busy: _resuming != null,quote: phoneContentSnippet(row, terms, notifier.sessionPreviews),onTap: () => _open(drawn, row),),diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dartindex c6cfeb0ec..478f52b42 100644--- a/mobile/lib/phone/phone_search_results.dart+++ b/mobile/lib/phone/phone_search_results.dart@@ -123,8 +123,9 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {row: row,terms: terms,now: now,- openable: search.canSubmit(row) && _resuming == null,+ openable: search.canSubmit(row),resuming: _resuming == row.id,+ busy: _resuming != null,// A row that is here for something said in its conversation quotes// it in place of its detail: nothing else on the row would explain// why it matched.diff --git a/mobile/lib/phone/phone_search_row.dart b/mobile/lib/phone/phone_search_row.dartindex e0fe5ed1a..874184f12 100644--- a/mobile/lib/phone/phone_search_row.dart+++ b/mobile/lib/phone/phone_search_row.dart@@ -30,6 +30,7 @@ class PhoneSearchRow extends StatefulWidget {required this.onTap,this.quote,this.resuming = false,+ this.busy = false,});final PhoneDestination row;@@ -51,6 +52,14 @@ class PhoneSearchRow extends StatefulWidget {/// edge spins instead of repeating `Stopped` at somebody already waiting.final bool resuming;+ /// Whether another row's resume is still running, so this one takes no tap until it settles.+ ///+ /// ⚠️ **Not folded into [openable], which is what it used to be.** [openable] is also what dims+ /// the row and names the reason on its trailing edge, so every other agent in the list read+ /// `No terminal` for as long as one was resuming — a claim about their terminals that was never+ /// true. Being briefly unable to take a tap is not a property of the agent.+ final bool busy;+/// The line of session content that explains a row nothing else on it would:/// see [phoneContentSnippet]. Replaces the identity line when there is one,/// because a row matched on something said in its conversation has nothing on@@ -64,8 +73,10 @@ class PhoneSearchRow extends StatefulWidget {class _PhoneSearchRowState extends State<PhoneSearchRow> {bool _pressed = false;+ bool get _tappable => widget.openable && !widget.busy;+void _press(bool pressed) {- if (!widget.openable || _pressed == pressed) return;+ if (!_tappable || _pressed == pressed) return;setState(() => _pressed = pressed);}@@ -86,7 +97,7 @@ class _PhoneSearchRowState extends State<PhoneSearchRow> {onTapDown: (_) => _press(true),onTapUp: (_) => _press(false),onTapCancel: () => _press(false),- onTap: widget.openable ? _open : null,+ onTap: _tappable ? _open : null,child: AnimatedContainer(duration: AppMotion.press,curve: AppMotion.curve,diff --git a/mobile/lib/phone/phone_search_row_trailing.dart b/mobile/lib/phone/phone_search_row_trailing.dartindex 6242789e9..e64273b63 100644--- a/mobile/lib/phone/phone_search_row_trailing.dart+++ b/mobile/lib/phone/phone_search_row_trailing.dart@@ -46,13 +46,15 @@ class PhoneSearchTrailing extends StatelessWidget {String? get _badge {final machine = row.machine;return switch (row.kind) {- PhoneDestinationKind.agent => !openable- ? 'No terminal'- // Saved work, not a dead row: the tap restarts it and opens it. Said- // plainly because the wait that follows is a second or two of nothing.- : row.entry?.agent.isStopped == true- ? 'Stopped'- : null,+ // Saved work, not a dead row: the tap resumes it and opens it. Said+ // plainly because the wait that follows is a second or two of nothing.+ // Stopped work with no conversation to reopen says so in the desktop's+ // words, rather than the `No terminal` of a live agent that lost its pane.+ PhoneDestinationKind.agent => switch (row.entry?.agent) {+ final agent? when agent.isStopped =>+ openable ? 'Stopped' : 'Resume unavailable',+ _ => openable ? null : 'No terminal',+ },PhoneDestinationKind.machine => switch (machine == null? null: phoneMachineStatusOf(machine)) {diff --git a/mobile/lib/phone/resume_agent.dart b/mobile/lib/phone/resume_agent.dartindex 0f047b927..9fa83f196 100644--- a/mobile/lib/phone/resume_agent.dart+++ b/mobile/lib/phone/resume_agent.dart@@ -1,5 +1,6 @@import 'dart:async';+import 'package:harness_mobile/core/models.dart';import 'package:harness_mobile/state/app_state.dart';import 'agent_index.dart';@@ -31,26 +32,40 @@ Future<String?> resumeAgentForOpen(AppNotifier notifier,AgentEntry entry,) async {- final result = await notifier.resumeAgent(entry.machineId, entry.agent.id);- if (result.error case final error?) return error;- if (_openable(notifier, entry)) return null;-- final ready = Completer<bool>();+ final stopped = entry.agent;+ final ready = Completer<void>();void check() {- if (ready.isCompleted) return;- if (_openable(notifier, entry)) ready.complete(true);+ if (!ready.isCompleted && _resumedTerminal(notifier, entry, stopped)) {+ ready.complete();+ }}notifier.addListener(check);Timer? timeout;try {+ // ⚠️ **Raced, as the desktop's `_resumeStoppedDestination` races them.** The daemon pushes the+ // resumed agent (`agent_synced`) as soon as its pane is up, and the reply can trail it — or be+ // lost to a dropped socket after the resume has in fact happened. Whichever says "there is a+ // terminal" first opens it; only a reply naming a failure, before any terminal, is an error.+ final reply = notifier.resumeAgent(entry.machineId, stopped.id);+ check();+ final error = await Future.any([+ reply.then((result) => result.error),+ ready.future.then((_) => null),+ ]);+ if (ready.isCompleted) return null;+ if (error != null) return error;+ // Confirmed; the pty follows it.+ final arrived = Completer<bool>();timeout = Timer(_terminalWait, () {- if (!ready.isCompleted) ready.complete(false);+ if (!arrived.isCompleted) arrived.complete(false);});- // Checked once more after subscribing: the agent can land between the test- // above and the listener going on, and nothing would fire again.- check();- if (await ready.future) return null;+ unawaited(+ ready.future.then((_) {+ if (!arrived.isCompleted) arrived.complete(true);+ }),+ );+ if (await arrived.future) return null;} finally {timeout?.cancel();notifier.removeListener(check);@@ -58,11 +73,17 @@ Future<String?> resumeAgentForOpen(return 'Resumed, but its terminal has not come back yet. Try again in a moment.';}-bool _openable(AppNotifier notifier, AgentEntry entry) =>- notifier- .stateOf(entry.machineId)- ?.agents- .where((agent) => agent.id == entry.agent.id)- .firstOrNull- ?.terminalAvailable ??- false;+/// Whether [stopped] is back with a terminal — the SAME conversation, the desktop's test: a+/// different session id is the daemon having started something else, not the work that was tapped.+bool _resumedTerminal(AppNotifier notifier, AgentEntry entry, Agent stopped) {+ final current = notifier+ .stateOf(entry.machineId)+ ?.agents+ .where((agent) => agent.id == stopped.id)+ .firstOrNull;+ return current != null &&+ current.terminalAvailable &&+ !current.isStopped &&+ current.launchState != 'failed' &&+ current.sessionId == stopped.sessionId;+}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex b72a6296a..3c12ece25 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -85,16 +85,19 @@ class RestartAgentResult {/// One deliberate creation, retained by the form if its reply is lost. Reusing/// it checks the original request; opening New agent starts a fresh intent.+/// The id a lifecycle request is checked by when its reply is lost — see `agent_create_status`.+String _newReceiptId() {+ final random = Random.secure();+ return List.generate(+ 16,+ (_) => random.nextInt(256),+ ).map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();+}+class AgentCreationAttempt {- AgentCreationAttempt() {- final random = Random.secure();- _id = List.generate(- 16,- (_) => random.nextInt(256),- ).map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();- }+ AgentCreationAttempt() : _id = _newReceiptId();- late final String _id;+ final String _id;String? _machineId, _targetId;Map<String, dynamic>? _choices;PaneSplitRequest? _split;@@ -5092,23 +5095,134 @@ class AppNotifier extends ChangeNotifier {////// An agent that already has a terminal succeeds without touching the machine:/// the caller's job is "make it openable", and it is.+ ///+ /// ⚠️ **`agent_resume`, never `agent_restart`.** The daemon routes the two to different services+ /// (`backendSocket.ts`): restart swaps the process inside a LIVE pane and refuses an agent with+ /// none (`NO_ACTIVE_PROCESS`, `RESTART_UNSUPPORTED_BACKEND`) — which is every stopped agent — while+ /// resume builds a pane and reopens the saved conversation by its session id. This used to send+ /// restart, so tapping a Stopped row could only ever fail.Future<RestartAgentResult> resumeAgent(String machineId, String agentId) {- final agent = stateOf(- machineId,- )?.agents.where((agent) => agent.id == agentId).firstOrNull;+ final machine = stateOf(machineId);+ final agent = machine?.agents+ .where((agent) => agent.id == agentId)+ .firstOrNull;if (agent?.terminalAvailable == true) {return Future.value(const RestartAgentResult());}- if (agent?.isStopped != true) {+ if (machine == null || agent == null || !agent.isStopped) {return Future.value(const RestartAgentResult(error: 'That harness is no longer available. Search again.',),);}- return restartAgent(machineId, agentId);+ // Refused here rather than round-tripped: the machine can only say RESUME_UNAVAILABLE.+ if (!agent.canResumeConversation) {+ return Future.value(+ const RestartAgentResult(+ error: 'This harness has no saved conversation to resume.',+ ),+ );+ }+ return _resumeWithReceipt(machine, agent);}+ /// Resumes whose outcome the machine has not confirmed yet, by agent → the receipt id they were+ /// sent with.+ ///+ /// ⚠️ **A lost reply is not a failed resume.** The daemon may be starting the conversation right+ /// now, and a second `agent_resume` would start it twice. So the next tap on the same agent asks+ /// `agent_create_status` about the SAME id instead, exactly as the desktop's restart attempt does;+ /// only a confirmed outcome — started, refused, gone — clears the entry.+ final Map<(String, String), String> _agentResumes = {};++ Future<RestartAgentResult> _resumeWithReceipt(+ MachineState machine,+ Agent stopped,+ ) async {+ final key = (machine.machine.machineId, stopped.id);+ final checking = _agentResumes[key];+ final receipt = checking ?? _newReceiptId();+ _agentResumes[key] = receipt;+ RestartAgentResult settle(String error) {+ _agentResumes.remove(key);+ return RestartAgentResult(error: error);+ }++ const unconfirmed = RestartAgentResult(+ error: 'The machine has not confirmed the resume yet. Tap the harness again to check.',+ );+ final Map<String, dynamic> result;+ try {+ result = await _conn(machine.machine.machineId).request(+ checking == null ? 'agent_resume' : 'agent_create_status',+ payload: {+ 'creationId': receipt,+ if (checking == null) 'agentId': stopped.id,+ },+ );+ } on WsRequestFailure catch (failure) {+ // A refusal to a first send happened before anything launched; anything else — a timeout,+ // INTERNAL, a status check the machine cannot answer — leaves the outcome unknown.+ if (checking != null || failure.code == 'INTERNAL') return unconfirmed;+ return settle(_resumeFailure(failure.code, failure.detail));+ } catch (_) {+ return unconfirmed;+ }+ if (result['creationId'] != receipt) return unconfirmed;+ switch (result['state']) {+ case 'created':+ break;+ case 'pending':+ return const RestartAgentResult(+ error: 'The machine is still resuming this harness. Tap it again in a moment.',+ );+ case 'unavailable':+ return settle('That harness is no longer available. Search again.');+ case 'failed':+ final failure = result['failure'];+ if (failure is! Map || failure['code'] is! String) return unconfirmed;+ return settle(+ _resumeFailure(failure['code'] as String, failure['detail']),+ );+ default:+ return unconfirmed;+ }+ final raw = result['agent'];+ if (raw is! Map || raw['id'] != stopped.id) return unconfirmed;+ final Agent resumed;+ try {+ resumed = Agent.fromJson(Map<String, dynamic>.from(raw));+ } catch (_) {+ return unconfirmed;+ }+ // The desktop's bar for "resumed": the same conversation, started — not a fresh session the+ // daemon fell back to, and not one still starting or already failed.+ if (result['resumed'] == false ||+ resumed.sessionId != stopped.sessionId ||+ resumed.launchState != 'ready') {+ return unconfirmed;+ }+ _agentResumes.remove(key);+ if (_disposed || machineStates[machine.machine.machineId] != machine) {+ return const RestartAgentResult();+ }+ _upsertAgent(machine, resumed);+ notifyListeners();+ return const RestartAgentResult();+ }++ /// The desktop's `_restartFailure` wording for a resume the machine refused.+ String _resumeFailure(String code, Object? detail) =>+ detail is String && detail.isNotEmpty+ ? detail+ : switch (code) {+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>+ 'Update the harness CLI on this machine to open saved harnesses.',+ 'AGENT_BUSY' => 'Another operation is changing this harness. Wait for it to finish, then retry.',+ _ => 'Could not open this harness: $code',+ };+Future<RestartAgentResult> restartAgent(String machineId,String agentId,@@ -6681,14 +6795,23 @@ class AppNotifier extends ChangeNotifier {if (raw is Map) {try {final agent = Agent.fromJson(Map<String, dynamic>.from(raw));+ _upsertAgent(machine, agent);if (agent.terminalAvailable) {- _upsertAgent(machine, agent);// A pane created before this agent's terminal was verified is still sitting on// "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is// already `loaded`, so this push is the only signal that it can attach now._attachPendingPanes(machine);} else {- await _removeAgent(machine, agent.id);+ // ⚠️ **Kept, not removed — the desktop's rule.** This is how a STOP arrives+ // (`publishStoppedAgent` pushes the agent with `status: 'stopped'`), and also how an+ // agent looks for a moment while its pane is re-verified. Removing it here made+ // stopped work vanish from the phone until the next full reload, so there was no row+ // left to resume. `agent_deleted` is what removes an agent; this only lets go of the+ // streams, which have no terminal behind them any more.+ for (final pane in panesFor(machine.machine.machineId).toList()) {+ if (pane.agentId != agent.id) continue;+ await _detachSession(pane, sendClose: false);+ }}} catch (_) {unawaited(_loadMachineData(machine, force: true));diff --git a/mobile/test/agent_pager_fixture.dart b/mobile/test/agent_pager_fixture.dartindex c00aba6f1..e3fbd0df2 100644--- a/mobile/test/agent_pager_fixture.dart+++ b/mobile/test/agent_pager_fixture.dart@@ -3,10 +3,12 @@ import 'dart:typed_data';import 'package:harness_mobile/auth/auth_session.dart';import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';import 'package:harness_mobile/core/models.dart';import 'package:harness_mobile/phone/agent_index.dart';import 'package:harness_mobile/phone/agent_swipe_list.dart';import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/state/pane_layout_store.dart';import 'package:harness_mobile/terminal/terminal_binary.dart';import 'package:harness_mobile/terminal/terminal_session.dart';import 'package:harness_mobile/viewer/viewer_key_store.dart';@@ -56,10 +58,14 @@ const pagerAgentIds = ['a', 'b', 'c', 'd'];/// One machine `m` running [pagerAgentIds], reached through [conn] — as a phone reaches it when/// [viewer], with no CLI and nothing written to disk.+/// [storage] gives the app the preferences a real one keeps across launches —+/// the agent to reopen among them. Left out, nothing is remembered anywhere,+/// which is what a test that is not about a relaunch wants.AppNotifier pagerApp(PagerConn conn, {bool online = true,bool viewer = false,+ LocalKeyValueStore? storage,}) {final session = AuthSession();final app = AppNotifier(@@ -67,6 +73,9 @@ AppNotifier pagerApp(authSession: session,configStore: null,connectionForTest: (_) => conn,+ paneLayoutStore: storage == null+ ? null+ : PaneLayoutStore(storage: storage),viewer: viewer? ViewerServices(config: AppConfig.dev,diff --git a/mobile/test/desk_fixture.dart b/mobile/test/desk_fixture.dartindex 3805cb616..2f6ee384e 100644--- a/mobile/test/desk_fixture.dart+++ b/mobile/test/desk_fixture.dart@@ -1,6 +1,7 @@import 'package:harness_mobile/api/api_client.dart';import 'package:harness_mobile/auth/auth_session.dart';import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/state/desk_sync.dart';import 'package:harness_mobile/state/phone_desk.dart';@@ -60,8 +61,9 @@ Future<AppNotifier> deskApp(PagerConn conn, {List<DeskTab> tabs = const [],bool opensTerminals = true,+ LocalKeyValueStore? storage,}) async {- final app = pagerApp(conn);+ final app = pagerApp(conn, storage: storage);app.api = DeskApi(tabs: tabs);if (!opensTerminals) {app.stateOf('m')!.terminalCapabilityAvailable = false;diff --git a/mobile/test/encrypted_down_types_test.dart b/mobile/test/encrypted_down_types_test.dartnew file mode 100644index 000000000..41bc89d9a--- /dev/null+++ b/mobile/test/encrypted_down_types_test.dart@@ -0,0 +1,36 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/e2ee/envelope.dart';++/// The phone seals exactly the frames the machine insists on.+///+/// ⚠️ **Read from the CLI's source, not copied into this test.** A type the CLI adds to+/// `ENCRYPTED_DOWN_TYPES` and the phone does not fails nowhere on the phone — the frame leaves in the+/// clear and the machine answers E2EE_REQUIRED, which is how `agent_resume` shipped broken. Only a+/// test that reads the CLI's list notices the day it grows.+void main() {+ /// The quoted names in a set literal, with `//` comments stripped first — the CLI's comments quote+ /// type names too.+ Set<String> namesIn(String source, String start, String end) {+ final from = source.indexOf(start);+ expect(from, isNonNegative, reason: 'could not find $start');+ final body = source.substring(from, source.indexOf(end, from));+ final code = body.split('\n').map((line) => line.split('//').first).join('\n');+ return {+ for (final match in RegExp(r"'([a-z0-9_]+)'").allMatches(code)) match[1]!,+ };+ }++ test('matches the CLI\'s ENCRYPTED_DOWN_TYPES', () {+ final core = File('../cli/src/lib/e2ee/core.ts');+ expect(core.existsSync(), isTrue, reason: 'run from mobile/ in the monorepo');+ final cli = namesIn(+ core.readAsStringSync(),+ 'ENCRYPTED_DOWN_TYPES = new Set<string>([',+ '])',+ );+ expect(cli, isNotEmpty);+ expect(encryptedDownTypes, cli);+ });+}diff --git a/mobile/test/phone_restore_last_agent_test.dart b/mobile/test/phone_restore_last_agent_test.dartnew file mode 100644index 000000000..fac2909be--- /dev/null+++ b/mobile/test/phone_restore_last_agent_test.dart@@ -0,0 +1,166 @@+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/agent_home.dart';+import 'package:harness_mobile/phone/agent_swipe.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'agent_pager_fixture.dart';+import 'desk_fixture.dart';+import 'voice_fakes.dart';++/// The phone opens on the agent it was left on.+///+/// ⚠️ **The window these are about is a daemon that has just started.** It clears every agent's+/// terminal availability as it loads its registry and fills it back in one agent at a time, as its+/// reconciler observes each pane — so a launch inside that window sees its own agent as unopenable+/// for a second or two. Reading that as "gone" put the phone on whichever agent happened to have+/// been verified first, which is the oldest one on the machine.+void main() {+ Future<void> pumpHome(WidgetTester tester, AppNotifier app) async {+ await tester.pumpWidget(+ MaterialApp(+ home: PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: (_, _) {},+ child: AgentHome(notifier: app),+ ),+ ),+ );+ // The record is read from storage, so the first frame cannot have it yet.+ await tester.pump();+ await tester.pump();+ // The visit the pager records is debounced (see [PhoneSearchHistory]); let it land rather than+ // leave its timer behind.+ await tester.pump(const Duration(milliseconds: 700));+ }++ /// The fixture dials its machine as it is built, and that load is still in flight when a test+ /// starts arranging the machine's agents. Let it land first, so the scene each test sets is the+ /// one the screen sees.+ Future<void> settleFixtureLoad(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 11));+ }++ String? openedAgent(WidgetTester tester) {+ final hosts = tester.widgetList<AgentSwipeHost>(+ find.byType(AgentSwipeHost),+ );+ return hosts.isEmpty ? null : hosts.first.agentId;+ }++ MemoryKeyValueStore remembering(String agentId) => MemoryKeyValueStore()+ ..values['phone_last_agent_v1'] = jsonEncode({+ 'machineId': 'm',+ 'agentId': agentId,+ });++ Agent agent(String id, {required bool terminal}) => Agent(+ id: id,+ name: id,+ engine: 'claude',+ project: const AgentProject(name: 'work', cwd: '/work'),+ terminalAvailable: terminal,+ );++ /// The machine listing [ids], as it is once its `agents_list` has landed.+ void machineLists(AppNotifier app, List<Agent> agents) => app.stateOf('m')!+ ..agents = agents+ ..agentLoadStatus = AgentLoadStatus.loaded;++ /// The daemon reporting one agent's terminal, the way its reconciler does when it has looked at+ /// the pane — the only signal that turns an agent back on once the list has landed.+ Future<void> reportTerminal(+ WidgetTester tester,+ AppNotifier app,+ String id,+ ) async {+ await app.handleEventForTest('m', {+ 'type': 'agent_synced',+ 'agentId': id,+ 'payload': <String, dynamic>{+ 'agent': <String, dynamic>{+ 'id': id,+ 'name': id,+ 'engine': 'claude',+ 'project': <String, dynamic>{'name': 'work', 'cwd': '/work'},+ 'terminal': <String, dynamic>{'available': true},+ },+ },+ });+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 700));+ }++ Future<AppNotifier> app(+ WidgetTester tester, {+ MemoryKeyValueStore? storage,+ }) async {+ final app = await deskApp(+ PagerConn(),+ opensTerminals: false,+ storage: storage,+ );+ addTearDown(app.dispose);+ await settleFixtureLoad(tester);+ return app;+ }++ testWidgets('opens the agent the last run left, not the first one', (+ tester,+ ) async {+ final notifier = await app(tester, storage: remembering('c'));+ machineLists(notifier, [+ for (final id in pagerAgentIds) agent(id, terminal: true),+ ]);+ await pumpHome(tester, notifier);+ expect(openedAgent(tester), 'c');+ });++ testWidgets('records the agent it opens, so the next launch finds it', (+ tester,+ ) async {+ final storage = MemoryKeyValueStore();+ final notifier = await app(tester, storage: storage);+ machineLists(notifier, [+ for (final id in pagerAgentIds) agent(id, terminal: true),+ ]);+ await pumpHome(tester, notifier);+ expect(storage.values['phone_last_agent_v1'], isNotNull);+ });++ testWidgets('waits for the remembered agent\'s terminal to be verified', (+ tester,+ ) async {+ final notifier = await app(tester, storage: remembering('c'));+ // The list has landed with the agent on it, but nothing has looked at its pane yet.+ machineLists(notifier, [+ for (final id in pagerAgentIds) agent(id, terminal: id != 'c'),+ ]);+ await pumpHome(tester, notifier);+ await reportTerminal(tester, notifier, 'c');+ expect(openedAgent(tester), 'c');+ });++ testWidgets('keeps the agent on screen when its terminal blinks out', (+ tester,+ ) async {+ final notifier = await app(tester, storage: remembering('c'));+ machineLists(notifier, [+ for (final id in pagerAgentIds) agent(id, terminal: true),+ ]);+ await pumpHome(tester, notifier);+ expect(openedAgent(tester), 'c', reason: 'opened on the record');+ // A refresh that has not verified this agent's terminal — it is still listed, so this is not a+ // deletion and there is nowhere for the screen to go.+ notifier.stateOf('m')!.agents = [+ for (final id in pagerAgentIds) agent(id, terminal: id != 'c'),+ ];+ await reportTerminal(tester, notifier, 'a');+ expect(openedAgent(tester), 'c');+ });+}diff --git a/mobile/test/phone_resume_agent_test.dart b/mobile/test/phone_resume_agent_test.dartnew file mode 100644index 000000000..2d64d0635--- /dev/null+++ b/mobile/test/phone_resume_agent_test.dart@@ -0,0 +1,148 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'agent_pager_fixture.dart';++/// A machine that answers each lifecycle request from a script, and records what it was asked.+class _ResumeConn extends PagerConn {+ final List<(String, Map<String, dynamic>)> requests = [];++ static const _lifecycle = {+ 'agent_resume',+ 'agent_restart',+ 'agent_create_status',+ };++ /// The reply to the next request; throwing stands for a reply that never arrived.+ Map<String, dynamic> Function(String type, Map<String, dynamic> payload)?+ answer;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ // The fixture's own traffic — agent lists, previews — is not what these tests are about.+ if (!_lifecycle.contains(type)) return {};+ requests.add((type, payload));+ return answer?.call(type, payload) ?? {};+ }+}++/// Tapping stopped work reopens its saved conversation — the desktop's `resumeAgent`.+void main() {+ Map<String, dynamic> agentJson({required bool stopped}) => {+ 'id': 'b',+ 'name': 'b',+ 'engine': 'claude',+ 'sessionId': 'session-b',+ 'status': stopped ? 'stopped' : 'active',+ 'project': <String, dynamic>{'name': 'work', 'cwd': '/work'},+ 'terminal': <String, dynamic>{'available': !stopped},+ };++ AppNotifier stoppedApp(_ResumeConn conn) {+ final app = pagerApp(conn);+ final machine = app.stateOf('m')!;+ machine.agents = [+ for (final agent in machine.agents)+ agent.id == 'b' ? Agent.fromJson(agentJson(stopped: true)) : agent,+ ];+ return app;+ }++ Map<String, dynamic> created(Map<String, dynamic> payload) => {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'resumed': true,+ 'agent': agentJson(stopped: false),+ };++ test('asks the machine to RESUME, not to restart', () async {+ final conn = _ResumeConn()..answer = (_, payload) => created(payload);+ final app = stoppedApp(conn);+ addTearDown(app.dispose);++ final result = await app.resumeAgent('m', 'b');++ expect(result.error, isNull);+ final (type, payload) = conn.requests.single;+ expect(type, 'agent_resume');+ expect(payload['agentId'], 'b');+ expect(payload['creationId'], isA<String>());+ final resumed = app.stateOf('m')!.agents.firstWhere((a) => a.id == 'b');+ expect(resumed.terminalAvailable, isTrue);+ expect(resumed.sessionId, 'session-b');+ });++ test('a lost reply is checked on the next tap, not sent again', () async {+ final conn = _ResumeConn()+ ..answer = (_, _) => throw StateError('socket dropped');+ final app = stoppedApp(conn);+ addTearDown(app.dispose);++ expect((await app.resumeAgent('m', 'b')).error, isNotNull);+ conn.answer = (_, payload) => created(payload);+ expect((await app.resumeAgent('m', 'b')).error, isNull);++ final [(firstType, first), (secondType, second)] = conn.requests;+ expect(firstType, 'agent_resume');+ expect(secondType, 'agent_create_status');+ expect(second['creationId'], first['creationId']);+ expect(second.containsKey('agentId'), isFalse);+ });++ test('a fresh session is not taken for the one that was tapped', () async {+ final conn = _ResumeConn()+ ..answer = (_, payload) => {+ ...created(payload),+ 'agent': {...agentJson(stopped: false), 'sessionId': 'another'},+ };+ final app = stoppedApp(conn);+ addTearDown(app.dispose);++ expect((await app.resumeAgent('m', 'b')).error, isNotNull);+ });++ test('stopped work with no saved conversation is refused here', () async {+ final conn = _ResumeConn()..answer = (_, payload) => created(payload);+ final app = pagerApp(conn);+ addTearDown(app.dispose);+ final machine = app.stateOf('m')!;+ machine.agents = [+ for (final agent in machine.agents)+ agent.id == 'b'+ ? Agent.fromJson({...agentJson(stopped: true)}..remove('sessionId'))+ : agent,+ ];++ expect((await app.resumeAgent('m', 'b')).error, isNotNull);+ // The machine could only answer RESUME_UNAVAILABLE, so it is not asked.+ expect(conn.requests, isEmpty);+ });++ test('a stop pushed by the machine keeps the agent, stopped', () async {+ final app = stoppedApp(_ResumeConn());+ addTearDown(app.dispose);++ await app.handleEventForTest('m', {+ 'type': 'agent_synced',+ 'agentId': 'c',+ 'payload': <String, dynamic>{+ 'agent': <String, dynamic>{+ 'id': 'c',+ 'name': 'c',+ 'engine': 'claude',+ 'status': 'stopped',+ 'project': <String, dynamic>{'name': 'work', 'cwd': '/work'},+ 'terminal': <String, dynamic>{'available': false},+ },+ },+ });++ final c = app.stateOf('m')!.agents.where((a) => a.id == 'c').single;+ expect(c.isStopped, isTrue);+ });+}diff --git a/mobile/test/phone_search_test.dart b/mobile/test/phone_search_test.dartindex 83bb40dd0..d66a3dd4c 100644--- a/mobile/test/phone_search_test.dart+++ b/mobile/test/phone_search_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';@@ -29,12 +31,16 @@ Agent _agent(int? minutesAgo,bool terminal = true,bool stopped = false,+ // Stopped work that a resume can reopen has a saved conversation; `resumable: false` is the+ // agent stopped before its engine ever saved one.+ bool resumable = true,String? gridModel,String? dshName,}) => Agent(id: id,name: 'work · $id',title: title,+ sessionId: resumable ? 'session-$id' : null,status: stopped ? 'stopped' : 'active',engine: 'codex',gridModel: gridModel,@@ -139,10 +145,13 @@ class _StoppedConn extends WsConn {onStatus: (_) {},);- /// What `agents_list` answers with; replaced by a restart.+ /// What `agents_list` answers with; replaced by a resume.List<Map<String, dynamic>> agents;final payloads = <Map<String, dynamic>>[];- final restarted = <String>[];+ final resumed = <String>[];++ /// Holds each resume reply until completed — a machine still bringing the agent back.+ Completer<void>? hold;@overrideFuture<void> waitUntilReady({required Duration timeout}) async {}@@ -157,13 +166,17 @@ class _StoppedConn extends WsConn {payloads.add(payload);return {'agents': agents};}- if (type == 'agent_restart') {+ // The daemon's receipt shape (`backendSocket.ts`): the id the phone sent, the outcome, and the+ // agent as it now is.+ if (type == 'agent_resume') {final id = payload['agentId'] as String;- restarted.add(id);+ resumed.add(id);+ await hold?.future;final agent = {'id': id,'name': 'work · $id','engine': 'claude',+ 'sessionId': 'session-$id','status': 'active','terminal': {'available': true},};@@ -171,7 +184,12 @@ class _StoppedConn extends WsConn {for (final row in agents)if (row['id'] == id) agent else row,];- return {'agent': agent, 'resumed': true};+ return {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'agent': agent,+ 'resumed': true,+ };}throw StateError('unexpected $type');}@@ -673,7 +691,11 @@ void main() {group('stopped work', () {test('every agents_list asks for it', () async {final conn = _StoppedConn([- {'id': 'live', 'name': 'work · live', 'terminal': {'available': true}},+ {+ 'id': 'live',+ 'name': 'work · live',+ 'terminal': {'available': true},+ },]);final app = _app([_machine('box', [])], conn: conn);addTearDown(app.dispose);@@ -713,12 +735,13 @@ void main() {expect(_agentIds(_rank(app, '')).first, 'saved');});- test('opening it restarts it, and waits for the terminal', () async {+ test('opening it resumes it, and waits for the terminal', () async {final conn = _StoppedConn([{'id': 'saved','name': 'work · saved','engine': 'claude',+ 'sessionId': 'session-saved','status': 'stopped','terminal': {'available': false},},@@ -731,7 +754,7 @@ void main() {expect(entry.agent.terminalAvailable, isFalse);expect(await resumeAgentForOpen(app, entry), isNull);- expect(conn.restarted, ['saved']);+ expect(conn.resumed, ['saved']);// ⚠️ The point of the wait: it returns only once there is a terminal to// open. The pager filters its pages to agents that have one, so handing// it an agent still without would have opened a different agent than the@@ -753,9 +776,72 @@ void main() {expect(await resumeAgentForOpen(app, entry), isNotNull);});- testWidgets('it is drawn as saved work, not as a dead row', (+ testWidgets('a resume in flight does not relabel the other rows', (+ tester,+ ) async {+ final conn = _StoppedConn([+ {+ 'id': 'live',+ 'name': 'work · live',+ 'terminal': {'available': true},+ },+ {+ 'id': 'saved',+ 'name': 'work · saved',+ 'engine': 'claude',+ 'sessionId': 'session-saved',+ 'status': 'stopped',+ 'terminal': {'available': false},+ },+ ])..hold = Completer<void>();+ final app = _app([+ _machine('box', [+ _agent('live', minutesAgo: 30),+ _agent('saved', minutesAgo: 1, stopped: true),+ ]),+ ], conn: conn);+ addTearDown(app.dispose);+ await tester.pumpWidget(+ MaterialApp(home: PhoneSearchPage(notifier: app)),+ );+ await tester.pump();++ await tester.tap(find.text('Stopped'));+ await tester.pump();++ // Taps wait for the resume, but the live agent still HAS its terminal — `No terminal` over it+ // was a claim about the agent that the in-flight resume had nothing to do with.+ expect(conn.resumed, ['saved']);+ expect(find.text('No terminal'), findsNothing);+ // The list's own notify debounce, so no timer outlives the test.+ await tester.pump(const Duration(milliseconds: 100));+ });++ testWidgets('with no saved conversation it says so, and takes no tap', (tester,) async {+ final app = _app([+ _machine('box', [+ _agent('live', minutesAgo: 30),+ _agent('blank', minutesAgo: 1, stopped: true, resumable: false),+ ]),+ ]);+ addTearDown(app.dispose);+ await tester.pumpWidget(+ MaterialApp(home: PhoneSearchPage(notifier: app)),+ );+ await tester.pump();++ // The desktop's word for it. `Stopped` promised a resume the machine can only refuse.+ expect(find.text('Resume unavailable'), findsOneWidget);+ expect(find.text('Stopped'), findsNothing);+ final blank = _agentRows(app)+ .firstWhere((row) => row.entry!.agent.id == 'blank');+ expect(blank.entry!.isOpenable, isFalse);+ await tester.pump(const Duration(milliseconds: 100));+ });++ testWidgets('it is drawn as saved work, not as a dead row', (tester) async {final app = _app([_machine('box', [_agent('live', minutesAgo: 30),@@ -796,19 +882,21 @@ void main() {final app = _app([machine]);addTearDown(app.dispose);final cache = PhoneSearchCatalogCache();- expect(- _agentIds(_rank(app, '', cache: cache)),- ['first', 'second', 'third'],- );+ expect(_agentIds(_rank(app, '', cache: cache)), [+ 'first',+ 'second',+ 'third',+ ]);// What a turn event does: the oldest agent is suddenly the most recently// active. The catalog is keyed on the SHAPE of the fleet, which a turn// does not change — so the list it is sitting in never hears about it.machine.agentActivityAt['third'] = DateTime.now();- expect(- _agentIds(_rank(app, '', cache: cache)),- ['first', 'second', 'third'],- );+ expect(_agentIds(_rank(app, '', cache: cache)), [+ 'first',+ 'second',+ 'third',+ ]);});test('an agent that starts working stays where it is', () {@@ -840,10 +928,11 @@ void main() {// Once something HAS been reached for, the history outranks all of that:// the agent visited leads even though its conversation is the stalest.- expect(- _agentIds(_rank(app, '', recent: ['agent:box\u0000alpha'])),- ['alpha', 'delta', 'bravo'],- );+ expect(_agentIds(_rank(app, '', recent: ['agent:box\u0000alpha'])), [+ 'alpha',+ 'delta',+ 'bravo',+ ]);});test('the agent the search was opened from is not buried', () {@@ -935,9 +1024,7 @@ void main() {);});- testWidgets('the list does not reshuffle under a finger', (- tester,- ) async {+ testWidgets('the list does not reshuffle under a finger', (tester) async {final machine = _machine('box', [_agent('3188', minutesAgo: 4),_agent('2312', minutesAgo: 30),