graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Fix desktop clipboard, updates, snapshot sessions, and GUI test focus
Rachb393c8c5dc81
diff --git a/apps/native/app/api/sessions/route.ts b/apps/native/app/api/sessions/route.tsindex 83ca43c5..09ae4a13 100644--- a/apps/native/app/api/sessions/route.ts+++ b/apps/native/app/api/sessions/route.ts@@ -70,6 +70,10 @@ export async function GET(req: NextRequest) {size: st.size,workspace: str(parsed.workspace) ?? str(header?.workspace) ?? found.workspace,local: found.local,+ // Saved file only — not a live REPL attach. The GUI must treat the+ // payload as a snapshot with unknown execution (#839).+ view: "snapshot",+ execution: "unknown",// The desktop never displayed raw provider history. Avoid allocating// its tool bodies and image payloads again in Chromium just to drop them....(req.nextUrl.searchParams.get("view") === "transcript"diff --git a/apps/native/components/site/BrowserPane.tsx b/apps/native/components/site/BrowserPane.tsxindex 1dfff34d..c5edd99b 100644--- a/apps/native/components/site/BrowserPane.tsx+++ b/apps/native/components/site/BrowserPane.tsx@@ -674,7 +674,7 @@ export default function BrowserPane({onChange={(e) => setUrl(e.target.value)}onFocus={(e) => e.currentTarget.select()}spellCheck={false}- placeholder="URL"+ placeholder="Search or enter a URL"aria-label="Address"title="Address (Cmd/Ctrl+L from the page)"className="h-7 min-w-0 flex-1 rounded-[7px] bg-field px-2 font-mono text-[12px] text-ink shadow-hairline outline-none placeholder:text-ink-3 focus:bg-hover"diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsxindex 6e6343ab..543a19f1 100644--- a/apps/native/components/site/ChatBubbles.tsx+++ b/apps/native/components/site/ChatBubbles.tsx@@ -93,6 +93,7 @@ export const AssistantBody = memo(function AssistantBody({scroller,following,reasoningLabel,+ snapshot,}: {turn: AssistantTurn;onOpenPath?: (path: string) => void;@@ -100,6 +101,7 @@ export const AssistantBody = memo(function AssistantBody({scroller?: RefObject<HTMLDivElement | null>;following: boolean;reasoningLabel?: string;+ snapshot?: boolean;}) {const thinking = turn.status === "thinking";const live = thinking || turn.status === "streaming";@@ -154,7 +156,7 @@ export const AssistantBody = memo(function AssistantBody({</div>),)}- <TurnActivity turn={turn} />+ <TurnActivity turn={turn} snapshot={snapshot} />{turn.error && (<p role="alert" className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>)}diff --git a/apps/native/components/site/ChatTranscript.tsx b/apps/native/components/site/ChatTranscript.tsxindex 5e1bdb35..677d108e 100644--- a/apps/native/components/site/ChatTranscript.tsx+++ b/apps/native/components/site/ChatTranscript.tsx@@ -5,9 +5,9 @@ import type { Msg } from "./harness-types";import { pinScrollerTail } from "@/lib/follow-scroll";const PAGE_SIZE = 80;-export default memo(function ChatTranscript({ messages, register, following, onOpenPath, onReview }: {+export default memo(function ChatTranscript({ messages, register, following, onOpenPath, onReview, snapshot }: {messages: Msg[]; register: (element: HTMLDivElement | null) => void; following: boolean;- onOpenPath: (path: string) => void; onReview: () => void;+ onOpenPath: (path: string) => void; onReview: () => void; snapshot?: boolean;}) {const scroller = useRef<HTMLDivElement>(null);const registerScroller = useCallback((element: HTMLDivElement | null) => {@@ -38,6 +38,11 @@ export default memo(function ChatTranscript({ messages, register, following, onO}, []);return <div ref={registerScroller} data-chat-transcriptclassName="min-h-0 min-w-0 max-w-full flex-1 overflow-x-hidden overflow-y-auto overscroll-contain" style={{ overflowAnchor: "none" }}>+ {snapshot && (+ <p role="status" data-session-snapshot className="mx-auto max-w-[720px] px-4 pt-4 text-[12.5px] leading-relaxed text-ink-2 sm:px-8">+ Saved snapshot — this view is not attached to a live REPL run. A follow-up continues here in the GUI.+ </p>+ )}<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;@@ -47,7 +52,7 @@ export default memo(function ChatTranscript({ messages, register, following, onO{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} />)}+ scroller={scroller} following={following && start + index === messages.length - 1} snapshot={snapshot} />)}</div></div>;});diff --git a/apps/native/components/site/DesktopUpdates.tsx b/apps/native/components/site/DesktopUpdates.tsxindex b3cd52fa..bfb45771 100644--- a/apps/native/components/site/DesktopUpdates.tsx+++ b/apps/native/components/site/DesktopUpdates.tsx@@ -102,7 +102,8 @@ export default function DesktopUpdates() {<buttontype="button"data-desktop-update-check- className="rounded-lg bg-hover px-3 py-1.5 text-left text-[12.5px] font-medium hover:bg-hover-2"+ disabled={state.status === "unavailable"}+ className="rounded-lg bg-hover px-3 py-1.5 text-left text-[12.5px] font-medium hover:bg-hover-2 disabled:opacity-50"onClick={() => void act("check")}>Check for Updates@@ -121,7 +122,8 @@ export default function DesktopUpdates() {data-desktop-update-automaticrole="switch"aria-checked={state.automatic}- className="flex items-center justify-between rounded-lg px-1 py-1 text-[12.5px] text-ink-2 hover:bg-hover"+ disabled={state.status === "unavailable"}+ className="flex items-center justify-between rounded-lg px-1 py-1 text-[12.5px] text-ink-2 hover:bg-hover disabled:opacity-50"onClick={() => void act("automatic", !state.automatic)}><span>Download updates automatically</span>diff --git a/apps/native/components/site/ElectronBrowserPane.tsx b/apps/native/components/site/ElectronBrowserPane.tsxindex 9f8f90c5..ff1ac9f2 100644--- a/apps/native/components/site/ElectronBrowserPane.tsx+++ b/apps/native/components/site/ElectronBrowserPane.tsx@@ -30,7 +30,10 @@ export default function ElectronBrowserPane({ chat, pins, onPinsChange, onAsk, osetError(""); const next = await desktop()!.browser(chat, method, params);if (next?.url !== undefined) { setInfo(next); setUrl(next.url === "about:blank" ? "" : next.url); localStorage.setItem(storageKey, next.url); }layoutRef.current();- } catch (err) { setError(err instanceof Error ? err.message : String(err)); }+ } catch (err) {+ const raw = err instanceof Error ? err.message : String(err);+ setError(/Invalid URL/i.test(raw) ? "Enter a web address or a search." : raw);+ }};useEffect(() => {const bridge = desktop()!;@@ -86,7 +89,7 @@ export default function ElectronBrowserPane({ chat, pins, onPinsChange, onAsk, o<button type="button" className={button} aria-label="Back" disabled={!info?.canGoBack} onClick={() => void command("back")}>←</button><button type="button" className={button} aria-label="Forward" disabled={!info?.canGoForward} onClick={() => void command("forward")}>→</button><button type="button" className={button} aria-label="Reload" onClick={() => void command("open", { url })}>↻</button>- <input ref={address} className="h-7 min-w-0 flex-1 rounded-md bg-field px-2 text-xs outline-none" aria-label="Address" placeholder="Enter a URL" value={url} onChange={e => setUrl(e.target.value)} onFocus={e => e.currentTarget.select()} />+ <input ref={address} className="h-7 min-w-0 flex-1 rounded-md bg-field px-2 text-xs outline-none" aria-label="Address" placeholder="Search or enter a URL" value={url} onChange={e => setUrl(e.target.value)} onFocus={e => e.currentTarget.select()} /><button className={button}>Go</button></form><div className="flex h-9 items-center gap-1 border-b border-line px-2">diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex df600512..516703b0 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -22,8 +22,9 @@ import FilesPane from "@/components/site/FilesPane";import BrowserPane from "@/components/site/DesktopBrowserPane";import { annotationsBlock, type BrowserPin } from "@/lib/browser/annotations";import { browserClose, browserHandle, browserNav } from "@/lib/browser-client";-import TaskRows from "@/components/primitives/TaskRows";import ChatTranscript from "./ChatTranscript";+import TasksSidebar from "./TasksSidebar";+import { MAX_COLUMNS, SPLIT_LIMIT_MESSAGE, splitLimitReached } from "./harness-split";import { useDesktopShortcuts } from "./useDesktopShortcuts";import EmptyState from "@/components/site/ChatEmpty";import {@@ -56,9 +57,6 @@ import {/** Whether the sidecar browser pane was open, restored after a reload. */const BROWSER_OPEN_KEY = "graff.native.browser.open";-/** Columns the split view will show at once, the active chat included. */-const MAX_COLUMNS = 4;-/** Rows the sidebar previews; the library pages the rest. */const SIDEBAR_PAGE = 12;@@ -116,6 +114,8 @@ export default function GraffHarness() {// the whole chat area, so opening it leaves the other side panes.const [projectsOpen, setProjectsOpen] = useState(false);const [conversationsOpen, setConversationsOpen] = useState(false);+ const [tasksOpen, setTasksOpen] = useState(false);+ const [splitNotice, setSplitNotice] = useState<string | null>(null);const openConversations = () => {setProjectsOpen(false);setAgentsOpen(false);@@ -152,9 +152,6 @@ export default function GraffHarness() {.slice(0, MAX_COLUMNS);const columnKey = columnIds.join(",");const { paneRef, tailing } = useChatScroll(chats, columnKey);- const active = chatThread.messages.length > 0;- const busy = busyIds.has(chatThread.id);- const chatModel = chatThread.model ?? model ?? undefined;const sessionId = sessionIds[chatThread.id] ?? null;const handleOf = (chatId: number) => chatHandle(pageRef.current, chatId);const setBusyFor = (chatId: number, on: boolean) =>@@ -364,6 +361,7 @@ export default function GraffHarness() {: {...c,title,+ snapshot: undefined,messages: [...c.messages,{ id: userId, role: "user", text: trimmed },@@ -480,7 +478,7 @@ export default function GraffHarness() {const id = ++chatIdRef.current;const messages: Msg[] = loaded.messages.map(m => ({ id: ++msgIdRef.current, ...m }));sessionNamesRef.current.set(id, name);- const next = [...chatsRef.current, { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name, cwd }];+ const next = [...chatsRef.current, { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name, cwd, snapshot: loaded.snapshot }];chatsRef.current = next; setChats(next);selectStored(id, cwd);void requireSession(id, false, loaded.meta.model ?? undefined).catch(() => undefined);@@ -515,7 +513,11 @@ export default function GraffHarness() {/** Another chat beside the ones on screen, in the workspace the active* chat is in. Up to four columns; past that they are too narrow to read. */const addPane = () => {- if (columnIds.length >= MAX_COLUMNS) return;+ if (splitLimitReached(columnIds.length)) {+ setSplitNotice(SPLIT_LIMIT_MESSAGE);+ return;+ }+ setSplitNotice(null);const id = (chatIdRef.current += 1);openChat(id);setPanes([...columnIds, id]);@@ -639,7 +641,7 @@ export default function GraffHarness() {{hasMessages ? (<div className="flex min-h-0 flex-1 flex-col">- <ChatTranscript key={thread.id} messages={thread.messages} register={paneRef(thread.id)} following={isFollowing} onOpenPath={openPath} onReview={openChanges} />+ <ChatTranscript key={thread.id} messages={thread.messages} register={paneRef(thread.id)} following={isFollowing} onOpenPath={openPath} onReview={openChanges} snapshot={thread.snapshot} /><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 && (@@ -682,7 +684,7 @@ export default function GraffHarness() {<PromptBardemo={false}tall={!compactPane}- placeholder={threadBusy ? "Queue a follow-up…" : "Follow up"}+ placeholder={threadBusy ? "Queue a follow-up…" : thread.snapshot ? "Continue here (starts a GUI session)" : "Follow up"}models={models}commands={commands[thread.id] ?? catalogCommands}root={cwdOf(thread)}@@ -783,6 +785,8 @@ export default function GraffHarness() {browserOpen={browserOpen} onBrowser={() => { setAgentsOpen(false); setProjectsOpen(false); setConversationsOpen(false); setFilesOpen(false); setBrowserOpen(open => !open); }} pinCount={pinCount}terminalVisible={terminalVisible} toggleTerminal={toggleTerminal} agentsOpen={agentsOpen}workingAgents={workingAgents}+ tasksOpen={tasksOpen} taskCount={paneTodos.length} onTasks={() => setTasksOpen(open => !open)}+ splitNotice={splitNotice}onAgents={() => { setProjectsOpen(false); setAgentsOpen(!agentsOpen); setFilesOpen(false); setBrowserOpen(false); setConversationsOpen(false); }} /><ConversationOpenNotice request={savedConversation.request} onCancel={savedConversation.cancel} onRetry={savedConversation.retry} /><div className="flex min-h-0 flex-1 gap-2.5">@@ -825,25 +829,8 @@ export default function GraffHarness() {/>)}- {!projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && active && paneTodos.length > 0 && (- <aside- className="hidden w-[360px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"- style={{ animation: "fade-in 300ms ease both" }}- >- <div className="flex h-11 shrink-0 items-center border-b border-line px-4">- <span className="text-[13px] font-semibold text-ink">Tasks</span>- </div>- <div className="min-h-0 flex-1 overflow-y-auto p-4">- <TaskRows- variant="List"- items={paneTodos.map((todo) => ({- key: todo.id,- label: todo.content,- status: todo.status === "in_progress" ? "in_progress" : todo.status === "completed" ? "completed" : "pending",- }))}- />- </div>- </aside>+ {!projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && tasksOpen && (+ <TasksSidebar items={paneTodos} onClose={() => setTasksOpen(false)} />)}</div>{terminalUsed && chatCwd && <TerminalPane key={chatCwd} cwd={chatCwd} visible={terminalVisible} onHide={() => setTerminalVisible(false)} />}diff --git a/apps/native/components/site/HarnessChrome.tsx b/apps/native/components/site/HarnessChrome.tsxindex 5d873f4a..5bfadc48 100644--- a/apps/native/components/site/HarnessChrome.tsx+++ b/apps/native/components/site/HarnessChrome.tsx@@ -11,11 +11,12 @@ type Props = {filesOpen: boolean; onFiles(): void; chatCwd?: string; workspaceName: string; onFolder(): void;openChanges(): void; browserOpen: boolean; onBrowser(): void; pinCount: number;terminalVisible: boolean; toggleTerminal(): void; agentsOpen: boolean; onAgents(): void; workingAgents?: number;+ tasksOpen?: boolean; taskCount?: number; onTasks?: () => void; splitNotice?: string | null;};export default function HarnessChrome({chats, activeId, busyIds, focusChat, closeChat, newChat,conversationsOpen, openConversations, split, toggleSplit, filesOpen, onFiles, chatCwd,workspaceName, onFolder, openChanges, browserOpen, onBrowser, pinCount, terminalVisible,- toggleTerminal, agentsOpen, onAgents, workingAgents = 0}: Props) {+ toggleTerminal, agentsOpen, onAgents, workingAgents = 0, tasksOpen = false, taskCount = 0, onTasks, splitNotice}: Props) {const frame = useRef<HTMLDivElement>(null);useEffect(() => { frame.current?.querySelector(`[data-tab-id="${activeId}"]`)?.scrollIntoView({block: "nearest", inline: "nearest"}); }, [activeId]);return (@@ -141,9 +142,16 @@ export default function HarnessChrome({chats, activeId, busyIds, focusChat, clos</button><button aria-label="Toggle terminal" aria-pressed={terminalVisible} title="Terminal (⌘J)" onClick={toggleTerminal} className="rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="m7 9 3 3-3 3m6 0h4"/></svg></button><button aria-label="Show agents" aria-pressed={agentsOpen} onClick={onAgents} className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="9" cy="7" r="3"/><path d="M3 20v-3a6 6 0 0 1 12 0v3M16 4a3 3 0 0 1 0 6M18 14a5 5 0 0 1 3 4v2"/></svg><span data-toolbar-label>Agents{workingAgents > 0 ? ` (${workingAgents})` : ""}</span>{workingAgents > 0 && <span className="size-1.5 shrink-0 animate-pulse rounded-full" style={{ background: "var(--accent)" }} aria-hidden />}</button>+ {onTasks && (+ <button type="button" aria-pressed={tasksOpen} aria-label="Show tasks" title="Tasks — open on demand, not when a chat has a list" disabled={taskCount === 0 && !tasksOpen} onClick={onTasks}+ className={`flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs hover:bg-hover disabled:opacity-40 ${tasksOpen ? "bg-hover-2 text-ink" : "text-ink-2"}`}>+ <span data-toolbar-label>Tasks{taskCount > 0 ? ` (${taskCount})` : ""}</span>+ </button>+ )}<ThemeToggle /><DesktopSettings /></div>+ {splitNotice && <p role="status" data-split-limit className="border-t border-line px-3 py-1.5 text-[12px] text-ink-2">{splitNotice}</p>}</div>);diff --git a/apps/native/components/site/TasksSidebar.tsx b/apps/native/components/site/TasksSidebar.tsxnew file mode 100644index 00000000..22d9a7ac--- /dev/null+++ b/apps/native/components/site/TasksSidebar.tsx@@ -0,0 +1,38 @@+"use client";++import TaskRows from "@/components/primitives/TaskRows";++export type TaskItem = { id: string; content: string; status: string };++export default function TasksSidebar({ items, onClose }: { items: TaskItem[]; onClose: () => void }) {+ if (items.length === 0) return null;+ return (+ <aside+ data-tasks-sidebar+ className="hidden w-[360px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"+ style={{ animation: "fade-in 300ms ease both" }}+ >+ <div className="flex h-11 shrink-0 items-center justify-between border-b border-line px-4">+ <span className="text-[13px] font-semibold text-ink">Tasks</span>+ <button+ type="button"+ aria-label="Close tasks"+ onClick={onClose}+ className="flex size-7 items-center justify-center rounded-[6px] text-ink-3 hover:bg-hover hover:text-ink"+ >+ ×+ </button>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-4">+ <TaskRows+ variant="List"+ items={items.map((todo) => ({+ key: todo.id,+ label: todo.content,+ status: todo.status === "in_progress" ? "in_progress" : todo.status === "completed" ? "completed" : "pending",+ }))}+ />+ </div>+ </aside>+ );+}diff --git a/apps/native/components/site/TurnActivity.tsx b/apps/native/components/site/TurnActivity.tsxindex d1503249..f93ccd95 100644--- a/apps/native/components/site/TurnActivity.tsx+++ b/apps/native/components/site/TurnActivity.tsx@@ -2,7 +2,7 @@import { useEffect, useState } from "react";import type { AssistantTurn } from "@/lib/acp";import { turnActivity } from "@/lib/turn-activity";-export default function TurnActivity({ turn }: { turn: AssistantTurn }) {+export default function TurnActivity({ turn, snapshot }: { turn: AssistantTurn; snapshot?: boolean }) {const [now, setNow] = useState(Date.now);const active = turn.status === "thinking" || turn.status === "streaming";useEffect(() => {@@ -16,7 +16,7 @@ export default function TurnActivity({ turn }: { turn: AssistantTurn }) {return () => { clearInterval(timer); document.removeEventListener("visibilitychange", sync); };}, [active]);if (!turn.startedAt && !active && !turn.error) return null;- const activity = turnActivity(turn, now);+ const activity = turnActivity(turn, now, snapshot ? { snapshot: true } : undefined);return <div data-turn-activity={activity.state} className={`mt-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] ${activity.state === "error" ? "text-red" : activity.live ? "text-ink-2" : "text-ink-3"}`}>{activity.live ? <span aria-hidden="true" className="size-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-r-transparent motion-reduce:animate-none" /> : <span aria-hidden="true">{activity.state === "error" ? "!" : activity.label === "Stopped" ? "■" : "✓"}</span>}<span role="status" aria-live="polite">{activity.label}</span><span aria-hidden="true">·</span><span data-activity-detail className="tabular-nums">{activity.detail}</span>diff --git a/apps/native/components/site/WorkspaceDialog.tsx b/apps/native/components/site/WorkspaceDialog.tsxindex ba5190f6..6a738872 100644--- a/apps/native/components/site/WorkspaceDialog.tsx+++ b/apps/native/components/site/WorkspaceDialog.tsx@@ -152,10 +152,7 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPiconst go = useCallback(async (target: string, opts: { pick?: boolean; refresh?: boolean } = {}) => {const n = (seq.current += 1);const refresh = opts.refresh === true;- if (!refresh) {- setBusy(true);- setListing(null);- }+ if (!refresh) setBusy(true);setError(null);try {const next = await browseFolders(target);diff --git a/apps/native/components/site/harness-split.test.ts b/apps/native/components/site/harness-split.test.tsnew file mode 100644index 00000000..766447ad--- /dev/null+++ b/apps/native/components/site/harness-split.test.ts@@ -0,0 +1,13 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { MAX_COLUMNS, SPLIT_LIMIT_MESSAGE, splitLimitReached } from "./harness-split.ts";++describe("split pane cap", () => {+ it("is four and names the readability limit", () => {+ assert.equal(MAX_COLUMNS, 4);+ assert.equal(splitLimitReached(3), false);+ assert.equal(splitLimitReached(4), true);+ assert.equal(splitLimitReached(5), true);+ assert.match(SPLIT_LIMIT_MESSAGE, /four panes/i);+ });+});diff --git a/apps/native/components/site/harness-split.ts b/apps/native/components/site/harness-split.tsnew file mode 100644index 00000000..f82c078b--- /dev/null+++ b/apps/native/components/site/harness-split.ts@@ -0,0 +1,9 @@+/** Columns the split view will show at once, the active chat included.+ * Past four, panes are too narrow to read. */+export const MAX_COLUMNS = 4;++export const SPLIT_LIMIT_MESSAGE = "Four panes is the limit so each chat stays readable.";++export function splitLimitReached(visible: number): boolean {+ return visible >= MAX_COLUMNS;+}diff --git a/apps/native/components/site/harness-types.ts b/apps/native/components/site/harness-types.tsindex e59f8934..a8a3483b 100644--- a/apps/native/components/site/harness-types.ts+++ b/apps/native/components/site/harness-types.ts@@ -9,7 +9,9 @@ export type Msg =export type Chat = { id: number; title: string | null; messages: Msg[]; model?: string; session?: string; cwd?: string;/** The model named this tab from its first prompt: the session poller,* which reads graff's own saved title, must leave it alone. */- titledByModel?: boolean };+ titledByModel?: boolean;+ /** Opened from a saved file — live REPL status is unknown (#839). */+ snapshot?: boolean };export function newPageToken(): string {return Math.random().toString(36).slice(2, 10);diff --git a/apps/native/electron/agents-visual.cjs b/apps/native/electron/agents-visual.cjsindex 7f717a0d..dc8bb18e 100644--- a/apps/native/electron/agents-visual.cjs+++ b/apps/native/electron/agents-visual.cjs@@ -6,7 +6,7 @@ async function runAgentVisuals({ win, origin, output }) {const selectChild = id => js(`(()=>{const id=${JSON.stringify(id)}, button=document.querySelector('[data-child-agent="'+id+'"]');if(button){button.click();return;}const select=document.querySelector('[aria-label="Select sub-agent"]');Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(select,id);select.dispatchEvent(new Event('change',{bubbles:true}));})()`);const wait = async source => { for (let i = 0; i < 200; i++) { if (await js(source)) return; await new Promise(r => setTimeout(r, 40)); } console.error(await js('document.body.innerText')); fs.writeFileSync(path.join(output, 'agents-failed.png'), (await win.webContents.capturePage()).toPNG()); throw Error(`Agent visual timeout: ${source}`); };win.webContents.on('console-message', (_e, level, message) => { if (level >= 2) console.error('Agent fixture:', message); });- win.show(); win.focus();+ require('./test-window.cjs').presentWindow(win);await win.loadURL(`${origin}/visual-tests/agents`);await wait(`document.body.textContent.includes('Implement navigation')`);assert.equal(await js(`document.querySelector('button[type="submit"]').disabled`), true);diff --git a/apps/native/electron/browser-visual.cjs b/apps/native/electron/browser-visual.cjsindex 1130d7b6..c78a4b5e 100644--- a/apps/native/electron/browser-visual.cjs+++ b/apps/native/electron/browser-visual.cjs@@ -13,7 +13,8 @@ async function runBrowserVisuals({ win: fixtureWindow, origin, output }) {});await new Promise(r => fixture.listen(0, '127.0.0.1', r));const url = `http://127.0.0.1:${fixture.address().port}/`;- const win = new BrowserWindow({ width: 1000, height: 760, show: true, webPreferences: { preload: path.join(__dirname, 'preload.cjs'), sandbox: true, contextIsolation: true } });+ const { presentWindow, testWindowOptions } = require('./test-window.cjs');+ const win = new BrowserWindow(testWindowOptions({ width: 1000, height: 760, webPreferences: { preload: path.join(__dirname, 'preload.cjs'), sandbox: true, contextIsolation: true } }));const wc = win.webContents, js = code => wc.executeJavaScript(code);const browser = new BrowserTabs(win, event => wc.send('browser-event', event));ipcMain.handle('browser', (_event, { chat, method, params }) => ['find', 'zoom'].includes(method) ? browserAction(browser, chat, method, params) : browser.command(chat, method, params));@@ -30,7 +31,7 @@ async function runBrowserVisuals({ win: fixtureWindow, origin, output }) {await wait(async () => !page.isLoading());await js(`document.querySelector('button[aria-pressed]').click()`);await wait(() => js(`document.querySelector('button[aria-pressed]').getAttribute('aria-pressed')==='true'`));- win.focus(); page.focus();+ presentWindow(win); page.focus();page.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });await wait(() => js(`document.querySelector('button[aria-pressed]').getAttribute('aria-pressed')==='false'`));await js(`document.querySelector('button[aria-pressed]').click()`); await sleep(100);@@ -66,7 +67,7 @@ async function runBrowserVisuals({ win: fixtureWindow, origin, output }) {console.log('Browser visuals passed: pin/cancel/numbered markers/remove, no target activation, zoom geometry, real and hidden PNG captures, suspended errors.');} finally {ipcMain.removeHandler('browser'); ipcMain.removeListener('browser-pin', pin); ipcMain.removeListener('browser-pick-cancelled', cancelled);- browser.closeAll(); win.destroy(); fixture.close(); fixtureWindow.show();+ browser.closeAll(); win.destroy(); fixture.close(); presentWindow(fixtureWindow);}}module.exports = { runBrowserVisuals };diff --git a/apps/native/electron/build.sh b/apps/native/electron/build.shindex 2a53dd9e..6ee2e84e 100644--- a/apps/native/electron/build.sh+++ b/apps/native/electron/build.sh@@ -47,6 +47,16 @@ xcrun clang -O2 -bundle -undefined dynamic_lookup -mmacosx-version-min=14.0 \/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $version" "$bundle/Contents/Info.plist"/usr/libexec/PlistBuddy -c 'Set :LSMinimumSystemVersion 14.0' "$bundle/Contents/Info.plist"/usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Codegraff' "$bundle/Contents/Info.plist" 2>/dev/null || true+macos="$bundle/Contents/MacOS"+if [[ -e "$macos/Electron" ]]; then+ mv "$macos/Electron" "$macos/Codegraff"+fi+/usr/libexec/PlistBuddy -c 'Set :CFBundleExecutable Codegraff' "$bundle/Contents/Info.plist"+exec_name="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$bundle/Contents/Info.plist")"+if [[ "$exec_name" == "Electron" || -e "$macos/Electron" || ! -x "$macos/Codegraff" ]]; then+ echo "Distribution builds must not retain the development executable name (Electron)." >&2+ exit 1+fibun "$here/build-icon.cjs" "$resources/electron.icns"# Local development signing; production notarization remains a separate release step.codesign --force --deep --sign - "$bundle"diff --git a/apps/native/electron/chat-scroll-visual.cjs b/apps/native/electron/chat-scroll-visual.cjsindex 5dc31ce1..36421203 100644--- a/apps/native/electron/chat-scroll-visual.cjs+++ b/apps/native/electron/chat-scroll-visual.cjs@@ -11,7 +11,7 @@ async function runChatScroll({ win, origin, output }) {}throw Error(`Chat scroll timed out: ${code}`);};- await wc.loadURL(origin); win.setSize(1100, 760); win.show(); win.focus();+ await wc.loadURL(origin); win.setSize(1100, 760); require('./test-window.cjs').presentWindow(win);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);await js(`(() => {const previous = window.fetch;diff --git a/apps/native/electron/composer-visual.cjs b/apps/native/electron/composer-visual.cjsindex 3346d498..ea8b9650 100644--- a/apps/native/electron/composer-visual.cjs+++ b/apps/native/electron/composer-visual.cjs@@ -3,7 +3,7 @@ const fs = require('node:fs');const path = require('node:path');async function runComposerVisual({ win, output }) {const js = code => win.webContents.executeJavaScript(code);- win.show(); win.focus(); win.webContents.focus();+ require('./test-window.cjs').presentWindow(win);await new Promise(r => setTimeout(r, 1600));await js(`document.querySelector('[aria-label="Choose model"] span.truncate').textContent='Example model with a long display name'`);for (const width of [220, 280, 360, 420, 520]) {diff --git a/apps/native/electron/dev-preview-visual.cjs b/apps/native/electron/dev-preview-visual.cjsindex c5156739..3ab55f04 100644--- a/apps/native/electron/dev-preview-visual.cjs+++ b/apps/native/electron/dev-preview-visual.cjs@@ -14,7 +14,9 @@ async function runDevPreview({ output }) {fs.writeFileSync(path.join(root, 'index.html'), html('Initial preview'));const bun = process.env.GRAFF_TEST_BUN || 'bun';const child = spawn(bun, ['run', 'dev'], { cwd: root, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PATH: `${path.dirname(bun)}:${process.env.PATH}` } });- const win = new BrowserWindow({ width: 900, height: 600, show: true });+ const { presentWindow, testWindowOptions } = require('./test-window.cjs');+ const win = new BrowserWindow(testWindowOptions({ width: 900, height: 600 }));+ presentWindow(win);const events = [], browser = new BrowserTabs(win, event => events.push(event));let bridge;try {diff --git a/apps/native/electron/gui-coding-smoke.cjs b/apps/native/electron/gui-coding-smoke.cjsindex a6d8cdfb..e5e05e23 100644--- a/apps/native/electron/gui-coding-smoke.cjs+++ b/apps/native/electron/gui-coding-smoke.cjs@@ -22,9 +22,10 @@ app.whenReady().then(async()=>{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 {presentWindow,testWindowOptions}=require('./test-window.cjs');+ win=new BrowserWindow(testWindowOptions({width:1440,height:920,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration: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"]')`);+ await win.loadURL(origin);presentWindow(win);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.');diff --git a/apps/native/electron/navigation-keyboard-visual.cjs b/apps/native/electron/navigation-keyboard-visual.cjsindex 7b7d6082..d5297ee2 100644--- a/apps/native/electron/navigation-keyboard-visual.cjs+++ b/apps/native/electron/navigation-keyboard-visual.cjs@@ -18,7 +18,7 @@ async function runNavigationKeyboard({win, origin}) {const modalContainsFocus = () => js(`document.querySelector('[aria-modal="true"]')?.contains(document.activeElement)`);const focusDiagnostic = () => js(`JSON.stringify({hasFocus:document.hasFocus(),active:document.activeElement?.outerHTML.slice(0,2500),modal:document.querySelector('[aria-modal="true"]')?.getAttribute('aria-label')})`);- await wc.loadURL(origin); win.show(); win.focus();+ await wc.loadURL(origin); require('./test-window.cjs').presentWindow(win);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);wc.send('desktop-action', 'new');await wait(`document.querySelectorAll('[aria-label="Close tab"]').length===2`);diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjsindex 4b94d11e..c26d4cbb 100644--- a/apps/native/electron/navigation-visual.cjs+++ b/apps/native/electron/navigation-visual.cjs@@ -4,7 +4,8 @@ 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}});+ const {presentWindow,testWindowOptions}=require('./test-window.cjs');+ const win=new BrowserWindow(testWindowOptions({width:1100,height:760,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false}}));installWindowState(win);ipcMain.handle('browser',()=>null);// The demo workspace name maps to a disposable real folder for PTY checks.const terminalRoot=path.join(output,'terminal-workspace');fs.mkdirSync(terminalRoot,{recursive:true});@@ -24,7 +25,7 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {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;data.result.current.model='example-model-with-a-long-name';data.result.models[0].name=data.result.current.model;return new Response(JSON.stringify(data),{headers:{'content-type':'application/json'}});}return response;};`});- await wc.loadURL(origin);win.focus();await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ await wc.loadURL(origin);presentWindow(win);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);if(process.env.GRAFF_VISUAL_SUITE==='splits'){await require('./split-focus-visual.cjs').runSplitFocus({win,origin,output});return;}const interactions = async () => {await require('./navigation-keyboard-visual.cjs').runNavigationKeyboard({win,origin});@@ -65,6 +66,6 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {assert.equal(await js(`!!document.querySelector('[data-workspace-menu]')`),false);if(process.platform==='darwin')await require('./terminal-visual.cjs').runTerminalVisual({win,output});console.log('Navigation visual checks passed: command catalog/new tabs, bounded keyboard menu, new/close/reopen, splits/zoom/resize, workspace search.');- } finally {terminals.closeAll();ipcMain.removeHandler('terminal');ipcMain.removeHandler('browser');win.destroy();fixtureWindow.show();fixtureWindow.focus();}+ } finally {terminals.closeAll();ipcMain.removeHandler('terminal');ipcMain.removeHandler('browser');win.destroy();presentWindow(fixtureWindow);}}module.exports={runNavigationVisuals};diff --git a/apps/native/electron/performance-benchmark.cjs b/apps/native/electron/performance-benchmark.cjsindex 7a88c701..aa246fca 100644--- a/apps/native/electron/performance-benchmark.cjs+++ b/apps/native/electron/performance-benchmark.cjs@@ -40,9 +40,9 @@ app.whenReady().then(async () => {if (i === 199) throw Error('Benchmark server did not start');await sleep(100);}- win = new BrowserWindow({ width: 1440, height: 920, show: true, titleBarStyle: 'hiddenInset',- webPreferences: { preload: path.join(root, 'electron/preload.cjs'), sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: true } });- app.focus({ steal: true }); win.show(); win.focus();+ win = new BrowserWindow(require('./test-window.cjs').testWindowOptions({ width: 1440, height: 920, titleBarStyle: 'hiddenInset',+ webPreferences: { preload: path.join(root, 'electron/preload.cjs'), sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: true } }));+ require('./test-window.cjs').presentWindow(win, app);const wc = win.webContents, js = code => wc.executeJavaScript(code);await wc.loadURL('about:blank');wc.on('console-message', event => { if (/Error|error|Illegal/.test(event.message || '')) console.error('Benchmark renderer:', event.message); });diff --git a/apps/native/electron/performance-scenarios.cjs b/apps/native/electron/performance-scenarios.cjsindex e583aeca..7f7463d0 100644--- a/apps/native/electron/performance-scenarios.cjs+++ b/apps/native/electron/performance-scenarios.cjs@@ -9,8 +9,9 @@ const { chromiumSample } = require('./hardware-profile.cjs');const { installGalleryFixture } = require('./gallery-fixture.cjs');const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));async function runPerformance({ win: fixtureWindow, origin, output }) {- const 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 } });+ const { presentWindow, testWindowOptions } = require('./test-window.cjs');+ const win = new BrowserWindow(testWindowOptions({ width: 1440, height: 920, titleBarStyle: 'hiddenInset',+ webPreferences: { preload: path.join(__dirname, 'preload.cjs'), sandbox: true, contextIsolation: true, nodeIntegration: false } }));fixtureWindow.destroy();await win.loadURL('about:blank');ipcMain.handle('browser', () => null);@@ -22,7 +23,7 @@ async function runPerformance({ win: fixtureWindow, origin, output }) {wc.debugger.attach('1.3');await wc.debugger.sendCommand('Page.enable');await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `(${installGalleryFixture.toString()})()` });- win.setSize(1440, 920); win.show(); win.focus();+ win.setSize(1440, 920); presentWindow(win);const sampleTree = intervalSampler(process.pid, () => 0);const profiler = new Profiler(async () => ({ ...await sampleTree(), ...await rendererSample(wc), ...chromiumSample(app.getAppMetrics()) }), enabled => { wc.send('profile-enabled', enabled); }, () => app.getGPUFeatureStatus());const longTask = (event, duration) => { if (event.sender === wc && Number.isFinite(duration)) profiler.record('renderer-long-task', duration); };diff --git a/apps/native/electron/policy.cjs b/apps/native/electron/policy.cjsindex c7b6231e..444695d0 100644--- a/apps/native/electron/policy.cjs+++ b/apps/native/electron/policy.cjs@@ -1,10 +1,26 @@const { timingSafeEqual } = require('node:crypto');+function looksLikeWebAddress(text) {+ if (!text || /\s/.test(text)) return false;+ if (/^(file|javascript|data|blob):/i.test(text) || /^[a-z][\w+.-]*:\/\//i.test(text)) return true;+ if (/^(about|data|blob|file|javascript):/i.test(text)) return true;+ if (/^(localhost|127\.0\.0\.1|\[::1\]|\d+\.\d+\.\d+\.\d+)(:|\/|$)/.test(text)) return true;+ if (/^[\w-]+(\.[\w-]+)+(:\d+)?([/?#]|$)/i.test(text)) return true;+ if (/^[\w.-]+:\d+([/?#]|$)/.test(text)) return true;+ return false;+}+function pageURL(raw) {const text = String(raw || '').trim();if (!text || text === 'about:blank') return 'about:blank';+ if (/^(file|javascript|data|blob):/i.test(text)) throw new Error('Only HTTP and HTTPS pages are supported');const local = /^(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(text);- const url = new URL(/^[a-z][\w+.-]*:/i.test(text) && !local ? text : `${local ? 'http' : 'https'}://${text}`);+ const candidate = looksLikeWebAddress(text)+ ? (/^[a-z][\w+.-]*:/i.test(text) && !local ? text : `${local ? 'http' : 'https'}://${text}`)+ : `https://www.google.com/search?q=${encodeURIComponent(text)}`;+ let url;+ try { url = new URL(candidate); }+ catch { throw new Error('Enter a web address or a search.'); }if (!['https:', 'http:'].includes(url.protocol)) throw new Error('Only HTTP and HTTPS pages are supported');if (url.username || url.password) throw new Error('Use the page sign-in form');return url.href;diff --git a/apps/native/electron/policy.test.cjs b/apps/native/electron/policy.test.cjsindex fa1ed650..9134e18c 100644--- a/apps/native/electron/policy.test.cjs+++ b/apps/native/electron/policy.test.cjs@@ -6,6 +6,11 @@ test('browser navigation permits web pages and local development, never executabassert.equal(pageURL('localhost:8080/demo'), 'http://localhost:8080/demo');for (const url of ['file:///etc/passwd', 'javascript:alert(1)', 'data:text/html,hi', 'https://name:[email protected]']) assert.throws(() => pageURL(url));});+test('ordinary words become a search instead of Invalid URL (#823)', () => {+ assert.equal(pageURL('zig comptime'), 'https://www.google.com/search?q=zig%20comptime');+ assert.equal(pageURL('hello'), 'https://www.google.com/search?q=hello');+ assert.match(pageURL('what is https'), /^https:\/\/www\.google\.com\/search\?q=/);+});test('browser automation requires its bearer token and rejects web origins', () => {assert.equal(authorized({ headers: { authorization: 'Bearer secret' } }, 'secret'), true);for (const headers of [{}, { authorization: 'Bearer wrong' }, { authorization: 'Bearer secret', origin: 'https://example.com' }]) assert.equal(authorized({ headers }, 'secret'), false);diff --git a/apps/native/electron/project-recovery-visual.cjs b/apps/native/electron/project-recovery-visual.cjsindex 7e3b527b..cc99dcd2 100644--- a/apps/native/electron/project-recovery-visual.cjs+++ b/apps/native/electron/project-recovery-visual.cjs@@ -135,7 +135,7 @@ async function runProjectRecovery({ win, origin, output }) {assert.ok(await js(`document.querySelector('[data-project-context]').textContent.includes('/demo/recovered')`),'A late folder listing cannot replace the chosen folder');await wc.loadURL(origin);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);- win.show(); win.focus();+ require('./test-window.cjs').presentWindow(win);console.log('Project recovery passed: initial/paged retry, stale searches, resume retry/cancel, navigation races, and typed folder validation.');}module.exports={runProjectRecovery};diff --git a/apps/native/electron/review-recovery-visual.cjs b/apps/native/electron/review-recovery-visual.cjsindex 6f9bfcef..cffa6dec 100644--- a/apps/native/electron/review-recovery-visual.cjs+++ b/apps/native/electron/review-recovery-visual.cjs@@ -51,7 +51,7 @@ async function runReviewRecovery({ win, origin, output }) {assert.ok(await js(`document.querySelector('[aria-label="File diff"]').textContent.includes('Changes unavailable')`),'Diff failures must not masquerade as binary files');await wc.loadURL(origin);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);- win.focus();+ require('./test-window.cjs').presentWindow(win);console.log('Review recovery passed: unavailable vs clean, explicit retry, stale filters/worktrees, and diff failures.');}module.exports={runReviewRecovery};diff --git a/apps/native/electron/smoke-desktop.cjs b/apps/native/electron/smoke-desktop.cjsindex 5baa7524..d1c50b0d 100644--- a/apps/native/electron/smoke-desktop.cjs+++ b/apps/native/electron/smoke-desktop.cjs@@ -46,7 +46,7 @@ async function smokeDesktop({ automation, computer, win, browser }) {computer.enabled = true;try {const wc = browser.tabs.get('smoke').view.webContents;- win.show(); win.focus(); wc.focus();+ require('./test-window.cjs').presentWindow(win);await wc.executeJavaScript("document.querySelector('#name').focus();document.querySelector('#name').select()");await new Promise(resolve => setTimeout(resolve, 300));const tree = await computer.command('snapshot', { pid: process.pid });diff --git a/apps/native/electron/smoke-launch.cjs b/apps/native/electron/smoke-launch.cjsindex 7523e64b..92e0942c 100644--- a/apps/native/electron/smoke-launch.cjs+++ b/apps/native/electron/smoke-launch.cjs@@ -17,12 +17,15 @@ async function run({ win, backend, browser }) {assert.equal(browser.liveCount, 0, 'An empty app must not create browser views');assert.equal((await fetch(`${backend.origin}/api/acp`)).status, 403);assert.equal(await js(`fetch('/api/acp').then(response => response.status)`), 200);+ const { app } = require('electron');+ assert.equal(app.isPackaged, true, 'Packaged launch must report isPackaged');+ assert.notEqual(path.basename(process.execPath), 'Electron', 'Packaged executable must not keep the development name');const resources = process.env.GRAFF_ELECTRON_RESOURCES || process.resourcesPath;const native = require(path.join(resources, 'native/activity.node'));assert.equal(typeof native.show, 'function');const version = execFileSync(path.join(resources, 'graff'), ['--version'], { encoding: 'utf8', timeout: 10000 }).trim();assert.match(version, /graff/i);- const report = { passed: ['bundled server', 'production composer', 'empty browser lifecycle', 'request authentication', 'native module ABI', 'bundled engine executable'], version };+ const report = { passed: ['bundled server', 'production composer', 'empty browser lifecycle', 'request authentication', 'native module ABI', 'bundled engine executable', 'packaged executable'], version };fs.writeFileSync(process.env.GRAFF_ELECTRON_SMOKE, JSON.stringify(report, null, 2));console.log('Packaged launch checks passed. No prompt sent or coding setting changed.');}diff --git a/apps/native/electron/smoke-ui.cjs b/apps/native/electron/smoke-ui.cjsindex 4240acd3..70a6c938 100644--- a/apps/native/electron/smoke-ui.cjs+++ b/apps/native/electron/smoke-ui.cjs@@ -1,7 +1,7 @@const assert = require('node:assert/strict');const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));async function smokeUI({ win, browser, backend }) {- require('electron').app.focus({ steal: true }); win.show(); win.focus();+ require('./test-window.cjs').presentWindow(win, require('electron').app);const js = expression => win.webContents.executeJavaScript(expression);const wait = async expression => {for (let n = 0; n < 100; n++) { if (await js(expression)) return; await sleep(100); }diff --git a/apps/native/electron/smoke.cjs b/apps/native/electron/smoke.cjsindex baa51e42..d90236f4 100644--- a/apps/native/electron/smoke.cjs+++ b/apps/native/electron/smoke.cjs@@ -52,7 +52,7 @@ async function run({ win, browser, automation, backend, metrics, activity, compuawait browser.command('smoke', 'pick', { enabled: true });const wc = browser.tabs.get('smoke').view.webContents;const point = await wc.executeJavaScript('(()=>{const r=document.querySelector("#button").getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()');- win.show(); win.focus(); wc.focus(); await sleep(300);+ require('./test-window.cjs').presentWindow(win); await sleep(300);wc.sendInputEvent({type:'mouseMove', ...point});wc.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 });wc.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 });diff --git a/apps/native/electron/split-focus-visual.cjs b/apps/native/electron/split-focus-visual.cjsindex 23156543..f27978b5 100644--- a/apps/native/electron/split-focus-visual.cjs+++ b/apps/native/electron/split-focus-visual.cjs@@ -11,7 +11,7 @@ async function runSplitFocus({win,origin,output}) {wc.sendInputEvent({type:'mouseDown',button:'left',clickCount:1,...point});wc.sendInputEvent({type:'mouseUp',button:'left',clickCount:1,...point});await new Promise(r=>setTimeout(r,100));};- await wc.loadURL(origin);win.setSize(1440,900);win.show();win.focus();+ await wc.loadURL(origin);win.setSize(1440,900);require('./test-window.cjs').presentWindow(win);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);await key('d',{metaKey:true});await key('d',{metaKey:true});await wait(`document.querySelectorAll('[data-chat]').length===3`);diff --git a/apps/native/electron/stress-visual.cjs b/apps/native/electron/stress-visual.cjsindex 2b548c0d..b0b83249 100644--- a/apps/native/electron/stress-visual.cjs+++ b/apps/native/electron/stress-visual.cjs@@ -5,7 +5,8 @@ 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, fullscreen = true}) {- 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}});+ const {presentWindow,testWindowOptions}=require('./test-window.cjs');+ const win = new BrowserWindow(testWindowOptions({width:1000,height:760,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration: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}`);};@@ -17,7 +18,7 @@ async function runStressVisuals({win: fixtureWindow, origin, output, fullscreenassert.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`);+ fixtureWindow.hide();presentWindow(win);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');@@ -51,7 +52,7 @@ async function runStressVisuals({win: fixtureWindow, origin, output, fullscreenassert.equal(await titleHeight(),36);const checkedFullscreen = fullscreen && process.platform === 'darwin';if(checkedFullscreen) {- win.show(); win.focus(); win.webContents.focus();+ require('./test-window.cjs').presentWindow(win);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());@@ -60,6 +61,6 @@ async function runStressVisuals({win: fixtureWindow, origin, output, fullscreen}fs.writeFileSync(path.join(output,'stress-results.json'),JSON.stringify({passed:['5000 tools','bounded output','1000 messages','unbroken input','long markdown','stream reading position',...(checkedFullscreen?['fullscreen and reload']:[])],fullscreen:checkedFullscreen?'passed':'not run',metrics},null,2));console.log('Stress visual checks passed: long tools/output/history/text, reading position. Fullscreen:', checkedFullscreen?'passed':'not run in this suite');- } finally {win.destroy();fixtureWindow.show();fixtureWindow.focus();}+ } finally {win.destroy();presentWindow(fixtureWindow);}}module.exports={runStressVisuals};diff --git a/apps/native/electron/test-window.cjs b/apps/native/electron/test-window.cjsnew file mode 100644index 00000000..4024caf5--- /dev/null+++ b/apps/native/electron/test-window.cjs@@ -0,0 +1,27 @@+/** Default GUI tests stay off the user's desktop (#832). Foreground+ * interaction is opt-in via GRAFF_ELECTRON_FOREGROUND=1. */++function testWindowMode() {+ if (process.env.GRAFF_ELECTRON_FOREGROUND === '1') return 'foreground';+ if (process.env.GRAFF_ELECTRON_VISIBLE === '1') return 'visible';+ return 'hidden';+}++function presentWindow(win, app) {+ const mode = testWindowMode();+ if (win.webContents && !win.webContents.isDestroyed()) win.webContents.setBackgroundThrottling(false);+ if (mode === 'foreground') {+ app?.focus?.({ steal: true });+ win.show();+ win.focus();+ } else if (mode === 'visible') {+ win.showInactive();+ }+ return mode;+}++function testWindowOptions(extra = {}) {+ return { show: false, ...extra, webPreferences: { backgroundThrottling: false, ...(extra.webPreferences || {}) } };+}++module.exports = { testWindowMode, presentWindow, testWindowOptions };diff --git a/apps/native/electron/test-window.test.cjs b/apps/native/electron/test-window.test.cjsnew file mode 100644index 00000000..ddd9413d--- /dev/null+++ b/apps/native/electron/test-window.test.cjs@@ -0,0 +1,26 @@+const { test, expect } = require('bun:test');+const { testWindowMode, presentWindow, testWindowOptions } = require('./test-window.cjs');++test('default GUI tests stay hidden and never steal focus (#832)', () => {+ const previous = process.env.GRAFF_ELECTRON_FOREGROUND;+ const visible = process.env.GRAFF_ELECTRON_VISIBLE;+ delete process.env.GRAFF_ELECTRON_FOREGROUND;+ delete process.env.GRAFF_ELECTRON_VISIBLE;+ expect(testWindowMode()).toBe('hidden');+ expect(testWindowOptions({ width: 10 }).show).toBe(false);+ const calls = [];+ presentWindow({ show() { calls.push('show'); }, focus() { calls.push('focus'); }, showInactive() { calls.push('inactive'); }, webContents: { isDestroyed: () => false, setBackgroundThrottling() {} } }, { focus() { calls.push('steal'); } });+ expect(calls).toEqual([]);+ process.env.GRAFF_ELECTRON_FOREGROUND = previous;+ process.env.GRAFF_ELECTRON_VISIBLE = visible;+});++test('foreground interaction is an explicit opt-in', () => {+ const previous = process.env.GRAFF_ELECTRON_FOREGROUND;+ process.env.GRAFF_ELECTRON_FOREGROUND = '1';+ expect(testWindowMode()).toBe('foreground');+ const calls = [];+ presentWindow({ show() { calls.push('show'); }, focus() { calls.push('focus'); }, showInactive() { calls.push('inactive'); }, webContents: { isDestroyed: () => true } }, { focus() { calls.push('steal'); } });+ expect(calls).toEqual(['steal', 'show', 'focus']);+ process.env.GRAFF_ELECTRON_FOREGROUND = previous;+});diff --git a/apps/native/electron/updates-visual.cjs b/apps/native/electron/updates-visual.cjsindex 6bb75efc..5760d305 100644--- a/apps/native/electron/updates-visual.cjs+++ b/apps/native/electron/updates-visual.cjs@@ -1,7 +1,8 @@const { BrowserWindow } = require('electron');const assert = require('node:assert/strict'), fs = require('node:fs'), path = require('node:path');async function runUpdateVisuals({ origin, output }) {- const win = new BrowserWindow({ width: 900, height: 650, show: true, webPreferences: { sandbox: true, contextIsolation: true, backgroundThrottling: false } });+ const { presentWindow, testWindowOptions } = require('./test-window.cjs');+ const win = new BrowserWindow(testWindowOptions({ width: 900, height: 650, webPreferences: { sandbox: true, contextIsolation: true } }));const wc = win.webContents, js = source => wc.executeJavaScript(source);const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await new Promise(r => setTimeout(r, 30)); } throw Error(source); };try {@@ -19,7 +20,7 @@ async function runUpdateVisuals({ origin, output }) {return {...base(),status:'idle'};}};` });await win.loadURL(`${origin}/visual-tests`);- win.focus();+ presentWindow(win);console.log('Update visual fixture loaded.');await wait(`!!document.querySelector('[data-case="waiting"]')`);for (const status of ['checking', 'error', 'current']) {diff --git a/apps/native/electron/updates.cjs b/apps/native/electron/updates.cjsindex c8647db7..cde38757 100644--- a/apps/native/electron/updates.cjs+++ b/apps/native/electron/updates.cjs@@ -4,8 +4,29 @@ const path = require('node:path');const FIRST_CHECK_MS = 30_000;const POLL_MS = 6 * 60 * 60 * 1000;-function createUpdates({ updater, version, available = true, automatic = true, notify, save = () => {}, onReady }) {- let state = { status: available ? 'idle' : 'unavailable', currentVersion: version, automatic, interactive: false };+function unavailableMessage(reason) {+ return {+ smoke: 'Update checks are disabled in this test build.',+ platform: 'Automatic updates are available on the macOS desktop app.',+ unpackaged: 'This build is not a packaged Codegraff app, so updates are disabled.',+ volume: 'Move Codegraff from the disk image into Applications, then check again.',+ config: 'This build has no update configuration.',+ }[reason] || 'Install a signed release in Applications to receive updates.';+}++function updateAvailability({ app, resources, env = process.env, execPath = process.execPath, platform = process.platform }) {+ if (env.GRAFF_ELECTRON_SMOKE) return { available: false, reason: 'smoke' };+ if (platform !== 'darwin') return { available: false, reason: 'platform' };+ if (!app.isPackaged) return { available: false, reason: 'unpackaged' };+ if (String(execPath).startsWith('/Volumes/')) return { available: false, reason: 'volume' };+ if (!require('node:fs').existsSync(require('node:path').join(resources, 'app-update.yml'))) return { available: false, reason: 'config' };+ return { available: true, reason: null };+}++function createUpdates({ updater, version, available = true, automatic = true, notify, save = () => {}, onReady, unavailableReason }) {+ const blocked = !available;+ const blockedMessage = blocked ? unavailableMessage(unavailableReason) : undefined;+ let state = { status: available ? 'idle' : 'unavailable', currentVersion: version, automatic: available ? automatic : false, interactive: false, message: blockedMessage };let checking = false;const emit = patch => { state = { ...state, ...patch }; notify({ ...state }); };if (available) {@@ -38,7 +59,7 @@ function createUpdates({ updater, version, available = true, automatic = true, nif (interactive) emit({ interactive: true });return;}- if (!available) { emit({ interactive, message: 'Install a signed release in Applications to receive updates.' }); return; }+ if (!available) { emit({ interactive, message: blockedMessage }); return; }checking = true;emit({ status: 'checking', interactive, message: undefined });try {@@ -65,10 +86,10 @@ function installUpdates({ app, win, ipcMain, trusted, resources }) {const prefs = path.join(app.getPath('userData'), 'updates.json');let automatic = true;try { automatic = JSON.parse(fs.readFileSync(prefs, 'utf8')).automatic !== false; } catch {}- const available = app.isPackaged && process.platform === 'darwin' && !process.env.GRAFF_ELECTRON_SMOKE &&- !process.execPath.startsWith('/Volumes/') && fs.existsSync(path.join(resources, 'app-update.yml'));+ const gate = updateAvailability({ app, resources });+ const available = gate.available;let autoItem;- const controller = createUpdates({ version: app.getVersion(), automatic, available,+ const controller = createUpdates({ version: app.getVersion(), automatic, available, unavailableReason: gate.reason,updater: available ? require('./updater-runtime.cjs') : null,save: value => { fs.mkdirSync(path.dirname(prefs), { recursive: true }); fs.writeFileSync(prefs, JSON.stringify({ automatic: value })); },notify: state => {@@ -90,8 +111,8 @@ function installUpdates({ app, win, ipcMain, trusted, resources }) {}).catch(() => {});},});- autoItem = { label: 'Automatically Download Updates', type: 'checkbox', checked: automatic,- click: item => controller.setAutomatic(item.checked) };+ autoItem = { label: 'Automatically Download Updates', type: 'checkbox', checked: available && automatic,+ enabled: available, click: item => controller.setAutomatic(item.checked) };ipcMain.handle('updates', async (event, action, value) => {trusted(event);if (action === 'check') await controller.check(true);@@ -105,8 +126,8 @@ function installUpdates({ app, win, ipcMain, trusted, resources }) {first.unref(); repeat.unref();app.once('before-quit', () => { clearTimeout(first); clearInterval(repeat); });return [- { label: 'Check for Updates…', click: () => void controller.check(true) },+ { label: 'Check for Updates…', enabled: available, click: () => void controller.check(true) },autoItem,];}-module.exports = { createUpdates, installUpdates, FIRST_CHECK_MS, POLL_MS };+module.exports = { createUpdates, installUpdates, updateAvailability, unavailableMessage, FIRST_CHECK_MS, POLL_MS };diff --git a/apps/native/electron/updates.test.cjs b/apps/native/electron/updates.test.cjsindex 69c8739f..7bc58985 100644--- a/apps/native/electron/updates.test.cjs+++ b/apps/native/electron/updates.test.cjs@@ -28,12 +28,24 @@ test('downloads in the background but never interrupts a running task automaticaexpect(f.updates.state().status).toBe('installing');});test('development and disk-image builds do not make update requests', async () => {- const f = fixture({ available: false });+ const f = fixture({ available: false, unavailableReason: 'unpackaged' });await f.updates.check(true);expect(f.checks()).toBe(0);expect(f.updates.state().status).toBe('unavailable');+ expect(f.updates.state().automatic).toBe(false);+ expect(f.updates.state().message).toMatch(/not a packaged Codegraff app/);expect(() => f.updates.restart()).toThrow('No downloaded update');});++test('availability names the blocking condition instead of a signing warning (#829)', () => {+ const { updateAvailability, unavailableMessage } = require('./updates.cjs');+ expect(updateAvailability({ app: { isPackaged: false }, resources: '/tmp', env: {}, platform: 'darwin', execPath: '/Apps/Codegraff' }).reason).toBe('unpackaged');+ expect(updateAvailability({ app: { isPackaged: true }, resources: '/tmp', env: {}, platform: 'linux', execPath: '/usr/bin/codegraff' }).reason).toBe('platform');+ expect(updateAvailability({ app: { isPackaged: true }, resources: '/tmp', env: {}, platform: 'darwin', execPath: '/Volumes/Codegraff/Codegraff' }).reason).toBe('volume');+ expect(updateAvailability({ app: { isPackaged: true }, resources: '/tmp', env: { GRAFF_ELECTRON_SMOKE: '1' }, platform: 'darwin', execPath: '/Apps/Codegraff' }).reason).toBe('smoke');+ expect(unavailableMessage('volume')).toMatch(/disk image/);+ expect(unavailableMessage('config')).toMatch(/update configuration/);+});test('offline checks recover and do not expose raw request details in the UI', async () => {const f = fixture();f.updater.checkForUpdates = async () => { throw Error('private request context'); };diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjsindex 61a05d66..8b57ee89 100644--- a/apps/native/electron/visual-tests.cjs+++ b/apps/native/electron/visual-tests.cjs@@ -1,4 +1,5 @@const { app, BrowserWindow, ipcMain } = require('electron');+const { presentWindow, testWindowOptions } = require('./test-window.cjs');const { spawn } = require('node:child_process');const fs = require('node:fs');const path = require('node:path');@@ -23,8 +24,8 @@ app.whenReady().then(async () => {server = spawn(process.env.GRAFF_TEST_BUN || 'bun', ['node_modules/next/dist/bin/next', 'start', '--port', String(port), '--hostname', '127.0.0.1'], { cwd: root, env: { ...process.env, GRAFF_VISUAL_TESTS: '1', GRAFF_DESKTOP_TOKEN: '', NEXT_TELEMETRY_DISABLED: '1' }, detached: true, stdio: ['ignore', log, log] });fs.closeSync(log);for (let i = 0; i < 100; i++) { try { if ((await fetch(`${origin}/visual-tests`)).ok) break; } catch {} if (i === 99) throw Error('Visual fixture server did not start'); await sleep(100); }- win = new BrowserWindow({ width: 900, height: 600, show: true, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });- app.focus({ steal: true }); win.show(); win.focus();+ win = new BrowserWindow(testWindowOptions({ width: 900, height: 600, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } }));+ presentWindow(win, app);const apiRequests = [];win.webContents.session.webRequest.onBeforeRequest((details, callback) => {const url = new URL(details.url);diff --git a/apps/native/lib/browser/url.test.ts b/apps/native/lib/browser/url.test.tsindex 75902ef4..d38c7b6a 100644--- a/apps/native/lib/browser/url.test.ts+++ b/apps/native/lib/browser/url.test.ts@@ -19,4 +19,13 @@ describe("normalizeUrl", () => {assert.equal(normalizeUrl(""), "about:blank");assert.equal(normalizeUrl(" "), "about:blank");});+ it("sends ordinary words to a search engine (#823)", () => {+ assert.equal(normalizeUrl("hello"), "https://www.google.com/search?q=hello");+ assert.equal(normalizeUrl("zig comptime"), "https://www.google.com/search?q=zig%20comptime");+ assert.equal(normalizeUrl("what is https"), "https://www.google.com/search?q=what%20is%20https");+ });+ it("does not treat blocked schemes as search", () => {+ assert.equal(normalizeUrl("javascript:alert(1)"), "javascript:alert(1)");+ assert.equal(normalizeUrl("file:///etc/passwd"), "file:///etc/passwd");+ });});diff --git a/apps/native/lib/browser/url.ts b/apps/native/lib/browser/url.tsindex 717c846f..5981b994 100644--- a/apps/native/lib/browser/url.ts+++ b/apps/native/lib/browser/url.ts@@ -1,12 +1,34 @@-/** What the address bar accepts: a full URL, a bare host, or a local- * address. A bare host becomes https; localhost and raw addresses stay- * http, since dev servers rarely speak TLS. Empty means a blank page. */+/** Address-bar handling: navigate URLs and hostnames, search ordinary words.+ * Blocked schemes stay errors — they are never turned into a search (#823). */++const SEARCH = "https://www.google.com/search?q=";++const BLOCKED = /^(file|javascript|data|blob):/i;+const EXPLICIT = /^[a-z][a-z0-9+.-]*:\/\//i;+const SPECIAL = /^(about|data|blob|file|javascript):/i;+const LOCAL = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|\d+\.\d+\.\d+\.\d+)(:\d+)?(\/|$)/i;+const HOST = /^[\w-]+(\.[\w-]+)+(:\d+)?([/?#]|$)/i;+const HOST_PORT = /^[\w.-]+:\d+([/?#]|$)/;++export function looksLikeWebAddress(raw: string): boolean {+ const t = raw.trim();+ if (!t || /\s/.test(t)) return false;+ if (BLOCKED.test(t) || EXPLICIT.test(t) || SPECIAL.test(t)) return true;+ if (LOCAL.test(t) || HOST.test(t) || HOST_PORT.test(t)) return true;+ return false;+}++export function searchUrl(query: string): string {+ return `${SEARCH}${encodeURIComponent(query.trim())}`;+}++/** What the address bar accepts: a URL, a bare host, or a search query. */export function normalizeUrl(raw: string): string {const t = raw.trim();if (!t) return "about:blank";- // `localhost:3000` is a host and port, not a scheme: a scheme needs `//`- // after it, except the few that never carry one.- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(t) || /^(about|data|blob|file|javascript):/i.test(t)) return t;- const local = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|\d+\.\d+\.\d+\.\d+)(:\d+)?(\/|$)/i.test(t);- return `${local ? "http" : "https"}://${t}`;+ if (BLOCKED.test(t) || EXPLICIT.test(t) || SPECIAL.test(t)) return t;+ if (looksLikeWebAddress(t)) {+ return `${LOCAL.test(t) ? "http" : "https"}://${t}`;+ }+ return searchUrl(t);}diff --git a/apps/native/lib/session-projection.test.ts b/apps/native/lib/session-projection.test.tsindex e81b0933..cd6926a8 100644--- a/apps/native/lib/session-projection.test.ts+++ b/apps/native/lib/session-projection.test.ts@@ -72,6 +72,7 @@ test("only an explicit transcript request projects raw history; the default APIconst response = await GET(new NextRequest(file.url("transcript")));const body = await response.json();expect(body.messages).toBeUndefined(); expect(body.presentation).toBe("transcript-v1");+ expect(body.view).toBe("snapshot"); expect(body.execution).toBe("unknown");expect(body.transcript).toEqual(transcriptFromMessages(raw, "demo"));expect(JSON.stringify(body)).not.toContain("hidden instructions");expect(JSON.stringify(body)).not.toContain("large body");@@ -87,7 +88,9 @@ test("projected and legacy responses restore exactly the same visible conversatiexpect(sessionFromResponse(projected)).toEqual(sessionFromResponse(legacy));const loaded = sessionFromResponse(projected);expect(loaded.messages.length).toBe(4);+ expect(loaded.snapshot).toBe(true);expect("presentation" in loaded.meta).toBe(false); expect("transcript" in loaded.meta).toBe(false);+ expect("view" in loaded.meta).toBe(false); expect("execution" in loaded.meta).toBe(false);} finally { file.cleanup(); }});diff --git a/apps/native/lib/sessions.test.ts b/apps/native/lib/sessions.test.tsindex 4cb31fb2..70546402 100644--- a/apps/native/lib/sessions.test.ts+++ b/apps/native/lib/sessions.test.ts@@ -1,6 +1,6 @@import { describe, it } from "node:test";import assert from "node:assert/strict";-import { dateGroup, groupSessions, sessionHint, transcriptFromMessages } from "./sessions.ts";+import { dateGroup, groupSessions, sessionFromResponse, sessionHint, transcriptFromMessages } from "./sessions.ts";describe("transcriptFromMessages", () => {it("restores Responses tool calls and completion answers without role fields", () => {@@ -60,6 +60,24 @@ describe("transcriptFromMessages", () => {const last = out[3];if (last.role !== "assistant") return;assert.equal(last.turn.text, "You're welcome.");+ assert.equal(last.turn.status, "done");+ });++ it("keeps a last turn thinking when a tool result never arrived (#839)", () => {+ const out = transcriptFromMessages([+ { role: "user", content: "keep going" },+ { role: "assistant", content: "Working.", tool_calls: [{ id: "c1", function: { name: "bash", arguments: '{"command":"sleep 30"}' } }] },+ ]);+ assert.equal(out.length, 2);+ const turn = out[1];+ if (turn.role !== "assistant") return;+ assert.equal(turn.turn.status, "thinking");+ assert.equal(turn.turn.tools[0].status, "running");+ });++ it("marks every saved-file response as a snapshot (#839)", () => {+ const loaded = sessionFromResponse({ name: "live", title: "Still running", model: null, provider: null, updatedMs: 1, size: 1 });+ assert.equal(loaded.snapshot, true);});it("marks failed tool results, keeps todos, and survives junk", () => {diff --git a/apps/native/lib/sessions.ts b/apps/native/lib/sessions.tsindex d9ac7ac1..2213eb68 100644--- a/apps/native/lib/sessions.ts+++ b/apps/native/lib/sessions.ts@@ -37,14 +37,27 @@ export type TranscriptMsg =| { role: "user"; text: string }| { role: "assistant"; turn: AssistantTurn };-export type SessionResponse = StoredSession & { messages?: unknown[]; presentation?: "transcript-v1"; transcript?: TranscriptMsg[] };+export type SessionResponse = StoredSession & {+ messages?: unknown[];+ presentation?: "transcript-v1";+ transcript?: TranscriptMsg[];+ /** Saved file only — not a live REPL attach (#839). */+ view?: "snapshot";+ execution?: "unknown";+};/** New servers project the existing GUI transcript before crossing into the* renderer. Keep raw responses readable for older servers and local fixtures. */-export function sessionFromResponse(body: SessionResponse): { meta: StoredSession; messages: TranscriptMsg[] } {- const { messages, presentation, transcript, ...meta } = body;- return { meta, messages: presentation === "transcript-v1" && Array.isArray(transcript)- ? transcript : transcriptFromMessages(messages ?? [], meta.model ?? undefined) };+export function sessionFromResponse(body: SessionResponse): { meta: StoredSession; messages: TranscriptMsg[]; snapshot: boolean } {+ const { messages, presentation, transcript, view: _view, execution: _execution, ...meta } = body;+ return {+ meta,+ // A saved file is never a live REPL attach. The GUI must not infer+ // that commentary or a successful load means the other surface finished (#839).+ snapshot: true,+ messages: presentation === "transcript-v1" && Array.isArray(transcript)+ ? transcript : transcriptFromMessages(messages ?? [], meta.model ?? undefined),+ };}const BASE = "/api/sessions";@@ -102,7 +115,7 @@ export async function listSessions(root?: string): Promise<StoredSession[]> {return page.sessions;}-export async function loadSession(name: string, root?: string, signal?: AbortSignal): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {+export async function loadSession(name: string, root?: string, signal?: AbortSignal): Promise<{ meta: StoredSession; messages: TranscriptMsg[]; snapshot: boolean }> {const res = await fetch(`${BASE}${withRoot({ name, root, view: "transcript" })}`, { cache: "no-store", signal });if (!res.ok) {const detail = await res.text().catch(() => "");@@ -223,10 +236,12 @@ export function transcriptFromMessages(raw: unknown[], model?: string): Transcriconst out: TranscriptMsg[] = [];let turn: AssistantTurn | null = null;const flush = () => {- if (turn) out.push({ role: "assistant", turn: { ...turn, status: "done" } });+ if (!turn) return;+ const pending = turn.tools.some((row) => row.status === "running");+ out.push({ role: "assistant", turn: { ...turn, status: pending ? "thinking" : "done" } });turn = null;};- const current = (): AssistantTurn => (turn ??= { ...emptyTurn(), model, status: "done" });+ const current = (): AssistantTurn => (turn ??= { ...emptyTurn(), model, status: "thinking" });for (const item of raw) {if (!item || typeof item !== "object") continue;@@ -274,7 +289,7 @@ export function transcriptFromMessages(raw: unknown[], model?: string): Transcriname: label,icon: iconFor(name),chip: chip === name ? "" : chip,- status: "ok",+ status: "running",detail: summarizeInput(name, input),path,};@@ -290,7 +305,7 @@ export function transcriptFromMessages(raw: unknown[], model?: string): Transcriconst failed = /^(error|failed|denied)\b/i.test(text);t.tools = t.tools.map((row, i) =>i === idx- ? { ...row, status: failed ? "error" : row.status, detail: text ? [...row.detail, { text: firstLine(text) }] : row.detail }+ ? { ...row, status: failed ? "error" : "ok", detail: text ? [...row.detail, { text: firstLine(text) }] : row.detail }: row,);}diff --git a/apps/native/lib/turn-activity.test.ts b/apps/native/lib/turn-activity.test.tsindex e4873e3b..2a6cf2bf 100644--- a/apps/native/lib/turn-activity.test.ts+++ b/apps/native/lib/turn-activity.test.ts@@ -2,6 +2,11 @@ import { test, expect } from "bun:test";import { emptyTurn, applyAcpUpdate, finishAcpTurn } from "./acp";import { turnActivity } from "./turn-activity";import { createTurnPainter } from "./turn-painter";+test("a saved snapshot does not claim the turn finished here (#839)", () => {+ const turn = { ...emptyTurn(), status: "done" as const, startedAt: 1000 };+ expect(turnActivity(turn, 2000).label).toBe("Turn finished");+ expect(turnActivity(turn, 2000, { snapshot: true }).label).toBe("Saved snapshot");+});test("commentary followed by silence stays visibly waiting", () => {const turn = { ...emptyTurn(), status: "streaming" as const, text: "Preparing the change.", connected: true, startedAt: 1000, lastUpdateAt: 4000, activityKind: "agent_message_chunk" };expect(turnActivity(turn, 25000)).toMatchObject({ live: true, label: "Waiting for Graff…", state: "waiting" });diff --git a/apps/native/lib/turn-activity.ts b/apps/native/lib/turn-activity.tsindex bc734600..0b6dde37 100644--- a/apps/native/lib/turn-activity.ts+++ b/apps/native/lib/turn-activity.ts@@ -1,5 +1,5 @@import type { AssistantTurn } from "./graff-events";-export function turnActivity(turn: AssistantTurn, now: number) {+export function turnActivity(turn: AssistantTurn, now: number, opts?: { snapshot?: boolean }) {const live = turn.status === "thinking" || turn.status === "streaming";const elapsed = Math.max(0, Math.floor((now - (turn.startedAt ?? now)) / 1000));const idle = Math.max(0, Math.floor((now - (turn.lastUpdateAt ?? turn.startedAt ?? now)) / 1000));@@ -7,7 +7,7 @@ export function turnActivity(turn: AssistantTurn, now: number) {const missing = turn.tools.filter(tool => tool.status === "interrupted").length;if (turn.status === "error") return { state: "error", label: "Response interrupted", detail: "You can send a follow-up to continue.", live: false };if (turn.status === "ask") return { state: "input", label: "Waiting for your answer", detail: "", live: false };- if (!live) return { state: "done", label: turn.stopReason === "cancelled" ? "Stopped" : "Turn finished", detail: missing ? `${missing} tool ${missing === 1 ? "result" : "results"} not received` : `${elapsed}s`, live: false };+ if (!live) return { state: "done", label: turn.stopReason === "cancelled" ? "Stopped" : opts?.snapshot ? "Saved snapshot" : "Turn finished", detail: missing ? `${missing} tool ${missing === 1 ? "result" : "results"} not received` : `${elapsed}s`, live: false };const label = !turn.connected ? "Starting Graff…" : running ? `Running ${running} ${running === 1 ? "tool" : "tools"}…` : turn.activityKind === "agent_thought_chunk" ? "Thinking…" : turn.activityKind === "agent_message_chunk" && idle < 2 ? "Writing response…" : "Waiting for Graff…";return { state: idle >= 15 ? "waiting" : "working", label, detail: idle >= 15 ? running ? `Waiting for tool output · ${idle}s since the last event` : `Waiting for a response · ${idle}s since the last event` : `${elapsed}s`, live: true };}diff --git a/apps/native/package.json b/apps/native/package.jsonindex 19444436..60ac2dc6 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -10,7 +10,7 @@"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000","mock-serve": "node scripts/mock-serve.mjs","lint": "next lint",- "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts",+ "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts components/site/harness-split.test.ts components/site/useDesktopShortcuts.test.ts","electron:build": "bash electron/build.sh","test:electron": "bun test electron/policy.test.cjs","test:desktop": "bun test lib ./electron/*.test.cjs",diff --git a/docs/adr/0099-gui-saved-sessions-are-snapshots.md b/docs/adr/0099-gui-saved-sessions-are-snapshots.mdnew file mode 100644index 00000000..6530652f--- /dev/null+++ b/docs/adr/0099-gui-saved-sessions-are-snapshots.md@@ -0,0 +1,29 @@+# 0099. GUI saved sessions are snapshots, not live REPL attach++Status: accepted 2026-09-10++## Context++Opening a `.graff/sessions` file in the GUI while the same conversation is+still running in the REPL painted an idle transcript and a normal follow-up+composer (#839). The saved JSON has no live execution field, and the GUI+derived "finished" from local turn status plus a successful load.++Attaching to the REPL process from the desktop is a different product path+and is not what `/api/sessions` returns.++## Decision++A GET of a saved session is a snapshot with unknown live status+(`view: "snapshot"`, `execution: "unknown"`). The GUI must label that view+and must not infer that commentary or a successful load means the other+surface finished. A follow-up in the GUI starts a GUI session; it does not+claim the REPL turn.++Unmatched tool calls in the last restored turn stay running so the snapshot+can still show in-progress work. That is display state, not a live attach.++## Consequences++Continuation ownership is explicit before the user sends. Live attach, if+added later, needs a different endpoint than the saved-file GET.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex a624dcd3..914467b3 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -108,6 +108,7 @@ record only when you need the evidence or the edge cases.| [0096](0096-desktop-link-destination.md) | Persist the desktop link destination outside origin-scoped storage; validate once and reveal the focused chat's Browser without navigating the app. || [0097](0097-isolate-probe-clipboards.md) | Offline PTY probes get private clipboard commands per process; direct probe runs retain OS clipboard integration. || [0098](0098-orphan-listeners-are-not-stop-authority.md) | Legacy listener discovery is read-only; stop authority requires verified ownership, port preflight checks both families, and unknown browser visibility protects listening jobs. |+| [0099](0099-gui-saved-sessions-are-snapshots.md) | A saved-session GET is a snapshot with unknown live status; the GUI must not infer the REPL finished. |## When to write onediff --git a/src/commands_model.zig b/src/commands_model.zigindex f03cf1e2..2d0c738a 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -4,7 +4,6 @@ const std = @import("std");const Io = std.Io;const Value = std.json.Value;const Allocator = std.mem.Allocator;-const builtin = @import("builtin");const ansi = @import("ansi.zig");const style = &ansi.style;@@ -53,8 +52,7 @@ const reasoning_levels = [_]PickItem{const vision = @import("vision.zig");const stageImagePath = vision.stageImagePath;-const visionCapable = vision.visionCapable;-const grabClipboardImage = vision.grabClipboardImage;+const commands_paste = @import("commands_paste.zig");fn providerKnown(id: []const u8) bool {return provider_mod.specFor(id) != null;@@ -556,35 +554,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;}- if (std.mem.eql(u8, line, "/paste")) {- if (builtin.os.tag != .macos) {- try out.writeAll("clipboard image paste is macOS-only — use /image <path>\n");- try out.flush();- return true;- }- if (!visionCapable(root.provider)) {- try out.print("⚠ {s} can't see images — /model to a vision model (claude-*, gpt-5*) first\n", .{root.provider.model});- try out.flush();- return true;- }- const grab = grabClipboardImage(root.io, root.gpa) orelse {- vision.tracePaste(root, "no_image", "none", 0, ""); // #350- try out.writeAll("no image on the clipboard — copy an image first (text? just paste it normally)\n");- try out.flush();- return true;- };- defer grab.release(root.io, root.gpa); // temp export never outlives the command- var pbuf: [320]u8 = undefined;- const pasted = stageImagePath(root, grab.path);- vision.tracePasteResult(root, grab.flavor, pasted);- switch (pasted) {- .ok => |o| try out.print("📎 clipboard image attached ({s}, via {s}) — sent with your next message\n", .{ vision.fmtBytes(pbuf[0..16], o.bytes), grab.flavor.name() }),- .no_vision => try out.print("⚠ {s} can't see images\n", .{root.provider.model}),- .too_large, .not_found, .read_error => try out.print("{s}\n", .{vision.stageMessage(&pbuf, pasted, "the clipboard image")}),- }- try out.flush();- return true;- }+ if (try commands_paste.tryHandle(root, line, out)) return true;if (std.mem.eql(u8, line, "/strict")) {root.strict = !root.strict;@import("prompt_cache_hud.zig").noteBust(.mode);diff --git a/src/commands_paste.zig b/src/commands_paste.zignew file mode 100644index 00000000..27e01a6e--- /dev/null+++ b/src/commands_paste.zig@@ -0,0 +1,47 @@+//! `/paste`: stage a clipboard image, naming access/extract/convert failures+//! separately from an empty clipboard (#843).++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;++const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const vision = @import("vision.zig");++pub fn tryHandle(root: *Agent, line: []const u8, out: *Io.Writer) !bool {+ if (!std.mem.eql(u8, line, "/paste")) return false;+ if (builtin.os.tag != .macos) {+ try out.writeAll("clipboard image paste is macOS-only — use /image <path>\n");+ try out.flush();+ return true;+ }+ if (!vision.visionCapable(root.provider)) {+ try out.print("⚠ {s} can't see images — /model to a vision model (claude-*, gpt-5*) first\n", .{root.provider.model});+ try out.flush();+ return true;+ }+ switch (vision.grabClipboardImage(root.io, root.gpa)) {+ .empty => {+ vision.tracePaste(root, "no_image", "none", 0, "");+ try out.writeAll("no image on the clipboard — copy an image first (text? just paste it normally)\n");+ },+ .failed => |kind| {+ vision.tracePaste(root, "failed", @tagName(kind), 0, "");+ try out.print("{s}\n", .{vision.pasteFailMessage(kind)});+ },+ .ok => |grab| {+ defer grab.release(root.io, root.gpa);+ var pbuf: [320]u8 = undefined;+ const pasted = vision.stageImagePath(root, grab.path);+ vision.tracePasteResult(root, grab.flavor, pasted);+ switch (pasted) {+ .ok => |o| try out.print("📎 clipboard image attached ({s}, via {s}) — sent with your next message\n", .{ vision.fmtBytes(pbuf[0..16], o.bytes), grab.flavor.name() }),+ .no_vision => try out.print("⚠ {s} can't see images\n", .{root.provider.model}),+ .too_large, .not_found, .read_error => try out.print("{s}\n", .{vision.stageMessage(&pbuf, pasted, "the clipboard image")}),+ }+ },+ }+ try out.flush();+ return true;+}diff --git a/src/tui_launch.zig b/src/tui_launch.zigindex 5f43c480..a4debf29 100644--- a/src/tui_launch.zig+++ b/src/tui_launch.zig@@ -327,7 +327,11 @@ fn pasteCb(ctx: ?*anyopaque, dest: []u8) isize {if (!vision.visionCapable(c.provider)) return pasteErr(dest, vision.no_vision_message);if (builtin.os.tag != .macos) return pasteErr(dest, "clipboard image paste is macOS-only — use /image <path>");const gpa = std.heap.page_allocator;- const grab = vision.grabClipboardImage(c.io, gpa) orelse return 0;+ const grab = switch (vision.grabClipboardImage(c.io, gpa)) {+ .ok => |g| g,+ .empty => return 0,+ .failed => |kind| return pasteErr(dest, vision.pasteFailMessage(kind)),+ };const n = @min(grab.path.len, dest.len);@memcpy(dest[0..n], grab.path[0..n]);if (grab.owned) {diff --git a/src/vision.zig b/src/vision.zigindex e9e82f4a..29dfb5d8 100644--- a/src/vision.zig+++ b/src/vision.zig@@ -21,11 +21,19 @@ const isImagePath = input_util.isImagePath;/// raw-byte budget (vision_clipboard.zig, 600-line goal). Re-exported below so/// readline/commands_model keep importing only `vision`.const clip = @import("vision_clipboard.zig");+const paste = @import("vision_paste.zig");pub const Flavor = clip.Flavor;pub const Grab = clip.Grab;+pub const FailKind = clip.FailKind;+pub const GrabAttempt = clip.GrabAttempt;pub const grabClipboardImage = clip.grabClipboardImage;pub const max_staged_image_bytes = clip.max_staged_image_bytes;pub const fmtBytes = clip.fmtMb;+pub const ClipboardPasteSource = paste.ClipboardPasteSource;+pub const clipboardPasteSource = paste.clipboardPasteSource;+pub const pasteMessage = paste.pasteMessage;+pub const pasteFailMessage = paste.pasteFailMessage;+pub const no_vision_message = paste.no_vision_message;pub const PendingImage = struct {media_type: []const u8,@@ -330,45 +338,10 @@ pub fn mcpImageHandoff(reg: anytype, supports_vision: bool, slot: *?PendingImagereturn true;}-/// Why a Ctrl-V clipboard paste did or did not produce an image (#258).-/// Ordered so the cheapest, most-likely-wrong condition is decided first.-/// (A terminal can't receive clipboard image bytes over stdin, so the actual-/// pixels are fetched from the OS by `grabClipboardImage`'s flavor cascade.)-pub const ClipboardPasteSource = union(enum) {- image: Grab,- no_image,- no_vision,- unsupported_platform,-};--/// Decide a Ctrl-V paste WITHOUT touching the clipboard unless it can help.-///-/// The vision check comes first deliberately: on a non-vision model the paste-/// can never succeed, so shelling out to the clipboard would spend a subprocess-/// (and on macOS, a pasteboard read of whatever the user last copied) purely to-/// produce an error. `grabber` is injected so the ordering is testable without-/// a real clipboard.-pub fn clipboardPasteSource(io: Io, gpa: Allocator, supports_vision: bool, is_macos: bool, grabber: anytype) ClipboardPasteSource {- if (!supports_vision) return .no_vision;- if (!is_macos) return .unsupported_platform;- return .{ .image = grabber(io, gpa) orelse return .no_image };-}--/// The user-facing line for every non-image paste outcome, so the caller's-/// switch stays one prong instead of three parallel string literals.-pub fn pasteMessage(source: ClipboardPasteSource) []const u8 {- return switch (source) {- .no_vision => no_vision_message,- .unsupported_platform => "clipboard image paste is macOS-only — use /image <path>",- .no_image => "no image on the clipboard — copy an image first (this is Ctrl-V; ⌘V can't be captured)",- .image => "",- };+test {+ _ = @import("vision_paste.zig");}-/// Shared by the pre-clipboard guard and the post-stage failure path, which-/// previously carried two copies of the same sentence.-pub const no_vision_message = "this model can't see images — /model to a vision one (claude-*, gpt-5*)";-test "imageMediaType from extension" {try std.testing.expectEqualStrings("image/png", imageMediaType("shot.png"));try std.testing.expectEqualStrings("image/jpeg", imageMediaType("p.jpg"));@@ -418,51 +391,6 @@ test "visionModel: vision-capable model families only" {try std.testing.expect(!visionModel("qwen2.5-coder-7b")); // text-only local model}-test "clipboardPasteSource: vision is checked before the clipboard is touched (#258)" {- // The ordering IS the fix: on a non-vision model the paste can never work,- // so the clipboard must not be read at all. `calls` proves that.- const MockGrabber = struct {- var calls: usize = 0;- var image: ?Grab = .{ .path = "/tmp/test.png", .flavor = .png, .owned = false };-- fn grab(_: Io, _: Allocator) ?Grab {- calls += 1;- return image;- }- };- const expectTag = struct {- fn expect(expected: std.meta.Tag(ClipboardPasteSource), actual: ClipboardPasteSource) !void {- try std.testing.expectEqual(expected, std.meta.activeTag(actual));- }- }.expect;-- MockGrabber.calls = 0;- const io = std.testing.io;- const gpa = std.testing.allocator;- try expectTag(.no_vision, clipboardPasteSource(io, gpa, false, true, MockGrabber.grab));- try expectTag(.no_vision, clipboardPasteSource(io, gpa, false, false, MockGrabber.grab));- try expectTag(.unsupported_platform, clipboardPasteSource(io, gpa, true, false, MockGrabber.grab));- try std.testing.expectEqual(@as(usize, 0), MockGrabber.calls);-- try expectTag(.image, clipboardPasteSource(io, gpa, true, true, MockGrabber.grab));- try std.testing.expectEqual(@as(usize, 1), MockGrabber.calls);-- MockGrabber.image = null;- try expectTag(.no_image, clipboardPasteSource(io, gpa, true, true, MockGrabber.grab));- try std.testing.expectEqual(@as(usize, 2), MockGrabber.calls);-}--test "pasteMessage: every non-image outcome has a distinct, non-empty line" {- const cases = [_]ClipboardPasteSource{ .no_vision, .unsupported_platform, .no_image };- for (cases, 0..) |a, i| {- try std.testing.expect(pasteMessage(a).len > 0);- for (cases[i + 1 ..]) |b|- try std.testing.expect(!std.mem.eql(u8, pasteMessage(a), pasteMessage(b)));- }- // The staged-failure path reuses the same sentence rather than duplicating it.- try std.testing.expectEqualStrings(no_vision_message, pasteMessage(.no_vision));-}-test "stageMessage: an oversized paste names both real sizes, and each failure reads differently (#349)" {var buf: [256]u8 = undefined;const too_big = stageMessage(&buf, .{ .too_large = .{ .bytes = 7_682_253, .limit = max_staged_image_bytes } }, "the clipboard image");diff --git a/src/vision_clipboard.zig b/src/vision_clipboard.zigindex 0c7f595f..4cc45473 100644--- a/src/vision_clipboard.zig+++ b/src/vision_clipboard.zig@@ -50,6 +50,19 @@ pub const Flavor = enum {}};+/// Why a clipboard extraction failed without yielding an image (#843).+/// Categories stay privacy-safe: they never include clipboard contents.+pub const FailKind = enum { access, extract, convert };++/// Result of one pasteboard grab. Null used to mean both "nothing there"+/// and "osascript/sips failed", which Ctrl-V then reported as an empty+/// clipboard.+pub const GrabAttempt = union(enum) {+ ok: Grab,+ empty,+ failed: FailKind,+};+/// A clipboard image that made it to disk.pub const Grab = struct {path: []const u8,@@ -140,7 +153,7 @@ pub fn sipsIsImage(io: Io, path: []const u8) bool {/// `POSIX path of …`, so a path that does not start with `/` is coercion/// output rather than a file. No comptime OS gate is needed — the only caller/// is `grabFurl`, reached solely through `grabClipboardImage`, which already-/// returns null off macOS.+/// returns `.empty` off macOS.pub fn furlLooksStageable(io: Io, path: []const u8, probe: anytype) bool {if (path.len == 0 or path[0] != '/') return false;const size = regularFileSize(io, path) orelse return false;@@ -236,21 +249,52 @@ pub fn planStage(io: Io, gpa: Allocator, path: []const u8, budget: u64, resize:// ── the flavor cascade ────────────────────────────────────────────────────-/// macOS: export the clipboard image to a file and return its path, trying one-/// pasteboard flavor per osascript invocation and stopping at the first that-/// yields a real file. Null means the clipboard genuinely holds no image.+/// Type names `clipboard info` reports for image-bearing pasteboards.+/// The string is flavor metadata only — never clipboard contents (#843).+pub fn pasteboardHintFromInfo(info: []const u8) enum { image, none } {+ for ([_][]const u8{ "PNGf", "TIFF", "JPEG", "JIFf", "PDF ", "furl" }) |mark| {+ if (std.mem.indexOf(u8, info, mark) != null) return .image;+ }+ return .none;+}++const FlavorTry = union(enum) {+ ok: Grab,+ miss,+ failed: FailKind,+};++/// macOS: export the clipboard image to a file, trying one pasteboard flavor+/// per osascript invocation and stopping at the first that yields a real file.///-/// The old implementation asked for `«class PNGf»` and nothing else. That-/// covers every raster clipboard (macOS synthesizes PNGf from TIFF/JPEG/HEIC-/// and from live data-provider promises), but it silently loses the two cases-/// users actually hit: a copied *file* (`furl`, what Telegram/Finder put up)-/// and a vector-only `PDF ` clipboard (Preview, Illustrator, Keynote). #350.-pub fn grabClipboardImage(io: Io, gpa: Allocator) ?Grab {- if (builtin.os.tag != .macos) return null;- if (grabPng(io, gpa)) |g| return g;- if (grabFurl(io, gpa)) |g| return g;- if (grabPdf(io, gpa)) |g| return g;- return null;+/// Distinguishes an empty clipboard from access / export / conversion failures+/// so Ctrl-V can say something other than "copy an image first" when the+/// pasteboard already holds one (#843). `clipboard info` is consulted only for+/// flavor class names — never for payload bytes.+pub fn grabClipboardImage(io: Io, gpa: Allocator) GrabAttempt {+ if (builtin.os.tag != .macos) return .empty;+ var saw_fail: ?FailKind = null;+ inline for (.{ grabPng, grabFurl, grabPdf }) |step| {+ switch (step(io, gpa)) {+ .ok => |g| return .{ .ok = g },+ .miss => {},+ .failed => |k| if (saw_fail == null) {+ saw_fail = k;+ },+ }+ }+ if (saw_fail) |k| return .{ .failed = k };+ return switch (pasteboardImageHint(io, gpa)) {+ .image => .{ .failed = .extract },+ .unknown => .{ .failed = .access },+ .none => .empty,+ };+}++fn pasteboardImageHint(io: Io, gpa: Allocator) enum { image, none, unknown } {+ const info = runCapture(io, gpa, &.{ "osascript", "-e", "clipboard info" }) orelse return .unknown;+ defer gpa.free(info);+ return if (pasteboardHintFromInfo(info) == .image) .image else .none;}/// `open for access` line with our per-invocation path baked in.@@ -258,12 +302,12 @@ fn openLine(gpa: Allocator, path: []const u8) ?[]const u8 {return std.fmt.allocPrint(gpa, "set fp to open for access POSIX file \"{s}\" with write permission", .{path}) catch null;}-fn grabPng(io: Io, gpa: Allocator) ?Grab {- const path = tempPath(io, gpa, "png") orelse return null;+fn grabPng(io: Io, gpa: Allocator) FlavorTry {+ const path = tempPath(io, gpa, "png") orelse return .{ .failed = .access };var keep = false;defer if (!keep) discard(io, gpa, path);- const open = openLine(gpa, path) orelse return null;+ const open = openLine(gpa, path) orelse return .{ .failed = .access };defer gpa.free(open);const argv = [_][]const u8{"osascript",@@ -286,36 +330,44 @@ fn grabPng(io: Io, gpa: Allocator) ?Grab {"-e","end try",};- if (!runQuiet(io, &argv)) return null;+ switch (runStatus(io, &argv)) {+ .spawn => return .{ .failed = .access },+ .failed => return .miss,+ .ok => {},+ }// Stat the export: osascript exiting 0 is not proof the bytes landed.- if ((regularFileSize(io, path) orelse 0) == 0) return null;+ if ((regularFileSize(io, path) orelse 0) == 0) return .{ .failed = .extract };keep = true;- return .{ .path = path, .flavor = .png, .owned = true };+ return .{ .ok = .{ .path = path, .flavor = .png, .owned = true } };}-fn grabFurl(io: Io, gpa: Allocator) ?Grab {- const raw = runCapture(io, gpa, &.{ "osascript", "-e", "POSIX path of (the clipboard as «class furl»)" }) orelse return null;+fn grabFurl(io: Io, gpa: Allocator) FlavorTry {+ const raw = switch (runCaptureStatus(io, gpa, &.{ "osascript", "-e", "POSIX path of (the clipboard as «class furl»)" })) {+ .ok => |s| s,+ .failed => return .miss,+ .spawn => return .{ .failed = .access },+ };defer gpa.free(raw);const src = std.mem.trim(u8, raw, " \t\r\n");- if (!furlLooksStageable(io, src, sipsIsImage)) return null;+ if (!furlLooksStageable(io, src, sipsIsImage)) return .miss;if (stageableExtension(src)) {// The user's own file, in place. `owned = false`: never delete it.- const dup = gpa.dupe(u8, src) catch return null;- return .{ .path = dup, .flavor = .furl, .owned = false };+ const dup = gpa.dupe(u8, src) catch return .{ .failed = .access };+ return .{ .ok = .{ .path = dup, .flavor = .furl, .owned = false } };}// A .heic/.tiff/.bmp/… that sips vouched for: normalize to PNG.- const out = tempPath(io, gpa, "png") orelse return null;+ const out = tempPath(io, gpa, "png") orelse return .{ .failed = .access };if (sipsToPng(io, src, out) and (regularFileSize(io, out) orelse 0) > 0)- return .{ .path = out, .flavor = .furl, .owned = true };+ return .{ .ok = .{ .path = out, .flavor = .furl, .owned = true } };discard(io, gpa, out);- return null;+ return .{ .failed = .convert };}-fn grabPdf(io: Io, gpa: Allocator) ?Grab {- const pdf = tempPath(io, gpa, "pdf") orelse return null;+fn grabPdf(io: Io, gpa: Allocator) FlavorTry {+ const pdf = tempPath(io, gpa, "pdf") orelse return .{ .failed = .access };defer discard(io, gpa, pdf); // the intermediate never outlives this call- const open = openLine(gpa, pdf) orelse return null;+ const open = openLine(gpa, pdf) orelse return .{ .failed = .access };defer gpa.free(open);const argv = [_][]const u8{"osascript",@@ -338,14 +390,18 @@ fn grabPdf(io: Io, gpa: Allocator) ?Grab {"-e","end try",};- if (!runQuiet(io, &argv)) return null;- if ((regularFileSize(io, pdf) orelse 0) == 0) return null;+ switch (runStatus(io, &argv)) {+ .spawn => return .{ .failed = .access },+ .failed => return .miss,+ .ok => {},+ }+ if ((regularFileSize(io, pdf) orelse 0) == 0) return .{ .failed = .extract };- const out = tempPath(io, gpa, "png") orelse return null;+ const out = tempPath(io, gpa, "png") orelse return .{ .failed = .access };if (sipsToPng(io, pdf, out) and (regularFileSize(io, out) orelse 0) > 0)- return .{ .path = out, .flavor = .pdf, .owned = true };+ return .{ .ok = .{ .path = out, .flavor = .pdf, .owned = true } };discard(io, gpa, out);- return null;+ return .{ .failed = .convert };}fn sipsToPng(io: Io, in: []const u8, out: []const u8) bool {@@ -355,45 +411,60 @@ fn sipsToPng(io: Io, in: []const u8, out: []const u8) bool {// ── subprocess plumbing ───────────────────────────────────────────────────+const RunStatus = enum { ok, failed, spawn };+fn runQuiet(io: Io, argv: []const []const u8) bool {+ return runStatus(io, argv) == .ok;+}++fn runStatus(io: Io, argv: []const []const u8) RunStatus {var child = std.process.spawn(io, .{.argv = argv,.stdin = .ignore,.stdout = .ignore,.stderr = .ignore,- }) catch return false;- const term = child.wait(io) catch return false;- return term == .exited and term.exited == 0;+ }) catch return .spawn;+ const term = child.wait(io) catch return .spawn;+ return if (term == .exited and term.exited == 0) .ok else .failed;}+const CaptureStatus = union(enum) { ok: []u8, failed, spawn };+/// stdout of a successful run, gpa-owned; null on spawn/read failure or a/// non-zero exit.fn runCapture(io: Io, gpa: Allocator, argv: []const []const u8) ?[]u8 {+ return switch (runCaptureStatus(io, gpa, argv)) {+ .ok => |s| s,+ .failed, .spawn => null,+ };+}++fn runCaptureStatus(io: Io, gpa: Allocator, argv: []const []const u8) CaptureStatus {var child = std.process.spawn(io, .{.argv = argv,.stdin = .ignore,.stdout = .pipe,.stderr = .ignore,- }) catch return null;+ }) catch return .spawn;const f = child.stdout orelse {_ = child.wait(io) catch {};- return null;+ return .spawn;};var rbuf: [4096]u8 = undefined;var fr = f.readerStreaming(io, &rbuf);const captured = fr.interface.allocRemaining(gpa, .limited(8 * 1024)) catch {_ = child.wait(io) catch {};- return null;+ return .spawn;};const term = child.wait(io) catch {gpa.free(captured);- return null;+ return .spawn;};if (term != .exited or term.exited != 0) {gpa.free(captured);- return null;+ return .failed;}- return captured;+ return .{ .ok = captured };}// ── formatting ────────────────────────────────────────────────────────────diff --git a/src/vision_clipboard_tests.zig b/src/vision_clipboard_tests.zigindex 4628c012..47221a31 100644--- a/src/vision_clipboard_tests.zig+++ b/src/vision_clipboard_tests.zig@@ -252,6 +252,16 @@ test "fmtMb: the size in the error line is the size the user sees" {try testing.expectEqualStrings("1.4 MB", fmtMb(&buf, 1_470_878));}+test "pasteboardHintFromInfo: image flavors vs text-only (#843)" {+ const hint = clip.pasteboardHintFromInfo;+ try testing.expectEqual(.image, hint("«class PNGf», 18432"));+ try testing.expectEqual(.image, hint("TIFF, 2048, furl"));+ try testing.expectEqual(.image, hint("«class PDF », 880"));+ try testing.expectEqual(.none, hint("«class utf8», 12"));+ try testing.expectEqual(.none, hint(""));+ try testing.expectEqual(.none, hint("missing value"));+}+test "max_staged_image_bytes: base64 of a full-budget image stays under the 5 MB wire cap" {const encoded = std.base64.standard.Encoder.calcSize(@intCast(max_staged_image_bytes));try testing.expect(encoded < 5_000_000);diff --git a/src/vision_paste.zig b/src/vision_paste.zignew file mode 100644index 00000000..b1b50ffb--- /dev/null+++ b/src/vision_paste.zig@@ -0,0 +1,116 @@+//! Ctrl-V / `/paste` outcome types. Split out of vision.zig so that file+//! stays under the 600-line ceiling while #843 can name an access/export/+//! conversion failure separately from an empty clipboard.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const clip = @import("vision_clipboard.zig");++pub const Grab = clip.Grab;+pub const FailKind = clip.FailKind;+pub const GrabAttempt = clip.GrabAttempt;++/// Why a Ctrl-V clipboard paste did or did not produce an image (#258, #843).+/// Ordered so the cheapest, most-likely-wrong condition is decided first.+pub const ClipboardPasteSource = union(enum) {+ image: Grab,+ no_image,+ failed: FailKind,+ no_vision,+ unsupported_platform,+};++pub const no_vision_message = "this model can't see images — /model to a vision one (claude-*, gpt-5*)";++/// Decide a Ctrl-V paste WITHOUT touching the clipboard unless it can help.+///+/// The vision check comes first deliberately: on a non-vision model the paste+/// can never succeed, so shelling out to the clipboard would spend a subprocess+/// (and on macOS, a pasteboard read of whatever the user last copied) purely to+/// produce an error. `grabber` is injected so the ordering is testable without+/// a real clipboard. It must return `GrabAttempt`.+pub fn clipboardPasteSource(io: Io, gpa: Allocator, supports_vision: bool, is_macos: bool, grabber: anytype) ClipboardPasteSource {+ if (!supports_vision) return .no_vision;+ if (!is_macos) return .unsupported_platform;+ return switch (grabber(io, gpa)) {+ .ok => |g| .{ .image = g },+ .empty => .no_image,+ .failed => |k| .{ .failed = k },+ };+}++pub fn pasteFailMessage(kind: FailKind) []const u8 {+ return switch (kind) {+ .access => "couldn't read the clipboard — grant Automation access for osascript, then try again",+ .extract => "the clipboard image could not be exported — try Copy again, or save it and /image <path>",+ .convert => "the clipboard image could not be converted — try a PNG or JPEG",+ };+}++/// The user-facing line for every non-image paste outcome, so the caller's+/// switch stays one prong instead of four parallel string literals.+pub fn pasteMessage(source: ClipboardPasteSource) []const u8 {+ return switch (source) {+ .no_vision => no_vision_message,+ .unsupported_platform => "clipboard image paste is macOS-only — use /image <path>",+ .no_image => "no image on the clipboard — copy an image first (this is Ctrl-V; ⌘V can't be captured)",+ .failed => |k| pasteFailMessage(k),+ .image => "",+ };+}++test "clipboardPasteSource: vision is checked before the clipboard is touched (#258)" {+ const MockGrabber = struct {+ var calls: usize = 0;+ var result: GrabAttempt = .{ .ok = .{ .path = "/tmp/test.png", .flavor = .png, .owned = false } };++ fn grab(_: Io, _: Allocator) GrabAttempt {+ calls += 1;+ return result;+ }+ };+ const expectTag = struct {+ fn expect(expected: std.meta.Tag(ClipboardPasteSource), actual: ClipboardPasteSource) !void {+ try std.testing.expectEqual(expected, std.meta.activeTag(actual));+ }+ }.expect;++ MockGrabber.calls = 0;+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ try expectTag(.no_vision, clipboardPasteSource(io, gpa, false, true, MockGrabber.grab));+ try expectTag(.no_vision, clipboardPasteSource(io, gpa, false, false, MockGrabber.grab));+ try expectTag(.unsupported_platform, clipboardPasteSource(io, gpa, true, false, MockGrabber.grab));+ try std.testing.expectEqual(@as(usize, 0), MockGrabber.calls);++ try expectTag(.image, clipboardPasteSource(io, gpa, true, true, MockGrabber.grab));+ try std.testing.expectEqual(@as(usize, 1), MockGrabber.calls);++ MockGrabber.result = .empty;+ try expectTag(.no_image, clipboardPasteSource(io, gpa, true, true, MockGrabber.grab));+ try std.testing.expectEqual(@as(usize, 2), MockGrabber.calls);++ MockGrabber.result = .{ .failed = .extract };+ try expectTag(.failed, clipboardPasteSource(io, gpa, true, true, MockGrabber.grab));+ try std.testing.expectEqual(@as(usize, 3), MockGrabber.calls);+}++test "pasteMessage: empty clipboard and extraction failure are distinct (#843)" {+ const cases = [_]ClipboardPasteSource{+ .no_vision,+ .unsupported_platform,+ .no_image,+ .{ .failed = .access },+ .{ .failed = .extract },+ .{ .failed = .convert },+ };+ for (cases, 0..) |a, i| {+ try std.testing.expect(pasteMessage(a).len > 0);+ for (cases[i + 1 ..]) |b|+ try std.testing.expect(!std.mem.eql(u8, pasteMessage(a), pasteMessage(b)));+ }+ try std.testing.expectEqualStrings(no_vision_message, pasteMessage(.no_vision));+ try std.testing.expectEqualStrings(pasteFailMessage(.extract), pasteMessage(.{ .failed = .extract }));+}