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.

fix(agentic-ide): make the pane bell actually fire, and report why a pane ended

Ruben Lütked2fd6494d4de
diff --git a/jarvis/agentic_ide/interrupted.py b/jarvis/agentic_ide/interrupted.py
index 1837b7feda..53d3a3dc70 100644
--- a/jarvis/agentic_ide/interrupted.py
+++ b/jarvis/agentic_ide/interrupted.py
@@ -16,11 +16,12 @@ 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.
+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:
@@ -56,6 +57,7 @@ from typing import TYPE_CHECKING, Any
from loguru import logger
+from .activity import read_activity
from .recap import condense
from .session import SessionError, accepts_prompts
@@ -241,6 +243,10 @@ def scan(registry: Registry) -> list[InterruptedPane]:
for term in session.terminals:
if not term.continuation_pending:
continue
+ if term.status == "live" and read_activity(term) != "waiting":
+ # A pane already working needs no nudge, and a pane asking a
+ # question needs an answer rather than a blind "continue".
+ 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
diff --git a/jarvis/agentic_ide/notifications.py b/jarvis/agentic_ide/notifications.py
index 6a226571a4..96e7bc15e9 100644
--- a/jarvis/agentic_ide/notifications.py
+++ b/jarvis/agentic_ide/notifications.py
@@ -38,13 +38,17 @@ for :data:`SETTLE_S` before anything is filed, and the flag is armed once per
episode: an agent that goes back to work re-arms it, and one that sits at its
prompt for an hour is reported once.
-## Why in memory, and why nothing is persisted
+## What is and is not persisted
An entry's whole value is the "jump to pane" behind it. Panes do not survive a
restart of the app, so a notification that did would point at a terminal that
no longer exists — the one thing worse than no notification. The store is a
bounded deque and is deliberately lost with the process.
+One boolean does survive: whether a pane was observed actively working. The
+resume snapshot uses that evidence to distinguish genuinely interrupted work
+from a conversation that had already finished or was awaiting an answer.
+
## Where it runs
One sweep task per registry, started when the first workspace opens and
@@ -218,6 +222,10 @@ class _PaneWatch:
#: Already reported for the CURRENT episode. Cleared when the pane changes
#: state, so the next stop is reported again.
announced: bool = False
+ #: The interruption evidence last checkpointed for this pane. Kept here as
+ #: well as on the terminal so an explicit prompt submission can change the
+ #: live field without making the sweep forget what is already on disk.
+ resume_needed: bool = False
def _detail(term: Any) -> str:
@@ -259,13 +267,26 @@ class ActivityWatcher:
def __init__(self, center: NotificationCenter) -> None:
self.center = center
self._panes: dict[tuple[str, str], _PaneWatch] = {}
+ self._resume_dirty = False
+
+ def take_resume_dirty(self) -> bool:
+ """Return and clear whether activity changed the resume checkpoint."""
+ changed = self._resume_dirty
+ self._resume_dirty = False
+ return changed
def forget_workspace(self, workspace_id: str) -> None:
"""Drop the per-pane memory of a workspace that is gone."""
for key in [k for k in self._panes if k[0] == workspace_id]:
del self._panes[key]
- def poll(self, registry: Registry, *, now: float | None = None) -> list[Notification]:
+ def poll(
+ self,
+ registry: Registry,
+ *,
+ now: float | None = None,
+ emit: bool = True,
+ ) -> list[Notification]:
"""Look at every pane once and file whatever has just happened."""
moment = time.time() if now is None else now
filed: list[Notification] = []
@@ -280,7 +301,7 @@ class ActivityWatcher:
continue
ident = (session.id, str(getattr(term, "key", "") or ""))
alive.add(ident)
- entry = self._step(session, term, ident, moment)
+ entry = self._step(session, term, ident, moment, emit=emit)
if entry is not None:
filed.append(entry)
@@ -291,16 +312,33 @@ class ActivityWatcher:
return filed
def _step(
- self, session: Any, term: Any, ident: tuple[str, str], now: float
+ self,
+ session: Any,
+ term: Any,
+ ident: tuple[str, str],
+ now: float,
+ *,
+ emit: bool,
) -> Notification | None:
- activity = read_activity(term)
+ # ``now`` travels into the read as well: whether a clock on screen is a
+ # RUNNING one is measured against the pane's last output, and a test
+ # that places a pane on its own timeline must not be judged against the
+ # wall clock (see activity.CLOCK_FRESH_S).
+ activity = read_activity(term, now=now)
watch = self._panes.get(ident)
if watch is None:
# First sight. Nothing is filed: the pane may have been sitting
# finished for an hour before this watcher existed, and announcing
# that on startup would fill the bell with history.
- self._panes[ident] = _PaneWatch(activity=activity, since=now, announced=True)
+ watch = _PaneWatch(
+ activity=activity,
+ since=now,
+ announced=True,
+ resume_needed=bool(getattr(term, "resume_continuation_needed", False)),
+ )
+ self._panes[ident] = watch
+ self._checkpoint_resume_state(term, activity, watch, now)
return None
if activity != watch.activity:
@@ -310,6 +348,8 @@ class ActivityWatcher:
watch.since = now
watch.announced = False
+ self._checkpoint_resume_state(term, activity, watch, now)
+
if watch.announced:
return None
@@ -325,6 +365,8 @@ class ActivityWatcher:
watch.announced = True
watch.worked = False
+ if not emit:
+ return None
return self.center.add(
Notification(
id=f"n{next(_ids)}",
@@ -341,6 +383,46 @@ class ActivityWatcher:
)
)
+ def _checkpoint_resume_state(
+ self, term: Any, activity: Activity, watch: _PaneWatch, now: float
+ ) -> None:
+ """Remember only turns proven to have been interrupted while working.
+
+ 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.
+ """
+ if activity == "working":
+ # A resumed CLI that is already working carried on by itself.
+ 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
+ ):
+ self._set_resume_needed(term, watch, False)
+
+ def _set_resume_needed(self, term: Any, watch: _PaneWatch, needed: bool) -> None:
+ term.resume_continuation_needed = needed
+ if watch.resume_needed == needed:
+ return
+ watch.resume_needed = needed
+ self._resume_dirty = True
+
@staticmethod
def _kind(activity: Activity, watch: _PaneWatch) -> Kind | None:
"""Which entry this state deserves, or none at all."""
@@ -421,6 +503,7 @@ def reset() -> None:
"""Drop everything — for tests, and for a registry that was torn down."""
_CENTER.clear()
_WATCHER._panes.clear() # noqa: SLF001 - same module, one owner
+ _WATCHER._resume_dirty = False # noqa: SLF001 - same module, one owner
reset_switch_cache()
@@ -447,10 +530,13 @@ async def _run(registry: Registry) -> None:
await asyncio.sleep(SWEEP_INTERVAL_S)
if not registry.sessions:
return
- if not enabled():
- continue
try:
- _WATCHER.poll(registry)
+ # Resume evidence is independent of the optional bell. Even
+ # with notifications disabled, restored panes must not be
+ # offered a blind Continue merely because history exists.
+ _WATCHER.poll(registry, emit=enabled())
+ if _WATCHER.take_resume_dirty():
+ await registry.persist_resume_activity()
except Exception as exc: # noqa: BLE001 - one bad pane must not end the sweep
logger.warning("Agentic IDE: pane notification sweep failed: {}", exc)
except asyncio.CancelledError: # pragma: no cover - shutdown
@@ -484,11 +570,28 @@ def stop() -> None:
task.cancel()
+def watching() -> bool:
+ """Is the sweep actually running right now?
+
+ Reported alongside the entries because an empty bell has two very different
+ causes — "nothing has happened" and "nobody is looking" — and they are
+ indistinguishable from the outside. They were indistinguishable from the
+ INSIDE too, the first time this feature reported nothing for an afternoon.
+ """
+ task = _sweep.task
+ return task is not None and not task.done()
+
+
def state() -> dict[str, Any]:
"""Everything the bell needs in one response."""
entries = _CENTER.list()
return {
"enabled": enabled(),
+ "watching": watching(),
+ # How many panes the sweep is holding state for. Zero while watching is
+ # true means it has not completed a pass yet; it should otherwise match
+ # the agent panes across every open workspace.
+ "panes_watched": len(_WATCHER._panes), # noqa: SLF001 - same module, one owner
"unread": sum(1 for entry in entries if not entry.read),
"notifications": [entry.to_dict() for entry in entries],
}
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.py
index b5d9f0c81f..e28d23446f 100644
--- a/jarvis/agentic_ide/resume_store.py
+++ b/jarvis/agentic_ide/resume_store.py
@@ -71,6 +71,11 @@ class SnapshotTerminal:
# and silently start fresh. An absent value (an older snapshot) means "the
# account that is active when it reopens" — the old behaviour exactly.
account: str | None = None
+ # True only when the pane was observed actively working when its last live
+ # state was checkpointed. This is the evidence the Continue control needs:
+ # a conversation existing does not mean its last turn was interrupted.
+ # Missing on older snapshots deliberately means False (fail closed).
+ continuation_needed: bool = False
def to_dict(self) -> dict[str, Any]:
return {
@@ -82,6 +87,7 @@ class SnapshotTerminal:
"resume": self.resume.to_dict() if self.resume else None,
"prompts_sent": self.prompts_sent,
"account": self.account,
+ "continuation_needed": self.continuation_needed,
}
@staticmethod
@@ -105,6 +111,7 @@ class SnapshotTerminal:
if isinstance(data.get("account"), str)
else None
),
+ continuation_needed=data.get("continuation_needed") is True,
)
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index c0b17a4b9c..b2b24c44a9 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -850,6 +850,11 @@ 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".
+ 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
@@ -1030,6 +1035,7 @@ class Terminal:
resume=self.resume,
prompts_sent=self.prompts_sent,
account=self.account,
+ continuation_needed=self.resume_continuation_needed,
)
@@ -1776,6 +1782,7 @@ class Registry:
slot=entry.slot,
resume=entry.resume,
prompts_sent=entry.prompts_sent,
+ resume_continuation_needed=entry.continuation_needed,
# The remembered account, re-validated: a pane must come back
# on the subscription whose history holds its conversation,
# and an account deleted in the meantime falls back to the
@@ -1975,6 +1982,15 @@ class Registry:
except Exception as exc: # noqa: BLE001 - the workspace comes first
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.
+
+ The activity sweep calls this only when a pane crosses a meaningful
+ boundary, never for each terminal repaint. Keeping it on the registry
+ preserves the snapshot lock and last-writer ordering of `_persist`.
+ """
+ await self._persist()
+
async def _forget(self) -> None:
"""Withdraw the resume offer, best-effort."""
try:
@@ -2313,7 +2329,11 @@ class Registry:
# 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
+ # A valid conversation may already be finished or waiting for input.
+ # Offer a nudge only when the previous live pane was observed working.
+ term.continuation_pending = term.resumed and term.resume_continuation_needed
+ if not term.resumed:
+ term.resume_continuation_needed = False
term.transcript.resize(cols, rows)
# A fresh process draws a fresh screen: anything the previous one left
@@ -2652,6 +2672,7 @@ class Registry:
# Dropping the pane off that list for a mere keypress would hide a
# stalled agent behind an accidental one.
term.continuation_pending = False
+ term.resume_continuation_needed = False
# And the pane's conversation may have just begun, which for most
# coding CLIs is the first moment its id exists on disk at all. A
# pane driven only by hand never goes through `send_prompt`, so
@@ -3227,6 +3248,7 @@ class Registry:
# 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
+ term.resume_continuation_needed = False
if submitted is not False:
# The conversation has (or may have) just begun, so for a CLI that
# cannot be told its id this is the moment that id starts existing —
@@ -3448,7 +3470,7 @@ def _mark_restored_continuations(terminals: list[Terminal]) -> None:
if term.resume is None or not accepts_prompts(term.agent):
continue
try:
- term.continuation_pending = has_conversation(
+ 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
diff --git a/jarvis/terminal/pty_manager.py b/jarvis/terminal/pty_manager.py
index 0f4b860e64..4711619757 100644
--- a/jarvis/terminal/pty_manager.py
+++ b/jarvis/terminal/pty_manager.py
@@ -83,6 +83,21 @@ prompt editor has opened, where the bytes appear as a line of
the PTY, and whatever it returns is written straight back. Same measurement,
same load: 0 ms. Nothing else moves off the pump — this is for replies that are
useless once late, not for output a human reads.
+
+## Why the exit code is normalized instead of forwarded
+
+A Windows exit code is an unsigned 32-bit value, and ``pywinpty`` hands it over
+exactly as the OS stored it. A child that ended with ``-1`` therefore arrives as
+``4294967295``, which is what the pane then showed the user: "[Codex exited —
+code 4294967295]" — a ten-digit number nobody can act on, for what is really a
+plain ``-1``. :func:`normalize_exit_code` re-signs it once, here, so every layer
+above (the pane header, the resume self-healing, the log) sees one convention.
+
+The same call fixes the older half of that bug: the code used to be read as
+``int(proc.exitstatus or -1)``, which turns a CLEAN exit into ``-1`` — zero is
+falsy. So quitting an agent with ``/exit`` was reported as a crash, and the
+resume self-healing in ``jarvis/agentic_ide/session.py`` (which restarts a pane
+whose exit code is not 0) restarted agents the user had deliberately closed.
"""
from __future__ import annotations
@@ -119,6 +134,32 @@ MAX_PENDING_CHARS = 256 * 1024
#: the output has to be delivered on.
_EMPTY_READ_BACKOFF_S = 0.005
+#: What every layer above reads as "the child is gone and nobody could say with
+#: what code". Distinct from a real ``-1``only in intent; both mean "not a clean
+#: stop", which is the one distinction anything above actually acts on.
+UNKNOWN_EXIT_CODE = -1
+
+
+def normalize_exit_code(raw: int | None) -> int:
+ """One convention for an exit code, whatever the backend reported.
+
+ ``None`` (the backend could not tell) becomes :data:`UNKNOWN_EXIT_CODE`, and
+ a Windows unsigned DWORD is re-signed, so ``4294967295`` reads as the ``-1``
+ it always was. Everything else is passed through — including ``0``, which
+ the old ``or -1`` idiom quietly turned into a failure (module docstring).
+ """
+ if raw is None:
+ return UNKNOWN_EXIT_CODE
+ code = int(raw)
+ # Only the top half of the unsigned range is folded, which is exactly the
+ # range a C `int` would have shown as negative: a POSIX status is 0-255 and
+ # an ordinary Windows code is small, so nothing legitimate lands in it.
+ # Windows NTSTATUS values (0xC000013A — stopped by Ctrl-C) fold too; the
+ # pane translates the ones worth naming back into words.
+ if 0x8000_0000 <= code <= 0xFFFF_FFFF:
+ code -= 0x1_0000_0000
+ return code
+
@dataclass(slots=True)
class PtySession:
@@ -319,10 +360,11 @@ class PtyManager:
session.tree.assign(pid)
except Exception as exc: # noqa: BLE001
logger.warning(
- "PTY could not be contained — its descendants will survive it",
- terminal_id=terminal_id,
- pid=pid,
- error=str(exc),
+ "PTY could not be contained — its descendants will survive it: "
+ "terminal={} pid={} error={}",
+ terminal_id,
+ pid,
+ exc,
)
session.reader_thread = threading.Thread(
target=self._reader_loop,
@@ -341,12 +383,12 @@ class PtyManager:
)
session.reader_thread.start()
logger.info(
- "PTY spawned",
- terminal_id=terminal_id,
- shell=shell_id,
- pid=pid,
- cols=cols,
- rows=rows,
+ "PTY spawned: shell={} terminal={} pid={} size={}x{}",
+ shell_id,
+ terminal_id,
+ pid,
+ cols,
+ rows,
)
return session
@@ -359,7 +401,7 @@ class PtyManager:
session.write(data)
return True
except Exception as exc: # noqa: BLE001
- logger.warning("PTY write failed", terminal_id=terminal_id, error=str(exc))
+ logger.warning("PTY write failed: terminal={} error={}", terminal_id, exc)
return False
def resize(self, terminal_id: str, cols: int, rows: int) -> bool:
@@ -370,7 +412,7 @@ class PtyManager:
session.proc.setwinsize(rows, cols)
return True
except Exception as exc: # noqa: BLE001
- logger.warning("PTY resize failed", terminal_id=terminal_id, error=str(exc))
+ logger.warning("PTY resize failed: terminal={} error={}", terminal_id, exc)
return False
def swap_sessions(self, id_a: str, id_b: str) -> bool:
@@ -414,11 +456,12 @@ class PtyManager:
session_b = self._sessions.get(id_b)
if session_a is None or session_b is None:
logger.debug(
- "PTY swap refused — unknown terminal",
- terminal_id=id_a,
- other_terminal_id=id_b,
- a_known=session_a is not None,
- b_known=session_b is not None,
+ "PTY swap refused — unknown terminal: {} (known={}) <-> {} "
+ "(known={})",
+ id_a,
+ session_a is not None,
+ id_b,
+ session_b is not None,
)
return False
if id_a == id_b:
@@ -427,7 +470,7 @@ class PtyManager:
self._sessions[id_b] = session_a
session_a.terminal_id = id_b
session_b.terminal_id = id_a
- logger.info("PTY sessions swapped", terminal_id=id_a, other_terminal_id=id_b)
+ logger.info("PTY sessions swapped: {} <-> {}", id_a, id_b)
return True
def close(self, terminal_id: str) -> bool:
@@ -472,9 +515,9 @@ class PtyManager:
tree.close()
except Exception as exc: # noqa: BLE001 - reaping is best-effort
logger.debug(
- "PTY tree teardown failed",
- terminal_id=session.terminal_id,
- error=str(exc),
+ "PTY tree teardown failed: terminal={} error={}",
+ session.terminal_id,
+ exc,
)
# No join — the reader thread is a daemon and may still be running
# through one last read(). That's fine; Python exit cleans it up.
@@ -519,29 +562,32 @@ class PtyManager:
raise
except Exception as exc: # noqa: BLE001 - the PTY outlives its viewer
logger.debug(
- "PTY output callback failed",
- terminal_id=session.terminal_id,
- error=str(exc),
+ "PTY output callback failed: terminal={} error={}",
+ session.terminal_id,
+ exc,
)
if session._finished:
break
if session._dropped_chars:
logger.warning(
- "PTY viewer could not keep up — dropped the oldest output",
- terminal_id=session.terminal_id,
- dropped_chars=session._dropped_chars,
+ "PTY viewer could not keep up — dropped the oldest output: "
+ "terminal={} dropped_chars={}",
+ session.terminal_id,
+ session._dropped_chars,
)
code = session._exit_code
try:
- await on_closed(session.terminal_id, -1 if code is None else code)
+ await on_closed(
+ session.terminal_id, UNKNOWN_EXIT_CODE if code is None else code
+ )
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 - the viewer may be gone
logger.debug(
- "PTY close callback failed",
- terminal_id=session.terminal_id,
- error=str(exc),
+ "PTY close callback failed: terminal={} error={}",
+ session.terminal_id,
+ exc,
)
# A child that ended BY ITSELF never goes through ``_terminate``, and
# the servers it started are exactly as orphaned as after a kill — a
@@ -554,9 +600,9 @@ class PtyManager:
tree.close()
except Exception as exc: # noqa: BLE001 - reaping is best-effort
logger.debug(
- "PTY tree teardown after exit failed",
- terminal_id=session.terminal_id,
- error=str(exc),
+ "PTY tree teardown after exit failed: terminal={} error={}",
+ session.terminal_id,
+ exc,
)
def _reader_loop(
@@ -587,9 +633,10 @@ class PtyManager:
except Exception as exc: # noqa: BLE001
# Process closed / pipe broken — normal end of life.
logger.debug(
- "PTY read exception (process presumably dead)",
- terminal_id=session.terminal_id,
- error=str(exc),
+ "PTY read exception (process presumably dead): "
+ "terminal={} error={}",
+ session.terminal_id,
+ exc,
)
break
if not data:
@@ -616,9 +663,9 @@ class PtyManager:
reply = on_probe(text)
except Exception as exc: # noqa: BLE001
logger.debug(
- "PTY probe failed",
- terminal_id=session.terminal_id,
- error=str(exc),
+ "PTY probe failed: terminal={} error={}",
+ session.terminal_id,
+ exc,
)
else:
if reply:
@@ -626,20 +673,28 @@ class PtyManager:
session.write(reply)
except Exception as exc: # noqa: BLE001
logger.debug(
- "PTY probe reply could not be written",
- terminal_id=session.terminal_id,
- error=str(exc),
+ "PTY probe reply could not be written: "
+ "terminal={} error={}",
+ session.terminal_id,
+ exc,
)
session.offer(text, loop)
finally:
try:
- exit_code = int(proc.exitstatus or -1)
+ exit_code = normalize_exit_code(proc.exitstatus)
except Exception: # noqa: BLE001
- exit_code = -1
+ exit_code = UNKNOWN_EXIT_CODE
session.finish(exit_code, loop)
+ # Both fields go in the MESSAGE. loguru treats keyword arguments as
+ # format arguments, and the app's file sink formats `{message}`
+ # alone — so a call that only passed them as keywords logged the
+ # bare sentence, and every past pane death was recorded without
+ # saying which pane or with what code. That is the line this bug
+ # needed and did not have.
logger.info(
- "PTY reader terminated",
- terminal_id=session.terminal_id,
- exit_code=exit_code,
+ "PTY reader terminated: shell={} terminal={} exit_code={}",
+ session.shell_id,
+ session.terminal_id,
+ exit_code,
)
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index 0f0520fe42..b5e8fc2ec8 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -73,6 +73,7 @@ import {
type PaneDropPayload,
} from "./paneDrop";
import { usePaneFileDrag } from "./paneFileDrag";
+import { describeExit, explainExit } from "./paneExit";
import { PaneRecap } from "./PaneRecap";
import { attachToTerminal } from "@/lib/agenticIdeApi";
import type { RecapReason, RecapSource } from "@/lib/agenticIdeApi";
@@ -739,9 +740,9 @@ export function AgenticTerminal({
term.focus();
},
onExit: (code) => {
- report("exited", `exit code ${code}`);
+ report("exited", explainExit(code));
writeToPane(
- `\r\n\x1b[33m[${displayName} exited — code ${code}]\x1b[0m\r\n`,
+ `\r\n\x1b[33m${describeExit(displayName, code)}\x1b[0m\r\n`,
);
},
onTrouble: (message, retrying) => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneExit.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneExit.test.ts
new file mode 100644
index 0000000000..b709a38cee
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneExit.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import { describeExit, explainExit } from "./paneExit";
+
+describe("paneExit", () => {
+ it("never shows the raw unsigned Windows code the bug report carried", () => {
+ // The backend re-signs it before it gets here; this pins that the pane has
+ // no path back to the ten-digit form the user was shown.
+ expect(describeExit("Codex", -1)).not.toContain("4294967295");
+ expect(describeExit("Codex", -1)).toContain("stopped unexpectedly");
+ expect(describeExit("Codex", -1)).toContain("Restart");
+ });
+
+ it("calls a clean stop a clean stop", () => {
+ expect(describeExit("Claude Code", 0)).toBe("[Claude Code stopped]");
+ expect(explainExit(0)).toBe("stopped");
+ });
+
+ it("names the Windows statuses whose meaning is unambiguous", () => {
+ expect(explainExit(-1073741510)).toContain("Ctrl-C");
+ expect(explainExit(-1073741510)).toContain("0xC000013A");
+ expect(explainExit(-1073741819)).toContain("access violation");
+ });
+
+ it("keeps an unrecognised code visible instead of guessing at it", () => {
+ // The number is the part worth searching for, so it stays — what must not
+ // happen is a confident explanation that is wrong.
+ expect(explainExit(137)).toContain("137");
+ expect(explainExit(137)).toContain("stopped unexpectedly");
+ });
+
+ it("wraps the explanation in the pane's own agent name", () => {
+ expect(describeExit("Codex", 3)).toBe(
+ "[Codex stopped unexpectedly (exit code 3) — use Restart to bring it back]",
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneExit.ts b/jarvis/ui/web/frontend/src/components/agentic/paneExit.ts
new file mode 100644
index 0000000000..1422c714a7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneExit.ts
@@ -0,0 +1,47 @@
+/**
+ * Turn a dead pane's exit code into a sentence a person can act on.
+ *
+ * The pane used to print the number raw: "[Codex exited — code 4294967295]".
+ * That value is a Windows exit code read as unsigned — the agent had really
+ * ended with -1 — and ten digits of it told the user nothing except that
+ * something had gone wrong in a way they could not look up. The backend now
+ * re-signs the code once (`jarvis/terminal/pty_manager.py::normalize_exit_code`)
+ * and this is the other half: naming the handful of codes that mean something
+ * specific, and otherwise saying plainly that the agent stopped on its own.
+ *
+ * Deliberately NOT a lookup of every possible status. A wrong-but-confident
+ * explanation is worse than none, so only codes whose meaning is unambiguous
+ * are named; everything else keeps the number, which is the part worth
+ * searching for.
+ */
+
+/**
+ * Windows NTSTATUS values a coding CLI actually dies with, already re-signed
+ * the way the backend hands them over. The hex form is what a user would find
+ * a description of, so it stays in the text.
+ */
+const WINDOWS_STATUS: ReadonlyMap<number, string> = new Map([
+ [-1073741510, "stopped with Ctrl-C (0xC000013A)"],
+ [-1073741819, "crashed — memory access violation (0xC0000005)"],
+ [-1073740791, "crashed — stack buffer overrun (0xC0000409)"],
+ [-1073740940, "crashed — heap corruption (0xC0000374)"],
+ [-1073740771, "crashed — unhandled exception (0xC000041D)"],
+ [-1073741502, "could not start — a required DLL was missing (0xC0000142)"],
+]);
+
+/** What the pane writes into the terminal when its agent is gone. */
+export function describeExit(name: string, code: number): string {
+ return `[${name} ${explainExit(code)}]`;
+}
+
+/** The same explanation without the pane's name — for the header's tooltip. */
+export function explainExit(code: number): string {
+ if (code === 0) return "stopped";
+ const known = WINDOWS_STATUS.get(code);
+ if (known) return known;
+ // -1 is what both a child that exited with -1 and a backend that could not
+ // read a code at all arrive as. They are one case to the reader: the agent is
+ // gone and did not stop cleanly.
+ if (code === -1) return "stopped unexpectedly — use Restart to bring it back";
+ return `stopped unexpectedly (exit code ${code}) — use Restart to bring it back`;
+}
diff --git a/tests/unit/agentic_ide/test_interrupted.py b/tests/unit/agentic_ide/test_interrupted.py
index e8f9e93e68..2b23265bc2 100644
--- a/tests/unit/agentic_ide/test_interrupted.py
+++ b/tests/unit/agentic_ide/test_interrupted.py
@@ -63,6 +63,7 @@ async def _restarted_pane(
*,
name: str = "Alex",
conversation: str = "conv-1",
+ continuation_needed: bool = True,
):
"""A pane whose agent was spawned onto a conversation that already exists.
@@ -75,6 +76,7 @@ async def _restarted_pane(
session.terminals[0].resume = ResumeHandle(
kind="claude_session", id=conversation, captured_at=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
@@ -106,6 +108,41 @@ async def test_a_pane_that_started_fresh_is_not_waiting(
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) == []
+
+
+ "screen",
+ [
+ "\r\nCooking (12s · esc to interrupt)\r\n",
+ "\r\nDo you want to continue?\r\n❯ 1. Yes\r\n",
+ ],
+)
+async def test_a_resumed_pane_already_working_or_asking_is_not_offered_continue(
+ registry: Registry,
+ tmp_path: Path,
+ existing_conversation: Any,
+ screen: str,
+) -> None:
+ """Active work needs no nudge; a question needs an answer, not a nudge."""
+ _session, term = await _restarted_pane(registry, tmp_path, existing_conversation)
+ term.transcript.clear()
+ term.transcript.feed(screen)
+
+ 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:
@@ -315,6 +352,7 @@ async def test_a_pane_still_starting_is_continued_when_it_comes_up(
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)
@@ -342,6 +380,7 @@ async def test_a_restored_pane_is_listed_before_its_agent_starts(
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,
@@ -358,11 +397,24 @@ async def test_a_restored_pane_is_listed_before_its_agent_starts(
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,
+ ),
],
)
],
diff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.py
index 959218643a..a63960f970 100644
--- a/tests/unit/agentic_ide/test_pane_notifications.py
+++ b/tests/unit/agentic_ide/test_pane_notifications.py
@@ -32,6 +32,35 @@ BUSY_SCREEN = "\r\n✳ Cooking… (12s · ↑ 1.2k tokens · esc to interrupt)\r
IDLE_SCREEN = "\r\n❯ \r\n"
QUESTION_SCREEN = "\r\nDo you want to make this edit to config.py?\r\n❯ 1. Yes\r\n"
+# Rows copied VERBATIM off the panes of a running workspace (Claude Code
+# 2.1.220, 2026-07-29), because the first version of this detector was written
+# against an assumption instead and the assumption was wrong: it looked for
+# "esc to interrupt", this build does not draw one in these states, so no pane
+# was ever seen working and the bell stayed empty while terminals finished all
+# around it. Whatever replaces the rule has to keep answering these correctly.
+REAL_WORKING = (
+ "\r\n· Scurrying… (2m 4s · ↓ 1.6k tokens)\r\n"
+ " Tip: Use /btw to ask a quick side question without interrupting Claude's current work\r\n"
+)
+REAL_THINKING = "\r\n· Crystallizing… (1m 54s · thinking)\r\n"
+REAL_FINISHED = (
+ "\r\n✻ Worked for 13m 27s\r\n"
+ ">\r\n"
+ " 📁 Personal Jarvis 🌿 main Opus 5 (1M context)\r\n"
+ " ⏵⏵ auto mode on (shift+tab to cycle) · ⁝ for age…\r\n"
+)
+# The startup screen of a pane nobody has typed into. Its authentication banner
+# sits there for the pane's whole life — treating it as a question would make
+# every idle terminal a standing "needs input".
+REAL_STARTUP_BANNER = (
+ "\r\n Claude Code v2.1.220\r\n"
+ " ▐▛███▜▌ Opus 5 (1M context) with xhigh effort\r\n"
+ "▝▜█████▛▘ Claude Max\r\n"
+ " ▘▘ ▝▝ ~\\Desktop\\Personal Jarvis\r\n"
+ " ‼ 1 MCP server needs authentication · run /mcp\r\n"
+ ">\r\n"
+)
+
@pytest.fixture(autouse=True)
def _clean_store() -> Any:
@@ -67,6 +96,92 @@ def _draw(term: Any, screen: str) -> None:
term.transcript.feed(screen)
+# ------------------------------------------------- reading the REAL terminals
+async def test_a_real_working_pane_is_seen_working(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The row this build actually draws while it works — no interrupt hint in it.
+
+ This is the regression that made the feature do nothing on the machine it
+ was built for: the pane is plainly busy and the detector called it idle.
+ """
+ _session, term = await _pane(registry, tmp_path)
+ _draw(term, REAL_WORKING)
+ term.last_output_at = 1000.0
+
+ assert read_activity(term, now=1001.0) == "working"
+
+
+async def test_a_real_thinking_pane_is_seen_working(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """No tokens, no hint — just the clock. Still working."""
+ _session, term = await _pane(registry, tmp_path)
+ _draw(term, REAL_THINKING)
+ term.last_output_at = 1000.0
+
+ assert read_activity(term, now=1001.0) == "working"
+
+
+async def test_a_real_finished_pane_is_seen_waiting(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """"Worked for 13m 27s" states a duration; it does not tick."""
+ _session, term = await _pane(registry, tmp_path)
+ _draw(term, REAL_FINISHED)
+ term.last_output_at = 1000.0
+
+ assert read_activity(term, now=1001.0) == "waiting"
+
+
+async def test_a_stale_clock_is_not_a_running_one(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A bracketed duration on a screen that stopped moving is text, not a clock.
+
+ Without this pairing, a frozen last frame — or an agent quoting "(3s)" in
+ its own answer — would read as an agent that is still working, and the pane
+ would never be reported at all.
+ """
+ _session, term = await _pane(registry, tmp_path)
+ _draw(term, REAL_WORKING)
+ term.last_output_at = 1000.0
+
+ assert read_activity(term, now=1000.0 + 60) == "waiting"
+
+
+async def test_the_startup_banner_is_not_a_question(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """It sits there for the pane's whole life — a standing banner, not an ask."""
+ _session, term = await _pane(registry, tmp_path)
+ _draw(term, REAL_STARTUP_BANNER)
+ term.last_output_at = 1000.0
+
+ assert read_activity(term, now=1001.0) == "waiting"
+
+
+async def test_a_real_pane_finishing_files_one_entry(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """End to end on the real rows: working → finished → exactly one entry."""
+ watcher = notifications.watcher()
+ _session, term = await _pane(registry, tmp_path)
+
+ _draw(term, REAL_WORKING)
+ term.last_output_at = 1000.0
+ assert watcher.poll(registry, now=1000.5) == []
+
+ term.transcript.clear()
+ _draw(term, REAL_FINISHED)
+ term.last_output_at = 1002.0
+ assert watcher.poll(registry, now=1002.5) == []
+
+ filed = watcher.poll(registry, now=1002.5 + notifications.SETTLE_S + 1)
+
+ assert [entry.kind for entry in filed] == ["completed"]
+
+
# ------------------------------------------------------------------- reading
async def test_the_interrupt_hint_is_what_marks_a_pane_busy(
registry: Registry, tmp_path: Path
@@ -129,6 +244,48 @@ async def test_a_pane_that_stops_working_is_reported_once(
assert watcher.poll(registry, now=400.0) == []
+async def test_only_observed_work_is_checkpointed_for_restart(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The Continue badge survives only the state that proves an interruption."""
+ watcher = notifications.watcher()
+ _session, term = await _pane(registry, tmp_path)
+
+ _draw(term, BUSY_SCREEN)
+ watcher.poll(registry, now=100.0, emit=False)
+ assert term.resume_continuation_needed is True
+ assert watcher.take_resume_dirty() is True
+ assert notifications.center().list() == [], "the bell switch does not disable checkpointing"
+
+ term.transcript.clear()
+ _draw(term, IDLE_SCREEN)
+ watcher.poll(registry, now=101.0, emit=False)
+ assert term.resume_continuation_needed is True, "a repaint gap must stay armed"
+ assert watcher.take_resume_dirty() is False
+
+ watcher.poll(registry, now=101.0 + notifications.SETTLE_S + 1, emit=False)
+ assert term.resume_continuation_needed is False
+ assert watcher.take_resume_dirty() is True
+
+
+async def test_a_question_clears_the_restart_checkpoint_immediately(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A question needs the user's answer; "continue" would be the wrong input."""
+ watcher = notifications.watcher()
+ _session, term = await _pane(registry, tmp_path)
+ _draw(term, BUSY_SCREEN)
+ watcher.poll(registry, now=100.0)
+ watcher.take_resume_dirty()
+
+ term.transcript.clear()
+ _draw(term, QUESTION_SCREEN)
+ watcher.poll(registry, now=101.0)
+
+ assert term.resume_continuation_needed is False
+ assert watcher.take_resume_dirty() is True
+
+
async def test_a_pane_that_was_never_busy_is_never_reported(
registry: Registry, tmp_path: Path
) -> None:
diff --git a/tests/unit/agentic_ide/test_resume_store.py b/tests/unit/agentic_ide/test_resume_store.py
index a8cfd967b9..48a9a04381 100644
--- a/tests/unit/agentic_ide/test_resume_store.py
+++ b/tests/unit/agentic_ide/test_resume_store.py
@@ -42,6 +42,7 @@ def _workspace(folder: str) -> resume_store.SnapshotWorkspace:
slot=0,
resume=ResumeHandle(kind="claude_session", id="u-1", captured_at=1.0),
prompts_sent=3,
+ continuation_needed=True,
),
resume_store.SnapshotTerminal(
key="blake", name="Blake", agent="codex", column=1, slot=0
@@ -61,6 +62,8 @@ def test_a_saved_snapshot_comes_back_intact(tmp_path: Path) -> None:
assert loaded.workspaces[0].terminals[0].resume is not None
assert loaded.workspaces[0].terminals[0].resume.id == "u-1"
assert loaded.workspaces[0].terminals[1].resume is None
+ assert loaded.workspaces[0].terminals[0].continuation_needed is True
+ assert loaded.workspaces[0].terminals[1].continuation_needed is False
assert loaded.workspaces[0].name == "Release review"
@@ -111,6 +114,7 @@ def test_a_snapshot_from_the_one_workspace_era_still_resumes(tmp_path: Path) ->
assert len(loaded.workspaces) == 1
assert loaded.workspaces[0].folder == str(tmp_path)
assert [t.name for t in loaded.workspaces[0].terminals] == ["Alex"]
+ assert loaded.workspaces[0].terminals[0].continuation_needed is False
assert loaded.saved_at == 42.0
diff --git a/tests/unit/terminal/test_pty_exit_code.py b/tests/unit/terminal/test_pty_exit_code.py
new file mode 100644
index 0000000000..e7f710585b
--- /dev/null
+++ b/tests/unit/terminal/test_pty_exit_code.py
@@ -0,0 +1,149 @@
+"""What a pane is told when its agent is gone.
+
+The reported bug: a Codex pane printed "[Codex exited — code 4294967295]". That
+number is a Windows exit code read as unsigned — the agent had ended with -1 —
+and the pane handed all ten digits to the user unchanged.
+
+Underneath it sat a second, quieter defect. The code was read as
+``int(proc.exitstatus or -1)``, so a CLEAN exit (0) was reported as -1: quitting
+an agent with ``/exit`` looked exactly like a crash, and the resume
+self-healing in ``jarvis/agentic_ide/session.py`` — which restarts a pane whose
+exit code is not 0 — restarted agents the user had deliberately closed.
+
+These pin both halves, on every OS: the handle is a fake, so no real
+pseudo-terminal (or coding agent) is needed to run them.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+
+import pytest
+
+import jarvis.terminal.pty_manager as pty_mod
+from jarvis.terminal.pty_manager import (
+ UNKNOWN_EXIT_CODE,
+ PtyManager,
+ normalize_exit_code,
+)
+
+
+class ExitingHandle:
+ """A ``PtyHandle`` that ends immediately with whatever the test asks for."""
+
+ def __init__(self, exitstatus: int | None) -> None:
+ self.pid = 4242
+ self.exitstatus = exitstatus
+ self._chunks: deque[str] = deque(["done\r\n"])
+ self._alive = True
+
+ def write(self, data: str) -> None:
+ return None
+
+ def setwinsize(self, rows: int, cols: int) -> None:
+ return None
+
+ def read(self, size: int) -> str:
+ if self._chunks:
+ return self._chunks.popleft()
+ self._alive = False
+ raise EOFError
+
+ def isalive(self) -> bool:
+ return self._alive
+
+ def terminate(self, force: bool) -> None:
+ self._alive = False
+
+
+class ScriptedBackend:
+ def __init__(self, handle: ExitingHandle) -> None:
+ self.handle = handle
+
+ def spawn(self, argv, cwd, cols, rows, env=None): # noqa: ANN001, ANN201
+ return self.handle
+
+
+async def _closed_code(monkeypatch, exitstatus: int | None) -> int: # noqa: ANN001
+ """Spawn a pane whose child ends with ``exitstatus``; return what the viewer got."""
+ handle = ExitingHandle(exitstatus)
+ monkeypatch.setattr(pty_mod, "make_pty_backend", lambda: ScriptedBackend(handle))
+ reported: list[int] = []
+ manager = PtyManager()
+
+ async def on_output(_tid: str, _text: str) -> None:
+ return
+
+ async def on_closed(_tid: str, code: int) -> None:
+ reported.append(code)
+
+ await manager.spawn(
+ shell_argv=("agent",),
+ shell_id="test",
+ cwd=None,
+ cols=80,
+ rows=24,
+ on_output=on_output,
+ on_closed=on_closed,
+ )
+ deadline = asyncio.get_running_loop().time() + 3.0
+ while not reported:
+ if asyncio.get_running_loop().time() > deadline:
+ raise AssertionError("the pane was never told its agent had exited")
+ await asyncio.sleep(0.005)
+ manager.close_all()
+ return reported[0]
+
+
+ ("raw", "expected"),
+ [
+ # The reported bug, exactly: pywinpty hands over the unsigned DWORD.
+ (0xFFFF_FFFF, -1),
+ # A clean stop stays a clean stop — the `or -1` idiom made it a failure.
+ (0, 0),
+ # Ordinary codes are untouched on every OS.
+ (1, 1),
+ (3, 3),
+ (255, 255),
+ # A Windows NTSTATUS re-signs like any other value above 2**31.
+ (0xC000_013A, -1073741510),
+ # Nothing to report is its own answer, not an invented number.
+ (None, UNKNOWN_EXIT_CODE),
+ ],
+)
+def test_exit_codes_are_normalized(raw: int | None, expected: int) -> None:
+ assert normalize_exit_code(raw) == expected
+
+
+async def test_a_clean_exit_is_reported_as_zero(monkeypatch) -> None: # noqa: ANN001
+ """The half that made `/exit` look like a crash and restarted closed panes."""
+ assert await _closed_code(monkeypatch, 0) == 0
+
+
+async def test_an_unsigned_windows_code_reaches_the_pane_signed(monkeypatch) -> None: # noqa: ANN001
+ """4294967295 never leaves this layer — the pane is told -1."""
+ assert await _closed_code(monkeypatch, 0xFFFF_FFFF) == -1
+
+
+async def test_an_unknown_code_is_not_invented(monkeypatch) -> None: # noqa: ANN001
+ """A backend that cannot say reports the one agreed 'not a clean stop'."""
+ assert await _closed_code(monkeypatch, None) == UNKNOWN_EXIT_CODE
+
+
+def test_the_exit_line_carries_its_fields_in_the_message() -> None:
+ """The line this bug needed and did not have.
+
+ loguru reads keyword arguments as FORMAT arguments and the app's file sink
+ formats ``{message}`` alone, so ``logger.info("PTY reader terminated",
+ exit_code=...)`` logged the bare sentence — every past pane death was
+ recorded without saying which pane or with what code. Pinned by reading the
+ source, because the sink that dropped them is configured elsewhere.
+ """
+ from pathlib import Path
+
+ source = Path(pty_mod.__file__).read_text(encoding="utf-8")
+ marker = "PTY reader terminated"
+ line = next(ln for ln in source.splitlines() if marker in ln)
+ assert "exit_code={}" in line, "the exit code must be part of the message"