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(ide): dock terminals in both directions and expand workspace navigation

rubenluetke10-beep08595f5a437e
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index f37d954a16..a4e3775956 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -2376,11 +2376,10 @@ class Registry:
"""Keep legacy geometry consistent with the persistent terminal order."""
# Rebuild the legacy split tree from the new order. Old geometry
# must never sort the terminals back into their previous positions.
- columns = (
- len(session.terminals)
- if len(session.terminals) <= 4
- else (len(session.terminals) + 1) // 2
- )
+ count = len(session.terminals)
+ # Two panes read best side by side. From three onward, balance the
+ # group into at most two rows and four columns (six becomes 3 x 2).
+ columns = 2 if count == 2 else min(4, (count + 1) // 2)
rows = [
layout_tree.normalize(
layout_tree.Split(
diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx
index 68ee323bab..fa2d16b1cf 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx
@@ -26,7 +26,9 @@ afterEach(cleanup);
it("keeps a manual collapse across polling and remount", () => {
const { unmount } = render(<IdeProjectTree />);
const selected = screen.getByTestId("ide-workspace-p1-w1");
- expect(selected.className).toContain("bg-muted");
+ expect(selected.parentElement?.className).toContain("bg-muted");
+ expect(selected.className).toContain("min-h-10");
+ expect(screen.getByTestId("ide-project-p1").firstElementChild?.className).toContain("min-h-11");
fireEvent.click(screen.getByRole("button", { name: "Collapse App" }));
expect(screen.queryByTestId("ide-workspace-p1-w1")).toBeNull();
act(() => useIdeProjectsStore.getState().publish([{ ...project() }], "p1-w1"));
@@ -83,6 +85,17 @@ it("marks a queued workspace before the active workspace changes", () => {
expect(row.textContent).toContain("Switching workspace");
});
+it("offers workspace options only on the active row and dispatches Jarvis Live", () => {
+ const second = { ...project("p2"), workspaces: [{ ...project("p2").workspaces[0], name: "Other" }] };
+ useIdeProjectsStore.setState({ projects: [project(), second] });
+ render(<IdeProjectTree />);
+ fireEvent.click(screen.getByRole("button", { name: "Workspace options for Work" }));
+ expect(useIdeProjectsStore.getState().action).toMatchObject({ kind: "workspace-options", workspaceId: "p1-w1" });
+ expect(screen.queryByRole("button", { name: "Workspace options for Other" })).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Jarvis Live" }));
+ expect(useIdeProjectsStore.getState().action?.kind).toBe("toggle-voice");
+});
+
it("pins and renames via the project API, then requests a guarded refresh", async () => {
render(<IdeProjectTree />);
fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));
diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx
index 6ab2e41de8..a5d7b317ae 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from "react";
-import { Check, ChevronDown, ChevronRight, Folder, Loader2, MoreHorizontal, Pin, Plus, X } from "lucide-react";
+import { Check, ChevronDown, ChevronRight, Folder, Loader2, Mic, MoreHorizontal, Pin, Plus, X } from "lucide-react";
import { ChatLibraryError, openProject, patchProject } from "@/lib/chatLibraryApi";
import type { IdeProject, ProjectWorkspace } from "@/lib/agenticIdeApi";
import { useEventStore } from "@/store/events";
@@ -28,6 +28,8 @@ export function IdeProjectTree() {
const connectProject = useIdeProjectsStore((state) => state.connectProject);
const newWorkspace = useIdeProjectsStore((state) => state.newWorkspace);
const activateWorkspace = useIdeProjectsStore((state) => state.activateWorkspace);
+ const openWorkspaceOptions = useIdeProjectsStore((state) => state.openWorkspaceOptions);
+ const toggleVoice = useIdeProjectsStore((state) => state.toggleVoice);
const requestRefresh = useIdeProjectsStore((state) => state.requestRefresh);
const pushToast = useEventStore((state) => state.pushToast);
const [expansion, setExpansion] = useState(readExpansion);
@@ -117,7 +119,7 @@ export function IdeProjectTree() {
const working = mutatingId === project.id;
const count = project.workspaces.reduce((total, workspace) => total + workspace.terminals, 0);
return <div key={project.id} className="mb-0.5" data-testid={`ide-project-${project.id}`}>
- <div className={`group relative flex min-h-9 items-center rounded-lg border border-transparent transition-colors hover:bg-muted/70 ${active ? "border-border/60 bg-muted" : ""}`}>
+ <div className={`group relative flex min-h-11 items-center rounded-xl border border-transparent transition-colors hover:bg-muted/70 ${active ? "border-border/50 bg-muted/55" : ""}`}>
{renamingId === project.id ? <form className="flex min-w-0 flex-1 items-center gap-1 px-2" onSubmit={(event) => { event.preventDefault(); const name = draftName.trim(); if (name && name !== project.name) void mutate(project, { name }); else setRenamingId(null); }}>
<input autoFocus aria-label={`Rename ${project.name}`} value={draftName} maxLength={80} disabled={working}
onChange={(event) => setDraftName(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); setRenamingId(null); } }}
@@ -127,13 +129,14 @@ export function IdeProjectTree() {
</form> : <>
<button type="button" aria-label={`${open ? "Collapse" : "Expand"} ${project.name}`} aria-expanded={open}
onClick={() => setProjectOpen(project.id, !open)}
- className="flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ title={project.name}
+ className="flex min-w-0 flex-1 items-center gap-2.5 px-2.5 py-2.5 text-left text-[16px] font-medium text-foreground group-hover:pr-16 group-focus-within:pr-16 [@media(hover:none)]:pr-16 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{open ? <ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
- <Folder className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <Folder className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{project.name}</span>
- {count > 0 && <span className="rounded bg-background/50 px-1.5 text-[11px] tabular-nums text-muted-foreground" aria-label={`${count} agent ${count === 1 ? "session" : "sessions"}`}>{count}</span>}
+ {count > 0 && <span className="rounded-md bg-background/50 px-1.5 py-0.5 text-xs tabular-nums text-muted-foreground" aria-label={`${count} agent ${count === 1 ? "session" : "sessions"}`}>{count}</span>}
</button>
- <div className="relative flex shrink-0 items-center pr-1" data-project-menu={project.id}>
+ <div className={`absolute right-1 top-1/2 flex -translate-y-1/2 items-center transition-opacity ${menuId === project.id ? "opacity-100" : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100"}`} data-project-menu={project.id}>
<button type="button" aria-label={`Project actions for ${project.name}`} title="Project actions" aria-expanded={menuId === project.id}
onClick={() => setMenuId((current) => current === project.id ? null : project.id)}
className="rounded p-1.5 text-muted-foreground/70 hover:bg-background/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
@@ -152,33 +155,44 @@ export function IdeProjectTree() {
</div>
</>}
</div>
- {open && <div className="ml-5 border-l border-border/70 pl-2">
+ {open && <div className="ml-5 border-l border-border/70 pl-2 pt-0.5">
{project.workspaces.map((workspace: ProjectWorkspace) => {
const pending = workspace.id === pendingWorkspaceId;
const selected = workspace.id === activeWorkspaceId;
- return <button key={workspace.id} type="button" data-testid={`ide-workspace-${workspace.id}`}
+ return <div key={workspace.id} className={`group/space flex min-h-10 items-center rounded-xl border border-transparent transition-colors hover:bg-muted/70 ${selected ? "border-border/50 bg-muted text-foreground" : ""} ${pending ? "bg-muted/80 text-foreground" : ""}`}>
+ <button type="button" data-testid={`ide-workspace-${workspace.id}`}
aria-current={selected ? "page" : undefined} aria-busy={pending || undefined}
title={workspace.status === "closed" && !workspace.restorable ? "This workspace cannot be restored on this machine" : undefined}
disabled={workspace.status === "closed" && !workspace.restorable}
onClick={() => activateWorkspace(workspace.id)}
- className={`flex min-h-8 w-full items-center gap-2 rounded-md border border-transparent px-2 text-left text-xs transition-colors hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-45 ${selected ? "border-border/60 bg-muted text-foreground" : "text-muted-foreground"} ${pending ? "bg-muted/80 text-foreground" : ""}`}>
- {pending ? <Loader2 aria-hidden className="h-3 w-3 shrink-0 animate-spin" />
- : <span aria-hidden className={`h-1.5 w-1.5 shrink-0 rounded-full ${workspace.status === "open" && workspace.live_terminals > 0 ? "bg-emerald-500" : "bg-muted-foreground/40"}`} />}
+ className={`flex min-h-10 min-w-0 flex-1 items-center gap-2.5 rounded-xl px-2.5 text-left text-[15px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-45 ${selected || pending ? "text-foreground" : "text-muted-foreground"}`}>
+ {pending ? <Loader2 aria-hidden className="h-3.5 w-3.5 shrink-0 animate-spin" />
+ : <span aria-hidden className={`h-2 w-2 shrink-0 rounded-full ${workspace.status === "open" && workspace.live_terminals > 0 ? "bg-emerald-500" : "bg-muted-foreground/40"}`} />}
<span className="min-w-0 flex-1 truncate">{workspace.name}</span>
- <span className="tabular-nums opacity-70">{workspace.terminals}</span>
+ <span className="text-xs tabular-nums opacity-70">{workspace.terminals}</span>
{pending && <span className="sr-only">Switching workspace</span>}
- </button>;
+ </button>
+ {selected && <button type="button" aria-label={`Workspace options for ${workspace.name}`} title="Workspace options"
+ onClick={() => openWorkspaceOptions(workspace.id)}
+ className="mr-1 rounded-md p-1.5 text-muted-foreground opacity-0 transition-opacity hover:bg-background/70 hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/space:opacity-100 group-focus-within/space:opacity-100 [@media(hover:none)]:opacity-100">
+ <MoreHorizontal className="h-4 w-4" />
+ </button>}
+ </div>;
})}
- {project.workspaces.length === 0 && <button type="button" onClick={() => newWorkspace(project.id)} className="px-2 py-2 text-left text-xs text-muted-foreground hover:text-foreground">Create workspace</button>}
+ {project.workspaces.length === 0 && <button type="button" onClick={() => newWorkspace(project.id)} className="px-2 py-2 text-left text-sm text-muted-foreground hover:text-foreground">Create workspace</button>}
</div>}
</div>;
};
- return <div data-testid="ide-project-tree" className="mt-1 px-2 pb-2">
- <div className="flex items-center justify-between px-2 pb-1 text-xs font-medium text-muted-foreground">
- <span>Projects</span>
- <button type="button" aria-label="Connect project" title="Connect project folder" onClick={connectProject}
- className="rounded p-1 hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><Plus className="h-3.5 w-3.5" /></button>
+ return <div data-testid="ide-project-tree" className="mx-2 mt-2 flex-1 rounded-2xl border border-border/50 bg-card/40 p-2 pb-3">
+ <div className="flex items-center justify-between px-2 pb-2 pt-1 text-[17px] font-semibold text-foreground">
+ <span>Workspaces</span>
+ <div className="flex items-center gap-0.5">
+ <button type="button" aria-label="Jarvis Live" title="Jarvis Live" onClick={toggleVoice}
+ className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><Mic className="h-4 w-4" /></button>
+ <button type="button" aria-label="Connect project" title="Connect project folder" onClick={connectProject}
+ className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><Plus className="h-4 w-4" /></button>
+ </div>
</div>
{visible.some((project) => project.pinned) && <>
<div className="px-2 pb-1 pt-2 text-[11px] font-medium text-muted-foreground">Pinned</div>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.test.tsx
new file mode 100644
index 0000000000..3f13431f24
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.test.tsx
@@ -0,0 +1,31 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { WorkspaceOptionsDialog } from "./WorkspaceOptionsDialog";
+
+afterEach(cleanup);
+const setup = () => ({
+ open: true, onOpenChange: vi.fn(), workspace: "Installer", count: 6, busy: false, canAdd: true,
+ onAdd: vi.fn(), onBalance: vi.fn(), onRename: vi.fn(), onClose: vi.fn(),
+ fontSize: 20, onFontSize: vi.fn(), appearance: null, onAppearance: vi.fn(),
+});
+
+it("keeps arrangement and display controls accessible without a main toolbar", () => {
+ const props = setup();
+ render(<WorkspaceOptionsDialog {...props} />);
+ expect(screen.getByRole("dialog", { name: "Workspace options" })).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Decrease terminal text size" }));
+ expect(props.onFontSize).toHaveBeenCalledWith(19);
+ fireEvent.click(screen.getByRole("button", { name: "light terminals" }));
+ expect(props.onAppearance).toHaveBeenCalledWith("light");
+ fireEvent.click(screen.getByRole("button", { name: "Balance layout" }));
+ expect(props.onOpenChange).toHaveBeenCalledWith(false);
+ expect(props.onBalance).toHaveBeenCalledOnce();
+});
+
+it("disables adding a ninth session and closes with Escape", () => {
+ const props = setup();
+ render(<WorkspaceOptionsDialog {...props} count={8} />);
+ expect((screen.getByRole("button", { name: "Add coding agent" }) as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.keyDown(document, { key: "Escape" });
+ expect(props.onOpenChange).toHaveBeenCalledWith(false);
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.tsx
new file mode 100644
index 0000000000..17d8fe972d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.tsx
@@ -0,0 +1,65 @@
+import * as Dialog from "@radix-ui/react-dialog";
+import { Columns2, Minus, Plus, X } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ workspace: string;
+ count: number;
+ busy: boolean;
+ canAdd: boolean;
+ onAdd: () => void;
+ onBalance: () => void;
+ onRename: () => void;
+ onClose: () => void;
+ fontSize: number;
+ onFontSize: (size: number) => void;
+ appearance: "light" | "dark" | null;
+ onAppearance: (appearance: "light" | "dark" | null) => void;
+}
+
+/** Workspace controls live off-canvas so the terminal area needs no toolbar. */
+export function WorkspaceOptionsDialog(props: Props) {
+ const icon = "flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-35";
+ const choose = (action: () => void) => { props.onOpenChange(false); action(); };
+ return <Dialog.Root open={props.open} onOpenChange={props.onOpenChange}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-background/70 backdrop-blur-sm" />
+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[90] w-[min(420px,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 space-y-5 rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-xl">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0"><Dialog.Title className="text-lg font-semibold">Workspace options</Dialog.Title>
+ <Dialog.Description className="mt-1 truncate text-sm text-muted-foreground">{props.workspace}</Dialog.Description></div>
+ <Dialog.Close aria-label="Close workspace options" className={icon}><X className="h-4 w-4" /></Dialog.Close>
+ </div>
+ <section aria-label="Terminal arrangement" className="space-y-2">
+ <button type="button" disabled={props.busy || props.count < 2} onClick={() => choose(props.onBalance)}
+ className="flex w-full items-center gap-2 rounded-lg border border-border px-3 py-2.5 text-sm hover:bg-muted disabled:opacity-40"><Columns2 className="h-4 w-4" />Balance layout</button>
+ <p className="text-xs leading-relaxed text-muted-foreground">Drag a terminal title to an edge to place it beside, above or below another terminal. Drop in the center to swap positions.</p>
+ </section>
+ <section aria-label="Terminal text size" className="flex items-center justify-between gap-2">
+ <span className="text-sm font-medium">Text size</span>
+ <div className="flex items-center gap-2">
+ <button type="button" aria-label="Decrease terminal text size" disabled={props.fontSize <= 9} onClick={() => props.onFontSize(props.fontSize - 1)} className={icon}><Minus className="h-3.5 w-3.5" /></button>
+ <span className="w-5 text-center text-sm tabular-nums">{props.fontSize}</span>
+ <button type="button" aria-label="Increase terminal text size" disabled={props.fontSize >= 22} onClick={() => props.onFontSize(props.fontSize + 1)} className={icon}><Plus className="h-3.5 w-3.5" /></button>
+ </div>
+ </section>
+ <section aria-label="Terminal appearance">
+ <p className="mb-2 text-sm font-medium">Terminal appearance</p>
+ <div className="flex gap-2">
+ {([null, "dark", "light"] as const).map((appearance) => <button type="button" key={appearance ?? "auto"}
+ aria-label={appearance ? `${appearance} terminals` : "Match app appearance"} aria-pressed={props.appearance === appearance}
+ onClick={() => props.onAppearance(appearance)} className={cn("flex-1 rounded-lg border px-2 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", props.appearance === appearance ? "border-foreground/35 bg-muted" : "border-border text-muted-foreground hover:bg-muted")}>
+ {appearance === null ? "Match app" : appearance === "dark" ? "Dark" : "Light"}</button>)}
+ </div>
+ </section>
+ <div className="border-t border-border pt-2">
+ <button type="button" disabled={props.busy || !props.canAdd || props.count >= 8} onClick={() => choose(props.onAdd)} className="block w-full rounded-lg px-2 py-2.5 text-left text-sm hover:bg-muted disabled:opacity-40">Add coding agent</button>
+ <button type="button" disabled={props.busy} onClick={() => choose(props.onRename)} className="block w-full rounded-lg px-2 py-2.5 text-left text-sm hover:bg-muted disabled:opacity-40">Rename workspace</button>
+ <button type="button" disabled={props.busy} onClick={() => choose(props.onClose)} className="block w-full rounded-lg px-2 py-2.5 text-left text-sm text-destructive hover:bg-muted disabled:opacity-40">Close workspace</button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx
index 18d94103ab..7fd7cd2dae 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx
@@ -1,9 +1,9 @@
import { useState } from "react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { SessionState } from "@/lib/agenticIdeApi";
-const api = vi.hoisted(() => ({ reorder: vi.fn(), rename: vi.fn(), toast: vi.fn() }));
-vi.mock("@/lib/agenticIdeApi", () => ({ reorderIdeTerminals: api.reorder, renameTerminal: api.rename }));
+const api = vi.hoisted(() => ({ move: vi.fn(), rename: vi.fn(), toast: vi.fn() }));
+vi.mock("@/lib/agenticIdeApi", () => ({ moveTerminal: api.move, renameTerminal: api.rename }));
vi.mock("@/store/events", () => ({ useEventStore: (select: (state: unknown) => unknown) => select({ pushToast: api.toast }) }));
vi.mock("./AgenticTerminal", () => ({ AgenticTerminal: (props: {
name: string; onToggleMaximize: () => void; onRestart: () => void; restartToken: number;
@@ -17,7 +17,8 @@ vi.mock("./AgenticTerminal", () => ({ AgenticTerminal: (props: {
<textarea aria-label={`Terminal input ${props.name}`} />
</div> }));
vi.mock("@/hooks/useTheme", () => ({ useThemeValue: () => "dark" }));
-import { columnsForSessions, swapSessions, WorkspaceTerminalGrid } from "./WorkspaceTerminalGrid";
+import { WorkspaceTerminalGrid } from "./WorkspaceTerminalGrid";
+import { balancedLayout, previewDock } from "./workspaceDocking";
class ResizeObserverStub { observe() {} disconnect() {} }
class PointerEventStub extends MouseEvent {
@@ -27,7 +28,7 @@ class PointerEventStub extends MouseEvent {
vi.stubGlobal("ResizeObserver", ResizeObserverStub);
vi.stubGlobal("PointerEvent", PointerEventStub);
const makeSession = (names = ["T1", "T2", "T3", "T4"]) => ({
- id: "w1", terminals: names.map((name) => ({ name, key: name, history_id: name, display_name: "Codex", agent: "codex" })),
+ id: "w1", layout: balancedLayout(names), terminals: names.map((name) => ({ name, key: name, history_id: name, display_name: "Codex", agent: "codex" })),
}) as SessionState;
const props = { onChanged: vi.fn(), onAdd: vi.fn(), onClose: vi.fn(), onSelect: vi.fn(), selected: "", fontSize: 13, appearance: null };
const order = () => [...document.querySelectorAll<HTMLElement>("[data-session-id]")].map((node) => node.dataset.sessionId);
@@ -38,8 +39,8 @@ const geometry = () => document.querySelectorAll<HTMLElement>("[data-session-id]
const dragToThird = () => {
geometry();
fireEvent.pointerDown(screen.getByRole("button", { name: "Move T1" }), { button: 0, pointerId: 1, clientX: 15, clientY: 15 });
- fireEvent.pointerMove(window, { pointerId: 1, clientX: 20, clientY: 450 });
- fireEvent.pointerUp(window, { pointerId: 1, clientX: 20, clientY: 450 });
+ fireEvent.pointerMove(window, { pointerId: 1, clientX: 195, clientY: 595 });
+ fireEvent.pointerUp(window, { pointerId: 1, clientX: 195, clientY: 595 });
};
function Controlled() {
const [session, setSession] = useState(makeSession());
@@ -48,36 +49,18 @@ function Controlled() {
beforeEach(() => { vi.clearAllMocks(); });
afterEach(cleanup);
-describe("workspace columns", () => {
- it("uses all useful space on wide displays and keeps six in the reference layout", () => {
- expect([1, 2, 3, 4, 5, 6, 7, 8].map((count) => columnsForSessions(count, 1800)))
- .toEqual([1, 2, 3, 4, 3, 3, 4, 4]);
- expect(columnsForSessions(4, 1100)).toBe(2);
- });
- it("never creates a third row, including manual column preferences", () => {
- expect(columnsForSessions(8, 680)).toBe(4);
- expect(columnsForSessions(3, 310)).toBe(2);
- expect(columnsForSessions(2, 310)).toBe(1);
- expect(columnsForSessions(8, 1800, 2)).toBe(4);
- expect(columnsForSessions(4, 1800, 2)).toBe(2);
- });
- it("swaps two slots without shifting the terminals between them", () => {
- expect(swapSessions(["a", "b", "c", "d"], "a", "c")).toEqual(["c", "b", "a", "d"]);
- });
-});
-
it("swaps immediately, persists once and preserves mounted terminal nodes", async () => {
- let finish!: (state: { session: SessionState }) => void;
- api.reorder.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ let finish!: (state: SessionState) => void;
+ api.move.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
render(<Controlled />);
const original = screen.getByLabelText("Terminal input T1");
dragToThird();
- expect(order()).toEqual(["T3", "T2", "T1", "T4"]);
+ expect(document.querySelector<HTMLElement>('[data-session-id="T1"]')!.style.top).toContain("50%");
expect(screen.getByLabelText("Terminal input T1")).toBe(original);
- expect(api.reorder).toHaveBeenCalledWith("w1", ["T3", "T2", "T1", "T4"]);
+ expect(api.move).toHaveBeenCalledWith("pane:T1", "pane:T3", "swap");
fireEvent.keyDown(document.querySelector('[data-session-id="T2"]')!, { altKey: true, key: "ArrowRight" });
- expect(api.reorder).toHaveBeenCalledTimes(1);
- await act(async () => finish({ session: makeSession(["T3", "T2", "T1", "T4"]) }));
+ expect(api.move).toHaveBeenCalledTimes(1);
+ await act(async () => finish(makeSession(["T3", "T2", "T1", "T4"])));
expect(order()).toEqual(["T3", "T2", "T1", "T4"]);
});
@@ -92,11 +75,11 @@ it("allows title pointer presses to select the pane without starting a reorder",
fireEvent.pointerUp(window, { pointerId: 1 });
fireEvent.click(handle, { detail: 1 });
expect(props.onSelect).toHaveBeenCalledExactlyOnceWith("T1");
- expect(api.reorder).not.toHaveBeenCalled();
+ expect(api.move).not.toHaveBeenCalled();
});
it("rolls back a rejected swap and releases the mutation barrier", async () => {
- api.reorder.mockRejectedValue(new Error("Connection lost"));
+ api.move.mockRejectedValue(new Error("Connection lost"));
const onMutationStart = vi.fn(), onMutationEnd = vi.fn();
render(<WorkspaceTerminalGrid {...props} session={makeSession()} onMutationStart={onMutationStart} onMutationEnd={onMutationEnd} />);
dragToThird();
@@ -107,13 +90,13 @@ it("rolls back a rejected swap and releases the mutation barrier", async () => {
});
it("cannot resurrect a removed terminal from a late response", async () => {
- let finish!: (state: { session: SessionState }) => void;
- api.reorder.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ let finish!: (state: SessionState) => void;
+ api.move.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
const changed = vi.fn();
const { rerender } = render(<WorkspaceTerminalGrid {...props} session={makeSession()} onChanged={changed} />);
dragToThird();
rerender(<WorkspaceTerminalGrid {...props} session={makeSession(["T2", "T3", "T4"])} onChanged={changed} />);
- await act(async () => finish({ session: makeSession(["T3", "T2", "T1", "T4"]) }));
+ await act(async () => finish(makeSession(["T3", "T2", "T1", "T4"])));
expect(changed).not.toHaveBeenCalled();
expect(order()).toEqual(["T2", "T3", "T4"]);
});
@@ -127,20 +110,64 @@ it("cancels a drag with Escape and does not steal terminal keyboard shortcuts",
fireEvent.keyDown(window, { key: "Escape" });
fireEvent.pointerUp(window, { clientX: 20, clientY: 450 });
fireEvent.keyDown(screen.getByLabelText("Terminal input T1"), { altKey: true, key: "ArrowRight" });
- expect(api.reorder).not.toHaveBeenCalled();
+ expect(api.move).not.toHaveBeenCalled();
});
it("receives drag movement over a terminal even when it stops event bubbling", async () => {
- api.reorder.mockResolvedValue({ session: makeSession(["T3", "T2", "T1", "T4"]) });
+ api.move.mockResolvedValue(makeSession(["T3", "T2", "T1", "T4"]));
render(<WorkspaceTerminalGrid {...props} session={makeSession()} />);
geometry();
const input = screen.getByLabelText("Terminal input T3");
input.addEventListener("pointermove", (event) => event.stopPropagation());
input.addEventListener("pointerup", (event) => event.stopPropagation());
fireEvent.pointerDown(screen.getByRole("button", { name: "Move T1" }), { button: 0, clientX: 15, clientY: 15 });
- fireEvent.pointerMove(input, { clientX: 20, clientY: 450 });
- fireEvent.pointerUp(input, { clientX: 20, clientY: 450 });
- await waitFor(() => expect(api.reorder).toHaveBeenCalledWith("w1", ["T3", "T2", "T1", "T4"]));
+ fireEvent.pointerMove(input, { clientX: 195, clientY: 595 });
+ fireEvent.pointerUp(input, { clientX: 195, clientY: 595 });
+ await waitFor(() => expect(api.move).toHaveBeenCalledWith("pane:T1", "pane:T3", "swap"));
+});
+
+it("docks beside or below another pane and restores the returned layout after remount", async () => {
+ const session = makeSession(["T1", "T2"]);
+ const stacked = { ...session, layout: previewDock(session.layout!, "T1", "T2", "below") };
+ api.move.mockResolvedValue(stacked);
+ const { unmount } = render(<WorkspaceTerminalGrid {...props} session={session} />);
+ geometry();
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Move T1" }), { button: 0, clientX: 15, clientY: 15 });
+ fireEvent.pointerMove(window, { clientX: 595, clientY: 380 });
+ expect(screen.getByTestId("dock-preview").dataset.position).toBe("below");
+ fireEvent.pointerUp(window, { clientX: 595, clientY: 380 });
+ await waitFor(() => expect(api.move).toHaveBeenCalledWith("pane:T1", "pane:T2", "below"));
+ await waitFor(() => expect(props.onChanged).toHaveBeenCalledWith(stacked));
+ unmount();
+ render(<WorkspaceTerminalGrid {...props} session={stacked} />);
+ expect(document.querySelector<HTMLElement>('[data-session-id="T1"]')!.style.width).toContain("100%");
+ expect(document.querySelector<HTMLElement>('[data-session-id="T1"]')!.style.top).toContain("50%");
+});
+
+it("cancels a pending drag when a workspace switch starts", () => {
+ const session = makeSession();
+ const { rerender } = render(<WorkspaceTerminalGrid {...props} session={session} />);
+ geometry();
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Move T1" }), { button: 0, clientX: 15, clientY: 15 });
+ fireEvent.pointerMove(window, { clientX: 195, clientY: 595 });
+ rerender(<WorkspaceTerminalGrid {...props} session={session} disabled />);
+ fireEvent.pointerUp(window, { clientX: 195, clientY: 595 });
+ expect(api.move).not.toHaveBeenCalled();
+ expect(screen.queryByTestId("dock-preview")).toBeNull();
+});
+
+it("keeps keyboard swaps in the same row when two neighbors share an x coordinate", async () => {
+ api.move.mockResolvedValue(makeSession(["T1", "T2", "T4", "T3"]));
+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} />);
+ fireEvent.keyDown(document.querySelector('[data-session-id="T3"]')!, { altKey: true, key: "ArrowRight" });
+ await waitFor(() => expect(api.move).toHaveBeenCalledWith("pane:T3", "pane:T4", "swap"));
+});
+
+it("does not select a diagonal pane when the bottom pane spans the whole row", async () => {
+ api.move.mockResolvedValue(makeSession(["T2", "T1", "T3"]));
+ render(<WorkspaceTerminalGrid {...props} session={makeSession(["T1", "T2", "T3"])} />);
+ fireEvent.keyDown(document.querySelector('[data-session-id="T1"]')!, { altKey: true, key: "ArrowRight" });
+ await waitFor(() => expect(api.move).toHaveBeenCalledWith("pane:T1", "pane:T2", "swap"));
});
it("only restarts the addressed session and shows survivors after maximized close", async () => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx
index 47f9efca82..2a6ab93db4 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx
@@ -2,34 +2,17 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { AgenticTerminal } from "./AgenticTerminal";
import { AgentMark } from "./AgentMark";
import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";
-import { renameTerminal, reorderIdeTerminals } from "@/lib/agenticIdeApi";
+import { moveTerminal, renameTerminal, type PaneMovePosition } from "@/lib/agenticIdeApi";
import { useThemeValue } from "@/hooks/useTheme";
import { useEventStore } from "@/store/events";
import { cn } from "@/lib/utils";
+import { treeLayout, treeLeaves, type LayoutNode } from "./treeLayout";
+import { DOCK_LABELS, dockPosition, fitsWorkspace, layoutSpan, paneStyle, previewDock, workspaceLayout } from "./workspaceDocking";
const GAP = 8;
-const MIN_WIDTH = 320;
+const MIN_WIDTH = 280;
const idOf = (terminal: TerminalState) => terminal.history_id ?? terminal.key;
-export function columnsForSessions(count: number, width: number, preference = 0): number {
- if (count < 1) return 1;
- const minimum = Math.ceil(count / 2);
- if (preference > 0) return Math.max(minimum, Math.min(count, 4, preference));
- const readable = Math.max(1, Math.min(4, Math.floor((width + GAP) / 380)));
- // Four wide panes in two rows left huge horizontal voids on large monitors.
- // Fit four beside each other when readable; six keep the reference's 3 x 2.
- const desired = count === 4 ? (readable >= 4 ? 4 : 2) : count <= 3 ? count : minimum;
- return Math.max(minimum, Math.min(readable, desired));
-}
-
-export function swapSessions(ids: string[], source: string, target: string): string[] {
- const from = ids.indexOf(source), to = ids.indexOf(target);
- if (from < 0 || to < 0 || from === to) return ids;
- const next = [...ids];
- [next[from], next[to]] = [next[to], next[from]];
- return next;
-}
-
interface Props {
session: SessionState;
onChanged: (session: SessionState) => void;
@@ -39,20 +22,20 @@ interface Props {
selected: string;
fontSize: number;
appearance: "light" | "dark" | null;
- columnPreference?: number;
+ disabled?: boolean;
onMutationStart?: () => void;
onMutationEnd?: () => void;
}
-interface DragFeedback { id: string; target: string | null; x: number; y: number }
+interface DropTarget { id: string; position: PaneMovePosition; allowed: boolean }
+interface DragFeedback { id: string; target: DropTarget | null; x: number; y: number }
-export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, fontSize, appearance, columnPreference = 0, onMutationStart, onMutationEnd }: Props) {
+export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, fontSize, appearance, disabled = false, onMutationStart, onMutationEnd }: Props) {
const theme = useThemeValue();
const pushToast = useEventStore((state) => state.pushToast);
const frame = useRef<HTMLDivElement>(null);
- const [width, setWidth] = useState(1280);
const [drag, setDrag] = useState<DragFeedback | null>(null);
- const [optimistic, setOptimistic] = useState<string[] | null>(null);
+ const [optimistic, setOptimistic] = useState<LayoutNode | null>(null);
const [saving, setSaving] = useState(false);
const [maximized, setMaximized] = useState<string | null>(null);
const [restarts, setRestarts] = useState<Record<string, number>>({});
@@ -60,14 +43,17 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe
const dragCleanup = useRef<(() => void) | null>(null);
const saveInFlight = useRef(false);
const mounted = useRef(true);
- const latest = useRef({ session, onChanged, onSelect, onMutationStart, onMutationEnd });
- latest.current = { session, onChanged, onSelect, onMutationStart, onMutationEnd };
+ const latest = useRef({ session, disabled, onChanged, onSelect, onMutationStart, onMutationEnd });
+ latest.current = { session, disabled, onChanged, onSelect, onMutationStart, onMutationEnd };
const members = session.terminals.map(idOf);
- const pendingOrderMatches = optimistic && optimistic.length === members.length && optimistic.every((id) => members.includes(id));
- const ids = pendingOrderMatches ? optimistic : members;
- const tiles = ids.map((id) => session.terminals.find((terminal) => idOf(terminal) === id)!);
- const columns = columnsForSessions(tiles.length, width, columnPreference);
+ const keys = session.terminals.map((terminal) => terminal.key);
+ const pendingKeys = treeLeaves(optimistic);
+ const pendingOrderMatches = optimistic && pendingKeys.length === keys.length && pendingKeys.every((key) => keys.includes(key));
+ const tree = pendingOrderMatches ? optimistic : workspaceLayout(session.layout, session.terminals);
+ const tiles = session.terminals;
+ const layout = treeLayout(tree, tiles);
+ const columns = Math.max(1, layoutSpan(tree, "row"));
const visibleMaximized = maximized && members.includes(maximized) ? maximized : null;
useEffect(() => {
@@ -77,36 +63,39 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe
useEffect(() => {
if (maximized && !members.includes(maximized)) setMaximized(null);
}, [maximized, members]);
+ useEffect(() => { if (disabled) dragCleanup.current?.(); }, [disabled]);
useEffect(() => {
const node = frame.current;
if (!node) return;
const observer = new ResizeObserver(([entry]) => {
- if (entry.contentRect.width > 0) setWidth(entry.contentRect.width);
- else dragCleanup.current?.();
+ if (entry.contentRect.width === 0) dragCleanup.current?.();
});
observer.observe(node);
return () => observer.disconnect();
}, []);
- const move = useCallback(async (sourceId: string, targetId: string) => {
- if (saveInFlight.current || sourceId === targetId) return;
+ const move = useCallback(async (sourceId: string, targetId: string, position: PaneMovePosition = "swap") => {
+ if (saveInFlight.current || latest.current.disabled || sourceId === targetId) return;
const owner = latest.current.session;
- const before = owner.terminals.map(idOf);
- const next = swapSessions(before, sourceId, targetId);
- if (next === before) return;
+ const source = owner.terminals.find((terminal) => idOf(terminal) === sourceId);
+ const target = owner.terminals.find((terminal) => idOf(terminal) === targetId);
+ const before = workspaceLayout(owner.layout, owner.terminals);
+ if (!before || !source || !target) return;
+ const next = previewDock(before, source.key, target.key, position);
+ if (!fitsWorkspace(next)) { setAnnouncement("Use at most four columns and two rows."); return; }
saveInFlight.current = true;
latest.current.onMutationStart?.();
setSaving(true);
setOptimistic(next);
- const source = owner.terminals.find((terminal) => idOf(terminal) === sourceId)!;
- const target = owner.terminals.find((terminal) => idOf(terminal) === targetId)!;
try {
- const state = await reorderIdeTerminals(owner.id, next);
+ // Unique pane identities fail closed if the active workspace changes.
+ const nextSession = await moveTerminal(source.history_id ? `pane:${source.history_id}` : source.name,
+ target.history_id ? `pane:${target.history_id}` : target.name, position);
if (!mounted.current || latest.current.session.id !== owner.id) return;
// A rename/close or a newer snapshot must never be overwritten by the
// response to an earlier drag. The parent also invalidates pending polls.
- if (latest.current.session === owner && state.session?.id === owner.id) latest.current.onChanged(state.session);
- setAnnouncement(`${source.name} and ${target.name} swapped.`);
+ if (latest.current.session === owner && nextSession.id === owner.id) latest.current.onChanged(nextSession);
+ setAnnouncement(position === "swap" ? `${source.name} and ${target.name} swapped.` : `${source.name} placed ${position} ${target.name}.`);
} catch (error) {
if (mounted.current) {
pushToast("error", (error as Error).message);
@@ -120,18 +109,27 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe
}, [pushToast]);
const startDrag = useCallback((id: string, event: React.PointerEvent) => {
- if (event.button !== 0 || dragCleanup.current || saveInFlight.current) return;
+ if (event.button !== 0 || latest.current.disabled || dragCleanup.current || saveInFlight.current) return;
const handle = event.currentTarget;
const pointer = event.pointerId;
const initialX = event.clientX, initialY = event.clientY;
let armed = false;
// Capture keeps xterm's selection/pointer handlers from eating a release.
handle.setPointerCapture?.(pointer);
- const targetAt = (x: number, y: number) => {
+ const targetAt = (x: number, y: number): DropTarget | null => {
const candidates = frame.current?.querySelectorAll<HTMLElement>("[data-session-id]") ?? [];
for (const tile of candidates) {
const rect = tile.getBoundingClientRect();
- if (rect.width > 0 && rect.height > 0 && x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) return tile.dataset.sessionId ?? null;
+ if (rect.width > 0 && rect.height > 0 && x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
+ const targetId = tile.dataset.sessionId;
+ const owner = latest.current.session;
+ const source = owner.terminals.find((terminal) => idOf(terminal) === id);
+ const target = owner.terminals.find((terminal) => idOf(terminal) === targetId);
+ const before = workspaceLayout(owner.layout, owner.terminals);
+ if (!source || !target || !before || targetId === id) return null;
+ const position = dockPosition(x, y, rect);
+ return { id: targetId!, position, allowed: fitsWorkspace(previewDock(before, source.key, target.key, position)) };
+ }
}
return null;
};
@@ -158,7 +156,7 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe
if (release.pointerId !== pointer) return;
const target = targetAt(release.clientX, release.clientY);
cleanup();
- if (armed && target && target !== id) void move(id, target);
+ if (armed && target?.allowed) void move(id, target.id, target.position);
};
dragCleanup.current = cleanup;
window.addEventListener("pointermove", onMove, { capture: true, passive: false });
@@ -183,38 +181,55 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe
const dragged = drag ? session.terminals.find((terminal) => idOf(terminal) === drag.id) : null;
return <div ref={frame} data-testid="workspace-terminal-grid" aria-busy={saving} className="relative h-full min-h-0 overflow-auto p-2">
- <div className="grid h-full gap-2" style={{
- gridTemplateColumns: `repeat(${visibleMaximized ? 1 : columns}, minmax(0, 1fr))`,
- gridTemplateRows: `repeat(${visibleMaximized ? 1 : Math.max(1, Math.ceil(tiles.length / columns))}, minmax(0, 1fr))`,
- minWidth: visibleMaximized ? undefined : `${columns * MIN_WIDTH + (columns - 1) * GAP}px`, minHeight: "280px",
+ <div className="relative h-full" style={{
+ minWidth: visibleMaximized ? undefined : `${columns * MIN_WIDTH + (columns - 1) * GAP}px`,
+ minHeight: visibleMaximized ? "240px" : `${Math.max(1, layoutSpan(tree, "column")) * 200}px`,
}}>
{tiles.map((terminal, index) => {
const id = idOf(terminal);
return <div key={id} data-session-id={id} tabIndex={0}
- aria-label={`${terminal.name}, position ${index + 1} of ${tiles.length}. Alt+Arrow swaps with a neighbor.`}
+ aria-label={`${terminal.name}. Drag to an edge to dock, or the center to swap. Alt+Arrow swaps with a neighbor.`}
onKeyDown={(event) => {
if (event.target !== event.currentTarget && !(event.target instanceof HTMLElement && event.target.closest("[data-ide-drag-handle]"))) return;
if (!event.altKey || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
event.preventDefault();
if (visibleMaximized) return;
- const delta = event.key === "ArrowLeft" ? -1 : event.key === "ArrowRight" ? 1 : event.key === "ArrowUp" ? -columns : columns;
- const target = tiles[index + delta];
- if (target) void move(id, idOf(target));
+ const box = layout.boxes[index];
+ if (!box) return;
+ const horizontal = event.key === "ArrowLeft" || event.key === "ArrowRight";
+ const sign = event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 1;
+ const center = horizontal ? box.x + box.w / 2 : box.y + box.h / 2;
+ const crossCenter = horizontal ? box.y + box.h / 2 : box.x + box.w / 2;
+ const candidates = tiles.map((entry, at) => ({ entry, box: layout.boxes[at] })).filter((candidate) => candidate.box && idOf(candidate.entry) !== id)
+ .map((candidate) => ({ ...candidate,
+ distance: ((horizontal ? candidate.box!.x + candidate.box!.w / 2 : candidate.box!.y + candidate.box!.h / 2) - center) * sign,
+ crossDistance: Math.abs((horizontal ? candidate.box!.y + candidate.box!.h / 2 : candidate.box!.x + candidate.box!.w / 2) - crossCenter),
+ overlap: horizontal
+ ? Math.min(box.y + box.h, candidate.box!.y + candidate.box!.h) - Math.max(box.y, candidate.box!.y)
+ : Math.min(box.x + box.w, candidate.box!.x + candidate.box!.w) - Math.max(box.x, candidate.box!.x),
+ }))
+ .filter((candidate) => candidate.distance > 0.001 && candidate.overlap > 0.001).sort((a, b) => a.distance - b.distance || a.crossDistance - b.crossDistance);
+ if (candidates[0]) void move(id, idOf(candidates[0].entry));
}}
- className={cn("relative min-h-0 min-w-0 rounded-2xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- drag?.id === id && "opacity-50", drag?.target === id && drag.id !== id && "ring-2 ring-ring",
+ style={paneStyle(visibleMaximized === id ? { x: 0, y: 0, w: 1, h: 1 } : layout.boxes[index]!)}
+ className={cn("min-h-0 min-w-0 rounded-2xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ drag?.id === id && "opacity-50",
visibleMaximized && visibleMaximized !== id && "hidden")}>
<AgenticTerminal headerMode="compact" agent={terminal.agent}
name={terminal.name} workspaceId={session.id} displayName={terminal.display_name}
recap={terminal.recap} promptCount={terminal.prompts_sent} appearance={appearance ?? theme} fontSize={fontSize}
focused={selected === terminal.name} onFocus={() => onSelect(terminal.name)}
maximized={visibleMaximized === id} onToggleMaximize={() => setMaximized((current) => current === id ? null : id)}
- onArrangeStart={visibleMaximized || saving ? undefined : (event) => startDrag(id, event)} arranging={drag?.id === id}
+ onArrangeStart={visibleMaximized || saving || disabled ? undefined : (event) => startDrag(id, event)} arranging={drag?.id === id}
onClose={() => onClose(terminal)} onAttachError={(message) => pushToast("error", message)}
onRename={(name) => rename(terminal, name)}
restartToken={restarts[id] ?? 0} onRestart={() => setRestarts((current) => ({ ...current, [id]: (current[id] ?? 0) + 1 }))}
splitDisabled={tiles.length >= 8} onSplit={() => onAdd()} />
- {drag?.target === id && drag.id !== id && <span aria-hidden="true" className="pointer-events-none absolute inset-x-0 top-11 mx-auto w-fit rounded-md bg-popover px-3 py-1.5 text-xs font-medium text-popover-foreground shadow-lg">Release to swap</span>}
+ {drag?.target?.id === id && <div aria-hidden="true" data-testid="dock-preview" data-position={drag.target.position}
+ className={cn("pointer-events-none absolute z-20 flex items-center justify-center rounded-xl border-2 p-2", drag.target.allowed ? "border-ring/70 bg-accent/[0.15]" : "border-destructive bg-background/80",
+ drag.target.position === "left" ? "inset-y-1 left-1 w-1/2" : drag.target.position === "right" ? "inset-y-1 right-1 w-1/2" : drag.target.position === "above" ? "inset-x-1 top-1 h-1/2" : drag.target.position === "below" ? "inset-x-1 bottom-1 h-1/2" : "inset-1")}>
+ <span className="rounded-md bg-popover px-3 py-2 text-center text-xs font-medium text-popover-foreground shadow-lg">{drag.target.allowed ? DOCK_LABELS[drag.target.position] : "Maximum 4 columns × 2 rows"}</span>
+ </div>}
</div>;
})}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.test.tsx
deleted file mode 100644
index fe03fa9277..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.test.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, expect, it, vi } from "vitest";
-import { WorkspaceToolbar } from "./WorkspaceToolbar";
-
-afterEach(cleanup);
-const setup = () => ({
- project: "Project", workspace: "Project", folder: "/code/project", count: 6, busy: false, canAdd: true,
- onAdd: vi.fn(), onRename: vi.fn(), onClose: vi.fn(), fontSize: 20, onFontSize: vi.fn(),
- appearance: null, onAppearance: vi.fn(), columns: 0, onColumns: vi.fn(), voiceOpen: false, onVoice: vi.fn(),
-});
-
-it("keeps the toolbar compact and exposes working display controls on demand", () => {
- const props = setup();
- render(<WorkspaceToolbar {...props} />);
- expect(screen.getAllByText("Project")).toHaveLength(1);
- expect(screen.queryByText("/code/project")).toBeNull();
- expect(screen.queryByRole("button", { name: "Decrease terminal text size" })).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "Workspace options" }));
- fireEvent.click(screen.getByRole("button", { name: "3 columns" }));
- expect(props.onColumns).toHaveBeenCalledWith(3);
- expect((screen.getByRole("button", { name: "2 columns" }) as HTMLButtonElement).disabled).toBe(true);
- fireEvent.click(screen.getByRole("button", { name: "Decrease terminal text size" }));
- expect(props.onFontSize).toHaveBeenCalledWith(19);
- fireEvent.click(screen.getByRole("button", { name: "light terminals" }));
- expect(props.onAppearance).toHaveBeenCalledWith("light");
- fireEvent.keyDown(document, { key: "Escape" });
- expect(screen.queryByRole("dialog", { name: "Workspace options" })).toBeNull();
-});
-
-it("dismisses after a workspace change and disables adding the ninth session", () => {
- const props = setup();
- const { rerender } = render(<WorkspaceToolbar {...props} />);
- fireEvent.click(screen.getByRole("button", { name: "Workspace options" }));
- rerender(<WorkspaceToolbar {...props} workspace="Another" count={8} />);
- expect(screen.queryByRole("dialog", { name: "Workspace options" })).toBeNull();
- expect((screen.getByRole("button", { name: "Add coding agent" }) as HTMLButtonElement).disabled).toBe(true);
-});
-
-it("shows the effective columns when a saved preference cannot fit this group", () => {
- const props = setup();
- const { rerender } = render(<WorkspaceToolbar {...props} count={1} columns={4} />);
- fireEvent.click(screen.getByRole("button", { name: "Workspace options" }));
- expect(screen.getByRole("button", { name: "1 columns" }).getAttribute("aria-pressed")).toBe("true");
- expect((screen.getByRole("button", { name: "4 columns" }) as HTMLButtonElement).disabled).toBe(true);
- rerender(<WorkspaceToolbar {...props} count={6} columns={2} />);
- expect(screen.getByRole("button", { name: "3 columns" }).getAttribute("aria-pressed")).toBe("true");
- expect(screen.getByRole("button", { name: "2 columns" }).getAttribute("aria-pressed")).toBe("false");
- expect(props.onColumns).not.toHaveBeenCalled();
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.tsx
deleted file mode 100644
index 77d3828fb8..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import { useEffect, useRef, useState } from "react";
-import { Mic, MoreHorizontal, Plus, Minus } from "lucide-react";
-import { cn } from "@/lib/utils";
-
-interface Props {
- project?: string;
- workspace?: string;
- folder?: string;
- count: number;
- busy: boolean;
- canAdd: boolean;
- onAdd: () => void;
- onRename: () => void;
- onClose: () => void;
- fontSize: number;
- onFontSize: (size: number) => void;
- appearance: "light" | "dark" | null;
- onAppearance: (appearance: "light" | "dark" | null) => void;
- columns: number;
- onColumns: (columns: number) => void;
- voiceOpen: boolean;
- onVoice: () => void;
-}
-
-/** Keep context short; display preferences live behind one explicit control. */
-export function WorkspaceToolbar(props: Props) {
- const [open, setOpen] = useState(false);
- // Keep the user's preference, but mark the column count this workspace can
- // actually render. Smaller groups must not advertise empty columns.
- const selectedColumns = props.columns === 0 ? 0 : Math.max(Math.ceil(props.count / 2), Math.min(props.count, 4, props.columns));
- const root = useRef<HTMLDivElement>(null);
- const trigger = useRef<HTMLButtonElement>(null);
- const panel = useRef<HTMLDivElement>(null);
- useEffect(() => {
- if (!open) return;
- panel.current?.focus();
- const outside = (event: PointerEvent) => {
- if (event.target instanceof Node && !root.current?.contains(event.target)) setOpen(false);
- };
- const escape = (event: KeyboardEvent) => {
- if (event.key === "Escape") { event.preventDefault(); setOpen(false); trigger.current?.focus(); }
- };
- document.addEventListener("pointerdown", outside);
- document.addEventListener("keydown", escape);
- return () => {
- document.removeEventListener("pointerdown", outside);
- document.removeEventListener("keydown", escape);
- };
- }, [open]);
- useEffect(() => { setOpen(false); }, [props.workspace, props.folder]);
- const icon = "flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-35";
- const option = (active: boolean) => cn("rounded-md border px-2.5 py-1.5 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-30", active ? "border-foreground/35 bg-muted text-foreground" : "border-border text-muted-foreground hover:bg-muted");
-
- return <header className="flex h-10 shrink-0 items-center justify-between gap-3 px-3" data-testid="workspace-toolbar">
- <div className="flex min-w-0 items-center gap-2 text-sm" title={props.folder}>
- {props.project && props.workspace && props.project !== props.workspace && <>
- <span className="truncate text-muted-foreground">{props.project}</span><span className="text-muted-foreground/50">/</span>
- </>}
- <span className="truncate font-medium">{props.workspace ?? props.project ?? "Projects"}</span>
- </div>
- <div className="flex shrink-0 items-center gap-1">
- {props.workspace && <>
- <button type="button" aria-label="Add coding agent" title="Add coding agent" className={icon}
- disabled={props.busy || !props.canAdd || props.count >= 8} onClick={props.onAdd}><Plus className="h-4 w-4" /></button>
- <div ref={root} className="relative">
- <button ref={trigger} type="button" aria-label="Workspace options" title="Workspace options" aria-expanded={open} aria-haspopup="dialog"
- className={icon} onClick={() => setOpen((value) => !value)}><MoreHorizontal className="h-4 w-4" /></button>
- {open && <div ref={panel} tabIndex={-1} role="dialog" aria-label="Workspace options"
- className="absolute right-0 top-full z-40 mt-1 w-64 space-y-4 rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-xl outline-none">
- <section aria-label="Grid columns">
- <p className="mb-2 text-xs font-medium text-muted-foreground">Columns</p>
- <div className="flex gap-1">
- {[0, 1, 2, 3, 4].map((count) => <button type="button" key={count} aria-label={count ? `${count} columns` : "Automatic columns"}
- aria-pressed={selectedColumns === count} disabled={count > 0 && (count * 2 < props.count || count > props.count)}
- onClick={() => props.onColumns(count)} className={option(selectedColumns === count)}>{count || "Auto"}</button>)}
- </div>
- </section>
- <section aria-label="Terminal text size" className="flex items-center justify-between gap-2">
- <span className="text-xs font-medium text-muted-foreground">Text size</span>
- <div className="flex items-center gap-2">
- <button type="button" aria-label="Decrease terminal text size" disabled={props.fontSize <= 9}
- onClick={() => props.onFontSize(props.fontSize - 1)} className={icon}><Minus className="h-3.5 w-3.5" /></button>
- <span className="w-5 text-center text-xs tabular-nums">{props.fontSize}</span>
- <button type="button" aria-label="Increase terminal text size" disabled={props.fontSize >= 22}
- onClick={() => props.onFontSize(props.fontSize + 1)} className={icon}><Plus className="h-3.5 w-3.5" /></button>
- </div>
- </section>
- <section aria-label="Terminal appearance">
- <p className="mb-2 text-xs font-medium text-muted-foreground">Terminal appearance</p>
- <div className="flex gap-1">
- {([null, "dark", "light"] as const).map((appearance) => <button type="button" key={appearance ?? "auto"}
- aria-label={appearance ? `${appearance} terminals` : "Match app appearance"} aria-pressed={props.appearance === appearance}
- onClick={() => props.onAppearance(appearance)} className={option(props.appearance === appearance)}>{appearance === null ? "Match app" : appearance === "dark" ? "Dark" : "Light"}</button>)}
- </div>
- </section>
- <div className="-mx-1 border-t border-border pt-2">
- <button type="button" disabled={props.busy} onClick={() => { setOpen(false); props.onRename(); }} className="block w-full rounded-md px-2 py-2 text-left text-xs hover:bg-muted disabled:opacity-40">Rename workspace</button>
- <button type="button" disabled={props.busy} onClick={() => { setOpen(false); props.onClose(); }} className="block w-full rounded-md px-2 py-2 text-left text-xs text-destructive hover:bg-muted disabled:opacity-40">Close workspace</button>
- </div>
- </div>}
- </div>
- </>}
- <button type="button" aria-label="Jarvis Live" title="Jarvis Live" aria-pressed={props.voiceOpen} onClick={props.onVoice}
- className={cn(icon, props.voiceOpen && "bg-muted text-foreground")}><Mic className="h-4 w-4" /></button>
- </div>
- </header>;
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/workspaceDocking.test.ts b/jarvis/ui/web/frontend/src/components/agentic/workspaceDocking.test.ts
new file mode 100644
index 0000000000..650c3487bd
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/workspaceDocking.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { balancedLayout, dockPosition, fitsWorkspace, layoutSpan, previewDock, workspaceLayout } from "./workspaceDocking";
+import { treeLayout, treeLeaves } from "./treeLayout";
+
+describe("workspace docking geometry", () => {
+ it("balances defaults from one through eight without exceeding two rows", () => {
+ for (let count = 1; count <= 8; count++) {
+ const tree = balancedLayout(Array.from({ length: count }, (_, i) => String(i)));
+ expect(layoutSpan(tree, "row")).toBe(count <= 2 ? count : Math.ceil(count / 2));
+ expect(layoutSpan(tree, "column")).toBe(count <= 2 ? 1 : 2);
+ expect(fitsWorkspace(tree)).toBe(true);
+ }
+ });
+
+ it("changes two side-by-side panes to a vertical stack and back without losing identities", () => {
+ const panes = [{ key: "a", name: "A" }, { key: "b", name: "B" }];
+ const row = balancedLayout(["a", "b"])!;
+ const stack = previewDock(row, "a", "b", "below");
+ expect(treeLayout(stack, panes).boxes).toEqual([{ x: 0, y: 0.5, w: 1, h: 0.5 }, { x: 0, y: 0, w: 1, h: 0.5 }]);
+ const again = previewDock(stack, "a", "b", "right");
+ expect(treeLayout(again, panes).boxes).toEqual([{ x: 0.5, y: 0, w: 0.5, h: 1 }, { x: 0, y: 0, w: 0.5, h: 1 }]);
+ expect(treeLeaves(row)).toEqual(["a", "b"]);
+ });
+
+ it("rejects a third row or fifth column while allowing swaps in a full workspace", () => {
+ const full = balancedLayout(["a", "b", "c", "d", "e", "f", "g", "h"])!;
+ expect(fitsWorkspace(previewDock(full, "e", "b", "above"))).toBe(false);
+ expect(fitsWorkspace(previewDock(full, "e", "b", "left"))).toBe(false);
+ expect(fitsWorkspace(previewDock(full, "a", "h", "swap"))).toBe(true);
+ });
+
+ it("distinguishes the four edges from the center regardless of card aspect ratio", () => {
+ const rect = { left: 10, top: 20, width: 800, height: 400 };
+ expect(dockPosition(20, 220, rect)).toBe("left");
+ expect(dockPosition(800, 220, rect)).toBe("right");
+ expect(dockPosition(410, 25, rect)).toBe("above");
+ expect(dockPosition(410, 415, rect)).toBe("below");
+ expect(dockPosition(410, 220, rect)).toBe("swap");
+ });
+
+ it("fits legacy single-row snapshots into the workspace bounds before drawing", () => {
+ const terminals = Array.from({ length: 6 }, (_, i) => ({ key: `t${i}` }));
+ const saved = { direction: "row" as const, children: terminals.map(({ key }) => ({ pane: key })), weights: terminals.map(() => 1) };
+ const rendered = workspaceLayout(saved, terminals);
+ expect(layoutSpan(rendered, "row")).toBe(3);
+ expect(layoutSpan(rendered, "column")).toBe(2);
+ expect(treeLeaves(rendered)).toEqual(terminals.map((terminal) => terminal.key));
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/workspaceDocking.ts b/jarvis/ui/web/frontend/src/components/agentic/workspaceDocking.ts
new file mode 100644
index 0000000000..ff1fc61458
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/workspaceDocking.ts
@@ -0,0 +1,86 @@
+import type { PaneMovePosition, TerminalState } from "@/lib/agenticIdeApi";
+import { isSplit, treeLayout, treeLeaves, type LayoutNode, type PaneBox } from "./treeLayout";
+
+export const DOCK_LABELS: Record<PaneMovePosition, string> = {
+ swap: "Swap positions", left: "Place on the left", right: "Place on the right",
+ above: "Place above", below: "Place below",
+};
+
+/** Balanced defaults: two panes share a row; three to eight use two rows. */
+export function balancedLayout(keys: readonly string[]): LayoutNode | null {
+ if (!keys.length) return null;
+ const columns = keys.length <= 2 ? keys.length : Math.ceil(keys.length / 2);
+ const split = (direction: "row" | "column", children: LayoutNode[]): LayoutNode =>
+ children.length === 1 ? children[0] : { direction, children, weights: children.map(() => 1) };
+ const rows: LayoutNode[] = [];
+ for (let i = 0; i < keys.length; i += columns) rows.push(split("row", keys.slice(i, i + columns).map((pane) => ({ pane }))));
+ return split("column", rows);
+}
+
+export function workspaceLayout(tree: LayoutNode | null | undefined, terminals: readonly Pick<TerminalState, "key">[]): LayoutNode | null {
+ const keys = terminals.map((terminal) => terminal.key);
+ const leaves = treeLeaves(tree);
+ return tree && fitsWorkspace(tree) && leaves.length === keys.length && new Set(leaves).size === keys.length && leaves.every((key) => keys.includes(key))
+ ? tree : balancedLayout(keys);
+}
+
+export function layoutSpan(tree: LayoutNode | null, axis: "row" | "column"): number {
+ if (!tree) return 0;
+ if (!isSplit(tree)) return 1;
+ const spans = tree.children.map((child) => layoutSpan(child, axis));
+ return tree.direction === axis ? spans.reduce((a, b) => a + b, 0) : Math.max(0, ...spans);
+}
+
+export function fitsWorkspace(tree: LayoutNode | null): boolean {
+ return layoutSpan(tree, "row") <= 4 && layoutSpan(tree, "column") <= 2;
+}
+
+export function isBalancedWorkspace(tree: LayoutNode | null | undefined, terminals: readonly Pick<TerminalState, "key" | "name">[]): boolean {
+ const current = treeLayout(workspaceLayout(tree, terminals), terminals).boxes;
+ const balanced = treeLayout(balancedLayout(terminals.map((terminal) => terminal.key)), terminals).boxes;
+ return current.every((box, index) => box && balanced[index] &&
+ (["x", "y", "w", "h"] as const).every((axis) => Math.abs(box[axis] - balanced[index]![axis]) < 0.00001));
+}
+
+/** Preview only: the server remains authoritative for the saved split tree. */
+export function previewDock(tree: LayoutNode, source: string, target: string, position: PaneMovePosition): LayoutNode {
+ if (source === target || !treeLeaves(tree).includes(source) || !treeLeaves(tree).includes(target)) return tree;
+ const swap = (node: LayoutNode): LayoutNode => isSplit(node)
+ ? { ...node, children: node.children.map(swap) }
+ : { pane: node.pane === source ? target : node.pane === target ? source : node.pane };
+ if (position === "swap") return swap(tree);
+ const remove = (node: LayoutNode): LayoutNode | null => {
+ if (!isSplit(node)) return node.pane === source ? null : node;
+ const children: LayoutNode[] = [], weights: number[] = [];
+ node.children.forEach((child, index) => {
+ const kept = remove(child);
+ if (kept) { children.push(kept); weights.push(node.weights[index] ?? 1); }
+ });
+ return children.length === 0 ? null : children.length === 1 ? children[0] : { ...node, children, weights };
+ };
+ const insert = (node: LayoutNode): LayoutNode => {
+ if (isSplit(node)) return { ...node, children: node.children.map(insert) };
+ if (node.pane !== target) return node;
+ const pair = [{ pane: source }, node];
+ if (position === "right" || position === "below") pair.reverse();
+ return { direction: position === "left" || position === "right" ? "row" : "column", children: pair, weights: [1, 1] };
+ };
+ return insert(remove(tree)!);
+}
+
+/** The nearest outer quarter is a docking edge; the middle swaps whole panes. */
+export function dockPosition(x: number, y: number, rect: Pick<DOMRect, "left" | "top" | "width" | "height">): PaneMovePosition {
+ const horizontal = (x - rect.left) / rect.width, vertical = (y - rect.top) / rect.height;
+ const edges: [PaneMovePosition, number][] = [["left", horizontal], ["right", 1 - horizontal], ["above", vertical], ["below", 1 - vertical]];
+ edges.sort((a, b) => a[1] - b[1]);
+ return edges[0][1] <= 0.25 ? edges[0][0] : "swap";
+}
+
+/** Keep terminal DOM nodes as siblings while their saved rectangles change. */
+export function paneStyle(box: PaneBox): React.CSSProperties {
+ return {
+ position: "absolute", left: `calc(${box.x * 100}% + ${box.x > 0 ? 4 : 0}px)`, top: `calc(${box.y * 100}% + ${box.y > 0 ? 4 : 0}px)`,
+ width: `calc(${box.w * 100}% - ${(box.x > 0 ? 4 : 0) + (box.x + box.w < 0.99999 ? 4 : 0)}px)`,
+ height: `calc(${box.h * 100}% - ${(box.y > 0 ? 4 : 0) + (box.y + box.h < 0.99999 ? 4 : 0)}px)`,
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
index f1ed955b8f..713cce1e28 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
@@ -12,6 +12,27 @@ import { NAV_GROUPS, NAV_FOOTER_ITEMS, SETTINGS_HUB_IDS } from "@/components/lay
import { isSectionId, useEventStore } from "@/store/events";
import { useHomeStore } from "@/store/home";
import { useIdeChatStore } from "@/store/ideChat";
+import { useIdeProjectsStore } from "@/store/ideProjects";
+
+test("IDE rail keeps workspace options and Jarvis Live reachable", () => {
+ act(() => {
+ useEventStore.setState({ activeSection: "agentic-ide" });
+ useIdeProjectsStore.setState({ activeWorkspaceId: null, action: null });
+ });
+ renderSidebar(SIDEBAR_RAIL_WIDTH);
+ expect(screen.queryByTestId("ide-project-tree")).toBeNull();
+ const options = screen.getByRole("button", { name: "Workspace options" }) as HTMLButtonElement;
+ expect(options.disabled).toBe(true);
+ fireEvent.click(screen.getByRole("button", { name: "Jarvis Live" }));
+ expect(useIdeProjectsStore.getState().action?.kind).toBe("toggle-voice");
+ act(() => useIdeProjectsStore.setState({ activeWorkspaceId: "w1" }));
+ expect(options.disabled).toBe(false);
+ fireEvent.click(options);
+ expect(useIdeProjectsStore.getState().action).toMatchObject({ kind: "workspace-options", workspaceId: "w1" });
+ fireEvent.click(screen.getByTestId("ide-back-to-jarvis"));
+ expect(useEventStore.getState().activeSection).toBe("chats");
+ cleanup();
+});
test("IDE sidebar puts Projects first and returns to the normal chat navigation", () => {
act(() => useEventStore.setState({ activeSection: "agentic-ide" }));
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 2e6ada94e9..036b138612 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -30,6 +30,7 @@ import { useConversations } from "@/hooks/useConversations";
import { useHomeStore } from "@/store/home";
import { useAgentChatStore } from "@/store/agentChat";
import { IdeProjectTree } from "@/components/agentic/IdeProjectTree";
+import { useIdeProjectsStore } from "@/store/ideProjects";
import { useAppInstance } from "@/hooks/useAppInstance";
import { usePublishIdentity } from "@/components/marketplace/PublishIdentity";
import { GigiMark } from "@/components/GigiMark";
@@ -168,6 +169,9 @@ export function Sidebar({
const t = useT();
const active = useEventStore((s) => s.activeSection);
const setActive = useEventStore((s) => s.setActiveSection);
+ const activeIdeWorkspaceId = useIdeProjectsStore((s) => s.activeWorkspaceId);
+ const openIdeWorkspaceOptions = useIdeProjectsStore((s) => s.openWorkspaceOptions);
+ const toggleIdeVoice = useIdeProjectsStore((s) => s.toggleVoice);
const voiceState = useEventStore((s) => s.voiceState);
const assistantName = useEventStore((s) => s.assistantName);
// The dev instance (a second, restartable app beside the live one — see
@@ -468,6 +472,18 @@ export function Sidebar({
<ChevronLeft aria-hidden className="h-3.5 w-3.5 shrink-0" />
{!railed && <span>Back to Jarvis</span>}
</button>
+ {railed && <div className="mt-2 flex flex-col items-center gap-1 border-t border-border/60 pt-2">
+ <button type="button" aria-label="Workspace options" title="Workspace options"
+ disabled={!activeIdeWorkspaceId}
+ onClick={() => { if (activeIdeWorkspaceId) openIdeWorkspaceOptions(activeIdeWorkspaceId); }}
+ className="flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-35">
+ <MoreHorizontal aria-hidden className="h-4 w-4" />
+ </button>
+ <button type="button" aria-label="Jarvis Live" title="Jarvis Live" onClick={toggleIdeVoice}
+ className="flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <Mic aria-hidden className="h-4 w-4" />
+ </button>
+ </div>}
</nav> : <nav aria-label={t("sidebar.sections")} className="space-y-1 px-2 py-2">
<ul className="space-y-1">
<li><Dialog.Root open={newChatOpen} onOpenChange={(open) => { if (!startingVoiceRef.current) setNewChatOpen(open); }}>
diff --git a/jarvis/ui/web/frontend/src/store/ideProjects.ts b/jarvis/ui/web/frontend/src/store/ideProjects.ts
index e7c69f0557..6ea09144e5 100644
--- a/jarvis/ui/web/frontend/src/store/ideProjects.ts
+++ b/jarvis/ui/web/frontend/src/store/ideProjects.ts
@@ -4,7 +4,9 @@ import type { IdeProject } from "@/lib/agenticIdeApi";
type IdeAction =
| { kind: "connect-project"; nonce: number }
| { kind: "new-workspace"; projectId: string; nonce: number }
- | { kind: "activate-workspace"; workspaceId: string; nonce: number };
+ | { kind: "activate-workspace"; workspaceId: string; nonce: number }
+ | { kind: "workspace-options"; workspaceId: string; nonce: number }
+ | { kind: "toggle-voice"; nonce: number };
interface IdeProjectsStore {
projects: IdeProject[];
@@ -18,6 +20,8 @@ interface IdeProjectsStore {
connectProject: () => void;
newWorkspace: (projectId: string) => void;
activateWorkspace: (workspaceId: string) => void;
+ openWorkspaceOptions: (workspaceId: string) => void;
+ toggleVoice: () => void;
}
export const useIdeProjectsStore = create<IdeProjectsStore>((set) => ({
@@ -32,4 +36,6 @@ export const useIdeProjectsStore = create<IdeProjectsStore>((set) => ({
connectProject: () => set((state) => ({ action: { kind: "connect-project", nonce: (state.action?.nonce ?? 0) + 1 } })),
newWorkspace: (projectId) => set((state) => ({ action: { kind: "new-workspace", projectId, nonce: (state.action?.nonce ?? 0) + 1 } })),
activateWorkspace: (workspaceId) => set((state) => ({ action: { kind: "activate-workspace", workspaceId, nonce: (state.action?.nonce ?? 0) + 1 } })),
+ openWorkspaceOptions: (workspaceId) => set((state) => ({ action: { kind: "workspace-options", workspaceId, nonce: (state.action?.nonce ?? 0) + 1 } })),
+ toggleVoice: () => set((state) => ({ action: { kind: "toggle-voice", nonce: (state.action?.nonce ?? 0) + 1 } })),
}));
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
index 6f9659c0d1..6d280bbc2f 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -2,16 +2,17 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libra
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AgenticIdeView } from "./AgenticIdeView";
import { useIdeProjectsStore } from "@/store/ideProjects";
+import { balancedLayout } from "@/components/agentic/workspaceDocking";
const api = vi.hoisted(() => ({
fetchIdeState: vi.fn(), fetchIdeProjects: vi.fn(), fetchIdeAgents: vi.fn(),
startIdeSession: vi.fn(), activateWorkspace: vi.fn(), restoreIdeWorkspace: vi.fn(),
- addTerminal: vi.fn(), closeTerminal: vi.fn(), closeWorkspace: vi.fn(), renameWorkspace: vi.fn(),
+ addTerminal: vi.fn(), closeTerminal: vi.fn(), closeWorkspace: vi.fn(), renameWorkspace: vi.fn(), reorderIdeTerminals: vi.fn(), pushToast: vi.fn(),
}));
const openProject = vi.hoisted(() => vi.fn());
vi.mock("@/lib/agenticIdeApi", () => api);
vi.mock("@/lib/chatLibraryApi", () => ({ openProject }));
-vi.mock("@/store/events", () => ({ useEventStore: (select: (value: unknown) => unknown) => select({ pushToast: vi.fn() }) }));
+vi.mock("@/store/events", () => ({ useEventStore: (select: (value: unknown) => unknown) => select({ pushToast: api.pushToast }) }));
vi.mock("@/components/agentic/FolderPicker", () => ({ FolderPicker: ({ onSelect }: { onSelect: (path: string) => void }) => <button onClick={() => onSelect("/code/app")}>Pick folder</button> }));
vi.mock("@/components/agentic/VoiceBubble", () => ({ VoiceBubble: () => null, storedVoiceBubbleOpen: () => false, storeVoiceBubbleOpen: vi.fn() }));
vi.mock("@/components/agentic/WorkspaceTerminalGrid", () => ({ WorkspaceTerminalGrid: ({ session, onAdd }: { session: { id: string }; onAdd: () => void }) => <><div data-testid="live-grid">{session.id}</div><button onClick={onAdd}>Pane add</button></> }));
@@ -129,7 +130,9 @@ describe("Agentic IDE project flow", () => {
}] }], active_project_id: "p1", active_workspace_id: "w1", max_terminals: 8 });
api.renameWorkspace.mockResolvedValue(current);
render(<AgenticIdeView />);
- fireEvent.click(await screen.findByRole("button", { name: "Workspace options" }));
+ await screen.findByTestId("live-grid");
+ expect(screen.queryByTestId("workspace-toolbar")).toBeNull();
+ act(() => useIdeProjectsStore.getState().openWorkspaceOptions("w1"));
fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));
fireEvent.change(screen.getByLabelText("Workspace name"), { target: { value: "Installer" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
@@ -137,4 +140,60 @@ describe("Agentic IDE project flow", () => {
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Rename workspace" })).toBeNull());
});
+ it("keeps six incrementally added agents in a balanced 3 by 2 layout", async () => {
+ const terminals = Array.from({ length: 6 }, (_, index) => ({ key: `t${index}`, history_id: `id${index}`, name: `T${index}` }));
+ const session = { id: "w1", project_id: "p1", folder: "/code/app", name: "App work", created_at: 0,
+ focus_mode: false, project: { name: "App" }, terminals: terminals.slice(0, 5), layout: balancedLayout(terminals.slice(0, 5).map((terminal) => terminal.key)) };
+ const current = { ...emptyState, active: true, active_id: "w1", session };
+ api.fetchIdeState.mockResolvedValue(current);
+ api.fetchIdeProjects.mockResolvedValue({ projects: [project], active_workspace_id: "w1" });
+ api.addTerminal.mockResolvedValue({ ...session, terminals, layout: { direction: "row", children: [session.layout, { pane: "t5" }], weights: [3, 1] } });
+ api.reorderIdeTerminals.mockResolvedValue({ ...current, session: { ...session, terminals, layout: balancedLayout(terminals.map((terminal) => terminal.key)) } });
+ render(<AgenticIdeView />);
+ fireEvent.click(await screen.findByRole("button", { name: "Pane add" }));
+ fireEvent.click(screen.getByRole("button", { name: "Codex" }));
+ await waitFor(() => expect(api.reorderIdeTerminals).toHaveBeenCalledWith("w1", terminals.map((terminal) => terminal.history_id)));
+ });
+
+ it("persists a balanced correction for an oversized restored layout", async () => {
+ const terminals = Array.from({ length: 6 }, (_, index) => ({ key: `t${index}`, history_id: `id${index}`, name: `T${index}` }));
+ const session = { id: "w1", project_id: "p1", folder: "/code/app", name: "Restored", created_at: 0,
+ focus_mode: false, project: { name: "App" }, terminals, layout: { direction: "row", children: terminals.map((terminal) => ({ pane: terminal.key })), weights: terminals.map(() => 1) } };
+ const current = { ...emptyState, active: true, active_id: "w1", session };
+ api.fetchIdeState.mockResolvedValue(current);
+ api.fetchIdeProjects.mockResolvedValue({ projects: [project], active_workspace_id: "w1" });
+ api.reorderIdeTerminals.mockResolvedValue({ ...current, session: { ...session, layout: balancedLayout(terminals.map((terminal) => terminal.key)) } });
+ render(<AgenticIdeView onScreen={false} />);
+ await screen.findByTestId("live-grid");
+ expect(api.reorderIdeTerminals).toHaveBeenCalledOnce();
+ expect(api.reorderIdeTerminals).toHaveBeenCalledWith("w1", terminals.map((terminal) => terminal.history_id));
+ });
+
+ it("never rebalances a different workspace returned by a delayed add", async () => {
+ const terminals = ["a", "b"].map((key) => ({ key, history_id: key, name: key }));
+ const session = { id: "w1", project_id: "p1", folder: "/code/app", name: "A", created_at: 0,
+ focus_mode: false, project: { name: "App" }, terminals, layout: balancedLayout(["a", "b"]) };
+ const current = { ...emptyState, active: true, active_id: "w1", session };
+ const otherSession = { ...session, id: "w2", name: "B", layout: { direction: "column", children: [{ pane: "a" }, { pane: "b" }], weights: [1, 1] } };
+ const other = { ...current, active_id: "w2", session: otherSession };
+ api.fetchIdeState.mockResolvedValue(current);
+ api.fetchIdeProjects.mockResolvedValue({ projects: [project], active_workspace_id: "w1" });
+ let finishAdd!: (value: unknown) => void;
+ api.addTerminal.mockImplementation(() => new Promise((resolve) => { finishAdd = resolve; }));
+ api.activateWorkspace.mockImplementation(async () => {
+ api.fetchIdeState.mockResolvedValue(other);
+ api.fetchIdeProjects.mockResolvedValue({ projects: [project], active_workspace_id: "w2" });
+ return other;
+ });
+ render(<AgenticIdeView onScreen={false} />);
+ fireEvent.click(await screen.findByRole("button", { name: "Pane add" }));
+ fireEvent.click(screen.getByRole("button", { name: "Codex" }));
+ await waitFor(() => expect(api.addTerminal).toHaveBeenCalled());
+ act(() => useIdeProjectsStore.getState().activateWorkspace("w2"));
+ await waitFor(() => expect(screen.getByTestId("live-grid").textContent).toBe("w2"));
+ await act(async () => finishAdd(otherSession));
+ expect(api.reorderIdeTerminals).not.toHaveBeenCalled();
+ expect(screen.getByTestId("live-grid").textContent).toBe("w2");
+ });
+
});
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index 086e918a68..52699b308b 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -4,7 +4,8 @@ import { FolderPicker } from "@/components/agentic/FolderPicker";
import { VoiceBubble, storedVoiceBubbleOpen, storeVoiceBubbleOpen } from "@/components/agentic/VoiceBubble";
import { WorkspaceTerminalGrid } from "@/components/agentic/WorkspaceTerminalGrid";
import { WorkspaceAgentSetup } from "@/components/agentic/WorkspaceAgentSetup";
-import { WorkspaceToolbar } from "@/components/agentic/WorkspaceToolbar";
+import { WorkspaceOptionsDialog } from "@/components/agentic/WorkspaceOptionsDialog";
+import { fitsWorkspace, isBalancedWorkspace } from "@/components/agentic/workspaceDocking";
import { AgentMark } from "@/components/agentic/AgentMark";
import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
@@ -12,20 +13,12 @@ import { useIdeProjectsStore } from "@/store/ideProjects";
import { openProject } from "@/lib/chatLibraryApi";
import {
activateWorkspace, addTerminal, closeTerminal, closeWorkspace, fetchIdeAgents, fetchIdeProjects, fetchIdeState, renameWorkspace,
- restoreIdeWorkspace, startIdeSession,
+ reorderIdeTerminals, restoreIdeWorkspace, startIdeSession,
type AgentStatus, type IdeProject, type IdeState, type TerminalState,
} from "@/lib/agenticIdeApi";
const FONT_KEY = "jarvis.agenticIde.terminalFontSize";
const APPEARANCE_KEY = "jarvis.agenticIde.terminalAppearance";
-const COLUMNS_KEY = "jarvis.agenticIde.columns.v1";
-
-function rememberedColumns(): number {
- try {
- const value = Number(localStorage.getItem(COLUMNS_KEY));
- return Number.isInteger(value) && value >= 0 && value <= 4 ? value : 0;
- } catch { return 0; /* Display preferences are optional when storage is blocked. */ }
-}
export interface AgenticIdeViewProps { onScreen?: boolean }
@@ -48,7 +41,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
const [workspaceAgents, setWorkspaceAgents] = useState<string[]>([]);
const [selected, setSelected] = useState("");
const [agentPicker, setAgentPicker] = useState<{ id: string; name: string } | null>(null);
- const [columns, setColumns] = useState(rememberedColumns);
+ const [optionsOpen, setOptionsOpen] = useState(false);
const [renameOpen, setRenameOpen] = useState(false);
const [renameValue, setRenameValue] = useState("");
const [busy, setBusy] = useState(false);
@@ -63,11 +56,15 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
const activationRunning = useRef(false);
const pendingActivation = useRef<string | null>(null);
const gridMutations = useRef(0);
+ const normalizingLayout = useRef(false);
const session = state?.session ?? null;
- const activeProject = projects.find((project) => project.id === session?.project_id || project.workspaces.some((workspace) => workspace.id === session?.id));
const installed = agents.filter((agent) => agent.installed && agent.kind !== "shell" && agent.accepts_prompts !== false);
const dialogOpen = projectDialog || workspaceProject !== null || renameOpen || agentPicker !== null;
+ useEffect(() => {
+ setOptionsOpen(false);
+ }, [session?.id]);
+
useEffect(() => {
if (!dialogOpen) return;
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
@@ -94,7 +91,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
}, [dialogOpen, projectDialog, workspaceProject, renameOpen, agentPicker, busy]);
const refresh = useCallback(async (allowDuringActivation = false) => {
- if ((activationRunning.current || gridMutations.current > 0) && !allowDuringActivation) return;
+ if (normalizingLayout.current || ((activationRunning.current || gridMutations.current > 0) && !allowDuringActivation)) return;
const epoch = ++refreshEpoch.current;
let [nextState, listing] = await Promise.all([fetchIdeState(), fetchIdeProjects()]);
// A workspace switch can fall between the two reads. Never publish a tree
@@ -103,6 +100,17 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
[nextState, listing] = await Promise.all([fetchIdeState(), fetchIdeProjects()]);
}
if (epoch !== refreshEpoch.current || pendingActivation.current || ((activationRunning.current || gridMutations.current > 0) && !allowDuringActivation) || nextState.active_id !== listing.active_workspace_id) return;
+ const incoming = nextState.session;
+ if (incoming?.layout && incoming.terminals.length <= 8 && !fitsWorkspace(incoming.layout)) {
+ // Older snapshots and terminals opened outside this view may exceed the
+ // grid bounds. Persist the same balanced fallback the grid displays.
+ normalizingLayout.current = true;
+ try {
+ nextState = await reorderIdeTerminals(incoming.id, incoming.terminals.map((terminal) => terminal.history_id ?? terminal.key));
+ listing = await fetchIdeProjects();
+ } finally { normalizingLayout.current = false; }
+ if (epoch !== refreshEpoch.current || pendingActivation.current || nextState.active_id !== listing.active_workspace_id) return;
+ }
setState(nextState);
setProjects(listing.projects);
publishProjects(listing.projects, listing.active_workspace_id);
@@ -193,13 +201,18 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
if (!action || handledAction.current === action.nonce) return;
handledAction.current = action.nonce;
if (action.kind === "connect-project") { setProjectDialog(true); return; }
+ if (action.kind === "workspace-options") { if (action.workspaceId === session?.id) setOptionsOpen(true); return; }
+ if (action.kind === "toggle-voice") {
+ setVoiceOpen((current) => { const next = !current; storeVoiceBubbleOpen(next); return next; });
+ return;
+ }
if (action.kind === "new-workspace") {
const project = projects.find((entry) => entry.id === action.projectId);
if (project) { setWorkspaceProject(project); setWorkspaceName(""); setWorkspaceAgents([installed[0]?.name ?? ""]); }
return;
}
void activateFromTree(action.workspaceId);
- }, [action, activateFromTree, installed, projects]);
+ }, [action, activateFromTree, installed, projects, session?.id]);
const connect = () => void run(async () => {
if (!projectPath) throw new Error("Choose a folder for this project.");
@@ -222,7 +235,14 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
});
const addAgent = (agentName: string, workspaceId: string) => void run(async () => {
- const next = await addTerminal({ workspace_id: workspaceId, agent: agentName, direction: "down" });
+ const wasBalanced = session?.id === workspaceId && isBalancedWorkspace(session.layout, session.terminals);
+ let next = await addTerminal({ workspace_id: workspaceId, agent: agentName, direction: "down" });
+ // Grow an automatic grid evenly; keep a custom arrangement until another
+ // pane would exceed the workspace bounds.
+ if (next.id === workspaceId && next.terminals.length > 1 && (wasBalanced || (next.layout && !fitsWorkspace(next.layout)))) {
+ const balanced = await reorderIdeTerminals(next.id, next.terminals.map((terminal) => terminal.history_id ?? terminal.key));
+ next = balanced.session ?? next;
+ }
setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current);
});
@@ -233,11 +253,11 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
const saveFont = (size: number) => { const next = Math.max(9, Math.min(22, size)); setFontSize(next); localStorage.setItem(FONT_KEY, String(next)); };
const saveAppearance = (next: "light" | "dark" | null) => { setAppearance(next); if (next) localStorage.setItem(APPEARANCE_KEY, next); else localStorage.removeItem(APPEARANCE_KEY); };
- const saveColumns = (next: number) => {
- setColumns(next);
- try { localStorage.setItem(COLUMNS_KEY, String(next)); }
- catch { /* Keep the current display choice if storage is unavailable. */ }
- };
+ const balanceLayout = () => void run(async () => {
+ if (!session) return;
+ const next = await reorderIdeTerminals(session.id, session.terminals.map((terminal) => terminal.history_id ?? terminal.key));
+ setState((current) => current?.session?.id === next.session?.id ? next : current);
+ });
const openAgentPicker = () => { if (session) setAgentPicker({ id: session.id, name: session.name ?? session.project.name }); };
const closeVoice = () => { setVoiceOpen(false); storeVoiceBubbleOpen(false); };
const jumpToPane = (workspaceId: string, pane: string) => void run(async () => {
@@ -257,16 +277,15 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
if (state === null) return <div data-testid="agentic-ide-loading" className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />Loading projects…</div>;
return <div className="relative flex h-full min-h-0 flex-col bg-background text-foreground" data-testid="igentic-ide">
- <WorkspaceToolbar project={activeProject?.name} workspace={session?.name ?? session?.project.name}
- folder={session?.folder} count={session?.terminals.length ?? 0} busy={busy} canAdd={installed.length > 0}
- onAdd={openAgentPicker} onRename={() => { setRenameValue(session?.name ?? session?.project.name ?? ""); setRenameOpen(true); }}
+ <WorkspaceOptionsDialog open={optionsOpen && !!session} onOpenChange={setOptionsOpen} workspace={session?.name ?? session?.project.name ?? ""}
+ count={session?.terminals.length ?? 0} busy={busy} canAdd={installed.length > 0}
+ onAdd={openAgentPicker} onBalance={balanceLayout} onRename={() => { setRenameValue(session?.name ?? session?.project.name ?? ""); setRenameOpen(true); }}
onClose={stopWorkspace} fontSize={fontSize} onFontSize={saveFont} appearance={appearance} onAppearance={saveAppearance}
- columns={columns} onColumns={saveColumns} voiceOpen={voiceOpen}
- onVoice={() => { const next = !voiceOpen; setVoiceOpen(next); storeVoiceBubbleOpen(next); }} />
+ />
<main className="min-h-0 flex-1">
{session ? <WorkspaceTerminalGrid key={session.id} session={session} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}
- onAdd={openAgentPicker} onClose={closeAgent} onSelect={setSelected} selected={selected} fontSize={fontSize} appearance={appearance} columnPreference={columns}
+ onAdd={openAgentPicker} onClose={closeAgent} onSelect={setSelected} selected={selected} fontSize={fontSize} appearance={appearance} disabled={busy}
onMutationStart={beginGridMutation} onMutationEnd={endGridMutation} />
: <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
<FolderPlus className="h-8 w-8 text-muted-foreground/70" />
diff --git a/tests/unit/agentic_ide/test_panes.py b/tests/unit/agentic_ide/test_panes.py
index 0daf75e69e..201a240aa6 100644
--- a/tests/unit/agentic_ide/test_panes.py
+++ b/tests/unit/agentic_ide/test_panes.py
@@ -71,9 +71,9 @@ async def _noop_exit(_code: int) -> None:
async def test_a_fresh_workspace_uses_row_major_terminal_order(
registry: Registry, tmp_path: Path
) -> None:
- """Three sessions share one row in the project workspace grid."""
+ """Three sessions balance across two columns and two rows."""
await _open(registry, tmp_path, 3)
- assert _layout(registry) == [("T1", 0, 0), ("T2", 1, 0), ("T3", 2, 0)]
+ assert _layout(registry) == [("T1", 0, 0), ("T2", 1, 0), ("T3", 0, 1)]
async def test_a_single_terminal_still_opens_alone(registry: Registry, tmp_path: Path) -> None:
diff --git a/tests/unit/agentic_ide/test_workspace_graph.py b/tests/unit/agentic_ide/test_workspace_graph.py
index 3410088f17..c1be17137c 100644
--- a/tests/unit/agentic_ide/test_workspace_graph.py
+++ b/tests/unit/agentic_ide/test_workspace_graph.py
@@ -10,7 +10,7 @@ from types import SimpleNamespace
import pytest
from fastapi import HTTPException
-from jarvis.agentic_ide import library, resume_store, session, workspace_catalog
+from jarvis.agentic_ide import layout_tree, library, resume_store, session, workspace_catalog
from jarvis.ui.web import agentic_ide_routes as routes
from tests.fakes.fake_pty_manager import FakePtyManager
@@ -111,6 +111,22 @@ async def test_eight_cap_applies_to_create_add_and_batch(registry, tmp_path):
assert len(space.terminals) == 8
+ ("count", "columns"),
+ [(1, 1), (2, 2), (3, 2), (4, 2), (5, 3), (6, 3), (7, 4), (8, 4)],
+)
+async def test_new_workspace_balances_one_to_eight_sessions(registry, tmp_path, count, columns):
+ space = await registry.start(str(tmp_path), [{"agent": "claude"}] * count)
+ hints = layout_tree.grid_hints(space.layout)
+
+ assert layout_tree.leaves(space.layout) == [term.key for term in space.terminals]
+ assert [hints[term.key] for term in space.terminals] == [
+ (index % columns, index // columns) for index in range(count)
+ ]
+ assert len({term.history_id for term in space.terminals}) == count
+ assert registry._pty.spawns == []
+
+
async def test_closed_sibling_stays_restorable_when_project_has_an_open_workspace(
registry, tmp_path
):