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): land the in-flight chat-stage rework — session list, rows-first grid, one view store
rubenluetke10-beep6b50683a9d70
diff --git a/jarvis/agentic_ide/layout_tree.py b/jarvis/agentic_ide/layout_tree.pyindex 42cc6082f5..11ec0a7680 100644--- a/jarvis/agentic_ide/layout_tree.py+++ b/jarvis/agentic_ide/layout_tree.py@@ -32,6 +32,11 @@ Every function returns a tree in canonical form:* ``weights`` has exactly one positive finite entry per child. A weight is aplain multiplier against its siblings (two children at 1 and 1 are equal),never pixels — pixels do not survive a window resize, a weight does.+* A grid stands on its ROWS. After every structural edit, a row of equally+ divided columns is transposed into a column of rows (``rows_outermost``) —+ the same picture, but each band owns its own vertical seam instead of one+ full-height seam owning them all. See that function for why one of the two+ readings has to win.## Room accounting@@ -150,9 +155,10 @@ def normalize(node: LayoutNode) -> LayoutNode:def leaves(node: LayoutNode | None) -> list[str]:"""Every pane key in READING order — the order `_renumber` sorts by.- Depth-first, children left to right / top to bottom. For the plain- "columns of stacks" shape this is exactly the old ``(column, slot)`` sort,- so call-sign numbering keeps meaning what it always meant.+ Depth-first, children left to right / top to bottom. Because+ :func:`rows_outermost` stands a grid on its rows, this is the order a+ person actually reads a workspace in — across the top band first, then+ the next — rather than down one column and back up the next."""if node is None:return []@@ -171,9 +177,18 @@ def contains(node: LayoutNode | None, pane: str) -> bool:def wizard_tree(panes: Iterable[str], depth: int) -> LayoutNode | None:"""The tree a wizard-opened workspace starts with.- Columns of ``depth``, each filled top to bottom before the next is opened- — the same arithmetic the wizard preview draws with (frontend- ``layout.ts``), so the workspace that appears is the one that was shown.+ The SHAPE is columns of ``depth`` — the same arithmetic the wizard preview+ draws with (frontend ``layout.ts``), so the workspace that appears is the+ one that was shown.++ The panes are then seated into that shape in READING order, which is the+ other half of the promise and the half that used to be free. Once a full+ rectangle stands on its rows (:func:`rows_outermost`) it is read across+ the top band first, so filling the shape column by column would put the+ second pane under the first and the third beside it. Callers hand their+ panes over in the order the user sees them — ``Registry.refold`` re-deals+ a workspace someone is watching — and a fold that quietly permutes them+ is a fold that cannot be undone by widening the window again."""keys = list(panes)if not keys:@@ -189,8 +204,31 @@ def wizard_tree(panes: Iterable[str], depth: int) -> LayoutNode | None:Split(direction="column", children=list(chunk), weights=[1.0] * len(chunk)))if len(columns) == 1:- return columns[0]- return Split(direction="row", children=columns, weights=[1.0] * len(columns))+ return _reseat(columns[0], keys)+ shape = _rows_outermost(Split(direction="row", children=columns, weights=[1.0] * len(columns)))+ return _reseat(shape, keys)+++def _reseat(node: LayoutNode, keys: Iterable[str]) -> LayoutNode:+ """``node``'s shape with its leaves refilled from ``keys``, in order.++ The shape decides where the cells are; this decides which pane sits in+ which. Keeping the two apart is what lets a caller pick a layout by its+ geometry and still hand its panes over in the order they should be read.+ """+ supply = iter(keys)++ def walk(current: LayoutNode) -> LayoutNode:+ if isinstance(current, Leaf):+ return Leaf(pane=next(supply))+ return Split(+ direction=current.direction,+ children=[walk(child) for child in current.children],+ weights=list(current.weights),+ pinned=current.pinned,+ )++ return walk(node)def from_grid(entries: Iterable[tuple[str, int, int]]) -> LayoutNode | None:@@ -198,7 +236,8 @@ def from_grid(entries: Iterable[tuple[str, int, int]]) -> LayoutNode | None:This is the migration path: resume snapshots written before the treeexisted carry the two integers per pane, and the columns-of-stacks shape- they describe is exactly representable — a row of column stacks.+ they describe is exactly representable — a row of column stacks, squared+ up by :func:`rows_outermost` when it forms a full rectangle."""by_column: dict[int, list[tuple[int, str]]] = {}for key, column, slot in entries:@@ -220,7 +259,7 @@ def from_grid(entries: Iterable[tuple[str, int, int]]) -> LayoutNode | None:)if len(columns) == 1:return columns[0]- return Split(direction="row", children=columns, weights=[1.0] * len(columns))+ return _rows_outermost(Split(direction="row", children=columns, weights=[1.0] * len(columns)))def _insert_beside(@@ -290,7 +329,7 @@ def split_pane(if anchor is not None:rewritten, found = _insert_beside(root, anchor, added, grown, after=True)if found:- return normalize(rewritten)+ return _rows_outermost(normalize(rewritten))return append_pane(root, added)@@ -308,7 +347,7 @@ def append_pane(root: LayoutNode | None, added: str) -> LayoutNode:share = sum(root.weights) / len(root.weights) if root.weights else 1.0root.children.append(Leaf(pane=added))root.weights.append(_clean_weight(share))- return normalize(root)+ return _rows_outermost(normalize(root))return Split(direction="row", children=[root, Leaf(pane=added)], weights=[1.0, 1.0])@@ -362,6 +401,126 @@ def _even_weights(node: Split) -> bool:return all(abs(share - first) <= EVEN_EPSILON * first for share in shares)+def _shares(node: Split) -> list[float]:+ """``node``'s weights as fractions of its own total.++ Comparable ACROSS containers, which raw weights are not: two columns at+ ``[1, 1]`` and ``[4, 4]`` divide their room at exactly the same height.+ """+ weights = [+ _clean_weight(node.weights[index] if index < len(node.weights) else 1.0)+ for index in range(len(node.children))+ ]+ total = sum(weights) or 1.0+ return [weight / total for weight in weights]+++def _is_one_grid(node: Split) -> bool:+ """Do ``node``'s children line up as ONE grid — same rows, same heights?++ True only when every child is a column, they all hold the same number of+ children, and they divide their height at the same fractions. That is+ exactly the condition under which :func:`rows_outermost` may transpose+ ``node`` without a single pane changing size.+ """+ if node.direction != "row" or len(node.children) < 2:+ return False+ columns: list[Split] = []+ for child in node.children:+ if not isinstance(child, Split) or child.direction != "column":+ return False+ columns.append(child)+ depth = len(columns[0].children)+ if depth < 2 or any(len(column.children) != depth for column in columns):+ return False+ first = _shares(columns[0])+ return all(+ abs(share - first[index]) <= EVEN_EPSILON * first[index]+ for column in columns[1:]+ for index, share in enumerate(_shares(column))+ )+++def rows_outermost(root: LayoutNode | None) -> LayoutNode | None:+ """A grid rewritten as rows of panes rather than columns of panes.++ Geometry in, the SAME geometry out — this moves no boundary and resizes+ no pane. What it changes is which container owns each boundary, and that+ decides how far a seam drag reaches.++ A workspace built by splitting right and then down twice comes out as+ ``row[column[a, c], column[b, d]]``: two columns side by side, so the+ line between them belongs to the ROOT and runs the full height. Dragging+ it under the bottom pair therefore resizes the top pair too — the two+ halves are welded together, which is what the maintainer reported on+ 2026-08-25 ("the upper and the lower terminal move with each other").+ Reaching the same 2×2 the other way round — split down, then right twice+ — gives ``column[row[a, b], row[c, d]]``, where each row owns its own+ vertical line and the two rows resize independently. Same picture, two+ behaviours, decided by the order the panes happened to be opened in.++ So a grid is put in ONE of those forms, always the second: side-by-side+ boundaries are the ones people size (a terminal needs width for its+ output far more often than a column needs its own height), and the cost+ is the single horizontal line now spanning the full width. Rows first is+ the maintainer's call, not a fact about split trees — both readings are+ legitimate, only one can be true at a time.++ The transpose is refused unless every column divides its height at the+ same fractions (:func:`_is_one_grid`): otherwise the horizontal lines sit+ at different heights and no single row structure can draw them. That is+ also what keeps this from undoing hand-dragged sizes — a column dragged+ out of line with its neighbours simply stops qualifying.++ Applied bottom-up, and only after STRUCTURAL edits (a split, a close, a+ move). A seam drag never comes through here: the client posts back the+ tree it was looking at, and reshaping under a drag would make the+ workspace jump under the pointer.+ """+ return None if root is None else _rows_outermost(root)+++def _rows_outermost(root: LayoutNode) -> LayoutNode:+ if isinstance(root, Leaf):+ return root++ node = Split(+ direction=root.direction,+ children=[_rows_outermost(child) for child in root.children],+ weights=list(root.weights),+ pinned=root.pinned,+ )+ if not _is_one_grid(node):+ return normalize(node)++ columns = [child for child in node.children if isinstance(child, Split)]+ # The columns' shared height fractions become the outer stack's weights;+ # the row's own weights become every new row's, so each band is cut at the+ # verticals the grid already had.+ heights = _shares(columns[0])+ widths = [+ _clean_weight(node.weights[index] if index < len(node.weights) else 1.0)+ for index in range(len(columns))+ ]+ bands = [+ Split(+ direction="row",+ children=[column.children[band] for column in columns],+ weights=list(widths),+ pinned=node.pinned,+ )+ for band in range(len(columns[0].children))+ ]+ return normalize(+ Split(+ direction="column",+ children=list(bands),+ weights=list(heights),+ pinned=any(column.pinned for column in columns),+ )+ )++def evened(root: LayoutNode | None) -> LayoutNode | None:"""Every TERMINAL back at an equal share — except where a hand set them.@@ -407,7 +566,15 @@ def remove_pane(root: LayoutNode | None, pane: str) -> LayoutNode | None:weight is dropped and the rest renormalise. A container left with onechild dissolves, which is how a workspace that was split apart folds backto simple shapes instead of accumulating scar tissue.++ A close can leave the survivors standing as a grid, so the result goes+ through :func:`rows_outermost` — once, at the end, never per recursion+ step."""+ return rows_outermost(_removed(root, pane))+++def _removed(root: LayoutNode | None, pane: str) -> LayoutNode | None:if root is None:return Noneif isinstance(root, Leaf):@@ -420,7 +587,7 @@ def remove_pane(root: LayoutNode | None, pane: str) -> LayoutNode | None:if isinstance(child, Leaf) and child.pane == pane:continueif isinstance(child, Split):- slimmed = remove_pane(child, pane)+ slimmed = _removed(child, pane)if slimmed is None:continuechildren.append(slimmed)@@ -476,7 +643,9 @@ def move_pane(direction: Direction = "row" if position in ("left", "right") else "column"after = position in ("right", "below")- slimmed = remove_pane(root, pane)+ # The untransposed removal on purpose: the drop is carved from the tree+ # the user was looking at, and the grid is squared up once, afterwards.+ slimmed = _removed(root, pane)if slimmed is None:return Leaf(pane=pane) if contains(root, pane) else rootrewritten, found = _insert_beside(slimmed, target, pane, direction, after)@@ -485,7 +654,7 @@ def move_pane(# DROP is recoverable; losing the PANE is not — put it back at the# edge rather than dropping it from the tree.return append_pane(slimmed, pane)- return normalize(rewritten)+ return _rows_outermost(normalize(rewritten))# ------------------------------------------------------------- serialization@@ -597,10 +766,12 @@ def grid_hints(root: LayoutNode | None) -> dict[str, tuple[int, int]]:"""Coarse legacy ``(column, slot)`` for every pane, from the tree.Consumers that describe the workspace in words ("the top-left terminal")- still think in columns, and for the common shapes the mapping is exact.- For deeper nesting it is deliberately coarse: the column is the pane's- top-level branch, the slot its reading position within that branch —- stable, ordered, and never claiming precision the flat model cannot hold.+ still think in columns, and for the common shapes the mapping is exact —+ both readings of a grid, since :func:`rows_outermost` puts one of them in+ the other's form. For deeper nesting it is deliberately coarse: the+ outermost branch fixes one coordinate, reading position within it the+ other — stable, ordered, and never claiming precision the flat model+ cannot hold."""if root is None:return {}@@ -610,5 +781,13 @@ def grid_hints(root: LayoutNode | None) -> dict[str, tuple[int, int]]:for column, child in enumerate(root.children)for slot, pane in enumerate(leaves(child))}- # A single stack (or a lone pane) is one column of many slots.+ if isinstance(root, Split):+ # A stack of bands: the band IS the slot, and reading across it gives+ # the column. A plain column of panes falls out of this as column 0.+ return {+ pane: (column, slot)+ for slot, child in enumerate(root.children)+ for column, pane in enumerate(leaves(child))+ }+ # A lone pane.return {pane: (0, slot) for slot, pane in enumerate(leaves(root))}diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 91887124a3..4a81bdaa23 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -834,6 +834,11 @@ class PaneViewer:exit: Anycols: introws: int+ #: Called — synchronously, ``(cols, rows)`` — whenever the shared PTY takes+ #: a size this viewer did not ask for, so a screen that no longer holds the+ #: pane can follow the one that does (see ``Registry._announce_geometry``).+ #: ``None`` for a viewer that only consumes bytes.+ geometry: Any = None@dataclass(frozen=True, slots=True)@@ -1244,6 +1249,51 @@ class Terminal:"account_label": account_label(self.account),}+ def to_row(self) -> dict[str, Any]:+ """This pane as ONE LINE in a list of conversations.++ Deliberately not ``to_dict``: that payload walks the pane's whole+ scrollback twice (the line count and the recap) and carries the layout+ and prompt statistics with it. A session list polls every open+ workspace's panes on a clock, so a dozen scrollback walks per poll is+ the difference between a list and a stutter — and none of what it pays+ for is a line in that list.++ What survives is what the line actually shows: who this pane is, what+ it was last asked to do, and whether it is still doing it. The activity+ reading is the same one the grid's badge uses (:mod:`.activity`), so a+ pane cannot say "working" in one place and "done" in the other.+ """+ reading = self.reading()+ return {+ "key": self.key,+ # The pane's LIFETIME id, not its call-sign: T1 is handed on to a+ # replacement pane, and a list that keys on the call-sign would+ # quietly show the newcomer's row as the dead one's.+ "history_id": self.history_id,+ "name": self.name,+ "agent": self.agent,+ "display_name": self.display_name,+ "accepts_prompts": accepts_prompts(self.agent),+ "status": self.status,+ "exit_code": self.exit_code,+ "activity": reading.activity,+ "activity_since": reading.since,+ "worked": has_work_behind_it(self),+ "started_at": self.started_at,+ "last_output_at": self.last_output_at,+ # The opening of what was last asked of it — the closest thing a+ # terminal has to a chat's title. Capped like the full state's copy.+ "last_prompt": self.last_prompt[:200],+ "last_prompt_at": self.last_prompt_at,+ # Whether a readable conversation could exist for this pane at all.+ # Whether one is actually on disk is the transcript endpoint's+ # answer; this only says the pane holds a handle to look up.+ "has_resume": self.resume is not None,+ "account": self.account,+ "account_label": account_label(self.account),+ }+def reading(self) -> Reading:"""Is this pane's agent working, or has it stopped — and since when?@@ -1362,14 +1412,9 @@ class Session:def contextual_terminal(self) -> Terminal | None:"""The one pane the visible surface puts in front of the user.- Nothing does, today: the grid shows a dozen panes at once, and chat- shows none — it is the agent chat, not a way of reading the terminals.- Picking one anyway would be a guess dressed as a fact, so this answers- None and the caller asks for a call-sign.-- The seam is kept rather than deleted because a surface that DOES stage- one pane is a plausible third value of the enum, and it would report- itself through exactly this field.+ Chat view stages exactly one pane and can answer. The grid never+ does — a dozen panes are visible there, and picking one of them would+ be a guess dressed as a fact."""if self.surface_view != VIEW_CHAT:return None@@ -1378,15 +1423,7 @@ class Session:return self.find(self.surface_terminal)def stages_one_pane(self) -> bool:- """May the visible surface name ONE pane as the one being read?-- The grid never may. ``chat`` may, and today never does: the current- bundle's chat surface is the agent chat and reports no terminal at all.- The permission is kept rather than hard-coded away because the browser- is the only layer that knows what is on screen, and a desktop window- holding a bundle from before the switch is still entitled to be- believed until it reloads itself.- """+ """Does the visible view show a single pane, rather than the wall?"""return self.surface_view == VIEW_CHATdef prompt_target_terminal(self) -> Terminal | None:@@ -1516,6 +1553,7 @@ def _watch(rows: int,*,claim_owner: bool = True,+ on_geometry: Any = None,) -> bool:"""Attach a viewer to ``term`` and optionally make it the owner.@@ -1525,7 +1563,7 @@ def _watch(away from the window that is actually in front of the user."""term.watchers = [w for w in term.watchers if not _same_viewer(w.output, on_output)]- term.watchers.append(PaneViewer(on_output, on_exit, cols, rows))+ term.watchers.append(PaneViewer(on_output, on_exit, cols, rows, on_geometry))if len(term.watchers) > MAX_WATCHERS:del term.watchers[0 : len(term.watchers) - MAX_WATCHERS]owner_is_attached = any(@@ -1537,6 +1575,45 @@ def _watch(return _same_viewer(term.viewer_output, on_output)+def _tell_geometry(watched: PaneViewer, cols: int, rows: int) -> None:+ """Hand one viewer the size the PTY is really in — never fatally.++ One screen that cannot be told (a socket mid-close, a handler that raises)+ must not cost the resize that already happened, nor the other screens+ their notice.+ """+ if watched.geometry is None:+ return+ try:+ watched.geometry(cols, rows)+ except Exception as exc: # noqa: BLE001 - one viewer's notice, not the resize+ logger.debug(+ "Agentic IDE: could not report a {}x{} geometry to a viewer: {}", cols, rows, exc+ )+++def _announce_geometry(term: Terminal, cols: int, rows: int, *, except_viewer: Any = None) -> None:+ """Tell every attached viewer BUT ``except_viewer`` the PTY's new size.++ A pane open in two windows has two screens and one pseudo-terminal, and the+ screen that does not hold the pane has no way of its own to notice that+ the size moved under it: its tile never changed, so it never measures+ again, and it goes on holding a grid the agent is no longer drawing for.+ The agent's next repaint then lands in that grid as fragments — rows+ wrapped at the wrong width, an interface finished into the corner of a+ pane that is much larger (reported 2026-08-25, a desktop pane displaced+ by a browser tab a tool had opened).++ The viewer that ASKED for the size is left out: it reflowed itself before+ asking, and the socket route reports to it separately when — and only+ when — its request was not granted (``report_geometry``).+ """+ for watched in term.watchers:+ if except_viewer is not None and _same_viewer(watched.output, except_viewer):+ continue+ _tell_geometry(watched, cols, rows)++def _viewers(term: Terminal) -> list[Any]:"""Every output callback this pane should write to, newest last.@@ -1679,6 +1756,30 @@ class Registry:"""Every open workspace as a tab card, in tab order."""return [s.to_card(active=s.id == self._active) for s in self._sessions.values()]+ def panes(self) -> list[dict[str, Any]]:+ """Every pane of EVERY open workspace, as rows for a conversation list.++ ``state()`` answers with the front workspace alone, because that is the+ one being drawn. A list of "everything I have running" is the other+ question: a workspace in a background tab is not a workspace that+ stopped, and a list that omits its four agents tells the user they have+ none. So this walks all of them, in tab order, and marks which one is at+ the front rather than hiding the rest.++ Each row carries its workspace's identity — the folder is what the list+ groups by, and the id is what a click needs to bring that tab forward.+ """+ rows: list[dict[str, Any]] = []+ for session in self._sessions.values():+ for term in session.terminals:+ row = term.to_row()+ row["workspace_id"] = session.id+ row["workspace_name"] = session.name+ row["folder"] = session.folder+ row["workspace_active"] = session.id == self._active+ rows.append(row)+ return rows+def state(self) -> dict[str, Any]:session = self.sessionreturn {@@ -2186,7 +2287,13 @@ class Registry:# hints describe instead of failing the reopen.if space.layout is not None:try:- session.layout = layout_tree.from_dict(space.layout)+ # Squared up on the way in: a workspace remembered as columns+ # side by side draws the same picture with one full-height+ # seam welding its bands together, and a reopen is the moment+ # to hand it back its per-band seams (see `rows_outermost`).+ session.layout = layout_tree.rows_outermost(+ layout_tree.from_dict(space.layout)+ )except ValueError as exc:logger.warning("Agentic IDE: the remembered layout of {} is unreadable, "@@ -2590,6 +2697,7 @@ class Registry:appearance: str | None = None,on_replay: Any = None,claim_owner: bool = True,+ on_geometry: Any = None,) -> Terminal:"""Point a viewer at terminal ``key`` — one attach at a time per pane.@@ -2612,6 +2720,9 @@ class Registry:replay goes to ``on_output`` — correct for an internal caller that onlywants the bytes, and wrong for a viewer that draws them, which is whythe socket route passes one.++ ``on_geometry`` is told, synchronously, whenever the shared PTY takes a+ size this viewer did not ask for — see ``_announce_geometry``."""found = self._locate(key, workspace_id)if found is None:@@ -2630,6 +2741,7 @@ class Registry:appearance=appearance,on_replay=on_replay,claim_owner=claim_owner,+ on_geometry=on_geometry,)async def _attach_locked(@@ -2643,6 +2755,7 @@ class Registry:appearance: str | None = None,on_replay: Any = None,claim_owner: bool = True,+ on_geometry: Any = None,) -> Terminal:"""Point a viewer at terminal ``key``, starting its agent if needed.@@ -2750,6 +2863,7 @@ class Registry:cols,rows,claim_owner=claim_owner,+ on_geometry=on_geometry,)term.reattached = Trueterm.stopping = False@@ -2764,6 +2878,10 @@ class Registry:# The TUI is about to redraw itself for the new geometry;# that redraw must not read as the agent working.term.last_resize_at = time.time()+ # The screens this viewer just displaced hold the old+ # grid; they follow the new one now, not at their next+ # unrelated window resize.+ _announce_geometry(term, cols, rows, except_viewer=on_output)needs_repaint = term.replay.truncatedif geometry_changed and is_coding_agent(term.agent):# A cursor-addressed TUI stream is meaningful only at the size@@ -2884,7 +3002,7 @@ class Registry:# in the replay buffer belongs to a terminal that no longer exists, and# replaying it to the next viewer would show output from a dead agent.term.replay.clear()- _watch(term, on_output, on_exit, cols, rows)+ _watch(term, on_output, on_exit, cols, rows, on_geometry=on_geometry)term.reattached = False# This pane is wanted again, so the last deliberate kill is history.term.stopping = False@@ -3674,6 +3792,9 @@ class Registry:# finished pane does not read as "working" every time the grid# re-lays itself out (chat view toggle, maximize, a dragged seam).term.last_resize_at = time.time()+ # Every OTHER screen on this pane is now showing a grid the agent is+ # no longer drawing for; tell them, so they can follow the owner.+ _announce_geometry(term, cols, rows, except_viewer=viewer)if is_coding_agent(term.agent):# Future viewers must not replay cursor moves produced for the old# grid into the new one. The live viewer already has its screen;@@ -3758,6 +3879,14 @@ class Registry:"Agentic IDE: could not restore {} to its promoted viewer's geometry",term.name,)+ # The survivor spent its time as a watcher following the departed+ # owner's grid, and the restore above leaves it out on purpose (it+ # is the viewer that "asked"). It is told outright instead: whether+ # the PTY moved or not, the size it is in now is the one to show,+ # and a screen holding the old owner's strip would otherwise keep+ # it until something in that window happened to resize.+ if term.pty_cols and term.pty_rows:+ _tell_geometry(survivor, term.pty_cols, term.pty_rows)returnterm.viewer_output = Noneterm.viewer_exit = None@@ -4578,7 +4707,9 @@ class Registry:return data# -------------------------------------------------------- name resolution- def find_terminal(self, wanted: str) -> tuple[Session, Terminal] | None:+ def find_terminal(+ self, wanted: str, workspace_id: str | None = None+ ) -> tuple[Session, Terminal] | None:"""A pane by call-sign, anywhere — the front workspace answering first.The FRONT workspace deciding first is what makes positional call-signs@@ -4591,7 +4722,19 @@ class Registry:a pane precisely so they can address it from anywhere: "tell Mika torun the tests" is an instruction to Mika, not a request to first go andfind which tab Mika is in.++ ``workspace_id`` turns that off and asks ONE workspace. A caller holding+ a list of panes already knows which tab each row came from, and letting+ the front workspace answer for it would hand back the wrong pane's+ conversation whenever two tabs both have a T1 — which every pair of+ workspaces does, since each numbers its panes from one."""+ if workspace_id is not None:+ owner = self._sessions.get(workspace_id)+ if owner is None:+ return None+ term = owner.find(wanted)+ return None if term is None else (owner, term)session = self.sessionif session is not None:term = session.find(wanted)diff --git a/jarvis/agentic_ide/workspace_view.py b/jarvis/agentic_ide/workspace_view.pyindex 029f4ee13f..d00ac8457d 100644--- a/jarvis/agentic_ide/workspace_view.py+++ b/jarvis/agentic_ide/workspace_view.py@@ -1,11 +1,10 @@-"""Which surface the Agentic IDE is showing right now.+"""Which way the user is reading the open workspace right now.-The backend has to know, and not for looks: deictic reference depends on it.-"This terminal" is only answerable when exactly one pane fills the screen, and-neither surface does that any more — the grid puts a dozen panes up, and since-2026-08-24 ``chat`` is not a way of reading them at all but the agent chat in-the workspace's folder, with no terminal on screen. So the report is what tells-the voice path to ask for a call-sign instead of guessing.+The Agentic IDE renders one set of panes two different ways, and the backend+has to know which one is on screen — not for looks, but because deictic+reference depends on it: "this terminal" is only answerable when exactly one+pane fills the screen. Chat view puts one there; the grid puts a dozen, and+guessing among them is less honest than asking for a call-sign.This module is layer 0 of the five-layer enum pattern(``docs/anti-drift-three-layer.md``). The value crosses from this package into@@ -24,19 +23,17 @@ from __future__ import annotations#: The wall of terminals — every pane visible at once, sized by dragged seams.VIEW_GRID = "grid"-#: The agent chat, running in this workspace's folder. No pane is on screen;-#: the terminals stay alive behind it (the browser covers them, never unmounts-#: them) and come back untouched when the grid does.+#: One pane on a calm stage, the rest on a rail, read like a conversation.VIEW_CHAT = "chat"-#: Every value the contract allows, in the order the switch offers them.+#: Every value the contract allows, in the order the toolbar offers them.WORKSPACE_VIEWS: tuple[str, ...] = (VIEW_GRID, VIEW_CHAT)#: What an unreadable or absent value falls back to.#:-#: The grid, deliberately: it is the surface that promises the least. A report-#: that arrives garbled must not be able to put a workspace into a state that-#: answers "this terminal" with a pane the user is not looking at.+#: The grid, deliberately: it is the view that promises the least. A surface+#: report that arrives garbled must not be able to switch a workspace into a+#: mode that answers "this terminal" with a pane the user is not looking at.VIEW_DEFAULT = VIEW_GRIDdiff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsxindex 78f31843e0..eafa3897b7 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx@@ -1354,6 +1354,115 @@ describe("pane refit", () => {});});+ /*+ * A pane open in two places — the desktop app and a tab some tool opened to+ * take a look — has two screens and ONE pseudo-terminal, and the server+ * hands the size to one of them. The other is told what the owner chose+ * (a `size` frame) and follows it, which is right while it is merely+ * watching and wrong the moment the user turns to it: until 2026-08-25 a+ * pane maximized in the desktop app was fitted to the whole window and+ * then resized straight back to the tab's strip, its agent drawing into+ * the top-left corner of it. Every size change the user makes HERE takes+ * the pane back.+ */+ const displacedBy = (cols: number, rows: number) => {+ act(() => {+ terminalHarness.handlers.current?.onGeometry?.({ cols, rows } as never);+ });+ expect(terminalHarness.resize).toHaveBeenCalledWith(cols, rows);+ terminalHarness.send.mockClear();+ };++ it("takes the pane back when it is maximized after another viewer took the size", () => {+ const view = render(pane(false));+ settle();+ displacedBy(30, 10);++ view.rerender(pane(true));+ settle();++ expect(terminalHarness.send).toHaveBeenCalledWith({+ t: "claim",+ cols: 80,+ rows: 24,+ });+ });++ it("takes the pane back when a seam drag ends after another viewer took the size", () => {+ const view = render(pane(false, { layoutBusy: true }));+ settle();+ displacedBy(30, 10);++ view.rerender(pane(false, { layoutBusy: false }));+ settle();++ expect(terminalHarness.send).toHaveBeenCalledWith({+ t: "claim",+ cols: 80,+ rows: 24,+ });+ });++ it("takes the pane back on a click even while the document claims to be hidden", () => {+ // The desktop shell can report an on-screen window as hidden for minutes+ // (2026-08-23). A pointer pressed on the pane is proof enough of where+ // the user is — gating this on the document's word left the app unable+ // to take its own terminals back at all.+ render(pane(false));+ settle();+ displacedBy(30, 10);+ vi.spyOn(document, "hasFocus").mockReturnValue(false);+ Object.defineProperty(document, "hidden", {+ configurable: true,+ get: () => true,+ });++ try {+ fireEvent.mouseDown(screen.getByTestId("agentic-terminal-host-Dana"));+ settle();+ } finally {+ Reflect.deleteProperty(document, "hidden");+ }++ expect(terminalHarness.send).toHaveBeenCalledWith({+ t: "claim",+ cols: 80,+ rows: 24,+ });+ });++ it("does not take a pane it is only watching from a window without focus", () => {+ // The browser tab beside the app, not in front: it follows the owner's+ // grid and stays quiet, whatever its own layout does.+ const view = render(pane(false));+ settle();+ displacedBy(30, 10);+ vi.spyOn(document, "hasFocus").mockReturnValue(false);++ view.rerender(pane(true));+ settle();++ expect(terminalHarness.send).not.toHaveBeenCalledWith(+ expect.objectContaining({ t: "claim" }),+ );+ });++ it("claims once, not on every pass of a settling layout", () => {+ // Three passes follow a maximize (see the effect). Holding the size after+ // the first, the pane has nothing to add on the next two.+ const view = render(pane(false));+ settle();+ displacedBy(30, 10);++ view.rerender(pane(true));+ settle();++ const claims = terminalHarness.send.mock.calls.filter(+ ([frame]) => (frame as { t: string }).t === "claim",+ );+ expect(claims).toHaveLength(1);+ });+it("keeps offering a size the socket could not carry", () => {// A pane measured while its backend was restarting must not treat the// frame as delivered. Nothing measures a pane again on its own, so a size@@ -1375,7 +1484,7 @@ describe("pane refit", () => {settle();expect(terminalHarness.send).toHaveBeenCalledWith({- t: "r",+ t: "claim",cols: 200,rows: 24,});@@ -1410,7 +1519,7 @@ describe("pane refit", () => {expect(terminalHarness.fit).toHaveBeenCalled();expect(terminalHarness.send).toHaveBeenCalledWith({- t: "r",+ t: "claim",cols: 66,rows: 20,});@@ -1438,7 +1547,7 @@ describe("pane refit", () => {expect(terminalHarness.fit).toHaveBeenCalled();expect(terminalHarness.send).toHaveBeenCalledWith({- t: "r",+ t: "claim",cols: 17,rows: 6,});@@ -1470,7 +1579,7 @@ describe("pane refit", () => {// fit() sizes xterm to the tile, so the agent hearing the tile's own// measurement IS the two agreeing.expect(terminalHarness.send).toHaveBeenCalledWith({- t: "r",+ t: "claim",cols: size.cols,rows: size.rows,});@@ -1514,7 +1623,7 @@ describe("pane refit", () => {// The pane takes the tile's 40 columns without touching a single point of// the reader's text size, which is what this pins.expect(terminalHarness.send).toHaveBeenCalledWith({- t: "r",+ t: "claim",cols: 40,rows: 20,});@@ -1742,7 +1851,7 @@ describe("pane refit while the agent is drawing", () => {expect(screen.queryByTestId("pane-too-narrow-Dana")).toBeNull();expect(screen.queryByTestId("pane-width-notice-Dana")).toBeNull();expect(terminalHarness.send).toHaveBeenCalledWith({- t: "r",+ t: "claim",cols: 22,rows: 30,});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneConversation.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneConversation.tsxnew file mode 100644index 0000000000..2c7c26e2f0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneConversation.tsx@@ -0,0 +1,204 @@+/**+ * A pane's conversation, read from the CLI's own record — the shared half.+ *+ * The dialog opened from a pane's scroll rail is what reads it: a look at the+ * conversation of the pane you are already watching, with a real scrollbar.+ * The fetch, the three empty states and the turn rendering live here rather+ * than inside that dialog so a second reader can be added without either of+ * them drifting from the other.+ *+ * Why the transcript comes from the CLI's file rather than the pane's screen is+ * argued in `jarvis/agentic_ide/agent_transcript.py`: a TUI is a picture, and+ * anything that reconstructs a conversation from it guesses.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import { AlertCircle, BookOpenText, RefreshCw } from "lucide-react";++import { useT } from "@/i18n";+import {+ fetchTerminalConversation,+ type ConversationResponse,+ type ConversationTurn,+} from "@/lib/agenticIdeApi";+import { cn } from "@/lib/utils";++export interface PaneConversationState {+ loading: boolean;+ error: string;+ conversation: ConversationResponse | null;+ /** Fetch again — the surfaces put this behind their own refresh button. */+ reload: () => void;+}++/**+ * Load one pane's conversation.+ *+ * `enabled` exists for the dialog, which is mounted while closed: fetching a+ * megabyte-tail transcript for a dialog nobody opened is a cost with nothing on+ * screen to show for it.+ */+export function usePaneConversation(+ terminal: string,+ workspaceId?: string,+ enabled = true,+): PaneConversationState {+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState("");+ const [conversation, setConversation] = useState<ConversationResponse | null>(null);+ const [reloadToken, setReloadToken] = useState(0);++ useEffect(() => {+ if (!enabled) return;+ let current = true;+ setLoading(true);+ setError("");+ fetchTerminalConversation(terminal, workspaceId)+ .then((result) => {+ if (current) setConversation(result);+ })+ .catch((reason: unknown) => {+ if (current) setError(reason instanceof Error ? reason.message : String(reason));+ })+ .finally(() => {+ if (current) setLoading(false);+ });+ return () => {+ current = false;+ };+ }, [enabled, reloadToken, terminal, workspaceId]);++ const reload = useCallback(() => setReloadToken((token) => token + 1), []);+ return { loading, error, conversation, reload };+}++/**+ * The conversation itself: skeleton, error, empty, or the turns.+ *+ * One component for all four because they are one question — "what is there to+ * read?" — and a surface that hand-rolled three of them would be the surface+ * that forgets one.+ */+export function PaneConversationBody({+ state,+ className,+ testId,+}: {+ state: PaneConversationState;+ className?: string;+ testId?: string;+}): JSX.Element {+ const t = useT();+ const scrollerRef = useRef<HTMLDivElement | null>(null);+ const { loading, error, conversation, reload } = state;+ const turns = conversation?.turns ?? [];+ const empty = !loading && !error && (!conversation || !conversation.available || turns.length === 0);++ useEffect(() => {+ // The newest exchange is what the user scrolled up FROM, so the view starts+ // at the bottom — exactly like the terminal it explains.+ if (loading || !conversation) return;+ const scroller = scrollerRef.current;+ if (scroller) scroller.scrollTop = scroller.scrollHeight;+ }, [loading, conversation]);++ if (loading) {+ return (+ <div className={cn("flex-1 space-y-4 overflow-hidden p-6", className)}>+ {["w-3/4", "w-full", "w-5/6", "w-2/3", "w-full", "w-4/5"].map((width, row) => (+ <div key={row} className={cn("h-3 animate-pulse rounded bg-muted/70", width)} />+ ))}+ </div>+ );+ }++ if (error) {+ return (+ <div className={cn("flex flex-1 flex-col items-center justify-center px-6 text-center", className)}>+ <AlertCircle className="mb-3 h-6 w-6 text-destructive" aria-hidden="true" />+ <p className="text-sm font-medium text-foreground">+ {t("agentic_grid.conversation.load_failed")}+ </p>+ <p className="mt-1 max-w-md text-xs text-muted-foreground" role="alert">+ {error}+ </p>+ <button+ type="button"+ onClick={reload}+ className="mt-4 inline-flex h-9 items-center gap-2 rounded-lg border border-border px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted active:translate-y-px"+ >+ <RefreshCw className="h-3.5 w-3.5" aria-hidden="true" />+ {t("agentic_grid.conversation.retry")}+ </button>+ </div>+ );+ }++ if (empty) {+ return (+ <div className={cn("flex flex-1 flex-col items-center justify-center px-6 text-center", className)}>+ <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl border border-border bg-muted/30">+ <BookOpenText className="h-5 w-5 text-muted-foreground" aria-hidden="true" />+ </div>+ <p className="text-sm font-medium text-foreground">+ {t("agentic_grid.conversation.empty_title")}+ </p>+ <p className="mt-1 max-w-sm text-xs leading-relaxed text-muted-foreground">+ {t("agentic_grid.conversation.empty_detail")}+ </p>+ </div>+ );+ }++ return (+ <div+ ref={scrollerRef}+ data-testid={testId ?? "pane-conversation-scroller"}+ className={cn("min-h-0 flex-1 overflow-y-auto scroll-pt-4 px-5 py-4 scrollbar-jarvis", className)}+ >+ {turns.map((turn, index) => (+ <TurnBlock key={index} turn={turn} />+ ))}+ </div>+ );+}++function TurnBlock({ turn }: { turn: ConversationTurn }): JSX.Element {+ const t = useT();+ const user = turn.role === "user";+ const tools = [...new Set(turn.steps.map((step) => step.tool))];+ const steps = t(+ turn.steps.length === 1+ ? "agentic_grid.conversation.steps_one"+ : "agentic_grid.conversation.steps_many",+ ).replace("{0}", String(turn.steps.length));+ return (+ <div className="mb-4 last:mb-0">+ <div+ className={cn(+ "mb-1 text-[10px] font-semibold uppercase tracking-[0.14em]",+ user ? "text-primary" : "text-muted-foreground",+ )}+ >+ {t(user ? "agentic_grid.conversation.you" : "agentic_grid.conversation.agent")}+ </div>+ {turn.text && (+ <div+ className={cn(+ "whitespace-pre-wrap break-words rounded-xl border px-3.5 py-2.5 text-[12.5px] leading-relaxed",+ user+ ? "border-primary/25 bg-primary/[0.07] text-foreground"+ : "border-border/60 bg-background/35 text-foreground/90",+ )}+ >+ {turn.text}+ </div>+ )}+ {turn.steps.length > 0 && (+ <div className="mt-1 truncate text-[10px] text-muted-foreground/80">+ {steps}+ {tools.length > 0 && <> · {tools.slice(0, 6).join(", ")}</>}+ </div>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneConversationDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneConversationDialog.tsxindex 9f6968abde..243ba3520c 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneConversationDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneConversationDialog.tsx@@ -8,26 +8,20 @@* agentic_ide_routes.py), which Jarvis owns end-to-end — so the scrollbar* here is a normal, accurate browser scrollbar over real content, identical* for every provider. Opened from the pane scroll rail.+ *+ * The fetch and the turns are shared with the session PAGE the chat sidebar+ * opens (./PaneConversation); this file is the dialog frame around them.*/-import { useEffect, useRef, useState } from "react";import * as Dialog from "@radix-ui/react-dialog";-import { AlertCircle, BookOpenText, RefreshCw, X } from "lucide-react";+import { BookOpenText, RefreshCw, X } from "lucide-react";import { useT } from "@/i18n";import {- fetchTerminalConversation,- type ConversationResponse,- type ConversationTurn,-} from "@/lib/agenticIdeApi";+ PaneConversationBody,+ usePaneConversation,+} from "@/components/agentic/PaneConversation";import { cn } from "@/lib/utils";-function fill(template: string, ...values: Array<string | number>): string {- return values.reduce<string>(- (text, value, index) => text.replace(`{${index}}`, String(value)),- template,- );-}-export function PaneConversationDialog({terminal,open,@@ -38,47 +32,9 @@ export function PaneConversationDialog({onOpenChange: (open: boolean) => void;}): JSX.Element {const t = useT();- const [loading, setLoading] = useState(false);- const [error, setError] = useState("");- const [conversation, setConversation] = useState<ConversationResponse | null>(- null,- );- const [reloadToken, setReloadToken] = useState(0);- const scrollerRef = useRef<HTMLDivElement | null>(null);-- useEffect(() => {- if (!open) return;- let current = true;- setLoading(true);- setError("");- fetchTerminalConversation(terminal)- .then((result) => {- if (current) setConversation(result);- })- .catch((reason: unknown) => {- if (current) {- setError(reason instanceof Error ? reason.message : String(reason));- }- })- .finally(() => {- if (current) setLoading(false);- });- return () => {- current = false;- };- }, [open, reloadToken, terminal]);-- useEffect(() => {- // The newest exchange is what the user scrolled up FROM, so the view- // starts at the bottom — exactly like the terminal it explains.- if (loading || !conversation) return;- const scroller = scrollerRef.current;- if (scroller) scroller.scrollTop = scroller.scrollHeight;- }, [loading, conversation]);-- const turns = conversation?.turns ?? [];- const empty =- !loading && !error && (!conversation || !conversation.available || turns.length === 0);+ // Mounted while closed on purpose (the rail keeps it), so the fetch waits+ // for the dialog to actually be opened.+ const state = usePaneConversation(terminal, undefined, open);return (<Dialog.Root open={open} onOpenChange={onOpenChange}>@@ -98,7 +54,7 @@ export function PaneConversationDialog({<div className="mb-1 flex items-center gap-2"><BookOpenText className="h-4 w-4 text-primary" aria-hidden="true" /><Dialog.Title className="font-display text-base font-semibold tracking-tight text-foreground">- {fill(t("agentic_grid.conversation.title"), terminal)}+ {t("agentic_grid.conversation.title").replace("{0}", terminal)}</Dialog.Title></div><Dialog.Description className="text-xs leading-relaxed text-muted-foreground">@@ -111,7 +67,7 @@ export function PaneConversationDialog({aria-label={t("agentic_grid.conversation.refresh")}title={t("agentic_grid.conversation.refresh")}data-testid="pane-conversation-refresh"- onClick={() => setReloadToken((token) => token + 1)}+ onClick={state.reload}className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground active:translate-y-px"><RefreshCw className="h-4 w-4" aria-hidden="true" />@@ -128,103 +84,9 @@ export function PaneConversationDialog({</div></header>- {loading ? (- <div className="flex-1 space-y-4 overflow-hidden p-6">- {["w-3/4", "w-full", "w-5/6", "w-2/3", "w-full", "w-4/5"].map(- (width, row) => (- <div- key={row}- className={cn("h-3 animate-pulse rounded bg-muted/70", width)}- />- ),- )}- </div>- ) : error ? (- <div className="flex flex-1 flex-col items-center justify-center px-6 text-center">- <AlertCircle className="mb-3 h-6 w-6 text-destructive" aria-hidden="true" />- <p className="text-sm font-medium text-foreground">- {t("agentic_grid.conversation.load_failed")}- </p>- <p className="mt-1 max-w-md text-xs text-muted-foreground" role="alert">- {error}- </p>- <button- type="button"- onClick={() => setReloadToken((token) => token + 1)}- className="mt-4 inline-flex h-9 items-center gap-2 rounded-lg border border-border px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted active:translate-y-px"- >- <RefreshCw className="h-3.5 w-3.5" aria-hidden="true" />- {t("agentic_grid.conversation.retry")}- </button>- </div>- ) : empty ? (- <div className="flex flex-1 flex-col items-center justify-center px-6 text-center">- <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl border border-border bg-muted/30">- <BookOpenText className="h-5 w-5 text-muted-foreground" aria-hidden="true" />- </div>- <p className="text-sm font-medium text-foreground">- {t("agentic_grid.conversation.empty_title")}- </p>- <p className="mt-1 max-w-sm text-xs leading-relaxed text-muted-foreground">- {t("agentic_grid.conversation.empty_detail")}- </p>- </div>- ) : (- <div- ref={scrollerRef}- data-testid="pane-conversation-scroller"- className="min-h-0 flex-1 overflow-y-auto scroll-pt-4 px-5 py-4 scrollbar-jarvis"- >- {turns.map((turn, index) => (- <TurnBlock key={index} turn={turn} />- ))}- </div>- )}+ <PaneConversationBody state={state} /></Dialog.Content></Dialog.Portal></Dialog.Root>);}--function TurnBlock({ turn }: { turn: ConversationTurn }): JSX.Element {- const t = useT();- const user = turn.role === "user";- const tools = [...new Set(turn.steps.map((step) => step.tool))];- return (- <div className="mb-4 last:mb-0">- <div- className={cn(- "mb-1 text-[10px] font-semibold uppercase tracking-[0.14em]",- user ? "text-primary" : "text-muted-foreground",- )}- >- {t(user ? "agentic_grid.conversation.you" : "agentic_grid.conversation.agent")}- </div>- {turn.text && (- <div- className={cn(- "whitespace-pre-wrap break-words rounded-xl border px-3.5 py-2.5 text-[12.5px] leading-relaxed",- user- ? "border-primary/25 bg-primary/[0.07] text-foreground"- : "border-border/60 bg-background/35 text-foreground/90",- )}- >- {turn.text}- </div>- )}- {turn.steps.length > 0 && (- <div className="mt-1 truncate text-[10px] text-muted-foreground/80">- {fill(- t(- turn.steps.length === 1- ? "agentic_grid.conversation.steps_one"- : "agentic_grid.conversation.steps_many",- ),- turn.steps.length,- )}- {tools.length > 0 && <> · {tools.slice(0, 6).join(", ")}</>}- </div>- )}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.tsxindex e4c97f011c..a4375ef299 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.tsx@@ -90,15 +90,6 @@ interface WorkspaceBarProps {* so the controls ride along in the space that was already there.*/actions?: React.ReactNode;- /**- * The `Chat | Grid` switch, pinned between the tabs and the controls.- *- * It lives in THIS row and nowhere else because it is the one control that- * has to be reachable from both surfaces it switches between — put it in the- * grid's own toolbar and pressing "Chat" would take the way back off screen- * with it.- */- viewSwitch?: React.ReactNode;/*** Rendered INSIDE another bar rather than as its own — drops the frame (its* border and outer padding) so the host row draws exactly one line.@@ -118,7 +109,6 @@ export function WorkspaceBar({onDropFiles,busy = false,actions,- viewSwitch,embedded = false,}: WorkspaceBarProps) {const t = useT();@@ -278,7 +268,7 @@ export function WorkspaceBar({// Nothing open, nothing to add to and no controls to carry: the wizard IS the// screen, and an empty bar above it would be furniture.- if (!hasTabs && !actions && !viewSwitch) return null;+ if (!hasTabs && !actions) return null;return (<div@@ -588,15 +578,6 @@ export function WorkspaceBar({</div>)}- {viewSwitch && (- <div- data-testid="workspace-bar-view-switch"- className="flex shrink-0 items-center"- >- {viewSwitch}- </div>- )}-{actions && (<divdata-testid="workspace-bar-actions"diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.tsxindex 0637bfe342..e49d65d341 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.tsx@@ -1,9 +1,11 @@import { useEffect, useMemo, useState } from "react";-import { ChevronLeft, Folder, MessageSquare, Plus, Trash2 } from "lucide-react";+import { ChevronLeft, Folder, MessageSquare, Plus, Terminal, Trash2 } from "lucide-react";import { CONVERSATIONS_REFRESH_MS } from "@/hooks/useConversations";import { useAgentSessionStore } from "@/store/agentChat";import { useIdeChatStore } from "@/store/ideChat";+import { useWorkspacePanes } from "@/store/workspacePanes";+import type { WorkspacePaneRow } from "@/lib/agenticIdeApi";import { folderLeaf } from "@/lib/folderPath";import { folderColor } from "@/components/agentic/folderColor";import { cn } from "@/lib/utils";@@ -22,6 +24,13 @@ const FOLDED = 5;* repository any of them is touching. The folder you have open leads, under* its own band; everything else follows underneath.*+ * Above the chats: the coding sessions RUNNING in the open workspace — the+ * panes of the terminal grid. Switching from grid to chat used to leave them+ * behind, because this column knew only about chat sessions and the grid knew+ * only about panes, so the same workspace looked like two unrelated places+ * depending on which view was on (maintainer, 2026-08-25). They are one list+ * now: click a session here and the view brings that pane to the front.+ ** The way back is the first thing in the column, not a hidden gesture: a* sidebar that swallows the navigation with no visible exit is a trap, so the* "Sections" button sits at the top where a back button belongs.@@ -31,6 +40,11 @@ export function WorkspaceChats() {const workspace = useIdeChatStore((s) => s.workspace);const setSidebarFace = useIdeChatStore((s) => s.setSidebarFace);+ const requestPane = useIdeChatStore((s) => s.requestPane);+ const stagedPane = useIdeChatStore((s) => s.stagedPane);+ // Shares one poll with every other reader of the list (see the store).+ const panes = useWorkspacePanes();+const sessions = useAgentSessionStore((s) => s.sessions);const activeSessionId = useAgentSessionStore((s) => s.activeSessionId);const loadSessions = useAgentSessionStore((s) => s.loadSessions);@@ -52,6 +66,17 @@ export function WorkspaceChats() {// The open workspace's folder always sorts first (see `groupByFolder`), so// the leading group is "this workspace" — unless nothing is open, in which// case every group is just another folder.+ /*+ * The sessions of the workspace that is open, in the grid's own order.+ *+ * Only this workspace's: the other tabs have their own panes, and a column+ * that mixed all of them would say nothing about where any of them runs.+ */+ const sessionsHere = useMemo(+ () => (workspace ? panes.filter((pane) => pane.workspace_id === workspace.id) : []),+ [panes, workspace],+ );+const openFolder = workspace?.path ?? "";const leads = openFolder !== "" && groups[0]?.folder === openFolder;const here = leads ? groups[0] : null;@@ -89,6 +114,27 @@ export function WorkspaceChats() {</div><div className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-1 pb-3">+ {workspace && (+ <section data-testid="workspace-chats-sessions">+ <Band>{t("ide_chats.running_sessions")}</Band>+ {sessionsHere.length === 0 ? (+ <p className="px-3 py-1 text-[11px] text-muted-foreground/50">+ {t("ide_chats.no_sessions_here")}+ </p>+ ) : (+ <ul className="space-y-px">+ {sessionsHere.map((pane) => (+ <SessionRow+ key={pane.history_id}+ pane={pane}+ active={pane.name === stagedPane}+ onOpen={() => requestPane(pane.workspace_id, pane.name)}+ />+ ))}+ </ul>+ )}+ </section>+ )}{here && (<><Band>{t("ide_chats.this_workspace")}</Band>@@ -208,6 +254,68 @@ function FolderGroup({);}+/**+ * One coding session of the open workspace.+ *+ * Reads like the chat row below it on purpose — same height, same indent, same+ * active treatment — because from where the user sits these are the same kind+ * of thing: a conversation with an agent. What differs is the mark (a terminal,+ * not a speech bubble) and the dot, which carries the state the grid's badge+ * shows: running, waiting to start, or finished.+ */+function SessionRow({+ pane,+ active,+ onOpen,+}: {+ pane: WorkspacePaneRow;+ active: boolean;+ onOpen: () => void;+}) {+ const t = useT();+ const label = pane.display_name || pane.name;+ return (+ <li className="group relative">+ <button+ type="button"+ onClick={onOpen}+ title={`${label} · ${pane.agent}`}+ data-testid="workspace-session-row"+ data-pane={pane.name}+ data-status={pane.status}+ className={cn(+ "flex w-full items-center gap-2 rounded-lg py-1.5 pl-3 pr-2 text-left transition-colors",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",+ active ? "bg-card text-foreground shadow-sm" : "hover:bg-background/60",+ )}+ >+ <Terminal+ aria-hidden+ className={cn("h-3.5 w-3.5 shrink-0", active ? "text-primary" : "text-muted-foreground")}+ />+ <span className="min-w-0 flex-1 truncate text-xs text-foreground">{label}</span>+ <span className="shrink-0 truncate font-mono text-[10px] text-muted-foreground/70">+ {pane.name}+ </span>+ <span+ aria-hidden+ title={t("ide_chats.session_here")}+ className={cn(+ "h-1.5 w-1.5 shrink-0 rounded-full",+ pane.status === "live"+ ? "bg-primary"+ : pane.status === "pending"+ ? "bg-muted-foreground/50"+ : pane.status === "error"+ ? "bg-destructive"+ : "bg-muted-foreground/30",+ )}+ />+ </button>+ </li>+ );+}+function ChatRow({id,title,diff --git a/jarvis/ui/web/frontend/src/components/agentic/chatState.test.ts b/jarvis/ui/web/frontend/src/components/agentic/chatState.test.tsnew file mode 100644index 0000000000..63e33ea0c4--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/chatState.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it } from "vitest";+import type { TerminalRecap, TerminalState } from "@/lib/agenticIdeApi";+import {+ chatTerminalIdentity,+ initialChatOrder,+ orderChatTerminals,+ reconcileChatOrder,+ sameRows,+ swapChatOrder,+} from "./chatState";++function terminal(+ key: string,+ column: number,+ historyId = `${key}-lifetime`,+ startedAt = column + 1,+): TerminalState {+ return {+ key,+ name: key.toUpperCase(),+ agent: "codex",+ display_name: "Codex",+ index: column,+ column,+ slot: 0,+ status: "live",+ exit_code: null,+ error: "",+ started_at: startedAt,+ history_id: historyId,+ last_output_at: null,+ idle_seconds: null,+ prompts_sent: 0,+ last_prompt: "",+ lines_captured: 0,+ };+}++function recap(name: string, activity = "waiting"): TerminalRecap {+ return {+ key: name.toLowerCase(),+ name,+ status: "live",+ recap: "Waiting for work",+ recap_detail: "The terminal is ready.",+ activity: activity as TerminalRecap["activity"],+ activity_since: 10,+ worked: true,+ };+}++describe("chat session ordering", () => {+ it("appends a split pane even when the grid inserts it in the middle", () => {+ const previous = ["t1-lifetime", "t2-lifetime", "t3-lifetime"];+ const gridOrderAfterSplit = [+ terminal("t1", 0),+ terminal("t4", 1),+ terminal("t2", 2),+ terminal("t3", 3),+ ];++ expect(reconcileChatOrder(previous, gridOrderAfterSplit)).toEqual([+ "t1-lifetime",+ "t2-lifetime",+ "t3-lifetime",+ "t4-lifetime",+ ]);+ });++ it("keeps surviving panes stable while removing closed panes", () => {+ expect(+ reconcileChatOrder(+ ["t1-lifetime", "t2-lifetime", "t3-lifetime"],+ [terminal("t3", 0), terminal("t1", 1)],+ ),+ ).toEqual(["t1-lifetime", "t3-lifetime"]);+ });++ it("orders terminal objects independently of their grid coordinates", () => {+ const terminals = [terminal("t1", 0), terminal("t3", 1), terminal("t2", 2)];+ expect(+ orderChatTerminals(terminals, ["t1-lifetime", "t2-lifetime", "t3-lifetime"]).map(+ (item) => item.key,+ ),+ ).toEqual(["t1", "t2", "t3"]);+ });++ it("sorts an unseen workspace by pane start time instead of grid position", () => {+ const terminals = [+ terminal("t3", 0, "third", 30),+ terminal("t1", 1, "first", 10),+ terminal("t2", 2, "second", 20),+ ];++ expect(initialChatOrder(terminals)).toEqual(["first", "second", "third"]);+ });++ it("treats a reused call-sign as a new pane lifetime", () => {+ const replacement = terminal("t1", 0, "new-t1", 50);++ expect(reconcileChatOrder(["old-t1", "t2-lifetime"], [replacement, terminal("t2", 1)])).toEqual(+ ["t2-lifetime", "new-t1"],+ );+ expect(chatTerminalIdentity(replacement)).toBe("new-t1");+ });++ it("exchanges exactly the two sessions that were dragged together", () => {+ expect(swapChatOrder(["first", "second", "third", "fourth"], "first", "third"))+ .toEqual(["third", "second", "first", "fourth"]);+ });++ it("keeps the existing order object when either dragged session is gone", () => {+ const order = ["first", "second"];+ expect(swapChatOrder(order, "first", "gone")).toBe(order);+ expect(swapChatOrder(order, "first", "first")).toBe(order);+ });+});++describe("recap poll equality", () => {+ it("recognizes a repeated response", () => {+ const current = { T1: recap("T1") };+ expect(sameRows(current, { T1: { ...current.T1 } })).toBe(true);+ });++ it("detects an activity transition", () => {+ expect(sameRows({ T1: recap("T1") }, { T1: recap("T1", "working") })).toBe(false);+ });++ it("detects a changed optional field even when both values are undefined", () => {+ const before: Record<string, TerminalRecap> = { T1: { ...recap("T1"), note: undefined } };+ const after: Record<string, TerminalRecap> = { T1: { ...recap("T1"), writer: undefined } };+ expect(sameRows(before, after)).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/chatState.ts b/jarvis/ui/web/frontend/src/components/agentic/chatState.tsnew file mode 100644index 0000000000..159008181c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/chatState.ts@@ -0,0 +1,101 @@+import type { TerminalState } from "@/lib/agenticIdeApi";++/** One pane lifetime, independent of its reusable grid call-sign. */+export function chatTerminalIdentity(terminal: TerminalState): string {+ return terminal.history_id ?? `${terminal.key}@${terminal.started_at ?? "pending"}`;+}++/** Best available arrival order when this browser has not seen the workspace. */+export function initialChatOrder(terminals: readonly TerminalState[]): readonly string[] {+ return [...terminals]+ .sort((left, right) => {+ const leftStarted = left.started_at ?? Number.POSITIVE_INFINITY;+ const rightStarted = right.started_at ?? Number.POSITIVE_INFINITY;+ return leftStarted - rightStarted || left.index - right.index;+ })+ .map(chatTerminalIdentity);+}++/** Keep chat sessions in arrival order even when the grid is rearranged. */+export function reconcileChatOrder(+ previous: readonly string[],+ terminals: readonly TerminalState[],+): readonly string[] {+ const current = terminals.map(chatTerminalIdentity);+ const live = new Set(current);+ const next = previous.filter((key) => live.has(key));+ const known = new Set(next);+ for (const key of current) {+ if (!known.has(key)) {+ next.push(key);+ known.add(key);+ }+ }+ return sameStrings(previous, next) ? previous : next;+}++/** Exchange two session positions without disturbing any rows between them. */+export function swapChatOrder(+ previous: readonly string[],+ first: string,+ second: string,+): readonly string[] {+ if (first === second) return previous;+ const firstIndex = previous.indexOf(first);+ const secondIndex = previous.indexOf(second);+ if (firstIndex < 0 || secondIndex < 0) return previous;+ const next = [...previous];+ next[firstIndex] = second;+ next[secondIndex] = first;+ return next;+}++/** Put terminal objects into the stable order used by the chat rail. */+export function orderChatTerminals(+ terminals: readonly TerminalState[],+ identities: readonly string[],+): TerminalState[] {+ const byIdentity = new Map(+ terminals.map((terminal) => [chatTerminalIdentity(terminal), terminal]),+ );+ return identities.flatMap((identity) => {+ const terminal = byIdentity.get(identity);+ return terminal ? [terminal] : [];+ });+}++/**+ * Avoid repainting every terminal when a poll returns unchanged rows.+ *+ * Generic over the row type because two polls need it for the same reason:+ * the recap poll (sentences, every 5s) and the activity poll (status words,+ * every 1.5s) both replace a per-pane map on a timer inside a very large+ * component, and a fresh-but-equal object every tick is a full re-render+ * bought for nothing.+ */+export function sameRows<T extends object>(+ current: Readonly<Record<string, T>>,+ next: Readonly<Record<string, T>>,+): boolean {+ const currentNames = Object.keys(current);+ const nextNames = Object.keys(next);+ if (currentNames.length !== nextNames.length) return false;+ return nextNames.every((name) => {+ const before = current[name];+ const after = next[name];+ if (!before || !after) return false;+ const beforeFields = Object.keys(before) as (keyof T)[];+ const afterFields = Object.keys(after) as (keyof T)[];+ if (+ beforeFields.length !== afterFields.length ||+ afterFields.some((field) => !Object.hasOwn(before, field))+ ) {+ return false;+ }+ return afterFields.every((field) => Object.is(before[field], after[field]));+ });+}++function sameStrings(left: readonly string[], right: readonly string[]): boolean {+ return left.length === right.length && left.every((value, index) => value === right[index]);+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/layout.test.ts b/jarvis/ui/web/frontend/src/components/agentic/layout.test.tsindex ba1f6311d0..d51282bac8 100644--- a/jarvis/ui/web/frontend/src/components/agentic/layout.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/layout.test.ts@@ -216,10 +216,11 @@ describe("columnDepthFor", () => {describe("wizardPanes", () => {it("is the columns of two the backend opens a workspace with", () => {- // Mirrors agentic_ide/session.py, which fills a column to- // WIZARD_COLUMN_HEIGHT before opening the next one. The preview feeds these- // to the same `paneGrid` the running workspace uses, so it cannot describe- // a layout the backend would never build.+ // Mirrors agentic_ide/layout_tree.py `wizard_tree`, which fills a column+ // to WIZARD_COLUMN_HEIGHT before opening the next one. The preview feeds+ // these to the same `paneGrid` the running workspace uses, so it cannot+ // describe a layout the backend would never build. Three does not fill its+ // last column, so it is read down the columns.expect(wizardPanes(3)).toEqual([{ column: 0, slot: 0 },{ column: 0, slot: 1 },@@ -227,6 +228,28 @@ describe("wizardPanes", () => {]);});+ it("fills a full rectangle across its bands, the way the backend seats it", () => {+ // The 2026-08-25 change: a rectangle is stood on its rows so each band+ // resizes on its own, and a tree standing on its rows is read across the+ // top band first. Four terminals therefore run 1-2 above 3-4 — not 1-2+ // down the left and 3-4 down the right, which is what the preview drew+ // while it was still guessing at the fill order.+ expect(wizardPanes(4)).toEqual([+ { column: 0, slot: 0 },+ { column: 1, slot: 0 },+ { column: 0, slot: 1 },+ { column: 1, slot: 1 },+ ]);+ expect(wizardPanes(6)).toEqual([+ { column: 0, slot: 0 },+ { column: 1, slot: 0 },+ { column: 2, slot: 0 },+ { column: 0, slot: 1 },+ { column: 1, slot: 1 },+ { column: 2, slot: 1 },+ ]);+ });+it("has no panes for an empty or nonsensical count", () => {expect(wizardPanes(0)).toEqual([]);expect(wizardPanes(-4)).toEqual([]);diff --git a/jarvis/ui/web/frontend/src/components/agentic/layout.ts b/jarvis/ui/web/frontend/src/components/agentic/layout.tsindex 65040afc2a..0dd55c2007 100644--- a/jarvis/ui/web/frontend/src/components/agentic/layout.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/layout.ts@@ -262,23 +262,36 @@ export const WIZARD_COLUMN_HEIGHT = 2;/*** The panes a wizard-opened workspace of ``count`` terminals starts with.*- * Columns of {@link WIZARD_COLUMN_HEIGHT}, each filled top to bottom before the- * next is opened — which is literally what the backend writes when it opens a- * session from the wizard (`agentic_ide/session.py`, the same arithmetic). Two- * terminals stand one above the other; three are a full column plus one beside- * it; six are three columns of two.- *- * It exists so the preview cannot describe a workspace the backend would never- * build. An earlier preview took a shortcut and derived its dots from the raw- * terminal COUNT, which happened to agree only while every terminal got a- * column of its own. Feed `paneGrid` the same panes the grid will receive and- * the preview stops being a second opinion.+ * Columns of {@link WIZARD_COLUMN_HEIGHT} — which is literally the shape the+ * backend writes when it opens a session from the wizard+ * (`agentic_ide/layout_tree.py`, `wizard_tree`). Two terminals stand one above+ * the other; three are a full column plus one beside it; six are three columns+ * of two.+ *+ * Which pane lands in which cell is the other half, and the two halves parted+ * ways on 2026-08-25. A workspace whose columns form a full RECTANGLE is now+ * stood on its rows by the backend, so that each band can be resized on its+ * own instead of one full-height seam dragging every band with it — and a tree+ * standing on its rows is read across the top band first. So a rectangle is+ * filled across, and a ragged shape (a count that does not fill its last+ * column) keeps being filled down, because it is not stood on anything.+ *+ * The whole function exists so the preview cannot describe a workspace the+ * backend would never build — and that now includes which terminal is WHERE,+ * because the preview labels its tiles with the agents' own names.*/export function wizardPanes(count: number): Positioned[] {- return Array.from({ length: Math.max(0, Math.trunc(count)) }, (_, index) => ({- column: Math.floor(index / WIZARD_COLUMN_HEIGHT),- slot: index % WIZARD_COLUMN_HEIGHT,- }));+ const total = Math.max(0, Math.trunc(count));+ const across = Math.ceil(total / WIZARD_COLUMN_HEIGHT);+ const rectangular = across > 0 && total === across * WIZARD_COLUMN_HEIGHT;+ return Array.from({ length: total }, (_, index) =>+ rectangular+ ? { column: index % across, slot: Math.floor(index / across) }+ : {+ column: Math.floor(index / WIZARD_COLUMN_HEIGHT),+ slot: index % WIZARD_COLUMN_HEIGHT,+ },+ );}/**diff --git a/jarvis/ui/web/frontend/src/store/ideChat.ts b/jarvis/ui/web/frontend/src/store/ideChat.tsindex e7a34b45e5..9b66a852e0 100644--- a/jarvis/ui/web/frontend/src/store/ideChat.ts+++ b/jarvis/ui/web/frontend/src/store/ideChat.ts@@ -37,20 +37,49 @@ export interface IdeWorkspace {*/export type IdeSidebarFace = "chats" | "sections";+/**+ * A session list asking for one pane to be brought to the front.+ *+ * The list lives in the app sidebar, the panes live inside the IDE view, and+ * neither can reach the other by props — so the ask travels through here and+ * the view performs it. The `nonce` is what makes asking for the SAME pane+ * twice work: without it a second click on the pane already staged changes+ * nothing observable, and the click reads as broken.+ */+export interface PaneRequest {+ workspaceId: string;+ pane: string;+ nonce: number;+}+interface IdeChatStore {view: WorkspaceView;workspace: IdeWorkspace | null;sidebarFace: IdeSidebarFace;+ paneRequest: PaneRequest | null;+ /**+ * The pane the chat view currently has on its stage, or null in grid view.+ *+ * Published by the grid so a session list somewhere else can mark the row+ * the user is reading. A list that cannot say which of eleven sessions is+ * open is a list you have to click through to find out.+ */+ stagedPane: string | null;setView: (next: WorkspaceView) => void;setWorkspace: (next: IdeWorkspace | null) => void;setSidebarFace: (next: IdeSidebarFace) => void;+ /** Bring a pane to the front, switching workspace first when it lives elsewhere. */+ requestPane: (workspaceId: string, pane: string) => void;+ setStagedPane: (pane: string | null) => void;}export const useIdeChatStore = create<IdeChatStore>((set) => ({view: storedViewMode() ?? "grid",workspace: null,sidebarFace: "chats",+ paneRequest: null,+ stagedPane: null,setView: (next) => {rememberViewMode(next);@@ -62,4 +91,12 @@ export const useIdeChatStore = create<IdeChatStore>((set) => ({setWorkspace: (next) => set({ workspace: next }),setSidebarFace: (next) => set({ sidebarFace: next }),+ requestPane: (workspaceId, pane) =>+ set((state) => ({+ paneRequest: { workspaceId, pane, nonce: (state.paneRequest?.nonce ?? 0) + 1 },+ })),+ setStagedPane: (pane) =>+ // Guarded: the grid publishes this from an effect that runs on every poll,+ // and an unconditional set would wake every subscriber each time.+ set((state) => (state.stagedPane === pane ? state : { stagedPane: pane })),}));diff --git a/jarvis/ui/web/frontend/src/store/workspacePanes.ts b/jarvis/ui/web/frontend/src/store/workspacePanes.tsnew file mode 100644index 0000000000..3a8a311246--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/workspacePanes.ts@@ -0,0 +1,85 @@+import { useEffect } from "react";+import { create } from "zustand";++import {+ fetchWorkspacePanes,+ type WorkspacePaneRow,+} from "@/lib/agenticIdeApi";++/**+ * Every coding session running in any open workspace, kept fresh in one place.+ *+ * Two views ask the same question at the same time — the chat sidebar's session+ * list and the session page it opens — and both want it to stay current, since+ * the whole point of the list is that a spinner turns into a dot when an agent+ * finishes. One store with ONE poll behind it, rather than a timer per view:+ * the second timer would double the request rate for a payload both are already+ * holding, and the two copies would disagree for up to a poll interval, which+ * is exactly the "working here, done there" split this list exists to end.+ *+ * The poll is reference-counted: it starts when the first view subscribes and+ * stops when the last one leaves, so nothing is polled while nobody is looking.+ */+const REFRESH_MS = 4000;++interface WorkspacePanesStore {+ panes: WorkspacePaneRow[];+ /** The workspace tab at the front, as the backend sees it. */+ activeId: string | null;+ /** Has a first answer arrived? An empty list before that means "not yet". */+ loaded: boolean;+ load: () => Promise<void>;+}++export const useWorkspacePanesStore = create<WorkspacePanesStore>((set) => ({+ panes: [],+ activeId: null,+ loaded: false,++ load: async () => {+ try {+ const result = await fetchWorkspacePanes();+ set({ panes: result.panes, activeId: result.active_id, loaded: true });+ } catch {+ // Offline, headless, or the workspace registry not up yet. The list keeps+ // what it had: a sidebar that empties itself on one failed poll would+ // read as "your agents are gone".+ }+ },+}));++let watchers = 0;+let timer: number | null = null;++/**+ * Subscribe this component to the pane list, sharing one poll with the others.+ *+ * Returns the rows so a caller can use it as a plain hook.+ */+export function useWorkspacePanes(): WorkspacePaneRow[] {+ const panes = useWorkspacePanesStore((s) => s.panes);+ useEffect(() => {+ watchers += 1;+ if (timer === null) {+ void useWorkspacePanesStore.getState().load();+ timer = window.setInterval(() => {+ void useWorkspacePanesStore.getState().load();+ }, REFRESH_MS);+ }+ return () => {+ watchers -= 1;+ if (watchers <= 0 && timer !== null) {+ window.clearInterval(timer);+ timer = null;+ }+ };+ }, []);+ return panes;+}++/** Test seam: forget the shared timer between cases. */+export function resetWorkspacePanesPoll(): void {+ if (timer !== null) window.clearInterval(timer);+ timer = null;+ watchers = 0;+}diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex e2c8d4d006..8a275cf781 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -5,14 +5,7 @@** * no workspace open → a five-step wizard: folder, how many terminals, an* aggregate agent allocation, grid or chat view, then start,- * * workspace open → one of TWO surfaces, picked by the switch in the bar:- * the terminal grid (see AgenticGrid) or the agent chat in this workspace's- * folder (see IdeChatSurface).- *- * The grid is never unmounted for the chat — it is covered. Every pane is a- * live coding agent, and unmounting one kills it; a workspace that lost eleven- * agents because somebody read a chat for a minute would be the worst bug this- * view could have.+ * * workspace open → the terminal grid (see AgenticGrid).** The wizard order is deliberate and matches how the decision actually gets* made: you know the folder first, the number of panes second, then which agent@@ -25,15 +18,8 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Loader2 } from "lucide-react";import { useEventStore } from "@/store/events";-import { AgenticGrid } from "@/components/agentic/AgenticGrid";-import {- storedViewMode,- type WorkspaceView,-} from "@/components/agentic/workspaceView";-import { ViewSwitch } from "@/components/agentic/ViewSwitch";-import { IdeChatSurface } from "@/components/agentic/IdeChatSurface";import { useIdeChatStore } from "@/store/ideChat";-import { cn } from "@/lib/utils";+import { AgenticGrid, rememberViewMode } from "@/components/agentic/AgenticGrid";import {VoiceBubble,storedVoiceBubbleOpen,@@ -172,23 +158,21 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const [folder, setFolder] = useState<string | null>(null);const [count, setCount] = useState(2);const [planned, setPlanned] = useState<PlannedTerminal[]>([]);- // Grid or chat, the wizard's last decision. Starts from the remembered- // reading preference so returning users see their usual answer preselected;- // it is written back only when a workspace actually opens (see `start`).- const [view, setView] = useState<WorkspaceView>(- () => storedViewMode() ?? "grid",- );/*- * Which surface an OPEN workspace is showing — the store, not this state.+ * Grid or chat — held in the store, not here.*- * The switch that changes it lives in the workspace bar and the sidebar- * changes face with it, so the answer has to be readable from outside this- * subtree. The wizard's `view` above is a different question ("how should the- * one I am about to open start?") and stays local until `start` publishes it.+ * Three copies of this answer used to exist (this view, the grid, the+ * store), coupled only by a localStorage key each of them read once on+ * mount. Flipping the switch in the workspace bar therefore moved the grid+ * and nothing else: the sidebar went on showing the app's sections, because+ * its copy of "which view" had been read minutes earlier and never heard+ * about the change (maintainer, 2026-08-25 — the sessions did not come+ * along when the view changed). One store, one answer, every reader on it.*/- const ideView = useIdeChatStore((s) => s.view);- const setIdeView = useIdeChatStore((s) => s.setView);- const setIdeWorkspace = useIdeChatStore((s) => s.setWorkspace);+ const view = useIdeChatStore((s) => s.view);+ const setView = useIdeChatStore((s) => s.setView);+ const publishWorkspace = useIdeChatStore((s) => s.setWorkspace);+ const paneRequest = useIdeChatStore((s) => s.paneRequest);// The registered subscriptions per CLI. Only ever used to OFFER a choice, so// a failed load costs the picker, never the wizard: with none loaded every// pane simply opens on the active account, exactly as before.@@ -573,9 +557,10 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const start = async () => {if (!folder) return;setBusy(true);- // Recorded BEFORE the workspace can mount, so the surface it opens on is- // the one the wizard was asked about. `setView` persists it too.- setIdeView(view);+ // Recorded BEFORE the grid can mount: a grid coming up in a fresh window+ // reads the stored preference, so the wizard's answer has to be on disk by+ // then. `setView` writes it too; this is the belt for the braces.+ rememberViewMode(view);try {// The open answers with the whole state — the new workspace AND the bar.// Re-fetching instead would be a race that can blank what was just opened.@@ -655,10 +640,58 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {* 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() });- };+ const jumpToPane = useCallback(+ async (workspaceId: string, pane: string) => {+ if (workspaceId !== session?.id) await switchTo(workspaceId);+ setJumpTo({ pane, nonce: Date.now() });+ },+ [session?.id, switchTo],+ );++ /*+ * Tell the rest of the app WHICH workspace is open.+ *+ * Nothing published this, so the store's `workspace` stayed null forever and+ * every reader that gates on it — the sidebar's chat face above all — was+ * unreachable code. The folder travels with it because that is the one thing+ * the IDE knows and a chat list does not: which project a session is+ * touching.+ */+ useEffect(() => {+ if (!onScreen) return;+ publishWorkspace(+ session+ ? { id: session.id, name: session.project.name, path: session.folder }+ : null,+ );+ }, [onScreen, publishWorkspace, session]);++ /*+ * Leaving the section hands the navigation back.+ *+ * Without this the sidebar keeps the workspace's chats while the user is+ * reading Costs, because "is a workspace open" stayed true after this view+ * went off screen.+ */+ useEffect(() => {+ if (onScreen) return;+ publishWorkspace(null);+ }, [onScreen, publishWorkspace]);++ /*+ * A session list asked for one pane.+ *+ * The list is in the app sidebar, outside this view and outside the grid, so+ * the ask arrives through the store and is performed here — by the same jump+ * the notification bell and the voice bubble use, which already knows how to+ * switch workspace first.+ */+ const lastPaneRequest = useRef(0);+ useEffect(() => {+ if (!paneRequest || paneRequest.nonce === lastPaneRequest.current) return;+ lastPaneRequest.current = paneRequest.nonce;+ void jumpToPane(paneRequest.workspaceId, paneRequest.pane);+ }, [jumpToPane, paneRequest]);/** A file dropped on a workspace TAB.@@ -867,34 +900,10 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {* carries them even with nothing open, which is why it renders at all in that* case. Passing them here as well would put Restart on screen twice.*/- /*- * The open workspace, published for everyone outside this subtree: the- * sidebar groups its chats by folder, and the chat surface runs in it.- * Cleared when nothing is open so neither shows a folder that is not there.- */- const workspaceFolder = session?.folder ?? "";- const workspaceName = session?.project.name ?? "";- const workspaceId = session?.id ?? "";- useEffect(() => {- setIdeWorkspace(- workspaceId- ? { id: workspaceId, name: workspaceName, path: workspaceFolder }- : null,- );- }, [workspaceId, workspaceName, workspaceFolder, setIdeWorkspace]);-const renderBar = (embedded: boolean) => (<WorkspaceBarembedded={embedded}actions={embedded ? undefined : <TopBarActions />}- /* Only with a workspace open: with none there is nothing to show on- either surface, and the wizard is the screen. A switch that changes- nothing visible is a dead control. */- viewSwitch={- session && !addingNew ? (- <ViewSwitch view={ideView} onView={setIdeView} />- ) : undefined- }workspaces={barWorkspaces}activeId={session?.id ?? null}addingNew={addingNew}@@ -910,80 +919,43 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {// ------------------------------------------------------------ running modeif (session && !addingNew) {- const onChat = ideView === "chat";return (<div className="flex h-full flex-col">- {/*- In chat mode the bar is its own row again: the grid it normally rides- in is behind the chat, and a switch you cannot see is a switch you- cannot switch back with.- */}- {onChat && renderBar(false)}- <div className="relative min-h-0 min-w-0 flex-1">+ <div className="min-h-0 min-w-0 flex-1">{/*Keyed by workspace, so switching tabs REPLACES the grid instead ofre-using it. That is deliberate: each pane's terminal is wired toone call-sign for its whole life, and re-using the component acrossworkspaces would leave xterm instances pointed at the panes of theworkspace that just left.-- COVERED for the chat, never hidden and never unmounted. `display:- none` would measure every terminal at 0x0 and hand its agent a- zero-column window; unmounting would kill the agent outright. At- opacity 0 the panes keep their real geometry and simply are not- looked at, so switching back is instant and nothing was disturbed.*/}- <div- className={cn(- "absolute inset-0",- onChat && "pointer-events-none opacity-0",- )}- aria-hidden={onChat}- data-testid="agentic-grid-layer"- >- <AgenticGrid- key={session.id}- session={session}- view={ideView}- workspaceBar={onChat ? undefined : renderBar(true)}- /* The app's own controls ride in whichever bar is visible;- in chat that is the standalone one above, so the grid must- not render a second, covered copy of them. */- appActions={onChat ? undefined : <TopBarActions />}- onAddProject={() => void startAdding()}- onNewSession={() => void startSession()}- onJumpToWorkspace={(id, pane) => void jumpToPane(id, pane)}- jumpTo={jumpTo}- focusMode={focusMode}- onToggleFocus={(v) => void toggleFocus(v)}- onClose={() => void close()}- busy={busy}- maxTerminals={maxTerminals}- agents={splitChoices}- /* An install started from a split menu changes the one thing this- list answers, and the sweep behind it is cached — so the re-read- is explicit rather than waited for. */- onAgentsChanged={() => void reloadAgents()}- onSessionChanged={setSession}- accounts={ideAccounts}- onStateChanged={applyStateFromSettings}- onScreen={onScreen}- onPromptTargetChange={setPromptTarget}- voiceOpen={voiceOpen}- onToggleVoice={toggleVoiceBubble}- />- </div>- {onChat && (- <div className="absolute inset-0 z-10 flex min-h-0 flex-col bg-background">- <IdeChatSurface- workspace={{- id: session.id,- name: session.project.name,- path: session.folder,- }}- />- </div>- )}+ <AgenticGrid+ key={session.id}+ session={session}+ workspaceBar={renderBar(true)}+ appActions={<TopBarActions />}+ onAddProject={() => void startAdding()}+ onNewSession={() => void startSession()}+ onJumpToWorkspace={(id, pane) => void jumpToPane(id, pane)}+ jumpTo={jumpTo}+ focusMode={focusMode}+ onToggleFocus={(v) => void toggleFocus(v)}+ onClose={() => void close()}+ busy={busy}+ maxTerminals={maxTerminals}+ agents={splitChoices}+ /* An install started from a split menu changes the one thing this+ list answers, and the sweep behind it is cached — so the re-read+ is explicit rather than waited for. */+ onAgentsChanged={() => void reloadAgents()}+ onSessionChanged={setSession}+ accounts={ideAccounts}+ onStateChanged={applyStateFromSettings}+ onScreen={onScreen}+ onPromptTargetChange={setPromptTarget}+ voiceOpen={voiceOpen}+ onToggleVoice={toggleVoiceBubble}+ /></div>{/*The floating voice bubble: talk to the assistant while the agentsdiff --git a/tests/unit/agentic_ide/test_many_terminals.py b/tests/unit/agentic_ide/test_many_terminals.pyindex 2c66843810..dea659d1b1 100644--- a/tests/unit/agentic_ide/test_many_terminals.py+++ b/tests/unit/agentic_ide/test_many_terminals.py@@ -166,8 +166,12 @@ async def test_restoring_a_hundred_panes_keeps_every_position(result = await registry.restore(snapshot)session = result.sessions[0]assert len(session.terminals) == ide.MAX_TERMINALS+ # Every pane sits exactly where it sat — twenty columns of five — read+ # back across the bands rather than down the columns, because a grid+ # stands on its rows once it is restored (`layout_tree.rows_outermost`).+ across = ide.MAX_TERMINALS // 5assert [(t.column, t.slot) for t in session.terminals] == [- (i // 5, i % 5) for i in range(ide.MAX_TERMINALS)+ (i % across, i // across) for i in range(ide.MAX_TERMINALS)]# Every pane keeps its own conversation — no two share a handle.ids = [t.resume.id for t in session.terminals if t.resume]diff --git a/tests/unit/agentic_ide/test_pane_refold.py b/tests/unit/agentic_ide/test_pane_refold.pyindex ef1ac7e3ae..9c09fa4a7b 100644--- a/tests/unit/agentic_ide/test_pane_refold.py+++ b/tests/unit/agentic_ide/test_pane_refold.py@@ -73,12 +73,15 @@ async def test_folds_a_row_of_six_into_three_columns_of_two("""await _open_in_a_row(registry, tmp_path, 6)await registry.refold(2)+ # Three across and two down, dealt in reading order: the panes keep the+ # sequence the user knows them by, so widening the window undoes the fold+ # instead of permuting the workspace.assert _layout(registry) == [("T1", 0, 0),- ("T2", 0, 1),- ("T3", 1, 0),- ("T4", 1, 1),- ("T5", 2, 0),+ ("T2", 1, 0),+ ("T3", 2, 0),+ ("T4", 0, 1),+ ("T5", 1, 1),("T6", 2, 1),]diff --git a/tests/unit/agentic_ide/test_ui_prefs.py b/tests/unit/agentic_ide/test_ui_prefs.pyindex c0cccbe87f..c95d86d950 100644--- a/tests/unit/agentic_ide/test_ui_prefs.py+++ b/tests/unit/agentic_ide/test_ui_prefs.py@@ -136,15 +136,16 @@ def test_the_toolbar_and_the_backend_agree_on_the_bounds() -> None:stored value stops at another, and the size silently changes on the nextrestart — the exact class of bug this store was added to end."""+ # The three numbers moved out of the grid into `paneFont.ts` on 2026-08-25+ # (the grid imports them); the parity check follows the definition.grid = (Path(__file__).resolve().parents[3]- / "jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx"+ / "jarvis/ui/web/frontend/src/components/agentic/paneFont.ts").read_text(encoding="utf-8")assert f"const FONT_MIN = {ui_prefs.FONT_MIN};" in gridassert f"const FONT_MAX = {ui_prefs.FONT_MAX};" in grid- # The grid holds the default as a named constant (it is also where- # Ctrl/Cmd+0 lands), so the parity check pins that definition rather than- # the inlined literal it used to be.+ # The default is a named constant too (it is also where Ctrl/Cmd+0 lands),+ # so the parity check pins that definition rather than an inlined literal.assert f"const FONT_DEFAULT = {ui_prefs.FONT_DEFAULT};" in gridassert "storedFontSize() ?? FONT_DEFAULT" in griddiff --git a/tests/unit/agentic_ide/test_viewer_handover.py b/tests/unit/agentic_ide/test_viewer_handover.pyindex 9c5f8d0f3b..6e8f8416d7 100644--- a/tests/unit/agentic_ide/test_viewer_handover.py+++ b/tests/unit/agentic_ide/test_viewer_handover.py@@ -41,6 +41,7 @@ class Viewer:def __init__(self) -> None:self.seen: list[str] = []self.exits: list[int] = []+ self.geometries: list[tuple[int, int]] = []async def output(self, text: str) -> None:self.seen.append(text)@@ -48,6 +49,9 @@ class Viewer:async def exit(self, code: int) -> None:self.exits.append(code)+ def geometry(self, cols: int, rows: int) -> None:+ self.geometries.append((cols, rows))+@propertydef screen(self) -> str:return "".join(self.seen)@@ -306,3 +310,93 @@ async def test_foreground_viewer_can_reclaim_its_geometry()assert term.viewer_output == app.outputassert fake_pty.resizes[-1] == (term.pty_id, 180, 50)+++async def test_a_displaced_viewer_is_told_the_size_the_owner_chose(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """The desktop pane a browser tab took over follows that tab's grid at once.++ Its own tile never changed, so nothing in that window would measure again+ — it used to hold the old grid until an unrelated resize, and the agent's+ repaints for the tab's width landed in it as fragments (2026-08-25).+ """+ session, term = await _one_pane(registry, tmp_path)+ app, tab = Viewer(), Viewer()+ await registry.attach(term.name, 180, 50, app.output, app.exit, on_geometry=app.geometry)+ await registry.attach(+ term.name,+ 60,+ 20,+ tab.output,+ tab.exit,+ claim_owner=False,+ on_geometry=tab.geometry,+ )+ assert app.geometries == [], "nothing moved yet — a watcher joining is not a resize"++ assert registry.claim_viewer(term.key, 60, 20, session.id, viewer=tab.output)++ assert app.geometries == [(60, 20)], "the displaced screen was not told where the PTY went"+ assert tab.geometries == [], (+ "the viewer that asked already reflowed itself; the route answers it separately"+ )+++async def test_a_viewer_that_takes_the_pane_at_attach_moves_the_others(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """A second window opening on the pane in front is a resize like any other."""+ _session, term = await _one_pane(registry, tmp_path)+ app, window = Viewer(), Viewer()+ await registry.attach(term.name, 180, 50, app.output, app.exit, on_geometry=app.geometry)++ await registry.attach(+ term.name, 100, 30, window.output, window.exit, on_geometry=window.geometry+ )++ assert app.geometries == [(100, 30)]+ assert window.geometries == []+++async def test_a_promoted_viewer_is_told_its_geometry_is_back(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """When the owner leaves, the survivor hears that the PTY is its size again.++ It spent its time as a watcher following the departed owner's grid, and+ the restore is a resize it "asked for" only in the sense that it once did+ — without a notice its screen kept the other window's strip.+ """+ session, term = await _one_pane(registry, tmp_path)+ app, tab = Viewer(), Viewer()+ await registry.attach(term.name, 180, 50, app.output, app.exit, on_geometry=app.geometry)+ await registry.attach(term.name, 60, 20, tab.output, tab.exit, on_geometry=tab.geometry)+ assert app.geometries == [(60, 20)]++ registry.detach(term.key, session.id, viewer=tab.output)++ assert term.viewer_output == app.output+ assert fake_pty.resizes[-1] == (term.pty_id, 180, 50)+ assert app.geometries[-1] == (180, 50), "the promoted screen was left holding the tab's grid"+++async def test_a_viewer_whose_notice_fails_costs_nobody_the_resize(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ session, term = await _one_pane(registry, tmp_path)+ broken, app, tab = Viewer(), Viewer(), Viewer()++ def explode(cols: int, rows: int) -> None:+ raise RuntimeError("socket already closed")++ await registry.attach(term.name, 180, 50, broken.output, broken.exit, on_geometry=explode)+ await registry.attach(term.name, 180, 50, app.output, app.exit, on_geometry=app.geometry)+ await registry.attach(+ term.name, 60, 20, tab.output, tab.exit, claim_owner=False, on_geometry=tab.geometry+ )++ assert registry.claim_viewer(term.key, 60, 20, session.id, viewer=tab.output)++ assert fake_pty.resizes[-1] == (term.pty_id, 60, 20)+ assert app.geometries == [(60, 20)]