graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: complete desktop commands and improve navigation
Rach Pradhan46f13c6c3f0f
diff --git a/apps/native/README.md b/apps/native/README.mdindex 63037212..1292b289 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -139,19 +139,64 @@ but the conversation stays on disk and can be moved back by hand.the row goes at once rather than after the next poll of the sessiondirectory.-## Keyboard+## Keyboard and commands-| Keys | What it does |+Type `/` in any composer to search the complete command catalog advertised by+Graff, including `/compact`. New tabs inherit it before starting a coding session.+Command behavior belongs to the engine; terminal display settings retain their+terminal meaning. Menus remain inside the window and scroll independently.++The desktop adapts familiar Ghostty bindings to chats and split panes:++| Keys | Action ||---|---|-| `⌘T` / `Ctrl+T` | New chat |-| `⌘W` / `Ctrl+W` | Close the active chat |-| `⇧⌘T` / `Ctrl+Shift+T` | Reopen the last closed chat, resuming its graff session so the conversation comes back |-| `⌘D` / `Ctrl+D` | Add a split, up to four columns |-| `⌘\` / `Ctrl+\` | Close every split, or open one when there are none |-| `⌘1`…`⌘8` | Jump to that tab; `⌘9` jumps to the last one |--These are the desktop app's keys. A browser keeps `⌘W`, `⌘T` and `⇧⌘T`-for its own tabs, so in a browser use the tab bar's buttons instead.+| `⌘N` / `⌘T` | New chat |+| `⌘W` | Close the active chat |+| `⇧⌘T` | Reopen the last closed chat |+| `Ctrl+Tab` / `Ctrl+Shift+Tab` | Next / previous chat |+| `⇧⌘]` / `⇧⌘[` | Next / previous chat |+| `⌘1`…`⌘8` / `⌘9` | Select a tab / select the last tab |+| `⌘D` / `⇧⌘D` | Split right / down, up to four panes |+| `⌘]` / `⌘[` or `⌥⌘` + arrow | Focus the next / previous split |+| `⇧⌘Enter` | Zoom the active split / restore all splits |+| `Ctrl+⌘` + arrow | Resize the active split |+| `Ctrl+⌘=` | Equalize split sizes |+| `⌘\` | Toggle splits |+| `⌘O` | Open a workspace folder |+| `⌘Enter` / `Ctrl+⌘F` | Toggle fullscreen |+| `⌘+` / `⌘−` / `⌘0` | Increase / decrease / reset interface zoom |++The File menu lists the main actions. Standard copy, paste, undo and text selection+remain native. Terminal-only actions such as sending escape sequences have no+chat equivalent. A web browser reserves some shortcuts for its own tabs.++Click the workspace name to search by name **or folder path**. The current+workspace is first; full paths distinguish folders with the same name. Arrow keys+browse results, Enter selects, and Escape returns to the previous control.++## GUI regression checks++Run these from this package with Bun:++```sh+bun run build+bun run test:desktop+bun run test:visual+```++The visual runner uses isolated synthetic data and makes no engine or model API+calls. It checks turn progress, interruption states, large tool groups and output,+long history, reading position during streaming, fullscreen transitions, command+menus, keyboard splits, workspace search and the Agents panel. Tool groups start+collapsed; expanded groups page their rows, and large output previews preserve+the beginning and end with an explicit omission marker. Older messages load on+request. These bounds limit rendering; they do not cap stored conversation size.++For a separate, opt-in real coding trial, run `electron/gui-coding-smoke.cjs` with+the package's Electron executable. It uses configured credentials in a disposable+workspace, checks the resulting code independently with Bun, then runs `/compact`.+Keep its logs and screenshots local. `bun run test:performance` adds synthetic+workload measurements; startup paint alone does not measure conversation UX.## Browser sidecar (experimental)diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex b52d3eb4..6f2ab04e 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -174,7 +174,7 @@ async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {const live = slots.get(chat);const same =live !== undefined &&- live.sessionId !== null &&+ live.sessionId !== null && live.transport.usable &&(!opts.model || live.model === opts.model) &&(!opts.resume || live.resume === opts.resume) &&(!opts.cwd || live.cwd === opts.cwd) &&diff --git a/apps/native/app/visual-tests/stress/page.tsx b/apps/native/app/visual-tests/stress/page.tsxnew file mode 100644index 00000000..53c6fa65--- /dev/null+++ b/apps/native/app/visual-tests/stress/page.tsx@@ -0,0 +1,7 @@+import { notFound } from 'next/navigation';+import StressFixture from './stress-fixture';+export const dynamic = 'force-dynamic';+export default function StressPage() {+ if (process.env.GRAFF_VISUAL_TESTS !== '1') notFound();+ return <StressFixture />;+}diff --git a/apps/native/app/visual-tests/stress/stress-fixture.tsx b/apps/native/app/visual-tests/stress/stress-fixture.tsxnew file mode 100644index 00000000..4c155bb3--- /dev/null+++ b/apps/native/app/visual-tests/stress/stress-fixture.tsx@@ -0,0 +1,35 @@+'use client';+import { useState, useRef, useEffect } from 'react';+import ChatTranscript from '@/components/site/ChatTranscript';+import { AssistantBody, UserBubble } from '@/components/site/ChatBubbles';+import { emptyTurn, applyAcpUpdate, type AssistantTurn } from '@/lib/acp';+import type { Msg } from '@/components/site/harness-types';+import { applyAppearance, type Appearance } from '@/lib/appearance';+const noop = () => {};+function makeTurn(name: string): AssistantTurn {+ const turn = { ...emptyTurn(), status:'done' as const, text:'The result stays readable after tool activity.' };+ if (name === 'tools') return { ...turn, tools:Array.from({length:5000},(_,i)=>({ id:`tool-${i}`,name:'Read',chip:`file-${i}.txt`,icon:'read',status:i===4999?'error' as const:'ok' as const,atChars:0,detail:[{text:('Output '+i+'\n').repeat(2000)}] })) };+ if (name === 'output') return applyAcpUpdate(turn, {sessionUpdate:'tool_call',toolCallId:'large',title:'Diagnostics',kind:'execute',status:'completed',content:[{type:'content',content:{type:'text',text:'FIRST LINE\n'+('Long diagnostic '.repeat(200)+'\n').repeat(200)+'FINAL ERROR'}}]});+ if (name === 'text') return {...turn, text:('## A useful section\n\n'+ 'Readable long conversation content. '.repeat(30)+'\n\n').repeat(160)};+ return turn;+}+export default function StressFixture() {+ const [name,setName]=useState('tools');+ const [turn,setTurn]=useState(()=>makeTurn('tools'));+ const [stream,setStream]=useState(false);+ const scroll=useRef<HTMLDivElement>(null);+ useEffect(()=>{ if(!stream)return; const timer=setInterval(()=>setTurn(t=>({...t,status:'streaming',text:t.text+' More streamed content.'})),50);return()=>clearInterval(timer);},[stream]);+ const history:Msg[]=Array.from({length:1000},(_,i)=>i%2?{id:i,role:'assistant',turn:{...emptyTurn(),status:'done',text:`Response ${i}`}}:{id:i,role:'user',text:`Message ${i}`});+ return <><main data-graff-main className="flex h-screen flex-col bg-page text-ink">+ <nav className="flex flex-wrap gap-2 p-2">+ {['tools','output','text','history','user'].map(value=><button key={value} data-stress-case={value} onClick={()=>{setStream(false);setName(value);setTurn(makeTurn(value));}}>{value}</button>)}+ {(['light','dark','codegraff'] as Appearance[]).map(theme=><button key={theme} data-stress-theme={theme} onClick={()=>applyAppearance(theme)}>{theme}</button>)}+ <button data-stream onClick={()=>setStream(!stream)}>Stream</button>+ </nav>+ {name==='history'?<ChatTranscript key={name} messages={history} register={noop} following={false} onOpenPath={noop} onReview={noop}/>:+ <div data-stress-scroll ref={scroll} className="min-h-0 flex-1 overflow-auto p-6"><div className="mx-auto max-w-[720px]">+ {name==='user'?<UserBubble text={'verylongunbrokeninput'.repeat(5000)}/>:<AssistantBody key={name} turn={turn} following={false} scroller={scroll}/>}+ </div></div>}+ <textarea aria-label="Stress composer" className="m-3 h-20 shrink-0 rounded-lg bg-surface p-3" placeholder="Still reachable while reading long content"/>+ </main></>;+}diff --git a/apps/native/components/primitives/ComposerMenu.tsx b/apps/native/components/primitives/ComposerMenu.tsxnew file mode 100644index 00000000..847596f2--- /dev/null+++ b/apps/native/components/primitives/ComposerMenu.tsx@@ -0,0 +1,59 @@+"use client";+import { useLayoutEffect, useRef, useState, type RefObject } from "react";+import { createPortal } from "react-dom";+import { Icon, GLYPHS, BRANDS, SOURCES } from "./prompt-demo";+type Row = { key: string; name: string; desc: string };+type Props = {+ anchor: RefObject<HTMLDivElement | null>; menu: "at" | "slash" | "skill"; rows: Row[]; query: string;+ active: number; engaged: boolean; setActive: (index: number) => void; setEngaged: (value: boolean) => void;+ connected: boolean; setConnected: (value: boolean) => void; demo: boolean; onPick: (row: Row) => void;+};+export default function ComposerMenu({ anchor, menu, rows, query, active, engaged, setActive, setEngaged, connected, setConnected, demo, onPick }: Props) {+ const panel = useRef<HTMLDivElement>(null), list = useRef<HTMLDivElement>(null);+ const [position, setPosition] = useState<{ top: number; left: number; width: number; maxHeight: number }>();+ useLayoutEffect(() => {+ const place = () => {+ const rect = anchor.current?.getBoundingClientRect(); if (!rect) return;+ const title = document.querySelector('[data-desktop-titlebar]')?.getBoundingClientRect().bottom ?? 0;+ const safeTop = Math.max(12, title + 8), above = Math.max(0, rect.top - safeTop - 8);+ const below = Math.max(0, innerHeight - rect.bottom - 20), up = above >= Math.min(360, below);+ const height = Math.min(360, up ? above : below, Math.max(1, rows.length) * 36 + 40);+ const width = Math.min(rect.width, innerWidth - 24);+ setPosition({ top: up ? rect.top - height - 8 : rect.bottom + 8,+ left: Math.max(12, Math.min(rect.left, innerWidth - width - 12)), width, maxHeight: height });+ };+ place();+ const scroll = (event: Event) => { if (!panel.current?.contains(event.target as Node)) place(); };+ window.addEventListener('resize', place); document.addEventListener('scroll', scroll, true);+ const observer = new ResizeObserver(place); if (anchor.current) observer.observe(anchor.current);+ return () => { window.removeEventListener('resize', place); document.removeEventListener('scroll', scroll, true); observer.disconnect(); };+ }, [anchor, rows.length]);+ useLayoutEffect(() => {+ const viewport = list.current, row = viewport?.children[active] as HTMLElement | undefined;+ if (!viewport || !row) return;+ if (row.offsetTop < viewport.scrollTop) viewport.scrollTop = row.offsetTop;+ else if (row.offsetTop + row.offsetHeight > viewport.scrollTop + viewport.clientHeight) viewport.scrollTop = row.offsetTop + row.offsetHeight - viewport.clientHeight;+ }, [active, query, position]);+ return createPortal(<div ref={panel} data-composer-menu className="fixed z-[200] flex flex-col overflow-hidden rounded-xl border border-line bg-surface p-1 shadow-raised"+ style={{ ...position, visibility: position ? "visible" : "hidden" }} onMouseLeave={() => setEngaged(false)}>+ <div ref={list} role="listbox" aria-label={menu === "slash" ? "Commands" : menu === "skill" ? "GUI skills" : "Sources and files"} className="relative min-h-0 overflow-y-auto overscroll-contain">+ {rows.map((row, i) => {+ const source = menu === "at" ? SOURCES.find(s => s.key === row.key) : undefined;+ const mark = source ? source.brand ? BRANDS[source.brand] : <Icon size={15}>{GLYPHS[source.glyph ?? "clip"]}</Icon>+ : row.key.startsWith("file:") ? <Icon size={15}>{GLYPHS.file}</Icon> : null;+ return <button key={row.key} type="button" role="option" aria-selected={i === active} title={`${row.name} — ${row.desc}`}+ onMouseDown={event => event.preventDefault()} onMouseEnter={() => { setActive(i); setEngaged(true); }} onClick={() => onPick(row)}+ className={`flex h-9 w-full items-center gap-2.5 rounded-md px-2 text-left ${engaged && i === active ? "bg-hover" : "hover:bg-hover"}`}>+ {mark && <span className="flex size-5 shrink-0 items-center justify-center text-ink-2">{mark}</span>}+ <span className="max-w-[55%] shrink-0 truncate text-[12.5px] font-medium text-ink">{row.name}</span>+ <span className="min-w-0 flex-1 truncate text-xs text-ink-3">{row.desc}</span>+ {source?.connect && <span onClick={event => { event.stopPropagation(); setConnected(!connected); }} className="shrink-0 text-xs text-accent-ink">{connected ? "Connected" : "Connect"}</span>}+ </button>;+ })}+ {!rows.length && <div role="status" className="px-2 py-3 text-xs text-ink-3">No matches for “{query}”</div>}+ </div>+ <div className="mt-1 shrink-0 border-t border-line px-2 py-1.5 text-[11px] text-ink-3">+ {menu === "slash" ? "Search commands · ↑↓ then Enter to select" : menu === "skill" ? "GUI skills · ↑↓ then Enter to select" : demo ? "Search sources & files" : "Search files or GUI skills · use $ for skills only"}+ </div>+ </div>, document.body);+}diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsxindex 9296c5eb..0a04e630 100644--- a/apps/native/components/primitives/PromptBar.tsx+++ b/apps/native/components/primitives/PromptBar.tsx@@ -1,12 +1,13 @@"use client";import { parseComposerToken as parseToken, guiSkillRows } from "@/lib/gui-skills";-import { Icon, GLYPHS, BRANDS, SOURCES, DEMO_COMMANDS, MODELS, FILES, DICTATION, AUTO_STEPS } from "./prompt-demo";+import { Icon, GLYPHS, SOURCES, DEMO_COMMANDS, MODELS, FILES, DICTATION, AUTO_STEPS } from "./prompt-demo";import ModelPicker from "./ModelPicker";import ModelEffortButtons from "./ModelEffortButtons";import type { ModelChoice } from "@/lib/acp-client";import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { createShader, playSweep, accentChain, ACCENTS } from "glimm";+import ComposerMenu from "./ComposerMenu";+import { useComposerSweep } from "./useComposerSweep";import type { AcpCommand } from "@/lib/acp";import {filesFrom,@@ -17,18 +18,6 @@ import {} from "@/lib/attachments";import { entryAt, historyKeyIntent, stepHistory } from "@/lib/prompt-history";-/* The built-in "prism" palette is only cyan→indigo→magenta, so a sweep- * reads as blue/purple. Build a true full-spectrum rainbow instead. */-const RAINBOW = accentChain([- ACCENTS.red,- ACCENTS.orange,- ACCENTS.yellow,- ACCENTS.green,- ACCENTS.cyan,- ACCENTS.blue,- ACCENTS.purple,-]);-/* ─────────────────────────────────────────────────────────* PROMPT BAR* A composer with real controls: attach, @ data sources,@@ -115,17 +104,14 @@ export default function PromptBar({const [autoStep, setAutoStep] = useState(0);const [expanded, setExpanded] = useState(false);const wide = expanded || tall;- const [rowBox, setRowBox] = useState<{ top: number; height: number } | null>(null);const [engaged, setEngaged] = useState(false);const controlsRef = useRef<HTMLDivElement>(null);const inputRef = useRef<HTMLTextAreaElement>(null);const fileInputRef = useRef<HTMLInputElement>(null);const measureRef = useRef<HTMLSpanElement>(null);const modelRef = useRef<HTMLButtonElement>(null);- const rowRefs = useRef<(HTMLButtonElement | null)[]>([]);- const glimmRef = useRef<HTMLCanvasElement>(null);- const shaderRef = useRef<ReturnType<typeof createShader> | null>(null);- const sweepingRef = useRef(false);+ const menuAnchor = useRef<HTMLDivElement>(null);+ const { glimmRef, celebrate } = useComposerSweep();/* hand control to the user: stop the demo loop, and when they aim at* the input itself, clear the demo's leftover draft for a clean start */@@ -197,72 +183,6 @@ export default function PromptBar({setEngaged(false);}, [menu, query]);- /* a single highlight glides to the active row instead of each row- * toggling its own background — matches the gliding pill in the nav */- useLayoutEffect(() => {- const target = rowRefs.current[active];- if (target) setRowBox({ top: target.offsetTop, height: target.offsetHeight });- }, [menu, query, active, connected, rows.length]);-- /* Build the shader with a pinned hue phase. createShader seeds its- * internal hueShift from Math.random(), which made the sweep a different- * colour on every reload — pin it so the rainbow is identical each time. */- const makeShader = () => {- const canvas = glimmRef.current;- if (!canvas) return null;- const random = Math.random;- Math.random = () => 0;- try {- return createShader({- canvas,- palette: RAINBOW,- direction: "ltr",- bandTight: 10,- swellAmount: 0.85,- });- } finally {- Math.random = random;- }- };-- /* Glimm shader lives inside the composer, invisible at rest. Selecting- * the flagship model fires a one-shot rainbow sweep across the interior. */- useEffect(() => {- shaderRef.current = makeShader();- return () => {- shaderRef.current?.destroy();- shaderRef.current = null;- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const celebrate = () => {- if (sweepingRef.current) return;- if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;- // Recreate the shader per sweep so uTime restarts at 0 — the hue phase- // (which drifts with time) is then identical on every trigger.- shaderRef.current?.destroy();- const shader = makeShader();- shaderRef.current = shader;- if (!shader) return;- sweepingRef.current = true;- const sweep = playSweep(shader, {- palette: RAINBOW,- direction: "ltr",- sweepMs: 570,- outroMs: 80,- peakAlpha: 1.3,- bandTight: 10,- brightness: 1.4,- swellAmount: 1,- waveSpeed: 1.8,- easing: "easeOutExpo",- });- sweep.done.finally(() => {- sweepingRef.current = false;- });- };-const selectModel = (next: PromptModel) => {setModel(next);setModelOpen(false);@@ -432,87 +352,12 @@ export default function PromptBar({onKeyDownCapture={takeOver}>{/* composer is the anchor — menus grow up from its top edge */}- <div className="relative">+ <div ref={menuAnchor} className="relative">{/* ── @ / slash menu ─────────────────────────────── */}- {menu && (- <div- onMouseLeave={() => setEngaged(false)}- className="absolute inset-x-0 bottom-full z-10 mb-2 rounded-[10px] bg-surface p-1 shadow-raised"- style={{ animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both", transformOrigin: "bottom center" }}- >- {/* single gliding highlight — appears once a row is hovered */}- <span- aria-hidden- className="pointer-events-none absolute inset-x-1 rounded-[6px] bg-hover"- style={{- top: rowBox?.top ?? 0,- height: rowBox?.height ?? 0,- opacity: rowBox && engaged && rows.length > 0 ? 1 : 0,- transition:- "top 220ms cubic-bezier(0.23,1,0.32,1), height 220ms cubic-bezier(0.23,1,0.32,1), opacity 150ms ease",- }}- />- {rows.map((row, i) => {- const source = menu === "at" ? SOURCES.find((s) => s.key === row.key) : undefined;- const mark = source ? (- source.brand ? BRANDS[source.brand] : <Icon size={15}>{GLYPHS[source.glyph ?? "clip"]}</Icon>- ) : row.key.startsWith("file:") ? (- <Icon size={15}>{GLYPHS.file}</Icon>- ) : null;- return (- <button- key={row.key}- type="button"- ref={(el) => {- rowRefs.current[i] = el;- }}- onMouseDown={(event) => event.preventDefault()}- onMouseEnter={() => {- setActive(i);- setEngaged(true);- }}- onClick={() => pick(row)}- className="relative z-10 flex h-9 w-full items-center gap-2.5 rounded-[6px] px-2 text-left"- >- {mark && (- <span className="flex size-5.5 shrink-0 items-center justify-center text-ink-2">{mark}</span>- )}- <span className="shrink-0 text-[12.5px] font-medium text-ink">- {row.name}- </span>- <span className="min-w-0 flex-1 truncate text-[12px] text-ink-3">{row.desc}</span>- {source?.connect && (- <span- role="button"- tabIndex={-1}- onClick={(event) => {- event.stopPropagation();- setConnected((current) => !current);- }}- className={`shrink-0 text-[12px] font-medium transition-colors duration-100 ${- connected ? "text-green" : "text-accent-ink hover:underline"- }`}- >- {connected ? "Connected" : "Connect"}- </span>- )}- </button>- );- })}- {rows.length === 0 && (- <div className="flex h-9 items-center px-2 text-[12px] text-ink-3">- No matches for “{query}”- </div>- )}- <div className="mt-1 border-t border-line px-2 pt-1.5 pb-1 text-[11px] text-ink-3">- {menu === "skill" ? "GUI skills · ↑↓ then Enter to select" : menu !== "at"- ? "Type to search commands"- : demo- ? "Type to search sources & files"- : "Search files or GUI skills · use $ for skills only"}- </div>- </div>- )}+ {menu && <ComposerMenu anchor={menuAnchor} menu={menu} rows={rows} query={query}+ active={active} engaged={engaged} setActive={setActive} setEngaged={setEngaged}+ connected={connected} setConnected={setConnected} demo={demo} onPick={pick} />}+{modelOpen && <ModelPicker models={catalog} selected={model} anchor={modelRef} onClose={() => setModelOpen(false)}onSelect={next => { selectModel(next); inputRef.current?.focus({ preventScroll: true }); }} />}diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsxindex 78ea6731..69383777 100644--- a/apps/native/components/primitives/SidebarNav.tsx+++ b/apps/native/components/primitives/SidebarNav.tsx@@ -19,7 +19,7 @@ import {} from "@/lib/icons";import CodeGraffMark from "./CodeGraffMark";import GlideMenu from "@/components/primitives/GlideMenu";-import { monogram } from "@/lib/workspaces";+import WorkspaceMenu from "./WorkspaceMenu";/* ─────────────────────────────────────────────────────────* SIDEBAR NAV@@ -161,87 +161,6 @@ function RailButton({);}-/** The switcher: every known workspace (check on the active one), then the- * two actions that lead somewhere — a folder picker and the settings sheet.- * The demo (no workspaces wired) shows the placeholder row alone. */-function WorkspaceMenu({- position,- current,- rows,- onSwitch,- onNew,- onSettings,- onClose,-}: {- position: { top: number; left: number };- current?: string;- rows: SidebarWorkspace[];- onSwitch?: (path: string) => void;- onNew?: () => void;- onSettings?: () => void;- onClose: () => void;-}) {- const list: SidebarWorkspace[] = rows.length > 0 ? rows : [{ path: WORKSPACE.key, name: WORKSPACE.name }];- const active = current ?? list[0]?.path;- const pick = (action?: () => void) => () => {- onClose();- action?.();- };- return createPortal(- <div- data-workspace-menu- className="fixed z-50 w-64 rounded-[14px] bg-surface p-1.5 shadow-overlay"- style={{- top: position.top,- left: position.left,- animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both",- transformOrigin: "top left",- }}- >- <GlideMenu className="flex flex-col gap-px" highlightClassName="inset-x-0 rounded-[8px] bg-hover-2">- {list.map((row) => (- <button- key={row.path}- data-menu-row- type="button"- title={row.path}- aria-current={row.path === active ? "true" : undefined}- onClick={pick(row.path === active ? undefined : () => onSwitch?.(row.path))}- className="relative z-10 flex h-10 w-full items-center gap-1.5 rounded-[8px] px-2 text-left"- >- <span className="flex size-6 shrink-0 items-center justify-center rounded-[7px] bg-ink text-[11px] font-semibold text-surface">- {monogram(row.name)}- </span>- <span className="min-w-0 flex-1 truncate text-[13.5px] font-medium text-ink">{row.name}</span>- {row.path === active && (- <span className="shrink-0 text-ink">- <IconCheckmark1Small size={18} />- </span>- )}- </button>- ))}- <div className="my-1 h-px bg-line" />- {[- { label: "Open a folder…", icon: <IconPlusMedium size={16} />, action: onNew },- { label: "Workspace settings…", icon: <IconSettingsGear1 size={16} />, action: onSettings },- ].map((item) => (- <button- key={item.label}- data-menu-row- type="button"- onClick={pick(item.action)}- className="relative z-10 flex h-9 w-full items-center gap-1.5 rounded-[8px] px-2 text-left"- >- <span className="flex size-5 shrink-0 items-center justify-center text-ink-2">{item.icon}</span>- <span className="min-w-0 flex-1 truncate text-[13.5px] text-ink">{item.label}</span>- </button>- ))}- </GlideMenu>- </div>,- document.body,- );-}-export default function SidebarNav({activeTitle,activeId,diff --git a/apps/native/components/primitives/ToolChips.tsx b/apps/native/components/primitives/ToolChips.tsxindex 3b4c3c76..151d55c7 100644--- a/apps/native/components/primitives/ToolChips.tsx+++ b/apps/native/components/primitives/ToolChips.tsx@@ -2,6 +2,7 @@import { useEffect, useState } from "react";import { createPortal } from "react-dom";+import ToolOutput from "./ToolOutput";/* ─────────────────────────────────────────────────────────* TOOL CHIPS@@ -129,6 +130,9 @@ export default function ToolChips({? Object.fromEntries((liveDiffs ?? []).map((d) => [d.file, d.lines ?? []])): DIFF_LINES;const [step, setStep] = useState(0);+ const [page, setPage] = useState(0);+ const pageSize = 50;+ const pageIndex = Math.min(page, Math.max(0, Math.ceil(rows.length / pageSize) - 1));const [open, setOpen] = useState(!live);/* tick once a second while any live row runs, so its timer counts up */const [, setClock] = useState(0);@@ -208,6 +212,8 @@ export default function ToolChips({const liveN = rows.filter((r) => "status" in r && r.status === "running").length;if (liveN) parts.push(liveN === 1 ? "running" : `${liveN} running`);const interrupted = rows.filter(row => "status" in row && row.status === "interrupted").length;+ const failed = rows.filter(row => "status" in row && row.status === "error").length;+ if (failed) parts.push(`${failed} failed`);if (interrupted) parts.push(`${interrupted} interrupted`);return parts.join(" · ") || `${rows.length} steps`;})()@@ -217,18 +223,24 @@ export default function ToolChips({)}{/* tool call rows */}- <div inert={!open} aria-hidden={!open} className="grid transition-[grid-template-rows,opacity] duration-300" style={{ gridTemplateRows: !showHeader || open ? "1fr" : "0fr", opacity: !showHeader || open ? 1 : 0 }}>+ {open && <div data-tool-group>+ {live && rows.length > pageSize && <div className="my-2 flex items-center gap-3 text-xs text-ink-2" aria-label="Tool pages">+ <button type="button" aria-label="Previous tools" disabled={pageIndex === 0} onClick={() => setPage(pageIndex - 1)} className="rounded px-2 py-1 hover:bg-hover disabled:opacity-40">Previous</button>+ <span>{pageIndex * pageSize + 1}–{Math.min(rows.length, (pageIndex + 1) * pageSize)} of {rows.length}</span>+ <button type="button" aria-label="Next tools" disabled={(pageIndex + 1) * pageSize >= rows.length} onClick={() => setPage(pageIndex + 1)} className="rounded px-2 py-1 hover:bg-hover disabled:opacity-40">Next</button>+ </div>}{/* -mx-1 + px-1.5 keeps content at the same x while giving therow hover pills room inside this overflow-hidden clip box */}- <div className="-mx-1 overflow-hidden px-1.5 pb-1">+ <div className="-mx-1 max-h-[min(55vh,480px)] overflow-auto overscroll-contain px-1.5 pb-1"><div className="mt-1.5 flex flex-col gap-1">- {(live ? rows : rows.slice(0, step)).map((row, i) => {+ {(live ? rows.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize) : rows.slice(0, step)).map((row, i) => {const rowKey = "id" in row && row.id ? row.id : `${row.label}-${i}`;const rowOpen = openRows.has(rowKey);return (<div key={rowKey} style={live ? undefined : { animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}><buttontype="button"+ data-tool-rowaria-expanded={rowOpen}onClick={() => toggleRow(rowKey)}className="group/row -mx-[3px] flex h-7 w-[calc(100%+6px)] min-w-0 items-center gap-2 rounded-control px-[3px] text-left transition-colors duration-100 hover:bg-hover-2"@@ -291,24 +303,8 @@ export default function ToolChips({})()}</button>- {/* expanded detail */}- <div- className="grid transition-[grid-template-rows,opacity] duration-300"- style={{ gridTemplateRows: rowOpen ? "1fr" : "0fr", opacity: rowOpen ? 1 : 0, transitionTimingFunction: "cubic-bezier(0.23, 1, 0.32, 1)" }}- >- <div className="min-h-0 overflow-hidden">- <div className="mt-0.5 mb-1 ml-2 flex flex-col gap-0.5 border-l border-line py-0.5 pl-3.5">- {row.detail.map((line, lineIdx) => (- <span- key={`${lineIdx}:${line.text}`}- className={`truncate text-[11.5px] leading-[1.6] ${row.detailMono ? "font-mono" : ""} ${line.tone === "add" ? "text-green" : "text-ink-2"}`}- >- {line.text}- </span>- ))}- </div>- </div>- </div>+ {rowOpen && <ToolOutput detail={row.detail} mono={row.detailMono} />}+</div>);})}@@ -355,7 +351,7 @@ export default function ToolChips({</div>)}</div>- </div>+ </div>}{preview && typeof document !== "undefined" && createPortal(<divclassName="fixed z-50 w-72 overflow-hidden rounded-[10px] bg-surface shadow-overlay"diff --git a/apps/native/components/primitives/ToolOutput.tsx b/apps/native/components/primitives/ToolOutput.tsxnew file mode 100644index 00000000..449f17be--- /dev/null+++ b/apps/native/components/primitives/ToolOutput.tsx@@ -0,0 +1,18 @@+"use client";+import { useState } from "react";++/** Mount only on disclosure. Long output scrolls inside the call, never the page. */+export default function ToolOutput({ detail, mono }: { detail: { text: string; tone?: "add" }[]; mono?: boolean }) {+ const [copied, setCopied] = useState(false);+ const [error, setError] = useState(false);+ const text = detail.map(line => line.text).join("\n");+ return <div className="my-1 ml-2 min-w-0 border-l border-line pl-3.5">+ <button type="button" className="mb-1 text-xs text-ink-3 hover:text-ink" onClick={() => {+ void navigator.clipboard.writeText(text).then(() => { setCopied(true); setError(false); }).catch(() => setError(true));+ }}>{copied ? "Copied" : "Copy output"}</button>+ {error && <span role="alert" className="ml-2 text-xs text-red">Could not copy. Select the output to copy it.</span>}+ <div data-tool-output tabIndex={0} role="region" aria-label="Tool output" className="max-h-64 overflow-auto overscroll-contain rounded outline-offset-2">+ {detail.length ? detail.map((line, index) => <pre key={index} className={`whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-[11.5px] leading-[1.6] ${mono ? "font-mono" : "font-sans"} ${line.tone === "add" ? "text-green" : "text-ink-2"}`}>{line.text}</pre>) : <p className="text-xs text-ink-3">No output received yet.</p>}+ </div>+ </div>;+}diff --git a/apps/native/components/primitives/WorkspaceMenu.tsx b/apps/native/components/primitives/WorkspaceMenu.tsxnew file mode 100644index 00000000..29f6829f--- /dev/null+++ b/apps/native/components/primitives/WorkspaceMenu.tsx@@ -0,0 +1,38 @@+'use client';+import { useEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { monogram } from '@/lib/workspaces';+type Row={path:string;name:string};+export default function WorkspaceMenu({position,current,rows,onSwitch,onNew,onSettings,onClose}:{+ position:{top:number;left:number};current?:string;rows:Row[];onSwitch?:(path:string)=>void;onNew?:()=>void;onSettings?:()=>void;onClose:()=>void;+}) {+ const [query,setQuery]=useState('');const input=useRef<HTMLInputElement>(null);const menu=useRef<HTMLDivElement>(null);+ const close=useRef(onClose);close.current=onClose;+ useEffect(()=>{const previous=document.activeElement as HTMLElement|null;input.current?.focus();const escape=(e:KeyboardEvent)=>{if(e.key==='Escape'){e.preventDefault();close.current();}};window.addEventListener('keydown',escape);return()=>{window.removeEventListener('keydown',escape);previous?.focus();};},[]);+ const list=rows.filter(row=>`${row.name} ${row.path}`.toLowerCase().includes(query.toLowerCase())).sort((a,b)=>Number(b.path===current)-Number(a.path===current)||a.name.localeCompare(b.name));+ const pick=(action?:()=>void)=>()=>{onClose();action?.();};+ const top=Math.min(position.top,Math.max(12,window.innerHeight-180));+ return createPortal(<div ref={menu} data-workspace-menu role="dialog" aria-label="Switch workspace"+ className="fixed z-50 flex flex-col overflow-hidden rounded-[14px] border border-line bg-surface shadow-overlay"+ style={{top,left:Math.max(12,Math.min(position.left,window.innerWidth-372)),width:'min(360px, calc(100vw - 24px))',maxHeight:`calc(100dvh - ${top+12}px)`}}+ onKeyDown={e=>{+ if(e.key==='ArrowDown'||e.key==='ArrowUp'){+ e.preventDefault();const buttons=[...menu.current!.querySelectorAll<HTMLButtonElement>('button:not(:disabled)')];const index=buttons.indexOf(document.activeElement as HTMLButtonElement);buttons[(index+(e.key==='ArrowDown'?1:-1)+buttons.length)%buttons.length]?.focus();+ } else if(e.key==='Enter'&&e.target===input.current){e.preventDefault();if(list[0])pick(()=>onSwitch?.(list[0].path))();}+ }}>+ <div className="shrink-0 border-b border-line p-2"><input ref={input} aria-label="Search workspaces" placeholder="Search by name or folder…" value={query} onChange={e=>setQuery(e.target.value)} className="h-9 w-full rounded-lg bg-field px-3 text-sm text-ink outline-none focus:ring-1 focus:ring-accent"/></div>+ <div className="min-h-0 max-h-80 overflow-y-auto overscroll-contain p-1.5" aria-label="Workspaces">+ {list.map(row=><button type="button" key={row.path} aria-current={row.path===current?'true':undefined} title={row.path} onClick={pick(()=>onSwitch?.(row.path))}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left hover:bg-hover focus-visible:bg-hover focus-visible:outline-none">+ <span aria-hidden className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-field text-xs text-ink-2">{monogram(row.name)}</span>+ <span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-ink">{row.name}</span><span className="block truncate font-mono text-[10px] text-ink-3">{row.path}</span></span>+ {row.path===current&&<span className="text-xs text-accent">Current</span>}+ </button>)}+ {!list.length&&<p className="p-3 text-sm text-ink-3">{query?'No matching workspaces.':'Open a folder to start a workspace.'}</p>}+ </div>+ <div className="shrink-0 border-t border-line p-1.5">+ <button type="button" onClick={pick(onNew)} className="flex w-full justify-between rounded-lg px-3 py-2 text-sm text-ink hover:bg-hover">Open a folder…<kbd className="text-xs text-ink-3">⌘O</kbd></button>+ <button type="button" onClick={pick(onSettings)} className="w-full rounded-lg px-3 py-2 text-left text-sm text-ink hover:bg-hover">Workspace settings…</button>+ </div>+ </div>,document.body);+}diff --git a/apps/native/components/primitives/useComposerSweep.ts b/apps/native/components/primitives/useComposerSweep.tsnew file mode 100644index 00000000..64c31b13--- /dev/null+++ b/apps/native/components/primitives/useComposerSweep.ts@@ -0,0 +1,22 @@+"use client";+import { useEffect, useRef } from "react";+import { createShader, playSweep, accentChain, ACCENTS } from "glimm";+const RAINBOW = accentChain([ACCENTS.red, ACCENTS.orange, ACCENTS.yellow, ACCENTS.green, ACCENTS.cyan, ACCENTS.blue, ACCENTS.purple]);++/** Allocate a GPU context only while the optional model celebration is visible. */+export function useComposerSweep() {+ const glimmRef = useRef<HTMLCanvasElement>(null);+ const shaderRef = useRef<ReturnType<typeof createShader> | null>(null);+ useEffect(() => () => { shaderRef.current?.destroy(); shaderRef.current = null; }, []);+ const celebrate = () => {+ if (shaderRef.current || !glimmRef.current || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;+ const shader = createShader({ canvas: glimmRef.current, palette: RAINBOW, direction: "ltr", bandTight: 10, swellAmount: 0.85 });+ if (!shader) return;+ shaderRef.current = shader;+ const sweep = playSweep(shader, { palette: RAINBOW, direction: "ltr", sweepMs: 570, outroMs: 80,+ peakAlpha: 1.3, bandTight: 10, brightness: 1.4, swellAmount: 1, waveSpeed: 1.8, easing: "easeOutExpo" });+ const finish = () => { if (shaderRef.current === shader) { shader.destroy(); shaderRef.current = null; } };+ void sweep.done.then(finish, finish);+ };+ return { glimmRef, celebrate };+}diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsxindex 6ccb2c11..521ea306 100644--- a/apps/native/components/site/ChatBubbles.tsx+++ b/apps/native/components/site/ChatBubbles.tsx@@ -56,7 +56,7 @@ export const UserBubble = memo(function UserBubble({ text }: { text: string }) {return (<div className="flex justify-end pl-10 sm:pl-24" style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}><div- className="rounded-xl px-3.5 py-2 text-[13px] leading-relaxed text-ink shadow-hairline"+ className="rounded-xl px-3.5 py-2 min-w-0 whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-[13px] leading-relaxed text-ink shadow-hairline"style={{ background: "color-mix(in oklab, var(--accent) 12%, var(--surface))" }}>{text}diff --git a/apps/native/components/site/ChatEmpty.tsx b/apps/native/components/site/ChatEmpty.tsxindex 92ef4f23..f1075e7b 100644--- a/apps/native/components/site/ChatEmpty.tsx+++ b/apps/native/components/site/ChatEmpty.tsx@@ -39,7 +39,7 @@ export default function EmptyState({onModelChange,history,cwd,- commands,+ commands, compact = false,}: {onSend: (text: string) => void; onSetting?: (text: string) => Promise<void>;health: Health | null;@@ -52,6 +52,7 @@ export default function EmptyState({cwd?: string;/** The slash commands this tab's agent advertised, for the / menu. */commands?: AcpCommand[];+ compact?: boolean;}) {const where = cwd ?? health?.cwd;const [offset, setOffset] = useState(0);@@ -69,20 +70,20 @@ export default function EmptyState({}, []);return (- <div className="mx-auto flex min-h-full max-w-[720px] flex-col justify-center px-4 py-10 sm:px-8">- <h1 className="text-[26px] font-normal tracking-[-0.02em] text-ink">+ <div className={`mx-auto flex min-h-full max-w-[720px] flex-col justify-center px-4 ${compact ? "py-2" : "py-10 sm:px-8"}`}>+ {!compact && <h1 className="text-[26px] font-normal tracking-[-0.02em] text-ink"><span className="home-reveal block text-ink-3" style={homeRevealStyle(stage >= 1)}>{greeting()}</span><span className="home-reveal block" style={homeRevealStyle(stage >= 2)}>What should graff work on?</span>- </h1>+ </h1>}- <div className="home-reveal relative mt-7" style={homeRevealStyle(stage >= 3)}>+ <div className={`relative ${compact ? "" : "home-reveal mt-7"}`} style={compact ? undefined : homeRevealStyle(stage >= 3)}><PromptBardemo={false}- tall+ tall={!compact}placeholder="Ask graff to read, edit, or review this workspace…"models={models}modelKey={modelKey}@@ -102,7 +103,7 @@ export default function EmptyState({)}</div>- <div className="home-reveal mt-6 flex flex-col" style={homeRevealStyle(stage >= 4)}>+ {!compact && <div className="home-reveal mt-6 flex flex-col" style={homeRevealStyle(stage >= 4)}>{shown.map((item) => (<buttonkey={item.id}@@ -129,7 +130,7 @@ export default function EmptyState({Shuffle suggestions</button></div>- </div>+ </div>}</div>);}diff --git a/apps/native/components/site/ChatTranscript.tsx b/apps/native/components/site/ChatTranscript.tsxnew file mode 100644index 00000000..f3eeface--- /dev/null+++ b/apps/native/components/site/ChatTranscript.tsx@@ -0,0 +1,37 @@+"use client";+import { useLayoutEffect, useRef, useState } from "react";+import { AssistantBody, UserBubble } from "./ChatBubbles";+import type { Msg } from "./harness-types";++const PAGE_SIZE = 80;+export default function ChatTranscript({ messages, register, following, onOpenPath, onReview }: {+ messages: Msg[]; register: (element: HTMLDivElement | null) => void; following: boolean;+ onOpenPath: (path: string) => void; onReview: () => void;+}) {+ const scroller = useRef<HTMLDivElement>(null);+ const [shown, setShown] = useState(PAGE_SIZE);+ const anchor = useRef<{ height: number; top: number } | null>(null);+ // Freeze the start after loading older messages so streaming cannot remove them.+ const [start, setStart] = useState(() => Math.max(0, messages.length - PAGE_SIZE));+ useLayoutEffect(() => {+ const el = scroller.current;+ if (el && anchor.current) {+ el.scrollTop = anchor.current.top + el.scrollHeight - anchor.current.height;+ anchor.current = null;+ }+ }, [shown]);+ return <div ref={element => { scroller.current = element; register(element); }} data-chat-transcript+ className="min-h-0 flex-1 overflow-y-auto overscroll-contain" style={{ overflowAnchor: "none" }}>+ <div className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 py-8 sm:px-8">+ {start > 0 && <button type="button" className="self-center rounded-lg bg-field px-3 py-2 text-xs text-ink-2 hover:bg-hover" onClick={() => {+ const el = scroller.current;+ if (el) anchor.current = { height: el.scrollHeight, top: el.scrollTop };+ setStart(Math.max(0, start - PAGE_SIZE)); setShown(shown + PAGE_SIZE);+ }}>Show earlier messages ({start})</button>}+ {messages.slice(start).map((message, index) => message.role === "user"+ ? <UserBubble key={message.id} text={message.text} />+ : <AssistantBody key={message.id} turn={message.turn} onOpenPath={onOpenPath} onReview={onReview}+ scroller={scroller} following={following && start + index === messages.length - 1} />)}+ </div>+ </div>;+}diff --git a/apps/native/components/site/DesktopTitlebar.tsx b/apps/native/components/site/DesktopTitlebar.tsxindex d5b20cbd..de4a0fe4 100644--- a/apps/native/components/site/DesktopTitlebar.tsx+++ b/apps/native/components/site/DesktopTitlebar.tsx@@ -3,5 +3,11 @@ import { useEffect, useState, type CSSProperties } from "react";export default function DesktopTitlebar() {const [enabled, setEnabled] = useState(false);useEffect(() => { if (window.graffDesktop) { setEnabled(true); document.documentElement.dataset.desktop = "true"; } }, []);- return enabled ? <><style>{`html[data-desktop="true"] [data-graff-main] { height: calc(100dvh - 36px); }`}</style><div aria-hidden className="h-9 border-b border-line bg-canvas" style={{ WebkitAppRegion: "drag" } as CSSProperties} /></> : null;+ return enabled ? <><style>{`+ html[data-desktop="true"] { --desktop-title-height: 36px; }+ html[data-desktop-fullscreen="true"] { --desktop-title-height: 0px; }+ html[data-desktop="true"] [data-graff-main] { height: calc(100dvh - var(--desktop-title-height)); }+ [data-desktop-titlebar] { height: var(--desktop-title-height); }+ html[data-desktop-fullscreen="true"] [data-desktop-titlebar] { display: none; }+ `}</style><div data-desktop-titlebar aria-hidden className="shrink-0 border-b border-line bg-canvas" style={{ WebkitAppRegion: "drag" } as CSSProperties} /></> : null;}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 41c4da6b..e67c42a5 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -18,7 +18,8 @@ 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 { AssistantBody, UserBubble } from "@/components/site/ChatBubbles";+import ChatTranscript from "./ChatTranscript";+import { useDesktopShortcuts } from "./useDesktopShortcuts";import EmptyState from "@/components/site/ChatEmpty";import {cancel,@@ -72,6 +73,7 @@ export default function GraffHarness() {const [sessionIds, setSessionIds] = useState<Record<number, string>>({});/** Per tab, the slash commands its agent advertised at session/new. */const [commands, setCommands] = useState<Record<number, AcpCommand[]>>({});+ const [catalogCommands, setCatalogCommands] = useState<AcpCommand[]>([]);const [stored, setStored] = useState<StoredSession[]>([]);const [storedTotal, setStoredTotal] = useState(0);const [busyIds, setBusyIds] = useState<ReadonlySet<number>>(() => new Set());@@ -117,10 +119,12 @@ export default function GraffHarness() {const pinsRef = useRef<Record<number, BrowserPin[]>>({});const chatIdRef = useRef(1);const msgIdRef = useRef(0);- const scrollRef = useRef<HTMLDivElement>(null);// Split view: chats shown beside the active one. Each column keeps its// own scroller and its own place in its transcript.const [panes, setPanes] = useState<number[]>([]);+ const [splitDirection, setSplitDirection] = useState<"row" | "column">("row");+ const [zoomedPane, setZoomedPane] = useState(false);+ const [paneWeights, setPaneWeights] = useState<Record<number, number>>({});const scrollEls = useRef(new Map<number, HTMLDivElement>());const [tailing, setTailing] = useState<Record<number, boolean>>({});const paneRef = (id: number) => (el: HTMLDivElement | null) => {@@ -184,7 +188,7 @@ export default function GraffHarness() {try {const { models: live, current, commands: available } = await fetchModels(sessionsRef.current.has(chatId) ? handleOf(chatId) : undefined, activePathRef.current ?? undefined);if (live.length > 0) setModels(live);- if (available) setCommands(old => ({ ...old, [chatId]: available }));+ if (available?.length) { setCatalogCommands(available); setCommands(old => ({ ...old, [chatId]: available })); }if (current) {setChatModel(chatId, current);setModelKey((fallback) => fallback ?? current);@@ -743,6 +747,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 threadBusy = busyIds.has(thread.id);const threadModel = thread.model ?? model ?? undefined;const threadQueued = queues[thread.id] ?? [];@@ -753,25 +758,8 @@ export default function GraffHarness() {{hasMessages ? (<div className="flex min-h-0 flex-1 flex-col">- <div ref={paneRef(thread.id)} className="min-h-0 flex-1 overflow-y-auto overscroll-contain" style={{ overflowAnchor: "none" }}>- <div className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 py-8 sm:px-8">- {thread.messages.map((message, index) =>- message.role === "user" ? (- <UserBubble key={message.id} text={message.text} />- ) : (- <AssistantBody- key={message.id}- turn={message.turn}- onOpenPath={openPath}- onReview={openChanges}- scroller={scrollRef}- following={isFollowing && index === thread.messages.length - 1}- />- ),- )}- </div>- </div>- <div className="shrink-0 bg-page px-4 pt-3 pb-6 sm:px-8">+ <ChatTranscript key={thread.id} messages={thread.messages} register={paneRef(thread.id)} following={isFollowing} onOpenPath={openPath} onReview={openChanges} />+ <div className={`shrink-0 bg-page px-4 ${compactPane ? "py-2" : "pt-3 pb-6 sm:px-8"}`}><div className="mx-auto max-w-[720px]">{threadPins > 0 && (<div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">@@ -827,10 +815,10 @@ export default function GraffHarness() {)}<PromptBardemo={false}- tall+ tall={!compactPane}placeholder={threadBusy ? "Queue a follow-up…" : "Follow up"}models={models}- commands={commands[thread.id] ?? []}+ commands={commands[thread.id] ?? catalogCommands}root={cwdOf(thread)}modelKey={threadModel}onModelChange={(key: string) => changeModel(key, thread.id)}@@ -847,7 +835,7 @@ export default function GraffHarness() {</div>) : (<div className="min-h-0 flex-1 overflow-y-auto">- <EmptyState+ <EmptyState compact={compactPane}onSend={(text: string) => void send(text, thread.id)} onSetting={text => settings.change(thread.id, text)}health={health}history={threadHistory}@@ -855,7 +843,7 @@ export default function GraffHarness() {models={models}modelKey={threadModel}onModelChange={(key: string) => changeModel(key, thread.id)}- commands={commands[thread.id] ?? []}+ commands={commands[thread.id] ?? catalogCommands}/></div>)}@@ -997,53 +985,12 @@ export default function GraffHarness() {</div>);- // The shortcuts read the current handlers through a ref, so the window- // listener below is installed once instead of on every render.- const keysRef = useRef({ closeChat, newChat, reopenClosed, toggleSplit, addPane, focusChat, chats, activeId });- keysRef.current = { closeChat, newChat, reopenClosed, toggleSplit, addPane, focusChat, chats, activeId };-- useEffect(() => {- const onKey = (event: KeyboardEvent) => {- if (!(event.metaKey || event.ctrlKey) || event.altKey) return;- const keys = keysRef.current;- const key = event.key.toLowerCase();- const take = () => {- event.preventDefault();- event.stopPropagation();- };- if (key === "w" && !event.shiftKey) {- take();- keys.closeChat(keys.activeId);- return;- }- if (key === "t") {- take();- if (event.shiftKey) keys.reopenClosed();- else keys.newChat();- return;- }- if (key === "d" && !event.shiftKey) {- take();- keys.addPane();- return;- }- if (key === "\\" && !event.shiftKey) {- take();- keys.toggleSplit();- return;- }- // ⌘1…⌘9 jump to a tab, ⌘9 to the last one, as in a browser.- if (!event.shiftKey && key >= "1" && key <= "9") {- const nth = Number(key);- const target = nth === 9 ? keys.chats[keys.chats.length - 1] : keys.chats[nth - 1];- if (!target) return;- take();- keys.focusChat(target.id);- }- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, []);+ useDesktopShortcuts({ closeChat, newChat, reopenClosed, toggleSplit, focusChat, chats, activeId, columns: columnIds,+ split: direction => { setSplitDirection(direction); setZoomedPane(false); addPane(); },+ zoomPane: () => setZoomedPane(value => !value),+ resizePane: delta => setPaneWeights(old => ({ ...old, [activeId]: Math.max(0.4, Math.min(3, (old[activeId] ?? 1) + delta)) })),+ equalize: () => setPaneWeights({}), openWorkspace: () => setDialog({ mode: "new" }),+ });catalogRef.current = { adopt: (id: number) => { if (!runningRef.current.has(id)) void adoptCatalog(id).catch(() => undefined); }, activeId };@@ -1051,7 +998,7 @@ export default function GraffHarness() {// 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.- const columns = columnIds.map((id) => chats.find((c) => c.id === id)).filter((c): c is Chat => c !== undefined);+ const columns = (zoomedPane ? [activeId] : columnIds).map((id) => chats.find((c) => c.id === id)).filter((c): c is Chat => c !== undefined);return (@@ -1085,7 +1032,7 @@ export default function GraffHarness() {/><div className="flex min-w-0 flex-1 flex-col gap-2.5">- <div className="flex min-h-0 flex-1 gap-2.5">+ <div className="flex min-h-0 flex-1 gap-2.5" style={{ flexDirection: splitDirection }}>{conversationsOpen ? (<section className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">{tabBar}@@ -1108,6 +1055,7 @@ export default function GraffHarness() {<sectionkey={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 ? (diff --git a/apps/native/components/site/useDesktopShortcuts.ts b/apps/native/components/site/useDesktopShortcuts.tsnew file mode 100644index 00000000..aa9dd9e0--- /dev/null+++ b/apps/native/components/site/useDesktopShortcuts.ts@@ -0,0 +1,58 @@+'use client';+import { useEffect, useRef } from 'react';+import { desktop } from '@/lib/desktop';+type Actions = {+ newChat():void; closeChat(id:number):void; reopenClosed():void; toggleSplit():void;+ split(direction:'row'|'column'):void; focusChat(id:number):void; zoomPane():void;+ resizePane(delta:number):void; equalize():void; openWorkspace():void;+ chats:{id:number}[]; columns:number[]; activeId:number;+};+export function useDesktopShortcuts(actions: Actions) {+ const ref=useRef(actions);ref.current=actions;+ useEffect(()=>{+ const dispatch=(action:string)=>{+ const a=ref.current;+ switch(action){+ case 'new':a.newChat();return true;+ case 'close':a.closeChat(a.activeId);return true;+ case 'reopen':a.reopenClosed();return true;+ case 'split-right':a.split('row');return true;+ case 'split-down':a.split('column');return true;+ case 'split-zoom':a.zoomPane();return true;+ case 'workspace':a.openWorkspace();return true;+ }+ return false;+ };+ const native=(event:Event)=>dispatch((event as CustomEvent<string>).detail);+ const onKey=(e:KeyboardEvent)=>{+ // Dialogs own their typing and navigation. Escape and Tab remain local.+ if(e.isComposing)return;+ 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);};+ 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;}+ else if(e.metaKey&&e.ctrlKey&&['=','+'].includes(k)){a.equalize();handled=true;}+ else if(e.altKey&&k.startsWith('arrow')){cycle(a.columns,k==='arrowleft'||k==='arrowup'?-1:1);handled=true;}+ else if(!e.altKey){+ if(k==='n'&&!e.shiftKey)handled=dispatch('new');+ else if(k==='t')handled=dispatch(e.shiftKey?'reopen':'new');+ else if(k==='w'&&!e.shiftKey)handled=dispatch('close');+ else if(k==='d')handled=dispatch(e.shiftKey?'split-down':'split-right');+ else if(k==='enter'&&e.shiftKey)handled=dispatch('split-zoom');+ 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(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;}+ }+ }+ if(handled){e.preventDefault();e.stopPropagation();}+ };+ window.addEventListener('keydown',onKey);window.addEventListener('graff-desktop-action',native);+ return()=>{window.removeEventListener('keydown',onKey);window.removeEventListener('graff-desktop-action',native);};+ },[]);+}diff --git a/apps/native/electron/gui-coding-smoke.cjs b/apps/native/electron/gui-coding-smoke.cjsnew file mode 100644index 00000000..7e800a1f--- /dev/null+++ b/apps/native/electron/gui-coding-smoke.cjs@@ -0,0 +1,45 @@+// Opt-in: a real GUI coding turn in a disposable workspace. Uses configured credentials.+const {app,BrowserWindow,ipcMain}=require('electron');+const {spawn,spawnSync}=require('node:child_process');+const fs=require('node:fs');const path=require('node:path');const os=require('node:os');const net=require('node:net');const assert=require('node:assert/strict');+const {installWindowState}=require('./window-state.cjs');+const temp=fs.mkdtempSync(path.join(os.tmpdir(),'graff-gui-coding-'));+app.setPath('userData',path.join(temp,'profile'));+const root=path.join(temp,'workspace');fs.mkdirSync(root);+fs.writeFileSync(path.join(temp,'mcp.json'),'{"mcpServers":{}}');+fs.writeFileSync(path.join(root,'median.ts'),'export function median(values: number[]) { const sorted = values.sort(); return sorted[Math.floor(sorted.length / 2)]; }\n');+fs.writeFileSync(path.join(root,'median.test.ts'),`import {test,expect} from 'bun:test';import {median} from './median';+test('numeric ordering',()=>expect(median([10,2,3])).toBe(3));+test('even arrays',()=>expect(median([4,1,2,3])).toBe(2.5));+test('does not mutate',()=>{const input=[3,1,2];median(input);expect(input).toEqual([3,1,2]);});+test('empty arrays',()=>expect(()=>median([])).toThrow());\n`);+spawnSync('git',['init','-q'],{cwd:root});+let server,win;const sleep=ms=>new Promise(r=>setTimeout(r,ms));+const deadline=setTimeout(()=>finish(1,new Error('Coding GUI audit timed out')),420000);+async function finish(code,error){clearTimeout(deadline);if(error)console.error(error.message);if(win&&!win.isDestroyed())win.destroy();if(server?.pid)try{process.kill(-server.pid,'SIGTERM');}catch{}console.log(`Audit artifacts: ${temp}`);app.exit(code);}+app.whenReady().then(async()=>{+ const ui=path.resolve(__dirname,'..');const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const port=probe.address().port;await new Promise(r=>probe.close(r));const origin=`http://127.0.0.1:${port}`;+ const log=fs.openSync(path.join(temp,'server.log'),'w');+ server=spawn(process.env.GRAFF_TEST_BUN||'bun',['node_modules/next/dist/bin/next','start','--port',String(port),'--hostname','127.0.0.1'],{cwd:ui,detached:true,stdio:['ignore',log,log],env:{...process.env,GRAFF_CWD:root,GRAFF_BIN:path.resolve(ui,'../../zig-out/bin/graff'),GRAFF_DESKTOP_TOKEN:'',GRAFF_MCP_CONFIG:path.join(temp,'mcp.json'),GRAFF_THEMES_DIR:path.join(temp,'themes'),NEXT_TELEMETRY_DISABLED:'1'}});fs.closeSync(log);+ for(let n=0;n<100;n++){try{if((await fetch(origin)).ok)break;}catch{}await sleep(100);}+ win=new BrowserWindow({width:1440,height:920,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);+ const js=c=>win.webContents.executeJavaScript(c);const wait=async(c,ms=30000)=>{const end=Date.now()+ms;while(Date.now()<end){if(await js(c))return;await sleep(100);}throw Error(`GUI condition timed out: ${c}`);};+ await win.loadURL(origin);win.focus();await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ const input=async text=>js(`(()=>{const e=document.querySelector('textarea[aria-label="Prompt"]');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,${JSON.stringify(text)});e.dispatchEvent(new Event('input',{bubbles:true}));})()`);+ const send=async text=>{await input(text);await wait(`!document.querySelector('[aria-label="Send"]').disabled`);await js(`document.querySelector('[aria-label="Send"]').click()`);await wait(`!!document.querySelector('article[aria-busy="true"]')`);await wait(`!document.querySelector('article[aria-busy="true"]')`,240000);};+ await send('Fix median.ts so every existing test passes. Preserve the tests. Use Bun to run them and report the result. Work only in this disposable workspace; do not use MCP or spawn subagents.');+ const checked=spawnSync(process.env.GRAFF_TEST_BUN||'bun',['test'],{cwd:root,encoding:'utf8'});fs.writeFileSync(path.join(temp,'verification.log'),checked.stdout+checked.stderr);+ fs.writeFileSync(path.join(temp,'coding.png'),(await win.webContents.capturePage()).toPNG());+ assert.equal(checked.status,0,'The GUI coding turn must produce a passing implementation');+ assert.equal(await js(`document.querySelectorAll('article [role="alert"]').length`),0);+ console.log('Real GUI coding turn passed all four independent tests.');+ await input('/compact');await wait(`!!document.querySelector('[role="listbox"]') || !!document.querySelector('[role="menu"]')`);+ assert.equal(await js(`document.body.textContent.includes('No matches for "compact"')`),false);+ await js(`document.querySelector('textarea[aria-label="Prompt"]').dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}))`);+ await send('/compact');+ fs.writeFileSync(path.join(temp,'compact.png'),(await win.webContents.capturePage()).toPNG());+ const result=await js(`JSON.stringify({errors:[...document.querySelectorAll('article [role="alert"]')].map(e=>e.textContent),last:document.querySelector('article:last-of-type')?.textContent})`);+ fs.writeFileSync(path.join(temp,'compact-result.json'),result);assert.equal(JSON.parse(result).errors.length,0);+ console.log('Compact command completed through the GUI.');+ await finish(0);+}).catch(error=>finish(1,error));diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjsindex 5a0d1596..29744cba 100644--- a/apps/native/electron/main.cjs+++ b/apps/native/electron/main.cjs@@ -14,6 +14,7 @@ const { rendererSample } = require('./renderer-profile.cjs');const { observeAgents, agentSampler } = require('./agent-observer.cjs');const { chromiumSample } = require('./hardware-profile.cjs');const fs = require('node:fs/promises');+const { installWindowState } = require('./window-state.cjs');const root = process.env.GRAFF_CWD || app.getPath('home');const resources = process.env.GRAFF_ELECTRON_RESOURCES || process.resourcesPath;@@ -55,6 +56,7 @@ app.whenReady().then(async () => {title: 'Codegraff', titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 14, y: 11 }, backgroundColor: '#fafaf9', show: false,webPreferences: { preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:app',contextIsolation: true, sandbox: true, nodeIntegration: false, backgroundThrottling: !process.env.GRAFF_ELECTRON_SMOKE } });+ installWindowState(win);browser = new BrowserTabs(win, message => { if (!win.isDestroyed()) win.webContents.send('browser-event', message); });win.on('close', () => browser.closeAll());win.webContents.on('did-start-navigation', (_event, _url, inPlace, mainFrame) => {@@ -101,6 +103,12 @@ app.whenReady().then(async () => {return ['find', 'zoom'].includes(method) ? browserAction(browser, chat, method, params) : browser.command(chat, method, params);});ipcMain.on('browser-overlay', (event, blocked) => { trusted(event); browser.setOverlay(blocked === true); });+ ipcMain.handle('window-control', (event, action) => {+ trusted(event);+ if (action === 'fullscreen') win.setFullScreen(!win.isFullScreen());+ else if (['zoom-in', 'zoom-out', 'reset-zoom'].includes(action)) win.webContents.setZoomLevel(action === 'reset-zoom' ? 0 : Math.max(-3, Math.min(4, win.webContents.getZoomLevel() + (action === 'zoom-in' ? 0.5 : -0.5))));+ else throw new Error('Unknown window action');+ });ipcMain.handle('activity', event => { trusted(event); return activity(); });ipcMain.on('browser-pin', (event, pin) => {const tab = [...browser.tabs.values()].find(t => t.view?.webContents === event.sender);@@ -112,6 +120,12 @@ app.whenReady().then(async () => {win.on('restore', () => win.webContents.send('browser-event', { type: 'layout' }));Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: 'Codegraff', submenu: [{ role: 'about' }, { label: 'Activity…', accelerator: 'CmdOrCtrl+,', click: () => void activity().catch(error => dialog.showErrorBox('Activity', error.message)) }, { label: 'Computer use…', click: () => void computer.configure().catch(error => dialog.showErrorBox('Computer use', error.message)) }, { type: 'separator' }, { role: 'quit' }] },+ { label: 'File', submenu: [+ ['New chat', 'CmdOrCtrl+N', 'new'], ['New tab', 'CmdOrCtrl+T', 'new'],+ ['Close chat', 'CmdOrCtrl+W', 'close'], ['Reopen closed chat', 'CmdOrCtrl+Shift+T', 'reopen'],+ ['Open workspace…', 'CmdOrCtrl+O', 'workspace'], ['Split right', 'CmdOrCtrl+D', 'split-right'],+ ['Split down', 'CmdOrCtrl+Shift+D', 'split-down'], ['Zoom split', 'CmdOrCtrl+Shift+Enter', 'split-zoom'],+ ].map(([label, accelerator, action]) => ({ label, accelerator, click: () => win.webContents.send('desktop-action', action) })) },{ role: 'editMenu' }, { label: 'View', submenu: [{ role: 'reload' }, { role: 'toggleDevTools' }, { role: 'togglefullscreen' }, { label: 'Release browser pages', click: () => { browser.closeAll(); win.webContents.send('browser-event', { type: 'released' }); } }] },{ label: 'Performance', submenu: [{ label: 'Start recording', click: () => void profiler.start() },diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjsnew file mode 100644index 00000000..e27d8472--- /dev/null+++ b/apps/native/electron/navigation-visual.cjs@@ -0,0 +1,48 @@+const {BrowserWindow,ipcMain}=require('electron');+const {installGalleryFixture}=require('./gallery-fixture.cjs');+const {installWindowState}=require('./window-state.cjs');+const assert=require('node:assert/strict');const path=require('node:path');const fs=require('node:fs');+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);+ const wc=win.webContents,js=async c=>{try{return await wc.executeJavaScript(c);}catch(error){console.error("Navigation expression:",c);throw error;}};+ wc.on("console-message",event=>{if(event.level>=2)console.error("Navigation renderer:",event.message);});+ const wait=async c=>{for(let i=0;i<150;i++){if(await js(c))return;await sleep(50);}throw Error(`Navigation timeout: ${c}`);};+ const key=async(key,extra={})=>{await js(`document.activeElement.dispatchEvent(new KeyboardEvent('keydown',${JSON.stringify({key,bubbles:true,cancelable:true,...extra})}))`);await sleep(100);};+ const input=async text=>{await js(`(()=>{const e=document.querySelector('textarea[aria-label="Prompt"]');e.focus();Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,${JSON.stringify(text)});e.dispatchEvent(new Event('input',{bubbles:true}));})()`);await sleep(100);};+ const tabs=()=>js(`document.querySelectorAll('[aria-label="Close tab"]').length`);+ try {+ fixtureWindow.hide();await wc.loadURL('about:blank');wc.debugger.attach('1.3');await wc.debugger.sendCommand('Page.enable');+ await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument',{source:`(${installGalleryFixture.toString()})();+ localStorage.setItem('graff.native.workspaces',JSON.stringify(Array.from({length:50},(_,i)=>({name:'Project '+(i%10),path:'/demo/folder-'+i}))));+ 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;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"]')`);+ await input('/compact');await wait(`!!document.querySelector('[role="option"]')`);assert.match(await js(`document.querySelector('[role="option"]').textContent`),/compact/);+ await key('Escape');await key('n',{metaKey:true});assert.equal(await tabs(),2);+ await input('/compact');await wait(`!!document.querySelector('[role="option"]')`);assert.match(await js(`document.querySelector('[role="option"]').textContent`),/compact/,'new chats inherit the command catalog');+ await input('/');await wait(`document.querySelectorAll('[role="option"]').length===101`);+ const bounds=await js(`(()=>{const r=document.querySelector('[data-composer-menu]').getBoundingClientRect(),l=document.querySelector('[role="listbox"]');return {top:r.top,bottom:r.bottom,height:innerHeight,scroll:l.scrollHeight>l.clientHeight}})()`);+ assert.ok(bounds.top>=0&&bounds.bottom<=bounds.height&&bounds.scroll,JSON.stringify(bounds));+ for(let i=0;i<15;i++)await key('ArrowDown');+ assert.ok(await js(`document.querySelector('[role="listbox"]').scrollTop>0`));await key('Enter');assert.match(await js(`document.querySelector('textarea').value`),/command-14/);+ await input('');await key('t',{metaKey:true});assert.equal(await tabs(),3);await key('w',{metaKey:true});assert.equal(await tabs(),2);await key('t',{metaKey:true,shiftKey:true});assert.equal(await tabs(),3);+ await key('d',{metaKey:true});await wait(`document.querySelectorAll('[data-chat]').length===2`);+ assert.equal(await js(`getComputedStyle(document.querySelector('[data-chat]').parentElement).flexDirection`),'row');+ await key('Enter',{metaKey:true,shiftKey:true});assert.equal(await js(`document.querySelectorAll('[data-chat]').length`),1);await key('Enter',{metaKey:true,shiftKey:true});+ await key('d',{metaKey:true,shiftKey:true});assert.equal(await js(`getComputedStyle(document.querySelector('[data-chat]').parentElement).flexDirection`),'column');+ await key('ArrowUp',{metaKey:true,ctrlKey:true});assert.ok(await js(`Array.from(document.querySelectorAll('[data-chat]')).some(e=>e.style.flexGrow!=='1')`));+ await key('=',{metaKey:true,ctrlKey:true});assert.ok(await js(`Array.from(document.querySelectorAll('[data-chat]')).every(e=>e.style.flexGrow==='1')`));+ assert.ok(await js(`Array.from(document.querySelectorAll('[data-chat]')).every(p=>{const r=p.getBoundingClientRect(),c=p.querySelector('[data-promptbar]').getBoundingClientRect();return c.top>=r.top&&c.bottom<=r.bottom})`),'stacked panes keep their composers visible');+ await key('o',{metaKey:true});await wait(`!!document.querySelector('[role="dialog"]')`);await key('Escape');+ await js(`document.querySelector('[aria-label="Workspace navigation"] button').click()`);await wait(`!!document.querySelector('[aria-label="Search workspaces"]')`);+ await js(`(()=>{const e=document.querySelector('[aria-label="Search workspaces"]');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,'folder-42');e.dispatchEvent(new Event('input',{bubbles:true}));})()`);await wait(`document.querySelector('[aria-label="Workspaces"]').querySelectorAll('button').length===1`);+ assert.match(await js(`document.querySelector('[aria-label="Workspaces"]').textContent`),/folder-42/);+ await js('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');+ fs.writeFileSync(path.join(output,'workspace-search.png'),(await wc.capturePage()).toPNG());await key('Escape');+ assert.equal(await js(`!!document.querySelector('[data-workspace-menu]')`),false);+ console.log('Navigation visual checks passed: command catalog/new tabs, bounded keyboard menu, new/close/reopen, splits/zoom/resize, workspace search.');+ } finally {ipcMain.removeHandler('browser');win.destroy();fixtureWindow.show();fixtureWindow.focus();}+}+module.exports={runNavigationVisuals};diff --git a/apps/native/electron/preload.cjs b/apps/native/electron/preload.cjsindex 5c473ef0..3ef38503 100644--- a/apps/native/electron/preload.cjs+++ b/apps/native/electron/preload.cjs@@ -2,6 +2,7 @@ const { contextBridge, ipcRenderer } = require('electron');contextBridge.exposeInMainWorld('graffDesktop', {browser: (chat, method, params) => ipcRenderer.invoke('browser', { chat, method, params }),activity: () => ipcRenderer.invoke('activity'),+ windowControl: action => ipcRenderer.invoke('window-control', action),subscribe: callback => {const listener = (_event, message) => callback(message);ipcRenderer.on('browser-event', listener);@@ -10,6 +11,12 @@ contextBridge.exposeInMainWorld('graffDesktop', {});let longTasks;+let fullscreen = false;+const applyWindowState = () => {+ if (document.documentElement) document.documentElement.dataset.desktopFullscreen = String(fullscreen);+};+ipcRenderer.on('window-state', (_event, state) => { fullscreen = state.fullscreen === true; applyWindowState(); });+window.addEventListener('DOMContentLoaded', applyWindowState);ipcRenderer.on('profile-enabled', (_event, enabled) => {longTasks?.disconnect();if (!enabled) return;@@ -43,3 +50,5 @@ window.addEventListener('DOMContentLoaded', () => {}).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['hidden', 'aria-hidden', 'role'] });update();});++ipcRenderer.on('desktop-action', (_event, action) => window.dispatchEvent(new CustomEvent('graff-desktop-action', { detail: action })));diff --git a/apps/native/electron/smoke-ui.cjs b/apps/native/electron/smoke-ui.cjsindex 624c64fc..eedc150d 100644--- a/apps/native/electron/smoke-ui.cjs+++ b/apps/native/electron/smoke-ui.cjs@@ -12,6 +12,12 @@ async function smokeUI({ win, browser, backend }) {await js(`document.querySelector(${JSON.stringify(selector)}).click()`); await sleep(100);};await wait(`!!document.querySelector('[aria-label="Appearance"]')`);+ const fileMenu = require('electron').Menu.getApplicationMenu().items.find(item => item.label === 'File').submenu;+ const beforeTabs = await js(`document.querySelectorAll('[aria-label="Close tab"]').length`);+ fileMenu.items.find(item => item.accelerator === 'CmdOrCtrl+N').click();+ await wait(`document.querySelectorAll('[aria-label="Close tab"]').length===${beforeTabs + 1}`);+ fileMenu.items.find(item => item.accelerator === 'CmdOrCtrl+W').click();+ await wait(`document.querySelectorAll('[aria-label="Close tab"]').length===${beforeTabs}`);await click('[aria-label="Appearance"]');await wait(`!!document.querySelector('[role="dialog"][aria-label="Appearance"]')`);for (const [name, expected] of [['White', 'light'], ['Black', 'dark'], ['Website', 'website'], ['CodeGraff', 'codegraff']]) {diff --git a/apps/native/electron/stress-visual.cjs b/apps/native/electron/stress-visual.cjsnew file mode 100644index 00000000..6aba3e3f--- /dev/null+++ b/apps/native/electron/stress-visual.cjs@@ -0,0 +1,63 @@+const { BrowserWindow } = require('electron');+const { installWindowState } = require('./window-state.cjs');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+async function runStressVisuals({win: fixtureWindow, origin, output}) {+ const win = new BrowserWindow({width:1000,height:760,show:true,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});+ installWindowState(win);+ const js = code => win.webContents.executeJavaScript(code);+ const wait = async expression => {for(let i=0;i<200;i++){if(await js(expression))return;await sleep(50);}throw Error(`Stress timeout: ${expression}`);};+ const click = async selector => {await js(`document.querySelector(${JSON.stringify(selector)}).click()`);await sleep(60);};+ const select = async name => {await click(`[data-stress-case="${name}"]`); await js('document.fonts.ready.then(()=>true)');};+ const metrics=[];+ const bounds=async()=>{+ const r=await js(`(()=>{const el=document.querySelector('[aria-label="Stress composer"]'),r=el.getBoundingClientRect();return {overflow:document.documentElement.scrollWidth>innerWidth,bottom:r.bottom,top:r.top,height:innerHeight}})()`);+ assert.equal(r.overflow,false);assert.ok(r.top>=0&&r.bottom<=r.height,JSON.stringify(r));+ };+ try {+ fixtureWindow.hide();win.show();win.focus();await win.loadURL(`${origin}/visual-tests/stress`);+ await wait(`!!document.querySelector('[data-tool-summary]')`);+ for(const theme of ['light','dark','codegraff']) {+ await click(`[data-stress-theme="${theme}"]`);await select('tools');+ assert.equal(await js(`document.querySelectorAll('[data-tool-row]').length`),0,'collapsed calls must not mount hidden rows');+ assert.match(await js(`document.querySelector('[data-tool-summary]').textContent`),/1 failed/);+ const start=Date.now();await click('[data-tool-summary]');+ assert.equal(await js(`document.querySelectorAll('[data-tool-row]').length`),50);+ assert.equal(await js(`document.querySelectorAll('[data-tool-output]').length`),0);+ await click('[data-tool-row]');await bounds();+ assert.ok(await js(`(()=>{const e=document.querySelector('[data-tool-output]');return e.scrollHeight>e.clientHeight&&e.clientHeight<=256})()`));+ await click('[aria-label="Next tools"]');+ assert.match(await js(`document.querySelector('[data-tool-row]').textContent`),/file-50/);+ assert.equal(await js(`document.querySelectorAll('[data-tool-output]').length`),0);+ metrics.push({theme,toolCount:5000,renderedRows:50,disclosureMs:Date.now()-start});+ await select('output');await click('[data-tool-summary]');await click('[data-tool-row]');+ const text=await js(`document.querySelector('[data-tool-output]').textContent`);+ assert.match(text,/FIRST LINE/);assert.match(text,/FINAL ERROR/);assert.match(text,/omitted/);await bounds();+ fs.writeFileSync(path.join(output,`stress-output-${theme}.png`),(await win.webContents.capturePage()).toPNG());+ }+ await select('history');+ assert.equal(await js(`document.querySelectorAll('article').length`),40,'initial history should mount only 80 messages');+ await click('[data-chat-transcript] button');+ assert.equal(await js(`document.querySelectorAll('article').length`),80);await bounds();+ await select('user');await bounds();+ await select('text');await bounds();await click('[data-stream]');+ await js(`document.querySelector('[data-stress-scroll]').scrollTop=200`);await sleep(100);+ const before=await js(`document.querySelector('[data-stress-scroll]').scrollTop`);await sleep(600);+ assert.ok(Math.abs(await js(`document.querySelector('[data-stress-scroll]').scrollTop`)-before)<4,'streaming must preserve a reader browsing earlier text');+ await click('[data-stream]');+ const titleHeight=()=>js(`document.querySelector('[data-desktop-titlebar]').getBoundingClientRect().height`);+ assert.equal(await titleHeight(),36);+ if(process.platform==='darwin') {+ win.setFullScreen(true);await wait(`document.documentElement.dataset.desktopFullscreen==='true'`);+ assert.equal(await titleHeight(),0);await bounds();+ fs.writeFileSync(path.join(output,'stress-fullscreen.png'),(await win.webContents.capturePage()).toPNG());+ await win.reload();await wait(`document.documentElement.dataset.desktopFullscreen==='true'`);assert.equal(await titleHeight(),0);+ win.setFullScreen(false);await wait(`document.documentElement.dataset.desktopFullscreen==='false'`);assert.equal(await titleHeight(),36);+ }+ fs.writeFileSync(path.join(output,'stress-results.json'),JSON.stringify({passed:['5000 tools','bounded output','1000 messages','unbroken input','long markdown','stream reading position','fullscreen and reload'],metrics},null,2));+ console.log('Stress visual checks passed: long tools/output/history/text, reading position, fullscreen.');+ } finally {win.destroy();fixtureWindow.show();fixtureWindow.focus();}+}+module.exports={runStressVisuals};diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjsindex 7d470563..07e9b369 100644--- a/apps/native/electron/visual-tests.cjs+++ b/apps/native/electron/visual-tests.cjs@@ -9,7 +9,7 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-visual-'));app.setPath('userData', path.join(temporary, 'profile'));let server, win;-const deadline = setTimeout(() => { console.error('Visual run exceeded 120 seconds'); finish(1); }, 120000);+const deadline = setTimeout(() => { console.error('Visual run exceeded 240 seconds'); finish(1); }, 240000);app.whenReady().then(async () => {const root = path.resolve(__dirname, '..'), output = process.env.GRAFF_VISUAL_OUTPUT || path.resolve(root, '../../zig-out/visual-tests');fs.mkdirSync(output, { recursive: true });@@ -55,6 +55,8 @@ app.whenReady().then(async () => {results.push(`${theme}/${name}`);}}+ await require('./stress-visual.cjs').runStressVisuals({ win, origin, output });+ await require('./navigation-visual.cjs').runNavigationVisuals({ win, origin, output });await require('./agents-visual.cjs').runAgentVisuals({ win, origin, output });if (process.env.GRAFF_PERFORMANCE_TESTS) await require('./performance-scenarios.cjs').runPerformance({ win, origin, output });assert.deepEqual(apiRequests, [], 'Visual fixtures must not call the engine or model APIs');diff --git a/apps/native/electron/window-state.cjs b/apps/native/electron/window-state.cjsnew file mode 100644index 00000000..f91f44b4--- /dev/null+++ b/apps/native/electron/window-state.cjs@@ -0,0 +1,10 @@+// Native fullscreen owns its title area; do not reserve the windowed drag strip.+function installWindowState(win) {+ const publish = () => {+ if (!win.isDestroyed()) win.webContents.send('window-state', { fullscreen: win.isFullScreen() });+ };+ win.on('enter-full-screen', publish);+ win.on('leave-full-screen', publish);+ win.webContents.on('did-finish-load', publish);+}+module.exports = { installWindowState };diff --git a/apps/native/lib/acp-client-stream.test.ts b/apps/native/lib/acp-client-stream.test.tsnew file mode 100644index 00000000..ffbe4bee--- /dev/null+++ b/apps/native/lib/acp-client-stream.test.ts@@ -0,0 +1,27 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {prompt} from './acp-client';+const chunk = {method:'session/update',params:{sessionId:'test',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Visible partial reply'}}}};+async function withWire(lines:unknown[], body:(received:unknown[])=>Promise<void>) {+ const original=globalThis.fetch, received:unknown[]=[];+ globalThis.fetch=async()=>new Response(lines.map(line=>JSON.stringify(line)).join('\n')+'\n');+ try {await body(received);} finally {globalThis.fetch=original;}+}+test('a disconnected stream preserves partial output and reports interruption',async()=>{+ await withWire([chunk],async received=>{+ await assert.rejects(async()=>{for await(const update of prompt('test','test','hello'))received.push(update);},/ended before/);+ assert.deepEqual(received,[chunk.params.update]);+ });+});+test('a cancelled turn produces a terminal event instead of a hanging spinner',async()=>{+ await withWire([chunk,{id:1,result:{stopReason:'cancelled'}}],async received=>{+ for await(const update of prompt('test','test','hello'))received.push(update);+ assert.deepEqual(received.at(-1),{sessionUpdate:'gui_turn_end',stopReason:'cancelled'});+ });+});+test('a bridge error is surfaced after any already delivered text',async()=>{+ await withWire([chunk,{id:1,error:{message:'Agent exited'}}],async received=>{+ await assert.rejects(async()=>{for await(const update of prompt('test','test','hello'))received.push(update);},/Agent exited/);+ assert.equal(received.length,1);+ });+});diff --git a/apps/native/lib/acp-transport.test.ts b/apps/native/lib/acp-transport.test.tsindex 8abc4ad1..cda3b3b6 100644--- a/apps/native/lib/acp-transport.test.ts+++ b/apps/native/lib/acp-transport.test.ts@@ -21,5 +21,28 @@ test("catalog replies cannot steal assistant notifications or close the prompt s});test("a child exit rejects pending requests instead of leaving a blank conversation", async () => {const { child, transport } = fixture(); const pending = transport.request("session/prompt", {}, 1000);- child.emit("exit", 1, null); await assert.rejects(pending, /exited/);+ child.emit("close", 1, null); await assert.rejects(pending, /exited/);+});++test("an exit before stdout drains does not lose the terminal reply", async () => {+ const { child, transport } = fixture(); const pending = transport.request("session/prompt", {}, 1000);+ child.emit("exit", 0, null);+ child.stdout.write(JSON.stringify({ id: 1, result: { stopReason: "end_turn" } }) + "\n");+ child.emit("close", 0, null);+ assert.deepEqual(await pending, { stopReason: "end_turn" });+});+test("a large batch of individually valid lines is not an oversized line", async () => {+ const { child, transport } = fixture(); let count = 0;+ const pending = transport.request("session/prompt", {}, 5000, () => count++);+ const line = JSON.stringify({ method: "session/update", params: { text: "x".repeat(1024) } }) + "\n";+ child.stdout.write(line.repeat(8200) + JSON.stringify({id:1,result:{}}) + "\n");+ await pending; assert.equal(count, 8201);+});++test("an oversized protocol line marks its session unusable so bootstrap can replace it", async () => {+ const { child, transport } = fixture(); const pending = transport.request("session/prompt", {}, 1000);+ assert.equal(transport.usable, true);+ child.stdout.write("x".repeat(8 * 1024 * 1024 + 1));+ await assert.rejects(pending, /exceeds limit/); assert.equal(transport.usable, false);+ await assert.rejects(transport.request("session/prompt"), /exceeds limit/);});diff --git a/apps/native/lib/acp-transport.ts b/apps/native/lib/acp-transport.tsindex a9e57d74..ab76a3c0 100644--- a/apps/native/lib/acp-transport.ts+++ b/apps/native/lib/acp-transport.ts@@ -16,14 +16,16 @@ export class AcpTransport {constructor(private child: Child, private notification: (message: Message) => void = () => {}) {child.stdout.on("data", chunk => this.feed(this.decoder.write(chunk)));child.once("error", error => this.fail(error));- child.once("exit", (code, signal) => this.fail(new Error(`graff acp exited (${code ?? signal})`)));+ // stdout may still deliver the final reply after exit, but never after close.+ child.once("close", (code, signal) => this.fail(new Error(`graff acp exited (${code ?? signal})`)));child.stdin.on("error", error => this.fail(error));}private feed(text: string) {+ if (this.failure) return;this.buffer += text;- if (this.buffer.length > 8 * 1024 * 1024) { this.fail(new Error("ACP line exceeds limit")); return; }let newline;while ((newline = this.buffer.indexOf("\n")) >= 0) {+ if (newline > 8 * 1024 * 1024) { this.fail(new Error("ACP line exceeds limit")); return; }const line = this.buffer.slice(0, newline); this.buffer = this.buffer.slice(newline + 1);let message: Message;try { message = JSON.parse(line); } catch { continue; }@@ -38,12 +40,16 @@ export class AcpTransport {else pending.resolve(message.result);}}+ if (this.buffer.length > 8 * 1024 * 1024) this.fail(new Error("ACP line exceeds limit"));}private fail(error: Error) {+ if (this.failure) return;this.failure = error;+ this.buffer = "";for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(error); }this.pending.clear(); this.listeners.clear();}+ get usable(): boolean { return this.failure === null; }notify(method: string, params?: unknown) {if (this.failure) throw this.failure;this.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method, params }) + "\n");diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.tsindex b04b86d6..ab07db0a 100644--- a/apps/native/lib/acp.ts+++ b/apps/native/lib/acp.ts@@ -1,3 +1,4 @@+import { boundToolDetail } from "./tool-detail";/** ACP v1 session/update shapes the native harness renders. */export type AcpContent = { type: "text"; text: string };@@ -94,8 +95,8 @@ function detailFromInput(input: Record<string, unknown>): ToolRow["detail"] {const newS = typeof input.new_string === "string" ? input.new_string : "";if (oldS || newS) {const lines: ToolRow["detail"] = [];- if (oldS) lines.push({ text: firstLine(oldS) });- if (newS) lines.push({ text: firstLine(newS), tone: "add" });+ if (oldS) lines.push({ text: oldS });+ if (newS) lines.push({ text: newS, tone: "add" });return lines;}if (typeof input.command === "string") return [{ text: input.command }];@@ -175,7 +176,7 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId.join("\n");const fromInput = detailFromInput(rawInput);const detail = contentText- ? [...(prev?.detail ?? fromInput), { text: firstLine(contentText) }]+ ? [...(prev?.detail ?? fromInput), { text: contentText }]: fromInput.length? fromInput: (prev?.detail ?? []);@@ -192,7 +193,7 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallIdicon: iconForKind(kind, title),chip: chipRaw === label || humanize(chipRaw) === label ? "" : chipRaw,status,- detail,+ detail: boundToolDetail(detail),path,startedAt: prev?.startedAt ?? Date.now(),atChars: prev?.atChars ?? turn.text.length,diff --git a/apps/native/lib/desktop.ts b/apps/native/lib/desktop.tsindex 706fb13a..899d9162 100644--- a/apps/native/lib/desktop.ts+++ b/apps/native/lib/desktop.ts@@ -3,6 +3,7 @@ import type { PageInfo } from "./browser-client";export type DesktopEvent = { type: string; chat?: string; info?: PageInfo; pin?: BrowserPin };export type DesktopBridge = {+ windowControl?(action: "fullscreen" | "zoom-in" | "zoom-out" | "reset-zoom"): Promise<void>;browser<T = PageInfo | null>(chat: string, method: string, params?: Record<string, unknown>): Promise<T>;activity(): Promise<{ rssMiB: number; cpuPercent: number; processes: number; browsers: number }>;subscribe(callback: (event: DesktopEvent) => void): () => void;diff --git a/apps/native/lib/tool-detail.test.ts b/apps/native/lib/tool-detail.test.tsnew file mode 100644index 00000000..a41e15f8--- /dev/null+++ b/apps/native/lib/tool-detail.test.ts@@ -0,0 +1,14 @@+import { test, expect } from 'bun:test';+import { applyAcpUpdate, emptyTurn } from './acp';+import { boundToolDetail, TOOL_DETAIL_LIMIT } from './tool-detail';+test('tool results preserve multiple lines and long diagnostics', () => {+ const text = 'first line\n' + 'long diagnostic '.repeat(100) + '\nfinal failure';+ const turn = applyAcpUpdate(emptyTurn(), { sessionUpdate:'tool_call', toolCallId:'read', title:'Read', kind:'read', status:'completed', content:[{type:'content',content:{type:'text',text}}] });+ expect(turn.tools[0].detail[0].text).toBe(text);+});+test('oversized GUI output keeps the head and tail with an explicit omission', () => {+ const text = 'START' + 'x'.repeat(TOOL_DETAIL_LIMIT * 3) + 'FINAL ERROR';+ const result = boundToolDetail([{text}]).map(row => row.text).join('\n');+ expect(result.startsWith('START')).toBe(true); expect(result.endsWith('FINAL ERROR')).toBe(true);+ expect(result).toContain('omitted'); expect(result.length).toBeLessThan(TOOL_DETAIL_LIMIT);+});diff --git a/apps/native/lib/tool-detail.ts b/apps/native/lib/tool-detail.tsnew file mode 100644index 00000000..e7bdee0c--- /dev/null+++ b/apps/native/lib/tool-detail.ts@@ -0,0 +1,9 @@+export const TOOL_DETAIL_LIMIT = 128 * 1024;+type Detail = { text: string; tone?: "add" };+/** Preserve useful head and tail, and never silently omit large tool output. */+export function boundToolDetail(detail: Detail[]): Detail[] {+ if (detail.reduce((sum, line) => sum + line.text.length + 1, 0) <= TOOL_DETAIL_LIMIT) return detail;+ const text = detail.map(line => line.text).join("\n");+ const half = TOOL_DETAIL_LIMIT / 2 - 128;+ return [{ text: text.slice(0, half) }, { text: `\n[Large output: ${text.length - half * 2} characters omitted from this GUI preview.]\n` }, { text: text.slice(-half) }];+}diff --git a/docs/adr/0077-desktop-command-parity-and-bounded-disclosure.md b/docs/adr/0077-desktop-command-parity-and-bounded-disclosure.mdnew file mode 100644index 00000000..c78cd9a3--- /dev/null+++ b/docs/adr/0077-desktop-command-parity-and-bounded-disclosure.md@@ -0,0 +1,30 @@+# 0077. Keep desktop commands in parity and bound transcript disclosure++Status: accepted++## Decision++ACP advertises the entire shared REPL command catalog, including commands whose+presentation remains terminal-specific. The desktop consumes that advertisement+and shares it with new tabs before they create coding sessions. A catalog parity+test prevents commands from silently disappearing from one client. The GUI does+not maintain a second, independently edited command list.++Command menus fit the available viewport. Tool groups stay collapsed until the+user opens them and mount only the current page of rows. Individual output is+mounted only on disclosure; oversized previews retain their beginning and end+with an explicit omission marker. Restored conversation history initially mounts+its newest page, with earlier messages available on request.++Desktop shortcuts adapt chat and split actions from familiar terminal conventions.+They do not emit terminal control sequences. Native fullscreen state removes the+windowed title spacer and is republished after renderer reloads.++## Consequences++Engine behavior remains shared across clients. Terminal-only display settings do+not become GUI themes merely because they are discoverable. GUI previews are+bounded and clearly labeled; stored sessions and engine results remain intact.+Loading earlier pages increases mounted history, so this is not full transcript+virtualization. Synthetic tests cover navigation and disclosure without a model;+real coding remains a separate, opt-in integration check.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 8144b3b0..19e11fc6 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -87,6 +87,7 @@ record only when you need the evidence or the edge cases.| [0074](0074-gui-skills-and-portable-themes.md) | Explicit desktop skills and validated themes live in the GUI; selected instructions travel over ACP. || [0075](0075-acp-adapter-and-desktop-measurements.md) | ACP presentation decoding is separate from session lifecycle; desktop performance uses bounded workload measurements and default Chromium acceleration. || [0076](0076-local-agent-panel.md) | Verified local peer discovery, non-consuming history, explicit queued DMs and anonymous profiler slots. |+| [0077](0077-desktop-command-parity-and-bounded-disclosure.md) | ACP shares the complete REPL catalog; desktop menus, tool disclosure and initial history rendering stay bounded. |## When to write onediff --git a/src/acp.zig b/src/acp.zigindex 5d5920f2..60c226d8 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -510,3 +510,12 @@ test {_ = @import("acp_protocol.zig");_ = @import("acp_stream.zig");}++test "ACP advertises the complete REPL command catalog including compact" {+ const catalog = @import("command_catalog.zig").commands;+ const advertised = proto.slashCommands();+ try std.testing.expectEqual(catalog.len, advertised.len);+ for (catalog, advertised) |command, exposed| {+ try std.testing.expectEqualStrings(command.name[1..], exposed.name);+ }+}diff --git a/src/acp_protocol.zig b/src/acp_protocol.zigindex 3bcb92e8..c412122d 100644--- a/src/acp_protocol.zig+++ b/src/acp_protocol.zig@@ -155,21 +155,6 @@ pub fn writeAvailableCommands(w: *Io.Writer, session_id: []const u8, commands: [});}-/// Commands the menu does not offer. Each one needs a terminal the client-/// does not have: a full-screen HUD, the raw-mode key loop a picker drives,-/// or the browser hand-off an OAuth flow waits on. Typing one still works —-/// it degrades to a text dump — but a menu entry that lands somewhere the-/// client cannot show is worse than no entry.-const terminal_only = [_][]const u8{- "/theme",- "/animation",- "/debug",- "/login",- "/paste",- "/image",- "/images",-};-/// The advertised set, built from the one catalog the REPL and tab/// completion already read, so a command cannot exist in one surface and be/// missing from the other. Names go out bare: ACP owns the leading slash.@@ -178,16 +163,12 @@ pub fn slashCommands() []const AvailableCommand {var out: [command_catalog.commands.len]AvailableCommand = undefined;var n: usize = 0;for (command_catalog.commands) |c| {- for (terminal_only) |skip| {- if (std.mem.eql(u8, c.name, skip)) break;- } else {- out[n] = .{- .name = c.name[1..],- .description = c.desc,- .input = .{ .hint = c.usage },- };- n += 1;- }+ out[n] = .{+ .name = c.name[1..],+ .description = c.desc,+ .input = .{ .hint = c.usage },+ };+ n += 1;}const frozen = out[0..n].*;break :blk frozen;