Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ide): agents carry on by themselves; retire the Continue mechanism

rubenluetke10-beep7c6b03e98218
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index 15c952382b..e5f5878db8 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -481,23 +481,3 @@ Reopen the coding workspace that was last open: the same folder, the same named
- **Desktop UI section:** `agentic-ide`
- **Voice example (EN):** "resume all my coding sessions"
-## `agentic-ide-interrupted` — List interrupted Agentic-IDE sessions
-
-Which coding terminals came back holding their conversation and have been told nothing since. That is what a restart leaves behind: reopening a workspace reconnects each pane to the conversation it was having, but the coding CLI reads that transcript and then WAITS at its prompt — so an agent stopped mid-task looks exactly like one that finished. Use this to answer 'what was interrupted?' before continuing anything. 'continuable' is per pane: a pane whose agent is not running cannot be typed into, and 'blocked_reason' says why.
-
-- **Endpoint:** `GET /api/agentic-ide/interrupted`
-- **Arguments:** none
-- **Requires confirmation:** no
-- **Desktop UI section:** `agentic-ide`
-- **Voice example (EN):** "which coding sessions were interrupted"
-
-## `agentic-ide-continue-interrupted` — Continue interrupted Agentic-IDE sessions
-
-Tell the coding terminals a restart left standing still to carry on: 'continue' is typed into each one and submitted. With no names, every interrupted pane in every open workspace — which is the shape of the problem, since a restart stops them all at once. CHECK THE REPLY: 'continued' really started, 'queued' had not finished starting yet and will carry on by itself within seconds (say 'shortly', not 'done'), 'unconfirmed' had the text typed in without a confirmed submit (it may be sitting in the input box — tell the user to look at that pane), and 'failed' names what refused and why. Reporting an unconfirmed or queued pane as running is the one wrong thing to do with this answer. Pressing twice is safe: each pane is claimed before anything is typed, so a repeat call cannot send a second 'continue' into the same agent.
-
-- **Endpoint:** `POST /api/agentic-ide/interrupted/continue`
-- **Arguments:** `names` (array; optional); `prompt` (string; optional)
-- **Requires confirmation:** no
-- **Desktop UI section:** `agentic-ide`
-- **Voice example (EN):** "continue the interrupted coding sessions"
-
diff --git a/docs/os-parity.md b/docs/os-parity.md
index e4d32831d7..6967397f41 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -26,9 +26,22 @@ error it always did.
After a power-off the host is gone, so the next start resumes every agent that
was running on its own conversation (each CLI's resume argument), in every
-workspace, and tells the ones that were working to continue. That path is
-identical on every OS; it depends only on login autostart, which is on by
-default on Windows, macOS and Linux (and a no-op on a headless host).
+workspace. Jarvis types nothing into any pane: Claude Code panes are resumed
+with the CLI's own `CLAUDE_CODE_RESUME_INTERRUPTED_TURN`, which finishes a
+turn the power cut interrupted (measured: killed at step 26 of 30, resumed to
+30 with nothing typed; without it the pane waited). That path is identical on
+every OS; it depends only on login autostart, which is on by default on
+Windows, macOS and Linux (and a no-op on a headless host).
+
+"Rebooted" is measured, not guessed: the host records the machine's boot time
+(`psutil.boot_time()`, all three OSes), and a host whose process is alive in
+this boot but slow to answer raises `HostUnreachable` — the app waits instead
+of resuming a second copy of each agent. Windows only: the host is started
+with `CREATE_BREAKAWAY_FROM_JOB`, and when the app's job refuses breakaway,
+through WMI `Win32_Process.Create` (verified: parent `WmiPrvSE.exe`, ConPTY
+output works); POSIX uses `start_new_session`, which no job semantics can
+override. A host that dies under a running app is replaced and its agents
+resumed the same way.
Evidence: Windows verified live — the host survives its client's hard exit
with the same PIDs and a replayed screen, and a real Claude Code pane killed
diff --git a/docs/product/extend-and-automate/agentic-ide.md b/docs/product/extend-and-automate/agentic-ide.md
index 72599c688c..24cc11180f 100644
--- a/docs/product/extend-and-automate/agentic-ide.md
+++ b/docs/product/extend-and-automate/agentic-ide.md
@@ -162,16 +162,21 @@ to them depends on what ended:
| What happened | What the agents do | What you see next time |
|---|---|---|
| You closed the app, or it crashed or restarted | They keep working | The last open workspaces come back by themselves in the same layout, with the same focused pane, and each pane shows what its agent printed meanwhile |
-| The computer was turned off or restarted | They stopped with the machine | After you sign in, Jarvis starts again (login autostart is on by default) and brings every agent that was running back on its own conversation. Agents that were in the middle of a task are told to continue; agents that were idle or waiting for your answer or an approval are resumed but not typed into |
+| The computer was turned off or restarted | They stopped with the machine | After you sign in, Jarvis starts again (login autostart is on by default) and brings every agent that was running back on its own conversation. A Claude Code agent that was cut off in the middle of a task finishes it by itself (the CLI's own interrupted-turn resume); a finished one stays finished. Other CLIs come back holding their conversation at their prompt. Jarvis never types anything into a pane |
| An agent ended by itself (for example `/exit`) | It stays ended | The pane comes back and starts when you open it |
| You closed every workspace before quitting | Nothing runs | Nothing reopens by itself; the workspaces stay in the sidebar |
| You pressed **Stop all agents** in the Agents panel | Every agent in every workspace ends | Same as closing every workspace |
+| The terminal host itself crashed while the app was open | They stopped with it | The app starts a new host and brings each of them back the same way as after a restart |
The terminal host exits on its own about a minute after its last agent ends.
If it cannot run on an install, agents run inside the app as before and end
-with it.
+with it. A host that is running but slow to answer is waited for; the app
+never starts a second copy of an agent beside one that is still alive. On
+Windows the host is started outside every job object of the app (through WMI
+when the app's job refuses to let it go), so it survives the app even when the
+app was launched from a terminal or an IDE.
-## Resume, Continue, or Forget
+## Resume or Forget
The local restore point records folders, tab names, pane positions, the focused
pane, call-signs, account choices, conversation handles, and whether each agent
@@ -181,9 +186,7 @@ folders are not silently reopened. A damaged restore point is kept aside as
A pane is **available** when its folder and CLI can open. It is **resumable**
only when that account's CLI history proves the conversation exists. Otherwise
-it opens fresh in the same layout. Inside a running app, resumed conversations
-wait at their prompts; review them before **Continue interrupted work**.
-**Queued** or **unconfirmed** does not mean running.
+it opens fresh in the same layout.
**Forget** removes only the restore point. It does not stop running agents,
delete project changes, clear prompt-history files, remove dropped files, or
diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.py
index 446c2df4d4..94e98f51a0 100644
--- a/jarvis/agentic_ide/agent_sessions.py
+++ b/jarvis/agentic_ide/agent_sessions.py
@@ -288,6 +288,31 @@ def resume_argv(agent: str, handle: ResumeHandle | None) -> tuple[str, ...] | No
return adapter.resume(handle.id)
+#: Environment a CLI is resumed with so it finishes an interrupted turn BY
+#: ITSELF, keyed by resume kind. Claude Code's own mechanism (measured against
+#: 2.1.283, 2026-09-28): with ``CLAUDE_CODE_RESUME_INTERRUPTED_TURN`` set, a
+#: resumed conversation whose last turn was cut off mid-way re-runs that turn —
+#: a pane killed at step 26 of 30 went on to 30 with nothing typed, and without
+#: it stayed at its prompt. A turn that had finished is left alone. The age
+#: limit is switched off (``0``): after a night with the machine off the turn
+#: is still the one the user asked for. CLIs without such a mechanism resume
+#: their conversation and wait at their prompt — Jarvis never types for them.
+_NATIVE_RESUME_ENV: dict[str, dict[str, str]] = {
+ "claude_session": {
+ "CLAUDE_CODE_RESUME_INTERRUPTED_TURN": "1",
+ "CLAUDE_CODE_RESUME_INTERRUPTED_TURN_MAX_AGE_MS": "0",
+ },
+}
+
+
+def resume_env(agent: str) -> dict[str, str]:
+ """Extra environment that lets ``agent`` finish an interrupted turn itself."""
+ adapter = _adapter_for(agent)
+ if adapter is None:
+ return {}
+ return dict(_NATIVE_RESUME_ENV.get(adapter.kind, {}))
+
+
def can_fork(agent: str) -> bool:
"""True when this coding CLI can copy one of its conversations into a new one."""
adapter = _adapter_for(agent)
diff --git a/jarvis/agentic_ide/interrupted.py b/jarvis/agentic_ide/interrupted.py
deleted file mode 100644
index f46e81008f..0000000000
--- a/jarvis/agentic_ide/interrupted.py
+++ /dev/null
@@ -1,465 +0,0 @@
-"""The panes a restart left standing still, and the nudge that starts them again.
-
-## The gap this closes
-
-Resuming a workspace brings the panes back and reconnects each one to the
-conversation it was having (see :mod:`.resume_store`). What it cannot do is make
-the agents carry on: a coding CLI launched with ``--resume`` reads its old
-transcript and then sits at its prompt. So an agent that was halfway through
-rewriting a module when the app was restarted comes back holding every detail of
-that job — and does nothing with it, forever, unless somebody says so.
-
-On screen those panes look exactly like panes that finished, which is the actual
-problem. The user's own report: *"the sessions were interrupted"* — twelve
-terminals back in their places, none of them working, and no way to tell which
-of them still had something to do.
-
-## What counts as interrupted
-
-Two pieces of evidence must agree. The saved pane must have been observed
-actively working before its process went away, and the resumed pane must now be
-idle at its prompt. A valid conversation alone proves neither: it may have
-finished cleanly or be waiting for the user's answer. The activity checkpoint
-is persisted with the resume snapshot; :attr:`Terminal.continuation_pending`
-then carries that decision through the current process.
-
-That matters, because the tempting heuristics are all wrong:
-
-* **"It has printed nothing for N minutes"** — an agent thinking hard about a
- large refactor prints nothing for minutes at a time, and a stalled one may
- redraw its status bar every second. Idle time measures the TUI, not the work.
-* **"Its transcript ends mid-sentence"** — a resumed pane's transcript starts
- empty. Whatever the old process printed died with its screen.
-* **"It was resumed"** alone — true of every pane in a restored workspace,
- including the ones somebody has already put back to work.
-* **"Its screen is moving, so it carried on by itself"** — the opposite
- mistake, and the one that broke this feature outright. A restored CLI
- repaints its banner and its old transcript for several seconds before it
- settles at a prompt; reading that as work retracted the offer for every
- restored pane within two sweeps of it coming back, so the button reported
- zero for ever. Only a submission stamped for the current process proves
- work; :attr:`Terminal.idle_seen` merely records that startup repainting has
- settled.
-
-## What the nudge is
-
-One short prompt, ``"continue"`` by default, typed into the pane exactly the way
-the prompt bar types one — same sanitizing, same submit verification, same
-honest three-state answer about whether it was accepted. This module adds no
-second write path into a PTY; it decides WHICH panes to send to and reports what
-happened. A caller can pass its own wording.
-
-Never triggered by opening a workspace. Sending "continue" to every resumed pane
-the moment a workspace comes back would restart twelve agents on twelve
-unattended tasks because somebody reopened a folder to look at one file, and an
-agent that was interrupted for a reason ("stop, that is the wrong approach")
-would resume exactly what it was told to stop doing. Inside a running app the
-offer is a button.
-
-The one automatic caller is the app's startup after a REBOOT
-(``Registry._continue_interrupted_after_reboot``): the agents' own process
-died with the machine, the checkpoint saw them working, and the user asked for
-exactly that recovery (RUB-102). An app that was merely closed never gets
-there — its agents kept running in the PTY host and are re-joined, not nudged.
-"""
-
-from __future__ import annotations
-
-import asyncio
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import TYPE_CHECKING, Any
-
-from loguru import logger
-
-from .activity import read_activity, shows_question
-from .fleet_actions import ready_for_prompt
-from .recap import condense
-from .session import SessionError, accepts_prompts
-
-if TYPE_CHECKING: # pragma: no cover - typing only
- from .session import Registry, Session, Terminal
-
-#: What a pane is told when the caller does not say. Short on purpose: the agent
-#: is holding the whole conversation, so the instruction it needs is the one word
-#: that means "carry on with what you were doing" in every coding CLI that has a
-#: transcript to carry on from. A longer sentence would compete with the plan the
-#: agent already has.
-CONTINUE_PROMPT = "continue"
-
-#: How much of the pane's last instruction travels with the offer. Enough to
-#: recognise which job it was, not the whole brief — this renders in a list.
-TASK_CHARS = 140
-
-
-@dataclass(frozen=True, slots=True)
-class InterruptedPane:
- """One pane that came back holding a conversation and was never restarted."""
-
- workspace_id: str
- #: The workspace tab's label, so a name identifies its folder in a list that
- #: spans several of them.
- workspace: str
- folder: str
- key: str
- name: str
- agent: str
- display_name: str
- status: str
- #: Will a "continue" reach it? False only for a pane whose agent is DEAD —
- #: an instruction cannot be typed into a terminal that exited, and saying so
- #: before the click is the point. A pane that is merely still starting is
- #: continuable: the instruction waits for it (see ``starting``).
- continuable: bool
- #: Its agent is still coming up. Continuing it is a promise kept a few
- #: seconds later, not a refusal.
- starting: bool
- #: A "continue" is already waiting to be delivered to it. What stops a second
- #: press from queueing a second one.
- queued: bool
- #: Why not, in one plain sentence. Empty when it can.
- blocked_reason: str
- #: What this pane was last asked to do, shortened. Empty when the last
- #: instruction came from the user's own keyboard rather than through Jarvis
- #: — the pane keeps no copy of what was typed into it directly.
- last_task: str
- prompts_sent: int
- #: When the current (resumed) process started. What the user reads as "since
- #: the restart".
- started_at: float | None
-
- def to_dict(self) -> dict[str, Any]:
- return {
- "workspace_id": self.workspace_id,
- "workspace": self.workspace,
- "folder": self.folder,
- "key": self.key,
- "name": self.name,
- "agent": self.agent,
- "display_name": self.display_name,
- "status": self.status,
- "continuable": self.continuable,
- "starting": self.starting,
- "queued": self.queued,
- "blocked_reason": self.blocked_reason,
- "last_task": self.last_task,
- "prompts_sent": self.prompts_sent,
- "started_at": self.started_at,
- }
-
-
-@dataclass(frozen=True, slots=True)
-class ContinueReport:
- """What sending the nudge actually did, pane by pane.
-
- Four lists rather than a count, because the outcomes need different words
- from whoever reports this: a pane that took the instruction, one whose agent
- is still starting and will get it shortly, one that took the text but never
- submitted it (the prompt is sitting in its input box and a human has to
- press Enter), and one that refused. Collapsing any of them into "it is
- running again" is the lie :meth:`Registry.send_prompt` goes to some length
- to avoid.
- """
-
- continued: list[str]
- unconfirmed: list[str]
- failed: list[tuple[str, str]]
- #: Panes whose process or input line is still starting. The instruction is
- #: held and delivered when it becomes writable — a promise, not a refusal.
- queued: list[str] = field(default_factory=list)
-
- @property
- def ok(self) -> bool:
- return not self.failed
-
- def to_dict(self) -> dict[str, Any]:
- return {
- "ok": self.ok,
- "continued": list(self.continued),
- "queued": list(self.queued),
- "unconfirmed": list(self.unconfirmed),
- "failed": [{"name": name, "detail": detail} for name, detail in self.failed],
- }
-
-
-def _workspace_label(session: Session) -> str:
- """What the workspace bar calls this workspace."""
- return session.name or session.profile.name or Path(session.folder).name or session.folder
-
-
-def _blocked_reason(term: Terminal) -> str:
- """Why this pane cannot be nudged right now, or an empty string.
-
- ``pending`` is deliberately NOT in here. A pane still waiting for a
- cold-start slot is not blocked, it is early — and treating "early" as
- "blocked" is what made the button skip terminals in a big workspace. Those
- are reported by :func:`_starting`, continued the moment they come up, and
- kept out of the refusal list entirely.
- """
- if term.status == "live" and term.pty_id:
- return ""
- if term.status == "pending":
- return ""
- if term.status == "error":
- return term.error or "Its agent could not be started."
- if term.status == "exited":
- code = term.exit_code
- ended = "finished" if code in (0, None) else f"stopped with exit code {code}"
- return f"Its agent {ended} — restart the pane before continuing it."
- return f"Its agent is not running (status: {term.status})."
-
-
-def _starting(term: Terminal) -> bool:
- """Is this pane's agent still on its way up?
-
- Cold starts are staggered on purpose (``COLD_START_LIMIT``), so a workspace
- of a dozen panes has most of them in this state for the first few seconds
- after it appears. A spawned process also stays here until its TUI exposes a
- real input line; process existence alone is not prompt readiness.
- """
- return term.status == "pending" or (
- term.status == "live" and bool(term.pty_id) and not ready_for_prompt(term)
- )
-
-
-def _describe(session: Session, term: Terminal) -> InterruptedPane:
- reason = _blocked_reason(term)
- starting = _starting(term)
- return InterruptedPane(
- workspace_id=session.id,
- workspace=_workspace_label(session),
- folder=session.folder,
- key=term.key,
- name=term.name,
- agent=term.agent,
- display_name=term.display_name,
- status=term.status,
- # A pane still starting counts as continuable: the instruction is not
- # refused, it is held and delivered when its agent comes up.
- continuable=not reason,
- starting=starting,
- queued=term.continue_when_ready,
- blocked_reason=reason,
- last_task=condense(term.last_prompt, TASK_CHARS),
- prompts_sent=term.prompts_sent,
- started_at=term.started_at,
- )
-
-
-def scan(registry: Registry) -> list[InterruptedPane]:
- """Every pane, in every open workspace, that is waiting to be told to carry on.
-
- Across ALL workspaces rather than only the one on screen, because that is
- the shape of the problem: a restart interrupts everything at once, and a
- button that only reported the front tab would leave the other three looking
- finished. Each entry names its workspace so the list stays readable.
-
- In tab order, then in grid order within each workspace — the order the panes
- are on screen, so a name in the list is findable by looking at the grid.
- """
- found: list[InterruptedPane] = []
- for session in registry.sessions:
- for term in session.terminals:
- if not term.continuation_pending:
- continue
- if term.status == "live" and shows_question(term):
- # A pane asking something needs an ANSWER, not a blind
- # "continue". Read straight off the screen rather than through
- # `read_activity`, which answers "working" first — a pane can be
- # repainting itself around a trust prompt, and that is precisely
- # a pane not to type into.
- continue
- if term.status == "live" and term.idle_seen and read_activity(term) != "waiting":
- # A pane already working needs no nudge.
- #
- # Only once the pane has been SEEN standing still, though. Until
- # then its screen is moving because its CLI is drawing itself
- # back onto it — which is what a restored pane does for its
- # first few seconds, and reading that as work hid every pane
- # this list exists to show (see `Terminal.idle_seen`).
- continue
- if not accepts_prompts(term.agent):
- # A plain terminal is a shell. Jarvis does not type into one, so
- # offering to continue it would be an offer that cannot be kept
- # (see `session.accepts_prompts`). It also never resumes a
- # conversation, so this is belt and braces.
- continue
- found.append(_describe(session, term))
- return found
-
-
-def _selected(
- panes: list[InterruptedPane], names: list[str] | None
-) -> tuple[list[InterruptedPane], list[tuple[str, str]]]:
- """The panes a caller asked for, and a refusal for each name that is not one.
-
- An unknown name is reported rather than ignored: a caller that asked for
- four panes and silently got three has been told the wrong thing about what
- is now running.
- """
- if not names:
- return list(panes), []
- by_name = {pane.name.casefold(): pane for pane in panes}
- by_key = {pane.key.casefold(): pane for pane in panes}
- chosen: list[InterruptedPane] = []
- rejected: list[tuple[str, str]] = []
- seen: set[str] = set()
- for wanted in names:
- needle = wanted.strip().casefold()
- pane = by_name.get(needle) or by_key.get(needle)
- if pane is None:
- rejected.append(
- (
- wanted,
- f"{wanted} is not waiting to be continued — it was never "
- "interrupted, or somebody has already put it back to work.",
- )
- )
- continue
- if pane.key in seen:
- continue
- seen.add(pane.key)
- chosen.append(pane)
- return chosen, rejected
-
-
-def _claim(
- registry: Registry, pane: InterruptedPane
-) -> tuple[Session, Terminal] | None:
- """Take a pane off the waiting list BEFORE anything is sent to it.
-
- **The bug this fixes.** Typing a prompt and verifying it takes seconds — the
- submit is confirmed against the pane's own screen — and the flag used to be
- cleared at the END of that. So a second press while the first was still in
- flight found the pane still "waiting", and the agent received "continue"
- twice; three presses, three times. Reported exactly that way.
-
- Claiming is therefore the first thing that happens, in one synchronous step
- with no ``await`` in it, so two overlapping requests cannot both win. The
- caller puts the flag back when the send fails, and the pane returns to the
- list rather than being silently dropped.
- """
- session = registry.get(pane.workspace_id)
- if session is None:
- return None
- term = session.find(pane.key)
- if term is None:
- return None
- if not term.continuation_pending:
- # Somebody got here first — another press, or the user typing into the
- # pane themselves between the scan and now.
- return None
- term.continuation_pending = False
- return session, term
-
-
-def _release(registry: Registry, pane: InterruptedPane) -> None:
- """Put a pane back on the waiting list after its nudge failed to go."""
- session = registry.get(pane.workspace_id)
- term = session.find(pane.key) if session is not None else None
- if term is not None:
- term.continuation_pending = True
-
-
-async def continue_panes(
- registry: Registry,
- *,
- names: list[str] | None = None,
- prompt: str = CONTINUE_PROMPT,
-) -> ContinueReport:
- """Tell the interrupted panes to carry on. Empty ``names`` means all of them.
-
- Sent through :meth:`Registry.send_prompt`, so every guarantee of the ordinary
- prompt path holds: control characters stripped, the completion popup closed
- before Enter, the submit verified against the pane's own screen, and a
- three-state answer about whether it went.
-
- Concurrently, because that verification watches the screen for up to a few
- seconds per pane and a grid of twelve would otherwise take the better part of
- a minute. The panes are independent processes with independent PTYs, so there
- is nothing to serialize; one pane refusing its prompt cannot affect another.
-
- **A pane still starting is queued, not skipped.** Cold starts are staggered
- (``COLD_START_LIMIT``), so most of a big workspace is still coming up in the
- seconds after it appears — the very window this button is pressed in. Those
- panes are marked and continued when their agent's input line is writable,
- and reported as ``queued`` rather than as done or refused.
-
- **Pressing twice cannot send twice.** Every pane is claimed off the waiting
- list synchronously before a single byte is typed (see :func:`_claim`), and
- put back only if its nudge could not be delivered.
- """
- text = (prompt or CONTINUE_PROMPT).strip() or CONTINUE_PROMPT
- chosen, failed = _selected(scan(registry), names)
-
- failed.extend((pane.name, pane.blocked_reason) for pane in chosen if not pane.continuable)
-
- queued: list[str] = []
- runnable: list[InterruptedPane] = []
- for pane in chosen:
- if not pane.continuable:
- continue
- claimed = _claim(registry, pane)
- if claimed is None:
- # Already claimed by a press that is still in flight. Not a failure
- # and not a second send — the first one is doing the work.
- continue
- owner, term = claimed
- if pane.starting:
- registry.defer_continue(owner, term, text)
- queued.append(pane.name)
- else:
- runnable.append(pane)
-
- async def _send(pane: InterruptedPane) -> tuple[InterruptedPane, Any]:
- try:
- return pane, await registry.send_prompt(
- pane.name,
- text,
- workspace_id=pane.workspace_id,
- )
- except SessionError as exc:
- return pane, exc
- except Exception as exc: # noqa: BLE001 - one pane must not fail the batch
- logger.warning("Agentic IDE: could not continue {}: {}", pane.name, exc)
- return pane, exc
-
- continued: list[str] = []
- unconfirmed: list[str] = []
- for pane, outcome in await asyncio.gather(*(_send(pane) for pane in runnable)):
- if isinstance(outcome, Exception):
- # Nothing reached the agent, so this one is still waiting.
- _release(registry, pane)
- failed.append((pane.name, str(outcome) or outcome.__class__.__name__))
- elif getattr(outcome, "submitted", None) is True:
- continued.append(pane.name)
- else:
- # Typed in, not provably submitted. Its own bucket: telling the user
- # this pane is running again would be a guess, and the fix is one
- # keypress in a pane they can see. NOT released — the text is in that
- # pane's input box, and offering to type it again would put a second
- # copy behind the first.
- unconfirmed.append(pane.name)
-
- if continued or unconfirmed or queued or failed:
- logger.info(
- "Agentic IDE: continued {} interrupted pane(s) "
- "({} queued until they start, {} unconfirmed, {} refused)",
- len(continued),
- len(queued),
- len(unconfirmed),
- len(failed),
- )
- return ContinueReport(
- continued=continued, queued=queued, unconfirmed=unconfirmed, failed=failed
- )
-
-
-__all__ = [
- "CONTINUE_PROMPT",
- "TASK_CHARS",
- "ContinueReport",
- "InterruptedPane",
- "continue_panes",
- "scan",
-]
diff --git a/jarvis/agentic_ide/notifications.py b/jarvis/agentic_ide/notifications.py
index 9f6ea45852..33fd035dea 100644
--- a/jarvis/agentic_ide/notifications.py
+++ b/jarvis/agentic_ide/notifications.py
@@ -731,30 +731,21 @@ class ActivityWatcher:
Entering ``working`` arms the checkpoint immediately. A plain prompt
must remain stable for the same settle window as completion notices,
because coding TUIs briefly remove their busy row between tool steps.
- Questions clear immediately: they need the user's answer, never a blind
- continuation prompt. A resumed pane that is still offering Continue is
- preserved while it waits at its prompt.
+ Questions clear immediately: a pane waiting for the user's answer was
+ not interrupted mid-work. The evidence is only ever read — by the bell
+ after an app restart — never acted on by typing into a pane.
"""
if activity == "working":
- # `read_activity` reaches this state only after a submission stamped
- # for the live process. The offer to continue is therefore spent.
- term.continuation_pending = False
self._set_resume_needed(term, watch, True)
return
if activity in {"asking", "failed"}:
- term.continuation_pending = False
self._set_resume_needed(term, watch, False)
return
if activity == "exited":
if getattr(term, "exit_code", None) in (0, None):
- term.continuation_pending = False
self._set_resume_needed(term, watch, False)
return
- if (
- activity == "waiting"
- and not getattr(term, "continuation_pending", False)
- and now - watch.since >= SETTLE_S
- ):
+ if activity == "waiting" and now - watch.since >= SETTLE_S:
self._set_resume_needed(term, watch, False)
def _set_resume_needed(self, term: Any, watch: _PaneWatch, needed: bool) -> None:
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.py
index 014ab8c468..c8116a1636 100644
--- a/jarvis/agentic_ide/resume_store.py
+++ b/jarvis/agentic_ide/resume_store.py
@@ -671,7 +671,7 @@ def all_closed_at() -> float | None:
"""When every workspace was last closed by hand, or None."""
try:
return float(_all_closed_path().read_text(encoding="utf-8").strip())
- except (OSError, ValueError):
+ except (OSError, ValueError): # no marker (or a torn one) means "never closed by hand"
return None
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 0fb2786e68..0d5b61a57f 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -102,6 +102,7 @@ from .agent_sessions import (
has_conversation,
launch_extra,
resume_argv,
+ resume_env,
)
from .folders import ProjectProfile, probe_project
from .names import free_positions, normalize, position_of, resolve
@@ -1166,37 +1167,16 @@ class Terminal:
# picked up an old transcript, "still running" means the same process has
# been working the whole time you were looking somewhere else.
reattached: bool = False
- # Was this pane last observed actively working before its process went
- # away? Persisted in the resume snapshot and kept separate from `resumed`:
- # an existing conversation may already be finished or waiting for input,
- # neither of which should receive a blind "continue".
+ # Was this pane last observed actively working? Checkpointed into the
+ # resume snapshot by the pane watcher. Evidence only — nothing is ever
+ # typed on its strength: a re-joined agent that was working and has since
+ # stopped is reported by the bell (``worked_while_detached``), and a
+ # resumed Claude pane finishes an interrupted turn by itself
+ # (``agent_sessions.resume_env``).
resume_continuation_needed: bool = False
- # This pane picked its old conversation back up, and NOBODY has told it what
- # to do since. That is the state a restart leaves behind: the agent is alive
- # and holds the whole transcript, but it was killed mid-task and a resumed
- # CLI sits at its prompt waiting rather than carrying on by itself — so the
- # work simply stops, silently, and looks exactly like a pane that finished.
- #
- # Raised where a restore establishes that this pane's conversation really
- # exists, and again where a process is SPAWNED onto one (see `attach`, which
- # also clears it when a resume failed and the pane came back empty). Cleared
- # by anything that counts as "somebody is driving this pane again": a prompt
- # from Jarvis, or a line the user typed into the pane themselves. Never
- # persisted — it describes the pane on screen, not the workspace on disk.
- continuation_pending: bool = False
- # "Continue this one as soon as it can be typed into."
- #
- # Cold starts are staggered (COLD_START_LIMIT), so in a workspace of a dozen
- # panes most are still waiting for a slot when the user presses Continue.
- # Sending only to the ones that happen to be up already is what made the
- # button look like it skipped terminals; refusing them would be the same
- # answer worn differently. So the wish is REMEMBERED here and spent by
- # `attach` once that pane's agent exposes a writable input line.
- continue_when_ready: bool = False
- # The exact nudge paired with ``continue_when_ready``. Usually the one-word
- # default, but the REST contract accepts custom wording and a queued pane
- # must not silently replace it while waiting for its cold-start slot.
- continue_prompt: str = ""
+ # This pane's agent died because the PTY host went away under a running
+ # app (not because it exited): it is resumed once a host is back.
+ lost_with_host: bool = False
# Has this pane's screen been observed STANDING STILL since its current
# process started?
#
@@ -1395,12 +1375,6 @@ class Terminal:
# anything" — the same picture, and not the same news.
"worked": has_work_behind_it(self),
"resumed": self.resumed,
- # Continued its old conversation and has had no instruction since —
- # the pane a restart left standing still. Carried in the ordinary
- # state so a client can mark it without a second request; the list
- # of them, with the reason each one can or cannot be nudged, is
- # `GET /interrupted`.
- "continuation_pending": self.continuation_pending,
# Whether a handle EXISTS, never the handle itself: it is an
# internal pointer into the CLI's history and no client needs it.
"has_resume": self.resume is not None,
@@ -1845,9 +1819,23 @@ async def _connect_pty_host(*, start: bool) -> Any:
so the terminal stack stays off the import path until a pane needs it
(AP-26).
"""
- from jarvis.terminal.pty_host_client import connect
+ from jarvis.terminal.pty_host_client import HostUnreachable, connect
+
+ try:
+ return await connect(start=start)
+ except HostUnreachable as exc:
+ # A host that is running holds agents; "not yet" is the only safe
+ # answer — never a reason to start them a second time.
+ logger.warning("Agentic IDE: {} — waiting for it", exc)
+ raise SessionNotReady(
+ "The terminal host is busy; the panes reconnect when it answers."
+ ) from exc
+
- return await connect(start=start)
+#: The exit code ``RemotePtyManager`` reports for every agent when its host goes
+#: away (``pty_manager.UNKNOWN_EXIT_CODE``); spelled out here so this module
+#: does not import the terminal stack at load time (AP-26).
+_HOST_LOST_CODE = -1
def _viewers(term: Terminal) -> list[Any]:
@@ -1990,6 +1978,10 @@ class Registry:
self._focus_dirty = False
self._host_lock = asyncio.Lock()
self._boot_restored = False
+ # The re-join retried in the background when the host did not answer
+ # at startup, and the one recovery pass after a host died under us.
+ self._rejoin_task: asyncio.Task[None] | None = None
+ self._host_recovery: asyncio.Task[None] | None = None
# ---------------------------------------------------------------- state
@property
@@ -2285,7 +2277,11 @@ class Registry:
return
self._boot_restored = True
self._host_enabled = True
- await self._attached_host()
+ try:
+ await self._attached_host()
+ host_reachable = True
+ except SessionNotReady: # a live host that is silent: waited for below, not an error
+ host_reachable = False
try:
snapshot = await asyncio.to_thread(resume_store.load)
closed_at = await asyncio.to_thread(resume_store.all_closed_at)
@@ -2322,33 +2318,56 @@ class Registry:
info.meta.get("name", "unnamed"),
)
manager.kill_hosted(info.terminal_id)
- await self._resume_after_reboot()
-
- async def _resume_after_reboot(self) -> None:
- """Bring back every agent a power-off or reboot ended, in every workspace.
-
- What Herdr calls native agent-session resume: the agents' processes died
- with the machine, so each one is started again on ITS OWN conversation
- (the CLI's ``--resume <id>`` and equivalents, see ``agent_sessions``) —
- not a fresh CLI, and not only in the workspace somebody happens to open.
-
- Which panes: every one still ``pending`` after the PTY host had its say
- (a pane whose agent survived was re-joined and is ``live``), whose agent
- was running at the last save (``Terminal.was_running`` — an agent that
- ended by itself stays ended), and whose CLI really holds the
- conversation its handle points at. A pane that was never given an
- instruction has nothing to resume and keeps starting when it is opened.
-
- On top of that, panes whose last checkpoint saw them WORKING are told to
- carry on (``interrupted.continue_panes``). That gate stays strict: a
- pane that was idle, finished or waiting for an answer or an approval is
- resumed but never typed into.
-
- The starts run without a viewer and go through the ordinary cold-start
- gate, so a dozen agents come back a few at a time.
- """
- from . import interrupted
+ if host_reachable:
+ await self._resume_lost_agents("the machine restarted or the terminal host ended")
+ else:
+ # A host is running but did not answer: its agents are alive.
+ # Resuming now would start a second copy of each one, so the panes
+ # wait and re-join once it answers (``_rejoin_when_reachable``).
+ self._rejoin_task = asyncio.create_task(
+ self._rejoin_when_reachable(), name="ide-host-rejoin"
+ )
+ async def _rejoin_when_reachable(self) -> None:
+ """Keep trying a live host that did not answer at startup, then re-join."""
+ delay = 2.0
+ for _attempt in range(30):
+ await asyncio.sleep(delay)
+ delay = min(delay * 1.5, 20.0)
+ try:
+ manager = await self._attached_host()
+ except SessionNotReady: # still silent; the next attempt follows after the delay
+ continue
+ for session in list(self._sessions.values()):
+ await self._adopt_hosted(session)
+ if manager is None:
+ # It ended while we waited: its agents ended with it.
+ await self._resume_lost_agents("the terminal host ended")
+ return
+ logger.warning("Agentic IDE: the terminal host never answered; panes stay waiting")
+
+ async def _resume_lost_agents(self, why: str) -> None:
+ """Bring back every agent whose process is gone, in every workspace.
+
+ Herdr's native agent-session resume: the process died (with the machine,
+ or with a host that crashed), so each agent is started again on ITS OWN
+ conversation (the CLI's ``--resume <id>`` and equivalents, see
+ ``agent_sessions``) — not a fresh CLI, and not only in the workspace
+ somebody happens to open.
+
+ Nothing is typed into any of them. A Claude Code pane is started with
+ its CLI's own interrupted-turn resume (``agent_sessions.resume_env``), so
+ a task the power cut interrupted runs on by itself; a finished one
+ stays finished; other CLIs come back holding their conversation at
+ their prompt.
+
+ Which panes: every one still ``pending`` (a pane whose agent survived
+ in the host was re-joined and is ``live``) whose agent was running at
+ the last save (an agent that ended by itself stays ended) and whose
+ CLI really holds the conversation its handle points at. The starts run
+ without a viewer through the ordinary cold-start gate, so a dozen
+ agents come back a few at a time.
+ """
pending = [
(session, term)
for session in self._sessions.values()
@@ -2357,6 +2376,7 @@ class Registry:
and term.was_running
and term.resume is not None
and accepts_prompts(term.agent)
+ and not term.computer_id
]
def _with_conversation() -> list[tuple[Session, Terminal]]:
@@ -2373,33 +2393,64 @@ class Registry:
)
return found
- resumable = await asyncio.to_thread(_with_conversation)
- try:
- report = await interrupted.continue_panes(self)
- except Exception as exc: # noqa: BLE001 - startup must not fail on this
- logger.warning("Agentic IDE: interrupted work not continued at startup: {}", exc)
- report = None
- starts = list(resumable)
- chosen = {id(term) for _session, term in starts}
- for session in self._sessions.values():
- for term in session.terminals:
- if term.status == "pending" and term.continue_when_ready and id(term) not in chosen:
- starts.append((session, term))
+ starts = await asyncio.to_thread(_with_conversation)
for session, term in starts:
- task = asyncio.create_task(
- self._start_unviewed(session, term), name=f"ide-resume-{term.key}"
- )
- self._cold_start_holds.add(task)
- task.add_done_callback(self._cold_start_holds.discard)
+ self._start_in_background(session, term)
if starts:
logger.info(
- "Agentic IDE: resuming {} agent(s) that a reboot ended ({} of them "
- "told to continue their work)",
+ "Agentic IDE: resuming {} agent(s) on their own conversations — {}",
len(starts),
- sum(1 for _session, term in starts if term.continue_when_ready),
+ why,
)
- elif report is not None and report.continued:
- logger.info("Agentic IDE: continued {} interrupted pane(s)", len(report.continued))
+
+ def _start_in_background(self, session: Session, term: Terminal) -> None:
+ task = asyncio.create_task(
+ self._start_unviewed(session, term), name=f"ide-resume-{term.key}"
+ )
+ self._cold_start_holds.add(task)
+ task.add_done_callback(self._cold_start_holds.discard)
+
+ def _host_went_away(self) -> bool:
+ """Did the PTY host this process was attached to just drop away?"""
+ current = self._pty
+ return bool(
+ current is not None
+ and getattr(current, "persistent", False)
+ and not getattr(current, "connected", True)
+ )
+
+ def _note_host_lost(self, term: Terminal) -> None:
+ """A pane lost its agent with the host: resume it once a host is back."""
+ term.lost_with_host = True
+ term.was_running = True
+ if self._host_recovery is None or self._host_recovery.done():
+ self._host_recovery = asyncio.create_task(
+ self._recover_from_host_loss(), name="ide-host-recovery"
+ )
+
+ async def _recover_from_host_loss(self) -> None:
+ """Replace a host that died under a running app and resume its agents.
+
+ Only what a crash of the host itself leaves behind: every agent in it
+ died together, the conversations are on disk, and the app is still up.
+ A fresh host is started (``_live_manager``) and each lost pane resumes
+ its own conversation, exactly as after a reboot — never a fresh CLI and
+ never a typed prompt.
+ """
+ await asyncio.sleep(1.0) # let every exit of the lost host arrive first
+ lost = [
+ (session, term)
+ for session in self._sessions.values()
+ for term in session.terminals
+ if term.lost_with_host and term.status == "exited"
+ ]
+ if not lost:
+ return
+ logger.warning("Agentic IDE: the terminal host went away — resuming {} agent(s)", len(lost))
+ for session, term in lost:
+ term.lost_with_host = False
+ term.status = "pending"
+ self._start_in_background(session, term)
async def _start_unviewed(self, session: Session, term: Terminal) -> None:
"""Start a pane's agent with nobody watching (the registry records output)."""
@@ -2469,10 +2520,8 @@ class Registry:
term.exit_code = None
term.resumed = False
term.worked_while_detached = term.resume_continuation_needed
- # Never interrupted, so never offered a "continue" — the flag
- # ``_mark_restored_continuations`` may have raised assumed a restart.
- term.continuation_pending = False
term.resume_continuation_needed = False
+ term.lost_with_host = False
term.started_at = info.started_at or time.time()
term.last_output_at = time.time() if result.replay else None
if await self._adopted_with_work(term):
@@ -2518,6 +2567,8 @@ class Registry:
term.pty_id = None
term.status = "exited"
term.exit_code = code
+ if code == _HOST_LOST_CODE and self._host_went_away():
+ self._note_host_lost(term)
for viewer in _exit_viewers(term):
await viewer(code)
@@ -3038,24 +3089,6 @@ class Registry:
)
terminals = [_restored(index, entry) for index, entry in enumerate(space.terminals)]
- # Which of them will come back mid-task, decided HERE rather than when
- # each pane's agent happens to start.
- #
- # **The bug this fixes.** `continuation_pending` used to be raised in
- # `attach`, which is the moment a pane's process is spawned — and cold
- # starts are deliberately staggered (see COLD_START_LIMIT), so in a
- # workspace of a dozen panes most of them are still `pending` seconds
- # after the grid appears. Anybody pressing "Continue" in that window got
- # the handful that had started and silently no others, which is exactly
- # the "it skips terminals that should have carried on" report.
- #
- # A restored pane's answer does not depend on its process at all: it
- # depends on whether the coding CLI's history really holds the
- # conversation the handle points at. That is knowable now, so it is
- # answered now — one thread hop for the whole workspace, since each
- # check is a filename lookup. `attach` still corrects it either way when
- # the process really starts (a resume that fails clears it).
- await asyncio.to_thread(_mark_restored_continuations, terminals)
# A snapshot remembers the call-signs each workspace had. Another one may
# hold them now, and two panes answering to one name would make every
# spoken instruction ambiguous — so a collision is renamed here. Only the
@@ -3322,7 +3355,7 @@ class Registry:
logger.warning("Agentic IDE: resume snapshot not written: {}", exc)
async def persist_resume_activity(self) -> None:
- """Checkpoint activity evidence used by the interrupted-work offer.
+ """Checkpoint the "was working" evidence the bell and the resume use.
The activity sweep calls this only when a pane crosses a meaningful
boundary, never for each terminal repaint. Keeping it on the registry
@@ -3878,8 +3911,7 @@ class Registry:
# busiest: a restore mounts every pane in one commit, so a dozen panes
# meant a dozen stalls interleaved with their own spawns. It only ever
# runs on a pane that HAS a handle, which is why the restore path was
- # the only one that ever felt it. `_mark_restored_continuations` already
- # takes the same call to a thread for the same reason.
+ # the only one that ever felt it.
home = account_home(term.agent, term.account)
continuing = resume_argv(term.agent, term.resume)
# A remote pane's history lives on that computer; its handle was
@@ -3961,18 +3993,7 @@ class Registry:
term.resumed = False
if minted is not None:
term.resume = minted
- # A process that inherits a conversation inherits whatever it was in the
- # middle of, and then waits. That is the whole reason this flag exists —
- # see the field. A fresh start clears it, so a pane that failed its
- # resume and came back empty is not reported as waiting to be nudged.
- # A valid conversation may already be finished or waiting for input.
- # Offer a nudge only when the previous live pane was observed working.
- # A Continue claimed while this pane was still pending stays claimed:
- # raising the flag again during attach would let a second click enqueue
- # the same nudge while the first is waiting for the input line.
- term.continuation_pending = (
- term.resumed and term.resume_continuation_needed and not term.continue_when_ready
- )
+ # A fresh start has no interrupted work behind it.
if not term.resumed:
term.resume_continuation_needed = False
@@ -4018,6 +4039,15 @@ class Registry:
async def _closed(_tid: str, code: int) -> None:
nonlocal recovered
term.pty_id = None
+ if code == _HOST_LOST_CODE and self._host_went_away():
+ # Not this agent failing: the host holding it went away. It is
+ # resumed on its own conversation once a host is back.
+ term.status = "exited"
+ term.exit_code = code
+ self._note_host_lost(term)
+ for viewer in _exit_viewers(term):
+ await viewer(code)
+ return
died_young = time.monotonic() - spawned_at < RESUME_FAILED_WINDOW_S
# Only a FAILED early exit is blamed on the resume. Quitting an
# agent normally exits 0, and a pane we killed ourselves reports a
@@ -4099,6 +4129,15 @@ class Registry:
term.error = str(exc)
raise
+ if term.resumed and not term.computer_id:
+ # The CLI's own "finish the turn that was cut off" (see
+ # ``agent_sessions.resume_env``) — how a resumed agent carries on
+ # without Jarvis ever typing into it.
+ native = resume_env(term.agent)
+ if native:
+ base = env if env is not None else _without_parent_agent_session(dict(os.environ))
+ env = {**(base if base is not None else os.environ), **native}
+
# The provider/account gate is acquired BEFORE the machine-wide gate.
# A Codex pane waiting on shared state must never occupy a CPU slot that
# an unrelated Claude/OpenCode pane could use immediately.
@@ -4238,66 +4277,9 @@ class Registry:
# one it just created, shortly from now. (Not on a remote pane:
# its history is on that computer, not in this machine's folders.)
self._schedule_lookup(session, term, term.cwd(session.folder), term.started_at)
- if term.continue_when_ready:
- # Somebody pressed "Continue" while this pane was still waiting for
- # a cold-start slot. The wish outlives the wait — see
- # `continue_when_ready` — and is spent HERE. As a task, because the
- # submit itself verifies the pane's screen for a few seconds and the
- # viewer should not wait for that receipt before attaching.
- self.defer_continue(session, term, term.continue_prompt)
await self._persist()
return term
- def defer_continue(self, session: Session, term: Terminal, prompt: str = "") -> None:
- """Remember a Continue nudge and schedule it once this pane is live.
-
- A pending pane carries the request into :meth:`attach`. A live pane may
- still be booting, so it enters the same background path immediately and
- :meth:`send_prompt` waits for the actual input line. There is one route
- for both states and therefore no fixed-delay race.
- """
- from .interrupted import CONTINUE_PROMPT
-
- term.continue_when_ready = True
- term.continue_prompt = (prompt or CONTINUE_PROMPT).strip() or CONTINUE_PROMPT
- if term.status != "live" or not term.pty_id:
- return
- queued_prompt = term.continue_prompt
- term.continue_when_ready = False
- term.continue_prompt = ""
- self._schedule_continue(session, term, queued_prompt)
-
- def _schedule_continue(self, session: Session, term: Terminal, prompt: str) -> None:
- """Send the deferred "carry on" to a pane that has just come up.
-
- Kept on the session's own task set, like the conversation-id lookups, so
- closing that workspace cancels it rather than leaving a nudge in flight
- for a pane that no longer exists.
- """
-
- async def _nudge() -> None:
- try:
- await self.send_prompt(
- term.name,
- prompt,
- workspace_id=session.id,
- )
- except SessionError as exc:
- # No bytes were written when readiness timed out or the pane
- # stopped. Put the offer back instead of losing the user's click.
- term.continuation_pending = True
- logger.warning(
- "Agentic IDE: {} came up but could not be continued: {}", term.name, exc
- )
- except asyncio.CancelledError:
- raise
- except Exception as exc: # noqa: BLE001 - a nudge must not kill the pane
- logger.warning("Agentic IDE: deferred continue for {} failed: {}", term.name, exc)
-
- task = asyncio.create_task(_nudge())
- session.lookups.add(task)
- task.add_done_callback(session.lookups.discard)
-
def _prepare_spawn(self, term: Terminal, folder: str) -> dict[str, str] | None:
"""Everything this pane's agent needs on disk, then its environment.
@@ -4512,11 +4494,8 @@ class Registry:
# Gated on a SUBMIT rather than on any keystroke: scrolling, arrow keys
# and a half-typed line are not an instruction.
if is_submit:
- # The user submitted something in the pane themselves, so this one
- # is being driven again and is no longer waiting to be nudged.
- # Dropping the pane off that list for a mere keypress would hide a
- # stalled agent behind an accidental one.
- term.continuation_pending = False
+ # The user submitted something in the pane themselves: whatever
+ # was interrupted before is superseded by this instruction.
term.resume_continuation_needed = False
# And this pane now has an instruction of its own, which is what
# makes its next stop worth reporting — a pane driven only by hand
@@ -6081,11 +6060,8 @@ class Registry:
term.name,
exc,
)
- # Somebody is driving this pane again, whatever the prompt said. Cleared
- # even when the pane did not submit the text: the instruction is sitting
- # in its input box in full, so offering to type "continue" behind it
- # would append a second line to a prompt the user still has to send.
- term.continuation_pending = False
+ # Somebody is driving this pane again: an earlier interrupted turn is
+ # superseded by this instruction.
term.resume_continuation_needed = False
if submitted is not False:
# The conversation has (or may have) just begun, so for a CLI that
@@ -6450,32 +6426,6 @@ def _unique_name(wanted: str, used: set[str]) -> str:
return f"{wanted} {suffix}"
-def _mark_restored_continuations(terminals: list[Terminal]) -> None:
- """Flag the restored panes that will come back in the middle of a job.
-
- Runs off the event loop (each check stats the coding CLI's history) and
- never raises: a pane whose history cannot be read is left unflagged, which
- costs an offer to continue it and nothing else.
-
- Holding a handle is not the same as having a conversation — a pane that was
- opened and never used holds an id that points at nothing — so this asks the
- CLI's own history, exactly as the resume offer does.
- """
- for term in terminals:
- if term.resume is None or not accepts_prompts(term.agent):
- continue
- try:
- term.continuation_pending = term.resume_continuation_needed and has_conversation(
- term.agent, term.resume, account_home(term.agent, term.account)
- )
- except Exception as exc: # noqa: BLE001 - a restore must never fail on this
- logger.debug(
- "Agentic IDE: could not tell whether {} has work to continue: {}",
- term.name,
- exc,
- )
-
-
def terminals_added_event(session: Session, created: list[Terminal], *, source_layer: str) -> Any:
"""The bus event announcing new panes to every connected client.
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 6191c3a4d7..f741f8f512 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -912,8 +912,6 @@ _AGENTIC_IDE_WORKSPACE_TOOL_NAMES: frozenset[str] = frozenset({
"agentic-ide-move-terminal",
"agentic-ide-close-agent-terminals",
"agentic-ide-focus",
- "agentic-ide-interrupted",
- "agentic-ide-continue-interrupted",
})
# Consequential action tools a signalless turn must never INHERIT from the
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index 7dc772a6e2..d14805292e 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -1478,78 +1478,6 @@ def _build_registry() -> tuple[AppCommand, ...]:
"es": ("restaura mis terminales",), # i18n-allow: input vocab
},
),
- AppCommand(
- id="agentic-ide-interrupted",
- title="List interrupted Agentic-IDE sessions",
- description=(
- "Which coding terminals came back holding their conversation "
- "and have been told nothing since. That is what a restart "
- "leaves behind: reopening a workspace reconnects each pane to "
- "the conversation it was having, but the coding CLI reads that "
- "transcript and then WAITS at its prompt — so an agent stopped "
- "mid-task looks exactly like one that finished. Use this to "
- "answer 'what was interrupted?' before continuing anything. "
- "'continuable' is per pane: a pane whose agent is not running "
- "cannot be typed into, and 'blocked_reason' says why."
- ),
- method="GET",
- path="/api/agentic-ide/interrupted",
- ui_section="agentic-ide",
- voice_aliases={
- "de": ("was wurde unterbrochen",), # i18n-allow: input vocab
- "en": ("which coding sessions were interrupted",),
- "es": ("qué sesiones se interrumpieron",), # i18n-allow: input vocab
- },
- ),
- AppCommand(
- id="agentic-ide-continue-interrupted",
- title="Continue interrupted Agentic-IDE sessions",
- description=(
- "Tell the coding terminals a restart left standing still to "
- "carry on: 'continue' is typed into each one and submitted. "
- "With no names, every interrupted pane in every open workspace "
- "— which is the shape of the problem, since a restart stops "
- "them all at once. CHECK THE REPLY: 'continued' really started, "
- "'queued' had not finished starting yet and will carry on by "
- "itself within seconds (say 'shortly', not 'done'), "
- "'unconfirmed' had the text typed in without a confirmed "
- "submit (it may be sitting in the input box — tell the user to "
- "look at that pane), and 'failed' names what refused and why. "
- "Reporting an unconfirmed or queued pane as running is the one "
- "wrong thing to do with this answer. Pressing twice is safe: "
- "each pane is claimed before anything is typed, so a repeat "
- "call cannot send a second 'continue' into the same agent."
- ),
- method="POST",
- path="/api/agentic-ide/interrupted/continue",
- params={
- "type": "object",
- "properties": {
- "names": {
- "type": "array",
- "items": {"type": "string"},
- "description": (
- "Call-signs to continue. Omit or leave empty to "
- "continue every interrupted pane."
- ),
- },
- "prompt": {
- "type": "string",
- "description": (
- "What to send instead of the default 'continue'. "
- "The agent still holds its whole conversation, so "
- "short beats elaborate."
- ),
- },
- },
- },
- ui_section="agentic-ide",
- voice_aliases={
- "de": ("mach mit den unterbrochenen sitzungen weiter",), # i18n-allow: input vocab
- "en": ("continue the interrupted coding sessions",),
- "es": ("continúa las sesiones interrumpidas",), # i18n-allow: input vocab
- },
- ),
)
diff --git a/jarvis/terminal/pty_host.py b/jarvis/terminal/pty_host.py
index 6c51113987..2c7e241c48 100644
--- a/jarvis/terminal/pty_host.py
+++ b/jarvis/terminal/pty_host.py
@@ -177,6 +177,10 @@ class PtyHost:
"token": self._token,
"proto": PROTOCOL_VERSION,
"started_at": time.time(),
+ # When the MACHINE booted. A client compares it with the current
+ # boot to know for certain that a missing host died with a
+ # reboot, rather than guessing from a failed connection.
+ "boot_time": _boot_time(),
},
)
logger.info("PTY host listening on 127.0.0.1:{} (pid {})", port, os.getpid())
@@ -458,11 +462,22 @@ def _write_state(path: Path, data: dict[str, Any]) -> None:
os.replace(tmp, path)
+def _boot_time() -> float:
+ """When this machine last booted (0.0 when it cannot be told)."""
+ try:
+ import psutil
+
+ return float(psutil.boot_time())
+ except Exception as exc: # noqa: BLE001 - optional evidence, never fatal
+ logger.debug("PTY host: boot time unavailable: {}", exc)
+ return 0.0
+
+
def _remove_state(path: Path, pid: int) -> None:
"""Remove the state file — only if it still describes THIS host."""
try:
current = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, ValueError):
+ except (OSError, ValueError): # gone or rewritten by a newer host: not ours to remove
return
if isinstance(current, dict) and current.get("pid") == pid:
try:
@@ -491,9 +506,25 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--state", required=True, help="Where to publish the port and token.")
parser.add_argument("--log", default=None, help="Log file (none when omitted).")
parser.add_argument("--idle-exit", type=float, default=IDLE_EXIT_S)
+ parser.add_argument(
+ "--token-file",
+ default=None,
+ help="Read the token from this file and delete it (a start that cannot pass env).",
+ )
args = parser.parse_args(argv)
token = os.environ.pop(TOKEN_ENV, "")
+ if not token and args.token_file:
+ token_path = Path(args.token_file)
+ try:
+ token = token_path.read_text(encoding="utf-8").strip()
+ except OSError as exc:
+ print(f"PTY host: token file unreadable: {exc}", file=sys.stderr)
+ finally:
+ try:
+ token_path.unlink()
+ except OSError as exc: # already gone is fine; anything else is logged
+ print(f"PTY host: token file not removed: {exc}", file=sys.stderr)
if not token:
print("PTY host: no token in the environment — refusing to start.", file=sys.stderr)
return 2
diff --git a/jarvis/terminal/pty_host_client.py b/jarvis/terminal/pty_host_client.py
index 4355273350..077b6ff5e8 100644
--- a/jarvis/terminal/pty_host_client.py
+++ b/jarvis/terminal/pty_host_client.py
@@ -158,6 +158,18 @@ class HostConnectionError(RuntimeError):
"""The host could not be reached, or dropped the connection."""
+class HostUnreachable(RuntimeError):
+ """A PTY host IS running for this user and boot, but did not answer.
+
+ Raised instead of returning ``None`` because the two mean opposite things
+ to the caller. ``None`` says "no host holds any agent": starting agents is
+ safe. This says "a host holds agents right now": starting one would run a
+ second copy of a live agent on the same conversation — the 2026-09-28
+ failure where panes came back doubled and a stray "continue" was typed
+ into agents that had never stopped. The caller waits and tries again.
+ """
+
+
class RemotePtyManager:
"""A ``PtyManager`` whose terminals live in the PTY host process."""
@@ -450,10 +462,54 @@ def _log_path() -> Path:
return user_data_dir() / "logs" / f"pty_host{suffix}.log"
+#: How long ``connect`` keeps trying a host that is alive but not answering
+#: (a busy machine right after login, a host mid-way through a large replay).
+LIVE_HOST_PATIENCE_S = 20.0
+
+
+def _current_boot_time() -> float:
+ try:
+ import psutil
+
+ return float(psutil.boot_time())
+ except Exception as exc: # noqa: BLE001 - optional evidence
+ logger.debug("PTY host: boot time unavailable: {}", exc)
+ return 0.0
+
+
+def host_is_alive(state: dict[str, Any] | None) -> bool:
+ """Is the host this state file describes still running, in THIS boot?
+
+ Three facts, all checked: the process exists, it is a PTY host (a pid is
+ reused after it dies), and it started after the machine last booted. A
+ state file from before a reboot therefore reads as dead however its pid
+ happens to be reused now — which is what makes "the machine restarted"
+ a measurement instead of a guess.
+ """
+ if not state or not state.get("pid"):
+ return False
+ try:
+ import psutil
+
+ proc = psutil.Process(int(state["pid"]))
+ cmdline = " ".join(proc.cmdline())
+ created = float(proc.create_time())
+ except Exception as exc: # noqa: BLE001 - gone, not ours, or unreadable: not alive
+ logger.debug("PTY host pid {} is not a live host: {}", state.get("pid"), exc)
+ return False
+ if "jarvis.terminal.pty_host" not in cmdline:
+ return False
+ boot = _current_boot_time()
+ recorded = float(state.get("boot_time") or 0.0)
+ if boot and recorded and abs(recorded - boot) > 5.0:
+ return False
+ return not boot or created >= boot - 5.0
+
+
def _read_state(path: Path) -> dict[str, Any] | None:
try:
data = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, ValueError):
+ except (OSError, ValueError): # no readable state file means no host to attach to
return None
return data if isinstance(data, dict) else None
@@ -538,6 +594,8 @@ def _start_host(state_path: Path, token: str) -> bool:
"--log",
str(_log_path()),
]
+ if sys.platform == "win32":
+ return _start_host_windows(argv, package_root, env, token, state_path)
try:
spawn_detached(argv, cwd=package_root, env=env)
except OSError as exc:
@@ -546,35 +604,140 @@ def _start_host(state_path: Path, token: str) -> bool:
return True
+def _start_host_windows(
+ argv: list[str], cwd: str, env: dict[str, str], token: str, state_path: Path
+) -> bool:
+ """Start the host so that NO job object of the app can take it down.
+
+ Windows kills every member of a job created with KILL_ON_JOB_CLOSE when
+ the job's last handle closes — and the app itself may sit in one (started
+ from a terminal, an IDE or an agent shell that uses jobs). A child only
+ leaves such a job with ``CREATE_BREAKAWAY_FROM_JOB``, and only when the job
+ allows it. ``relauncher.spawn_detached`` falls back to starting INSIDE the
+ job when breakaway is refused, which for the host means dying with the app
+ it exists to outlive. So a refused breakaway goes through WMI instead:
+ ``Win32_Process.Create`` starts the process under the WMI service, outside
+ every job of ours (the approach cmux and others document). WMI cannot pass
+ an environment, so the token travels in a user-only file the host deletes.
+ """
+ import subprocess
+
+ flags = (
+ getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
+ | getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
+ | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
+ | getattr(subprocess, "CREATE_BREAKAWAY_FROM_JOB", 0x01000000)
+ )
+ try:
+ subprocess.Popen( # noqa: S603 - our own interpreter, fixed arguments
+ argv,
+ cwd=cwd,
+ env=env,
+ creationflags=flags,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ close_fds=True,
+ )
+ return True
+ except PermissionError:
+ logger.info("PTY host: the app's job refuses breakaway — starting it through WMI")
+ except OSError as exc:
+ logger.warning("PTY host could not be started: {}", exc)
+ return False
+ return _start_host_via_wmi(argv, cwd, token, state_path)
+
+
+def _start_host_via_wmi(argv: list[str], cwd: str, token: str, state_path: Path) -> bool:
+ import subprocess
+
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ token_file = state_path.with_name(state_path.stem + f".{os.getpid()}.token")
+ try:
+ token_file.parent.mkdir(parents=True, exist_ok=True)
+ token_file.write_text(token, encoding="utf-8")
+ except OSError as exc:
+ logger.warning("PTY host token file could not be written: {}", exc)
+ return False
+ # python.exe, not pythonw: ConPTY needs a console of its own to attach the
+ # pseudo-console to (a pythonw host died on its first spawn, measured
+ # 2026-09-28), even though the app itself may run under pythonw. Its window
+ # is hidden through ``ShowWindow=0`` below.
+ exe = Path(argv[0])
+ console = exe.with_name("python.exe")
+ command = [str(console if console.exists() else exe), *argv[1:]]
+ command += ["--token-file", str(token_file)]
+ line = subprocess.list2cmdline(command).replace("'", "''")
+ folder = cwd.replace("'", "''")
+ script = (
+ "$si = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly "
+ "-Property @{ShowWindow=[uint16]0}; "
+ "$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments "
+ f"@{{CommandLine='{line}'; CurrentDirectory='{folder}'; ProcessStartupInformation=$si}}; "
+ "exit [int]$r.ReturnValue"
+ )
+ try:
+ done = subprocess.run( # noqa: S603 - fixed PowerShell script, our own arguments
+ ["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ capture_output=True,
+ timeout=30,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ logger.warning("PTY host could not be started through WMI: {}", exc)
+ return False
+ if done.returncode != 0:
+ logger.warning("PTY host WMI start returned {}", done.returncode)
+ return False
+ return True
+
+
async def connect(*, start: bool = True) -> RemotePtyManager | None:
- """Attach to the running PTY host, starting one if none answers.
+ """Attach to the running PTY host, starting one only when none is running.
- Never raises; ``None`` means "keep terminals in this process" (module
- docstring).
+ ``None`` means "no host holds any agent — keep terminals in this process"
+ (module docstring). A host that is running but does not answer raises
+ :class:`HostUnreachable` after :data:`LIVE_HOST_PATIENCE_S`: it is never
+ mistaken for a missing one, and a second host is never started beside it.
"""
if not host_available():
return None
state_path = _state_path()
state = await asyncio.to_thread(_read_state, state_path)
- if state is not None and state.get("port") and state.get("token"):
- if state.get("proto") != PROTOCOL_VERSION:
- # A host from another build may be holding agents; never replace it
- # blindly. It exits on its own once they are gone.
- logger.warning(
- "PTY host speaks protocol {} (this build: {}) — terminals stay in-process",
- state.get("proto"),
- PROTOCOL_VERSION,
- )
- return None
- found = await _handshake(int(state["port"]), str(state["token"]), wait_s=3.0)
- if found is not None:
- manager = _manager_from(*found)
- logger.info(
- "PTY host attached (pid {}) — {} terminal(s) still running",
- manager.host_pid,
- len(manager.hosted()),
+ alive = await asyncio.to_thread(host_is_alive, state)
+ if alive and state is not None and state.get("proto") == PROTOCOL_VERSION:
+ deadline = time.monotonic() + LIVE_HOST_PATIENCE_S
+ delay = 0.25
+ while True:
+ found = await _handshake(int(state["port"]), str(state["token"]), wait_s=3.0)
+ if found is not None:
+ manager = _manager_from(*found)
+ logger.info(
+ "PTY host attached (pid {}) — {} terminal(s) still running",
+ manager.host_pid,
+ len(manager.hosted()),
+ )
+ return manager
+ if time.monotonic() >= deadline or not await asyncio.to_thread(host_is_alive, state):
+ break
+ await asyncio.sleep(delay)
+ delay = min(delay * 2, 2.0)
+ if await asyncio.to_thread(host_is_alive, state):
+ raise HostUnreachable(
+ f"The terminal host (pid {state.get('pid')}) is running but not answering."
)
- return manager
+ state = None # it died while we waited: treat it as gone
+ if alive and state is not None:
+ # Alive, but speaking another protocol: a host from another build that
+ # still holds its agents. Starting ours beside it would run a second
+ # copy of each of them, so it is reported as unreachable instead; it
+ # exits on its own once its agents are gone.
+ raise HostUnreachable(
+ f"The terminal host (pid {state.get('pid')}) speaks protocol "
+ f"{state.get('proto')}, this build speaks {PROTOCOL_VERSION}."
+ )
if not start:
return None
@@ -601,6 +764,8 @@ async def connect(*, start: bool = True) -> RemotePtyManager | None:
__all__ = [
"AdoptResult",
"HostConnectionError",
+ "HostUnreachable",
+ "host_is_alive",
"HostedInfo",
"RemotePtyManager",
"RemoteSession",
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 5d1015cfb3..610beae69d 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -26,8 +26,6 @@ Endpoints (prefix ``/api/agentic-ide``):
* ``GET /resume`` → the last workspace, offered back
* ``POST /resume`` → reopen it (same panes, same places)
* ``DELETE /resume`` → forget it and start fresh
-* ``GET /interrupted`` → panes that came back and were never restarted
-* ``POST /interrupted/continue`` → tell them to carry on ("continue")
* ``PUT /mode`` → focused coding mode on/off
* ``GET /ui-preferences`` → remembered terminal text size
* ``PUT /ui-preferences`` → remember another one (survives restarts)
@@ -85,7 +83,6 @@ from jarvis.agentic_ide import (
drop_analysis,
drops,
git_changes,
- interrupted,
native_picker,
notifications,
prompt_attachments,
@@ -1096,51 +1093,6 @@ class ResumeOffer(BaseModel):
workspaces: list[ResumeWorkspace] = Field(default_factory=list)
-class InterruptedPane(BaseModel):
- """One pane that came back with its conversation and was never restarted."""
-
- workspace_id: str = ""
- workspace: str = Field(default="", description="The workspace tab this pane belongs to.")
- folder: str = ""
- key: str
- name: str
- agent: str
- display_name: str
- status: str
- continuable: bool = Field(
- description=(
- "Will a 'continue' reach it? False only when its agent is DEAD — an "
- "instruction cannot be typed into a terminal that exited. A pane "
- "that is merely still starting IS continuable; see 'starting'."
- )
- )
- starting: bool = Field(
- default=False,
- description=(
- "Its agent is still coming up (cold starts are staggered). Continuing "
- "it is a promise kept a few seconds later, not a refusal."
- ),
- )
- queued: bool = Field(
- default=False,
- description="A 'continue' is already waiting to be delivered to this pane.",
- )
- blocked_reason: str = Field(
- default="", description="Why not, in one sentence. Empty when it can."
- )
- last_task: str = Field(
- default="",
- description=(
- "What this pane was last asked to do, shortened. Empty when its last "
- "instruction was typed into the pane directly rather than sent by Jarvis."
- ),
- )
- prompts_sent: int = 0
- started_at: float | None = Field(
- default=None, description="When the resumed agent process started."
- )
-
-
class PaneNotification(BaseModel):
"""One thing that happened in one pane, as the bell lists it."""
@@ -1214,62 +1166,6 @@ class NotificationsChangedResponse(BaseModel):
unread: int = 0
-class InterruptedResponse(BaseModel):
- """Every pane, in every open workspace, that is waiting to be told to carry on."""
-
- count: int = 0
- continuable_count: int = Field(
- default=0, description="How many of them can be continued right now."
- )
- prompt: str = Field(default="", description="The instruction the continue action would send.")
- panes: list[InterruptedPane] = Field(default_factory=list)
-
-
-class ContinueInterruptedRequest(BaseModel):
- names: list[str] = Field(
- default_factory=list,
- description=(
- "Call-signs to continue. Empty continues every interrupted pane in "
- "every open workspace. A name that is not waiting to be continued is "
- "reported in 'failed' rather than silently ignored."
- ),
- )
- prompt: str = Field(
- default="",
- description=(
- "What to send instead of the default 'continue'. The agent still "
- "holds its whole conversation, so short beats elaborate."
- ),
- )
-
-
-class ContinueInterruptedResponse(BaseModel):
- ok: bool = True
- continued: list[str] = Field(
- default_factory=list, description="Panes that accepted the instruction and started."
- )
- queued: list[str] = Field(
- default_factory=list,
- description=(
- "Panes whose agent had not started yet. The instruction is held and "
- "delivered the moment each one comes up — say 'shortly', not 'done'."
- ),
- )
- unconfirmed: list[str] = Field(
- default_factory=list,
- description=(
- "Panes the text was typed into without a confirmed submit. Their prompt "
- "may be sitting in the input box — say so rather than claiming they ran."
- ),
- )
- failed: list[dict] = Field(
- default_factory=list, description="Panes that could not be continued, with the reason."
- )
- remaining: int = Field(
- default=0, description="Interrupted panes still waiting after this call."
- )
-
-
class TerminalActivity(BaseModel):
"""What one pane is DOING, and nothing about what it is doing it about.
@@ -2475,68 +2371,6 @@ async def resume_workspace(request: Request) -> dict:
}
- "/interrupted",
- response_model=InterruptedResponse,
- summary="Coding sessions that were interrupted and never restarted",
-)
-def get_interrupted() -> InterruptedResponse:
- """Which panes came back holding a conversation and have been told nothing since.
-
- The state a restart leaves behind. Resuming reconnects each pane to the
- conversation it was having, but a coding CLI launched on an old transcript
- reads it and then waits — so an agent that was halfway through a job comes
- back knowing everything about it and doing nothing, looking exactly like a
- pane that finished.
-
- ``continuable`` is per pane and answered against the machine as it is now: a
- pane whose agent is not running cannot be typed into, and ``blocked_reason``
- says why. An empty list is the normal answer — nothing was interrupted.
- """
- panes = interrupted.scan(get_registry())
- return InterruptedResponse(
- count=len(panes),
- continuable_count=sum(1 for pane in panes if pane.continuable),
- prompt=interrupted.CONTINUE_PROMPT,
- panes=[InterruptedPane(**pane.to_dict()) for pane in panes],
- )
-
-
- "/interrupted/continue",
- response_model=ContinueInterruptedResponse,
- summary="Tell interrupted coding sessions to carry on",
-)
-async def continue_interrupted(req: ContinueInterruptedRequest) -> ContinueInterruptedResponse:
- """Type ``continue`` into the panes a restart left standing still.
-
- With no ``names``, every interrupted pane in every open workspace — which is
- the shape of the problem, since a restart interrupts them all at once. The
- instruction goes through the ordinary prompt path, so the same guarantees
- hold: control characters stripped, the submit verified against the pane's own
- screen, and three honest outcomes rather than two.
-
- **Read ``unconfirmed``.** Those panes were typed into without a confirmed
- submit: the text may be sitting in the input box waiting for a keypress.
- Reporting them as running is the one wrong thing to do with this answer.
-
- ``409`` only when no workspace is open at all. Nothing to continue is a
- normal, empty success.
- """
- registry = get_registry()
- if not registry.sessions:
- raise HTTPException(status_code=409, detail="No Agentic-IDE session is running.")
- report = await interrupted.continue_panes(
- registry, names=req.names, prompt=req.prompt or interrupted.CONTINUE_PROMPT
- )
- return ContinueInterruptedResponse(
- **report.to_dict(),
- # Re-scanned rather than subtracted: a pane the user drove themselves
- # while this call was in flight has left the list too.
- remaining=len(interrupted.scan(registry)),
- )
-
-
@router.get(
"/notifications",
response_model=PaneNotificationsResponse,
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 77d34231b8..163a0a0afb 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -87,16 +87,6 @@ vi.mock("@/lib/agenticIdeApi", () => ({
promptTerminal: vi.fn(),
// Reached from the toolbar's settings panel, which the grid always renders.
setIdeActiveAccount: vi.fn(),
- // Polled by the toolbar's "Continue" control, which the grid also always
- // renders. Answers "nothing was interrupted" so these tests see the ordinary
- // toolbar rather than a badge none of them are about.
- fetchInterrupted: vi.fn(async () => ({
- count: 0,
- continuable_count: 0,
- prompt: "continue",
- panes: [],
- })),
- continueInterrupted: vi.fn(),
// Polled by the header bell, which the grid also always renders. Answers
// "nothing has stopped" so these tests see a plain toolbar rather than a
// badge none of them are about.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index 19fef7aef9..83b6e0c39e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -67,7 +67,6 @@ import {
hasLayoutViolations,
type MeasuredPane,
} from "./paneLayoutGuard";
-import { ContinueInterrupted } from "./ContinueInterrupted";
import { PaneNotifications } from "./PaneNotifications";
import { isVoiceActive } from "./useVoiceCall";
// One strip of chips, one drop handler and one paste handler for every
@@ -2267,19 +2266,9 @@ export function AgenticGrid({
onFontSize={setFontSize}
/>
- {/* Which terminals stopped while you were looking at another one.
- Before "Continue" rather than after it, because the two answer the
- same question at different scales — this one is "what happened",
- that one is "what should start again" — and reading them in that
- order is how somebody decides they need the second at all. */}
+ {/* Which terminals stopped while you were looking at another one. */}
<PaneNotifications onJump={jumpToNotification} onScreen={onScreen} />
- {/* Work a restart stopped: which panes came back holding a conversation
- and were never told to carry on, and the one click that tells them.
- The pane headers catch up on their own — a continued agent starts
- printing, and the recap poll above is already watching for that. */}
- <ContinueInterrupted busy={busy || working} onScreen={onScreen} />
-
{/* Which subscription the next terminal spends, and the way to change
it without leaving the workspace. */}
<WorkspaceSettings
diff --git a/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.test.tsx
deleted file mode 100644
index a80452190d..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.test.tsx
+++ /dev/null
@@ -1,266 +0,0 @@
-/**
- * Component tests for the "Continue interrupted" toolbar control.
- *
- * What matters here is not the layout but WHAT THE USER IS TOLD before and after
- * the click. Three things carry the feature and each one has been a real failure
- * mode somewhere in this app:
- *
- * 1. A pane whose agent is not running must be visibly un-continuable BEFORE the
- * click, not after — otherwise the button promises work it cannot start.
- * 2. A pane the instruction was typed into without a confirmed submit is its own
- * outcome. Reporting it as "carrying on" is the exact lie the backend's
- * three-state answer exists to prevent.
- * 3. Nothing interrupted is a normal, quiet answer — never an error.
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-
-const pushToast = vi.fn();
-vi.mock("@/store/events", () => ({
- useEventStore: (selector: (s: Record<string, unknown>) => unknown) =>
- selector({ pushToast, assistantName: "Jarvis" }),
-}));
-
-vi.mock("@/lib/agenticIdeApi", () => ({
- fetchInterrupted: vi.fn(),
- continueInterrupted: vi.fn(),
-}));
-
-import { ContinueInterrupted } from "./ContinueInterrupted";
-import {
- continueInterrupted,
- fetchInterrupted,
- type ContinueResult,
- type InterruptedOffer,
- type InterruptedPane,
-} from "@/lib/agenticIdeApi";
-
-function pane(over: Partial<InterruptedPane> = {}): InterruptedPane {
- return {
- workspace_id: "ide_1",
- workspace: "Personal Jarvis",
- folder: "/repo",
- key: "alex",
- name: "Alex",
- agent: "claude",
- display_name: "Claude Code",
- status: "live",
- continuable: true,
- blocked_reason: "",
- last_task: "rewrite the resume store",
- prompts_sent: 3,
- started_at: 1000,
- ...over,
- };
-}
-
-function offer(panes: InterruptedPane[]): InterruptedOffer {
- return {
- count: panes.length,
- continuable_count: panes.filter((p) => p.continuable).length,
- prompt: "continue",
- panes,
- };
-}
-
-function result(over: Partial<ContinueResult> = {}): ContinueResult {
- return {
- ok: true,
- continued: [],
- queued: [],
- unconfirmed: [],
- failed: [],
- remaining: 0,
- ...over,
- };
-}
-
-const asked = () => vi.mocked(fetchInterrupted);
-const told = () => vi.mocked(continueInterrupted);
-
-
-/** jest-dom is not set up here, so this asks the element itself. */
-function disabled(testId: string): boolean {
- return (screen.getByTestId(testId) as HTMLButtonElement).disabled;
-}
-
-async function openDialog() {
- render(<ContinueInterrupted />);
- await waitFor(() => expect(asked()).toHaveBeenCalled());
- fireEvent.click(screen.getByTestId("continue-interrupted-open"));
- return screen.findByTestId("continue-interrupted");
-}
-
-describe("ContinueInterrupted", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- asked().mockResolvedValue(offer([]));
- told().mockResolvedValue(result());
- });
-
- afterEach(cleanup);
-
- it("counts the waiting panes on the button", async () => {
- asked().mockResolvedValue(offer([pane(), pane({ key: "blake", name: "Blake" })]));
-
- render(<ContinueInterrupted />);
-
- const badge = await screen.findByTestId("continue-interrupted-count");
- expect(badge.textContent).toBe("2");
- });
-
- it("stays quiet when nothing was interrupted", async () => {
- render(<ContinueInterrupted />);
- await waitFor(() => expect(asked()).toHaveBeenCalled());
-
- expect(screen.queryByTestId("continue-interrupted-count")).toBeNull();
- });
-
- it("re-checks when the dialog is opened", async () => {
- // The whole point of the button: "check what was interrupted" must be a
- // fresh answer, not whatever the background poll last happened to see.
- asked().mockResolvedValue(offer([pane()]));
-
- await openDialog();
-
- expect(asked()).toHaveBeenCalledTimes(2);
- });
-
- it("says which pane cannot be continued, and why, before the click", async () => {
- asked().mockResolvedValue(
- offer([
- pane({
- key: "blake",
- name: "Blake",
- status: "exited",
- continuable: false,
- blocked_reason: "Its agent stopped with exit code 1 — restart the pane first.",
- }),
- ]),
- );
-
- await openDialog();
-
- expect(screen.getByText(/restart the pane first/)).toBeTruthy();
- expect(disabled("continue-pane-Blake")).toBe(true);
- expect(disabled("continue-interrupted-all")).toBe(true);
- });
-
- it("continues one named pane from its own button", async () => {
- asked().mockResolvedValue(offer([pane(), pane({ key: "blake", name: "Blake" })]));
- told().mockResolvedValue(result({ continued: ["Blake"], remaining: 1 }));
-
- await openDialog();
- fireEvent.click(screen.getByTestId("continue-pane-Blake"));
-
- await waitFor(() => expect(told()).toHaveBeenCalledWith(["Blake"]));
- });
-
- it("continues every pane with no names at all", async () => {
- asked().mockResolvedValue(offer([pane()]));
- told().mockResolvedValue(result({ continued: ["Alex"] }));
-
- await openDialog();
- fireEvent.click(screen.getByTestId("continue-interrupted-all"));
-
- await waitFor(() => expect(told()).toHaveBeenCalledWith(undefined));
- });
-
- it("reports a pane that never submitted as a warning, not a success", async () => {
- asked().mockResolvedValue(offer([pane()]));
- told().mockResolvedValue(result({ ok: true, unconfirmed: ["Alex"], remaining: 1 }));
-
- await openDialog();
- fireEvent.click(screen.getByTestId("continue-interrupted-all"));
-
- await waitFor(() => expect(pushToast).toHaveBeenCalled());
- const [tone, message] = pushToast.mock.calls.at(-1) as [string, string];
- expect(tone).toBe("warning");
- expect(message).toContain("Alex");
- });
-
- it("reports a refusal as an error and names the reason", async () => {
- asked().mockResolvedValue(offer([pane()]));
- told().mockResolvedValue(
- result({ ok: false, failed: [{ name: "Alex", detail: "not running" }], remaining: 1 }),
- );
-
- await openDialog();
- fireEvent.click(screen.getByTestId("continue-interrupted-all"));
-
- await waitFor(() => expect(pushToast).toHaveBeenCalled());
- const [tone, message] = pushToast.mock.calls.at(-1) as [string, string];
- expect(tone).toBe("error");
- expect(message).toContain("not running");
- });
-
- it("closes once nothing is left waiting", async () => {
- asked().mockResolvedValueOnce(offer([pane()])).mockResolvedValueOnce(offer([pane()]));
- told().mockResolvedValue(result({ continued: ["Alex"] }));
- asked().mockResolvedValue(offer([]));
-
- await openDialog();
- fireEvent.click(screen.getByTestId("continue-interrupted-all"));
-
- await waitFor(() => expect(screen.queryByTestId("continue-interrupted")).toBeNull());
- });
-
- it("cannot be pressed twice while the first instruction is in flight", async () => {
- // A delivery takes seconds — the submit is verified against the pane's own
- // screen — and a live button in that window is a button somebody presses
- // again. Two presses used to mean the agent got "continue" twice.
- asked().mockResolvedValue(offer([pane()]));
- let release: (value: ContinueResult) => void = () => {};
- told().mockReturnValue(
- new Promise<ContinueResult>((resolve) => {
- release = resolve;
- }),
- );
-
- await openDialog();
- fireEvent.click(screen.getByTestId("continue-interrupted-all"));
-
- await waitFor(() => expect(disabled("continue-interrupted-all")).toBe(true));
- expect(disabled("continue-pane-Alex")).toBe(true);
- fireEvent.click(screen.getByTestId("continue-interrupted-all"));
- fireEvent.click(screen.getByTestId("continue-pane-Alex"));
-
- expect(told()).toHaveBeenCalledTimes(1);
- release(result({ continued: ["Alex"] }));
- });
-
- it("says a still-starting pane will carry on, rather than claiming it did", async () => {
- asked().mockResolvedValue(offer([pane({ starting: true, status: "pending" })]));
- told().mockResolvedValue(result({ queued: ["Alex"], remaining: 1 }));
-
- await openDialog();
- expect(screen.getByTestId("interrupted-starting-Alex")).toBeTruthy();
- fireEvent.click(screen.getByTestId("continue-interrupted-all"));
-
- await waitFor(() => expect(pushToast).toHaveBeenCalled());
- const [, message] = pushToast.mock.calls.at(-1) as [string, string];
- expect(message).toContain("Alex");
- expect(message).not.toContain("carrying on");
- });
-
- it("leaves a pane alone once its continue is already queued", async () => {
- // The backend is holding one for it. A second press would queue a second.
- asked().mockResolvedValue(offer([pane({ starting: true, queued: true })]));
-
- await openDialog();
-
- expect(disabled("continue-pane-Alex")).toBe(true);
- });
-
- it("keeps its last count when the check fails", async () => {
- // A backend hiccup must not put an error in front of somebody who is
- // working — the control is a convenience, never the workspace.
- asked().mockRejectedValue(new Error("backend is warming up"));
-
- render(<ContinueInterrupted />);
- await waitFor(() => expect(asked()).toHaveBeenCalled());
-
- expect(pushToast).not.toHaveBeenCalled();
- expect(screen.queryByTestId("continue-interrupted-count")).toBeNull();
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx b/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx
deleted file mode 100644
index 6a8342214f..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx
+++ /dev/null
@@ -1,423 +0,0 @@
-/**
- * "Continue interrupted" — the toolbar button that restarts work a restart stopped.
- *
- * ## The gap it closes
- *
- * Resuming a workspace brings the panes back and reconnects each one to the
- * conversation it was having. It cannot make the agents carry on: a coding CLI
- * launched on an old transcript reads it and then waits at its prompt. So an
- * agent that was halfway through a job comes back knowing every detail of it and
- * doing nothing — and on screen that is indistinguishable from a pane that
- * finished. The user's report was exactly that: the sessions were interrupted,
- * twelve terminals sat there, and nothing said which of them still had work.
- *
- * So: a button that checks, a list that says which panes are waiting, and one
- * click that types `continue` into them.
- *
- * ## Why a button and not an automatic nudge
- *
- * Sending "continue" to every resumed pane the moment a workspace comes back
- * would restart twelve agents on twelve unattended tasks because somebody
- * reopened a folder to look at one file. And an agent that was interrupted ON
- * PURPOSE ("stop, that is the wrong approach") would cheerfully resume the thing
- * it was told to stop. The offer is a click, never a side effect of opening a
- * workspace.
- *
- * ## Why it lists panes rather than just counting them
- *
- * Because "continue" is not one answer. A pane whose agent is not running cannot
- * be typed into at all, and each pane carries the job it was last given — which
- * is how somebody decides that two of the five are worth restarting and the
- * others are not. Both are shown BEFORE the click, not discovered after it.
- */
-import { useCallback, useEffect, useState } from "react";
-import * as Dialog from "@radix-ui/react-dialog";
-import { AlertCircle, FolderGit2, Loader2, PlayCircle, Terminal, X } from "lucide-react";
-
-import { useT } from "@/i18n";
-import { cn } from "@/lib/utils";
-import { useDocumentVisible } from "@/hooks/useDocumentVisible";
-import {
- continueInterrupted,
- fetchInterrupted,
- type ContinueResult,
- type InterruptedOffer,
- type InterruptedPane,
-} from "@/lib/agenticIdeApi";
-import { useEventStore } from "@/store/events";
-
-/**
- * How often the count behind the button is refreshed.
- *
- * Slower than the recap poll on purpose: this answer only changes when a pane is
- * resumed or driven again, which is a human-paced event. The dialog re-reads on
- * open regardless, so nothing on screen is ever the stale copy.
- */
-const POLL_MS = 15_000;
-
-const EMPTY: InterruptedOffer = {
- count: 0,
- continuable_count: 0,
- prompt: "continue",
- panes: [],
-};
-
-interface ContinueInterruptedProps {
- /** Disable the control while the workspace is busy with something else. */
- busy?: boolean;
- /**
- * Is the section holding this control the one on screen? The workspace stays
- * mounted behind other sections (see MainView), and this poll runs for as
- * long as it is open. Defaults to true — the behaviour before it could hide.
- */
- onScreen?: boolean;
-}
-
-/** One line of plain language for what the button will actually do. */
-export function continueSummary(offer: InterruptedOffer, t: (key: string) => string): string {
- if (offer.count === 0) return t("agentic_grid.continue.none");
- const blocked = offer.count - offer.continuable_count;
- const base = t(
- offer.continuable_count === 1
- ? "agentic_grid.continue.summary_one"
- : "agentic_grid.continue.summary_many",
- ).replace("{0}", String(offer.continuable_count));
- if (blocked === 0) return base;
- return `${base} ${t("agentic_grid.continue.summary_blocked").replace("{0}", String(blocked))}`;
-}
-
-/** What to tell the user after the instruction went out. */
-export function continueOutcome(
- result: ContinueResult,
- t: (key: string) => string,
-): { tone: "success" | "warning" | "error"; message: string } {
- const parts: string[] = [];
- if (result.continued.length > 0) {
- parts.push(
- t("agentic_grid.continue.result_continued")
- .replace("{0}", String(result.continued.length))
- .replace("{1}", result.continued.join(", ")),
- );
- }
- // Held, not sent: their agents are still starting. Said separately because
- // "carrying on" would be a claim about panes that have not been typed into
- // yet — they are a promise the backend keeps a few seconds later.
- if (result.queued.length > 0) {
- parts.push(
- t("agentic_grid.continue.result_queued")
- .replace("{0}", String(result.queued.length))
- .replace("{1}", result.queued.join(", ")),
- );
- }
- // Its own sentence, never folded into the success count: those panes were
- // typed into without a confirmed submit, so the text may be sitting in the
- // input box waiting for a keypress the user has to make.
- if (result.unconfirmed.length > 0) {
- parts.push(
- t("agentic_grid.continue.result_unconfirmed").replace("{0}", result.unconfirmed.join(", ")),
- );
- }
- if (result.failed.length > 0) {
- parts.push(
- t("agentic_grid.continue.result_failed").replace(
- "{0}",
- result.failed.map((f) => `${f.name} (${f.detail})`).join("; "),
- ),
- );
- }
- const tone =
- result.failed.length > 0 && result.continued.length === 0
- ? "error"
- : result.failed.length > 0 || result.unconfirmed.length > 0
- ? "warning"
- : "success";
- return { tone, message: parts.join(" ") || t("agentic_grid.continue.none") };
-}
-
-function PaneRow({
- pane,
- busy,
- sending,
- onContinue,
-}: {
- pane: InterruptedPane;
- busy: boolean;
- /** This pane's own instruction is in flight — its button is spent. */
- sending: boolean;
- onContinue: () => void;
-}) {
- const t = useT();
- // Already spoken for: in flight from this window, or held by the backend
- // until its agent comes up. Either way a second press would be a second
- // "continue" into the same conversation.
- const spent = sending || Boolean(pane.queued);
- return (
- <li
- data-testid={`interrupted-pane-${pane.name}`}
- className={cn(
- "rounded-lg border p-3",
- pane.continuable ? "border-border bg-card" : "border-foreground/40 bg-foreground/10",
- )}
- >
- <div className="flex flex-wrap items-start justify-between gap-2">
- <div className="min-w-0">
- <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
- <Terminal className="h-3.5 w-3.5 shrink-0 translate-y-0.5 text-primary" />
- <span className="font-medium text-foreground">{pane.name}</span>
- <span className="text-xs text-muted-foreground">{pane.display_name}</span>
- <span className="flex items-center gap-1 text-xs text-muted-foreground">
- <FolderGit2 className="h-3 w-3 shrink-0" />
- {pane.workspace}
- </span>
- </div>
- {pane.last_task ? (
- <p className="mt-1 text-xs text-muted-foreground">
- {t("agentic_grid.continue.last_task").replace("{0}", pane.last_task)}
- </p>
- ) : (
- <p className="mt-1 text-xs text-muted-foreground">
- {t("agentic_grid.continue.no_task")}
- </p>
- )}
- {!pane.continuable && (
- <p className="mt-1.5 flex items-start gap-1.5 text-xs text-foreground">
- <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
- {pane.blocked_reason}
- </p>
- )}
- {pane.continuable && pane.starting && (
- <p
- data-testid={`interrupted-starting-${pane.name}`}
- className="mt-1.5 text-xs text-muted-foreground"
- >
- {t("agentic_grid.continue.starting")}
- </p>
- )}
- </div>
- <button
- type="button"
- data-testid={`continue-pane-${pane.name}`}
- className="btn-ghost shrink-0 disabled:cursor-not-allowed disabled:opacity-40"
- disabled={busy || spent || !pane.continuable}
- onClick={onContinue}
- >
- {sending ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <PlayCircle className="h-4 w-4" />
- )}
- {spent ? t("agentic_grid.continue.sending") : t("agentic_grid.continue.one")}
- </button>
- </div>
- </li>
- );
-}
-
-export function ContinueInterrupted({
- busy = false,
- onScreen = true,
-}: ContinueInterruptedProps) {
- const t = useT();
- const pushToast = useEventStore((s) => s.pushToast);
- const [offer, setOffer] = useState<InterruptedOffer>(EMPTY);
- const [open, setOpen] = useState(false);
- const [working, setWorking] = useState(false);
- // Call-signs whose instruction is in flight from THIS window. Per pane rather
- // than one global flag, so continuing one pane does not freeze the buttons of
- // the others while it waits for its screen to change.
- const [sending, setSending] = useState<Set<string>>(() => new Set());
-
- const refresh = useCallback(async (): Promise<InterruptedOffer> => {
- try {
- const next = await fetchInterrupted();
- setOffer(next);
- return next;
- } catch {
- // A failed check must not put an error in front of somebody who is
- // working — the button simply keeps its last honest count.
- return EMPTY;
- }
- }, []);
-
- /*
- * Poll only while there is somebody to show a count to.
- *
- * Two ways for that to be false and one answer for both: the window is
- * minimized or behind another (`documentVisible`), or the user is in another
- * section while this workspace stays mounted behind it (`onScreen`).
- *
- * Binding the effect to that answer rather than checking it inside the tick
- * is also the catch-up: coming back rebuilds the effect, and the first thing
- * a rebuilt effect does is read. That matters here more than most — the
- * restart that interrupts the panes is exactly the event that happens while
- * nobody is looking.
- */
- const documentVisible = useDocumentVisible();
- const polling = onScreen && documentVisible;
- useEffect(() => {
- if (!polling) return;
- void refresh();
- const timer = window.setInterval(() => void refresh(), POLL_MS);
- return () => window.clearInterval(timer);
- }, [refresh, polling]);
-
- const run = async (names?: string[]) => {
- // Which panes this press owns, marked BEFORE the request goes out.
- //
- // Delivering a "continue" takes seconds — the submit is verified against
- // the pane's own screen — and a button that stays live for that whole time
- // is a button somebody presses again. The backend refuses the duplicate
- // too (it claims each pane synchronously), but a control that looks
- // clickable and silently does nothing is its own bug: this makes the wait
- // visible where the click happened.
- const claimed = names ?? offer.panes.filter((p) => p.continuable).map((p) => p.name);
- setSending((current) => new Set([...current, ...claimed]));
- setWorking(true);
- try {
- const result = await continueInterrupted(names);
- const { tone, message } = continueOutcome(result, t);
- pushToast(tone, message);
- const next = await refresh();
- // Nothing left to offer: close rather than leave an empty dialog in front
- // of a workspace the user now wants to watch.
- if (next.count === 0) setOpen(false);
- } catch (e) {
- pushToast("error", (e as Error).message);
- } finally {
- setSending((current) => {
- const rest = new Set(current);
- for (const name of claimed) rest.delete(name);
- return rest;
- });
- setWorking(false);
- }
- };
-
- const waiting = offer.count > 0;
- return (
- <Dialog.Root
- open={open}
- onOpenChange={(next) => {
- if (working) return;
- setOpen(next);
- // Checked on every open, so the list is never the poll's stale copy —
- // and so the button answers "check what was interrupted" honestly even
- // when the count behind it happens to be a few seconds old.
- if (next) void refresh();
- }}
- >
- <Dialog.Trigger asChild>
- <button
- type="button"
- data-testid="continue-interrupted-open"
- disabled={busy}
- title={t("agentic_grid.continue.hint")}
- className={cn(
- // Quiet at rest, amber only while panes actually wait — the same
- // rule the rest of the toolbar follows (TOOLBAR_BTN in AgenticGrid).
- "flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40",
- waiting
- ? "bg-foreground/15 text-foreground hover:bg-foreground/25"
- : "text-muted-foreground hover:bg-secondary hover:text-foreground",
- )}
- >
- <PlayCircle className="h-4 w-4" />
- {t("agentic_grid.continue.button")}
- {waiting && (
- <span
- data-testid="continue-interrupted-count"
- className="rounded bg-foreground/25 px-1.5 py-0.5 font-mono text-micro"
- >
- {offer.count}
- </span>
- )}
- </button>
- </Dialog.Trigger>
-
- <Dialog.Portal>
- <Dialog.Overlay className="fixed inset-0 z-50 bg-background backdrop-blur-sm" />
- <Dialog.Content
- data-testid="continue-interrupted"
- className="fixed left-1/2 top-1/2 z-50 flex max-h-[min(40rem,calc(100vh-4rem))] w-[min(40rem,calc(100vw-3rem))] -translate-x-1/2 -translate-y-1/2 flex-col rounded-lg bg-popover shadow-float"
- onEscapeKeyDown={(event) => {
- if (working) event.preventDefault();
- }}
- onPointerDownOutside={(event) => {
- if (working) event.preventDefault();
- }}
- >
- <div className="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
- <div className="min-w-0">
- <Dialog.Title className="font-display text-base font-semibold">
- {t("agentic_grid.continue.title")}
- </Dialog.Title>
- <Dialog.Description className="mt-1 text-xs text-muted-foreground">
- {t("agentic_grid.continue.description")}
- </Dialog.Description>
- </div>
- <Dialog.Close asChild>
- <button
- type="button"
- aria-label={t("agentic_grid.continue.close")}
- disabled={working}
- className="shrink-0 rounded-lg p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"
- >
- <X className="h-4 w-4" />
- </button>
- </Dialog.Close>
- </div>
-
- <div className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-5 py-4">
- {offer.count === 0 ? (
- <p data-testid="continue-interrupted-empty" className="text-sm text-muted-foreground">
- {t("agentic_grid.continue.none")}
- </p>
- ) : (
- <ul className="space-y-2">
- {offer.panes.map((pane) => (
- <PaneRow
- key={`${pane.workspace_id}:${pane.key}`}
- pane={pane}
- busy={busy}
- sending={sending.has(pane.name)}
- onContinue={() => void run([pane.name])}
- />
- ))}
- </ul>
- )}
- </div>
-
- <div className="flex flex-wrap items-center justify-between gap-2 border-t border-border px-5 py-3">
- <p className="min-w-0 text-xs text-muted-foreground">{continueSummary(offer, t)}</p>
- <div className="flex shrink-0 items-center gap-2">
- <Dialog.Close asChild>
- <button type="button" className="btn-ghost" disabled={working}>
- {t("agentic_grid.continue.close")}
- </button>
- </Dialog.Close>
- <button
- type="button"
- data-testid="continue-interrupted-all"
- className="btn-primary disabled:cursor-not-allowed disabled:opacity-40"
- disabled={busy || working || offer.continuable_count === 0}
- onClick={() => void run()}
- >
- {working ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <PlayCircle className="h-4 w-4" />
- )}
- {working
- ? t("agentic_grid.continue.sending")
- : t("agentic_grid.continue.all").replace(
- "{0}",
- String(offer.continuable_count),
- )}
- </button>
- </div>
- </div>
- </Dialog.Content>
- </Dialog.Portal>
- </Dialog.Root>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.tsx
index 99077b2dcd..1e1b307c6c 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.tsx
@@ -59,11 +59,10 @@ import { useEventStore } from "@/store/events";
/**
* How often the bell asks.
*
- * Faster than the interrupted-panes poll (15 s) because this one is about
- * REACTION: an agent finishing is the moment the user is waiting for, and a
- * quarter-minute of silence after it is a quarter-minute of them still
- * watching the wall. The backend's own sweep runs every 2 s, so this is the
- * slower half of the pair either way.
+ * Five seconds because this one is about REACTION: an agent finishing is the
+ * moment the user is waiting for, and a quarter-minute of silence after it is
+ * a quarter-minute of them still watching the wall. The backend's own sweep
+ * runs every 2 s, so this is the slower half of the pair either way.
*/
export const POLL_MS = 5_000;
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 242e467a87..6d2180ca21 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -4397,27 +4397,6 @@
"more_controls": "Weitere Arbeitsbereich-Steuerelemente",
"close_controls": "Arbeitsbereich-Steuerelemente schließen"
},
- "continue": {
- "button": "Fortsetzen",
- "hint": "Prüfen, welche Coding-Sitzungen unterbrochen wurden, und sie weiterarbeiten lassen.",
- "title": "Unterbrochene Coding-Sitzungen",
- "description": "Diese Panes sind mit ihrem Gespräch zurückgekommen, haben aber nie erfahren, was als Nächstes zu tun ist — ein Neustart stoppt einen Agenten mitten in der Arbeit, und eine fortgesetzte CLI wartet an ihrer Eingabezeile.",
- "none": "Nichts wurde unterbrochen — jedes Pane hat seit dem Start eine Anweisung bekommen.",
- "one": "Fortsetzen",
- "all": "Alle fortsetzen ({0})",
- "close": "Schließen",
- "last_task": "Zuletzt beauftragt mit: {0}",
- "no_task": "Die letzte Anweisung wurde direkt ins Pane getippt, deshalb gibt es hier keine Kopie davon.",
- "summary_one": "1 Pane wird zum Weitermachen aufgefordert.",
- "summary_many": "{0} Panes werden zum Weitermachen aufgefordert.",
- "summary_blocked": "{0} können erst fortgesetzt werden, wenn ihre Agenten wieder laufen.",
- "result_continued": "{0} Pane(s) machen weiter: {1}.",
- "result_unconfirmed": "Diese Panes bitte selbst prüfen — die Anweisung wurde eingetippt, aber nicht sichtbar abgeschickt: {0}.",
- "result_failed": "Konnten nicht fortgesetzt werden: {0}.",
- "sending": "Wird gesendet …",
- "starting": "Der Agent startet noch — er wird fortgesetzt, sobald er läuft.",
- "result_queued": "{0} starten noch; sie machen weiter, sobald sie laufen: {1}."
- },
"even": {
"label": "Terminal-Größen angleichen",
"hint": "Jedes Terminal bekommt dieselbe Größe. Nichts wird verschoben — die Grenzen gleichen sich dort an, wo sie schon sind.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index fdf13005c3..617bef4149 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -4430,27 +4430,6 @@
"more_controls": "More workspace controls",
"close_controls": "Close workspace controls"
},
- "continue": {
- "button": "Continue",
- "hint": "Check which coding sessions were interrupted and tell them to carry on.",
- "title": "Interrupted coding sessions",
- "description": "These panes came back holding their conversation and were never told what to do next — restarting the app stops an agent mid-task, and a resumed CLI waits at its prompt instead of carrying on.",
- "none": "Nothing was interrupted — every pane has been given something to do since it started.",
- "one": "Continue",
- "all": "Continue all ({0})",
- "close": "Close",
- "last_task": "Last asked to: {0}",
- "no_task": "Its last instruction was typed into the pane directly, so there is no copy of it here.",
- "summary_one": "1 pane will be told to continue.",
- "summary_many": "{0} panes will be told to continue.",
- "summary_blocked": "{0} cannot be continued until their agents are running again.",
- "result_continued": "{0} pane(s) carrying on: {1}.",
- "result_unconfirmed": "Check these panes yourself — the instruction was typed in but never seen to submit: {0}.",
- "result_failed": "Could not be continued: {0}.",
- "sending": "Sending …",
- "starting": "Its agent is still starting — it will be continued as soon as it is up.",
- "result_queued": "{0} still starting; they carry on the moment they are up: {1}."
- },
"even": {
"label": "Even out the terminal sizes",
"hint": "Give every terminal the same size. Nothing is moved — the boundaries even out where they already are.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 2e24496460..121020b895 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -4397,27 +4397,6 @@
"more_controls": "Más controles del espacio de trabajo",
"close_controls": "Cerrar controles del espacio de trabajo"
},
- "continue": {
- "button": "Continuar",
- "hint": "Comprueba qué sesiones de programación se interrumpieron y pídeles que sigan.",
- "title": "Sesiones de programación interrumpidas",
- "description": "Estos paneles volvieron con su conversación pero nunca supieron qué hacer a continuación: reiniciar la aplicación detiene a un agente a mitad de tarea, y una CLI reanudada espera en su línea de entrada.",
- "none": "No se interrumpió nada: todos los paneles han recibido una instrucción desde que arrancaron.",
- "one": "Continuar",
- "all": "Continuar todos ({0})",
- "close": "Cerrar",
- "last_task": "Última petición: {0}",
- "no_task": "Su última instrucción se escribió directamente en el panel, así que aquí no hay copia.",
- "summary_one": "Se pedirá a 1 panel que continúe.",
- "summary_many": "Se pedirá a {0} paneles que continúen.",
- "summary_blocked": "{0} no se pueden continuar hasta que sus agentes vuelvan a ejecutarse.",
- "result_continued": "{0} panel(es) continúan: {1}.",
- "result_unconfirmed": "Revisa estos paneles tú mismo: la instrucción se escribió pero no se vio enviarse: {0}.",
- "result_failed": "No se pudieron continuar: {0}.",
- "sending": "Enviando …",
- "starting": "Su agente todavía está arrancando: continuará en cuanto esté listo.",
- "result_queued": "{0} aún arrancan; seguirán en cuanto estén listos: {1}."
- },
"even": {
"label": "Igualar el tamaño de los terminales",
"hint": "Da a cada terminal el mismo tamaño. No se mueve nada: los bordes se igualan donde ya están.",
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index afd590ba88..28fe0bab54 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -578,76 +578,6 @@ export interface ResumeResult {
skipped: { folder: string; detail: string }[];
}
-/**
- * One pane that came back holding its conversation and was never restarted.
- *
- * The state a restart leaves behind: resuming reconnects a pane to the
- * conversation it was having, but a coding CLI launched on an old transcript
- * reads it and then waits at its prompt. So the agent knows everything about the
- * job it was halfway through and does nothing with it — which on screen is
- * indistinguishable from a pane that finished.
- */
-export interface InterruptedPane {
- workspace_id: string;
- /** The workspace tab it belongs to — a list can span several. */
- workspace: string;
- folder: string;
- key: string;
- name: string;
- agent: string;
- display_name: string;
- status: string;
- /**
- * Will a "continue" reach it? False only when its agent is DEAD — a pane that
- * is merely still starting IS continuable, the instruction just waits for it.
- */
- continuable: boolean;
- /**
- * Its agent is still coming up.
- *
- * Cold starts are staggered on purpose, so most of a big workspace is in this
- * state for the first seconds after it appears — which is exactly when this
- * button gets pressed. Those panes are queued, never skipped.
- */
- starting?: boolean;
- /** A "continue" is already on its way to this pane. */
- queued?: boolean;
- /** Why not, in one sentence. Empty when it can be continued. */
- blocked_reason: string;
- /** What it was last asked to do. Empty when that instruction was typed in by hand. */
- last_task: string;
- prompts_sent: number;
- started_at: number | null;
-}
-
-export interface InterruptedOffer {
- count: number;
- continuable_count: number;
- /** The instruction the continue action sends — "continue" unless configured. */
- prompt: string;
- panes: InterruptedPane[];
-}
-
-export interface ContinueResult {
- ok: boolean;
- /** Panes that accepted the instruction and started. */
- continued: string[];
- /**
- * Panes whose agent had not started yet. The instruction is held and delivered
- * when each comes up — "shortly", never "done".
- */
- queued: string[];
- /**
- * Panes the text was typed into without a confirmed submit — the prompt may be
- * sitting in the input box. Reporting these as running is the one wrong thing
- * to do with this answer.
- */
- unconfirmed: string[];
- failed: { name: string; detail: string }[];
- /** Interrupted panes still waiting afterwards. */
- remaining: number;
-}
-
export interface TerminalPlan {
agent: string;
name?: string;
@@ -1704,44 +1634,6 @@ export async function closeTerminals(names: string[]): Promise<CloseTerminalsRes
};
}
-/**
- * Which panes are waiting to be told to carry on, across every open workspace.
- *
- * Its own read rather than part of `fetchIdeState`: the answer changes only when
- * a pane is resumed or driven again, and folding it into the state poll would
- * re-send every workspace to update a number.
- */
-export function fetchInterrupted(): Promise<InterruptedOffer> {
- return getJson<InterruptedOffer>("/api/agentic-ide/interrupted");
-}
-
-/**
- * Tell interrupted panes to carry on. No names means every one of them.
- *
- * `prompt` overrides the default "continue" — the agent still holds its whole
- * conversation, so short beats elaborate.
- */
-export async function continueInterrupted(
- names?: string[],
- prompt?: string,
-): Promise<ContinueResult> {
- const res = await fetch("/api/agentic-ide/interrupted/continue", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ names: names ?? [], prompt: prompt ?? "" }),
- });
- if (!res.ok) throw new Error(await detail(res));
- const body = (await res.json()) as Partial<ContinueResult>;
- return {
- ok: body.ok ?? false,
- continued: body.continued ?? [],
- queued: body.queued ?? [],
- unconfirmed: body.unconfirmed ?? [],
- failed: body.failed ?? [],
- remaining: body.remaining ?? 0,
- };
-}
-
/**
* What happened in one pane, as the header bell lists it.
*
diff --git a/tests/unit/agentic_ide/test_ide_runtime_lifecycle.py b/tests/unit/agentic_ide/test_ide_runtime_lifecycle.py
index cf6d868fb2..91b5b12cd2 100644
--- a/tests/unit/agentic_ide/test_ide_runtime_lifecycle.py
+++ b/tests/unit/agentic_ide/test_ide_runtime_lifecycle.py
@@ -8,7 +8,6 @@
from __future__ import annotations
-import asyncio
import time
from pathlib import Path
@@ -16,7 +15,7 @@ import pytest
from jarvis.agentic_ide import resume_store
from jarvis.agentic_ide import session as ide
-from tests.unit.agentic_ide.test_pty_host_adoption import ConnectRecorder, FakeHostedPool
+from tests.unit.agentic_ide.test_pty_host_adoption import FakeHostedPool
@pytest.fixture(autouse=True)
@@ -50,10 +49,6 @@ def _snapshot(folder: Path, *, working: bool, focused: str = "") -> None:
)
-def _checkpoint_says_working(terminals: list[ide.Terminal]) -> None:
- # The real check asks the CLI's own history; here the checkpoint is enough.
- for term in terminals:
- term.continuation_pending = term.resume_continuation_needed
# ------------------------------------------------------------------ focus
@@ -92,72 +87,6 @@ async def test_a_focus_on_a_pane_that_is_gone_is_dropped(tmp_path: Path) -> None
assert registry.sessions[0].focused == ""
-# ----------------------------------------------------------- after reboot
-async def test_reboot_starts_and_continues_panes_that_were_working(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _snapshot(tmp_path, working=True)
- monkeypatch.setattr(ide, "_mark_restored_continuations", _checkpoint_says_working)
- pool = FakeHostedPool() # a fresh host: nothing survived the reboot
- monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))
-
- registry = ide.Registry()
- nudged: list[tuple[str, str]] = []
-
- async def record_prompt(name: str, text: str, **_kwargs: object) -> None:
- nudged.append((name, text))
-
- monkeypatch.setattr(registry, "send_prompt", record_prompt)
- await registry.boot_restore()
- for _ in range(100):
- if len(nudged) == 2:
- break
- await asyncio.sleep(0.02)
-
- # Both agents were started although no viewer ever connected ...
- assert sorted(meta["history_id"] for meta in pool.metas) == ["hist-1", "hist-2"]
- # ... and each was told to carry on exactly once, once it was live.
- assert sorted(nudged) == [("T1", "continue"), ("T2", "continue")]
- assert all(term.status == "live" for term in registry.sessions[0].terminals)
-
-
-async def test_agents_that_survived_are_rejoined_not_continued(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _snapshot(tmp_path, working=True)
- monkeypatch.setattr(ide, "_mark_restored_continuations", _checkpoint_says_working)
- pool = FakeHostedPool()
- pool.add_hosted("h-1", history_id="hist-1")
- pool.add_hosted("h-2", history_id="hist-2")
- monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))
-
- registry = ide.Registry()
- await registry.boot_restore()
- await asyncio.sleep(0.05)
-
- session = registry.sessions[0]
- assert pool.adopted == ["h-1", "h-2"]
- assert pool.metas == [] # nothing new was spawned
- assert not any(term.continuation_pending for term in session.terminals)
- assert not any(term.continue_when_ready for term in session.terminals)
-
-
-async def test_panes_that_were_idle_are_not_continued_after_reboot(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _snapshot(tmp_path, working=False)
- monkeypatch.setattr(ide, "_mark_restored_continuations", _checkpoint_says_working)
- pool = FakeHostedPool()
- monkeypatch.setattr(ide, "_connect_pty_host", ConnectRecorder(pool))
-
- registry = ide.Registry()
- await registry.boot_restore()
- await asyncio.sleep(0.05)
-
- assert pool.metas == []
- assert all(term.status == "pending" for term in registry.sessions[0].terminals)
-
-
# ------------------------------------------------------------------- stop
async def test_stop_runtime_ends_everything_and_blocks_the_auto_reopen(tmp_path: Path) -> None:
pool = FakeHostedPool()
diff --git a/tests/unit/agentic_ide/test_interrupted.py b/tests/unit/agentic_ide/test_interrupted.py
deleted file mode 100644
index 2823ba24e9..0000000000
--- a/tests/unit/agentic_ide/test_interrupted.py
+++ /dev/null
@@ -1,659 +0,0 @@
-"""Panes a restart left standing still, and the nudge that starts them again.
-
-Resuming a workspace reconnects each pane to its conversation and stops there: a
-coding CLI launched on an old transcript reads it and waits at its prompt. So
-twelve panes come back holding twelve half-finished jobs and none of them move,
-which on screen is indistinguishable from twelve panes that finished.
-
-The tests below drive the REAL attach path rather than setting the flag by hand,
-because the flag is not the feature — where it is raised and what clears it is.
-Getting either edge wrong is a live failure: a missed pane sits dead forever, and
-a false one offers to type "continue" behind a prompt the user is still writing.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import time
-from pathlib import Path
-from typing import Any
-
-import pytest
-
-from jarvis.agentic_ide import (
- activity,
- fleet_actions,
- interrupted,
- notifications,
- resume_store,
-)
-from jarvis.agentic_ide import session as session_mod
-from jarvis.agentic_ide.agent_sessions import ResumeHandle
-from jarvis.agentic_ide.session import Registry
-from jarvis.ui.web import agentic_ide_routes
-from tests.fakes.fake_pty_manager import FakePtyManager
-
-
[email protected](autouse=True)
-def _clean_watcher() -> Any:
- """No pane memory carried in from another test, and none left behind."""
- notifications.reset()
- yield
- notifications.reset()
-
-
-def fake_pty() -> FakePtyManager:
- return FakePtyManager()
-
-
-def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
- monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
- # The submit verification watches the screen; keep its windows short but
- # non-zero, so the fake's repaint still gets a turn on the event loop.
- monkeypatch.setattr(session_mod, "_SUBMIT_POLL_S", 0.01)
- monkeypatch.setattr(session_mod, "_SUBMIT_WINDOW_S", 0.04)
- monkeypatch.setattr(session_mod, "_SUBMIT_RETRY_AFTER_S", 0.02)
- monkeypatch.setattr(session_mod, "_ARRIVAL_POLL_S", 0.01)
- monkeypatch.setattr(session_mod, "_ARRIVAL_WINDOW_S", 0.04)
- monkeypatch.setattr(fleet_actions, "READY_POLL_S", 0.01)
- monkeypatch.setattr(fleet_actions, "READY_TIMEOUT_S", 0.12)
- return Registry(pty_manager=fake_pty)
-
-
-async def _noop(_text: str) -> None:
- return None
-
-
-async def _noop_exit(_code: int) -> None:
- return None
-
-
-async def _restarted_pane(
- registry: Registry,
- folder: Path,
- existing_conversation: Any,
- *,
- name: str = "Alex",
- conversation: str = "conv-1",
- continuation_needed: bool = True,
- agent: str = "claude",
-):
- """A pane whose agent was spawned onto a conversation that already exists.
-
- Exactly what a resumed workspace produces: the handle survives in the restore
- point, the CLI's own history really holds the conversation, and attaching
- launches the agent with ``--resume``.
- """
- session = await registry.start(str(folder), [{"agent": agent, "name": name}])
- existing_conversation(conversation, agent=agent)
- kind = "codex_rollout" if agent == "codex" else "claude_session"
- session.terminals[0].resume = ResumeHandle(
- kind=kind, id=conversation, captured_at=0.0 if agent == "codex" else 1.0
- )
- session.terminals[0].resume_continuation_needed = continuation_needed
- term = await registry.attach(name, 100, 30, _noop, _noop_exit)
- assert term.resumed is True, "the fixture must reproduce a real resume"
- return session, term
-
-
-# ------------------------------------------------------------------ the scan
-async def test_a_resumed_pane_is_waiting_to_be_continued(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """It holds the whole conversation and nobody has told it anything since."""
- session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
-
- waiting = interrupted.scan(registry)
-
- assert [pane.name for pane in waiting] == [term.name]
- assert waiting[0].continuable is True
- assert waiting[0].blocked_reason == ""
- assert waiting[0].workspace_id == session.id
- assert waiting[0].folder == session.folder
-
-
-async def test_a_pane_that_started_fresh_is_not_waiting(
- registry: Registry, tmp_path: Path
-) -> None:
- """No conversation was continued, so there is nothing to carry on with."""
- await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])
- await registry.attach("Alex", 100, 30, _noop, _noop_exit)
-
- assert interrupted.scan(registry) == []
-
-
-async def test_a_finished_conversation_is_not_called_interrupted(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """Conversation history is not evidence that its last turn was cut off."""
- await _restarted_pane(
- registry,
- tmp_path,
- existing_conversation,
- continuation_needed=False,
- )
-
- assert interrupted.scan(registry) == []
-
-
-async def test_delayed_output_does_not_hide_a_resumed_pane_from_continue(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """A settled restore still needs Continue until this process gets a task."""
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
- term.idle_seen = True
- term.last_output_at = time.time()
-
- found = interrupted.scan(registry)
-
- assert [pane.name for pane in found] == [term.name]
- assert term.reading().activity == "waiting"
- assert term.continuation_pending is True
-
-
-async def test_resumed_startup_output_without_a_submission_is_still_offered(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """Startup repainting has no current-process submission, so it is not work.
-
- A restored CLI redraws its banner and its old transcript for several seconds
- before it settles at a prompt. Treating that movement as work filtered every
- restored pane out of this list in exactly the seconds somebody pressed the
- button. The absent generation-stamped submission keeps the offer intact.
- """
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
- assert term.idle_seen is False, "a freshly spawned process has settled nothing"
- term.last_output_at = time.time()
-
- assert [pane.name for pane in interrupted.scan(registry)] == [term.name]
-
-
-async def test_a_resumed_pane_asking_a_question_is_not_offered_continue(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """A question needs an answer, not a blind "continue".
-
- The one place content is still consulted, and only ever to make a settled
- pane MORE specific — so this one does belong on the screen.
- """
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
- term.transcript.clear()
- term.transcript.feed("\r\nDo you want to continue?\r\n❯ 1. Yes\r\n")
-
- assert interrupted.scan(registry) == []
-
-
-async def test_a_pane_re_joining_a_running_agent_is_not_waiting(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """Switching workspaces is not an interruption — that agent never stopped.
-
- The common case once several workspaces are open, and the one a naive
- "was it resumed?" test would report wrongly on every tab switch.
- """
- await _restarted_pane(registry, tmp_path, existing_conversation)
- await interrupted.continue_panes(registry)
- assert interrupted.scan(registry) == []
-
- registry.detach("alex")
- await registry.attach("Alex", 100, 30, _noop, _noop_exit)
-
- assert interrupted.scan(registry) == [], "re-joining a live agent restarts nothing"
-
-
-async def test_a_prompt_takes_a_pane_off_the_list(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """Somebody is driving it again — whatever the prompt happened to say."""
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
-
- await registry.send_prompt(term.name, "actually, do the other thing")
-
- assert interrupted.scan(registry) == []
-
-
-async def test_typing_into_the_pane_yourself_takes_it_off_the_list(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """A line the user submitted by hand is an instruction too."""
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
-
- registry.write(term.key, "keep going")
- assert len(interrupted.scan(registry)) == 1, "half a typed line is not an instruction"
-
- registry.write(term.key, "\r")
- assert interrupted.scan(registry) == []
-
-
-async def test_a_dead_pane_is_listed_but_cannot_be_continued(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """Still interrupted work — it just cannot be typed into until it runs again."""
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
- term.status = "exited"
- term.exit_code = 1
- term.pty_id = None
-
- waiting = interrupted.scan(registry)
-
- assert len(waiting) == 1
- assert waiting[0].continuable is False
- assert "restart" in waiting[0].blocked_reason.lower()
-
-
-async def test_panes_from_every_open_workspace_are_reported(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """A restart interrupts every workspace at once, not just the front one."""
- first = tmp_path / "one"
- second = tmp_path / "two"
- first.mkdir()
- second.mkdir()
- session_a, _ = await _restarted_pane(
- registry, first, existing_conversation, name="Alex", conversation="conv-a"
- )
- session_b, _ = await _restarted_pane(
- registry, second, existing_conversation, name="Blake", conversation="conv-b"
- )
-
- waiting = interrupted.scan(registry)
-
- assert {pane.workspace_id for pane in waiting} == {session_a.id, session_b.id}
- assert {pane.name for pane in waiting} == {"Alex", "Blake"}
-
-
-# -------------------------------------------------------------- the continue
-async def test_continue_sends_the_word_and_clears_the_list(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path, existing_conversation: Any
-) -> None:
- fake_pty.tui_echo = True # a pane that draws what it is given
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
-
- report = await interrupted.continue_panes(registry)
-
- assert fake_pty.typed[0] == interrupted.CONTINUE_PROMPT
- assert report.continued == [term.name]
- assert report.ok is True
- assert interrupted.scan(registry) == []
-
-
-async def test_a_caller_may_send_its_own_wording(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path, existing_conversation: Any
-) -> None:
- fake_pty.tui_echo = True
- await _restarted_pane(registry, tmp_path, existing_conversation)
-
- await interrupted.continue_panes(registry, prompt="carry on where you left off")
-
- assert fake_pty.typed[0] == "carry on where you left off"
-
-
-async def test_a_pane_that_never_submitted_is_reported_separately(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path, existing_conversation: Any
-) -> None:
- """Typed in but not provably sent is its own answer, never "it is running"."""
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
- # Make the screen look like the input line kept the text.
- on_output = fake_pty.spawns[-1]["on_output"]
- await on_output("pty", f"\x1b[2J\x1b[H❯ {interrupted.CONTINUE_PROMPT}\r\n")
- # That write is what a pane RECEIVING this screen does, and it stamps the
- # pane as having just moved. The state under test is the one after it came
- # to rest: the text is sitting on the input line and nothing else happens.
- term.last_output_at = time.time() - activity.STILL_S - 1
-
- report = await interrupted.continue_panes(registry)
-
- assert report.continued == []
- assert report.unconfirmed == [term.name]
-
-
-async def test_only_the_named_panes_are_continued(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path, existing_conversation: Any
-) -> None:
- fake_pty.tui_echo = True
- first = tmp_path / "one"
- second = tmp_path / "two"
- first.mkdir()
- second.mkdir()
- await _restarted_pane(registry, first, existing_conversation, name="Alex", conversation="c-a")
- await _restarted_pane(registry, second, existing_conversation, name="Blake", conversation="c-b")
-
- report = await interrupted.continue_panes(registry, names=["Blake"])
-
- assert report.continued == ["Blake"]
- assert [pane.name for pane in interrupted.scan(registry)] == ["Alex"]
-
-
-async def test_an_unknown_name_is_refused_rather_than_ignored(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """A caller told "four panes are running" when three are has been misled."""
- await _restarted_pane(registry, tmp_path, existing_conversation)
-
- report = await interrupted.continue_panes(registry, names=["Nobody"])
-
- assert report.continued == []
- assert [name for name, _ in report.failed] == ["Nobody"]
-
-
-async def test_a_dead_pane_fails_with_its_reason(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
- term.status = "error"
- term.error = "claude is not on PATH."
- term.pty_id = None
-
- report = await interrupted.continue_panes(registry)
-
- assert report.continued == []
- assert report.failed == [(term.name, "claude is not on PATH.")]
-
-
-# ------------------------------------------------------ pressing twice, big grids
-# Three live complaints, one test group. All of them are about a workspace with
-# more than a couple of panes, which is the only size where any of them shows up.
-
-
-async def test_pressing_continue_twice_sends_it_once(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path, existing_conversation: Any
-) -> None:
- """A second press while the first is in flight must not repeat the word.
-
- Delivering a prompt takes seconds — the submit is verified against the pane's
- own screen — and the pane used to stay on the waiting list for all of it. So
- two presses put "continue" into the agent twice and three put it in three
- times, which is what the user saw.
- """
- fake_pty.tui_echo = True
- _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
-
- first, second = await asyncio.gather(
- interrupted.continue_panes(registry),
- interrupted.continue_panes(registry),
- )
-
- assert fake_pty.typed.count(interrupted.CONTINUE_PROMPT) == 1, fake_pty.typed
- assert sorted([*first.continued, *second.continued]) == [term.name]
- # The press that lost the race says nothing happened rather than claiming it
- # continued a pane it never touched.
- assert not (first.failed or second.failed)
-
-
-async def test_a_pane_still_starting_is_continued_when_it_comes_up(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path, existing_conversation: Any
-) -> None:
- """The big-workspace bug: cold starts are staggered, so most panes are `pending`.
-
- Pressing Continue in that window used to reach only the handful that had
- already started — reported as "some terminals are skipped". The instruction
- is now held and delivered when the pane's agent appears.
- """
- fake_pty.tui_echo = True
- session = await registry.start(
- str(tmp_path), [{"agent": "claude", "name": "Alex"}, {"agent": "claude", "name": "Blake"}]
- )
- existing_conversation("conv-late")
- late = session.terminals[1]
- late.resume = ResumeHandle(kind="claude_session", id="conv-late", captured_at=1.0)
- late.resume_continuation_needed = True
- late.continuation_pending = True # what a restore establishes before any spawn
-
- report = await interrupted.continue_panes(registry)
-
- assert report.queued == ["Blake"], "a pane that has not started yet is queued, not skipped"
- assert report.continued == []
- assert late.continue_when_ready is True
-
- # Now the grid gets round to it — the pane connects and its agent starts.
- await registry.attach("Blake", 100, 30, _noop, _noop_exit)
- await _settle(session)
-
- assert fake_pty.typed.count(interrupted.CONTINUE_PROMPT) == 1, fake_pty.typed
- assert late.continue_when_ready is False
- assert interrupted.scan(registry) == []
-
-
-async def test_continue_queues_a_live_codex_until_its_input_line_appears(
- registry: Registry,
- fake_pty: FakePtyManager,
- tmp_path: Path,
- existing_conversation: Any,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The pending claim survives spawn and the whole live-but-booting phase."""
- monkeypatch.setattr(fleet_actions, "READY_TIMEOUT_S", 1.0)
- fake_pty.tui_echo = True
- session = await registry.start(
- str(tmp_path), [{"agent": "codex", "name": "Cody"}]
- )
- existing_conversation("conv-codex", agent="codex")
- term = session.terminals[0]
- term.resume = ResumeHandle(kind="codex_rollout", id="conv-codex", captured_at=0.0)
- term.resume_continuation_needed = True
- term.continuation_pending = True
-
- report = await interrupted.continue_panes(registry)
-
- assert report.queued == ["Cody"]
- assert report.continued == []
- assert fake_pty.typed == []
-
- mounting = asyncio.create_task(
- registry.attach("Cody", 100, 30, _noop, _noop_exit)
- )
- for _ in range(50):
- if term.status == "live":
- break
- await asyncio.sleep(0.01)
- assert term.status == "live"
- second_press = await interrupted.continue_panes(registry)
- assert second_press.to_dict() == {
- "ok": True,
- "continued": [],
- "queued": [],
- "unconfirmed": [],
- "failed": [],
- }
-
- await fake_pty.emit(
- term.pty_id,
- "\x1b[2J\x1b[H\u203a Ask Codex anything\x1b[1;3H\x1b[?25h",
- )
- await asyncio.wait_for(mounting, timeout=1.0)
- await _settle(session)
-
- assert fake_pty.typed.count(interrupted.CONTINUE_PROMPT) == 1
- assert term.submitted is True
- assert interrupted.scan(registry) == []
-
-
-async def test_a_restored_pane_is_listed_before_its_agent_starts(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """A restore knows what has work to continue — it does not need the spawn.
-
- This is the other half of the same bug: the list itself used to fill up only
- as the panes started, so a user who pressed the button early was shown three
- of twelve and told that was all of them.
- """
- existing_conversation("conv-restored")
- existing_conversation("conv-finished")
- resume_store.save(
- resume_store.Snapshot(
- saved_at=100.0,
- workspaces=[
- resume_store.SnapshotWorkspace(
- session_id="ide_old",
- folder=str(tmp_path),
- terminals=[
- resume_store.SnapshotTerminal(
- key="alex",
- name="Alex",
- agent="claude",
- resume=ResumeHandle(
- kind="claude_session", id="conv-restored", captured_at=1.0
- ),
- prompts_sent=2,
- continuation_needed=True,
- ),
- # No handle at all: nothing to continue, so it must NOT
- # be offered — that would be a promise with nothing
- # behind it.
- resume_store.SnapshotTerminal(key="blake", name="Blake", agent="claude"),
- # A valid history whose previous turn was already
- # settled: resumable, but not interrupted.
- resume_store.SnapshotTerminal(
- key="casey",
- name="Casey",
- agent="claude",
- resume=ResumeHandle(
- kind="claude_session", id="conv-finished", captured_at=1.0
- ),
- prompts_sent=1,
- continuation_needed=False,
- ),
- ],
- )
- ],
- )
- )
-
- await registry.restore(resume_store.load())
-
- waiting = interrupted.scan(registry)
- assert [pane.name for pane in waiting] == ["Alex"]
- assert waiting[0].status == "pending", "listed before anything spawned"
- assert waiting[0].continuable is True
- assert waiting[0].starting is True
-
-
-async def test_a_restored_pane_survives_its_own_start_up_burst(
- registry: Registry, tmp_path: Path, existing_conversation: Any
-) -> None:
- """The whole chain, end to end, through the sweep that used to break it.
-
- A restored CLI repaints its banner, its model line and its old transcript
- for several seconds before it settles — and the detector under all of this
- reads MOVEMENT, so that burst is frame-for-frame an agent at work. Both
- readers drew that conclusion: the notification sweep retracted the pane's
- `continuation_pending` and the scan filtered it out, within two sweeps of
- every resumed pane coming back. The dialog then said "nothing was
- interrupted" over a grid of panes sitting at their prompts, for ever.
-
- So the burst is driven here for real, on both clocks the two readers use.
- """
- existing_conversation("conv-restored")
- resume_store.save(
- resume_store.Snapshot(
- saved_at=100.0,
- workspaces=[
- resume_store.SnapshotWorkspace(
- session_id="ide_old",
- folder=str(tmp_path),
- terminals=[
- resume_store.SnapshotTerminal(
- key="alex",
- name="Alex",
- agent="claude",
- resume=ResumeHandle(
- kind="claude_session", id="conv-restored", captured_at=1.0
- ),
- prompts_sent=2,
- continuation_needed=True,
- )
- ],
- )
- ],
- )
- )
- await registry.restore(resume_store.load())
- term = await registry.attach("Alex", 100, 30, _noop, _noop_exit)
- assert term.resumed is True, "the fixture must reproduce a real resume"
-
- watcher = notifications.watcher()
- for frame in range(3):
- term.transcript.clear()
- term.transcript.feed(f"\r\n replaying the old conversation, frame {frame}\r\n")
- # The scan reads the wall clock through the byte fallback, the sweep
- # reads its own timeline through the screen digest. Both have to see a
- # pane that is busy drawing itself.
- term.last_output_at = time.time()
- watcher.poll(registry, now=100.0 + frame * notifications.SWEEP_INTERVAL_S, emit=False)
-
- assert term.continuation_pending is True, "drawing itself is not carrying on"
- assert [pane.name for pane in interrupted.scan(registry)] == ["Alex"]
-
-
-async def _settle(session: Any) -> None:
- """Wait only for this session's deferred work, never the whole test loop."""
- pending = tuple(session.lookups)
- if pending:
- await asyncio.wait_for(asyncio.gather(*pending), timeout=2.0)
-
-
-# ----------------------------------------------------------------- the routes
-# The CLI-first contract: everything the button does is an endpoint, so the same
-# action is reachable from `jarvis api agentic-ide ...` and from a coding agent.
-
-
-def api(registry: Registry, monkeypatch: pytest.MonkeyPatch) -> Any:
- """The router with the fake-PTY registry behind it, instead of the real one."""
- from fastapi import FastAPI
-
- monkeypatch.setattr(session_mod, "_REGISTRY", registry)
- app = FastAPI()
- app.include_router(agentic_ide_routes.router)
- return app
-
-
-def _client(app: Any) -> Any:
- import httpx
-
- return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")
-
-
-async def test_the_route_answers_empty_with_nothing_open(api: Any) -> None:
- """A fresh app has nothing to continue — an empty answer, never an error."""
- async with _client(api) as client:
- body = (await client.get("/api/agentic-ide/interrupted")).json()
-
- assert body["count"] == 0
- assert body["panes"] == []
- assert body["prompt"] == interrupted.CONTINUE_PROMPT
-
-
-async def test_continuing_with_nothing_open_is_a_conflict(api: Any) -> None:
- async with _client(api) as client:
- refused = await client.post("/api/agentic-ide/interrupted/continue", json={})
-
- assert refused.status_code == 409
-
-
-async def test_the_route_lists_a_waiting_pane_and_continues_it(
- api: Any,
- registry: Registry,
- fake_pty: FakePtyManager,
- tmp_path: Path,
- existing_conversation: Any,
-) -> None:
- fake_pty.tui_echo = True
- session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
-
- async with _client(api) as client:
- listed = (await client.get("/api/agentic-ide/interrupted")).json()
- continued = (
- await client.post("/api/agentic-ide/interrupted/continue", json={})
- ).json()
-
- assert listed["count"] == 1
- assert listed["continuable_count"] == 1
- assert listed["panes"][0]["name"] == term.name
- assert listed["panes"][0]["workspace_id"] == session.id
-
- assert continued["ok"] is True
- assert continued["continued"] == [term.name]
- assert continued["remaining"] == 0
diff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.py
index 7d111ebbff..de60a4aad0 100644
--- a/tests/unit/agentic_ide/test_pane_notifications.py
+++ b/tests/unit/agentic_ide/test_pane_notifications.py
@@ -461,29 +461,22 @@ async def test_a_question_clears_the_restart_checkpoint_immediately(
assert watcher.take_resume_dirty() is True
-async def test_a_restored_pane_painting_itself_keeps_its_continue_offer(
+async def test_a_restored_pane_painting_itself_is_not_checkpointed_as_working(
registry: Registry, tmp_path: Path
) -> None:
- """The regression that broke the Continue button outright.
+ """A restored CLI redraws its banner and old transcript before it settles.
- A restored CLI redraws its banner and its old transcript for several seconds
- before it settles, and this detector reads MOVEMENT — so that burst is
- frame-for-frame an agent at work. Retracting `continuation_pending` for it
- took every restored pane off the Continue list within two sweeps of coming
- back, and the dialog reported "nothing was interrupted" for ever.
-
- Movement only counts once the pane has been SEEN standing still.
+ This detector reads MOVEMENT, so that burst is frame-for-frame an agent at
+ work — but nobody gave it a task, so it must not be recorded as a job the
+ next restart would report as interrupted.
"""
watcher = notifications.watcher()
_session, term = await _pane(registry, tmp_path)
- # What a restore leaves behind: the pane picked its conversation back up and
- # nobody has told it anything since.
- term.continuation_pending = True
assert term.idle_seen is False, "a freshly spawned process has settled nothing"
_busy(watcher, registry, term, start=100.0, tasked=False)
- assert term.continuation_pending is True, "a CLI drawing itself is not the agent working"
+ assert term.resume_continuation_needed is False, "a CLI drawing itself is not working"
async def test_a_new_process_for_the_same_pane_discards_the_old_screen_observation(
@@ -496,7 +489,6 @@ async def test_a_new_process_for_the_same_pane_discards_the_old_screen_observati
_rest(watcher, registry, term, IDLE_SCREEN, at=100.0, emit=False)
assert term.idle_seen is True
- term.continuation_pending = True
term.resume_continuation_needed = False
term.process_generation += 1
term.idle_seen = False
@@ -504,32 +496,29 @@ async def test_a_new_process_for_the_same_pane_discards_the_old_screen_observati
# A replacement CLI initially redraws the same prompt as its predecessor.
watcher.poll(registry, now=200.0, emit=False)
assert term.idle_seen is False
- assert term.continuation_pending is True
assert term.resume_continuation_needed is False
term.transcript.clear()
_draw(term, BUSY_SCREEN)
watcher.poll(registry, now=200.0 + notifications.SWEEP_INTERVAL_S, emit=False)
- assert term.continuation_pending is True
assert term.resume_continuation_needed is False
-async def test_a_new_submission_after_settle_retracts_the_offer(
+async def test_a_new_submission_after_settle_is_checkpointed_as_working(
registry: Registry, tmp_path: Path
) -> None:
"""A generation-stamped task, not prior stillness, proves resumed work."""
watcher = notifications.watcher()
_session, term = await _pane(registry, tmp_path)
- term.continuation_pending = True
# It comes up, paints itself, and settles at its prompt.
_rest(watcher, registry, term, IDLE_SCREEN, at=100.0, emit=False)
assert term.idle_seen is True
- assert term.continuation_pending is True, "sitting at a prompt is what waiting looks like"
+ assert term.resume_continuation_needed is False, "sitting at a prompt is not working"
_busy(watcher, registry, term, start=100.0 + STILL_S + 2)
- assert term.continuation_pending is False
+ assert term.resume_continuation_needed is True
async def test_a_pane_that_was_never_busy_is_never_reported(
diff --git a/tests/unit/agentic_ide/test_reboot_resume.py b/tests/unit/agentic_ide/test_reboot_resume.py
index 45cbb1b5d5..e6bf54d55c 100644
--- a/tests/unit/agentic_ide/test_reboot_resume.py
+++ b/tests/unit/agentic_ide/test_reboot_resume.py
@@ -103,29 +103,28 @@ async def test_every_running_agent_is_resumed_in_every_workspace(
assert nudged == []
-async def test_working_agents_are_also_told_to_continue(
+async def test_agents_carry_on_by_themselves_never_by_a_typed_continue(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
+ """Jarvis types nothing; Claude Code finishes an interrupted turn itself.
+
+ Every resumed Claude pane is started with the CLI's own interrupted-turn
+ resume in its environment (measured: a pane killed at step 26 of 30 went on
+ to 30 with nothing typed; without it, it waited at its prompt).
+ """
ws, _ = _save(tmp_path, [_pane(1, working=True), _pane(2)])
_store(ws)
- monkeypatch.setattr(
- ide,
- "_mark_restored_continuations",
- lambda terms: [
- setattr(t, "continuation_pending", t.resume_continuation_needed) for t in terms
- ],
- )
pool = FakeHostedPool()
- registry, nudged = await _boot(monkeypatch, pool)
+ _registry, nudged = await _boot(monkeypatch, pool)
await _settle(pool, 2)
- for _ in range(100):
- if nudged:
- break
- await asyncio.sleep(0.02)
- assert len(pool.metas) == 2
- assert nudged == ["T1"]
+ assert len(pool.spawns) == 2
+ for spawn in pool.spawns:
+ env = spawn["env"] or {}
+ assert env.get("CLAUDE_CODE_RESUME_INTERRUPTED_TURN") == "1"
+ assert env.get("CLAUDE_CODE_RESUME_INTERRUPTED_TURN_MAX_AGE_MS") == "0"
+ assert nudged == []
async def test_agents_that_ended_by_themselves_stay_ended(
@@ -218,3 +217,62 @@ async def test_a_survivor_that_was_working_is_marked_for_the_bell(
assert session.find("T2").worked_while_detached is False
# Re-joined agents are never nudged: they never stopped.
assert nudged == []
+
+
+async def test_a_live_host_that_does_not_answer_is_never_taken_for_a_reboot(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The 2026-09-28 failure: agents started a second time beside living ones.
+
+ A host that is running but silent holds agents. Boot must wait for it, not
+ resume every pane in-process as if the machine had restarted.
+ """
+ ws, _ = _save(tmp_path, [_pane(1), _pane(2)])
+ _store(ws)
+ starts: list[bool] = []
+
+ async def silent_host(*, start: bool) -> object:
+ starts.append(start)
+ raise ide.SessionNotReady("The terminal host is busy.")
+
+ monkeypatch.setattr(ide, "_connect_pty_host", silent_host)
+ registry = ide.Registry()
+ await registry.boot_restore()
+ await asyncio.sleep(0.05)
+
+ assert all(t.status == "pending" for t in registry.sessions[0].terminals)
+ assert starts and not any(starts), "a host is never STARTED beside a living one"
+ assert registry._rejoin_task is not None
+ registry._rejoin_task.cancel()
+
+
+async def test_agents_lost_with_a_crashed_host_come_back_on_their_conversations(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ ws, _ = _save(tmp_path, [_pane(1)])
+ _store(ws)
+ first = FakeHostedPool()
+ first.add_hosted("h-1", history_id="hist-1")
+ second = FakeHostedPool()
+
+ async def connect(*, start: bool) -> object:
+ return second if start else first
+
+ monkeypatch.setattr(ide, "_connect_pty_host", connect)
+ registry = ide.Registry()
+ await registry.boot_restore()
+ term = registry.sessions[0].find("T1")
+ assert term.pty_id == "h-1"
+
+ # The host dies under the running app: every agent reports the unknown code.
+ first.connected = False
+ _on_output, on_closed = first._callbacks["h-1"]
+ await on_closed("h-1", -1)
+ for _ in range(200):
+ if second.spawns:
+ break
+ await asyncio.sleep(0.02)
+
+ argv = " ".join(second.spawns[0]["argv"]) if second.spawns else ""
+ assert "--resume conv-1" in argv, argv
+ assert (second.spawns[0]["env"] or {}).get("CLAUDE_CODE_RESUME_INTERRUPTED_TURN") == "1"
diff --git a/tests/unit/terminal/test_pty_host_client.py b/tests/unit/terminal/test_pty_host_client.py
index 7700375aed..1b6f6a61e5 100644
--- a/tests/unit/terminal/test_pty_host_client.py
+++ b/tests/unit/terminal/test_pty_host_client.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import asyncio
import json
+import os
from collections.abc import AsyncIterator, Callable
from typing import Any
@@ -451,3 +452,56 @@ async def test_a_refused_spawn_raises(host: FakeHost) -> None:
assert manager.connected is True
finally:
await _cleanup(manager)
+
+
+# ------------------------------------------------ alive vs gone, never guessed
+def test_a_state_file_only_counts_for_a_live_pty_host() -> None:
+ from jarvis.terminal import pty_host_client as client
+
+ assert client.host_is_alive(None) is False
+ # This test process is alive but is not a PTY host (a reused pid).
+ assert client.host_is_alive({"pid": os.getpid(), "boot_time": 0}) is False
+ assert client.host_is_alive({"pid": 2**22 + 12345}) is False
+
+
+async def test_a_live_host_that_does_not_answer_raises_and_starts_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.terminal import pty_host_client as client
+
+ started: list[str] = []
+ monkeypatch.setattr(client, "host_available", lambda: True)
+ monkeypatch.setattr(
+ client,
+ "_read_state",
+ lambda path: {"pid": 4242, "port": 1, "token": "t", "proto": client.PROTOCOL_VERSION},
+ )
+ monkeypatch.setattr(client, "host_is_alive", lambda state: True)
+
+ async def no_answer(port: int, token: str, wait_s: float) -> None:
+ return None
+
+ monkeypatch.setattr(client, "_handshake", no_answer)
+ monkeypatch.setattr(client, "LIVE_HOST_PATIENCE_S", 0.3)
+ monkeypatch.setattr(client, "_start_host", lambda path, token: started.append(token) or True)
+
+ with pytest.raises(client.HostUnreachable):
+ await client.connect(start=True)
+ assert started == [], "a second host must never be started beside a live one"
+
+
+async def test_a_dead_host_is_replaced(monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.terminal import pty_host_client as client
+
+ started: list[str] = []
+ monkeypatch.setattr(client, "host_available", lambda: True)
+ monkeypatch.setattr(
+ client,
+ "_read_state",
+ lambda path: {"pid": 4242, "port": 1, "token": "old", "proto": client.PROTOCOL_VERSION},
+ )
+ monkeypatch.setattr(client, "host_is_alive", lambda state: False)
+ monkeypatch.setattr(client, "_start_host", lambda path, token: started.append(token) or False)
+
+ assert await client.connect(start=True) is None
+ assert len(started) == 1