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): split a pane inside its own column, and pick the CLI

Ruben Lütkee8caf3f3f555
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 75ba29cae5..ae4b42faf0 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -203,11 +203,19 @@ class Terminal:
agent: str # "claude" | "codex"
display_name: str # "Claude Code"
index: int
- # Grid row this pane sits in. Panes sharing a row render side by side, which
- # is what "split right" produces; "split down" opens a new row. A full split
- # TREE (arbitrary nesting, draggable separators) is deliberately NOT modelled
- # — rows express both buttons the UI offers and stay readable.
- row: int = 0
+ # Where the pane sits in the grid, on TWO axes: the workspace is a
+ # left-to-right list of columns, and each column is a top-to-bottom stack.
+ # "Split right" opens a new column beside the anchor; "split down" adds a
+ # pane to the anchor's OWN column and leaves every other column alone.
+ #
+ # The second axis is load-bearing. With only a row number, "split down"
+ # could only mean "open a new row", and a row is window-wide by definition —
+ # so splitting one pane squashed every other pane to half height. A full
+ # split TREE (arbitrary nesting, draggable separators) is still deliberately
+ # NOT modelled: two axes express both buttons the UI offers and stay
+ # readable.
+ column: int = 0
+ slot: int = 0
status: Status = "pending"
pty_id: str | None = None
exit_code: int | None = None
@@ -227,7 +235,8 @@ class Terminal:
"agent": self.agent,
"display_name": self.display_name,
"index": self.index,
- "row": self.row,
+ "column": self.column,
+ "slot": self.slot,
"status": self.status,
"exit_code": self.exit_code,
"error": self.error,
@@ -385,6 +394,9 @@ class Registry:
agent=agent,
display_name=AGENT_DISPLAY.get(agent, agent),
index=index,
+ # A wizard-opened workspace is one row of columns; the
+ # user's own "split down" is what creates a stack.
+ column=index,
)
)
@@ -582,12 +594,14 @@ class Registry:
"""Open one more terminal in the running workspace.
``direction`` decides where it lands relative to ``anchor``:
- ``"right"`` joins the anchor's row (side by side), ``"down"`` opens a new
- row directly beneath it and pushes the rows below down. Without an anchor
- the new pane goes after the last one.
+ ``"right"`` opens a new column beside the anchor, ``"down"`` splits the
+ anchor's own column and stacks the new pane under it — leaving every
+ other column at full height. Without an anchor the new pane goes after
+ the last one.
The agent defaults to the anchor's, because splitting a Claude Code pane
- almost always means "another one of these".
+ usually means "another one of these" — but a caller may name any
+ installed agent, which is how the UI offers a choice of coding CLI.
"""
async with self._lock:
session = self._session
@@ -630,17 +644,22 @@ class Registry:
suffix += 1
if base is None:
- row = 0
- position = len(session.terminals)
+ column, slot = 0, 0
elif direction == "right":
- row = base.row
- position = session.terminals.index(base) + 1
+ # A new column of its own, immediately right of the anchor's;
+ # everything further right shifts one column over.
+ column, slot = base.column + 1, 0
+ for other in session.terminals:
+ if other.column >= column:
+ other.column += 1
else:
- row = base.row + 1
+ # Inside the anchor's column, directly beneath it. No other
+ # column is touched — that is what makes this a real split
+ # rather than a new window-wide row.
+ column, slot = base.column, base.slot + 1
for other in session.terminals:
- if other.row >= row:
- other.row += 1
- position = session.terminals.index(base) + 1
+ if other.column == column and other.slot >= slot:
+ other.slot += 1
term = Terminal(
key=normalize(final) or f"t{len(session.terminals)}",
@@ -648,9 +667,10 @@ class Registry:
agent=chosen,
display_name=AGENT_DISPLAY.get(chosen, chosen),
index=len(session.terminals),
- row=row,
+ column=column,
+ slot=slot,
)
- session.terminals.insert(position, term)
+ session.terminals.append(term)
self._renumber(session)
logger.info(
"Agentic IDE: added terminal {} ({}) {} of {}",
@@ -661,6 +681,44 @@ class Registry:
)
return term
+ async def add_terminals(
+ self, count: int, *, agent: str | None = None
+ ) -> tuple[list[Terminal], bool]:
+ """Open up to ``count`` more panes — the batch behind "open five more".
+
+ Returns the panes that were created and whether the workspace cap
+ truncated the request, because those are two different answers the caller
+ has to speak out loud: five requested with three opened is a success the
+ user must hear ("room for three"), not a silent partial.
+
+ Deliberately a loop over ``add_terminal`` rather than a second placement
+ implementation: the anchor, the call-sign pool, and the grid position are
+ already decided there, and a batch that placed panes its own way would
+ drift from what the split buttons do.
+
+ The cap is the expected stopping point, so hitting it is not an error.
+ A failure with NOTHING opened is — an unknown agent or a vanished binary
+ must not be reported as "nothing to do".
+ """
+ if self._session is None:
+ raise SessionError("No Agentic-IDE session is running.")
+ wanted = max(1, int(count))
+ created: list[Terminal] = []
+ for _ in range(wanted):
+ try:
+ created.append(await self.add_terminal(agent=agent))
+ except SessionError as exc:
+ if not created:
+ raise
+ logger.info(
+ "Agentic IDE: batch stopped after {} of {} panes: {}",
+ len(created),
+ wanted,
+ exc,
+ )
+ break
+ return created, len(created) < wanted
+
async def close_terminal(self, wanted: str) -> Terminal:
"""Stop one terminal's agent and remove its pane from the workspace."""
async with self._lock:
@@ -686,16 +744,24 @@ class Registry:
@staticmethod
def _renumber(session: Session) -> None:
- """Re-pack indexes and rows after an insert or a removal.
+ """Re-pack the grid after an insert or a removal.
- Removing the only pane of a row would otherwise leave a gap in the row
- numbers and the grid would render an empty band.
+ Three things at once, all of them about not leaking holes into the UI:
+ the terminal list is sorted back into reading order (left to right, top
+ to bottom), column numbers are packed so emptying a column does not
+ render as a blank stripe, and each column's slots are packed so closing
+ the middle of a stack does not leave a gap in it.
"""
- rows = sorted({t.row for t in session.terminals})
- remap = {old: new for new, old in enumerate(rows)}
+ session.terminals.sort(key=lambda t: (t.column, t.slot))
+
+ columns = sorted({t.column for t in session.terminals})
+ remap = {old: new for new, old in enumerate(columns)}
+ next_slot: dict[int, int] = {}
for position, term in enumerate(session.terminals):
term.index = position
- term.row = remap.get(term.row, 0)
+ term.column = remap.get(term.column, 0)
+ term.slot = next_slot.get(term.column, 0)
+ next_slot[term.column] = term.slot + 1
# --------------------------------------------------------------- prompt
async def send_prompt(self, wanted: str, text: str) -> Terminal:
@@ -802,6 +868,28 @@ class Registry:
return data
+def terminals_added_event(
+ session: Session, created: list[Terminal], *, source_layer: str
+) -> Any:
+ """The bus event announcing new panes to every connected client.
+
+ A free function rather than a registry call, because the registry has no bus:
+ it is a plain in-process holder, and reaching for a process-wide bus from
+ inside it would be the lateral dependency the architecture forbids. The two
+ callers that DO hold one (the REST route and the voice fast-path) build the
+ event here so both send exactly the same payload.
+ """
+ from jarvis.core.events import AgenticIdeTerminalsAdded
+
+ return AgenticIdeTerminalsAdded(
+ session_id=session.id,
+ names=tuple(t.name for t in created),
+ agent=created[0].agent if created else "",
+ folder=session.folder,
+ source_layer=source_layer,
+ )
+
+
_REGISTRY: Registry | None = None
@@ -833,4 +921,5 @@ __all__ = [
"get_registry",
"reset_registry",
"sanitize_prompt",
+ "terminals_added_event",
]
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 5fd7638453..d2512b8a7a 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -83,7 +83,10 @@ class AddTerminalRequest(BaseModel):
)
direction: str = Field(
default="right",
- description="'right' places it beside the anchor, 'down' below it.",
+ description=(
+ "'right' opens a new column beside the anchor, 'down' splits the "
+ "anchor's own column and stacks the new pane under it."
+ ),
)
@@ -413,9 +416,11 @@ async def set_mode(req: ModeRequest) -> dict:
async def add_terminal(req: AddTerminalRequest) -> dict:
"""Add a terminal to the running workspace, beside or below another one.
- ``direction="right"`` puts it in the same grid row as ``anchor`` (side by
- side); ``"down"`` opens a new row underneath. The agent defaults to the
- anchor's, since splitting a pane usually means "another one of these".
+ ``direction="right"`` opens a new column beside ``anchor``; ``"down"``
+ splits the anchor's own column and stacks the new pane underneath it,
+ leaving every other column untouched. The agent defaults to the anchor's,
+ since splitting a pane usually means "another one of these" — pass ``agent``
+ to run a different coding CLI in the new pane.
"""
try:
term = await get_registry().add_terminal(
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 6a6a473d0a..142d4be6d0 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -1,6 +1,18 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+// jsdom has no layout observer. The grid only needs the callback in a real
+// browser; a no-op keeps its initial layout deterministic in component tests.
+class ResizeObserverPolyfill {
+ constructor(_callback: ResizeObserverCallback) {}
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+if (typeof globalThis.ResizeObserver === "undefined") {
+ globalThis.ResizeObserver = ResizeObserverPolyfill;
+}
+
const pushToast = vi.fn();
vi.mock("@/store/events", () => ({
useEventStore: (selector: (s: Record<string, unknown>) => unknown) =>
@@ -13,6 +25,12 @@ vi.mock("@/lib/agenticIdeApi", () => ({
promptTerminal: vi.fn(),
}));
+// The grid follows the app theme for its terminal colours; these tests render
+// it outside the provider, so the hook is stubbed rather than the whole app.
+vi.mock("@/hooks/useTheme", () => ({
+ useThemeValue: () => "dark",
+}));
+
/**
* xterm needs a real canvas, so the pane is stubbed — but the stub exposes the
* same action buttons, because what these tests check is the WIRING: which call
@@ -23,20 +41,29 @@ vi.mock("./AgenticTerminal", () => ({
name,
maximized,
splitDisabled,
+ restartToken,
+ onRestart,
+ agents,
onToggleMaximize,
- onSplitRight,
- onSplitDown,
+ onSplit,
onClose,
}: {
name: string;
maximized?: boolean;
splitDisabled?: boolean;
+ restartToken?: number;
+ onRestart?: () => void;
+ agents?: Array<{ name: string }>;
onToggleMaximize?: () => void;
- onSplitRight?: () => void;
- onSplitDown?: () => void;
+ onSplit?: (direction: "right" | "down", agent?: string) => void;
onClose?: () => void;
}) => (
- <div data-testid={`pane-${name}`} data-maximized={maximized ? "yes" : "no"}>
+ <div
+ data-testid={`pane-${name}`}
+ data-maximized={maximized ? "yes" : "no"}
+ data-agents={(agents ?? []).map((a) => a.name).join(",")}
+ data-restart-token={String(restartToken ?? 0)}
+ >
{name}
<button data-testid={`pane-maximize-${name}`} onClick={onToggleMaximize}>
max
@@ -44,20 +71,32 @@ vi.mock("./AgenticTerminal", () => ({
<button
data-testid={`pane-split-right-${name}`}
disabled={splitDisabled}
- onClick={onSplitRight}
+ onClick={() => onSplit?.("right")}
>
right
</button>
<button
data-testid={`pane-split-down-${name}`}
disabled={splitDisabled}
- onClick={onSplitDown}
+ onClick={() => onSplit?.("down")}
>
down
</button>
+ {/* The pane's own CLI picker lives in AgenticTerminal; here it stands for
+ "the user chose a specific agent for this split". */}
+ <button
+ data-testid={`pane-split-down-codex-${name}`}
+ disabled={splitDisabled}
+ onClick={() => onSplit?.("down", "codex")}
+ >
+ down as codex
+ </button>
<button data-testid={`pane-close-${name}`} onClick={onClose}>
close
</button>
+ <button data-testid={`pane-restart-${name}`} onClick={onRestart}>
+ restart
+ </button>
</div>
),
PaneStatusPill: () => <span>live</span>,
@@ -67,14 +106,16 @@ import { AgenticGrid } from "./AgenticGrid";
import * as api from "@/lib/agenticIdeApi";
import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";
-function pane(name: string, row: number, index: number): TerminalState {
+/** One pane at (column, slot) — the workspace is columns of stacked panes. */
+function pane(name: string, column: number, slot: number, index: number): TerminalState {
return {
key: name.toLowerCase(),
name,
agent: "claude",
display_name: "Claude Code",
index,
- row,
+ column,
+ slot,
status: "live",
exit_code: null,
error: "",
@@ -87,7 +128,8 @@ function pane(name: string, row: number, index: number): TerminalState {
};
}
-function sessionWith(panes: Array<[string, number]>): SessionState {
+/** `panes` are [name, column, slot] triples; slot defaults to 0 (one row). */
+function sessionWith(panes: Array<[string, number] | [string, number, number]>): SessionState {
return {
id: "ide_test",
folder: "/work/project",
@@ -107,21 +149,21 @@ function sessionWith(panes: Array<[string, number]>): SessionState {
},
created_at: 0,
focus_mode: false,
- terminals: panes.map(([name, row], i) => pane(name, row, i)),
+ terminals: panes.map(([name, column, slot], i) => pane(name, column, slot ?? 0, i)),
};
}
const BASE = sessionWith([
["Mika", 0],
- ["Nova", 0],
+ ["Nova", 1],
]);
beforeEach(() => {
vi.mocked(api.addTerminal).mockResolvedValue(
sessionWith([
["Mika", 0],
- ["Aria", 0],
- ["Nova", 0],
+ ["Aria", 1],
+ ["Nova", 2],
]),
);
vi.mocked(api.closeTerminal).mockResolvedValue(sessionWith([["Nova", 0]]));
@@ -134,21 +176,22 @@ afterEach(() => {
function renderGrid(session = BASE, extra: Record<string, unknown> = {}) {
const onSessionChanged = vi.fn();
+ const onClose = vi.fn();
render(
<AgenticGrid
session={session}
focusMode={false}
onToggleFocus={vi.fn()}
- onClose={vi.fn()}
+ onClose={onClose}
onSessionChanged={onSessionChanged}
{...extra}
/>,
);
- return { onSessionChanged };
+ return { onSessionChanged, onClose };
}
describe("pane actions", () => {
- it("splitting right asks for a pane in the same row", async () => {
+ it("splitting right asks for a column beside the anchor", async () => {
const { onSessionChanged } = renderGrid();
fireEvent.click(screen.getByTestId("pane-split-right-Mika"));
await waitFor(() =>
@@ -160,17 +203,44 @@ describe("pane actions", () => {
await waitFor(() => expect(onSessionChanged).toHaveBeenCalled());
});
- it("splitting down asks for a new row", async () => {
+ it("splitting down asks to split the anchor's own column", async () => {
renderGrid();
fireEvent.click(screen.getByTestId("pane-split-down-Nova"));
await waitFor(() =>
expect(api.addTerminal).toHaveBeenCalledWith({
anchor: "Nova",
direction: "down",
+ agent: undefined,
}),
);
});
+ it("passes the CLI the user picked through to the new pane", async () => {
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-split-down-codex-Nova"));
+ await waitFor(() =>
+ expect(api.addTerminal).toHaveBeenCalledWith({
+ anchor: "Nova",
+ direction: "down",
+ agent: "codex",
+ }),
+ );
+ });
+
+ it("offers every known CLI to the panes, installed or not", () => {
+ // The pane disables the uninstalled ones rather than hiding them, so the
+ // grid hands over the whole list.
+ renderGrid(BASE, {
+ agents: [
+ { name: "claude", displayName: "Claude Code", installed: true },
+ { name: "codex", displayName: "Codex", installed: false },
+ ],
+ });
+ expect(screen.getByTestId("pane-Mika").getAttribute("data-agents")).toBe(
+ "claude,codex",
+ );
+ });
+
it("a new pane becomes the prompt target", async () => {
renderGrid();
fireEvent.click(screen.getByTestId("pane-split-right-Mika"));
@@ -206,6 +276,74 @@ describe("pane actions", () => {
});
});
+describe("grid layout", () => {
+ /** The one grid container every pane is a direct child of. */
+ function gridEl(): HTMLElement {
+ const cell = screen.getAllByTestId(/^pane-cell-/)[0];
+ const container = cell.parentElement;
+ if (!container) throw new Error("no grid container");
+ return container;
+ }
+
+ /** The inline style of a pane's cell, as written (jsdom keeps it verbatim). */
+ function cellStyle(name: string): string {
+ return screen.getByTestId(`pane-cell-${name}`).getAttribute("style") ?? "";
+ }
+
+ it("puts a fresh workspace side by side in one row", () => {
+ renderGrid(sessionWith([["Mika", 0], ["Nova", 1], ["Aria", 2], ["Kai", 3]]));
+ expect(gridEl().style.gridTemplateColumns).toBe("repeat(4, minmax(0, 1fr))");
+ expect(gridEl().style.gridTemplateRows).toBe("repeat(1, minmax(0, 1fr))");
+ });
+
+ it("a downward split takes only its OWN column, not the whole width", () => {
+ // The reported bug: splitting one pane used to open a window-wide row and
+ // squash every other pane to half height. Nova's column holds two panes;
+ // Mika and Aria keep their full height beside it.
+ renderGrid(
+ sessionWith([
+ ["Mika", 0, 0],
+ ["Nova", 1, 0],
+ ["Vega", 1, 1],
+ ["Aria", 2, 0],
+ ]),
+ );
+ expect(gridEl().style.gridTemplateColumns).toBe("repeat(3, minmax(0, 1fr))");
+ expect(gridEl().style.gridTemplateRows).toBe("repeat(2, minmax(0, 1fr))");
+ expect(cellStyle("Mika")).toContain("grid-row: 1 / span 2");
+ expect(cellStyle("Aria")).toContain("grid-row: 1 / span 2");
+ expect(cellStyle("Nova")).toContain("grid-row: 1 / span 1");
+ expect(cellStyle("Vega")).toContain("grid-row: 2 / span 1");
+ // Both panes of the split share one column.
+ expect(cellStyle("Nova")).toContain("grid-column: 2");
+ expect(cellStyle("Vega")).toContain("grid-column: 2");
+ });
+
+ it("wraps a crowded workspace into two even bands", () => {
+ // 12 columns side by side are too narrow to read anything in, so they break
+ // into 6 above and 6 below.
+ const panes = Array.from({ length: 12 }, (_, i) => [`T${i + 1}`, i] as [string, number]);
+ renderGrid(sessionWith(panes));
+ expect(gridEl().style.gridTemplateColumns).toBe("repeat(6, minmax(0, 1fr))");
+ expect(cellStyle("T7")).toContain("grid-row: 2 / span 1");
+ // Same parent for every pane — a pane that moves to another parent element
+ // is remounted, and remounting kills the agent behind it.
+ expect(screen.getByTestId("pane-cell-T12").parentElement).toBe(
+ screen.getByTestId("pane-cell-T1").parentElement,
+ );
+ });
+
+ it("gives a maximized pane the whole grid", () => {
+ const panes = Array.from({ length: 12 }, (_, i) => [`T${i + 1}`, i] as [string, number]);
+ renderGrid(sessionWith(panes));
+ fireEvent.click(screen.getByTestId("pane-maximize-T3"));
+ // Without this the pane would stay in its one-sixth cell while the rest of
+ // the workspace is blank.
+ expect(cellStyle("T3")).toContain("grid-column: 1 / -1");
+ expect(cellStyle("T3")).toContain("grid-row: 1 / -1");
+ });
+});
+
describe("maximize", () => {
it("hides the other panes without unmounting them", () => {
// Unmounting would tear down the WebSocket and kill the agent, so the other
@@ -230,16 +368,17 @@ describe("maximize", () => {
);
});
- it("hides a whole row that holds no maximized pane", () => {
+ it("keeps a stacked pane mounted while another one is maximized", () => {
renderGrid(
sessionWith([
- ["Mika", 0],
- ["Nova", 1],
+ ["Mika", 0, 0],
+ ["Nova", 0, 1],
]),
);
fireEvent.click(screen.getByTestId("pane-maximize-Mika"));
- // Nova's entire row is hidden, not just the pane.
+ // Nova is hidden, never removed — removing it would kill its agent.
expect(screen.getByTestId("pane-Nova")).toBeTruthy();
+ expect(screen.getByTestId("pane-cell-Nova").className).toContain("hidden");
});
});
@@ -296,3 +435,81 @@ describe("closing a pane", () => {
expect(screen.getByRole("button", { name: /open a terminal/i })).toBeTruthy();
});
});
+
+describe("closing the workspace", () => {
+ it("asks before stopping every coding agent", () => {
+ const { onClose } = renderGrid();
+ fireEvent.click(screen.getByTitle("Close the workspace and stop every agent in it"));
+
+ expect(screen.getByTestId("confirm-close-workspace")).toBeTruthy();
+ expect(screen.getByText(/Close this workspace\?/i)).toBeTruthy();
+ expect(screen.getByText(/stops all 2 coding agents/i)).toBeTruthy();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it("cancelling leaves the workspace and every agent open", () => {
+ const { onClose } = renderGrid();
+ fireEvent.click(screen.getByTitle("Close the workspace and stop every agent in it"));
+ fireEvent.click(screen.getByRole("button", { name: /keep workspace open/i }));
+
+ expect(screen.queryByTestId("confirm-close-workspace")).toBeNull();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it("only requests shutdown after explicit confirmation", () => {
+ const { onClose } = renderGrid();
+ fireEvent.click(screen.getByTitle("Close the workspace and stop every agent in it"));
+ fireEvent.click(screen.getByTestId("confirm-close-workspace-confirm"));
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("escape safely cancels the workspace dialog", () => {
+ const { onClose } = renderGrid();
+ fireEvent.click(screen.getByTitle("Close the workspace and stop every agent in it"));
+ fireEvent.keyDown(screen.getByTestId("confirm-close-workspace"), { key: "Escape" });
+
+ expect(screen.queryByTestId("confirm-close-workspace")).toBeNull();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
+
+describe("restarting a dead pane", () => {
+ it("bumps only that pane's restart token", () => {
+ // An exited agent leaves a pane with nothing in it and no way back. The token
+ // is what reconnects it — and it must not disturb the neighbours, whose live
+ // agents would die with their sockets.
+ renderGrid();
+ const before = {
+ mika: screen.getByTestId("pane-Mika").getAttribute("data-restart-token"),
+ nova: screen.getByTestId("pane-Nova").getAttribute("data-restart-token"),
+ };
+ fireEvent.click(screen.getByTestId("pane-restart-Mika"));
+
+ expect(screen.getByTestId("pane-Mika").getAttribute("data-restart-token")).not.toBe(
+ before.mika,
+ );
+ expect(screen.getByTestId("pane-Nova").getAttribute("data-restart-token")).toBe(
+ before.nova,
+ );
+ });
+
+ it("can be used more than once", () => {
+ renderGrid();
+ const pane = () => screen.getByTestId("pane-Mika").getAttribute("data-restart-token");
+ const first = pane();
+ fireEvent.click(screen.getByTestId("pane-restart-Mika"));
+ const second = pane();
+ fireEvent.click(screen.getByTestId("pane-restart-Mika"));
+ expect(new Set([first, second, pane()]).size).toBe(3);
+ });
+
+ it("restarting does not touch the workspace on the server", () => {
+ // Reconnecting is a client-side act: the pane's socket closes and reopens, and
+ // the backend spawns a fresh agent for it. No pane is added or removed.
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-restart-Mika"));
+ expect(api.addTerminal).not.toHaveBeenCalled();
+ expect(api.closeTerminal).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index d01d1f944b..ddb8095d2f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -38,7 +38,7 @@
* redrawing on every keystroke that is both slow and subtly misaligned. The
* canvas renderer draws on a grid, which is what a terminal actually is.
*/
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { WebLinksAddon } from "@xterm/addon-web-links";
@@ -53,6 +53,7 @@ import {
Maximize2,
Minimize2,
Rows2,
+ RotateCcw,
X,
} from "lucide-react";
import { cn } from "@/lib/utils";
@@ -64,6 +65,17 @@ import {
export type PaneStatus = "connecting" | "live" | "exited" | "error";
+/** A coding CLI a split may start, as offered by the pane's split menu. */
+export interface SplitAgentChoice {
+ /** Backend id — "claude", "codex". */
+ name: string;
+ /** What the user reads — "Claude Code". */
+ displayName: string;
+ installed: boolean;
+}
+
+export type SplitDirection = "right" | "down";
+
interface AgenticTerminalProps {
/** Terminal call-sign — also the WS path segment. */
name: string;
@@ -78,14 +90,34 @@ interface AgenticTerminalProps {
/** True while this pane fills the whole grid. */
maximized?: boolean;
onToggleMaximize?: () => void;
- /** Open another terminal beside this one. */
- onSplitRight?: () => void;
- /** Open another terminal below this one. */
- onSplitDown?: () => void;
+ /**
+ * Open another terminal beside or below this one.
+ *
+ * `agent` is the coding CLI the user picked from the split menu; omitted, the
+ * new pane inherits this pane's agent.
+ */
+ onSplit?: (direction: SplitDirection, agent?: string) => void;
+ /**
+ * Coding CLIs the split menu offers. With one (or none) there is nothing to
+ * choose, so the split buttons act immediately instead of opening a menu.
+ */
+ agents?: SplitAgentChoice[];
/** Close this pane (the caller asks for confirmation first). */
onClose?: () => void;
/** Disable the split buttons — the workspace is at its terminal limit. */
splitDisabled?: boolean;
+ /** Called when the user asks a dead pane to start a fresh agent. */
+ onRestart?: () => void;
+ /**
+ * Bump to reconnect this pane.
+ *
+ * An exited agent leaves a dead pane with no way back: the connect effect runs
+ * on mount only (deliberately — see the file header), and remounting is not an
+ * option because it is what kills a LIVE agent. So the token is part of the
+ * effect's identity: changing it tears down this one socket and opens a fresh
+ * one, and the backend spawns a new agent for it.
+ */
+ restartToken?: number;
}
function socketUrl(name: string, cols: number, rows: number): string {
@@ -106,10 +138,12 @@ export function AgenticTerminal({
onStatus,
maximized = false,
onToggleMaximize,
- onSplitRight,
- onSplitDown,
+ onSplit,
+ agents,
onClose,
splitDisabled = false,
+ onRestart,
+ restartToken = 0,
}: AgenticTerminalProps) {
const containerRef = useRef<HTMLDivElement | null>(null);
const termRef = useRef<Terminal | null>(null);
@@ -118,6 +152,9 @@ export function AgenticTerminal({
// process together) without reaching into the connect effect's socket.
const resizeRef = useRef<(() => void) | null>(null);
const statusRef = useRef<PaneStatus>("connecting");
+ // Mirrored into state purely so the header can show/hide the restart button;
+ // it transitions a handful of times per pane, never per output chunk.
+ const [visibleStatus, setVisibleStatus] = useState<PaneStatus>("connecting");
// Latest callbacks/appearance without re-running the connect effect.
const onStatusRef = useRef(onStatus);
const initialRef = useRef({ appearance, fontSize });
@@ -194,6 +231,7 @@ export function AgenticTerminal({
const report = (status: PaneStatus, detail?: string) => {
statusRef.current = status;
+ setVisibleStatus(status);
onStatusRef.current?.(status, detail);
};
@@ -324,7 +362,7 @@ export function AgenticTerminal({
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
// appearance/fontSize must NOT rebuild the pane (it would kill the agent).
- }, [name]);
+ }, [name, restartToken]);
// Live restyle — no reconnect, so the running agent is untouched. The canvas
// renderer caches rendered glyphs per colour in a texture atlas, so a theme
@@ -367,14 +405,16 @@ export function AgenticTerminal({
data-testid={`agentic-pane-${name}`}
>
<PaneHeader
+ dead={visibleStatus === "exited" || visibleStatus === "error"}
+ onRestart={onRestart}
name={name}
displayName={displayName}
appearance={appearance}
focused={focused}
maximized={maximized}
onToggleMaximize={onToggleMaximize}
- onSplitRight={onSplitRight}
- onSplitDown={onSplitDown}
+ onSplit={onSplit}
+ agents={agents}
onClose={onClose}
splitDisabled={splitDisabled}
/>
@@ -390,10 +430,12 @@ function PaneHeader({
focused,
maximized,
onToggleMaximize,
- onSplitRight,
- onSplitDown,
+ onSplit,
+ agents,
onClose,
splitDisabled,
+ dead,
+ onRestart,
}: {
name: string;
displayName: string;
@@ -401,15 +443,31 @@ function PaneHeader({
focused: boolean;
maximized: boolean;
onToggleMaximize?: () => void;
- onSplitRight?: () => void;
- onSplitDown?: () => void;
+ onSplit?: (direction: SplitDirection, agent?: string) => void;
+ agents?: SplitAgentChoice[];
onClose?: () => void;
splitDisabled: boolean;
+ /** The agent in this pane has exited or failed — offer to start it again. */
+ dead: boolean;
+ onRestart?: () => void;
}) {
const light = appearance === "light";
+ // Which split button opened the CLI picker, if any.
+ const [picking, setPicking] = useState<SplitDirection | null>(null);
+
+ // With one installed CLI there is nothing to pick, so the button splits
+ // straight away — a menu with a single entry is a click tax, not a choice.
+ const choices = agents ?? [];
+ const offersChoice = choices.filter((a) => a.installed).length > 1;
+
+ const startSplit = (direction: SplitDirection) => {
+ if (offersChoice) setPicking((current) => (current === direction ? null : direction));
+ else onSplit?.(direction);
+ };
+
return (
<header
- className="group/header flex items-center justify-between gap-2 border-b px-3 py-2"
+ className="group/header relative flex items-center justify-between gap-2 border-b px-3 py-2"
style={{
borderColor: PANE_CHROME[appearance].border,
background: light ? "rgba(0,0,0,0.025)" : "rgba(255,255,255,0.03)",
@@ -448,6 +506,23 @@ function PaneHeader({
: "opacity-0 focus-within:opacity-100 group-hover/header:opacity-100",
)}
>
+ {dead && (
+ <button
+ type="button"
+ aria-label={`Restart ${name}`}
+ title={`Start a fresh ${displayName} in ${name}`}
+ data-testid={`pane-restart-${name}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ onRestart?.();
+ }}
+ onMouseDown={(e) => e.stopPropagation()}
+ className="mr-1 flex items-center gap-1 rounded bg-primary/20 px-2 py-0.5 text-[11px] font-medium text-primary transition-colors hover:bg-primary/30"
+ >
+ <RotateCcw className="h-3 w-3" />
+ Restart
+ </button>
+ )}
<PaneAction
label={maximized ? `Restore ${name}` : `Maximize ${name}`}
testId={`pane-maximize-${name}`}
@@ -461,16 +536,18 @@ function PaneHeader({
testId={`pane-split-right-${name}`}
light={light}
disabled={splitDisabled}
- onClick={onSplitRight}
+ expanded={offersChoice ? picking === "right" : undefined}
+ onClick={onSplit ? () => startSplit("right") : undefined}
>
<Columns2 className="h-3.5 w-3.5" />
</PaneAction>
<PaneAction
- label={`Open another terminal below ${name}`}
+ label={`Split ${name} and open a terminal below it`}
testId={`pane-split-down-${name}`}
light={light}
disabled={splitDisabled}
- onClick={onSplitDown}
+ expanded={offersChoice ? picking === "down" : undefined}
+ onClick={onSplit ? () => startSplit("down") : undefined}
>
<Rows2 className="h-3.5 w-3.5" />
</PaneAction>
@@ -484,16 +561,99 @@ function PaneHeader({
<X className="h-3.5 w-3.5" />
</PaneAction>
</div>
+
+ {picking && (
+ <SplitAgentMenu
+ paneName={name}
+ direction={picking}
+ agents={choices}
+ onDismiss={() => setPicking(null)}
+ onPick={(agent) => {
+ setPicking(null);
+ onSplit?.(picking, agent);
+ }}
+ />
+ )}
</header>
);
}
+/**
+ * The CLI picker a split button opens.
+ *
+ * Splitting used to inherit the anchor's agent silently, which made running a
+ * Codex pane next to a Claude Code one impossible from the grid — you had to
+ * close the workspace and start it again from the wizard. The backend always
+ * accepted an agent per terminal; this is the surface that finally asks.
+ *
+ * A CLI that is not installed stays listed but disabled, so the absence is
+ * visible and explains itself rather than the entry simply not being there.
+ */
+function SplitAgentMenu({
+ paneName,
+ direction,
+ agents,
+ onPick,
+ onDismiss,
+}: {
+ paneName: string;
+ direction: SplitDirection;
+ agents: SplitAgentChoice[];
+ onPick: (agent: string) => void;
+ onDismiss: () => void;
+}) {
+ return (
+ <>
+ {/* Click-anywhere-else to dismiss, without a global listener that would
+ outlive the pane. */}
+ <div className="fixed inset-0 z-40" onMouseDown={onDismiss} />
+ <div
+ role="menu"
+ aria-label={`Which CLI should run ${direction === "right" ? "beside" : "below"} ${paneName}?`}
+ data-testid={`pane-split-menu-${direction}-${paneName}`}
+ className="absolute right-2 top-full z-50 mt-1 w-56 rounded-lg border border-border bg-card p-1 shadow-xl"
+ onMouseDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") onDismiss();
+ }}
+ >
+ <p className="px-2 py-1.5 text-[11px] uppercase tracking-wider text-muted-foreground">
+ {direction === "right" ? "Open beside — which CLI?" : "Split below — which CLI?"}
+ </p>
+ {agents.map((agent) => (
+ <button
+ key={agent.name}
+ type="button"
+ role="menuitem"
+ autoFocus={agent.installed && agent === agents.find((a) => a.installed)}
+ disabled={!agent.installed}
+ data-testid={`pane-split-${direction}-${paneName}-${agent.name}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ onPick(agent.name);
+ }}
+ className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-primary/10 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent"
+ >
+ <span>{agent.displayName}</span>
+ {!agent.installed && (
+ <span className="text-[10px] uppercase tracking-wide text-muted-foreground">
+ not installed
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ </>
+ );
+}
+
function PaneAction({
label,
testId,
light,
danger = false,
disabled = false,
+ expanded,
onClick,
children,
}: {
@@ -502,6 +662,8 @@ function PaneAction({
light: boolean;
danger?: boolean;
disabled?: boolean;
+ /** Set when this button opens a menu — announces its state to a screen reader. */
+ expanded?: boolean;
onClick?: () => void;
children: React.ReactNode;
}) {
@@ -511,6 +673,8 @@ function PaneAction({
aria-label={label}
title={label}
data-testid={testId}
+ aria-haspopup={expanded === undefined ? undefined : "menu"}
+ aria-expanded={expanded}
disabled={disabled || !onClick}
onClick={(e) => {
// The pane's own mousedown selects it as the prompt target; an action
diff --git a/jarvis/ui/web/frontend/src/components/agentic/layout.test.ts b/jarvis/ui/web/frontend/src/components/agentic/layout.test.ts
index d1e565c067..0f4737a4c1 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/layout.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/layout.test.ts
@@ -1,25 +1,25 @@
import { describe, expect, it } from "vitest";
-import { MAX_PANES_PER_BAND, paneColumns, paneLines, paneRows } from "./layout";
+import { MAX_PANES_PER_BAND, paneColumns, paneGrid, paneLines } from "./layout";
describe("paneColumns", () => {
it("keeps a small workspace on one line", () => {
- // What the grid actually does today for every one of these: one row,
- // panes side by side. The wizard preview has to say the same thing.
+ // What the grid actually does today for every one of these: one band,
+ // columns side by side. The wizard preview has to say the same thing.
for (const n of [1, 2, 3, 4, 6, 8, 10]) {
expect(paneColumns(n)).toBe(n);
}
});
it("wraps beyond the readable width instead of shrinking panes further", () => {
- // 12 panes on one line leaves each of them too narrow to read, so they
- // break into two even lines: 6 above, 6 below.
+ // 12 columns on one line leaves each of them too narrow to read, so they
+ // break into two even bands: 6 above, 6 below.
expect(paneColumns(11)).toBe(6);
expect(paneColumns(12)).toBe(6);
});
- it("keeps the lines even rather than filling the first one up", () => {
- // 21 panes could be 10 + 10 + 1; an almost empty last line next to two
- // full ones looks broken, so every line gets the same width.
+ it("keeps the bands even rather than filling the first one up", () => {
+ // 21 columns could be 10 + 10 + 1; an almost empty last line next to two
+ // full ones looks broken, so every band gets the same width.
expect(paneColumns(21)).toBe(7);
expect(paneColumns(20)).toBe(10);
});
@@ -34,12 +34,12 @@ describe("paneColumns", () => {
});
describe("paneLines", () => {
- it("is one line while the row fits", () => {
+ it("is one band while the workspace fits", () => {
expect(paneLines(1)).toBe(1);
expect(paneLines(10)).toBe(1);
});
- it("grows with the wrap, so a wrapped row gets the height for it", () => {
+ it("grows with the wrap, so a wrapped workspace gets the height for it", () => {
expect(paneLines(11)).toBe(2);
expect(paneLines(12)).toBe(2);
expect(paneLines(21)).toBe(3);
@@ -50,34 +50,78 @@ describe("paneLines", () => {
});
});
-describe("paneRows", () => {
- const term = (name: string, row: number) => ({ name, row });
+describe("paneGrid", () => {
+ const pane = (column: number, slot: number) => ({ column, slot });
- it("groups the panes by the row the backend gave them", () => {
- const panes = [term("Mika", 0), term("Nova", 0), term("Aria", 1)];
- expect(paneRows(panes).map((r) => r.map((p) => p.name))).toEqual([
- ["Mika", "Nova"],
- ["Aria"],
+ it("puts a fresh workspace side by side on one row", () => {
+ const grid = paneGrid([pane(0, 0), pane(1, 0), pane(2, 0)]);
+ expect(grid.columns).toBe(3);
+ expect(grid.rows).toBe(1);
+ expect(grid.placements).toEqual([
+ { column: 1, row: 1, rowSpan: 1 },
+ { column: 2, row: 1, rowSpan: 1 },
+ { column: 3, row: 1, rowSpan: 1 },
]);
});
- it("keeps an over-wide row whole — the grid wraps it, not this", () => {
- // Splitting it here would move panes into a new parent element on every
- // wrap, which unmounts them and kills the agents behind them.
- const panes = Array.from({ length: 12 }, (_, i) => term(`T${i + 1}`, 0));
- const rows = paneRows(panes);
- expect(rows).toHaveLength(1);
- expect(rows[0]).toHaveLength(12);
+ it("splits DOWN inside one column and leaves the others full height", () => {
+ // The whole point of the two-axis model: splitting the middle pane must not
+ // halve the panes beside it, which is what a full-width row used to do.
+ const grid = paneGrid([pane(0, 0), pane(1, 0), pane(1, 1), pane(2, 0)]);
+ expect(grid.columns).toBe(3);
+ expect(grid.rows).toBe(2);
+ expect(grid.placements).toEqual([
+ { column: 1, row: 1, rowSpan: 2 }, // untouched neighbour, still full height
+ { column: 2, row: 1, rowSpan: 1 }, // the anchor, now the top half
+ { column: 2, row: 2, rowSpan: 1 }, // the pane the split opened
+ { column: 3, row: 1, rowSpan: 2 },
+ ]);
+ });
+
+ it("makes columns of different depths end flush at the bottom", () => {
+ // A column of 2 next to a column of 3: six rows, spanned 3 and 2, so both
+ // columns fill exactly the same height.
+ const grid = paneGrid([
+ pane(0, 0),
+ pane(0, 1),
+ pane(1, 0),
+ pane(1, 1),
+ pane(1, 2),
+ ]);
+ expect(grid.rows).toBe(6);
+ expect(grid.placements).toEqual([
+ { column: 1, row: 1, rowSpan: 3 },
+ { column: 1, row: 4, rowSpan: 3 },
+ { column: 2, row: 1, rowSpan: 2 },
+ { column: 2, row: 3, rowSpan: 2 },
+ { column: 2, row: 5, rowSpan: 2 },
+ ]);
+ });
+
+ it("wraps a crowded workspace into a second band", () => {
+ const panes = Array.from({ length: 12 }, (_, i) => pane(i, 0));
+ const grid = paneGrid(panes);
+ expect(grid.columns).toBe(6);
+ expect(grid.rows).toBe(2);
+ // The seventh column starts the second band, back at the left edge.
+ expect(grid.placements[6]).toEqual({ column: 1, row: 2, rowSpan: 1 });
+ expect(grid.placements[11]).toEqual({ column: 6, row: 2, rowSpan: 1 });
+ });
+
+ it("closes gaps the backend left in the column numbers", () => {
+ // close_terminal() re-packs columns, but a session read mid-change can
+ // still carry a gap — an empty column would render as a blank stripe.
+ const grid = paneGrid([pane(0, 0), pane(4, 0)]);
+ expect(grid.columns).toBe(2);
+ expect(grid.placements.map((p) => p.column)).toEqual([1, 2]);
});
- it("skips rows the backend left empty", () => {
- // close_terminal() re-packs rows, but a session read mid-change can still
- // carry a gap — an empty row would render as a blank stripe.
- const panes = [term("Mika", 0), term("Nova", 3)];
- expect(paneRows(panes).map((r) => r.length)).toEqual([1, 1]);
+ it("orders a column by slot, not by arrival", () => {
+ const grid = paneGrid([pane(0, 2), pane(0, 0), pane(0, 1)]);
+ expect(grid.placements.map((p) => p.row)).toEqual([3, 1, 2]);
});
it("handles an empty workspace", () => {
- expect(paneRows([])).toEqual([]);
+ expect(paneGrid([])).toEqual({ columns: 0, rows: 0, placements: [] });
});
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/layout.ts b/jarvis/ui/web/frontend/src/components/agentic/layout.ts
index 16ddd2e966..98b9f8fce4 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/layout.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/layout.ts
@@ -9,34 +9,109 @@
* preview that contradicts the thing it previews is worse than no preview, and
* the only durable fix is that both call the same function.
*
- * The rule: panes stay on one line for as long as they stay readable, and wrap
- * into EVEN lines once they don't. Even, because filling the first line to the
- * cap and leaving a remainder (12 → 10 + 2) reads as a broken layout, whereas
- * 6 + 6 reads as a grid. Below the cap nothing wraps, so the common two-,
- * four-, and eight-pane workspaces keep the single row they have today.
+ * ## The workspace is COLUMNS of stacked panes
*
- * Note what this returns: a WIDTH, not a list of lines. The grid renders one
- * row's panes as siblings in a CSS grid and lets the browser wrap them, which
- * matters because every pane has to stay mounted — moving a pane into a new
- * parent element would tear down its WebSocket and kill the agent behind it.
+ * A workspace is a left-to-right list of columns, and each column is a
+ * top-to-bottom stack of one or more panes. "Split right" opens a new column
+ * beside the anchor; "split down" adds a pane to the anchor's OWN column and
+ * leaves every other column untouched.
+ *
+ * That is the whole point of the model. The earlier one had a single axis — a
+ * pane knew only its row — so "split down" could only mean "open a new row",
+ * and a row spans the whole window by definition. Splitting one pane therefore
+ * squashed all the others to half height, which is not what splitting a pane
+ * means anywhere else. A second axis is the smallest thing that fixes it.
+ *
+ * ## Why one grid and not nested containers
+ *
+ * The obvious rendering — a flex row of column elements, each a flex column of
+ * panes — is wrong here, and expensively so. Every pane must stay MOUNTED for
+ * its whole life: unmounting one tears down its WebSocket and kills the coding
+ * agent behind it. React re-parents children when the element tree changes
+ * shape, so closing a column would remount the panes of every column after it.
+ *
+ * `paneGrid` therefore returns COORDINATES, not nested lists. All panes are
+ * siblings inside one grid container that never changes, and a layout change is
+ * only ever a change of numbers on each pane. Nothing is re-parented, so
+ * nothing remounts.
*/
/**
- * Most panes that may share one line.
+ * Most columns that may share one band (one line of columns) when the available
+ * width is unknown — a last-resort ceiling, not the number to lay out by.
*
- * Past this, panes get too narrow for their terminal content to survive — an
- * agent's output wraps into an unreadable column and the pane is there in name
- * only. Wrapping keeps every pane wide enough to actually read.
+ * Use `bandCapacityFor(widthPx)` wherever the width IS known, which is every
+ * real render. A fixed count cannot work: ten columns in a 2560 px window give
+ * each pane ~256 px, but the same ten in a 1440 px window give ~144 px — about
+ * 18 characters. Measured at that width, Claude Code truncates every line and
+ * breaks single words across rows ("Clau/de/Max"), which is exactly the
+ * unreadable pane reported on 2026-07-25 with eight terminals in one band.
*/
export const MAX_PANES_PER_BAND = 10;
-/** Anything with a grid row — the pane fields this module actually needs. */
-interface Positioned {
+/**
+ * Narrowest a pane may get before its agent's output stops being readable.
+ *
+ * An agent TUI draws boxes, file trees and status rows; below roughly 45
+ * characters it truncates them and the pane becomes decoration. At the default
+ * 13 px monospace a character is ~7.8 px wide, so 45 characters plus the pane's
+ * frame and padding lands near 380 px. Deliberately a floor on WIDTH rather than
+ * a count, so the same rule holds on a laptop and on a 4K display.
+ */
+export const MIN_PANE_WIDTH_PX = 380;
+
+/**
+ * How many columns fit in ``widthPx`` without starving them.
+ *
+ * Returns at least 1 — one unreadably narrow pane still beats no pane — and
+ * never more than `MAX_PANES_PER_BAND`.
+ */
+export function bandCapacityFor(
+ widthPx: number,
+ minPaneWidth: number = MIN_PANE_WIDTH_PX,
+): number {
+ if (!Number.isFinite(widthPx) || widthPx <= 0) return MAX_PANES_PER_BAND;
+ const fits = Math.floor(widthPx / Math.max(1, minPaneWidth));
+ return Math.max(1, Math.min(MAX_PANES_PER_BAND, fits));
+}
+
+/**
+ * Ceiling on the grid's row unit (see `paneGrid`).
+ *
+ * The unit is the least common multiple of the column heights, which stays
+ * small for real workspaces (columns of 3, 4 and 5 panes → 60). The cap only
+ * exists so a pathological mix can never ask the browser for a grid with tens
+ * of thousands of rows.
+ */
+const MAX_ROW_UNIT = 120;
+
+/** A pane's place in the workspace — the fields this module actually needs. */
+export interface Positioned {
+ /** Which column, left to right. */
+ column: number;
+ /** Position within that column, top to bottom. */
+ slot: number;
+}
+
+/** Where one pane sits in the CSS grid. All values are 1-based, as CSS wants. */
+export interface PanePlacement {
+ column: number;
row: number;
+ /** Grid rows this pane spans — how a short column fills the same height. */
+ rowSpan: number;
+}
+
+/** The rendered grid: its size, plus one placement per pane, in input order. */
+export interface PaneGrid {
+ /** `grid-template-columns` count. */
+ columns: number;
+ /** `grid-template-rows` count. */
+ rows: number;
+ placements: PanePlacement[];
}
/**
- * Panes per line for a row of ``count`` panes: the row's width in the grid.
+ * Columns per band for a workspace of ``count`` columns: the grid's width.
*
* Also the wizard's preview width, which is the point — the dots the user sees
* before starting are the arrangement they get.
@@ -49,34 +124,77 @@ export function paneColumns(count: number, maxPerBand: number = MAX_PANES_PER_BA
}
/**
- * Lines a row of ``count`` panes occupies once wrapped.
+ * Bands a workspace of ``count`` columns occupies once wrapped.
*
- * The grid gives a wrapped row proportionally more height, so a row of 12
- * (two lines) does not get squeezed into the same band as a row of 1.
+ * A wrapped workspace is taller, so the grid needs proportionally more rows —
+ * otherwise two bands share the height of one and every pane is half as tall.
*/
export function paneLines(count: number, maxPerBand: number = MAX_PANES_PER_BAND): number {
const width = paneColumns(count, maxPerBand);
return width === 0 ? 0 : Math.ceil(count / width);
}
+function greatestCommonDivisor(a: number, b: number): number {
+ let [x, y] = [Math.abs(a), Math.abs(b)];
+ while (y) [x, y] = [y, x % y];
+ return x || 1;
+}
+
/**
- * The workspace's rows, in render order, with empty ones dropped.
+ * Place every pane in one CSS grid.
+ *
+ * Columns are read off the panes' own `column` values (gaps closed, so a
+ * half-applied close never renders a blank stripe) and each column's panes are
+ * ordered by `slot`.
*
- * Rows come from the backend and carry the user's own splits ("split down"
- * opens a row). A gap in the row numbers — possible while a close is still
- * being packed away — must not render as a blank stripe.
+ * Height is the subtle part: columns hold different numbers of panes, and all
+ * of them have to end flush at the bottom. So the grid's row count is the
+ * least common multiple of the column heights — a column of 2 spans 3 rows per
+ * pane where a column of 3 spans 2 — and every column fills exactly the same
+ * height whatever it holds.
*/
-export function paneRows<T extends Positioned>(panes: readonly T[]): T[][] {
- const rows: T[][] = [];
- const byRow = new Map<number, T[]>();
- for (const pane of panes) {
- let row = byRow.get(pane.row);
- if (!row) {
- row = [];
- byRow.set(pane.row, row);
- rows.push(row);
- }
- row.push(pane);
+export function paneGrid<T extends Positioned>(
+ panes: readonly T[],
+ maxPerBand: number = MAX_PANES_PER_BAND,
+): PaneGrid {
+ if (panes.length === 0) return { columns: 0, rows: 0, placements: [] };
+
+ // Column index by the pane's own column number, gaps closed.
+ const ordered = [...new Set(panes.map((p) => p.column))].sort((a, b) => a - b);
+ const columnIndex = new Map(ordered.map((column, index) => [column, index]));
+
+ // Each column's panes, top to bottom, as indexes into `panes`.
+ const stacks: number[][] = ordered.map(() => []);
+ panes.forEach((pane, index) => stacks[columnIndex.get(pane.column) ?? 0].push(index));
+ for (const stack of stacks) {
+ stack.sort((a, b) => panes[a].slot - panes[b].slot);
}
- return rows;
+
+ const perBand = Math.max(1, paneColumns(ordered.length, maxPerBand));
+ const bands = Math.ceil(ordered.length / perBand);
+
+ let unit = 1;
+ for (const stack of stacks) {
+ const height = Math.max(1, stack.length);
+ const next = (unit / greatestCommonDivisor(unit, height)) * height;
+ // Past the cap the exact fit is abandoned rather than the layout: every
+ // pane keeps one row, so a column simply ends higher than its neighbours.
+ unit = next <= MAX_ROW_UNIT ? next : unit;
+ }
+
+ const placements: PanePlacement[] = new Array(panes.length);
+ stacks.forEach((stack, index) => {
+ const band = Math.floor(index / perBand);
+ const column = (index % perBand) + 1;
+ const span = Math.max(1, Math.floor(unit / Math.max(1, stack.length)));
+ stack.forEach((pane, position) => {
+ placements[pane] = {
+ column,
+ row: band * unit + position * span + 1,
+ rowSpan: span,
+ };
+ });
+ });
+
+ return { columns: perBand, rows: bands * unit, placements };
}
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index b29411fb7c..64d1b3a454 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -82,8 +82,10 @@ export interface TerminalState {
agent: string;
display_name: string;
index: number;
- /** Grid row: panes sharing a row render side by side. */
- row: number;
+ /** Grid column, left to right. Each column is its own stack of panes. */
+ column: number;
+ /** Position within that column, top to bottom. */
+ slot: number;
status: "pending" | "live" | "exited" | "error";
exit_code: number | null;
error: string;
@@ -204,8 +206,10 @@ export async function endIdeSession(): Promise<void> {
/**
* Open one more terminal in the running workspace.
*
- * `direction` decides where it lands relative to `anchor`: "right" joins that
- * pane's row, "down" opens a new row beneath it. Returns the updated workspace.
+ * `direction` decides where it lands relative to `anchor`: "right" opens a new
+ * column beside that pane, "down" splits the pane's own column and stacks the
+ * new one under it. `agent` picks the coding CLI to run — omitted, the new pane
+ * inherits the anchor's. Returns the updated workspace.
*/
export async function addTerminal(payload: {
anchor?: string;
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index c0012079b3..df8c3cb7e6 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -35,6 +35,7 @@ import { useEventStore } from "@/store/events";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { AgenticGrid } from "@/components/agentic/AgenticGrid";
+import { paneColumns } from "@/components/agentic/layout";
import { FolderPicker } from "@/components/agentic/FolderPicker";
import {
endIdeSession,
@@ -54,7 +55,9 @@ interface PlannedTerminal {
name: string;
}
-const COUNT_CHOICES = [1, 2, 3, 4, 6, 8] as const;
+// Offered up to the backend's cap, so the busiest workspace the app supports is
+// one click away rather than eleven splits.
+const COUNT_CHOICES = [1, 2, 3, 4, 6, 8, 10, 12] as const;
/**
* Terminal plan for ``count`` panes, preserving whatever the user already chose
@@ -158,6 +161,18 @@ export function AgenticIdeView() {
const installed = useMemo(() => agents.filter((a) => a.installed), [agents]);
const defaultAgent = installed[0]?.name ?? "claude";
+ // What the grid's split menus offer. Uninstalled CLIs stay in the list but
+ // disabled, so their absence is visible rather than silently missing.
+ const splitChoices = useMemo(
+ () =>
+ agents.map((a) => ({
+ name: a.name,
+ displayName: a.display_name,
+ installed: a.installed,
+ })),
+ [agents],
+ );
+
const chooseCount = (n: number) => {
setCount(n);
setPlanned((prev) => buildPlan(n, prev, defaultAgent, suggested));
@@ -253,6 +268,7 @@ export function AgenticIdeView() {
onClose={() => void close()}
busy={busy}
maxTerminals={meta?.max_terminals ?? 12}
+ agents={splitChoices}
onSessionChanged={setSession}
/>
{modeIntroFor === session.id && (
@@ -334,9 +350,9 @@ export function AgenticIdeView() {
{step === 1 && (
<Section
title="How many terminals?"
- hint="Each terminal runs its own agent, side by side in a grid."
+ hint="Each terminal runs its own agent. The dots show how they will sit — side by side, wrapping onto a second line once there are too many to stay readable."
>
- <div className="grid grid-cols-3 gap-3 sm:grid-cols-6">
+ <div className="grid grid-cols-4 gap-3 sm:grid-cols-8">
{COUNT_CHOICES.filter((n) => n <= (meta?.max_terminals ?? 12)).map((n) => (
<button
key={n}
@@ -678,18 +694,28 @@ function AgentChoice({
);
}
+/**
+ * The arrangement ``n`` terminals will actually open in.
+ *
+ * The column count comes from the same function the running grid lays itself
+ * out with — it used to have its own (three per line), so choosing 4 previewed
+ * 3 above and 1 below and then opened 4 side by side. A preview is only worth
+ * showing while it cannot disagree with the real thing.
+ */
function DotGrid({ n, active }: { n: number; active: boolean }) {
- const cols = n <= 1 ? 1 : n <= 2 ? 2 : n <= 6 ? 3 : 4;
+ const cols = Math.max(1, paneColumns(n));
+ const tight = cols > 6;
return (
<div
- className="grid gap-1"
+ className={cn("grid", tight ? "gap-0.5" : "gap-1")}
style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}
>
{Array.from({ length: n }).map((_, i) => (
<span
key={i}
className={cn(
- "h-2 w-2 rounded-[3px]",
+ "rounded-[3px]",
+ tight ? "h-1.5 w-1.5" : "h-2 w-2",
active ? "bg-primary" : "bg-muted-foreground/40",
)}
/>
diff --git a/tests/unit/web/test_agentic_ide_grid.py b/tests/unit/web/test_agentic_ide_grid.py
new file mode 100644
index 0000000000..e19907a37e
--- /dev/null
+++ b/tests/unit/web/test_agentic_ide_grid.py
@@ -0,0 +1,135 @@
+"""Grid geometry of the Agentic-IDE workspace: where a split puts a pane.
+
+The workspace is a left-to-right list of columns, each a top-to-bottom stack.
+The distinction these tests defend is that "split down" affects the anchor's
+column ONLY. The earlier one-axis model could not express that — a downward
+split opened a window-wide row, so splitting one pane halved the height of
+every other pane in the workspace.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import Registry
+
+
[email protected](autouse=True)
+def _agents_installed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Pretend both coding CLIs are on PATH — this suite tests geometry only.
+
+ Without it the fixture depends on what the developer happens to have
+ installed, which is exactly the maintainer-config trap (AP-23).
+ """
+ monkeypatch.setattr(session_mod, "agent_argv", lambda agent: ("fake", agent))
+
+
+async def _workspace(tmp_path, panes: int = 3) -> Registry:
+ registry = Registry()
+ await registry.start(
+ str(tmp_path),
+ [{"agent": "claude"} for _ in range(panes)],
+ )
+ return registry
+
+
+def grid(registry: Registry) -> list[tuple[str, int, int]]:
+ """The workspace as (name, column, slot), in the order the UI renders it."""
+ session = registry.session
+ assert session is not None
+ return [(t.name, t.column, t.slot) for t in session.terminals]
+
+
+async def test_wizard_opens_one_row_of_columns(tmp_path) -> None:
+ registry = await _workspace(tmp_path, 4)
+ assert [(c, s) for _, c, s in grid(registry)] == [(0, 0), (1, 0), (2, 0), (3, 0)]
+
+
+async def test_split_down_stacks_inside_the_anchors_own_column(tmp_path) -> None:
+ registry = await _workspace(tmp_path, 3)
+ names = [name for name, _, _ in grid(registry)]
+ await registry.add_terminal(anchor=names[1], direction="down")
+
+ placed = grid(registry)
+ # The middle column now holds two panes; the neighbours keep their own
+ # column to themselves and are NOT pushed into a shorter row.
+ assert [(c, s) for _, c, s in placed] == [(0, 0), (1, 0), (1, 1), (2, 0)]
+ assert placed[1][1] == placed[2][1] # anchor and new pane share a column
+
+
+async def test_split_right_opens_a_column_beside_the_anchor(tmp_path) -> None:
+ registry = await _workspace(tmp_path, 3)
+ names = [name for name, _, _ in grid(registry)]
+ added = await registry.add_terminal(anchor=names[0], direction="right")
+
+ placed = grid(registry)
+ assert [(c, s) for _, c, s in placed] == [(0, 0), (1, 0), (2, 0), (3, 0)]
+ # It landed directly right of the anchor, pushing the rest one column over.
+ assert placed[1][0] == added.name
+ assert added.column == 1
+ assert added.slot == 0
+
+
+async def test_a_stacked_column_survives_a_split_right_elsewhere(tmp_path) -> None:
+ registry = await _workspace(tmp_path, 2)
+ names = [name for name, _, _ in grid(registry)]
+ await registry.add_terminal(anchor=names[0], direction="down")
+ await registry.add_terminal(anchor=names[1], direction="right")
+
+ # Column 0 keeps its stack of two; the new pane is a column of its own.
+ assert [(c, s) for _, c, s in grid(registry)] == [(0, 0), (0, 1), (1, 0), (2, 0)]
+
+
+async def test_closing_the_top_of_a_stack_packs_the_slots(tmp_path) -> None:
+ registry = await _workspace(tmp_path, 2)
+ names = [name for name, _, _ in grid(registry)]
+ await registry.add_terminal(anchor=names[0], direction="down")
+ await registry.close_terminal(names[0])
+
+ # No hole where the closed pane was: the survivor moves up to slot 0,
+ # otherwise the grid renders a blank half-column.
+ assert [(c, s) for _, c, s in grid(registry)] == [(0, 0), (1, 0)]
+
+
+async def test_closing_a_whole_column_packs_the_columns(tmp_path) -> None:
+ registry = await _workspace(tmp_path, 3)
+ names = [name for name, _, _ in grid(registry)]
+ await registry.close_terminal(names[1])
+
+ assert [(c, s) for _, c, s in grid(registry)] == [(0, 0), (1, 0)]
+
+
+async def test_terminals_stay_in_reading_order(tmp_path) -> None:
+ """Left to right, top to bottom — the order the prompt-bar chips use."""
+ registry = await _workspace(tmp_path, 2)
+ first, second = [name for name, _, _ in grid(registry)]
+ await registry.add_terminal(anchor=second, direction="down")
+ await registry.add_terminal(anchor=first, direction="down")
+
+ placed = grid(registry)
+ assert [(c, s) for _, c, s in placed] == [(0, 0), (0, 1), (1, 0), (1, 1)]
+ assert [t.index for t in registry.session.terminals] == [0, 1, 2, 3]
+
+
+async def test_split_may_name_a_different_agent(tmp_path) -> None:
+ """The pane the UI's CLI picker opens: same split, other coding agent."""
+ registry = await _workspace(tmp_path, 1)
+ names = [name for name, _, _ in grid(registry)]
+ added = await registry.add_terminal(anchor=names[0], direction="down", agent="codex")
+
+ assert added.agent == "codex"
+ assert added.display_name == "Codex"
+ # ...and it landed in the anchor's column, like any other downward split.
+ assert (added.column, added.slot) == (0, 1)
+
+
+async def test_split_inherits_the_anchors_agent_when_none_is_named(tmp_path) -> None:
+ registry = await _workspace(tmp_path, 1)
+ names = [name for name, _, _ in grid(registry)]
+ await registry.add_terminal(anchor=names[0], direction="right", agent="codex")
+
+ session = registry.session
+ assert session is not None
+ codex_pane = session.terminals[1].name
+ inherited = await registry.add_terminal(anchor=codex_pane, direction="down")
+ assert inherited.agent == "codex"