graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: preserve desktop focus during GUI verification
Rach Pradhan3255d39c75c0
diff --git a/apps/native/electron/README.md b/apps/native/electron/README.mdindex 64233203..9eed3674 100644--- a/apps/native/electron/README.md+++ b/apps/native/electron/README.md@@ -43,7 +43,7 @@ After packaging, a real Electron smoke test needs no paid model calls:```shGRAFF_CWD="$PWD" GRAFF_ELECTRON_SMOKE=/tmp/graff-electron-smoke.json \- zig-out/electron/Codegraff.app/Contents/MacOS/Electron+ zig-out/electron/Codegraff.app/Contents/MacOS/Codegraff```The existing AppKit/Kuri shell remains a fallback through@@ -114,10 +114,11 @@ harness workspace. The native GUI's ACP bridge uses one stdout reader androutes 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. 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.+draggable titlebar. Automated smoke runs stay hidden and non-focusable by default.+Native Activity sheets and OS keyboard/screen checks require explicit+`GRAFF_ELECTRON_FOREGROUND=1`, which can take desktop focus. The report records+skipped native checks. `GRAFF_SMOKE_SKIP_INPUT=1` disables native keyboard input+even when foreground mode is requested. See [visual test modes](VISUAL-TESTS.md).The v2 profiler adds document LCP/FCP, maximum observed interaction duration,recording-period layout shift, renderer heap and DOM size, GPU-process CPU/RSSdiff --git a/apps/native/electron/VISUAL-TESTS.md b/apps/native/electron/VISUAL-TESTS.mdindex bb6d1429..e13745eb 100644--- a/apps/native/electron/VISUAL-TESTS.md+++ b/apps/native/electron/VISUAL-TESTS.md@@ -1,30 +1,30 @@# Desktop visual tests-From `apps/native`, run `bun run build`, then `bun run test:visual`.-This renders scripted turn states in hidden, isolated Electron windows and+For a fresh checkout, run these from `apps/native`:++```sh+bun install --frozen-lockfile+bun node_modules/electron/install.js+bun run build+bun run test:visual+```++The explicit Electron install also works when Bun skips dependency postinstall scripts.+This renders scripted turn states in hidden, non-focusable Electron windows andchecks visible progress, layout, disclosure state, completion and interruptionin White, Black and CodeGraff themes. PNGs and results go to-`zig-out/visual-tests`; set `GRAFF_VISUAL_OUTPUT` to use another directory.+`zig-out/visual-tests`; `test-run.json` records the mode, result and skipped checks. 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.+benchmarks share the window policy. Page input uses Chromium's trusted input+path without sending keyboard or mouse events to the desktop.++On macOS visual and benchmark launchers start a read-only OS observer before+Electron. Unexpected activation fails the run; hidden mode also rejects visible+windows. The observer requires the Xcode command-line tools.+`bun run test:background` checks repeated hidden windows, trusted input,+screenshots and cleanup without a UI build. It also runs before hidden visual suites.+`GRAFF_TEST_FOREGROUND=1` remains an alias for the explicit foreground mode below.No engine binary, model account, MCP server or model request is used. Requeststo API routes are blocked and fail the test. The fixture page is unavailable@@ -40,6 +40,58 @@ scrolling regressions on their own. It exercises actual mouse and Tab input,per-chat drafts, delayed uploads, request failures and late responses. Thesechecks also run in the full visual suite and the Projects suite.+## Desktop focus and native coverage (#832)++The visual, benchmark, coding-smoke and packaged-smoke entry points install the+same hidden-window policy before Electron becomes ready. Default runs never+request foreground activation. No environment flag is needed for this default.+Test constructor overrides cannot enable showing/focus, and unexpected native+activation calls fail the run. Errors never retry by bringing a window forward.++On macOS, verify the real process while continuing to use another application:++```sh+bun run test:focus+bun run test:focus node_modules/.bin/electron electron/test-window-probe.cjs+bun run test:tagged+```++The focus observer requires Xcode command-line tools. It observes activation,+visible windows and cleanup; it neither switches applications nor injects input.+Switching applications during a run is allowed. The output reports how many+such switches were observed; zero means that particular scenario was not tested.+The observer currently supports macOS only.++Some checks need a visible window. Default hidden runs explicitly skip embedded+browser pin input/captures and native fullscreen. Packaged smoke tests+also skip OS keyboard injection/screen capture and the native Activity sheet.+These skips are coverage limits, not passes. A hidden WebContentsView did not+accept the pin-input sequence reliably, including through DevTools input. A+visible inactive host does support those browser checks without taking focus.+**Visible windows can still cover your current app.** Keep the default hidden+mode when tests must stay out of the way; visible mode is for watching tests:++```sh+GRAFF_ELECTRON_VISIBLE=1 bun run test:browser+GRAFF_ELECTRON_VISIBLE=1 bun run test:focus+```++This mode prohibits macOS app activation as well as window focus. A window-only+restriction was insufficient because focusing embedded web contents could still+activate the app. The observer allows visible windows in this mode but still+fails on any app activation or leftover test app.++These commands **can take desktop focus** and are explicit opt-ins:++```sh+GRAFF_ELECTRON_FOREGROUND=1 bun run test:visual+```++`GRAFF_ELECTRON_VISIBLE=1` does not enable OS keyboard injection, native+fullscreen or Activity sheets. For packaged smoke runs the same foreground+flag is required before any OS input; `GRAFF_SMOKE_SKIP_INPUT=1` still disables+that input even in foreground mode. OS permissions alone never opt in.+## Repeatable performance and README captures### Comparing production builds@@ -53,13 +105,11 @@ 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 trusted wheel input. It measures renderer heap after collection, summed+and Chromium wheel input. It measures renderer heap after collection, summedprocess RSS, script/layout work and frame callback intervals. Repeat both runs-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.+and compare matching scenarios. Hidden runs disable background throttling and retain hardware acceleration.+For presentation measurements explicitly opt into foreground mode on the same+display; hidden results do not establish on-screen refresh or native focus behavior.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/browser-address-visual.cjs b/apps/native/electron/browser-address-visual.cjsnew file mode 100644index 00000000..74789702--- /dev/null+++ b/apps/native/electron/browser-address-visual.cjs@@ -0,0 +1,36 @@+const assert = require('node:assert/strict');+async function runBrowserAddress({ wc, browser, destination, guard, wait }) {+ const js = code => wc.executeJavaScript(code);+ const searches = [];+ const safe = guard(destination);+ // Redirect only the expected search URL to local HTML before any network I/O.+ const query = 'how to center a div 世界';+ const expected = `https://www.google.com/search?q=${encodeURIComponent(query)}`;+ browser.session.webRequest.onBeforeRequest((details, callback) => {+ if (details.url === expected) { searches.push(details.url); callback({ redirectURL: destination }); }+ else safe(details, callback);+ });+ await js(`document.querySelector('[aria-label="Browser"]').click()`);+ await wait(`!!document.querySelector('input[aria-label="Address"]')`);+ await js('new Promise(resolve=>setTimeout(resolve,200))'); // Let the restored address arrive before editing it.+ const submit = async text => {+ await js(`(()=>{const e=document.querySelector('input[aria-label="Address"]');e.focus();Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,${JSON.stringify(text)});e.dispatchEvent(new Event('input',{bubbles:true}));})()`);+ await wait(`document.querySelector('input[aria-label="Address"]').value===${JSON.stringify(text)}`);+ await js('new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true))))');+ await js(`document.querySelector('input[aria-label="Address"]').form.requestSubmit()`);+ };+ await submit(query);+ await wait(() => searches.length === 1, 'ordinary words reach the search URL');+ await wait(() => browser.tabs.get(browser.visible)?.view?.webContents.getURL() === destination + '/', 'search fixture loaded');+ assert.deepEqual(searches, [expected]);+ assert.equal(await js(`!!document.querySelector('aside [role="alert"]')`), false, 'Search terms do not show Invalid URL');+ // Check scheme rejection in the real IPC path without treating it as a search.+ const oldURL = browser.tabs.get(browser.visible).view.webContents.getURL();+ await submit('javascript:alert(1)');+ await wait(`document.querySelector('aside [role="alert"]')?.textContent.includes('Only HTTP and HTTPS')`);+ assert.equal(browser.tabs.get(browser.visible).view.webContents.getURL(), oldURL);+ assert.equal(searches.length, 1);+ await js(`document.querySelector('[aria-label="Close browser"]').click()`);+ console.log('#823 browser address passed: ordinary Unicode search through real preload/IPC/navigation, no Invalid URL, unsafe scheme rejected.');+}+module.exports = { runBrowserAddress };diff --git a/apps/native/electron/browser-visual.cjs b/apps/native/electron/browser-visual.cjsindex ccb4590c..3b95c752 100644--- a/apps/native/electron/browser-visual.cjs+++ b/apps/native/electron/browser-visual.cjs@@ -8,6 +8,7 @@ const path = require('node:path');const fs = require('node:fs');const sleep = ms => new Promise(r => setTimeout(r, ms));async function runBrowserVisuals({ win: fixtureWindow, origin, output }) {+ if (!require('./test-window.cjs').visibleWindowCheck('embedded browser native pin input and captures')) return;const fixture = http.createServer((_req, res) => {res.setHeader('content-type', 'text/html');res.end('<!doctype html><title>Pin fixture</title><style>body{margin:0;background:#e5f3ff}button{margin:50px;width:180px;height:80px}article{height:1600px}</style><button id="target" onpointerdown="document.body.dataset.activated=1" onclick="document.body.dataset.clicked=1">Choose this element</button><article>Scroll fixture</article>');diff --git a/apps/native/electron/gui-coding-smoke.cjs b/apps/native/electron/gui-coding-smoke.cjsindex d2a8bc09..f125cfec 100644--- a/apps/native/electron/gui-coding-smoke.cjs+++ b/apps/native/electron/gui-coding-smoke.cjs@@ -1,6 +1,7 @@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');+require('./test-window.cjs').installTestWindowPolicy(app);const {spawn,spawnSync}=require('node:child_process');const fs=require('node:fs');const path=require('node:path');const os=require('node:os');const net=require('node:net');const assert=require('node:assert/strict');const {installWindowState}=require('./window-state.cjs');diff --git a/apps/native/electron/link-destination-visual.cjs b/apps/native/electron/link-destination-visual.cjsindex 05ef1e04..e3a425ae 100644--- a/apps/native/electron/link-destination-visual.cjs+++ b/apps/native/electron/link-destination-visual.cjs@@ -183,6 +183,7 @@ async function runLinkDestinationVisuals({ origin, output }) {assert.equal(routed.length, before, 'same-origin links bypass external routing');assert.ok(await js(`!!document.querySelector('textarea[aria-label="Prompt"]')`));assert.deepEqual(errors, [], 'browser IPC completes without errors');+ await require('./browser-address-visual.cjs').runBrowserAddress({ wc, browser, destination, guard, wait });assert.deepEqual(blocked, [], 'no external network or engine/model requests attempted');console.log('Link destination visuals passed: default/save/switch, reload and fresh-store persistence, normal/blank links, closed-browser reveal, overlays, unsafe/same-origin links, split focus and preserved app.');} finally {diff --git a/apps/native/electron/native/TestFocusMonitor.swift b/apps/native/electron/native/TestFocusMonitor.swiftindex 22bbc9bc..e1c29696 100644--- a/apps/native/electron/native/TestFocusMonitor.swift+++ b/apps/native/electron/native/TestFocusMonitor.swift@@ -2,6 +2,7 @@import AppKitimport CoreGraphics+let allowVisible = ProcessInfo.processInfo.environment["GRAFF_ELECTRON_VISIBLE"] == "1"var target: pid_t?var activations: [pid_t] = []var visibleSamples: [pid_t: Int] = [:]@@ -26,7 +27,7 @@ func finish() {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)+ exit(target != nil && activated == 0 && (allowVisible || visible == 0) ? 0 : 1)}let token = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { notification inif let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication {diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjsindex 41e17a4e..6ba600fe 100644--- a/apps/native/electron/navigation-visual.cjs+++ b/apps/native/electron/navigation-visual.cjs@@ -26,6 +26,7 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {const commands=[{name:'compact',description:'Compact conversation context'},...Array.from({length:100},(_,i)=>({name:'command-'+i,description:'Command '+i}))];const galleryFetch=window.fetch;window.fetch=async(input,options)=>{const response=await galleryFetch(input,options);if(options?.body&&JSON.parse(options.body).method==='bootstrap')return new Response(JSON.stringify({sessionId:'demo',commands}),{headers:{'content-type':'application/json'}});if(String(input).includes('/api/models')){const data=await response.json();data.result.commands=commands;data.result.current.model='example-model-with-a-long-name';data.result.models[0].name=data.result.current.model;return new Response(JSON.stringify(data),{headers:{'content-type':'application/json'}});}return response;};`});await wc.loadURL(origin);testDesktop.present(win);await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ if(process.env.GRAFF_VISUAL_SUITE==='tagged'){await require('./yxlyx-regressions-visual.cjs').runYxlyxRegressions({win,origin});return;}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});@@ -34,6 +35,7 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {await require('./chat-scroll-visual.cjs').runChatScroll({win,origin,output});};if(process.env.GRAFF_VISUAL_SUITE==='interactions'){await interactions();return;}+ await require('./yxlyx-regressions-visual.cjs').runYxlyxRegressions({win,origin});await require('./projects-visual.cjs').runProjectVisuals({win,origin,output});await require('./project-recovery-visual.cjs').runProjectRecovery({win,origin,output});await require('./review-recovery-visual.cjs').runReviewRecovery({win,origin,output});diff --git a/apps/native/electron/performance-benchmark.cjs b/apps/native/electron/performance-benchmark.cjsindex 8d61a309..e23cfeca 100644--- a/apps/native/electron/performance-benchmark.cjs+++ b/apps/native/electron/performance-benchmark.cjs@@ -2,6 +2,7 @@ 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/outputconst { app, BrowserWindow, ipcMain, screen, contentTracing } = require('electron');+require('./test-window.cjs').installTestWindowPolicy(app);const { spawn } = require('node:child_process');const fs = require('node:fs');const path = require('node:path');diff --git a/apps/native/electron/single-instance.cjs b/apps/native/electron/single-instance.cjsindex f8e035bf..355f990f 100644--- a/apps/native/electron/single-instance.cjs+++ b/apps/native/electron/single-instance.cjs@@ -6,6 +6,7 @@ function claimDesktopInstance(app, window) {const focus = () => {const win = window();if (!win || win.isDestroyed()) return;+ if (process.env.GRAFF_ELECTRON_SMOKE) { require('./test-window.cjs').presentWindow(win, app); return; }if (win.isMinimized()) win.restore();win.show();win.focus();diff --git a/apps/native/electron/smoke-browser-pin.cjs b/apps/native/electron/smoke-browser-pin.cjsnew file mode 100644index 00000000..db1a39ae--- /dev/null+++ b/apps/native/electron/smoke-browser-pin.cjs@@ -0,0 +1,22 @@+const assert = require('node:assert/strict');+const { ipcMain } = require('electron');+async function smokeBrowserPin({ browser, win }) {+ if (!require('./test-window.cjs').visibleWindowCheck('embedded browser native pin input')) return 'Skipped: requires visible-window opt-in';+ const testDesktop = require('./test-desktop.cjs');+ const wc = browser.tabs.get('smoke').view.webContents;+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+ const pinReceived = new Promise((resolve, reject) => {+ const timeout = setTimeout(() => { ipcMain.removeListener('browser-pin', listener); reject(new Error('Picker did not send a pin')); }, 3000);+ const listener = (_event, pin) => { clearTimeout(timeout); ipcMain.removeListener('browser-pin', listener); resolve(pin); };+ ipcMain.on('browser-pin', listener);+ });+ await browser.command('smoke', 'pick', { enabled: true });+ 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);+ 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');+ return 'native pin input passed';+}+module.exports = { smokeBrowserPin };diff --git a/apps/native/electron/smoke-desktop.cjs b/apps/native/electron/smoke-desktop.cjsindex 8c3674b8..58aa3e1a 100644--- a/apps/native/electron/smoke-desktop.cjs+++ b/apps/native/electron/smoke-desktop.cjs@@ -30,22 +30,25 @@ async function smokeDesktop({ automation, computer, win, browser }) {const invoke = (name, args) => rpc('tools/call', { name, arguments: args });const snapshot = await invoke('browser', { action: 'snapshot' });assert.match(snapshot.content[0].text, /Browser fixture/);- const screenshot = await invoke('browser', { action: 'screenshot' });- assert.equal(screenshot.content[0].type, 'image');- assert.ok(screenshot.content[0].data.length > 100);+ let pageCapture = 'Skipped: embedded browser capture requires visible-window opt-in';+ if (require('./test-window.cjs').visibleWindowCheck('embedded browser page capture')) {+ const screenshot = await invoke('browser', { action: 'screenshot' });+ assert.equal(screenshot.content[0].type, 'image');+ assert.ok(screenshot.content[0].data.length > 100);+ pageCapture = 'browser image response passed';+ }const status = await invoke('computer', { action: 'status' });assert.equal(JSON.parse(status.content[0].text).enabled, false);assert.equal((await invoke('computer', { action: 'apps' })).isError, true);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(Array.isArray(apps.apps));- if (testDesktop.foreground) assert.ok(apps.apps.some(app => app.pid === process.pid));+ assert.equal(apps.apps.some(app => app.pid === process.pid), require('./test-window.cjs').testWindowMode() === 'foreground', 'Only regular foreground apps appear in native app discovery');assert.equal(await win.webContents.executeJavaScript(`fetch('/api/browser').then(r=>r.status)`), 410);const permissions = computer.status();- 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) {+ const foreground = require('./test-window.cjs').foregroundCheck('native keyboard injection and screen capture');+ let nativeInput = !foreground || process.env.GRAFF_SMOKE_SKIP_INPUT ? 'Skipped: native input requires foreground opt-in and OS permissions' : 'OS permission unavailable';+ if (foreground && !process.env.GRAFF_SMOKE_SKIP_INPUT && permissions.accessibility && permissions.screenRecording) {computer.enabled = true;try {const wc = browser.tabs.get('smoke').view.webContents;@@ -62,7 +65,7 @@ async function smokeDesktop({ automation, computer, win, browser }) {nativeInput = 'native AX snapshot, CGEvent typing into test page, and screen capture passed';} finally { computer.enabled = false; }}- return { mcp: 'stdio discovery, browser snapshot/image, disabled computer gate passed', permissions, nativeApps: apps.apps.length, nativeInput };+ return { mcp: 'stdio discovery, browser snapshot, disabled computer gate passed', pageCapture, permissions, nativeApps: apps.apps.length, nativeInput };} finally { child.stdin.end(); child.kill(); for (const waiter of waiters.values()) clearTimeout(waiter.timer); }}module.exports = { smokeDesktop };diff --git a/apps/native/electron/smoke.cjs b/apps/native/electron/smoke.cjsindex b8e237ee..1af22088 100644--- a/apps/native/electron/smoke.cjs+++ b/apps/native/electron/smoke.cjs@@ -4,7 +4,6 @@ const http = require('node:http');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { ipcMain } = require('electron');const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));async function run({ win, browser, automation, backend, metrics, activity, computer, profiler }) {@@ -45,19 +44,8 @@ async function run({ win, browser, automation, backend, metrics, activity, compuassert.equal(await request('evaluate', { expression: 'document.querySelector("#name").value' }), 'ACP browser');await request('click', { selector: '#button' });assert.match((await request('snapshot')).text, /Clicked/);- const pinReceived = new Promise((resolve, reject) => {- const timeout = setTimeout(() => { ipcMain.removeListener('browser-pin', listener); reject(new Error('Picker did not send a pin')); }, 3000);- const listener = (_event, pin) => { clearTimeout(timeout); ipcMain.removeListener('browser-pin', listener); resolve(pin); };- ipcMain.on('browser-pin', listener);- });- 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)}})()');- 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.pinInput = await require('./smoke-browser-pin.cjs').smokeBrowserPin({ browser, win });report.desktop = await require('./smoke-desktop.cjs').smokeDesktop({ automation, computer, win, browser });await request('zoom', { factor: 1.2 });assert.equal(wc.getZoomFactor(), 1.2);@@ -98,14 +86,15 @@ async function run({ win, browser, automation, backend, metrics, activity, compureport.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'})})`);- if (testDesktop.foreground) {+ if (require('./test-window.cjs').foregroundCheck('native Activity sheet')) {await activity(); report.swiftUI = 'native module loaded and sheet presented';- } else report.swiftUI = 'Native sheet requires GRAFF_TEST_FOREGROUND=1';- report.testDesktop = testDesktop.assertSafe();+ } else report.swiftUI = 'Skipped: native Activity sheet requires foreground opt-in';await sleep(500);const output = process.env.GRAFF_ELECTRON_SMOKE;+ const { testWindowMode, skippedChecks } = require('./test-window.cjs');+ report.mode = testWindowMode(); report.skipped = [...skippedChecks];fs.writeFileSync(output, JSON.stringify(report, null, 2));- console.log('Electron smoke passed: navigation, isolation, pins, automation, suspension, real ACP. Native sheet:', report.swiftUI);+ console.log('Electron smoke passed: navigation, isolation, automation, suspension, real ACP. Native checks are recorded separately.');} finally { fixture.close(); fs.rmSync(cwd, { recursive: true, force: true }); }}module.exports = { run };diff --git a/apps/native/electron/stress-visual.cjs b/apps/native/electron/stress-visual.cjsindex 7b8cc876..b95ed1ae 100644--- a/apps/native/electron/stress-visual.cjs+++ b/apps/native/electron/stress-visual.cjs@@ -50,7 +50,7 @@ async function runStressVisuals({win: fixtureWindow, origin, output, fullscreenawait click('[data-stream]');const titleHeight=()=>js(`document.querySelector('[data-desktop-titlebar]').getBoundingClientRect().height`);assert.equal(await titleHeight(),36);- const checkedFullscreen = fullscreen && process.platform === 'darwin' && testDesktop.foreground;+ const checkedFullscreen = fullscreen && process.platform === 'darwin' && require('./test-window.cjs').foregroundCheck('native fullscreen and reload');if(checkedFullscreen) {testDesktop.present(win); await testDesktop.focusTestPage(win.webContents);win.setFullScreen(true);await wait(`document.documentElement.dataset.desktopFullscreen==='true'`);diff --git a/apps/native/electron/test-entrypoints.test.cjs b/apps/native/electron/test-entrypoints.test.cjsnew file mode 100644index 00000000..e1b8ac32--- /dev/null+++ b/apps/native/electron/test-entrypoints.test.cjs@@ -0,0 +1,32 @@+const { test, expect } = require('bun:test');+const fs = require('node:fs');+const path = require('node:path');+const ts = require('typescript');++// Catch the original #832 failure mode: a new test bypasses the shared helper.+// Parse code so strings containing renderer .focus() are not mistaken for OS focus.+test('every test BrowserWindow constructor uses the enforced options', () => {+ let checked = 0;+ for (const name of fs.readdirSync(__dirname).filter(n => n.endsWith('.cjs') && !n.endsWith('.test.cjs') && n !== 'main.cjs' && n !== 'test-window-policy.cjs')) {+ 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) && node.expression.getText(source) === 'BrowserWindow') {+ checked++;+ expect(node.arguments?.[0]?.getText(source), name).toMatch(/testWindowOptions\(/);+ }+ if (ts.isCallExpression(node) && /(?:^|\.)createWindow$/.test(node.expression.getText(source))) checked++;+ ts.forEachChild(node, visit);+ };+ visit(source);+ }+ expect(checked).toBeGreaterThanOrEqual(9);+});++test('standalone Electron test entry points install policy before waiting for readiness', () => {+ for (const name of ['visual-tests.cjs', 'performance-benchmark.cjs', 'gui-coding-smoke.cjs', 'test-window-probe.cjs']) {+ const source = fs.readFileSync(path.join(__dirname, name), 'utf8');+ const install = source.search(/installTestWindowPolicy\(app\)|require\('\.\/test-desktop\.cjs'\)/);+ expect(install, name).toBeGreaterThanOrEqual(0);+ expect(install, name).toBeLessThan(source.indexOf('app.whenReady()'));+ }+});diff --git a/apps/native/electron/test-window-policy.cjs b/apps/native/electron/test-window-policy.cjsindex 7ac5f5f9..0713c070 100644--- a/apps/native/electron/test-window-policy.cjs+++ b/apps/native/electron/test-window-policy.cjs@@ -1,40 +1,37 @@// 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 { testWindowMode, testWindowOptions, presentWindow, installTestWindowPolicy } = require('./test-window.cjs');+ const mode = testWindowMode(env), foreground = mode === 'foreground';const violations = [], observed = new Set();- if (!foreground && platform === 'darwin') app.setActivationPolicy('prohibited');+ installTestWindowPolicy(app, env, platform);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`); };+ for (const event of mode === 'hidden' ? ['show', 'focus'] : ['focus']) {+ win.on(event, () => violations.push(`Unexpected window ${event}`));}};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 } : {}) } });+ const options = value => testWindowOptions(value, env);return {foreground,createWindow(value) {const win = new BrowserWindow(options(value)); guard(win); return win;},present(win) {- if (foreground) { win.show(); win.focus(); }+ presentWindow(win, app, undefined, env);},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');+ if (mode === 'hidden') 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] };+ return { mode: mode === 'hidden' ? 'background' : mode, windows: observed.size, violations: [...violations] };},cleanup() {// Every window, including windows created by nested suites or failed steps.diff --git a/apps/native/electron/test-window-policy.test.cjs b/apps/native/electron/test-window-policy.test.cjsindex 04037e19..cba7c7cd 100644--- a/apps/native/electron/test-window-policy.test.cjs+++ b/apps/native/electron/test-window-policy.test.cjs@@ -12,6 +12,7 @@ function fixture(env = {}) {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'); }+ showInactive() { this.visible = true; this.emit('show'); }focus() { this.focused = true; this.emit('focus'); }isVisible() { return !!this.visible; }isFocused() { return !!this.focused; }@@ -41,7 +42,7 @@ test('#832: one exact opt-in enables foreground checks; unrelated flags never en}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(calls).toEqual(['app.focus']); 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', () => {@@ -62,7 +63,7 @@ test('#832: all GUI test modules use the shared window and input policy', () =>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.isNewExpression(node) && /BrowserWindow$/.test(node.expression.getText(source)) && !/^testWindowOptions\(/.test(node.arguments?.[0]?.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))) {@@ -71,7 +72,7 @@ test('#832: all GUI test modules use the shared window and input policy', () =>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;+ if (ts.isIfStatement(parent) && /testDesktop.foreground|checkedFullscreen|^foreground &&/.test(parent.expression.getText(source))) guarded = true;parent = parent.parent;}if (!guarded) bypasses.push(`${name}: unguarded native ${method}`);@@ -83,3 +84,16 @@ test('#832: all GUI test modules use the shared window and input policy', () =>}expect(bypasses).toEqual([]);});++test('#832: visible fixtures retain prohibited activation and pass cleanup assertions', () => {+ const { policy, app, calls } = fixture({ GRAFF_ELECTRON_VISIBLE: '1' });+ const win = policy.createWindow({ show: true, focusable: true });+ require('./test-window.cjs').installTestWindowPolicy(app);+ policy.present(win);+ expect(calls).toEqual(['prohibited']);+ expect(win.isVisible()).toBe(true);+ expect(win.isFocused()).toBe(false);+ expect(() => win.focus()).toThrow('GRAFF_ELECTRON_FOREGROUND');+ expect(policy.assertSafe()).toMatchObject({ mode: 'visible', windows: 1, violations: [] });+ policy.cleanup();+});diff --git a/apps/native/electron/test-window-probe.cjs b/apps/native/electron/test-window-probe.cjsnew file mode 100644index 00000000..a650cf4c--- /dev/null+++ b/apps/native/electron/test-window-probe.cjs@@ -0,0 +1,46 @@+// Real Electron acceptance check, including later windows and activation events.+const { app, BrowserWindow } = require('electron');+const { installTestWindowPolicy, testWindowOptions, presentWindow } = require('./test-window.cjs');+const assert = require('node:assert/strict');+const fs = require('node:fs'), os = require('node:os'), path = require('node:path');+installTestWindowPolicy(app);+const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-window-probe-'));+app.setPath('userData', temporary);+app.on('window-all-closed', () => {});+const timeout = setTimeout(() => finish(1), 15000);+let win;+assert.equal(require('./single-instance.cjs').claimDesktopInstance(app, () => win), true);+app.whenReady().then(async () => {+ for (let index = 0; index < 3; index++) {+ win = new BrowserWindow(testWindowOptions({ width: 400, height: 300 }));+ presentWindow(win, app);+ await win.loadURL('data:text/html,<style>body{background:rgb(30,150,80)}</style><input id="first"><button id="next">Next</button>');+ assert.equal(win.isVisible(), false); assert.equal(win.isFocusable(), false); assert.equal(win.isFocused(), false);+ for (const action of ['show', 'focus', 'showInactive', 'restore', 'moveTop']) assert.throws(() => win[action](), /#832/);+ assert.throws(() => win.setFullScreen(true), /#832/);+ // The packaged smoke branch must also keep reopen/second-instance hidden.+ process.env.GRAFF_ELECTRON_SMOKE = 'probe';+ app.emit('activate'); app.emit('second-instance');+ delete process.env.GRAFF_ELECTRON_SMOKE;+ await win.webContents.executeJavaScript('document.querySelector("input").focus()');+ win.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' });+ win.webContents.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' });+ await new Promise(resolve => setTimeout(resolve, 100));+ assert.equal(await win.webContents.executeJavaScript('document.activeElement.id'), 'next');+ assert.equal(win.isFocused(), false);+ const shot = await win.webContents.capturePage();+ assert.ok(!shot.isEmpty());+ assert.equal(win.isVisible(), false, 'capture must leave its window hidden');+ win.destroy();+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ assert.equal(BrowserWindow.getAllWindows().length, 0);+ console.log('#832 real-window probe passed: three hidden windows, Tab input, screenshots, reopen events, blocked activation/fullscreen, cleanup.');+ finish(0);+}).catch(error => { console.error(error); finish(1); });+function finish(code) {+ clearTimeout(timeout);+ if (win && !win.isDestroyed()) win.destroy();+ fs.rmSync(temporary, { recursive: true, force: true });+ app.exit(code);+}diff --git a/apps/native/electron/test-window.cjs b/apps/native/electron/test-window.cjsindex da5faf8e..cde6a03e 100644--- a/apps/native/electron/test-window.cjs+++ b/apps/native/electron/test-window.cjs@@ -1,22 +1,73 @@-// Compatibility helpers; new fixtures use test-desktop.cjs.-function testWindowMode() {- if (process.env.GRAFF_TEST_FOREGROUND === '1') return 'foreground';+/** GUI verification is hidden by default (#832). Native OS interaction needs+ * GRAFF_ELECTRON_FOREGROUND=1; visible windows never activate the app. */+function testWindowMode(env = process.env) {+ if (env.GRAFF_ELECTRON_FOREGROUND === '1' || env.GRAFF_TEST_FOREGROUND === '1') return 'foreground';+ if (env.GRAFF_ELECTRON_VISIBLE === '1') return 'visible';return 'hidden';}-function presentWindow(win, app, extra = {}) {- const mode = testWindowMode();- if (win.webContents && !win.webContents.isDestroyed()) win.webContents.setBackgroundThrottling(false);+function presentWindow(win, app, _extra, env = process.env) {+ const mode = testWindowMode(env);+ if (mode !== 'foreground' && 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 { ...extra, show: false, webPreferences: { backgroundThrottling: false, ...(extra.webPreferences || {}) } };+function testWindowOptions(extra = {}, env = process.env) {+ return { ...extra, show: false, focusable: testWindowMode(env) === 'foreground',+ webPreferences: { ...extra.webPreferences, ...(testWindowMode(env) !== 'foreground' ? { backgroundThrottling: false } : {}) } };}-module.exports = { testWindowMode, presentWindow, testWindowOptions };+const skippedChecks = new Set();+function foregroundCheck(name, env = process.env) {+ if (testWindowMode(env) === 'foreground') return true;+ skippedChecks.add(name);+ console.log(`SKIP: ${name} requires GRAFF_ELECTRON_FOREGROUND=1 (takes desktop focus).`);+ return false;+}++function visibleWindowCheck(name, env = process.env) {+ if (testWindowMode(env) !== 'hidden') return true;+ skippedChecks.add(name);+ console.log(`SKIP: ${name} requires GRAFF_ELECTRON_VISIBLE=1 (visible without desktop focus).`);+ return false;+}++// Install before app.whenReady(), including when the test entry point is run directly.+// OS policy prevents activation; method guards fail on accidental test bypasses.+const installed = new WeakSet();+function installTestWindowPolicy(app, env = process.env, platform = process.platform) {+ if (installed.has(app)) return;+ installed.add(app);+ const mode = testWindowMode(env);+ console.log(`Electron tests: ${mode}.`);+ if (mode === 'visible') console.log('Visible opt-in: windows keep keyboard focus elsewhere but can cover your work. Use hidden mode for no desktop overlap.');+ if (mode === 'foreground') {+ console.log('Foreground opt-in: these checks can take desktop focus and send native input.');+ return;+ }+ // Accessory policy still lets WebContents.focus() activate macOS itself,+ // even when its BrowserWindow is non-focusable. Both quiet modes prohibit it.+ if (platform === 'darwin') app.setActivationPolicy('prohibited');+ const refuse = action => () => { throw Error(`#832: ${action} requires GRAFF_ELECTRON_FOREGROUND=1 (or GRAFF_TEST_FOREGROUND=1)`); };+ app.focus = refuse('app.focus');+ app.on('browser-window-created', (_event, win) => {+ win.setFocusable?.(false);+ for (const method of ['show', 'focus', 'restore', 'moveTop', 'maximize']) win[method] = refuse(method);+ for (const method of ['setFullScreen', 'setSimpleFullScreen', 'setKiosk']) {+ const original = win[method]?.bind(win);+ win[method] = enabled => { if (enabled) refuse(method)(); return original?.(enabled); };+ }+ if (mode === 'hidden') win.showInactive = refuse('showInactive in hidden mode');+ win.on('focus', () => { console.error('#832: unexpected test window focus'); app.exit?.(1); });+ if (mode === 'hidden') win.on('show', () => { console.error('#832: unexpected visible test window'); app.exit?.(1); });+ });+}++module.exports = { testWindowMode, presentWindow, testWindowOptions, foregroundCheck, visibleWindowCheck, installTestWindowPolicy, skippedChecks };diff --git a/apps/native/electron/test-window.test.cjs b/apps/native/electron/test-window.test.cjsindex 7f57b1b3..1080b3c7 100644--- a/apps/native/electron/test-window.test.cjs+++ b/apps/native/electron/test-window.test.cjs@@ -1,38 +1,85 @@-const { test, expect } = require('bun:test');-const { testWindowMode, presentWindow, testWindowOptions } = require('./test-window.cjs');+const { test, expect, beforeEach, afterEach } = require('bun:test');+const { EventEmitter } = require('node:events');+const { testWindowMode, presentWindow, testWindowOptions, installTestWindowPolicy, foregroundCheck, visibleWindowCheck } = require('./test-window.cjs');+const keys = ['GRAFF_ELECTRON_FOREGROUND', 'GRAFF_ELECTRON_VISIBLE', 'GRAFF_TEST_FOREGROUND'];+let saved;+beforeEach(() => { saved = keys.map(key => process.env[key]); keys.forEach(key => delete process.env[key]); });+afterEach(() => keys.forEach((key, i) => { if (saved[i] === undefined) delete process.env[key]; else process.env[key] = saved[i]; }));+function fixture() {+ const calls = [];+ const win = new EventEmitter(), app = new EventEmitter();+ for (const method of ['show', 'focus', 'showInactive', 'restore', 'moveTop', 'setFullScreen', 'setSimpleFullScreen', 'setKiosk', 'setFocusable']) win[method] = (...args) => calls.push([method, ...args]);+ win.webContents = { isDestroyed: () => false, setBackgroundThrottling() {} };+ app.focus = () => calls.push(['app.focus']);+ app.setActivationPolicy = policy => calls.push(['policy', policy]);+ app.exit = code => calls.push(['exit', code]);+ return { calls, win, app };+}-test('default GUI tests stay hidden and never steal focus (#832)', () => {- const previous = process.env.GRAFF_TEST_FOREGROUND;- const visible = process.env.GRAFF_ELECTRON_VISIBLE;- delete process.env.GRAFF_TEST_FOREGROUND;- delete process.env.GRAFF_ELECTRON_VISIBLE;+test('hidden is the default and constructor overrides cannot opt in (#832)', () => {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(testWindowMode({ GRAFF_ELECTRON_FOREGROUND: 'true' })).toBe('hidden');+ const options = testWindowOptions({ show: true, focusable: true, width: 10, webPreferences: { sandbox: true, backgroundThrottling: true } });+ expect(options).toMatchObject({ show: false, focusable: false, width: 10, webPreferences: { sandbox: true, backgroundThrottling: false } });+ const { calls, win, app } = fixture();+ expect(presentWindow(win, app, { mapped: true })).toBe('hidden');expect(calls).toEqual([]);- process.env.GRAFF_TEST_FOREGROUND = previous;- process.env.GRAFF_ELECTRON_VISIBLE = visible;+ expect(foregroundCheck('native input')).toBe(false);});-test('foreground interaction is an explicit opt-in', () => {- 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_TEST_FOREGROUND = previous;+test('visible preview is non-focusable and never activates the app', () => {+ process.env.GRAFF_ELECTRON_VISIBLE = '1';+ const { calls, win, app } = fixture();+ expect(testWindowOptions().focusable).toBe(false);+ expect(presentWindow(win, app)).toBe('visible');+ expect(calls).toEqual([['showInactive']]);+ expect(foregroundCheck('native input')).toBe(false);});-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_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('hidden');- expect(calls).toEqual([]);- process.env.GRAFF_TEST_FOREGROUND = previous;- process.env.GRAFF_ELECTRON_VISIBLE = visible;+test('only explicit foreground opt-in enables activation and native input', () => {+ process.env.GRAFF_ELECTRON_FOREGROUND = '1';+ process.env.GRAFF_ELECTRON_VISIBLE = '1';+ const { calls, win, app } = fixture();+ expect(testWindowOptions().focusable).toBe(true);+ expect(presentWindow(win, app)).toBe('foreground');+ expect(calls).toEqual([['app.focus'], ['show'], ['focus']]);+ expect(foregroundCheck('native input')).toBe(true);+});++test('process policy blocks bypasses on every window, including later windows', () => {+ const { calls, win, app } = fixture();+ installTestWindowPolicy(app);+ for (const window of [win, fixture().win]) {+ app.emit('browser-window-created', {}, window);+ for (const method of ['show', 'focus', 'showInactive', 'restore', 'moveTop']) expect(() => window[method]()).toThrow('#832');+ for (const method of ['setFullScreen', 'setSimpleFullScreen', 'setKiosk']) expect(() => window[method](true)).toThrow('#832');+ window.setFullScreen(false);+ }+ expect(() => app.focus()).toThrow('#832');+ win.emit('focus'); win.emit('show');+ expect(calls.filter(call => call[0] === 'exit')).toEqual([['exit', 1], ['exit', 1]]);+});++test('packaged native pin check skips before touching browser input without opt-in', async () => {+ const forbidden = new Proxy({}, { get() { throw Error('must not touch native input'); } });+ const { smokeBrowserPin } = require('./smoke-browser-pin.cjs');+ expect(await smokeBrowserPin({ browser: forbidden, win: forbidden })).toMatch(/Skipped/);+ expect(visibleWindowCheck('browser input')).toBe(false);+ process.env.GRAFF_ELECTRON_VISIBLE = '1';+ expect(visibleWindowCheck('browser input')).toBe(true);+ expect(foregroundCheck('OS input')).toBe(false);+});+++test('visible mode blocks macOS application activation as well as window focus', () => {+ process.env.GRAFF_ELECTRON_VISIBLE = '1';+ const { calls, win, app } = fixture();+ installTestWindowPolicy(app);+ app.emit('browser-window-created', {}, win);+ presentWindow(win, app);+ if (process.platform === 'darwin') expect(calls).toContainEqual(['policy', 'prohibited']);+ expect(calls).toContainEqual(['setFocusable', false]);+ expect(calls).toContainEqual(['showInactive']);+ expect(() => app.focus()).toThrow('#832');+ expect(() => win.focus()).toThrow('#832');});diff --git a/apps/native/electron/updates-visual.cjs b/apps/native/electron/updates-visual.cjsindex a13ea1ca..b8c80439 100644--- a/apps/native/electron/updates-visual.cjs+++ b/apps/native/electron/updates-visual.cjs@@ -58,6 +58,14 @@ async function runUpdateVisuals({ origin, output }) {await wait(`document.querySelector('[data-desktop-update-automatic]')?.getAttribute('aria-checked')==='false'`);assert.equal(await js('window.__automatic'), false, 'settings toggle persists automatic downloads');fs.writeFileSync(path.join(output, 'update-settings.png'), (await wc.capturePage(undefined, { stayAwake: true })).toPNG());+ for (const reason of ['smoke', 'platform', 'unpackaged', 'volume', 'config']) {+ const message = require('./updates.cjs').unavailableMessage(reason);+ await js(`window.__update({status:'unavailable',automatic:false,interactive:true,message:${JSON.stringify(message)}})`);+ await wait(`document.querySelector('[data-desktop-update-panel]').textContent.includes(${JSON.stringify(message)})`);+ assert.equal(await js(`document.querySelector('[data-desktop-update-check]').disabled`), true);+ assert.equal(await js(`document.querySelector('[data-desktop-update-automatic]').disabled`), true);+ }+ console.log('#829 update settings passed: exact unavailable reason and disabled check/automatic controls for all five build conditions.');console.log('Update UI passed: quiet checks/errors, download progress, explicit restart, in-app settings.');} finally { win.destroy(); }}diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjsindex 3c297921..5cd93246 100644--- a/apps/native/electron/visual-tests.cjs+++ b/apps/native/electron/visual-tests.cjs@@ -10,12 +10,13 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-visual-'));app.setPath('userData', path.join(temporary, 'profile'));let server, win;+const output = process.env.GRAFF_VISUAL_OUTPUT || path.resolve(__dirname, '../../../zig-out/visual-tests');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');+ const root = path.resolve(__dirname, '..');fs.mkdirSync(output, { recursive: true });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));@@ -64,15 +65,15 @@ app.whenReady().then(async () => {assert.deepEqual(apiRequests, [], 'Browser fixtures never call engine or model APIs');return;}- if (['projects', 'splits', 'interactions'].includes(process.env.GRAFF_VISUAL_SUITE)) {+ if (['projects', 'splits', 'interactions', 'tagged'].includes(process.env.GRAFF_VISUAL_SUITE)) {await require('./navigation-visual.cjs').runNavigationVisuals({ win, origin, output });- if (process.env.GRAFF_VISUAL_SUITE !== 'interactions') {+ if (!['interactions', 'tagged'].includes(process.env.GRAFF_VISUAL_SUITE)) {await require('./browser-visual.cjs').runBrowserVisuals({ win, origin, output });await require('./dev-preview-visual.cjs').runDevPreview({ output });await require('./link-destination-visual.cjs').runLinkDestinationVisuals({ origin, output });}assert.deepEqual(apiRequests, [], 'Project fixtures never call engine or model APIs');- fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: process.env.GRAFF_VISUAL_SUITE === 'interactions' ? ['keyboard, composer, files and reading'] : ['projects and navigation', 'browser'], apiRequests }, null, 2));+ fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: [process.env.GRAFF_VISUAL_SUITE === 'tagged' ? 'saved snapshots, optional Tasks and split limit' : process.env.GRAFF_VISUAL_SUITE === 'interactions' ? 'keyboard, composer, files and reading' : 'projects and navigation'], skipped: [...require('./test-window.cjs').skippedChecks], apiRequests }, null, 2));return;}if (process.env.GRAFF_VISUAL_SUITE === 'stress') {@@ -143,6 +144,10 @@ function finish(code) {console.log('Test desktop:', JSON.stringify(testDesktop.assertSafe()));} catch (error) { console.error(error); code = 1; }testDesktop.cleanup();+ const { testWindowMode, skippedChecks } = require('./test-window.cjs');+ fs.mkdirSync(output, { recursive: true });+ fs.writeFileSync(path.join(output, 'test-run.json'), JSON.stringify({ suite: process.env.GRAFF_VISUAL_SUITE || 'all', status: code !== 0 ? 'failed' : skippedChecks.size ? 'passed-with-skips' : 'passed', mode: testWindowMode(), skipped: [...skippedChecks] }, null, 2));+ if (skippedChecks.size) console.log(`Coverage limits: ${[...skippedChecks].join('; ')}. See test-run.json.`);if (server?.pid) try { process.kill(-server.pid, 'SIGTERM'); } catch {}app.once('quit', () => { fs.rmSync(temporary, { recursive: true, force: true }); });app.exit(code);diff --git a/apps/native/electron/yxlyx-regressions-visual.cjs b/apps/native/electron/yxlyx-regressions-visual.cjsnew file mode 100644index 00000000..668f0aa6--- /dev/null+++ b/apps/native/electron/yxlyx-regressions-visual.cjs@@ -0,0 +1,71 @@+const assert = require('node:assert/strict');++// Exercise the actual GUI wiring for #825 and #839 using saved-file and+// transport fixtures. Never connects to a real REPL or a search engine.+async function runYxlyxRegressions({ win, origin }) {+ const wc = win.webContents, js = async code => {+ try { return await wc.executeJavaScript(code); }+ catch (error) { console.error('Tagged regression expression:', code); throw error; }+ };+ const wait = async code => {+ for (let i = 0; i < 120; i++) { if (await js(code)) return; await new Promise(r => setTimeout(r, 50)); }+ throw Error(`Tagged regression timed out: ${code}`);+ };+ await wc.loadURL(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ await js(`(() => {+ const previous = window.fetch;+ const json = body => new Response(JSON.stringify(body), {headers:{'content-type':'application/json'}});+ const row = {name:'active-snapshot',title:'Active snapshot fixture',updatedMs:Date.now(),size:100,local:true};+ window.snapshotPrompts = [];+ window.fetch = async (input, options) => {+ const url = new URL(String(input), location.origin);+ if (url.pathname === '/api/sessions') {+ if (!url.searchParams.has('name')) return json({sessions:[row],total:1,nextCursor:null});+ return json({...row,view:'snapshot',execution:'unknown',messages:[+ {role:'user',content:'Continue the pending check'},+ {role:'assistant',content:'Working.',tool_calls:[+ {id:'todo',function:{name:'todo_write',arguments:JSON.stringify({todos:[{content:'Verify pending work',status:'in_progress'}]})}},+ {id:'pending',function:{name:'bash',arguments:JSON.stringify({command:'pending-check'})}}+ ]}+ ]});+ }+ if (url.pathname === '/api/acp' && options?.body) window.snapshotPrompts.push(JSON.parse(options.body));+ return previous(input, options);+ };+ })()`);+ await js(`document.querySelector('button[aria-label="Conversations"]').click()`);+ await wait(`document.querySelector('[data-conversation-library]')?.textContent.includes('Active snapshot fixture')`);+ await js(`Array.from(document.querySelectorAll('[data-conversation-library] li button')).find(e=>e.textContent.includes('Active snapshot fixture')).click()`);+ await wait(`!!document.querySelector('[data-session-snapshot]')`);+ assert.match(await js(`document.querySelector('[data-session-snapshot]').textContent`), /not attached to a live REPL/);+ await wait(`!!document.querySelector('[data-saved-snapshot]')`);+ assert.equal(await js(`document.querySelector('[data-chat][data-focused="true"] textarea')`), null, 'A saved snapshot cannot accept input before explicit continuation');+ assert.match(await js(`document.querySelector('[data-saved-snapshot]').textContent`), /Live status unknown/);+ assert.equal(await js(`document.querySelector('[data-chat][data-focused="true"]').textContent.includes('Turn finished')`), false);+ assert.equal(await js(`window.snapshotPrompts.some(r=>r.method==='session/prompt')`), false, 'Opening a snapshot never sends a prompt');++ await wait(`!document.querySelector('[aria-label="Show tasks"]').disabled`);+ assert.equal(await js(`!!document.querySelector('[data-tasks-sidebar]')`), false, 'Saved todos never force open Tasks');+ await js(`document.querySelector('[aria-label="Show tasks"]').click()`);+ await wait(`!!document.querySelector('[data-tasks-sidebar]')`);+ assert.equal(await js(`getComputedStyle(document.querySelector('[data-tasks-sidebar]')).display`), 'flex');+ await js(`document.querySelector('[aria-label="Close tasks"]').click()`);+ await wait(`!document.querySelector('[data-tasks-sidebar]')`);+ await js(`document.querySelector('[aria-label="Files"]').click()`);+ await js(`document.querySelector('[aria-label="Files"]').click()`);+ assert.equal(await js(`!!document.querySelector('[data-tasks-sidebar]')`), false, 'Navigation respects closing Tasks');+ for (let count = 2; count <= 4; count++) {+ wc.send('desktop-action', 'split-right');+ await wait(`document.querySelectorAll('[data-chat]').length===${count}`);+ }+ wc.send('desktop-action', 'split-right');+ await wait(`!!document.querySelector('[data-split-limit]')`);+ assert.equal(await js(`document.querySelectorAll('[data-chat]').length`), 4);+ assert.match(await js(`document.querySelector('[data-split-limit]').textContent`), /four|4/i);+ assert.match(await js(`document.querySelector('[data-split-limit]').textContent`), /read/i);+ await wc.loadURL(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ console.log('Tagged GUI checks passed: #839 saved snapshot disclosure and no false completion; #825 optional Tasks, close/navigation, four-pane limit explanation.');+}+module.exports = { runYxlyxRegressions };diff --git a/apps/native/package.json b/apps/native/package.jsonindex a3fe3574..14c36e97 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -29,7 +29,10 @@"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",- "test:mcp-apps": "bun test lib/mcp-apps.test.ts && playwright test -c playwright.mcp.config.ts"+ "test:mcp-apps": "bun test lib/mcp-apps.test.ts && playwright test -c playwright.mcp.config.ts",+ "test:focus": "bun scripts/test-desktop-focus.mjs",+ "test:tagged": "GRAFF_VISUAL_SUITE=tagged bun scripts/test-visual.mjs",+ "test:browser": "GRAFF_VISUAL_SUITE=browser bun scripts/test-visual.mjs"},"dependencies": {"@streamdown/code": "^1.1.1",diff --git a/apps/native/scripts/check-desktop-focus.swift b/apps/native/scripts/check-desktop-focus.swiftnew file mode 100644index 00000000..5a3a5624--- /dev/null+++ b/apps/native/scripts/check-desktop-focus.swift@@ -0,0 +1,61 @@+// macOS acceptance observer for #832. Does not activate apps or inject input.+// Usage: compiled-observer /absolute/test-root command [arguments...]+import AppKit+import CoreGraphics+import Foundation++let args = Array(CommandLine.arguments.dropFirst())+guard args.count >= 2 else { fputs("Expected test root and command\n", stderr); exit(2) }+let root = URL(fileURLWithPath: args[0]).standardizedFileURL.path + "/"+let allowVisible = ProcessInfo.processInfo.environment["GRAFF_ELECTRON_VISIBLE"] == "1"+let child = Process()+child.executableURL = URL(fileURLWithPath: "/usr/bin/env")+child.arguments = Array(args.dropFirst())+var testPids = Set<pid_t>()+var activations = 0+var visibleSamples = 0+var samples = 0+var otherAppSwitches = 0+var previousFront = NSWorkspace.shared.frontmostApplication?.processIdentifier+func isTestApp(_ app: NSRunningApplication) -> Bool {+ if app.executableURL?.standardizedFileURL.path.hasPrefix(root) == true {+ testPids.insert(app.processIdentifier)+ return true+ }+ return false+}+let observer = NSWorkspace.shared.notificationCenter.addObserver(+ forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main+) { event in+ if let app = event.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication {+ if isTestApp(app) { activations += 1 }+ else if app.processIdentifier != previousFront { otherAppSwitches += 1 }+ previousFront = app.processIdentifier+ }+}+do { try child.run() } catch { fputs("Failed to launch test: \(error)\n", stderr); exit(2) }+func sample() {+ samples += 1+ for app in NSWorkspace.shared.runningApplications { _ = isTestApp(app) }+ if let front = NSWorkspace.shared.frontmostApplication, isTestApp(front) { activations += 1 }+ guard let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else {+ fputs("Could not inspect on-screen windows; focus acceptance is unverified.\n", stderr)+ child.terminate()+ exit(2)+ }+ if windows.contains(where: { row in+ guard let pid = row[kCGWindowOwnerPID as String] as? Int32 else { return false }+ return testPids.contains(pid)+ }) { visibleSamples += 1 }+}+while child.isRunning {+ sample()+ RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.02))+}+// Include shutdown and delayed activation notifications.+for _ in 0..<25 { sample(); RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.02)) }+NSWorkspace.shared.notificationCenter.removeObserver(observer)+let remaining = NSWorkspace.shared.runningApplications.filter { isTestApp($0) }.count+print("Desktop focus check: \(samples) samples, \(testPids.count) test apps, \(activations) test activations, \(visibleSamples) visible-window samples, \(remaining) remaining test apps, \(otherAppSwitches) other-app switches.")+if testPids.isEmpty { fputs("No Electron app observed; focus acceptance is unverified.\n", stderr); exit(2) }+exit(activations == 0 && (allowVisible || visibleSamples == 0) && remaining == 0 ? child.terminationStatus : 1)diff --git a/apps/native/scripts/test-desktop-focus.mjs b/apps/native/scripts/test-desktop-focus.mjsnew file mode 100644index 00000000..e94fad94--- /dev/null+++ b/apps/native/scripts/test-desktop-focus.mjs@@ -0,0 +1,22 @@+// Observe macOS activation/window state around a real test command (#832).+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+if (process.platform !== 'darwin') throw Error('Desktop focus acceptance observer currently requires macOS.');+if (process.env.GRAFF_ELECTRON_FOREGROUND === '1' || process.env.GRAFF_TEST_FOREGROUND === '1') {+ throw Error('Focus acceptance requires a non-activating mode. Unset GRAFF_ELECTRON_FOREGROUND.');+}+const temporary = mkdtempSync(path.join(tmpdir(), 'graff-focus-observer-'));+try {+ const observer = path.join(temporary, 'observer');+ const compiled = spawnSync('xcrun', ['swiftc', path.join(root, 'scripts/check-desktop-focus.swift'), '-o', observer], { stdio: 'inherit' });+ if (compiled.error) throw compiled.error;+ if (compiled.status !== 0) throw Error('Could not build macOS focus observer.');+ const command = process.argv.slice(2);+ const child = spawnSync(observer, [root, ...(command.length ? command : [process.execPath, 'scripts/test-visual.mjs'])], { cwd: root, stdio: 'inherit' });+ if (child.error) throw child.error;+ process.exitCode = child.status ?? 1;+} finally { rmSync(temporary, { recursive: true, force: true }); }diff --git a/apps/native/scripts/test-electron.mjs b/apps/native/scripts/test-electron.mjsindex 97c5513a..cd6b4e22 100644--- a/apps/native/scripts/test-electron.mjs+++ b/apps/native/scripts/test-electron.mjs@@ -7,6 +7,7 @@ import path from 'node:path';import { createInterface } from 'node:readline';import { fileURLToPath } from 'node:url';const require = createRequire(import.meta.url);+const { testWindowMode } = require('../electron/test-window.cjs');const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');async function focusMonitor() {@@ -41,7 +42,7 @@ async function focusMonitor() {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) {+ if (code !== 0 || !report?.observed || report.foregroundActivations || (testWindowMode() === 'hidden' && report.visibleWindowSamples)) {throw Error(`Desktop isolation failed: ${JSON.stringify(report ?? { observerExit: code })}`);}return report;@@ -52,7 +53,7 @@ async function focusMonitor() {// 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 foreground = testWindowMode() === 'foreground';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 },diff --git a/apps/native/scripts/test-visual.mjs b/apps/native/scripts/test-visual.mjsindex a212b3f0..6e8f3bf6 100644--- a/apps/native/scripts/test-visual.mjs+++ b/apps/native/scripts/test-visual.mjs@@ -1,4 +1,6 @@+import { createRequire } from 'node:module';+const { testWindowMode } = createRequire(import.meta.url)('../electron/test-window.cjs');import { runElectron } from './test-electron.mjs';-const ready = process.env.GRAFF_TEST_FOREGROUND === '1'+const ready = testWindowMode() !== 'hidden'|| await runElectron('electron/background-regression.cjs') === 0;if (ready) await runElectron('electron/visual-tests.cjs');diff --git a/docs/adr/0101-gui-tests-preserve-desktop-focus.md b/docs/adr/0101-gui-tests-preserve-desktop-focus.mdindex 06748fbe..fd5f60bf 100644--- a/docs/adr/0101-gui-tests-preserve-desktop-focus.md+++ b/docs/adr/0101-gui-tests-preserve-desktop-focus.md@@ -1,40 +1,44 @@-# 0101. GUI tests preserve desktop focus by default+# 0101. GUI tests preserve desktop focus and report native coverage gaps-Status: accepted 2026-09-10+Status: accepted 2026-09-11## 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.+#832 persisted after adding a window helper: individual visual suites still+called `show()`/`focus()`, a browser fixture implicitly displayed its host,+and packaged smoke tests could present native UI or inject OS input.+A hidden-window helper test could pass while those entry points took focus.## 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.+Automated Electron entry points install a process policy before readiness.+Default windows are hidden and non-focusable; both hidden and visible-inactive+modes use macOS [prohibited activation policy](https://www.electronjs.org/docs/latest/api/app#appsetactivationpolicypolicy-macos). Unexpected show/focus/fullscreen calls fail+instead of silently activating a test window. Constructor overrides cannot+turn presentation on. Packaged smoke tests use the same policy, including+reopen events. Normal interactive app launches retain their usual behavior.++`GRAFF_ELECTRON_VISIBLE=1` allows visible, non-focusable windows without app+activation, and enables embedded-browser pin input and captures. It can still+overlap the current application: no activation does not mean no obstruction.+Only the default hidden mode keeps test windows off the desktop.+`GRAFF_ELECTRON_FOREGROUND=1` explicitly permits activation. Native fullscreen,+Activity sheets, and OS input checks still need that foreground opt-in.+Skipped checks are printed and visual runs record them in `test-run.json`; they must not be described as passed.## 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.+The hidden renderer can exercise composer input, Tab traversal, split resizing,+link routing and screenshots. Embedded WebContentsView pin input did not pass+while hidden, including a page-targeted DevTools input experiment. Showing the+host inactive allows those checks to pass without activation. Accessory policy+was insufficient: embedded-page focus activated the app despite non-focusable+windows. Prohibited activation policy preserved both visibility and the active+application in an OS-observed browser run. Hidden tests do not establish native+presentation or real desktop input correctness.++`test:focus` observes actual macOS app activation and visible windows around the+runner. `test-window-probe.cjs` covers repeated windows, reopen events, input,+capture and cleanup. The observer reports other-app switches without causing+them; zero observed switches does not verify a manual app-switch scenario.+The native observer currently verifies macOS only.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 85852753..ea523672 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -112,7 +112,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. |+| [0101](0101-gui-tests-preserve-desktop-focus.md) | GUI tests stay hidden by default; visible opt-in can overlap other apps, and native foreground checks require separate opt-in. |## When to write one