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): decide a pane is busy from the terminal, not the product

Ruben Lütkec8dd0230e978
diff --git a/jarvis/agentic_ide/activity.py b/jarvis/agentic_ide/activity.py
index 1592762a95..4fee8ae897 100644
--- a/jarvis/agentic_ide/activity.py
+++ b/jarvis/agentic_ide/activity.py
@@ -9,85 +9,78 @@ looks exactly like the eleven around it that are still thinking. So the user
watches the grid, or comes back twenty minutes later to find that everything
had been finished for nineteen of them.
-This module reads one pane's CURRENT SCREEN and answers with one word. The
-transitions between those words are what :mod:`.notifications` turns into
-something the user can be told.
-
-## Why the screen and not the transcript
-
-The transcript walks the whole scrollback and folds repeated rows — the right
-shape for "summarize what happened here", the wrong one for "what is on screen
-right now", which is a single grid of at most a few dozen rows. The screen is
-what a person looking at the pane would see, and that is the question.
-
-## What it looks at, and what it deliberately does not
-
-**Working** is answered by THREE signals, most specific first, because no
-single one covers every product or every phase of a turn. Rows below are copied
-off real sessions of the CLIs installed here, not imagined:
-
-1. **A running clock** — the bracketed elapsed time these products tick once a
- second while they work, and drop the instant they stop::
-
- ✻ Meandering… (2m 4s · ↓ 5.3k tokens) ← Claude Code, thinking
- • Working (1s • esc to interrupt) ← Codex, thinking
- ✻ Worked for 13m 27s ← finished, no brackets
-
-2. **An interrupt hint** ("esc to interrupt"), for a CLI that shows one without
- a clock.
-
-3. **The pane is printing right now** — no knowledge of the CLI at all, which
- is what makes a product nobody has measured behave correctly.
-
-Each covers a phase the others miss, and both gaps were measured rather than
-guessed. The first version of this module used the hint ALONE, reasoning that
-it is near-universal: the installed Claude Code does not draw one in the states
-that matter, so no pane was ever seen working and the bell stayed empty while
-terminals finished all around it. A clock-only rule then failed the other way —
-Codex draws its clock while it thinks and DROPS it while it writes the answer,
-so a reply still arriving read as a pane that had finished.
-
-**Idle time alone never says "finished"**, and that is load-bearing. An agent
-thinking hard about a large refactor prints nothing readable for minutes at a
-time, while a stalled one may redraw its status bar every second — the same
-reasoning :mod:`.interrupted` sets out. Freshness is used only in the positive
-direction: to confirm a clock on screen is TICKING, and to notice that output
-is arriving. Silence on its own proves nothing.
-
-**Output in the shadow of a keystroke is not the agent working.** A terminal
-echoes what a person types, so a pane being typed into is "producing output";
-without that exclusion, pausing mid-sentence while writing a prompt would read
-as an agent that just finished.
-
-**A finished pane is not read from its prose.** The rule is only ever "it was
-drawing a running clock and now it is not", so what the agent WROTE never
-decides whether it is done. That keeps the detector working for a CLI nobody
-has taught it about, in a language nobody anticipated.
-
-The one place content is consulted is :data:`ASK_FRAGMENTS` — telling "it
-finished" apart from "it is asking you something" genuinely needs to see the
-question. It can only ever UPGRADE a pane that has already been established as
-not-working, never claim one is busy or idle, so a phrase it has never seen
-costs the user a more specific word and nothing else.
+## The rule: read the TERMINAL, never the product
+
+**A pane is working while its screen keeps changing, and waiting once the
+screen has stood still.** That is the whole detector, and it is deliberately a
+property of the terminal rather than of whatever is running inside it. A
+workspace opens five different coding CLIs today and an unknown number
+tomorrow; a rule that knows what any of them prints is a rule that breaks on
+the next one, in the next release, or in the next language.
+
+Two earlier versions proved that the hard way:
+
+* **"It draws an interrupt hint while busy."** The installed Claude Code does
+ not, in the states that matter. No pane was ever seen working, so the one
+ transition the feature watches for could not happen, and the bell stayed
+ empty while terminals finished all around it.
+* **"It ticks a bracketed clock while busy."** Codex ticks one while it THINKS
+ and drops it while it WRITES, so a reply still arriving read as finished. The
+ same pattern also matched the model banner every pane carries — ``Opus 5 (1M
+ context)`` case-folds to ``(1m context)`` — and read every idle terminal as
+ busy.
+
+Both mistakes have the same shape: a claim about a product, checked against one
+product. Screen movement makes no claim at all.
+
+## Why this is safe, measured rather than assumed
+
+Sampled twice a second across Claude Code, Codex, OpenCode and Kimi
+(2026-07-29):
+
+=================== ==========================================
+While WAITING 0 screen changes in 40 samples, all four
+While WORKING a change every sample — longest gap 0.5 s
+After finishing still for 107 s and counting
+=================== ==========================================
+
+So the two states are not close: a working pane repaints at least twice a
+second, and an idle one is perfectly still. None of these products draws its
+own blinking cursor, keeps a clock in a status bar, or emits a heartbeat — any
+of which would have sunk this approach, which is why it was measured first.
+:data:`STILL_S` sits eight times above the longest observed gap.
+
+## Screen CONTENT, not bytes
+
+Bytes arriving is the weaker signal and would be the tempting one, since it
+needs no state. A terminal receives plenty of bytes that change nothing a
+person can see: cursor moves, a row repainted with identical characters, replies
+to the emulator queries a CLI makes at startup. Fingerprinting the visible rows
+answers "did anything CHANGE", which is the question. (Bytes are still used as
+a fallback for a caller that has no previous screen to compare against.)
+
+## The one exclusion
+
+**Movement in the shadow of a keystroke is not the agent working.** A terminal
+echoes what a person types, so a pane being typed into is a pane whose screen
+changes; without this, writing a prompt by hand reads as a busy agent, and the
+moment the user pauses to think the pane is reported finished. Keystrokes are
+stamped on the pane (``Terminal.last_input_at``) and movement in their shadow
+does not count.
## Honest limits
-A CLI that draws neither a clock nor a hint AND thinks in complete silence for
-longer than the settle window reads as finished while it is still thinking.
-Both CLIs measurable here show something the whole time — an agent that gave no
-sign of life for a minute would be indistinguishable from a hung one for its
-user too — but a product nobody has run cannot be promised more than this.
-
-An agent whose process WEDGES stops ticking, so it reads as finished a few
+An agent whose process WEDGES stops repainting, so it reads as finished a few
seconds later; the wording ("finished and waiting at its prompt") is then
optimistic, which is the one case where this is wrong in the user's favour
-rather than silent. A plain shell pane is not an agent and is left out entirely
-by the caller.
+rather than silent. A CLI that genuinely draws nothing at all while it works —
+none of the four measured — would be reported early. A plain shell pane is not
+an agent and is left out entirely by the caller.
"""
from __future__ import annotations
-import re
+import hashlib
import time
from typing import TYPE_CHECKING, Any, Literal
@@ -97,91 +90,42 @@ if TYPE_CHECKING: # pragma: no cover - typing only
#: What one pane is doing, in one word.
#:
#: ``starting`` — no agent process yet (a pane waiting for a cold-start slot).
-#: ``working`` — its CLI is drawing an interrupt hint, so it is busy.
-#: ``waiting`` — alive, not busy: sitting at its prompt.
-#: ``asking`` — not busy AND showing a question or a choice.
+#: ``working`` — its screen is moving.
+#: ``waiting`` — alive and still.
+#: ``asking`` — still, AND showing a question or a choice.
#: ``failed`` — its agent could not be started.
#: ``exited`` — its process is gone.
Activity = Literal["starting", "working", "waiting", "asking", "failed", "exited"]
-#: How many of the pane's visible rows are read. A TUI keeps its status row and
-#: its input box at the BOTTOM of the screen, so the answer is always in the
-#: last few rows — and a full-screen agent's upper rows are its transcript,
-#: which may quote any phrase here without meaning it now.
-TAIL_ROWS = 8
-
-#: The RUNNING CLOCK a coding CLI draws while it is working: an elapsed time in
-#: brackets, ticking once a second.
-#:
-#: This is the primary signal, and it is structural rather than verbal — which
-#: is the whole reason it was chosen over the wording. Measured against the CLIs
-#: actually installed here:
-#:
-#: ✻ Meandering… (2m 4s · ↓ 5.3k tokens) ← working
-#: ▌ Working (28m 55s · Esc to interrupt) ← working
-#: ✻ Worked for 13m 27s ← finished, no brackets
-#:
-#: A spinner word is random ("Meandering", "Scurrying", "Crystallizing"), the
-#: hint next to it differs per product and per version, and both are English. A
-#: bracketed live clock is none of those things: every one of these products
-#: draws one while it works and drops it the moment it stops.
-#:
-#: **Anchored on SECONDS**, and that is not cosmetic. "any number followed by a
-#: time letter in brackets" also matches the model banner these panes carry on
-#: every frame — ``Opus 5 (1M context)``, which case-folds to ``(1m context)``
-#: — so every idle terminal in the workspace read as busy and nothing was ever
-#: reported. A clock that ticks always shows the ticking unit.
-_LIVE_CLOCK_RE = re.compile(r"\(\s*(?:\d+\s*[hm]\s+)*\d+\s*s\b")
-
-#: How recently the pane must have printed for a visible clock to count as a
-#: RUNNING one.
-#:
-#: The pairing is what makes the signal safe. A clock ticks, so a pane drawing
-#: one is producing output every second; a bracketed duration on a screen that
-#: has been still for longer than this is text about a clock, not a clock —
-#: an agent quoting "(3s)" in its own answer, or a frame frozen where it stopped.
-CLOCK_FRESH_S = 8.0
-
-#: How recently a pane must have printed to count as "still producing output".
-#:
-#: The THIRD signal, and the only one that needs no knowledge of the CLI at all
-#: — which is what makes the detector work for a product nobody has measured.
-#: Measured need: Codex draws its clock while it thinks and DROPS it while it
-#: writes the answer, so a clock-only rule reports "finished" in the middle of a
-#: reply that is still arriving. A pane that is printing is working, whatever it
-#: is printing and whichever product is printing it.
+#: How long the screen must stand still before the pane counts as waiting.
#:
-#: Generous rather than tight: a streaming answer arrives in bursts with pauses
-#: between them, and each pause must not read as the end.
-OUTPUT_QUIET_S = 3.0
-
-#: Interrupt hints some CLIs draw while busy, lower-cased. The SECOND way in,
-#: kept because a CLI may show one without a clock; a product that shows neither
-#: simply never reports finishing, which is the safe way to be wrong.
+#: Eight times the longest gap measured while an agent worked (0.5 s, see the
+#: module docstring), so an agent between two steps is never mistaken for one
+#: that stopped — while a pane that really has finished is recognised within a
+#: few seconds. The notification on top of this waits again (`SETTLE_S`), so
+#: nothing is filed until a pane has been quiet for roughly ten seconds.
+STILL_S = 4.0
+
+#: How many of the pane's visible rows the fingerprint covers.
#:
-#: Shared rather than per-product: the wording is near-universal among those
-#: that show it at all, and splitting it per entry would mean a CLI registered
-#: tomorrow starting with an empty set. An entry adds its own peculiarities
-#: through ``WorkspaceAgent.busy_fragments``.
-BUSY_FRAGMENTS: tuple[str, ...] = (
- "to interrupt",
- "esc to stop",
- "ctrl+c to stop",
- "ctrl-c to stop",
- "to cancel",
-)
-
-#: A visible question or choice: the pane is not busy, and it is not simply
-#: waiting either — somebody has to answer it before anything else happens.
+#: The BOTTOM of the screen: a TUI keeps its status row, its spinner and its
+#: input box there, and that is where the movement is. Fingerprinting the whole
+#: screen would also work, and would additionally react to a scrollback shift
+#: that changes nothing about whether the agent is busy.
+TAIL_ROWS = 12
+
+#: A visible question or choice. This does NOT decide whether a pane is busy —
+#: it only chooses the WORD for a pane already established as still, so a
+#: terminal waiting for an answer can say so rather than claiming it finished.
#:
-#: Deliberately SHORT, and every entry is a phrase a TUI only writes when it is
-#: actually asking. Two classes were tried and removed: a startup BANNER ("1 MCP
-#: server needs authentication") sits on screen for the pane's whole life and
-#: would make every idle terminal a standing question, and bare verbs
-#: ("confirm", "approve") match an agent's ordinary prose about its own work.
+#: Every entry is a phrase a TUI writes only while actually asking. Two classes
+#: were tried and removed: a startup BANNER ("1 MCP server needs
+#: authentication") sits on screen for the pane's whole life and would make
+#: every idle terminal a standing question, and bare verbs ("confirm",
+#: "approve") match an agent's ordinary prose about its own work.
#:
-#: Only ever consulted for a pane already established as not-working (see the
-#: module docstring), so a miss costs a word, never a wrong state.
+#: A phrase nobody has anticipated costs the user a more specific word and
+#: nothing else — the entry is still filed, as "finished".
ASK_FRAGMENTS: tuple[str, ...] = (
"do you want",
"would you like",
@@ -197,29 +141,11 @@ ASK_FRAGMENTS: tuple[str, ...] = (
)
-def _extra_busy_fragments(agent: str) -> tuple[str, ...]:
- """Whatever the registered CLI adds to the shared busy set.
-
- Defensive like the rest of the read path: a build without the registry, or
- an entry that predates the field, contributes nothing rather than raising
- inside a poll that runs every couple of seconds.
- """
- try:
- from jarvis.workspace.agents import get_agent
-
- spec = get_agent(str(agent or ""))
- except Exception: # noqa: BLE001 - a state read must never fail on decoration
- return ()
- if spec is None:
- return ()
- return tuple(str(f).lower() for f in getattr(spec, "busy_fragments", ()) or ())
-
-
-def _visible_rows(term: Any) -> list[str]:
- """The pane's bottom rows as they are on screen right now, lower-cased.
+def visible_rows(term: Any) -> list[str]:
+ """The pane's bottom rows as they are on screen right now.
- Reads the replayed SCREEN rather than the cleaned transcript: a status row
- that repeats unchanged is folded away by the transcript, and that row is
+ Reads the replayed SCREEN rather than the cleaned transcript: the transcript
+ folds a status row that repeats unchanged, and movement in that row is
precisely the signal here.
"""
transcript = getattr(term, "transcript", None)
@@ -228,63 +154,70 @@ def _visible_rows(term: Any) -> list[str]:
rows = screen.display() if screen is not None else []
except Exception: # noqa: BLE001 - a test double may expose no real screen
return []
- return [str(row).lower() for row in rows[-TAIL_ROWS:]]
+ return [str(row) for row in rows[-TAIL_ROWS:]]
-def _contains(rows: Sequence[str], fragments: Sequence[str]) -> bool:
- return any(fragment in row for row in rows for fragment in fragments)
-
-
-def _clock_running(rows: Sequence[str], term: Any, *, now: float | None = None) -> bool:
- """Is a live elapsed-time clock being drawn right now?
+def screen_digest(term: Any) -> str:
+ """A fingerprint of what this pane is showing.
- Both halves are required, and the second is what keeps the first honest —
- see :data:`CLOCK_FRESH_S`. ``now`` is injectable so a test can place a pane
- on a timeline instead of racing the wall clock.
+ Compared against the previous one to answer "did the screen move?". Short
+ and cheap: a dozen rows hashed, called once per pane per sweep.
"""
- if not any(_LIVE_CLOCK_RE.search(row) for row in rows):
- return False
- last = getattr(term, "last_output_at", None)
- if not last:
- return False
- moment = time.time() if now is None else now
- return moment - float(last) <= CLOCK_FRESH_S
+ return hashlib.sha1( # noqa: S324 - a change detector, not a security digest
+ "\n".join(visible_rows(term)).encode("utf-8", "replace")
+ ).hexdigest()
+
+def _contains(rows: Sequence[str], fragments: Sequence[str]) -> bool:
+ lowered = [row.lower() for row in rows]
+ return any(fragment in row for row in lowered for fragment in fragments)
-def _printing_now(term: Any, *, now: float | None = None) -> bool:
- """Is this pane producing output that is the AGENT's rather than an echo?
- A terminal echoes every character a person types, so "bytes arrived" alone
- would call a pane busy while somebody writes a prompt into it — and then
- report it finished the moment they paused to think. Keystrokes are stamped
- on the pane (``last_input_at``), and output arriving in their shadow does
- not count.
+def _typing_now(term: Any, moment: float) -> bool:
+ """Is somebody at this pane's keyboard right now?
- This is the signal that needs no knowledge of the CLI, and it is what makes
- a product nobody has measured behave correctly.
+ A terminal echoes keystrokes, so movement while a person types is not the
+ agent working — see the module docstring.
"""
- last_out = getattr(term, "last_output_at", None)
- if not last_out:
- return False
- moment = time.time() if now is None else now
- since = moment - float(last_out)
- # A stamp in the FUTURE is not freshness, it is a clock that does not agree
- # with the caller's — a pane carrying wall-clock times read on a synthetic
- # timeline, or a machine whose clock stepped. Silence is the honest answer.
- if since < 0 or since > OUTPUT_QUIET_S:
- return False
last_in = getattr(term, "last_input_at", None)
- if last_in and 0 <= moment - float(last_in) <= OUTPUT_QUIET_S:
+ if not last_in:
return False
- return True
+ since = moment - float(last_in)
+ return 0 <= since <= STILL_S
-def read_activity(term: Any, *, now: float | None = None) -> Activity:
+def _moving(term: Any, moment: float, still_since: float | None) -> bool:
+ """Has this pane's screen changed recently enough to call it busy?
+
+ ``still_since`` is when the screen was last seen to CHANGE, tracked by the
+ caller across sweeps. Without it — a caller with no previous screen to
+ compare against — this falls back to "bytes arrived recently", which is the
+ weaker form of the same question and errs towards "busy".
+ """
+ if _typing_now(term, moment):
+ return False
+ if still_since is None:
+ last_out = getattr(term, "last_output_at", None)
+ if not last_out:
+ return False
+ since = moment - float(last_out)
+ return 0 <= since <= STILL_S
+ since = moment - float(still_since)
+ # A stamp in the FUTURE is not freshness — it is a clock that does not agree
+ # with the caller's. Silence is the honest answer.
+ return 0 <= since <= STILL_S
+
+
+def read_activity(
+ term: Any, *, now: float | None = None, still_since: float | None = None
+) -> Activity:
"""What ``term`` is doing at this instant.
- Duck-typed on purpose — :class:`~.session.Terminal` imports this module's
- siblings, and every attribute is read defensively so a test double carrying
- half a pane answers with a word instead of an ``AttributeError``.
+ ``still_since`` is the moment this pane's screen last changed, which the
+ caller tracks across sweeps (see :func:`screen_digest`). Duck-typed on
+ purpose — :class:`~.session.Terminal` imports this module's siblings — so a
+ test double carrying half a pane answers with a word rather than an
+ ``AttributeError``.
"""
status = str(getattr(term, "status", "") or "pending")
if status == "error":
@@ -296,18 +229,10 @@ def read_activity(term: Any, *, now: float | None = None) -> Activity:
# a pane that has not started has not finished anything either.
return "starting"
- rows = _visible_rows(term)
- # Three ways to be busy, most specific first. Each covers a phase the others
- # miss: the clock covers thinking with nothing to show, the hint covers a
- # CLI that shows one without a clock, and printing covers writing an answer
- # — which is exactly when Codex drops its clock.
- if _clock_running(rows, term, now=now):
- return "working"
- if _contains(rows, (*BUSY_FRAGMENTS, *_extra_busy_fragments(getattr(term, "agent", "")))):
- return "working"
- if _printing_now(term, now=now):
+ moment = time.time() if now is None else now
+ if _moving(term, moment, still_since):
return "working"
- if _contains(rows, ASK_FRAGMENTS):
+ if _contains(visible_rows(term), ASK_FRAGMENTS):
return "asking"
return "waiting"
@@ -325,12 +250,12 @@ def is_settled(activity: str) -> bool:
__all__ = [
"ASK_FRAGMENTS",
- "BUSY_FRAGMENTS",
- "CLOCK_FRESH_S",
- "OUTPUT_QUIET_S",
"SETTLED",
+ "STILL_S",
"TAIL_ROWS",
"Activity",
"is_settled",
"read_activity",
+ "screen_digest",
+ "visible_rows",
]
diff --git a/jarvis/agentic_ide/notifications.py b/jarvis/agentic_ide/notifications.py
index 96e7bc15e9..b6a5910478 100644
--- a/jarvis/agentic_ide/notifications.py
+++ b/jarvis/agentic_ide/notifications.py
@@ -69,7 +69,7 @@ from typing import TYPE_CHECKING, Any, Literal
from loguru import logger
-from .activity import Activity, is_settled, read_activity
+from .activity import STILL_S, Activity, is_settled, read_activity, screen_digest
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Iterable
@@ -226,6 +226,13 @@ class _PaneWatch:
#: 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
+ #: Fingerprint of what this pane was showing at the previous sweep, and when
+ #: that picture last CHANGED. This pair is the detector: a screen that keeps
+ #: moving is an agent at work, one that stands still is a terminal waiting
+ #: (see :mod:`.activity`). Held here rather than on the terminal because it
+ #: is the watcher's own bookkeeping — nothing else has any use for it.
+ digest: str = ""
+ changed_at: float = 0.0
def _detail(term: Any) -> str:
@@ -239,9 +246,9 @@ def _detail(term: Any) -> str:
def _title(kind: Kind, term: Any) -> str:
"""What the entry says, in one clause.
- Careful about what it claims: a pane that stopped drawing its interrupt hint
- has gone quiet, and that is all anybody knows. "Finished" is the honest word
- for that; "done" or "succeeded" would not be.
+ Careful about what it claims: a pane whose screen stopped moving has gone
+ quiet, and that is all anybody knows. "Finished" is the honest word for
+ that; "done" or "succeeded" would not be.
"""
if kind == "completed":
return "Finished and waiting at its prompt"
@@ -320,27 +327,45 @@ class ActivityWatcher:
*,
emit: bool,
) -> Notification | None:
- # ``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)
+ # Whether this pane's screen is MOVING is the whole detector, and
+ # movement can only be seen by comparing against the previous sweep —
+ # so the fingerprint is taken first and the answer is derived from it.
watch = self._panes.get(ident)
-
+ digest = screen_digest(term)
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.
+ #
+ # Its screen is recorded as having stood still for a LONG time, not
+ # as having just changed, and the difference is a bug that got as
+ # far as the tests: whether the screen is moving cannot be known
+ # from a single look, and assuming movement makes the pane "busy"
+ # for one sweep — after which it "stops", which is a finished
+ # notification for every quiet terminal in the workspace. Assuming
+ # stillness costs one sweep of latency for a pane that really is
+ # working, and claims nothing that was not observed.
+ settled_at = now - STILL_S - 1.0
+ activity = read_activity(term, now=now, still_since=settled_at)
watch = _PaneWatch(
activity=activity,
since=now,
announced=True,
resume_needed=bool(getattr(term, "resume_continuation_needed", False)),
+ digest=digest,
+ changed_at=settled_at,
)
self._panes[ident] = watch
self._checkpoint_resume_state(term, activity, watch, now)
return None
+ if digest != watch.digest:
+ watch.digest = digest
+ watch.changed_at = now
+ # ``now`` travels into the read as well, so a test can place a pane on
+ # its own timeline instead of racing the wall clock.
+ activity = read_activity(term, now=now, still_since=watch.changed_at)
+
if activity != watch.activity:
if watch.activity == "working":
watch.worked = True
diff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.py
index a63960f970..2145051874 100644
--- a/tests/unit/agentic_ide/test_pane_notifications.py
+++ b/tests/unit/agentic_ide/test_pane_notifications.py
@@ -23,7 +23,7 @@ import pytest
from jarvis.agentic_ide import notifications
from jarvis.agentic_ide import session as session_mod
-from jarvis.agentic_ide.activity import read_activity
+from jarvis.agentic_ide.activity import STILL_S, read_activity
from jarvis.agentic_ide.session import Registry
from tests.fakes.fake_pty_manager import FakePtyManager
@@ -61,6 +61,45 @@ REAL_STARTUP_BANNER = (
">\r\n"
)
+# --- EVERY CLI a workspace can open, at rest (measured 2026-07-29) -----------
+#
+# The detector must hold for all of them, so the cases below are parametrized
+# over these rather than written against one product. They look nothing like
+# each other — different box drawing, different status lines, different
+# languages of chrome — which is the point: the rule reads the terminal, not
+# the thing running in it.
+#
+# Also measured, and the reason the rule is safe: while WAITING, all four
+# changed their screen 0 times in 40 samples over 20 seconds; while WORKING,
+# the longest gap between changes was 0.5 s.
+REST_SCREENS = {
+ "claude": (
+ "\r\n ‼ 1 MCP server needs authentication · run /mcp\r\n"
+ "❯ Reply with exactly one word: ping\r\n"
+ "● ping\r\n"
+ "✻ Sautéed for 2s\r\n"
+ "❯\r\n"
+ " 📁 probe-repo 🌿 master Opus 5 (1M context)\r\n"
+ ),
+ "codex": (
+ "\r\n• You have 1 usage limit reset available. Run /usage to use one.\r\n"
+ "• ping\r\n"
+ "› Improve documentation in @filename\r\n"
+ " gpt-5.6-sol xhigh fast · ~\\probe-repo\r\n"
+ ),
+ "opencode": (
+ "\r\n ┃ Build · Nano Banana Pro Google\r\n"
+ " ╹▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\r\n"
+ " tab agents ctrl+p commands\r\n"
+ ),
+ "kimi": (
+ "\r\n ✦ Use Kimi K3 with High thinking effort\r\n"
+ " Error: LLM not set, send \"/login\" to login\r\n"
+ " │ > \r\n"
+ " C:\\probe-repo \r\n"
+ ),
+}
+
@pytest.fixture(autouse=True)
def _clean_store() -> Any:
@@ -84,9 +123,11 @@ async def _noop_exit(_code: int) -> None:
return None
-async def _pane(registry: Registry, folder: Path, *, name: str = "Alex"):
+async def _pane(
+ registry: Registry, folder: Path, *, name: str = "Alex", agent: str = "claude"
+):
"""One live pane in one workspace, through the real attach path."""
- session = await registry.start(str(folder), [{"agent": "claude", "name": name}])
+ session = await registry.start(str(folder), [{"agent": agent, "name": name}])
term = await registry.attach(name, 100, 30, _noop, _noop_exit)
return session, term
@@ -96,69 +137,152 @@ def _draw(term: Any, screen: str) -> None:
term.transcript.feed(screen)
+def _quiet_since(term: Any, at: float) -> None:
+ """Say this pane last printed at ``at`` and nobody has typed into it.
+
+ Attaching a pane stamps it with the WALL clock, while these tests run on a
+ synthetic timeline — so without this a pane is "printing right now" against
+ every `now` a test picks, and the third busy signal (see
+ `activity.OUTPUT_QUIET_S`) answers before the screen is ever consulted.
+ Tests about what is ON the screen say so explicitly.
+ """
+ term.last_output_at = at
+ term.last_input_at = None
+
+
+def _busy(watcher: Any, registry: Registry, term: Any, *, start: float, sweeps: int = 3) -> float:
+ """Drive a pane through ``sweeps`` sweeps of a MOVING screen.
+
+ A pane is busy because its picture keeps changing, so making one busy in a
+ test means changing its picture — repeatedly, since a single change cannot
+ be told from a pane that was already still. Returns the moment of the last
+ sweep, which is when the screen stopped moving.
+ """
+ at = start
+ for step in range(sweeps):
+ at = start + step * notifications.SWEEP_INTERVAL_S
+ term.transcript.clear()
+ _draw(term, f"\r\n· working, frame {step}\r\n")
+ watcher.poll(registry, now=at)
+ return at
+
+
+def _rest(
+ watcher: Any, registry: Registry, term: Any, screen: str, *, at: float, emit: bool = True
+) -> list:
+ """Show ``screen`` and let it stand still long enough to count as settled."""
+ term.transcript.clear()
+ _draw(term, screen)
+ watcher.poll(registry, now=at, emit=emit)
+ return watcher.poll(registry, now=at + STILL_S + 1, emit=emit)
+
+
# ------------------------------------------------- reading the REAL terminals
-async def test_a_real_working_pane_is_seen_working(
+#
+# One rule, four products, no product knowledge: a screen that MOVES is an agent
+# at work, a screen that stands still is a terminal waiting. Each case below
+# drives the real rows of a real CLI through the detector.
+
+
[email protected]("agent,screen", list(REST_SCREENS.items()))
+async def test_a_still_screen_is_a_waiting_pane(
+ registry: Registry, tmp_path: Path, agent: str, screen: str
+) -> None:
+ """Every CLI at rest, read the same way — measured: idle panes never repaint."""
+ _session, term = await _pane(registry, tmp_path, agent=agent, name="Px")
+ _draw(term, screen)
+
+ assert read_activity(term, now=1030.0, still_since=1000.0) == "waiting"
+
+
[email protected]("agent,screen", list(REST_SCREENS.items()))
+async def test_a_moving_screen_is_a_working_pane(
+ registry: Registry, tmp_path: Path, agent: str, screen: str
+) -> None:
+ """And every CLI while its screen moves, whatever it happens to be drawing."""
+ _session, term = await _pane(registry, tmp_path, agent=agent, name="Px")
+ _draw(term, screen)
+
+ assert read_activity(term, now=1000.5, still_since=1000.0) == "working"
+
+
+async def test_movement_is_the_only_thing_that_counts(
registry: Registry, tmp_path: Path
) -> None:
- """The row this build actually draws while it works — no interrupt hint in it.
+ """The rows this build draws while WORKING are not treated as special.
- 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.
+ The point of the rewrite: these are the exact rows that fooled two earlier
+ versions — one looked for an interrupt hint they do not contain, the next
+ for a bracketed clock that also matched the model banner. Frozen on screen,
+ they mean a pane that has stopped, and that is now the answer.
"""
_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"
+ assert read_activity(term, now=1030.0, still_since=1000.0) == "waiting"
-async def test_a_real_thinking_pane_is_seen_working(
+async def test_a_pane_whose_screen_keeps_changing_is_working(
registry: Registry, tmp_path: Path
) -> None:
- """No tokens, no hint — just the clock. Still working."""
+ """Through the watcher, which is what actually tracks the movement."""
+ watcher = notifications.watcher()
_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"
+ _draw(term, REAL_WORKING)
+ watcher.poll(registry, now=100.0)
+ for tick in range(1, 6):
+ # A different screen every sweep, exactly as a running agent produces.
+ term.transcript.clear()
+ _draw(term, f"\r\n· Scurrying… ({tick}m 4s · ↓ {tick}.6k tokens)\r\n")
+ assert watcher.poll(registry, now=100.0 + tick * 2) == []
+ assert watcher._panes[(_session.id, term.key)].activity == "working"
-async def test_a_real_finished_pane_is_seen_waiting(
+async def test_the_startup_banner_is_not_a_question(
registry: Registry, tmp_path: Path
) -> None:
- """"Worked for 13m 27s" states a duration; it does not tick."""
+ """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_FINISHED)
- term.last_output_at = 1000.0
+ _draw(term, REAL_STARTUP_BANNER)
- assert read_activity(term, now=1001.0) == "waiting"
+ assert read_activity(term, now=1030.0, still_since=1000.0) == "waiting"
-async def test_a_stale_clock_is_not_a_running_one(
+async def test_a_visible_choice_is_told_apart_from_a_finished_pane(
registry: Registry, tmp_path: Path
) -> None:
- """A bracketed duration on a screen that stopped moving is text, not a clock.
+ """Content decides the WORD, never whether the pane is busy."""
+ _session, term = await _pane(registry, tmp_path)
+ _draw(term, QUESTION_SCREEN)
+
+ assert read_activity(term, now=1030.0, still_since=1000.0) == "asking"
- 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.
+
+async def test_typing_into_a_pane_is_not_the_agent_working(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A terminal echoes keystrokes, and an echo is not work.
+
+ Without this, writing a prompt by hand reads as a busy agent — and the
+ moment the user pauses to think, the pane is reported as finished.
"""
_session, term = await _pane(registry, tmp_path)
- _draw(term, REAL_WORKING)
- term.last_output_at = 1000.0
+ _draw(term, IDLE_SCREEN)
+ term.last_input_at = 1000.0
- assert read_activity(term, now=1000.0 + 60) == "waiting"
+ assert read_activity(term, now=1000.2, still_since=1000.0) == "waiting"
-async def test_the_startup_banner_is_not_a_question(
+async def test_movement_after_the_typing_stopped_is_work(
registry: Registry, tmp_path: Path
) -> None:
- """It sits there for the pane's whole life — a standing banner, not an ask."""
+ """The other side of the same rule: once the keyboard is quiet, movement counts."""
_session, term = await _pane(registry, tmp_path)
- _draw(term, REAL_STARTUP_BANNER)
- term.last_output_at = 1000.0
+ _draw(term, IDLE_SCREEN)
+ term.last_input_at = 1000.0
- assert read_activity(term, now=1001.0) == "waiting"
+ assert read_activity(term, now=1010.2, still_since=1010.0) == "working"
async def test_a_real_pane_finishing_files_one_entry(
@@ -174,10 +298,14 @@ async def test_a_real_pane_finishing_files_one_entry(
term.transcript.clear()
_draw(term, REAL_FINISHED)
- term.last_output_at = 1002.0
+ _quiet_since(term, 1002.0)
+ # Still "working" here: it printed half a second ago, and a reply arrives in
+ # bursts. The clock is gone but the pane is not done talking.
assert watcher.poll(registry, now=1002.5) == []
+ # Past the output window, so this is where the settle timer actually starts.
+ assert watcher.poll(registry, now=1010.0) == []
- filed = watcher.poll(registry, now=1002.5 + notifications.SETTLE_S + 1)
+ filed = watcher.poll(registry, now=1010.0 + notifications.SETTLE_S + 1)
assert [entry.kind for entry in filed] == ["completed"]
@@ -199,7 +327,8 @@ async def test_a_pane_at_its_prompt_reads_as_waiting(
_session, term = await _pane(registry, tmp_path)
_draw(term, IDLE_SCREEN)
- assert read_activity(term) == "waiting"
+ _quiet_since(term, 1000.0)
+ assert read_activity(term, now=1030.0) == "waiting"
async def test_a_visible_question_reads_as_asking(registry: Registry, tmp_path: Path) -> None:
@@ -207,7 +336,8 @@ async def test_a_visible_question_reads_as_asking(registry: Registry, tmp_path:
_session, term = await _pane(registry, tmp_path)
_draw(term, QUESTION_SCREEN)
- assert read_activity(term) == "asking"
+ _quiet_since(term, 1000.0)
+ assert read_activity(term, now=1030.0) == "asking"
async def test_a_pane_with_no_agent_yet_is_not_idle(registry: Registry, tmp_path: Path) -> None:
@@ -225,17 +355,15 @@ async def test_a_pane_that_stops_working_is_reported_once(
watcher = notifications.watcher()
session, term = await _pane(registry, tmp_path)
- _draw(term, BUSY_SCREEN)
- assert watcher.poll(registry, now=100.0) == []
+ stopped = _busy(watcher, registry, term, start=100.0)
- # A real TUI repaints the row it drew the hint on; the fake screen is told
- # to do the same rather than letting the old row scroll along underneath.
- term.transcript.clear()
- _draw(term, IDLE_SCREEN)
- # Seen as settled, but not yet for long enough to be believed.
- assert watcher.poll(registry, now=101.0) == []
+ # The picture now stops changing. Standing still is not instantly "finished"
+ # — a pane between two steps looks exactly the same for a moment.
+ assert watcher.poll(registry, now=stopped + 1) == []
+ # Still enough to count as settled, but the settle window has not run.
+ assert watcher.poll(registry, now=stopped + STILL_S + 1) == []
- filed = watcher.poll(registry, now=100.0 + notifications.SETTLE_S + 2)
+ filed = watcher.poll(registry, now=stopped + STILL_S + notifications.SETTLE_S + 2)
assert [entry.kind for entry in filed] == ["completed"]
assert filed[0].pane == term.name
assert filed[0].workspace_id == session.id
@@ -251,19 +379,25 @@ async def test_only_observed_work_is_checkpointed_for_restart(
watcher = notifications.watcher()
_session, term = await _pane(registry, tmp_path)
- _draw(term, BUSY_SCREEN)
- watcher.poll(registry, now=100.0, emit=False)
+ stopped = _busy(watcher, registry, term, start=100.0)
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"
+ # The screen stops moving, but not for long enough yet: a pane between two
+ # steps must stay armed, or a restart would not offer to continue it.
term.transcript.clear()
_draw(term, IDLE_SCREEN)
- watcher.poll(registry, now=101.0, emit=False)
+ watcher.poll(registry, now=stopped + 1, 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)
+ # Two waits stack, and both are load-bearing: the screen has to stand still
+ # long enough to count as settled at all (STILL_S), and only then does the
+ # settle window for "this really is over" start running (SETTLE_S).
+ settled_at = stopped + STILL_S + 2
+ watcher.poll(registry, now=settled_at, emit=False)
+ watcher.poll(registry, now=settled_at + notifications.SETTLE_S + 1, emit=False)
assert term.resume_continuation_needed is False
assert watcher.take_resume_dirty() is True
@@ -274,13 +408,10 @@ async def test_a_question_clears_the_restart_checkpoint_immediately(
"""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)
+ stopped = _busy(watcher, registry, term, start=100.0)
watcher.take_resume_dirty()
- term.transcript.clear()
- _draw(term, QUESTION_SCREEN)
- watcher.poll(registry, now=101.0)
+ _rest(watcher, registry, term, QUESTION_SCREEN, at=stopped + 2)
assert term.resume_continuation_needed is False
assert watcher.take_resume_dirty() is True
@@ -337,10 +468,15 @@ async def test_a_question_is_reported_even_though_it_never_worked(
_draw(term, IDLE_SCREEN)
watcher.poll(registry, now=100.0)
+ # The question APPEARING is itself a screen change, so it settles like any
+ # other before it is believed.
term.transcript.clear()
_draw(term, QUESTION_SCREEN)
watcher.poll(registry, now=101.0)
- filed = watcher.poll(registry, now=101.0 + notifications.SETTLE_S + 1)
+ assert watcher.poll(registry, now=101.0 + STILL_S + 1) == []
+ filed = watcher.poll(
+ registry, now=101.0 + STILL_S + notifications.SETTLE_S + 2
+ )
assert [entry.kind for entry in filed] == ["needs_input"]
@@ -353,13 +489,11 @@ async def test_going_back_to_work_re_arms_the_report(
_session, term = await _pane(registry, tmp_path)
for round_start in (100.0, 500.0):
- term.transcript.clear()
- _draw(term, BUSY_SCREEN)
- watcher.poll(registry, now=round_start)
- term.transcript.clear()
- _draw(term, IDLE_SCREEN)
- watcher.poll(registry, now=round_start + 1)
- filed = watcher.poll(registry, now=round_start + notifications.SETTLE_S + 2)
+ stopped = _busy(watcher, registry, term, start=round_start)
+ watcher.poll(registry, now=stopped + STILL_S + 1)
+ filed = watcher.poll(
+ registry, now=stopped + STILL_S + notifications.SETTLE_S + 2
+ )
assert [entry.kind for entry in filed] == ["completed"], round_start
@@ -427,12 +561,9 @@ async def test_closing_a_workspace_takes_its_notifications_with_it(
"""Each entry is a "jump to this pane" button, and the panes have just died."""
watcher = notifications.watcher()
session, term = await _pane(registry, tmp_path)
- _draw(term, BUSY_SCREEN)
- watcher.poll(registry, now=100.0)
- term.transcript.clear()
- _draw(term, IDLE_SCREEN)
- watcher.poll(registry, now=101.0)
- watcher.poll(registry, now=100.0 + notifications.SETTLE_S + 2)
+ stopped = _busy(watcher, registry, term, start=100.0)
+ watcher.poll(registry, now=stopped + STILL_S + 1)
+ watcher.poll(registry, now=stopped + STILL_S + notifications.SETTLE_S + 2)
assert notifications.center().list() != []
await registry.end(session.id)
diff --git a/tests/unit/web/test_agentic_ide_pty_socket.py b/tests/unit/web/test_agentic_ide_pty_socket.py
index 338c7c8275..15c2441b2e 100644
--- a/tests/unit/web/test_agentic_ide_pty_socket.py
+++ b/tests/unit/web/test_agentic_ide_pty_socket.py
@@ -19,7 +19,7 @@ from typing import Any
import pytest
from jarvis.agentic_ide import session as session_mod
-from jarvis.agentic_ide.session import Registry
+from jarvis.agentic_ide.session import Registry, SessionError
from jarvis.ui.web import agentic_ide_routes as routes
from tests.fakes.fake_pty_manager import FakePtyManager
@@ -90,17 +90,50 @@ async def test_refused_handshake_is_recorded_not_only_closed(
assert any("Mika" in record.getMessage() for record in caplog.records)
+async def test_attach_before_the_workspace_is_open_asks_the_pane_to_wait(
+ registry: Registry,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """"Not yet" and "not here" are different answers, and this is the first.
+
+ No workspace is open, which is exactly what a full grid of panes runs into
+ for a second or two after the backend restarts. Answering 4404 here made
+ every one of them give up permanently and the workspace came back frozen, so
+ this case has a code of its own (4503) that means "come back". The record in
+ the log still names the pane either way.
+ """
+ monkeypatch.setattr(routes, "credentials_valid", lambda scope: True)
+ ws = FakeWebSocket(cols="80", rows="24")
+
+ with caplog.at_level(logging.INFO, logger=routes.__name__):
+ await routes.agentic_pty(ws, "Mika")
+
+ assert ws.closed == (4503, "not ready")
+ assert ws.sent and ws.sent[0]["t"] == "error"
+ logged = " ".join(record.getMessage() for record in caplog.records)
+ assert "Mika" in logged
+
+
async def test_failed_attach_is_recorded_with_pane_and_reason(
registry: Registry,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
- """A refused attach says which pane and why — in the log, not only on screen."""
+ """A refused attach says which pane and why — in the log, not only on screen.
+
+ This is the terminal failure, not the "try again" one above: a spawn that
+ will not come back. It is the case where nobody is hovering over the red
+ badge, because it tends to hit every pane at once.
+ """
monkeypatch.setattr(routes, "credentials_valid", lambda scope: True)
+
+ async def _refuse(*_args: Any, **_kwargs: Any) -> None:
+ raise SessionError("the session could not be started")
+
+ monkeypatch.setattr(registry, "attach", _refuse)
ws = FakeWebSocket(cols="80", rows="24")
- # No workspace is open, which is exactly what a pane reconnecting across a
- # backend restart runs into.
with caplog.at_level(logging.WARNING, logger=routes.__name__):
await routes.agentic_pty(ws, "Mika")