graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: keep split pane focus and layout stable
Rach Pradhane20c6c5b25fb
diff --git a/apps/native/README.md b/apps/native/README.mdindex 1ecbc974..6657dfaa 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -204,8 +204,10 @@ the beginning and end with an explicit omission marker. Older messages load onrequest. These bounds limit rendering; they do not cap stored conversation size.For a focused pass, `bun run test:projects` covers folder selection, conversation-and review recovery, navigation, terminals, and browser previews. `bun run-test:stress` covers long transcripts and tool output without changing macOS+and review recovery, navigation, terminals, and browser previews. `bun run test:splits`+checks native close routing, stable pane order, draft preservation while visiting+Projects, and mouse resizing in both directions. `bun run test:stress`+covers long transcripts and tool output without changing macOSSpaces. The full `test:visual` suite additionally checks native fullscreentransitions; the stress results explicitly report fullscreen as not run.diff --git a/apps/native/components/site/ChatSplitLayout.tsx b/apps/native/components/site/ChatSplitLayout.tsxnew file mode 100644index 00000000..fa11c9c0--- /dev/null+++ b/apps/native/components/site/ChatSplitLayout.tsx@@ -0,0 +1,76 @@+import { Fragment, useEffect, useRef, useState, type Dispatch, type ReactNode, type SetStateAction } from "react";+import { IconFolder } from "@/lib/icons";+import type { Chat } from "./harness-types";+type Weights = Record<number, number>;++function Divider({ left, right, direction, weights, setWeights, index }: {+ left: number; right: number; direction: "row" | "column"; weights: Weights;+ setWeights: Dispatch<SetStateAction<Weights>>; index: number;+}) {+ const vertical = direction === "row";+ const drag = useRef<{ start: number; extent: number; first: number; sum: number } | null>(null);+ const [dragging, setDragging] = useState(false);+ const sum = (weights[left] ?? 1) + (weights[right] ?? 1);+ const ratio = (weights[left] ?? 1) / sum;+ const resize = (fraction: number, total = sum) => setWeights(current => ({ ...current, [left]: fraction * total, [right]: (1 - fraction) * total }));+ useEffect(() => {+ if (!dragging) return;+ const { cursor, userSelect } = document.body.style;+ document.body.style.cursor = vertical ? "col-resize" : "row-resize"; document.body.style.userSelect = "none";+ return () => { document.body.style.cursor = cursor; document.body.style.userSelect = userSelect; };+ }, [dragging, vertical]);+ const move = (position: number) => {+ const value = drag.current;+ if (!value) return;+ const minimum = Math.min(vertical ? 180 : 120, value.extent / 3);+ const first = Math.max(minimum, Math.min(value.extent - minimum, value.first + position - value.start));+ resize(first / value.extent, value.sum);+ };+ return <div role="separator" tabIndex={0} aria-label={`Resize chat panes ${index + 1} and ${index + 2}`}+ aria-orientation={vertical ? "vertical" : "horizontal"} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(ratio * 100)}+ title="Drag to resize · Double-click to balance" data-chat-divider+ className={`group flex shrink-0 touch-none items-center justify-center outline-none ${vertical ? "w-2.5 cursor-col-resize" : "h-2.5 cursor-row-resize"}`}+ onPointerDown={event => {+ if (event.button !== 0) return;+ const a = event.currentTarget.previousElementSibling?.getBoundingClientRect(), b = event.currentTarget.nextElementSibling?.getBoundingClientRect();+ if (!a || !b) return;+ event.preventDefault(); event.currentTarget.focus({ preventScroll: true });+ drag.current = { start: vertical ? event.clientX : event.clientY, first: vertical ? a.width : a.height, extent: vertical ? a.width + b.width : a.height + b.height, sum };+ event.currentTarget.setPointerCapture(event.pointerId); setDragging(true);+ }}+ onPointerMove={event => move(vertical ? event.clientX : event.clientY)}+ onPointerUp={event => { move(vertical ? event.clientX : event.clientY); drag.current = null; setDragging(false); if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); }}+ onLostPointerCapture={() => { drag.current = null; setDragging(false); }}+ onPointerCancel={() => { drag.current = null; setDragging(false); }}+ onDoubleClick={() => resize(0.5)}+ onKeyDown={event => {+ const delta = event.key === (vertical ? "ArrowLeft" : "ArrowUp") ? -0.05 : event.key === (vertical ? "ArrowRight" : "ArrowDown") ? 0.05 : 0;+ if (delta) { event.preventDefault(); event.stopPropagation(); resize(Math.max(0.15, Math.min(0.85, ratio + delta))); }+ }}>+ <span className={`${vertical ? "h-8 w-0.5" : "h-0.5 w-8"} rounded-full ${dragging ? "bg-accent" : "bg-line-strong group-hover:bg-accent group-focus-visible:bg-accent"}`} />+ </div>;+}++export default function ChatSplitLayout({ threads, activeId, direction, weights, setWeights, onFocus, onClose, folder, body, split }: {+ threads: Chat[]; activeId: number; direction: "row" | "column"; weights: Weights;+ setWeights: Dispatch<SetStateAction<Weights>>; onFocus(id: number): void; onClose(id: number): void;+ folder(thread: Chat): { name: string; path?: string }; body(thread: Chat): ReactNode; split: boolean;+}) {+ return <div data-chat-layout className="flex min-h-0 min-w-0 flex-1" style={{ flexDirection: direction }}>+ {threads.map((thread, index) => <Fragment key={thread.id}>+ <section data-chat={thread.id} data-focused={thread.id === activeId} aria-label={`Chat pane ${index + 1}`}+ onPointerDownCapture={() => { if (thread.id !== activeId) onFocus(thread.id); }}+ onFocusCapture={() => { if (thread.id !== activeId) onFocus(thread.id); }}+ style={{ flexGrow: weights[thread.id] ?? 1, minHeight: 0, borderColor: split && thread.id === activeId ? "var(--accent)" : undefined }}+ className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">+ {split && <header className="flex h-9 shrink-0 items-center gap-2 border-b border-line px-3">+ <button type="button" aria-pressed={thread.id === activeId} onClick={() => onFocus(thread.id)} title="Focus this chat" className="min-w-0 flex-1 truncate text-left text-xs font-medium">{thread.title ?? `Chat ${thread.id}`}</button>+ <span title={folder(thread).path} className="flex min-w-0 max-w-[40%] items-center gap-1 text-[11px] text-ink-3"><IconFolder size={13} /><span className="truncate">{folder(thread).name}</span></span>+ <button type="button" aria-label="Close this split" title="Close this chat (⌘W)" onClick={() => onClose(thread.id)} className="flex size-6 shrink-0 items-center justify-center rounded text-ink-3 hover:bg-hover hover:text-ink">×</button>+ </header>}+ {body(thread)}+ </section>+ {index < threads.length - 1 && <Divider left={thread.id} right={threads[index + 1].id} direction={direction} weights={weights} setWeights={setWeights} index={index} />}+ </Fragment>)}+ </div>;+}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 1732db02..48ab62fe 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -6,7 +6,8 @@ import { useSavedConversation, ConversationOpenNotice } from "./useSavedConversaimport { restoreProjects, persistProjects } from "@/lib/project-preferences";import { createTurnPainter } from "@/lib/turn-painter";import { useQuietSettings } from "./useQuietSettings";-import reviewStyles from "./ChangesPane.module.css";+import HarnessChrome from "./HarnessChrome";+import ChatSplitLayout from "./ChatSplitLayout";import TerminalPane from "./TerminalPane";import { sidebarRecents, sessionFooterTitle } from "./harness-sidebar";import AgentsPane from "./AgentsPane";@@ -19,11 +20,9 @@ import SidebarNav from "@/components/primitives/SidebarNav";import ConversationsPane from "@/components/site/ConversationsPane";import FilesPane from "@/components/site/FilesPane";import BrowserPane from "@/components/site/DesktopBrowserPane";-import { IconChat, IconFolder, IconGlobe } from "@/lib/icons";import { annotationsBlock, type BrowserPin } from "@/lib/browser/annotations";import { browserClose, browserHandle, browserNav } from "@/lib/browser-client";import TaskRows from "@/components/primitives/TaskRows";-import { ThemeToggle } from "@/components/site/ThemeToggle";import ChatTranscript from "./ChatTranscript";import { useDesktopShortcuts } from "./useDesktopShortcuts";import EmptyState from "@/components/site/ChatEmpty";@@ -109,7 +108,7 @@ export default function GraffHarness() {// drops on it, which ride ahead of the chat's next prompt.const [browserOpen, setBrowserOpen] = useBrowserVisibility(BROWSER_OPEN_KEY, (chat) => {const target = chats.find(c => chatHandle(pageRef.current, c.id) === chat);- if (target) { setActiveId(target.id); setConversationsOpen(false); setFilesOpen(false); } return !!target;+ if (target) { focusChat(target.id); setFilesOpen(false); } return !!target;});// The conversation library: every saved chat, paged and searchable. It takes// the whole chat area, so opening it leaves the other side panes.@@ -117,6 +116,7 @@ export default function GraffHarness() {const [conversationsOpen, setConversationsOpen] = useState(false);const openConversations = () => {setProjectsOpen(false);+ setAgentsOpen(false);setFilesOpen(false);setBrowserOpen(false);setConversationsOpen(true);@@ -125,7 +125,7 @@ export default function GraffHarness() {const pinsRef = useRef<Record<number, BrowserPin[]>>({});const chatIdRef = useRef(1);const msgIdRef = useRef(0);- // Split view: chats shown beside the active one. Each column keeps its+ // Split view: ordered visible chats, independent of focus. Each keeps its// own scroller and its own place in its transcript.const [panes, setPanes] = useState<number[]>([]);const [splitDirection, setSplitDirection] = useState<"row" | "column">("row");@@ -150,10 +150,8 @@ export default function GraffHarness() {const closedRef = useRef<{ session: string | null; cwd?: string; resumable: boolean }[]>([]);const chatThread = chats.find((c) => c.id === activeId) ?? chats[0];- // The ids on screen, in order: the active chat then its split panes. A- // chat appears once — the swap below can put one in `panes` twice, and a- // closed chat can linger there — so this is the last word on what shows.- const columnIds = [chatThread.id, ...panes]+ // Split positions are independent of keyboard focus.+ const columnIds = (panes.length ? panes : [chatThread.id]).filter((id, i, all) => all.indexOf(id) === i && chats.some((c) => c.id === id)).slice(0, MAX_COLUMNS);const columnKey = columnIds.join(",");@@ -319,6 +317,7 @@ export default function GraffHarness() {};const openPath = useCallback((path: string) => {+ setProjectsOpen(false); setAgentsOpen(false); setBrowserOpen(false);setConversationsOpen(false);setFilesOpen(true);setFileRequest({ path, n: (fileReqRef.current += 1) });@@ -457,7 +456,9 @@ export default function GraffHarness() {sessionNamesRef.current.set(id, session);const cwd = activePathRef.current ?? undefined;const ws = findWorkspace(workspacesRef.current, cwd);- setChats((current) => [...current, { id, title: null, messages: [], model: ws?.model ?? model ?? undefined, session, cwd }]);+ const next = [...chatsRef.current, { id, title: null, messages: [], model: ws?.model ?? model ?? undefined, session, cwd }];+ chatsRef.current = next; setChats(next);+ setPanes(current => current.map(pane => pane === activeId ? id : pane));setActiveId(id);setFilesOpen(false);setConversationsOpen(false);@@ -467,8 +468,7 @@ export default function GraffHarness() {};const selectStored = (id: number, cwd?: string) => {- if (cwd) activateWorkspace(cwd);- setActiveId(id); setFilesOpen(false); setConversationsOpen(false); setProjectsOpen(false); setFollowing(true);+ focusChat(id); setFilesOpen(false); setFollowing(true);};const savedConversation = useSavedConversation({context: `${activePath ?? ""}:${activeId}`,@@ -488,20 +488,13 @@ export default function GraffHarness() {const newChat = () => openChat((chatIdRef.current += 1));- /** Make a chat the active one. If it is already a split pane, the chat it- * replaces takes that pane, so the same two stay on screen. */+ /** Focus a visible chat in place, or replace only the focused split. */const focusChat = (id: number) => {setProjectsOpen(false);+ setConversationsOpen(false);const folder = chatsRef.current.find(chat => chat.id === id)?.cwd;if (folder && folder !== activePathRef.current) activateWorkspace(folder);- const here = activeId;- setPanes((current) => {- if (!current.includes(id)) return current.filter((pane) => pane !== id);- const swapped = current.map((pane) => (pane === id ? here : pane));- // `here` may already have been a pane, and the chat now in front must- // not also be one: either would draw the same chat in two columns.- return swapped.filter((pane, i) => swapped.indexOf(pane) === i && pane !== id);- });+ setPanes(current => current.includes(id) ? current : current.map(pane => pane === activeId ? id : pane));setActiveId(id);};@@ -520,18 +513,12 @@ export default function GraffHarness() {/** Another chat beside the ones on screen, in the workspace the active* chat is in. Up to four columns; past that they are too narrow to read. */const addPane = () => {- if (panesRef.current.length + 1 >= MAX_COLUMNS) return;- const keep = activeId;+ if (columnIds.length >= MAX_COLUMNS) return;const id = (chatIdRef.current += 1);openChat(id);- // openChat makes the new tab active; the split keeps the current chat- // where it is and puts the new one beside it.- setActiveId(keep);- setPanes((current) => [...current, id]);+ setPanes([...columnIds, id]);};- const closePane = (id: number) => setPanes((current) => current.filter((pane) => pane !== id));-/** The toolbar button: split when there is one column, close the split* when there are more. ⌘D always adds one. */const toggleSplit = () => {@@ -555,7 +542,8 @@ export default function GraffHarness() {};const closeChat = (id: number) => {- setPanes((current) => current.filter((pane) => pane !== id));+ const visible = columnIds.filter(pane => pane !== id);+ setPanes(visible.length > 1 ? visible : []);const going = chatsRef.current.find((c) => c.id === id);if (going) {// Keep the last few closed tabs; a tab that got as far as a message@@ -566,14 +554,15 @@ export default function GraffHarness() {];}dropChat(id);- const remaining = chats.filter((c) => c.id !== id);+ const remaining = chatsRef.current.filter((c) => c.id !== id);+ chatsRef.current = remaining;if (remaining.length === 0) {setChats([]);openChat((chatIdRef.current += 1));return;}setChats(remaining);- if (id === activeId) setActiveId(remaining[remaining.length - 1].id);+ if (id === activeId) focusChat(visible[Math.min(columnIds.indexOf(id), visible.length - 1)] ?? remaining[remaining.length - 1].id);};const pickRecent = (id: string) => {@@ -594,7 +583,7 @@ export default function GraffHarness() {const { switchWorkspace, addWorkspace, saveWorkspace, forgetWorkspace, newProjectChat, activateWorkspace } = workspaceActions({workspacesRef, activePathRef, chatsRef, chatIdRef, activeId, root: health?.cwd,- setWorkspaces, setActivePath, setChats, setPanes, setActiveId, setFilesOpen, setDialog,+ setWorkspaces, setActivePath, setChats, setActiveId: focusChat, setFilesOpen, setDialog,refreshStored, requireSession, adoptCatalog, openChat,});@@ -615,13 +604,17 @@ export default function GraffHarness() {// Every visible column follows its own tail: jump to the bottom when it// appears, and stop following as soon as the reader scrolls up in it.+ const initializedScrollers = useRef(new WeakSet<HTMLElement>());useEffect(() => {const off: (() => void)[] = [];for (const id of columnKey.split(",").filter(Boolean).map(Number)) {const el = scrollEls.current.get(id);if (!el) continue;- el.scrollTop = el.scrollHeight;- setTailing((current) => (current[id] === true ? current : { ...current, [id]: true }));+ if (!initializedScrollers.current.has(el)) {+ el.scrollTop = el.scrollHeight;+ initializedScrollers.current.add(el);+ setTailing(current => ({ ...current, [id]: true }));+ }const onScroll = () => {const next = isFollowingTail(el);setTailing((current) => (current[id] === next ? current : { ...current, [id]: next }));@@ -662,7 +655,7 @@ export default function GraffHarness() {const columnBody = (thread: Chat) => {const isFollowing = tailing[thread.id] ?? true;const hasMessages = thread.messages.length > 0;- const compactPane = splitDirection === "column" && columns.length > 1;+ const compactPane = columnIds.length > 1;const threadBusy = busyIds.has(thread.id);const threadModel = thread.model ?? model ?? undefined;const threadQueued = queues[thread.id] ?? [];@@ -685,7 +678,7 @@ export default function GraffHarness() {<buttontype="button"onClick={() => {- setActiveId(thread.id);+ focusChat(thread.id);setFilesOpen(false);setBrowserOpen(true);}}@@ -769,140 +762,6 @@ export default function GraffHarness() {);};- const tabBar = (- <div className={`${reviewStyles.chatbar} flex h-11 shrink-0 items-center border-b border-line px-2`}>- {/* Tabs scroll independently; toolbar labels collapse in narrow panes. */}- <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">- {chats.map((c) => (- <div- key={c.id}- className={`group/tab flex h-7 w-36 shrink-0 items-center gap-0.5 rounded-[7px] pl-2.5 pr-1 text-[12.5px] font-medium transition-colors duration-100 ${- c.id === activeId ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"- }`}- >- {busyIds.has(c.id) && (- <span- className="mr-1 size-1.5 shrink-0 animate-pulse rounded-full"- style={{ background: "var(--accent)" }}- aria-label="Working"- />- )}- <button- type="button"- aria-pressed={c.id === activeId}- onClick={() => {- focusChat(c.id);- setConversationsOpen(false);- }}- title={c.title ?? "New chat"}- className="min-w-0 flex-1 text-left"- >- <span className="block truncate">{c.title ?? "New chat"}</span>- </button>- <button- type="button"- aria-label="Close tab"- title={c.id === activeId ? "Close tab (⌘W) — ⇧⌘T brings it back" : "Close tab"}- onClick={() => closeChat(c.id)}- className="-my-1 flex size-6 shrink-0 items-center justify-center rounded-[5px] text-ink-3 transition-[background-color,color] duration-100 hover:bg-hover-2 hover:text-ink"- >- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>- <path d="M18 6L6 18M6 6l12 12" />- </svg>- </button>- </div>- ))}- <button- type="button"- aria-label="New chat"- title="New chat (⌘T)"- onClick={newChat}- className="ml-0.5 flex size-7 shrink-0 items-center justify-center rounded-[7px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"- >- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>- <path d="M12 5v14M5 12h14" />- </svg>- </button>- </div>- <div className={`${reviewStyles.actions} flex shrink-0 items-center gap-2 pl-2 pr-1`}>- <button- type="button"- aria-pressed={conversationsOpen}- onClick={openConversations}- title="All conversations"- className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${- conversationsOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"- }`}- >- <IconChat size={14} />- <span data-toolbar-label className="hidden sm:inline">Chats</span>- </button>- <button- type="button"- aria-pressed={panes.length > 0}- onClick={toggleSplit}- title={panes.length > 0 ? "Close the splits (⌘\\)" : "Split the view: another chat beside this one (⌘D adds one)"}- className={`flex size-7 items-center justify-center rounded-[7px] transition-colors duration-100 ${- panes.length > 0 ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"- }`}- >- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>- <rect x="3" y="4" width="18" height="16" rx="2" />- <path d="M12 4v16" />- </svg>- </button>- <button- type="button"- aria-pressed={filesOpen}- onClick={() => {- setBrowserOpen(false);- setConversationsOpen(false);- setFilesOpen((open) => !open);- }}- title={`${chatCwd ?? "Workspace"}\nShow this chat's files`}- className={`flex h-7 items-center gap-1.5 rounded-l-[7px] pl-2 pr-1.5 text-[12px] font-medium transition-colors duration-100 ${- filesOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"- }`}- >- <IconFolder size={14} />- <span data-toolbar-label className="max-w-40 truncate font-mono text-[11.5px]">{workspaceName}</span>- </button>- <button- type="button"- aria-label="Open a folder"- onClick={() => setDialog({ mode: "new" })}- title="Open another folder to work in"- className="-ml-2 flex h-7 items-center rounded-r-[7px] pl-0.5 pr-1.5 text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>- <path d="M6 9l6 6 6-6" />- </svg>- </button>- <button type="button" onClick={openChanges} className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover" aria-label="Review workspace changes" title="Review workspace changes"><svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M5 5h14v14H5zM8 9h8M8 12h8M8 15h4" /></svg><span data-toolbar-label>Changes</span></button>- <button- type="button"- aria-pressed={browserOpen}- onClick={() => {- setFilesOpen(false);- setBrowserOpen((open) => !open);- }}- title="Sidecar browser — a Chrome tab this chat and its agent share"- className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${- browserOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"- }`}- >- <IconGlobe size={14} />- <span data-toolbar-label className="text-[11.5px]">Browser</span>- {pinCount > 0 && (- <span className="rounded-full bg-accent px-1.5 text-[10px] font-semibold text-white tabular-nums">{pinCount}</span>- )}- </button>- <button aria-label="Toggle terminal" aria-pressed={terminalVisible} title="Terminal (⌘J)" onClick={toggleTerminal} className="rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="m7 9 3 3-3 3m6 0h4"/></svg></button>- <button aria-label="Show agents" aria-pressed={agentsOpen} onClick={() => { setAgentsOpen(!agentsOpen); setFilesOpen(false); setBrowserOpen(false); setConversationsOpen(false); }} className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="9" cy="7" r="3"/><path d="M3 20v-3a6 6 0 0 1 12 0v3M16 4a3 3 0 0 1 0 6M18 14a5 5 0 0 1 3 4v2"/></svg><span data-toolbar-label>Agents</span></button>- <ThemeToggle />- </div>- </div>- );useDesktopShortcuts({ closeChat, newChat, reopenClosed, toggleSplit, focusChat, chats, activeId, columns: columnIds,split: direction => { setSplitDirection(direction); setZoomedPane(false); addPane(); },@@ -914,9 +773,7 @@ export default function GraffHarness() {catalogRef.current = { adopt: (id: number) => { if (!runningRef.current.has(id)) void adoptCatalog(id).catch(() => undefined); }, activeId };const paneTodos = lastAssistant?.turn.todos ?? [];- // The active chat is the first column; the panes follow it. A chat that- // was closed, or became the active one, leaves the split rather than- // showing twice. Four columns is as narrow as a chat stays readable.+ // Zoom only changes visibility; the split order is retained.const columns = (zoomedPane ? [activeId] : columnIds).map((id) => chats.find((c) => c.id === id)).filter((c): c is Chat => c !== undefined);@@ -934,6 +791,7 @@ export default function GraffHarness() {onSeeAll={openConversations}activeNav={projectsOpen ? "projects" : filesOpen ? (fileRequest?.changes ? "changes" : "workspace") : browserOpen ? "browser" : conversationsOpen ? "conversations" : "home"}onNavigate={(key) => {+ setAgentsOpen(false);setProjectsOpen(key === "projects");if (key === "changes") { openChanges(); return; }if (key === "workspace") setFileRequest(null);@@ -954,8 +812,15 @@ export default function GraffHarness() {/><div className="flex min-w-0 flex-1 flex-col gap-2.5">+ <HarnessChrome chats={chats} activeId={activeId} busyIds={busyIds} focusChat={focusChat} closeChat={closeChat} newChat={newChat}+ conversationsOpen={conversationsOpen} openConversations={openConversations} split={panes.length > 0} toggleSplit={toggleSplit}+ filesOpen={filesOpen} onFiles={() => { setAgentsOpen(false); setFileRequest(null); setProjectsOpen(false); setBrowserOpen(false); setConversationsOpen(false); setFilesOpen(fileRequest?.changes ? true : !filesOpen); }}+ chatCwd={chatCwd} workspaceName={workspaceName} onFolder={() => setDialog({ mode: "new" })} openChanges={openChanges}+ browserOpen={browserOpen} onBrowser={() => { setAgentsOpen(false); setProjectsOpen(false); setConversationsOpen(false); setFilesOpen(false); setBrowserOpen(open => !open); }} pinCount={pinCount}+ terminalVisible={terminalVisible} toggleTerminal={toggleTerminal} agentsOpen={agentsOpen}+ onAgents={() => { setProjectsOpen(false); setAgentsOpen(!agentsOpen); setFilesOpen(false); setBrowserOpen(false); setConversationsOpen(false); }} /><ConversationOpenNotice request={savedConversation.request} onCancel={savedConversation.cancel} onRetry={savedConversation.retry} />- <div className="flex min-h-0 flex-1 gap-2.5" style={{ flexDirection: splitDirection }}>+ <div className="flex min-h-0 flex-1 gap-2.5">{projectsOpen ? (<ProjectsPane workspaces={workspaces} current={activePath} onOpen={() => setDialog({ mode: "new" })}onClose={() => setProjectsOpen(false)}@@ -963,7 +828,6 @@ export default function GraffHarness() {onNewChat={newProjectChat} />) : conversationsOpen ? (<section className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">- {tabBar}<ConversationsPaneroot={chatCwd}activeId={chatThread.session ?? null}@@ -974,56 +838,12 @@ export default function GraffHarness() {}}/></section>- ) : (- <>- {columns.map((thread, slot) => (- <section- key={thread.id}- data-chat={thread.id}- style={{ flexGrow: paneWeights[thread.id] ?? 1, minHeight: 0 }}- className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page"- >- {slot === 0 ? (- tabBar- ) : (- <div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-3">- {busyIds.has(thread.id) && (- <span className="size-1.5 shrink-0 animate-pulse rounded-full" style={{ background: "var(--accent)" }} aria-label="Working" />- )}- <button- type="button"- onClick={() => focusChat(thread.id)}- title="Make this the main chat"- className="min-w-0 flex-1 truncate text-left text-[12.5px] font-medium text-ink"- >- {thread.title ?? "New chat"}- </button>- <span- title={cwdOf(thread) ?? "workspace"}- className="flex h-7 shrink-0 items-center gap-1.5 rounded-[7px] px-1.5 text-[12px] font-medium text-ink-2"- >- <IconFolder size={14} />- <span className="max-w-32 truncate font-mono text-[11.5px]">{workspaceNameOf(thread)}</span>- </span>- <button- type="button"- aria-label="Close this split"- title="Close this split"- onClick={() => closePane(thread.id)}- className="flex size-7 shrink-0 items-center justify-center rounded-[6px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>- <path d="M18 6L6 18M6 6l12 12" />- </svg>- </button>- </div>- )}- {columnBody(thread)}- </section>- ))}-- </>- )}+ ) : null}+ <div className="min-h-0 min-w-0 flex-1" style={{ display: projectsOpen || conversationsOpen ? "none" : "flex" }}>+ <ChatSplitLayout threads={columns} activeId={activeId} direction={splitDirection} weights={paneWeights} setWeights={setPaneWeights}+ onFocus={focusChat} onClose={closeChat} folder={thread => ({name: workspaceNameOf(thread), path: cwdOf(thread)})}+ body={columnBody} split={columnIds.length > 1} />+ </div>{agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && <AgentsPane key={chatCwd} root={chatCwd} onClose={() => setAgentsOpen(false)} />}{filesOpen && !projectsOpen && !conversationsOpen && (fileRequest?.changes ? <ChangesPane root={chatThread.cwd} onClose={() => setFilesOpen(false)} /> : <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />)}diff --git a/apps/native/components/site/HarnessChrome.tsx b/apps/native/components/site/HarnessChrome.tsxnew file mode 100644index 00000000..66c5b1f2--- /dev/null+++ b/apps/native/components/site/HarnessChrome.tsx@@ -0,0 +1,148 @@+import { IconChat, IconFolder, IconGlobe } from "@/lib/icons";+import { useEffect, useRef } from "react";+import { ThemeToggle } from "./ThemeToggle";+import type { Chat } from "./harness-types";+import reviewStyles from "./ChangesPane.module.css";+type Props = {+ chats: Chat[]; activeId: number; busyIds: ReadonlySet<number>;+ focusChat(id: number): void; closeChat(id: number): void; newChat(): void;+ conversationsOpen: boolean; openConversations(): void; split: boolean; toggleSplit(): void;+ filesOpen: boolean; onFiles(): void; chatCwd?: string; workspaceName: string; onFolder(): void;+ openChanges(): void; browserOpen: boolean; onBrowser(): void; pinCount: number;+ terminalVisible: boolean; toggleTerminal(): void; agentsOpen: boolean; onAgents(): void;+};+export default function HarnessChrome({chats, activeId, busyIds, focusChat, closeChat, newChat,+ conversationsOpen, openConversations, split, toggleSplit, filesOpen, onFiles, chatCwd,+ workspaceName, onFolder, openChanges, browserOpen, onBrowser, pinCount, terminalVisible,+ toggleTerminal, agentsOpen, onAgents}: Props) {+ const frame = useRef<HTMLDivElement>(null);+ useEffect(() => { frame.current?.querySelector(`[data-tab-id="${activeId}"]`)?.scrollIntoView({block: "nearest", inline: "nearest"}); }, [activeId]);+ return (+ <div ref={frame} data-workspace-toolbar className={`${reviewStyles.chatbar} flex shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page`}>+ {/* Tabs scroll independently; toolbar labels collapse in narrow panes. */}+ <div className="flex h-10 min-w-0 shrink-0 items-center gap-1 overflow-x-auto px-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ {chats.map((c) => (+ <div+ data-tab-id={c.id}+ key={c.id}+ className={`group/tab flex h-7 w-36 shrink-0 items-center gap-0.5 rounded-[7px] pl-2.5 pr-1 text-[12.5px] font-medium transition-colors duration-100 ${+ c.id === activeId ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"+ }`}+ >+ {busyIds.has(c.id) && (+ <span+ className="mr-1 size-1.5 shrink-0 animate-pulse rounded-full"+ style={{ background: "var(--accent)" }}+ aria-label="Working"+ />+ )}+ <button+ type="button"+ aria-pressed={c.id === activeId}+ onClick={() => {+ focusChat(c.id);+ }}+ title={c.title ?? (chats.length > 1 ? `Chat ${c.id}` : "New chat")}+ className="min-w-0 flex-1 text-left"+ >+ <span className="block truncate">{c.title ?? (chats.length > 1 ? `Chat ${c.id}` : "New chat")}</span>+ </button>+ <button+ type="button"+ aria-label="Close tab"+ title={c.id === activeId ? "Close tab (⌘W) — ⇧⌘T brings it back" : "Close tab"}+ onClick={() => closeChat(c.id)}+ className="-my-1 flex size-6 shrink-0 items-center justify-center rounded-[5px] text-ink-3 transition-[background-color,color] duration-100 hover:bg-hover-2 hover:text-ink"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>+ <path d="M18 6L6 18M6 6l12 12" />+ </svg>+ </button>+ </div>+ ))}+ <button+ type="button"+ aria-label="New chat"+ title="New chat (⌘T)"+ onClick={newChat}+ className="ml-0.5 flex size-7 shrink-0 items-center justify-center rounded-[7px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"+ >+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>+ <path d="M12 5v14M5 12h14" />+ </svg>+ </button>+ </div>+ <div className={`${reviewStyles.actions} flex min-h-10 shrink-0 items-center gap-2 overflow-x-auto border-t border-line px-2 py-1`}>+ <button+ type="button"+ aria-pressed={conversationsOpen}+ onClick={openConversations}+ title="All conversations"+ className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${+ conversationsOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"+ }`}+ >+ <IconChat size={14} />+ <span data-toolbar-label className="hidden sm:inline">Chats</span>+ </button>+ <button+ type="button"+ aria-pressed={split}+ onClick={toggleSplit}+ title={split ? "Close the splits (⌘\\)" : "Split the view: another chat beside this one (⌘D adds one)"}+ className={`flex size-7 items-center justify-center rounded-[7px] transition-colors duration-100 ${+ split ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"+ }`}+ >+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>+ <rect x="3" y="4" width="18" height="16" rx="2" />+ <path d="M12 4v16" />+ </svg>+ </button>+ <button+ type="button"+ aria-pressed={filesOpen}+ onClick={onFiles}+ title={`${chatCwd ?? "Workspace"}\nShow this chat's files`}+ className={`flex h-7 items-center gap-1.5 rounded-l-[7px] pl-2 pr-1.5 text-[12px] font-medium transition-colors duration-100 ${+ filesOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"+ }`}+ >+ <IconFolder size={14} />+ <span data-toolbar-label className="max-w-40 truncate font-mono text-[11.5px]">{workspaceName}</span>+ </button>+ <button+ type="button"+ aria-label="Open a folder"+ onClick={onFolder}+ title="Open another folder to work in"+ className="-ml-2 flex h-7 items-center rounded-r-[7px] pl-0.5 pr-1.5 text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>+ <path d="M6 9l6 6 6-6" />+ </svg>+ </button>+ <button type="button" onClick={openChanges} className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover" aria-label="Review workspace changes" title="Review workspace changes"><svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M5 5h14v14H5zM8 9h8M8 12h8M8 15h4" /></svg><span data-toolbar-label>Changes</span></button>+ <button+ type="button"+ aria-pressed={browserOpen}+ onClick={onBrowser}+ title="Sidecar browser — a Chrome tab this chat and its agent share"+ className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${+ browserOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"+ }`}+ >+ <IconGlobe size={14} />+ <span data-toolbar-label className="text-[11.5px]">Browser</span>+ {pinCount > 0 && (+ <span className="rounded-full bg-accent px-1.5 text-[10px] font-semibold text-white tabular-nums">{pinCount}</span>+ )}+ </button>+ <button aria-label="Toggle terminal" aria-pressed={terminalVisible} title="Terminal (⌘J)" onClick={toggleTerminal} className="rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="m7 9 3 3-3 3m6 0h4"/></svg></button>+ <button aria-label="Show agents" aria-pressed={agentsOpen} onClick={onAgents} className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="9" cy="7" r="3"/><path d="M3 20v-3a6 6 0 0 1 12 0v3M16 4a3 3 0 0 1 0 6M18 14a5 5 0 0 1 3 4v2"/></svg><span data-toolbar-label>Agents</span></button>+ <ThemeToggle />+ </div>+ </div>+ );++}diff --git a/apps/native/components/site/harness-workspace-actions.ts b/apps/native/components/site/harness-workspace-actions.tsindex 22816bae..75c763d6 100644--- a/apps/native/components/site/harness-workspace-actions.ts+++ b/apps/native/components/site/harness-workspace-actions.ts@@ -8,13 +8,13 @@ type Actions = {workspacesRef: Ref<Workspace[]>; activePathRef: Ref<string | null>;chatsRef: Ref<Chat[]>; chatIdRef: Ref<number>; activeId: number; root?: string;setWorkspaces: Setter<Workspace[]>; setActivePath: Setter<string | null>;- setChats: Setter<Chat[]>; setPanes: Setter<number[]>; setActiveId: Setter<number>;+ setChats: Setter<Chat[]>; setActiveId: (id: number) => void;setFilesOpen: Setter<boolean>; setDialog: (value: null) => void;refreshStored: () => Promise<void>; requireSession: (id: number, force: boolean) => Promise<string>;adoptCatalog: (id: number) => Promise<unknown>; openChat: (id: number) => void;};export function workspaceActions({workspacesRef, activePathRef, chatsRef, chatIdRef, activeId, root,- setWorkspaces, setActivePath, setChats, setPanes, setActiveId, setFilesOpen, setDialog,+ setWorkspaces, setActivePath, setChats, setActiveId, setFilesOpen, setDialog,refreshStored, requireSession, adoptCatalog, openChat}: Actions) {const persistWorkspaces = (list: Workspace[]) => {workspacesRef.current = list;@@ -39,7 +39,6 @@ export function workspaceActions({workspacesRef, activePathRef, chatsRef, chatId// React has re-rendered with the new cwd.chatsRef.current = next;setChats(next);- setPanes((current) => current.filter((pane) => pane !== chatId));setActiveId(chatId);void requireSession(chatId, true).then(() => adoptCatalog(chatId))diff --git a/apps/native/components/site/useDesktopShortcuts.ts b/apps/native/components/site/useDesktopShortcuts.tsindex 51f4d6cd..ef62a484 100644--- a/apps/native/components/site/useDesktopShortcuts.ts+++ b/apps/native/components/site/useDesktopShortcuts.ts@@ -14,6 +14,8 @@ export function useDesktopShortcuts(actions: Actions) {const a=ref.current;switch(action){case 'new':a.newChat();return true;+ // Pointer/focus capture and pane navigation share one active pane.+ // The text cursor can still be in the previous pane after a shortcut.case 'close':a.closeChat(a.activeId);return true;case 'reopen':a.reopenClosed();return true;case 'split-right':a.split('row');return true;@@ -32,7 +34,11 @@ export function useDesktopShortcuts(actions: Actions) {if(document.querySelector('[role="dialog"]'))return;const a=ref.current,k=e.key.toLowerCase();let handled=false;const command=e.metaKey||e.ctrlKey;- const cycle=(ids:number[],delta:number)=>{const index=ids.indexOf(a.activeId);const id=ids[(index+delta+ids.length)%ids.length];if(id!==undefined)a.focusChat(id);};+ const focus=(id:number)=>{+ a.focusChat(id);+ requestAnimationFrame(()=>document.querySelector<HTMLTextAreaElement>(`[data-chat="${id}"] textarea`)?.focus({preventScroll:true}));+ };+ const cycle=(ids:number[],delta:number)=>{const index=ids.indexOf(a.activeId);const id=ids[(index+delta+ids.length)%ids.length];if(id!==undefined)focus(id);};if(e.ctrlKey&&!e.metaKey&&k==='tab'){cycle(a.chats.map(c=>c.id),e.shiftKey?-1:1);handled=true;}else if(command){if(e.metaKey&&e.ctrlKey&&k.startsWith('arrow')){a.resizePane(k==='arrowleft'||k==='arrowup'?-0.2:0.2);handled=true;}@@ -48,7 +54,7 @@ export function useDesktopShortcuts(actions: Actions) {else if(k==='o'&&!e.shiftKey)handled=dispatch('workspace');else if(k==='\\'){a.toggleSplit();handled=true;}else if(['[',']','{','}'].includes(k)){cycle(e.shiftKey?a.chats.map(c=>c.id):a.columns,k==='['||k==='{'?-1:1);handled=true;}- else if(!e.shiftKey&&/^[1-9]$/.test(k)){const chat=k==='9'?a.chats.at(-1):a.chats[Number(k)-1];if(chat)a.focusChat(chat.id);handled=true;}+ else if(!e.shiftKey&&/^[1-9]$/.test(k)){const chat=k==='9'?a.chats.at(-1):a.chats[Number(k)-1];if(chat)focus(chat.id);handled=true;}else if(k==='enter'||(e.ctrlKey&&k==='f')){void desktop()?.windowControl?.('fullscreen');handled=true;}else if(['=','+','-','0'].includes(k)){void desktop()?.windowControl?.(k==='0'?'reset-zoom':k==='-'?'zoom-out':'zoom-in');handled=true;}}diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjsindex 3d673911..d7b0f5ad 100644--- a/apps/native/electron/navigation-visual.cjs+++ b/apps/native/electron/navigation-visual.cjs@@ -6,7 +6,6 @@ const sleep=ms=>new Promise(r=>setTimeout(r,ms));async function runNavigationVisuals({win:fixtureWindow,origin,output}) {const win=new BrowserWindow({width:1100,height:760,show:true,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});installWindowState(win);ipcMain.handle('browser',()=>null);- ipcMain.handle('projects',()=>null);// The demo workspace name maps to a disposable real folder for PTY checks.const terminalRoot=path.join(output,'terminal-workspace');fs.mkdirSync(terminalRoot,{recursive:true});const helper=path.join(output,'graff-terminal');@@ -26,9 +25,11 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {const commands=[{name:'compact',description:'Compact conversation context'},...Array.from({length:100},(_,i)=>({name:'command-'+i,description:'Command '+i}))];const galleryFetch=window.fetch;window.fetch=async(input,options)=>{const response=await galleryFetch(input,options);if(options?.body&&JSON.parse(options.body).method==='bootstrap')return new Response(JSON.stringify({sessionId:'demo',commands}),{headers:{'content-type':'application/json'}});if(String(input).includes('/api/models')){const data=await response.json();data.result.commands=commands;data.result.current.model='example-model-with-a-long-name';data.result.models[0].name=data.result.current.model;return new Response(JSON.stringify(data),{headers:{'content-type':'application/json'}});}return response;};`});await wc.loadURL(origin);win.focus();await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ if(process.env.GRAFF_VISUAL_SUITE==='splits'){await require('./split-focus-visual.cjs').runSplitFocus({win,origin,output});return;}await require('./projects-visual.cjs').runProjectVisuals({win,origin,output});await require('./project-recovery-visual.cjs').runProjectRecovery({win,origin,output});await require('./review-recovery-visual.cjs').runReviewRecovery({win,origin,output});+ await require('./split-focus-visual.cjs').runSplitFocus({win,origin,output});await require('./composer-visual.cjs').runComposerVisual({win,output});await require('./split-composer-visual.cjs').runSplitComposerVisual({win,output,key});await input('/compact');await wait(`!!document.querySelector('[role="option"]')`);assert.match(await js(`document.querySelector('[role="option"]').textContent`),/compact/);@@ -56,6 +57,6 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {assert.equal(await js(`!!document.querySelector('[data-workspace-menu]')`),false);if(process.platform==='darwin')await require('./terminal-visual.cjs').runTerminalVisual({win,output});console.log('Navigation visual checks passed: command catalog/new tabs, bounded keyboard menu, new/close/reopen, splits/zoom/resize, workspace search.');- } finally {terminals.closeAll();ipcMain.removeHandler('terminal');ipcMain.removeHandler('browser');ipcMain.removeHandler('projects');win.destroy();fixtureWindow.show();fixtureWindow.focus();}+ } finally {terminals.closeAll();ipcMain.removeHandler('terminal');ipcMain.removeHandler('browser');win.destroy();fixtureWindow.show();fixtureWindow.focus();}}module.exports={runNavigationVisuals};diff --git a/apps/native/electron/split-focus-visual.cjs b/apps/native/electron/split-focus-visual.cjsnew file mode 100644index 00000000..23156543--- /dev/null+++ b/apps/native/electron/split-focus-visual.cjs@@ -0,0 +1,73 @@+const assert=require('node:assert/strict');+const fs=require('node:fs');+const path=require('node:path');+async function runSplitFocus({win,origin,output}) {+ const wc=win.webContents,js=code=>wc.executeJavaScript(code);+ const wait=async code=>{for(let i=0;i<120;i++){if(await js(code))return;await new Promise(r=>setTimeout(r,50));}throw Error(`Split check timed out: ${code}`);};+ const key=async(key,extra={})=>{await js(`document.activeElement.dispatchEvent(new KeyboardEvent('keydown',${JSON.stringify({key,bubbles:true,cancelable:true,...extra})}))`);await new Promise(r=>setTimeout(r,100));};+ const ids=()=>js(`Array.from(document.querySelectorAll('[data-chat]')).map(e=>Number(e.dataset.chat))`);+ const pointer=async selector=>{+ const point=await js(`(()=>{const r=document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);+ wc.sendInputEvent({type:'mouseDown',button:'left',clickCount:1,...point});wc.sendInputEvent({type:'mouseUp',button:'left',clickCount:1,...point});+ await new Promise(r=>setTimeout(r,100));+ };+ await wc.loadURL(origin);win.setSize(1440,900);win.show();win.focus();+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ await key('d',{metaKey:true});await key('d',{metaKey:true});+ await wait(`document.querySelectorAll('[data-chat]').length===3`);+ const original=await ids();+ await js(`document.querySelectorAll('[data-chat] textarea').forEach((e,i)=>{Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,'Draft '+i);e.dispatchEvent(new Event('input',{bubbles:true}));})`);+ await pointer(`[data-chat="${original[1]}"] textarea`);+ fs.writeFileSync(path.join(output,'split-before-close.png'),(await wc.capturePage()).toPNG());+ // Use the same IPC channel as the native menu's Cmd+W accelerator.+ wc.send('desktop-action','close');+ await wait(`document.querySelectorAll('[data-chat]').length===2`);+ assert.deepEqual(await ids(),[original[0],original[2]],'Cmd+W must close the pane whose composer was clicked, preserving the remaining order');+ assert.equal(await js(`document.querySelector('[data-chat="${original[0]}"] textarea').value`),'Draft 0');+ assert.equal(await js(`document.querySelector('[data-chat="${original[2]}"] textarea').value`),'Draft 2');+ assert.equal(await js(`document.querySelectorAll('[data-workspace-toolbar]').length`),1,'One shared toolbar stays above all panes');+ await pointer(`[data-chat="${original[0]}"] textarea`);+ assert.deepEqual(await ids(),[original[0],original[2]],'Pointer focus cannot move panes');+ await key('ArrowRight',{metaKey:true,altKey:true});+ assert.deepEqual(await ids(),[original[0],original[2]],'Keyboard focus cannot move panes');+ assert.equal(await js(`Number(document.querySelector('[data-chat][data-focused="true"]').dataset.chat)`),original[2]);+ assert.equal(await js(`Number(document.activeElement.closest('[data-chat]')?.dataset.chat)`),original[2],'Keyboard navigation moves text focus to the selected pane');+ await js(`document.querySelector('button[aria-label="Projects"]').click()`);+ await wait(`!!document.querySelector('[aria-label="Search projects"]')`);+ await js(`Array.from(document.querySelectorAll('button')).find(b=>b.textContent==='Back to chat').click()`);+ assert.equal(await js(`document.querySelector('[data-chat="${original[0]}"] textarea').value`),'Draft 0','Projects navigation preserves drafts');+ const drag=async(direction,delta)=>{+ const before=await js(`document.querySelector('[data-chat]').getBoundingClientRect().${direction==='row'?'width':'height'}`);+ const start=await js(`(()=>{const r=document.querySelector('[data-chat-divider]').getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);+ const end={...start,[direction==='row'?'x':'y']:start[direction==='row'?'x':'y']+delta};+ wc.sendInputEvent({type:'mouseDown',button:'left',clickCount:1,...start});wc.sendInputEvent({type:'mouseMove',button:'left',...end});wc.sendInputEvent({type:'mouseUp',button:'left',clickCount:1,...end});+ await new Promise(r=>setTimeout(r,100));+ const after=await js(`document.querySelector('[data-chat]').getBoundingClientRect().${direction==='row'?'width':'height'}`);+ assert.ok(after>before+20,`Mouse divider must resize ${direction} panes: ${before} -> ${after}`);+ };+ await drag('row',80);+ fs.writeFileSync(path.join(output,'split-resized.png'),(await wc.capturePage()).toPNG());+ await key('=',{metaKey:true,ctrlKey:true});+ await key('d',{metaKey:true,shiftKey:true});+ await wait(`document.querySelectorAll('[data-chat]').length===3`);+ await drag('column',45);+ const stacked=await ids();+ await pointer(`[data-chat="${stacked[1]}"] textarea`);+ await key('w',{metaKey:true});+ await wait(`document.querySelectorAll('[data-chat]').length===2`);+ assert.deepEqual(await ids(),[stacked[0],stacked[2]],'DOM keyboard shortcut also closes the focused stacked pane');+ await key('d',{metaKey:true});+ await wait(`document.querySelectorAll('[data-chat]').length===3`);+ assert.ok(await js(`(()=>{const bar=document.querySelector('[data-workspace-toolbar]').getBoundingClientRect();return Array.from(document.querySelectorAll('[data-chat]')).every(p=>p.getBoundingClientRect().top>=bar.bottom)})()`),'Toolbar must not be packed into the first pane');+ assert.equal(await js(`document.querySelectorAll('[data-chat] [data-project-context]').length`),0,'Split panes do not repeat the full onboarding card');+ fs.writeFileSync(path.join(output,'split-stable.png'),(await wc.capturePage()).toPNG());+ const finalPanes=await ids();+ await pointer(`[data-chat="${finalPanes[0]}"] textarea`);+ await key('ArrowRight',{metaKey:true,altKey:true});+ wc.send('desktop-action','close');+ await wait(`document.querySelectorAll('[data-chat]').length===2`);+ assert.deepEqual(await ids(),[finalPanes[0],finalPanes[2]],'Native close follows keyboard pane focus even when the text cursor was in another pane');+ await wc.loadURL(origin);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ console.log('Split interaction passed: native/DOM close routing, stable pointer/keyboard focus, preserved drafts, mouse resizing in both directions, shared toolbar.');+}+module.exports={runSplitFocus};diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjsindex 3f28e859..4ea28a00 100644--- a/apps/native/electron/visual-tests.cjs+++ b/apps/native/electron/visual-tests.cjs@@ -12,6 +12,7 @@ let server, win;const deadline = setTimeout(() => { console.error('Visual run exceeded 240 seconds'); finish(1); }, 240000);app.whenReady().then(async () => {ipcMain.handle('updates', () => ({ status: 'unavailable', currentVersion: '1.0.0', automatic: false, interactive: false }));+ ipcMain.handle('projects', () => null);const root = path.resolve(__dirname, '..'), output = process.env.GRAFF_VISUAL_OUTPUT || path.resolve(root, '../../zig-out/visual-tests');fs.mkdirSync(output, { recursive: true });assert.ok(fs.existsSync(path.join(root, '.next/BUILD_ID')), 'Run bun run build before visual tests.');@@ -37,7 +38,7 @@ app.whenReady().then(async () => {fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: ['update UI', 'update transport'], apiRequests }, null, 2));return;}- if (process.env.GRAFF_VISUAL_SUITE === 'projects') {+ if (['projects', 'splits'].includes(process.env.GRAFF_VISUAL_SUITE)) {await require('./navigation-visual.cjs').runNavigationVisuals({ win, origin, output });await require('./browser-visual.cjs').runBrowserVisuals({ win, origin, output });await require('./dev-preview-visual.cjs').runDevPreview({ output });diff --git a/apps/native/package.json b/apps/native/package.jsonindex ad2b5d0f..46312451 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -17,6 +17,7 @@"test:visual": "bun scripts/test-visual.mjs","test:updates": "GRAFF_VISUAL_SUITE=updates bun scripts/test-visual.mjs","test:projects": "GRAFF_VISUAL_SUITE=projects bun scripts/test-visual.mjs",+ "test:splits": "GRAFF_VISUAL_SUITE=splits bun scripts/test-visual.mjs","test:stress": "GRAFF_VISUAL_SUITE=stress bun scripts/test-visual.mjs","test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs"},diff --git a/docs/adr/0081-desktop-split-focus-and-layout.md b/docs/adr/0081-desktop-split-focus-and-layout.mdnew file mode 100644index 00000000..8a52f3fe--- /dev/null+++ b/docs/adr/0081-desktop-split-focus-and-layout.md@@ -0,0 +1,38 @@+# 0081. Desktop split positions are independent of focus++Status: accepted++## Context++Making the active chat the first split column caused focus changes to move panes.+Typing in another pane did not consistently update the close shortcut's target.+The first pane also carried every tab and workspace control, which crowded its+header as more splits opened. Visiting Projects unmounted composers and lost+unsent drafts.++## Decision++Keep the ordered visible chat IDs separate from the active chat ID. Pointer and+keyboard focus update the active ID without reordering visible panes. Selecting+a hidden tab replaces only the focused slot. Closing a chat removes its tab and+pane, then focuses an adjacent visible chat.++Tabs and workspace controls live in a shared toolbar above all panes. Each split+has a compact, consistent header identifying its chat and folder. Adjacent panes+can be resized by dragging their separator or using its arrow keys; double-click+balances the pair. The active pane has an accent border.++Projects and Conversations hide the chat layout while keeping it mounted, so+visiting either surface preserves visible composers and transcript positions.++## Consequences++Pane order no longer encodes focus; new navigation must update the active ID.+Native and renderer close actions use that same ID, since the DOM text cursor+may remain in a previous pane after a keyboard navigation shortcut. Hidden+navigation retains the existing visible pane components until chat selection+changes or the chats close.++The offline desktop suite exercises actual mouse clicks and divider drags,+native menu close delivery, keyboard pane navigation, draft preservation, and+toolbar geometry in both split directions.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 33e9fe8a..11404220 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -91,6 +91,7 @@ record only when you need the evidence or the edge cases.| [0078](0078-workspace-terminals-are-lazy-pty-sessions.md) | Desktop workspace terminals start lazily, preserve hidden shells and bound output through a trusted PTY bridge. || [0079](0079-desktop-updates-are-signed-and-user-restarted.md) | Signed desktop updates download in the background and install only on explicit restart; one process owns each profile. || [0080](0080-desktop-projects-are-folders.md) | Desktop projects are folders; preferences survive local UI origin changes, and new chats inherit the focused project's folder. |+| [0081](0081-desktop-split-focus-and-layout.md) | Split positions remain stable as focus changes; shared controls and draggable separators keep navigation usable. |## When to write one