Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): the grid draws the split tree, and even means every terminal
rubenluetke10-beepd0d23cf1be6b
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsxindex 837877b0f9..438807c006 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx@@ -42,6 +42,7 @@ vi.mock("@/lib/agenticIdeApi", () => ({closeTerminals: vi.fn(),moveTerminal: vi.fn(),renameTerminal: vi.fn(),+ saveLayoutWeights: vi.fn(),// Polled by the grid so the pane headers keep saying what their agents are// doing. Resolves empty by default; the recap tests give it real rows.fetchTerminalRecaps: vi.fn(async () => ({@@ -238,6 +239,7 @@ vi.mock("./AgenticTerminal", () => ({import { AgenticGrid } from "./AgenticGrid";import * as api from "@/lib/agenticIdeApi";import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";+import type { LayoutNode } from "./treeLayout";/** One pane at (column, slot) — the workspace is columns of stacked panes. */function pane(name: string, column: number, slot: number, index: number): TerminalState {@@ -261,10 +263,43 @@ function pane(name: string, column: number, slot: number, index: number): Termin};}+/**+ * The split tree the backend would send for panes at these (column, slot)+ * places — a row of stacks, every share even. Tests that are about UNEVEN+ * shares pass an explicit `layout` instead.+ */+function treeFromGrid(terminals: TerminalState[]): LayoutNode | null {+ const byColumn = new Map<number, TerminalState[]>();+ for (const term of terminals) {+ byColumn.set(term.column, [...(byColumn.get(term.column) ?? []), term]);+ }+ const columns: LayoutNode[] = [...byColumn.keys()]+ .sort((a, b) => a - b)+ .map((column) => {+ const stack = (byColumn.get(column) ?? []).sort((a, b) => a.slot - b.slot);+ return stack.length === 1+ ? { pane: stack[0].key }+ : {+ direction: "column" as const,+ children: stack.map((term) => ({ pane: term.key })),+ weights: stack.map(() => 1),+ };+ });+ if (columns.length === 0) return null;+ if (columns.length === 1) return columns[0];+ return { direction: "row", children: columns, weights: columns.map(() => 1) };+}+/** `panes` are [name, column, slot] triples; slot defaults to 0 (one row). */-function sessionWith(panes: Array<[string, number] | [string, number, number]>): SessionState {+function sessionWith(+ panes: Array<[string, number] | [string, number, number]>,+ layout?: LayoutNode | null,+): SessionState {+ const terminals = panes.map(([name, column, slot], i) => pane(name, column, slot ?? 0, i));return {id: "ide_test",+ layout: layout === undefined ? treeFromGrid(terminals) : layout,+ terminals,folder: "/work/project",project: {path: "/work/project",@@ -282,7 +317,6 @@ function sessionWith(panes: Array<[string, number] | [string, number, number]>):},created_at: 0,focus_mode: false,- terminals: panes.map(([name, column, slot], i) => pane(name, column, slot ?? 0, i)),};}@@ -309,6 +343,9 @@ beforeEach(() => {window.localStorage.clear();paneActiveHistory.clear();window.localStorage.setItem("jarvis.agenticIde.composerHeight.v2", "176");+ // Seam drags post their result fire-and-forget; an auto-mock returning+ // undefined would crash the `.catch` chain rather than fail an assertion.+ vi.mocked(api.saveLayoutWeights).mockResolvedValue(sessionWith([]));vi.mocked(api.addTerminal).mockResolvedValue(sessionWith([["Mika", 0],@@ -1092,6 +1129,42 @@ describe("the compose narration line", () => {window,new CustomEvent("jarvis:agentic-ide-compose", { detail }),);++ it("shows the latest beat while the brief is being written", () => {+ renderGrid();++ beat({+ session_id: "ide_test",+ terminal: "Mika",+ stage: "thinking",+ message: "Reading the code before Mika is briefed - 3 file outlines.",+ });++ expect(screen.getByTestId("agentic-compose-progress").textContent).toContain(+ "Reading the code before Mika is briefed",+ );+ });++ it("clears the line once the delivery is announced", () => {+ renderGrid();+ beat({ session_id: "ide_test", terminal: "Mika", stage: "drafting", message: "Writing." });++ fireEvent(+ window,+ new CustomEvent("jarvis:agentic-ide-prompt", {+ detail: { terminal: "Mika", submitted: true },+ }),+ );++ expect(screen.queryByTestId("agentic-compose-progress")).toBeNull();+ });++ it("ignores beats that belong to another workspace", () => {+ renderGrid();++ beat({ session_id: "ide_other", terminal: "Mika", stage: "start", message: "Writing." });++ expect(screen.queryByTestId("agentic-compose-progress")).toBeNull();});});@@ -1129,42 +1202,6 @@ describe("dropping files on the prompt bar", () => {await waitFor(() => expect(api.attachToTerminal).toHaveBeenCalled());const [name, payload] = vi.mocked(api.attachToTerminal).mock.calls[0];-- it("shows the latest beat while the brief is being written", () => {- renderGrid();-- beat({- session_id: "ide_test",- terminal: "Mika",- stage: "thinking",- message: "Reading the code before Mika is briefed - 3 file outlines.",- });-- expect(screen.getByTestId("agentic-compose-progress").textContent).toContain(- "Reading the code before Mika is briefed",- );- });-- it("clears the line once the delivery is announced", () => {- renderGrid();- beat({ session_id: "ide_test", terminal: "Mika", stage: "drafting", message: "Writing." });-- fireEvent(- window,- new CustomEvent("jarvis:agentic-ide-prompt", {- detail: { terminal: "Mika", submitted: true },- }),- );-- expect(screen.queryByTestId("agentic-compose-progress")).toBeNull();- });-- it("ignores beats that belong to another workspace", () => {- renderGrid();-- beat({ session_id: "ide_other", terminal: "Mika", stage: "start", message: "Writing." });-- expect(screen.queryByTestId("agentic-compose-progress")).toBeNull();expect(name).toBe("Mika");expect(payload.analyze).toBe(true);// Held rather than typed: the user is still writing the sentence that@@ -1411,8 +1448,6 @@ describe("prompt bar seam", () => {* boundaries between them were plain borders with nothing to grab.*/describe("resizing the workspace", () => {- const WEIGHTS_KEY = "jarvis.agenticIde.paneWeights.v1.ide_test";-/** jsdom measures nothing, and a drag is pixels — so give it a size. */function measured(width: number, height: number) {const spies = [@@ -1429,8 +1464,17 @@ describe("resizing the workspace", () => {return Math.round(Number(match[1]) * 10) / 10;}- function stored(): { columns: number[]; panes: Record<string, number> } {- return JSON.parse(window.localStorage.getItem(WEIGHTS_KEY) ?? "{}");+ /** The tree the grid last posted to the backend, or null. */+ function savedTree(): LayoutNode | null {+ const calls = vi.mocked(api.saveLayoutWeights).mock.calls;+ return calls.length > 0 ? (calls[calls.length - 1][0] as LayoutNode) : null;+ }++ /** Root-level weights of the last posted tree, rounded for assertions. */+ function savedRootWeights(): number[] | null {+ const tree = savedTree();+ if (!tree || !("children" in tree)) return null;+ return tree.weights.map((weight) => Math.round(weight * 100) / 100);}/*@@ -1483,9 +1527,10 @@ describe("resizing the workspace", () => {it("puts a grab handle on every boundary between panes", () => {renderGrid(sessionWith([["Mika", 0], ["Nova", 0, 1], ["Aria", 1]]));- // One between the two columns, one between the panes stacked in the first.- expect(screen.getByTestId("pane-seam-column:0:1")).toBeTruthy();- expect(screen.getByTestId("pane-seam-pane:Mika:Nova")).toBeTruthy();+ // One between the two columns (a root boundary), one between the panes+ // stacked in the first column (a boundary inside child 0).+ expect(screen.getByTestId("pane-seam-root:1")).toBeTruthy();+ expect(screen.getByTestId("pane-seam-0:1")).toBeTruthy();});it("offers one seam per boundary the USER made, and no others", () => {@@ -1502,7 +1547,7 @@ describe("resizing the workspace", () => {const restore = measured(1800, 600);try {renderGrid(sessionWith([["Mika", 0], ["Nova", 1], ["Aria", 2]]));- dragSeamBy("pane-seam-column:0:1", 600, 900);+ dragSeamBy("pane-seam-root:1", 600, 900);// A sixth of the line moved from Nova to Mika...expect(widthOf("Mika")).toBe(50);@@ -1549,23 +1594,25 @@ describe("resizing the workspace", () => {const restore = measured(1000, 600);try {renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));- holdSeam("pane-seam-column:0:1", 500);+ holdSeam("pane-seam-root:1", 500);act(() => {window.dispatchEvent(new MouseEvent("pointermove", { clientX: 750 }));});await flushFrame();expect(widthOf("Mika")).toBe(75);- // ...and the workspace has not been told yet: a drag that committed per- // frame is what re-rendered every terminal on every pointer move.- expect(stored().columns).toEqual([]);+ // ...and nothing has been committed or posted yet: a drag that wrote+ // per frame is what re-rendered every terminal on every pointer move.+ expect(api.saveLayoutWeights).not.toHaveBeenCalled();act(() => window.dispatchEvent(new MouseEvent("pointerup")));// The release keeps exactly what was on screen — no snap back to the// frame before it, and no second jump.expect(widthOf("Mika")).toBe(75);- expect(stored().columns).toEqual([1.5, 0.5]);+ // The result reaches the backend (debounced), so the sizes survive a+ // restart on any machine and come back with a resumed workspace.+ await waitFor(() => expect(savedRootWeights()).toEqual([1.5, 0.5]));} finally {restore();}@@ -1589,7 +1636,7 @@ describe("resizing the workspace", () => {// pane once, and counting that as a frame of the drag would be measuring// the test's own setup.await flushFrame();- holdSeam("pane-seam-column:0:1", 500);+ holdSeam("pane-seam-root:1", 500);const before = paneRenders.get("Mika") ?? 0;for (const x of [560, 620, 680, 750]) {@@ -1626,7 +1673,7 @@ describe("resizing the workspace", () => {const busy = () => screen.getByTestId("pane-Mika").getAttribute("data-layout-busy");expect(busy()).toBe("no");- holdSeam("pane-seam-column:0:1", 500);+ holdSeam("pane-seam-root:1", 500);expect(busy()).toBe("yes");act(() => window.dispatchEvent(new MouseEvent("pointerup")));@@ -1649,12 +1696,14 @@ describe("resizing the workspace", () => {expect(busy()).toBe("no");});- it("remembers the sizes so a restart brings the workspace back as it was", () => {+ it("posts the sizes so a restart brings the workspace back as it was", async () => {const restore = measured(1000, 600);try {renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));- dragSeamBy("pane-seam-column:0:1", 500, 750);- expect(stored().columns).toEqual([1.5, 0.5]);+ dragSeamBy("pane-seam-root:1", 500, 750);+ // The whole tree travels; the backend adopts its weights and persists+ // them in the resume snapshot — no browser storage involved any more.+ await waitFor(() => expect(savedRootWeights()).toEqual([1.5, 0.5]));} finally {restore();}@@ -1664,10 +1713,10 @@ describe("resizing the workspace", () => {const restore = measured(1000, 600);try {renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));- dragSeamBy("pane-seam-column:0:1", 500, 750);+ dragSeamBy("pane-seam-root:1", 500, 750);expect(widthOf("Mika")).toBe(75);- fireEvent.doubleClick(screen.getByTestId("pane-seam-column:0:1"));+ fireEvent.doubleClick(screen.getByTestId("pane-seam-root:1"));expect(widthOf("Mika")).toBe(50);} finally {restore();@@ -1683,7 +1732,7 @@ describe("resizing the workspace", () => {* rearrange anything — which pane sits in which column, and which pane is* stacked under which, is exactly what the user asked to keep.*/- it("evens every terminal out on one click", () => {+ it("evens every terminal out on one click", async () => {const restore = measured(1800, 900);try {renderGrid(@@ -1696,8 +1745,8 @@ describe("resizing the workspace", () => {);// Out of shape on BOTH axes: one column dragged wide, and the stack// inside another column dragged so its two panes are unequal.- dragSeamBy("pane-seam-column:0:1", 600, 900);- dragSeamDownBy("pane-seam-pane:Nova:Vega", 450, 700);+ dragSeamBy("pane-seam-root:1", 600, 900);+ dragSeamDownBy("pane-seam-1:1", 450, 700);expect(widthOf("Mika")).not.toBe(33.3);expect(Math.round(box("Vega").height)).not.toBe(50);@@ -1710,9 +1759,12 @@ describe("resizing the workspace", () => {// ...and the two panes sharing a column splitting its height equally.expect(box("Nova").height).toBeCloseTo(50, 3);expect(box("Vega").height).toBeCloseTo(50, 3);- // Remembered, so the workspace comes back straight rather than snapping- // to the pre-click sizes on the next mount.- expect(stored()).toEqual({ columns: [], panes: {} });+ // Posted, so the workspace comes back straight rather than snapping to+ // the pre-click sizes on the next mount.+ await waitFor(() => {+ const tree = savedTree();+ expect(tree && "weights" in tree && tree.weights).toEqual([1, 1, 1]);+ });} finally {restore();}@@ -1729,7 +1781,7 @@ describe("resizing the workspace", () => {["Aria", 2],]),);- dragSeamBy("pane-seam-column:0:1", 600, 900);+ dragSeamBy("pane-seam-root:1", 600, 900);fireEvent.click(screen.getByTestId("agentic-even-panes"));@@ -1754,7 +1806,7 @@ describe("resizing the workspace", () => {renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));expect(disabled("agentic-even-panes")).toBe(true);- dragSeamBy("pane-seam-column:0:1", 500, 750);+ dragSeamBy("pane-seam-root:1", 500, 750);expect(disabled("agentic-even-panes")).toBe(false);fireEvent.click(screen.getByTestId("agentic-even-panes"));@@ -1770,7 +1822,7 @@ describe("resizing the workspace", () => {const restore = measured(1000, 600);try {renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));- dragSeamBy("pane-seam-column:0:1", 500, 750);+ dragSeamBy("pane-seam-root:1", 500, 750);fireEvent.click(screen.getByTestId("pane-maximize-Mika"));expect(disabled("agentic-even-panes")).toBe(true);@@ -1785,7 +1837,7 @@ describe("resizing the workspace", () => {const restore = measured(1000, 600);try {renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));- const seam = screen.getByTestId("pane-seam-column:0:1");+ const seam = screen.getByTestId("pane-seam-root:1");fireEvent.keyDown(seam, { key: "ArrowRight", shiftKey: true });// One coarse step of 64 px out of 1000, moved from Nova to Mika.expect(widthOf("Mika")).toBe(56.4);@@ -1794,77 +1846,59 @@ describe("resizing the workspace", () => {}});- it("halves the pane that was split instead of resizing every other one", async () => {- // The complaint: splitting one terminal used to narrow all of them, because- // a new pane meant a new share of the window rather than half of its anchor.- vi.mocked(api.addTerminal).mockResolvedValue(- sessionWith([["Mika", 0], ["New", 1], ["Nova", 2]]),+ it("draws the halved anchor the backend's tree describes after a split", async () => {+ // The halving itself is the backend's (`layout_tree.split_pane`, covered+ // there); the grid's job is to DRAW the tree the response carries instead+ // of second-guessing it with its own weights.+ const next = sessionWith([["Mika", 0], ["New", 1], ["Nova", 2]], {+ direction: "row",+ children: [{ pane: "mika" }, { pane: "new" }, { pane: "nova" }],+ weights: [0.5, 0.5, 1],+ });+ vi.mocked(api.addTerminal).mockResolvedValue(next);+ const { onSessionChanged, rerender } = renderGrid(+ sessionWith([["Mika", 0], ["Nova", 1]]),);- renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));fireEvent.click(screen.getByTestId("pane-split-right-Mika"));+ await waitFor(() => expect(onSessionChanged).toHaveBeenCalledWith(next));+ // The view owns the session prop, so the response reaches the grid the+ // way it does in the app: as a new prop.+ rerender({ session: next });- await waitFor(() => expect(stored().columns).toEqual([0.5, 0.5, 1]));- });-- it("halves it downwards too, leaving the column beside it full height", async () => {- vi.mocked(api.addTerminal).mockResolvedValue(- sessionWith([["Mika", 0], ["New", 0, 1], ["Nova", 1]]),- );- renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));-- fireEvent.click(screen.getByTestId("pane-split-down-Mika"));-- await waitFor(() => expect(stored().panes).toEqual({ Mika: 0.5, New: 0.5 }));+ expect(widthOf("Mika")).toBe(25);+ expect(widthOf("New")).toBe(25);+ expect(widthOf("Nova")).toBe(50);});/** The workspace changes WITHOUT this grid doing it.*- * A terminal opened by voice, closed by another client, or rearranged by the- * backend resuming after a restart arrives here as nothing but a new- * `session` prop — no callback ran, so nothing remapped the index-keyed- * column weights. This is how a closed pane's dragged width ended up on a- * different pane's column (2026-07-31: one pane squeezed, its nearly empty- * neighbour twice as wide).+ * A terminal opened by voice, closed by another client, or the backend+ * resuming after a restart arrives here as nothing but a new `session`+ * prop. The tree in it is the whole answer now — including the sizes, which+ * the backend carries per pane KEY, so nothing here has to guess which pane+ * a dragged width belonged to (the index-keyed failure of 2026-07-31).*/- it("keeps dragged widths with their panes when the workspace changes from outside", async () => {+ it("follows the authoritative tree when the workspace changes from outside", async () => {const restore = measured(1800, 600);try {const { rerender } = renderGrid(sessionWith([["Mika", 0], ["Nova", 1], ["Aria", 2]]),);- // Drag the seam between Nova and Aria so Aria is the wide one.- dragSeamBy("pane-seam-column:1:2", 1200, 900);+ dragSeamBy("pane-seam-root:2", 1200, 900);expect(widthOf("Aria")).toBe(50);- // Mika goes away without this grid being asked — every index shifts.- rerender({ session: sessionWith([["Nova", 0], ["Aria", 1]]) });-- // Aria keeps the width it was dragged to; index-keyed weights would have- // handed it to Nova and squeezed Aria instead.- expect(widthOf("Aria")).toBe(75);- expect(widthOf("Nova")).toBe(25);- } finally {- restore();- }- });+ // Mika was closed elsewhere. The backend dissolved its share and kept+ // Nova's and Aria's dragged weights — the new tree says all of that.+ rerender({+ session: sessionWith([["Nova", 0], ["Aria", 1]], {+ direction: "row",+ children: [{ pane: "nova" }, { pane: "aria" }],+ weights: [0.5, 1.5],+ }),+ });- it("carries dragged widths across a reload behind which the workspace changed", () => {- // What an earlier session left behind: Aria dragged wide while Mika still- // existed. The reload happens after Mika was closed elsewhere, so the- // stored index-keyed widths no longer match the session being mounted.- window.localStorage.setItem(- WEIGHTS_KEY,- JSON.stringify({ columns: [1, 0.5, 1.5], bands: [], panes: {} }),- );- window.localStorage.setItem(- "jarvis.agenticIde.paneArrangement.v1.ide_test",- JSON.stringify({ Mika: 0, Nova: 1, Aria: 2 }),- );- const restore = measured(1800, 600);- try {- renderGrid(sessionWith([["Nova", 0], ["Aria", 1]]));expect(widthOf("Aria")).toBe(75);expect(widthOf("Nova")).toBe(25);} finally {@@ -1872,42 +1906,42 @@ describe("resizing the workspace", () => {}});- it("does not remap a second time when the session catches up with the grid's own action", async () => {- // The grid's own split remaps (and rebases) in the same breath as the- // request; the session prop then arrives describing the same arrangement.- // Reading that as fresh drift would remap already-remapped weights.- const next = sessionWith([["Mika", 0], ["New", 1], ["Nova", 2]]);- vi.mocked(api.addTerminal).mockResolvedValue(next);- const restore = measured(1800, 600);+ it("keeps the dragged sizes when the same shape comes back with older weights", async () => {+ // The session prop catches up on its own schedule (a poll, an event), and+ // what it echoes may predate the drag that just happened. As long as the+ // SHAPE matches, the local sizes are at least as fresh — snapping back to+ // the server's would make every drag twitch a moment later.+ const restore = measured(1000, 600);try {const { rerender } = renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));- fireEvent.click(screen.getByTestId("pane-split-right-Mika"));- await waitFor(() => expect(stored().columns).toEqual([0.5, 0.5, 1]));+ dragSeamBy("pane-seam-root:1", 500, 750);+ expect(widthOf("Mika")).toBe(75);- rerender({ session: next });+ rerender({ session: sessionWith([["Mika", 0], ["Nova", 1]]) });- expect(stored().columns).toEqual([0.5, 0.5, 1]);- expect(widthOf("Mika")).toBe(25);- expect(widthOf("Nova")).toBe(50);+ expect(widthOf("Mika")).toBe(75);} finally {restore();}});- it("waits out a seam drag before answering outside drift, then answers it", async () => {+ it("lets a structural change win over a drag it interrupted", async () => {const restore = measured(1800, 600);try {const { rerender } = renderGrid(sessionWith([["Mika", 0], ["Nova", 1], ["Aria", 2]]),);- dragSeamBy("pane-seam-column:1:2", 1200, 900);- expect(widthOf("Aria")).toBe(50);-// Grab a seam and, while the pointer is down, let the workspace change- // under the gesture. The remap must not fight the drag's direct painting- // — and must still land once the pointer is released.- holdSeam("pane-seam-column:0:1", 600);- rerender({ session: sessionWith([["Nova", 0], ["Aria", 1]]) });+ // under the gesture: the drag's tree describes panes that are partly+ // gone, so on release the server's NEW tree is the only honest layout.+ holdSeam("pane-seam-root:1", 600);+ rerender({+ session: sessionWith([["Nova", 0], ["Aria", 1]], {+ direction: "row",+ children: [{ pane: "nova" }, { pane: "aria" }],+ weights: [0.5, 1.5],+ }),+ });act(() => window.dispatchEvent(new MouseEvent("pointerup")));expect(widthOf("Aria")).toBe(75);@@ -1918,23 +1952,28 @@ describe("resizing the workspace", () => {});it("does not read a rename as a rearrangement", async () => {- vi.mocked(api.renameTerminal).mockResolvedValue(- sessionWith([["Frontend", 0], ["Nova", 1]]),- );+ // The tree references panes by KEY, and a rename leaves the key alone —+ // so the renamed pane keeps the width that was dragged for it.+ const renamed = sessionWith([["Frontend", 0], ["Nova", 1]]);+ renamed.terminals[0].key = "mika";+ renamed.layout = {+ direction: "row",+ children: [{ pane: "mika" }, { pane: "nova" }],+ weights: [1, 1],+ };+ vi.mocked(api.renameTerminal).mockResolvedValue(renamed);const restore = measured(1000, 600);try {const { rerender } = renderGrid(sessionWith([["Mika", 0], ["Nova", 1]]));- dragSeamBy("pane-seam-column:0:1", 500, 750);+ dragSeamBy("pane-seam-root:1", 500, 750);expect(widthOf("Mika")).toBe(75);fireEvent.click(screen.getByTestId("pane-rename-Mika"));await waitFor(() =>expect(api.renameTerminal).toHaveBeenCalledWith("Mika", "Frontend"),);- rerender({ session: sessionWith([["Frontend", 0], ["Nova", 1]]) });+ rerender({ session: renamed });- // The renamed pane keeps the width that was dragged for it — a remap- // here would have seen "Mika left, Frontend arrived" and reset it.expect(widthOf("Frontend")).toBe(75);} finally {restore();diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex 51a5bca472..6b29e17457 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -57,19 +57,13 @@ import { AgentPickerMenu, offersAgentChoice, type SplitAgentChoice } from "./Ageimport type { TerminalAppearance } from "./terminalThemes";import { installZoomKeyBridge, type ZoomIntent } from "./terminalZoom";import {- evenWeights,- isEvenLayout,- paneArrangement,- paneLayout,- panesFromArrangement,- remapColumnWeights,- sameArrangement,- weightsAfterSplit,+ isEvenTree,+ treeLayout,+ type LayoutNode,type PaneBox,type PaneSeam,- type PaneWeights,-} from "./paneLayout";-import { loadStoredArrangement, saveStoredArrangement, usePaneWeights } from "./usePaneWeights";+} from "./treeLayout";+import { useTreeSizes } from "./useTreeSizes";import {describeLayoutViolations,findLayoutViolations,@@ -791,6 +785,12 @@ export function AgenticGrid({recapCache.workspaceId === session.id ? recapCache.rows : {};// The editor owns ordinary keystrokes so typing does not re-render every// xterm pane in this very large component. This seed changes only when the+ // parent intentionally replaces the draft (successful send).+ const [promptSeed, setPromptSeed] = useState({ value: "", revision: 0 });+ const replacePrompt = useCallback((value: string) => {+ setPromptSeed((current) => ({ value, revision: current.revision + 1 }));+ }, []);+ const [sending, setSending] = useState(false);// The live line about the brief being written for a pane of THIS workspace.// Composition is 10-30 s of real model work; without this line the bar// showed a silent spinner for all of it, and a working composer and a@@ -839,12 +839,6 @@ export function AgenticGrid({window.removeEventListener("jarvis:agentic-ide-prompt", onDelivered);};}, [session.id]);- // parent intentionally replaces the draft (successful send).- const [promptSeed, setPromptSeed] = useState({ value: "", revision: 0 });- const replacePrompt = useCallback((value: string) => {- setPromptSeed((current) => ({ value, revision: current.revision + 1 }));- }, []);- const [sending, setSending] = useState(false);// Bumping a pane's token reconnects just that pane, which respawns its agent.// Keyed by call-sign so closing or splitting never disturbs the others.@@ -1312,11 +1306,11 @@ export function AgenticGrid({/** The sizes the panes are drawn at, and the seams between them.*- * Kept apart from the arrangement on purpose: `session.terminals` says which- * column and slot each pane is in and only the backend may change that, while- * the weights say how much room each one gets and only this browser does. A- * drag therefore never waits on a request, and a workspace opened on a second- * machine is the same arrangement at that machine's own sizes.+ * Both live in ONE split tree (`session.layout`): the backend owns its+ * structure — which pane sits where — and a seam drag here edits only its+ * weights, locally first so the gesture never waits on a request, then+ * posted back so the sizes survive a restart and come back with a resumed+ * workspace (see `useTreeSizes`).*/const canvasRef = useRef<HTMLDivElement | null>(null);@@ -1365,8 +1359,8 @@ export function AgenticGrid({* agrees with what is already on screen and nothing flickers on release.*/const paintDraggedLayout = useCallback(- (next: PaneWeights) => {- const live = paneLayout(session.terminals, next);+ (next: LayoutNode) => {+ const live = treeLayout(next, session.terminals);session.terminals.forEach((term, index) => {const node = paneNodes.current.get(term.name);const box = live.boxes[index];@@ -1382,8 +1376,8 @@ export function AgenticGrid({[session.terminals],);- const sizes = usePaneWeights(- session.id,+ const sizes = useTreeSizes(+ session.layout ?? null,// Measured at the moment of the drag rather than kept in state: the canvas// IS the visible workspace now, so its live size is the only truth a// pixels-to-weights conversion needs. A canvas that is not there yet@@ -1398,8 +1392,8 @@ export function AgenticGrid({paintDraggedLayout,);const layout = useMemo(- () => paneLayout(session.terminals, sizes.weights),- [session.terminals, sizes.weights],+ () => treeLayout(sizes.tree, session.terminals),+ [session.terminals, sizes.tree],);/*@@ -1417,82 +1411,16 @@ export function AgenticGrid({* another one; the boundaries simply even out where they already are. The* same act therefore covers every arrangement there is: columns side by* side share the width equally, and panes stacked in one column share that- * column's height equally.+ * column's height equally. "Equal" is measured in TERMINALS, not tree+ * nodes — a nested group of two stacks is two terminals wide and receives+ * two shares, so every pane on screen lands at the same width.*/const evenPanes = useCallback(() => {- sizes.setWeights(evenWeights());- }, [sizes.setWeights]);+ sizes.evenAll();+ }, [sizes.evenAll]);/** Would evening out change anything? Answers for the button's own state. */- const alreadyEven = useMemo(- () => isEvenLayout(session.terminals, sizes.weights),- [session.terminals, sizes.weights],- );-- /*- * Which panes the current column weights are keyed to.- *- * Weights are stored by COLUMN INDEX (see `paneLayout`), and the backend- * renumbers columns on every open and close. The grid's own actions remap- * the weights in the same breath — but a workspace also changes from OUTSIDE- * this grid: a terminal opened by voice, a second client, the backend- * resuming after a restart. Those arrive as a new `session.terminals` with- * nothing else said, and index-keyed widths then land on whichever pane- * holds the index now (observed 2026-07-31: after a restart re-opened the- * workspace, one pane inherited the width its closed neighbour had been- * dragged to, and the pane that owned it was squeezed instead).- *- * So the arrangement the weights belong to is tracked in a ref — updated by- * every action that already remaps — and persisted beside the weights. The- * effect below answers any drift between it and the session with the same- * remap the grid's own actions use, which also covers a fresh mount whose- * stored weights were keyed to an arrangement that changed while no grid- * was watching.- */- const weightsBasis = useRef<Record<string, number> | null>(null);- const weightsBasisFor = useRef<string | null>(null);-- /** Declare the weights remapped: they are keyed to ``terminals`` now. */- const rebaseWeights = useCallback(- (terminals: readonly { name: string; column: number; slot: number }[]) => {- const arrangement = paneArrangement(terminals);- weightsBasis.current = arrangement;- weightsBasisFor.current = session.id;- saveStoredArrangement(session.id, arrangement);- },- [session.id],- );-- useEffect(() => {- // A workspace switch loads that workspace's weights (see `usePaneWeights`),- // so the basis switches with it: its stored arrangement when one survives,- // otherwise the session as it stands — never the outgoing workspace's. A- // workspace seen for the first time stores its arrangement right away,- // because the stored copy is what makes the weights readable after a- // restart behind which the workspace changed.- if (weightsBasisFor.current !== session.id) {- weightsBasisFor.current = session.id;- const stored = loadStoredArrangement(session.id);- weightsBasis.current = stored ?? paneArrangement(session.terminals);- if (!stored) saveStoredArrangement(session.id, weightsBasis.current);- }- const basis = weightsBasis.current;- const current = paneArrangement(session.terminals);- if (!basis || sameArrangement(basis, current)) return;- // Never mid-drag. The gesture paints the panes directly and commits its- // weights from a snapshot taken at pointer-down (see `usePaneWeights`), so- // a remap here would both be clobbered by that commit and re-render every- // live terminal under the pointer. `sizes.dragging` is a dependency, so- // the drift is answered the moment the pointer is released.- if (sizes.dragging !== null) return;- // Runs AFTER the hook's own load effect in the same commit, so on a- // workspace switch this updater already sees that workspace's weights.- sizes.setWeights((weights) =>- remapColumnWeights(weights, panesFromArrangement(basis), session.terminals),- );- weightsBasis.current = current;- saveStoredArrangement(session.id, current);- }, [session.id, session.terminals, sizes.dragging, sizes.setWeights]);+ const alreadyEven = useMemo(() => isEvenTree(sizes.tree), [sizes.tree]);/** Hold the dragged sizes against anything else that renders mid-gesture.@@ -1511,7 +1439,7 @@ export function AgenticGrid({*/useLayoutEffect(() => {if (sizes.dragging === null) return;- const inFlight = sizes.liveWeights.current;+ const inFlight = sizes.liveTree.current;if (inFlight) paintDraggedLayout(inFlight);});@@ -1683,27 +1611,9 @@ export function AgenticGrid({// A fresh pane should receive the next prompt — that is why it was opened.const known = new Set(session.terminals.map((t) => t.name));const added = next.terminals.find((t) => !known.has(t.name));- /*- * A split HALVES the pane it was asked of, and touches nothing else.- *- * This is the behaviour people expect from every tiling terminal and- * editor, and the one the old workspace did not have: a new pane became a- * new full-height column, so every other pane on the line lost width to- * make room for it. Splitting the pane you clicked should be a local- * event — see `weightsAfterSplit`.- */- sizes.setWeights((current) =>- anchor && added- ? weightsAfterSplit(- current,- session.terminals,- next.terminals,- anchor,- added.name,- )- : remapColumnWeights(current, session.terminals, next.terminals),- );- rebaseWeights(next.terminals);+ // A split HALVES the pane it was asked of and touches nothing else —+ // the backend's tree already says so (`layout_tree.split_pane`), and+ // `next.layout` carries the result. Nothing to remap here any more.// ...unless it is a plain terminal — that one is typed into by hand, and// stealing the target would silently redirect the next prompt into a pane// that refuses it.@@ -1774,22 +1684,19 @@ export function AgenticGrid({* (they repeat the identical gesture, observed 2026-08-07). Saying* "already there" turns a silent nothing into an answer.*/- const placement = (- terms: readonly { name: string; column: number; slot: number }[],- ) => terms.map((pane) => `${pane.name}:${pane.column}.${pane.slot}`).join(" ");- if (placement(next.terminals) === placement(session.terminals)) {+ // The tree IS the placement, so "did anything move" is one comparison+ // — including moves the coarse column/slot hints cannot see, like a+ // drop that only changes nesting.+ if (+ JSON.stringify(next.layout ?? null) ===+ JSON.stringify(session.layout ?? null)+ ) {pushToast("info",t("agentic_grid.arrange.already_there").replace("{0}", moved),);return;}- // Column widths follow the panes that carried them, so a pane dropped- // into a wide column does not drag that column's width away with it.- sizes.setWeights((current) =>- remapColumnWeights(current, session.terminals, next.terminals),- );- rebaseWeights(next.terminals);onSessionChanged?.(next);setJustMoved({ name: moved, nonce: Date.now() });} catch (error) {@@ -1798,7 +1705,7 @@ export function AgenticGrid({setWorking(false);}},- [onSessionChanged, pushToast, rebaseWeights, session.terminals, sizes.setWeights, t],+ [onSessionChanged, pushToast, session.layout, t],);const arrange = usePaneArrange(@@ -2121,18 +2028,8 @@ export function AgenticGrid({);setSentAt((current) => rekey(current, from, to));setRestartTokens((current) => rekey(current, from, to));- // The pane's dragged height is keyed by call-sign too, and the basis- // map is what stops the remap effect from reading a rename as "one- // pane left, another arrived" — which would put the lone column of a- // renamed pane back at its default width.- sizes.setWeights((current) => ({- ...current,- panes: rekey(current.panes, from, to),- }));- if (weightsBasis.current) {- weightsBasis.current = rekey(weightsBasis.current, from, to);- saveStoredArrangement(session.id, weightsBasis.current);- }+ // The layout tree is keyed by the pane's KEY, which is exactly what a+ // rename leaves alone — sizes need no rekeying at all.setTarget((current) => (current === from ? to : current));setMaximized((current) => (current === from ? to : current));setPendingClose((current) => (current === from ? to : current));@@ -2157,7 +2054,7 @@ export function AgenticGrid({setWorking(false);}},- [onSessionChanged, pushToast, session.id, sizes.setWeights],+ [onSessionChanged, pushToast, session.id],);/** Where the bell's "jump to pane" goes — here, or via the view for a tab. */@@ -2194,10 +2091,8 @@ export function AgenticGrid({const next = await closeTerminal(name);setPendingClose(null);if (maximized === name) setMaximized(null);- // The surviving columns keep the widths they were dragged to; the closed- // pane's own height weight goes with it.- sizes.setWeights((current) => remapColumnWeights(current, session.terminals, next.terminals));- rebaseWeights(next.terminals);+ // The survivors keep the room they were dragged to — the backend's tree+ // dissolves the closed pane's share to its siblings (`remove_pane`).onSessionChanged?.(next);if (target === name) setTarget(next.terminals.find(takesPrompts)?.name ?? "");} catch (e) {@@ -2213,10 +2108,6 @@ export function AgenticGrid({const result = await closeTerminals(names);setPendingSelectionClose(null);setSelectedTerminals(new Set(result.failed.map((item) => item.name)));- sizes.setWeights((current) =>- remapColumnWeights(current, session.terminals, result.session.terminals),- );- rebaseWeights(result.session.terminals);onSessionChanged?.(result.session);const remaining = new Set(result.session.terminals.map((term) => term.name));if (maximized && !remaining.has(maximized)) setMaximized(null);@@ -2240,8 +2131,6 @@ export function AgenticGrid({}};- // No delivery event will arrive to clear the narration for this send.- setComposeBeat(null);const setStatus = useCallback((name: string, status: PaneStatus, detail?: string) => {setStatuses((prev) => ({ ...prev, [name]: { status, detail } }));}, []);@@ -2353,6 +2242,8 @@ export function AgenticGrid({}} catch (e) {pushToast("error", (e as Error).message);+ // No delivery event will arrive to clear the narration for this send.+ setComposeBeat(null);} finally {setSending(false);}@@ -3401,15 +3292,6 @@ export function AgenticGrid({onClick={() => composer.resize(COMPOSER_DEFAULT_PX)}className="flex shrink-0 items-center gap-1.5 rounded-control px-2 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground">- {composeBeat && (- <div- data-testid="agentic-compose-progress"- className="flex shrink-0 items-center gap-2 px-3 pt-2 text-[11px] text-muted-foreground"- >- <Loader2 className="h-3 w-3 shrink-0 animate-spin text-primary" />- <span className="truncate">{composeBeat.message}</span>- </div>- )}<ChevronUp className="h-3.5 w-3.5" />Write instead</button>@@ -3521,6 +3403,15 @@ export function AgenticGrid({/></div>)}+ {composeBeat && (+ <div+ data-testid="agentic-compose-progress"+ className="flex shrink-0 items-center gap-2 px-3 pt-2 text-[11px] text-muted-foreground"+ >+ <Loader2 className="h-3 w-3 shrink-0 animate-spin text-primary" />+ <span className="truncate">{composeBeat.message}</span>+ </div>+ )}{/*The input takes whatever the seam left over, which is the point ofdragging it: pull the bar up and you get a real writing surface, not adiff --git a/jarvis/ui/web/frontend/src/components/agentic/treeLayout.test.ts b/jarvis/ui/web/frontend/src/components/agentic/treeLayout.test.tsnew file mode 100644index 0000000000..df30f31609--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/treeLayout.test.ts@@ -0,0 +1,268 @@+/**+ * The split tree's client half: the geometry it draws, and the weight edits+ * a drag makes. Structure edits are the backend's (`layout_tree.py`) — these+ * tests cover what the GRID does with the tree it is handed.+ */+import { describe, expect, it } from "vitest";++import {+ dragSeam,+ evenSeam,+ evenedTree,+ isEvenTree,+ treeLayout,+ treeLeaves,+ type LayoutNode,+ type LayoutSplit,+} from "./treeLayout";++const panes = (...keys: string[]) =>+ keys.map((key) => ({ key, name: key.toUpperCase() }));++/** The reported drawing: T1|T3 in the top half, T2 full width below. */+const drawnShape: LayoutNode = {+ direction: "column",+ children: [+ {+ direction: "row",+ children: [{ pane: "t1" }, { pane: "t3" }],+ weights: [1, 1],+ },+ { pane: "t2" },+ ],+ weights: [1, 1],+};++describe("treeLayout", () => {+ it("draws the split-beside-the-top-pane shape the flat grid never could", () => {+ const { boxes } = treeLayout(drawnShape, panes("t1", "t3", "t2"));+ expect(boxes[0]).toEqual({ x: 0, y: 0, w: 0.5, h: 0.5 }); // t1 top-left+ expect(boxes[1]).toEqual({ x: 0.5, y: 0, w: 0.5, h: 0.5 }); // t3 top-right+ expect(boxes[2]).toEqual({ x: 0, y: 0.5, w: 1, h: 0.5 }); // t2 FULL width+ });++ it("puts a seam on every sibling boundary, addressed by container path", () => {+ const { seams } = treeLayout(drawnShape, panes("t1", "t3", "t2"));+ expect(seams).toHaveLength(2);+ const vertical = seams.find((seam) => seam.orientation === "vertical");+ const horizontal = seams.find((seam) => seam.orientation === "horizontal");+ expect(vertical).toMatchObject({ path: [0], boundary: 1, x: 0.5, h: 0.5 });+ expect(horizontal).toMatchObject({ path: [], boundary: 1, y: 0.5, w: 1 });+ expect(vertical?.label).toContain("T1");+ expect(vertical?.label).toContain("T3");+ });++ it("sizes children by their weights", () => {+ const tree: LayoutNode = {+ direction: "row",+ children: [{ pane: "t1" }, { pane: "t2" }],+ weights: [3, 1],+ };+ const { boxes } = treeLayout(tree, panes("t1", "t2"));+ expect(boxes[0]?.w).toBeCloseTo(0.75);+ expect(boxes[1]?.x).toBeCloseTo(0.75);+ expect(boxes[1]?.w).toBeCloseTo(0.25);+ });++ it("treats missing or junk weights as an even share", () => {+ const tree: LayoutNode = {+ direction: "row",+ children: [{ pane: "t1" }, { pane: "t2" }],+ weights: [Number.NaN],+ };+ const { boxes } = treeLayout(tree, panes("t1", "t2"));+ expect(boxes[0]?.w).toBeCloseTo(0.5);+ });++ it("falls back to an even row when the tree does not cover the panes", () => {+ const stale: LayoutNode = { pane: "ghost" };+ const { boxes, seams } = treeLayout(stale, panes("t1", "t2"));+ expect(boxes[0]).toEqual({ x: 0, y: 0, w: 0.5, h: 1 });+ expect(boxes[1]).toEqual({ x: 0.5, y: 0, w: 0.5, h: 1 });+ expect(seams).toHaveLength(1);+ });++ it("lays a lone pane out as the whole workspace", () => {+ const { boxes, seams } = treeLayout(null, panes("t1"));+ expect(boxes[0]).toEqual({ x: 0, y: 0, w: 1, h: 1 });+ expect(seams).toEqual([]);+ });++ it("reads leaves left-to-right, top-to-bottom", () => {+ expect(treeLeaves(drawnShape)).toEqual(["t1", "t3", "t2"]);+ });+});++describe("dragSeam", () => {+ const row: LayoutNode = {+ direction: "row",+ children: [{ pane: "t1" }, { pane: "t2" }],+ weights: [1, 1],+ };++ it("trades weight between the two neighbours and nobody else", () => {+ const { seams } = treeLayout(row, panes("t1", "t2"));+ const dragged = dragSeam(row, seams[0], 250, 1000) as LayoutSplit;+ expect(dragged.weights[0]).toBeCloseTo(1.5);+ expect(dragged.weights[1]).toBeCloseTo(0.5);+ });++ it("never drags a pane below its pixel floor", () => {+ const { seams } = treeLayout(row, panes("t1", "t2"));+ const dragged = dragSeam(row, seams[0], 100000, 1000) as LayoutSplit;+ // 120 px of 1000 is 0.24 of the pair's combined weight of 2.+ expect(dragged.weights[1]).toBeCloseTo(0.24);+ });++ it("converts pixels against the container's own span, not the window's", () => {+ // The stack occupies the right HALF, so its seam divides 500 of 1000 px.+ const nested: LayoutNode = {+ direction: "row",+ children: [+ { pane: "t1" },+ {+ direction: "column",+ children: [{ pane: "t2" }, { pane: "t3" }],+ weights: [1, 1],+ },+ ],+ weights: [1, 1],+ };+ const { seams } = treeLayout(nested, panes("t1", "t2", "t3"));+ const inner = seams.find((seam) => seam.orientation === "horizontal");+ expect(inner?.axisFraction).toBeCloseTo(1); // full height…+ const vertical = seams.find((seam) => seam.orientation === "vertical");+ expect(vertical?.axisFraction).toBeCloseTo(1); // …and full width at root+ });++ it("changes nothing when the workspace reshaped under the gesture", () => {+ const { seams } = treeLayout(row, panes("t1", "t2"));+ const reshaped: LayoutNode = { pane: "t1" };+ expect(dragSeam(reshaped, seams[0], 100, 1000)).toBe(reshaped);+ });++ it("leaves the tree it was given untouched", () => {+ const { seams } = treeLayout(row, panes("t1", "t2"));+ dragSeam(row, seams[0], 250, 1000);+ expect((row as LayoutSplit).weights).toEqual([1, 1]);+ });+});++describe("evening out", () => {+ it("evenSeam levels exactly the two neighbours", () => {+ const tree: LayoutNode = {+ direction: "row",+ children: [{ pane: "t1" }, { pane: "t2" }, { pane: "t3" }],+ weights: [3, 1, 2],+ };+ const { seams } = treeLayout(tree, panes("t1", "t2", "t3"));+ const levelled = evenSeam(tree, seams[0]) as LayoutSplit;+ expect(levelled.weights).toEqual([2, 2, 2]);+ expect((tree as LayoutSplit).weights).toEqual([3, 1, 2]);+ });++ it("evenedTree resets every container", () => {+ const dragged: LayoutNode = {+ direction: "column",+ children: [+ {+ direction: "row",+ children: [{ pane: "t1" }, { pane: "t3" }],+ weights: [3, 1],+ },+ { pane: "t2" },+ ],+ weights: [5, 1],+ };+ expect(isEvenTree(dragged)).toBe(false);+ const evened = evenedTree(dragged);+ expect(isEvenTree(evened)).toBe(true);+ });++ it("isEvenTree calls equal weights even whatever their scale", () => {+ const tree: LayoutNode = {+ direction: "row",+ children: [{ pane: "t1" }, { pane: "t2" }],+ weights: [7, 7],+ };+ expect(isEvenTree(tree)).toBe(true);+ });++ /**+ * The reported workspace of 2026-08-12: a row whose middle child is a+ * NESTED group of four terminals (two side-by-side stacks). Equal container+ * weights drew the grouped terminals at half the width of their neighbours,+ * yet the old per-container check called that "even" and disabled the+ * button — the click the report says "doesn't work" never ran.+ */+ const nestedWorkspace: LayoutNode = {+ direction: "row",+ children: [+ {+ direction: "column",+ children: [{ pane: "t2" }, { pane: "t8" }],+ weights: [1, 1],+ },+ { pane: "t1" },+ {+ direction: "column",+ children: [+ {+ direction: "row",+ children: [{ pane: "t3" }, { pane: "t6" }],+ weights: [1, 1],+ },+ {+ direction: "row",+ children: [{ pane: "t4" }, { pane: "t5" }],+ weights: [1, 1],+ },+ ],+ weights: [1, 1],+ },+ {+ direction: "column",+ children: [{ pane: "t9" }, { pane: "t11" }],+ weights: [1, 1],+ },+ ],+ weights: [1, 1, 1, 1],+ };++ it("calls a nested group at container-equal weights UNEVEN", () => {+ expect(isEvenTree(nestedWorkspace)).toBe(false);+ });++ it("evens a nested group to equal TERMINAL widths, arrangement untouched", () => {+ const evened = evenedTree(nestedWorkspace);+ expect(isEvenTree(evened)).toBe(true);+ expect(treeLeaves(evened)).toEqual(treeLeaves(nestedWorkspace));+ const { boxes } = treeLayout(+ evened,+ panes("t2", "t8", "t1", "t3", "t6", "t4", "t5", "t9", "t11"),+ );+ // Five stripes across: t2-stack, t1, t3, t6, t9-stack — every terminal+ // one fifth wide, including the four inside the nested group.+ for (const box of boxes) expect(box?.w).toBeCloseTo(0.2);+ // And the stacks still split at the middle.+ const t3 = boxes[3];+ expect(t3?.h).toBeCloseTo(0.5);+ });++ it("evenSeam levels the TERMINALS beside a nested group, not its wrapper", () => {+ const { seams } = treeLayout(+ nestedWorkspace,+ panes("t2", "t8", "t1", "t3", "t6", "t4", "t5", "t9", "t11"),+ );+ // The root seam between t1 and the nested group (children 1 and 2).+ const seam = seams.find(+ (candidate) => candidate.path.length === 0 && candidate.boundary === 2,+ );+ expect(seam).toBeDefined();+ const levelled = evenSeam(nestedWorkspace, seam!) as LayoutSplit;+ // Their combined weight of 2 splits one third / two thirds: the group+ // lines up two terminals, so each of the three ends up the same width.+ expect(levelled.weights[1]).toBeCloseTo(2 / 3);+ expect(levelled.weights[2]).toBeCloseTo(4 / 3);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/treeLayout.ts b/jarvis/ui/web/frontend/src/components/agentic/treeLayout.tsnew file mode 100644index 0000000000..c8e0356f09--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/treeLayout.ts@@ -0,0 +1,401 @@+/**+ * The workspace's split tree, and the geometry it draws as.+ *+ * The workspace used to be a flat "columns × slots" grid (`./paneLayout`, now+ * retired). That model made one split direction local and the other global by+ * construction: "split right" could only mean a full-height column, so+ * splitting the top pane of a stack restructured the whole workspace — the+ * exact complaint of 2026-08-12, delivered as a drawing.+ *+ * The BACKEND now owns the layout as a split tree (`jarvis/agentic_ide/+ * layout_tree.py`): a `row` lays its children side by side, a `column` stacks+ * them, a leaf is one pane, and every split carves only the clicked pane's+ * rectangle. This module is the tree's client half:+ *+ * * `treeLayout` turns the tree the session state carries into the same kind+ * of fractional boxes and draggable seams the grid has always painted —+ * panes stay absolutely positioned siblings inside ONE container, so+ * nothing is ever re-parented and no terminal remounts.+ * * `dragSeam` / `evenSeam` / `evenedTree` rewrite WEIGHTS, immutably, and+ * are the only edits a client ever makes to the tree. Structure changes+ * (split, close, move) are asked of the backend, whose answer carries the+ * new tree — one authority, never two placement arithmetics drifting.+ *+ * ## Weights, not pixels+ *+ * A weight is a plain multiplier against its siblings (1 and 1 are equal, 2+ * and 1 is a third), never pixels — pixels do not survive a window resize, a+ * second monitor, or the app opening on a laptop. The seam-drag math is the+ * proven arithmetic from the retired module, unchanged: pixels become weight+ * through the workspace's size along the drag axis, scaled by the fraction of+ * that axis the seam's own container spans (a nested stack's seam divides the+ * stack, not the window).+ *+ * ## Wire form IS the working form+ *+ * The session state's `layout` field arrives as exactly these shapes —+ * `{pane}` leaves and `{direction, children, weights}` splits — so there is+ * no parse step and no second representation to keep in sync. What the drag+ * hook posts back (`saveLayoutWeights`) is the same value.+ */++/** One pane, referenced by its terminal KEY ("t1") — stable across renames. */+export interface LayoutLeaf {+ pane: string;+}++/** A container: children side by side (`row`) or stacked (`column`). */+export interface LayoutSplit {+ direction: "row" | "column";+ children: LayoutNode[];+ weights: number[];+}++export type LayoutNode = LayoutLeaf | LayoutSplit;++export function isSplit(node: LayoutNode): node is LayoutSplit {+ return typeof node === "object" && node !== null && "children" in node;+}++/** Smallest a pane may be dragged to, on either axis. */+export const MIN_SEAM_PANE_PX = 120;++/** A pane's rectangle, as fractions of the workspace on both axes. */+export interface PaneBox {+ x: number;+ y: number;+ w: number;+ h: number;+}++/**+ * A draggable boundary between two siblings of one container.+ *+ * `x`/`y`/`w`/`h` describe the LINE: a vertical seam has no width and a+ * horizontal one no height, so the renderer positions it by its centre and+ * stretches it along the other axis.+ *+ * `path` + `boundary` are the seam's address: the container's child-index+ * path from the root, and the gap it divides (between children `boundary-1`+ * and `boundary`). A drag resolves them against the tree it STARTED from, so+ * a slow pointer cannot land its weights on a container that moved.+ */+export interface PaneSeam {+ id: string;+ orientation: "vertical" | "horizontal";+ x: number;+ y: number;+ w: number;+ h: number;+ /** Child-index path from the root to the container this seam divides. */+ path: number[];+ /** The gap's index within that container: between boundary-1 and boundary. */+ boundary: number;+ /** Combined weight of every sibling the drag redistributes within. */+ groupWeight: number;+ /**+ * Fraction of the workspace axis the container spans along the drag axis —+ * what turns a pointer's pixels into weight. 1 for a root-level seam; a+ * seam inside a half-width stack works against that half.+ */+ axisFraction: number;+ /** Plain-language name, used as the seam's tooltip and accessible label. */+ label: string;+}++/** Everything the grid needs to draw a workspace at the sizes it was given. */+export interface WorkspaceLayout {+ /** One box per input pane, in input order. */+ boxes: (PaneBox | undefined)[];+ seams: PaneSeam[];+}++function cleanWeight(value: unknown): number {+ const number = typeof value === "number" ? value : Number(value);+ return Number.isFinite(number) && number > 0 ? number : 1;+}++/** Every pane key in reading order — depth-first, left/top first. */+export function treeLeaves(node: LayoutNode | null | undefined): string[] {+ if (!node) return [];+ if (!isSplit(node)) return [node.pane];+ return node.children.flatMap((child) => treeLeaves(child));+}++const firstLeaf = (node: LayoutNode): string =>+ isSplit(node) ? firstLeaf(node.children[0]) : node.pane;+const lastLeaf = (node: LayoutNode): string =>+ isSplit(node) ? lastLeaf(node.children[node.children.length - 1]) : node.pane;++/** The minimum a pane must know for this module: its key, and a spoken name. */+export interface SizedPane {+ key: string;+ name: string;+}++/**+ * Lay the workspace out: the tree in, boxes and seams out.+ *+ * The tree normally covers exactly the session's panes — the backend keeps it+ * that way. When it does not (a half-applied update racing a poll), the panes+ * are laid out as one even row instead: every pane visible somewhere beats a+ * blank rectangle, and the next state push repairs the shape.+ */+export function treeLayout(+ tree: LayoutNode | null | undefined,+ panes: readonly SizedPane[],+): WorkspaceLayout {+ if (panes.length === 0) return { boxes: [], seams: [] };++ const keys = new Set(panes.map((pane) => pane.key));+ const covered = treeLeaves(tree);+ const usable =+ tree != null &&+ covered.length === keys.size &&+ covered.every((pane) => keys.has(pane));+ const root: LayoutNode = usable+ ? (tree as LayoutNode)+ : panes.length === 1+ ? { pane: panes[0].key }+ : {+ direction: "row",+ children: panes.map((pane) => ({ pane: pane.key })),+ weights: panes.map(() => 1),+ };++ const names = new Map(panes.map((pane) => [pane.key, pane.name]));+ const byKey = new Map<string, PaneBox>();+ const seams: PaneSeam[] = [];++ const walk = (node: LayoutNode, box: PaneBox, path: number[]): void => {+ if (!isSplit(node)) {+ byKey.set(node.pane, box);+ return;+ }+ const along = node.direction === "row" ? box.w : box.h;+ const weights = node.children.map((_, index) => cleanWeight(node.weights[index]));+ const total = weights.reduce((sum, weight) => sum + weight, 0) || 1;+ let cursor = node.direction === "row" ? box.x : box.y;+ // "root" for the top-level container, else the child-index path — short,+ // stable while the structure stands, and readable in a test failure.+ const at = path.length === 0 ? "root" : path.join(".");+ node.children.forEach((child, index) => {+ const share = (weights[index] / total) * along;+ if (index > 0) {+ const before = names.get(lastLeaf(node.children[index - 1])) ?? "the pane before";+ const after = names.get(firstLeaf(child)) ?? "the pane after";+ seams.push(+ node.direction === "row"+ ? {+ id: `${at}:${index}`,+ orientation: "vertical",+ x: cursor,+ y: box.y,+ w: 0,+ h: box.h,+ path,+ boundary: index,+ groupWeight: total,+ axisFraction: box.w,+ label: `Drag to resize ${before} and ${after}`,+ }+ : {+ id: `${at}:${index}`,+ orientation: "horizontal",+ x: box.x,+ y: cursor,+ w: box.w,+ h: 0,+ path,+ boundary: index,+ groupWeight: total,+ axisFraction: box.h,+ label: `Drag to resize ${before} and ${after}`,+ },+ );+ }+ walk(+ child,+ node.direction === "row"+ ? { x: cursor, y: box.y, w: share, h: box.h }+ : { x: box.x, y: cursor, w: box.w, h: share },+ [...path, index],+ );+ cursor += share;+ });+ };++ walk(root, { x: 0, y: 0, w: 1, h: 1 }, []);+ return { boxes: panes.map((pane) => byKey.get(pane.key)), seams };+}++/** The container a seam's path names, resolved against ``root`` — or null. */+function containerAt(root: LayoutNode, path: number[]): LayoutSplit | null {+ let node: LayoutNode = root;+ for (const index of path) {+ if (!isSplit(node)) return null;+ const child: LayoutNode | undefined = node.children[index];+ if (!child) return null;+ node = child;+ }+ return isSplit(node) ? node : null;+}++/** ``root`` with the container at ``path`` carrying ``weights`` — immutably. */+function withWeights(root: LayoutNode, path: number[], weights: number[]): LayoutNode {+ if (!isSplit(root)) return root;+ if (path.length === 0) return { ...root, weights };+ const [head, ...rest] = path;+ const child = root.children[head];+ if (!child) return root;+ const children = [...root.children];+ children[head] = withWeights(child, rest, weights);+ return { ...root, children };+}++/**+ * Move one seam by ``deltaPx`` and hand back the tree that produces it.+ *+ * The two neighbours trade weight and nothing else changes — that is what+ * makes a drag local rather than a re-layout. Both sides are held at+ * `MIN_SEAM_PANE_PX`, and two panes that cannot both meet the minimum share+ * what there is evenly rather than one being dragged out of existence. A seam+ * whose container no longer exists (the workspace reshaped mid-gesture)+ * changes nothing.+ */+export function dragSeam(+ root: LayoutNode,+ seam: PaneSeam,+ deltaPx: number,+ axisPx: number,+): LayoutNode {+ const span = axisPx * seam.axisFraction;+ if (!Number.isFinite(span) || span <= 0) return root;+ const node = containerAt(root, seam.path);+ if (!node || seam.boundary < 1 || seam.boundary >= node.children.length) return root;++ const weights = node.children.map((_, index) => cleanWeight(node.weights[index]));+ const before = weights[seam.boundary - 1];+ const after = weights[seam.boundary];+ const total = before + after;+ const perPx = seam.groupWeight / span;+ const min = MIN_SEAM_PANE_PX * perPx;++ let nextBefore: number;+ if (total <= min * 2) {+ nextBefore = total / 2;+ } else {+ const wanted = before + deltaPx * perPx;+ nextBefore = Math.min(total - min, Math.max(min, wanted));+ }+ weights[seam.boundary - 1] = nextBefore;+ weights[seam.boundary] = total - nextBefore;+ return withWeights(root, seam.path, weights);+}++/**+ * How many pane stripes a subtree lines up along ``direction``.+ *+ * "Even" is judged in TERMINALS, not in tree children: a nested group holding+ * two side-by-side stacks is two stripes wide and must be given twice the+ * weight of a lone pane for every terminal to come out the same width. A+ * split running the other way does not multiply — its widest member is how+ * much room the group needs. Without this, a workspace like+ * ``row[pane, group-of-two, pane]`` "evens" to quarters and the grouped+ * terminals end up half as wide as their neighbours (reported 2026-08-12).+ */+function axisSpan(node: LayoutNode, direction: "row" | "column"): number {+ if (!isSplit(node)) return 1;+ const spans = node.children.map((child) => axisSpan(child, direction));+ if (spans.length === 0) return 1;+ return node.direction === direction+ ? spans.reduce((sum, span) => sum + span, 0)+ : Math.max(...spans);+}++/**+ * Level a seam's two neighbours, leaving every other pane alone.+ *+ * Their combined weight is dealt out by stripe count, so "level" means the+ * TERMINALS either side end up the same size even when one side is a nested+ * group — the same yardstick `evenedTree` and `isEvenTree` use.+ */+export function evenSeam(root: LayoutNode, seam: PaneSeam): LayoutNode {+ const node = containerAt(root, seam.path);+ if (!node || seam.boundary < 1 || seam.boundary >= node.children.length) return root;+ const weights = node.children.map((_, index) => cleanWeight(node.weights[index]));+ const before = axisSpan(node.children[seam.boundary - 1], node.direction);+ const after = axisSpan(node.children[seam.boundary], node.direction);+ const total = weights[seam.boundary - 1] + weights[seam.boundary];+ weights[seam.boundary - 1] = (total * before) / (before + after);+ weights[seam.boundary] = (total * after) / (before + after);+ return withWeights(root, seam.path, weights);+}++/**+ * The same tree with every TERMINAL back at an equal share of the workspace.+ *+ * Weights are stripe counts rather than a flat 1, so a nested group is given+ * as much room as the terminals it lines up — the arrangement itself is never+ * touched, only how the boundaries fall.+ */+export function evenedTree(root: LayoutNode): LayoutNode {+ if (!isSplit(root)) return root;+ return {+ ...root,+ children: root.children.map((child) => evenedTree(child)),+ weights: root.children.map((child) => axisSpan(child, root.direction)),+ };+}++/**+ * Same structure, same panes in the same places — weights ignored.+ *+ * The drag hook keeps its locally dragged weights only while the server's+ * tree still has this shape; a structural change (a split, a close, a move,+ * another client) always wins over an in-flight size preference.+ */+export function sameShape(+ a: LayoutNode | null | undefined,+ b: LayoutNode | null | undefined,+): boolean {+ if (!a || !b) return !a && !b;+ const aSplit = isSplit(a);+ const bSplit = isSplit(b);+ if (!aSplit || !bSplit) {+ return !aSplit && !bSplit && (a as LayoutLeaf).pane === (b as LayoutLeaf).pane;+ }+ if (a.direction !== b.direction || a.children.length !== b.children.length) {+ return false;+ }+ return a.children.every((child, index) => sameShape(child, b.children[index]));+}++/**+ * How far apart two sibling weights may be and still count as the same size.+ *+ * Relative, because weights are multipliers: 7 and 7.0000001 are the same+ * pane on any physical screen, and so are 1 and 1.00000001.+ */+const EVEN_EPSILON = 1e-4;++/**+ * Is every TERMINAL already at the share `evenedTree` would give it?+ *+ * Judged per stripe, the way `evenedTree` deals weights out — the button this+ * answers for disables on "already even", so the two must agree or the fix+ * for an uneven workspace is a control that refuses the click (the 2026-08-12+ * report: equal container weights over a nested group read as "even" while+ * one terminal drew four times the size of another).+ */+export function isEvenTree(root: LayoutNode | null | undefined): boolean {+ if (!root || !isSplit(root)) return true;+ const shares = root.children.map(+ (child, index) => cleanWeight(root.weights[index]) / axisSpan(child, root.direction),+ );+ const first = shares[0];+ if (!shares.every((share) => Math.abs(share - first) <= EVEN_EPSILON * first)) {+ return false;+ }+ return root.children.every((child) => isEvenTree(child));+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/useTreeSizes.ts b/jarvis/ui/web/frontend/src/components/agentic/useTreeSizes.tsnew file mode 100644index 0000000000..2a897ea101--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/useTreeSizes.ts@@ -0,0 +1,262 @@+/**+ * The workspace's own sizes: held while you drag them, remembered afterwards.+ *+ * The split tree the backend sends (`SessionState.layout`) carries both the+ * arrangement AND the weights, so sizes are no longer a browser-local+ * sidecar: a drag edits the local copy for the duration of the gesture and+ * then posts the result back (`saveLayoutWeights`). That is what lets sizes+ * survive an app restart on any machine, come back with a resumed workspace,+ * and stay one single authority — the localStorage weights this replaces+ * could disagree with the workspace whenever the backend reshaped it while+ * no grid was watching, and needed a whole remapping machinery to catch up.+ *+ * The backend, in turn, only ever ADOPTS weights into the shape it already+ * has, so a drag racing a voice-opened pane loses quietly and the next state+ * push snaps the grid to reality.+ *+ * ## Why a drag does not go through React+ *+ * `onPreview` is handed each frame's tree INSTEAD of state being written, and+ * state is written exactly once, when the pointer is released. A pointer+ * emits up to 120 moves a second, and every pane is a live terminal — routing+ * the gesture through state re-rendered the whole wall per move and dropped+ * the drag to a few frames a second (see the history in the retired+ * `usePaneWeights`). Painting the boxes directly costs one layout computation+ * and N style writes per frame and does not touch React at all.+ */+import { useCallback, useEffect, useRef, useState } from "react";++import { saveLayoutWeights } from "../../lib/agenticIdeApi";+import {+ dragSeam,+ evenSeam,+ evenedTree,+ sameShape,+ type LayoutNode,+ type PaneSeam,+} from "./treeLayout";++/** How far one arrow-key press moves a seam. Matches `PaneResizer`. */+const KEY_STEP_PX = 16;++/** How long after the last size edit the result is posted to the backend. */+const SAVE_DEBOUNCE_MS = 600;++/** How big the workspace currently is, in px, along each axis. */+export interface WorkspaceExtent {+ width: number;+ height: number;+}++export interface TreeSizeControls {+ /** The tree to lay out: the user's fresher local sizes, else the server's. */+ tree: LayoutNode | null;+ /** Id of the seam being dragged right now, if any. */+ dragging: string | null;+ /** Begin a drag — wire to a seam's `onPointerDown`. */+ startDrag: (seam: PaneSeam, event: React.PointerEvent) => void;+ /** Move a seam by ``deltaPx`` — the keyboard equivalent of a drag. */+ nudge: (seam: PaneSeam, deltaPx: number) => void;+ /** Give a seam's two neighbours the same size — wire to `onDoubleClick`. */+ even: (seam: PaneSeam) => void;+ /** Every pane back to an equal share — the toolbar's "even out". */+ evenAll: () => void;+ /**+ * The tree a drag is currently at, or null when nothing is being dragged.+ * How a caller that repaints mid-gesture recovers the in-flight sizes.+ */+ liveTree: React.MutableRefObject<LayoutNode | null>;+}++/**+ * Drag state for every seam in one workspace.+ *+ * `serverTree` is the layout the session state carries; `extent` is read as a+ * function because the workspace can be resized mid-drag and the+ * pixels-to-weight conversion has to use the size the seam is actually being+ * dragged across.+ */+export function useTreeSizes(+ serverTree: LayoutNode | null | undefined,+ extent: () => WorkspaceExtent,+ onPreview?: (tree: LayoutNode) => void,+): TreeSizeControls {+ /*+ * The local override holds sizes the user chose that the server has not+ * echoed back yet. It stays in force exactly as long as the server's tree+ * keeps the shape it was dragged against: any structural change — a split,+ * a close, a move, another client — wins immediately, because a stale+ * override laid over a reshaped workspace would place panes that no longer+ * exist.+ */+ const [override, setOverride] = useState<LayoutNode | null>(null);+ const tree =+ override && sameShape(override, serverTree ?? null)+ ? override+ : (serverTree ?? null);++ const [dragging, setDragging] = useState<string | null>(null);++ /*+ * Saves are debounced and fire-and-forget: a run of arrow-key nudges is one+ * write, and a failed write costs nothing but persistence — the sizes stay+ * on screen from the override, and the next successful edit re-sends the+ * whole tree anyway.+ */+ const pendingSave = useRef<LayoutNode | null>(null);+ const saveTimer = useRef<number | undefined>(undefined);+ const flushSave = useCallback(() => {+ if (saveTimer.current !== undefined) {+ window.clearTimeout(saveTimer.current);+ saveTimer.current = undefined;+ }+ const unsaved = pendingSave.current;+ pendingSave.current = null;+ if (!unsaved) return;+ saveLayoutWeights(unsaved).catch((error) => {+ console.warn("Agentic IDE: pane sizes were not persisted:", error);+ });+ }, []);+ const commit = useCallback(+ (next: LayoutNode) => {+ setOverride(next);+ pendingSave.current = next;+ if (saveTimer.current !== undefined) window.clearTimeout(saveTimer.current);+ saveTimer.current = window.setTimeout(flushSave, SAVE_DEBOUNCE_MS);+ },+ [flushSave],+ );+ // An unmount (switching workspaces, closing the view) must not eat the last+ // gesture — post whatever is still waiting on the way out.+ useEffect(() => flushSave, [flushSave]);++ // Drag anchors — refs so the move handler never reads a stale closure. The+ // drag works from the tree it STARTED with, so a slow pointer cannot+ // accumulate rounding drift over a hundred frames.+ const active = useRef<{ seam: PaneSeam; point: number; from: LayoutNode } | null>(+ null,+ );+ const point = useRef(0);+ const live = useRef<LayoutNode | null>(null);++ const treeRef = useRef(tree);+ treeRef.current = tree;+ const extentRef = useRef(extent);+ extentRef.current = extent;+ const previewRef = useRef(onPreview);+ previewRef.current = onPreview;++ const startDrag = useCallback((seam: PaneSeam, event: React.PointerEvent) => {+ const from = treeRef.current;+ if (!from) return;+ event.preventDefault();+ const at = seam.orientation === "vertical" ? event.clientX : event.clientY;+ active.current = { seam, point: at, from };+ point.current = at;+ live.current = null;+ setDragging(seam.id);+ }, []);++ useEffect(() => {+ if (!dragging) return;++ const axisPx = (seam: PaneSeam) => {+ const size = extentRef.current();+ return seam.orientation === "vertical" ? size.width : size.height;+ };++ // One computation and one paint per FRAME, however many moves the pointer+ // delivered in it.+ let frame: number | undefined;+ const apply = () => {+ frame = undefined;+ const drag = active.current;+ if (!drag) return;+ const next = dragSeam(+ drag.from,+ drag.seam,+ point.current - drag.point,+ axisPx(drag.seam),+ );+ live.current = next;+ if (previewRef.current) previewRef.current(next);+ else commit(next);+ };++ const onMove = (event: PointerEvent) => {+ const drag = active.current;+ if (!drag) return;+ point.current =+ drag.seam.orientation === "vertical" ? event.clientX : event.clientY;+ if (frame === undefined) frame = requestAnimationFrame(apply);+ };+ const settle = () => {+ // Land the last move before committing, so the sizes React is told+ // about are the ones already on screen.+ if (frame !== undefined) {+ cancelAnimationFrame(frame);+ apply();+ }+ const settled = live.current;+ active.current = null;+ live.current = null;+ setDragging(null);+ if (settled) commit(settled);+ };+ const onUp = () => settle();+ // A cancelled pointer (a touch taken over by the browser, a window that+ // lost the device) must commit too: the boxes are already painted at the+ // dragged sizes.+ const onCancel = () => settle();++ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", onUp);+ window.addEventListener("pointercancel", onCancel);+ // Lock the cursor and suppress text selection for the whole drag, so the+ // pointer can wander off the 6px grip without the drag looking broken.+ const previousCursor = document.body.style.cursor;+ const previousSelect = document.body.style.userSelect;+ document.body.style.cursor =+ active.current?.seam.orientation === "vertical" ? "col-resize" : "row-resize";+ document.body.style.userSelect = "none";++ return () => {+ if (frame !== undefined) cancelAnimationFrame(frame);+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onUp);+ window.removeEventListener("pointercancel", onCancel);+ document.body.style.cursor = previousCursor;+ document.body.style.userSelect = previousSelect;+ };+ }, [commit, dragging]);++ const nudge = useCallback(+ (seam: PaneSeam, deltaPx: number) => {+ const current = treeRef.current;+ if (!current) return;+ const size = extentRef.current();+ const axis = seam.orientation === "vertical" ? size.width : size.height;+ commit(dragSeam(current, seam, deltaPx, axis));+ },+ [commit],+ );++ const even = useCallback(+ (seam: PaneSeam) => {+ const current = treeRef.current;+ if (!current) return;+ commit(evenSeam(current, seam));+ },+ [commit],+ );++ const evenAll = useCallback(() => {+ const current = treeRef.current;+ if (!current) return;+ commit(evenedTree(current));+ }, [commit]);++ return { tree, dragging, startDrag, nudge, even, evenAll, liveTree: live };+}++export { KEY_STEP_PX };diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 503fca5935..a20504ddba 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -2,6 +2,10 @@// workspaceApi/chatsApi), `no-store` everywhere because WebView2 happily serves// a stale folder listing or terminal state from cache otherwise.+// Type-only: the split tree's wire form is defined next to the code that lays+// it out, and the session state simply carries it.+import type { LayoutNode } from "../components/agentic/treeLayout";+export interface AgentStatus {name: string;display_name: string;@@ -140,9 +144,13 @@ export interface TerminalState {*/accepts_prompts?: boolean;index: number;- /** Grid column, left to right. Each column is its own stack of panes. */+ /**+ * Coarse "roughly which column" hint, derived from the workspace's split+ * tree. The GEOMETRY is `SessionState.layout`; these two numbers survive+ * for consumers that only talk about the grid (the resume offer's dots).+ */column: number;- /** Position within that column, top to bottom. */+ /** Coarse position within that column, top to bottom — same caveat. */slot: number;status: "pending" | "live" | "exited" | "error";exit_code: number | null;@@ -305,6 +313,12 @@ export interface SessionState {project: ProjectProfile;created_at: number;focus_mode: boolean;+ /**+ * WHERE every pane sits and how much room it has — the split tree the grid+ * draws from (see `components/agentic/treeLayout`). Null only while the+ * workspace has no panes; absent from states sent by older backends.+ */+ layout?: LayoutNode | null;terminals: TerminalState[];}@@ -1032,6 +1046,27 @@ export async function addTerminal(payload: {return body.state.session;}+/**+ * Persist the pane sizes a seam drag produced.+ *+ * Sends back the whole tree this client was looking at. The backend adopts+ * only the WEIGHTS, and only while the workspace still has that shape — a+ * drag that raced a voice-opened pane is quietly declined, and the returned+ * state carries the authoritative tree either way.+ */+export async function saveLayoutWeights(layout: LayoutNode): Promise<SessionState> {+ const res = await fetch("/api/agentic-ide/layout/weights", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ layout }),+ });+ 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 saving pane sizes.");+ 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";