Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): let a terminal be renamed the way a workspace tab is
Ruben Lütke9158e4678044
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex d6a695f143..94ffa80b60 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 = Noneprompts_sent: int = 0last_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 Nonekey = 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 termmatched = 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@@ -3147,6 +3165,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 +3410,25 @@ class Registry:term.last_submit_at = term.last_prompt_atterm.submitted = submittedterm.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 +3509,6 @@ class Registry:)return Nonereturn 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/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex ebc64088fb..e279368d04 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -31,6 +31,7 @@ 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/{name}`` → give that pane another call-sign* ``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 +66,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 +83,7 @@ from jarvis.agentic_ide.names import default_namesfrom jarvis.agentic_ide.session import (AGENT_DISPLAY,MAX_PROMPT_CHARS,+ MAX_TERMINAL_NAME,MAX_TERMINALS,MAX_WORKSPACES,Session,@@ -317,6 +319,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 +918,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 +946,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 +1869,34 @@ async def close_terminals_by_agent(request: Request, agent: str) -> dict:}[email protected]("/terminals/{name}", summary="Rename one terminal")+async def rename_terminal(name: str, req: RenameTerminalRequest) -> dict:+ """Give the pane ``name`` 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(name, req.name)+ except SessionError as exc:+ message = str(exc)+ status = 409 if "already called" in message else 404+ raise HTTPException(status_code=status, detail=message) from exc+ return {+ "ok": True,+ "renamed": term.name,+ "previous": name,+ "terminal": term.to_dict(),+ "workspace_id": session.id,+ "state": get_registry().state(),+ }++@router.delete("/terminals/{name}",summary="Close one terminal",@@ -2047,6 +2090,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 +2171,6 @@ async def terminal_attach(which is what makes dropping a screenshot work against an agent thatcannot 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 theagent 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.tsxindex 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.tsxindex aeec89ccd0..f626a757d5 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) => {@@ -1622,6 +1703,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. Undefineddiff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsxindex 4143763e3b..6793dc2897 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx@@ -645,3 +645,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.tsxindex ebfd071fac..789aa6d4c6 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -49,12 +49,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 +116,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,7 +214,7 @@ 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;@@ -230,6 +239,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,6 +298,8 @@ export function AgenticTerminal({displayName,recap,recapDetail,+ recapMeta,+ recapActions,accountLabel,promptCount = 0,appearance,@@ -291,6 +311,7 @@ export function AgenticTerminal({onToggleMaximize,onSplit,agents,+ onRename,onClose,splitDisabled = false,onAttachError,@@ -1122,6 +1143,8 @@ export function AgenticTerminal({displayName={displayName}recap={recap}recapDetail={recapDetail}+ recapMeta={recapMeta}+ recapActions={recapActions}accountLabel={accountLabel}promptCount={promptCount}appearance={appearance}@@ -1130,6 +1153,7 @@ export function AgenticTerminal({onToggleMaximize={onToggleMaximize}onSplit={onSplit}agents={agents}+ onRename={onRename}onClose={onClose}splitDisabled={splitDisabled}/>@@ -1253,6 +1277,7 @@ function PaneHeader({onToggleMaximize,onSplit,agents,+ onRename,onClose,splitDisabled,dead,@@ -1275,6 +1300,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. */@@ -1287,6 +1313,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.@@ -1339,24 +1385,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>+ )}+ </>+ )}<PaneRecapname={name}displayName={displayName}diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 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.pynew file mode 100644index 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/web/test_agentic_ide_rename_terminal_route.py b/tests/unit/web/test_agentic_ide_rename_terminal_route.pynew file mode 100644index 0000000000..edcc4b68e4--- /dev/null+++ b/tests/unit/web/test_agentic_ide_rename_terminal_route.py@@ -0,0 +1,89 @@+"""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