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(ide): move a terminal into another workspace without restarting it
rubenluetke10-beepa3dae6b895de
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.mdindex 17f83512be..30787c607e 100644--- a/docs/jarvis-cli-reference.md+++ b/docs/jarvis-cli-reference.md@@ -110,6 +110,7 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`- `jarvis ide archive-terminal <name> --restore --workspace --dry-run` — Hide a coding session from the chat list, or restore it.- `jarvis ide close-terminals <names> --yes --dry-run` — Stop several coding agents and close their terminal panes.+- `jarvis ide move-terminal <name> <target_workspace> --workspace --dry-run` — Move a terminal pane into another open workspace.- `jarvis ide rename-terminal <name> <new_name> --dry-run` — Rename a running terminal pane without restarting its agent.## local-modelsdiff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 5aaa1d8b35..59c15d41ce 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -3659,6 +3659,12 @@ class Registry:term = session.find(key)return None if term is None else (session, term)+ def _owner_of(self, term: Terminal) -> Session | None:+ """The open workspace that holds ``term`` right now, if any."""+ return next(+ (s for s in self._sessions.values() if any(t is term for t in s.terminals)), None+ )+@asynccontextmanagerasync def _cold_start_slot(self, ready: Callable[[], Awaitable[bool]] | None = None@@ -4219,14 +4225,19 @@ class Registry:)term.resume = Noneterm.resumed = False+ # By identity and in the workspace that holds it NOW: the pane+ # may have been moved to another tab since it started+ # (`transfer_terminal`), and its old key there may already+ # belong to a different pane.+ owner = self._owner_of(term) or sessiontry:await self.attach(- key,+ "pane:" + term.history_id,cols,rows,term.viewer_output or on_output,term.viewer_exit or on_exit,- workspace_id=session.id,+ workspace_id=owner.id,)except SessionError as exc:logger.warning("Agentic IDE: {} could not be restarted: {}", term.name, exc)@@ -6079,6 +6090,130 @@ class Registry:)return moved+ async def transfer_terminal(+ self, wanted: str, *, workspace_id: str | None, target_workspace_id: str+ ) -> tuple[Session, Session, Terminal]:+ """Move pane ``wanted`` out of its workspace into another OPEN one.++ For the chat that was started in the wrong tab. The agent is neither+ stopped nor restarted: its process, scrollback, conversation and+ prompt history all belong to the pane (``history_id``), not to the+ workspace, so moving it is the same re-parenting a workspace switch+ already relies on — the new workspace's grid attaches a viewer and+ re-joins the running agent.++ What does change is only what is scoped to ONE workspace:++ * the call-sign and key, which are unique per tab — a "T2" moving into+ a tab that already has a T2 takes the lowest free number there, a+ custom name keeps itself unless it is taken (``_unique_name``);+ * the folder. The agent keeps working where it was started; a pane+ moved into a workspace on ANOTHER folder records that folder as its+ own (the field a worktree fork uses), so a later restart resumes the+ same conversation in the same place instead of an empty chat in the+ new folder. Moved back home, the field empties again.++ Returns ``(source, target, terminal)``. Moving a pane into the tab it is+ already in is a no-op, not an error — a drop the user took back.+ """+ async with self._lock:+ source = self.get(workspace_id)+ if source is None:+ raise SessionError(+ "That workspace is not open."+ if workspace_id is not None+ else "No Agentic-IDE session is running."+ )+ term = source.find(wanted)+ if term is None:+ known = ", ".join(t.name for t in source.terminals) or "none"+ raise SessionError(f"No terminal called {wanted!r}. Running: {known}.")+ target = self._sessions.get(target_workspace_id)+ if target is None:+ raise SessionError(+ "That workspace is not open. Open it first, then move the terminal there."+ )+ if target.id == source.id:+ return source, target, term+ if len(target.terminals) >= MAX_TERMINALS:+ raise SessionError(+ f"{target.name} already has the maximum of {MAX_TERMINALS} terminals."+ )+ if term.placing:+ raise SessionError(+ f"{term.name} is still being set up on its computer. "+ "Move it once it has started there."+ )++ old_key, old_name = term.key, term.name+ cwd = term.cwd(source.folder)+ term.folder = "" if _same_folder(cwd, target.folder) else cwd++ # Out of the old workspace the way a close takes a pane out, minus+ # the kill: its rectangle folds away and its bell entries go (they+ # are "jump to this pane" buttons keyed by the old tab and key).+ source.terminals.remove(term)+ source.layout = layout_tree.remove_pane(source.layout, old_key)+ self._renumber(source)+ names = {normalize(old_name), normalize(old_key)}++ def _left(pointer: str) -> bool:+ """Does a remembered selection of the old tab name the moved pane?"""+ return bool(pointer) and (+ pointer == f"pane:{term.history_id}" or normalize(pointer) in names+ )++ if _left(source.surface_terminal):+ source.surface_terminal = ""+ if _left(source.surface_prompt_target):+ source.surface_prompt_target = ""+ if _left(source.focused):+ source.focused = ""+ opening.forget(old_key)+ try:+ from . import notifications++ notifications.center().forget_pane(source.id, old_key)+ except Exception as exc: # noqa: BLE001 - never fail a move on bookkeeping+ logger.warning(+ "Agentic IDE: could not clear notifications for a moved pane: {}", exc+ )+ # The screens watching it belong to the old tab's grid, which drops+ # the pane on its next read. The new tab's grid attaches its own+ # viewer and takes the "re-join a running agent" path in `attach`.+ term.viewer_output = None+ term.viewer_exit = None+ term.watchers.clear()+ term.prompt_viewers.clear()++ # Into the new one with a call-sign and key that are free there.+ term.name = _unique_name(old_name, {normalize(t.name) for t in target.terminals})+ keys = {t.key for t in target.terminals}+ key = old_key if old_key not in keys else (normalize(term.name) or "t")+ stem, suffix = key, 2+ while key in keys:+ key = f"{stem}{suffix}"+ suffix += 1+ term.key = key+ target.terminals.append(term)+ # It joins the workspace edge like an anchor-less add: no pane was+ # chosen to sit beside, and every pane then gets an even share.+ target.layout = layout_tree.append_pane(target.layout, term.key)+ columns, rows = layout_tree.grid_span(target.layout)+ if columns > MAX_GRID_COLUMNS or rows > MAX_GRID_ROWS:+ self._row_major_grid(target)+ target.layout = layout_tree.evened(target.layout)+ self._renumber(target)+ await self._persist()+ logger.info(+ "Agentic IDE: moved terminal {} from workspace {} to {} as {}",+ old_name,+ source.name,+ target.name,+ term.name,+ )+ return source, target, term+async def refold(self, depth: int) -> Session:"""Re-deal every pane into columns ``depth`` deep, in reading order.@@ -6974,6 +7109,18 @@ def _prevailing_agent(session: Session) -> str:return "claude"+def _same_folder(left: str, right: str) -> bool:+ """Do two folder strings the registry already holds name one place?++ Compared as text, without touching the disk: both sides were resolved when+ their workspace or pane was opened, so only spelling (separators, and case+ on the platforms whose filesystem ignores it) can still differ.+ """+ if not left or not right:+ return False+ return os.path.normcase(os.path.normpath(left)) == os.path.normcase(os.path.normpath(right))++def _unique_name(wanted: str, used: set[str]) -> str:"""``wanted`` if it is free, otherwise the nearest name that is.diff --git a/jarvis/cli_ctl/command_index.py b/jarvis/cli_ctl/command_index.pyindex ae366323f3..a8ddd007fb 100644--- a/jarvis/cli_ctl/command_index.py+++ b/jarvis/cli_ctl/command_index.py@@ -124,7 +124,7 @@ COMMAND_INDEX: dict[str, tuple[str, ...]] = {'message <name> "<text>"',),"frontier": ("pending", "ack"),- "ide": ("rename-terminal", "close-terminals", "archive-terminal"),+ "ide": ("rename-terminal", "close-terminals", "archive-terminal", "move-terminal"),"local-models": ("assistant setup","assistant diagnose",diff --git a/jarvis/cli_ctl/commands/ide.py b/jarvis/cli_ctl/commands/ide.pyindex f428fbd2dd..85108fbc28 100644--- a/jarvis/cli_ctl/commands/ide.py+++ b/jarvis/cli_ctl/commands/ide.py@@ -56,6 +56,35 @@ def archive_terminal()[email protected]("move-terminal")+def move_terminal(+ name: Annotated[str, typer.Argument(help="Terminal call-sign.")],+ target_workspace: Annotated[+ str, typer.Argument(help="Id of the open workspace to move the terminal into.")+ ],+ workspace: Annotated[+ str | None,+ typer.Option("--workspace", help="Workspace id the terminal is in now."),+ ] = None,+ dry_run: bool = options.dry_opt(),+) -> None:+ """Move a terminal pane into another open workspace.++ Its agent keeps running. The pane may get another call-sign when the+ target workspace already has one by that name; the answer says which.+ """+ body: dict[str, object] = {"target_workspace_id": target_workspace}+ if workspace:+ body["workspace_id"] = workspace+ invoke.run(+ "POST",+ f"/api/agentic-ide/terminals/{quote(name, safe='')}/transfer",+ body=body,+ 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/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 83575f49c8..ea1f3af74d 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -398,6 +398,19 @@ class MoveTerminalRequest(BaseModel):)+class TransferTerminalRequest(BaseModel):+ """Which open workspace a pane should belong to from now on."""++ workspace_id: str | None = Field(+ default=None,+ description="Workspace the pane is in now; defaults to the workspace on screen.",+ )+ target_workspace_id: str = Field(+ min_length=1,+ description="Open workspace to move the pane into.",+ )++class RefoldRequest(BaseModel):"""How deep the workspace's columns should be from now on."""@@ -2915,6 +2928,42 @@ async def move_terminal(name: str, req: MoveTerminalRequest) -> dict:}+ "/terminals/{name}/transfer",+ summary="Move a terminal into another open workspace",+)+async def transfer_terminal(request: Request, name: str, req: TransferTerminalRequest) -> dict:+ """Move pane ``name`` out of its workspace into ``target_workspace_id``.++ The agent keeps running — same process, same conversation, same folder —+ and only changes which tab it is listed and drawn in. Its call-sign may+ change when the target tab already has a pane by that name; the answer+ says which name it carries now. Moving a pane into the tab it is already+ in succeeds and changes nothing.+ """+ registry = get_registry()+ try:+ source, target, term = await registry.transfer_terminal(+ name, workspace_id=req.workspace_id, target_workspace_id=req.target_workspace_id+ )+ except SessionError as exc:+ # A pane or workspace that is not there is not found; a full or busy+ # target is a conflict the caller can resolve and retry.+ message = str(exc)+ status = 404 if message.startswith("No terminal called") else 409+ raise HTTPException(status_code=status, detail=message) from exc+ if source.id != target.id:+ await _announce_workspace(request, source, "updated")+ await _announce_workspace(request, target, "updated")+ return {+ "ok": True,+ "terminal": term.to_dict(),+ "source_workspace_id": source.id,+ "target_workspace_id": target.id,+ "state": registry.state(),+ }++@router.post("/layout/weights", summary="Apply dragged pane sizes to the workspace")async def set_layout_weights(req: LayoutWeightsRequest) -> dict:"""Persist the pane sizes a seam drag produced.diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 6dcb052b7b..3c70c402bf 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -525,6 +525,8 @@ interface AgenticTerminalProps {computerName?: string;/** Compact header only: "Run on …" / "Bring back" menu entries. */placementItems?: { label: string; run: () => void }[];+ /** Compact header only: "Move to <workspace>" menu entries. */+ workspaceItems?: { label: string; run: () => void }[];/** Registry identity and optional custom logo for the compact header. */agent?: string;agentLogoUrl?: string;@@ -665,6 +667,7 @@ export function AgenticTerminal({branch,computerName,placementItems,+ workspaceItems,agent,agentLogoUrl,recap,@@ -2643,6 +2646,7 @@ export function AgenticTerminal({branch,computerName,placementItems,+ workspaceItems,};return (diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.panedrop.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.panedrop.test.tsxnew file mode 100644index 0000000000..5d37781891--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.panedrop.test.tsx@@ -0,0 +1,58 @@+/**+ * Sidebar rows a terminal pane can be dropped on.+ *+ * The grid finds a drop target by these attributes under the pointer, so they+ * are the whole contract: only an OPEN workspace can take a running pane (a+ * closed one has no grid to re-join it), and a one-row project carries them on+ * its single header, because that header is the workspace row there.+ */+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { IdeProjectTree } from "./IdeProjectTree";+import { useIdeProjectsStore } from "@/store/ideProjects";+import type { IdeProject } from "@/lib/agenticIdeApi";++vi.mock("@/lib/agenticIdeApi", () => ({ IdeApiError: class extends Error {} }));+vi.mock("@/lib/chatLibraryApi", () => ({ ChatLibraryError: class extends Error {} }));++function workspace(id: string, name: string, status: "open" | "closed" = "open") {+ return { id, name, status, live_terminals: 1, terminals: 1, restorable: true };+}++function project(id: string, name: string, workspaces: ReturnType<typeof workspace>[]): IdeProject {+ return {+ id, path: `/${id}`, name, color: null, pinned: false, archived: false, scratch: false,+ created_at: 0, last_opened_at: 0, exists: true, chats: 0, workspaces,+ } as unknown as IdeProject;+}++beforeEach(() => {+ localStorage.clear();+ useIdeProjectsStore.setState({+ projects: [+ project("p1", "Personal Jarvis", [workspace("w1", "Personal Jarvis 2"), workspace("w2", "Blog"), workspace("w3", "Old", "closed")]),+ project("p2", "Website", [workspace("w4", "Website")]),+ ],+ activeWorkspaceId: "w1",+ pendingWorkspaceId: null,+ refreshRequest: null,+ action: null,+ });+});+afterEach(cleanup);++it("lets a pane be dropped on open workspaces only", () => {+ render(<IdeProjectTree />);++ const blog = screen.getByTestId("ide-workspace-row-w2");+ expect(blog.getAttribute("data-pane-drop-workspace")).toBe("w2");+ expect(blog.getAttribute("data-pane-drop-name")).toBe("Blog");+ expect(screen.getByTestId("ide-workspace-row-w3").hasAttribute("data-pane-drop-workspace")).toBe(false);+});++it("puts the drop target on a one-row project's header", () => {+ render(<IdeProjectTree />);++ expect(screen.getByTestId("ide-project-header-p2").getAttribute("data-pane-drop-workspace")).toBe("w4");+ expect(screen.getByTestId("ide-project-header-p1").hasAttribute("data-pane-drop-workspace")).toBe(false);+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsxindex 9b08245bc7..996063859c 100644--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx@@ -11,6 +11,15 @@ import { useIdeProjectsStore } from "@/store/ideProjects";const EXPANSION_KEY = "jarvis.ide.projectExpansion.v1";const WORKSPACE_DRAG_MIME = "application/x-jarvis-workspace-id";const PROJECT_DRAG_MIME = "application/x-jarvis-project-id";+/**+ * An open workspace row accepts a terminal pane dragged out of the grid: the+ * grid reads these attributes under the pointer and lights the row with+ * `data-pane-drop-active` while the pane hovers it (WorkspaceTerminalGrid).+ */+function paneDropProps(workspace: ProjectWorkspace | null): Record<string, string> {+ return workspace?.status === "open" ? { "data-pane-drop-workspace": workspace.id, "data-pane-drop-name": workspace.name } : {};+}+const PANE_DROP_ACTIVE = "data-[pane-drop-active=true]:bg-primary/10 data-[pane-drop-active=true]:ring-1 data-[pane-drop-active=true]:ring-inset data-[pane-drop-active=true]:ring-primary/60";/*** What a 405 on a reorder means: this view already knows drag and drop, but* the backend serving it predates the endpoint — a restart brings the two@@ -432,6 +441,7 @@ export function IdeProjectTree() {return <div key={project.id} className="mb-px" data-testid={`ide-project-${project.id}`}><div draggable={projectDraggable}data-testid={`ide-project-header-${project.id}`}+ {...paneDropProps(solo)}onContextMenu={(event) => solo ? openWorkspaceMenu(event, project.id, solo.id) : openProjectMenu(event, project.id)}onDragStart={(event) => {if (!projectDraggable) { event.preventDefault(); return; }@@ -465,7 +475,7 @@ export function IdeProjectTree() {clearProjectDragState();void moveProject(sourceId, project.id, before);}}- className={`group relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted ${active ? "text-foreground" : ""} ${soloSelected || soloPending ? "bg-muted" : ""} ${isProjectDragged ? "opacity-40" : ""} ${isProjectDropBefore ? "before:absolute before:-top-0.5 before:left-2 before:right-2 before:h-0.5 before:rounded-full before:bg-primary" : ""} ${isProjectDropAfter ? "after:absolute after:-bottom-0.5 after:left-2 after:right-2 after:h-0.5 after:rounded-full after:bg-primary" : ""} ${projectDraggable ? "cursor-grab active:cursor-grabbing" : ""}`}>+ className={`group relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted ${active ? "text-foreground" : ""} ${soloSelected || soloPending ? "bg-muted" : ""} ${isProjectDragged ? "opacity-40" : ""} ${isProjectDropBefore ? "before:absolute before:-top-0.5 before:left-2 before:right-2 before:h-0.5 before:rounded-full before:bg-primary" : ""} ${isProjectDropAfter ? "after:absolute after:-bottom-0.5 after:left-2 after:right-2 after:h-0.5 after:rounded-full after:bg-primary" : ""} ${projectDraggable ? "cursor-grab active:cursor-grabbing" : ""} ${PANE_DROP_ACTIVE}`}>{renamingId === project.id ? <form className="flex min-w-0 flex-1 items-center gap-1 px-2" onSubmit={(event) => { event.preventDefault(); const name = draftName.trim(); if (name && name !== project.name) void mutate(project, { name }); else setRenamingId(null); }}><input autoFocus aria-label={`Rename ${project.name}`} value={draftName} maxLength={80} disabled={working}onChange={(event) => setDraftName(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); setRenamingId(null); } }}@@ -529,6 +539,7 @@ export function IdeProjectTree() {const isDropAfter = dropTarget?.id === workspace.id && !dropTarget.before;return <div key={workspace.id}data-testid={`ide-workspace-row-${workspace.id}`}+ {...paneDropProps(workspace)}draggable={draggable}onContextMenu={(event) => openWorkspaceMenu(event, project.id, workspace.id)}onDragStart={(event) => {@@ -562,7 +573,7 @@ export function IdeProjectTree() {clearDragState();void moveWorkspace(sourceId, workspace.id, before);}}- className={`group/space relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted ${selected ? "bg-muted text-foreground" : ""} ${pending ? "bg-muted/80 text-foreground" : ""} ${isDragged ? "opacity-40" : ""} ${isDropBefore ? "before:absolute before:-top-0.5 before:left-2 before:right-2 before:h-0.5 before:rounded-full before:bg-primary" : ""} ${isDropAfter ? "after:absolute after:-bottom-0.5 after:left-2 after:right-2 after:h-0.5 after:rounded-full after:bg-primary" : ""}`}>+ className={`group/space relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted ${selected ? "bg-muted text-foreground" : ""} ${pending ? "bg-muted/80 text-foreground" : ""} ${isDragged ? "opacity-40" : ""} ${isDropBefore ? "before:absolute before:-top-0.5 before:left-2 before:right-2 before:h-0.5 before:rounded-full before:bg-primary" : ""} ${isDropAfter ? "after:absolute after:-bottom-0.5 after:left-2 after:right-2 after:h-0.5 after:rounded-full after:bg-primary" : ""} ${PANE_DROP_ACTIVE}`}>{renamingWorkspaceId === workspace.id ? (<formclassName="flex min-w-0 flex-1 items-center gap-1 px-2 py-1"diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.transfer.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.transfer.test.tsxnew file mode 100644index 0000000000..102039dd43--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.transfer.test.tsx@@ -0,0 +1,111 @@+/**+ * Moving a pane into another open workspace, from its menu or by dropping it+ * on that workspace's row in the sidebar.+ *+ * The agent keeps running; only the tab that lists it changes. What the grid+ * owes is to send the pane's stable identity (never a call-sign another tab+ * also has), to drop the pane from its own screen with the answer, and to say+ * when the pane arrived under another name.+ */+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { SessionState } from "@/lib/agenticIdeApi";+const api = vi.hoisted(() => ({ transfer: vi.fn(), move: vi.fn(), toast: vi.fn() }));+vi.mock("@/lib/agenticIdeApi", () => ({ transferTerminal: api.transfer, moveTerminal: api.move }));+vi.mock("@/store/events", () => ({ useEventStore: (select: (state: unknown) => unknown) => select({ pushToast: api.toast }) }));+vi.mock("./AgenticTerminal", () => ({ AgenticTerminal: (props: {+ name: string;+ onArrangeStart?: (event: React.PointerEvent) => void;+ workspaceItems?: { label: string; run: () => void }[];+}) => <div data-testid={`pane-${props.name}`}>+ <button type="button" onPointerDown={props.onArrangeStart}>Move {props.name}</button>+ {(props.workspaceItems ?? []).map((item) => <button key={item.label} type="button" onClick={item.run}>{props.name}: {item.label}</button>)}+</div> }));+vi.mock("@/hooks/useTheme", () => ({ useThemeValue: () => "dark" }));+import { WorkspaceTerminalGrid } from "./WorkspaceTerminalGrid";+import { balancedLayout } from "./workspaceDocking";++class ResizeObserverStub { observe() {} disconnect() {} }+class PointerEventStub extends MouseEvent {+ pointerId: number;+ constructor(type: string, init: PointerEventInit = {}) { super(type, init); this.pointerId = init.pointerId ?? 1; }+}+vi.stubGlobal("ResizeObserver", ResizeObserverStub);+vi.stubGlobal("PointerEvent", PointerEventStub);++const makeSession = (names = ["T1", "T2"]) => ({+ id: "w1", layout: balancedLayout(names), terminals: names.map((name) => ({ name, key: name.toLowerCase(), history_id: `h-${name}`, display_name: "Claude Code", agent: "claude" })),+}) as SessionState;+const workspaces = [{ id: "w1", name: "Personal Jarvis" }, { id: "w2", name: "Blog" }, { id: "w3", name: "VMs" }];+const props = { onChanged: vi.fn(), onAdd: vi.fn(), onClose: vi.fn(), onSelect: vi.fn(), selected: "", fontSize: 13, appearance: null, workspaces };++/** A sidebar row as IdeProjectTree draws it, and a pointer that finds it right of x=1000. */+function sidebarRow(id: string, name: string): HTMLElement {+ const row = document.createElement("div");+ row.setAttribute("data-pane-drop-workspace", id);+ row.setAttribute("data-pane-drop-name", name);+ const label = document.createElement("span");+ row.appendChild(label);+ document.body.appendChild(row);+ document.elementFromPoint = ((x: number) => (x > 1000 ? label : null)) as typeof document.elementFromPoint;+ return row;+}++beforeEach(() => { vi.clearAllMocks(); });+afterEach(() => { cleanup(); document.body.innerHTML = ""; });++it("offers every other open workspace and moves the pane by its identity", async () => {+ api.transfer.mockResolvedValue({ terminal: { name: "T3" }, state: { session: makeSession(["T1"]) } });+ const onChanged = vi.fn();+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} onChanged={onChanged} />);++ expect(screen.queryByRole("button", { name: "T2: Move to Personal Jarvis" })).toBeNull();+ expect(screen.getByRole("button", { name: "T2: Move to VMs" })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "T2: Move to Blog" }));++ await waitFor(() => expect(api.transfer).toHaveBeenCalledExactlyOnceWith("pane:h-T2", "w1", "w2"));+ await waitFor(() => expect(onChanged).toHaveBeenCalledOnce());+ expect(onChanged.mock.calls[0][0].terminals.map((t: { name: string }) => t.name)).toEqual(["T1"]);+ // It arrived under another call-sign; the user is told which.+ expect(api.toast).toHaveBeenCalledWith("success", "T2 moved to Blog as T3. Its agent keeps running.");+});++it("says why a move was refused and keeps the pane", async () => {+ api.transfer.mockRejectedValue(new Error("Blog already has the maximum of 12 terminals."));+ const onChanged = vi.fn(), onMutationEnd = vi.fn();+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} onChanged={onChanged} onMutationEnd={onMutationEnd} />);++ fireEvent.click(screen.getByRole("button", { name: "T1: Move to Blog" }));++ await waitFor(() => expect(api.toast).toHaveBeenCalledWith("error", "Blog already has the maximum of 12 terminals."));+ expect(onChanged).not.toHaveBeenCalled();+ expect(onMutationEnd).toHaveBeenCalledOnce();+});++it("moves a pane dropped on a workspace in the sidebar, lighting the row while it hovers", async () => {+ api.transfer.mockResolvedValue({ terminal: { name: "T1" }, state: { session: makeSession(["T2"]) } });+ const row = sidebarRow("w2", "Blog");+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} />);++ fireEvent.pointerDown(screen.getByRole("button", { name: "Move T1" }), { button: 0, pointerId: 1, clientX: 15, clientY: 15 });+ fireEvent.pointerMove(window, { pointerId: 1, clientX: 1200, clientY: 40 });+ expect(row.getAttribute("data-pane-drop-active")).toBe("true");+ expect(screen.getByText("Move to Blog")).toBeTruthy();+ fireEvent.pointerUp(window, { pointerId: 1, clientX: 1200, clientY: 40 });++ expect(row.hasAttribute("data-pane-drop-active")).toBe(false);+ await waitFor(() => expect(api.transfer).toHaveBeenCalledExactlyOnceWith("pane:h-T1", "w1", "w2"));+ expect(api.move).not.toHaveBeenCalled();+});++it("ignores the row of the workspace the pane is already in", () => {+ const row = sidebarRow("w1", "Personal Jarvis");+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} />);++ fireEvent.pointerDown(screen.getByRole("button", { name: "Move T1" }), { button: 0, pointerId: 1, clientX: 15, clientY: 15 });+ fireEvent.pointerMove(window, { pointerId: 1, clientX: 1200, clientY: 40 });+ expect(row.hasAttribute("data-pane-drop-active")).toBe(false);+ fireEvent.pointerUp(window, { pointerId: 1, clientX: 1200, clientY: 40 });++ expect(api.transfer).not.toHaveBeenCalled();+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsxindex a2a3bf2a01..cec851fbb3 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx@@ -4,7 +4,7 @@ import { AgentMark } from "./AgentMark";import { ForkPaneDialog, type ForkMode, type ForkSource } from "./ForkPaneDialog";import type { PaneSplitDirection } from "./WorkspaceTerminalHeader";import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";-import { forkTerminal, moveTerminal, placeTerminal, renameTerminal, type PaneMovePosition } from "@/lib/agenticIdeApi";+import { forkTerminal, moveTerminal, placeTerminal, renameTerminal, transferTerminal, type PaneMovePosition } from "@/lib/agenticIdeApi";import { useComputerChoices } from "@/hooks/useComputers";import { useThemeValue } from "@/hooks/useTheme";import { useEventStore } from "@/store/events";@@ -57,12 +57,18 @@ interface Props {* or rounded cards. The reader picks it in Workspace options.*/paneStyle?: PaneStyle;+ /** Every open workspace; a pane can be moved into any of the others. */+ workspaces?: readonly WorkspaceChoice[];}+interface WorkspaceChoice { id: string; name: string }interface DropTarget { id: string; position: PaneMovePosition; allowed: boolean }-interface DragFeedback { id: string; target: DropTarget | null; x: number; y: number }+interface DragFeedback { id: string; target: DropTarget | null; x: number; y: number; workspace?: WorkspaceChoice | null }-export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, maxPanes = MAX_WORKSPACE_PANES, fontSize, appearance, disabled = false, onMutationStart, onMutationEnd, paneStyle: look = "classic" }: Props) {+/** The attribute a sidebar row carries when a dragged pane may be dropped on it. */+const WORKSPACE_DROP = "data-pane-drop-workspace";++export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, maxPanes = MAX_WORKSPACE_PANES, fontSize, appearance, disabled = false, onMutationStart, onMutationEnd, paneStyle: look = "classic", workspaces = [] }: Props) {const theme = useThemeValue();const pushToast = useEventStore((state) => state.pushToast);// The pane an agent card in the side panel pointed at, framed in blue.@@ -189,6 +195,34 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe}}, [pushToast]);+ // "Move to <workspace>", from the pane menu or by dropping the pane on a+ // workspace in the sidebar: the pane leaves this grid and joins that tab+ // with its agent still running, and that tab's grid re-joins it.+ const [transferring, setTransferring] = useState<string | null>(null);+ const transfer = useCallback(async (sourceId: string, target: WorkspaceChoice) => {+ const owner = latest.current.session;+ const terminal = owner.terminals.find((entry) => idOf(entry) === sourceId);+ if (!terminal || target.id === owner.id || saveInFlight.current || latest.current.disabled) return;+ saveInFlight.current = true;+ latest.current.onMutationStart?.();+ setTransferring(sourceId);+ try {+ const result = await transferTerminal(terminal.history_id ? `pane:${terminal.history_id}` : terminal.name, owner.id, target.id);+ if (!mounted.current) return;+ const next = result.state.session;+ if (next && latest.current.session === owner && next.id === owner.id) latest.current.onChanged(next);+ const renamed = result.terminal.name !== terminal.name ? ` as ${result.terminal.name}` : "";+ pushToast("success", `${terminal.name} moved to ${target.name}${renamed}. Its agent keeps running.`);+ setAnnouncement(`${terminal.name} moved to ${target.name}${renamed}.`);+ } catch (error) {+ if (mounted.current) pushToast("error", (error as Error).message);+ } finally {+ saveInFlight.current = false;+ latest.current.onMutationEnd?.();+ if (mounted.current) setTransferring(null);+ }+ }, [pushToast]);+const startDrag = useCallback((id: string, event: React.PointerEvent) => {if (event.button !== 0 || latest.current.disabled || dragCleanup.current || saveInFlight.current) return;const handle = event.currentTarget;@@ -214,14 +248,32 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe}return null;};+ // A workspace row in the sidebar under the pointer. It is lit straight on+ // the DOM: the sidebar is another component, and this is one attribute+ // for the length of a drag, not state it needs to own.+ let litRow: HTMLElement | null = null;+ const workspaceAt = (x: number, y: number): WorkspaceChoice | null => {+ const row = document.elementFromPoint?.(x, y)?.closest<HTMLElement>(`[${WORKSPACE_DROP}]`) ?? null;+ const targetId = row?.getAttribute(WORKSPACE_DROP) ?? "";+ const hit = row && targetId && targetId !== latest.current.session.id ? row : null;+ if (hit !== litRow) {+ litRow?.removeAttribute("data-pane-drop-active");+ hit?.setAttribute("data-pane-drop-active", "true");+ litRow = hit;+ }+ return hit ? { id: targetId, name: hit.getAttribute("data-pane-drop-name") || "that workspace" } : null;+ };const onMove = (motion: PointerEvent) => {if (motion.pointerId !== pointer) return;if (!armed && Math.hypot(motion.clientX - initialX, motion.clientY - initialY) <= 5) return;armed = true;motion.preventDefault();- setDrag({ id, target: targetAt(motion.clientX, motion.clientY), x: motion.clientX, y: motion.clientY });+ const workspace = workspaceAt(motion.clientX, motion.clientY);+ setDrag({ id, target: workspace ? null : targetAt(motion.clientX, motion.clientY), workspace, x: motion.clientX, y: motion.clientY });};const cleanup = () => {+ litRow?.removeAttribute("data-pane-drop-active");+ litRow = null;window.removeEventListener("pointermove", onMove, true);window.removeEventListener("pointerup", onUp, true);window.removeEventListener("pointercancel", onCancel, true);@@ -235,9 +287,11 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSeconst onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); key.stopPropagation(); cleanup(); } };const onUp = (release: PointerEvent) => {if (release.pointerId !== pointer) return;- const target = targetAt(release.clientX, release.clientY);+ const workspace = armed ? workspaceAt(release.clientX, release.clientY) : null;+ const target = workspace ? null : targetAt(release.clientX, release.clientY);cleanup();- if (armed && target?.allowed) void move(id, target.id, target.position);+ if (armed && workspace) void transfer(id, workspace);+ else if (armed && target?.allowed) void move(id, target.id, target.position);};dragCleanup.current = cleanup;window.addEventListener("pointermove", onMove, { capture: true, passive: false });@@ -245,7 +299,7 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSewindow.addEventListener("pointercancel", onCancel, true);window.addEventListener("blur", cleanup);window.addEventListener("keydown", onKey, true);- }, [move]);+ }, [move, transfer]);const rename = async (terminal: TerminalState, name: string) => {const owner = latest.current.session;@@ -396,6 +450,8 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSesplitDisabled={tiles.length >= maxPanes} onSplit={(direction) => onAdd(terminal.name, direction)}branch={terminal.branch || undefined}computerName={computerName(terminal)} placementItems={placementItems(terminal)}+ workspaceItems={transferring || saving || disabled ? [] : workspaces.filter((workspace) => workspace.id !== session.id)+ .map((workspace) => ({ label: `Move to ${workspace.name}`, run: () => void transfer(id, workspace) }))}onFork={terminal.accepts_prompts === false ? undefined : () => setForking({ name: terminal.name, agent: terminal.agent, displayName: terminal.display_name, workspaceId: session.id })} />{drag?.target?.id === id && <div aria-hidden="true" data-testid="dock-preview" data-position={drag.target.position}className={cn("pointer-events-none absolute z-20 flex items-center justify-center border-2 p-2", minimal ? "rounded-none" : "rounded-xl", drag.target.allowed ? "border-ring/70 bg-accent/[0.15]" : "border-destructive bg-background/80",@@ -428,6 +484,7 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe{drag && dragged && <div aria-hidden="true" className="pointer-events-none fixed z-[100] flex items-center gap-2 rounded-lg border border-border bg-popover px-3 py-2 text-sm font-medium text-popover-foreground shadow-xl"style={{ left: drag.x + 14, top: drag.y + 14 }}><AgentMark agent={dragged.agent} label={dragged.display_name} variant="plain" />{dragged.name}+ {drag.workspace && <span className="font-normal text-muted-foreground">Move to {drag.workspace.name}</span>}</div>}<span className="sr-only" role="status">{announcement}</span><ForkPaneDialog source={forking} busy={forkBusy} onCancel={() => setForking(null)} onConfirm={(choice) => void fork(choice)} />diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsxindex 0966bec12e..cc0527c3f3 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx@@ -1,6 +1,6 @@import { useEffect, useId, useLayoutEffect, useRef, useState, type ComponentType, type CSSProperties, type MouseEvent, type PointerEvent, type SVGProps } from "react";import { createPortal } from "react-dom";-import { Check, GitBranch, Maximize2, Minimize2, MoreHorizontal, Plus, Server, X } from "lucide-react";+import { Check, FolderInput, GitBranch, Maximize2, Minimize2, MoreHorizontal, Plus, Server, X } from "lucide-react";import { AgentMark } from "./AgentMark";import { BranchIcon } from "./branchIcon";import { usePaneTitle } from "@/store/paneRecaps";@@ -39,6 +39,8 @@ interface Props {computerName?: string;/** "Run on …" / "Bring back" entries for the pane's menu. */placementItems?: { label: string; run: () => void }[];+ /** "Move to <workspace>" entries: the pane joins another open workspace, still running. */+ workspaceItems?: { label: string; run: () => void }[];/*** `bar` is the card's title bar. `tile` is the minimal tile's: the same* title and controls in a slimmer, square row, closer to a multiplexer's@@ -66,7 +68,7 @@ export function WorkspaceTerminalHeader({name, workspaceId, promptCount = 0, agent, agentLogoUrl, displayName, status, appearance, arranging = false,maximized = false, addDisabled = false, onArrangeStart, onActivate, onToggleMaximize,onAdd, onClose, onRename, onOpenConversation, onOpenChat, onRestart, onFork, branch,- computerName, placementItems, variant = "bar", focused = false,+ computerName, placementItems, workspaceItems, variant = "bar", focused = false,}: Props) {const brand = PANE_BRAND[appearance];// The pane's goal in a few words, in place of its call-sign; the call-sign@@ -190,6 +192,7 @@ export function WorkspaceTerminalHeader({onOpenConversation && { label: "Conversation history", run: onOpenConversation },onOpenChat && { label: "Open as chat", run: onOpenChat },stopped && onRestart && { label: "Restart agent", run: onRestart },+ ...(workspaceItems ?? []).map((item, index) => ({ ...item, Icon: FolderInput, separated: index === 0 })),...(placementItems ?? []).map((item, index) => ({ ...item, Icon: Server, separated: index === 0 })),] as (MenuItem | false | undefined | null)[]).filter((item): item is MenuItem => Boolean(item)).map((item) =><button type="button" role="menuitem" key={item.label} onClick={() => choose(item.run)}diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex f51c3a6673..0a986f520d 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -1494,6 +1494,40 @@ export async function moveTerminal(return body.state.session;}+/** What moving a pane into another workspace answers with. */+export interface TerminalTransfer {+ /** The pane as it is now — its call-sign may have changed in the new tab. */+ terminal: TerminalState;+ source_workspace_id: string;+ target_workspace_id: string;+ state: IdeState;+}++/**+ * Move a running pane into another open workspace.+ *+ * The agent is not restarted: its process, conversation and folder stay as+ * they are, and only the tab that lists and draws it changes. The pane keeps+ * its call-sign unless the target tab already has one by that name — the+ * answer's `terminal.name` is the one it answers to now.+ */+export async function transferTerminal(+ name: string,+ workspaceId: string,+ targetWorkspaceId: string,+): Promise<TerminalTransfer> {+ const res = await fetch(+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/transfer`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ workspace_id: workspaceId, target_workspace_id: targetWorkspaceId }),+ },+ );+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as TerminalTransfer;+}+/*** Give one pane another call-sign.*diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex e7f6034abe..1026e91506 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -487,7 +487,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {<IdeSidePanelFrame markInUse={paneStyle === "minimal"}>{session ? <WorkspaceTerminalGrid key={session.id} session={session} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}onAdd={openAgentPicker} onClose={closeAgent} onSelect={setSelected} selected={selected} maxPanes={maxPanes} fontSize={fontSize} appearance={appearance} disabled={busy}- onMutationStart={beginGridMutation} onMutationEnd={endGridMutation} paneStyle={paneStyle} />+ onMutationStart={beginGridMutation} onMutationEnd={endGridMutation} paneStyle={paneStyle} workspaces={state.workspaces ?? []} />: <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center"><FolderPlus className="h-8 w-8 text-muted-foreground/70" /><h1 className="text-lg font-medium">{projects.some((project) => !project.scratch && !project.archived) ? "Choose a workspace" : "Connect a project"}</h1>diff --git a/tests/unit/agentic_ide/test_pane_transfer.py b/tests/unit/agentic_ide/test_pane_transfer.pynew file mode 100644index 0000000000..ce929bfa8d--- /dev/null+++ b/tests/unit/agentic_ide/test_pane_transfer.py@@ -0,0 +1,275 @@+"""Moving a pane into another open workspace — the chat started in the wrong tab.++The promise is the same one rearranging makes inside a grid: nothing is started+or stopped. The agent's process, conversation and history belong to the pane,+so moving it only changes which tab lists and draws it. What a tab owns on its+own — the call-sign, the key, the folder — is what these tests pin, because+every failure there is silent on screen: two panes answering to one name, or a+pane whose next restart opens an empty chat in the wrong folder.+"""+from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from jarvis.agentic_ide import resume_store+from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.session import MAX_TERMINALS, Registry, SessionError+from jarvis.ui.web import agentic_ide_routes as routes+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}",))+ instance = Registry(pty_manager=fake_pty)+ monkeypatch.setattr(routes, "get_registry", lambda: instance)+ return instance+++def _request() -> SimpleNamespace:+ return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(bus=None)))+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++async def _two_tabs(registry: Registry, folder: Path, first: int = 2, second: int = 2):+ source = await registry.start(str(folder), [{"agent": "claude"}] * first, name="Jarvis")+ target = await registry.start(str(folder), [{"agent": "claude"}] * second, name="Blog")+ return source, target+++async def test_a_running_agent_moves_without_a_restart(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """The whole point: the agent keeps working, the new tab re-joins it."""+ source, target = await _two_tabs(registry, tmp_path)+ await registry.attach("T1", 80, 24, _noop, _noop_exit, workspace_id=source.id)+ term = source.find("T1")+ assert term is not None and term.status == "live"+ pty_id, history_id = term.pty_id, term.history_id++ _, _, moved = await registry.transfer_terminal(+ "T1", workspace_id=source.id, target_workspace_id=target.id+ )++ assert moved is term+ assert fake_pty.closed == []+ assert len(fake_pty.spawns) == 1+ assert moved.pty_id == pty_id and moved.status == "live"+ assert all(t.history_id != history_id for t in source.terminals)+ assert any(t is moved for t in target.terminals)++ # The new tab's viewer takes the re-join path: still exactly one process.+ await registry.attach(moved.name, 100, 30, _noop, _noop_exit, workspace_id=target.id)+ assert len(fake_pty.spawns) == 1+ assert moved.viewer_output is _noop+++async def test_the_old_tabs_viewer_lets_go(registry: Registry, tmp_path: Path) -> None:+ """The old grid's socket stops being fed, and its late detach hits nothing."""+ source, target = await _two_tabs(registry, tmp_path)+ await registry.attach("T2", 80, 24, _noop, _noop_exit, workspace_id=source.id)++ _, _, moved = await registry.transfer_terminal(+ "T2", workspace_id=source.id, target_workspace_id=target.id+ )++ assert moved.viewer_output is None and moved.watchers == []+ registry.detach("T2", workspace_id=source.id, viewer=_noop)+ assert registry.write("T2", "x", workspace_id=source.id) is False+++async def test_a_taken_position_moves_to_the_lowest_free_number(+ registry: Registry, tmp_path: Path+) -> None:+ """A "T2" joining a tab that has a T2 must not leave two panes called T2."""+ source, target = await _two_tabs(registry, tmp_path)++ _, _, moved = await registry.transfer_terminal(+ "T2", workspace_id=source.id, target_workspace_id=target.id+ )++ assert moved.name == "T3"+ assert sorted(t.name for t in target.terminals) == ["T1", "T2", "T3"]+ assert len({t.key for t in target.terminals}) == 3+ assert [t.name for t in source.terminals] == ["T1"]+++async def test_a_custom_name_travels_and_is_suffixed_only_when_taken(+ registry: Registry, tmp_path: Path+) -> None:+ source, target = await _two_tabs(registry, tmp_path)+ await registry.rename_terminal("T1", "Mika") # the front tab is "Blog"+ await registry.activate(source.id)+ await registry.rename_terminal("T1", "Mika")++ _, _, moved = await registry.transfer_terminal(+ "Mika", workspace_id=source.id, target_workspace_id=target.id+ )++ assert moved.name == "Mika 2"+ assert target.find("Mika 2") is moved+++async def test_its_key_never_collides_with_a_renamed_pane(+ registry: Registry, tmp_path: Path+) -> None:+ """A renamed pane keeps its key, so a free NAME does not mean a free key."""+ source, target = await _two_tabs(registry, tmp_path, first=1, second=1)+ await registry.rename_terminal("T1", "Writer") # Blog's t1 is now "Writer"++ _, _, moved = await registry.transfer_terminal(+ "T1", workspace_id=source.id, target_workspace_id=target.id+ )++ assert moved.name == "T1"+ assert len({t.key for t in target.terminals}) == 2+ assert target.find("T1") is moved+++async def test_another_folder_is_remembered_and_forgotten_on_the_way_home(+ registry: Registry, tmp_path: Path+) -> None:+ """The agent keeps working where it started, and a restart resumes there."""+ jarvis_dir, blog_dir = tmp_path / "jarvis", tmp_path / "blog"+ jarvis_dir.mkdir()+ blog_dir.mkdir()+ source = await registry.start(str(jarvis_dir), [{"agent": "claude"}] * 2, name="Jarvis")+ target = await registry.start(str(blog_dir), [{"agent": "claude"}], name="Blog")++ _, _, moved = await registry.transfer_terminal(+ "T2", workspace_id=source.id, target_workspace_id=target.id+ )+ assert moved.cwd(target.folder) == source.folder++ _, _, back = await registry.transfer_terminal(+ moved.name, workspace_id=target.id, target_workspace_id=source.id+ )+ assert back.folder == ""+ assert back.cwd(source.folder) == source.folder+++async def test_the_same_folder_needs_no_folder_of_its_own(+ registry: Registry, tmp_path: Path+) -> None:+ source, target = await _two_tabs(registry, tmp_path)+ _, _, moved = await registry.transfer_terminal(+ "T1", workspace_id=source.id, target_workspace_id=target.id+ )+ assert moved.folder == ""+++async def test_the_move_is_saved_with_the_new_tab(registry: Registry, tmp_path: Path) -> None:+ """After a restart the pane comes back in the tab it was moved to."""+ source, target = await _two_tabs(registry, tmp_path)+ term = source.find("T1")+ assert term is not None++ await registry.transfer_terminal("T1", workspace_id=source.id, target_workspace_id=target.id)++ saved = {+ w.session_id: {t.history_id for t in w.terminals} for w in resume_store.load().workspaces+ }+ assert term.history_id in saved[target.id]+ assert term.history_id not in saved[source.id]+++async def test_the_old_tab_forgets_a_selection_of_the_moved_pane(+ registry: Registry, tmp_path: Path+) -> None:+ source, target = await _two_tabs(registry, tmp_path)+ source.focused = "T2"+ source.surface_prompt_target = "T2"++ await registry.transfer_terminal("T2", workspace_id=source.id, target_workspace_id=target.id)++ assert source.focused == "" and source.surface_prompt_target == ""+++async def test_moving_into_the_same_tab_changes_nothing(+ registry: Registry, tmp_path: Path+) -> None:+ source, _ = await _two_tabs(registry, tmp_path)+ before = [(t.name, t.key) for t in source.terminals]++ await registry.transfer_terminal("T1", workspace_id=source.id, target_workspace_id=source.id)++ assert [(t.name, t.key) for t in source.terminals] == before+++async def test_a_full_or_closed_target_is_refused(registry: Registry, tmp_path: Path) -> None:+ source, target = await _two_tabs(registry, tmp_path, second=MAX_TERMINALS)++ with pytest.raises(SessionError, match="maximum"):+ await registry.transfer_terminal(+ "T1", workspace_id=source.id, target_workspace_id=target.id+ )+ with pytest.raises(SessionError, match="not open"):+ await registry.transfer_terminal(+ "T1", workspace_id=source.id, target_workspace_id="ide_missing"+ )+ assert len(source.terminals) == 2+++async def test_the_route_answers_with_the_new_name_and_both_tabs(+ registry: Registry, tmp_path: Path+) -> None:+ source, target = await _two_tabs(registry, tmp_path)++ body = await routes.transfer_terminal(+ _request(),+ "T2",+ routes.TransferTerminalRequest(workspace_id=source.id, target_workspace_id=target.id),+ )++ assert body["terminal"]["name"] == "T3"+ assert body["source_workspace_id"] == source.id+ assert body["target_workspace_id"] == target.id+++async def test_the_route_tells_a_missing_pane_from_a_missing_tab(+ registry: Registry, tmp_path: Path+) -> None:+ source, target = await _two_tabs(registry, tmp_path)++ with pytest.raises(HTTPException) as missing_pane:+ await routes.transfer_terminal(+ _request(),+ "T9",+ routes.TransferTerminalRequest(workspace_id=source.id, target_workspace_id=target.id),+ )+ with pytest.raises(HTTPException) as missing_tab:+ await routes.transfer_terminal(+ _request(),+ "T1",+ routes.TransferTerminalRequest(workspace_id=source.id, target_workspace_id="ide_x"),+ )++ assert missing_pane.value.status_code == 404+ assert missing_tab.value.status_code == 409diff --git a/tests/unit/cli_ctl/test_commands_ide.py b/tests/unit/cli_ctl/test_commands_ide.pyindex 8ed2036e58..80c5791856 100644--- a/tests/unit/cli_ctl/test_commands_ide.py+++ b/tests/unit/cli_ctl/test_commands_ide.py@@ -78,3 +78,15 @@ def test_close_terminals_exits_nonzero_when_any_terminal_remains_open(capture_apassert result.exit_code == 1assert '"failed"' in result.stdout+++def test_move_terminal_names_both_workspaces(capture_api) -> None:+ result = runner.invoke(+ app, ["ide", "move-terminal", "T2", "ide_blog", "--workspace", "ide_jarvis"]+ )++ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["method"] == "POST"+ assert call["path"] == "/api/agentic-ide/terminals/T2/transfer"+ assert call["body"] == {"target_workspace_id": "ide_blog", "workspace_id": "ide_jarvis"}