Skip to content

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

feat(agentic-ide): let a terminal be picked up by its header and put somewhere else

Ruben Lütke76cfae2645d7
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index c34b5f762f..3bf79625a9 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -281,6 +281,26 @@ Open one or more additional coding terminals in the open workspace. Use this whe
- **Desktop UI section:** `agentic-ide`
- **Voice example (EN):** "spawn five new claude code terminals"
+## `agentic-ide-move-terminal` — Move an Agentic-IDE terminal in the grid
+
+Rearrange the open workspace: put one terminal at another one's place. Nothing is started or stopped — the panes keep their agents and their conversations, only where they are drawn changes. Use it for 'swap Mika and Nova', 'put Mika next to Nova', 'move Mika under Nova'. 'swap' exchanges the two panes and leaves the rest of the grid alone; 'left'/'right' give the moved pane its own column beside the target; 'above'/'below' stack it in the target's column. Both names must be terminals that are already open.
+
+- **Endpoint:** `POST /api/agentic-ide/terminals/{name}/move`
+- **Arguments:** `name` (string; required); `target` (string; required); `position` (one of: swap, left, right, above, below; optional)
+- **Requires confirmation:** no
+- **Desktop UI section:** `agentic-ide`
+- **Voice example (EN):** "swap mika and nova"
+
+## `agentic-ide-close-agent-terminals` — Close Agentic-IDE terminals by coding agent
+
+Stop and remove every terminal of one coding CLI in the front workspace. Use only when the user explicitly asks to close all Claude Code or all Codex terminals; this is destructive and requires confirmation.
+
+- **Endpoint:** `DELETE /api/agentic-ide/terminals/agent/{agent}`
+- **Arguments:** `agent` (one of: claude, codex; required)
+- **Requires confirmation:** yes
+- **Desktop UI section:** `agentic-ide`
+- **Voice example (EN):** "close all codex terminals"
+
## `agentic-ide-focus` — Toggle Agentic-IDE focus mode
Turn the focused coding mode on or off. While on, answers are given inside the open coding workspace; turning it off returns to normal behaviour without stopping any agent.
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index a3ae3c8281..280280d8ec 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -113,6 +113,13 @@ AGENT_DISPLAY: dict[str, str] = {"claude": "Claude Code", "codex": "Codex"}
# Nobody reaches 100 deliberately; anyone who mistypes their way past it gets a
# sentence instead of a frozen desktop.
MAX_TERMINALS = 100
+# 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
+# round and nothing else about the arrangement should change. The four sides are
+# the same placements the split buttons already express — the difference is that
+# these move a pane that exists instead of opening one.
+MOVE_POSITIONS = ("swap", "left", "right", "above", "below")
# Transport ceiling for one injected prompt. Raised from 4000 once composed
# prompts became structured briefs that describe the code they point at: at
# 4000 the cap, not the writer, was deciding where a brief ended. Bracketed
@@ -2166,6 +2173,84 @@ class Registry:
break
return created, len(created) < wanted
+ async def move_terminal(
+ self, wanted: str, *, target: str, position: str = "swap"
+ ) -> Terminal:
+ """Put an existing pane somewhere else in the grid.
+
+ The rearranging half of the two-axis model ``add_terminal`` builds: no
+ agent is started or stopped here, no PTY is touched, and no pane is
+ remounted — only the two numbers that say where a pane is drawn change.
+ That is precisely why rearranging is safe to offer at all. A workspace of
+ a dozen agents is assembled one split at a time and ends up in an order
+ nobody chose; without this the only way to fix it was to close a working
+ agent and open it again somewhere else.
+
+ ``position`` says what the drop meant, relative to ``target``:
+
+ * ``"swap"`` — the two panes exchange places. The one move that keeps the
+ grid's shape exactly as it was, which is what "these two are the wrong
+ way round" asks for.
+ * ``"left"`` / ``"right"`` — the pane becomes a column of its own on that
+ side of the target; every column from there rightwards shifts over.
+ * ``"above"`` / ``"below"`` — the pane joins the target's OWN column at
+ that place, and only that column's stack moves.
+
+ Dropping a pane on itself is a no-op rather than an error: it is what a
+ user who changed their mind mid-drag does, and refusing it would turn a
+ cancelled gesture into a red banner.
+ """
+ async with self._lock:
+ session = self.session
+ if session is None:
+ raise SessionError("No Agentic-IDE session is running.")
+ if position not in MOVE_POSITIONS:
+ allowed = ", ".join(f"'{item}'" for item in MOVE_POSITIONS)
+ raise SessionError(f"Position must be one of {allowed}.")
+
+ known = ", ".join(t.name for t in session.terminals) or "none"
+ moved = session.find(wanted)
+ if moved is None:
+ raise SessionError(f"No terminal called {wanted!r}. Running: {known}.")
+ anchor = session.find(target)
+ if anchor is None:
+ raise SessionError(f"No terminal called {target!r}. Running: {known}.")
+ if anchor.key == moved.key:
+ return moved
+
+ if position == "swap":
+ moved.column, anchor.column = anchor.column, moved.column
+ moved.slot, anchor.slot = anchor.slot, moved.slot
+ elif position in ("left", "right"):
+ # A column of its own beside the target. The moved pane is left
+ # out of the shift — it is being placed, not pushed — and the
+ # column it vacates is closed by `_renumber` below, so a pane
+ # that was already on that side lands exactly where it started.
+ column = anchor.column if position == "left" else anchor.column + 1
+ for other in session.terminals:
+ if other is not moved and other.column >= column:
+ other.column += 1
+ moved.column, moved.slot = column, 0
+ else:
+ # Into the target's own stack. Every other column stays put —
+ # the same property that makes "split down" a real split.
+ column = anchor.column
+ slot = anchor.slot if position == "above" else anchor.slot + 1
+ for other in session.terminals:
+ if other is not moved and other.column == column and other.slot >= slot:
+ other.slot += 1
+ moved.column, moved.slot = column, slot
+
+ self._renumber(session)
+ await self._persist()
+ logger.info(
+ "Agentic IDE: moved terminal {} {} {}",
+ moved.name,
+ position,
+ anchor.name,
+ )
+ return moved
+
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])
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index d5c718d61c..1d5ae52054 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -750,6 +750,78 @@ def _build_registry() -> tuple[AppCommand, ...]:
"es": ("abre dos terminales de codex",), # i18n-allow: input vocab
},
),
+ AppCommand(
+ id="agentic-ide-move-terminal",
+ title="Move an Agentic-IDE terminal in the grid",
+ description=(
+ "Rearrange the open workspace: put one terminal at another "
+ "one's place. Nothing is started or stopped — the panes keep "
+ "their agents and their conversations, only where they are "
+ "drawn changes. Use it for 'swap Mika and Nova', 'put Mika "
+ "next to Nova', 'move Mika under Nova'. "
+ "'swap' exchanges the two panes and leaves the rest of the grid "
+ "alone; 'left'/'right' give the moved pane its own column beside "
+ "the target; 'above'/'below' stack it in the target's column. "
+ "Both names must be terminals that are already open."
+ ),
+ method="POST",
+ path="/api/agentic-ide/terminals/{name}/move",
+ params={
+ "type": "object",
+ "properties": {
+ "name": _str_param(
+ "Call-sign of the terminal to move, e.g. 'Mika'.",
+ min_length=1,
+ ),
+ "target": _str_param(
+ "Call-sign of the terminal it should move to, e.g. 'Nova'.",
+ min_length=1,
+ ),
+ "position": _str_param(
+ "Where it lands relative to the target.",
+ enum=["swap", "left", "right", "above", "below"],
+ ),
+ },
+ "required": ["name", "target"],
+ },
+ path_params=("name",),
+ ui_section="agentic-ide",
+ voice_aliases={
+ "de": ("tausche mika und nova",), # i18n-allow: input vocab
+ "en": ("swap mika and nova",),
+ "es": ("intercambia mika y nova",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="agentic-ide-close-agent-terminals",
+ title="Close Agentic-IDE terminals by coding agent",
+ description=(
+ "Stop and remove every terminal of one coding CLI in the front "
+ "workspace. Use only when the user explicitly asks to close all "
+ "Claude Code or all Codex terminals; this is destructive and "
+ "requires confirmation."
+ ),
+ method="DELETE",
+ path="/api/agentic-ide/terminals/agent/{agent}",
+ params={
+ "type": "object",
+ "properties": {
+ "agent": _str_param(
+ "Coding agent whose terminals should be closed.",
+ enum=["claude", "codex"],
+ ),
+ },
+ "required": ["agent"],
+ },
+ path_params=("agent",),
+ dangerous=True,
+ ui_section="agentic-ide",
+ voice_aliases={
+ "de": ("schließe alle codex terminals",), # i18n-allow: input vocab
+ "en": ("close all codex terminals",),
+ "es": ("cierra todas las terminales de codex",), # i18n-allow: input vocab
+ },
+ ),
AppCommand(
id="agentic-ide-focus",
title="Toggle Agentic-IDE focus mode",
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 6b10554087..e64f67779f 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -189,6 +189,23 @@ class AddTerminalsRequest(BaseModel):
account: str | None = Field(default=None, description=_ACCOUNT_FIELD_DESCRIPTION)
+class MoveTerminalRequest(BaseModel):
+ """Where an existing pane should be drawn from now on."""
+
+ target: str = Field(
+ min_length=1,
+ description="Call-sign of the pane it was dropped on, e.g. 'Mika'.",
+ )
+ position: str = Field(
+ default="swap",
+ description=(
+ "'swap' exchanges the two panes and keeps the grid's shape; "
+ "'left'/'right' give the moved pane its own column beside the "
+ "target; 'above'/'below' put it in the target's own column."
+ ),
+ )
+
+
class CloseTerminalsRequest(BaseModel):
"""The terminal panes one destructive batch action should stop."""
@@ -1356,6 +1373,81 @@ async def add_terminals(request: Request, req: AddTerminalsRequest) -> dict:
}
[email protected]("/terminals/{name}/move", summary="Move a terminal to another place in the grid")
+async def move_terminal(name: str, req: MoveTerminalRequest) -> dict:
+ """Rearrange the workspace: put the pane ``name`` at ``target``'s place.
+
+ Nothing is started or stopped — this only changes where a running pane is
+ drawn, which is what makes rearranging safe on a grid full of working
+ agents. ``position="swap"`` exchanges the two panes and leaves the grid's
+ shape untouched; ``"left"``/``"right"`` give the moved pane a column of its
+ own beside the target; ``"above"``/``"below"`` put it into the target's own
+ column, moving only that stack.
+
+ Dropping a pane onto itself succeeds and changes nothing.
+ """
+ try:
+ term = await get_registry().move_terminal(
+ name, target=req.target, position=req.position
+ )
+ except SessionError as exc:
+ # Three different fixes on the caller's side, so three different codes:
+ # a position this grid cannot express is a bad request, a workspace that
+ # is not open is a conflict, and everything left is an unknown call-sign.
+ message = str(exc)
+ if "Position must be" in message:
+ status = 422
+ elif "No Agentic-IDE session" in message:
+ status = 409
+ else:
+ status = 404
+ raise HTTPException(status_code=status, detail=message) from exc
+ return {
+ "ok": True,
+ "moved": term.name,
+ "target": req.target,
+ "position": req.position,
+ "terminal": term.to_dict(),
+ "state": get_registry().state(),
+ }
+
+
+ "/terminals/agent/{agent}",
+ summary="Close every terminal of one coding agent",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def close_terminals_by_agent(request: Request, agent: str) -> dict:
+ """Stop every pane running one thing — a coding CLI, or the plain terminal."""
+ chosen = agent.casefold().strip()
+ if chosen not in AGENT_DISPLAY:
+ known = ", ".join(f"'{name}'" for name in AGENT_DISPLAY)
+ raise HTTPException(status_code=422, detail=f"Agent must be one of {known}.")
+ registry = get_registry()
+ session = registry.session
+ if session is None:
+ raise HTTPException(status_code=409, detail="No Agentic-IDE session is running.")
+ closed = await close_agent_terminals(registry, chosen)
+ bus = getattr(request.app.state, "bus", None)
+ if bus is not None and closed:
+ try:
+ await bus.publish(
+ terminals_closed_event(
+ session,
+ closed,
+ source_layer="agentic_ide_routes",
+ )
+ )
+ except Exception as exc: # noqa: BLE001 - the panes are already closed
+ log.debug("AgenticIdeTerminalsClosed publish failed: %s", exc)
+ return {
+ "ok": True,
+ "agent": chosen,
+ "closed": [term.name for term in closed],
+ "state": registry.state(),
+ }
+
+
@router.delete(
"/terminals/{name}",
summary="Close one terminal",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index e7364cc2e3..7a3e20778f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -887,6 +887,9 @@ function PaneHeader({
/** The agent in this pane has exited or failed — offer to start it again. */
dead: boolean;
onRestart?: () => void;
+ /** Press on the header picks the pane up; absent leaves it undraggable. */
+ onArrangeStart?: (event: React.PointerEvent) => void;
+ arranging?: boolean;
}) {
const light = appearance === "light";
// Which split button opened the CLI picker, if any.
@@ -904,10 +907,40 @@ function PaneHeader({
return (
<header
- className="group/header relative flex items-center justify-between gap-1.5 border-b px-2 py-1"
+ data-testid={`pane-header-${name}`}
+ // The grip. It is the header itself rather than a separate handle icon,
+ // because that is where the gesture is already expected — every window on
+ // every desktop is dragged by its title bar.
+ //
+ // The press is ignored when it lands on one of the header's own controls:
+ // the buttons stop `mousedown`, which says nothing about `pointerdown`, so
+ // without this check pressing Close would also pick the pane up and a
+ // twitchy hand would move a pane it meant to shut.
+ onPointerDown={
+ onArrangeStart
+ ? (event) => {
+ const target = event.target as HTMLElement | null;
+ if (target?.closest("button, a, input, [role='menuitem']")) return;
+ onArrangeStart(event);
+ }
+ : undefined
+ }
+ title={
+ onArrangeStart
+ ? `Drag ${name} by this bar to move it — drop it on another terminal to swap, or near an edge to place it there`
+ : undefined
+ }
+ className={cn(
+ "group/header relative flex items-center justify-between gap-1.5 border-b px-2 py-1",
+ onArrangeStart && (arranging ? "cursor-grabbing" : "cursor-grab"),
+ )}
style={{
borderColor: PANE_CHROME[appearance].border,
background: light ? "rgba(0,0,0,0.025)" : "rgba(255,255,255,0.03)",
+ // Claims the touch gesture for the drag. Without it a touch that starts
+ // on the header scrolls the workspace instead of lifting the pane, and
+ // the drag never begins at all.
+ touchAction: onArrangeStart ? "none" : undefined,
}}
>
<div className="flex min-w-0 flex-1 items-center gap-2">
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneArrange.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneArrange.test.ts
new file mode 100644
index 0000000000..012e12d762
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneArrange.test.ts
@@ -0,0 +1,84 @@
+/**
+ * What a drop MEANS — the half of pane dragging that can be wrong silently.
+ *
+ * Every failure here looks like the grid ignoring the user: a corner that
+ * resolves to the wrong edge puts a pane one column off, and a centre zone that
+ * is too small turns "swap these two" into "move it to the left of that one",
+ * which rearranges the whole row instead of exchanging two panes.
+ */
+import { describe, expect, it } from "vitest";
+
+import { pickTarget, zoneFor, type PaneRect } from "./paneArrange";
+
+/** A 200×100 pane at the origin — round numbers so the fractions are readable. */
+const RECT: PaneRect = { left: 0, top: 0, width: 200, height: 100 };
+
+describe("zoneFor", () => {
+ it("reads the middle of a pane as a swap", () => {
+ expect(zoneFor(RECT, 100, 50)).toBe("swap");
+ });
+
+ it("keeps the swap zone big enough to hit without aiming", () => {
+ // Anywhere in the middle 40 % × 40 %, which is a large target on purpose:
+ // swapping two panes is the move people reach for.
+ expect(zoneFor(RECT, 65, 35)).toBe("swap");
+ expect(zoneFor(RECT, 135, 65)).toBe("swap");
+ });
+
+ it("reads each edge as a placement on that side", () => {
+ expect(zoneFor(RECT, 5, 50)).toBe("left");
+ expect(zoneFor(RECT, 195, 50)).toBe("right");
+ expect(zoneFor(RECT, 100, 3)).toBe("above");
+ expect(zoneFor(RECT, 100, 97)).toBe("below");
+ });
+
+ it("resolves a corner to the edge it is actually nearer", () => {
+ // 4 % across, 20 % down: closer to the left edge than to the top one.
+ expect(zoneFor(RECT, 8, 20)).toBe("left");
+ // 20 % across, 4 % down: the other way round.
+ expect(zoneFor(RECT, 40, 4)).toBe("above");
+ });
+
+ it("respects a pane that is not at the origin", () => {
+ const offset: PaneRect = { left: 500, top: 300, width: 200, height: 100 };
+ expect(zoneFor(offset, 600, 350)).toBe("swap");
+ expect(zoneFor(offset, 505, 350)).toBe("left");
+ });
+
+ it("falls back to swap for a pane with no measurable box", () => {
+ // A hidden pane cannot produce a sensible edge, and swap is the one answer
+ // that can never render an impossible layout.
+ expect(zoneFor({ left: 0, top: 0, width: 0, height: 0 }, 0, 0)).toBe("swap");
+ });
+});
+
+describe("pickTarget", () => {
+ const targets = [
+ { name: "Mika", rect: { left: 0, top: 0, width: 200, height: 100 } },
+ { name: "Nova", rect: { left: 200, top: 0, width: 200, height: 100 } },
+ ];
+
+ it("names the pane under the pointer and what a drop would do", () => {
+ expect(pickTarget(targets, "Mika", 300, 50)).toEqual({
+ target: "Nova",
+ zone: "swap",
+ });
+ });
+
+ it("never offers the pane that is being carried", () => {
+ // Hovering the pane in your hand is not a drop — offering one would put a
+ // highlight on the thing being dragged.
+ expect(pickTarget(targets, "Mika", 100, 50)).toBeNull();
+ });
+
+ it("answers nothing when the pointer is outside every pane", () => {
+ expect(pickTarget(targets, "Mika", 900, 900)).toBeNull();
+ });
+
+ it("skips panes that are not laid out", () => {
+ const hidden = [
+ { name: "Nova", rect: { left: 0, top: 0, width: 0, height: 0 } },
+ ];
+ expect(pickTarget(hidden, "Mika", 0, 0)).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneArrange.ts b/jarvis/ui/web/frontend/src/components/agentic/paneArrange.ts
new file mode 100644
index 0000000000..417b1396fb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/paneArrange.ts
@@ -0,0 +1,277 @@
+/**
+ * Picking a terminal up by its header and putting it somewhere else.
+ *
+ * A workspace is assembled one split at a time, so it ends up in whatever order
+ * the splits happened rather than the order the work is in. Until now the only
+ * way to fix that was to close a pane and open a new one somewhere else — which
+ * kills a working coding agent and its whole conversation. Dragging moves the
+ * pane instead: the same process, the same socket, two different numbers.
+ *
+ * ## Why pointer events and not HTML5 drag-and-drop
+ *
+ * The panes are already a drop target for FILES (see ./paneFileDrag), and the
+ * browser gives a page exactly one drag protocol — a second one over the same
+ * elements means every `dragover` has to decide which of the two gestures it is
+ * looking at, on a `DataTransfer` that deliberately hides its payload until the
+ * drop. Pointer events are a separate channel entirely, so dropping a screenshot
+ * onto a pane and dropping a PANE onto a pane can never be confused for one
+ * another. They also work with touch and pen for free, and let this file own the
+ * ghost and the highlight rather than negotiating a drag image with the browser.
+ *
+ * ## Why a threshold before the drag arms
+ *
+ * The header is also where the user clicks to focus a pane, and a mouse moves a
+ * pixel or two during an ordinary click. Arming immediately would turn every
+ * click on a header into a drag that lands back where it started — visually a
+ * flicker, and one mis-drop away from rearranging the grid by accident.
+ */
+import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
+
+/** Where a drop means the pane should go, relative to the pane under the cursor. */
+export type DropZone = "swap" | "left" | "right" | "above" | "below";
+
+/**
+ * How much of a pane's width/height each edge zone takes.
+ *
+ * 0.3 leaves the middle 40 % × 40 % as the swap zone, and swap is deliberately
+ * the biggest target: "these two are the wrong way round" is the move people
+ * actually reach for, and it is the only one that leaves the rest of the grid
+ * exactly as it was. The edges then still start well inside the pane, so hitting
+ * "put it to the left of this one" never requires pixel accuracy.
+ */
+export const EDGE_FRACTION = 0.3;
+
+/** Pixels the pointer must travel before a click on a header becomes a drag. */
+export const DRAG_THRESHOLD_PX = 5;
+
+/** The part of a rectangle this module needs — `DOMRect` satisfies it. */
+export interface PaneRect {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+/** Which drop a point inside ``rect`` means. */
+export function zoneFor(
+ rect: PaneRect,
+ x: number,
+ y: number,
+ edge: number = EDGE_FRACTION,
+): DropZone {
+ // A pane with no measurable box (hidden behind a maximized sibling, or not
+ // laid out yet) can still be pointed at in theory. Swap is the answer that
+ // cannot produce a nonsensical layout, so it is the fallback.
+ if (rect.width <= 0 || rect.height <= 0) return "swap";
+ const fx = (x - rect.left) / rect.width;
+ const fy = (y - rect.top) / rect.height;
+ const sides: Array<[DropZone, number]> = [
+ ["left", fx],
+ ["right", 1 - fx],
+ ["above", fy],
+ ["below", 1 - fy],
+ ];
+ // The nearest edge wins, which is what resolves the corners: a point in the
+ // top-left corner is closer to whichever of the two edges it is nearer to.
+ let best: [DropZone, number] = sides[0];
+ for (const side of sides) {
+ if (side[1] < best[1]) best = side;
+ }
+ return best[1] > edge ? "swap" : best[0];
+}
+
+/** A pane the drag can be dropped on, as measured right now. */
+export interface PaneTarget {
+ name: string;
+ rect: PaneRect;
+}
+
+/** What the pointer is currently over, if it is over anything droppable. */
+export interface ArrangeHover {
+ target: string;
+ zone: DropZone;
+}
+
+/**
+ * The pane under ``(x, y)`` and what dropping there would mean.
+ *
+ * The held pane is skipped rather than returning "you are over yourself":
+ * hovering the pane in your hand is not a drop, and offering one would put a
+ * highlight on the thing that is being dragged.
+ */
+export function pickTarget(
+ targets: readonly PaneTarget[],
+ held: string | null,
+ x: number,
+ y: number,
+): ArrangeHover | null {
+ for (const candidate of targets) {
+ if (candidate.name === held) continue;
+ const { rect } = candidate;
+ if (rect.width <= 0 || rect.height <= 0) continue;
+ if (
+ x >= rect.left &&
+ x <= rect.left + rect.width &&
+ y >= rect.top &&
+ y <= rect.top + rect.height
+ ) {
+ return { target: candidate.name, zone: zoneFor(rect, x, y) };
+ }
+ }
+ return null;
+}
+
+export interface PaneArrange {
+ /** Call-sign of the pane currently in hand, or null when nothing is held. */
+ held: string | null;
+ /** The pane under the cursor and what a drop there would do. */
+ hover: ArrangeHover | null;
+ /** Viewport coordinates of the cursor, for the label that follows it. */
+ point: { x: number; y: number } | null;
+ /** Start a drag — wired to the pane header's `pointerdown`. */
+ start: (name: string, event: ReactPointerEvent) => void;
+ /** Ref callback that lets a pane cell be measured as a drop target. */
+ registerCell: (name: string) => (element: HTMLElement | null) => void;
+}
+
+/**
+ * Track one pane drag from the header press to the drop.
+ *
+ * ``onDrop`` runs once, with the pane that was carried, the pane it was dropped
+ * on and what that drop meant. A drag that ends on nothing, on the pane itself,
+ * or on Escape reports nothing at all.
+ */
+export function usePaneArrange(
+ onDrop: (moved: string, target: string, zone: DropZone) => void,
+): PaneArrange {
+ const cells = useRef(new Map<string, HTMLElement>());
+ // One stable ref callback per pane. A fresh closure each render would make
+ // React detach and re-attach every cell on every render, so a pane could be
+ // unregistered at the exact moment a drag measures it.
+ const refCallbacks = useRef(new Map<string, (element: HTMLElement | null) => void>());
+ const pending = useRef<{ name: string; pointerId: number; x: number; y: number } | null>(
+ null,
+ );
+ const cleanup = useRef<(() => void) | null>(null);
+ // Mirrors of the state below, so the pointer handlers read the current values
+ // without being re-created (and re-registered) on every move.
+ const heldRef = useRef<string | null>(null);
+ const hoverRef = useRef<ArrangeHover | null>(null);
+ const onDropRef = useRef(onDrop);
+ onDropRef.current = onDrop;
+
+ const [held, setHeld] = useState<string | null>(null);
+ const [hover, setHover] = useState<ArrangeHover | null>(null);
+ const [point, setPoint] = useState<{ x: number; y: number } | null>(null);
+
+ const finish = useCallback((commit: boolean) => {
+ const moved = heldRef.current;
+ const drop = hoverRef.current;
+ cleanup.current?.();
+ cleanup.current = null;
+ pending.current = null;
+ heldRef.current = null;
+ hoverRef.current = null;
+ setHeld(null);
+ setHover(null);
+ setPoint(null);
+ // `moved` is null for a press that never crossed the threshold — an
+ // ordinary click on the header, which must stay an ordinary click.
+ if (commit && moved && drop && drop.target !== moved) {
+ onDropRef.current(moved, drop.target, drop.zone);
+ }
+ }, []);
+
+ const measure = useCallback((): PaneTarget[] => {
+ const rows: PaneTarget[] = [];
+ for (const [name, element] of cells.current) {
+ rows.push({ name, rect: element.getBoundingClientRect() });
+ }
+ return rows;
+ }, []);
+
+ const start = useCallback(
+ (name: string, event: ReactPointerEvent) => {
+ // Left button only. The right one opens the app's own context menu, and
+ // the middle one is a paste on some platforms — neither is a drag.
+ if (event.button !== 0) return;
+ // A drag already in flight (a second finger, a stuck pointer) is left
+ // alone rather than replaced halfway through.
+ if (pending.current) return;
+ pending.current = {
+ name,
+ pointerId: event.pointerId,
+ x: event.clientX,
+ y: event.clientY,
+ };
+
+ const onMove = (moveEvent: globalThis.PointerEvent) => {
+ const origin = pending.current;
+ if (!origin || moveEvent.pointerId !== origin.pointerId) return;
+ if (heldRef.current === null) {
+ const travelled = Math.hypot(
+ moveEvent.clientX - origin.x,
+ moveEvent.clientY - origin.y,
+ );
+ if (travelled < DRAG_THRESHOLD_PX) return;
+ heldRef.current = origin.name;
+ setHeld(origin.name);
+ }
+ // Stops the browser from turning the drag into a text selection that
+ // sweeps across every pane it crosses.
+ moveEvent.preventDefault();
+ setPoint({ x: moveEvent.clientX, y: moveEvent.clientY });
+ const next = pickTarget(
+ measure(),
+ heldRef.current,
+ moveEvent.clientX,
+ moveEvent.clientY,
+ );
+ hoverRef.current = next;
+ setHover(next);
+ };
+
+ const onUp = (upEvent: globalThis.PointerEvent) => {
+ if (upEvent.pointerId !== pending.current?.pointerId) return;
+ finish(true);
+ };
+ const onCancel = () => finish(false);
+ const onKey = (keyEvent: globalThis.KeyboardEvent) => {
+ if (keyEvent.key === "Escape") finish(false);
+ };
+ // Also a backstop: a pointerup delivered outside the window never
+ // arrives, and a pane would otherwise stay stuck to the cursor.
+ const onBlur = () => finish(false);
+
+ window.addEventListener("pointermove", onMove, { passive: false });
+ window.addEventListener("pointerup", onUp);
+ window.addEventListener("pointercancel", onCancel);
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("blur", onBlur);
+ cleanup.current = () => {
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", onUp);
+ window.removeEventListener("pointercancel", onCancel);
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("blur", onBlur);
+ };
+ },
+ [finish, measure],
+ );
+
+ // A workspace closed mid-drag would leave the listeners behind.
+ useEffect(() => () => cleanup.current?.(), []);
+
+ const registerCell = useCallback((name: string) => {
+ const existing = refCallbacks.current.get(name);
+ if (existing) return existing;
+ const callback = (element: HTMLElement | null) => {
+ if (element) cells.current.set(name, element);
+ else cells.current.delete(name);
+ };
+ refCallbacks.current.set(name, callback);
+ return callback;
+ }, []);
+
+ return { held, hover, point, start, registerCell };
+}
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 87ba8077a8..40ff0b39ca 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -692,6 +692,37 @@ export async function addTerminal(payload: {
return body.state.session;
}
+/** Where a dragged pane may land relative to the pane it was dropped on. */
+export type PaneMovePosition = "swap" | "left" | "right" | "above" | "below";
+
+/**
+ * Move a running pane to another place in the grid.
+ *
+ * Nothing is started or stopped — only the two numbers that say where a pane is
+ * drawn change, which is what makes rearranging safe on a grid full of working
+ * agents. The answer carries the whole workspace, so the grid redraws from this
+ * call alone rather than polling for the layout it just asked for.
+ */
+export async function moveTerminal(
+ name: string,
+ target: string,
+ position: PaneMovePosition = "swap",
+): Promise<SessionState> {
+ const res = await fetch(
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/move`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ target, position }),
+ },
+ );
+ 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 moving 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_move.py b/tests/unit/agentic_ide/test_pane_move.py
new file mode 100644
index 0000000000..ed04400d60
--- /dev/null
+++ b/tests/unit/agentic_ide/test_pane_move.py
@@ -0,0 +1,215 @@
+"""Rearranging panes that already exist — the drag-and-drop half of the grid.
+
+`add_terminal` decides where a NEW pane lands; this decides where a running one
+moves to, in the same two axes (columns of stacked panes). The arithmetic is
+pinned here because every failure mode is silent on screen: a pane that lands
+one column off looks like the grid ignored the drop, and a pane that collides
+with another leaves a blank stripe where an agent should be.
+
+Nothing here starts or stops an agent, which is the whole reason rearranging is
+offered at all — the last test says so explicitly.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import 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)])
+
+
+def _layout(registry: Registry) -> list[tuple[str, int, int]]:
+ """(name, column, slot) in render order — the shape the grid draws."""
+ return [(t.name, t.column, t.slot) for t in registry.session.terminals]
+
+
+async def _noop(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
+
+
+# ----------------------------------------------------------------------- swap
+async def test_swap_exchanges_two_panes_and_keeps_the_shape(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The move a user reaches for most: these two are the wrong way round."""
+ await _open(registry, tmp_path, 3)
+ await registry.move_terminal("Alex", target="Casey", position="swap")
+ assert _layout(registry) == [("Casey", 0, 0), ("Blake", 1, 0), ("Alex", 2, 0)]
+
+
+async def test_swap_works_between_a_stacked_pane_and_a_lone_one(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Columns of different heights: the two places trade, the stacks do not."""
+ await _open(registry, tmp_path, 2)
+ lower = await registry.add_terminal(anchor="Alex", direction="down")
+ assert _layout(registry) == [("Alex", 0, 0), (lower.name, 0, 1), ("Blake", 1, 0)]
+
+ await registry.move_terminal(lower.name, target="Blake", position="swap")
+ assert _layout(registry) == [("Alex", 0, 0), ("Blake", 0, 1), (lower.name, 1, 0)]
+
+
+# ------------------------------------------------------------ left and right
+async def test_moving_right_of_a_pane_puts_it_in_its_own_column(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 3)
+ await registry.move_terminal("Alex", target="Blake", position="right")
+ assert _layout(registry) == [("Blake", 0, 0), ("Alex", 1, 0), ("Casey", 2, 0)]
+
+
+async def test_moving_left_of_a_pane_shifts_that_column_over(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 3)
+ await registry.move_terminal("Casey", target="Blake", position="left")
+ assert _layout(registry) == [("Alex", 0, 0), ("Casey", 1, 0), ("Blake", 2, 0)]
+
+
+async def test_moving_to_the_side_it_is_already_on_changes_nothing(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The no-op drag must not walk a pane one column further every time."""
+ await _open(registry, tmp_path, 3)
+ await registry.move_terminal("Alex", target="Blake", position="left")
+ assert _layout(registry) == [("Alex", 0, 0), ("Blake", 1, 0), ("Casey", 2, 0)]
+
+
+async def test_pulling_a_stacked_pane_out_into_its_own_column(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The way back out of a stack — otherwise a split down is a one-way door."""
+ await _open(registry, tmp_path, 1)
+ lower = await registry.add_terminal(anchor="Alex", direction="down")
+ await registry.move_terminal(lower.name, target="Alex", position="right")
+ assert _layout(registry) == [("Alex", 0, 0), (lower.name, 1, 0)]
+
+
+# ----------------------------------------------------------- above and below
+async def test_moving_below_a_pane_joins_its_column(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Only the target's column moves; every other column keeps its height."""
+ await _open(registry, tmp_path, 3)
+ await registry.move_terminal("Casey", target="Alex", position="below")
+ assert _layout(registry) == [("Alex", 0, 0), ("Casey", 0, 1), ("Blake", 1, 0)]
+
+
+async def test_moving_above_a_pane_pushes_its_stack_down(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 2)
+ lower = await registry.add_terminal(anchor="Alex", direction="down")
+ await registry.move_terminal("Blake", target=lower.name, position="above")
+ assert _layout(registry) == [
+ ("Alex", 0, 0),
+ ("Blake", 0, 1),
+ (lower.name, 0, 2),
+ ]
+
+
+async def test_reordering_inside_one_column(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 1)
+ middle = await registry.add_terminal(anchor="Alex", direction="down")
+ bottom = await registry.add_terminal(anchor=middle.name, direction="down")
+
+ await registry.move_terminal("Alex", target=bottom.name, position="below")
+ assert _layout(registry) == [
+ (middle.name, 0, 0),
+ (bottom.name, 0, 1),
+ ("Alex", 0, 2),
+ ]
+
+
+async def test_emptying_a_column_repacks_the_grid(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A vacated column would otherwise render as a blank stripe."""
+ await _open(registry, tmp_path, 3)
+ await registry.move_terminal("Blake", target="Casey", position="below")
+ assert _layout(registry) == [("Alex", 0, 0), ("Casey", 1, 0), ("Blake", 1, 1)]
+
+
+# --------------------------------------------------------------- refusals
+async def test_dropping_a_pane_on_itself_changes_nothing(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """A cancelled gesture, not an error — it must not raise at the user."""
+ await _open(registry, tmp_path, 2)
+ await registry.move_terminal("Alex", target="Alex", position="right")
+ assert _layout(registry) == [("Alex", 0, 0), ("Blake", 1, 0)]
+
+
+async def test_an_unknown_pane_names_the_running_ones(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 2)
+ with pytest.raises(SessionError, match="Alex, Blake"):
+ await registry.move_terminal("Gandalf", target="Alex", position="swap")
+
+
+async def test_an_unknown_target_is_refused(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 2)
+ with pytest.raises(SessionError, match="Gandalf"):
+ await registry.move_terminal("Alex", target="Gandalf", position="swap")
+
+
+async def test_an_impossible_position_is_refused(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 2)
+ with pytest.raises(SessionError, match="Position must be"):
+ await registry.move_terminal("Alex", target="Blake", position="diagonally")
+
+
+async def test_moving_without_a_workspace_is_refused(registry: Registry) -> None:
+ with pytest.raises(SessionError, match="No Agentic-IDE session"):
+ await registry.move_terminal("Alex", target="Blake", position="swap")
+
+
+# ------------------------------------------------------------------- safety
+async def test_moving_a_pane_leaves_its_agent_running(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """The whole premise: rearranging is not a close-and-reopen."""
+ await _open(registry, tmp_path, 2)
+ await registry.attach("Alex", 80, 24, _noop, _noop_exit)
+ pty_id = registry.session.find("Alex").pty_id
+
+ await registry.move_terminal("Alex", target="Blake", position="right")
+
+ term = registry.session.find("Alex")
+ assert term.pty_id == pty_id, "the same PTY, so the same live agent"
+ assert pty_id not in fake_pty.closed
diff --git a/tests/unit/agentic_ide/test_pane_move_route.py b/tests/unit/agentic_ide/test_pane_move_route.py
new file mode 100644
index 0000000000..ad86c449db
--- /dev/null
+++ b/tests/unit/agentic_ide/test_pane_move_route.py
@@ -0,0 +1,135 @@
+"""`POST /api/agentic-ide/terminals/{name}/move` — the drop the grid reports.
+
+The placement arithmetic is pinned in ``test_pane_move.py``; what this file is
+about is the contract a client depends on: the answer carries the workspace as
+it now is (so the grid can redraw without a second read), and the three ways a
+move can be refused arrive as three different status codes — a caller that gets
+one code for "no such pane" and "no such direction" cannot tell the user which
+of the two to fix.
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agentic_ide import session as ide
+from jarvis.ui.web import agentic_ide_routes
+
+
+def client() -> TestClient:
+ ide.reset_registry()
+ app = FastAPI()
+ app.include_router(agentic_ide_routes.router)
+ with TestClient(app) as test_client:
+ yield test_client
+ ide.reset_registry()
+
+
+def _workspace(tmp_path, names: tuple[str, ...] = ("Mika", "Nova")) -> ide.Session:
+ """An open workspace of side-by-side panes, without spawning anything."""
+ registry = ide.get_registry()
+ session = ide.Session(
+ id="ide_test",
+ folder=str(tmp_path),
+ name="Test",
+ profile=ide.probe_project(tmp_path),
+ terminals=[
+ ide.Terminal(
+ key=name.lower(),
+ name=name,
+ agent="claude",
+ display_name="Claude Code",
+ index=index,
+ column=index,
+ slot=0,
+ )
+ for index, name in enumerate(names)
+ ],
+ created_at=0.0,
+ )
+ registry._sessions[session.id] = session # noqa: SLF001 - no spawn in a unit test
+ registry._active = session.id # noqa: SLF001
+ return session
+
+
+def _layout(body: dict) -> list[tuple[str, int, int]]:
+ return [
+ (term["name"], term["column"], term["slot"])
+ for term in body["state"]["session"]["terminals"]
+ ]
+
+
+def test_a_swap_answers_with_the_rearranged_workspace(client, tmp_path) -> None:
+ _workspace(tmp_path)
+
+ reply = client.post(
+ "/api/agentic-ide/terminals/Mika/move",
+ json={"target": "Nova", "position": "swap"},
+ )
+
+ assert reply.status_code == 200
+ body = reply.json()
+ assert body["moved"] == "Mika"
+ assert body["target"] == "Nova"
+ # The whole point of returning state: the grid redraws from this alone.
+ assert _layout(body) == [("Nova", 0, 0), ("Mika", 1, 0)]
+
+
+def test_position_defaults_to_swap(client, tmp_path) -> None:
+ """The plain "these two belong the other way round" drop needs no argument."""
+ _workspace(tmp_path)
+
+ body = client.post(
+ "/api/agentic-ide/terminals/Mika/move", json={"target": "Nova"}
+ ).json()
+
+ assert body["position"] == "swap"
+ assert _layout(body) == [("Nova", 0, 0), ("Mika", 1, 0)]
+
+
+def test_a_pane_can_be_moved_into_another_columns_stack(client, tmp_path) -> None:
+ _workspace(tmp_path, ("Mika", "Nova", "Robin"))
+
+ body = client.post(
+ "/api/agentic-ide/terminals/Robin/move",
+ json={"target": "Mika", "position": "below"},
+ ).json()
+
+ assert _layout(body) == [("Mika", 0, 0), ("Robin", 0, 1), ("Nova", 1, 0)]
+
+
+def test_an_unknown_pane_is_a_404_that_names_the_real_ones(client, tmp_path) -> None:
+ _workspace(tmp_path)
+
+ reply = client.post(
+ "/api/agentic-ide/terminals/Gandalf/move",
+ json={"target": "Nova", "position": "swap"},
+ )
+
+ assert reply.status_code == 404
+ assert "Mika, Nova" in reply.json()["detail"]
+
+
+def test_an_impossible_position_is_a_422(client, tmp_path) -> None:
+ """A different fix from a wrong name, so a different status."""
+ _workspace(tmp_path)
+
+ reply = client.post(
+ "/api/agentic-ide/terminals/Mika/move",
+ json={"target": "Nova", "position": "diagonally"},
+ )
+
+ assert reply.status_code == 422
+ assert "Position must be" in reply.json()["detail"]
+
+
+def test_moving_without_an_open_workspace_is_a_409(client) -> None:
+ reply = client.post(
+ "/api/agentic-ide/terminals/Mika/move",
+ json={"target": "Nova", "position": "swap"},
+ )
+
+ assert reply.status_code == 409