Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(ide): simplify terminal grid and stabilize workspace navigation
rubenluetke10-beep74c9b412aca1
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsxindex fb0ec37f0c..d106b1cc39 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx@@ -284,6 +284,30 @@ describe("AgenticTerminal layout", () => {expect(screen.queryByTestId("pane-scroll-history-Dana")).toBeNull();});+ it("opts into compact chrome without recreating the terminal or exposing recap hover controls", () => {+ const onFocus = vi.fn();+ const props = { name: "Dana", displayName: "Codex", agent: "codex", appearance: "dark" as const, fontSize: 13, recap: "Detailed work summary", onFocus };+ const { rerender } = render(<AgenticTerminal {...props} />);+ const host = screen.getByTestId("agentic-terminal-host-Dana");+ const instances = terminalHarness.instances.length;+ expect(screen.getByTestId("pane-header-Dana")).toBeTruthy();+ rerender(<AgenticTerminal {...props} headerMode="compact" />);+ expect(screen.queryByTestId("pane-header-Dana")).toBeNull();+ expect(screen.getByTestId("workspace-terminal-header-Dana")).toBeTruthy();+ expect(screen.queryByTestId("pane-recap-Dana")).toBeNull();+ expect(screen.queryByTestId("pane-header-tip-Dana")).toBeNull();+ expect(screen.getByTestId("agentic-terminal-host-Dana")).toBe(host);+ expect(terminalHarness.instances.length).toBe(instances);+ expect(screen.getByTestId("agentic-pane-Dana").className).toContain("rounded-2xl");+ const title = screen.getByTestId("pane-move-Dana");+ title.focus();+ const focuses = terminalHarness.focus.mock.calls.length;+ fireEvent.click(title);+ expect(onFocus).toHaveBeenCalledOnce();+ expect(document.activeElement).toBe(title);+ expect(terminalHarness.focus.mock.calls.length).toBe(focuses);+ });+it("keeps the wheel on terminal history even while the CLI tracks the mouse", () => {render(<AgenticTerminaldiff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 6af14fbf40..2e1007e68f 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -137,6 +137,7 @@ import {import { PromptReceipt } from "./PromptReceipt";import { PromptHistoryButton } from "./PromptHistoryButton";import { PaneConversationDialog } from "./PaneConversationDialog";+import { WorkspaceTerminalHeader } from "./WorkspaceTerminalHeader";import { useT } from "@/i18n";/**@@ -414,6 +415,11 @@ interface AgenticTerminalProps {workspaceId?: string;/** Agent label shown in the pane header ("Claude Code"). */displayName: string;+ /** Compact workspace chrome is opt-in; legacy grids retain their existing header. */+ headerMode?: "legacy" | "compact";+ /** Registry identity and optional custom logo for the compact header. */+ agent?: string;+ agentLogoUrl?: string;/*** What this session is doing, in one clause — the header's main label.*@@ -538,6 +544,9 @@ export function AgenticTerminal({name,workspaceId,displayName,+ headerMode = "legacy",+ agent,+ agentLogoUrl,recap,recapDetail,recapMeta,@@ -2241,7 +2250,8 @@ export function AgenticTerminal({// click landed, and the ring around it faded in over the next 150 ms.// On a grid where the focused pane is the one standing accent, that// read as a flicker rather than as a pane taking focus.- "relative flex h-full w-full flex-col overflow-hidden rounded-lg border backdrop-blur-[4px]",+ "relative flex h-full w-full flex-col overflow-hidden border backdrop-blur-[4px]",+ headerMode === "compact" ? "rounded-2xl" : "rounded-lg","transition-[box-shadow,border-color,opacity] duration-150 ease-out motion-reduce:transition-none",// Focus steps the RIM one notch, from the structural hairline to// `--border-strong`, and stops there. It used to add a translucent@@ -2288,7 +2298,28 @@ export function AgenticTerminal({}}data-testid={`agentic-pane-${name}`}>- <PaneHeader+ {headerMode === "compact" ? <WorkspaceTerminalHeader+ name={name}+ workspaceId={workspaceId}+ promptCount={promptCount}+ agent={agent ?? ""}+ agentLogoUrl={agentLogoUrl}+ displayName={displayName}+ status={visibleStatus}+ appearance={appearance}+ arranging={arranging}+ maximized={maximized}+ addDisabled={splitDisabled}+ onArrangeStart={onArrangeStart}+ onActivate={() => { onFocus?.(); takeOwnershipRef.current?.(); }}+ onToggleMaximize={onToggleMaximize}+ onAdd={onSplit ? () => onSplit("right") : undefined}+ onClose={onClose}+ onRename={onRename}+ onOpenConversation={() => setHistoryOpen(true)}+ onOpenChat={onOpenChat}+ onRestart={onRestart}+ /> : <PaneHeaderworkspaceId={workspaceId}status={visibleStatus}statusDetail={statusDetail}@@ -2315,7 +2346,7 @@ export function AgenticTerminal({splitDisabled={splitDisabled}onOpenConversation={() => setHistoryOpen(true)}onOpenChat={onOpenChat}- />+ />}{/*What went wrong, kept on screen for as long as it is true — and the oneway out of it. See PaneStatusNotice for why this is a row of its owndiff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsxindex 017ab56f7d..68ee323bab 100644--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx@@ -1,22 +1,132 @@-import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";-import { afterEach, expect, it } from "vitest";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";import { IdeProjectTree } from "./IdeProjectTree";import { useIdeProjectsStore } from "@/store/ideProjects";import type { IdeProject } from "@/lib/agenticIdeApi";+import { ChatLibraryError } from "@/lib/chatLibraryApi";+const patchProject = vi.hoisted(() => vi.fn());+const openProject = vi.hoisted(() => vi.fn());+vi.mock("@/lib/chatLibraryApi", () => ({ patchProject, openProject,+ ChatLibraryError: class extends Error { constructor(message: string, readonly status: number) { super(message); } },+}));++const project = (id = "p1", pinned = false) => ({ id, path: `/${id}`, name: id === "p1" ? "App" : "New App",+ color: null, pinned, archived: false, scratch: false, created_at: 0, last_opened_at: 0, exists: true, chats: 0,+ workspaces: [{ id: `${id}-w1`, name: "Work", status: "open", live_terminals: 1, terminals: 1, restorable: true }] }) as IdeProject;++beforeEach(() => {+ localStorage.clear();+ patchProject.mockReset().mockResolvedValue({});+ openProject.mockReset().mockResolvedValue({ id: "p1" });+ useIdeProjectsStore.setState({ projects: [project()], activeWorkspaceId: "p1-w1", pendingWorkspaceId: null, refreshRequest: null, action: null });+});afterEach(cleanup);-it("preserves a manually collapsed active project across graph refreshes", () => {- const project = { id: "p1", path: "/app", name: "App", archived: false, scratch: false,- workspaces: [{ id: "w1", name: "Work", status: "open", live_terminals: 1, terminals: 1, restorable: true }] } as IdeProject;- useIdeProjectsStore.setState({ projects: [project], activeWorkspaceId: "w1", action: null });- render(<IdeProjectTree />);- const selected = screen.getByTestId("ide-workspace-w1");+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.className).not.toContain("bg-accent");- const toggle = screen.getByRole("button", { name: "Collapse App" });- fireEvent.click(toggle);- expect(screen.queryByTestId("ide-workspace-w1")).toBeNull();- act(() => useIdeProjectsStore.getState().publish([{ ...project, workspaces: [...project.workspaces] }], "w1"));- expect(screen.queryByTestId("ide-workspace-w1")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Collapse App" }));+ expect(screen.queryByTestId("ide-workspace-p1-w1")).toBeNull();+ act(() => useIdeProjectsStore.getState().publish([{ ...project() }], "p1-w1"));+ expect(screen.queryByTestId("ide-workspace-p1-w1")).toBeNull();+ unmount();+ render(<IdeProjectTree />);+ expect(screen.queryByTestId("ide-workspace-p1-w1")).toBeNull();+});++it("expands the same active workspace after a close and reopen", () => {+ render(<IdeProjectTree />);+ fireEvent.click(screen.getByRole("button", { name: "Collapse App" }));+ act(() => useIdeProjectsStore.getState().publish([project()], null));+ act(() => useIdeProjectsStore.getState().publish([project()], "p1-w1"));+ expect(screen.getByTestId("ide-workspace-p1-w1")).toBeDefined();+});++it("opens the first new project and keeps its plus independent", () => {+ useIdeProjectsStore.setState({ projects: [project()], activeWorkspaceId: null });+ render(<IdeProjectTree />);+ expect(screen.getByTestId("ide-workspace-p1-w1")).toBeDefined();+ fireEvent.click(screen.getByRole("button", { name: "Collapse App" }));+ fireEvent.click(screen.getByRole("button", { name: "New workspace in App" }));+ expect(screen.queryByTestId("ide-workspace-p1-w1")).toBeNull();+ expect(useIdeProjectsStore.getState().action?.kind).toBe("new-workspace");+ fireEvent.click(screen.getByRole("button", { name: "Connect project" }));+ expect(useIdeProjectsStore.getState().action?.kind).toBe("connect-project");+});++it("expands a manually collapsed project when its first workspace becomes active", () => {+ useIdeProjectsStore.setState({ projects: [project()], activeWorkspaceId: null });+ render(<IdeProjectTree />);+ fireEvent.click(screen.getByRole("button", { name: "Collapse App" }));+ expect(screen.queryByTestId("ide-workspace-p1-w1")).toBeNull();+ act(() => useIdeProjectsStore.getState().publish([project()], "p1-w1"));+ expect(screen.getByTestId("ide-workspace-p1-w1")).toBeDefined();+});++it("counts agent sessions across a project's workspaces", () => {+ const withTwo = { ...project(), workspaces: [+ { ...project().workspaces[0], terminals: 6 },+ { ...project().workspaces[0], id: "p1-w2", terminals: 3 },+ ] };+ useIdeProjectsStore.setState({ projects: [withTwo] });+ render(<IdeProjectTree />);+ expect(screen.getByLabelText("9 agent sessions").textContent).toBe("9");+});++it("marks a queued workspace before the active workspace changes", () => {+ render(<IdeProjectTree />);+ act(() => useIdeProjectsStore.getState().setPendingWorkspaceId("p1-w1"));+ const row = screen.getByTestId("ide-workspace-p1-w1");+ expect(row.getAttribute("aria-busy")).toBe("true");+ expect(row.textContent).toContain("Switching workspace");+});++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" }));+ fireEvent.click(screen.getByRole("button", { name: "Pin project" }));+ await waitFor(() => expect(patchProject).toHaveBeenCalledWith("p1", { pinned: true }));+ await waitFor(() => expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(1));+ fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));+ fireEvent.click(screen.getByRole("button", { name: "Rename project" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Rename App" }), { target: { value: "Better App" } });+ fireEvent.click(screen.getByRole("button", { name: "Save App" }));+ await waitFor(() => expect(patchProject).toHaveBeenCalledWith("p1", { name: "Better App" }));+ await waitFor(() => expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(2));+});++it("registers a legacy derived project only after PATCH 404, then retries once", async () => {+ patchProject.mockRejectedValueOnce(new ChatLibraryError("missing", 404)).mockResolvedValueOnce({});+ render(<IdeProjectTree />);+ fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));+ fireEvent.click(screen.getByRole("button", { name: "Pin project" }));+ await waitFor(() => expect(patchProject).toHaveBeenCalledTimes(2));+ expect(openProject).toHaveBeenCalledTimes(1);+ expect(openProject).toHaveBeenCalledWith("/p1");+ expect(patchProject).toHaveBeenNthCalledWith(2, "p1", { pinned: true });+ expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(1);+});++it("does not register or retry on non-404 metadata errors", async () => {+ patchProject.mockRejectedValueOnce(new ChatLibraryError("denied", 403));+ render(<IdeProjectTree />);+ fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));+ fireEvent.click(screen.getByRole("button", { name: "Pin project" }));+ await waitFor(() => expect(patchProject).toHaveBeenCalledTimes(1));+ expect(openProject).not.toHaveBeenCalled();+ expect(useIdeProjectsStore.getState().refreshRequest).toBeNull();+});++it("submits only one metadata mutation when a project action is pressed twice", async () => {+ let finish!: (value: unknown) => void;+ patchProject.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ render(<IdeProjectTree />);+ fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));+ const pin = screen.getByRole("button", { name: "Pin project" });+ act(() => { fireEvent.click(pin); fireEvent.click(pin); });+ expect(patchProject).toHaveBeenCalledTimes(1);+ act(() => finish({}));+ await waitFor(() => expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(1));});diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsxindex 6694c097fd..6ab2e41de8 100644--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx@@ -1,66 +1,191 @@import { useEffect, useRef, useState } from "react";-import { ChevronDown, ChevronRight, Folder, Plus } from "lucide-react";+import { Check, ChevronDown, ChevronRight, Folder, Loader2, 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";import { useIdeProjectsStore } from "@/store/ideProjects";-/** The IDE's compact project navigation. Workspace IDs, never paths, select runtime context. */+const EXPANSION_KEY = "jarvis.ide.projectExpansion.v1";++function readExpansion(): Record<string, boolean> {+ try {+ const value: unknown = JSON.parse(localStorage.getItem(EXPANSION_KEY) ?? "{}");+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};+ return Object.fromEntries(Object.entries(value).filter(([, open]) => typeof open === "boolean")) as Record<string, boolean>;+ } catch { return {}; /* Expansion is an optional preference; unavailable storage keeps defaults usable. */ }+}++function saveExpansion(value: Record<string, boolean>): void {+ try { localStorage.setItem(EXPANSION_KEY, JSON.stringify(value)); }+ catch { /* Browsers without storage keep the current in-memory choice. */ }+}++/** Compact, accessible navigation over real projects and their workspace IDs. */export function IdeProjectTree() {const projects = useIdeProjectsStore((state) => state.projects);const activeWorkspaceId = useIdeProjectsStore((state) => state.activeWorkspaceId);+ const pendingWorkspaceId = useIdeProjectsStore((state) => state.pendingWorkspaceId);const connectProject = useIdeProjectsStore((state) => state.connectProject);const newWorkspace = useIdeProjectsStore((state) => state.newWorkspace);const activateWorkspace = useIdeProjectsStore((state) => state.activateWorkspace);- const [expanded, setExpanded] = useState<string[]>([]);- const lastAutoExpandedWorkspace = useRef<string | null>(null);+ const requestRefresh = useIdeProjectsStore((state) => state.requestRefresh);+ const pushToast = useEventStore((state) => state.pushToast);+ const [expansion, setExpansion] = useState(readExpansion);+ const [menuId, setMenuId] = useState<string | null>(null);+ const [renamingId, setRenamingId] = useState<string | null>(null);+ const [draftName, setDraftName] = useState("");+ const [mutatingId, setMutatingId] = useState<string | null>(null);+ const sawProjectSnapshot = useRef(false);+ const lastActiveId = useRef<string | null>(null);+ const lastPendingId = useRef<string | null>(null);+ const knownProjectIds = useRef<Set<string> | null>(null);+ const mutatingProjects = useRef<Set<string>>(new Set());+ const visible = projects.filter((project) => !project.archived && !project.scratch);+ const activeProject = visible.find((project) => project.workspaces.some((workspace) => workspace.id === activeWorkspaceId));++ const setProjectOpen = (id: string, open: boolean) => setExpansion((previous) => {+ const next = { ...previous, [id]: open };+ saveExpansion(next);+ return next;+ });useEffect(() => {- const current = projects.find((project) => project.workspaces.some((workspace) => workspace.id === activeWorkspaceId));- if (current && activeWorkspaceId !== lastAutoExpandedWorkspace.current) {- lastAutoExpandedWorkspace.current = activeWorkspaceId;- setExpanded((old) => old.includes(current.id) ? old : [...old, current.id]);+ if (!sawProjectSnapshot.current) {+ if (visible.length === 0) return;+ sawProjectSnapshot.current = true;+ lastActiveId.current = activeWorkspaceId;+ // Initial hydration respects a saved collapse, even for the active row.+ return;+ }+ if (lastActiveId.current !== activeWorkspaceId) {+ lastActiveId.current = activeWorkspaceId;+ if (activeProject) setProjectOpen(activeProject.id, true);}- }, [activeWorkspaceId, projects]);+ }, [activeWorkspaceId, activeProject?.id, projects]);- return <div data-testid="ide-project-tree" className="mt-1 px-2 pb-2">- <div className="group 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-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <Plus className="h-3.5 w-3.5" />- </button>- </div>- {projects.filter((project) => !project.archived && !project.scratch).map((project) => {- const open = expanded.includes(project.id);- const active = project.workspaces.some((workspace) => workspace.id === activeWorkspaceId);- return <div key={project.id} className="mb-0.5">- <div className={`group flex min-h-9 items-center rounded-lg transition-colors hover:bg-muted/70 ${active ? "bg-muted" : ""}`}>+ useEffect(() => {+ if (pendingWorkspaceId === null) { lastPendingId.current = null; return; }+ if (lastPendingId.current === pendingWorkspaceId) return;+ const project = visible.find((entry) => entry.workspaces.some((workspace) => workspace.id === pendingWorkspaceId));+ if (project) { lastPendingId.current = pendingWorkspaceId; setProjectOpen(project.id, true); }+ }, [pendingWorkspaceId, projects]);++ useEffect(() => {+ const ids = new Set(visible.map((project) => project.id));+ if (knownProjectIds.current) {+ for (const id of ids) if (!knownProjectIds.current.has(id)) setProjectOpen(id, true);+ }+ if (ids.size > 0) knownProjectIds.current = ids;+ }, [projects]);++ useEffect(() => {+ if (!menuId) return;+ const dismiss = (event: PointerEvent) => {+ if (!(event.target instanceof Element) || event.target.closest("[data-project-menu]")?.getAttribute("data-project-menu") !== menuId) setMenuId(null);+ };+ const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") setMenuId(null); };+ document.addEventListener("pointerdown", dismiss);+ document.addEventListener("keydown", onKey);+ return () => { document.removeEventListener("pointerdown", dismiss); document.removeEventListener("keydown", onKey); };+ }, [menuId]);++ const mutate = async (project: IdeProject, changes: { pinned?: boolean; name?: string }) => {+ if (mutatingProjects.current.has(project.id)) return;+ mutatingProjects.current.add(project.id);+ setMutatingId(project.id);+ try {+ try {+ await patchProject(project.id, changes);+ } catch (error) {+ if (!(error instanceof ChatLibraryError) || error.status !== 404) throw error;+ // Legacy workspace snapshots can appear in the graph before the chat+ // library has saved their derived project row. Register once, then+ // retry the same metadata patch without changing an existing name.+ await openProject(project.path);+ await patchProject(project.id, changes);+ }+ setMenuId(null);+ setRenamingId(null);+ requestRefresh();+ } catch (error) { pushToast("error", (error as Error).message); }+ finally { mutatingProjects.current.delete(project.id); setMutatingId(null); }+ };++ const projectRow = (project: IdeProject) => {+ const open = expansion[project.id] ?? (project.id === activeProject?.id || (!activeWorkspaceId && visible[0]?.id === project.id));+ const active = project.id === activeProject?.id;+ 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" : ""}`}>+ {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); } }}+ className="min-w-0 flex-1 rounded border border-input bg-background px-2 py-1 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring" />+ <button type="submit" aria-label={`Save ${project.name}`} disabled={working || !draftName.trim()} className="rounded p-1 text-muted-foreground hover:text-foreground disabled:opacity-40"><Check className="h-4 w-4" /></button>+ <button type="button" aria-label={`Cancel renaming ${project.name}`} onClick={() => setRenamingId(null)} className="rounded p-1 text-muted-foreground hover:text-foreground"><X className="h-4 w-4" /></button>+ </form> : <><button type="button" aria-label={`${open ? "Collapse" : "Expand"} ${project.name}`} aria-expanded={open}- onClick={() => setExpanded((old) => open ? old.filter((id) => id !== project.id) : [...old, project.id])}+ 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">{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" /><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>}</button>- <button type="button" aria-label={`New workspace in ${project.name}`} title="New workspace" onClick={() => newWorkspace(project.id)}- className="mr-1 rounded p-1.5 text-muted-foreground opacity-70 hover:bg-background hover:text-foreground group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <Plus className="h-3.5 w-3.5" />- </button>- </div>- {open && <div className="ml-5 border-l border-border/70 pl-2">- {project.workspaces.map((workspace) => <button key={workspace.id} type="button"- data-testid={`ide-workspace-${workspace.id}`}- aria-current={workspace.id === activeWorkspaceId ? "page" : undefined}+ <div className="relative flex shrink-0 items-center pr-1" 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">+ {working ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <MoreHorizontal className="h-3.5 w-3.5" />}+ </button>+ <button type="button" aria-label={`New workspace in ${project.name}`} title="New workspace" onClick={() => newWorkspace(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">+ <Plus className="h-3.5 w-3.5" />+ </button>+ {menuId === project.id && <div className="absolute right-0 top-full z-30 mt-1 min-w-40 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg">+ <button type="button" disabled={working} onClick={() => void mutate(project, { pinned: !project.pinned })}+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-muted disabled:opacity-50"><Pin className="h-3.5 w-3.5" />{project.pinned ? "Unpin project" : "Pin project"}</button>+ <button type="button" disabled={working} onClick={() => { setMenuId(null); setDraftName(project.name); setRenamingId(project.id); }}+ className="block w-full rounded px-2 py-1.5 text-left text-xs hover:bg-muted disabled:opacity-50">Rename project</button>+ </div>}+ </div>+ </>}+ </div>+ {open && <div className="ml-5 border-l border-border/70 pl-2">+ {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}`}+ 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 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 ${workspace.id === activeWorkspaceId ? "bg-muted text-foreground" : "text-muted-foreground"}`}>- <span 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-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"}`} />}<span className="min-w-0 flex-1 truncate">{workspace.name}</span><span className="tabular-nums opacity-70">{workspace.terminals}</span>- </button>)}- {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>}- </div>}- </div>;- })}- {projects.every((project) => project.archived || project.scratch) && <p className="px-2 py-2 text-xs text-muted-foreground">Connect a folder to start a project.</p>}+ {pending && <span className="sr-only">Switching workspace</span>}+ </button>;+ })}+ {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>}+ </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>+ </div>+ {visible.some((project) => project.pinned) && <>+ <div className="px-2 pb-1 pt-2 text-[11px] font-medium text-muted-foreground">Pinned</div>+ {visible.filter((project) => project.pinned).map(projectRow)}+ {visible.some((project) => !project.pinned) && <div className="px-2 pb-1 pt-3 text-[11px] font-medium text-muted-foreground">Other projects</div>}+ </>}+ {visible.filter((project) => !project.pinned).map(projectRow)}+ {visible.length === 0 && <p className="px-2 py-2 text-xs text-muted-foreground">Connect a folder to start a project.</p>}</div>;}diff --git a/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.test.tsxindex eac4a7b078..4082c8ee8a 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.test.tsx@@ -49,6 +49,20 @@ beforeEach(() => {});describe("PromptHistoryButton", () => {+ it("keeps history open when its overflow trigger becomes hidden", async () => {+ const onOpen = vi.fn();+ const restoreFocus = vi.fn();+ const { rerender } = render(<div><PromptHistoryButton terminal="Nova" workspaceId="ide_alpha" count={2} triggerMode="menu-item" onOpen={onOpen} restoreFocus={restoreFocus} /></div>);+ fireEvent.click(screen.getByRole("menuitem"));+ expect(onOpen).toHaveBeenCalledOnce();+ rerender(<div hidden><PromptHistoryButton terminal="Nova" workspaceId="ide_alpha" count={2} triggerMode="menu-item" onOpen={onOpen} restoreFocus={restoreFocus} /></div>);+ await waitFor(() => expect(screen.getByTestId("prompt-history-dialog")).toBeTruthy());+ await waitFor(() => expect(fetchMock).toHaveBeenCalledWith("Nova", "ide_alpha"));+ fireEvent.keyDown(screen.getByTestId("prompt-history-dialog"), { key: "Escape" });+ await waitFor(() => expect(screen.queryByTestId("prompt-history-dialog")).toBeNull());+ expect(restoreFocus).toHaveBeenCalledOnce();+ });+it("puts a small, counted history control in the pane header", () => {render(<PromptHistoryButtondiff --git a/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.tsx b/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.tsxindex c2037258fd..c5938f980d 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PromptHistoryButton.tsx@@ -46,10 +46,18 @@ export function PromptHistoryButton({terminal,workspaceId,count,+ triggerMode = "icon",+ onOpen,+ restoreFocus,}: {terminal: string;workspaceId?: string;count: number;+ /** A workspace overflow uses a text menu item; legacy headers keep the icon. */+ triggerMode?: "icon" | "menu-item";+ onOpen?: () => void;+ /** The menu trigger can be hidden while the history dialog stays mounted. */+ restoreFocus?: () => void;/*** Whether the PANE this button sits on wears the light appearance.*@@ -122,18 +130,22 @@ export function PromptHistoryButton({open={open}onOpenChange={(next) => {setOpen(next);+ if (next) onOpen?.();if (!next) setCopyState("idle");}}><Dialog.Trigger asChild><buttontype="button"+ role={triggerMode === "menu-item" ? "menuitem" : undefined}aria-label={triggerLabel}title={triggerLabel}data-testid={`pane-prompt-history-${terminal}`}onMouseDown={(event) => event.stopPropagation()}className={cn(- "flex h-6 min-w-6 shrink-0 items-center justify-center gap-1 rounded-md px-1.5",+ triggerMode === "menu-item"+ ? "flex w-full items-center gap-2 rounded px-2.5 py-2 text-left text-xs focus:bg-[color:var(--pane-chip)] focus:outline-none"+ : "flex h-6 min-w-6 shrink-0 items-center justify-center gap-1 rounded-md px-1.5","text-micro font-medium tabular-nums transition-colors active:translate-y-px",// The header's own `--pane-*` ladder, exactly as PaneAction next// door reads it. This used to be a hex per appearance, which is@@ -144,13 +156,14 @@ export function PromptHistoryButton({)}><History className="h-3.5 w-3.5" aria-hidden="true" />- {count > 0 && <span>{count}</span>}+ {triggerMode === "menu-item" ? <span>{t("agentic_grid.history.title")}</span> : count > 0 && <span>{count}</span>}</button></Dialog.Trigger><Dialog.Portal><Dialog.Overlay className="fixed inset-0 z-[80] bg-scrim/75 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none" /><Dialog.Content+ onCloseAutoFocus={restoreFocus ? (event) => { event.preventDefault(); restoreFocus(); } : undefined}data-testid="prompt-history-dialog"className={cn("fixed left-1/2 top-1/2 z-[90] flex max-h-[82dvh] w-[min(940px,calc(100vw-2rem))]",diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsxindex 15a6e4f497..18d94103ab 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.test.tsx@@ -1,63 +1,154 @@-import { describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { useState } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import type { SessionState } from "@/lib/agenticIdeApi";-const reorder = vi.hoisted(() => vi.fn());-vi.mock("@/lib/agenticIdeApi", () => ({ reorderIdeTerminals: reorder }));-vi.mock("./AgenticTerminal", () => ({ AgenticTerminal: ({ name, onToggleMaximize, onArrangeStart, showArrangeHandle }: { name: string; onToggleMaximize: () => void; onArrangeStart?: (event: React.PointerEvent) => void; showArrangeHandle?: boolean }) => <>- <button onClick={onToggleMaximize}>{name}</button>- {showArrangeHandle && <button type="button" data-ide-drag-handle="true" onPointerDown={onArrangeStart}>Move {name}</button>}-</> }));+const api = vi.hoisted(() => ({ reorder: vi.fn(), rename: vi.fn(), toast: vi.fn() }));+vi.mock("@/lib/agenticIdeApi", () => ({ reorderIdeTerminals: api.reorder, 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;+ onFocus: () => void;+ onArrangeStart?: (event: React.PointerEvent) => void;+}) => <div onMouseDown={props.onFocus}>+ <button onClick={props.onToggleMaximize}>Maximize {props.name}</button>+ <button type="button" data-ide-drag-handle="true" onPointerDown={props.onArrangeStart}>Move {props.name}</button>+ <button onClick={props.onRestart}>Restart {props.name}</button>+ <output data-testid={`restart-${props.name}`}>{props.restartToken}</output>+ <textarea aria-label={`Terminal input ${props.name}`} />+</div> }));vi.mock("@/hooks/useTheme", () => ({ useThemeValue: () => "dark" }));-import { columnsForSessions } from "./WorkspaceTerminalGrid";-import { WorkspaceTerminalGrid } from "./WorkspaceTerminalGrid";+import { columnsForSessions, swapSessions, WorkspaceTerminalGrid } from "./WorkspaceTerminalGrid";class ResizeObserverStub { observe() {} disconnect() {} }+class PointerEventStub extends MouseEvent {+ pointerId: number;+ constructor(type: string, init: PointerEventInit = {}) { super(type, init); this.pointerId = init.pointerId ?? 1; }+}vi.stubGlobal("ResizeObserver", ResizeObserverStub);-vi.stubGlobal("PointerEvent", MouseEvent);+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" })),+}) 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);+const geometry = () => document.querySelectorAll<HTMLElement>("[data-session-id]").forEach((node, index) => {+ const x = (index % 2) * 400, y = Math.floor(index / 2) * 400;+ node.getBoundingClientRect = () => ({ left: x, top: y, right: x + 390, bottom: y + 390, width: 390, height: 390, x, y, toJSON() {} });+});+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 });+};+function Controlled() {+ const [session, setSession] = useState(makeSession());+ return <WorkspaceTerminalGrid {...props} session={session} onChanged={setSession} />;+}+beforeEach(() => { vi.clearAllMocks(); });+afterEach(cleanup);-describe("workspace session columns", () => {- it("uses the compact reference layout on a wide desktop", () => {+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, 2, 3, 3, 4, 4]);+ .toEqual([1, 2, 3, 4, 3, 3, 4, 4]);+ expect(columnsForSessions(4, 1100)).toBe(2);});-- it("limits columns as available width shrinks", () => {+ 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; }));+ render(<Controlled />);+ const original = screen.getByLabelText("Terminal input T1");+ dragToThird();+ expect(order()).toEqual(["T3", "T2", "T1", "T4"]);+ expect(screen.getByLabelText("Terminal input T1")).toBe(original);+ expect(api.reorder).toHaveBeenCalledWith("w1", ["T3", "T2", "T1", "T4"]);+ 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(order()).toEqual(["T3", "T2", "T1", "T4"]);+});++it("allows title pointer presses to select the pane without starting a reorder", () => {+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} />);+ const handle = screen.getByRole("button", { name: "Move T1" });+ const down = new PointerEvent("pointerdown", { bubbles: true, cancelable: true, button: 0, pointerId: 1 });+ fireEvent(handle, down);+ // Browsers suppress compatibility mousedown when pointerdown is cancelled.+ expect(down.defaultPrevented).toBe(false);+ if (!down.defaultPrevented) fireEvent.mouseDown(handle);+ fireEvent.pointerUp(window, { pointerId: 1 });+ fireEvent.click(handle, { detail: 1 });+ expect(props.onSelect).toHaveBeenCalledExactlyOnceWith("T1");+ expect(api.reorder).not.toHaveBeenCalled();+});++it("rolls back a rejected swap and releases the mutation barrier", async () => {+ api.reorder.mockRejectedValue(new Error("Connection lost"));+ const onMutationStart = vi.fn(), onMutationEnd = vi.fn();+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} onMutationStart={onMutationStart} onMutationEnd={onMutationEnd} />);+ dragToThird();+ await waitFor(() => expect(api.toast).toHaveBeenCalledWith("error", "Connection lost"));+ expect(order()).toEqual(["T1", "T2", "T3", "T4"]);+ expect(onMutationStart).toHaveBeenCalledOnce();+ expect(onMutationEnd).toHaveBeenCalledOnce();+});++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; }));+ 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"]) }));+ expect(changed).not.toHaveBeenCalled();+ expect(order()).toEqual(["T2", "T3", "T4"]);+});++it("cancels a drag with Escape and does not steal terminal keyboard shortcuts", () => {+ render(<WorkspaceTerminalGrid {...props} session={makeSession()} />);+ geometry();+ const handle = screen.getByRole("button", { name: "Move T1" });+ fireEvent.pointerDown(handle, { button: 0, clientX: 15, clientY: 15 });+ fireEvent.pointerMove(window, { clientX: 20, clientY: 450 });+ 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();+});++it("receives drag movement over a terminal even when it stops event bubbling", async () => {+ api.reorder.mockResolvedValue({ session: 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"]));});-it("shows the remaining pane when a maximized session closes", async () => {- const terminal = (name: string) => ({ name, key: name, history_id: name, display_name: name });- const session = (names: string[]) => ({ id: "w1", terminals: names.map(terminal) }) as SessionState;- const props = { onChanged: vi.fn(), onAdd: vi.fn(), onClose: vi.fn(), onSelect: vi.fn(), selected: "", fontSize: 13, appearance: null };- const { rerender } = render(<WorkspaceTerminalGrid session={session(["T1", "T2"])} {...props} />);- fireEvent.click(screen.getByRole("button", { name: "T1" }));- rerender(<WorkspaceTerminalGrid session={session(["T2"])} {...props} />);- await waitFor(() => expect(screen.getByRole("button", { name: "T2" }).closest("[data-session-id]")?.className).not.toContain("hidden"));-});--it("reorders through the visible handle and leaves terminal keys alone", async () => {- reorder.mockReset();- const session = { id: "w1", terminals: ["T1", "T2"].map((name) => ({ name, key: name, history_id: name, display_name: name })) } as SessionState;- reorder.mockResolvedValue({ session });- const props = { onChanged: vi.fn(), onAdd: vi.fn(), onClose: vi.fn(), onSelect: vi.fn(), selected: "", fontSize: 13, appearance: null };- render(<WorkspaceTerminalGrid session={session} {...props} />);- const source = screen.getByRole("button", { name: "Move T1" });- const target = document.querySelector<HTMLElement>('[data-session-id="T2"]');- Object.defineProperty(document, "elementFromPoint", { configurable: true, value: vi.fn(() => target) });- fireEvent.pointerDown(source, { button: 0, clientX: 10, clientY: 10 });- fireEvent.pointerMove(window, { clientX: 35, clientY: 10 });- fireEvent.pointerUp(window, { clientX: 35, clientY: 10 });- await waitFor(() => expect(reorder).toHaveBeenCalledWith("w1", ["T2", "T1"]));-- reorder.mockClear();- const tile = document.querySelector<HTMLElement>('[data-session-id="T1"]')!;- const terminalInput = document.createElement("textarea");- tile.appendChild(terminalInput);- fireEvent.keyDown(terminalInput, { altKey: true, key: "ArrowRight" });- expect(reorder).not.toHaveBeenCalled();- fireEvent.keyDown(tile, { altKey: true, key: "ArrowRight" });- await waitFor(() => expect(reorder).toHaveBeenCalledWith("w1", ["T2", "T1"]));+it("only restarts the addressed session and shows survivors after maximized close", async () => {+ const { rerender } = render(<WorkspaceTerminalGrid {...props} session={makeSession(["T1", "T2"])} />);+ fireEvent.click(screen.getByRole("button", { name: "Restart T1" }));+ expect(screen.getByTestId("restart-T1").textContent).toBe("1");+ expect(screen.getByTestId("restart-T2").textContent).toBe("0");+ fireEvent.click(screen.getByRole("button", { name: "Maximize T1" }));+ rerender(<WorkspaceTerminalGrid {...props} session={makeSession(["T2"])} />);+ await waitFor(() => expect(screen.getByRole("button", { name: "Maximize T2" }).closest("[data-session-id]")?.className).not.toContain("hidden"));});diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsxindex 190098d13e..47f9efca82 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx@@ -1,15 +1,33 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { AgenticTerminal } from "./AgenticTerminal";+import { AgentMark } from "./AgentMark";import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";-import { reorderIdeTerminals } from "@/lib/agenticIdeApi";+import { renameTerminal, reorderIdeTerminals } from "@/lib/agenticIdeApi";import { useThemeValue } from "@/hooks/useTheme";import { useEventStore } from "@/store/events";+import { cn } from "@/lib/utils";-export function columnsForSessions(count: number, width: number): number {+const GAP = 8;+const MIN_WIDTH = 320;+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 readable = Math.max(1, Math.min(4, Math.floor(width / 320) || 1));- const desired = count <= 3 ? count : count <= 4 ? 2 : count <= 6 ? 3 : 4;- return Math.max(Math.ceil(count / 2), Math.min(readable, desired));+ 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 {@@ -21,102 +39,189 @@ interface Props {selected: string;fontSize: number;appearance: "light" | "dark" | null;+ columnPreference?: number;+ onMutationStart?: () => void;+ onMutationEnd?: () => void;}-export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, fontSize, appearance }: Props) {+interface DragFeedback { id: string; target: string | null; x: number; y: number }++export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSelect, selected, fontSize, appearance, columnPreference = 0, onMutationStart, onMutationEnd }: Props) {const theme = useThemeValue();const pushToast = useEventStore((state) => state.pushToast);const frame = useRef<HTMLDivElement>(null);const [width, setWidth] = useState(1280);- const [dragging, setDragging] = useState<string | null>(null);- const [hover, setHover] = useState<string | null>(null);+ const [drag, setDrag] = useState<DragFeedback | null>(null);+ const [optimistic, setOptimistic] = useState<string[] | null>(null);+ const [saving, setSaving] = useState(false);const [maximized, setMaximized] = useState<string | null>(null);+ const [restarts, setRestarts] = useState<Record<string, number>>({});+ const [announcement, setAnnouncement] = useState("");const dragCleanup = useRef<(() => void) | null>(null);- const ordered = session.terminals;- const columns = columnsForSessions(ordered.length, width);+ const saveInFlight = useRef(false);+ const mounted = useRef(true);+ const latest = useRef({ session, onChanged, onSelect, onMutationStart, onMutationEnd });+ latest.current = { session, onChanged, onSelect, onMutationStart, onMutationEnd };- useEffect(() => {- if (maximized && !ordered.some((terminal) => (terminal.history_id ?? terminal.key) === maximized)) setMaximized(null);- }, [maximized, ordered]);+ 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 visibleMaximized = maximized && members.includes(maximized) ? maximized : null;+ useEffect(() => {+ mounted.current = true;+ return () => { mounted.current = false; dragCleanup.current?.(); };+ }, []);+ useEffect(() => {+ if (maximized && !members.includes(maximized)) setMaximized(null);+ }, [maximized, members]);useEffect(() => {const node = frame.current;if (!node) return;- const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));+ const observer = new ResizeObserver(([entry]) => {+ if (entry.contentRect.width > 0) setWidth(entry.contentRect.width);+ else dragCleanup.current?.();+ });observer.observe(node);return () => observer.disconnect();}, []);- useEffect(() => () => dragCleanup.current?.(), []);const move = useCallback(async (sourceId: string, targetId: string) => {- if (sourceId === targetId) return;- const ids = ordered.map((terminal) => terminal.history_id ?? terminal.key);- const from = ids.indexOf(sourceId);- const to = ids.indexOf(targetId);- if (from < 0 || to < 0) return;- ids.splice(to, 0, ids.splice(from, 1)[0]);+ if (saveInFlight.current || sourceId === targetId) return;+ const owner = latest.current.session;+ const before = owner.terminals.map(idOf);+ const next = swapSessions(before, sourceId, targetId);+ if (next === before) 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(session.id, ids);- if (state.session) onChanged(state.session);+ const state = await reorderIdeTerminals(owner.id, next);+ 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.`);} catch (error) {- pushToast("error", (error as Error).message);+ if (mounted.current) {+ pushToast("error", (error as Error).message);+ setAnnouncement("Could not save the arrangement. The previous order was restored.");+ }+ } finally {+ saveInFlight.current = false;+ latest.current.onMutationEnd?.();+ if (mounted.current) { setSaving(false); setOptimistic(null); }}- }, [onChanged, ordered, pushToast, session.id]);+ }, [pushToast]);const startDrag = useCallback((id: string, event: React.PointerEvent) => {- if (event.button !== 0 || dragCleanup.current) return;- const initialX = event.clientX;- const initialY = event.clientY;+ if (event.button !== 0 || 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 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;+ }+ return null;+ };const onMove = (motion: PointerEvent) => {- if (!armed && Math.hypot(motion.clientX - initialX, motion.clientY - initialY) > 5) { armed = true; setDragging(id); }- if (!armed) return;- const tile = document.elementFromPoint(motion.clientX, motion.clientY)?.closest<HTMLElement>("[data-session-id]");- setHover(tile?.dataset.sessionId ?? null);+ if (motion.pointerId !== pointer) return;+ if (!armed && Math.hypot(motion.clientX - initialX, motion.clientY - initialY) <= 5) return;+ armed = true;+ motion.preventDefault();+ setDrag({ id, target: targetAt(motion.clientX, motion.clientY), x: motion.clientX, y: motion.clientY });};const cleanup = () => {- window.removeEventListener("pointermove", onMove);- window.removeEventListener("pointerup", onUp);- window.removeEventListener("pointercancel", onCancel);+ window.removeEventListener("pointermove", onMove, true);+ window.removeEventListener("pointerup", onUp, true);+ window.removeEventListener("pointercancel", onCancel, true);+ window.removeEventListener("blur", cleanup);+ window.removeEventListener("keydown", onKey, true);+ if (handle.hasPointerCapture?.(pointer)) handle.releasePointerCapture(pointer);dragCleanup.current = null;- setDragging(null);- setHover(null);+ if (mounted.current) setDrag(null);};- const onCancel = () => cleanup();+ const onCancel = (cancel: PointerEvent) => { if (cancel.pointerId === pointer) cleanup(); };+ const onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); key.stopPropagation(); cleanup(); } };const onUp = (release: PointerEvent) => {+ if (release.pointerId !== pointer) return;+ const target = targetAt(release.clientX, release.clientY);cleanup();- const tile = document.elementFromPoint(release.clientX, release.clientY)?.closest<HTMLElement>("[data-session-id]");- if (armed && tile?.dataset.sessionId) void move(id, tile.dataset.sessionId);+ if (armed && target && target !== id) void move(id, target);};dragCleanup.current = cleanup;- window.addEventListener("pointermove", onMove);- window.addEventListener("pointerup", onUp);- window.addEventListener("pointercancel", onCancel);+ window.addEventListener("pointermove", onMove, { capture: true, passive: false });+ window.addEventListener("pointerup", onUp, true);+ window.addEventListener("pointercancel", onCancel, true);+ window.addEventListener("blur", cleanup);+ window.addEventListener("keydown", onKey, true);}, [move]);- const tiles = useMemo(() => ordered.map((terminal) => ({ ...terminal, stableId: terminal.history_id ?? terminal.key })), [ordered]);- return <div ref={frame} data-testid="workspace-terminal-grid" className="h-full min-h-0 overflow-auto p-2.5">- <div className="grid h-full gap-2.5" style={{ gridTemplateColumns: `repeat(${maximized ? 1 : columns}, minmax(0, 1fr))`, gridTemplateRows: `repeat(${maximized ? 1 : Math.ceil(tiles.length / columns)}, minmax(0, 1fr))`, minWidth: maximized ? undefined : `${columns * 320}px`, minHeight: "280px" }}>- {tiles.map((terminal, index) => <div key={terminal.stableId} data-session-id={terminal.stableId}- tabIndex={0} aria-label={`${terminal.name}, position ${index + 1} of ${tiles.length}. Press Alt+Arrow keys to reorder.`}- 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();- const delta = event.key === "ArrowLeft" ? -1 : event.key === "ArrowRight" ? 1 : event.key === "ArrowUp" ? -columns : columns;- const target = tiles[index + delta];- if (target) void move(terminal.stableId, target.stableId);- }}- className={`relative min-h-0 min-w-0 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${dragging === terminal.stableId ? "opacity-60" : ""} ${hover === terminal.stableId && dragging !== terminal.stableId ? "ring-2 ring-primary" : ""} ${maximized && maximized !== terminal.stableId ? "hidden" : ""}`}>- <AgenticTerminal 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={maximized === terminal.stableId} onToggleMaximize={() => setMaximized((current) => current === terminal.stableId ? null : terminal.stableId)}- onArrangeStart={maximized ? undefined : (event) => startDrag(terminal.stableId, event)}- showArrangeHandle={!maximized}- onClose={() => onClose(terminal)} onAttachError={(message) => pushToast("error", message)}- splitDisabled={tiles.length >= 8} onSplit={() => onAdd()} />- </div>)}+ const rename = async (terminal: TerminalState, name: string) => {+ const owner = latest.current.session;+ latest.current.onMutationStart?.();+ try {+ const next = await renameTerminal(terminal.history_id ? `pane:${terminal.history_id}` : terminal.name, name);+ if (!mounted.current || next.id !== latest.current.session.id) return false;+ if (latest.current.session === owner) latest.current.onChanged(next);+ if (selected === terminal.name) latest.current.onSelect(next.terminals.find((entry) => idOf(entry) === idOf(terminal))?.name ?? name);+ return true;+ } catch (error) { pushToast("error", (error as Error).message); return false; }+ finally { latest.current.onMutationEnd?.(); }+ };+ 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",+ }}>+ {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.`}+ 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));+ }}+ 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",+ 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}+ 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>}+ </div>;+ })}</div>+ {drag && dragged && <div aria-hidden="true" className="pointer-events-none fixed z-[100] flex items-center gap-2 rounded-lg border border-border bg-popover px-3 py-2 text-sm font-medium text-popover-foreground shadow-xl"+ style={{ left: drag.x + 14, top: drag.y + 14 }}>+ <AgentMark agent={dragged.agent} label={dragged.display_name} variant="plain" />{dragged.name}+ </div>}+ <span className="sr-only" role="status">{announcement}</span></div>;}diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsxnew file mode 100644index 0000000000..b04fa46fc6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx@@ -0,0 +1,125 @@+import { act, fireEvent, render, screen, within } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { WorkspaceTerminalHeader } from "./WorkspaceTerminalHeader";+import { PANE_BRAND, PANE_CHROME, themeFor } from "./terminalThemes";++const BASE = { name: "Dana", agent: "codex", displayName: "Codex", appearance: "dark" as const, status: "live" as const };++function pressPointer(target: Element, button = 0) {+ fireEvent(target, new MouseEvent("pointerdown", { bubbles: true, button }));+}++describe("compact workspace terminal header", () => {+ it("uses the name and accurate status without a verbose toolbar", () => {+ render(<WorkspaceTerminalHeader {...BASE} onOpenConversation={() => {}} />);+ const header = screen.getByTestId("workspace-terminal-header-Dana");+ expect(header.className).toContain("h-9");+ expect(within(header).getByText("Dana")).toBeTruthy();+ expect(within(header).getByRole("img", { name: "Dana: live" }).style.background).toBeTruthy();+ expect(screen.getByTestId("agent-mark-codex").dataset.logo).toContain("openai.svg");+ expect(within(header).getAllByRole("button")).toHaveLength(5);+ expect(screen.queryByRole("menu")).toBeNull();+ });++ it("starts drag from the entire title but never from header controls", () => {+ const arrange = vi.fn();+ render(<WorkspaceTerminalHeader {...BASE} onArrangeStart={arrange} onOpenConversation={() => {}} />);+ pressPointer(screen.getByText("Dana"));+ expect(arrange).toHaveBeenCalledTimes(1);+ pressPointer(screen.getByTestId("workspace-terminal-header-Dana"));+ expect(arrange).toHaveBeenCalledTimes(2);+ pressPointer(screen.getByRole("button", { name: "More actions for Dana" }));+ pressPointer(screen.getByText("Dana"), 2);+ expect(arrange).toHaveBeenCalledTimes(2);+ const title = screen.getByRole("button", { name: "Move Dana" });+ expect(title.dataset.ideDragHandle).toBe("true");+ expect(title.getAttribute("aria-keyshortcuts")).toContain("Alt+ArrowLeft");+ });++ it("wires maximize, add and close and honors the eight-agent limit", () => {+ const maximize = vi.fn(), add = vi.fn(), close = vi.fn();+ const { rerender } = render(<WorkspaceTerminalHeader {...BASE} onToggleMaximize={maximize} onAdd={add} onClose={close} />);+ fireEvent.click(screen.getByRole("button", { name: "Maximize Dana" }));+ fireEvent.click(screen.getByRole("button", { name: "Add agent beside Dana" }));+ fireEvent.click(screen.getByRole("button", { name: "Close Dana" }));+ expect(maximize).toHaveBeenCalledOnce();+ expect(add).toHaveBeenCalledOnce();+ expect(close).toHaveBeenCalledOnce();+ rerender(<WorkspaceTerminalHeader {...BASE} maximized addDisabled onToggleMaximize={maximize} onAdd={add} onClose={close} />);+ expect(screen.getByRole("button", { name: "Restore Dana" })).toBeTruthy();+ expect((screen.getByRole("button", { name: "Add agent beside Dana" }) as HTMLButtonElement).disabled).toBe(true);+ });++ it("selects on keyboard activation without stealing move focus or repeating pointer selection", () => {+ const activate = vi.fn();+ render(<WorkspaceTerminalHeader {...BASE} onActivate={activate} onArrangeStart={(event) => event.preventDefault()} />);+ const title = screen.getByRole("button", { name: "Move Dana" });+ fireEvent.click(title, { detail: 1 });+ expect(activate).not.toHaveBeenCalled();+ title.focus();+ fireEvent.click(title, { detail: 0 });+ expect(activate).toHaveBeenCalledOnce();+ expect(document.activeElement).toBe(title);+ });++ it("keeps menu focus navigable and restores focus on Escape", () => {+ render(<WorkspaceTerminalHeader {...BASE} onRename={async () => true} onOpenConversation={() => {}} />);+ const more = screen.getByRole("button", { name: "More actions for Dana" });+ fireEvent.click(more);+ expect(document.activeElement).toBe(screen.getByRole("menuitem", { name: "Rename" }));+ fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" });+ expect(document.activeElement).toBe(screen.getByRole("menuitem", { name: "Conversation history" }));+ fireEvent.keyDown(document.activeElement!, { key: "Escape" });+ expect(screen.queryByRole("menu")).toBeNull();+ expect(document.activeElement).toBe(more);+ });++ it("closes the overflow after opening history and exposes restart only when stopped", () => {+ const history = vi.fn(), restart = vi.fn();+ const { rerender } = render(<WorkspaceTerminalHeader {...BASE} onOpenConversation={history} onRestart={restart} />);+ fireEvent.click(screen.getByRole("button", { name: "More actions for Dana" }));+ expect(screen.queryByRole("menuitem", { name: "Restart agent" })).toBeNull();+ fireEvent.click(screen.getByRole("menuitem", { name: "Conversation history" }));+ expect(history).toHaveBeenCalledOnce();+ expect(screen.queryByRole("menu")).toBeNull();+ rerender(<WorkspaceTerminalHeader {...BASE} status="exited" onOpenConversation={history} onRestart={restart} />);+ fireEvent.click(screen.getByRole("button", { name: "More actions for Dana" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Restart agent" }));+ expect(restart).toHaveBeenCalledOnce();+ });++ it("keeps a refused rename editable and permits cancellation", async () => {+ const rename = vi.fn().mockResolvedValue(false);+ render(<WorkspaceTerminalHeader {...BASE} onRename={rename} />);+ fireEvent.click(screen.getByRole("button", { name: "More actions for Dana" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Rename" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Name for Dana" }), { target: { value: "Installer" } });+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Save name" })); });+ expect(rename).toHaveBeenCalledWith("Installer");+ expect((screen.getByRole("textbox", { name: "Name for Dana" }) as HTMLInputElement).value).toBe("Installer");+ fireEvent.keyDown(screen.getByRole("textbox"), { key: "Escape" });+ expect(screen.queryByRole("textbox")).toBeNull();+ });++ it("uses the terminal's light appearance even within a dark app", () => {+ render(<div className="dark"><WorkspaceTerminalHeader {...BASE} appearance="light" onOpenConversation={() => {}} /></div>);+ const header = screen.getByTestId("workspace-terminal-header-Dana");+ expect(header.style.getPropertyValue("--pane-ink")).toBe(PANE_BRAND.light.ink);+ expect(header.style.background).toBe(PANE_CHROME.light.shell);+ const mark = screen.getByTestId("agent-mark-codex");+ expect(mark.className).toContain("[&>.bg-foreground]:!bg-[color:var(--pane-ink)]");+ const dot = screen.getByRole("img", { name: "Dana: live" });+ const expected = document.createElement("span");+ expected.style.background = themeFor("light").green ?? "";+ expect(dot.style.background).toBe(expected.style.background);+ fireEvent.click(screen.getByRole("button", { name: "More actions for Dana" }));+ expect(screen.getByRole("menu").style.background).toBe("rgb(255, 255, 255)");+ });++ it("dismisses the menu when the user starts interacting elsewhere", () => {+ render(<><WorkspaceTerminalHeader {...BASE} onOpenConversation={() => {}} /><button>Outside</button></>);+ fireEvent.click(screen.getByRole("button", { name: "More actions for Dana" }));+ pressPointer(screen.getByRole("button", { name: "Outside" }));+ expect(screen.queryByRole("menu")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsxnew file mode 100644index 0000000000..e04b91938f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx@@ -0,0 +1,172 @@+import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent } from "react";+import { createPortal } from "react-dom";+import { Check, Maximize2, Minimize2, MoreHorizontal, Plus, X } from "lucide-react";+import { AgentMark } from "./AgentMark";+import { PromptHistoryButton } from "./PromptHistoryButton";+import { PANE_BRAND, PANE_CHROME, themeFor, type PaneEdgeState, type TerminalAppearance } from "./terminalThemes";++interface Props {+ name: string;+ workspaceId?: string;+ promptCount?: number;+ agent: string;+ agentLogoUrl?: string;+ displayName: string;+ status: PaneEdgeState;+ appearance: TerminalAppearance;+ arranging?: boolean;+ maximized?: boolean;+ addDisabled?: boolean;+ onArrangeStart?: (event: PointerEvent) => void;+ onActivate?: () => void;+ onToggleMaximize?: () => void;+ onAdd?: () => void;+ onClose?: () => void;+ onRename?: (name: string) => Promise<boolean>;+ onOpenConversation?: () => void;+ onOpenChat?: () => void;+ onRestart?: () => void;+}++const ACTION_CLASS = "flex h-7 w-7 shrink-0 items-center justify-center rounded text-[color:var(--pane-ink-muted)] hover:bg-[color:var(--pane-chip)] hover:text-[color:var(--pane-ink)] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[color:var(--pane-ink)] disabled:opacity-35";++/** Quiet workspace chrome; terminal rendering and connection state stay in AgenticTerminal. */+export function WorkspaceTerminalHeader({+ name, workspaceId, promptCount = 0, agent, agentLogoUrl, displayName, status, appearance, arranging = false,+ maximized = false, addDisabled = false, onArrangeStart, onActivate, onToggleMaximize,+ onAdd, onClose, onRename, onOpenConversation, onOpenChat, onRestart,+}: Props) {+ const brand = PANE_BRAND[appearance];+ const chrome = PANE_CHROME[appearance];+ const theme = themeFor(appearance);+ const menuId = useId();+ const dragHintId = useId();+ const menuRef = useRef<HTMLDivElement>(null);+ const moreRef = useRef<HTMLButtonElement>(null);+ const [menuPosition, setMenuPosition] = useState<{ left: number; top: number } | null>(null);+ const [draft, setDraft] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);+ const [renameError, setRenameError] = useState("");+ const stopped = status === "exited" || status === "error";+ const menuOpen = menuPosition !== null;+ const variables = {+ "--pane-ink": brand.ink,+ "--pane-ink-muted": brand.inkMuted,+ "--pane-chip": brand.chip,+ color: brand.ink,+ } as CSSProperties;++ useEffect(() => {+ if (!menuOpen) return;+ menuRef.current?.querySelector<HTMLButtonElement>("[role=menuitem]")?.focus();+ const outside = (event: globalThis.PointerEvent) => {+ if (event.target instanceof Node && !menuRef.current?.contains(event.target) && !moreRef.current?.contains(event.target)) setMenuPosition(null);+ };+ const dismiss = () => setMenuPosition(null);+ document.addEventListener("pointerdown", outside);+ window.addEventListener("resize", dismiss);+ window.addEventListener("scroll", dismiss, true);+ return () => {+ document.removeEventListener("pointerdown", outside);+ window.removeEventListener("resize", dismiss);+ window.removeEventListener("scroll", dismiss, true);+ };+ }, [menuOpen]);++ const toggleMenu = () => {+ const rect = moreRef.current?.getBoundingClientRect();+ if (!rect) return;+ setMenuPosition((current) => current ? null : {+ left: Math.max(8, Math.min(rect.right - 200, window.innerWidth - 208)),+ top: Math.max(8, Math.min(rect.bottom + 4, window.innerHeight - 184)),+ });+ };+ const choose = (action: () => void) => { setMenuPosition(null); action(); };+ const commitRename = async () => {+ const wanted = draft?.trim();+ if (!wanted || wanted === name) { setDraft(null); return; }+ setSaving(true);+ setRenameError("");+ try { if (await onRename?.(wanted) !== false) setDraft(null); }+ catch (error) { setRenameError(error instanceof Error ? error.message : "The name could not be saved."); }+ finally { setSaving(false); }+ };++ return <>+ <header data-testid={`workspace-terminal-header-${name}`}+ className="relative flex h-9 min-h-9 shrink-0 select-none items-center gap-1 border-b pl-2.5 pr-1"+ style={{ ...variables, borderColor: chrome.border, background: chrome.shell, touchAction: onArrangeStart ? "none" : undefined }}+ onPointerDown={(event) => {+ if (event.button !== 0 || (event.target as HTMLElement).closest("[data-header-control]")) return;+ setMenuPosition(null);+ onArrangeStart?.(event);+ }}>+ {draft === null ? <button type="button" data-ide-drag-handle="true" data-testid={`pane-move-${name}`}+ // Pointer selection is handled by the pane's mousedown. Keyboard+ // activation selects too, while retaining focus for Alt+Arrow moves.+ onClick={(event) => { if (event.detail === 0) onActivate?.(); }}+ aria-label={onArrangeStart ? `Move ${name}` : name}+ aria-describedby={onArrangeStart ? dragHintId : undefined}+ aria-keyshortcuts={onArrangeStart ? "Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown" : undefined}+ className={`flex h-full min-w-0 flex-1 items-center gap-2 rounded text-left text-sm font-medium focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[color:var(--pane-ink)] ${onArrangeStart ? arranging ? "cursor-grabbing" : "cursor-grab" : "cursor-default"}`}>+ <span role="img" aria-label={`${name}: ${status}`} className="h-1.5 w-1.5 shrink-0 rounded-full"+ style={{ background: status === "live" ? theme.green : status === "error" ? theme.red : status === "connecting" ? theme.yellow : brand.inkFaint }} />+ <AgentMark agent={agent} label={displayName} logoUrl={agentLogoUrl} variant="plain" size="sm"+ className="!text-[color:var(--pane-ink)] [&>.bg-foreground]:!bg-[color:var(--pane-ink)]" />+ <span className="truncate">{name}</span>+ </button> : <form data-header-control="true" className="flex min-w-0 flex-1 items-center gap-1"+ onSubmit={(event) => { event.preventDefault(); void commitRename(); }}>+ <input autoFocus aria-label={`Name for ${name}`} value={draft} maxLength={40} disabled={saving}+ aria-invalid={Boolean(renameError)}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); setDraft(null); setRenameError(""); } }}+ className="min-w-0 flex-1 rounded border px-1.5 py-0.5 text-sm outline-none"+ style={{ borderColor: chrome.border, background: chrome.float, color: brand.ink }} />+ <button type="submit" aria-label="Save name" disabled={saving} className={ACTION_CLASS}><Check className="h-3.5 w-3.5" /></button>+ <button type="button" aria-label="Cancel rename" disabled={saving} onClick={() => { setDraft(null); setRenameError(""); }} className={ACTION_CLASS}><X className="h-3.5 w-3.5" /></button>+ </form>}+ <span id={dragHintId} className="sr-only">Drag to reorder, or focus this title and press Alt with an arrow key.</span>+ <div data-header-control="true" className="flex shrink-0 items-center gap-0.5">+ <button ref={moreRef} type="button" aria-label={`More actions for ${name}`} aria-haspopup="menu" aria-expanded={menuOpen}+ aria-controls={menuOpen ? menuId : undefined} onClick={toggleMenu}+ onKeyDown={(event) => { if (event.key === "ArrowDown") { event.preventDefault(); toggleMenu(); } }}+ className={ACTION_CLASS}><MoreHorizontal className="h-4 w-4" /></button>+ <button type="button" aria-label={`${maximized ? "Restore" : "Maximize"} ${name}`} disabled={!onToggleMaximize}+ onClick={onToggleMaximize} className={ACTION_CLASS}>{maximized ? <Minimize2 className="h-3.5 w-3.5" /> : <Maximize2 className="h-3.5 w-3.5" />}</button>+ <button type="button" aria-label={`Add agent beside ${name}`} disabled={addDisabled || !onAdd}+ onClick={onAdd} className={ACTION_CLASS}><Plus className="h-4 w-4" /></button>+ <button type="button" aria-label={`Close ${name}`} disabled={!onClose} onClick={onClose} className={ACTION_CLASS}><X className="h-4 w-4" /></button>+ </div>+ </header>+ {renameError && <p role="alert" className="px-2 py-1 text-xs" style={{ color: theme.red }}>{renameError}</p>}+ {createPortal(<div ref={menuRef} id={menuId} role="menu" hidden={!menuOpen} aria-label={`Actions for ${name}`}+ className="fixed z-[90] w-[200px] rounded-lg border p-1 shadow-lg"+ style={{ ...variables, ...(menuPosition ?? { left: 0, top: 0 }), borderColor: chrome.border, background: chrome.float }}+ onPointerDown={(event) => event.stopPropagation()}+ onBlur={(event) => {+ if (event.relatedTarget instanceof Node && !event.currentTarget.contains(event.relatedTarget) && event.relatedTarget !== moreRef.current) setMenuPosition(null);+ }}+ onKeyDown={(event) => {+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setMenuPosition(null); moreRef.current?.focus(); return; }+ if (event.key === "Tab") { setMenuPosition(null); moreRef.current?.focus(); return; }+ if (!["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) return;+ event.preventDefault();+ const items = Array.from(menuRef.current?.querySelectorAll<HTMLButtonElement>("[role=menuitem]") ?? []);+ const at = items.indexOf(document.activeElement as HTMLButtonElement);+ const index = event.key === "Home" ? 0 : event.key === "End" ? items.length - 1 : (at + (event.key === "ArrowDown" ? 1 : -1) + items.length) % items.length;+ items[index]?.focus();+ }}>+ {[+ onRename && { label: "Rename", run: () => { setDraft(name); setRenameError(""); } },+ onOpenConversation && { label: "Conversation history", run: onOpenConversation },+ onOpenChat && { label: "Open as chat", run: onOpenChat },+ stopped && onRestart && { label: "Restart agent", run: onRestart },+ ].filter((item): item is { label: string; run: () => void } => Boolean(item)).map((item) =>+ <button type="button" role="menuitem" key={item.label} onClick={() => choose(item.run)}+ className="block w-full rounded px-2.5 py-2 text-left text-xs hover:bg-[color:var(--pane-chip)] focus:bg-[color:var(--pane-chip)] focus:outline-none">{item.label}</button>,+ )}+ <PromptHistoryButton terminal={name} workspaceId={workspaceId} count={promptCount} triggerMode="menu-item"+ onOpen={() => setMenuPosition(null)} restoreFocus={() => moreRef.current?.focus()} />+ </div>, document.body)}+ </>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.test.tsxnew file mode 100644index 0000000000..fe03fa9277--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.test.tsx@@ -0,0 +1,49 @@+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.tsxnew file mode 100644index 0000000000..77d3828fb8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceToolbar.tsx@@ -0,0 +1,107 @@+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/store/ideProjects.ts b/jarvis/ui/web/frontend/src/store/ideProjects.tsindex 466f7a0867..e7c69f0557 100644--- a/jarvis/ui/web/frontend/src/store/ideProjects.ts+++ b/jarvis/ui/web/frontend/src/store/ideProjects.ts@@ -9,8 +9,12 @@ type IdeAction =interface IdeProjectsStore {projects: IdeProject[];activeWorkspaceId: string | null;+ pendingWorkspaceId: string | null;+ refreshRequest: { nonce: number } | null;action: IdeAction | null;publish: (projects: IdeProject[], activeWorkspaceId: string | null) => void;+ setPendingWorkspaceId: (workspaceId: string | null) => void;+ requestRefresh: () => void;connectProject: () => void;newWorkspace: (projectId: string) => void;activateWorkspace: (workspaceId: string) => void;@@ -19,8 +23,12 @@ interface IdeProjectsStore {export const useIdeProjectsStore = create<IdeProjectsStore>((set) => ({projects: [],activeWorkspaceId: null,+ pendingWorkspaceId: null,+ refreshRequest: null,action: null,publish: (projects, activeWorkspaceId) => set({ projects, activeWorkspaceId }),+ setPendingWorkspaceId: (pendingWorkspaceId) => set({ pendingWorkspaceId }),+ requestRefresh: () => set((state) => ({ refreshRequest: { nonce: (state.refreshRequest?.nonce ?? 0) + 1 } })),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 } })),diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeActivation.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeActivation.test.tsxindex 7b7c1703d7..d3b685998c 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeActivation.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeActivation.test.tsx@@ -1,20 +1,100 @@import { act, cleanup, render, screen, waitFor } from "@testing-library/react";-import { afterEach, expect, it, vi } from "vitest";+import { afterEach, beforeEach, expect, it, vi } from "vitest";import { useIdeProjectsStore } from "@/store/ideProjects";import { AgenticIdeView } from "./AgenticIdeView";const api = vi.hoisted(() => ({fetchIdeState: vi.fn(), fetchIdeProjects: vi.fn(), fetchIdeAgents: vi.fn(),activateWorkspace: vi.fn(), restoreIdeWorkspace: vi.fn(),+ pushToast: vi.fn(),}));vi.mock("@/lib/agenticIdeApi", () => api);vi.mock("@/lib/chatLibraryApi", () => ({ openProject: vi.fn() }));-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: () => null }));vi.mock("@/components/agentic/VoiceBubble", () => ({ VoiceBubble: () => null, storedVoiceBubbleOpen: () => false, storeVoiceBubbleOpen: vi.fn() }));vi.mock("@/components/agentic/WorkspaceTerminalGrid", () => ({ WorkspaceTerminalGrid: ({ session }: { session: { id: string } }) => <div data-testid="live-grid">{session.id}</div> }));afterEach(cleanup);+beforeEach(() => vi.clearAllMocks());++function deferred() {+ let resolve!: (value: unknown) => void;+ let reject!: (reason: Error) => void;+ const promise = new Promise((done, fail) => { resolve = done; reject = fail; });+ return { promise, resolve, reject };+}++function setupRecovery() {+ const stateFor = (id: string) => ({ active: true, active_id: id, max_terminals: 8, workspaces: [], session: {+ id, project_id: "p1", folder: "/code/app", name: id, created_at: 0, focus_mode: false,+ project: { name: "App" }, terminals: [],+ } });+ let current = stateFor("Previous");+ const project = { id: "p1", path: "/code/app", name: "App", archived: false, scratch: false,+ workspaces: ["Previous", "A", "B", "C"].map((id) => ({ id, name: id, project_id: "p1", folder: "/code/app", status: "open" })) };+ api.fetchIdeState.mockImplementation(() => Promise.resolve(current));+ api.fetchIdeProjects.mockImplementation(() => Promise.resolve({ projects: [project], active_project_id: "p1",+ active_workspace_id: current.active_id, max_terminals: 8 }));+ api.fetchIdeAgents.mockResolvedValue({ terminal_available: true, max_terminals: 8, agents: [] });+ useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, pendingWorkspaceId: null, refreshRequest: null, action: null });+ const activations = { A: deferred(), B: deferred(), C: deferred() };+ api.activateWorkspace.mockImplementation((id: keyof typeof activations) => activations[id].promise);+ const setCurrent = (id: string) => { current = stateFor(id); return current; };+ return { activations, setCurrent };+}++it("reconciles a superseded successful activation immediately when the latest switch fails", async () => {+ const { activations, setCurrent } = setupRecovery();+ render(<AgenticIdeView onScreen={false} />);+ expect((await screen.findByTestId("live-grid")).textContent).toBe("Previous");+ act(() => useIdeProjectsStore.getState().activateWorkspace("A"));+ await waitFor(() => expect(api.activateWorkspace).toHaveBeenCalledWith("A"));+ act(() => useIdeProjectsStore.getState().activateWorkspace("B"));+ act(() => activations.A.resolve(setCurrent("A")));+ await waitFor(() => expect(api.activateWorkspace).toHaveBeenCalledWith("B"));+ const recovery = deferred();+ api.fetchIdeState.mockImplementationOnce(() => recovery.promise);+ const reads = api.fetchIdeState.mock.calls.length;+ act(() => activations.B.reject(new Error("Workspace B is unavailable")));+ await waitFor(() => expect(api.fetchIdeState).toHaveBeenCalledTimes(reads + 1));+ expect(useIdeProjectsStore.getState().pendingWorkspaceId).toBe("B");+ expect(screen.getByTestId("live-grid").textContent).toBe("Previous");+ act(() => recovery.resolve(setCurrent("A")));+ await waitFor(() => expect(screen.getByTestId("live-grid").textContent).toBe("A"));+ expect(useIdeProjectsStore.getState().activeWorkspaceId).toBe("A");+ expect(useIdeProjectsStore.getState().pendingWorkspaceId).toBeNull();+ expect(api.activateWorkspace.mock.calls.map(([id]) => id)).toEqual(["A", "B"]);+ expect(api.pushToast).toHaveBeenCalledWith("error", "Workspace B is unavailable");+});++it("preserves a newer workspace click while failure recovery is reading the backend", async () => {+ const { activations, setCurrent } = setupRecovery();+ render(<AgenticIdeView onScreen={false} />);+ await screen.findByTestId("live-grid");+ act(() => useIdeProjectsStore.getState().activateWorkspace("A"));+ await waitFor(() => expect(api.activateWorkspace).toHaveBeenCalledWith("A"));+ act(() => useIdeProjectsStore.getState().activateWorkspace("B"));+ act(() => activations.A.resolve(setCurrent("A")));+ await waitFor(() => expect(api.activateWorkspace).toHaveBeenCalledWith("B"));+ const recovery = deferred();+ api.fetchIdeState.mockImplementationOnce(() => recovery.promise);+ const reads = api.fetchIdeState.mock.calls.length;+ act(() => activations.B.reject(new Error("Workspace B is unavailable")));+ await waitFor(() => expect(api.fetchIdeState).toHaveBeenCalledTimes(reads + 1));+ act(() => useIdeProjectsStore.getState().activateWorkspace("C"));+ expect(useIdeProjectsStore.getState().pendingWorkspaceId).toBe("C");+ expect(api.activateWorkspace.mock.calls.map(([id]) => id)).toEqual(["A", "B"]);+ act(() => recovery.resolve(setCurrent("A")));+ await waitFor(() => expect(api.activateWorkspace).toHaveBeenCalledWith("C"));+ expect(screen.getByTestId("live-grid").textContent).toBe("Previous");+ expect(useIdeProjectsStore.getState().pendingWorkspaceId).toBe("C");+ act(() => activations.C.resolve(setCurrent("C")));+ await waitFor(() => expect(screen.getByTestId("live-grid").textContent).toBe("C"));+ expect(useIdeProjectsStore.getState().activeWorkspaceId).toBe("C");+ expect(useIdeProjectsStore.getState().pendingWorkspaceId).toBeNull();+ expect(api.activateWorkspace.mock.calls.map(([id]) => id)).toEqual(["A", "B", "C"]);+});it("serializes rapid workspace switches and displays only the latest result", async () => {const card = (id: string) => ({ id, project_id: "p1", folder: "/code/app", name: id, branch: null,@@ -30,7 +110,7 @@ it("serializes rapid workspace switches and displays only the latest result", asapi.fetchIdeProjects.mockImplementation(() => Promise.resolve({ projects: [project],active_project_id: "p1", active_workspace_id: current.active_id, max_terminals: 8 }));api.fetchIdeAgents.mockResolvedValue({ terminal_available: true, max_terminals: 8, agents: [] });- useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, action: null });+ useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, pendingWorkspaceId: null, refreshRequest: null, action: null });let resolveA!: (value: unknown) => void;let resolveB!: (value: unknown) => void;api.activateWorkspace.mockImplementation((id: string) => id === "A"diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsxindex fd62a03820..6f9659c0d1 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx@@ -14,7 +14,7 @@ vi.mock("@/lib/chatLibraryApi", () => ({ openProject }));vi.mock("@/store/events", () => ({ useEventStore: (select: (value: unknown) => unknown) => select({ pushToast: vi.fn() }) }));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 }: { session: { id: string } }) => <div data-testid="live-grid">{session.id}</div> }));+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></> }));const emptyState = { active: false, session: null, max_terminals: 8, workspaces: [], active_id: null };const project = { id: "p1", path: "/code/app", name: "App", color: null, pinned: false, archived: false,@@ -26,7 +26,7 @@ beforeEach(() => {api.fetchIdeState.mockResolvedValue(emptyState);api.fetchIdeProjects.mockResolvedValue({ projects: [], active_project_id: null, active_workspace_id: null, max_terminals: 8 });api.fetchIdeAgents.mockResolvedValue({ terminal_available: true, max_terminals: 8, suggested_names: [], agents: [agent] });- useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, action: null });+ useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, pendingWorkspaceId: null, refreshRequest: null, action: null });});afterEach(cleanup);@@ -104,6 +104,20 @@ describe("Agentic IDE project flow", () => {expect(api.activateWorkspace).not.toHaveBeenCalled();});+ it("shows add-agent choices in a dialog and pins the new session to its workspace", async () => {+ const session = { id: "w1", project_id: "p1", folder: "/code/app", name: "App work", created_at: 0,+ focus_mode: false, project: { name: "App" }, terminals: [] };+ 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);+ render(<AgenticIdeView />);+ fireEvent.click(await screen.findByRole("button", { name: "Pane add" }));+ expect(screen.getByRole("dialog", { name: "Add coding agent" })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Codex" }));+ await waitFor(() => expect(api.addTerminal).toHaveBeenCalledWith({ workspace_id: "w1", agent: "codex", direction: "down" }));+ });+it("exposes compact workspace rename and close actions", async () => {const session = { id: "w1", project_id: "p1", folder: "/code/app", name: "App work", created_at: 0,focus_mode: false, project: { name: "App" }, terminals: [] };@@ -115,7 +129,7 @@ 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 actions" }));+ fireEvent.click(await screen.findByRole("button", { name: "Workspace options" }));fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));fireEvent.change(screen.getByLabelText("Workspace name"), { target: { value: "Installer" } });fireEvent.click(screen.getByRole("button", { name: "Save" }));diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex 877d4fcb81..086e918a68 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -1,9 +1,11 @@import { useCallback, useEffect, useRef, useState } from "react";-import { FolderPlus, Loader2, Mic, Moon, MoreHorizontal, Plus, Sun, X, ZoomIn, ZoomOut } from "lucide-react";+import { FolderPlus, Loader2, X } from "lucide-react";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 { AgentMark } from "@/components/agentic/AgentMark";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";import { useIdeProjectsStore } from "@/store/ideProjects";@@ -16,6 +18,14 @@ import {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 }@@ -24,6 +34,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const pushToast = useEventStore((state) => state.pushToast);const action = useIdeProjectsStore((state) => state.action);const publishProjects = useIdeProjectsStore((state) => state.publish);+ const refreshRequest = useIdeProjectsStore((state) => state.refreshRequest);const setWorkspace = useIdeChatStore((state) => state.setWorkspace);const setWorkspaces = useIdeChatStore((state) => state.setWorkspaces);const [state, setState] = useState<IdeState | null>(null);@@ -36,8 +47,8 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const [workspaceName, setWorkspaceName] = useState("");const [workspaceAgents, setWorkspaceAgents] = useState<string[]>([]);const [selected, setSelected] = useState("");- const [agentMenu, setAgentMenu] = useState(false);- const [workspaceMenu, setWorkspaceMenu] = useState(false);+ const [agentPicker, setAgentPicker] = useState<{ id: string; name: string } | null>(null);+ const [columns, setColumns] = useState(rememberedColumns);const [renameOpen, setRenameOpen] = useState(false);const [renameValue, setRenameValue] = useState("");const [busy, setBusy] = useState(false);@@ -51,10 +62,11 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const refreshEpoch = useRef(0);const activationRunning = useRef(false);const pendingActivation = useRef<string | null>(null);+ const gridMutations = useRef(0);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;+ const dialogOpen = projectDialog || workspaceProject !== null || renameOpen || agentPicker !== null;useEffect(() => {if (!dialogOpen) return;@@ -67,7 +79,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {if (event.key === "Escape") {event.preventDefault();if (workspaceProject && busy) { event.stopPropagation(); return; }- setProjectDialog(false); setWorkspaceProject(null); setRenameOpen(false);+ setProjectDialog(false); setWorkspaceProject(null); setRenameOpen(false); setAgentPicker(null);return;}if (event.key !== "Tab") return;@@ -79,10 +91,10 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {};document.addEventListener("keydown", onKeyDown, true);return () => { document.removeEventListener("keydown", onKeyDown, true); previous?.focus(); };- }, [dialogOpen, projectDialog, workspaceProject, renameOpen, busy]);+ }, [dialogOpen, projectDialog, workspaceProject, renameOpen, agentPicker, busy]);const refresh = useCallback(async (allowDuringActivation = false) => {- if (activationRunning.current && !allowDuringActivation) return;+ if ((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@@ -90,12 +102,26 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {if (nextState.active_id !== listing.active_workspace_id) {[nextState, listing] = await Promise.all([fetchIdeState(), fetchIdeProjects()]);}- if (epoch !== refreshEpoch.current || pendingActivation.current || (activationRunning.current && !allowDuringActivation) || nextState.active_id !== listing.active_workspace_id) return;+ if (epoch !== refreshEpoch.current || pendingActivation.current || ((activationRunning.current || gridMutations.current > 0) && !allowDuringActivation) || nextState.active_id !== listing.active_workspace_id) return;setState(nextState);setProjects(listing.projects);publishProjects(listing.projects, listing.active_workspace_id);}, [publishProjects]);+ useEffect(() => {+ if (refreshRequest) void refresh().catch((error) => pushToast("error", (error as Error).message));+ }, [refreshRequest, refresh, pushToast]);++ const beginGridMutation = useCallback(() => {+ gridMutations.current += 1;+ ++refreshEpoch.current;+ }, []);+ const endGridMutation = useCallback(() => {+ gridMutations.current = Math.max(0, gridMutations.current - 1);+ ++refreshEpoch.current;+ if (gridMutations.current === 0) void refresh().catch((error) => pushToast("error", (error as Error).message));+ }, [refresh, pushToast]);+useEffect(() => {void refresh().catch((error) => pushToast("error", (error as Error).message));void fetchIdeAgents(true).then((response) => setAgents(response.agents)).catch((error) => pushToast("error", (error as Error).message));@@ -126,13 +152,16 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const activateFromTree = useCallback(async (workspaceId: string) => {pendingActivation.current = workspaceId;+ useIdeProjectsStore.getState().setPendingWorkspaceId(workspaceId);if (activationRunning.current) return;activationRunning.current = true;++refreshEpoch.current;setBusy(true);+ let lastAttempt = workspaceId;try {while (pendingActivation.current) {const targetId = pendingActivation.current;+ lastAttempt = targetId;pendingActivation.current = null;const target = useIdeProjectsStore.getState().projects.flatMap((project) => project.workspaces).find((workspace) => workspace.id === targetId);try {@@ -144,11 +173,19 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {await refresh(true);} catch (error) {pushToast("error", (error as Error).message);+ // A superseded activation may already have changed the backend.+ // Reconcile before clearing the pending marker; refresh's guards+ // discard this snapshot if another workspace click arrives meanwhile.+ if (!pendingActivation.current) {+ try { await refresh(true); }+ catch (refreshError) { pushToast("error", (refreshError as Error).message); }+ }}}} finally {activationRunning.current = false;setBusy(false);+ if (useIdeProjectsStore.getState().pendingWorkspaceId === lastAttempt) useIdeProjectsStore.getState().setPendingWorkspaceId(null);}}, [pushToast, refresh]);@@ -184,20 +221,24 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {setWorkspaceProject(null);});- const addAgent = (agentName?: string) => void run(async () => {- if (!session) return;- if (session.terminals.length >= 8) throw new Error("This workspace already has eight sessions.");- const next = await addTerminal({ workspace_id: session.id, agent: agentName ?? installed[0]?.name, direction: "down" });- setState((current) => current ? { ...current, session: next } : current);+ const addAgent = (agentName: string, workspaceId: string) => void run(async () => {+ const next = await addTerminal({ workspace_id: workspaceId, agent: agentName, direction: "down" });+ setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current);});const closeAgent = (terminal: TerminalState) => void run(async () => {if (!session || !window.confirm(`Close ${terminal.name}? Its coding agent will stop.`)) return;- await closeTerminal(terminal.name, session.id);+ await closeTerminal(terminal.history_id ? `pane:${terminal.history_id}` : terminal.name, session.id);});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 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 () => {if (workspaceId !== session?.id) setState(await activateWorkspace(workspaceId));@@ -211,43 +252,22 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const stopWorkspace = () => void run(async () => {if (!session || !window.confirm(`Close ${session.name ?? session.project.name}? Its coding agents will stop.`)) return;setState(await closeWorkspace(session.id));- setWorkspaceMenu(false);});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">- <header className="flex min-h-14 shrink-0 items-center gap-3 border-b border-border/70 px-4">- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2 text-sm font-medium">- <span className="truncate">{activeProject?.name ?? "Projects"}</span>- {session && <><span className="text-muted-foreground">/</span><span className="truncate text-muted-foreground">{session.name ?? session.project.name}</span></>}- </div>- {session && <div className="truncate text-[11px] text-muted-foreground" title={session.folder}>{session.folder}</div>}- </div>- {session && <>- <span className="hidden text-xs tabular-nums text-muted-foreground sm:inline">{session.terminals.length} / 8 agents</span>- <div className="relative"><button type="button" aria-label="Add coding agent" title="Add coding agent" aria-expanded={agentMenu} disabled={busy || session.terminals.length >= 8 || installed.length === 0} onClick={() => setAgentMenu((value) => !value)} className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40"><Plus className="h-4 w-4" /></button>- {agentMenu && <div className="absolute right-0 top-full z-30 mt-1 min-w-40 rounded-lg border border-border bg-popover p-1 shadow-lg">{installed.map((agent) => <button key={agent.name} type="button" onClick={() => { setAgentMenu(false); addAgent(agent.name); }} className="block w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent">{agent.display_name}</button>)}</div>}- </div>- <div className="mx-1 h-4 w-px bg-border" />- <button type="button" aria-label="Decrease terminal text size" onClick={() => saveFont(fontSize - 1)} className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"><ZoomOut className="h-4 w-4" /></button>- <span className="w-5 text-center text-xs tabular-nums text-muted-foreground">{fontSize}</span>- <button type="button" aria-label="Increase terminal text size" onClick={() => saveFont(fontSize + 1)} className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"><ZoomIn className="h-4 w-4" /></button>- <button type="button" aria-label="Toggle terminal appearance" title="Toggle terminal light and dark appearance" onClick={() => saveAppearance((appearance ?? "dark") === "dark" ? "light" : "dark")} className="ml-1 rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground">{appearance === "light" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}</button>- <div className="relative"><button type="button" aria-label="Workspace actions" aria-expanded={workspaceMenu} onClick={() => setWorkspaceMenu((value) => !value)} className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"><MoreHorizontal className="h-4 w-4" /></button>- {workspaceMenu && <div className="absolute right-0 top-full z-30 mt-1 min-w-40 rounded-lg border border-border bg-popover p-1 shadow-lg">- <button type="button" onClick={() => { setWorkspaceMenu(false); setRenameValue(session.name ?? session.project.name); setRenameOpen(true); }} className="block w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent">Rename workspace</button>- <button type="button" onClick={stopWorkspace} className="block w-full rounded px-2 py-1.5 text-left text-xs text-destructive hover:bg-accent">Close workspace</button>- </div>}- </div>- </>}- <button type="button" aria-label="Jarvis Live" title="Jarvis Live" onClick={() => { const next = !voiceOpen; setVoiceOpen(next); storeVoiceBubbleOpen(next); }} className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"><Mic className="h-4 w-4" /></button>- </header>+ <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); }}+ 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={() => setAgentMenu(true)} onClose={closeAgent} onSelect={setSelected} selected={selected} fontSize={fontSize} appearance={appearance} />+ onAdd={openAgentPicker} onClose={closeAgent} onSelect={setSelected} selected={selected} fontSize={fontSize} appearance={appearance} columnPreference={columns}+ 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" /><h1 className="text-lg font-medium">{projects.some((project) => !project.scratch && !project.archived) ? "Choose a workspace" : "Connect a project"}</h1>@@ -258,6 +278,25 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {<VoiceBubble open={voiceOpen} onClose={closeVoice} onScreen={onScreen} onJumpToPane={jumpToPane} promptTarget={selected} />+ {agentPicker && <div className="fixed inset-0 z-[80] flex items-center justify-center bg-background/75 p-4 backdrop-blur-sm"+ role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setAgentPicker(null); }}>+ <section data-ide-dialog tabIndex={-1} role="dialog" aria-modal="true" aria-label="Add coding agent"+ className="w-full max-w-lg rounded-2xl border border-border bg-card p-5 shadow-2xl">+ <div className="mb-4 flex items-center justify-between gap-3">+ <div><h2 className="text-base font-semibold">Add coding agent</h2><p className="mt-1 text-xs text-muted-foreground">{agentPicker.name}</p></div>+ <button type="button" aria-label="Close" onClick={() => setAgentPicker(null)} className="rounded-md p-1.5 hover:bg-muted"><X className="h-4 w-4" /></button>+ </div>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {installed.map((agent) => <button key={agent.name} type="button" disabled={busy}+ onClick={() => { const owner = agentPicker.id; setAgentPicker(null); addAgent(agent.name, owner); }}+ className="flex min-h-12 items-center gap-3 rounded-lg border border-border px-3 py-2 text-left text-sm font-medium hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <AgentMark agent={agent.name} label={agent.display_name} logoUrl={agent.logo_url} variant="plain" />{agent.display_name}+ </button>)}+ </div>+ {installed.length === 0 && <p className="text-sm text-muted-foreground">Connect a coding agent in CLIs to continue.</p>}+ </section>+ </div>}+{projectDialog && <div className="fixed inset-0 z-[80] flex items-center justify-center bg-background/75 p-4 backdrop-blur-sm" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setProjectDialog(false); }}><section data-ide-dialog tabIndex={-1} role="dialog" aria-modal="true" aria-label="Connect project" className="flex max-h-[85vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-border bg-card shadow-2xl"><div className="flex items-center justify-between border-b border-border px-5 py-3"><h2 className="text-sm font-semibold">Connect project folder</h2><button type="button" aria-label="Close" onClick={() => setProjectDialog(false)}><X className="h-4 w-4" /></button></div>