Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agentic-ide): a terminal reads as the agent chat — one click, same timeline, terminal one click back

rubenluetke10-beepb809f876447b
diff --git a/jarvis/agentic_ide/agent_transcript.py b/jarvis/agentic_ide/agent_transcript.py
index 165d4d12a5..d3647f5422 100644
--- a/jarvis/agentic_ide/agent_transcript.py
+++ b/jarvis/agentic_ide/agent_transcript.py
@@ -44,6 +44,7 @@ import json
import re
from collections.abc import Callable
from dataclasses import dataclass, field
+from datetime import datetime
from pathlib import Path
from typing import Any
@@ -436,6 +437,532 @@ def read(agent: str, session_id: str, *, home: Path | None = None) -> list[Turn]
return live[-MAX_TURNS:]
+# --------------------------------------------------------------------------- #
+# the conversation as agent-chat events
+# --------------------------------------------------------------------------- #
+#
+# The turns above are a summary: prose and the names of the steps. The agent
+# CHAT renders more than that — the thinking where it happened (or how long it
+# took where the vendor redacts it), every tool call with its result, the
+# tokens a turn cost — and it renders all of it from ONE vocabulary, the event
+# log of :mod:`jarvis.agent_chat.events`. So a pane's transcript is offered in
+# that vocabulary too: the same reducer that folds a chat session's log then
+# folds a terminal's, and the Agentic IDE can put a running CLI on the chat
+# stage without a second renderer that would drift from the first.
+#
+# The cut between turns is the person's own message, exactly as the chat's
+# runners cut them: everything the agent did after one and before the next is
+# one turn. Timestamps come from the records, so a thought's duration is the
+# gap to whatever the agent wrote next, and a tool result is timed from its
+# call. Nothing here guesses at a clock the file does not carry.
+
+
+def _ts_ms(value: Any) -> int | None:
+ """A record's ``timestamp`` as epoch milliseconds, or ``None``.
+
+ Both shapes the CLIs write: ISO-8601 text (Claude Code, Codex) and a plain
+ epoch number, in seconds or milliseconds. Anything else is not a time.
+ """
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return int(value * 1000) if value < 1e12 else int(value)
+ if isinstance(value, str) and value.strip():
+ raw = value.strip()
+ if raw.endswith(("Z", "z")):
+ raw = raw[:-1] + "+00:00"
+ try:
+ return int(datetime.fromisoformat(raw).timestamp() * 1000)
+ except ValueError:
+ return None
+ return None
+
+
+def _summary(name: str, args: Any) -> str:
+ """The one argument a tool call is read by — the same pick `_headline` makes."""
+ target, _detail = _headline(args)
+ return target or name
+
+
+class _EventLog:
+ """The agent-chat event log of one transcript, built in file order.
+
+ ``live`` is what the caller knows and the file does not: whether the pane
+ is still working. A file ends the same way whether the agent finished an
+ hour ago or is thinking right now, so the last turn is closed as ``done``
+ when the pane is idle and left running — its last thought announced as a
+ live one — when it is not. The timeline then says "thinking…" for a pane
+ that is, and "Done" for one that stopped, from the same file.
+ """
+
+ def __init__(self, *, provider: str, live: bool) -> None:
+ self.events: list[dict[str, Any]] = []
+ self.provider = provider
+ self.live = live
+ self.model = ""
+ self.effort = ""
+ self.turn_id: str | None = None
+ self.turns = 0
+ self.turn_started_ms = 0
+ self.last_ms = 0
+ self.error: str | None = None
+ self._usage_by_message: dict[str, dict[str, int]] = {}
+ self._usage: dict[str, int] = {}
+ self._call_started: dict[str, int] = {}
+ #: A finished thought waits for the NEXT record's timestamp, which is
+ #: the only place its duration can be read from.
+ self._thought: tuple[str, str, int] | None = None
+
+ # ----------------------------------------------------------------- core
+ def _emit(self, kind: str, payload: dict[str, Any], ts: int) -> None:
+ self.last_ms = max(self.last_ms, ts)
+ self.events.append(
+ {"seq": len(self.events) + 1, "ts_ms": ts, "kind": kind, "payload": payload}
+ )
+
+ def _ensure_turn(self, ts: int) -> str:
+ if self.turn_id is None:
+ self.turns += 1
+ self.turn_id = f"turn-{self.turns}"
+ self.turn_started_ms = ts
+ self._usage_by_message = {}
+ self._usage = {}
+ self.error = None
+ self._emit(
+ "turn_started",
+ {
+ "turn_id": self.turn_id,
+ "provider": self.provider,
+ "model": self.model,
+ "effort": self.effort,
+ "runner": "cli",
+ },
+ ts,
+ )
+ return self.turn_id
+
+ def _flush_thought(self, now: int) -> None:
+ if self._thought is None:
+ return
+ text, message_id, started = self._thought
+ self._thought = None
+ self._emit(
+ "reasoning",
+ {
+ "turn_id": self.turn_id,
+ "message_id": message_id,
+ "text": text,
+ "duration_ms": max(0, now - started),
+ },
+ started,
+ )
+
+ def close_turn(self, ts: int, status: str = "done") -> None:
+ """End the open turn, if any — a boundary reached or the agent stopped."""
+ if self.turn_id is None:
+ return
+ self._flush_thought(ts)
+ self._emit(
+ "turn_finished",
+ {
+ "turn_id": self.turn_id,
+ "status": status,
+ "duration_ms": max(0, max(ts, self.last_ms) - self.turn_started_ms),
+ "usage": dict(self._usage),
+ "error": self.error,
+ "cost_usd": None,
+ },
+ max(ts, self.last_ms),
+ )
+ self.turn_id = None
+
+ # -------------------------------------------------------------- records
+ def user(self, text: str, ts: int) -> None:
+ body = _clip(text)
+ if not body:
+ return
+ self.close_turn(ts)
+ self._emit("user_message", {"text": body}, ts)
+
+ def thinking(self, text: str, message_id: str, ts: int) -> None:
+ self._ensure_turn(ts)
+ self._flush_thought(ts)
+ self._thought = (_clip(text), message_id, ts)
+
+ def text(self, text: str, message_id: str, ts: int) -> None:
+ body = _clip(text)
+ if not body:
+ return
+ turn_id = self._ensure_turn(ts)
+ self._flush_thought(ts)
+ self._emit(
+ "assistant_text",
+ {"turn_id": turn_id, "message_id": message_id, "text": body},
+ ts,
+ )
+
+ def tool_call(self, call_id: str, name: str, args: Any, ts: int) -> None:
+ turn_id = self._ensure_turn(ts)
+ self._flush_thought(ts)
+ self._call_started[call_id] = ts
+ payload = args if isinstance(args, dict) else {"input": args}
+ self._emit(
+ "tool_call",
+ {
+ "turn_id": turn_id,
+ "call_id": call_id,
+ "name": name,
+ "input": payload,
+ "summary": _summary(name, args),
+ },
+ ts,
+ )
+
+ def tool_result(self, call_id: str, output: Any, is_error: bool, ts: int) -> None:
+ turn_id = self._ensure_turn(ts)
+ self._flush_thought(ts)
+ started = self._call_started.get(call_id)
+ self._emit(
+ "tool_result",
+ {
+ "turn_id": turn_id,
+ "call_id": call_id,
+ "output": _clip(_result_text(output)),
+ "is_error": bool(is_error),
+ "duration_ms": max(0, ts - started) if started is not None else None,
+ },
+ ts,
+ )
+
+ def usage(self, message_id: str, usage: Any, ts: int) -> None:
+ """One message's token report, folded into the turn's running total.
+
+ A message id repeats across the records of one reply (a thought, a
+ sentence, a tool call each carry the same usage), so the report is kept
+ once per id — and at its LARGEST, because the first copy is the
+ message-start snapshot whose output count is a placeholder (BUG-173).
+ """
+ if not isinstance(usage, dict) or self.turn_id is None:
+ return
+ counted = {
+ key: int(usage[key])
+ for key in _USAGE_KEYS
+ if isinstance(usage.get(key), int | float) and not isinstance(usage.get(key), bool)
+ }
+ details = usage.get("output_tokens_details")
+ if isinstance(details, dict) and isinstance(details.get("thinking_tokens"), int | float):
+ counted["thinking_tokens"] = int(details["thinking_tokens"])
+ if not counted:
+ return
+ previous = self._usage_by_message.get(message_id)
+ if previous:
+ counted = {k: max(counted.get(k, 0), previous.get(k, 0)) for k in (*counted, *previous)}
+ if counted == previous:
+ return
+ self._usage_by_message[message_id] = counted
+ totals: dict[str, int] = {}
+ for per_message in self._usage_by_message.values():
+ for key, value in per_message.items():
+ totals[key] = totals.get(key, 0) + value
+ self._usage = totals
+ self._emit("usage_delta", {"turn_id": self.turn_id, "usage": totals}, ts)
+
+ def usage_total(self, usage: dict[str, int], ts: int) -> None:
+ """A turn-level total, from a CLI that reports one instead of per message."""
+ if not usage or self.turn_id is None:
+ return
+ self._usage = dict(usage)
+ self._emit("usage_delta", {"turn_id": self.turn_id, "usage": dict(usage)}, ts)
+
+ # ---------------------------------------------------------------- close
+ def finish(self) -> list[dict[str, Any]]:
+ """The log, ended the way the pane's state says it ended."""
+ if self.turn_id is not None:
+ if self.live:
+ # Still working: the last thought is the one happening now.
+ if self._thought is not None:
+ text, message_id, started = self._thought
+ self._thought = None
+ self._emit(
+ "reasoning_started",
+ {"turn_id": self.turn_id, "message_id": message_id},
+ started,
+ )
+ if text:
+ self._emit(
+ "reasoning_delta",
+ {"turn_id": self.turn_id, "message_id": message_id, "text": text},
+ started,
+ )
+ else:
+ self.close_turn(self.last_ms)
+ elif self.live and self.events and self.events[-1]["kind"] == "user_message":
+ # Asked and not yet answered, on a pane that is working: open the
+ # turn so the timeline says so instead of ending on the question.
+ self._ensure_turn(self.events[-1]["ts_ms"])
+ return _last_turns(self.events, MAX_TURNS)
+
+
+#: The token counts worth carrying — the chat shows output only, but the rest
+#: is what a later cost line would read (jarvis/agent_chat/runner_cli.py).
+_USAGE_KEYS = (
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation_input_tokens",
+)
+
+
+def _result_text(content: Any) -> str:
+ """A tool result's text, whatever shape the CLI stored it in."""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for block in content:
+ if isinstance(block, dict):
+ if block.get("type") == "text" or "text" in block:
+ parts.append(str(block.get("text") or ""))
+ elif block.get("type") == "image":
+ parts.append("[image]")
+ elif isinstance(block, str):
+ parts.append(block)
+ return "\n".join(p for p in parts if p)
+ if isinstance(content, dict):
+ for key in ("output", "content", "text"):
+ if isinstance(content.get(key), str | list):
+ return _result_text(content[key])
+ try:
+ return json.dumps(content, ensure_ascii=False)
+ except (TypeError, ValueError):
+ return str(content)
+ return "" if content is None else str(content)
+
+
+def _last_turns(events: list[dict[str, Any]], limit: int) -> list[dict[str, Any]]:
+ """The events of the last ``limit`` exchanges — cut at a person's message.
+
+ Every turn starts at a ``user_message``, so cutting there drops whole
+ turns and never the head of one; the previous turn's ``turn_finished``
+ comes right before the message and goes with its turn.
+ """
+ starts = [i for i, ev in enumerate(events) if ev["kind"] == "user_message"]
+ if len(starts) <= limit:
+ return events
+ return events[starts[-limit] :]
+
+
+def _claude_events(session_id: str, home: Path | None, live: bool) -> list[dict[str, Any]] | None:
+ path = _claude_file(session_id, home)
+ if path is None:
+ return None
+ log = _EventLog(provider="claude", live=live)
+ for row in _rows(path):
+ # A sidechain is a sub-agent's own conversation, filed in the same
+ # record; it is not what this pane said.
+ if row.get("isSidechain"):
+ continue
+ kind = str(row.get("type") or "")
+ if kind not in ("user", "assistant"):
+ continue
+ message = row.get("message")
+ if not isinstance(message, dict):
+ continue
+ ts = _ts_ms(row.get("timestamp")) or log.last_ms
+ content = message.get("content")
+ if kind == "user":
+ # `isMeta` marks the harness writing in the user's name — command
+ # caveats, session notes — which no person typed.
+ if row.get("isMeta"):
+ continue
+ if isinstance(content, str):
+ log.user(_spoken(content), ts)
+ continue
+ if not isinstance(content, list):
+ continue
+ spoken: list[str] = []
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ btype = str(block.get("type") or "")
+ if btype == "tool_result":
+ log.tool_result(
+ str(block.get("tool_use_id") or ""),
+ block.get("content"),
+ bool(block.get("is_error")),
+ ts,
+ )
+ elif btype == "text":
+ spoken.append(str(block.get("text") or ""))
+ if spoken:
+ log.user(_spoken("\n\n".join(spoken)), ts)
+ continue
+
+ # assistant
+ model = message.get("model")
+ if isinstance(model, str) and model:
+ log.model = model
+ effort = row.get("effort")
+ if isinstance(effort, str) and effort:
+ log.effort = effort
+ mid = str(message.get("id") or row.get("uuid") or "")
+ row_id = str(row.get("uuid") or mid)
+ if isinstance(content, str):
+ log.text(content, row_id, ts)
+ log.usage(mid, message.get("usage"), ts)
+ continue
+ if not isinstance(content, list):
+ continue
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ btype = str(block.get("type") or "")
+ if btype == "thinking":
+ log.thinking(str(block.get("thinking") or ""), mid, ts)
+ elif btype == "text":
+ log.text(str(block.get("text") or ""), row_id, ts)
+ elif btype == "tool_use":
+ log.tool_call(
+ str(block.get("id") or row_id),
+ str(block.get("name") or "tool"),
+ block.get("input"),
+ ts,
+ )
+ log.usage(mid, message.get("usage"), ts)
+ return log.finish()
+
+
+def _codex_events(session_id: str, home: Path | None, live: bool) -> list[dict[str, Any]] | None:
+ path = _codex_file(session_id, home)
+ if path is None:
+ return None
+ log = _EventLog(provider="codex", live=live)
+ for row in _rows(path):
+ kind = str(row.get("type") or "")
+ payload = row.get("payload")
+ if not isinstance(payload, dict):
+ continue
+ ts = _ts_ms(row.get("timestamp")) or log.last_ms
+ if kind == "turn_context":
+ model = payload.get("model")
+ if isinstance(model, str) and model:
+ log.model = model
+ continue
+ if kind == "event_msg":
+ ptype = str(payload.get("type") or "")
+ if ptype == "task_complete":
+ error = payload.get("error")
+ if isinstance(error, dict) and error.get("message"):
+ log.error = str(error["message"])
+ log.close_turn(ts, "error")
+ else:
+ log.close_turn(ts)
+ elif ptype == "turn_aborted":
+ log.close_turn(ts, "cancelled")
+ elif ptype == "token_count":
+ info = payload.get("info")
+ usage = (
+ info.get("last_token_usage") or info.get("total_token_usage")
+ if isinstance(info, dict)
+ else None
+ )
+ if isinstance(usage, dict):
+ counted = {
+ key: int(usage[key])
+ for key in _USAGE_KEYS
+ if isinstance(usage.get(key), int | float)
+ and not isinstance(usage.get(key), bool)
+ }
+ log.usage_total(counted, ts)
+ continue
+ if kind != "response_item":
+ continue
+ ptype = str(payload.get("type") or "")
+ item_id = str(payload.get("id") or payload.get("call_id") or f"row-{len(log.events)}")
+ if ptype == "message":
+ role = str(payload.get("role") or "")
+ content = payload.get("content")
+ texts: list[str] = []
+ if isinstance(content, str):
+ texts.append(content)
+ elif isinstance(content, list):
+ texts.extend(
+ str(block.get("text") or "")
+ for block in content
+ if isinstance(block, dict) and str(block.get("type") or "").endswith("text")
+ )
+ joined = "\n\n".join(t for t in texts if t)
+ if role == "user":
+ log.user(_spoken(joined), ts)
+ elif role == "assistant":
+ log.text(joined, item_id, ts)
+ # `developer` is the harness briefing the model — not conversation.
+ elif ptype in ("function_call", "local_shell_call", "custom_tool_call"):
+ arguments = payload.get("arguments")
+ if isinstance(arguments, str):
+ try:
+ arguments = json.loads(arguments)
+ except (ValueError, TypeError):
+ # Keep the raw string — the timeline prints either shape.
+ pass
+ log.tool_call(
+ item_id,
+ str(payload.get("name") or payload.get("type") or "tool"),
+ arguments,
+ ts,
+ )
+ elif ptype in ("function_call_output", "custom_tool_call_output"):
+ output = payload.get("output")
+ is_error = False
+ if isinstance(output, dict):
+ is_error = bool(output.get("is_error") or output.get("error"))
+ log.tool_result(item_id, output, is_error, ts)
+ elif ptype == "reasoning":
+ parts: list[str] = []
+ for key in ("summary", "content"):
+ blocks = payload.get(key)
+ if isinstance(blocks, list):
+ parts.extend(
+ str(block.get("text") or "")
+ for block in blocks
+ if isinstance(block, dict) and block.get("text")
+ )
+ log.thinking("\n\n".join(p for p in parts if p), item_id, ts)
+ return log.finish()
+
+
+_EVENT_READERS: dict[str, Callable[[str, Path | None, bool], list[dict[str, Any]] | None]] = {
+ "claude": _claude_events,
+ "codex": _codex_events,
+}
+
+
+def read_events(
+ agent: str,
+ session_id: str,
+ *,
+ home: Path | None = None,
+ live: bool = False,
+) -> list[dict[str, Any]] | None:
+ """The recent conversation of one session as agent-chat events, oldest first.
+
+ The same ``None`` contract as :func:`read`: no readable record, no file yet,
+ or a file that cannot be read — the caller shows the live pane. ``live``
+ says whether the pane is still working, which decides how the last turn
+ ends (see :class:`_EventLog`).
+ """
+ reader = _EVENT_READERS.get(str(agent or "").strip().lower())
+ if reader is None or not str(session_id or "").strip():
+ return None
+ try:
+ return reader(session_id.strip(), home, live)
+ except OSError as exc:
+ logger.warning(
+ "Agent transcript: {} session {} unreadable as events: {}", agent, session_id, exc
+ )
+ return None
+
+
__all__ = [
"MAX_TEXT",
"MAX_TURNS",
@@ -443,4 +970,5 @@ __all__ = [
"Turn",
"can_read",
"read",
+ "read_events",
]
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index f5565c334d..2623029fb1 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -1201,6 +1201,32 @@ async def get_state() -> dict:
return get_registry().state()
[email protected]("/panes", summary="Every coding session running in any open workspace")
+async def get_panes() -> dict:
+ """One row per pane, across ALL open workspaces — not just the front one.
+
+ ``/state`` describes the workspace being drawn. This answers the other
+ question, the one a session list asks: what do I have running anywhere? A
+ workspace sitting in a background tab is still running its agents, and a
+ list that showed only the front tab would tell someone with three tabs open
+ that two of them are empty.
+
+ Each row is a line, not a workspace state: who the pane is, what it was
+ last asked, and whether it is still working (see
+ :mod:`jarvis.agentic_ide.activity` — the same reading the grid's badge
+ shows, so the two can never disagree). ``readable`` says whether this
+ pane's conversation can be opened as a page; the transcript itself is
+ ``GET /terminals/{name}/conversation``.
+ """
+ registry = get_registry()
+ rows = registry.panes()
+ for row in rows:
+ row["readable"] = bool(row.get("has_resume")) and agent_transcript.can_read(
+ str(row.get("agent", ""))
+ )
+ return {"panes": rows, "active_id": registry.active_id}
+
+
@router.get("/state/brief", summary="Agentic-IDE workspace state, briefly")
async def get_state_brief() -> dict:
"""The workspace as a language model needs it to steer the panes.
@@ -2827,7 +2853,7 @@ async def terminal_report(name: str, lines: int = 40) -> dict:
"/terminals/{name}/conversation",
summary="One terminal's conversation, as the CLI itself recorded it",
)
-async def terminal_conversation(name: str) -> dict:
+async def terminal_conversation(name: str, workspace: str | None = None) -> dict:
"""The turns of a pane's conversation — roles, prose and the steps between.
Read from the coding CLI's OWN record rather than from the pane's screen. A
@@ -2849,8 +2875,13 @@ async def terminal_conversation(name: str) -> dict:
Collapsing the two is a real bug: a pane whose id has not been discovered
yet would be treated as a CLI that can never be read, and a conversation
that was seconds away would never be shown.
+
+ ``workspace`` names the tab the pane belongs to. Without it the front
+ workspace answers first, which is right for a spoken "show me T2" and wrong
+ for a list: every workspace numbers its panes from T1, so a row clicked in a
+ background tab would open the front tab's conversation instead.
"""
- found = get_registry().find_terminal(name)
+ found = get_registry().find_terminal(name, workspace)
if found is None:
raise HTTPException(status_code=404, detail=f"No terminal called {name}")
_session, term = found
@@ -2894,6 +2925,55 @@ async def terminal_conversation(name: str) -> dict:
}
+ "/terminals/{name}/timeline",
+ summary="One terminal's conversation as agent-chat events",
+)
+async def terminal_timeline(name: str, workspace: str | None = None) -> dict:
+ """The pane's conversation in the agent chat's own event vocabulary.
+
+ The chat stage of the Agentic IDE shows a running coding CLI the way the
+ front page shows a chat — the thinking where it happened, every tool call
+ with its result, the tokens a turn cost — and it does so with the SAME
+ timeline component. That component folds the event log of
+ :mod:`jarvis.agent_chat.events`; this answers in that log's shape, read
+ from the CLI's own transcript (:func:`agent_transcript.read_events`), so
+ one renderer serves both and neither can drift from the other.
+
+ Same two "no" as the conversation endpoint (``readable`` / ``available``),
+ for the same reasons. ``live`` is what the file cannot know and the stage
+ needs: whether the pane is still working — it decides whether the last
+ turn is drawn as running or as done, and how eagerly a client polls.
+ """
+ found = get_registry().find_terminal(name, workspace)
+ if found is None:
+ raise HTTPException(status_code=404, detail=f"No terminal called {name}")
+ _session, term = found
+ readable = agent_transcript.can_read(term.agent)
+ reading = term.reading()
+ live = reading.activity in ("working", "starting")
+ base = {
+ "terminal": term.name,
+ "agent": term.agent,
+ "readable": readable,
+ "live": live,
+ "activity": reading.activity,
+ }
+ handle = term.resume
+ if handle is None or not readable:
+ return {**base, "available": False, "events": []}
+ events = await asyncio.to_thread(
+ agent_transcript.read_events,
+ term.agent,
+ handle.id,
+ home=account_home(term.agent, term.account),
+ live=live,
+ )
+ if events is None:
+ return {**base, "available": False, "events": []}
+ return {**base, "available": True, "events": events}
+
+
@router.get(
"/voice-attachments",
summary="List every file batch waiting for a spoken terminal prompt",
@@ -3736,14 +3816,39 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
granted = registry.pty_geometry(term.key, pane_workspace)
if granted is None or granted == requested:
return
+ await send_size(*granted)
+
+ async def send_size(cols: int, rows: int) -> None:
async with send_lock:
try:
- await ws.send_json(
- {"t": "size", "cols": granted[0], "rows": granted[1]}
- )
+ await ws.send_json({"t": "size", "cols": cols, "rows": rows})
except Exception: # noqa: BLE001, S110 - viewer gone
pass
+ # The size reports this socket still owes — kept so the loop cannot drop a
+ # pending one, and forgotten as each goes out.
+ geometry_reports: set[asyncio.Task[None]] = set()
+
+ def on_geometry(cols: int, rows: int) -> None:
+ """The PTY moved under this viewer — say so, out of the caller's way.
+
+ The other half of ``report_geometry``. That one answers this socket's
+ OWN request; this is called by the registry when ANOTHER viewer moved
+ the pane's size, or when this viewer was promoted back to a size it
+ had asked for earlier (``Registry._announce_geometry``). Synchronous
+ because ``Registry.resize`` is, and scheduled rather than awaited so a
+ slow or dead socket cannot hold up the resize that already happened.
+ """
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # Outside the event loop nothing can be sent — and nothing calls
+ # this from there but a test driving the registry by hand.
+ return
+ task = loop.create_task(send_size(cols, rows))
+ geometry_reports.add(task)
+ task.add_done_callback(geometry_reports.discard)
+
async def on_prompt(notice: dict) -> None:
"""This pane was just handed a prompt — tell the viewer outright.
@@ -3814,6 +3919,7 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:
appearance=appearance,
on_replay=on_replay,
claim_owner=claim_owner,
+ on_geometry=on_geometry,
)
except SessionNotReady as exc:
# "Not yet", not "not here": this pane connected while its workspace was
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 55be5d74c1..b4356401f3 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -42,6 +42,17 @@ vi.mock("@/lib/agenticIdeApi", () => ({
closeTerminals: vi.fn(),
moveTerminal: vi.fn(),
renameTerminal: vi.fn(),
+ // The chat stage's poll: a readable pane with nothing said yet, so the stage
+ // renders its empty state and no test has to wait on a transcript.
+ fetchTerminalTimeline: vi.fn(async (name: string) => ({
+ terminal: name,
+ agent: "claude",
+ readable: true,
+ available: true,
+ live: false,
+ activity: "",
+ events: [],
+ })),
saveLayoutWeights: vi.fn(),
// Polled by the grid so the pane headers keep saying what their agents are
// doing. Resolves empty by default; the recap tests give it real rows.
@@ -246,6 +257,7 @@ vi.mock("./AgenticTerminal", () => ({
import { AgenticGrid } from "./AgenticGrid";
import * as api from "@/lib/agenticIdeApi";
import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";
+import { useIdeChatStore } from "@/store/ideChat";
import type { LayoutNode } from "./treeLayout";
/** One pane at (column, slot) — the workspace is columns of stacked panes. */
@@ -339,6 +351,10 @@ beforeEach(() => {
// the order the tests happen to run in.
window.localStorage.clear();
paneActiveHistory.clear();
+ // Grid-or-chat lives in a module-level store since 2026-08-25, so a test
+ // that ends in chat view would start the next one there too. Every case
+ // begins in the grid, the way a fresh window does.
+ useIdeChatStore.setState({ view: "grid", stagedPane: null, paneRequest: null });
// Seam drags post their result fire-and-forget; an auto-mock returning
// undefined would crash the `.catch` chain rather than fail an assertion.
vi.mocked(api.saveLayoutWeights).mockResolvedValue(sessionWith([]));
@@ -2417,7 +2433,12 @@ describe("chat view", () => {
renderGrid(FOUR);
toChat();
expect(screen.getByTestId("agentic-chat-rail").className).not.toContain("hidden");
- // Mika is the prompt target, so it takes the stage; the others hide.
+ // Mika is the prompt target, so it takes the stage — read as a chat by
+ // default, its terminal cell hidden like the others' and one click away.
+ expect(screen.getByTestId("pane-chat-Mika")).toBeTruthy();
+ expect(cellClass("Mika")).toContain("hidden");
+ fireEvent.click(screen.getByTestId("pane-chat-show-terminal"));
+ expect(screen.queryByTestId("pane-chat-Mika")).toBeNull();
expect(cellClass("Mika")).not.toContain("hidden");
for (const name of ["Nova", "Aria", "Kai"]) {
expect(cellClass(name)).toContain("hidden");
@@ -2499,13 +2520,25 @@ describe("chat view", () => {
renderGrid(FOUR);
toChat();
fireEvent.click(screen.getByTestId("chat-rail-Aria"));
+ expect(screen.getByTestId("pane-chat-Aria")).toBeTruthy();
+ expect(screen.queryByTestId("pane-chat-Mika")).toBeNull();
+ // The reading sticks: once the terminal is what is on stage, the next
+ // rail click shows the next pane's terminal, not its chat.
+ fireEvent.click(screen.getByTestId("pane-chat-show-terminal"));
expect(cellClass("Aria")).not.toContain("hidden");
expect(cellClass("Mika")).toContain("hidden");
+ fireEvent.click(screen.getByTestId("chat-rail-Mika"));
+ expect(screen.queryByTestId("pane-chat-Mika")).toBeNull();
+ expect(cellClass("Mika")).not.toContain("hidden");
+ expect(cellClass("Aria")).toContain("hidden");
});
it("activates an externally added pane on its first chat-stage render", () => {
const { rerender } = renderGrid(FOUR);
toChat();
+ // The terminal is what is on stage here: behind the chat every pane is
+ // hidden alike, and this contract is about the pane that is SHOWN.
+ fireEvent.click(screen.getByTestId("pane-chat-show-terminal"));
paneActiveHistory.clear();
rerender({
@@ -2567,8 +2600,8 @@ describe("chat view", () => {
// Chromium follows a drag release with a compatibility click on the row
// below it. That click belongs to the drag and must not switch the stage.
fireEvent.click(screen.getByTestId("chat-rail-Aria"));
- expect(cellClass("Mika")).not.toContain("hidden");
- expect(cellClass("Aria")).toContain("hidden");
+ expect(screen.getByTestId("pane-chat-Mika")).toBeTruthy();
+ expect(screen.queryByTestId("pane-chat-Aria")).toBeNull();
await waitFor(() =>
expect(
JSON.parse(
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index 22f6527a2b..0a8e78486e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -81,6 +81,9 @@ import { isVoiceActive } from "./useVoiceCall";
import { WorkspaceSettings } from "./WorkspaceSettings";
import { WorkspaceExplorer } from "./WorkspaceExplorer";
import { WorkspaceFileViewer } from "./WorkspaceFileViewer";
+import { PaneChat } from "./PaneChat";
+import { useIdeChatStore } from "@/store/ideChat";
+import type { WorkspaceView } from "@/components/agentic/workspaceView";
import {
chatTerminalIdentity,
initialChatOrder,
@@ -515,33 +518,24 @@ const APPEARANCE_KEY = "jarvis.agenticIde.terminalAppearance";
* Layer 4 of the enum contract; `jarvis/agentic_ide/workspace_view.py` is the
* source of truth and the backend asserts the two agree at import.
*/
-export type WorkspaceView = "grid" | "chat";
-
-/** Every value, in the order the toolbar and the wizard offer them. */
-export const WORKSPACE_VIEWS: readonly WorkspaceView[] = ["grid", "chat"];
-
-function isWorkspaceView(raw: string): raw is WorkspaceView {
- return (WORKSPACE_VIEWS as readonly string[]).includes(raw);
-}
-
-const VIEW_KEY = "jarvis.agenticIde.workspaceView";
-const CHAT_ORDER_KEY_PREFIX = "jarvis.agenticIde.chatOrder.v1";
-
-export function storedViewMode(): WorkspaceView | null {
- return readStored(VIEW_KEY, (raw) => (isWorkspaceView(raw) ? raw : null));
-}
-
-/**
- * Record which way the workspace should be read, ahead of the grid mounting.
+/*
+ * The enum, its storage and the wizard's entry point live in
+ * `workspaceView.ts` and are re-exported here for the callers that have always
+ * imported them from the grid.
*
- * Exported for the workspace wizard: its last step asks grid-or-chat before
- * anything opens, and the grid then simply reads the answer on mount — the
- * same stored preference the toolbar toggle below keeps, so the wizard's
- * choice and a later toggle can never disagree about where the answer lives.
+ * They were DEFINED here as well until 2026-08-25 — a second copy of the type,
+ * the value list and the localStorage key, agreeing with the first only by
+ * coincidence. One of them is now a re-export, which is the only arrangement
+ * in which they cannot drift.
*/
-export function rememberViewMode(next: WorkspaceView): void {
- writeStored(VIEW_KEY, next);
-}
+export {
+ WORKSPACE_VIEWS,
+ rememberViewMode,
+ storedViewMode,
+ type WorkspaceView,
+} from "@/components/agentic/workspaceView";
+
+const CHAT_ORDER_KEY_PREFIX = "jarvis.agenticIde.chatOrder.v1";
function storedChatOrder(workspaceId: string): readonly string[] | null {
return readStored(`${CHAT_ORDER_KEY_PREFIX}.${workspaceId}`, (raw) => {
@@ -775,20 +769,26 @@ export function AgenticGrid({
* which way someone reads their agents is a display preference of this
* screen, not workspace state worth a round-trip.
*/
- const [viewMode, setViewModeState] = useState<WorkspaceView>(() => storedViewMode() ?? "grid");
+ const viewMode = useIdeChatStore((s) => s.view);
+ const setStoreView = useIdeChatStore((s) => s.setView);
const [explorerOpen, setExplorerOpen] = useState(false);
const [openedWorkspaceFile, setOpenedWorkspaceFile] = useState<string | null>(null);
const openedWorkspaceFileTrigger = useRef<HTMLElement | null>(null);
- const setViewMode = useCallback((next: WorkspaceView) => {
- setViewModeState(next);
- rememberViewMode(next);
- // Chat shows one pane at most; a leftover maximize from the grid would
- // silently pin the stage to a pane the chat rail does not highlight.
- if (next !== "grid") setMaximized(null);
- // An open CLI picker belongs to the button that opened it, and that button
- // just left the screen — it must not be waiting there on the way back.
- setPicking(null);
- }, []);
+ const setViewMode = useCallback(
+ (next: WorkspaceView) => {
+ // The store writes the preference through as well, so the grid, the bar
+ // and the sidebar all turn on the same answer instead of three copies of
+ // it (maintainer, 2026-08-25: switching view left the sessions behind).
+ setStoreView(next);
+ // Chat shows one pane at most; a leftover maximize from the grid would
+ // silently pin the stage to a pane the chat rail does not highlight.
+ if (next !== "grid") setMaximized(null);
+ // An open CLI picker belongs to the button that opened it, and that button
+ // just left the screen — it must not be waiting there on the way back.
+ setPicking(null);
+ },
+ [setStoreView],
+ );
const chatView = viewMode === "chat";
useEffect(() => {
@@ -815,6 +815,17 @@ export function AgenticGrid({
* effects, so a pane closed by another client simply falls back.
*/
const [chatPane, setChatPane] = useState<string | null>(null);
+ /*
+ * How the staged pane is drawn: as the chat (its transcript through the
+ * agent chat's timeline — ./PaneChat) or as the terminal itself. Chat is the
+ * default, because that is what the stage is FOR; the terminal is one click
+ * away for the things only it can do — a permission prompt, a question the
+ * CLI asks in its own TUI. The choice sticks across stage changes: a rail
+ * click shows the next pane the way the person was reading the last one,
+ * and each reading has the other one click away (the stage's "Show
+ * terminal", the pane header's "Read as a chat"). No silent resets.
+ */
+ const [stageMode, setStageMode] = useState<"chat" | "terminal">("chat");
// Null until the first render has been seen: on mount every pane is "new",
// and announcing a restored workspace's eight panes would be a light show.
// Kept beside the stage selection because a newly arrived pane must be
@@ -1477,6 +1488,30 @@ export function AgenticGrid({
return names[0] ?? null;
}, [arrivingChatPane, chatPane, target, session.terminals]);
+ /** The pane on the stage, as the workspace knows it — null off the stage. */
+ const stagedTerm = useMemo(
+ () => (chatView ? (session.terminals.find((term) => term.name === chatSelected) ?? null) : null),
+ [chatView, chatSelected, session.terminals],
+ );
+ // The chat is on: the staged pane's cell is hidden like every other pane's,
+ // and its conversation is drawn over the canvas instead.
+ const chatStage = stagedTerm !== null && stageMode === "chat";
+
+ /**
+ * One click from any pane to its conversation: the chat view, this pane on
+ * the stage, the stage in chat mode. From the grid's header buttons and
+ * from the stage's own "show terminal" detour alike.
+ */
+ const openAsChat = useCallback(
+ (term: TerminalState) => {
+ setChatPane(term.name);
+ if (takesPrompts(term)) setTarget(term.name);
+ setStageMode("chat");
+ setViewMode("chat");
+ },
+ [setViewMode],
+ );
+
/*
* The browser is the only layer that knows what is actually on screen. Hand
* that fact to the backend so voice and chat can resolve "this terminal"
@@ -1487,6 +1522,11 @@ export function AgenticGrid({
* visible terminals would be less honest than making the user name one.
*/
const stagedPane = chatView ? chatSelected : null;
+ const publishStagedPane = useIdeChatStore((s) => s.setStagedPane);
+ useEffect(() => {
+ // The app sidebar's session list marks the row being read from this.
+ publishStagedPane(stagedPane);
+ }, [publishStagedPane, stagedPane]);
useEffect(() => {
void syncAgenticIdeSurface({
workspaceId: session.id,
@@ -2745,8 +2785,15 @@ export function AgenticGrid({
*
* The lift stays: a staged pane genuinely IS raised above
* the rail beside it.
+ *
+ * While the stage shows the CHAT the staged pane hides
+ * like the rest — its conversation is drawn over the
+ * canvas (PaneChat below) and the terminal waits one
+ * click away, alive.
*/
- "shadow-lg"
+ chatStage
+ ? "hidden"
+ : "shadow-lg"
: "hidden"
: maximized !== null && !isMaximized && "hidden",
)}
@@ -2784,7 +2831,7 @@ export function AgenticGrid({
fontSize={fontSize}
geometryReady={gridMeasured}
focused={target === term.name}
- active={!chatView || onStage}
+ active={!chatView || (onStage && !chatStage)}
maximized={isMaximized}
layoutBusy={layoutBusy}
splitDisabled={atLimit || busy || working}
@@ -2819,6 +2866,10 @@ export function AgenticGrid({
arranging={arrange.held === term.name}
restartToken={restartTokens[term.name] ?? 0}
onRestart={() => restartPane(term.name)}
+ // A plain shell has no conversation to read; every coding CLI
+ // gets the button, and a CLI without a readable record says
+ // so on the stage rather than hiding the way there.
+ onOpenChat={takesPrompts(term) ? () => openAsChat(term) : undefined}
/>
{/* Where a drop on THIS pane would put the pane in hand. Every
other pane is outlined the moment a drag starts, so the grid
@@ -2891,6 +2942,26 @@ export function AgenticGrid({
</div>
);
})}
+ {/*
+ The stage in chat mode: the staged pane's conversation, drawn with
+ the agent chat's timeline over the canvas. Keyed by workspace AND
+ pane so a stage change starts from an empty column instead of
+ showing the last pane's turns under the new pane's name.
+ */}
+ {chatStage && stagedTerm && (
+ <PaneChat
+ key={`${session.id}:${stagedTerm.name}`}
+ terminal={stagedTerm.name}
+ workspaceId={session.id}
+ agentLabel={
+ agents?.find((choice) => choice.name === stagedTerm.agent)?.displayName ??
+ stagedTerm.agent
+ }
+ activity={activityOf(stagedTerm).activity}
+ promptable={takesPrompts(stagedTerm)}
+ onShowTerminal={() => setStageMode("terminal")}
+ />
+ )}
{/*
The boundaries, and the whole reason they are their own elements.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index 3ca9c1fcd5..d251a0e8a9 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -61,6 +61,7 @@ import {
Check,
Loader2,
Maximize2,
+ MessageSquare,
Minimize2,
Paperclip,
Pencil,
@@ -470,6 +471,12 @@ interface AgenticTerminalProps {
onAttachError?: (message: string) => void;
/** Called when the user asks a dead pane to start a fresh agent. */
onRestart?: () => void;
+ /**
+ * Read this pane as a chat: the workspace's chat stage, this pane on it,
+ * drawn with the agent chat's timeline (see ./PaneChat). Absent on a plain
+ * shell pane, which has no conversation to read.
+ */
+ onOpenChat?: () => void;
/**
* Press on the pane's header — the grip that picks this pane up.
*
@@ -535,6 +542,7 @@ export function AgenticTerminal({
splitDisabled = false,
onAttachError,
onRestart,
+ onOpenChat,
restartToken = 0,
onArrangeStart,
arranging = false,
@@ -549,6 +557,8 @@ export function AgenticTerminal({
// process together) without reaching into the connect effect's socket.
const resizeRef = useRef<(() => void) | null>(null);
const claimResizeRef = useRef<(() => void) | null>(null);
+ /** The claim a gesture inside the pane makes — see `takeOwnership`. */
+ const takeOwnershipRef = useRef<(() => void) | null>(null);
const visibilityRef = useRef<{
show: (afterFlush?: () => void) => void;
park: () => void;
@@ -1290,10 +1300,41 @@ export function AgenticTerminal({
* socket is told unconditionally.
*/
let sentSize: { cols: number; rows: number } | null = null;
+ /*
+ * Does this pane believe it holds the one shared PTY geometry?
+ *
+ * A pseudo-terminal has exactly one size and a pane may be open in more
+ * than one place — the desktop app, a browser tab beside it, a window a
+ * tool opened to take a look — so the server hands the size to ONE viewer
+ * and answers every other viewer's request with the geometry the owner
+ * chose (see `onGeometry`). This flag is what tells a claim apart from a
+ * repeat: a pane that owns the size and measures the same tile again has
+ * nothing to say, while a pane that was displaced must speak up even
+ * though its own measurement never changed. Set when a claim goes out,
+ * cleared whenever the agent is reported to be in a size this pane did
+ * not ask for.
+ */
+ let owned = false;
+ /*
+ * May this pane take the shared size without being asked to?
+ *
+ * The passive test, for the moments the browser reports on its own — the
+ * window regaining focus, a pane becoming the active stage, the grid
+ * settling after a maximize. A window that does not hold focus is not the
+ * one the user is reading, so it must not pull the agent's screen over to
+ * its own dimensions.
+ *
+ * `document.hidden` is deliberately NOT consulted. The desktop shell can
+ * report a window that is plainly on screen as hidden for minutes at a
+ * time (2026-08-23), and gating ownership on it left the app unable to
+ * take its own terminals back: a tab some tool had opened took the size,
+ * and every click and every maximize in the app was answered with that
+ * tab's geometry — the agent drawing into the top-left corner of a pane
+ * that had just been made to fill the window (2026-08-25).
+ */
const viewerMayOwn = () =>
activeRef.current &&
- !documentHidden() &&
(typeof document === "undefined" ||
typeof document.hasFocus !== "function" ||
document.hasFocus());
@@ -1382,16 +1423,20 @@ export function AgenticTerminal({
// Already delivered and unchanged: the fit above was the whole job.
// Re-announcing a size makes the agent on the other end redraw its
// entire screen, and a pane refits several times per settling layout.
+ // A claim is exempt only while the pane does not hold the size — once
+ // it does, a claim for the same measurement is the same repeat.
if (
- !claimOwner &&
+ (!claimOwner || owned) &&
sentSize &&
sentSize.cols === size.cols &&
sentSize.rows === size.rows
) {
return;
}
- if (socket?.send({ t: claimOwner ? "claim" : "r", ...size }))
+ if (socket?.send({ t: claimOwner ? "claim" : "r", ...size })) {
sentSize = size;
+ if (claimOwner) owned = true;
+ }
};
/** A fit this pane is holding back until its parser reaches a gap. */
@@ -1466,11 +1511,35 @@ export function AgenticTerminal({
applyResize(claimOwner);
};
resizeRef.current = sendResize;
- const claimResize = () => {
- if (viewerMayOwn()) sendResize(true);
- };
+ /**
+ * Take the shared size if this window may, and refit either way.
+ *
+ * A refit that merely ASKS is answered, when another viewer holds the
+ * pane, with that viewer's geometry — so a pane maximized in this window
+ * would be fitted to its full tile and then resized straight back to the
+ * strip some other window is showing. Every size change the user causes
+ * here therefore claims rather than asks. The fallback matters just as
+ * much: a pane that may not own (inactive, or in a window without focus)
+ * still has to follow its tile, or the effects that route through this
+ * would stop refitting exactly the panes that are not in front.
+ */
+ const claimResize = () => sendResize(viewerMayOwn());
claimResizeRef.current = claimResize;
+ /**
+ * The same, on the strength of a gesture INSIDE this pane.
+ *
+ * A pointer pressed on the pane is proof enough that this is the window in
+ * front of the user, whatever `document.hasFocus()` has to say — the
+ * desktop shell's answer to that question can lag the truth, and a click
+ * that is not allowed to take the pane back leaves the user with no way
+ * to do so at all.
+ */
+ const takeOwnership = () => {
+ if (activeRef.current) sendResize(true);
+ };
+ takeOwnershipRef.current = takeOwnership;
+ const openedWithClaim = viewerMayOwn();
socket = openPaneSocket(
{
name,
@@ -1486,7 +1555,7 @@ export function AgenticTerminal({
cols: term.cols >= MIN_REAL_COLS ? term.cols : 80,
rows: term.rows >= MIN_REAL_ROWS ? term.rows : 24,
appearance: appearanceRef.current,
- claimOwner: viewerMayOwn(),
+ claimOwner: openedWithClaim,
},
{
onOpen: () => {
@@ -1496,6 +1565,10 @@ export function AgenticTerminal({
// This is also what hands over a size that was measured while the
// pane was unreachable.
sentSize = null;
+ // Ownership is settled by the handshake: a socket opened with a
+ // claim holds the size from its first byte, one opened without is a
+ // watcher until something in this window takes the pane.
+ owned = openedWithClaim;
// The spawn used a best-effort size (the mount-time fit usually runs
// before the grid cell is measured), and resizes sent while the socket
// was connecting were dropped — without this the agent's full-screen
@@ -1527,6 +1600,10 @@ export function AgenticTerminal({
*/
onGeometry: ({ cols, rows }) => {
if (disposed) return;
+ // Whatever the numbers, the agent is in a size this pane did not
+ // ask for — refused, or chosen by another window. The next gesture
+ // here claims instead of repeating a request that was turned down.
+ owned = false;
if (term.cols === cols && term.rows === rows) return;
try {
term.resize(cols, rows);
@@ -1803,6 +1880,7 @@ export function AgenticTerminal({
fitRef.current = null;
resizeRef.current = null;
claimResizeRef.current = null;
+ takeOwnershipRef.current = null;
if (visibilityRef.current === visibility) visibilityRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
@@ -1936,8 +2014,9 @@ export function AgenticTerminal({
// telling the terminal process leaves the agent formatting for the old
// width — it keeps wrapping at 100 columns in a pane that now holds 80, and
// every line breaks in the wrong place. The two must move together, so this
- // goes through the same resize path the observer uses.
- resizeRef.current?.();
+ // goes through the same resize path the observer uses — claiming, because
+ // a text size is chosen in THIS window (see `claimResize`).
+ (claimResizeRef.current ?? resizeRef.current)?.();
}, [fontSize, terminalEpoch]);
/*
@@ -1956,9 +2035,15 @@ export function AgenticTerminal({
* knowledge instead of waited for. Three passes because the grid settles over
* a frame or two — and they are nearly free: a fit that lands on the size the
* terminal already has sends nothing at all.
+ *
+ * Claimed, not merely requested (see `claimResize`): maximizing is the user
+ * opening a pane up to READ it, and a request from a window that had lost
+ * the pane to another viewer was being answered with that viewer's size —
+ * the pane filled the window and its agent kept drawing into the top-left
+ * corner of it (2026-08-25).
*/
useEffect(() => {
- const refit = () => resizeRef.current?.();
+ const refit = () => (claimResizeRef.current ?? resizeRef.current)?.();
const frame = requestAnimationFrame(refit);
const timers = [
window.setTimeout(refit, 120),
@@ -1985,8 +2070,12 @@ export function AgenticTerminal({
*/
useEffect(() => {
if (layoutBusy) return;
- resizeRef.current?.();
- const frame = requestAnimationFrame(() => resizeRef.current?.());
+ // A seam was dragged in this window: the size it lands on is claimed, so
+ // a pane another viewer had taken cannot snap back the moment it is let
+ // go of (see `claimResize`).
+ const refit = () => (claimResizeRef.current ?? resizeRef.current)?.();
+ refit();
+ const frame = requestAnimationFrame(refit);
return () => cancelAnimationFrame(frame);
}, [layoutBusy]);
@@ -2067,7 +2156,7 @@ export function AgenticTerminal({
<div
onMouseDown={() => {
onFocus?.();
- claimResizeRef.current?.();
+ takeOwnershipRef.current?.();
}}
{...dragHandlers}
className={cn(
@@ -2147,6 +2236,7 @@ export function AgenticTerminal({
onClose={onClose}
splitDisabled={splitDisabled}
onOpenConversation={() => setHistoryOpen(true)}
+ onOpenChat={onOpenChat}
/>
{/*
What went wrong, kept on screen for as long as it is true — and the one
@@ -2295,6 +2385,7 @@ function PaneHeader({
onArrangeStart,
arranging = false,
onOpenConversation,
+ onOpenChat,
}: {
workspaceId?: string;
name: string;
@@ -2324,6 +2415,8 @@ function PaneHeader({
arranging?: boolean;
/** Opens the pane's recorded conversation — the mode-proof scroll history. */
onOpenConversation?: () => void;
+ /** Puts this pane on the chat stage, read with the agent chat's timeline. */
+ onOpenChat?: () => void;
}) {
const t = useT();
const light = appearance === "light";
@@ -2803,6 +2896,19 @@ function PaneHeader({
count={promptCount}
light={light}
/>
+ {/* One click from a terminal to the same conversation read as a chat
+ — the timeline the front page's chat draws, with this pane's
+ thinking, tool calls and answers in it (maintainer, 2026-08-26). */}
+ {onOpenChat && (
+ <PaneAction
+ label={t("agentic_grid.pane_chat.open").replace("{0}", name)}
+ testId={`pane-open-chat-${name}`}
+ light={light}
+ onClick={onOpenChat}
+ >
+ <MessageSquare className="h-3.5 w-3.5" aria-hidden="true" />
+ </PaneAction>
+ )}
{/* The one scroll-history entry point that cannot flicker away: the
CLI may flip its scroll-owner mode mid-session (Claude Code does),
but the pane's recorded conversation is always openable. */}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChat.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChat.test.tsx
new file mode 100644
index 0000000000..b95d6d6818
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChat.test.tsx
@@ -0,0 +1,255 @@
+/**
+ * The chat stage: a terminal's transcript, drawn with the agent chat's timeline.
+ *
+ * Pinned here: the poll's cadence follows the pane's state, an unchanged poll
+ * re-renders nothing, the transcript's events come out as the same turn the
+ * front page's chat would draw (thinking, tool call with result, answer, the
+ * closing line), the composer types what was written into the pane verbatim,
+ * and a CLI without a readable record says so instead of showing a blank.
+ */
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import * as api from "@/lib/agenticIdeApi";
+import type { TerminalTimelineResponse } from "@/lib/agenticIdeApi";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import {
+ eventsSignature,
+ PaneChat,
+ POLL_IDLE_MS,
+ POLL_WORKING_MS,
+ pollIntervalFor,
+} from "@/components/agentic/PaneChat";
+
+vi.mock("@/lib/agenticIdeApi", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/agenticIdeApi")>()),
+ fetchTerminalTimeline: vi.fn(),
+ promptTerminal: vi.fn(),
+}));
+
+const T0 = 1_787_800_000_000;
+
+function ev(seq: number, kind: string, payload: Record<string, unknown>, at = 0): AgentChatEvent {
+ return { seq, ts_ms: T0 + at, kind, payload };
+}
+
+/** One finished exchange, the way `agent_transcript.read_events` writes it. */
+const EXCHANGE: AgentChatEvent[] = [
+ ev(1, "user_message", { text: "Fix the login bug" }),
+ ev(2, "turn_started", {
+ turn_id: "turn-1",
+ provider: "claude",
+ model: "claude-opus-5",
+ effort: "xhigh",
+ runner: "cli",
+ }, 1000),
+ ev(3, "reasoning", { turn_id: "turn-1", message_id: "m1", text: "", duration_ms: 3500 }, 1000),
+ ev(4, "assistant_text", { turn_id: "turn-1", message_id: "r1", text: "Looking at it now." }, 4500),
+ ev(5, "tool_call", {
+ turn_id: "turn-1",
+ call_id: "call-1",
+ name: "Read",
+ input: { file_path: "src/login.ts" },
+ summary: "src/login.ts",
+ }, 5000),
+ ev(6, "tool_result", {
+ turn_id: "turn-1",
+ call_id: "call-1",
+ output: "export const login = 1;",
+ is_error: false,
+ duration_ms: 2000,
+ }, 7000),
+ ev(7, "assistant_text", { turn_id: "turn-1", message_id: "r2", text: "Found it." }, 9000),
+ ev(8, "turn_finished", {
+ turn_id: "turn-1",
+ status: "done",
+ duration_ms: 8000,
+ usage: { output_tokens: 80 },
+ error: null,
+ cost_usd: null,
+ }, 9000),
+];
+
+function answer(overrides: Partial<TerminalTimelineResponse> = {}): TerminalTimelineResponse {
+ return {
+ terminal: "T1",
+ agent: "claude",
+ readable: true,
+ available: true,
+ live: false,
+ activity: "",
+ events: EXCHANGE,
+ ...overrides,
+ };
+}
+
+function renderStage(props: Partial<React.ComponentProps<typeof PaneChat>> = {}) {
+ const onShowTerminal = vi.fn();
+ const utils = render(
+ <PaneChat
+ terminal="T1"
+ workspaceId="ide_test"
+ agentLabel="Claude Code"
+ activity=""
+ promptable
+ onShowTerminal={onShowTerminal}
+ {...props}
+ />,
+ );
+ return { ...utils, onShowTerminal };
+}
+
+beforeEach(() => {
+ vi.mocked(api.fetchTerminalTimeline).mockReset();
+ vi.mocked(api.promptTerminal).mockReset();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("pollIntervalFor", () => {
+ it("reads quickly while the agent works and slowly once it stops", () => {
+ expect(pollIntervalFor(true, "")).toBe(POLL_WORKING_MS);
+ expect(pollIntervalFor(false, "working")).toBe(POLL_WORKING_MS);
+ expect(pollIntervalFor(false, "starting")).toBe(POLL_WORKING_MS);
+ expect(pollIntervalFor(false, "waiting")).toBe(POLL_IDLE_MS);
+ expect(pollIntervalFor(false, "")).toBe(POLL_IDLE_MS);
+ });
+});
+
+describe("eventsSignature", () => {
+ it("tells a grown transcript from an unchanged one", () => {
+ const same = eventsSignature(EXCHANGE, false);
+ expect(eventsSignature([...EXCHANGE], false)).toBe(same);
+ expect(eventsSignature(EXCHANGE.slice(0, -1), false)).not.toBe(same);
+ expect(eventsSignature(EXCHANGE, true)).not.toBe(same);
+ // A record that grew in place — the same seq, more text — is a change.
+ const grown = EXCHANGE.map((e) =>
+ e.seq === 7 ? { ...e, payload: { ...e.payload, text: "Found it, and fixed it." } } : e,
+ );
+ expect(eventsSignature(grown, false)).not.toBe(same);
+ });
+});
+
+describe("PaneChat", () => {
+ it("draws the transcript as the chat's own turn", async () => {
+ vi.mocked(api.fetchTerminalTimeline).mockResolvedValue(answer());
+ renderStage();
+
+ await screen.findByTestId("pane-chat-timeline");
+ expect(api.fetchTerminalTimeline).toHaveBeenCalledWith("T1", "ide_test");
+ // The person's line, and ONE assistant turn under the pane's byline.
+ expect(screen.getByTestId("agent-message-user").textContent).toContain("Fix the login bug");
+ const turns = screen.getAllByTestId("agent-turn");
+ expect(turns).toHaveLength(1);
+ expect(turns[0].getAttribute("data-status")).toBe("done");
+ expect(turns[0].textContent).toContain("Claude Code");
+ expect(turns[0].textContent).toContain("claude-opus-5");
+ expect(turns[0].textContent).toContain("Looking at it now.");
+ expect(turns[0].textContent).toContain("Found it.");
+ // The tool call is a row under the name the CLI's own log uses.
+ expect(turns[0].textContent).toContain("Read");
+ expect(turns[0].textContent).toContain("src/login.ts");
+ // The closing line says the turn ended, with its output tokens.
+ expect(screen.getByTestId("agent-turn-footer").getAttribute("data-outcome")).toBe("done");
+ });
+
+ it("says when the CLI keeps no readable record, with the way to the terminal", async () => {
+ vi.mocked(api.fetchTerminalTimeline).mockResolvedValue(
+ answer({ readable: false, available: false, events: [] }),
+ );
+ const { onShowTerminal } = renderStage({ agentLabel: "Grok Build" });
+
+ const empty = await screen.findByTestId("pane-chat-not-readable");
+ expect(empty.textContent).toContain("No readable record");
+ // No composer either: there is no conversation to add to.
+ expect(screen.queryByTestId("pane-chat-composer")).toBeNull();
+ fireEvent.click(screen.getByTestId("pane-chat-show-terminal"));
+ expect(onShowTerminal).toHaveBeenCalledTimes(1);
+ });
+
+ it("waits, rather than gives up, while the record has not appeared yet", async () => {
+ vi.mocked(api.fetchTerminalTimeline).mockResolvedValue(
+ answer({ available: false, events: [] }),
+ );
+ renderStage();
+ await screen.findByTestId("pane-chat-waiting");
+ expect(screen.getByTestId("pane-chat-composer")).toBeTruthy();
+ });
+
+ it("flags a pane that is asking something only the terminal can answer", async () => {
+ vi.mocked(api.fetchTerminalTimeline).mockResolvedValue(answer());
+ renderStage({ activity: "asking" });
+ await screen.findByTestId("pane-chat-timeline");
+ expect(screen.getByTestId("pane-chat-asking").textContent).toContain(
+ "The agent is asking you something",
+ );
+ });
+
+ it("types what was written into the pane, verbatim, and reads again", async () => {
+ vi.mocked(api.fetchTerminalTimeline).mockResolvedValue(answer());
+ vi.mocked(api.promptTerminal).mockResolvedValue({
+ terminal: "T1",
+ sent: "Now the tests",
+ composed_by: "raw",
+ files: [],
+ submitted: true,
+ });
+ renderStage();
+ await screen.findByTestId("pane-chat-timeline");
+ const before = vi.mocked(api.fetchTerminalTimeline).mock.calls.length;
+
+ const box = screen.getByPlaceholderText(/Message T1/) as HTMLTextAreaElement;
+ fireEvent.change(box, { target: { value: "Now the tests" } });
+ fireEvent.keyDown(box, { key: "Enter" });
+
+ await waitFor(() =>
+ expect(api.promptTerminal).toHaveBeenCalledWith("T1", "Now the tests", { compose: false }),
+ );
+ await waitFor(() => expect(box.value).toBe(""));
+ // A send re-reads the record at once instead of waiting for the next poll.
+ await waitFor(() =>
+ expect(vi.mocked(api.fetchTerminalTimeline).mock.calls.length).toBeGreaterThan(before),
+ );
+ });
+
+ it("says so when the pane did not take the message", async () => {
+ vi.mocked(api.fetchTerminalTimeline).mockResolvedValue(answer());
+ vi.mocked(api.promptTerminal).mockResolvedValue({
+ terminal: "T1",
+ sent: "hi",
+ composed_by: "raw",
+ files: [],
+ submitted: false,
+ detail: "still in the input box",
+ });
+ renderStage();
+ await screen.findByTestId("pane-chat-timeline");
+ const box = screen.getByPlaceholderText(/Message T1/);
+ fireEvent.change(box, { target: { value: "hi" } });
+ fireEvent.click(screen.getByTestId("pane-chat-send"));
+ const notice = await screen.findByTestId("pane-chat-notice-warning");
+ expect(notice.textContent).toContain("T1 did not take the message: still in the input box");
+ });
+
+ it("keeps the column on one failed poll and re-polls on the working cadence", async () => {
+ vi.useFakeTimers();
+ vi.mocked(api.fetchTerminalTimeline).mockResolvedValueOnce(answer({ live: true }));
+ renderStage();
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(screen.getByTestId("pane-chat-timeline")).toBeTruthy();
+
+ vi.mocked(api.fetchTerminalTimeline).mockRejectedValueOnce(new Error("offline"));
+ await act(async () => {
+ vi.advanceTimersByTime(POLL_WORKING_MS);
+ await Promise.resolve();
+ });
+ // Still there: a column that empties itself on one failed read would say
+ // the conversation is gone.
+ expect(screen.getByTestId("pane-chat-timeline")).toBeTruthy();
+ expect(api.fetchTerminalTimeline).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChat.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChat.tsx
new file mode 100644
index 0000000000..d337b010e7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChat.tsx
@@ -0,0 +1,566 @@
+/**
+ * A terminal pane read as a chat — what the Agentic IDE's chat stage shows.
+ *
+ * The pane behind this is a live coding CLI in a PTY, and a TUI is a picture:
+ * it cannot be read as a conversation off the screen. What CAN be read is the
+ * record the CLI keeps for itself, which the backend serves in the agent
+ * chat's own event vocabulary (`GET /terminals/{name}/timeline`). Those events
+ * fold through the same reducer and draw through the same `AgentTimeline` as
+ * the front page's chat — the thinking where it happened (or how long it took
+ * where the vendor redacts it), each tool call with its result, the answer as
+ * Markdown, the turn's state and its output tokens. One renderer, so the two
+ * chats cannot drift apart (maintainer, 2026-08-26: the terminals should turn
+ * into the chat view we built, with one click).
+ *
+ * The terminal is never gone. Questions and permission prompts are asked in
+ * the TUI and answered there, so the stage keeps one button back to the pane
+ * itself, and says so out loud the moment the pane's activity reads "asking".
+ * The composer types what is written into that pane, verbatim — this is a
+ * conversation with the agent, not a brief Jarvis writes on the user's behalf.
+ *
+ * Polling, not a socket: the record is a file the CLI appends to, and a poll
+ * every couple of seconds while the agent works (slower once it stops) is the
+ * honest cadence for that. The backend says which of the two it is (`live`).
+ */
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type KeyboardEvent,
+} from "react";
+import {
+ ArrowUp,
+ CircleAlert,
+ MessageSquare,
+ RefreshCw,
+ SquareTerminal,
+} from "lucide-react";
+
+import { AgentTimeline } from "@/components/agentchat/AgentTimeline";
+import {
+ EMPTY_TIMELINE,
+ reduceEvents,
+ type Timeline,
+} from "@/components/agentchat/reduce";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ fetchTerminalTimeline,
+ promptTerminal,
+ type PaneActivity,
+ type TerminalTimelineResponse,
+} from "@/lib/agenticIdeApi";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+/** Poll cadence while the agent is working — a tool result every couple of seconds is what it produces. */
+export const POLL_WORKING_MS = 2000;
+/** Poll cadence once it has stopped — only a new message from elsewhere could change the file. */
+export const POLL_IDLE_MS = 6000;
+
+/** How soon the next read follows, from what the last one said about the pane. */
+export function pollIntervalFor(live: boolean, activity: PaneActivity): number {
+ return live || activity === "working" || activity === "starting"
+ ? POLL_WORKING_MS
+ : POLL_IDLE_MS;
+}
+
+/**
+ * A cheap fingerprint of an event list, so an unchanged poll re-renders nothing.
+ *
+ * The file only ever grows, and a record is written whole (a finished block,
+ * a tool result), so length plus the last event's identity plus the text
+ * volume tells the two lists apart — without folding sixty turns to find out
+ * that nothing happened.
+ */
+export function eventsSignature(events: AgentChatEvent[], live: boolean): string {
+ const last = events[events.length - 1];
+ let chars = 0;
+ for (const ev of events) {
+ const p = ev.payload;
+ if (typeof p.text === "string") chars += p.text.length;
+ if (typeof p.output === "string") chars += p.output.length;
+ }
+ return `${events.length}:${last?.seq ?? 0}:${last?.ts_ms ?? 0}:${last?.kind ?? ""}:${chars}:${live ? 1 : 0}`;
+}
+
+export interface PaneTimelineState {
+ timeline: Timeline;
+ /** Null until the first answer; false is a settled "this CLI keeps no record". */
+ readable: boolean | null;
+ available: boolean;
+ live: boolean;
+ activity: PaneActivity;
+ /** True until the first answer for THIS pane has arrived. */
+ loading: boolean;
+ error: string;
+ /** Read again now — the composer calls it right after a send. */
+ reload: () => void;
+}
+
+/**
+ * Keep one pane's timeline current.
+ *
+ * Re-armed per pane: switching the stage to another terminal starts from an
+ * empty column rather than showing the previous pane's conversation under
+ * the new pane's name for a poll interval.
+ */
+export function usePaneTimeline(
+ terminal: string,
+ workspaceId: string | undefined,
+ enabled: boolean,
+): PaneTimelineState {
+ const [timeline, setTimeline] = useState<Timeline>(EMPTY_TIMELINE);
+ const [readable, setReadable] = useState<boolean | null>(null);
+ const [available, setAvailable] = useState(false);
+ const [live, setLive] = useState(false);
+ const [activity, setActivity] = useState<PaneActivity>("");
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState("");
+ const [reloadToken, setReloadToken] = useState(0);
+ const signatureRef = useRef("");
+
+ useEffect(() => {
+ // A new pane: forget the old one's answer before the first read lands.
+ setTimeline(EMPTY_TIMELINE);
+ setReadable(null);
+ setAvailable(false);
+ setLive(false);
+ setActivity("");
+ setLoading(true);
+ setError("");
+ signatureRef.current = "";
+ }, [terminal, workspaceId]);
+
+ useEffect(() => {
+ if (!enabled) return;
+ let cancelled = false;
+ let timer: number | null = null;
+
+ const apply = (res: TerminalTimelineResponse) => {
+ setReadable(res.readable);
+ setAvailable(res.available);
+ setLive(res.live);
+ setActivity(res.activity);
+ setError("");
+ setLoading(false);
+ const signature = eventsSignature(res.events, res.live);
+ if (signature !== signatureRef.current) {
+ signatureRef.current = signature;
+ setTimeline(reduceEvents(EMPTY_TIMELINE, res.events));
+ }
+ return pollIntervalFor(res.live, res.activity);
+ };
+
+ const tick = async () => {
+ let next = POLL_IDLE_MS;
+ try {
+ const res = await fetchTerminalTimeline(terminal, workspaceId);
+ if (cancelled) return;
+ next = apply(res);
+ } catch (reason: unknown) {
+ if (cancelled) return;
+ // Keep what is on screen: a column that empties itself on one failed
+ // poll would read as "the conversation is gone".
+ setError(reason instanceof Error ? reason.message : String(reason));
+ setLoading(false);
+ }
+ if (!cancelled) timer = window.setTimeout(() => void tick(), next);
+ };
+
+ void tick();
+ return () => {
+ cancelled = true;
+ if (timer !== null) window.clearTimeout(timer);
+ };
+ }, [enabled, terminal, workspaceId, reloadToken]);
+
+ const reload = useCallback(() => setReloadToken((token) => token + 1), []);
+ return { timeline, readable, available, live, activity, loading, error, reload };
+}
+
+export interface PaneChatProps {
+ /** The pane's call-sign — T1, or a name the user gave it. */
+ terminal: string;
+ workspaceId: string;
+ /** What the CLI is called — "Claude Code", "Codex" — the turns' byline. */
+ agentLabel: string;
+ /** The grid's own reading of the pane: working, waiting, asking… */
+ activity: PaneActivity;
+ /** Can this pane be typed into at all? A plain shell cannot. */
+ promptable: boolean;
+ /** Back to the terminal itself — the question it is asking lives there. */
+ onShowTerminal: () => void;
+}
+
+export function PaneChat({
+ terminal,
+ workspaceId,
+ agentLabel,
+ activity,
+ promptable,
+ onShowTerminal,
+}: PaneChatProps) {
+ const t = useT();
+ const state = usePaneTimeline(terminal, workspaceId, true);
+ const items = state.timeline.items;
+ const providerLabel = useCallback(() => agentLabel, [agentLabel]);
+ // Approvals never come out of a transcript — the CLI asks in its own TUI.
+ const noDecision = useCallback(() => undefined, []);
+ // The grid's reading is fresher than the poll's (it has the socket); the
+ // poll's is the fallback for a pane the grid has not read yet.
+ const paneActivity = activity || state.activity;
+ const asking = paneActivity === "asking";
+
+ return (
+ <div
+ className="absolute inset-0 z-20 flex min-h-0 flex-col rounded-lg bg-background"
+ data-testid={`pane-chat-${terminal}`}
+ data-pane={terminal}
+ data-activity={paneActivity}
+ >
+ <header className="flex h-11 shrink-0 items-center gap-2 border-b border-border px-4">
+ <MessageSquare className="h-4 w-4 shrink-0 text-primary" aria-hidden />
+ <span className="font-mono text-xs font-semibold text-foreground">{terminal}</span>
+ <span className="min-w-0 flex-1 truncate text-sm text-muted-foreground">{agentLabel}</span>
+ <button
+ type="button"
+ onClick={state.reload}
+ title={t("agentic_grid.pane_chat.reload")}
+ aria-label={t("agentic_grid.pane_chat.reload")}
+ data-testid="pane-chat-reload"
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ >
+ <RefreshCw className={cn("h-4 w-4", state.loading && "animate-spin")} aria-hidden />
+ </button>
+ <button
+ type="button"
+ onClick={onShowTerminal}
+ data-testid="pane-chat-show-terminal"
+ className={cn(
+ "inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-2.5 text-xs font-medium transition-colors",
+ asking
+ ? "border-primary/50 bg-primary/10 text-foreground hover:bg-primary/15"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground",
+ )}
+ >
+ <SquareTerminal className="h-3.5 w-3.5" aria-hidden />
+ {t("agentic_grid.pane_chat.show_terminal")}
+ </button>
+ </header>
+
+ {asking && (
+ <div
+ role="status"
+ data-testid="pane-chat-asking"
+ className="flex shrink-0 items-start gap-2 border-b border-primary/30 bg-primary/[0.07] px-4 py-2 text-xs"
+ >
+ <CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" aria-hidden />
+ <div className="min-w-0">
+ <div className="font-medium text-foreground">{t("agentic_grid.pane_chat.asking_title")}</div>
+ <div className="text-muted-foreground">{t("agentic_grid.pane_chat.asking_detail")}</div>
+ </div>
+ </div>
+ )}
+
+ <PaneChatBody
+ state={state}
+ terminal={terminal}
+ agentLabel={agentLabel}
+ providerLabel={providerLabel}
+ onDecide={noDecision}
+ onShowTerminal={onShowTerminal}
+ />
+
+ {state.readable !== false && (
+ <div className="w-full max-w-[760px] self-center px-6 pb-5 pt-2">
+ <PaneComposer
+ terminal={terminal}
+ promptable={promptable}
+ onSent={state.reload}
+ hasContent={items.length > 0}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function PaneChatBody({
+ state,
+ terminal,
+ agentLabel,
+ providerLabel,
+ onDecide,
+ onShowTerminal,
+}: {
+ state: PaneTimelineState;
+ terminal: string;
+ agentLabel: string;
+ providerLabel: (id: string) => string;
+ onDecide: () => void;
+ onShowTerminal: () => void;
+}) {
+ const t = useT();
+ const items = state.timeline.items;
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ // Follow the conversation unless the person scrolled up to read: the
+ // column sticks to its end while it is at the end, and stays put otherwise.
+ const stickRef = useRef(true);
+ const lastId = items[items.length - 1]?.id ?? null;
+ const lastCount = useMemo(() => {
+ const last = items[items.length - 1];
+ return last && last.type === "turn" ? last.blocks.length : 0;
+ }, [items]);
+
+ useLayoutEffect(() => {
+ const viewport = viewportOf(rootRef.current);
+ if (!viewport || !stickRef.current) return;
+ viewport.scrollTop = viewport.scrollHeight;
+ }, [lastId, lastCount, terminal]);
+
+ useEffect(() => {
+ stickRef.current = true;
+ }, [terminal]);
+
+ const onScroll = useCallback(() => {
+ const viewport = viewportOf(rootRef.current);
+ if (!viewport) return;
+ const gap = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
+ stickRef.current = gap < 80;
+ }, []);
+
+ if (state.readable === false) {
+ return (
+ <Empty
+ icon={<SquareTerminal className="h-5 w-5 text-muted-foreground" aria-hidden />}
+ title={t("agentic_grid.pane_chat.not_readable_title")}
+ detail={t("agentic_grid.pane_chat.not_readable_detail")}
+ testId="pane-chat-not-readable"
+ >
+ <button
+ type="button"
+ onClick={onShowTerminal}
+ 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"
+ >
+ <SquareTerminal className="h-3.5 w-3.5" aria-hidden />
+ {t("agentic_grid.pane_chat.show_terminal")}
+ </button>
+ </Empty>
+ );
+ }
+
+ if (state.loading) {
+ return (
+ <div className="mx-auto w-full max-w-[760px] flex-1 space-y-4 overflow-hidden px-6 py-8" data-testid="pane-chat-loading">
+ {["w-2/3", "w-full", "w-5/6", "w-1/2", "w-full", "w-4/5"].map((width, row) => (
+ <div key={row} className={cn("h-3 animate-pulse rounded bg-muted/70", width)} />
+ ))}
+ </div>
+ );
+ }
+
+ if (state.error && items.length === 0) {
+ return (
+ <Empty
+ icon={<CircleAlert className="h-5 w-5 text-destructive" aria-hidden />}
+ title={t("agentic_grid.pane_chat.load_failed")}
+ detail={state.error}
+ testId="pane-chat-error"
+ >
+ <button
+ type="button"
+ onClick={state.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"
+ >
+ <RefreshCw className="h-3.5 w-3.5" aria-hidden />
+ {t("agentic_grid.pane_chat.retry")}
+ </button>
+ </Empty>
+ );
+ }
+
+ if (!state.available || items.length === 0) {
+ return (
+ <Empty
+ icon={<MessageSquare className="h-5 w-5 text-muted-foreground" aria-hidden />}
+ title={t("agentic_grid.pane_chat.waiting_title")}
+ detail={t("agentic_grid.pane_chat.waiting_detail")}
+ testId="pane-chat-waiting"
+ />
+ );
+ }
+
+ return (
+ <ScrollArea ref={rootRef} className="min-h-0 w-full flex-1" onScrollCapture={onScroll}>
+ <div
+ className="relative mx-auto flex w-full max-w-[760px] flex-col gap-5 px-6 pb-6 pt-8"
+ data-testid="pane-chat-timeline"
+ >
+ <AgentTimeline
+ items={items}
+ assistantName={agentLabel}
+ providerLabel={providerLabel}
+ onDecide={onDecide}
+ />
+ </div>
+ </ScrollArea>
+ );
+}
+
+function Empty({
+ icon,
+ title,
+ detail,
+ testId,
+ children,
+}: {
+ icon: React.ReactNode;
+ title: string;
+ detail: string;
+ testId: string;
+ children?: React.ReactNode;
+}) {
+ return (
+ <div
+ className="flex flex-1 flex-col items-center justify-center px-6 text-center"
+ data-testid={testId}
+ >
+ <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl border border-border bg-muted/30">
+ {icon}
+ </div>
+ <p className="text-sm font-medium text-foreground">{title}</p>
+ <p className="mt-1 max-w-sm text-xs leading-relaxed text-muted-foreground">{detail}</p>
+ {children}
+ </div>
+ );
+}
+
+/**
+ * The stage's composer: what is written is typed into the pane, as written.
+ *
+ * The same card the agent chat's composer draws — border, radius, shadow, the
+ * arrow — minus the picks that make no sense for a PTY (provider, model,
+ * effort, permission mode: the CLI in the pane decided those when it
+ * started). Enter sends, Shift+Enter breaks the line, like every chat.
+ */
+function PaneComposer({
+ terminal,
+ promptable,
+ onSent,
+ hasContent,
+}: {
+ terminal: string;
+ promptable: boolean;
+ onSent: () => void;
+ hasContent: boolean;
+}) {
+ const t = useT();
+ const [value, setValue] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [notice, setNotice] = useState<{ tone: "error" | "warning"; text: string } | null>(null);
+ const canSend = promptable && !busy && value.trim().length > 0;
+
+ const send = useCallback(async () => {
+ const text = value.trim();
+ if (!text || busy || !promptable) return;
+ setBusy(true);
+ setNotice(null);
+ try {
+ // Verbatim: `compose` off. A brief written FOR the person belongs to the
+ // voice path; here the person is talking to the agent themselves.
+ const result = await promptTerminal(terminal, text, { compose: false });
+ setValue("");
+ if (result.submitted === false) {
+ setNotice({
+ tone: "warning",
+ text: t("agentic_grid.pane_chat.not_taken")
+ .replace("{0}", terminal)
+ .replace("{1}", result.detail ?? ""),
+ });
+ }
+ onSent();
+ } catch (reason: unknown) {
+ setNotice({
+ tone: "error",
+ text: t("agentic_grid.pane_chat.send_failed")
+ .replace("{0}", terminal)
+ .replace("{1}", reason instanceof Error ? reason.message : String(reason)),
+ });
+ } finally {
+ setBusy(false);
+ }
+ }, [value, busy, promptable, terminal, onSent, t]);
+
+ const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void send();
+ }
+ };
+
+ return (
+ <div
+ data-testid="pane-chat-composer"
+ className={cn(
+ "relative flex flex-col gap-2 rounded-2xl border border-border bg-card p-3 shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.05),0_8px_24px_rgb(var(--scrim-rgb)/0.06)] transition-[border-color,box-shadow]",
+ "focus-within:border-primary/40",
+ )}
+ >
+ <textarea
+ data-jarvis-chat-input=""
+ autoFocus={!hasContent}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={onKeyDown}
+ placeholder={
+ promptable
+ ? t("agentic_grid.pane_chat.placeholder").replace("{0}", terminal)
+ : t("agentic_grid.pane_chat.not_promptable")
+ }
+ disabled={!promptable}
+ rows={2}
+ className="max-h-48 w-full resize-none bg-transparent px-1 py-1 text-[15px] leading-relaxed text-foreground placeholder:text-muted-foreground focus-visible:outline-none disabled:opacity-50"
+ />
+ <div className="flex items-center gap-2">
+ <span className="min-w-0 flex-1 truncate px-1 text-xs text-muted-foreground" role="status">
+ {busy
+ ? t("agentic_grid.pane_chat.sending")
+ : notice && (
+ <span
+ data-testid={`pane-chat-notice-${notice.tone}`}
+ className={cn(notice.tone === "error" ? "text-destructive" : "text-foreground")}
+ >
+ {notice.text}
+ </span>
+ )}
+ </span>
+ <button
+ type="button"
+ onClick={() => void send()}
+ disabled={!canSend}
+ aria-label={t("agentic_grid.pane_chat.send").replace("{0}", terminal)}
+ title={t("agentic_grid.pane_chat.send").replace("{0}", terminal)}
+ data-testid="pane-chat-send"
+ className={cn(
+ "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-colors",
+ canSend
+ ? "bg-primary text-primary-foreground hover:bg-primary/90"
+ : "bg-secondary text-muted-foreground/60",
+ )}
+ >
+ <ArrowUp className="h-4 w-4" />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/** Radix renders the scrolling element as the viewport inside our ScrollArea root. */
+function viewportOf(root: HTMLElement | null): HTMLElement | null {
+ if (!root) return null;
+ return (root.querySelector("[data-radix-scroll-area-viewport]") as HTMLElement | null) ?? root;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.test.tsx
index 8d6639831e..ba01c5f4b4 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceChats.test.tsx
@@ -4,7 +4,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WorkspaceChats, groupByFolder } from "@/components/agentic/WorkspaceChats";
import { useAgentSessionStore } from "@/store/agentChat";
import { useIdeChatStore } from "@/store/ideChat";
+import {
+ resetWorkspacePanesPoll,
+ useWorkspacePanesStore,
+} from "@/store/workspacePanes";
import type { AgentChatSession } from "@/lib/agentChatApi";
+import type { WorkspacePaneRow } from "@/lib/agenticIdeApi";
const HERE = "C:\\Users\\dev\\Personal Jarvis";
const THERE = "C:\\Users\\dev\\AiGrokAgents";
@@ -26,6 +31,46 @@ function chat(id: string, title: string, cwd: string, updated: number): AgentCha
};
}
+function pane(
+ name: string,
+ displayName: string,
+ workspaceId: string,
+ status: WorkspacePaneRow["status"] = "live",
+): WorkspacePaneRow {
+ return {
+ workspace_id: workspaceId,
+ workspace_name: "Personal Jarvis",
+ folder: HERE,
+ workspace_active: workspaceId === "w1",
+ key: name,
+ history_id: `${name}@${workspaceId}`,
+ name,
+ agent: "claude",
+ display_name: displayName,
+ accepts_prompts: true,
+ status,
+ exit_code: null,
+ activity: "",
+ activity_since: 0,
+ worked: true,
+ started_at: 1,
+ last_output_at: 2,
+ last_prompt: "",
+ last_prompt_at: null,
+ has_resume: false,
+ readable: true,
+ account: null,
+ account_label: null,
+ };
+}
+
+const PANES = [
+ pane("T1", "Claude Code", "w1"),
+ pane("T2", "Codex", "w1", "exited"),
+ // Another workspace's pane: it belongs to that tab's list, not this one.
+ pane("T9", "Elsewhere", "w2"),
+];
+
const SESSIONS = [
chat("a", "Restore Command Deck", HERE, 9_000),
chat("b", "Plan the marketing", HERE, 8_000),
@@ -40,7 +85,18 @@ const newChat = vi.fn();
describe("the sidebar's chat face", () => {
beforeEach(() => {
vi.clearAllMocks();
+ resetWorkspacePanesPoll();
+ useWorkspacePanesStore.setState({
+ panes: PANES,
+ activeId: "w1",
+ loaded: true,
+ // The component subscribes to the shared poll; a real fetch in jsdom
+ // would only be caught and discarded, so the seed stands in for it.
+ load: async () => {},
+ });
useIdeChatStore.setState({
+ paneRequest: null,
+ stagedPane: null,
view: "chat",
sidebarFace: "chats",
workspace: { id: "w1", name: "Personal Jarvis", path: HERE },
@@ -62,6 +118,39 @@ describe("the sidebar's chat face", () => {
afterEach(cleanup);
+ it("lists the coding sessions running in the open workspace", () => {
+ // The complaint this guards (maintainer, 2026-08-25): switching from the
+ // terminal grid to chat left the workspace's sessions behind, because this
+ // column knew only about chat sessions.
+ render(<WorkspaceChats />);
+
+ const rows = screen.getAllByTestId("workspace-session-row");
+ expect(rows.map((row) => row.dataset.pane)).toEqual(["T1", "T2"]);
+ expect(rows[0].textContent).toContain("Claude Code");
+ // Another workspace's pane belongs to that tab, not to this column.
+ expect(rows.map((row) => row.dataset.pane)).not.toContain("T9");
+ });
+
+ it("asks the view to bring the session that was clicked to the front", () => {
+ render(<WorkspaceChats />);
+
+ fireEvent.click(screen.getByText("Codex"));
+
+ const asked = useIdeChatStore.getState().paneRequest;
+ expect(asked?.workspaceId).toBe("w1");
+ expect(asked?.pane).toBe("T2");
+ });
+
+ it("marks the session the chat view has on stage", () => {
+ useIdeChatStore.setState({ stagedPane: "T2" });
+ render(<WorkspaceChats />);
+
+ const rows = screen.getAllByTestId("workspace-session-row");
+ const staged = rows.find((row) => row.dataset.pane === "T2");
+ expect(staged?.className).toContain("bg-card");
+ expect(rows.find((row) => row.dataset.pane === "T1")?.className).not.toContain("bg-card");
+ });
+
it("puts the open workspace's folder first, its chats under it", () => {
render(<WorkspaceChats />);
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 903029ffe9..8940fd521b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -4831,6 +4831,11 @@
"new_session": "Neue Session",
"no_workspace": "Kein Workspace geöffnet.",
"no_sessions_here": "Noch keine Coding-Sessions in diesem Workspace",
+ "other_folders": "Andere Ordner",
+ "new_chat_here": "Neuer Chat hier",
+ "no_chats_here": "Noch keine Chats hier",
+ "running_sessions": "Coding-Sessions",
+ "session_here": "Läuft in diesem Workspace",
"show_more": "Mehr anzeigen"
},
"agentic_grid": {
@@ -4948,6 +4953,26 @@
"steps_many": "{0} Arbeitsschritte",
"grip_hint": "Klicken: Verlauf öffnen · Ziehen: scrollen"
},
+ "pane_chat": {
+ "open": "{0} als Chat lesen",
+ "show_terminal": "Terminal zeigen",
+ "show_chat": "Chat zeigen",
+ "asking_title": "Der Agent fragt dich etwas",
+ "asking_detail": "Rückfragen und Berechtigungsanfragen beantwortest du im Terminal selbst.",
+ "not_readable_title": "Keine lesbare Aufzeichnung",
+ "not_readable_detail": "Dieses CLI führt keine Gesprächsdatei — es lässt sich nur als Terminal beobachten.",
+ "waiting_title": "Warten auf den ersten Austausch",
+ "waiting_detail": "Das Gespräch erscheint hier, sobald der Agent es aufgezeichnet hat.",
+ "load_failed": "Das Gespräch konnte nicht geladen werden.",
+ "retry": "Erneut versuchen",
+ "reload": "Gespräch neu laden",
+ "placeholder": "Nachricht an {0} — wird wörtlich ins Terminal getippt",
+ "send": "An {0} senden",
+ "sending": "Wird gesendet…",
+ "send_failed": "Senden an {0} fehlgeschlagen: {1}",
+ "not_taken": "{0} hat die Nachricht nicht angenommen: {1}",
+ "not_promptable": "Dieses Fenster nimmt keine getippten Nachrichten an."
+ },
"selection": {
"start": "Terminals auswählen",
"finish": "Auswahl beenden",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index b721e87fcf..09326f24c6 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -4831,6 +4831,11 @@
"new_session": "New session",
"no_workspace": "No workspace is open.",
"no_sessions_here": "No coding sessions in this workspace yet",
+ "other_folders": "Other folders",
+ "new_chat_here": "New chat here",
+ "no_chats_here": "No chats here yet",
+ "running_sessions": "Coding sessions",
+ "session_here": "Running in this workspace",
"show_more": "Show more"
},
"agentic_grid": {
@@ -4948,6 +4953,26 @@
"steps_many": "{0} tool steps",
"grip_hint": "Click: open history · drag: scroll"
},
+ "pane_chat": {
+ "open": "Read {0} as a chat",
+ "show_terminal": "Show terminal",
+ "show_chat": "Show chat",
+ "asking_title": "The agent is asking you something",
+ "asking_detail": "Questions and permission prompts are answered in the terminal itself.",
+ "not_readable_title": "No readable record",
+ "not_readable_detail": "This CLI keeps no conversation file, so it can only be watched as a terminal.",
+ "waiting_title": "Waiting for the first exchange",
+ "waiting_detail": "The conversation appears here as soon as the agent has recorded it.",
+ "load_failed": "The conversation could not be loaded.",
+ "retry": "Try again",
+ "reload": "Reload the conversation",
+ "placeholder": "Message {0} — typed into the terminal as written",
+ "send": "Send to {0}",
+ "sending": "Sending…",
+ "send_failed": "Could not send to {0}: {1}",
+ "not_taken": "{0} did not take the message: {1}",
+ "not_promptable": "This pane does not take typed messages."
+ },
"selection": {
"start": "Select terminals",
"finish": "Done selecting",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index d2e28fded8..7c3f017a34 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -4831,6 +4831,11 @@
"new_session": "Nueva sesión",
"no_workspace": "No hay ningún espacio de trabajo abierto.",
"no_sessions_here": "Aún no hay sesiones de programación en este espacio de trabajo",
+ "other_folders": "Otras carpetas",
+ "new_chat_here": "Nuevo chat aquí",
+ "no_chats_here": "Aún no hay chats aquí",
+ "running_sessions": "Sesiones de código",
+ "session_here": "En ejecución en este workspace",
"show_more": "Mostrar más"
},
"agentic_grid": {
@@ -4948,6 +4953,26 @@
"steps_many": "{0} pasos de herramienta",
"grip_hint": "Clic: abrir historial · arrastrar: desplazar"
},
+ "pane_chat": {
+ "open": "Leer {0} como chat",
+ "show_terminal": "Mostrar terminal",
+ "show_chat": "Mostrar chat",
+ "asking_title": "El agente te está preguntando algo",
+ "asking_detail": "Las preguntas y solicitudes de permiso se responden en el propio terminal.",
+ "not_readable_title": "Sin registro legible",
+ "not_readable_detail": "Esta CLI no guarda un archivo de conversación, así que solo puede verse como terminal.",
+ "waiting_title": "Esperando el primer intercambio",
+ "waiting_detail": "La conversación aparece aquí en cuanto el agente la haya registrado.",
+ "load_failed": "No se pudo cargar la conversación.",
+ "retry": "Reintentar",
+ "reload": "Recargar la conversación",
+ "placeholder": "Mensaje para {0} — se escribe en el terminal tal cual",
+ "send": "Enviar a {0}",
+ "sending": "Enviando…",
+ "send_failed": "No se pudo enviar a {0}: {1}",
+ "not_taken": "{0} no aceptó el mensaje: {1}",
+ "not_promptable": "Este panel no acepta mensajes escritos."
+ },
"selection": {
"start": "Seleccionar terminales",
"finish": "Terminar selección",
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 6f9450dea9..6976ec2aef 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -5,6 +5,9 @@
// Type-only: the split tree's wire form is defined next to the code that lays
// it out, and the session state simply carries it.
import type { LayoutNode } from "../components/agentic/treeLayout";
+// Type-only: a pane's transcript is served in the agent chat's event shape so
+// the chat's own reducer can fold it (see `fetchTerminalTimeline`).
+import type { AgentChatEvent } from "./agentChatApi";
export interface AgentStatus {
name: string;
@@ -703,12 +706,99 @@ export interface ConversationResponse {
*/
export function fetchTerminalConversation(
name: string,
+ workspaceId?: string,
): Promise<ConversationResponse> {
+ // The workspace is not optional detail when the caller came from a LIST:
+ // every workspace numbers its panes from T1, so without it a row from a
+ // background tab would open the front tab's conversation.
+ const query = workspaceId ? `?workspace=${encodeURIComponent(workspaceId)}` : "";
return getJson<ConversationResponse>(
- `/api/agentic-ide/terminals/${encodeURIComponent(name)}/conversation`,
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/conversation${query}`,
);
}
+/**
+ * The pane's conversation in the agent chat's own event vocabulary.
+ *
+ * `events` fold through `components/agentchat/reduce` exactly like a chat
+ * session's log, which is how the IDE's chat stage draws a running CLI with
+ * the front page's timeline. `readable` / `available` mean what they mean on
+ * the conversation endpoint; `live` is whether the pane is still working —
+ * the file alone cannot tell, so the backend reads it off the pane.
+ */
+export interface TerminalTimelineResponse {
+ terminal: string;
+ agent: string;
+ readable: boolean;
+ available: boolean;
+ live: boolean;
+ activity: PaneActivity;
+ events: AgentChatEvent[];
+}
+
+export function fetchTerminalTimeline(
+ name: string,
+ workspaceId?: string,
+): Promise<TerminalTimelineResponse> {
+ const query = workspaceId ? `?workspace=${encodeURIComponent(workspaceId)}` : "";
+ return getJson<TerminalTimelineResponse>(
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/timeline${query}`,
+ );
+}
+
+/**
+ * One coding session running in a workspace — a line, not a workspace state.
+ *
+ * The rows behind the chat sidebar's session list. Every open workspace is in
+ * here, not only the tab at the front: a workspace in a background tab keeps
+ * running its agents, and a list that skipped it would tell someone with three
+ * tabs open that two of them are empty.
+ */
+export interface WorkspacePaneRow {
+ /** The workspace tab this pane belongs to. */
+ workspace_id: string;
+ workspace_name: string;
+ /** Its project folder — what the sidebar groups by. */
+ folder: string;
+ /** Is that workspace the one at the front right now? */
+ workspace_active: boolean;
+ /** The call-sign (T1, or a name the user gave it) — reusable after a close. */
+ key: string;
+ /** The pane's own lifetime id: stable where the call-sign is not. */
+ history_id: string;
+ name: string;
+ agent: string;
+ display_name: string;
+ accepts_prompts: boolean;
+ status: "pending" | "live" | "exited" | "error";
+ exit_code: number | null;
+ /** Working, waiting, asking… — the same reading the grid's badge shows. */
+ activity: PaneActivity;
+ activity_since: number;
+ /** Has anything ever been asked of this pane? Separates "done" from "idle". */
+ worked: boolean;
+ started_at: number | null;
+ last_output_at: number | null;
+ /** The opening of the last prompt — a terminal's closest thing to a title. */
+ last_prompt: string;
+ last_prompt_at: number | null;
+ has_resume: boolean;
+ /** Can this pane's conversation be opened as a page? */
+ readable: boolean;
+ account: string | null;
+ account_label: string | null;
+}
+
+export interface WorkspacePanesResponse {
+ panes: WorkspacePaneRow[];
+ active_id: string | null;
+}
+
+/** Every pane of every OPEN workspace, for the session list. */
+export function fetchWorkspacePanes(): Promise<WorkspacePanesResponse> {
+ return getJson<WorkspacePanesResponse>("/api/agentic-ide/panes");
+}
+
function recapUrl(name: string, workspaceId?: string, suffix = ""): string {
const query = workspaceId
? `?workspace_id=${encodeURIComponent(workspaceId)}`
diff --git a/tests/unit/agentic_ide/test_agent_transcript_events.py b/tests/unit/agentic_ide/test_agent_transcript_events.py
new file mode 100644
index 0000000000..e9d9c4ba2a
--- /dev/null
+++ b/tests/unit/agentic_ide/test_agent_transcript_events.py
@@ -0,0 +1,407 @@
+"""The transcript as agent-chat events: what the chat stage folds.
+
+Fixtures are written in the shape the CLIs actually put on disk, for the same
+reason as in ``test_agent_transcript.py`` — the reader's whole point is that it
+reads THAT file, so a tidied-up fixture would pass while the stage stayed blank.
+The cases here are the ones the stage depends on: where a turn is cut, where
+the thinking's duration comes from, that a tool result lands on its call, and
+how the last turn ends depending on whether the pane is still working.
+"""
+
+from __future__ import annotations
+
+import calendar
+import json
+from pathlib import Path
+
+from jarvis.agentic_ide import agent_transcript
+
+
+def _write(path: Path, rows: list[dict]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ "\n".join(json.dumps(row, ensure_ascii=False) for row in rows) + "\n",
+ encoding="utf-8",
+ )
+
+
+def _claude_session(home: Path, session_id: str, rows: list[dict]) -> None:
+ _write(home / "projects" / "C--some--folder" / f"{session_id}.jsonl", rows)
+
+
+def _at(seconds: float) -> str:
+ """An ISO timestamp ``seconds`` into a fixed minute — what Claude Code writes."""
+ whole = int(seconds)
+ frac = int(round((seconds - whole) * 1000))
+ return f"2026-08-26T17:15:{whole:02d}.{frac:03d}Z"
+
+
+def _user(text: str, at: float, **extra: object) -> dict:
+ return {
+ "type": "user",
+ "timestamp": _at(at),
+ "uuid": f"u-{at}",
+ "message": {"role": "user", "content": [{"type": "text", "text": text}]},
+ **extra,
+ }
+
+
+def _assistant(block: dict, at: float, mid: str = "msg_1", **extra: object) -> dict:
+ return {
+ "type": "assistant",
+ "timestamp": _at(at),
+ "uuid": f"a-{at}",
+ "message": {
+ "id": mid,
+ "model": "claude-opus-5",
+ "role": "assistant",
+ "content": [block],
+ "usage": {"input_tokens": 2, "output_tokens": 40},
+ },
+ "effort": "xhigh",
+ **extra,
+ }
+
+
+def _tool_result(call_id: str, text: str, at: float, is_error: bool = False) -> dict:
+ return {
+ "type": "user",
+ "timestamp": _at(at),
+ "uuid": f"r-{at}",
+ "message": {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": call_id,
+ "content": text,
+ "is_error": is_error,
+ }
+ ],
+ },
+ }
+
+
+def _kinds(events: list[dict]) -> list[str]:
+ return [ev["kind"] for ev in events]
+
+
+class TestClaudeEvents:
+ def test_one_exchange_becomes_one_turn_in_the_chat_vocabulary(self, tmp_path: Path) -> None:
+ _claude_session(
+ tmp_path,
+ "abc",
+ [
+ _user("Fix the login bug", 0),
+ _assistant({"type": "thinking", "thinking": "", "signature": "x"}, 1),
+ _assistant({"type": "text", "text": "Looking at it now."}, 4.5),
+ _assistant(
+ {
+ "type": "tool_use",
+ "id": "call-1",
+ "name": "Read",
+ "input": {"file_path": "src/login.ts"},
+ },
+ 5,
+ ),
+ _tool_result("call-1", "export const login = …", 7),
+ _assistant({"type": "text", "text": "Found it."}, 9, mid="msg_2"),
+ ],
+ )
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path, live=False)
+ assert events is not None
+ # The token reports ride alongside (a transient kind — the reducer only
+ # keeps the latest), so the order that matters is everything else's.
+ assert [k for k in _kinds(events) if k != "usage_delta"] == [
+ "user_message",
+ "turn_started",
+ "reasoning",
+ "assistant_text",
+ "tool_call",
+ "tool_result",
+ "assistant_text",
+ "turn_finished",
+ ]
+ # One report per MESSAGE, not per record: msg_1 spans three records.
+ assert _kinds(events).count("usage_delta") == 2
+ by_kind = {ev["kind"]: ev for ev in events}
+ assert by_kind["user_message"]["payload"]["text"] == "Fix the login bug"
+ started = by_kind["turn_started"]["payload"]
+ assert started == {
+ "turn_id": "turn-1",
+ "provider": "claude",
+ "model": "claude-opus-5",
+ "effort": "xhigh",
+ "runner": "cli",
+ }
+ # Redacted thinking still says how long it took: the gap to the next
+ # record, which is the only clock the file carries.
+ reasoning = by_kind["reasoning"]["payload"]
+ assert reasoning["text"] == ""
+ assert reasoning["duration_ms"] == 3500
+ call = by_kind["tool_call"]["payload"]
+ assert (call["call_id"], call["name"], call["summary"]) == (
+ "call-1",
+ "Read",
+ "src/login.ts",
+ )
+ result = by_kind["tool_result"]["payload"]
+ assert result["call_id"] == "call-1"
+ assert result["output"] == "export const login = …"
+ assert result["duration_ms"] == 2000
+ finished = by_kind["turn_finished"]["payload"]
+ assert finished["status"] == "done"
+ # Two messages, counted once each — not once per record of a message.
+ assert finished["usage"]["output_tokens"] == 80
+ assert finished["duration_ms"] == 8000
+ # Timestamps are the file's, not the clock's: seq ascends, ts follows the rows.
+ assert [ev["seq"] for ev in events] == list(range(1, len(events) + 1))
+ assert events[0]["ts_ms"] < events[-1]["ts_ms"]
+
+ def test_thinking_with_words_keeps_them(self, tmp_path: Path) -> None:
+ _claude_session(
+ tmp_path,
+ "abc",
+ [
+ _user("go", 0),
+ _assistant({"type": "thinking", "thinking": "Check the tests first."}, 1),
+ _assistant({"type": "text", "text": "On it."}, 2),
+ ],
+ )
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path)
+ assert events is not None
+ reasoning = next(ev for ev in events if ev["kind"] == "reasoning")
+ assert reasoning["payload"]["text"] == "Check the tests first."
+
+ def test_a_working_pane_leaves_its_last_turn_running(self, tmp_path: Path) -> None:
+ """Same file, two endings: the pane's state decides, not the file."""
+ rows = [
+ _user("go", 0),
+ _assistant({"type": "text", "text": "Reading."}, 1),
+ _assistant({"type": "thinking", "thinking": "", "signature": "x"}, 2),
+ ]
+ _claude_session(tmp_path, "abc", rows)
+ idle = agent_transcript.read_events("claude", "abc", home=tmp_path, live=False)
+ live = agent_transcript.read_events("claude", "abc", home=tmp_path, live=True)
+ assert idle is not None and live is not None
+ assert _kinds(idle)[-2:] == ["reasoning", "turn_finished"]
+ # Still thinking: announced as a live thought, and the turn stays open.
+ assert _kinds(live)[-1] == "reasoning_started"
+ assert "turn_finished" not in _kinds(live)
+
+ def test_a_question_not_yet_answered_opens_a_turn_only_while_working(
+ self, tmp_path: Path
+ ) -> None:
+ _claude_session(tmp_path, "abc", [_user("go", 0)])
+ idle = agent_transcript.read_events("claude", "abc", home=tmp_path, live=False)
+ live = agent_transcript.read_events("claude", "abc", home=tmp_path, live=True)
+ assert idle is not None and _kinds(idle) == ["user_message"]
+ assert live is not None and _kinds(live) == ["user_message", "turn_started"]
+
+ def test_turns_are_cut_at_the_persons_messages(self, tmp_path: Path) -> None:
+ _claude_session(
+ tmp_path,
+ "abc",
+ [
+ _user("first", 0),
+ _assistant({"type": "text", "text": "one"}, 1),
+ _user("second", 2),
+ _assistant({"type": "text", "text": "two"}, 3, mid="msg_2"),
+ ],
+ )
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path)
+ assert events is not None
+ turn_ids = [ev["payload"]["turn_id"] for ev in events if ev["kind"] == "turn_started"]
+ assert turn_ids == ["turn-1", "turn-2"]
+ kinds = _kinds(events)
+ # The first turn is closed BEFORE the second question is recorded.
+ assert kinds.index("turn_finished") < kinds.index("user_message", 1)
+
+ def test_harness_and_sidechain_records_are_not_the_conversation(self, tmp_path: Path) -> None:
+ _claude_session(
+ tmp_path,
+ "abc",
+ [
+ _user("<local-command-caveat>ignore</local-command-caveat>", 0, isMeta=True),
+ _user("<task-notification>done</task-notification>", 0.5),
+ _user("real question", 1),
+ _assistant({"type": "text", "text": "sub-agent chatter"}, 2, isSidechain=True),
+ _assistant({"type": "text", "text": "answer"}, 3),
+ ],
+ )
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path)
+ assert events is not None
+ users = [ev["payload"]["text"] for ev in events if ev["kind"] == "user_message"]
+ assert users == ["real question"]
+ texts = [ev["payload"]["text"] for ev in events if ev["kind"] == "assistant_text"]
+ assert texts == ["answer"]
+
+ def test_only_the_last_turns_are_answered(self, tmp_path: Path) -> None:
+ rows: list[dict] = []
+ for n in range(agent_transcript.MAX_TURNS + 5):
+ rows.append(_user(f"q{n}", n * 2))
+ rows.append(_assistant({"type": "text", "text": f"a{n}"}, n * 2 + 1, mid=f"m{n}"))
+ _claude_session(tmp_path, "abc", rows)
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path)
+ assert events is not None
+ users = [ev["payload"]["text"] for ev in events if ev["kind"] == "user_message"]
+ assert len(users) == agent_transcript.MAX_TURNS
+ assert users[-1] == f"q{agent_transcript.MAX_TURNS + 4}"
+ # The cut is at a question, so the first event is one — never half a turn.
+ assert events[0]["kind"] == "user_message"
+
+ def test_no_file_is_none_not_an_error(self, tmp_path: Path) -> None:
+ assert agent_transcript.read_events("claude", "nope", home=tmp_path) is None
+ assert agent_transcript.read_events("shell", "abc", home=tmp_path) is None
+
+
+def _codex_session(home: Path, session_id: str, rows: list[dict]) -> None:
+ _write(
+ home
+ / "sessions"
+ / "2026"
+ / "08"
+ / "25"
+ / f"rollout-2026-08-25T16-50-19-{session_id}.jsonl",
+ rows,
+ )
+
+
+def _item(payload: dict, at: float) -> dict:
+ return {"timestamp": _at(at), "type": "response_item", "payload": payload}
+
+
+class TestCodexEvents:
+ def test_rollout_records_become_the_same_vocabulary(self, tmp_path: Path) -> None:
+ _codex_session(
+ tmp_path,
+ "sess-1",
+ [
+ {
+ "timestamp": _at(0),
+ "type": "turn_context",
+ "payload": {"turn_id": "t", "model": "gpt-5.6-terra"},
+ },
+ _item(
+ {
+ "type": "message",
+ "role": "developer",
+ "content": [{"type": "input_text", "text": "<skills>…</skills>"}],
+ },
+ 0.1,
+ ),
+ _item(
+ {
+ "type": "message",
+ "role": "user",
+ "content": [{"type": "input_text", "text": "list the files"}],
+ },
+ 1,
+ ),
+ _item(
+ {
+ "type": "reasoning",
+ "id": "rs_1",
+ "summary": [{"type": "summary_text", "text": "Need a listing."}],
+ },
+ 2,
+ ),
+ _item(
+ {
+ "type": "function_call",
+ "call_id": "fc_1",
+ "name": "shell",
+ "arguments": json.dumps({"command": ["ls"]}),
+ },
+ 3,
+ ),
+ _item(
+ {"type": "function_call_output", "call_id": "fc_1", "output": "a.txt\nb.txt"},
+ 4,
+ ),
+ _item(
+ {
+ "type": "message",
+ "id": "msg_1",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "Two files."}],
+ },
+ 5,
+ ),
+ {
+ "timestamp": _at(6),
+ "type": "event_msg",
+ "payload": {"type": "task_complete", "turn_id": "t", "error": None},
+ },
+ ],
+ )
+ events = agent_transcript.read_events("codex", "sess-1", home=tmp_path, live=True)
+ assert events is not None
+ assert _kinds(events) == [
+ "user_message",
+ "turn_started",
+ "reasoning",
+ "tool_call",
+ "tool_result",
+ "assistant_text",
+ "turn_finished",
+ ]
+ by_kind = {ev["kind"]: ev for ev in events}
+ assert by_kind["turn_started"]["payload"]["model"] == "gpt-5.6-terra"
+ assert by_kind["reasoning"]["payload"]["text"] == "Need a listing."
+ assert by_kind["reasoning"]["payload"]["duration_ms"] == 1000
+ assert by_kind["tool_call"]["payload"]["input"] == {"command": ["ls"]}
+ assert by_kind["tool_result"]["payload"]["output"] == "a.txt\nb.txt"
+ # `task_complete` ends the turn even on a pane that is still "working":
+ # the CLI itself said it was done.
+ assert by_kind["turn_finished"]["payload"]["status"] == "done"
+
+ def test_a_failed_task_ends_the_turn_in_error(self, tmp_path: Path) -> None:
+ _codex_session(
+ tmp_path,
+ "sess-2",
+ [
+ _item(
+ {
+ "type": "message",
+ "role": "user",
+ "content": [{"type": "input_text", "text": "hi"}],
+ },
+ 1,
+ ),
+ _item(
+ {
+ "type": "message",
+ "id": "m",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "…"}],
+ },
+ 2,
+ ),
+ {
+ "timestamp": _at(3),
+ "type": "event_msg",
+ "payload": {
+ "type": "task_complete",
+ "error": {"message": "You've hit your usage limit."},
+ },
+ },
+ ],
+ )
+ events = agent_transcript.read_events("codex", "sess-2", home=tmp_path)
+ assert events is not None
+ finished = events[-1]
+ assert finished["kind"] == "turn_finished"
+ assert finished["payload"]["status"] == "error"
+ assert finished["payload"]["error"] == "You've hit your usage limit."
+
+
+class TestTimestamps:
+ def test_iso_and_epoch_shapes(self) -> None:
+ expected = calendar.timegm((2026, 8, 26, 17, 15, 42)) * 1000 + 847
+ assert agent_transcript._ts_ms("2026-08-26T17:15:42.847Z") == expected
+ assert agent_transcript._ts_ms(expected / 1000) == expected
+ assert agent_transcript._ts_ms(expected) == expected
+ assert agent_transcript._ts_ms("not a time") is None
+ assert agent_transcript._ts_ms(None) is None
+ assert agent_transcript._ts_ms(True) is None