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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): tell the user which terminal stopped, and take them to it
Ruben Lütkebef7227c55a7
diff --git a/jarvis/agentic_ide/activity.py b/jarvis/agentic_ide/activity.pynew file mode 100644index 0000000000..7cceac5683--- /dev/null+++ b/jarvis/agentic_ide/activity.py@@ -0,0 +1,198 @@+"""Is this pane working, waiting for you, or done?++## The question this answers++A workspace is a wall of terminals, and the one thing the wall cannot tell you+at a glance is which of them stopped. A coding CLI that finishes a job does not+announce it: the spinner row disappears, the input box comes back, and the pane+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 read from the CLI's own interrupt hint. Every coding TUI+observed so far draws one while — and only while — it is busy: Claude Code+("esc to interrupt"), Codex ("Esc to interrupt"). It is the closest thing to a+protocol these products have, it means the same thing in all of them, and it is+drawn on the pane's own initiative rather than inferred by us.++**Idle time is not used**, and that is load-bearing. An agent thinking hard+about a large refactor prints nothing for minutes at a time, while a stalled+one may redraw its status bar every second — the same reasoning+:mod:`.interrupted` sets out. A silence timer would report both wrongly.++**A finished pane is not read from its text.** The rule is only ever "it was+drawing the interrupt hint 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.++## Honest limits++A CLI that draws no interrupt hint at all reads as ``waiting`` for its whole+life, so it produces no "finished" notification rather than a wrong one. A+plain shell pane is not an agent and is left out entirely by the caller.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any, Literal++if TYPE_CHECKING: # pragma: no cover - typing only+ from collections.abc import Sequence++#: 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.+#: ``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 interrupt hint a coding CLI draws while it is working, lower-cased.+#:+#: Shared rather than per-product on purpose: the wording is near-universal, and+#: splitting it per entry would mean a CLI registered tomorrow starting with an+#: empty set and never reporting that it finished anything. 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.+#:+#: 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.+ASK_FRAGMENTS: tuple[str, ...] = (+ "do you want",+ "would you like",+ "(y/n)",+ "[y/n]",+ "yes/no",+ "press enter to continue",+ "continue? ",+ "1. yes",+ "❯ 1.",+ "> 1.",+ "needs authentication",+ "waiting for your",+ "select an option",+ "choose an option",+ "confirm",+ "approve",+)+++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.++ 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+ precisely the signal here.+ """+ transcript = getattr(term, "transcript", None)+ screen = getattr(transcript, "screen", None)+ try:+ 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:]]+++def _contains(rows: Sequence[str], fragments: Sequence[str]) -> bool:+ return any(fragment in row for row in rows for fragment in fragments)+++def read_activity(term: Any) -> 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``.+ """+ status = str(getattr(term, "status", "") or "pending")+ if status == "error":+ return "failed"+ if status == "exited":+ return "exited"+ if status != "live" or not getattr(term, "pty_id", None):+ # Still waiting for a cold-start slot, or between processes. Not idle:+ # a pane that has not started has not finished anything either.+ return "starting"++ rows = _visible_rows(term)+ if _contains(rows, (*BUSY_FRAGMENTS, *_extra_busy_fragments(getattr(term, "agent", "")))):+ return "working"+ if _contains(rows, ASK_FRAGMENTS):+ return "asking"+ return "waiting"+++#: The activities that mean "nobody is waiting on this pane's agent right now".+#: A transition INTO one of these, out of ``working``, is what the user wanted+#: to be told about.+SETTLED: frozenset[str] = frozenset({"waiting", "asking"})+++def is_settled(activity: str) -> bool:+ """Has this pane stopped working (as opposed to never having started)?"""+ return activity in SETTLED+++__all__ = [+ "ASK_FRAGMENTS",+ "BUSY_FRAGMENTS",+ "SETTLED",+ "TAIL_ROWS",+ "Activity",+ "is_settled",+ "read_activity",+]diff --git a/jarvis/agentic_ide/notifications.py b/jarvis/agentic_ide/notifications.pynew file mode 100644index 0000000000..6a226571a4--- /dev/null+++ b/jarvis/agentic_ide/notifications.py@@ -0,0 +1,514 @@+"""Tell the user when a pane stopped needing them to watch it.++## The gap this closes++A workspace runs up to a dozen coding agents at once, in panes the size of a+postcard. Each of them works for anything between twenty seconds and half an+hour, and none of them says when it is done — the spinner row simply stops+being drawn. So the only way to know that the agent you are waiting for has+finished is to keep looking at the wall, and the actual outcome is that work+sits finished and unread for as long as it takes the user to notice.++This module watches every pane in every open workspace, notices the moment one+stops working, and files a short entry saying so. The bell in the IDE header+carries the count; the panel behind it lists the entries and jumps to the pane+that raised each one.++## What it will and will not claim++Four kinds, and each one is something the pane itself established:++* ``completed`` — it was working, and it is not any more.+* ``needs_input`` — it is not working and there is a question on its screen.+* ``exited`` — its process is gone (with the exit code, if there was one).+* ``failed`` — its agent could not be started at all.++Nothing here reads the agent's prose to decide whether the job went well: a+"completed" entry means the pane went quiet, never that the work is correct.+That distinction is in the wording the UI shows, because promising the second+one would be a lie the module is in no position to tell.++## Why a debounce, and why it is the whole trick++A coding TUI drops its interrupt hint for a moment between steps — while it+waits for a permission answer, or repaints between tool calls. Reporting the+first frame in which the hint is absent would file "finished" several times per+minute for a pane that is working normally. So a pane has to have been settled+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++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.++## Where it runs++One sweep task per registry, started when the first workspace opens and+finishing by itself once the last one closes (AP-26: nothing new on the boot+path — with no workspace open, nothing here runs at all). The poll itself reads+each pane's replayed screen, which is a list of at most a few dozen strings, so+a dozen panes cost microseconds every couple of seconds.+"""++from __future__ import annotations++import asyncio+import time+from collections import deque+from dataclasses import dataclass, field+from itertools import count+from typing import TYPE_CHECKING, Any, Literal++from loguru import logger++from .activity import Activity, is_settled, read_activity++if TYPE_CHECKING: # pragma: no cover - typing only+ from collections.abc import Iterable++ from .session import Registry++#: What one entry is about.+Kind = Literal["completed", "needs_input", "exited", "failed"]++#: How long a pane must have been settled before its stop is reported. Long+#: enough to sit out the gap a TUI leaves between two steps, short enough that+#: the bell is still news — see the module docstring.+SETTLE_S = 5.0++#: How often every pane is looked at. The read is a few string scans per pane,+#: so this is about how quickly the bell should react, not about cost.+SWEEP_INTERVAL_S = 2.0++#: How many entries are kept. A heavy day across six workspaces produces a few+#: dozen; past this the oldest fall off the back, which is the right end to lose+#: — the panes they point at are the ones most likely to be gone.+MAX_ENTRIES = 200++#: How long the config switch is trusted before it is read from disk again.+#: ``load_config`` parses the TOML on every call, and the sweep runs every two+#: seconds; re-reading it each time would put a file read on the event loop for+#: a value that changes about once a year.+SWITCH_TTL_S = 15.0++#: How much of the pane's own recap travels with an entry — one line under the+#: headline, not a paragraph.+DETAIL_CHARS = 160++_ids = count(1)+++@dataclass(frozen=True, slots=True)+class Notification:+ """One thing that happened in one pane."""++ id: str+ kind: Kind+ #: Which workspace it happened in, and what that tab is called — an entry+ #: list spans every open workspace, so a pane call-sign alone ("T3") does+ #: not identify anything.+ workspace_id: str+ workspace: str+ pane_key: str+ pane: str+ agent: str+ display_name: str+ #: One clause: what happened. Written here rather than in the client so the+ #: CLI and the UI say the same thing.+ title: str+ #: What the pane was doing, from its own recap. May be empty.+ detail: str+ created_at: float+ read: bool = False++ def to_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "kind": self.kind,+ "workspace_id": self.workspace_id,+ "workspace": self.workspace,+ "pane_key": self.pane_key,+ "pane": self.pane,+ "agent": self.agent,+ "display_name": self.display_name,+ "title": self.title,+ "detail": self.detail,+ "created_at": self.created_at,+ "read": self.read,+ }+++class NotificationCenter:+ """The bounded list of entries, newest first.++ Not thread-safe and deliberately so: everything that touches it runs on the+ event loop — the sweep task that files entries and the routes that read+ them.+ """++ def __init__(self, limit: int = MAX_ENTRIES) -> None:+ self._entries: deque[Notification] = deque(maxlen=limit)++ def add(self, entry: Notification) -> Notification:+ self._entries.append(entry)+ return entry++ def list(self) -> list[Notification]:+ """Newest first — the order the panel renders."""+ return list(reversed(self._entries))++ @property+ def unread(self) -> int:+ return sum(1 for entry in self._entries if not entry.read)++ def mark_read(self, ids: Iterable[str] | None = None) -> int:+ """Mark the given entries read; without ids, every one of them.++ Returns how many CHANGED, so a caller can tell "there was nothing to+ do" from "four were cleared" instead of guessing from the new count.+ """+ wanted = None if ids is None else {str(i) for i in ids}+ changed = 0+ for index, entry in enumerate(self._entries):+ if entry.read or (wanted is not None and entry.id not in wanted):+ continue+ # Frozen on purpose — the entry is replaced rather than mutated, so+ # a list handed out earlier keeps saying what it said.+ self._entries[index] = Notification(**{**entry.to_dict(), "read": True})+ changed += 1+ return changed++ def clear(self, ids: Iterable[str] | None = None) -> int:+ """Drop the given entries; without ids, all of them."""+ if ids is None:+ dropped = len(self._entries)+ self._entries.clear()+ return dropped+ wanted = {str(i) for i in ids}+ kept = [entry for entry in self._entries if entry.id not in wanted]+ dropped = len(self._entries) - len(kept)+ self._entries.clear()+ self._entries.extend(kept)+ return dropped++ def forget_workspace(self, workspace_id: str) -> int:+ """Drop the entries of a workspace that has been closed.++ Their "jump to pane" cannot be honoured any more, and an entry that+ silently does nothing when pressed is worse than one that is gone.+ """+ return self.clear(+ entry.id for entry in self._entries if entry.workspace_id == workspace_id+ )+++@dataclass(slots=True)+class _PaneWatch:+ """What one pane was last seen doing, and whether that was reported."""++ activity: Activity+ since: float+ #: Has this pane been working since the last entry was filed for it? What+ #: makes "it finished" different from "it has been idle all along".+ worked: bool = False+ #: Already reported for the CURRENT episode. Cleared when the pane changes+ #: state, so the next stop is reported again.+ announced: bool = False+++def _detail(term: Any) -> str:+ """One line about what the pane was doing, from state it already keeps."""+ text = " ".join(str(getattr(term, "last_prompt", "") or "").split())+ if not text:+ return ""+ return text if len(text) <= DETAIL_CHARS else f"{text[:DETAIL_CHARS].rsplit(' ', 1)[0]}…"+++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.+ """+ if kind == "completed":+ return "Finished and waiting at its prompt"+ if kind == "needs_input":+ return "Waiting for your answer"+ if kind == "failed":+ problem = " ".join(str(getattr(term, "error", "") or "").split())+ return f"Could not start — {problem}" if problem else "Its agent could not be started"+ code = getattr(term, "exit_code", None)+ if code in (0, None):+ return "Its agent exited"+ return f"Its agent exited with code {code}"+++class ActivityWatcher:+ """Turns pane state transitions into notifications, one sweep at a time.++ Split from the sweep task so the whole decision — what counts as a stop,+ when it is reported, and what it is called — is a plain synchronous function+ of (panes, clock) and can be tested without a PTY, a loop, or a wait.+ """++ def __init__(self, center: NotificationCenter) -> None:+ self.center = center+ self._panes: dict[tuple[str, str], _PaneWatch] = {}++ 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]:+ """Look at every pane once and file whatever has just happened."""+ moment = time.time() if now is None else now+ filed: list[Notification] = []+ alive: set[tuple[str, str]] = set()++ for session in registry.sessions:+ for term in session.terminals:+ if not _is_agent(term):+ # A plain shell has no notion of finishing a job — it sits+ # at a prompt for its whole life, which would file an entry+ # the moment it is opened and never again.+ continue+ ident = (session.id, str(getattr(term, "key", "") or ""))+ alive.add(ident)+ entry = self._step(session, term, ident, moment)+ if entry is not None:+ filed.append(entry)++ # Panes that were closed take their memory with them, or a workspace+ # cycled often enough would grow this dict without bound.+ for gone in self._panes.keys() - alive:+ del self._panes[gone]+ return filed++ def _step(+ self, session: Any, term: Any, ident: tuple[str, str], now: float+ ) -> Notification | None:+ activity = read_activity(term)+ 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)+ return None++ if activity != watch.activity:+ if watch.activity == "working":+ watch.worked = True+ watch.activity = activity+ watch.since = now+ watch.announced = False++ if watch.announced:+ return None++ kind = self._kind(activity, watch)+ if kind is None:+ return None+ # A pane that merely STOPPED has to hold still first — see the module+ # docstring on the gap a TUI leaves between two steps. A dead or broken+ # one is news immediately: there is no repaint gap to sit out, and the+ # state cannot flip back on its own.+ if is_settled(activity) and now - watch.since < SETTLE_S:+ return None++ watch.announced = True+ watch.worked = False+ return self.center.add(+ Notification(+ id=f"n{next(_ids)}",+ kind=kind,+ workspace_id=str(session.id),+ workspace=str(getattr(session, "name", "") or ""),+ pane_key=ident[1],+ pane=str(getattr(term, "name", "") or ""),+ agent=str(getattr(term, "agent", "") or ""),+ display_name=str(getattr(term, "display_name", "") or ""),+ title=_title(kind, term),+ detail=_detail(term),+ created_at=now,+ )+ )++ @staticmethod+ def _kind(activity: Activity, watch: _PaneWatch) -> Kind | None:+ """Which entry this state deserves, or none at all."""+ if activity == "failed":+ return "failed"+ if activity == "exited":+ return "exited"+ if activity == "asking":+ # Reported whether or not it worked first: a question is the pane+ # asking for the user by name, and a CLI that asks one at startup+ # (an unauthenticated MCP server, a trust prompt) has never worked.+ return "needs_input"+ if activity == "waiting" and watch.worked:+ return "completed"+ return None+++def _is_agent(term: Any) -> bool:+ """Does this pane run an agent, rather than being a bare shell?"""+ try:+ from .session import accepts_prompts++ return bool(accepts_prompts(str(getattr(term, "agent", "") or "")))+ except Exception: # noqa: BLE001 - a sweep must never fail on a lookup+ return True+++# --------------------------------------------------------------------- switch+_switch: tuple[float, bool] = (0.0, True)+++def enabled() -> bool:+ """Is pane notification switched on for this install?++ Cached briefly (:data:`SWITCH_TTL_S`) rather than read per sweep: the value+ lives in ``jarvis.toml``, ``load_config`` parses that file on every call,+ and this runs every couple of seconds. A config that cannot be read at all+ answers "on" — the feature is additive, and failing closed here would make a+ broken config look like a broken bell.+ """+ global _switch+ cached_at, value = _switch+ now = time.monotonic()+ if now - cached_at < SWITCH_TTL_S:+ return value+ try:+ from jarvis.core.config import load_config++ value = bool(getattr(load_config().agentic_ide, "pane_notifications", True))+ except Exception: # noqa: BLE001 - never let a config read stop the sweep+ value = True+ _switch = (now, value)+ return value+++def reset_switch_cache() -> None:+ """Forget the cached switch — for tests, and for a live config change."""+ global _switch+ _switch = (0.0, True)+++# ---------------------------------------------------------------------- store+_CENTER = NotificationCenter()+_WATCHER = ActivityWatcher(_CENTER)+++def center() -> NotificationCenter:+ """The process-wide store the routes read."""+ return _CENTER+++def watcher() -> ActivityWatcher:+ """The process-wide watcher the sweep drives."""+ return _WATCHER+++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+ reset_switch_cache()+++@dataclass(slots=True)+class _Sweep:+ """The one background task, and the handle that keeps it single."""++ task: asyncio.Task[None] | None = field(default=None)+++_sweep = _Sweep()+++async def _run(registry: Registry) -> None:+ """Poll until the last workspace closes, then finish.++ Self-terminating rather than cancelled from the outside: closing a workspace+ happens in several places, and a task that has to be stopped by each of them+ is a task that outlives one of them. With no workspace open there is nothing+ to watch, and the next ``start`` brings it back.+ """+ try:+ while True:+ await asyncio.sleep(SWEEP_INTERVAL_S)+ if not registry.sessions:+ return+ if not enabled():+ continue+ try:+ _WATCHER.poll(registry)+ 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+ raise+ finally:+ _sweep.task = None+++def start(registry: Registry) -> None:+ """Make sure the sweep is running for ``registry``. Idempotent.++ Called where a workspace is opened. Never on the boot path (AP-26): an+ install whose user has not opened the IDE runs none of this.+ """+ if _sweep.task is not None and not _sweep.task.done():+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ # No loop (a synchronous test, a CLI path). Nothing to schedule, and the+ # feature is additive — the routes still answer from an empty store.+ return+ _sweep.task = loop.create_task(_run(registry), name="agentic-ide-notifications")+++def stop() -> None:+ """Cancel the sweep — for tests and for a full shutdown."""+ task = _sweep.task+ _sweep.task = None+ if task is not None and not task.done():+ task.cancel()+++def state() -> dict[str, Any]:+ """Everything the bell needs in one response."""+ entries = _CENTER.list()+ return {+ "enabled": enabled(),+ "unread": sum(1 for entry in entries if not entry.read),+ "notifications": [entry.to_dict() for entry in entries],+ }+++__all__ = [+ "DETAIL_CHARS",+ "MAX_ENTRIES",+ "SETTLE_S",+ "SWEEP_INTERVAL_S",+ "ActivityWatcher",+ "Kind",+ "Notification",+ "NotificationCenter",+ "center",+ "enabled",+ "reset",+ "reset_switch_cache",+ "start",+ "state",+ "stop",+ "watcher",+]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex f853a0eeb6..ea52603d20 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -1569,6 +1569,16 @@ class Registry:file_index.prime_index(str(root))except Exception as exc: # noqa: BLE001 - the index is a conveniencelogger.warning("Agentic IDE: file index not primed: {}", exc)+ # Start watching the panes for the moment they stop working. Here rather+ # than at boot (AP-26): an install whose user never opens the IDE never+ # runs the sweep at all, and the sweep finishes by itself once the last+ # workspace closes.+ try:+ from . import notifications++ notifications.start(self)+ except Exception as exc: # noqa: BLE001 - the bell is additive+ logger.warning("Agentic IDE: pane notifications not started: {}", exc)await self._persist()return session@@ -1969,6 +1979,17 @@ class Registry:manager.close(term.pty_id)except Exception: # noqa: BLE001, S110 - best-effort teardownpass+ # Its pane notifications go with it. Each one is a "jump to this pane"+ # button, and the panes have just been killed — an entry that quietly+ # does nothing when pressed is worse than one that is gone.+ try:+ from . import notifications++ notifications.center().forget_workspace(workspace_id)+ notifications.watcher().forget_workspace(workspace_id)+ except Exception as exc: # noqa: BLE001 - teardown must not fail on this+ logger.warning("Agentic IDE: could not clear notifications for a closed tab: {}", exc)+# Drop THIS folder's codebase index. A blanket reset would take the# other open workspaces' indexes with it and silently cost them their# `@file` suggestions.diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 393bcec607..7cb9a24c45 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -3167,6 +3167,16 @@ class AgenticIdeConfig(BaseModel):),)+ pane_notifications: bool = Field(+ default=True,+ description=(+ "Collect a notification whenever a terminal stops working, asks a "+ "question, or its agent exits — the bell in the Agentic IDE header. "+ "Off stops the background sweep entirely; the bell then only shows "+ "what was already collected."+ ),+ )+@field_validator("prompt_writer", mode="before")@classmethoddef _usable_writer(cls, value: object) -> str:diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex bbd2dc52fb..832f1a9b33 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -64,6 +64,7 @@ from jarvis.agentic_ide import (drops,interrupted,native_picker,+ notifications,recap_engine,recents,resume_store,@@ -691,6 +692,64 @@ class InterruptedPane(BaseModel):)+class PaneNotification(BaseModel):+ """One thing that happened in one pane, as the bell lists it."""++ id: str+ kind: str = Field(+ description=(+ "What happened: 'completed' (it was working and stopped), "+ "'needs_input' (a question is on its screen), 'exited' (its process "+ "is gone) or 'failed' (its agent could not be started)."+ )+ )+ workspace_id: str+ workspace: str = Field(default="", description="What that workspace tab is called.")+ pane_key: str+ pane: str = Field(default="", description="The pane's call-sign — 'T3'.")+ agent: str = Field(default="", description="The coding CLI's id.")+ display_name: str = Field(default="", description="What the user reads — 'Claude Code'.")+ title: str = Field(+ default="",+ description=(+ "One clause saying what happened. 'Finished' means the pane went "+ "quiet, never that the work is correct — nothing here reads the "+ "agent's output to judge its result."+ ),+ )+ detail: str = Field(default="", description="What the pane was last asked to do.")+ created_at: float+ read: bool = False+++class PaneNotificationsResponse(BaseModel):+ """The bell's whole state in one answer."""++ enabled: bool = Field(+ default=True,+ description=(+ "Is the background sweep collecting new entries? False when "+ "[agentic_ide].pane_notifications is off — the list then only holds "+ "what was collected before."+ ),+ )+ unread: int = 0+ notifications: list[PaneNotification] = Field(default_factory=list)+++class ReadNotificationsRequest(BaseModel):+ ids: list[str] = Field(+ default_factory=list,+ description="Entries to mark read. Empty marks every one of them.",+ )+++class NotificationsChangedResponse(BaseModel):+ ok: bool = True+ changed: int = Field(default=0, description="How many entries this call actually altered.")+ unread: int = 0++class InterruptedResponse(BaseModel):"""Every pane, in every open workspace, that is waiting to be told to carry on."""@@ -1429,6 +1488,81 @@ async def continue_interrupted(req: ContinueInterruptedRequest) -> ContinueInter)+ "/notifications",+ response_model=PaneNotificationsResponse,+ summary="Terminals that finished, asked something, or stopped",+)+async def get_notifications() -> PaneNotificationsResponse:+ """What the bell in the Agentic-IDE header is showing.++ Newest first, across EVERY open workspace — a pane in a background tab is+ exactly the one whose finishing nobody would otherwise notice. Each entry+ names its workspace and its call-sign, which is what the client's "jump to+ pane" needs to switch tabs before it scrolls.++ A ``completed`` entry means the pane stopped drawing the interrupt hint its+ CLI draws while it is busy. That is a claim about the terminal, not about+ the work: nothing here reads the agent's output to decide whether the job+ went well.++ Entries live in memory and go with the workspace they belong to. A restart+ empties the list on purpose — the panes it pointed at are gone.+ """+ return PaneNotificationsResponse(**notifications.state())+++ "/notifications/read",+ response_model=NotificationsChangedResponse,+ summary="Mark terminal notifications as read",+)+async def read_notifications(req: ReadNotificationsRequest) -> NotificationsChangedResponse:+ """Clear the unread count, for the given entries or for all of them.++ The entries stay in the list — this only stops the bell from counting them.+ ``changed`` is how many were actually unread, so "there was nothing to do"+ is distinguishable from "four were cleared".+ """+ center = notifications.center()+ changed = center.mark_read(req.ids or None)+ return NotificationsChangedResponse(changed=changed, unread=center.unread)+++ "/notifications",+ response_model=NotificationsChangedResponse,+ summary="Discard every terminal notification",+)+async def clear_notifications() -> NotificationsChangedResponse:+ """Throw the whole list away.++ Nothing about a pane changes: an entry is a note that something happened,+ and discarding it stops the note being shown. Every agent it came from+ keeps running exactly as it was.+ """+ center = notifications.center()+ dropped = center.clear()+ return NotificationsChangedResponse(changed=dropped, unread=center.unread)+++ "/notifications/{notification_id}",+ response_model=NotificationsChangedResponse,+ summary="Discard one terminal notification",+)+async def clear_notification(notification_id: str) -> NotificationsChangedResponse:+ """Throw one entry away. An id that is not in the list is a quiet no-op.++ Not a 404: the entry may have gone with its workspace between the client+ reading the list and pressing the button, and the outcome the caller wanted+ — that entry is not there — is the one they got.+ """+ center = notifications.center()+ dropped = center.clear([notification_id])+ return NotificationsChangedResponse(changed=dropped, unread=center.unread)++@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.tsxindex 75b389615a..e930c52eef 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx@@ -58,6 +58,16 @@ vi.mock("@/lib/agenticIdeApi", () => ({panes: [],})),continueInterrupted: vi.fn(),+ // Polled by the header bell, which the grid also always renders. Answers+ // "nothing has stopped" so these tests see a plain toolbar rather than a+ // badge none of them are about.+ fetchPaneNotifications: vi.fn(async () => ({+ enabled: true,+ unread: 0,+ notifications: [],+ })),+ markPaneNotificationsRead: vi.fn(async () => 0),+ clearPaneNotifications: vi.fn(async () => undefined),}));// The grid follows the app theme for its terminal colours; these tests render@@ -540,6 +550,51 @@ describe("grid layout", () => {});});+describe("jump to pane", () => {+ /*+ * What a notification is FOR. An entry says "T3 finished" and the only useful+ * next move is to read T3 — which in a grid of twelve means making it big+ * enough to read. A jump that merely scrolled would land the user back in+ * front of the postcard they could not read in the first place.+ */+ it("maximizes the pane it was asked for", () => {+ const panes = Array.from({ length: 12 }, (_, i) => [`T${i + 1}`, i] as [string, number]);+ const { rerender } = renderGrid(sessionWith(panes));++ rerender({ jumpTo: { pane: "T7", nonce: 1 } });++ expect(screen.getByTestId("pane-T7").getAttribute("data-maximized")).toBe("yes");+ // ...and the eleven it covers are hidden rather than unmounted — the same+ // rule as an ordinary maximize, because unmounting kills the agent.+ expect(screen.getByTestId("pane-T2").parentElement?.className).toContain("hidden");+ });++ it("can be sent to the same pane twice", () => {+ // The nonce is the whole reason the prop is an object: an effect cannot+ // re-fire on a value that has not changed, so a second jump to the pane the+ // user has since restored would silently do nothing.+ const { rerender } = renderGrid();+ rerender({ jumpTo: { pane: "Nova", nonce: 1 } });+ fireEvent.click(screen.getByTestId("pane-maximize-Nova"));+ expect(screen.getByTestId("pane-Nova").getAttribute("data-maximized")).toBe("no");++ rerender({ jumpTo: { pane: "Nova", nonce: 2 } });++ expect(screen.getByTestId("pane-Nova").getAttribute("data-maximized")).toBe("yes");+ });++ it("says so rather than maximizing a stranger when the pane is gone", () => {+ // An entry outlives the terminal it came from by up to one poll, and pane+ // names are reused: "whatever is called T4 now" is the wrong terminal.+ const { rerender } = renderGrid();++ rerender({ jumpTo: { pane: "Ghost", nonce: 1 } });++ expect(screen.getByTestId("pane-Mika").getAttribute("data-maximized")).toBe("no");+ expect(pushToast).toHaveBeenCalledWith("warning", expect.stringContaining("Ghost"));+ });+});+describe("maximize", () => {it("hides the other panes without unmounting them", () => {// Unmounting would tear down the WebSocket and kill the agent, so the otherdiff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex 1e0ee68dcc..cb327bda6b 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -68,6 +68,7 @@ import {} from "./paneLayout";import { usePaneWeights } from "./usePaneWeights";import { ContinueInterrupted } from "./ContinueInterrupted";+import { PaneNotifications } from "./PaneNotifications";import { PromptPreview } from "./PromptPreview";import { WorkspaceSettings } from "./WorkspaceSettings";import { usePaneFileDrag } from "./paneFileDrag";@@ -95,6 +96,7 @@ import {type DropAttachment,type IdeAccountState,type IdeState,+ type PaneNotification,type SessionState,type TerminalRecap,} from "@/lib/agenticIdeApi";@@ -152,6 +154,29 @@ interface AgenticGridProps {* a frontend change reaches the user through that Restart button.*/appActions?: React.ReactNode;+ /**+ * Take the user to a pane in ANOTHER workspace, on behalf of the header bell.+ *+ * A notification list spans every open tab — a pane in a background workspace+ * is precisely the one whose finishing nobody would otherwise notice — so+ * "jump to pane" sometimes means switching tab first. This grid cannot do+ * that: it is keyed by workspace and is replaced when one is switched to. The+ * view above owns both halves and hands the pane back through `jumpTo`.+ *+ * Left out, an entry from another workspace still lists; pressing its jump+ * does nothing rather than lying about where it went.+ */+ onJumpToWorkspace?: (workspaceId: string, pane: string) => void;+ /**+ * "Maximize this pane and scroll to it" — set by the view after a cross-+ * workspace jump has landed.+ *+ * Carries a `nonce` because the same pane may be jumped to twice in a row,+ * and a value that has not changed cannot re-fire an effect. It is not a+ * state the grid holds: acting on it is a one-shot, and what stays afterwards+ * is an ordinary maximized pane the user can restore themselves.+ */+ jumpTo?: { pane: string; nonce: number } | null;}const FONT_MIN = 10;@@ -402,6 +427,8 @@ export function AgenticGrid({onStateChanged,workspaceBar,appActions,+ onJumpToWorkspace,+ jumpTo = null,onScreen = true,}: AgenticGridProps) {const t = useT();@@ -963,6 +990,64 @@ export function AgenticGrid({return () => window.clearTimeout(timer);}, [session.terminals]);+ /*+ * "Jump to pane" — from the header bell, or from the view after a tab switch.+ *+ * Three things, in this order: the pane is maximized, it is scrolled to, and+ * it wears the same arrival ring a freshly opened pane does. Maximizing is+ * what the user asked for — a notification about a pane is a request to READ+ * that pane, and reading a postcard-sized terminal in a grid of twelve is the+ * problem, not the answer. The ring covers the case where the pane was+ * already the maximized one and nothing visibly moved.+ *+ * Silently ignored for a pane that is no longer here: an entry outlives the+ * terminal it came from by up to one poll, and a stray maximize of "whatever+ * is called T4 now" would be worse than nothing happening.+ */+ const [jump, setJump] = useState<{ pane: string; nonce: number } | null>(null);+ // One request from two sources: the bell in this header (same workspace) and+ // the view above it (after a tab switch). Both land in one place so the+ // acting effect below has a single trigger to watch.+ useEffect(() => {+ if (jumpTo) setJump(jumpTo);+ }, [jumpTo]);++ useEffect(() => {+ const wanted = jump?.pane;+ if (!wanted) return;+ if (!session.terminals.some((term) => term.name === wanted)) {+ // The entry outlives the terminal it came from by up to one poll. Say so+ // rather than maximizing whatever is called T4 now.+ pushToast("warning", t("agentic_grid.notifications.gone").replace("{0}", wanted));+ return;+ }+ setMaximized(wanted);+ setJustOpened(new Set([wanted]));+ const node = paneNodes.current.get(wanted);+ // Probed rather than assumed — `scrollIntoView` is absent in jsdom and in+ // some embedded WebViews, and a maximized pane fills the grid anyway.+ if (typeof node?.scrollIntoView === "function") {+ node.scrollIntoView({ block: "nearest", behavior: "smooth" });+ }+ const timer = window.setTimeout(() => setJustOpened(new Set()), 2600);+ return () => window.clearTimeout(timer);+ // `session.terminals` deliberately absent: this fires on a JUMP, not every+ // time a pane opens or closes underneath one.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [jump]);++ /** Where the bell's "jump to pane" goes — here, or via the view for a tab. */+ const jumpToNotification = useCallback(+ (entry: PaneNotification) => {+ if (entry.workspace_id && entry.workspace_id !== session.id) {+ onJumpToWorkspace?.(entry.workspace_id, entry.pane);+ return;+ }+ setJump({ pane: entry.pane, nonce: Date.now() });+ },+ [onJumpToWorkspace, session.id],+ );+/** When a pane may be picked up at all.*@@ -1270,6 +1355,13 @@ export function AgenticGrid({</button></div>+ {/* Which terminals stopped while you were looking at another one.+ Before "Continue" rather than after it, because the two answer the+ same question at different scales — this one is "what happened",+ that one is "what should start again" — and reading them in that+ order is how somebody decides they need the second at all. */}+ <PaneNotifications onJump={jumpToNotification} onScreen={onScreen} />+{/* Work a restart stopped: which panes came back holding a conversationand were never told to carry on, and the one click that tells them.The pane headers catch up on their own — a continued agent startsdiff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.test.tsxnew file mode 100644index 0000000000..73927549ca--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.test.tsx@@ -0,0 +1,213 @@+/**+ * Component tests for the header bell.+ *+ * The feature is not the list, it is the four things around it, and each one has+ * an obvious wrong implementation:+ *+ * 1. The badge is the whole point of a bell — it has to appear with a count and+ * go away once the panel has been looked at, or nothing on screen ever says+ * a terminal stopped.+ * 2. "Jump to pane" has to hand the ENTRY back, not a name. An entry from+ * another workspace needs its workspace id, and a caller that only receives+ * "T3" cannot switch tab to the right one.+ * 3. Discarding must clear on screen immediately. It is a delete button, and one+ * that waits for a round-trip reads as a broken one.+ * 4. An empty bell and a switched-off bell must not look the same, or "nothing+ * is arriving" has no visible cause.+ */+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", () => ({+ fetchPaneNotifications: vi.fn(),+ markPaneNotificationsRead: vi.fn(),+ clearPaneNotifications: vi.fn(),+}));++import { PaneNotifications, ago } from "./PaneNotifications";+import {+ clearPaneNotifications,+ fetchPaneNotifications,+ markPaneNotificationsRead,+ type PaneNotification,+ type PaneNotificationsState,+} from "@/lib/agenticIdeApi";++function entry(over: Partial<PaneNotification> = {}): PaneNotification {+ return {+ id: "n1",+ kind: "completed",+ workspace_id: "ide_1",+ workspace: "Personal Jarvis",+ pane_key: "t1",+ pane: "T1",+ agent: "claude",+ display_name: "Claude Code",+ title: "Finished and waiting at its prompt",+ detail: "rewrite the resume store",+ created_at: Date.now() / 1000 - 180,+ read: false,+ ...over,+ };+}++function state(entries: PaneNotification[], over: Partial<PaneNotificationsState> = {}) {+ return {+ enabled: true,+ unread: entries.filter((e) => !e.read).length,+ notifications: entries,+ ...over,+ };+}++const fetchMock = vi.mocked(fetchPaneNotifications);+const readMock = vi.mocked(markPaneNotificationsRead);+const clearMock = vi.mocked(clearPaneNotifications);++beforeEach(() => {+ vi.clearAllMocks();+ fetchMock.mockResolvedValue(state([]));+ readMock.mockResolvedValue(0);+ clearMock.mockResolvedValue(undefined);+});++afterEach(cleanup);++async function open() {+ const bell = await screen.findByTestId("pane-notifications-bell");+ fireEvent.click(bell);+ return screen.findByTestId("pane-notifications-panel");+}++describe("the bell", () => {+ it("shows a count when terminals have stopped and nobody has looked", async () => {+ fetchMock.mockResolvedValue(state([entry(), entry({ id: "n2", pane: "T2" })]));+ render(<PaneNotifications onJump={vi.fn()} />);++ const badge = await screen.findByTestId("pane-notifications-count");+ expect(badge.textContent).toBe("2");+ });++ it("stays quiet with nothing to report", async () => {+ render(<PaneNotifications onJump={vi.fn()} />);++ await screen.findByTestId("pane-notifications-bell");+ expect(screen.queryByTestId("pane-notifications-count")).toBeNull();+ });++ it("clears the count once the panel has been opened", async () => {+ fetchMock.mockResolvedValue(state([entry()]));+ render(<PaneNotifications onJump={vi.fn()} />);+ await screen.findByTestId("pane-notifications-count");++ await open();++ await waitFor(() => expect(readMock).toHaveBeenCalled());+ await waitFor(() =>+ expect(screen.queryByTestId("pane-notifications-count")).toBeNull(),+ );+ });+});++describe("the panel", () => {+ it("says which pane and what happened, not just that something did", async () => {+ fetchMock.mockResolvedValue(state([entry()]));+ render(<PaneNotifications onJump={vi.fn()} />);++ const panel = await open();++ expect(panel.textContent).toContain("T1");+ expect(panel.textContent).toContain("Finished and waiting at its prompt");+ // The workspace travels too: a call-sign counts from T1 in every tab.+ expect(panel.textContent).toContain("Personal Jarvis");+ });++ it("hands the whole entry to the jump, so another workspace can be reached", async () => {+ const onJump = vi.fn();+ const other = entry({ id: "n9", workspace_id: "ide_other", pane: "T4" });+ fetchMock.mockResolvedValue(state([other]));+ render(<PaneNotifications onJump={onJump} />);+ await open();++ fireEvent.click(await screen.findByTestId("pane-notification-jump"));++ expect(onJump).toHaveBeenCalledWith(expect.objectContaining({+ workspace_id: "ide_other",+ pane: "T4",+ }));+ // And it gets out of the way — the jump is about seeing the grid.+ await waitFor(() =>+ expect(screen.queryByTestId("pane-notifications-panel")).toBeNull(),+ );+ });++ it("removes a discarded entry immediately rather than after the round-trip", async () => {+ let resolveDelete: () => void = () => {};+ clearMock.mockImplementation(+ () => new Promise<void>((resolve) => (resolveDelete = resolve)),+ );+ fetchMock.mockResolvedValue(state([entry(), entry({ id: "n2", pane: "T2" })]));+ render(<PaneNotifications onJump={vi.fn()} />);+ await open();+ expect(screen.getAllByTestId("pane-notification")).toHaveLength(2);++ fireEvent.click(screen.getAllByTestId("pane-notification-discard")[0]);++ await waitFor(() =>+ expect(screen.getAllByTestId("pane-notification")).toHaveLength(1),+ );+ resolveDelete();+ });++ it("empties on 'discard all'", async () => {+ fetchMock.mockResolvedValue(state([entry(), entry({ id: "n2" })]));+ render(<PaneNotifications onJump={vi.fn()} />);+ await open();++ fireEvent.click(screen.getByTestId("pane-notifications-clear"));++ await waitFor(() => expect(screen.getByTestId("pane-notifications-empty")).toBeTruthy());+ expect(clearMock).toHaveBeenCalledWith(undefined);+ });++ it("distinguishes 'nothing happened' from 'collection is switched off'", async () => {+ fetchMock.mockResolvedValue(state([], { enabled: false }));+ render(<PaneNotifications onJump={vi.fn()} />);++ const panel = await open();++ expect(panel.textContent).toContain("switched off");+ });++ it("labels each kind so a failure is not read as a success", async () => {+ fetchMock.mockResolvedValue(+ state([+ entry({ id: "a", kind: "needs_input" }),+ entry({ id: "b", kind: "failed" }),+ ]),+ );+ render(<PaneNotifications onJump={vi.fn()} />);++ const panel = await open();++ expect(panel.textContent).toContain("NEEDS INPUT");+ expect(panel.textContent).toContain("FAILED");+ });+});++describe("relative time", () => {+ it("reads in whatever unit keeps it short", () => {+ const now = 1_000_000_000_000;+ const at = now / 1000;+ expect(ago(at - 12, now)).toBe("12s ago");+ expect(ago(at - 180, now)).toBe("3m ago");+ expect(ago(at - 7200, now)).toBe("2h ago");+ expect(ago(at - 172_800, now)).toBe("2d ago");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.tsxnew file mode 100644index 0000000000..9d0af0c447--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneNotifications.tsx@@ -0,0 +1,475 @@+/**+ * The bell in the Agentic IDE header — "which of these terminals stopped?"+ *+ * ## The gap it closes+ *+ * A workspace is up to a dozen coding agents in panes the size of a postcard,+ * each working for anything between twenty seconds and half an hour. None of+ * them announces that it is done: the spinner row simply stops being drawn, and+ * a finished pane looks exactly like the eleven around it that are still+ * thinking. So the only way to know is to keep watching the wall — and the real+ * outcome is that work sits finished and unread until somebody happens to look.+ *+ * The bell counts what the backend noticed while nobody was looking; the panel+ * behind it lists the entries and takes you to the pane that raised each one.+ *+ * ## Why it opens as an anchored panel and not a modal+ *+ * The list exists to send you somewhere. A centred dialog with an overlay hides+ * the grid it is about, so "jump to T7" would mean reading a name, dismissing+ * the dialog, and finding T7 yourself. Anchored under the bell, the grid stays+ * visible behind it and the jump lands somewhere you can see happening.+ *+ * Rendered in a PORTAL for the same reason `PaneRecap` is: the header row is a+ * flex line of buttons that clips its own overflow, and a panel bounded by it+ * would be a few centimetres wide.+ *+ * ## What "read" means here+ *+ * Opening the panel marks everything read — the count is a "look at this",+ * and looking at it is the whole condition. The entries stay in the list until+ * they are discarded or their workspace closes, so nothing is lost by opening+ * it; only the badge goes quiet.+ */+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";+import { createPortal } from "react-dom";+import {+ AlertTriangle,+ Bell,+ CheckCircle2,+ CircleHelp,+ PowerOff,+ Trash2,+ X,+} from "lucide-react";++import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useDocumentVisible } from "@/hooks/useDocumentVisible";+import {+ clearPaneNotifications,+ fetchPaneNotifications,+ markPaneNotificationsRead,+ type PaneNotification,+ type PaneNotificationKind,+ type PaneNotificationsState,+} from "@/lib/agenticIdeApi";+import { useEventStore } from "@/store/events";++/**+ * How often the bell asks.+ *+ * Faster than the interrupted-panes poll (15 s) because this one is about+ * REACTION: an agent finishing is the moment the user is waiting for, and a+ * quarter-minute of silence after it is a quarter-minute of them still+ * watching the wall. The backend's own sweep runs every 2 s, so this is the+ * slower half of the pair either way.+ */+export const POLL_MS = 5_000;++/** How wide the panel gets, and the margin it keeps from the window edge. */+const PANEL_WIDTH = 400;+const VIEWPORT_MARGIN = 12;++const EMPTY: PaneNotificationsState = {+ enabled: true,+ unread: 0,+ notifications: [],+};++/** "3m ago" / "2h ago" — the same shape the pane recap card uses. */+export function ago(at: number, now: number = Date.now()): string {+ const seconds = Math.max(0, Math.round(now / 1000 - at));+ if (seconds < 60) return `${seconds}s ago`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;+ if (seconds < 86_400) return `${Math.floor(seconds / 3600)}h ago`;+ return `${Math.floor(seconds / 86_400)}d ago`;+}++/**+ * How one kind reads and looks.+ *+ * The label is short and upper-cased in the list, because it is scanned rather+ * than read — the sentence that says what actually happened is the entry's own+ * `title`, which the backend writes so the CLI and this panel never drift.+ */+const KINDS: Record<+ PaneNotificationKind,+ { key: string; icon: typeof CheckCircle2; tone: string }+> = {+ completed: {+ key: "agentic_grid.notifications.kind_completed",+ icon: CheckCircle2,+ tone: "text-emerald-400",+ },+ needs_input: {+ key: "agentic_grid.notifications.kind_needs_input",+ icon: CircleHelp,+ tone: "text-amber-400",+ },+ exited: {+ key: "agentic_grid.notifications.kind_exited",+ icon: PowerOff,+ tone: "text-muted-foreground",+ },+ failed: {+ key: "agentic_grid.notifications.kind_failed",+ icon: AlertTriangle,+ tone: "text-destructive",+ },+};++interface Anchor {+ top: number;+ right: number;+ width: number;+ maxHeight: number;+}++/** Where the panel goes, measured off the bell it hangs from. */+function anchorTo(node: HTMLElement | null): Anchor | null {+ if (!node || typeof window === "undefined") return null;+ const rect = node.getBoundingClientRect();+ const width = Math.min(PANEL_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2);+ const top = rect.bottom + 8;+ return {+ top,+ // Right-aligned to the bell, then held inside the window — the bell sits at+ // the far end of the header, so a left-anchored panel would hang off it.+ right: Math.max(VIEWPORT_MARGIN, window.innerWidth - rect.right),+ width,+ maxHeight: Math.max(180, window.innerHeight - top - VIEWPORT_MARGIN),+ };+}++export interface PaneNotificationsProps {+ /**+ * Take the user to the pane an entry came from. The parent owns this because+ * it owns the grid: switching workspace, un-maximizing whatever was+ * maximized, and scrolling the pane into view are all its state.+ */+ onJump: (entry: PaneNotification) => void;+ /**+ * Is the section holding this control the one on screen? The workspace stays+ * mounted behind other sections (see MainView), and this poll runs for as+ * long as it is open. Defaults to true — the behaviour before it could hide.+ */+ onScreen?: boolean;+}++export function PaneNotifications({ onJump, onScreen = true }: PaneNotificationsProps) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [state, setState] = useState<PaneNotificationsState>(EMPTY);+ const [open, setOpen] = useState(false);+ const [anchor, setAnchor] = useState<Anchor | null>(null);+ const bellRef = useRef<HTMLButtonElement | null>(null);+ const panelRef = useRef<HTMLDivElement | null>(null);+ // Re-rendered on a slow beat so "3m ago" does not sit at "3m ago" for an+ // hour while the panel stays open.+ const [tick, setTick] = useState(() => Date.now());++ const refresh = useCallback(async (): Promise<PaneNotificationsState> => {+ try {+ const next = await fetchPaneNotifications();+ setState(next);+ return next;+ } catch {+ // A closed workspace, a backend still warming, a dropped request. The+ // bell is additive — showing the last known count beats an error toast+ // every few seconds for something nobody asked for.+ return EMPTY;+ }+ }, []);++ /*+ * Poll only while somebody could see the count: not in another section+ * (`onScreen`), not behind another window (`documentVisible`). Binding the+ * effect to that answer rather than checking inside the tick is also the+ * catch-up — coming back rebuilds the effect, and a rebuilt effect reads.+ */+ const documentVisible = useDocumentVisible();+ const polling = onScreen && documentVisible;+ useEffect(() => {+ if (!polling) return;+ void refresh();+ const timer = window.setInterval(() => void refresh(), POLL_MS);+ return () => window.clearInterval(timer);+ }, [refresh, polling]);++ useEffect(() => {+ if (!open) return;+ const timer = window.setInterval(() => setTick(Date.now()), 30_000);+ return () => window.clearInterval(timer);+ }, [open]);++ // Measured before paint, so the panel never appears in the wrong place for a+ // frame and then jumps.+ useLayoutEffect(() => {+ if (!open) return;+ const place = () => setAnchor(anchorTo(bellRef.current));+ place();+ window.addEventListener("resize", place);+ window.addEventListener("scroll", place, true);+ return () => {+ window.removeEventListener("resize", place);+ window.removeEventListener("scroll", place, true);+ };+ }, [open]);++ // Click anywhere else, or Escape, closes it. A panel that can only be closed+ // by its own X is a panel in the way of the grid it is about.+ useEffect(() => {+ if (!open) return;+ const onPointer = (event: MouseEvent) => {+ const target = event.target as Node | null;+ if (panelRef.current?.contains(target ?? null)) return;+ if (bellRef.current?.contains(target ?? null)) return;+ setOpen(false);+ };+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") setOpen(false);+ };+ document.addEventListener("mousedown", onPointer);+ document.addEventListener("keydown", onKey);+ return () => {+ document.removeEventListener("mousedown", onPointer);+ document.removeEventListener("keydown", onKey);+ };+ }, [open]);++ const toggle = async () => {+ const next = !open;+ setOpen(next);+ if (!next) return;+ // Read on open, so the list is never the poll's stale copy.+ const fresh = await refresh();+ if (fresh.unread === 0) return;+ try {+ await markPaneNotificationsRead();+ setState((current) => ({+ ...current,+ unread: 0,+ notifications: current.notifications.map((n) => ({ ...n, read: true })),+ }));+ } catch {+ // The badge stays up and clears on the next open. Nothing is lost, and a+ // toast for a failed bookkeeping call would be noise about noise.+ }+ };++ const discard = async (id?: string) => {+ // Cleared on screen first: the user pressed a delete button, and that+ // should not wait for a round-trip. A failed call is corrected by the very+ // next poll, five seconds away.+ setState((current) => ({+ ...current,+ notifications: id+ ? current.notifications.filter((n) => n.id !== id)+ : [],+ unread: id+ ? current.notifications.filter((n) => n.id !== id && !n.read).length+ : 0,+ }));+ try {+ await clearPaneNotifications(id);+ } catch (e) {+ pushToast("error", (e as Error).message);+ void refresh();+ }+ };++ const jump = (entry: PaneNotification) => {+ setOpen(false);+ onJump(entry);+ };++ const unread = state.unread;+ const entries = state.notifications;++ return (+ <>+ <button+ ref={bellRef}+ type="button"+ data-testid="pane-notifications-bell"+ aria-label={t("agentic_grid.notifications.title")}+ aria-expanded={open}+ title={+ unread > 0+ ? t("agentic_grid.notifications.hint_unread").replace("{0}", String(unread))+ : t("agentic_grid.notifications.hint")+ }+ onClick={() => void toggle()}+ className={cn(+ "relative flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border transition-colors",+ unread > 0+ ? "border-primary/60 bg-primary/15 text-primary hover:bg-primary/25"+ : "border-border text-muted-foreground hover:border-primary/40 hover:text-foreground",+ )}+ >+ <Bell className={cn("h-4 w-4", unread > 0 && "animate-[pulse_2s_ease-in-out_2]")} />+ {unread > 0 && (+ <span+ data-testid="pane-notifications-count"+ className="absolute -right-1.5 -top-1.5 min-w-[1rem] rounded-full bg-primary px-1 text-center font-mono text-[10px] font-semibold leading-4 text-primary-foreground"+ >+ {unread > 99 ? "99+" : unread}+ </span>+ )}+ </button>++ {open &&+ anchor &&+ typeof document !== "undefined" &&+ createPortal(+ <div+ ref={panelRef}+ data-testid="pane-notifications-panel"+ role="dialog"+ aria-label={t("agentic_grid.notifications.title")}+ style={{+ position: "fixed",+ top: anchor.top,+ right: anchor.right,+ width: anchor.width,+ maxHeight: anchor.maxHeight,+ }}+ className="z-[60] flex flex-col overflow-hidden rounded-xl border border-border bg-card shadow-2xl"+ >+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-3">+ <Bell className="h-4 w-4 shrink-0 text-muted-foreground" />+ <h2 className="min-w-0 flex-1 truncate font-display text-sm font-semibold">+ {t("agentic_grid.notifications.title")}+ </h2>+ <button+ type="button"+ data-testid="pane-notifications-clear"+ aria-label={t("agentic_grid.notifications.clear_all")}+ title={t("agentic_grid.notifications.clear_all")}+ disabled={entries.length === 0}+ onClick={() => void discard()}+ className="shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30"+ >+ <Trash2 className="h-4 w-4" />+ </button>+ <button+ type="button"+ aria-label={t("agentic_grid.notifications.close")}+ onClick={() => setOpen(false)}+ className="shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ >+ <X className="h-4 w-4" />+ </button>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis">+ {entries.length === 0 ? (+ <p+ data-testid="pane-notifications-empty"+ className="px-4 py-6 text-xs leading-relaxed text-muted-foreground"+ >+ {state.enabled+ ? t("agentic_grid.notifications.empty")+ : t("agentic_grid.notifications.disabled")}+ </p>+ ) : (+ <ul className="divide-y divide-border/60">+ {entries.map((entry) => (+ <Row+ key={entry.id}+ entry={entry}+ now={tick}+ onJump={() => jump(entry)}+ onDiscard={() => void discard(entry.id)}+ />+ ))}+ </ul>+ )}+ </div>++ {!state.enabled && entries.length > 0 && (+ <p className="shrink-0 border-t border-border px-4 py-2 text-[11px] text-muted-foreground">+ {t("agentic_grid.notifications.disabled")}+ </p>+ )}+ </div>,+ document.body,+ )}+ </>+ );+}++function Row({+ entry,+ now,+ onJump,+ onDiscard,+}: {+ entry: PaneNotification;+ now: number;+ onJump: () => void;+ onDiscard: () => void;+}) {+ const t = useT();+ const kind = KINDS[entry.kind] ?? KINDS.completed;+ const Icon = kind.icon;++ return (+ <li+ data-testid="pane-notification"+ data-kind={entry.kind}+ className={cn("group px-4 py-3", !entry.read && "bg-primary/[0.06]")}+ >+ <div className="flex items-start gap-3">+ <Icon className={cn("mt-0.5 h-4 w-4 shrink-0", kind.tone)} aria-hidden />+ <div className="min-w-0 flex-1">+ <div className="flex items-baseline gap-2">+ <span className="truncate font-semibold text-foreground">{entry.pane}</span>+ <span className="truncate text-[11px] uppercase tracking-wide text-muted-foreground">+ {t(kind.key)}+ </span>+ <span className="ml-auto shrink-0 text-[11px] tabular-nums text-muted-foreground">+ {ago(entry.created_at, now)}+ </span>+ </div>+ {/* What actually happened, in the backend's own words — and the+ workspace it happened in, because the list spans every open tab+ and a call-sign counts from T1 in each of them. */}+ <p className="mt-0.5 truncate text-xs text-muted-foreground">+ {entry.display_name}+ {entry.workspace ? ` · ${entry.workspace}` : ""}+ </p>+ <p className="mt-1 text-xs leading-relaxed text-foreground/80">{entry.title}</p>+ {entry.detail && (+ <p className="mt-1 line-clamp-2 text-[11px] leading-relaxed text-muted-foreground">+ {t("agentic_grid.notifications.last_task").replace("{0}", entry.detail)}+ </p>+ )}+ <div className="mt-2 flex items-center gap-2">+ <button+ type="button"+ data-testid="pane-notification-jump"+ onClick={onJump}+ className="rounded-md border border-primary/50 bg-primary/10 px-2 py-1 text-[11px] font-medium text-primary transition-colors hover:bg-primary/20"+ >+ {t("agentic_grid.notifications.jump")}+ </button>+ <button+ type="button"+ data-testid="pane-notification-discard"+ aria-label={t("agentic_grid.notifications.discard")}+ title={t("agentic_grid.notifications.discard")}+ onClick={onDiscard}+ className="rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100"+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </div>+ </div>+ </div>+ </li>+ );+}++export default PaneNotifications;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 8eda7f1723..c92c907be8 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3526,6 +3526,23 @@"cancel": "Offen lassen","confirm": "Ausgewählte schließen","close_failed": "Diese Terminals konnten nicht geschlossen werden: {0}"+ },+ "notifications": {+ "title": "Benachrichtigungen",+ "hint": "Terminals, die fertig sind, etwas fragen oder gestoppt haben.",+ "hint_unread": "{0} Terminal-Meldung(en), die du noch nicht gesehen hast.",+ "empty": "Nichts zu melden — jedes Terminal arbeitet noch oder ist seit deinem letzten Blick unverändert.",+ "disabled": "Das Sammeln neuer Benachrichtigungen ist in deinen Einstellungen ausgeschaltet ([agentic_ide].pane_notifications).",+ "jump": "Zum Terminal springen",+ "discard": "Diese Benachrichtigung verwerfen",+ "clear_all": "Alle Benachrichtigungen verwerfen",+ "close": "Schließen",+ "last_task": "Zuletzt beauftragt mit: {0}",+ "kind_completed": "FERTIG",+ "kind_needs_input": "BRAUCHT EINGABE",+ "kind_exited": "GESTOPPT",+ "kind_failed": "FEHLGESCHLAGEN",+ "gone": "{0} gibt es in diesem Workspace nicht mehr — das Terminal wurde geschlossen, seit die Benachrichtigung kam."}},"prompt_writer": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex cd908023ab..90cc5a155a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3527,6 +3527,23 @@"cancel": "Keep them open","confirm": "Close selected","close_failed": "These terminals could not be closed: {0}"+ },+ "notifications": {+ "title": "Notifications",+ "hint": "Terminals that finished, asked something, or stopped.",+ "hint_unread": "{0} terminal update(s) you have not seen yet.",+ "empty": "Nothing to report — every terminal is either working or has been like this since you last looked.",+ "disabled": "Collecting new notifications is switched off in your settings ([agentic_ide].pane_notifications).",+ "jump": "Jump to pane",+ "discard": "Discard this notification",+ "clear_all": "Discard all notifications",+ "close": "Close",+ "last_task": "Last asked to: {0}",+ "kind_completed": "COMPLETED",+ "kind_needs_input": "NEEDS INPUT",+ "kind_exited": "STOPPED",+ "kind_failed": "FAILED",+ "gone": "{0} is not in this workspace any more — that terminal was closed since the notification arrived."}},"prompt_writer": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex a08a7f4d4d..2a1c37305c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3526,6 +3526,23 @@"cancel": "Mantenerlos abiertos","confirm": "Cerrar seleccionados","close_failed": "No se pudieron cerrar estos terminales: {0}"+ },+ "notifications": {+ "title": "Notificaciones",+ "hint": "Terminales que han terminado, preguntan algo o se han detenido.",+ "hint_unread": "{0} aviso(s) de terminal que aún no has visto.",+ "empty": "Nada que informar: cada terminal sigue trabajando o está igual que la última vez que miraste.",+ "disabled": "La recogida de notificaciones nuevas está desactivada en tus ajustes ([agentic_ide].pane_notifications).",+ "jump": "Ir al panel",+ "discard": "Descartar esta notificación",+ "clear_all": "Descartar todas las notificaciones",+ "close": "Cerrar",+ "last_task": "Última tarea encargada: {0}",+ "kind_completed": "COMPLETADO",+ "kind_needs_input": "NECESITA RESPUESTA",+ "kind_exited": "DETENIDO",+ "kind_failed": "FALLIDO",+ "gone": "{0} ya no está en este espacio de trabajo: ese terminal se cerró después de llegar la notificación."}},"prompt_writer": {diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 6f958099d3..29ef58a303 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -884,6 +884,84 @@ export async function continueInterrupted(};}+/**+ * What happened in one pane, as the header bell lists it.+ *+ * `kind` is what the backend established from the pane's own screen, never from+ * reading the agent's prose: `completed` means it stopped drawing the interrupt+ * hint its CLI shows while busy — the terminal went quiet, which is a different+ * claim from "the work is right".+ */+export type PaneNotificationKind =+ | "completed"+ | "needs_input"+ | "exited"+ | "failed";++export interface PaneNotification {+ id: string;+ kind: PaneNotificationKind;+ /** Which workspace it happened in — the list spans every open one. */+ workspace_id: string;+ workspace: string;+ pane_key: string;+ /** The pane's call-sign — "T3". */+ pane: string;+ agent: string;+ /** What the user reads — "Claude Code". */+ display_name: string;+ title: string;+ /** What that pane was last asked to do. May be empty. */+ detail: string;+ created_at: number;+ read: boolean;+}++export interface PaneNotificationsState {+ /** False when the background sweep is switched off in jarvis.toml. */+ enabled: boolean;+ unread: number;+ notifications: PaneNotification[];+}++/** Everything the bell shows, newest first, across every open workspace. */+export async function fetchPaneNotifications(): Promise<PaneNotificationsState> {+ const body = await getJson<Partial<PaneNotificationsState>>(+ "/api/agentic-ide/notifications",+ );+ return {+ enabled: body.enabled ?? true,+ unread: body.unread ?? 0,+ notifications: body.notifications ?? [],+ };+}++/** Stop the bell counting these entries. No ids means every one of them. */+export async function markPaneNotificationsRead(ids?: string[]): Promise<number> {+ const res = await fetch("/api/agentic-ide/notifications/read", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ids: ids ?? [] }),+ });+ if (!res.ok) throw new Error(await detail(res));+ const body = (await res.json()) as { unread?: number };+ return body.unread ?? 0;+}++/**+ * Throw entries away — one by id, or the whole list without one.+ *+ * Nothing about the pane changes: the agent behind a discarded entry keeps+ * running exactly as it was.+ */+export async function clearPaneNotifications(id?: string): Promise<void> {+ const url = id+ ? `/api/agentic-ide/notifications/${encodeURIComponent(id)}`+ : "/api/agentic-ide/notifications";+ const res = await fetch(url, { method: "DELETE" });+ if (!res.ok) throw new Error(await detail(res));+}+/** The active subscription per coding CLI, without the whole workspace state. */export async function fetchIdeAccounts(): Promise<IdeAccountState[]> {const body = await getJson<{ accounts: IdeAccountState[] }>(diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex 310271f55c..82ddff0d2c 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -516,6 +516,24 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {}};+ /*+ * "Jump to a pane in another workspace", from the header bell.+ *+ * The grid cannot do this half itself: it is keyed by workspace, so switching+ * tab REPLACES it — a maximize applied before the switch would land on the+ * grid that is about to be thrown away, and one applied after it has no+ * component left to call. So the wish is parked here, survives the swap, and+ * is handed to the grid that comes up as `jumpTo`.+ *+ * The nonce is what lets the same pane be jumped to twice in a row: an effect+ * cannot re-fire on a value that has not changed.+ */+ const [jumpTo, setJumpTo] = useState<{ pane: string; nonce: number } | null>(null);+ const jumpToPane = async (workspaceId: string, pane: string) => {+ if (workspaceId !== session?.id) await switchTo(workspaceId);+ setJumpTo({ pane, nonce: Date.now() });+ };+/** A file dropped on a workspace TAB.*@@ -728,6 +746,8 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {session={session}workspaceBar={renderBar(true)}appActions={<TopBarActions />}+ onJumpToWorkspace={(id, pane) => void jumpToPane(id, pane)}+ jumpTo={jumpTo}focusMode={focusMode}onToggleFocus={(v) => void toggleFocus(v)}onClose={() => void close()}diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.pyindex 3cfb48319c..1175d37ad0 100644--- a/jarvis/workspace/agents.py+++ b/jarvis/workspace/agents.py@@ -239,6 +239,12 @@ class WorkspaceAgent:#: TUI furniture to strip before a transcript is summarised — banners,#: status bars, key hints. Additive to the shared set.chrome_fragments: tuple[str, ...] = ()+ #: The hint this CLI draws while — and only while — it is busy, so a pane+ #: that stopped working can be told apart from one that never started.+ #: Additive to the shared set in :mod:`jarvis.agentic_ide.activity`, which+ #: already covers the near-universal "esc to interrupt" wording; an entry+ #: names only its own peculiarity.+ busy_fragments: tuple[str, ...] = ()#: The per-project instructions file this CLI reads (CLAUDE.md, AGENTS.md).instruction_filename: str = ""diff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.pynew file mode 100644index 0000000000..959218643a--- /dev/null+++ b/tests/unit/agentic_ide/test_pane_notifications.py@@ -0,0 +1,299 @@+"""The bell: which terminals stopped while nobody was looking at them.++A workspace runs a dozen coding agents in postcard-sized panes, and none of them+announces that it is done — the spinner row simply stops being drawn. So the+feature is entirely about the TRANSITION, and every test here is about getting+that edge right rather than about the store around it:++* a pane that was busy and went quiet is reported ONCE,+* a pane that has been idle since it appeared is never reported at all,+* the gap a TUI leaves between two steps does not produce a notification,+* and an entry never outlives the workspace whose pane it points at.++Each of those has an obvious wrong implementation that looks correct in a demo+and is unusable in a grid of twelve.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++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.session import Registry+from tests.fakes.fake_pty_manager import FakePtyManager++# What a coding CLI draws while it is working, and what it draws when it is not.+BUSY_SCREEN = "\r\n✳ Cooking… (12s · ↑ 1.2k tokens · esc to interrupt)\r\n"+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"++[email protected](autouse=True)+def _clean_store() -> Any:+ """Every test starts with an empty bell and no per-pane memory."""+ notifications.reset()+ yield+ notifications.reset()+++def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ return Registry(pty_manager=FakePtyManager())+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++async def _pane(registry: Registry, folder: Path, *, name: str = "Alex"):+ """One live pane in one workspace, through the real attach path."""+ session = await registry.start(str(folder), [{"agent": "claude", "name": name}])+ term = await registry.attach(name, 100, 30, _noop, _noop_exit)+ return session, term+++def _draw(term: Any, screen: str) -> None:+ """Put ``screen`` on the pane's replayed terminal, as its agent would."""+ term.transcript.feed(screen)+++# ------------------------------------------------------------------- reading+async def test_the_interrupt_hint_is_what_marks_a_pane_busy(+ registry: Registry, tmp_path: Path+) -> None:+ """The one signal every coding TUI draws while — and only while — it works."""+ _session, term = await _pane(registry, tmp_path)++ _draw(term, BUSY_SCREEN)+ assert read_activity(term) == "working"+++async def test_a_pane_at_its_prompt_reads_as_waiting(+ registry: Registry, tmp_path: Path+) -> None:+ _session, term = await _pane(registry, tmp_path)++ _draw(term, IDLE_SCREEN)+ assert read_activity(term) == "waiting"+++async def test_a_visible_question_reads_as_asking(registry: Registry, tmp_path: Path) -> None:+ """Told apart from "finished" because the two want different words."""+ _session, term = await _pane(registry, tmp_path)++ _draw(term, QUESTION_SCREEN)+ assert read_activity(term) == "asking"+++async def test_a_pane_with_no_agent_yet_is_not_idle(registry: Registry, tmp_path: Path) -> None:+ """A pane waiting for a cold-start slot has not finished anything."""+ session = await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])++ assert read_activity(session.terminals[0]) == "starting"+++# --------------------------------------------------------------- transitions+async def test_a_pane_that_stops_working_is_reported_once(+ registry: Registry, tmp_path: Path+) -> None:+ """The whole feature, in one test: busy → quiet → exactly one entry."""+ watcher = notifications.watcher()+ session, term = await _pane(registry, tmp_path)++ _draw(term, BUSY_SCREEN)+ assert watcher.poll(registry, now=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) == []++ filed = watcher.poll(registry, now=100.0 + 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++ # And never again for the same stop, however long the pane sits there.+ assert watcher.poll(registry, now=400.0) == []+++async def test_a_pane_that_was_never_busy_is_never_reported(+ registry: Registry, tmp_path: Path+) -> None:+ """Otherwise every workspace would ring its own bell the moment it opened.++ The failure this pins is not hypothetical for a "pane is idle" rule: a+ freshly attached pane sits at its prompt for the seconds before its first+ instruction, which under that rule is a finished job per pane per open.+ """+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ _draw(term, IDLE_SCREEN)++ for moment in (100.0, 110.0, 200.0, 900.0):+ assert watcher.poll(registry, now=moment) == []+++async def test_a_repaint_gap_does_not_file_a_notification(+ registry: Registry, tmp_path: Path+) -> None:+ """A TUI drops its hint for a moment between steps — that is not "finished".++ Without the settle window this fires several times a minute for a pane that+ is working normally, which is the version of this feature nobody would leave+ switched on.+ """+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)++ _draw(term, BUSY_SCREEN)+ watcher.poll(registry, now=100.0)+ # The hint is gone for one sweep...+ term.transcript.clear()+ _draw(term, IDLE_SCREEN)+ assert watcher.poll(registry, now=101.0) == []+ # ...and back before the settle window elapses.+ term.transcript.clear()+ _draw(term, BUSY_SCREEN)+ assert watcher.poll(registry, now=102.0) == []+ assert watcher.poll(registry, now=100.0 + notifications.SETTLE_S + 5) == []+++async def test_a_question_is_reported_even_though_it_never_worked(+ registry: Registry, tmp_path: Path+) -> None:+ """A CLI that asks something at startup has never been busy — and still needs you."""+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ _draw(term, IDLE_SCREEN)+ watcher.poll(registry, now=100.0)++ 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 [entry.kind for entry in filed] == ["needs_input"]+++async def test_going_back_to_work_re_arms_the_report(+ registry: Registry, tmp_path: Path+) -> None:+ """A pane given a second job reports its second stop too."""+ watcher = notifications.watcher()+ _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)+ assert [entry.kind for entry in filed] == ["completed"], round_start+++async def test_a_dead_agent_is_reported_without_waiting(+ registry: Registry, tmp_path: Path+) -> None:+ """There is no repaint gap to sit out — the state cannot flip back by itself."""+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ watcher.poll(registry, now=100.0)++ term.status = "exited"+ term.exit_code = 1+ filed = watcher.poll(registry, now=100.5)++ assert [entry.kind for entry in filed] == ["exited"]+ assert "1" in filed[0].title+++async def test_the_first_sweep_never_files_history(registry: Registry, tmp_path: Path) -> None:+ """A pane that has been finished for an hour is not news on the first look."""+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ _draw(term, IDLE_SCREEN)++ assert watcher.poll(registry, now=100.0) == []+ assert notifications.center().list() == []+++# --------------------------------------------------------------------- store+def test_reading_only_stops_the_count_not_the_list() -> None:+ center = notifications.NotificationCenter()+ center.add(_entry("n1"))+ center.add(_entry("n2"))+ assert center.unread == 2++ changed = center.mark_read()++ assert changed == 2+ assert center.unread == 0+ assert len(center.list()) == 2, "the entries stay — only the badge goes quiet"+++def test_the_list_is_newest_first() -> None:+ center = notifications.NotificationCenter()+ center.add(_entry("n1"))+ center.add(_entry("n2"))++ assert [entry.id for entry in center.list()] == ["n2", "n1"]+++def test_the_store_is_bounded() -> None:+ """A long day must not grow the process."""+ center = notifications.NotificationCenter(limit=3)+ for index in range(10):+ center.add(_entry(f"n{index}"))++ assert len(center.list()) == 3+ assert [entry.id for entry in center.list()] == ["n9", "n8", "n7"]+++async def test_closing_a_workspace_takes_its_notifications_with_it(+ registry: Registry, tmp_path: Path+) -> None:+ """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)+ assert notifications.center().list() != []++ await registry.end(session.id)++ assert notifications.center().list() == []+++def _entry(entry_id: str) -> notifications.Notification:+ return notifications.Notification(+ id=entry_id,+ kind="completed",+ workspace_id="ws1",+ workspace="Demo",+ pane_key="t1",+ pane="T1",+ agent="claude",+ display_name="Claude Code",+ title="Finished and waiting at its prompt",+ detail="",+ created_at=1.0,+ )diff --git a/tests/unit/agentic_ide/test_pane_notifications_route.py b/tests/unit/agentic_ide/test_pane_notifications_route.pynew file mode 100644index 0000000000..549bd4143f--- /dev/null+++ b/tests/unit/agentic_ide/test_pane_notifications_route.py@@ -0,0 +1,132 @@+"""The bell's REST surface — the CLI-first half (CLAUDE.md §5).++The panel in the header is one client of this. The other is a terminal: the+same three questions ("what stopped?", "stop counting these", "throw them+away") have to be answerable from `jarvis api agentic-ide ...` without the+desktop app being open, which is exactly the situation somebody checking on a+long-running fleet is in.+"""++from __future__ import annotations++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agentic_ide import notifications++[email protected](autouse=True)+def _clean_store():+ notifications.reset()+ yield+ notifications.reset()+++def client() -> TestClient:+ from jarvis.ui.web.agentic_ide_routes import router++ app = FastAPI()+ app.include_router(router)+ return TestClient(app)+++def _fill(count: int = 2) -> None:+ for index in range(count):+ notifications.center().add(+ notifications.Notification(+ id=f"n{index}",+ kind="completed",+ workspace_id="ws1",+ workspace="Demo",+ pane_key=f"t{index}",+ pane=f"T{index}",+ agent="claude",+ display_name="Claude Code",+ title="Finished and waiting at its prompt",+ detail="Rewrite the ranking pipeline",+ created_at=float(index),+ )+ )+++def test_an_empty_bell_is_a_normal_answer(client: TestClient) -> None:+ """Nothing has stopped. That is a 200 with an empty list, never an error."""+ body = client.get("/api/agentic-ide/notifications").json()++ assert body["unread"] == 0+ assert body["notifications"] == []+++def test_it_lists_newest_first_with_everything_a_jump_needs(client: TestClient) -> None:+ """A call-sign counts from T1 in EVERY workspace, so the id has to travel."""+ _fill()++ body = client.get("/api/agentic-ide/notifications").json()++ assert [entry["id"] for entry in body["notifications"]] == ["n1", "n0"]+ assert body["unread"] == 2+ first = body["notifications"][0]+ assert first["workspace_id"] == "ws1"+ assert first["pane"] == "T1"+ assert first["kind"] == "completed"+++def test_reading_clears_the_count_and_keeps_the_list(client: TestClient) -> None:+ _fill()++ marked = client.post("/api/agentic-ide/notifications/read", json={"ids": []}).json()++ assert marked["changed"] == 2+ assert marked["unread"] == 0+ body = client.get("/api/agentic-ide/notifications").json()+ assert len(body["notifications"]) == 2+ assert all(entry["read"] for entry in body["notifications"])+++def test_one_entry_can_be_read_on_its_own(client: TestClient) -> None:+ _fill()++ marked = client.post("/api/agentic-ide/notifications/read", json={"ids": ["n0"]}).json()++ assert marked["changed"] == 1+ assert marked["unread"] == 1+++def test_discarding_one_leaves_the_rest(client: TestClient) -> None:+ _fill()++ dropped = client.delete("/api/agentic-ide/notifications/n0").json()++ assert dropped["changed"] == 1+ body = client.get("/api/agentic-ide/notifications").json()+ assert [entry["id"] for entry in body["notifications"]] == ["n1"]+++def test_discarding_something_that_is_already_gone_is_quiet(client: TestClient) -> None:+ """It may have left with its workspace between the read and the click."""+ _fill()++ dropped = client.delete("/api/agentic-ide/notifications/nope")++ assert dropped.status_code == 200+ assert dropped.json()["changed"] == 0+++def test_discarding_everything_empties_the_bell(client: TestClient) -> None:+ _fill(4)++ dropped = client.delete("/api/agentic-ide/notifications").json()++ assert dropped["changed"] == 4+ assert client.get("/api/agentic-ide/notifications").json()["notifications"] == []+++def test_the_switch_is_reported_so_a_quiet_bell_is_explainable(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """"Nothing is arriving" and "collection is off" must not look the same."""+ monkeypatch.setattr(notifications, "enabled", lambda: False)++ assert client.get("/api/agentic-ide/notifications").json()["enabled"] is False