Skip to content

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

Python

test(gui): run native presentation checks on macOS CI

justrach66a2d4d93374
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml
index 84f607ac..d24cdf96 100644
--- a/.github/workflows/desktop.yml
+++ b/.github/workflows/desktop.yml
@@ -1,9 +1,10 @@
name: desktop
on:
+ workflow_dispatch:
pull_request:
paths: ['apps/native/**', '.github/workflows/desktop.yml']
push:
- branches: [main]
+ branches: [main, 'release/**']
paths: ['apps/native/**', '.github/workflows/desktop.yml']
permissions:
contents: read
@@ -27,4 +28,43 @@ jobs:
- run: bun run test:projects
- run: bun run test:stress
- run: bun run test:agents
+ - run: bun run test:sessions
- run: bun build electron/updater-runtime.cjs --target=node --format=cjs --external electron --outfile /tmp/updater-runtime.cjs
+ native:
+ name: native macOS GUI
+ runs-on: macos-26
+ timeout-minutes: 20
+ defaults:
+ run:
+ working-directory: apps/native
+ steps:
+ - uses: actions/checkout@v7
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: '1.4.2'
+ - run: bun install --frozen-lockfile
+ - name: Native graphical session, Activity sheet and OS capabilities
+ run: bun run test:native
+ env:
+ GRAFF_ELECTRON_FOREGROUND: '1'
+ - run: bun run build
+ - name: Foreground GUI suite including native fullscreen
+ run: bun run test:visual
+ env:
+ GRAFF_ELECTRON_FOREGROUND: '1'
+ - name: Require native fullscreen coverage
+ run: bun scripts/check-native-ci.mjs
+ - name: Native coverage report
+ if: always()
+ run: bun scripts/check-native-ci.mjs --summary
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: native-gui-results
+ path: |
+ zig-out/native-tests/native-results.json
+ zig-out/visual-tests/test-run.json
+ zig-out/visual-tests/stress-results.json
+ zig-out/visual-tests/stress-fullscreen.png
+ if-no-files-found: warn
+ retention-days: 7
diff --git a/apps/native/electron/VISUAL-TESTS.md b/apps/native/electron/VISUAL-TESTS.md
index e13745eb..6c36965a 100644
--- a/apps/native/electron/VISUAL-TESTS.md
+++ b/apps/native/electron/VISUAL-TESTS.md
@@ -1,5 +1,29 @@
# Desktop visual tests
+## Native CI coverage
+
+The desktop workflow keeps the background suite and adds a separate `macos-26`
+job with `GRAFF_ELECTRON_FOREGROUND=1`. It runs on pull requests and pushes to
+`main` and release branches. Its windows and fullscreen transitions belong to
+the CI machine's desktop, not the developer's desktop.
+
+`bun run test:native` compiles the production Activity/Computer Use bridge and
+a test-only AppKit observer. It requires a usable display and native window
+focus, then opens, dismisses with Return, and reopens the real SwiftUI Activity
+sheet. The foreground visual suite separately verifies fullscreen entry,
+reload, titlebar state and fullscreen exit. Missing reports or skipped fullscreen
+coverage fail `check-native-ci.mjs`.
+
+Native OS typing/Accessibility inspection and display capture require macOS
+permissions. The native runner does not request or change them. It runs each
+available check and records missing permissions as skips in the job summary
+and `native-results.json`; they are never reported as passed. On a runner with
+preconfigured permissions, `GRAFF_NATIVE_REQUIRE_OS_INPUT=1` makes them required.
+
+For compilation without opening windows, run
+`bun scripts/test-native.mjs --build-only`. Running `test:native` locally without
+explicit foreground opt-in fails before Electron starts.
+
For a fresh checkout, run these from `apps/native`:
```sh
diff --git a/apps/native/electron/native-ci.test.cjs b/apps/native/electron/native-ci.test.cjs
new file mode 100644
index 00000000..0172ddc0
--- /dev/null
+++ b/apps/native/electron/native-ci.test.cjs
@@ -0,0 +1,25 @@
+const { test, expect } = require('bun:test');
+const { spawnSync } = require('node:child_process');
+const path = require('node:path');
+const { validateCoverage } = require('../scripts/check-native-ci.mjs');
+
+test('the native CI launcher cannot activate a local desktop without explicit opt-in', () => {
+ for (const flags of [{}, { GRAFF_ELECTRON_VISIBLE: '1' }]) {
+ const env = { ...process.env, GRAFF_TEST_FOREGROUND: '', GRAFF_ELECTRON_FOREGROUND: '', ...flags };
+ const result = spawnSync(process.execPath, [path.join(__dirname, '../scripts/test-native.mjs')], { env, encoding: 'utf8', timeout: 5000 });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('Native GUI tests require GRAFF_ELECTRON_FOREGROUND=1');
+ expect(result.stdout).not.toContain('Electron tests:');
+ }
+});
+
+test('native CI rejects missing reports, background passes and skipped fullscreen checks', () => {
+ const native = { status: 'passed' }, visual = { mode: 'foreground', status: 'passed' }, stress = { fullscreen: 'passed' };
+ expect(() => validateCoverage(native, visual, stress)).not.toThrow();
+ for (const reports of [
+ [null, visual, stress], [native, null, stress], [native, visual, null],
+ [{ status: 'failed' }, visual, stress], [native, { ...visual, mode: 'hidden' }, stress],
+ [native, { ...visual, status: 'passed-with-skips' }, stress], [native, visual, { fullscreen: 'not run' }],
+ ]) expect(() => validateCoverage(...reports)).toThrow();
+ expect(() => validateCoverage({ status: 'passed-with-skips', skipped: ['OS permission unavailable'] }, visual, stress)).not.toThrow();
+});
diff --git a/apps/native/electron/native-gui.cjs b/apps/native/electron/native-gui.cjs
new file mode 100644
index 00000000..f3673cd8
--- /dev/null
+++ b/apps/native/electron/native-gui.cjs
@@ -0,0 +1,75 @@
+const testDesktop = require('./test-desktop.cjs');
+const { app, screen } = require('electron');
+const { ComputerUse } = require('./computer.cjs');
+const assert = require('node:assert/strict');
+const fs = require('node:fs'), path = require('node:path'), os = require('node:os');
+const resources = process.argv[2];
+const output = process.env.GRAFF_NATIVE_OUTPUT || path.resolve(__dirname, '../../../zig-out/native-tests');
+const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-native-test-'));
+app.setPath('userData', profile);
+const report = { status: 'running', passed: [], skipped: [] };
+let win, finished = false;
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const wait = async (condition, message) => {
+ for (let n = 0; n < 150; n++) { if (await condition()) return; await sleep(100); }
+ throw Error(message);
+};
+const deadline = setTimeout(() => finish(Error('Native GUI checks timed out')), 60000);
+function finish(error) {
+ if (finished) return;
+ finished = true; clearTimeout(deadline);
+ report.status = error ? 'failed' : report.skipped.length ? 'passed-with-skips' : 'passed';
+ if (error) { report.error = error.message; console.error(error); }
+ fs.mkdirSync(output, { recursive: true });
+ fs.writeFileSync(path.join(output, 'native-results.json'), JSON.stringify(report, null, 2));
+ testDesktop.cleanup(); fs.rmSync(profile, { recursive: true, force: true });
+ app.exit(error ? 1 : 0);
+}
+app.whenReady().then(async () => {
+ assert.ok(testDesktop.foreground, 'Native checks need an isolated foreground desktop');
+ assert.ok(screen.getAllDisplays().some(display => display.bounds.width > 0 && display.bounds.height > 0), 'CI has no usable display');
+ const native = require(path.join(resources, 'native/activity.node'));
+ const probe = require(path.join(resources, 'native/test-window-probe.node'));
+ win = testDesktop.createWindow({ width: 900, height: 720, webPreferences: { sandbox: true } });
+ const wc = win.webContents, handle = win.getNativeWindowHandle();
+ const inspect = () => JSON.parse(probe.inspect(handle));
+ await wc.loadURL('data:text/html,<title>Native test</title><input aria-label="Native input" id="input"><p>Isolated native GUI fixture</p>');
+ testDesktop.present(win);
+ await wait(() => { const state = inspect(); return state.active && state.visible && state.key && state.screens > 0; }, 'CI cannot activate a native window; a graphical login session is required');
+ report.passed.push('graphical session and native window focus');
+ for (let n = 0; n < 2; n++) {
+ native.show(handle, JSON.stringify({ rssMiB: 64, cpuPercent: 0, processes: 1, browsers: 0 }));
+ await wait(() => { const state = inspect(); return state.sheetAttached && state.sheetVisible && state.sheetKey; }, 'The production Activity sheet did not become visible and key');
+ const state = inspect();
+ assert.equal(state.sheetTitle, 'Activity');
+ assert.ok(state.sheetWidth >= 400 && state.sheetHeight > 200, 'The SwiftUI sheet has no usable content area');
+ probe.pressReturn(handle);
+ await wait(() => !inspect().sheetAttached, 'Return did not activate the Activity sheet Done button');
+ }
+ report.passed.push('production SwiftUI sheet presentation, Done key, dismissal and reopening');
+ const computer = new ComputerUse(resources, win);
+ const permissions = computer.status();
+ report.permissions = { accessibility: permissions.accessibility, screenRecording: permissions.screenRecording };
+ computer.enabled = true;
+ try {
+ if (permissions.accessibility) {
+ testDesktop.present(win);
+ await wc.executeJavaScript('document.querySelector("input").focus()');
+ const tree = await computer.command('snapshot', { pid: process.pid });
+ assert.ok(tree.elements.length > 0);
+ await computer.command('type', { pid: process.pid, text: 'native-input' });
+ await wait(() => wc.executeJavaScript('document.querySelector("input").value === "native-input"'), 'Native OS typing did not reach the test window');
+ report.passed.push('native Accessibility snapshot and OS typing');
+ } else report.skipped.push('native Accessibility snapshot and OS typing: Accessibility permission unavailable');
+ if (permissions.screenRecording) {
+ const capture = await computer.command('screenshot');
+ assert.ok(capture.data.length > 100);
+ report.passed.push('native display capture');
+ } else report.skipped.push('native display capture: Screen Recording permission unavailable');
+ } finally { computer.enabled = false; }
+ for (const reason of report.skipped) console.log(`SKIP: ${reason}`);
+ if (process.env.GRAFF_NATIVE_REQUIRE_OS_INPUT === '1') assert.deepEqual(report.skipped, [], 'This runner must have preconfigured OS permissions');
+ console.log('Native GUI checks:', JSON.stringify(report));
+}).then(() => finish()).catch(finish);
+process.on('SIGTERM', () => finish(Error('Native tests interrupted')));
+process.on('SIGINT', () => finish(Error('Native tests interrupted')));
diff --git a/apps/native/electron/native/test-window-probe.m b/apps/native/electron/native/test-window-probe.m
new file mode 100644
index 00000000..298a788c
--- /dev/null
+++ b/apps/native/electron/native/test-window-probe.m
@@ -0,0 +1,63 @@
+// Test-only observer loaded into Electron; it never ships in the native bridge.
+#import <AppKit/AppKit.h>
+#include <node_api.h>
+#include <string.h>
+
+static NSWindow *windowArg(napi_env env, napi_callback_info info) {
+ size_t argc = 1, size = 0;
+ napi_value arg;
+ void *bytes = NULL, *pointer = NULL;
+ if (napi_get_cb_info(env, info, &argc, &arg, NULL, NULL) != napi_ok || argc != 1 ||
+ napi_get_buffer_info(env, arg, &bytes, &size) != napi_ok || size != sizeof(pointer)) {
+ napi_throw_type_error(env, NULL, "Expected a native window handle");
+ return nil;
+ }
+ memcpy(&pointer, bytes, sizeof(pointer));
+ return [(__bridge NSView *)pointer window];
+}
+
+static napi_value json(napi_env env, NSDictionary *value) {
+ NSData *data = [NSJSONSerialization dataWithJSONObject:value options:0 error:nil];
+ napi_value result;
+ napi_create_string_utf8(env, data.bytes, data.length, &result);
+ return result;
+}
+
+static napi_value inspect(napi_env env, napi_callback_info info) {
+ NSWindow *window = windowArg(env, info);
+ if (!window) return NULL;
+ NSWindow *sheet = window.attachedSheet;
+ return json(env, @{
+ @"active": @(NSApp.active), @"screens": @(NSScreen.screens.count),
+ @"visible": @(window.visible), @"key": @(window.keyWindow),
+ @"sheetAttached": @(sheet != nil), @"sheetVisible": @(sheet.visible),
+ @"sheetKey": @(sheet.keyWindow), @"sheetTitle": sheet.title ?: @"",
+ @"sheetWidth": @(sheet.frame.size.width), @"sheetHeight": @(sheet.frame.size.height)
+ });
+}
+
+static napi_value pressReturn(napi_env env, napi_callback_info info) {
+ NSWindow *window = windowArg(env, info);
+ if (!window) return NULL;
+ NSWindow *target = window.attachedSheet ?: window;
+ // Exercise AppKit's default-button routing, without global event injection.
+ for (NSNumber *type in @[@(NSEventTypeKeyDown), @(NSEventTypeKeyUp)]) {
+ NSEvent *event = [NSEvent keyEventWithType:type.unsignedIntegerValue
+ location:NSZeroPoint modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime
+ windowNumber:target.windowNumber context:nil characters:@"\r"
+ charactersIgnoringModifiers:@"\r" isARepeat:NO keyCode:36];
+ [NSApp sendEvent:event];
+ }
+ napi_value result;
+ napi_get_undefined(env, &result);
+ return result;
+}
+
+NAPI_MODULE_INIT() {
+ napi_property_descriptor methods[] = {
+ { "inspect", NULL, inspect, NULL, NULL, NULL, napi_default, NULL },
+ { "pressReturn", NULL, pressReturn, NULL, NULL, NULL, napi_default, NULL },
+ };
+ napi_define_properties(env, exports, sizeof(methods) / sizeof(methods[0]), methods);
+ return exports;
+}
diff --git a/apps/native/electron/test-entrypoints.test.cjs b/apps/native/electron/test-entrypoints.test.cjs
index e1b8ac32..5ee4e483 100644
--- a/apps/native/electron/test-entrypoints.test.cjs
+++ b/apps/native/electron/test-entrypoints.test.cjs
@@ -23,7 +23,7 @@ test('every test BrowserWindow constructor uses the enforced options', () => {
});
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']) {
+ for (const name of ['visual-tests.cjs', 'performance-benchmark.cjs', 'gui-coding-smoke.cjs', 'test-window-probe.cjs', 'native-gui.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);
diff --git a/apps/native/package.json b/apps/native/package.json
index 14c36e97..7001a256 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -27,6 +27,7 @@
"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:native": "bun scripts/test-native.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",
diff --git a/apps/native/scripts/check-native-ci.mjs b/apps/native/scripts/check-native-ci.mjs
new file mode 100644
index 00000000..7ead5d58
--- /dev/null
+++ b/apps/native/scripts/check-native-ci.mjs
@@ -0,0 +1,34 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+export function validateCoverage(native, visual, stress) {
+ assert.ok(['passed', 'passed-with-skips'].includes(native?.status), 'Native Activity and graphical-session checks did not pass');
+ assert.equal(visual?.mode, 'foreground', 'CI must exercise foreground presentation');
+ assert.equal(visual?.status, 'passed', 'CI cannot silently skip foreground GUI checks');
+ assert.equal(stress?.fullscreen, 'passed', 'CI must exercise native fullscreen and reload');
+}
+if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
+const read = file => {
+ try { return JSON.parse(fs.readFileSync(path.join(root, 'zig-out', file), 'utf8')); }
+ catch { return null; }
+};
+const native = read('native-tests/native-results.json');
+const visual = read('visual-tests/test-run.json');
+const stress = read('visual-tests/stress-results.json');
+if (process.argv[2] === '--summary') {
+ const lines = ['## Native macOS GUI coverage', '',
+ `- Native checks: ${native?.status ?? 'no report'}`,
+ ...(native?.passed ?? []).map(name => `- Passed: ${name}`),
+ ...(native?.skipped ?? []).map(name => `- **Skipped:** ${name}`),
+ `- Foreground GUI suite: ${visual?.status ?? 'no report'}`,
+ `- Fullscreen transition and reload: ${stress?.fullscreen ?? 'no report'}`, '',
+ 'OS input and display capture require permissions granted to the runner. Missing permissions do not count as passed.', ''];
+ if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, lines.join('\n'));
+ else console.log(lines.join('\n'));
+} else {
+ validateCoverage(native, visual, stress);
+ console.log('Required native GUI and fullscreen checks passed.');
+}
+}
diff --git a/apps/native/scripts/test-native.mjs b/apps/native/scripts/test-native.mjs
new file mode 100644
index 00000000..ab82ed4e
--- /dev/null
+++ b/apps/native/scripts/test-native.mjs
@@ -0,0 +1,35 @@
+import { spawn } from 'node:child_process';
+import { createRequire } from 'node:module';
+import { mkdirSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { runElectron } from './test-electron.mjs';
+const require = createRequire(import.meta.url);
+const { testWindowMode } = require('../electron/test-window.cjs');
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const buildOnly = process.argv.length === 3 && process.argv[2] === '--build-only';
+if (process.argv.length > (buildOnly ? 3 : 2)) throw Error('Usage: test-native.mjs [--build-only]');
+if (!buildOnly && testWindowMode() !== 'foreground') {
+ throw Error('Native GUI tests require GRAFF_ELECTRON_FOREGROUND=1. Run them on an isolated CI desktop; --build-only does not launch windows.');
+}
+if (process.platform !== 'darwin') throw Error('Native GUI tests require macOS.');
+const resources = path.resolve(process.env.GRAFF_NATIVE_TEST_RESOURCES || path.join(root, '../../zig-out/native-tests/build'));
+const native = path.join(resources, 'native');
+mkdirSync(native, { recursive: true });
+const run = (command, args) => new Promise((resolve, reject) => {
+ const child = spawn(command, args, { cwd: root, stdio: 'inherit' });
+ child.once('error', reject);
+ child.once('exit', code => code === 0 ? resolve() : reject(Error(`${command} exited ${code}`)));
+});
+const target = `${process.arch === 'arm64' ? 'arm64' : 'x86_64'}-apple-macosx14.0`;
+await run('xcrun', ['swiftc', '-O', '-emit-library', '-module-name', 'GraffActivity', '-target', target,
+ 'electron/native/Activity.swift', 'electron/native/ComputerUse.swift', '-o', path.join(native, 'libGraffActivity.dylib'),
+ '-Xlinker', '-install_name', '-Xlinker', '@rpath/libGraffActivity.dylib']);
+const common = ['clang', '-O2', '-bundle', '-undefined', 'dynamic_lookup', '-mmacosx-version-min=14.0',
+ '-I', path.join(root, 'node_modules/node-api-headers/include')];
+await run('xcrun', [...common, 'electron/native/activity.c', '-L', native, '-lGraffActivity',
+ '-Wl,-rpath,@loader_path', '-o', path.join(native, 'activity.node')]);
+await run('xcrun', [...common, '-fobjc-arc', '-framework', 'AppKit', 'electron/native/test-window-probe.m',
+ '-o', path.join(native, 'test-window-probe.node')]);
+if (buildOnly) console.log('Native test bridge compiled. No GUI was launched.');
+else await runElectron('electron/native-gui.cjs', [resources]);
diff --git a/docs/adr/0101-gui-tests-preserve-desktop-focus.md b/docs/adr/0101-gui-tests-preserve-desktop-focus.md
index fd5f60bf..632a09ff 100644
--- a/docs/adr/0101-gui-tests-preserve-desktop-focus.md
+++ b/docs/adr/0101-gui-tests-preserve-desktop-focus.md
@@ -26,6 +26,18 @@ Only the default hidden mode keeps test windows off the desktop.
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.
+CI runs a separate native job on a hosted macOS graphical session. That job
+explicitly enables foreground mode and requires real window focus, production
+Activity sheet presentation and default-button dismissal, plus fullscreen and
+reload coverage from the visual suite. A missing graphical session or skipped
+fullscreen check fails CI. The normal local command remains hidden.
+
+Accessibility and Screen Recording permission are checked without requesting
+consent. OS input and display capture run when permitted; otherwise the native
+report and CI summary list them as skipped. A preconfigured runner can set
+`GRAFF_NATIVE_REQUIRE_OS_INPUT=1` to make those permissions mandatory. An ordinary
+hosted-runner pass does not establish OS input coverage when permission is absent.
+
## Consequences
The hidden renderer can exercise composer input, Tab traversal, split resizing,