Skip to content

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

fix(agentic-ide): restore terminal state and rename controls

Ruben Lütke7a0921091761
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index 0401047e8d..5f75bc2b76 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -341,6 +341,16 @@ Open one or more additional coding terminals in the open workspace, WITHOUT givi
- **Desktop UI section:** `agentic-ide`
- **Voice example (EN):** "spawn five new claude code terminals"
+## `agentic-ide-rename-terminal` — Rename an Agentic-IDE terminal
+
+Give one running terminal another call-sign without restarting its agent or losing its conversation. Use it when the user asks to rename a pane, for example 'rename T1 to Frontend'. The old call-sign must name a terminal that is already open, and the new one must be unique inside that workspace.
+
+- **Endpoint:** `PATCH /api/agentic-ide/terminals/{terminal}`
+- **Arguments:** `terminal` (string; required); `name` (string; required)
+- **Requires confirmation:** no
+- **Desktop UI section:** `agentic-ide`
+- **Voice example (EN):** "rename t1 to frontend"
+
## `agentic-ide-move-terminal` — Move an Agentic-IDE terminal in the grid
Rearrange the open workspace: put one terminal at another one's place. Nothing is started or stopped — the panes keep their agents and their conversations, only where they are drawn changes. Use it for 'swap Mika and Nova', 'put Mika next to Nova', 'move Mika under Nova'. 'swap' exchanges the two panes and leaves the rest of the grid alone; 'left'/'right' give the moved pane its own column beside the target; 'above'/'below' stack it in the target's column. Both names must be terminals that are already open.
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.md
index 5ba6ace904..743185802e 100644
--- a/docs/jarvis-cli-reference.md
+++ b/docs/jarvis-cli-reference.md
@@ -101,6 +101,7 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`
## ide
- `jarvis ide close-terminals <names> --yes --dry-run` — Stop several coding agents and close their terminal panes.
+- `jarvis ide rename-terminal <name> <new_name> --dry-run` — Rename a running terminal pane without restarting its agent.
## marketplace
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index d6a695f143..c75f426c94 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -201,6 +201,12 @@ def _unavailable(agent: str) -> str:
# Nobody reaches 100 deliberately; anyone who mistypes their way past it gets a
# sentence instead of a frozen desktop.
MAX_TERMINALS = 100
+# How long a pane's call-sign may be. Half the workspace tab's 80, and for a
+# different reason: a workspace name is read, a call-sign is SAID — it is how a
+# user addresses one agent among several out loud, and it also has to fit in a
+# pane header that may be a quarter of a screen wide. Long enough for "Frontend
+# rewrite", short enough that it stays a name rather than a description.
+MAX_TERMINAL_NAME = 40
# Where a pane may land when it is dragged onto another one, in the same two
# axes the grid is built from (columns of stacked panes). "swap" is listed first
# because it is the one a user reaches for most: two panes are the wrong way
@@ -775,17 +781,17 @@ class Terminal:
agent: str # "claude" | "codex"
display_name: str # "Claude Code"
index: int
+ # Stable for THIS pane's lifetime and deliberately unrelated to its visible
+ # call-sign. A closed T1 and a new T1 are different panes; a renamed T1 is
+ # still the same pane. Prompt-history files use this id to preserve exactly
+ # that boundary across app restarts.
+ history_id: str = field(default_factory=lambda: uuid4().hex)
# Where the pane sits in the grid, on TWO axes: the workspace is a
# left-to-right list of columns, and each column is a top-to-bottom stack.
# "Split right" opens a new column beside the anchor; "split down" adds a
# pane to the anchor's OWN column and leaves every other column alone.
#
# The second axis is load-bearing. With only a row number, "split down"
- # Stable for THIS pane's lifetime and deliberately unrelated to its visible
- # call-sign. A closed T1 and a new T1 are different panes; a renamed T1 is
- # still the same pane. Prompt-history files use this id to preserve exactly
- # that boundary across app restarts.
- history_id: str = field(default_factory=lambda: uuid4().hex)
# could only mean "open a new row", and a row is window-wide by definition —
# so splitting one pane squashed every other pane to half height. A full
# split TREE (arbitrary nesting, draggable separators) is still deliberately
@@ -819,18 +825,18 @@ class Terminal:
last_input_at: float | None = None
prompts_sent: int = 0
last_prompt: str = ""
- # When the last prompt was handed to this pane, as a wall-clock timestamp.
- #
- # The receipt the user is shown is built from THIS rather than from the
- # terminal stream, and that is the whole point. A pane proves a prompt
- # arrived by echoing it, which requires a chain of things to have gone
- # right at one particular moment: the pane on screen, its output un-parked,
# The current process's records are kept as a fallback if the local history
# file cannot be written. The full durable history is loaded only when its
# UI is opened, never in the workspace-state hot path.
prompt_records: list[prompt_history.PromptHistoryEntry] = field(
default_factory=list, repr=False, compare=False
)
+ # When the last prompt was handed to this pane, as a wall-clock timestamp.
+ #
+ # The receipt the user is shown is built from THIS rather than from the
+ # terminal stream, and that is the whole point. A pane proves a prompt
+ # arrived by echoing it, which requires a chain of things to have gone
+ # right at one particular moment: the pane on screen, its output un-parked,
# its socket up, the emulator painted. Every link in that chain has failed
# in production at least once, and each failure looks identical from the
# user's chair — Jarvis says it sent the brief and the pane shows nothing,
@@ -1060,13 +1066,13 @@ class Terminal:
key=self.key,
name=self.name,
agent=self.agent,
+ history_id=self.history_id,
column=self.column,
slot=self.slot,
resume=self.resume,
prompts_sent=self.prompts_sent,
account=self.account,
continuation_needed=self.resume_continuation_needed,
- history_id=self.history_id,
)
@@ -1104,12 +1110,24 @@ class Session:
restored_from: str = ""
def find(self, wanted: str) -> Terminal | None:
- """Terminal by key, call-sign, or a spoken phrase containing one."""
+ """Terminal by call-sign, key, or a spoken phrase containing one.
+
+ Call-signs are tried across EVERY pane before any key is, and that
+ order is load-bearing once panes can be renamed. A pane keeps the key
+ it was opened with (it is what the running pseudo-terminal is filed
+ under), so renaming T1 to "Frontend" leaves a pane whose key is still
+ ``t1`` — and the next pane opened is free to take the call-sign T1.
+ Asking about keys first would then hand "T1" to the pane the user
+ renamed precisely so it would stop being T1.
+ """
if not wanted:
return None
key = normalize(wanted)
for term in self.terminals:
- if normalize(term.key) == key or normalize(term.name) == key:
+ if normalize(term.name) == key:
+ return term
+ for term in self.terminals:
+ if normalize(term.key) == key:
return term
matched = resolve(wanted, [t.name for t in self.terminals])
if matched is None:
@@ -1809,6 +1827,7 @@ class Registry:
agent=entry.agent,
display_name=agent_display(entry.agent),
index=index,
+ history_id=entry.history_id or uuid4().hex,
column=entry.column,
slot=entry.slot,
resume=entry.resume,
@@ -1827,7 +1846,6 @@ class Registry:
#
# **The bug this fixes.** `continuation_pending` used to be raised in
# `attach`, which is the moment a pane's process is spawned — and cold
- history_id=entry.history_id or uuid4().hex,
# starts are deliberately staggered (see COLD_START_LIMIT), so in a
# workspace of a dozen panes most of them are still `pending` seconds
# after the grid appears. Anybody pressing "Continue" in that window got
@@ -2260,6 +2278,11 @@ class Registry:
progress every time somebody looked away, which is precisely what having
several workspaces would otherwise cost.
+ A replay is valid only at the geometry that produced its cursor moves.
+ When the viewer comes back at another size, the old drawing is replaced
+ by its terminal-mode prologue and a live repaint. This is still the same
+ process and conversation; only the stale pixels are discarded.
+
**That replay goes out on ``on_replay``, not on ``on_output``, because a
viewer has to CLEAR its screen before drawing it.** The two are the same
bytes and completely different instructions: live output continues a
@@ -2313,25 +2336,40 @@ class Registry:
_watch(term, on_output, on_exit)
term.reattached = True
term.stopping = False
- term.transcript.resize(cols, rows)
- manager.resize(term.pty_id, cols, rows)
- replay = term.replay.text()
+ geometry_changed = (term.transcript.cols, term.transcript.rows) != (
+ cols,
+ rows,
+ )
+ if geometry_changed:
+ geometry_changed = manager.resize(term.pty_id, cols, rows)
+ if geometry_changed:
+ term.transcript.resize(cols, rows)
+ needs_repaint = term.replay.truncated
+ if geometry_changed and is_coding_agent(term.agent):
+ # A cursor-addressed TUI stream is meaningful only at the size
+ # that produced it. Replaying the old geometry after a grid
+ # re-layout leaves status rows and command fragments behind
+ # the new paint. Keep the terminal modes, drop those drawing
+ # bytes, and let the live agent rebuild one clean screen below.
+ replay = term.replay.rebase_for_resize()
+ needs_repaint = True
+ else:
+ replay = term.replay.text()
if replay:
- # Hand over the raw stream that drew the current screen. A
- # coding agent's TUI is a painted surface, not a log: without
- # this the pane comes back blank until the agent happens to
- # repaint, which looks exactly like a dead terminal.
+ # Hand over either the stream that drew the current screen, or
+ # (after a geometry change) the terminal-mode prologue that a
+ # clean repaint must draw on. A coding agent's TUI is a painted
+ # surface, not a log: the viewer needs one of those two rebuild
+ # paths rather than an append to whatever it held before.
#
# On the replay channel when the viewer offered one — see the
# docstring for what appending it to a screen that already had
# a copy of it looked like.
await (on_replay or on_output)(replay)
- if term.replay.truncated:
- # The tail is all this pane has, and it no longer starts where
- # the agent started drawing. Replaying it alone brings back the
- # one row the agent rewrote last and empty space where its
- # prompt box should be — see ReplayBuffer's docstring. Ask for
- # a fresh paint instead of hoping one arrives.
+ if needs_repaint:
+ # Either the tail lost its opening frame, or its cursor moves
+ # belong to another geometry. Neither can rebuild this viewer.
+ # Ask for a fresh paint instead of hoping one arrives.
await self._nudge_repaint(term, cols, rows)
logger.debug("Agentic IDE: {} re-joined a running agent", term.name)
return term
@@ -2843,8 +2881,17 @@ class Registry:
return False
# The replayed screen has to follow the real one; otherwise the
# transcript keeps wrapping at the old width.
+ if (term.transcript.cols, term.transcript.rows) == (cols, rows):
+ return True
+ if not self._manager().resize(term.pty_id, cols, rows):
+ return False
+ if is_coding_agent(term.agent):
+ # Future viewers must not replay cursor moves produced for the old
+ # grid into the new one. The live viewer already has its screen;
+ # this only starts a clean replay epoch for the next reconnect.
+ term.replay.rebase_for_resize()
term.transcript.resize(cols, rows)
- return self._manager().resize(term.pty_id, cols, rows)
+ return True
def detach(self, key: str, workspace_id: str | None = None, viewer: Any = None) -> None:
"""Let go of a pane's viewer. The agent behind it keeps running.
@@ -3147,6 +3194,60 @@ class Registry:
)
return moved
+ async def rename_terminal(self, wanted: str, name: str) -> tuple[Session, Terminal]:
+ """Give one pane a new call-sign, without touching what runs in it.
+
+ The pane's own identity as far as its RUNNING agent is concerned is its
+ key, not its call-sign: the pseudo-terminal is filed under the key, and
+ the key is deliberately left alone here. So renaming is exactly what a
+ user expects it to be — the label changes, the agent keeps working, its
+ conversation and scrollback are untouched. The viewer reconnects (it
+ addresses the pane by call-sign) and repaints from the transcript,
+ which is the same path a workspace switch already takes.
+
+ The new call-sign has to be usable as ONE, which is what the checks are
+ about: a name nobody can say is a pane nobody can send work to.
+
+ * It must contain something to compare — ``normalize`` keeps letters
+ and digits only, so a name of pure punctuation would leave the pane
+ addressable by nothing at all.
+ * It must be free within THIS workspace, the scope a call-sign lives
+ in. Two panes answering to one name make every spoken instruction a
+ coin flip over which agent gets the work.
+
+ Searching every open workspace rather than only the front one, because
+ a custom call-sign is exactly what somebody gives a pane so they can
+ address it from anywhere — including to rename it.
+ """
+ cleaned = " ".join(name.split()).strip()
+ if not cleaned:
+ raise SessionError("Give the terminal a name.")
+ if len(cleaned) > MAX_TERMINAL_NAME:
+ raise SessionError(
+ f"Terminal names can be at most {MAX_TERMINAL_NAME} characters."
+ )
+ if not normalize(cleaned):
+ raise SessionError("Give the terminal a name with letters or numbers in it.")
+ async with self._lock:
+ found = self.find_terminal(wanted)
+ if found is None:
+ raise self._unknown_terminal(wanted)
+ session, term = found
+ if term.name == cleaned:
+ return session, term
+ if any(
+ other is not term and normalize(other.name) == normalize(cleaned)
+ for other in session.terminals
+ ):
+ raise SessionError(
+ f"Another terminal in this workspace is already called {cleaned!r}."
+ )
+ previous = term.name
+ term.name = cleaned
+ await self._persist()
+ logger.info("Agentic IDE: renamed terminal {} to {}", previous, cleaned)
+ return session, term
+
async def close_terminal(self, wanted: str) -> Terminal:
"""Stop one terminal's agent and remove its pane from the workspace."""
closed, failed = await self.close_terminals([wanted])
@@ -3338,6 +3439,25 @@ class Registry:
term.last_submit_at = term.last_prompt_at
term.submitted = submitted
term.sent_multiline = multiline and submitted is True
+ history_entry = prompt_history.PromptHistoryEntry(
+ id=uuid4().hex,
+ sequence=term.prompts_sent,
+ text=payload,
+ at=term.last_prompt_at,
+ submitted=submitted,
+ )
+ # Memory first: even a read-only or temporarily unavailable data folder
+ # must not make a prompt disappear from the history while the pane is
+ # still open. Disk is the persistence layer, not the only copy.
+ term.prompt_records.append(history_entry)
+ try:
+ await asyncio.to_thread(prompt_history.append, term.history_id, history_entry)
+ except OSError as exc:
+ logger.warning(
+ "Agentic IDE: could not persist the prompt history for {}: {}",
+ term.name,
+ exc,
+ )
# Somebody is driving this pane again, whatever the prompt said. Cleared
# even when the pane did not submit the text: the instruction is sitting
# in its input box in full, so offering to type "continue" behind it
@@ -3418,25 +3538,6 @@ class Registry:
)
return None
return left_the_box
- history_entry = prompt_history.PromptHistoryEntry(
- id=uuid4().hex,
- sequence=term.prompts_sent,
- text=payload,
- at=term.last_prompt_at,
- submitted=submitted,
- )
- # Memory first: even a read-only or temporarily unavailable data folder
- # must not make a prompt disappear from the history while the pane is
- # still open. Disk is the persistence layer, not the only copy.
- term.prompt_records.append(history_entry)
- try:
- await asyncio.to_thread(prompt_history.append, term.history_id, history_entry)
- except OSError as exc:
- logger.warning(
- "Agentic IDE: could not persist the prompt history for {}: {}",
- term.name,
- exc,
- )
async def _await_arrival(self, term: Terminal, payload: str) -> bool:
"""Wait until the pane visibly holds ``payload``, or give up.
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
index 32da602d7e..c9029b9212 100644
--- a/jarvis/agentic_ide/transcript.py
+++ b/jarvis/agentic_ide/transcript.py
@@ -292,6 +292,29 @@ class ReplayBuffer:
text = text[remnant.end() :]
return self._mode_prologue() + "\x1b[0m" + text
+ def rebase_for_resize(self) -> str:
+ """Forget drawing bytes tied to the old geometry, preserving modes.
+
+ Cursor-addressed TUI output only has meaning at the terminal size that
+ produced it. Replaying that stream into a differently sized viewer
+ leaves old status rows and fragments between the newly painted ones.
+ A resize therefore starts a new replay epoch: the caller sends this
+ returned prologue to a reset viewer, then asks the live TUI to repaint.
+
+ Private modes survive because most coding CLIs negotiate alternate
+ screen and mouse tracking only once, at process startup. Dropping
+ those together with the stale drawing would repair the text while
+ silently breaking the pane's mouse and scrollbar.
+ """
+ prologue = self._mode_prologue() + "\x1b[0m"
+ self._chunks.clear()
+ self._size = 0
+ self.truncated = False
+ self._open_escape = False
+ self._chunks.append(prologue)
+ self._size = len(prologue)
+ return prologue
+
def clear(self) -> None:
"""Forget everything — this buffer is being handed to a fresh process.
diff --git a/jarvis/cli_ctl/commands/ide.py b/jarvis/cli_ctl/commands/ide.py
index 14cb3fc703..8246e0ea1f 100644
--- a/jarvis/cli_ctl/commands/ide.py
+++ b/jarvis/cli_ctl/commands/ide.py
@@ -2,6 +2,7 @@
from __future__ import annotations
from typing import Annotated
+from urllib.parse import quote
import typer
@@ -10,6 +11,22 @@ from jarvis.cli_ctl import invoke, options
app = typer.Typer(no_args_is_help=True, help="Control Agentic IDE terminal panes.")
[email protected]("rename-terminal")
+def rename_terminal(
+ name: Annotated[str, typer.Argument(help="Current terminal call-sign.")],
+ new_name: Annotated[str, typer.Argument(help="New terminal call-sign.")],
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Rename a running terminal pane without restarting its agent."""
+ invoke.run(
+ "PATCH",
+ f"/api/agentic-ide/terminals/{quote(name, safe='')}",
+ body={"name": new_name},
+ dry_run=dry_run,
+ dangerous=False,
+ )
+
+
@app.command("close-terminals")
def close_terminals(
names: Annotated[list[str], typer.Argument(help="Terminal call-signs to close.")],
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index 0bfe41061d..3147e1a8de 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -837,8 +837,9 @@ def _build_registry() -> tuple[AppCommand, ...]:
"Send an instruction to the coding agent in ONE terminal. "
"Terminals are called T plus their place in the grid (T1, T2, "
"T3, left to right). Use this whenever the user tells a "
- "terminal to do something "
- "('tell T1 to ...', 'T2 soll ...', 'let terminal three " # i18n-allow: quoted addressing example
+ "terminal to do something ('tell T1 to ...', "
+ "'T2 soll ...', " # i18n-allow: quoted addressing example
+ "'let terminal three "
"refactor ...', 'prompt the second terminal') "
"— that work belongs to that agent, never to a background "
"worker. For SEVERAL terminals ('T1 and T2 both ...', 'let "
@@ -979,7 +980,9 @@ def _build_registry() -> tuple[AppCommand, ...]:
},
ui_section="agentic-ide",
voice_aliases={
- "de": ("spawne ein terminal und lass es die tests fixen",), # i18n-allow: input vocab
+ "de": (
+ "spawne ein terminal und lass es die tests fixen", # i18n-allow
+ ),
"en": ("open a terminal and have it fix the tests",),
"es": ("abre una terminal y que arregle las pruebas",), # i18n-allow: input vocab
},
@@ -1035,6 +1038,41 @@ def _build_registry() -> tuple[AppCommand, ...]:
"es": ("abre dos terminales de codex",), # i18n-allow: input vocab
},
),
+ AppCommand(
+ id="agentic-ide-rename-terminal",
+ title="Rename an Agentic-IDE terminal",
+ description=(
+ "Give one running terminal another call-sign without restarting "
+ "its agent or losing its conversation. Use it when the user asks "
+ "to rename a pane, for example 'rename T1 to Frontend'. The old "
+ "call-sign must name a terminal that is already open, and the new "
+ "one must be unique inside that workspace."
+ ),
+ method="PATCH",
+ path="/api/agentic-ide/terminals/{terminal}",
+ params={
+ "type": "object",
+ "properties": {
+ "terminal": _str_param(
+ "Current call-sign of the terminal, e.g. 'T1'.",
+ min_length=1,
+ ),
+ "name": _str_param(
+ "New call-sign for the terminal, e.g. 'Frontend'.",
+ min_length=1,
+ max_length=40,
+ ),
+ },
+ "required": ["terminal", "name"],
+ },
+ path_params=("terminal",),
+ ui_section="agentic-ide",
+ voice_aliases={
+ "de": ("benenne t1 in frontend um",), # i18n-allow: input vocab
+ "en": ("rename t1 to frontend",),
+ "es": ("renombra t1 a frontend",), # i18n-allow: input vocab
+ },
+ ),
AppCommand(
id="agentic-ide-move-terminal",
title="Move an Agentic-IDE terminal in the grid",
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index ebc64088fb..c08c87ebeb 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -31,6 +31,8 @@ Endpoints (prefix ``/api/agentic-ide``):
* ``POST /fanout`` → run ONE task across several agents
(open the panes, divide the work, brief each one, report who was reached)
* ``GET /terminals/{name}/report`` → what one named terminal is doing
+* ``PATCH /terminals/{terminal}`` → give that pane another call-sign
+* ``GET /terminals/{name}/prompts`` → every prompt handed to that pane
* ``POST /terminals/{name}/prompt`` → type a prompt into it and press Enter
* ``POST /terminals/{name}/attach`` → drop/paste files onto a pane
* ``WS /pty/{name}`` → the pane's live terminal stream
@@ -65,9 +67,9 @@ from jarvis.agentic_ide import (
interrupted,
native_picker,
notifications,
+ prompt_history,
recap_engine,
recents,
- prompt_history,
resume_store,
)
from jarvis.agentic_ide.agent_sessions import has_conversation
@@ -82,6 +84,7 @@ from jarvis.agentic_ide.names import default_names
from jarvis.agentic_ide.session import (
AGENT_DISPLAY,
MAX_PROMPT_CHARS,
+ MAX_TERMINAL_NAME,
MAX_TERMINALS,
MAX_WORKSPACES,
Session,
@@ -317,6 +320,19 @@ class RenameWorkspaceRequest(BaseModel):
)
+class RenameTerminalRequest(BaseModel):
+ """A new call-sign for one pane."""
+
+ name: str = Field(
+ min_length=1,
+ max_length=MAX_TERMINAL_NAME,
+ description=(
+ "New call-sign for the pane. The agent running in it is not touched — "
+ "only the name it is addressed by changes."
+ ),
+ )
+
+
class WorkspaceCard(BaseModel):
"""One open workspace, as the workspace bar shows it."""
@@ -903,22 +919,6 @@ class LastPrompt(BaseModel):
prompts_sent: int = Field(default=0, description="How many prompts this pane has been sent.")
-class RecapEdit(BaseModel):
- """A recap the user is writing for one pane themselves."""
-
- recap: str = Field(
- description=(
- "The header line. Empty clears a hand-written recap and hands the "
- "pane back to the automatic one."
- ),
- max_length=recap_engine.MAX_EDIT_HEADLINE * 4,
- )
- recap_detail: str = Field(
- default="",
- description="The longer version behind it. Optional; the header line stands alone.",
- max_length=recap_engine.MAX_EDIT_DETAIL * 2,
- )
-
class PromptHistoryItem(BaseModel):
"""One exact prompt in a pane's delivery history."""
@@ -947,6 +947,22 @@ class PromptHistoryResponse(BaseModel):
items: list[PromptHistoryItem] = Field(default_factory=list)
+class RecapEdit(BaseModel):
+ """A recap the user is writing for one pane themselves."""
+
+ recap: str = Field(
+ description=(
+ "The header line. Empty clears a hand-written recap and hands the "
+ "pane back to the automatic one."
+ ),
+ max_length=recap_engine.MAX_EDIT_HEADLINE * 4,
+ )
+ recap_detail: str = Field(
+ default="",
+ description="The longer version behind it. Optional; the header line stands alone.",
+ max_length=recap_engine.MAX_EDIT_DETAIL * 2,
+ )
+
# --------------------------------------------------------------------------- #
# REST #
@@ -1854,6 +1870,39 @@ async def close_terminals_by_agent(request: Request, agent: str) -> dict:
}
[email protected]("/terminals/{terminal}", summary="Rename one terminal")
+async def rename_terminal(terminal: str, req: RenameTerminalRequest) -> dict:
+ """Give the pane ``terminal`` another call-sign.
+
+ Nothing is started, stopped or restarted: the agent in the pane keeps
+ working and keeps its conversation. Only the name it is addressed by
+ changes — on screen, in a spoken instruction, and in every route that takes
+ a ``{name}``.
+
+ ``404`` when no pane answers to ``name``, ``409`` when another pane in the
+ same workspace already carries the new one.
+ """
+ try:
+ session, term = await get_registry().rename_terminal(terminal, req.name)
+ except SessionError as exc:
+ message = str(exc)
+ if "already called" in message:
+ status = 409
+ elif message.startswith("No terminal called"):
+ status = 404
+ else:
+ status = 422
+ raise HTTPException(status_code=status, detail=message) from exc
+ return {
+ "ok": True,
+ "renamed": term.name,
+ "previous": terminal,
+ "terminal": term.to_dict(),
+ "workspace_id": session.id,
+ "state": get_registry().state(),
+ }
+
+
@router.delete(
"/terminals/{name}",
summary="Close one terminal",
@@ -2047,6 +2096,43 @@ async def get_last_prompt(name: str, workspace_id: str | None = None) -> LastPro
)
+ "/terminals/{name}/prompts",
+ response_model=PromptHistoryResponse,
+ summary="Every prompt sent to one terminal",
+)
+async def get_prompt_history(
+ name: str, workspace_id: str | None = None
+) -> PromptHistoryResponse:
+ """Read every exact prompt handed to this pane, newest first.
+
+ Prompt bodies live outside the workspace snapshot and are loaded only for
+ this request. That keeps the IDE's state poll and first-screen restore small
+ even when a workspace has many panes with long coding briefs.
+ """
+ term, _session = _pane_for_recap(name, workspace_id)
+ stored = await asyncio.to_thread(prompt_history.load, term.history_id)
+ entries = prompt_history.merged(stored, term.prompt_records)
+ total = max(term.prompts_sent, len(entries))
+ return PromptHistoryResponse(
+ name=term.name,
+ total=total,
+ available=len(entries),
+ complete=len(entries) >= term.prompts_sent,
+ items=[
+ PromptHistoryItem(
+ id=entry.id,
+ sequence=entry.sequence,
+ text=entry.text,
+ chars=len(entry.text),
+ at=entry.at,
+ submitted=entry.submitted,
+ )
+ for entry in reversed(entries)
+ ],
+ )
+
+
@router.get("/terminals/{name}/report", summary="What one terminal is doing")
async def terminal_report(name: str, lines: int = 40) -> dict:
"""Status plus the recent readable output of the terminal called ``name``."""
@@ -2091,43 +2177,6 @@ async def terminal_attach(
which is what makes dropping a screenshot work against an agent that
cannot open one.
* ``deliver=false`` stores and analyses without typing anything into the
- "/terminals/{name}/prompts",
- response_model=PromptHistoryResponse,
- summary="Every prompt sent to one terminal",
-)
-async def get_prompt_history(
- name: str, workspace_id: str | None = None
-) -> PromptHistoryResponse:
- """Read every exact prompt handed to this pane, newest first.
-
- Prompt bodies live outside the workspace snapshot and are loaded only for
- this request. That keeps the IDE's state poll and first-screen restore small
- even when a workspace has many panes with long coding briefs.
- """
- term, _session = _pane_for_recap(name, workspace_id)
- stored = await asyncio.to_thread(prompt_history.load, term.history_id)
- entries = prompt_history.merged(stored, term.prompt_records)
- total = max(term.prompts_sent, len(entries))
- return PromptHistoryResponse(
- name=term.name,
- total=total,
- available=len(entries),
- complete=len(entries) >= term.prompts_sent,
- items=[
- PromptHistoryItem(
- id=entry.id,
- sequence=entry.sequence,
- text=entry.text,
- chars=len(entry.text),
- at=entry.at,
- submitted=entry.submitted,
- )
- for entry in reversed(entries)
- ],
- )
-
-
pane, for a caller that is assembling a prompt rather than handing the
agent a path right now. The files are on disk and referenced either way,
so nothing is lost if the user then walks away.
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 111990d08e..5709a6ea6f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -39,6 +39,7 @@ vi.mock("@/lib/agenticIdeApi", () => ({
closeTerminals: vi.fn(),
composePrompt: vi.fn(),
moveTerminal: vi.fn(),
+ renameTerminal: 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.
fetchTerminalRecaps: vi.fn(async () => ({
@@ -99,6 +100,7 @@ vi.mock("./AgenticTerminal", () => ({
agents,
onToggleMaximize,
onSplit,
+ onRename,
onClose,
onArrangeStart,
arranging,
@@ -114,6 +116,7 @@ vi.mock("./AgenticTerminal", () => ({
agents?: Array<{ name: string }>;
onToggleMaximize?: () => void;
onSplit?: (direction: "right" | "down", agent?: string) => void;
+ onRename?: (name: string) => Promise<boolean>;
onClose?: () => void;
onArrangeStart?: (event: PointerEventLike) => void;
arranging?: boolean;
@@ -165,6 +168,14 @@ vi.mock("./AgenticTerminal", () => ({
>
down as codex
</button>
+ {/* The real editor lives in the pane header; here it stands for "the user
+ typed a new call-sign and pressed Save". */}
+ <button
+ data-testid={`pane-rename-${name}`}
+ onClick={() => void onRename?.("Frontend")}
+ >
+ rename
+ </button>
<button data-testid={`pane-close-${name}`} onClick={onClose}>
close
</button>
@@ -1973,3 +1984,78 @@ describe("panes that appear from outside the grid", () => {
Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView");
});
});
+
+describe("renaming a pane", () => {
+ /** The workspace as it comes back once "Mika" has become "Frontend". */
+ const RENAMED = (() => {
+ const next = sessionWith([
+ ["Frontend", 0],
+ ["Nova", 1],
+ ]);
+ // The key is what survives a rename — it is what the running terminal is
+ // filed under — so the answer keeps Mika's.
+ next.terminals[0] = { ...next.terminals[0], key: "mika" };
+ return next;
+ })();
+
+ it("asks the backend and redraws from its answer", async () => {
+ vi.mocked(api.renameTerminal).mockResolvedValue(RENAMED);
+ const { onSessionChanged } = renderGrid();
+
+ fireEvent.click(screen.getByTestId("pane-rename-Mika"));
+
+ await waitFor(() =>
+ expect(api.renameTerminal).toHaveBeenCalledWith("Mika", "Frontend"),
+ );
+ expect(onSessionChanged).toHaveBeenCalledWith(RENAMED);
+ });
+
+ it("carries the maximized pane across to its new name", async () => {
+ vi.mocked(api.renameTerminal).mockResolvedValue(RENAMED);
+ const { rerender } = renderGrid();
+
+ fireEvent.click(screen.getByTestId("pane-maximize-Mika"));
+ expect(screen.getByTestId("pane-Mika").getAttribute("data-maximized")).toBe("yes");
+
+ fireEvent.click(screen.getByTestId("pane-rename-Mika"));
+ await waitFor(() => expect(api.renameTerminal).toHaveBeenCalled());
+ rerender({ session: RENAMED });
+
+ // Renaming a pane must not un-maximize it: the state is filed under a name
+ // this grid itself just changed, and losing it would look like the rename
+ // had restarted something.
+ expect(screen.getByTestId("pane-Frontend").getAttribute("data-maximized")).toBe(
+ "yes",
+ );
+ });
+
+ it("keeps the prompt bar pointed at the pane it was pointed at", async () => {
+ vi.mocked(api.renameTerminal).mockResolvedValue(RENAMED);
+ const { rerender } = renderGrid();
+
+ expect(screen.getByPlaceholderText(/instruction for Mika/i)).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId("pane-rename-Mika"));
+ await waitFor(() => expect(api.renameTerminal).toHaveBeenCalled());
+ rerender({ session: RENAMED });
+
+ expect(screen.getByPlaceholderText(/instruction for Frontend/i)).toBeTruthy();
+ });
+
+ it("says what went wrong and leaves the workspace alone", async () => {
+ vi.mocked(api.renameTerminal).mockRejectedValue(
+ new Error("Another terminal in this workspace is already called 'Nova'."),
+ );
+ const { onSessionChanged } = renderGrid();
+
+ fireEvent.click(screen.getByTestId("pane-rename-Mika"));
+
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith(
+ "error",
+ expect.stringContaining("already called"),
+ ),
+ );
+ expect(onSessionChanged).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index aeec89ccd0..bd51f0434b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -90,6 +90,7 @@ import {
clearTerminalRecap,
fetchTerminalRecaps,
refreshTerminalRecap,
+ renameTerminal,
setTerminalRecap,
promptTerminal,
type ComposedPreview,
@@ -99,6 +100,7 @@ import {
type PaneNotification,
type SessionState,
type TerminalRecap,
+ type TerminalState,
} from "@/lib/agenticIdeApi";
interface AgenticGridProps {
@@ -401,6 +403,23 @@ function takesPrompts(term: { accepts_prompts?: boolean }): boolean {
return term.accepts_prompts !== false;
}
+/**
+ * The same map with one pane's entry filed under its new call-sign.
+ *
+ * This grid keys a pane's UI state (its status, its recap, its restart token)
+ * by call-sign, which is the right key right up until a pane is renamed. An
+ * untouched map would leave that state stranded under a name nothing looks up
+ * any more, and the pane would come back blank for no reason a user could see.
+ *
+ * Returns the map unchanged when there is nothing filed under `from`, so a
+ * rename cannot churn state that was never there.
+ */
+function rekey<T>(map: Record<string, T>, from: string, to: string): Record<string, T> {
+ if (!(from in map)) return map;
+ const { [from]: value, ...rest } = map;
+ return { ...rest, [to]: value };
+}
+
function storedAppearance(): TerminalAppearance | null {
return readStored(APPEARANCE_KEY, (raw) =>
raw === "light" || raw === "dark" ? raw : null,
@@ -1050,6 +1069,68 @@ export function AgenticGrid({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jump]);
+ /**
+ * Give one pane another call-sign.
+ *
+ * The backend changes a label and nothing else — the agent keeps running and
+ * keeps its conversation. This side has more to do than redraw, because a
+ * call-sign is the key half this grid files a pane's UI state under: which
+ * pane the prompt bar types into, which one is maximized, which are selected,
+ * what each is doing. Every one of those maps is carried across to the new
+ * name here rather than left to expire, since a pane that loses its focus,
+ * its maximized state and its status line the moment it is renamed reads as a
+ * rename that restarted something.
+ *
+ * `knownPanes` is carried too: it is what tells a genuinely NEW pane apart
+ * from one that was already here, and without this a rename would announce
+ * the pane as freshly opened.
+ *
+ * Answers whether the name was taken, so the editor can stay open on a
+ * refusal (a duplicate call-sign) with the text still in it.
+ */
+ const renamePane = useCallback(
+ async (pane: TerminalState, wanted: string): Promise<boolean> => {
+ const from = pane.name;
+ const cleaned = wanted.trim();
+ if (!cleaned || cleaned === from) return true;
+ setWorking(true);
+ try {
+ const next = await renameTerminal(from, cleaned);
+ // The name the backend really settled on, read back off the pane's key
+ // rather than assumed from the input — the key is what survives a
+ // rename, which is exactly why it is the thing to look the pane up by.
+ const to =
+ next.terminals.find((term) => term.key === pane.key)?.name ?? cleaned;
+ setStatuses((current) => rekey(current, from, to));
+ setRecaps((current) => rekey(current, from, to));
+ setRestartTokens((current) => rekey(current, from, to));
+ setTarget((current) => (current === from ? to : current));
+ setMaximized((current) => (current === from ? to : current));
+ setPendingClose((current) => (current === from ? to : current));
+ setSelectedTerminals((current) => {
+ if (!current.has(from)) return current;
+ const set = new Set(current);
+ set.delete(from);
+ set.add(to);
+ return set;
+ });
+ const known = knownPanes.current;
+ if (known?.has(from)) {
+ known.delete(from);
+ known.add(to);
+ }
+ onSessionChanged?.(next);
+ return true;
+ } catch (error) {
+ pushToast("error", (error as Error).message);
+ return false;
+ } finally {
+ setWorking(false);
+ }
+ },
+ [onSessionChanged, pushToast],
+ );
+
/** Where the bell's "jump to pane" goes — here, or via the view for a tab. */
const jumpToNotification = useCallback(
(entry: PaneNotification) => {
@@ -1609,6 +1690,7 @@ export function AgenticGrid({
promptCount={term.prompts_sent}
appearance={appearance}
fontSize={fontSize}
+ geometryReady={gridWidth > 0 && gridHeight > 0}
focused={target === term.name}
maximized={isMaximized}
layoutBusy={layoutBusy}
@@ -1622,6 +1704,7 @@ export function AgenticGrid({
setMaximized((current) => (current === term.name ? null : term.name))
}
onSplit={(direction, agent) => void split(term.name, direction, agent)}
+ onRename={(next) => renamePane(term, next)}
onClose={() => setPendingClose(term.name)}
onAttachError={(message) => pushToast("error", message)}
// Picked up by its header, put down on another pane. Undefined
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
index 4143763e3b..ad1b2034b6 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
@@ -141,6 +141,32 @@ describe("AgenticTerminal layout", () => {
expect(terminalHarness.open).toHaveBeenCalledWith(host);
expect(terminalHarness.observe).toHaveBeenCalledWith(host);
});
+
+ it("waits for the area-aware grid measurement before opening the PTY", () => {
+ const view = render(
+ <AgenticTerminal
+ name="Dana"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ geometryReady={false}
+ />,
+ );
+
+ expect(terminalHarness.open).not.toHaveBeenCalled();
+
+ view.rerender(
+ <AgenticTerminal
+ name="Dana"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ geometryReady
+ />,
+ );
+
+ expect(terminalHarness.open).toHaveBeenCalled();
+ });
});
describe("pane keyboard", () => {
@@ -645,3 +671,119 @@ describe("pane start-up feedback", () => {
expect(screen.queryByTestId("agentic-pane-starting-T5")).toBeNull();
});
});
+
+describe("renaming a pane", () => {
+ beforeEach(() => {
+ globalThis.ResizeObserver = ResizeObserverHarness;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("offers no rename control when the owner cannot save one", () => {
+ render(
+ <AgenticTerminal
+ name="T1"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ />,
+ );
+
+ // A pencil that opens an editor nothing can save would be worse than the
+ // plain badge it replaces.
+ expect(screen.queryByTestId("pane-rename-T1")).toBeNull();
+ });
+
+ it("saves the typed call-sign", async () => {
+ const onRename = vi.fn(async () => true);
+ render(
+ <AgenticTerminal
+ name="T1"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ onRename={onRename}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("pane-rename-T1"));
+ const input = screen.getByTestId("pane-rename-input-T1") as HTMLInputElement;
+ // It opens on the current name, so a small correction is not a retype.
+ expect(input.value).toBe("T1");
+ fireEvent.change(input, { target: { value: "Frontend" } });
+ fireEvent.click(screen.getByTestId("pane-rename-save-T1"));
+
+ await act(async () => undefined);
+ expect(onRename).toHaveBeenCalledWith("Frontend");
+ expect(screen.queryByTestId("pane-rename-input-T1")).toBeNull();
+ });
+
+ it("keeps the typing when the name was refused", async () => {
+ const onRename = vi.fn(async () => false);
+ render(
+ <AgenticTerminal
+ name="T1"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ onRename={onRename}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("pane-rename-T1"));
+ fireEvent.change(screen.getByTestId("pane-rename-input-T1"), {
+ target: { value: "Api" },
+ });
+ fireEvent.click(screen.getByTestId("pane-rename-save-T1"));
+
+ await act(async () => undefined);
+ // A duplicate call-sign is a name to CHANGE — throwing the typing away
+ // would make the user retype the part that was fine.
+ const input = screen.getByTestId("pane-rename-input-T1") as HTMLInputElement;
+ expect(input.value).toBe("Api");
+ });
+
+ it("closes on Escape without saving", async () => {
+ const onRename = vi.fn(async () => true);
+ render(
+ <AgenticTerminal
+ name="T1"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ onRename={onRename}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("pane-rename-T1"));
+ fireEvent.keyDown(screen.getByTestId("pane-rename-input-T1"), {
+ key: "Escape",
+ });
+
+ await act(async () => undefined);
+ expect(onRename).not.toHaveBeenCalled();
+ expect(screen.queryByTestId("pane-rename-input-T1")).toBeNull();
+ });
+
+ it("does not call the backend when the name was not changed", async () => {
+ const onRename = vi.fn(async () => true);
+ render(
+ <AgenticTerminal
+ name="T1"
+ displayName="Claude Code"
+ appearance="dark"
+ fontSize={13}
+ onRename={onRename}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("pane-rename-T1"));
+ fireEvent.click(screen.getByTestId("pane-rename-save-T1"));
+
+ await act(async () => undefined);
+ expect(onRename).not.toHaveBeenCalled();
+ expect(screen.queryByTestId("pane-rename-input-T1")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index fe28c51f83..b3d58171a1 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -9,8 +9,9 @@
* 2. Appearance and font size are applied to the LIVE instance in their own
* effects. Rebuilding the terminal when the user flips to dark mode would
* tear down the WebSocket, which kills the agent running behind it and
- * loses the whole session. So the connect effect depends on the pane key
- * alone.
+ * loses the whole session. So the connect effect depends on pane identity,
+ * restart intent and one-way initial geometry readiness — never live
+ * appearance state.
*
* ## Why this pane is configured the way it is
*
@@ -49,12 +50,14 @@ import { Unicode11Addon } from "@xterm/addon-unicode11";
import "@xterm/xterm/css/xterm.css";
import {
AlertCircle,
+ Check,
Circle,
Columns2,
Loader2,
Maximize2,
Minimize2,
Paperclip,
+ Pencil,
Rows2,
RotateCcw,
X,
@@ -114,6 +117,13 @@ import { PromptHistoryButton } from "./PromptHistoryButton";
*/
const RECEIPT_MAX_AGE_MS = 30 * 60 * 1000;
+/**
+ * How long a call-sign may be — the same cap the backend enforces
+ * (`MAX_TERMINAL_NAME`), so the field stops where the save would have failed
+ * rather than letting somebody type a name that comes back rejected.
+ */
+const MAX_TERMINAL_NAME = 40;
+
export type PaneStatus = "connecting" | "live" | "exited" | "error";
/**
@@ -205,12 +215,21 @@ interface AgenticTerminalProps {
* Which subscription this pane runs on ("Work seat"), when that is worth
* saying. Undefined for everyone with a single login — the header must not
* grow a badge that answers a question the user does not have.
- */
+ */
accountLabel?: string | null;
/** Number shown beside the pane header's prompt-history icon. */
promptCount?: number;
appearance: TerminalAppearance;
fontSize: number;
+ /**
+ * Has the grid measured the pane's final opening geometry?
+ *
+ * Area-aware layouts cannot know their band count until the container has a
+ * height. Opening the PTY during the width-only first pass attaches it at one
+ * size and immediately moves it to another, while its replay is still being
+ * parsed. Omitted for standalone uses, which already render at a fixed size.
+ */
+ geometryReady?: boolean;
/** Highlight this pane as the prompt target. */
focused?: boolean;
onFocus?: () => void;
@@ -230,6 +249,15 @@ interface AgenticTerminalProps {
* choose, so the split buttons act immediately instead of opening a menu.
*/
agents?: SplitAgentChoice[];
+ /**
+ * Give this pane another call-sign.
+ *
+ * Answers whether the name was accepted, so the editor can stay open with the
+ * text still in it when the workspace already has a pane by that name.
+ * Omitted, the header shows no rename control at all rather than one that
+ * would do nothing.
+ */
+ onRename?: (name: string) => Promise<boolean>;
/** Close this pane (the caller asks for confirmation first). */
onClose?: () => void;
/** Disable the split buttons — the workspace is at its terminal limit. */
@@ -280,10 +308,13 @@ export function AgenticTerminal({
displayName,
recap,
recapDetail,
+ recapMeta,
+ recapActions,
accountLabel,
promptCount = 0,
appearance,
fontSize,
+ geometryReady = true,
focused = false,
onFocus,
onStatus,
@@ -291,6 +322,7 @@ export function AgenticTerminal({
onToggleMaximize,
onSplit,
agents,
+ onRename,
onClose,
splitDisabled = false,
onAttachError,
@@ -359,6 +391,7 @@ export function AgenticTerminal({
layoutBusyRef.current = layoutBusy;
useEffect(() => {
+ if (!geometryReady) return;
const container = containerRef.current;
if (!container) return;
@@ -925,7 +958,7 @@ export function AgenticTerminal({
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
// appearance/fontSize must NOT rebuild the pane (it would kill the agent).
- }, [name, restartToken]);
+ }, [name, restartToken, geometryReady]);
// Live restyle — no reconnect, so the running agent is untouched. The canvas
// renderer caches rendered glyphs per colour in a texture atlas, so a theme
@@ -1114,6 +1147,8 @@ export function AgenticTerminal({
displayName={displayName}
recap={recap}
recapDetail={recapDetail}
+ recapMeta={recapMeta}
+ recapActions={recapActions}
accountLabel={accountLabel}
promptCount={promptCount}
appearance={appearance}
@@ -1122,6 +1157,7 @@ export function AgenticTerminal({
onToggleMaximize={onToggleMaximize}
onSplit={onSplit}
agents={agents}
+ onRename={onRename}
onClose={onClose}
splitDisabled={splitDisabled}
/>
@@ -1134,7 +1170,9 @@ export function AgenticTerminal({
`min-h-0` is equally load-bearing: this is a shrinking flex child, and
xterm's canvas must not become its implicit minimum height.
*/}
- <div className="relative min-h-0 flex-1 overflow-hidden px-1.5 pb-0.5 pt-0.5">
+ <div
+ className="relative min-h-0 flex-1 overflow-hidden px-1.5 pb-0.5 pt-0.5"
+ >
<div
ref={containerRef}
data-testid={`agentic-terminal-host-${name}`}
@@ -1231,6 +1269,7 @@ function PaneHeader({
onToggleMaximize,
onSplit,
agents,
+ onRename,
onClose,
splitDisabled,
dead,
@@ -1253,6 +1292,7 @@ function PaneHeader({
onToggleMaximize?: () => void;
onSplit?: (direction: SplitDirection, agent?: string) => void;
agents?: SplitAgentChoice[];
+ onRename?: (name: string) => Promise<boolean>;
onClose?: () => void;
splitDisabled: boolean;
/** The agent in this pane has exited or failed — offer to start it again. */
@@ -1265,6 +1305,26 @@ function PaneHeader({
const light = appearance === "light";
// Which split button opened the CLI picker, if any.
const [picking, setPicking] = useState<SplitDirection | null>(null);
+ // The call-sign editor: null while the badge is just a badge, otherwise the
+ // text being typed. Empty string is a real state (the field was cleared), so
+ // "is it open" cannot be read off the text — hence null rather than "".
+ const [draft, setDraft] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ const commitRename = async () => {
+ const wanted = (draft ?? "").trim();
+ if (!wanted || wanted === name) {
+ setDraft(null);
+ return;
+ }
+ setSaving(true);
+ // Kept open on a refusal — a duplicate call-sign is a name to CHANGE, and
+ // throwing the typing away would make the user retype the part that was
+ // fine. The grid says what went wrong.
+ const accepted = await onRename?.(wanted);
+ setSaving(false);
+ if (accepted !== false) setDraft(null);
+ };
// With one installed CLI there is nothing to pick, so the button splits
// straight away — a menu with a single entry is a click tax, not a choice.
@@ -1317,24 +1377,115 @@ function PaneHeader({
}}
>
<div className="flex min-w-0 flex-1 items-center gap-2">
- <span
- className={cn(
- "shrink-0 rounded-md px-2 py-0.5 font-display text-[13px] font-semibold tracking-tight",
- focused ? "bg-primary/20 text-primary" : "",
- )}
- style={
- focused
- ? undefined
- : {
- color: light ? "#2b2b33" : "#e8e8ec",
- background: light
- ? "rgba(0,0,0,0.05)"
- : "rgba(255,255,255,0.06)",
- }
- }
- >
- {name}
- </span>
+ {draft !== null ? (
+ /*
+ * The call-sign, being typed.
+ *
+ * A form rather than a bare input so Enter saves the way it does in
+ * every other name field in the app, and Escape closes it — the two
+ * keys somebody renaming a pane will reach for without looking.
+ */
+ <form
+ className="flex shrink-0 items-center gap-1"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void commitRename();
+ }}
+ >
+ <input
+ autoFocus
+ value={draft}
+ maxLength={MAX_TERMINAL_NAME}
+ disabled={saving}
+ aria-label={`Rename ${name}`}
+ data-testid={`pane-rename-input-${name}`}
+ onFocus={(event) => event.currentTarget.select()}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") setDraft(null);
+ // The pane underneath is a live terminal listening for keys.
+ // Without this, typing a name also types into the agent.
+ event.stopPropagation();
+ }}
+ className={cn(
+ "w-32 rounded-md px-2 py-0.5 font-display text-[13px] font-semibold tracking-tight outline-none",
+ "border border-primary/50 focus:border-primary disabled:opacity-60",
+ )}
+ style={{
+ color: light ? "#2b2b33" : "#e8e8ec",
+ background: light ? "rgba(0,0,0,0.04)" : "rgba(255,255,255,0.06)",
+ }}
+ />
+ <button
+ type="submit"
+ disabled={saving || !draft.trim()}
+ aria-label={`Save name for ${name}`}
+ data-testid={`pane-rename-save-${name}`}
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-primary hover:bg-primary/15 disabled:opacity-40"
+ >
+ {saving ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Check className="h-3 w-3" />
+ )}
+ </button>
+ <button
+ type="button"
+ disabled={saving}
+ aria-label={`Cancel renaming ${name}`}
+ onClick={() => setDraft(null)}
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </form>
+ ) : (
+ <>
+ <span
+ // Double-click is the gesture every tab strip and file manager
+ // already uses for "rename this", so it is offered here too — but
+ // it is never the only way in, because nothing on screen advertises
+ // it. The pencil beside it is what makes the feature findable.
+ onDoubleClick={onRename ? () => setDraft(name) : undefined}
+ title={onRename ? `${name} — double-click to rename` : undefined}
+ className={cn(
+ "shrink-0 rounded-md px-2 py-0.5 font-display text-[13px] font-semibold tracking-tight",
+ focused ? "bg-primary/20 text-primary" : "",
+ )}
+ style={
+ focused
+ ? undefined
+ : {
+ color: light ? "#2b2b33" : "#e8e8ec",
+ background: light
+ ? "rgba(0,0,0,0.05)"
+ : "rgba(255,255,255,0.06)",
+ }
+ }
+ >
+ {name}
+ </span>
+ {onRename && (
+ <button
+ type="button"
+ aria-label={`Rename ${name}`}
+ title={`Rename ${name}`}
+ data-testid={`pane-rename-${name}`}
+ onClick={() => setDraft(name)}
+ onMouseDown={(event) => event.stopPropagation()}
+ className={cn(
+ "flex h-5 w-5 shrink-0 items-center justify-center rounded transition-opacity",
+ "opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100",
+ light
+ ? "text-[#6b6b73] hover:bg-black/10"
+ : "text-[#9a9aa5] hover:bg-white/10",
+ )}
+ >
+ <Pencil className="h-3 w-3" />
+ </button>
+ )}
+ </>
+ )}
<PaneRecap
name={name}
displayName={displayName}
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index a69c0a85b6..3eaa30bf51 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -842,6 +842,32 @@ export async function moveTerminal(
return body.state.session;
}
+/**
+ * Give one pane another call-sign.
+ *
+ * Nothing is started or stopped — the agent keeps working and keeps its
+ * conversation. The pane simply answers to a different name afterwards, in the
+ * header, in a spoken instruction, and in every route that takes a name.
+ */
+export async function renameTerminal(
+ name: string,
+ newName: string,
+): Promise<SessionState> {
+ const res = await fetch(
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: newName }),
+ },
+ );
+ if (!res.ok) throw new Error(await detail(res));
+ const body = (await res.json()) as { state: IdeState };
+ if (!body.state.session)
+ throw new Error("The workspace closed while renaming a terminal.");
+ return body.state.session;
+}
+
/** Stop one terminal's agent and remove its pane. Returns the updated workspace. */
export async function closeTerminal(name: string): Promise<SessionState> {
const res = await fetch(
diff --git a/tests/unit/agentic_ide/test_pane_rename.py b/tests/unit/agentic_ide/test_pane_rename.py
new file mode 100644
index 0000000000..7ae248b4f4
--- /dev/null
+++ b/tests/unit/agentic_ide/test_pane_rename.py
@@ -0,0 +1,190 @@
+"""Giving a running pane another call-sign.
+
+A rename touches one string and must touch nothing else — that is the entire
+contract, and every test here is a way of failing it. The pane's key is what
+its running pseudo-terminal is filed under, so a rename that moved the key
+would take the agent away from the viewer; the call-sign is what a spoken
+instruction resolves against, so a rename that left the OLD name answering
+would silently split one pane into two addresses.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import resume_store
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import MAX_TERMINAL_NAME, Registry, SessionError
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
[email protected](autouse=True)
+def _isolated_recents(
+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Keep the recents file out of the developer's real data directory."""
+ from jarvis.agentic_ide import recents
+
+ store = tmp_path_factory.mktemp("recents") / "recents.json"
+ monkeypatch.setattr(recents, "_store_path", lambda: store)
+
+
+def fake_pty() -> FakePtyManager:
+ return FakePtyManager()
+
+
+def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ return Registry(pty_manager=fake_pty)
+
+
+async def _open(registry: Registry, folder: Path, count: int = 2):
+ return await registry.start(str(folder), [{"agent": "claude"} for _ in range(count)])
+
+
+# ------------------------------------------------------------------ the rename
+async def test_renaming_changes_the_call_sign_and_nothing_else(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The label moves; the pane's identity, place and agent stay put."""
+ await _open(registry, tmp_path, 2)
+ before = registry.session.terminals[0]
+ key, column, slot, agent = before.key, before.column, before.slot, before.agent
+
+ _, term = await registry.rename_terminal("T1", "Frontend")
+
+ assert term.name == "Frontend"
+ assert (term.key, term.column, term.slot, term.agent) == (key, column, slot, agent)
+ assert [t.name for t in registry.session.terminals] == ["Frontend", "T2"]
+
+
+async def test_the_pane_answers_to_its_new_name(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A rename is only real if the next instruction reaches the pane by it."""
+ await _open(registry, tmp_path, 2)
+ await registry.rename_terminal("T1", "Frontend")
+
+ found = registry.find_terminal("Frontend")
+ assert found is not None
+ assert found[1].key == registry.session.terminals[0].key
+
+
+async def test_a_freed_call_sign_goes_to_the_next_pane_that_asks_for_it(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """T1 renamed frees T1 — and the pane that takes it is the one T1 means.
+
+ The renamed pane keeps the key ``t1`` (its pseudo-terminal is filed under
+ it), so this is precisely where a key-first lookup would hand "T1" back to
+ the pane the user renamed to stop it being T1.
+ """
+ await _open(registry, tmp_path, 1)
+ await registry.rename_terminal("T1", "Frontend")
+ fresh = await registry.add_terminal(direction="right")
+
+ assert fresh.name == "T1"
+ found = registry.find_terminal("T1")
+ assert found is not None
+ assert found[1].key == fresh.key
+
+
+async def test_renaming_never_touches_the_running_agent(
+ registry: Registry, tmp_path: Path, fake_pty: FakePtyManager
+) -> None:
+ """No pane is closed, no process is spawned — that is what makes it safe."""
+ await _open(registry, tmp_path, 2)
+ spawns = len(fake_pty.spawns)
+ closed = len(fake_pty.closed)
+
+ await registry.rename_terminal("T2", "Tests")
+
+ assert len(fake_pty.spawns) == spawns
+ assert len(fake_pty.closed) == closed
+
+
+async def test_renaming_to_the_same_name_is_a_no_op(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Opening the editor and pressing Save unchanged is not an error."""
+ await _open(registry, tmp_path, 1)
+ _, term = await registry.rename_terminal("T1", "T1")
+ assert term.name == "T1"
+
+
+async def test_surrounding_whitespace_is_cleaned_up(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A pasted name arrives with spaces; the pane must not be called ' Api '."""
+ await _open(registry, tmp_path, 1)
+ _, term = await registry.rename_terminal("T1", " Api layer ")
+ assert term.name == "Api layer"
+
+
+# ------------------------------------------------------------------- refusals
+async def test_a_name_another_pane_already_carries_is_refused(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Two panes on one call-sign make every spoken instruction a coin flip."""
+ await _open(registry, tmp_path, 2)
+ await registry.rename_terminal("T1", "Frontend")
+
+ with pytest.raises(SessionError, match="already called"):
+ await registry.rename_terminal("T2", "frontend")
+
+ assert [t.name for t in registry.session.terminals] == ["Frontend", "T2"]
+
+
+async def test_an_empty_name_is_refused(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 1)
+ with pytest.raises(SessionError, match="Give the terminal a name"):
+ await registry.rename_terminal("T1", " ")
+
+
+async def test_a_name_with_nothing_to_match_on_is_refused(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Punctuation normalizes to nothing, leaving a pane nobody can address."""
+ await _open(registry, tmp_path, 1)
+ with pytest.raises(SessionError, match="letters or numbers"):
+ await registry.rename_terminal("T1", "!!! ---")
+ assert registry.session.terminals[0].name == "T1"
+
+
+async def test_an_overlong_name_is_refused(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 1)
+ with pytest.raises(SessionError, match="at most"):
+ await registry.rename_terminal("T1", "x" * (MAX_TERMINAL_NAME + 1))
+
+
+async def test_an_unknown_pane_says_which_ones_exist(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The error names the running panes — the answer to the question asked."""
+ await _open(registry, tmp_path, 2)
+ with pytest.raises(SessionError, match="T1, T2"):
+ await registry.rename_terminal("T7", "Frontend")
+
+
+# ---------------------------------------------------------------- persistence
+async def test_the_new_name_survives_a_reopen(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A pane called "Frontend" today is still Frontend after a restart.
+
+ Through the restore snapshot rather than an in-memory copy: the name is
+ written where the workspace is remembered, or a rename lasts exactly until
+ the app is closed.
+ """
+ await _open(registry, tmp_path, 2)
+ await registry.rename_terminal("T1", "Frontend")
+
+ stored = resume_store.load()
+ assert stored is not None
+ fresh = Registry(pty_manager=FakePtyManager())
+ result = await fresh.restore(stored)
+
+ assert [t.name for s in result.sessions for t in s.terminals] == ["Frontend", "T2"]
diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.py
index 8050649266..a6ebc8ac87 100644
--- a/tests/unit/agentic_ide/test_session.py
+++ b/tests/unit/agentic_ide/test_session.py
@@ -281,12 +281,14 @@ async def test_coming_back_rejoins_the_running_agent_and_replays_its_screen(
async def _capture(text: str) -> None:
seen.append(text)
- back = await registry.attach(term.name, 100, 30, _capture, _noop_exit)
+ fake_pty.resizes.clear()
+ back = await registry.attach(term.name, 80, 24, _capture, _noop_exit)
assert back.pty_id == original_pty, "the same agent process must be re-joined"
assert len(fake_pty.spawns) == spawns_before, "nothing may be respawned"
assert back.reattached is True
assert "building…" in "".join(seen), "the screen must come back with the pane"
+ assert fake_pty.resizes == [], "re-joining at the current size must not redraw it"
async def test_a_pane_whose_replay_lost_its_start_asks_the_agent_to_repaint(
@@ -319,27 +321,37 @@ async def test_a_pane_whose_replay_lost_its_start_asks_the_agent_to_repaint(
assert sizes[-1] == (100, 30), "the pane must be left at the size it really is"
-async def test_an_intact_replay_leaves_the_agent_alone(
+async def test_a_geometry_change_rebases_an_intact_replay_and_repaints(
registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
) -> None:
- """No nudge when the tail is whole — it already rebuilds the screen.
-
- The redraw is cheap but not free, and it is the common case that must stay
- untouched: a pane that printed less than its replay budget comes back from
- its own bytes.
- """
+ """Cursor moves recorded at one size must never be replayed at another."""
session = await _open(registry, tmp_path, [{"agent": "claude"}])
term = session.terminals[0]
await registry.attach(term.name, 80, 24, _noop_output, _noop_exit)
pty = term.pty_id
- await fake_pty.emit(pty, "\x1b[32mbuilding…\x1b[0m")
+ await fake_pty.emit(pty, "\x1b[?1049h\x1b[32mOLD STATUS ROW\x1b[0m")
registry.detach(term.key, session.id)
+ replayed: list[str] = []
+
+ async def _capture_replay(text: str) -> None:
+ replayed.append(text)
+
fake_pty.resizes.clear()
- await registry.attach(term.name, 100, 30, _noop_output, _noop_exit)
+ await registry.attach(
+ term.name,
+ 100,
+ 30,
+ _noop_output,
+ _noop_exit,
+ on_replay=_capture_replay,
+ )
sizes = [(cols, rows) for tid, cols, rows in fake_pty.resizes if tid == pty]
- assert sizes == [(100, 30)], "an intact replay must not cost a repaint"
+ restored = "".join(replayed)
+ assert "OLD STATUS ROW" not in restored
+ assert "\x1b[?1049h" in restored, "alternate-screen ownership must survive"
+ assert sizes == [(100, 30), (100, 29), (100, 30)]
async def test_closing_a_workspace_stops_only_its_own_agents(
@@ -536,8 +548,8 @@ async def test_a_displaced_viewer_cannot_resize_the_pane_it_lost(
assert fake_pty.resizes == [], "a displaced viewer must not move the agent's screen"
# The viewer that actually holds the pane still can.
- assert registry.resize(term.key, 200, 50, viewer=second_viewer) is True
- assert fake_pty.resizes == [(term.pty_id, 200, 50)]
+ assert registry.resize(term.key, 201, 50, viewer=second_viewer) is True
+ assert fake_pty.resizes == [(term.pty_id, 201, 50)]
async def test_an_internal_resize_needs_no_viewer(
@@ -554,3 +566,16 @@ async def test_an_internal_resize_needs_no_viewer(
assert registry.resize(term.key, 120, 40) is True
assert fake_pty.resizes == [(term.pty_id, 120, 40)]
+
+
+async def test_a_duplicate_resize_does_not_make_the_tui_repaint(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The socket handshake already applied this size; its echo is a no-op."""
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("T1", 80, 24, _noop_output, _noop_exit)
+ term = registry.session.terminals[0]
+ fake_pty.resizes.clear()
+
+ assert registry.resize(term.key, 80, 24) is True
+ assert fake_pty.resizes == []
diff --git a/tests/unit/agentic_ide/test_transcript.py b/tests/unit/agentic_ide/test_transcript.py
index 70fdf2e1af..d64790fdcf 100644
--- a/tests/unit/agentic_ide/test_transcript.py
+++ b/tests/unit/agentic_ide/test_transcript.py
@@ -288,6 +288,24 @@ def test_an_untruncated_replay_is_still_verbatim() -> None:
assert buffer.text() == stream
+def test_rebasing_for_a_resize_drops_old_drawing_but_preserves_modes() -> None:
+ """A TUI stream is geometry-bound; its negotiated terminal state is not."""
+ buffer = ReplayBuffer()
+ buffer.feed("\x1b[?1049h\x1b[?1006hOLD STATUS ROW")
+
+ prologue = buffer.rebase_for_resize()
+
+ assert "OLD STATUS ROW" not in prologue
+ assert "OLD STATUS ROW" not in buffer.text()
+ assert "\x1b[?1049h" in prologue
+ assert "\x1b[?1006h" in prologue
+ assert prologue.endswith("\x1b[0m")
+ assert buffer.truncated is False
+
+ buffer.feed("NEW SCREEN")
+ assert buffer.text() == prologue + "NEW SCREEN"
+
+
def test_a_replay_forgets_the_modes_when_it_is_cleared() -> None:
buffer = ReplayBuffer(limit=32)
buffer.feed("\x1b[?1049h" + "z" * 100)
diff --git a/tests/unit/cli_ctl/test_commands_ide.py b/tests/unit/cli_ctl/test_commands_ide.py
index aecebffbf3..bcd8c3f2dd 100644
--- a/tests/unit/cli_ctl/test_commands_ide.py
+++ b/tests/unit/cli_ctl/test_commands_ide.py
@@ -8,6 +8,18 @@ from jarvis.cli_ctl.__main__ import app
runner = CliRunner()
+def test_rename_terminal_sends_the_new_call_sign(capture_api) -> None:
+ result = runner.invoke(app, ["ide", "rename-terminal", "API pane", "Frontend"])
+
+ assert result.exit_code == 0
+ call = capture_api["calls"][-1]
+ assert call["method"] == "PATCH"
+ # The capture fixture exposes the decoded URL path; the client still
+ # percent-encodes the space on the wire.
+ assert call["path"] == "/api/agentic-ide/terminals/API pane"
+ assert call["body"] == {"name": "Frontend"}
+
+
def test_close_terminals_requires_confirmation(capture_api) -> None:
result = runner.invoke(app, ["ide", "close-terminals", "Mika", "Nova"])
diff --git a/tests/unit/web/test_agentic_ide_rename_terminal_route.py b/tests/unit/web/test_agentic_ide_rename_terminal_route.py
new file mode 100644
index 0000000000..4d9d4bb0dd
--- /dev/null
+++ b/tests/unit/web/test_agentic_ide_rename_terminal_route.py
@@ -0,0 +1,103 @@
+"""The endpoint behind renaming a pane.
+
+The route itself is thin — the rules live in the registry — so what is pinned
+here is the part a caller depends on: the answer says which pane was renamed
+and what it used to be called, and the two ways it can fail are told apart by
+status code. A duplicate call-sign is something the caller fixes by typing a
+different name (409); a call-sign nobody answers to is a different mistake
+entirely (404), and a UI that cannot distinguish them can only say "it didn't
+work".
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from jarvis.agentic_ide.session import SessionError
+from jarvis.ui.web import agentic_ide_routes as routes
+
+
+def _terminal(name: str) -> SimpleNamespace:
+ return SimpleNamespace(name=name, to_dict=lambda: {"name": name, "key": "t1"})
+
+
+class FakeRegistry:
+ """Registry stand-in: records the call, returns or raises what was scripted."""
+
+ def __init__(self, *, result=None, error: SessionError | None = None) -> None:
+ self._result = result
+ self._error = error
+ self.calls: list[tuple[str, str]] = []
+
+ async def rename_terminal(self, wanted: str, name: str):
+ self.calls.append((wanted, name))
+ if self._error is not None:
+ raise self._error
+ return self._result
+
+ def state(self) -> dict:
+ return {"active": True}
+
+
+async def test_a_rename_answers_with_both_names(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Both, because the caller has UI filed under the OLD one to move across."""
+ session = SimpleNamespace(id="ide_test")
+ registry = FakeRegistry(result=(session, _terminal("Frontend")))
+ monkeypatch.setattr(routes, "get_registry", lambda: registry)
+
+ result = await routes.rename_terminal(
+ "T1", routes.RenameTerminalRequest(name="Frontend")
+ )
+
+ assert registry.calls == [("T1", "Frontend")]
+ assert result["ok"] is True
+ assert result["renamed"] == "Frontend"
+ assert result["previous"] == "T1"
+ assert result["workspace_id"] == "ide_test"
+ assert result["terminal"]["name"] == "Frontend"
+ # The whole state travels back, so the grid redraws from this one answer
+ # instead of polling for the change it just made.
+ assert result["state"] == {"active": True}
+
+
+async def test_a_name_another_pane_carries_is_a_conflict(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ registry = FakeRegistry(
+ error=SessionError("Another terminal in this workspace is already called 'Api'.")
+ )
+ monkeypatch.setattr(routes, "get_registry", lambda: registry)
+
+ with pytest.raises(HTTPException) as caught:
+ await routes.rename_terminal("T2", routes.RenameTerminalRequest(name="Api"))
+
+ assert caught.value.status_code == 409
+ assert "already called" in caught.value.detail
+
+
+async def test_an_unknown_pane_is_a_not_found(monkeypatch: pytest.MonkeyPatch) -> None:
+ registry = FakeRegistry(error=SessionError("No terminal called 'T7'. Running: T1."))
+ monkeypatch.setattr(routes, "get_registry", lambda: registry)
+
+ with pytest.raises(HTTPException) as caught:
+ await routes.rename_terminal("T7", routes.RenameTerminalRequest(name="Api"))
+
+ assert caught.value.status_code == 404
+ # The panes that DO exist travel with it — the answer to the question asked.
+ assert "Running: T1" in caught.value.detail
+
+
+async def test_an_invalid_call_sign_is_unprocessable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ registry = FakeRegistry(
+ error=SessionError("Give the terminal a name with letters or numbers in it.")
+ )
+ monkeypatch.setattr(routes, "get_registry", lambda: registry)
+
+ with pytest.raises(HTTPException) as caught:
+ await routes.rename_terminal("T1", routes.RenameTerminalRequest(name="---"))
+
+ assert caught.value.status_code == 422