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(agentic-ide): offer to continue the sessions a restart interrupted

Ruben Lütke52adec8d4298
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index 0d3989024d..5b34994ed0 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -301,3 +301,23 @@ 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, '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 pane as running is the one wrong thing to do with this answer.
+
+- **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/jarvis/agentic_ide/interrupted.py b/jarvis/agentic_ide/interrupted.py
new file mode 100644
index 0000000000..8226490a80
--- /dev/null
+++ b/jarvis/agentic_ide/interrupted.py
@@ -0,0 +1,317 @@
+"""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
+
+One flag, set in exactly one place. :attr:`Terminal.continuation_pending` is
+raised when a pane's agent process is SPAWNED onto an existing conversation, and
+cleared the moment anybody drives that pane again — a prompt from Jarvis, or a
+line the user submitted in the pane themselves. Everything here reads that flag
+rather than re-deriving the state from timestamps or transcript contents.
+
+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.
+
+## 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.
+
+Deliberately not automatic. 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. The offer is a button.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from loguru import logger
+
+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
+ #: Can it be nudged right now? False for a pane whose agent is not running —
+ #: an instruction cannot be typed into a dead terminal, and saying so before
+ #: the click is the point.
+ continuable: 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,
+ "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.
+
+ Three lists rather than a count, because the three outcomes need different
+ words from whoever reports this: a pane that took the instruction, one that
+ refused it, and one that took the text but never submitted it (the prompt is
+ sitting in its input box and a human has to press Enter). Collapsing the
+ third into either of the others is the lie :meth:`Registry.send_prompt` goes
+ to some length to avoid.
+ """
+
+ continued: list[str]
+ unconfirmed: list[str]
+ failed: list[tuple[str, str]]
+
+ @property
+ def ok(self) -> bool:
+ return not self.failed
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "ok": self.ok,
+ "continued": list(self.continued),
+ "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."""
+ if term.status == "live" and term.pty_id:
+ return ""
+ if term.status == "pending":
+ return "Its agent has not started yet — open the workspace so the pane connects."
+ 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 _describe(session: Session, term: Terminal) -> InterruptedPane:
+ reason = _blocked_reason(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,
+ continuable=not reason,
+ 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 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
+
+
+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.
+ """
+ text = (prompt or CONTINUE_PROMPT).strip() or CONTINUE_PROMPT
+ chosen, failed = _selected(scan(registry), names)
+
+ blocked = [pane for pane in chosen if not pane.continuable]
+ failed.extend((pane.name, pane.blocked_reason) for pane in blocked)
+ runnable = [pane for pane in chosen if pane.continuable]
+
+ async def _send(pane: InterruptedPane) -> tuple[InterruptedPane, Any]:
+ try:
+ return pane, await registry.send_prompt(pane.name, text)
+ 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):
+ 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.
+ unconfirmed.append(pane.name)
+
+ if continued or unconfirmed or failed:
+ logger.info(
+ "Agentic IDE: continued {} interrupted pane(s) ({} unconfirmed, {} refused)",
+ len(continued),
+ len(unconfirmed),
+ len(failed),
+ )
+ return ContinueReport(continued=continued, unconfirmed=unconfirmed, failed=failed)
+
+
+__all__ = [
+ "CONTINUE_PROMPT",
+ "TASK_CHARS",
+ "ContinueReport",
+ "InterruptedPane",
+ "continue_panes",
+ "scan",
+]
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 1e5ca6fd5c..3f4259aaf8 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -511,6 +511,18 @@ 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
+ # 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.
+ #
+ # Set only where a process is SPAWNED onto an existing conversation (see
+ # `attach`), and 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 is a fact about the process that is
+ # running now, not about the workspace.
+ continuation_pending: bool = False
transcript: Transcript = field(default_factory=Transcript)
# The RAW output stream, kept so the next viewer can be handed the screen
# this pane is actually showing. Cleared on a fresh spawn, so what a viewer
@@ -569,6 +581,12 @@ class Terminal:
"recap": summary.headline,
"recap_detail": summary.detail,
"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,
@@ -1519,6 +1537,11 @@ 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.
+ term.continuation_pending = term.resumed
term.transcript.resize(cols, rows)
# A fresh process draws a fresh screen: anything the previous one left
@@ -1737,6 +1760,14 @@ class Registry:
term = found[1]
if not term.pty_id:
return False
+ if term.continuation_pending and ("\r" in data or "\n" in data):
+ # The user submitted something in the pane themselves, so this one
+ # is being driven again and is no longer waiting to be nudged.
+ # Gated on a SUBMIT rather than on any keystroke: scrolling, arrow
+ # keys and a half-typed line are not an instruction, and dropping
+ # the pane off the list for those would hide a stalled agent behind
+ # an accidental keypress.
+ term.continuation_pending = False
return self._manager().write(term.pty_id, data)
async def _nudge_repaint(self, term: Terminal, cols: int, rows: int) -> None:
@@ -2135,6 +2166,11 @@ class Registry:
term.last_prompt = payload
term.submitted = submitted
term.sent_multiline = multiline and submitted is True
+ # 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
logger.info(
"Agentic IDE prompt -> {} ({}, {}): {}",
term.name,
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index 622dfc28d3..ff9c289904 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -802,6 +802,74 @@ 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, "
+ "'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 pane as running is the one wrong "
+ "thing to do with this answer."
+ ),
+ 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/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index c56ff267c3..c4b872122c 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -20,6 +20,8 @@ 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
* ``POST /terminals`` → open one more pane (split)
* ``POST /terminals/batch`` → open N more panes at once
@@ -53,7 +55,13 @@ from fastapi import (
)
from pydantic import BaseModel, Field
-from jarvis.agentic_ide import native_picker, recap_engine, recents, resume_store
+from jarvis.agentic_ide import (
+ interrupted,
+ native_picker,
+ recap_engine,
+ recents,
+ resume_store,
+)
from jarvis.agentic_ide.agent_sessions import has_conversation
from jarvis.agentic_ide.device import device_name
from jarvis.agentic_ide.folders import list_dir, search_folders, start_points
@@ -495,6 +503,90 @@ 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=(
+ "Can it be told to continue right now? False when its agent is not "
+ "running — an instruction cannot be typed into a dead terminal."
+ )
+ )
+ 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 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."
+ )
+ 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 TerminalRecap(BaseModel):
"""What one pane is doing, in the two lengths its header renders."""
@@ -1057,6 +1149,68 @@ async def resume_workspace() -> dict:
}
+ "/interrupted",
+ response_model=InterruptedResponse,
+ summary="Coding sessions that were interrupted and never restarted",
+)
+async 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.post(
"/terminals/close-batch",
summary="Close several terminals",
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 544bf00335..b82333fe04 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -34,6 +34,16 @@ 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(),
}));
// The grid follows the app theme for its terminal colours; these tests render
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index 65d6b30dec..f8252c2cda 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -50,6 +50,7 @@ import {
MIN_PANE_HEIGHT_PX,
paneGrid,
} from "./layout";
+import { ContinueInterrupted } from "./ContinueInterrupted";
import { PromptPreview } from "./PromptPreview";
import { WorkspaceSettings } from "./WorkspaceSettings";
import { usePaneFileDrag } from "./paneFileDrag";
@@ -753,6 +754,12 @@ export function AgenticGrid({
</button>
</div>
+ {/* 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} />
+
{/* 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
new file mode 100644
index 0000000000..8ced128396
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.test.tsx
@@ -0,0 +1,218 @@
+/**
+ * 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: [],
+ 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("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
new file mode 100644
index 0000000000..4e594c5f1b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx
@@ -0,0 +1,356 @@
+/**
+ * "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, PlayCircle, Terminal, X } from "lucide-react";
+
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+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;
+}
+
+/** 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(", ")),
+ );
+ }
+ // 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,
+ onContinue,
+}: {
+ pane: InterruptedPane;
+ busy: boolean;
+ onContinue: () => void;
+}) {
+ const t = useT();
+ return (
+ <li
+ data-testid={`interrupted-pane-${pane.name}`}
+ className={cn(
+ "rounded-lg border p-3",
+ pane.continuable ? "border-border bg-card/60" : "border-amber-500/40 bg-amber-500/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-amber-200">
+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ {pane.blocked_reason}
+ </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 || !pane.continuable}
+ onClick={onContinue}
+ >
+ <PlayCircle className="h-4 w-4" />
+ {t("agentic_grid.continue.one")}
+ </button>
+ </div>
+ </li>
+ );
+}
+
+export function ContinueInterrupted({ busy = false }: 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);
+
+ 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;
+ }
+ }, []);
+
+ useEffect(() => {
+ const pull = () => {
+ // A hidden window has nobody to show a count to, and this poll runs for
+ // as long as the workspace is open.
+ if (typeof document !== "undefined" && document.hidden) return;
+ void refresh();
+ };
+ pull();
+ const timer = window.setInterval(pull, POLL_MS);
+ // Coming back to the foreground skips every tick spent hidden — and the
+ // restart that interrupts the panes is exactly the event that happens while
+ // nobody is looking.
+ const onVisible = () => {
+ if (!document.hidden) void refresh();
+ };
+ document.addEventListener("visibilitychange", onVisible);
+ return () => {
+ window.clearInterval(timer);
+ document.removeEventListener("visibilitychange", onVisible);
+ };
+ }, [refresh]);
+
+ const run = async (names?: string[]) => {
+ 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 {
+ 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(
+ "flex shrink-0 items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40",
+ waiting
+ ? "border-amber-500/60 bg-amber-500/15 text-amber-200"
+ : "border-border text-muted-foreground hover:border-primary/40 hover:text-foreground",
+ )}
+ >
+ <PlayCircle className="h-4 w-4" />
+ {t("agentic_grid.continue.button")}
+ {waiting && (
+ <span
+ data-testid="continue-interrupted-count"
+ className="rounded bg-amber-500/25 px-1.5 py-0.5 font-mono text-[10px]"
+ >
+ {offer.count}
+ </span>
+ )}
+ </button>
+ </Dialog.Trigger>
+
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-50 bg-background/70 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-2xl border border-border bg-card shadow-2xl"
+ 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 || working}
+ 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()}
+ >
+ <PlayCircle className="h-4 w-4" />
+ {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/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index bfd2f56b72..348a1dad59 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -269,6 +269,58 @@ 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;
+ /** False when its agent is not running: an instruction cannot be typed into it. */
+ continuable: 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 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;
@@ -661,6 +713,73 @@ 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 ?? [],
+ unconfirmed: body.unconfirmed ?? [],
+ failed: body.failed ?? [],
+ remaining: body.remaining ?? 0,
+ };
+}
+
+/** The active subscription per coding CLI, without the whole workspace state. */
+export async function fetchIdeAccounts(): Promise<IdeAccountState[]> {
+ const body = await getJson<{ accounts: IdeAccountState[] }>(
+ "/api/agentic-ide/accounts",
+ );
+ return body.accounts ?? [];
+}
+
+/**
+ * Switch which subscription NEW terminals of one coding CLI open on.
+ *
+ * Panes that are already open keep the account they started with — a running
+ * agent must never be moved onto a plan whose history has never seen its
+ * conversation. Returns the whole workspace state, so the caller never has to
+ * re-read to find out what it just changed.
+ */
+export async function setIdeActiveAccount(
+ agent: string,
+ accountId: string,
+): Promise<IdeState> {
+ const res = await fetch("/api/agentic-ide/accounts/active", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ agent, account_id: accountId }),
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ const body = (await res.json()) as { state: IdeState };
+ return body.state;
+}
+
export async function setFocusMode(enabled: boolean): Promise<boolean> {
const res = await fetch("/api/agentic-ide/mode", {
method: "PUT",
diff --git a/tests/unit/agentic_ide/test_interrupted.py b/tests/unit/agentic_ide/test_interrupted.py
new file mode 100644
index 0000000000..01190f43d4
--- /dev/null
+++ b/tests/unit/agentic_ide/test_interrupted.py
@@ -0,0 +1,330 @@
+"""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
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.agentic_ide import interrupted
+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
+
+
+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)
+ 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",
+):
+ """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": "claude", "name": name}])
+ existing_conversation(conversation)
+ session.terminals[0].resume = ResumeHandle(
+ kind="claude_session", id=conversation, captured_at=1.0
+ )
+ 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_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")
+
+ 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.")]
+
+
+# ----------------------------------------------------------------- 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