Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(gui): guard saved snapshots and keep tests in background

justrachf149edc478df
diff --git a/apps/native/README.md b/apps/native/README.md
index 05853f9d..f0675d2f 100644
--- a/apps/native/README.md
+++ b/apps/native/README.md
@@ -225,9 +225,10 @@ bun run test:desktop
bun run test:visual
```
-The visual runner uses isolated synthetic data and makes no engine or model API
+The visual runner keeps all windows hidden by default, preserves desktop focus,
+uses isolated synthetic data and makes no engine or model API
calls. It checks turn progress, interruption states, large tool groups and output,
-long history, reading position during streaming, fullscreen transitions, command
+long history, reading position during streaming, command
menus, keyboard splits, workspace search and the Agents panel. Tool groups start
collapsed; expanded groups page their rows, and large output previews preserve
the beginning and end with an explicit omission marker. Older messages load on
@@ -241,8 +242,11 @@ and review recovery, navigation, terminals, and browser previews. `bun run test:
checks native close routing, stable pane order, draft preservation while visiting
Projects, and mouse resizing in both directions. `bun run test:stress`
covers long transcripts and tool output without changing macOS
-Spaces. The full `test:visual` suite additionally checks native fullscreen
-transitions; the stress results explicitly report fullscreen as not run.
+Spaces. Native fullscreen transitions in the full `test:visual` suite require
+`GRAFF_TEST_FOREGROUND=1`; default reports explicitly mark them as not run.
+`bun run test:background` checks hidden-window creation, trusted page input and
+cleanup without a UI build. On macOS an OS observer watches the entire visual
+run, including Electron startup, and fails it on activation or visible windows.
`bun run test:agents` covers live, completed and failed children, tool disclosure,
late replies after selection changes, and inspection without sending messages.
diff --git a/apps/native/components/site/ChatColumn.tsx b/apps/native/components/site/ChatColumn.tsx
new file mode 100644
index 00000000..2af893a5
--- /dev/null
+++ b/apps/native/components/site/ChatColumn.tsx
@@ -0,0 +1,51 @@
+"use client";
+import type { ComponentProps } from "react";
+import PromptBar from "@/components/primitives/PromptBar";
+import type { Health } from "@/lib/acp-client";
+import type { loadSession } from "@/lib/sessions";
+import ChatTranscript from "./ChatTranscript";
+import EmptyState from "./ChatEmpty";
+import PromptQueue from "./PromptQueue";
+import SavedSnapshot from "./SavedSnapshot";
+import type { Chat } from "./harness-types";
+
+export default function ChatColumn({ thread, compact, following, register, onOpenPath, onReview,
+ prompt, queue, pins, onShowPins, onClearPins, health, onOpenProject, onProjects, onConversations,
+ onRefresh, onContinue }: {
+ thread: Chat; compact: boolean; following: boolean;
+ register: (element: HTMLDivElement | null) => void;
+ onOpenPath: (path: string) => void; onReview: () => void;
+ prompt: ComponentProps<typeof PromptBar> & Required<Pick<ComponentProps<typeof PromptBar>, "onSend" | "models" | "onModelChange">>;
+ queue: ComponentProps<typeof PromptQueue>;
+ pins: number; onShowPins: () => void; onClearPins: () => void;
+ health: Health | null; onOpenProject: () => void; onProjects: () => void; onConversations: () => void;
+ onRefresh: (loaded: Awaited<ReturnType<typeof loadSession>>) => void; onContinue: () => void;
+}) {
+ if (!thread.messages.length && !thread.snapshot) return <div className="min-h-0 flex-1 overflow-y-auto">
+ <EmptyState compact={compact} onOpenProject={onOpenProject} onProjects={onProjects}
+ onContinue={onConversations} onReview={onReview} onSend={prompt.onSend} onSetting={prompt.onSetting}
+ health={health} history={prompt.history} cwd={prompt.root} models={prompt.models}
+ modelKey={prompt.modelKey} onModelChange={prompt.onModelChange} commands={prompt.commands} />
+ </div>;
+ return <div className="flex min-h-0 flex-1 flex-col">
+ <ChatTranscript messages={thread.messages} register={register} following={following}
+ onOpenPath={onOpenPath} onReview={onReview} snapshot={thread.snapshot} />
+ <div className={`shrink-0 bg-page px-4 ${compact ? "py-2" : "pt-3 pb-6 sm:px-8"}`}>
+ <div className="mx-auto max-w-[720px]">
+ {thread.snapshot && thread.session ? <SavedSnapshot name={thread.session} cwd={thread.cwd}
+ onRefresh={onRefresh} onContinue={onContinue} /> : <>
+ {pins > 0 && <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">
+ <span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Pinned</span>
+ <span className="min-w-0 flex-1 truncate text-ink">{pins} element{pins === 1 ? "" : "s"} in the browser go with your next message</span>
+ <button type="button" onClick={onShowPins} className="shrink-0 rounded px-1.5 text-[11.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink">Show</button>
+ <button type="button" aria-label="Clear pins" onClick={onClearPins} className="flex size-5 shrink-0 items-center justify-center rounded-[5px] text-ink-3 hover:bg-hover hover:text-ink">
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden><path d="M18 6L6 18M6 6l12 12" /></svg>
+ </button>
+ </div>}
+ <PromptQueue {...queue} />
+ <PromptBar {...prompt} tall={!compact} placeholder={prompt.busy ? "Queue a follow-up…" : "Follow up"} />
+ </>}
+ </div>
+ </div>
+ </div>;
+}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 516703b0..401ef284 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -15,14 +15,14 @@ import { newPageToken, newSessionName, type Chat, type Msg } from "./harness-typ
import ChangesPane from "./ChangesPane";
import { useBrowserVisibility } from "./useBrowserVisibility";
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
-import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";
+import { type PromptModel } from "@/components/primitives/PromptBar";
import SidebarNav from "@/components/primitives/SidebarNav";
import ConversationsPane from "@/components/site/ConversationsPane";
import FilesPane from "@/components/site/FilesPane";
import BrowserPane from "@/components/site/DesktopBrowserPane";
import { annotationsBlock, type BrowserPin } from "@/lib/browser/annotations";
import { browserClose, browserHandle, browserNav } from "@/lib/browser-client";
-import ChatTranscript from "./ChatTranscript";
+import ChatColumn from "./ChatColumn";
import TasksSidebar from "./TasksSidebar";
import { MAX_COLUMNS, SPLIT_LIMIT_MESSAGE, splitLimitReached } from "./harness-split";
import { useDesktopShortcuts } from "./useDesktopShortcuts";
@@ -41,7 +41,6 @@ import {
import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AcpCommand, type AssistantTurn } from "@/lib/acp";
import { useChatScroll } from "./useChatScroll";
import { enqueuePrompt, shiftQueuedPrompt } from "@/lib/prompt-queue";
-import PromptQueue from "./PromptQueue";
import { usePromptQueue } from "./usePromptQueue";
import { dateGroup, listSessionsPage, relativeTime, removeSession, type StoredSession } from "@/lib/sessions";
import { loadHistory, mergeHistory, pushHistory, saveHistory } from "@/lib/prompt-history";
@@ -209,6 +208,7 @@ export default function GraffHarness() {
}, []);
const requireSession = async (chatId: number, reset = false, key?: string): Promise<string> => {
+ if (chatsRef.current.find(c => c.id === chatId)?.snapshot) throw new Error("Continue here before resuming this saved snapshot.");
const live = sessionsRef.current.get(chatId);
if (!reset && live) return live;
const chat = chatsRef.current.find((c) => c.id === chatId);
@@ -441,7 +441,7 @@ export default function GraffHarness() {
const send = async (text: string, forChat?: number) => {
const trimmed = text.trim();
const chatId = forChat ?? chatThread.id;
- if (!trimmed) return;
+ if (!trimmed || chatsRef.current.find(c => c.id === chatId)?.snapshot) return;
await settings.wait(chatId);
if (runningRef.current.has(chatId) || busyIds.has(chatId)) {
setQueue(chatId, enqueuePrompt(queuesRef.current[chatId] ?? [], trimmed, (queueIdRef.current += 1)));
@@ -481,7 +481,6 @@ export default function GraffHarness() {
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);
},
});
const openStored = (name: string, cwd = activePathRef.current ?? undefined) => savedConversation.open(name, cwd);
@@ -624,110 +623,41 @@ export default function GraffHarness() {
const sidebarWorkspace = activeWorkspace ?? (activePath ? { path: activePath, name: basename(activePath) } : undefined);
const footerTitle = sessionFooterTitle(chatThread.session, sessionId, chatCwd);
- /** One chat column: its transcript (or the empty state) and its composer.
- * A plain function, not a component, so the split view can render two of
- * them without React remounting either on every parent render. */
- const columnBody = (thread: Chat) => {
- const isFollowing = tailing[thread.id] ?? true;
- const hasMessages = thread.messages.length > 0;
- const compactPane = columnIds.length > 1;
- const threadBusy = busyIds.has(thread.id);
- const threadModel = thread.model ?? model ?? undefined;
- const threadQueued = queues[thread.id] ?? [];
- const threadPins = (pinsByChat[thread.id] ?? []).length;
- const threadHistory = mergeHistory(history, thread.messages.flatMap((m) => (m.role === "user" ? [m.text] : [])));
- return (
- <>
-
- {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} 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 && (
- <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">
- <span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Pinned</span>
- <span className="min-w-0 flex-1 truncate text-ink">
- {threadPins} element{threadPins === 1 ? "" : "s"} in the browser go with your next message
- </span>
- <button
- type="button"
- onClick={() => {
- focusChat(thread.id);
- setFilesOpen(false);
- setBrowserOpen(true);
- }}
- className="shrink-0 rounded px-1.5 text-[11.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink"
- >
- Show
- </button>
- <button
- type="button"
- aria-label="Clear pins"
- onClick={() => setPins(thread.id, [])}
- className="flex size-5 shrink-0 items-center justify-center rounded-[5px] text-ink-3 hover:bg-hover hover:text-ink"
- >
- <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden>
- <path d="M18 6L6 18M6 6l12 12" />
- </svg>
- </button>
- </div>
- )}
- <PromptQueue items={threadQueued} busy={threadBusy} status={steerStatus[thread.id]}
- error={cancelError[thread.id]}
- onRemove={item => removeQueued(thread.id, item)}
- onSteer={item => steerer.steer(thread.id, item, () => {
- const session = sessionsRef.current.get(thread.id);
- if (!session) return Promise.reject(new Error("Session unavailable"));
- return cancel(handleOf(thread.id), session);
- })} />
- <PromptBar
- demo={false}
- tall={!compactPane}
- 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)}
- modelKey={threadModel}
- onModelChange={(key: string) => changeModel(key, thread.id)}
- onSend={(text: string) => void send(text, thread.id)} onSetting={text => settings.change(thread.id, text)}
- history={threadHistory}
- busy={threadBusy}
- onStop={() => {
- const live = sessionsRef.current.get(thread.id);
- if (!live) {
- setCancelError(current => ({ ...current, [thread.id]: "Nothing to interrupt yet." }));
- return;
- }
- void cancel(handleOf(thread.id), live).catch(err => {
- setCancelError(current => ({ ...current, [thread.id]: err instanceof Error ? err.message : "Could not interrupt the current turn" }));
- });
- }}
- />
- </div>
- </div>
- </div>
- ) : (
- <div className="min-h-0 flex-1 overflow-y-auto">
- <EmptyState compact={compactPane}
- onOpenProject={() => setDialog({ mode: "new" })}
- onProjects={() => setProjectsOpen(true)}
- onContinue={openConversations} onReview={openChanges}
- onSend={(text: string) => void send(text, thread.id)} onSetting={text => settings.change(thread.id, text)}
- health={health}
- history={threadHistory}
- cwd={cwdOf(thread)}
- models={models}
- modelKey={threadModel}
- onModelChange={(key: string) => changeModel(key, thread.id)}
- commands={commands[thread.id] ?? catalogCommands}
- />
- </div>
- )}
- </>
- );
- };
-
+ const columnBody = (thread: Chat) => <ChatColumn key={thread.id} thread={thread}
+ compact={columnIds.length > 1} following={tailing[thread.id] ?? true} register={paneRef(thread.id)}
+ onOpenPath={openPath} onReview={openChanges}
+ onRefresh={loaded => {
+ const messages: Msg[] = loaded.messages.map(m => ({ id: ++msgIdRef.current, ...m }));
+ setChats(current => current.map(c => c.id === thread.id && c.snapshot ? { ...c, messages } : c));
+ }}
+ onContinue={() => {
+ const next = chatsRef.current.map(c => c.id === thread.id ? { ...c, snapshot: false } : c);
+ chatsRef.current = next; setChats(next);
+ }}
+ prompt={{ demo: false, models, commands: commands[thread.id] ?? catalogCommands,
+ root: cwdOf(thread), modelKey: thread.model ?? model ?? undefined,
+ onModelChange: key => changeModel(key, thread.id), onSend: text => void send(text, thread.id),
+ onSetting: text => settings.change(thread.id, text),
+ history: mergeHistory(history, thread.messages.flatMap(m => m.role === "user" ? [m.text] : [])),
+ busy: busyIds.has(thread.id), onStop: () => {
+ const live = sessionsRef.current.get(thread.id);
+ if (!live) { setCancelError(current => ({ ...current, [thread.id]: "Nothing to interrupt yet." })); return; }
+ void cancel(handleOf(thread.id), live).catch(err => {
+ setCancelError(current => ({ ...current, [thread.id]: err instanceof Error ? err.message : "Could not interrupt the current turn" }));
+ });
+ },
+ }}
+ queue={{ items: queues[thread.id] ?? [], busy: busyIds.has(thread.id), status: steerStatus[thread.id], error: cancelError[thread.id],
+ onRemove: item => removeQueued(thread.id, item), onSteer: item => steerer.steer(thread.id, item, () => {
+ const session = sessionsRef.current.get(thread.id);
+ if (!session) return Promise.reject(new Error("Session unavailable"));
+ return cancel(handleOf(thread.id), session);
+ }),
+ }}
+ pins={(pinsByChat[thread.id] ?? []).length}
+ onShowPins={() => { focusChat(thread.id); setFilesOpen(false); setBrowserOpen(true); }}
+ onClearPins={() => setPins(thread.id, [])} health={health}
+ onOpenProject={() => setDialog({ mode: "new" })} onProjects={() => setProjectsOpen(true)} onConversations={openConversations} />;
useDesktopShortcuts({ closeChat, newChat, reopenClosed, toggleSplit, focusChat, chats, activeId, columns: columnIds,
split: direction => { setSplitDirection(direction); setZoomedPane(null); addPane(); },
diff --git a/apps/native/components/site/SavedSnapshot.tsx b/apps/native/components/site/SavedSnapshot.tsx
new file mode 100644
index 00000000..4178f784
--- /dev/null
+++ b/apps/native/components/site/SavedSnapshot.tsx
@@ -0,0 +1,37 @@
+"use client";
+import { useEffect, useRef, useState } from "react";
+import { loadSession } from "@/lib/sessions";
+
+export default function SavedSnapshot({ name, cwd, onRefresh, onContinue }: {
+ name: string; cwd?: string;
+ onRefresh: (loaded: Awaited<ReturnType<typeof loadSession>>) => void;
+ onContinue: () => void;
+}) {
+ const pending = useRef<AbortController | null>(null);
+ const [refreshing, setRefreshing] = useState(false);
+ const [error, setError] = useState(false);
+ useEffect(() => () => { pending.current?.abort(); }, [name, cwd]);
+ const refresh = async () => {
+ pending.current?.abort();
+ const controller = new AbortController(); pending.current = controller;
+ setRefreshing(true); setError(false);
+ try {
+ const loaded = await loadSession(name, cwd, controller.signal);
+ if (!controller.signal.aborted) onRefresh(loaded);
+ } catch {
+ if (!controller.signal.aborted) setError(true);
+ } finally {
+ if (!controller.signal.aborted) setRefreshing(false);
+ }
+ };
+ return <section data-saved-snapshot aria-label="Saved conversation snapshot" className="rounded-[12px] border border-line bg-surface p-4 text-[13px] text-ink-2">
+ <p role="status" className="font-medium text-ink">Saved snapshot · Live status unknown</p>
+ <p className="mt-1">Work may still be running in another window. Refresh to read the latest save.</p>
+ <p className="mt-1">Stop work in the other window before choosing Continue here.</p>
+ {error && <p role="alert" className="mt-2 text-red">Could not refresh the snapshot. Try again.</p>}
+ <div className="mt-3 flex flex-wrap gap-2">
+ <button type="button" data-refresh-snapshot disabled={refreshing} onClick={() => void refresh()} className="rounded-control px-3 py-1.5 hover:bg-hover disabled:opacity-50">{refreshing ? "Refreshing…" : "Refresh snapshot"}</button>
+ <button type="button" data-continue-snapshot disabled={refreshing} onClick={onContinue} className="rounded-control bg-hover-2 px-3 py-1.5 text-ink disabled:opacity-50">Continue here</button>
+ </div>
+ </section>;
+}
diff --git a/apps/native/components/site/TurnActivity.tsx b/apps/native/components/site/TurnActivity.tsx
index f93ccd95..4122cb55 100644
--- a/apps/native/components/site/TurnActivity.tsx
+++ b/apps/native/components/site/TurnActivity.tsx
@@ -15,10 +15,10 @@ export default function TurnActivity({ turn, snapshot }: { turn: AssistantTurn;
sync(); document.addEventListener("visibilitychange", sync);
return () => { clearInterval(timer); document.removeEventListener("visibilitychange", sync); };
}, [active]);
- if (!turn.startedAt && !active && !turn.error) return null;
+ if (!turn.startedAt && !active && !turn.error && turn.status !== "snapshot") return null;
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>}
+ {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 === "snapshot" ? "○" : 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>
</div>;
}
diff --git a/apps/native/electron/README.md b/apps/native/electron/README.md
index 9aca3f1f..64233203 100644
--- a/apps/native/electron/README.md
+++ b/apps/native/electron/README.md
@@ -114,9 +114,10 @@ harness workspace. The native GUI's ACP bridge uses one stdout reader and
routes replies by request ID so catalog refreshes cannot steal assistant text.
The macOS window keeps native close/minimize/full-screen controls in a reserved
-draggable titlebar. For smoke runs while using another app, set
-`GRAFF_SMOKE_SKIP_INPUT=1` to skip native keyboard injection; the report records
-that omission.
+draggable titlebar. Smoke runs stay hidden by default and require
+`GRAFF_TEST_FOREGROUND=1` before presenting native sheets or injecting native
+keyboard input. Reports record omitted foreground checks. In an explicitly
+foreground run, `GRAFF_SMOKE_SKIP_INPUT=1` still skips native keyboard injection.
The v2 profiler adds document LCP/FCP, maximum observed interaction duration,
recording-period layout shift, renderer heap and DOM size, GPU-process CPU/RSS
diff --git a/apps/native/electron/VISUAL-TESTS.md b/apps/native/electron/VISUAL-TESTS.md
index 9366d818..bb6d1429 100644
--- a/apps/native/electron/VISUAL-TESTS.md
+++ b/apps/native/electron/VISUAL-TESTS.md
@@ -1,11 +1,31 @@
# Desktop visual tests
From `apps/native`, run `bun run build`, then `bun run test:visual`.
-This opens an isolated Electron window, renders scripted turn states, and
+This renders scripted turn states in hidden, isolated Electron windows and
checks visible progress, layout, disclosure state, completion and interruption
in White, Black and CodeGraff themes. PNGs and results go to
`zig-out/visual-tests`; set `GRAFF_VISUAL_OUTPUT` to use another directory.
+All visual suites, standalone GUI coding trials, packaged smoke checks and
+benchmarks use the shared background window policy. Tests keep the user's active
+application focused; creating, switching or cleaning up fixtures does not show
+or activate windows. Page input uses Chromium's trusted input path, including
+real Tab navigation, without sending keyboard or mouse events to the desktop.
+
+On macOS the visual and benchmark launchers start a read-only OS observer before
+Electron. Any activation or visible test window fails the run. The observer needs
+the Xcode command-line tools and requests no Accessibility or screen-capture
+permission. `bun run test:background` exercises the policy without a UI build:
+repeated windows, trusted input, screenshots, rejected activation and cleanup.
+The same background regression runs automatically before default visual suites.
+`bun run test:desktop` checks that future fixtures use the shared policy.
+
+Native fullscreen, native computer input and native sheets require explicit
+opt-in: `GRAFF_TEST_FOREGROUND=1 bun run test:visual`. These checks may activate
+windows and change macOS Spaces. Default reports identify them as not run.
+The foreground option also applies to packaged smoke checks and benchmarks;
+`GRAFF_SMOKE_SKIP_INPUT=1` still disables native computer input in foreground mode.
+
No engine binary, model account, MCP server or model request is used. Requests
to API routes are blocked and fail the test. The fixture page is unavailable
unless the test server sets `GRAFF_VISUAL_TESTS=1`. Tests use the production
@@ -33,10 +53,13 @@ bun run benchmark:desktop /absolute/candidate/apps/native /absolute/local-result
```
The runner creates a fresh profile and uses synthetic code fences, mermaid diagrams, long prose,
-and native wheel input. It measures renderer heap after collection, summed
+and trusted wheel input. It measures renderer heap after collection, summed
process RSS, script/layout work and frame callback intervals. Repeat both runs
-and compare matching scenarios. Keep the window visible on the same display;
-the runner retains production background throttling and hardware acceleration.
+and compare matching scenarios in the same window mode. The default background
+mode disables throttling so hidden pages keep rendering. Reports record the mode.
+For display/presentation measurements, explicitly use `GRAFF_TEST_FOREGROUND=1`
+for both runs and keep the windows on the same display; that mode retains
+production throttling. Both modes retain Chromium hardware acceleration.
RSS includes shared pages and is not an exclusive physical-memory measurement.
Set `GRAFF_BENCHMARK_TRACE=scroll`, `code`, or `mermaid` for a separate local Chromium trace.
diff --git a/apps/native/electron/agents-visual.cjs b/apps/native/electron/agents-visual.cjs
index dc8bb18e..622745fe 100644
--- a/apps/native/electron/agents-visual.cjs
+++ b/apps/native/electron/agents-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
@@ -6,7 +7,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); });
- require('./test-window.cjs').presentWindow(win);
+ testDesktop.present(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/background-regression.cjs b/apps/native/electron/background-regression.cjs
new file mode 100644
index 00000000..d6d230e4
--- /dev/null
+++ b/apps/native/electron/background-regression.cjs
@@ -0,0 +1,48 @@
+const { app, BrowserWindow, WebContentsView } = require('electron');
+const assert = require('node:assert/strict');
+const { createWindow, present, focusTestPage, testInput, assertSafe, cleanup, foreground } = require('./test-desktop.cjs');
+const os = require('node:os'), fs = require('node:fs'), path = require('node:path');
+const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-background-'));
+app.setPath('userData', path.join(temporary, 'profile'));
+app.on('window-all-closed', () => {}); // The test, not the last fixture window, owns exit status.
+const deadline = setTimeout(() => finish(1), 30000);
+async function finish(code) {
+ clearTimeout(deadline);
+ try { assertSafe(); } catch (error) { console.error(error); code = 1; }
+ cleanup(); fs.rmSync(temporary, { recursive: true, force: true }); app.exit(code);
+}
+app.whenReady().then(async () => {
+ assert.equal(foreground, false, 'The background regression must run without foreground opt-in');
+ for (let n = 0; n < 3; n++) {
+ const win = createWindow({ width: 640, height: 480, show: true, webPreferences: { sandbox: true } });
+ present(win);
+ const wc = win.webContents;
+ await wc.loadURL('data:text/html,' + encodeURIComponent('<input id="first"><button id="second" onclick="document.body.dataset.clicked=event.isTrusted">Second</button>'));
+ await focusTestPage(wc);
+ await wc.executeJavaScript('document.querySelector("#first").focus()');
+ await testInput(wc, { type: 'keyDown', keyCode: 'Tab' });
+ await testInput(wc, { type: 'keyUp', keyCode: 'Tab' });
+ assert.equal(await wc.executeJavaScript('document.activeElement.id'), 'second', 'Hidden Chromium still performs real Tab navigation');
+ const point = await wc.executeJavaScript('(()=>{const r=document.querySelector("#second").getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()');
+ await testInput(wc, { type: 'mouseDown', button: 'left', clickCount: 1, ...point });
+ await testInput(wc, { type: 'mouseUp', button: 'left', clickCount: 1, ...point });
+ assert.equal(await wc.executeJavaScript('document.body.dataset.clicked'), 'true', 'Pointer events stay trusted without desktop input');
+ if (n === 1) {
+ const view = new WebContentsView({ webPreferences: { sandbox: true, backgroundThrottling: true } });
+ win.contentView.addChildView(view); view.setBounds({ x: 0, y: 100, width: 400, height: 200 });
+ const page = view.webContents;
+ await page.loadURL('data:text/html,' + encodeURIComponent('<input><script>document.addEventListener("keydown",e=>document.body.dataset.key=e.key)</script>'));
+ await testInput(page, { type: 'keyDown', keyCode: 'Escape' });
+ assert.equal(await page.executeJavaScript('document.body.dataset.key'), 'Escape', 'Input reaches an embedded page without native window focus');
+ win.contentView.removeChildView(view); page.close();
+ }
+ assert.ok(!(await wc.capturePage()).isEmpty(), 'Hidden windows still render screenshots');
+ assert.throws(() => win.show(), /GRAFF_TEST_FOREGROUND/);
+ assert.throws(() => win.focus(), /GRAFF_TEST_FOREGROUND/);
+ assertSafe();
+ if (n !== 1) win.destroy(); // Leave one nested window for failure-style cleanup.
+ }
+ cleanup();
+ assert.equal(BrowserWindow.getAllWindows().length, 0);
+ console.log('Background regression passed: repeated hidden windows, trusted Tab/pointer input, embedded page input, screenshots, blocked activation and complete cleanup.');
+}).then(() => finish(0)).catch(error => { console.error(error); finish(1); });
diff --git a/apps/native/electron/browser-visual.cjs b/apps/native/electron/browser-visual.cjs
index 96a9418b..ccb4590c 100644
--- a/apps/native/electron/browser-visual.cjs
+++ b/apps/native/electron/browser-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const { BrowserWindow, ipcMain, nativeImage } = require('electron');
const { BrowserTabs } = require('./browser-tabs.cjs');
const { browserAction } = require('./browser-actions.cjs');
@@ -13,18 +14,17 @@ 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 { 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 win = testDesktop.createWindow({ 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));
- const pin = (event, value) => { if (event.sender === browser.tabs.get('browser-test')?.view?.webContents) { wc.focus(); wc.send('browser-event', { type: 'pin', chat: 'browser-test', pin: value }); } };
+ const pin = (event, value) => { if (event.sender === browser.tabs.get('browser-test')?.view?.webContents) { void testDesktop.focusTestPage(wc); wc.send('browser-event', { type: 'pin', chat: 'browser-test', pin: value }); } };
const cancelled = event => { if (event.sender === browser.tabs.get('browser-test')?.view?.webContents) wc.send('browser-event', { type: 'pick-cancelled', chat: 'browser-test' }); };
ipcMain.on('browser-pin', pin); ipcMain.on('browser-pick-cancelled', cancelled);
const wait = async (fn, what) => { for (let i = 0; i < 100; i++) { if (await fn()) return; await sleep(50); } throw Error(`Browser visual timed out: ${what}`); };
try {
fixtureWindow.hide();
- presentWindow(win, undefined, { mapped: true });
+ testDesktop.present(win);
await win.loadURL(`${origin}/visual-tests/browser?url=${encodeURIComponent(url)}`);
await wait(() => js(`!!document.querySelector('[aria-pressed="false"]:not(:disabled)')`), 'pin control');
await wait(() => browser.tabs.get('browser-test')?.view?.webContents.getURL() === url, 'fixture URL');
@@ -35,14 +35,14 @@ async function runBrowserVisuals({ win: fixtureWindow, origin, output }) {
await js(`document.querySelector('button[aria-pressed]').click()`);
await wait(() => js(`document.querySelector('button[aria-pressed]').getAttribute('aria-pressed')==='true'`), 'pick armed');
await wait(() => picking(), 'pick mode on page');
- page.focus();
- page.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
+ await testDesktop.focusTestPage(page);
+ await testDesktop.testInput(page, { type: 'keyDown', keyCode: 'Escape' });
await wait(() => js(`document.querySelector('button[aria-pressed]').getAttribute('aria-pressed')==='false'`), 'Escape cancel');
await js(`document.querySelector('button[aria-pressed]').click()`);
await wait(() => picking(), 'pick mode after recancel');
- page.sendInputEvent({ type: 'mouseMove', x: 100, y: 80 });
- page.sendInputEvent({ type: 'mouseDown', x: 100, y: 80, button: 'left', clickCount: 1 });
- page.sendInputEvent({ type: 'mouseUp', x: 100, y: 80, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(page, { type: 'mouseMove', x: 100, y: 80 });
+ await testDesktop.testInput(page, { type: 'mouseDown', x: 100, y: 80, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(page, { type: 'mouseUp', x: 100, y: 80, button: 'left', clickCount: 1 });
await wait(() => js(`!!document.querySelector('[aria-label="Note for pin 1"]')`), 'pin note');
await wait(() => page.executeJavaScript(`document.querySelector('[data-graff-pins]')?.textContent==='1'`), 'pin marker');
assert.equal(await page.executeJavaScript('document.body.dataset.activated || document.body.dataset.clicked || null'), null, 'pinning must not activate the target');
@@ -72,7 +72,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(); presentWindow(fixtureWindow);
+ browser.closeAll(); win.destroy(); fixture.close(); testDesktop.present(fixtureWindow);
}
}
module.exports = { runBrowserVisuals };
diff --git a/apps/native/electron/chat-overflow-visual.cjs b/apps/native/electron/chat-overflow-visual.cjs
index acaddbdb..751f8f6d 100644
--- a/apps/native/electron/chat-overflow-visual.cjs
+++ b/apps/native/electron/chat-overflow-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
@@ -79,8 +80,8 @@ async function runChatOverflow({ win, origin, output }) {
return result.width;
};
const wheel = async (point, deltaX, deltaY) => {
- wc.sendInputEvent({ type: 'mouseMove', ...point });
- wc.sendInputEvent({ type: 'mouseWheel', ...point, deltaX, deltaY, canScroll: true });
+ await testDesktop.testInput(wc, { type: 'mouseMove', ...point });
+ await testDesktop.testInput(wc, { type: 'mouseWheel', ...point, deltaX, deltaY, canScroll: true });
await sleep(200);
};
const viewportWheels = async label => {
diff --git a/apps/native/electron/chat-scroll-visual.cjs b/apps/native/electron/chat-scroll-visual.cjs
index 36421203..0f3503aa 100644
--- a/apps/native/electron/chat-scroll-visual.cjs
+++ b/apps/native/electron/chat-scroll-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
@@ -11,7 +12,7 @@ async function runChatScroll({ win, origin, output }) {
}
throw Error(`Chat scroll timed out: ${code}`);
};
- await wc.loadURL(origin); win.setSize(1100, 760); require('./test-window.cjs').presentWindow(win);
+ await wc.loadURL(origin); win.setSize(1100, 760); testDesktop.present(win);
await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
await js(`(() => {
const previous = window.fetch;
diff --git a/apps/native/electron/composer-interaction-visual.cjs b/apps/native/electron/composer-interaction-visual.cjs
index f7c5fd0d..fff31a50 100644
--- a/apps/native/electron/composer-interaction-visual.cjs
+++ b/apps/native/electron/composer-interaction-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const { ipcMain } = require('electron');
const fs = require('node:fs');
@@ -26,12 +27,12 @@ async function runComposerInteractions({ win, origin, output }) {
const point = await js(`(()=>{const r=document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
// Hover can scroll the active option or reposition its portal. Settle it
// before pressing, then verify that the coordinates still hit this row.
- wc.sendInputEvent({ type: 'mouseMove', ...point });
+ await testDesktop.testInput(wc, { type: 'mouseMove', ...point });
await frames();
const ready = await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)}),r=e.getBoundingClientRect();return Math.round(r.x+r.width/2)===${point.x}&&Math.round(r.y+r.height/2)===${point.y}&&e.contains(document.elementFromPoint(${point.x},${point.y}));})()`);
if (!ready) continue;
- wc.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point });
- wc.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point });
+ await testDesktop.testInput(wc, { type: 'mouseDown', button: 'left', clickCount: 1, ...point });
+ await testDesktop.testInput(wc, { type: 'mouseUp', button: 'left', clickCount: 1, ...point });
await pause();
return;
}
@@ -42,7 +43,7 @@ async function runComposerInteractions({ win, origin, output }) {
const windowActions = [];
ipcMain.handle('window-control', (_event, action) => { windowActions.push(action); });
try {
- await wc.loadURL(origin); win.setSize(1440, 900); win.show(); win.focus();
+ await wc.loadURL(origin); win.setSize(1440, 900); testDesktop.present(win);
await wait(`!!document.querySelector('textarea') && !document.querySelector('[aria-label="Choose model"]').textContent.includes('Loading')`);
await js(`(()=>{
const original=window.fetch;window.composerRequests=[];window.composerCancels=0;window.fileChooserClicks=0;
@@ -67,7 +68,7 @@ async function runComposerInteractions({ win, origin, output }) {
assert.equal(await js('document.querySelector("textarea").value'), '$gui-theme ', 'A portaled skill selection must reach the composer');
// Do not let a stationary pointer hover newly mounted options during IME checks.
- wc.sendInputEvent({ type: 'mouseMove', x: 1, y: 1 });
+ await testDesktop.testInput(wc, { type: 'mouseMove', x: 1, y: 1 });
await frames();
await input('/');
await wait(`document.querySelectorAll('[data-composer-menu] [role="option"]').length>10`);
@@ -116,8 +117,8 @@ async function runComposerInteractions({ win, origin, output }) {
await input('Keep this split draft');
await pointer(`[data-chat="${first}"] textarea`);
// Use a native key event so an accidental textarea newline is observable.
- wc.sendInputEvent({ type: 'keyDown', keyCode: 'Enter', modifiers: ['meta', 'shift'] });
- wc.sendInputEvent({ type: 'keyUp', keyCode: 'Enter', modifiers: ['meta', 'shift'] });
+ await testDesktop.testInput(wc, { type: 'keyDown', keyCode: 'Enter', modifiers: ['meta', 'shift'] });
+ await testDesktop.testInput(wc, { type: 'keyUp', keyCode: 'Enter', modifiers: ['meta', 'shift'] });
await wait(`document.querySelectorAll('[data-chat]').length===1`);
assert.equal(await draft(first), 'First unsent draft', 'Split zoom must not insert a newline');
await key('Enter', { metaKey: true, shiftKey: true });
diff --git a/apps/native/electron/composer-visual.cjs b/apps/native/electron/composer-visual.cjs
index ea8b9650..dab18241 100644
--- a/apps/native/electron/composer-visual.cjs
+++ b/apps/native/electron/composer-visual.cjs
@@ -1,9 +1,10 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
async function runComposerVisual({ win, output }) {
const js = code => win.webContents.executeJavaScript(code);
- require('./test-window.cjs').presentWindow(win);
+ testDesktop.present(win); await testDesktop.focusTestPage(win.webContents);
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.cjs
index 3ab55f04..8d1caec2 100644
--- a/apps/native/electron/dev-preview-visual.cjs
+++ b/apps/native/electron/dev-preview-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const { BrowserWindow } = require('electron');
const { BrowserTabs } = require('./browser-tabs.cjs');
const { startAutomation } = require('./automation.cjs');
@@ -14,9 +15,7 @@ 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 { presentWindow, testWindowOptions } = require('./test-window.cjs');
- const win = new BrowserWindow(testWindowOptions({ width: 900, height: 600 }));
- presentWindow(win);
+ const win = testDesktop.createWindow({ width: 900, height: 600 });
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.cjs
index e5e05e23..d2a8bc09 100644
--- a/apps/native/electron/gui-coding-smoke.cjs
+++ b/apps/native/electron/gui-coding-smoke.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
// Opt-in: a real GUI coding turn in a disposable workspace. Uses configured credentials.
const {app,BrowserWindow,ipcMain}=require('electron');
const {spawn,spawnSync}=require('node:child_process');
@@ -16,16 +17,15 @@ test('empty arrays',()=>expect(()=>median([])).toThrow());\n`);
spawnSync('git',['init','-q'],{cwd:root});
let server,win;const sleep=ms=>new Promise(r=>setTimeout(r,ms));
const deadline=setTimeout(()=>finish(1,new Error('Coding GUI audit timed out')),420000);
-async function finish(code,error){clearTimeout(deadline);if(error)console.error(error.message);if(win&&!win.isDestroyed())win.destroy();if(server?.pid)try{process.kill(-server.pid,'SIGTERM');}catch{}console.log(`Audit artifacts: ${temp}`);app.exit(code);}
+async function finish(code,error){clearTimeout(deadline);if(error)console.error(error.message);try{console.log("Test desktop:",JSON.stringify(testDesktop.assertSafe()));}catch(e){console.error(e);code=1;}testDesktop.cleanup();if(server?.pid)try{process.kill(-server.pid,'SIGTERM');}catch{}console.log(`Audit artifacts: ${temp}`);app.exit(code);}
app.whenReady().then(async()=>{
const ui=path.resolve(__dirname,'..');const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const port=probe.address().port;await new Promise(r=>probe.close(r));const origin=`http://127.0.0.1:${port}`;
const log=fs.openSync(path.join(temp,'server.log'),'w');
server=spawn(process.env.GRAFF_TEST_BUN||'bun',['node_modules/next/dist/bin/next','start','--port',String(port),'--hostname','127.0.0.1'],{cwd:ui,detached:true,stdio:['ignore',log,log],env:{...process.env,GRAFF_CWD:root,GRAFF_BIN:path.resolve(ui,'../../zig-out/bin/graff'),GRAFF_DESKTOP_TOKEN:'',GRAFF_MCP_CONFIG:path.join(temp,'mcp.json'),GRAFF_THEMES_DIR:path.join(temp,'themes'),NEXT_TELEMETRY_DISABLED:'1'}});fs.closeSync(log);
for(let n=0;n<100;n++){try{if((await fetch(origin)).ok)break;}catch{}await sleep(100);}
- 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);
+ win=testDesktop.createWindow({width:1440,height:920,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});installWindowState(win);ipcMain.handle('browser',()=>null);
const js=c=>win.webContents.executeJavaScript(c);const wait=async(c,ms=30000)=>{const end=Date.now()+ms;while(Date.now()<end){if(await js(c))return;await sleep(100);}throw Error(`GUI condition timed out: ${c}`);};
- await win.loadURL(origin);presentWindow(win);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
+ await win.loadURL(origin);testDesktop.present(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/link-destination-visual.cjs b/apps/native/electron/link-destination-visual.cjs
index 2e3b4c28..05ef1e04 100644
--- a/apps/native/electron/link-destination-visual.cjs
+++ b/apps/native/electron/link-destination-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const { BrowserWindow, ipcMain } = require('electron');
const { BrowserTabs } = require('./browser-tabs.cjs');
const { installExternalLinks } = require('./external-links.cjs');
@@ -19,7 +20,7 @@ async function runLinkDestinationVisuals({ origin, output }) {
});
await new Promise(resolve => fixture.listen(0, '127.0.0.1', resolve));
const destination = `http://127.0.0.1:${fixture.address().port}`;
- const win = new BrowserWindow({ width: 1440, height: 900, show: true, webPreferences: {
+ const win = testDesktop.createWindow({ width: 1440, height: 900, webPreferences: {
preload: path.join(__dirname, 'preload.cjs'), partition: `link-destination-${path.basename(directory)}`,
sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false,
} });
@@ -121,7 +122,7 @@ async function runLinkDestinationVisuals({ origin, output }) {
try {
await wc.loadURL('about:blank'); wc.debugger.attach('1.3'); await wc.debugger.sendCommand('Page.enable');
await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `(${installGalleryFixture.toString()})();` });
- await wc.loadURL(origin); win.focus(); await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
+ await wc.loadURL(origin); testDesktop.present(win); await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
assert.equal(await js(`typeof window.graffDesktop.linkSettings`), 'function', 'real preload exposes linkSettings');
await openSettings(); await selected('system');
assert.equal(await store.load(), 'system');
@@ -167,8 +168,8 @@ async function runLinkDestinationVisuals({ origin, output }) {
for (const id of panes) {
const selector = `[data-chat="${id}"] textarea`;
const point = await js(`(()=>{const r=document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
- wc.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point });
- wc.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point });
+ await testDesktop.testInput(wc, { type: 'mouseDown', button: 'left', clickCount: 1, ...point });
+ await testDesktop.testInput(wc, { type: 'mouseUp', button: 'left', clickCount: 1, ...point });
await wait(`document.querySelector('[data-chat][data-focused="true"]')?.dataset.chat===${JSON.stringify(id)}`);
await route('graff', '', `split-${id}`); handles.push(browser.visible);
assert.equal(await js(`document.querySelector('[data-chat][data-focused="true"]').dataset.chat`), id);
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index 5723d6e2..94aa8d50 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -1,4 +1,6 @@
const { app, BrowserWindow, ipcMain, Menu, dialog } = require('electron');
+const testDesktop = process.env.GRAFF_ELECTRON_SMOKE ? require('./test-desktop.cjs') : null;
+const createWindow = testDesktop?.createWindow ?? (options => new BrowserWindow(options));
const path = require('node:path');
const { randomBytes } = require('node:crypto');
const { treeSample, intervalSampler } = require('./process-metrics.cjs');
@@ -35,6 +37,7 @@ async function metrics() {
return { rssMiB, cpuPercent, processes, browsers: browser.liveCount };
}
async function activity() {
+ if (testDesktop && !testDesktop.foreground) throw Error('Native activity checks require GRAFF_TEST_FOREGROUND=1');
const snapshot = await metrics();
if (process.platform === 'darwin') {
const native = require(path.join(resources, 'native/activity.node'));
@@ -48,8 +51,12 @@ function trusted(event) {
}
function stop() {
if (quitting) return; quitting = true;
+ let unsafe = false;
+ try { testDesktop?.assertSafe(); } catch (error) { console.error(error); unsafe = true; }
terminals?.closeAll();
profiler?.stop(); browser?.closeAll(); automation?.server.close(); backend?.stop();
+ testDesktop?.cleanup();
+ if (unsafe) app.exit(1);
}
app.on('before-quit', stop);
app.on('window-all-closed', () => app.quit());
@@ -59,7 +66,7 @@ process.on('SIGINT', () => app.quit());
app.whenReady().then(async () => {
app.setAccessibilitySupportEnabled(true);
const token = randomBytes(32).toString('hex');
- win = new BrowserWindow({ width: 1440, height: 920, minWidth: 900, minHeight: 600,
+ win = createWindow({ width: 1440, height: 920, minWidth: 900, minHeight: 600,
title: 'Codegraff', titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 14, y: 11 }, backgroundColor: '#fafaf9', show: false,
webPreferences: { preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:app',
contextIsolation: true, sandbox: true, nodeIntegration: false, backgroundThrottling: !process.env.GRAFF_ELECTRON_SMOKE } });
@@ -167,6 +174,8 @@ app.whenReady().then(async () => {
] },
{ role: 'windowMenu' },
]));
- await win.loadURL(backend.origin); win.setWindowButtonVisibility(true); win.show(); profiler.record('ui-ready');
+ await win.loadURL(backend.origin); win.setWindowButtonVisibility(true);
+ if (testDesktop) testDesktop.present(win); else win.show();
+ profiler.record('ui-ready');
if (process.env.GRAFF_ELECTRON_SMOKE) require(process.env.GRAFF_SMOKE_LAUNCH_ONLY ? './smoke-launch.cjs' : './smoke.cjs').run({ win, browser, automation, backend, metrics, activity, computer, profiler }).then(() => app.quit()).catch(error => { console.error(error); stop(); app.exit(1); });
}).catch(error => { console.error(error); stop(); app.exit(1); });
diff --git a/apps/native/electron/native/TestFocusMonitor.swift b/apps/native/electron/native/TestFocusMonitor.swift
new file mode 100644
index 00000000..22bbc9bc
--- /dev/null
+++ b/apps/native/electron/native/TestFocusMonitor.swift
@@ -0,0 +1,48 @@
+// Read-only test observer. No activation, input injection, screenshots or AX permissions.
+import AppKit
+import CoreGraphics
+
+var target: pid_t?
+var activations: [pid_t] = []
+var visibleSamples: [pid_t: Int] = [:]
+var finished = false
+func sample() {
+ if let pid = NSWorkspace.shared.frontmostApplication?.processIdentifier,
+ activations.last != pid { activations.append(pid) }
+ if let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] {
+ let owners = Set(windows.compactMap { row -> pid_t? in
+ guard (row[kCGWindowLayer as String] as? Int) == 0,
+ (row[kCGWindowAlpha as String] as? Double ?? 1) > 0 else { return nil }
+ return (row[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value
+ })
+ for pid in owners { visibleSamples[pid, default: 0] += 1 }
+ }
+}
+func finish() {
+ guard !finished else { return }
+ finished = true; sample()
+ let activated = target.map { pid in activations.filter { $0 == pid }.count } ?? 0
+ let visible = target.flatMap { visibleSamples[$0] } ?? 0
+ let report: [String: Any] = ["foregroundActivations": activated, "visibleWindowSamples": visible, "observed": target != nil]
+ let data = try! JSONSerialization.data(withJSONObject: report, options: [.sortedKeys])
+ print(String(data: data, encoding: .utf8)!); fflush(stdout)
+ exit(target != nil && activated == 0 && visible == 0 ? 0 : 1)
+}
+let token = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { notification in
+ if let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication {
+ activations.append(app.processIdentifier)
+ }
+}
+let timer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in sample() }
+sample()
+print("ready"); fflush(stdout)
+DispatchQueue.global().async {
+ while let line = readLine() {
+ DispatchQueue.main.async {
+ if line == "stop" { finish() }
+ else if let pid = pid_t(line) { target = pid; sample() }
+ }
+ }
+ DispatchQueue.main.async { finish() }
+}
+RunLoop.main.run()
diff --git a/apps/native/electron/navigation-keyboard-visual.cjs b/apps/native/electron/navigation-keyboard-visual.cjs
index d5297ee2..162deb53 100644
--- a/apps/native/electron/navigation-keyboard-visual.cjs
+++ b/apps/native/electron/navigation-keyboard-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
async function runNavigationKeyboard({win, origin}) {
@@ -9,8 +10,8 @@ async function runNavigationKeyboard({win, origin}) {
};
// Real input is essential: synthetic KeyboardEvents do not move Tab focus.
const key = async (keyCode, modifiers = []) => {
- wc.sendInputEvent({type: 'keyDown', keyCode, modifiers});
- wc.sendInputEvent({type: 'keyUp', keyCode, modifiers});
+ await testDesktop.testInput(wc, {type: 'keyDown', keyCode, modifiers});
+ await testDesktop.testInput(wc, {type: 'keyUp', keyCode, modifiers});
await pause();
};
const click = selector => js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});e.focus();e.click();})()`);
@@ -18,7 +19,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); require('./test-window.cjs').presentWindow(win);
+ await wc.loadURL(origin); testDesktop.present(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.cjs
index c26d4cbb..41e17a4e 100644
--- a/apps/native/electron/navigation-visual.cjs
+++ b/apps/native/electron/navigation-visual.cjs
@@ -1,11 +1,11 @@
+const testDesktop = require('./test-desktop.cjs');
const {BrowserWindow,ipcMain}=require('electron');
const {installGalleryFixture}=require('./gallery-fixture.cjs');
const {installWindowState}=require('./window-state.cjs');
const assert=require('node:assert/strict');const path=require('node:path');const fs=require('node:fs');
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
async function runNavigationVisuals({win:fixtureWindow,origin,output}) {
- const {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}}));
+ const win=testDesktop.createWindow({width:1100,height:760,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling: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});
@@ -20,12 +20,12 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {
const input=async text=>{await js(`(()=>{const e=document.querySelector('textarea[aria-label="Prompt"]');e.focus();Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,${JSON.stringify(text)});e.dispatchEvent(new Event('input',{bubbles:true}));})()`);await sleep(100);};
const tabs=()=>js(`document.querySelectorAll('[aria-label="Close tab"]').length`);
try {
- fixtureWindow.hide();await wc.loadURL('about:blank');wc.debugger.attach('1.3');await wc.debugger.sendCommand('Page.enable');
+ fixtureWindow.hide();await wc.loadURL('about:blank');testDesktop.attachTestDebugger(wc);await wc.debugger.sendCommand('Page.enable');
await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument',{source:`(${installGalleryFixture.toString()})();
localStorage.setItem('graff.native.workspaces',JSON.stringify(Array.from({length:50},(_,i)=>({name:'Project '+(i%10),path:'/demo/folder-'+i}))));
const commands=[{name:'compact',description:'Compact conversation context'},...Array.from({length:100},(_,i)=>({name:'command-'+i,description:'Command '+i}))];
const galleryFetch=window.fetch;window.fetch=async(input,options)=>{const response=await galleryFetch(input,options);if(options?.body&&JSON.parse(options.body).method==='bootstrap')return new Response(JSON.stringify({sessionId:'demo',commands}),{headers:{'content-type':'application/json'}});if(String(input).includes('/api/models')){const data=await response.json();data.result.commands=commands;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);presentWindow(win);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
+ await wc.loadURL(origin);testDesktop.present(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});
@@ -66,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();presentWindow(fixtureWindow);}
+ } finally {terminals.closeAll();ipcMain.removeHandler('terminal');ipcMain.removeHandler('browser');win.destroy();testDesktop.present(fixtureWindow);}
}
module.exports={runNavigationVisuals};
diff --git a/apps/native/electron/performance-benchmark.cjs b/apps/native/electron/performance-benchmark.cjs
index aa246fca..8d61a309 100644
--- a/apps/native/electron/performance-benchmark.cjs
+++ b/apps/native/electron/performance-benchmark.cjs
@@ -1,4 +1,5 @@
-// Same workload for both builds. Runs a visible production renderer in an isolated profile.
+const testDesktop = require('./test-desktop.cjs');
+// Same workload for both builds. Hidden by default; display measurements opt in.
// Usage: electron electron/performance-benchmark.cjs /absolute/app/root /absolute/output
const { app, BrowserWindow, ipcMain, screen, contentTracing } = require('electron');
const { spawn } = require('node:child_process');
@@ -12,6 +13,7 @@ const { installPerformanceWorkload, frameRecorder, summarizeFrames } = require('
const { treeSample } = require('./process-metrics.cjs');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const root = path.resolve(process.argv[2] || path.join(__dirname, '..'));
+const dist = process.env.GRAFF_NEXT_DIST_DIR || '.next';
const output = path.resolve(process.argv[3] || path.join(root, '../../zig-out/performance/current'));
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-benchmark-'));
app.setPath('userData', path.join(temporary, 'profile'));
@@ -21,7 +23,7 @@ const deadline = setTimeout(() => { console.error('Benchmark exceeded 180 second
app.whenReady().then(async () => {
console.log('Benchmark: launching isolated production app');
fs.mkdirSync(output, { recursive: true });
- assert.ok(fs.existsSync(path.join(root, '.next/BUILD_ID')), 'Build the selected app first');
+ assert.ok(fs.existsSync(path.join(root, dist, 'BUILD_ID')), 'Build the selected app first');
// Match production accessibility policy; never disable assistive technology.
if (fs.readFileSync(path.join(root, 'electron/main.cjs'), 'utf8').includes('app.setAccessibilitySupportEnabled(true)')) app.setAccessibilitySupportEnabled(true);
for (const [channel, result] of [['updates', { status: 'unavailable', currentVersion: '1.0.0', automatic: false, interactive: false }], ['projects', null], ['browser', null]]) ipcMain.handle(channel, () => result);
@@ -40,9 +42,9 @@ app.whenReady().then(async () => {
if (i === 199) throw Error('Benchmark server did not start');
await sleep(100);
}
- 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);
+ win = testDesktop.createWindow({ width: 1440, height: 920, titleBarStyle: 'hiddenInset',
+ webPreferences: { preload: path.join(root, 'electron/preload.cjs'), sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: true } });
+ testDesktop.present(win);
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); });
@@ -57,7 +59,7 @@ app.whenReady().then(async () => {
if (url.origin === origin && url.pathname.startsWith('/api/')) unexpected.push(url.pathname);
callback({ cancel: blocked });
});
- wc.debugger.attach('1.3');
+ testDesktop.attachTestDebugger(wc);
await wc.debugger.sendCommand('Page.enable');
await wc.debugger.sendCommand('Performance.enable');
await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `(${installGalleryFixture.toString()})();(${installPerformanceWorkload.toString()})()` });
@@ -103,7 +105,7 @@ app.whenReady().then(async () => {
};
console.log('Benchmark: warmup');
await send('warmup'); await sleep(1500);
- const report = { workloadVersion: 2, build: fs.readFileSync(path.join(root, '.next/BUILD_ID'), 'utf8').trim(),
+ const report = { workloadVersion: 2, testDesktop: testDesktop.assertSafe(), build: fs.readFileSync(path.join(root, dist, 'BUILD_ID'), 'utf8').trim(),
runtime: { electron: process.versions.electron, chrome: process.versions.chrome },
display: (() => { const display = screen.getDisplayMatching(win.getBounds()); return { frequencyHz: display.displayFrequency, scaleFactor: display.scaleFactor, window: win.getBounds() }; })(),
acceleration: app.getGPUFeatureStatus(), accessibility: app.accessibilitySupportEnabled,
@@ -126,7 +128,7 @@ app.whenReady().then(async () => {
// Real wheel input exercises Chromium's scroll path, including main-thread listeners.
const point = await js(`(()=>{const r=document.querySelector('[data-chat-transcript]').getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
for (let i = 0; i < 360; i++) {
- wc.sendInputEvent({ type: 'mouseWheel', ...point, deltaY: i % 180 < 90 ? -24 : 24, deltaX: 0, canScroll: true });
+ await testDesktop.testInput(wc, { type: 'mouseWheel', ...point, deltaY: i % 180 < 90 ? -24 : 24, deltaX: 0, canScroll: true });
await sleep(8);
}
};
@@ -148,7 +150,9 @@ app.whenReady().then(async () => {
function finish(code) {
clearTimeout(deadline);
- if (win && !win.isDestroyed()) win.destroy();
+ try { console.log('Test desktop:', JSON.stringify(testDesktop.assertSafe())); }
+ catch (error) { console.error(error); code = 1; }
+ testDesktop.cleanup();
if (server?.pid) try { process.kill(-server.pid, 'SIGTERM'); } catch {}
fs.rmSync(temporary, { recursive: true, force: true });
app.exit(code);
diff --git a/apps/native/electron/performance-scenarios.cjs b/apps/native/electron/performance-scenarios.cjs
index 7f7463d0..49df46a7 100644
--- a/apps/native/electron/performance-scenarios.cjs
+++ b/apps/native/electron/performance-scenarios.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const path = require('node:path');
@@ -9,9 +10,8 @@ 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 { 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 } }));
+ const win = testDesktop.createWindow({ width: 1440, height: 920, titleBarStyle: 'hiddenInset',
+ webPreferences: { preload: path.join(__dirname, 'preload.cjs'), sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
fixtureWindow.destroy();
await win.loadURL('about:blank');
ipcMain.handle('browser', () => null);
@@ -20,10 +20,10 @@ async function runPerformance({ win: fixtureWindow, origin, output }) {
const wc = win.webContents, js = code => wc.executeJavaScript(code);
wc.on('console-message', event => { if (/Error|error|Illegal/.test(event.message || '')) console.error('Fixture renderer:', event.message); });
const wait = async expression => { for (let n = 0; n < 300; n++) { if (await js(expression)) return; await sleep(50); } throw Error(`Scenario timeout: ${expression}; ${await js("JSON.stringify({state:document.querySelector('[data-turn-activity]')?.textContent,text:document.querySelector('article')?.textContent,visibility:document.visibilityState})")}`); };
- wc.debugger.attach('1.3');
+ testDesktop.attachTestDebugger(wc);
await wc.debugger.sendCommand('Page.enable');
await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `(${installGalleryFixture.toString()})()` });
- win.setSize(1440, 920); presentWindow(win);
+ win.setSize(1440, 920); testDesktop.present(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); };
@@ -47,8 +47,8 @@ async function runPerformance({ win: fixtureWindow, origin, output }) {
await js('document.fonts.ready.then(()=>true)');
const click = async selector => {
const point = await js(`(()=>{const r=document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
- wc.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
- wc.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(wc, { type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(wc, { type: 'mouseUp', ...point, button: 'left', clickCount: 1 });
};
const capture = async name => {
console.log('Performance: capture', name);
@@ -84,6 +84,7 @@ async function runPerformance({ win: fixtureWindow, origin, output }) {
await send('Stream the demonstration transcript.');
await profiler.capture(0); profiler.stop();
const report = profiler.report();
+ report.testDesktop = testDesktop.assertSafe();
report.scenario = 'Synthetic full GUI: baseline startup and controls; candidate streamed transcript. Different workloads, not a before/after optimization claim. No engine or model calls.';
fs.writeFileSync(path.join(output, 'performance.json'), JSON.stringify(report, null, 2));
console.log(JSON.stringify({ baseline: report.baseline, streaming: report.candidate, acceleration: report.acceleration }));
diff --git a/apps/native/electron/project-recovery-visual.cjs b/apps/native/electron/project-recovery-visual.cjs
index cc99dcd2..75257bbf 100644
--- a/apps/native/electron/project-recovery-visual.cjs
+++ b/apps/native/electron/project-recovery-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
@@ -135,7 +136,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"]')`);
- require('./test-window.cjs').presentWindow(win);
+ testDesktop.present(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.cjs
index cffa6dec..b5cffbb9 100644
--- a/apps/native/electron/review-recovery-visual.cjs
+++ b/apps/native/electron/review-recovery-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
@@ -51,7 +52,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"]')`);
- require('./test-window.cjs').presentWindow(win);
+ testDesktop.present(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/saved-session-visual.cjs b/apps/native/electron/saved-session-visual.cjs
new file mode 100644
index 00000000..fad6a511
--- /dev/null
+++ b/apps/native/electron/saved-session-visual.cjs
@@ -0,0 +1,90 @@
+const testDesktop = require('./test-desktop.cjs');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { installGalleryFixture } = require('./gallery-fixture.cjs');
+
+// Exercise the real conversation picker, decoder, transcript and composer.
+// Only transport is synthetic; no provider calls or real session files.
+async function runSavedSessionVisuals({ win, origin, output }) {
+ const wc = win.webContents, js = source => wc.executeJavaScript(source);
+ const wait = async source => {
+ for (let i = 0; i < 150; i++) {
+ if (await js(source)) return;
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ fs.writeFileSync(path.join(output, 'saved-session-failed.png'), (await wc.capturePage()).toPNG());
+ throw Error(`Saved session timeout: ${source}`);
+ };
+ await wc.loadURL('about:blank');
+ testDesktop.attachTestDebugger(wc);
+ await wc.debugger.sendCommand('Page.enable');
+ const { identifier } = await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `
+ (${installGalleryFixture.toString()})();
+ const previousFetch = window.fetch;
+ window.savedFixture = { completed: false, fail: false, requests: [] };
+ const row = name => ({ name, title: name, updatedMs: 100, model: null, provider: null, size: 100 });
+ window.fetch = async (input, options) => {
+ const url = new URL(String(input), location.origin), fixture = window.savedFixture;
+ if (url.pathname === '/api/acp' && options?.body) fixture.requests.push(JSON.parse(options.body));
+ if (url.pathname !== '/api/sessions') return previousFetch(input, options);
+ const json = value => new Response(JSON.stringify(value), { headers: { 'content-type': 'application/json' } });
+ const name = url.searchParams.get('name');
+ if (!name) return json({ sessions: [row('active-repl'), row('empty-repl')], total: 2, nextCursor: null });
+ if (fixture.fail) return new Response('Snapshot unavailable', { status: 503 });
+ return json({ ...row(name), messages: name === 'empty-repl' ? [] : [
+ { role: 'user', content: 'Check the files and report the result.' },
+ { role: 'assistant', content: 'I am checking the remaining files.', tool_calls: [
+ { id: 'check', function: { name: 'bash', arguments: '{"command":"check-files"}' } }
+ ] },
+ ...(fixture.completed ? [{ role: 'tool', tool_call_id: 'check', content: 'Checks passed.' },
+ { role: 'assistant', content: 'All files checked.' }] : [])
+ ] });
+ };
+ ` });
+ try {
+ await wc.loadURL(origin);
+ await wait(`!!document.querySelector('[aria-label="Conversations"]')`);
+ await js(`document.querySelector('[aria-label="Conversations"]').click()`);
+ await wait(`document.querySelector('[data-conversation-library]')?.textContent.includes('active-repl')`);
+ await js(`Array.from(document.querySelectorAll('[data-conversation-library] li button')).find(e=>e.textContent.includes('active-repl')).click()`);
+ await wait(`document.body.textContent.includes('I am checking the remaining files.')`);
+ await wait(`!!document.querySelector('[data-saved-snapshot]')`);
+ assert.match(await js(`document.querySelector('[data-saved-snapshot]').textContent`), /Live status unknown/);
+ assert.equal(await js(`document.querySelector('[data-chat] textarea[aria-label="Prompt"]')`), null, 'Snapshot cannot accept follow-ups');
+ assert.equal(await js(`document.querySelector('article')?.dataset.turnStatus`), 'snapshot', 'Intermediate prose is not a completed turn');
+ assert.equal(await js(`document.querySelector('[data-turn-activity]')?.textContent.includes('Turn finished')`), false);
+ const resumed = () => js(`window.savedFixture.requests.filter(r=>r.method==='bootstrap'&&r.params?.resume==='active-repl').length`);
+ assert.equal(await resumed(), 0, 'Opening shared history must not resume its writer');
+ assert.equal(await js(`window.savedFixture.requests.some(r=>r.method==='session/prompt')`), false);
+ await js(`window.savedFixture.fail=true;document.querySelector('[data-saved-snapshot] [data-refresh-snapshot]').click()`);
+ await wait(`!!document.querySelector('[data-saved-snapshot] [role="alert"]')`);
+ assert.ok(await js(`document.body.textContent.includes('I am checking the remaining files.')`), 'Refresh failure preserves history');
+ await js(`window.savedFixture.fail=false;window.savedFixture.completed=true;document.querySelector('[data-refresh-snapshot]').click()`);
+ await wait(`document.body.textContent.includes('All files checked.')`);
+ assert.match(await js(`document.querySelector('[data-saved-snapshot]').textContent`), /Live status unknown/, 'Successful refresh is still a snapshot');
+ assert.equal(await resumed(), 0);
+ await js('document.fonts.ready.then(()=>true)');
+ await js(`Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{}))).then(()=>true)`);
+ assert.equal(await js(`getComputedStyle(document.querySelector('article')).opacity`), '1');
+ fs.writeFileSync(path.join(output, 'saved-session-snapshot.png'), (await wc.capturePage()).toPNG());
+ await js(`document.querySelector('[data-continue-snapshot]').click()`);
+ await wait(`!!document.querySelector('[data-chat] textarea[aria-label="Prompt"]')`);
+ assert.equal(await resumed(), 0, 'Explicit continuation enables the composer; spawning waits for a prompt');
+ await js(`(()=>{const e=document.querySelector('[data-chat] textarea[aria-label="Prompt"]');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,'Continue the review.');e.dispatchEvent(new Event('input',{bubbles:true}));})()`);
+ await js(`document.querySelector('[data-chat] textarea').dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true,cancelable:true}))`);
+ await wait(`window.savedFixture.requests.some(r=>r.method==='session/prompt')`);
+ assert.equal(await resumed(), 1);
+ await wait(`!!document.querySelector('[data-turn-activity="done"]')`);
+ await js(`document.querySelector('[aria-label="Conversations"]').click()`);
+ await wait(`document.querySelector('[data-conversation-library]')?.textContent.includes('empty-repl')`);
+ await js(`Array.from(document.querySelectorAll('[data-conversation-library] li button')).find(e=>e.textContent.includes('empty-repl')).click()`);
+ await wait(`!!document.querySelector('[data-saved-snapshot]')`);
+ assert.equal(await js(`document.querySelector('[data-chat] textarea')`), null, 'Empty saved sessions also require explicit continuation');
+ console.log('Saved session GUI checks passed: intermediate commentary, read-only ownership, failed/completed refresh, explicit continuation, empty history.');
+ } finally {
+ await wc.debugger.sendCommand('Page.removeScriptToEvaluateOnNewDocument', { identifier });
+ wc.debugger.detach();
+ }
+}
+module.exports = { runSavedSessionVisuals };
diff --git a/apps/native/electron/smoke-desktop.cjs b/apps/native/electron/smoke-desktop.cjs
index d1c50b0d..8c3674b8 100644
--- a/apps/native/electron/smoke-desktop.cjs
+++ b/apps/native/electron/smoke-desktop.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const { spawn } = require('node:child_process');
const readline = require('node:readline');
@@ -38,15 +39,17 @@ async function smokeDesktop({ automation, computer, win, browser }) {
assert.equal((await invoke('computer', { action: 'requestPermissions' })).isError, true);
// Native discovery is read-only; never request OS permission from an automated test.
const apps = computer.native('apps');
- assert.ok(apps.apps.some(app => app.pid === process.pid));
+ assert.ok(Array.isArray(apps.apps));
+ if (testDesktop.foreground) assert.ok(apps.apps.some(app => app.pid === process.pid));
assert.equal(await win.webContents.executeJavaScript(`fetch('/api/browser').then(r=>r.status)`), 410);
const permissions = computer.status();
- let nativeInput = process.env.GRAFF_SMOKE_SKIP_INPUT ? 'Skipped interactive input for this run' : 'OS permission unavailable';
- if (!process.env.GRAFF_SMOKE_SKIP_INPUT && permissions.accessibility && permissions.screenRecording) {
+ let nativeInput = !testDesktop.foreground ? 'Native input requires GRAFF_TEST_FOREGROUND=1'
+ : process.env.GRAFF_SMOKE_SKIP_INPUT ? 'Skipped interactive input for this run' : 'OS permission unavailable';
+ if (testDesktop.foreground && !process.env.GRAFF_SMOKE_SKIP_INPUT && permissions.accessibility && permissions.screenRecording) {
computer.enabled = true;
try {
const wc = browser.tabs.get('smoke').view.webContents;
- require('./test-window.cjs').presentWindow(win);
+ testDesktop.present(win); await testDesktop.focusTestPage(wc);
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-model-picker.cjs b/apps/native/electron/smoke-model-picker.cjs
index ad8cb369..7958b892 100644
--- a/apps/native/electron/smoke-model-picker.cjs
+++ b/apps/native/electron/smoke-model-picker.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
@@ -32,8 +33,8 @@ async function smokeModelPicker({ win }) {
assert.equal(await js(`document.activeElement.getAttribute('aria-activedescendant')===document.querySelectorAll('[role=option]')[1].id`), true);
// Click the current choice through real mouse events; it must stay clickable in the portal.
const point = await js(`(()=>{const r=document.querySelector('[role=option]').getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
- win.webContents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
- win.webContents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(win.webContents, { type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(win.webContents, { type: 'mouseUp', ...point, button: 'left', clickCount: 1 });
await wait(`!document.querySelector('[aria-label="Choose a model"]')`);
await click('[aria-label="Choose model"]');
await wait(`!!document.querySelector('[aria-label="Choose a model"]')`);
diff --git a/apps/native/electron/smoke-review-resize.cjs b/apps/native/electron/smoke-review-resize.cjs
index 4de1036f..c6cc9d3b 100644
--- a/apps/native/electron/smoke-review-resize.cjs
+++ b/apps/native/electron/smoke-review-resize.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function smokeReviewResize({ win }) {
@@ -5,11 +6,11 @@ async function smokeReviewResize({ win }) {
const paneWidth = () => js(`document.querySelector('[aria-label="Workspace changes"]').getBoundingClientRect().width`);
const original = await paneWidth();
const point = await js(`(()=>{const r=document.querySelector('[aria-label="Resize changes panel"]').getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+100)}})()`);
- win.webContents.sendInputEvent({ type: 'mouseMove', ...point });
- win.webContents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
- win.webContents.sendInputEvent({ type: 'mouseMove', x: point.x + 90, y: point.y, button: 'left' });
+ await testDesktop.testInput(win.webContents, { type: 'mouseMove', ...point });
+ await testDesktop.testInput(win.webContents, { type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(win.webContents, { type: 'mouseMove', x: point.x + 90, y: point.y, button: 'left' });
await sleep(100);
- win.webContents.sendInputEvent({ type: 'mouseUp', x: point.x + 90, y: point.y, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(win.webContents, { type: 'mouseUp', x: point.x + 90, y: point.y, button: 'left', clickCount: 1 });
await sleep(100);
const resized = await paneWidth();
assert.ok(Math.abs(original - resized - 90) < 3, `drag changed width ${original} → ${resized}`);
diff --git a/apps/native/electron/smoke-ui.cjs b/apps/native/electron/smoke-ui.cjs
index 70a6c938..45894a3e 100644
--- a/apps/native/electron/smoke-ui.cjs
+++ b/apps/native/electron/smoke-ui.cjs
@@ -1,7 +1,8 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function smokeUI({ win, browser, backend }) {
- require('./test-window.cjs').presentWindow(win, require('electron').app);
+ testDesktop.present(win);
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.cjs
index d90236f4..b8e237ee 100644
--- a/apps/native/electron/smoke.cjs
+++ b/apps/native/electron/smoke.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const http = require('node:http');
const fs = require('node:fs');
@@ -52,10 +53,10 @@ async function run({ win, browser, automation, backend, metrics, activity, compu
await 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)}})()');
- 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 });
+ testDesktop.present(win); await testDesktop.focusTestPage(wc); await sleep(300);
+ await testDesktop.testInput(wc, {type:'mouseMove', ...point});
+ await testDesktop.testInput(wc, { type: 'mouseDown', ...point, button: 'left', clickCount: 1 });
+ await testDesktop.testInput(wc, { type: 'mouseUp', ...point, button: 'left', clickCount: 1 });
assert.equal((await pinReceived).element.selector, '#button');
report.desktop = await require('./smoke-desktop.cjs').smokeDesktop({ automation, computer, win, browser });
await request('zoom', { factor: 1.2 });
@@ -97,11 +98,14 @@ async function run({ win, browser, automation, backend, metrics, activity, compu
report.settings = 'real ACP effort and fast commands updated harness state';
await win.webContents.executeJavaScript(`fetch('/api/acp',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({chat:'electron-smoke',method:'dispose'})})`);
- await activity(); report.swiftUI = 'native module loaded and sheet presented';
+ if (testDesktop.foreground) {
+ await activity(); report.swiftUI = 'native module loaded and sheet presented';
+ } else report.swiftUI = 'Native sheet requires GRAFF_TEST_FOREGROUND=1';
+ report.testDesktop = testDesktop.assertSafe();
await sleep(500);
const output = process.env.GRAFF_ELECTRON_SMOKE;
fs.writeFileSync(output, JSON.stringify(report, null, 2));
- console.log('Electron smoke passed: navigation, isolation, pins, automation, suspension, real ACP, SwiftUI.');
+ console.log('Electron smoke passed: navigation, isolation, pins, automation, suspension, real ACP. Native sheet:', report.swiftUI);
} finally { fixture.close(); fs.rmSync(cwd, { recursive: true, force: true }); }
}
module.exports = { run };
diff --git a/apps/native/electron/split-focus-visual.cjs b/apps/native/electron/split-focus-visual.cjs
index f27978b5..b216a1eb 100644
--- a/apps/native/electron/split-focus-visual.cjs
+++ b/apps/native/electron/split-focus-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const path=require('node:path');
@@ -8,10 +9,10 @@ async function runSplitFocus({win,origin,output}) {
const ids=()=>js(`Array.from(document.querySelectorAll('[data-chat]')).map(e=>Number(e.dataset.chat))`);
const pointer=async selector=>{
const point=await js(`(()=>{const r=document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
- wc.sendInputEvent({type:'mouseDown',button:'left',clickCount:1,...point});wc.sendInputEvent({type:'mouseUp',button:'left',clickCount:1,...point});
+ await testDesktop.testInput(wc, {type:'mouseDown',button:'left',clickCount:1,...point});await testDesktop.testInput(wc, {type:'mouseUp',button:'left',clickCount:1,...point});
await new Promise(r=>setTimeout(r,100));
};
- await wc.loadURL(origin);win.setSize(1440,900);require('./test-window.cjs').presentWindow(win);
+ await wc.loadURL(origin);win.setSize(1440,900);testDesktop.present(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`);
@@ -40,7 +41,7 @@ async function runSplitFocus({win,origin,output}) {
const before=await js(`document.querySelector('[data-chat]').getBoundingClientRect().${direction==='row'?'width':'height'}`);
const start=await js(`(()=>{const r=document.querySelector('[data-chat-divider]').getBoundingClientRect();return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`);
const end={...start,[direction==='row'?'x':'y']:start[direction==='row'?'x':'y']+delta};
- wc.sendInputEvent({type:'mouseDown',button:'left',clickCount:1,...start});wc.sendInputEvent({type:'mouseMove',button:'left',...end});wc.sendInputEvent({type:'mouseUp',button:'left',clickCount:1,...end});
+ await testDesktop.testInput(wc, {type:'mouseDown',button:'left',clickCount:1,...start});await testDesktop.testInput(wc, {type:'mouseMove',button:'left',...end});await testDesktop.testInput(wc, {type:'mouseUp',button:'left',clickCount:1,...end});
await new Promise(r=>setTimeout(r,100));
const after=await js(`document.querySelector('[data-chat]').getBoundingClientRect().${direction==='row'?'width':'height'}`);
assert.ok(after>before+20,`Mouse divider must resize ${direction} panes: ${before} -> ${after}`);
diff --git a/apps/native/electron/stress-visual.cjs b/apps/native/electron/stress-visual.cjs
index b0b83249..7b8cc876 100644
--- a/apps/native/electron/stress-visual.cjs
+++ b/apps/native/electron/stress-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const { BrowserWindow } = require('electron');
const { installWindowState } = require('./window-state.cjs');
const assert = require('node:assert/strict');
@@ -5,8 +6,7 @@ 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 {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}}));
+ const win = testDesktop.createWindow({width:1000,height:760,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});
installWindowState(win);
const js = code => win.webContents.executeJavaScript(code);
const wait = async expression => {for(let i=0;i<200;i++){if(await js(expression))return;await sleep(50);}throw Error(`Stress timeout: ${expression}`);};
@@ -18,7 +18,7 @@ async function runStressVisuals({win: fixtureWindow, origin, output, fullscreen
assert.equal(r.overflow,false);assert.ok(r.top>=0&&r.bottom<=r.height,JSON.stringify(r));
};
try {
- fixtureWindow.hide();presentWindow(win);await win.loadURL(`${origin}/visual-tests/stress`);
+ fixtureWindow.hide();testDesktop.present(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');
@@ -50,9 +50,9 @@ async function runStressVisuals({win: fixtureWindow, origin, output, fullscreen
await click('[data-stream]');
const titleHeight=()=>js(`document.querySelector('[data-desktop-titlebar]').getBoundingClientRect().height`);
assert.equal(await titleHeight(),36);
- const checkedFullscreen = fullscreen && process.platform === 'darwin';
+ const checkedFullscreen = fullscreen && process.platform === 'darwin' && testDesktop.foreground;
if(checkedFullscreen) {
- require('./test-window.cjs').presentWindow(win);
+ testDesktop.present(win); await testDesktop.focusTestPage(win.webContents);
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,7 +60,7 @@ async function runStressVisuals({win: fixtureWindow, origin, output, fullscreen
win.setFullScreen(false);await wait(`document.documentElement.dataset.desktopFullscreen==='false'`);assert.equal(await titleHeight(),36);
}
fs.writeFileSync(path.join(output,'stress-results.json'),JSON.stringify({passed:['5000 tools','bounded output','1000 messages','unbroken input','long markdown','stream reading position',...(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();presentWindow(fixtureWindow);}
+ console.log('Stress visual checks passed: long tools/output/history/text, reading position. Fullscreen:', checkedFullscreen?'passed':'requires GRAFF_TEST_FOREGROUND=1');
+ } finally {win.destroy();testDesktop.present(fixtureWindow);}
}
module.exports={runStressVisuals};
diff --git a/apps/native/electron/task-rows-visual.cjs b/apps/native/electron/task-rows-visual.cjs
index bac736d3..c3fa6d30 100644
--- a/apps/native/electron/task-rows-visual.cjs
+++ b/apps/native/electron/task-rows-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert = require('node:assert/strict');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
@@ -14,11 +15,12 @@ async function testTaskRows({ win, origin }) {
const row = index => `document.querySelector('[data-task-rows]').firstElementChild.children[${index}]`;
const expanded = index => `${row(index)}.querySelector('button')?.getAttribute('aria-expanded')`;
const key = async keyCode => {
- win.webContents.sendInputEvent({ type: 'keyDown', keyCode });
- if (keyCode === 'Enter' || keyCode === 'Space') {
- win.webContents.sendInputEvent({ type: 'char', keyCode: keyCode === 'Enter' ? '\r' : ' ' });
+ await testDesktop.testInput(win.webContents, { type: 'keyDown', keyCode });
+ // Chromium's background Enter already carries its character event.
+ if ((keyCode === 'Enter' && testDesktop.foreground) || keyCode === 'Space') {
+ await testDesktop.testInput(win.webContents, { type: 'char', keyCode: keyCode === 'Enter' ? '\r' : ' ' });
}
- win.webContents.sendInputEvent({ type: 'keyUp', keyCode });
+ await testDesktop.testInput(win.webContents, { type: 'keyUp', keyCode });
await sleep(40);
};
let revision = 0;
@@ -44,7 +46,7 @@ async function testTaskRows({ win, origin }) {
};
await win.loadURL(`${origin}/visual-tests/tasks`);
await wait(`document.querySelector('[data-tasks-fixture]')?.dataset.ready==='true'`);
- win.show(); win.focus();
+ testDesktop.present(win);
await js('document.fonts.ready.then(()=>true)');
for (const variant of ['Capsules', 'List']) {
const items = [
diff --git a/apps/native/electron/terminal-visual.cjs b/apps/native/electron/terminal-visual.cjs
index a6d6cd6b..17d6fe1d 100644
--- a/apps/native/electron/terminal-visual.cjs
+++ b/apps/native/electron/terminal-visual.cjs
@@ -1,3 +1,4 @@
+const testDesktop = require('./test-desktop.cjs');
const assert=require('node:assert/strict');const fs=require('node:fs');const path=require('node:path');
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
async function runTerminalVisual({win,output}) {
@@ -8,7 +9,7 @@ async function runTerminalVisual({win,output}) {
await wait(`document.querySelector('[data-workspace-terminal]').textContent.includes('Shell ready')`);
await js(`document.querySelector('.xterm-helper-textarea').focus()`);
await wc.insertText("printf '\\n%s\\n' TERMINAL_GUI_READY");
- wc.sendInputEvent({type:"keyDown",keyCode:"Return"});wc.sendInputEvent({type:"keyUp",keyCode:"Return"});
+ await testDesktop.testInput(wc, {type:"keyDown",keyCode:"Return"});await testDesktop.testInput(wc, {type:"keyUp",keyCode:"Return"});
await wait(`Array.from(document.querySelectorAll('.xterm-rows > div')).some(row=>row.textContent.trim()==='TERMINAL_GUI_READY')`);
const before=await js(`document.querySelector('[data-workspace-terminal]').getBoundingClientRect().height`);
await js(`document.querySelector('[aria-label="Resize terminal"]').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowUp',bubbles:true}))`);
diff --git a/apps/native/electron/test-desktop.cjs b/apps/native/electron/test-desktop.cjs
new file mode 100644
index 00000000..5d113619
--- /dev/null
+++ b/apps/native/electron/test-desktop.cjs
@@ -0,0 +1,43 @@
+const { createTestWindowPolicy } = require('./test-window-policy.cjs');
+// Requiring this module is explicit: only test entrypoints and fixtures use it.
+const policy = createTestWindowPolicy(require('electron'));
+const buttons = new WeakMap();
+const attachTestDebugger = wc => { if (!wc.debugger.isAttached()) wc.debugger.attach('1.3'); };
+async function focusTestPage(wc) {
+ // Select the target WebContentsView inside its hidden, unfocusable window.
+ // This does not activate the BrowserWindow (the native policy forbids that).
+ wc.focus();
+ if (policy.foreground) return;
+ wc.setBackgroundThrottling(false);
+ attachTestDebugger(wc);
+ // Focus inside Chromium, never in the desktop window manager. This preserves
+ // native Tab navigation and trusted input while another application is active.
+ await wc.debugger.sendCommand('Emulation.setFocusEmulationEnabled', { enabled: true });
+}
+const modifierBits = list => (list ?? []).reduce((bits, name) => bits | ({ alt: 1, control: 2, ctrl: 2, meta: 4, shift: 8 }[name] ?? 0), 0);
+async function testInput(wc, event) {
+ if (policy.foreground) { wc.sendInputEvent(event); return; }
+ await focusTestPage(wc);
+ const modifiers = modifierBits(event.modifiers);
+ if (event.type === 'char') return wc.debugger.sendCommand('Input.dispatchKeyEvent', { type: 'char', text: event.keyCode, modifiers });
+ if (event.type.startsWith('key')) {
+ const key = event.keyCode === 'Return' ? 'Enter' : event.keyCode === 'Space' ? ' ' : event.keyCode;
+ const code = { Tab: 9, Enter: 13, Escape: 27, Backspace: 8, Delete: 46, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40 }[key]
+ ?? (key.length === 1 ? key.toUpperCase().charCodeAt(0) : undefined);
+ if (code === undefined) throw Error(`Unsupported test key: ${key}`);
+ return wc.debugger.sendCommand('Input.dispatchKeyEvent', { type: event.type, key,
+ code: key === ' ' ? 'Space' : key.length === 1 ? `Key${key.toUpperCase()}` : key, windowsVirtualKeyCode: code, modifiers,
+ ...(key === 'Enter' && event.type === 'keyDown' && !modifiers ? { text: '\r' } : {}) });
+ }
+ const type = { mouseDown: 'mousePressed', mouseUp: 'mouseReleased', mouseMove: 'mouseMoved', mouseWheel: 'mouseWheel' }[event.type];
+ if (!type) throw Error(`Unsupported test input: ${event.type}`);
+ const bit = { left: 1, right: 2, middle: 4 }[event.button] ?? 0;
+ const pressed = event.type === 'mouseDown' ? (buttons.get(wc) ?? 0) | bit
+ : event.type === 'mouseUp' ? (buttons.get(wc) ?? 0) & ~bit : buttons.get(wc) ?? 0;
+ buttons.set(wc, pressed);
+ return wc.debugger.sendCommand('Input.dispatchMouseEvent', { type, x: event.x, y: event.y,
+ button: event.button ?? (pressed & 1 ? 'left' : 'none'), buttons: pressed,
+ clickCount: event.clickCount ?? 0, modifiers,
+ ...(type === 'mouseWheel' ? { deltaX: -(event.deltaX ?? 0), deltaY: -(event.deltaY ?? 0) } : {}) });
+}
+module.exports = { ...policy, attachTestDebugger, focusTestPage, testInput };
diff --git a/apps/native/electron/test-window-policy.cjs b/apps/native/electron/test-window-policy.cjs
new file mode 100644
index 00000000..7ac5f5f9
--- /dev/null
+++ b/apps/native/electron/test-window-policy.cjs
@@ -0,0 +1,46 @@
+// Test-only policy. Production windows must not import or inherit this policy.
+const assert = require('node:assert/strict');
+function createTestWindowPolicy({ app, BrowserWindow }, env = process.env, platform = process.platform) {
+ const foreground = env.GRAFF_TEST_FOREGROUND === '1';
+ const violations = [], observed = new Set();
+ if (!foreground && platform === 'darwin') app.setActivationPolicy('prohibited');
+ const guard = win => {
+ if (observed.has(win)) return;
+ observed.add(win);
+ if (foreground) return;
+ for (const event of ['show', 'focus']) win.on(event, () => violations.push(`Unexpected window ${event}`));
+ // Fail before a test or cleanup path can expose or activate its window.
+ for (const method of ['show', 'showInactive', 'focus', 'restore', 'maximize', 'setFullScreen']) {
+ win[method] = () => { throw Error(`${method} requires GRAFF_TEST_FOREGROUND=1`); };
+ }
+ };
+ app.on('browser-window-created', (_event, win) => guard(win));
+ if (!foreground) app.focus = () => { throw Error('app.focus requires GRAFF_TEST_FOREGROUND=1'); };
+ const options = value => ({ ...value, show: false, focusable: foreground,
+ webPreferences: { ...value.webPreferences, ...(!foreground ? { backgroundThrottling: false } : {}) } });
+ return {
+ foreground,
+ createWindow(value) {
+ const win = new BrowserWindow(options(value)); guard(win); return win;
+ },
+ present(win) {
+ if (foreground) { win.show(); win.focus(); }
+ },
+ assertSafe() {
+ if (!foreground) {
+ assert.deepEqual(violations, [], 'Background tests must never show or activate native windows');
+ for (const win of BrowserWindow.getAllWindows()) {
+ assert.equal(win.isVisible(), false, 'A background test window became visible');
+ assert.equal(win.isFocused(), false, 'A background test window took native focus');
+ }
+ }
+ return { mode: foreground ? 'foreground' : 'background', windows: observed.size, violations: [...violations] };
+ },
+ cleanup() {
+ // Every window, including windows created by nested suites or failed steps.
+ for (const win of BrowserWindow.getAllWindows()) win.destroy();
+ assert.equal(BrowserWindow.getAllWindows().length, 0, 'Test windows remain after cleanup');
+ },
+ };
+}
+module.exports = { createTestWindowPolicy };
diff --git a/apps/native/electron/test-window-policy.test.cjs b/apps/native/electron/test-window-policy.test.cjs
new file mode 100644
index 00000000..04037e19
--- /dev/null
+++ b/apps/native/electron/test-window-policy.test.cjs
@@ -0,0 +1,85 @@
+const { test, expect } = require('bun:test');
+const { EventEmitter } = require('node:events');
+const { createTestWindowPolicy } = require('./test-window-policy.cjs');
+const fs = require('node:fs');
+const path = require('node:path');
+const ts = require('typescript');
+function fixture(env = {}) {
+ const app = new EventEmitter(), calls = [], windows = new Set();
+ app.setActivationPolicy = value => calls.push(value);
+ app.focus = () => calls.push('app.focus');
+ class Window extends EventEmitter {
+ constructor(options) { super(); this.options = options; windows.add(this); app.emit('browser-window-created', {}, this); }
+ static getAllWindows() { return [...windows]; }
+ show() { this.visible = true; this.emit('show'); }
+ focus() { this.focused = true; this.emit('focus'); }
+ isVisible() { return !!this.visible; }
+ isFocused() { return !!this.focused; }
+ destroy() { windows.delete(this); }
+ }
+ return { policy: createTestWindowPolicy({ app, BrowserWindow: Window }, env, 'darwin'), app, calls, Window };
+}
+test('#832: every background test window rejects native activation, including cleanup paths', () => {
+ const { policy, app, calls } = fixture();
+ const a = policy.createWindow({ show: true, focusable: true, webPreferences: { sandbox: true, backgroundThrottling: true } });
+ const b = policy.createWindow({});
+ expect(calls).toEqual(['prohibited']);
+ expect(a.options).toMatchObject({ show: false, focusable: false, webPreferences: { sandbox: true, backgroundThrottling: false } });
+ policy.present(a); policy.present(b);
+ for (const action of ['show', 'showInactive', 'focus', 'restore', 'maximize', 'setFullScreen']) {
+ expect(() => b[action](true)).toThrow('GRAFF_TEST_FOREGROUND=1');
+ }
+ expect(() => app.focus()).toThrow('GRAFF_TEST_FOREGROUND=1');
+ expect(policy.assertSafe()).toEqual({ mode: 'background', windows: 2, violations: [] });
+ policy.cleanup();
+ expect(policy.assertSafe().violations).toEqual([]);
+});
+test('#832: one exact opt-in enables foreground checks; unrelated flags never enable them', () => {
+ for (const env of [{ GRAFF_TEST_FOREGROUND: '0' }, { GRAFF_TEST_FOREGROUND: 'true' }, { GRAFF_PERFORMANCE_TESTS: '1' }, { GRAFF_ELECTRON_SMOKE: '/tmp/report' }]) {
+ const { policy } = fixture(env);
+ expect(policy.foreground).toBe(false); policy.cleanup();
+ }
+ const { policy, calls } = fixture({ GRAFF_TEST_FOREGROUND: '1' });
+ const win = policy.createWindow({}); policy.present(win);
+ expect(calls).toEqual([]); expect(win.isVisible()).toBe(true); expect(win.isFocused()).toBe(true);
+ expect(policy.assertSafe().mode).toBe('foreground'); policy.cleanup();
+});
+test('#832: unsolicited show/focus events fail verification and all failed-suite windows are cleaned up', () => {
+ const { policy, Window } = fixture();
+ const win = policy.createWindow({});
+ win.emit('focus');
+ expect(() => policy.assertSafe()).toThrow('must never show or activate');
+ policy.createWindow({});
+ policy.cleanup();
+ expect(Window.getAllWindows()).toEqual([]);
+});
+
+test('#832: all GUI test modules use the shared window and input policy', () => {
+ // Parse actual calls, not renderer JS embedded in fixture strings: focusing a
+ // DOM control is expected, activating a native test window is not.
+ const files = fs.readdirSync(__dirname).filter(name => /visual|smoke|performance-(benchmark|scenarios)/.test(name) && name.endsWith('.cjs') && !name.endsWith('.test.cjs'));
+ const bypasses = [];
+ for (const name of files) {
+ const source = ts.createSourceFile(name, fs.readFileSync(path.join(__dirname, name), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+ const visit = node => {
+ if (ts.isNewExpression(node) && /BrowserWindow$/.test(node.expression.getText(source))) bypasses.push(`${name}: direct BrowserWindow`);
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
+ const owner = node.expression.expression.getText(source), method = node.expression.name.text;
+ if (method === 'sendInputEvent' || (['show', 'showInactive', 'focus', 'restore', 'maximize'].includes(method) && /^(win|fixtureWindow|app)$/.test(owner))) {
+ bypasses.push(`${name}: ${owner}.${method}`);
+ }
+ if (method === 'setFullScreen' || (owner === 'computer' && method === 'command' && node.arguments[0]?.text === 'type')) {
+ let parent = node.parent, guarded = false;
+ while (parent) {
+ if (ts.isIfStatement(parent) && /testDesktop.foreground|checkedFullscreen/.test(parent.expression.getText(source))) guarded = true;
+ parent = parent.parent;
+ }
+ if (!guarded) bypasses.push(`${name}: unguarded native ${method}`);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ }
+ expect(bypasses).toEqual([]);
+});
diff --git a/apps/native/electron/test-window.cjs b/apps/native/electron/test-window.cjs
index 106b9638..da5faf8e 100644
--- a/apps/native/electron/test-window.cjs
+++ b/apps/native/electron/test-window.cjs
@@ -1,31 +1,22 @@
-/** Default GUI tests stay off the user's desktop (#832). Foreground
- * interaction is opt-in via GRAFF_ELECTRON_FOREGROUND=1. */
-
+// Compatibility helpers; new fixtures use test-desktop.cjs.
function testWindowMode() {
- if (process.env.GRAFF_ELECTRON_FOREGROUND === '1') return 'foreground';
- if (process.env.GRAFF_ELECTRON_VISIBLE === '1') return 'visible';
+ if (process.env.GRAFF_TEST_FOREGROUND === '1') return 'foreground';
return 'hidden';
}
function presentWindow(win, app, extra = {}) {
- // A WebContentsView host has to be mapped: the chrome measures the
- // pane with getBoundingClientRect, and sendInputEvent only reaches
- // the page when the view is visible. showInactive keeps #832 — we
- // still do not steal focus unless foreground is requested.
- const mode = extra.mapped && testWindowMode() === 'hidden' ? 'visible' : testWindowMode();
+ 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 || {}) } };
+ return { ...extra, show: false, 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.cjs
index ca259f88..7f57b1b3 100644
--- a/apps/native/electron/test-window.test.cjs
+++ b/apps/native/electron/test-window.test.cjs
@@ -2,37 +2,37 @@ 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 previous = process.env.GRAFF_TEST_FOREGROUND;
const visible = process.env.GRAFF_ELECTRON_VISIBLE;
- delete process.env.GRAFF_ELECTRON_FOREGROUND;
+ delete process.env.GRAFF_TEST_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_TEST_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';
+ const previous = process.env.GRAFF_TEST_FOREGROUND;
+ process.env.GRAFF_TEST_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;
+ process.env.GRAFF_TEST_FOREGROUND = previous;
});
-test('mapped presentWindow shows inactive so a BrowserView host can measure', () => {
- const previous = process.env.GRAFF_ELECTRON_FOREGROUND;
+test('mapped BrowserView fixtures cannot make hidden windows visible', () => {
+ const previous = process.env.GRAFF_TEST_FOREGROUND;
const visible = process.env.GRAFF_ELECTRON_VISIBLE;
- delete process.env.GRAFF_ELECTRON_FOREGROUND;
+ delete process.env.GRAFF_TEST_FOREGROUND;
delete process.env.GRAFF_ELECTRON_VISIBLE;
const calls = [];
- expect(presentWindow({ show() { calls.push('show'); }, focus() { calls.push('focus'); }, showInactive() { calls.push('inactive'); }, webContents: { isDestroyed: () => false, setBackgroundThrottling() {} } }, { focus() { calls.push('steal'); } }, { mapped: true })).toBe('visible');
- expect(calls).toEqual(['inactive']);
- process.env.GRAFF_ELECTRON_FOREGROUND = previous;
+ expect(presentWindow({ show() { calls.push('show'); }, focus() { calls.push('focus'); }, showInactive() { calls.push('inactive'); }, webContents: { isDestroyed: () => false, setBackgroundThrottling() {} } }, { focus() { calls.push('steal'); } }, { mapped: true })).toBe('hidden');
+ expect(calls).toEqual([]);
+ process.env.GRAFF_TEST_FOREGROUND = previous;
process.env.GRAFF_ELECTRON_VISIBLE = visible;
});
diff --git a/apps/native/electron/updates-visual.cjs b/apps/native/electron/updates-visual.cjs
index 5760d305..a13ea1ca 100644
--- a/apps/native/electron/updates-visual.cjs
+++ b/apps/native/electron/updates-visual.cjs
@@ -1,13 +1,13 @@
+const testDesktop = require('./test-desktop.cjs');
const { BrowserWindow } = require('electron');
const assert = require('node:assert/strict'), fs = require('node:fs'), path = require('node:path');
async function runUpdateVisuals({ origin, output }) {
- const { presentWindow, testWindowOptions } = require('./test-window.cjs');
- const win = new BrowserWindow(testWindowOptions({ width: 900, height: 650, webPreferences: { sandbox: true, contextIsolation: true } }));
+ const win = testDesktop.createWindow({ width: 900, height: 650, webPreferences: { sandbox: true, contextIsolation: true, backgroundThrottling: false } });
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 {
await wc.loadURL('about:blank');
- wc.debugger.attach('1.3');
+ testDesktop.attachTestDebugger(wc);
await wc.debugger.sendCommand('Page.enable');
await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `
window.__restarts=0;window.__automatic=true;let listener;
@@ -20,7 +20,7 @@ async function runUpdateVisuals({ origin, output }) {
return {...base(),status:'idle'};
}};` });
await win.loadURL(`${origin}/visual-tests`);
- presentWindow(win);
+ testDesktop.present(win);
console.log('Update visual fixture loaded.');
await wait(`!!document.querySelector('[data-case="waiting"]')`);
for (const status of ['checking', 'error', 'current']) {
@@ -45,8 +45,8 @@ async function runUpdateVisuals({ origin, output }) {
})()`);
assert.equal(target.visible, true, 'restart action is visible and receives pointer input');
fs.writeFileSync(path.join(output, 'update-ready.png'), (await wc.capturePage(undefined, { stayAwake: true })).toPNG());
- wc.sendInputEvent({ type: 'mouseDown', x: Math.round(target.x), y: Math.round(target.y), button: 'left', clickCount: 1 });
- wc.sendInputEvent({ type: 'mouseUp', x: Math.round(target.x), y: Math.round(target.y), button: 'left', clickCount: 1 });
+ await testDesktop.testInput(wc, { type: 'mouseDown', x: Math.round(target.x), y: Math.round(target.y), button: 'left', clickCount: 1 });
+ await testDesktop.testInput(wc, { type: 'mouseUp', x: Math.round(target.x), y: Math.round(target.y), button: 'left', clickCount: 1 });
await wait(`window.__restarts===1`);
await wait(`document.querySelector('[data-desktop-update]')?.textContent.includes('Preparing to restart')`);
await js(`document.querySelector('[data-desktop-update-settings]').click()`);
diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjs
index 8b57ee89..3c297921 100644
--- a/apps/native/electron/visual-tests.cjs
+++ b/apps/native/electron/visual-tests.cjs
@@ -1,5 +1,5 @@
+const testDesktop = require('./test-desktop.cjs');
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');
@@ -12,11 +12,12 @@ app.setPath('userData', path.join(temporary, 'profile'));
let server, win;
const deadline = setTimeout(() => { console.error('Visual run exceeded 240 seconds'); finish(1); }, 240000);
app.whenReady().then(async () => {
+ const savedOnly = process.env.GRAFF_VISUAL_SUITE === 'sessions';
ipcMain.handle('updates', () => ({ status: 'unavailable', currentVersion: '1.0.0', automatic: false, interactive: false }));
ipcMain.handle('projects', () => null);
const root = path.resolve(__dirname, '..'), output = process.env.GRAFF_VISUAL_OUTPUT || path.resolve(root, '../../zig-out/visual-tests');
fs.mkdirSync(output, { recursive: true });
- assert.ok(fs.existsSync(path.join(root, '.next/BUILD_ID')), 'Run bun run build before visual tests.');
+ assert.ok(fs.existsSync(path.join(root, process.env.GRAFF_NEXT_DIST_DIR || '.next', 'BUILD_ID')), 'Run bun run build before visual tests.');
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve));
const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
const origin = `http://127.0.0.1:${port}`;
@@ -24,8 +25,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(testWindowOptions({ width: 900, height: 600, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } }));
- presentWindow(win, app);
+ win = testDesktop.createWindow({ width: 900, height: 600, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ testDesktop.present(win);
const apiRequests = [];
win.webContents.session.webRequest.onBeforeRequest((details, callback) => {
const url = new URL(details.url);
@@ -51,6 +52,18 @@ app.whenReady().then(async () => {
fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: ['update UI', 'update transport'], apiRequests }, null, 2));
return;
}
+ if (savedOnly) {
+ await require('./saved-session-visual.cjs').runSavedSessionVisuals({ win, origin, output });
+ assert.deepEqual(apiRequests, [], 'Saved session fixtures never call engine or model APIs');
+ testDesktop.assertSafe();
+ return;
+ }
+ if (process.env.GRAFF_VISUAL_SUITE === 'browser') {
+ await require('./browser-visual.cjs').runBrowserVisuals({ win, origin, output });
+ await require('./dev-preview-visual.cjs').runDevPreview({ output });
+ assert.deepEqual(apiRequests, [], 'Browser fixtures never call engine or model APIs');
+ return;
+ }
if (['projects', 'splits', 'interactions'].includes(process.env.GRAFF_VISUAL_SUITE)) {
await require('./navigation-visual.cjs').runNavigationVisuals({ win, origin, output });
if (process.env.GRAFF_VISUAL_SUITE !== 'interactions') {
@@ -111,6 +124,7 @@ app.whenReady().then(async () => {
await require('./chat-overflow-visual.cjs').runChatOverflow({ win, origin, output });
await require('./chat-overflow-edge-visual.cjs').runOverflowEdges({ win, origin });
await require('./stress-visual.cjs').runStressVisuals({ win, origin, output });
+ await require('./saved-session-visual.cjs').runSavedSessionVisuals({ win, origin, output });
await require('./navigation-visual.cjs').runNavigationVisuals({ win, origin, output });
await require('./browser-visual.cjs').runBrowserVisuals({ win, origin, output });
await require('./agents-visual.cjs').runAgentVisuals({ win, origin, output });
@@ -125,8 +139,13 @@ app.whenReady().then(async () => {
}).then(() => finish(0)).catch(error => { console.error(error); finish(1); });
function finish(code) {
clearTimeout(deadline);
- if (win && !win.isDestroyed()) win.destroy();
+ try {
+ console.log('Test desktop:', JSON.stringify(testDesktop.assertSafe()));
+ } catch (error) { console.error(error); code = 1; }
+ testDesktop.cleanup();
if (server?.pid) try { process.kill(-server.pid, 'SIGTERM'); } catch {}
app.once('quit', () => { fs.rmSync(temporary, { recursive: true, force: true }); });
app.exit(code);
}
+process.on('SIGTERM', () => finish(1));
+process.on('SIGINT', () => finish(1));
diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.ts
index e641fb00..84bad6b5 100644
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@ -75,7 +75,7 @@ export type AskPrompt = {
question: string;
};
-export type TurnStatus = "thinking" | "streaming" | "ask" | "done" | "error";
+export type TurnStatus = "thinking" | "streaming" | "ask" | "done" | "error" | "snapshot";
export type AssistantTurn = {
startedAt?: number;
diff --git a/apps/native/lib/session-projection.test.ts b/apps/native/lib/session-projection.test.ts
index cd6926a8..9faf2143 100644
--- a/apps/native/lib/session-projection.test.ts
+++ b/apps/native/lib/session-projection.test.ts
@@ -6,6 +6,7 @@ import { NextRequest } from "next/server";
import { GET } from "../app/api/sessions/route";
import { loadSession, sessionFromResponse, transcriptFromMessages } from "./sessions";
import { withGuiSkillContext } from "./gui-skills";
+import { turnActivity } from "./turn-activity";
const raw = [
{ role: "system", content: "Not conversation text" },
@@ -123,3 +124,21 @@ test("the projected client keeps empty legacy histories and server failures read
await expect(loadSession("example")).rejects.toThrow("503: Temporarily unavailable");
} finally { globalThis.fetch = previous; }
});
+
+test("#839: intermediate and final-looking saved prose cannot establish live completion", () => {
+ const meta = { name: "active", title: null, model: null, provider: null, updatedMs: 100, size: 100 };
+ for (const content of ["I am checking the remaining files.", "All files checked."]) {
+ const messages = [{ role: "user", content: "Check the files" }, { role: "assistant", content }];
+ const projected = transcriptFromMessages(messages);
+ // Older projection servers claimed completion; the client must not trust it.
+ const oldProjection = projected.map(m => m.role === "assistant" ? { ...m, turn: { ...m.turn, status: "done" as const } } : m);
+ for (const body of [{ ...meta, messages }, { ...meta, presentation: "transcript-v1" as const, transcript: oldProjection }]) {
+ const loaded = sessionFromResponse(body);
+ const answer = loaded.messages[1];
+ expect(answer.role).toBe("assistant");
+ if (answer.role !== "assistant") throw Error("Missing assistant");
+ expect(answer.turn.status).toBe("snapshot");
+ expect(turnActivity(answer.turn, 100_000)).toEqual({ state: "snapshot", label: "Saved snapshot", detail: "Live status unknown", live: false });
+ }
+ }
+});
diff --git a/apps/native/lib/sessions.test.ts b/apps/native/lib/sessions.test.ts
index 70546402..6aed5992 100644
--- a/apps/native/lib/sessions.test.ts
+++ b/apps/native/lib/sessions.test.ts
@@ -46,7 +46,7 @@ describe("transcriptFromMessages", () => {
const first = out[1];
assert.equal(first.role, "assistant");
if (first.role !== "assistant") return;
- assert.equal(first.turn.status, "done");
+ assert.equal(first.turn.status, "snapshot");
assert.equal(first.turn.model, "glm-5.3-flash");
assert.equal(first.turn.text, "Created demo.md.");
assert.equal(first.turn.tools.length, 1);
@@ -60,10 +60,10 @@ 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");
+ assert.equal(last.turn.status, "snapshot");
});
- it("keeps a last turn thinking when a tool result never arrived (#839)", () => {
+ it("keeps pending tool rows in a saved snapshot when a 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"}' } }] },
@@ -71,7 +71,7 @@ describe("transcriptFromMessages", () => {
assert.equal(out.length, 2);
const turn = out[1];
if (turn.role !== "assistant") return;
- assert.equal(turn.turn.status, "thinking");
+ assert.equal(turn.turn.status, "snapshot");
assert.equal(turn.turn.tools[0].status, "running");
});
diff --git a/apps/native/lib/sessions.ts b/apps/native/lib/sessions.ts
index 2213eb68..85d5c83c 100644
--- a/apps/native/lib/sessions.ts
+++ b/apps/native/lib/sessions.ts
@@ -56,7 +56,7 @@ export function sessionFromResponse(body: SessionResponse): { meta: StoredSessio
// 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),
+ ? transcript.map(message => message.role === "assistant" ? { ...message, turn: { ...message.turn, status: "snapshot" } } : message) : transcriptFromMessages(messages ?? [], meta.model ?? undefined),
};
}
@@ -237,11 +237,10 @@ export function transcriptFromMessages(raw: unknown[], model?: string): Transcri
let turn: AssistantTurn | null = null;
const flush = () => {
if (!turn) return;
- const pending = turn.tools.some((row) => row.status === "running");
- out.push({ role: "assistant", turn: { ...turn, status: pending ? "thinking" : "done" } });
+ out.push({ role: "assistant", turn: { ...turn, status: "snapshot" } });
turn = null;
};
- const current = (): AssistantTurn => (turn ??= { ...emptyTurn(), model, status: "thinking" });
+ const current = (): AssistantTurn => (turn ??= { ...emptyTurn(), model, status: "snapshot" });
for (const item of raw) {
if (!item || typeof item !== "object") continue;
diff --git a/apps/native/lib/turn-activity.ts b/apps/native/lib/turn-activity.ts
index 0b6dde37..c70eaec3 100644
--- a/apps/native/lib/turn-activity.ts
+++ b/apps/native/lib/turn-activity.ts
@@ -1,5 +1,6 @@
import type { AssistantTurn } from "./graff-events";
export function turnActivity(turn: AssistantTurn, now: number, opts?: { snapshot?: boolean }) {
+ if (turn.status === "snapshot" || opts?.snapshot) return { state: "snapshot", label: "Saved snapshot", detail: "Live status unknown", live: false };
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));
diff --git a/apps/native/package.json b/apps/native/package.json
index 72ddd245..7a07aab1 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -25,6 +25,8 @@
"test:overflow": "GRAFF_VISUAL_SUITE=overflow node scripts/test-visual.mjs",
"test:agents": "GRAFF_VISUAL_SUITE=agents bun scripts/test-visual.mjs",
"test:tasks": "GRAFF_VISUAL_SUITE=tasks node scripts/test-visual.mjs",
+ "test:sessions": "GRAFF_VISUAL_SUITE=sessions bun scripts/test-visual.mjs",
+ "test:background": "bun scripts/test-background.mjs",
"test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs",
"benchmark:desktop": "bun scripts/benchmark-desktop.mjs"
},
diff --git a/apps/native/scripts/benchmark-desktop.mjs b/apps/native/scripts/benchmark-desktop.mjs
index 098259fe..c3b98306 100644
--- a/apps/native/scripts/benchmark-desktop.mjs
+++ b/apps/native/scripts/benchmark-desktop.mjs
@@ -1,10 +1,2 @@
-import { createRequire } from 'node:module';
-import { spawn } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-const require = createRequire(import.meta.url);
-const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const args = [path.join(root, 'electron/performance-benchmark.cjs'), ...process.argv.slice(2)];
-const child = spawn(require('electron'), args, { cwd: root, stdio: 'inherit', env: { ...process.env, GRAFF_TEST_BUN: process.execPath } });
-child.on('error', error => { console.error(error.message); process.exitCode = 1; });
-child.on('exit', code => { process.exitCode = code ?? 1; });
+import { runElectron } from './test-electron.mjs';
+await runElectron('electron/performance-benchmark.cjs', process.argv.slice(2));
diff --git a/apps/native/scripts/test-background.mjs b/apps/native/scripts/test-background.mjs
new file mode 100644
index 00000000..b5040912
--- /dev/null
+++ b/apps/native/scripts/test-background.mjs
@@ -0,0 +1,2 @@
+import { runElectron } from './test-electron.mjs';
+await runElectron('electron/background-regression.cjs');
diff --git a/apps/native/scripts/test-electron.mjs b/apps/native/scripts/test-electron.mjs
new file mode 100644
index 00000000..97c5513a
--- /dev/null
+++ b/apps/native/scripts/test-electron.mjs
@@ -0,0 +1,77 @@
+import { spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { createRequire } from 'node:module';
+import { existsSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { createInterface } from 'node:readline';
+import { fileURLToPath } from 'node:url';
+const require = createRequire(import.meta.url);
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+async function focusMonitor() {
+ const source = path.join(root, 'electron/native/TestFocusMonitor.swift');
+ const hash = createHash('sha256').update(readFileSync(source)).digest('hex').slice(0, 16);
+ const binary = path.join(tmpdir(), `graff-test-focus-${process.arch}-${hash}`);
+ if (!existsSync(binary)) await new Promise((resolve, reject) => {
+ const compiler = spawn('xcrun', ['swiftc', source, '-o', binary], { stdio: ['ignore', 'ignore', 'pipe'] });
+ let errors = '';
+ compiler.stderr.on('data', data => { errors += data; });
+ compiler.once('error', reject);
+ compiler.once('exit', code => code === 0 ? resolve() : reject(Error(`Could not build desktop focus observer: ${errors}`)));
+ });
+ const child = spawn(binary, [], { stdio: ['pipe', 'pipe', 'inherit'] });
+ const lines = createInterface({ input: child.stdout });
+ let report;
+ const exited = new Promise(resolve => child.once('exit', code => resolve(code)));
+ try {
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(Error('Desktop focus observer did not start')), 15000);
+ child.once('error', error => { clearTimeout(timer); reject(error); });
+ child.once('exit', () => { clearTimeout(timer); reject(Error('Desktop focus observer exited before readiness')); });
+ lines.on('line', line => {
+ if (line === 'ready') { clearTimeout(timer); resolve(); }
+ else { try { report = JSON.parse(line); } catch {} }
+ });
+ });
+ } catch (error) { child.kill(); throw error; }
+ return {
+ watch(pid) { child.stdin.write(`${pid}\n`); },
+ async stop() {
+ child.stdin.end('stop\n');
+ const timer = setTimeout(() => child.kill(), 5000);
+ const code = await exited; clearTimeout(timer); lines.close();
+ if (code !== 0 || !report?.observed || report.foregroundActivations || report.visibleWindowSamples) {
+ throw Error(`Desktop isolation failed: ${JSON.stringify(report ?? { observerExit: code })}`);
+ }
+ return report;
+ },
+ };
+}
+
+// The observer starts before Electron, so it catches launch activation as well
+// as later test steps. Switching to a different user app is allowed throughout.
+export async function runElectron(entry, args = []) {
+ const foreground = process.env.GRAFF_TEST_FOREGROUND === '1';
+ const monitor = process.platform === 'darwin' && !foreground ? await focusMonitor() : null;
+ const child = spawn(require('electron'), [path.resolve(root, entry), ...args], {
+ cwd: root, stdio: 'inherit', env: { ...process.env, GRAFF_TEST_BUN: process.execPath },
+ });
+ if (child.pid) monitor?.watch(child.pid);
+ const interrupt = signal => { child.kill(signal); };
+ const term = () => interrupt('SIGTERM'), sigint = () => interrupt('SIGINT');
+ process.once('SIGTERM', term); process.once('SIGINT', sigint);
+ let code = 1;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once('error', reject);
+ child.once('exit', exit => resolve(exit ?? 1));
+ });
+ } finally {
+ process.removeListener('SIGTERM', term); process.removeListener('SIGINT', sigint);
+ if (monitor) console.log('Desktop isolation:', JSON.stringify(await monitor.stop()));
+ else console.log(`Desktop isolation: ${foreground ? 'foreground opt-in' : 'native window policy (OS observer is macOS-only)'}`);
+ }
+ process.exitCode = code;
+ return code;
+}
diff --git a/apps/native/scripts/test-visual.mjs b/apps/native/scripts/test-visual.mjs
index d6c26aa0..a212b3f0 100644
--- a/apps/native/scripts/test-visual.mjs
+++ b/apps/native/scripts/test-visual.mjs
@@ -1,6 +1,4 @@
-import { createRequire } from 'node:module';
-import { spawn } from 'node:child_process';
-const require = createRequire(import.meta.url);
-const child = spawn(require('electron'), ['electron/visual-tests.cjs'], { stdio: 'inherit', env: { ...process.env, GRAFF_TEST_BUN: process.execPath } });
-child.on('error', error => { console.error(error.message); process.exitCode = 1; });
-child.on('exit', code => { process.exitCode = code ?? 1; });
+import { runElectron } from './test-electron.mjs';
+const ready = process.env.GRAFF_TEST_FOREGROUND === '1'
+ || await runElectron('electron/background-regression.cjs') === 0;
+if (ready) await runElectron('electron/visual-tests.cjs');
diff --git a/docs/adr/0099-gui-saved-sessions-are-snapshots.md b/docs/adr/0099-gui-saved-sessions-are-snapshots.md
index 6530652f..fc981dad 100644
--- a/docs/adr/0099-gui-saved-sessions-are-snapshots.md
+++ b/docs/adr/0099-gui-saved-sessions-are-snapshots.md
@@ -25,5 +25,11 @@ can still show in-progress work. That is display state, not a live attach.
## Consequences
+Opening and refreshing history never bootstrap an ACP session. The composer
+is replaced by Refresh snapshot and Continue here controls, including for empty
+histories. Continue here enables composing; the first prompt resumes the saved
+session. Saved turns keep unknown execution status after refresh, including
+when reading older projected responses.
+
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/0101-gui-tests-preserve-desktop-focus.md b/docs/adr/0101-gui-tests-preserve-desktop-focus.md
new file mode 100644
index 00000000..06748fbe
--- /dev/null
+++ b/docs/adr/0101-gui-tests-preserve-desktop-focus.md
@@ -0,0 +1,40 @@
+# 0101. GUI tests preserve desktop focus by default
+
+Status: accepted 2026-09-10
+
+## Context
+
+Independent GUI suites created visible windows and repeatedly called native
+show/focus methods, including while restoring fixture windows during cleanup.
+Making one suite hidden did not protect other suites or launch-time activation
+(#832). Native input injection also coupled tests to the user's focused app.
+
+## Decision
+
+All Electron test windows use one test-only policy. Background is the default:
+windows start hidden and unfocusable, macOS application activation is prohibited,
+and later native show/focus operations fail before executing. Cleanup destroys
+every test window, including windows left by nested suites or failed steps.
+
+Page-level tests send trusted Chromium protocol input and emulate page focus.
+This keeps pointer routing and real Tab navigation testable without activating
+the operating-system window. Background fixtures disable renderer throttling.
+
+Only `GRAFF_TEST_FOREGROUND=1` opts into visible windows and native interaction.
+Fullscreen, native computer input and native sheets require that opt-in. Reports
+identify omitted native checks and benchmark window mode; background frame
+timing must not be presented as foreground display timing.
+
+The visual and benchmark launchers start a read-only macOS focus/window observer
+before Electron. Activation or visible test windows fail the run. User switching
+between other apps is allowed. A standalone background regression exercises
+repeated windows, trusted input, screenshots, rejected activation and cleanup.
+Unit and source-policy tests keep new fixtures from bypassing the shared helpers.
+
+## Consequences
+
+Ordinary GUI verification can run while the user works elsewhere. Foreground
+native checks remain separately opt-in. The OS observer requires the macOS
+command-line developer tools; other platforms use native-window assertions.
+Production application window behavior is unchanged; packaged smoke mode alone
+uses the test policy.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index af2a22e1..5eaeeeeb 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -111,6 +111,7 @@ record only when you need the evidence or the edge cases.
| [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. |
| [0100](0100-publication-claims-and-verified-completion.md) | Non-draft PRs fail closed on CI/Verification/helper-only claims; artifact presence ACK is not ownership; recipe success is verified task success. |
+| [0101](0101-gui-tests-preserve-desktop-focus.md) | GUI tests stay hidden with trusted page input; native foreground checks require explicit opt-in. |
## When to write one
diff --git a/docs/issue-fix-queue.md b/docs/issue-fix-queue.md
new file mode 100644
index 00000000..bf6e9dfe
--- /dev/null
+++ b/docs/issue-fix-queue.md
@@ -0,0 +1,18 @@
+# Requested issue fixes
+
+Checked 2026-09-10. These open issues contain an explicit `@justrach` mention
+by yxlyx in the issue body or a comment. Requested work is tracked here; an issue
+stays open until its fix is reviewed and delivered.
+
+| Issue | Work | Status | Regression coverage |
+|---|---|---|---|
+| [#839](https://github.com/justrach/codegraff/issues/839) | Saved GUI conversations must not imply external execution finished. | Implemented; saved-session GUI regression coverage | Open intermediate REPL history in the GUI; verify snapshot status, refresh and explicit continuation. |
+| [#823](https://github.com/justrach/codegraff/issues/823#issuecomment-5613707588) | Browser input should search ordinary terms and explain invalid addresses. | Queued | Search terms, hostnames, valid URLs and blocked schemes through the Browser form. |
+| [#825](https://github.com/justrach/codegraff/issues/825#issuecomment-5613669743) | Make Tasks optional and explain the split-pane limit. | Queued | Explicit open/close, dismissal across updates/navigation and feedback at the pane limit. |
+| [#829](https://github.com/justrach/codegraff/issues/829#issuecomment-5613854701) | Explain update unavailability accurately and align both menu controls. | Queued | Unavailability reasons, disabled controls and a supported manual update check. |
+| [#832](https://github.com/justrach/codegraff/issues/832#issuecomment-5613862436) | GUI tests must preserve desktop focus by default. | Implemented; shared background policy and regression coverage | Shared hidden-window policy, automatic background preflight, trusted page input, macOS activation/window observation and explicit foreground opt-in. |
+| [#845](https://github.com/justrach/codegraff/issues/845#issuecomment-5614160827) | Keep the thinking indicator live during follow-up composition and queuing. | Queued | Indicator progress, preserved input and queue delivery after the active turn. |
+
+All default visual suites use the shared background policy. Native fullscreen,
+computer input and native sheets remain explicitly opt-in; their foreground
+checks were not run as part of this background verification.