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(ide): title panes with the name their coding CLI gave the session

rubenluetke10-beepe0bf58134c11
diff --git a/jarvis/agentic_ide/cli_title.py b/jarvis/agentic_ide/cli_title.py
new file mode 100644
index 0000000000..95a979a6cf
--- /dev/null
+++ b/jarvis/agentic_ide/cli_title.py
@@ -0,0 +1,289 @@
+"""The title a pane's coding CLI gave its own session — taken, never written.
+
+Claude Code and Codex both name a conversation themselves, with their own
+subscription, a moment after it starts: Claude Code appends an ``ai-title``
+record to its transcript (and a ``custom-title`` one on ``/rename``) and puts
+the same words in the terminal's window title as ``"✳ <topic>"``; Codex keeps
+a ``thread_name`` per thread in ``session_index.jsonl``. That is exactly the
+navigation label a pane header wants — so the header takes it instead of
+paying a second model to write another one.
+
+Two sources, in order:
+
+* **The CLI's own record on disk.** Durable: it survives a backend restart and
+ a pane that has not repainted its title since. Read off the event loop,
+ incrementally (only the bytes appended since the last read), and re-checked
+ on a slow clock, because a CLI renames a session rarely.
+* **The live window title** (OSC 0/2, :attr:`ScreenBuffer.title`). Works for
+ every CLI that sets one, before the record exists, and on a pane running on
+ another computer whose files are not on this disk. Spinner and status glyphs
+ are stripped, and a title that only names the program, the folder or a
+ shell executable is not a title.
+
+Never raises: this sits on the path of every state read.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+import threading
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from . import agent_sessions
+
+#: How often a pane's record is looked at again. A CLI names a session once,
+#: shortly after the first message, and renames it rarely; a few seconds of
+#: delay on a rename is invisible, a file read per pane per poll is not.
+RECHECK_S = 15.0
+
+#: Longest title kept. A CLI's own title is a few words; this only stops a
+#: pathological window title from becoming the transport's problem.
+MAX_CHARS = 120
+
+#: Entries are dropped on pane close (:func:`forget`); this bound only keeps a
+#: process that never closes anything from growing without limit.
+MAX_ENTRIES = 512
+
+#: Window titles that name the program rather than the session.
+_GENERIC = frozenset({"claude", "claude code", "codex", "openai codex", "gemini", "opencode"})
+
+#: Leading spinner / status glyphs: anything up to the first letter or digit.
+_LEAD_RE = re.compile(r"^[\W_]+", flags=re.UNICODE)
+
+#: A shell or executable path set as the title (``C:\WINDOWS\system32\cmd.exe``).
+_EXE_RE = re.compile(r"(?i)^(?:[a-z]:)?[\\/].*|.*\.(?:exe|cmd|bat|ps1)$")
+
+
+@dataclass
+class _Record:
+ """What has been read of one pane's record file so far."""
+
+ path: Path | None = None
+ offset: int = 0
+ ai_title: str = ""
+ custom_title: str = ""
+ checked_at: float = 0.0
+ inflight: bool = False
+
+ @property
+ def title(self) -> str:
+ return self.custom_title or self.ai_title
+
+
+@dataclass
+class _CodexIndex:
+ """``session_index.jsonl`` of one CODEX_HOME, read incrementally."""
+
+ offset: int = 0
+ names: dict[str, str] = field(default_factory=dict)
+
+
+_records: dict[tuple[str, str], _Record] = {}
+_codex_indexes: dict[str, _CodexIndex] = {}
+#: Several panes' reads run on executor threads and share one index per home.
+_codex_lock = threading.Lock()
+
+
+def title_for(term: Any) -> str:
+ """The title ``term``'s CLI gave its session, or "" when it has none yet."""
+ try:
+ return _clip(_recorded(term) or window_title(term))
+ except Exception as exc: # noqa: BLE001 - a title must never break a state read
+ logger.debug("Agentic IDE: CLI title of {} unreadable: {}", getattr(term, "key", "?"), exc)
+ return ""
+
+
+def window_title(term: Any) -> str:
+ """The pane's live window title, cleaned — "" when it names no session."""
+ transcript = getattr(term, "transcript", None)
+ screen = getattr(transcript, "screen", None)
+ return clean_window_title(
+ str(getattr(screen, "title", "") or ""),
+ names=(
+ str(getattr(term, "agent", "") or ""),
+ str(getattr(term, "display_name", "") or ""),
+ Path(str(getattr(term, "folder", "") or "")).name,
+ ),
+ )
+
+
+def clean_window_title(raw: str, *, names: tuple[str, ...] = ()) -> str:
+ """``"⠋ Fix login test"`` → ``"Fix login test"``; a program/folder name → ""."""
+ if _EXE_RE.match(raw.strip()):
+ return ""
+ text = " ".join(_LEAD_RE.sub("", raw.strip()).split())
+ if not text or _EXE_RE.match(text):
+ return ""
+ lowered = text.casefold()
+ if lowered in _GENERIC or lowered in {n.strip().casefold() for n in names if n.strip()}:
+ return ""
+ return text
+
+
+def _clip(text: str) -> str:
+ text = " ".join(str(text or "").split())
+ return text if len(text) <= MAX_CHARS else text[: MAX_CHARS - 1].rstrip() + "…"
+
+
+def _recorded(term: Any) -> str:
+ """The title from the CLI's record on disk — cached, read off the loop."""
+ if getattr(term, "computer_id", ""):
+ return "" # its record lives on the other computer
+ agent = str(getattr(term, "agent", "") or "").strip().lower()
+ if agent not in ("claude", "codex"):
+ return ""
+ handle = getattr(term, "resume", None)
+ session_id = str(getattr(handle, "id", "") or "").strip() if handle is not None else ""
+ if not session_id:
+ return ""
+ # Lifetime id, like the recap cache: two workspaces can each hold a "t5".
+ pane = str(getattr(term, "history_id", "") or getattr(term, "key", "") or "")
+ key = (pane, session_id)
+ entry = _records.get(key)
+ if entry is None:
+ if len(_records) >= MAX_ENTRIES:
+ _records.pop(next(iter(_records)))
+ entry = _records[key] = _Record()
+ now = time.monotonic()
+ if entry.inflight or (entry.checked_at and now - entry.checked_at < RECHECK_S):
+ return entry.title
+ entry.inflight = True
+ home = _home(term)
+
+ def _read() -> None:
+ try:
+ if agent == "claude":
+ _read_claude(entry, session_id, home)
+ else:
+ entry.ai_title = _codex_name(session_id, home)
+ except Exception as exc: # noqa: BLE001 - a title must never break a state read
+ logger.debug("Agentic IDE: title record of {} unreadable: {}", session_id, exc)
+ finally:
+ entry.checked_at = time.monotonic()
+ entry.inflight = False
+
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # No loop (a worker thread, a test): nothing to keep free, so answer now.
+ _read()
+ return entry.title
+ loop.run_in_executor(None, _read)
+ return entry.title
+
+
+def _read_claude(entry: _Record, session_id: str, home: Path | None) -> None:
+ """Fold the records appended since the last read into ``entry``."""
+ if entry.path is None:
+ projects = agent_sessions._claude_home(home) / "projects"
+ if not projects.is_dir():
+ return
+ entry.path = next(projects.glob(f"*/{session_id}.jsonl"), None)
+ if entry.path is None:
+ return
+ try:
+ size = entry.path.stat().st_size
+ except OSError:
+ entry.path = None # moved or deleted; look it up again next time
+ return
+ if size < entry.offset:
+ entry.offset = 0 # rewritten from scratch
+ if size == entry.offset:
+ return
+ with entry.path.open("rb") as handle:
+ handle.seek(entry.offset)
+ chunk = handle.read(size - entry.offset)
+ # Only whole lines: a record being appended right now is read next time.
+ end = chunk.rfind(b"\n") + 1
+ entry.offset += end
+ for line in chunk[:end].splitlines():
+ if b"-title" not in line:
+ continue # cheap pre-filter; almost every line is conversation
+ row = _json(line)
+ kind = row.get("type")
+ if kind == "custom-title":
+ entry.custom_title = str(row.get("customTitle") or "").strip()
+ elif kind == "ai-title":
+ entry.ai_title = str(row.get("aiTitle") or "").strip()
+
+
+def _codex_name(session_id: str, home: Path | None) -> str:
+ """The newest ``thread_name`` Codex recorded for ``session_id``."""
+ path = agent_sessions._codex_home(home) / "session_index.jsonl"
+ with _codex_lock:
+ return _codex_name_locked(path, session_id)
+
+
+def _codex_name_locked(path: Path, session_id: str) -> str:
+ index = _codex_indexes.setdefault(str(path), _CodexIndex())
+ try:
+ size = path.stat().st_size
+ except OSError:
+ return ""
+ if size < index.offset:
+ index.offset, index.names = 0, {}
+ if size > index.offset:
+ with path.open("rb") as handle:
+ handle.seek(index.offset)
+ chunk = handle.read(size - index.offset)
+ end = chunk.rfind(b"\n") + 1
+ index.offset += end
+ for line in chunk[:end].splitlines():
+ row = _json(line)
+ thread, name = str(row.get("id") or ""), str(row.get("thread_name") or "").strip()
+ if thread and name:
+ index.names[thread] = name
+ return index.names.get(session_id, "")
+
+
+def _json(line: bytes) -> dict[str, Any]:
+ try:
+ row = json.loads(line)
+ except ValueError:
+ return {}
+ return row if isinstance(row, dict) else {}
+
+
+def _home(term: Any) -> Path | None:
+ """The config dir this pane's CLI keeps its history in, when redirected."""
+ account = str(getattr(term, "account", "") or "")
+ agent = str(getattr(term, "agent", "") or "")
+ if not account:
+ return None
+ try:
+ from jarvis import agent_accounts
+
+ if agent not in agent_accounts.platforms():
+ return None
+ return agent_accounts.config_dir_for(agent, account) # type: ignore[arg-type]
+ except Exception as exc: # noqa: BLE001 - the default home is the honest fallback
+ logger.debug("Agentic IDE: account folder for {} is unknown: {}", agent, exc)
+ return None
+
+
+def forget(key: str) -> None:
+ """Drop what is remembered about one pane (its lifetime id) — it has been closed."""
+ for cached in [item for item in _records if item[0] == key]:
+ _records.pop(cached, None)
+
+
+def reset_for_tests() -> None:
+ _records.clear()
+ _codex_indexes.clear()
+
+
+__all__ = [
+ "RECHECK_S",
+ "clean_window_title",
+ "forget",
+ "reset_for_tests",
+ "title_for",
+ "window_title",
+]
diff --git a/jarvis/agentic_ide/recap_engine.py b/jarvis/agentic_ide/recap_engine.py
index a054f49cb7..6c68e3fca5 100644
--- a/jarvis/agentic_ide/recap_engine.py
+++ b/jarvis/agentic_ide/recap_engine.py
@@ -63,7 +63,7 @@ from typing import TYPE_CHECKING, Any
from loguru import logger
-from . import recap
+from . import cli_title, recap
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Sequence
@@ -199,12 +199,17 @@ BY_RULES = "heuristic"
#: The user wrote it themselves, through the pencil in the pane header. It wins
#: over both of the above and is never overwritten by a background summary.
BY_USER = "user"
+#: The coding CLI in the pane named its own session (Claude Code's ``ai-title``,
+#: Codex's ``thread_name``, a window title) — :mod:`.cli_title`. Outranks the
+#: model and the rules, and costs nothing: the CLI already paid for it.
+BY_CLI = "cli"
#: Why the recap on screen is the one on screen. Machine-readable on purpose:
#: the wording belongs to the UI, and the whole point of the field is that
#: "this line is thin" stops being a mystery. Rendered in the recap card.
WHY_PINNED = "pinned" # you wrote it
WHY_SUMMARIZED = "summarized" # a model read the pane and wrote it
+WHY_CLI_TITLE = "cli_title" # the pane's own CLI named the session
WHY_DISABLED = "disabled" # model recaps switched off in settings
WHY_NOT_STARTED = "not_started" # nothing has run in this pane yet
WHY_WARMING = "warming" # too little output so far to summarize
@@ -473,17 +478,18 @@ def _state(key: str) -> _PaneState:
def _enabled() -> bool:
"""Is the model-written recap switched on for this install?
- Read live rather than cached, so turning it off in ``jarvis.toml`` takes
- effect on the next poll instead of on the next restart. A config that cannot
- be loaded answers "on": the deterministic floor is what runs anyway when
- nothing else works.
+ Off unless the user opted in: the coding CLIs name their sessions
+ themselves (:mod:`.cli_title`), so a second, paid name is not worth a
+ background request. Read live rather than cached, so switching it in
+ ``jarvis.toml`` takes effect on the next poll. A config that cannot be
+ loaded answers "off" — nothing the user did not ask for may bill a key.
"""
try:
from jarvis.core.config import load_config
- return bool(getattr(load_config().agentic_ide, "smart_recaps", True))
+ return bool(getattr(load_config().agentic_ide, "smart_recaps", False))
except Exception: # noqa: BLE001 - a recap must never break a state read
- return True
+ return False
def _ui_language() -> str:
@@ -575,6 +581,16 @@ def recap_for(term: Any, *, lines: Sequence[str] | None = None) -> SmartRecap:
generated_at=entry.pinned_at,
reason=WHY_PINNED,
)
+ named = cli_title.title_for(term)
+ if named:
+ plain = recap.summarize(term, lines=None if lines is None else list(lines))
+ return SmartRecap(
+ headline=recap.condense(named, MAX_EDIT_HEADLINE),
+ detail=plain.detail,
+ source=BY_CLI,
+ reason=WHY_CLI_TITLE,
+ writer=str(getattr(term, "display_name", "") or ""),
+ )
if entry is not None and entry.headline:
return SmartRecap(
headline=entry.headline,
@@ -625,9 +641,12 @@ def known_headline(term: Any) -> str:
fact everything there is to say.
"""
entry = _panes.get(pane_id(term))
+ if entry is not None and entry.pinned_headline:
+ return entry.pinned_headline
+ named = cli_title.title_for(term)
+ if named:
+ return recap.condense(named, MAX_EDIT_HEADLINE)
if entry is not None:
- if entry.pinned_headline:
- return entry.pinned_headline
if entry.headline:
return entry.headline
asked_at = float(getattr(term, "last_prompt_at", None) or 0.0)
@@ -662,6 +681,10 @@ def refresh_soon(term: Any, *, lines: Sequence[str], folder: str = "") -> None:
# sentence nothing renders.
if entry.pinned_headline:
return
+ # The CLI named this session itself; a summary would buy a second name
+ # that the header never shows.
+ if cli_title.title_for(term):
+ return
now = time.time()
if entry.inflight or now < entry.quiet_until:
return
@@ -1296,6 +1319,7 @@ def _floor(term: Any, rows: Sequence[str], why: str, *, note: str = "") -> Smart
def forget(key: str) -> None:
"""Drop what is remembered about one pane — it has been closed."""
_panes.pop(key, None)
+ cli_title.forget(key)
def reset_for_tests() -> None:
@@ -1306,9 +1330,11 @@ def reset_for_tests() -> None:
_inflight = 0
_provider_failures.clear()
_provider_quiet_until.clear()
+ cli_title.reset_for_tests()
__all__ = [
+ "BY_CLI",
"BY_MODEL",
"BY_RULES",
"BY_USER",
@@ -1324,6 +1350,7 @@ __all__ = [
"NO_PROVIDER_NOTE",
"PROVIDER_FAILURES_BEFORE_QUIET",
"PROVIDER_QUIET_S",
+ "WHY_CLI_TITLE",
"WHY_DISABLED",
"WHY_NOT_STARTED",
"WHY_PINNED",
diff --git a/jarvis/agentic_ide/screen.py b/jarvis/agentic_ide/screen.py
index cce97268d6..397e790e4b 100644
--- a/jarvis/agentic_ide/screen.py
+++ b/jarvis/agentic_ide/screen.py
@@ -64,6 +64,7 @@ class ScreenBuffer:
"_scroll_top",
"_scroll_bottom",
"_wrap_pending",
+ "title",
)
def __init__(self, cols: int = 100, rows: int = 30, scrollback: int = 800) -> None:
@@ -79,6 +80,10 @@ class ScreenBuffer:
self._scroll_top = 0
self._scroll_bottom = self.rows - 1
self._wrap_pending = False
+ # The window title the program last set (OSC 0 / OSC 2), verbatim.
+ # Coding CLIs name their session there themselves — Claude Code writes
+ # "✳ <topic>" — which is a pane title nobody has to pay a model for.
+ self.title = ""
# ------------------------------------------------------------------ grid
def _blank_row(self) -> list[str]:
@@ -194,8 +199,10 @@ class ScreenBuffer:
j = start + 2
while j < n:
if data[j] == "\x07":
+ self._osc(data[start + 2 : j])
return j - start + 1
if data[j] == "\x1b" and j + 1 < n and data[j + 1] == "\\":
+ self._osc(data[start + 2 : j])
return j - start + 2
if data[j] == "\x1b":
return 0 if j + 1 >= n else j - start + 1
@@ -223,6 +230,12 @@ class ScreenBuffer:
# Anything else (7/8 save-restore cursor, =/>, ...) — skip the two bytes.
return 2
+ def _osc(self, body: str) -> None:
+ """Keep a window-title change; every other OSC carries no screen content."""
+ code, sep, text = body.partition(";")
+ if sep and code in {"0", "2"}:
+ self.title = text
+
def _handle_csi(self, data: str, start: int) -> int:
n = len(data)
j = start + 2
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 97f7c9e457..e7af6ffe45 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -4269,12 +4269,12 @@ class AgenticIdeConfig(BaseModel):
)
smart_recaps: bool = Field(
- default=True,
+ default=False,
description=(
- "Let a model write each pane's header recap — what the pane set out "
- "to do, where it stands, what is outstanding. Off falls back to the "
- "transcript-derived one, which costs nothing and says much less. An "
- "install with no reachable provider gets the fallback either way."
+ "Let a model write a pane's header title when its coding CLI has not "
+ "named the session itself. Off (the default) uses the CLI's own title "
+ "(Claude Code, Codex) and otherwise the pane's first or last prompt, "
+ "which costs nothing. On spends background model requests."
),
)
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index e0eef43a53..8ad0ca0fe9 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -1261,6 +1261,7 @@ class TerminalRecap(TerminalActivity):
default="heuristic",
description=(
"Who wrote this recap: 'user' when the user wrote it themselves, "
+ "'cli' when the pane's coding CLI named its own session, "
"'model' when a brain summarized the pane, 'heuristic' when it was "
"derived from the transcript by rule — which is what an install with "
"no reachable provider always gets."
@@ -1269,7 +1270,7 @@ class TerminalRecap(TerminalActivity):
reason: str = Field(
default="",
description=(
- "Why this recap and not a better one: 'pinned', 'summarized', "
+ "Why this recap and not a better one: 'pinned', 'cli_title', 'summarized', "
"'disabled', 'not_started', 'warming', 'working', 'queued' or "
"'unavailable'. The UI turns it into a sentence, so a thin recap "
"explains itself instead of looking broken."
@@ -1277,7 +1278,9 @@ class TerminalRecap(TerminalActivity):
)
writer: str = Field(
default="",
- description="The model that wrote it, when one did. Empty otherwise.",
+ description=(
+ "The model that wrote it, or the CLI that named the session. Empty otherwise."
+ ),
)
note: str = Field(
default="",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.tsx
index e6e05606a6..f68e42fd54 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.tsx
@@ -76,6 +76,7 @@ export const MAX_DETAIL = 2000;
*/
const WHY: Partial<Record<RecapReason, string>> = {
pinned: "You wrote this. It stays until you reset it.",
+ cli_title: "The agent in this pane named its session itself.",
disabled:
"Model recaps are switched off, so this is read from the pane's own output.",
not_started: "Nothing is running in this pane yet, so there is nothing to summarize.",
@@ -92,6 +93,11 @@ const WHY: Partial<Record<RecapReason, string>> = {
function credit(source: RecapSource, writer: string): { label: string; icon: JSX.Element } {
if (source === "user")
return { label: "Written by you", icon: <User className="h-3 w-3" /> };
+ if (source === "cli")
+ return {
+ label: writer ? `Named by ${writer}` : "Named by the agent",
+ icon: <Terminal className="h-3 w-3" />,
+ };
if (source === "model")
return {
label: writer ? `Summarized by ${writer}` : "Summarized by a model",
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 61a872ac8c..3558a35000 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -284,9 +284,10 @@ export type PaneActivity =
* Who wrote the recap on screen.
*
* `"user"` outranks both machines: a pane the user has labelled themselves
- * keeps that label until they clear it.
+ * keeps that label until they clear it. `"cli"` is the title the pane's own
+ * coding CLI gave its session (Claude Code, Codex) — free, and next in line.
*/
-export type RecapSource = "user" | "model" | "heuristic";
+export type RecapSource = "user" | "cli" | "model" | "heuristic";
/**
* Why this recap and not a better one.
@@ -297,6 +298,7 @@ export type RecapSource = "user" | "model" | "heuristic";
*/
export type RecapReason =
| "pinned"
+ | "cli_title"
| "summarized"
| "disabled"
| "not_started"
diff --git a/jarvis/ui/web/frontend/src/store/paneRecaps.ts b/jarvis/ui/web/frontend/src/store/paneRecaps.ts
index 938eb81748..5950322b61 100644
--- a/jarvis/ui/web/frontend/src/store/paneRecaps.ts
+++ b/jarvis/ui/web/frontend/src/store/paneRecaps.ts
@@ -10,11 +10,11 @@ import { sessionTitle } from "@/components/agentic/sessionTitle";
* Every pane's short title — a few words naming its goal — for the workspace
* on screen.
*
- * The titles come from `/recaps`: a model reads each pane and writes a 3–5
- * word navigation label (`recap_engine`). That poll is also the ONLY thing
- * that asks the backend to write those labels at all — the summarizer runs
- * because somebody is looking — so the grid headers and the side panel share
- * one reference-counted poll here rather than each running their own.
+ * The titles come from `/recaps`: the title the pane's coding CLI gave its
+ * own session (`cli_title`), else one the user pinned, else — only when the
+ * user switched model recaps on — a model-written label (`recap_engine`). The
+ * grid headers and the side panel share one reference-counted poll here
+ * rather than each running their own.
*
* It polls only while the Agentic IDE is the section on screen: the view stays
* mounted when hidden, and a hidden workspace needs no fresh titles.
@@ -72,8 +72,8 @@ export function usePaneRecapPoll(): void {
/**
* The words a pane is labelled with instead of its call-sign.
*
- * A title the user pinned or the model wrote wins. Before one exists, the
- * pane's own topic (`sessionTitle`: its last prompt, the message that opened
+ * A title the user pinned, the CLI gave its session, or the model wrote wins.
+ * Before one exists, the pane's own topic (`sessionTitle`: its last prompt, the message that opened
* the conversation) stands in; a pane that was never asked anything has no
* topic, and "" tells the caller to fall back to the call-sign.
*/
@@ -82,7 +82,8 @@ export function paneTitleFrom(
row: Parameters<typeof sessionTitle>[0] | undefined,
): string {
const written = (recap?.recap ?? "").trim();
- if (written && (recap?.source === "model" || recap?.source === "user")) return written;
+ const named = recap?.source === "user" || recap?.source === "cli" || recap?.source === "model";
+ if (written && named) return written;
if (!row) return "";
const topic = sessionTitle(row).trim();
return topic && topic !== row.display_name && topic !== row.name ? topic : "";
diff --git a/tests/unit/agentic_ide/test_cli_title.py b/tests/unit/agentic_ide/test_cli_title.py
new file mode 100644
index 0000000000..7ad62cb54b
--- /dev/null
+++ b/tests/unit/agentic_ide/test_cli_title.py
@@ -0,0 +1,200 @@
+"""Pane titles come from the coding CLI itself, not from a paid summary.
+
+Claude Code records an ``ai-title`` (and ``custom-title`` on ``/rename``) in
+its transcript and shows it as the window title; Codex keeps a ``thread_name``
+in ``session_index.jsonl``. These tests pin that the header takes those words,
+that a title naming only the program or the folder is ignored, and that no
+model summary is scheduled for a pane its CLI has already named.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import cli_title, recap_engine
+from jarvis.agentic_ide.agent_sessions import ResumeHandle
+from jarvis.agentic_ide.screen import ScreenBuffer
+from jarvis.agentic_ide.session import Terminal
+
+
[email protected](autouse=True)
+def _clean():
+ recap_engine.reset_for_tests()
+ yield
+ recap_engine.reset_for_tests()
+
+
+def _pane(agent: str = "claude", display_name: str = "Claude Code", **changes: object) -> Terminal:
+ term = Terminal(
+ key="t1",
+ name="T1",
+ agent=agent,
+ display_name=display_name,
+ index=0,
+ status="live",
+ )
+ for name, value in changes.items():
+ setattr(term, name, value)
+ return term
+
+
+def _write_jsonl(path: Path, rows: list[dict]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8", newline="\n") as handle:
+ for row in rows:
+ handle.write(json.dumps(row) + "\n")
+
+
+# ------------------------------------------------------------ window title
+
+
+def test_the_screen_keeps_the_last_window_title_in_both_terminators() -> None:
+ screen = ScreenBuffer()
+ screen.feed("\x1b]0;✳ Claude Code\x07hello")
+ assert screen.title == "✳ Claude Code"
+ screen.feed("\x1b]2;⠋ Fix login test\x1b\\")
+ assert screen.title == "⠋ Fix login test"
+ # A hyperlink is an OSC too, and must not touch the title.
+ screen.feed("\x1b]8;;https://example.com\x07link\x1b]8;;\x07")
+ assert screen.title == "⠋ Fix login test"
+
+
+def test_a_title_split_across_two_reads_is_still_read() -> None:
+ screen = ScreenBuffer()
+ screen.feed("\x1b]0;✳ Pane ti")
+ screen.feed("tles from the CLI\x07")
+ assert screen.title == "✳ Pane titles from the CLI"
+
+
+ ("raw", "expected"),
+ [
+ ("✳ Terminal titles in the IDE", "Terminal titles in the IDE"),
+ ("⠹ Fix login test", "Fix login test"),
+ ("✳ Claude Code", ""),
+ ("codex", ""),
+ ("⠇ Personal Jarvis", ""),
+ ("C:\\windows\\system32\\cmd.exe ", ""),
+ ("/usr/bin/zsh", ""),
+ ("", ""),
+ ],
+)
+def test_a_window_title_is_cleaned_and_program_names_are_dropped(raw: str, expected: str) -> None:
+ names = ("claude", "Claude Code", "Personal Jarvis")
+ assert cli_title.clean_window_title(raw, names=names) == expected
+
+
+def test_a_pane_takes_its_live_window_title() -> None:
+ term = _pane(folder="/work/Personal Jarvis")
+ term.transcript.feed("\x1b]0;⠐ Terminal titles from the CLI\x07")
+
+ assert cli_title.title_for(term) == "Terminal titles from the CLI"
+
+
+def test_codex_naming_only_its_folder_is_not_a_title() -> None:
+ term = _pane(agent="codex", display_name="Codex", folder="/work/Personal Jarvis")
+ term.transcript.feed("\x1b]0;⠋ Personal Jarvis\x07")
+
+ assert cli_title.title_for(term) == ""
+
+
+# ------------------------------------------------------------ CLI records
+
+
+def test_claude_s_own_title_record_wins_and_a_rename_outranks_it(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(cli_title, "RECHECK_S", 0.0)
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path))
+ session_id = "11111111-2222-3333-4444-555555555555"
+ record = tmp_path / "projects" / "proj" / f"{session_id}.jsonl"
+ _write_jsonl(
+ record,
+ [
+ {"type": "user", "message": {"role": "user", "content": "hi"}},
+ {"type": "ai-title", "aiTitle": "Terminal titles in the IDE", "sessionId": session_id},
+ ],
+ )
+ term = _pane(resume=ResumeHandle(kind="claude_session", id=session_id, captured_at=0.0))
+ term.transcript.feed("\x1b]0;✳ Something older\x07")
+
+ assert cli_title.title_for(term) == "Terminal titles in the IDE"
+
+ # Only the appended bytes are read next time, and /rename wins.
+ _write_jsonl(record, [{"type": "custom-title", "customTitle": "Demo branch"}])
+ assert cli_title.title_for(term) == "Demo branch"
+ _write_jsonl(record, [{"type": "ai-title", "aiTitle": "A newer automatic title"}])
+ assert cli_title.title_for(term) == "Demo branch"
+
+
+def test_codex_s_thread_name_is_the_title(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(cli_title, "RECHECK_S", 0.0)
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ index = tmp_path / "session_index.jsonl"
+ _write_jsonl(
+ index,
+ [
+ {"id": "other", "thread_name": "Someone else"},
+ {"id": "abc", "thread_name": "Analyse the paste bug"},
+ ],
+ )
+ term = _pane(
+ agent="codex",
+ display_name="Codex",
+ resume=ResumeHandle(kind="codex_rollout", id="abc", captured_at=0.0),
+ )
+
+ assert cli_title.title_for(term) == "Analyse the paste bug"
+
+ _write_jsonl(index, [{"id": "abc", "thread_name": "Paste bug — fixed"}])
+ assert cli_title.title_for(term) == "Paste bug — fixed"
+
+
+# ------------------------------------------------------------ recap engine
+
+
+def test_the_header_shows_the_cli_title_over_the_floor() -> None:
+ term = _pane(last_prompt="please look at the thing")
+ term.transcript.feed("\x1b]0;✳ Terminal titles in the IDE\x07")
+
+ answer = recap_engine.recap_for(term, lines=term.transcript.lines())
+
+ assert answer.source == recap_engine.BY_CLI
+ assert answer.reason == recap_engine.WHY_CLI_TITLE
+ assert answer.headline == "Terminal titles in the IDE"
+ assert answer.writer == "Claude Code"
+ assert recap_engine.known_headline(term) == "Terminal titles in the IDE"
+
+
+def test_a_pinned_title_still_outranks_the_cli() -> None:
+ term = _pane()
+ term.transcript.feed("\x1b]0;✳ Terminal titles in the IDE\x07")
+ recap_engine.pin(recap_engine.pane_id(term), "Leave this one alone")
+
+ assert recap_engine.recap_for(term, lines=[]).headline == "Leave this one alone"
+
+
+def test_a_pane_its_cli_named_is_never_summarized(monkeypatch) -> None:
+ monkeypatch.setattr(recap_engine, "_enabled", lambda: True)
+ spawned: list[str] = []
+ monkeypatch.setattr(recap_engine, "_spawn", lambda term, key, rows, folder: spawned.append(key))
+ term = _pane()
+ term.transcript.feed("\x1b]0;✳ Terminal titles in the IDE\x07")
+
+ recap_engine.refresh_soon(term, lines=[f"row {n}" for n in range(80)])
+
+ assert spawned == []
+
+
+def test_model_recaps_are_off_unless_switched_on(monkeypatch) -> None:
+ from types import SimpleNamespace
+
+ monkeypatch.setattr(
+ "jarvis.core.config.load_config", lambda: SimpleNamespace(agentic_ide=SimpleNamespace())
+ )
+ assert recap_engine._enabled() is False # noqa: SLF001
+
+ from jarvis.core.config import AgenticIdeConfig
+
+ assert AgenticIdeConfig().smart_recaps is False
diff --git a/tests/unit/agentic_ide/test_recap_route.py b/tests/unit/agentic_ide/test_recap_route.py
index 5c5fee1faa..695d065244 100644
--- a/tests/unit/agentic_ide/test_recap_route.py
+++ b/tests/unit/agentic_ide/test_recap_route.py
@@ -19,9 +19,11 @@ from jarvis.ui.web import agentic_ide_routes
@pytest.fixture
-def client() -> TestClient:
+def client(monkeypatch) -> TestClient:
ide.reset_registry()
recap_engine.reset_for_tests()
+ # Model recaps are opt-in; these routes are tested as an install that opted in.
+ monkeypatch.setattr(recap_engine, "_enabled", lambda: True)
app = FastAPI()
app.include_router(agentic_ide_routes.router)
with TestClient(app) as test_client: