graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Add an opt-in macOS session observer on the screen edge
justrach882efc6ad11e
diff --git a/apps/native/components/site/DesktopSettings.tsx b/apps/native/components/site/DesktopSettings.tsxindex 1b39329c..0086fb4c 100644--- a/apps/native/components/site/DesktopSettings.tsx+++ b/apps/native/components/site/DesktopSettings.tsx@@ -6,26 +6,39 @@ import { desktop, type LinkDestination } from "@/lib/desktop";export default function DesktopSettings({ labeled = false, embedded = false }: { labeled?: boolean; embedded?: boolean }) {const [available, setAvailable] = useState(false);+ const [canObserver, setCanObserver] = useState(false);const [open, setOpen] = useState(false);const [destination, setDestination] = useState<LinkDestination | null>(null);+ const [observer, setObserver] = useState<boolean | null>(null);const [saving, setSaving] = useState(false);const [error, setError] = useState("");const trigger = useRef<HTMLButtonElement>(null);const panel = useRef<HTMLDivElement>(null);- useEffect(() => setAvailable(!!desktop()?.linkSettings), []);+ useEffect(() => {+ setAvailable(!!desktop()?.linkSettings || !!desktop()?.notchSettings);+ }, []);useEffect(() => {if (!embedded) return;let alive = true;void desktop()?.linkSettings?.("load").then(value => { if (alive) setDestination(value); }).catch(() => { if (alive) setError("Could not load link settings."); });+ void desktop()?.notchSettings?.("load").then(value => {+ if (!alive) return;+ if (typeof value === "boolean") { setCanObserver(true); setObserver(value); }+ }).catch(() => { if (alive) setCanObserver(false); });return () => { alive = false; };}, [embedded]);useEffect(() => {if (!open) return;let alive = true;- setDestination(null); setError("");- void desktop()!.linkSettings!("load").then(value => { if (alive) setDestination(value); })+ setDestination(null); setObserver(null); setError("");+ void desktop()?.linkSettings?.("load").then(value => { if (alive) setDestination(value); }).catch(() => { if (alive) setError("Could not load link settings. Close Settings and try again."); });+ void desktop()?.notchSettings?.("load").then(value => {+ if (!alive) return;+ if (typeof value === "boolean") { setCanObserver(true); setObserver(value); }+ else setCanObserver(false);+ }).catch(() => { if (alive) setCanObserver(false); });panel.current?.querySelector<HTMLButtonElement>("button")?.focus();const keys = (event: KeyboardEvent) => {if (event.key === "Escape") { event.stopPropagation(); setOpen(false); restoreActionFocus(trigger.current); }@@ -46,15 +59,31 @@ export default function DesktopSettings({ labeled = false, embedded = false }: {catch { setError("Could not save link settings. Try again."); }finally { setSaving(false); }};+ const chooseObserver = async (value: boolean) => {+ setSaving(true); setError("");+ try {+ const next = await desktop()!.notchSettings!("save", value);+ if (typeof next === "boolean") setObserver(next);+ }+ catch { setError("Could not save observer settings. Try again."); }+ finally { setSaving(false); }+ };if (!available) return null;const fields = <>- <fieldset disabled={destination === null || saving}>+ {desktop()?.linkSettings && <fieldset disabled={destination === null || saving}><legend className="mb-1 text-xs font-medium">Open web links in</legend><p className="mb-3 text-xs text-ink-3">Choose where links from conversations open. Graff keeps pages beside your chat.</p><div className="flex flex-col gap-2">{([['system', 'System default browser'], ['graff', 'Graff built-in Browser']] as const).map(([value, label]) =><button key={value} aria-pressed={destination === value} onClick={() => void choose(value)} className={`rounded-lg border px-3 py-2 text-left text-xs focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-50 ${destination === value ? "border-accent bg-accent-tint" : "border-line hover:bg-hover"}`}>{label}</button>)}</div>- </fieldset>+ </fieldset>}+ {canObserver && <fieldset disabled={observer === null || saving} className={desktop()?.linkSettings ? "mt-4" : undefined}>+ <legend className="mb-1 text-xs font-medium">Session observer</legend>+ <p className="mb-3 text-xs text-ink-3">A pill on the right screen edge while Codegraff is in the background. Off until you turn it on.</p>+ <div className="flex flex-col gap-2">{([[false, 'Hide'], [true, 'Show']] as const).map(([value, label]) =>+ <button key={label} aria-pressed={observer === value} onClick={() => void chooseObserver(value)} className={`rounded-lg border px-3 py-2 text-left text-xs focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-50 ${observer === value ? "border-accent bg-accent-tint" : "border-line hover:bg-hover"}`}>{label}</button>+ )}</div>+ </fieldset>}{saving && <p role="status" className="mt-3 text-xs text-ink-3">Saving…</p>}{error && <p role="alert" className="mt-3 text-xs text-red">{error}</p>}</>;diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex c2f69c10..563c3cc6 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -6,8 +6,8 @@ import { useUnreadChats } from "./useUnreadChats";import { useHarnessSessions } from "./useHarnessSessions";import { resumeQueuedPrompt } from "@/lib/prompt-queue-resume";import { createPromptRunner } from "./harness-prompt-runner";-import { workspaceActions } from "./harness-workspace-actions";+import { useNotchObserver } from "./useNotchObserver";import { useSavedConversation, ConversationOpenNotice } from "./useSavedConversation";import { useQuietSettings } from "./useQuietSettings";import { useTabDrag } from "./useTabDrag";@@ -481,6 +481,7 @@ export default function GraffHarness() {onClearPins={() => setPins(thread.id, [])} health={health}onOpenProject={() => setDialog({ mode: "new" })} onProjects={() => setProjectsOpen(true)} onConversations={openConversations} />;+ useNotchObserver(chats, busyIds, focusChat);useDesktopShortcuts({ closeChat, newChat, reopenClosed, toggleSplit, focusChat, chats: groups.tabs.map(tab => ({ id: groups.focusOf(tab.id) })), activeId, columns: columnIds,split: direction => { setZoomedPane(null); addPane(direction); },zoomPane: () => setZoomedPane(value => value === null ? activeId : null),@@ -488,7 +489,6 @@ export default function GraffHarness() {toggleTerminal, equalize: groups.balance, openWorkspace: () => setDialog({ mode: "new" }),});-const paneTodos = lastAssistant?.turn.todos ?? [];// Zoom only changes visibility; the split order is retained.const columns = (zoomedPane !== null ? [zoomedPane] : columnIds).map((id) => chats.find((c) => c.id === id)).filter((c): c is Chat => c !== undefined);diff --git a/apps/native/components/site/useNotchObserver.ts b/apps/native/components/site/useNotchObserver.tsnew file mode 100644index 00000000..cdb297f3--- /dev/null+++ b/apps/native/components/site/useNotchObserver.ts@@ -0,0 +1,61 @@+"use client";+import { useEffect, useRef } from "react";+import { agentRequest, type LocalAgent } from "@/lib/agents";+import { desktop } from "@/lib/desktop";+import { notchSnapshot } from "@/lib/notch-snapshot";+import type { Chat } from "./harness-types";++async function loadAgents(): Promise<LocalAgent[]> {+ try {+ const data = await agentRequest(undefined, { action: "list", scope: "device" });+ return Array.isArray(data?.agents) ? data.agents : [];+ } catch {+ return [];+ }+}++/** Push live ACP work to the edge observer. The panel itself never takes focus. */+export function useNotchObserver(chats: Chat[], busyIds: ReadonlySet<number>, focusChat: (id: number) => void) {+ const chatsRef = useRef(chats);+ const busyRef = useRef(busyIds);+ const focusRef = useRef(focusChat);+ const agentsRef = useRef<LocalAgent[]>([]);+ chatsRef.current = chats;+ busyRef.current = busyIds;+ focusRef.current = focusChat;++ useEffect(() => {+ const bridge = desktop();+ if (!bridge?.notch) return undefined;+ const publish = () => {+ void bridge.notch?.({ sessions: notchSnapshot(chatsRef.current, busyRef.current, Date.now(), agentsRef.current) });+ };+ publish();+ const timer = setInterval(publish, 1000);+ const agents = setInterval(() => {+ void loadAgents().then((list) => {+ agentsRef.current = list;+ publish();+ });+ }, 5000);+ void loadAgents().then((list) => {+ agentsRef.current = list;+ publish();+ });+ return () => {+ clearInterval(timer);+ clearInterval(agents);+ void bridge.notch?.({ sessions: [] });+ };+ }, []);++ useEffect(() => {+ void desktop()?.notch?.({ sessions: notchSnapshot(chats, busyIds, Date.now(), agentsRef.current) });+ }, [chats, busyIds]);++ useEffect(() => {+ return desktop()?.notchSubscribe?.((id) => {+ if (id > 0) focusRef.current(id);+ });+ }, []);+}diff --git a/apps/native/electron/README.md b/apps/native/electron/README.mdindex d8201d3d..49279432 100644--- a/apps/native/electron/README.md+++ b/apps/native/electron/README.md@@ -46,6 +46,11 @@ process-tree sample. macOS 26 uses grouped Liquid Glass surfaces. RSS sums maydouble-count shared pages; CPU is the lifetime average from `ps`, not a sampledinstantaneous peak. Closing the application terminates its Bun/ACP process group.+**Settings → Session observer** (or View → Session observer) pins a SwiftUI+notch to the right screen edge while the app is in the background. Off until+you turn it on. Cells are live ACP work, not chat titles. Hover for the+label; click to focus that chat. The panel never becomes the key window.+Run checks with Bun from `apps/native`:```shdiff --git a/apps/native/electron/build.sh b/apps/native/electron/build.shindex 71f5d531..7405b4ce 100644--- a/apps/native/electron/build.sh+++ b/apps/native/electron/build.sh@@ -36,11 +36,14 @@ cp "$(command -v bun)" "$resources/bun"cp "$root/zig-out/bin/graff" "$resources/graff"xcrun clang -O2 -Wall -Wextra -mmacosx-version-min=14.0 "$here/native/terminal.c" -o "$resources/native/graff-terminal"xcrun swiftc -O -emit-library -module-name GraffActivity -target arm64-apple-macosx14.0 \- "$here/native/Activity.swift" "$here/native/ComputerUse.swift" "$here/native/Glass.swift" -o "$resources/native/libGraffActivity.dylib" \+ "$here/native/Activity.swift" "$here/native/ComputerUse.swift" "$here/native/Glass.swift" \+ "$here/native/NotchLayout.swift" "$here/native/NotchView.swift" "$here/native/NotchPanel.swift" \+ -o "$resources/native/libGraffActivity.dylib" \-Xlinker -install_name -Xlinker @rpath/libGraffActivity.dylibxcrun clang -O2 -bundle -undefined dynamic_lookup -mmacosx-version-min=14.0 \-I "$ui/node_modules/node-api-headers/include" "$here/native/activity.c" \-L "$resources/native" -lGraffActivity -Wl,-rpath,@loader_path -o "$resources/native/activity.node"+bun "$here/check-native-symbols.cjs" "$resources/native"/usr/libexec/PlistBuddy -c 'Set :CFBundleIdentifier dev.codegraff' "$bundle/Contents/Info.plist"/usr/libexec/PlistBuddy -c 'Set :CFBundleName Codegraff' "$bundle/Contents/Info.plist"/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $version" "$bundle/Contents/Info.plist"diff --git a/apps/native/electron/check-native-symbols.cjs b/apps/native/electron/check-native-symbols.cjsnew file mode 100644index 00000000..4fc3aa0b--- /dev/null+++ b/apps/native/electron/check-native-symbols.cjs@@ -0,0 +1,32 @@+const { execFileSync } = require('node:child_process');+const path = require('node:path');++// Node-API entrypoints intentionally use dynamic_lookup. Our Swift bridge+// entrypoints must not: a missing one can become a null call during addon load.+function checkNativeSymbols(directory) {+ const imports = execFileSync('nm', ['-u', path.join(directory, 'activity.node')], { encoding: 'utf8' });+ const exports = execFileSync('nm', ['-gU', path.join(directory, 'libGraffActivity.dylib')], { encoding: 'utf8' });+ const symbols = text => new Set(text.match(/\b_graff_[a-zA-Z0-9_]+\b/g) || []);+ const required = symbols(imports), provided = symbols(exports);+ if (!required.size) throw new Error('Native bridge exposes no graff imports to verify');+ const missing = [...required].filter(symbol => !provided.has(symbol));+ if (missing.length) throw new Error(`Native bridge symbols not exported: ${missing.join(', ')}`);+ // Exercise NAPI_MODULE_INIT in the same Electron runtime used by the app,+ // without opening windows or installing a click callback.+ execFileSync(require('electron'), ['-e', `+ const bridge = require(process.env.GRAFF_NATIVE_ADDON);+ for (const key of ['show', 'computer', 'glass', 'updateNotch', 'hideNotch', 'inspectNotch', 'layoutNotch', 'onNotchClick']) {+ if (typeof bridge[key] !== 'function') throw new Error('Missing native method: ' + key);+ }+ `], {+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', GRAFF_NATIVE_ADDON: path.resolve(directory, 'activity.node') },+ timeout: 15000, stdio: 'pipe',+ });+ return required.size;+}++if (require.main === module) {+ if (process.argv.length !== 3) throw new Error('Usage: check-native-symbols.cjs <native directory>');+ console.log(`Native bridge exports verified: ${checkNativeSymbols(process.argv[2])}`);+}+module.exports = { checkNativeSymbols };diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjsindex 1e783d78..1151d24b 100644--- a/apps/native/electron/main.cjs+++ b/apps/native/electron/main.cjs@@ -18,6 +18,8 @@ const { chromiumSample } = require('./hardware-profile.cjs');const fs = require('node:fs/promises');const { Terminals } = require('./terminal.cjs');const { installWindowState } = require('./window-state.cjs');+const { createNotch, notchStore } = require('./notch.cjs');+const { pollCodexUsage } = require('./notch-usage.cjs');const root = process.env.GRAFF_CWD || app.getPath('home');const resources = process.env.GRAFF_ELECTRON_RESOURCES || process.resourcesPath;@@ -26,6 +28,7 @@ app.setPath('userData', process.env.GRAFF_ELECTRON_PROFILE || (process.env.GRAFFif (process.env.GRAFF_ELECTRON_SMOKE) process.env.GRAFF_THEMES_DIR = path.join(app.getPath('userData'), 'themes');let win, browser, backend, automation, computer, profiler;let terminals;+let notch;const workspaceRequests = require('./workspace-open.cjs').workspaceOpen(target => {if (win && !win.isDestroyed()) win.webContents.send('workspace-open', target);});@@ -57,6 +60,7 @@ function stop() {return stopPromise = (async () => {let unsafe = false;try { testDesktop?.assertSafe(); } catch (error) { console.error(error); unsafe = true; }+ notch?.hide();terminals?.closeAll();profiler?.stop(); browser?.closeAll(); automation?.server.close(); await backend?.stop();testDesktop?.cleanup();@@ -99,6 +103,40 @@ app.whenReady().then(async () => {if (mainFrame && !inPlace) { workspaceRequests.loading(); browser.closeAll(); terminals.closeAll(); }});computer = new ComputerUse(resources, win);+ if (process.platform === 'darwin') {+ try {+ const native = require(path.join(resources, 'native/activity.node'));+ notch = createNotch({+ native: {+ updateNotch: json => native.updateNotch(json),+ hideNotch: () => native.hideNotch(),+ inspectNotch: () => native.inspectNotch(),+ },+ store: notchStore(app.getPath('userData')),+ allow: !testDesktop,+ activate: id => {+ if (!win || win.isDestroyed()) return;+ if (win.isMinimized()) win.restore();+ win.show();+ win.focus();+ if (id > 0) win.webContents.send('notch-select', id);+ },+ });+ if (typeof native.onNotchClick === 'function') native.onNotchClick(id => notch.clicked(Number(id)));+ if (notch && !testDesktop) {+ const tick = () => {+ pollCodexUsage().then(cells => notch.setExtra(cells)).catch(() => notch.setExtra([]));+ };+ tick();+ setInterval(tick, 60_000);+ }+ } catch { /* unpackaged trees without the dylib keep the React app only */ }+ }+ ipcMain.on('notch', (event, snapshot) => {+ trusted(event);+ if (!snapshot || typeof snapshot !== 'object' || JSON.stringify(snapshot).length > 16000) return;+ notch?.update(snapshot);+ });const sampleTree = intervalSampler(process.pid, () => browser.liveCount);const sampleAgents = agentSampler();profiler = new Profiler(async () => {@@ -163,6 +201,19 @@ app.whenReady().then(async () => {if (action === 'save') return linkSettings.save(value);throw new Error('Unknown link settings action');});+ ipcMain.handle('notch-settings', (event, action, value) => {+ trusted(event);+ if (!notch) return null;+ if (action === 'load') return notch.enabled();+ if (action === 'save') {+ const enabled = notch.setEnabled(!!value);+ const view = Menu.getApplicationMenu()?.items.find(item => item.label === 'View');+ const item = view?.submenu?.items.find(entry => entry.label === 'Session observer');+ if (item) item.checked = enabled;+ return enabled;+ }+ throw new Error('Unknown notch settings action');+ });installExternalLinks(win.webContents, backend.origin, async url => {if (await linkSettings.load() === 'graff') {if (!win.isDestroyed()) win.webContents.send('browser-event', { type: 'open-link', url });@@ -193,7 +244,7 @@ app.whenReady().then(async () => {} }, { label: 'Browser passkey help…', click: () => void require('./webauthn.cjs').showPasskeyHelp({window: win, browser, dialog, shell: require('electron').shell, configured: passkeysConfigured,}).catch(() => dialog.showErrorBox('Browser passkeys', 'Could not open the default browser. Use another sign-in method on the site.')) }] },- { role: 'editMenu' }, { label: 'View', submenu: [{ role: 'reload' }, { role: 'toggleDevTools' }, { role: 'togglefullscreen' }, { label: 'Release browser pages', click: () => { browser.closeAll(); win.webContents.send('browser-event', { type: 'released' }); } }] },+ { role: 'editMenu' }, { label: 'View', submenu: [{ role: 'reload' }, { role: 'toggleDevTools' }, { role: 'togglefullscreen' }, { label: 'Session observer', type: 'checkbox', checked: !!notch?.enabled(), visible: process.platform === 'darwin', click: item => { item.checked = notch?.setEnabled(item.checked) ?? false; } }, { label: 'Release browser pages', click: () => { browser.closeAll(); win.webContents.send('browser-event', { type: 'released' }); } }] },{ label: 'Performance', submenu: [{ label: 'Start recording', click: () => void profiler.start() },{ label: 'Mark candidate phase', click: () => profiler.mark('candidate') },diff --git a/apps/native/electron/native-gui.cjs b/apps/native/electron/native-gui.cjsindex 8f734771..088cad6b 100644--- a/apps/native/electron/native-gui.cjs+++ b/apps/native/electron/native-gui.cjs@@ -60,6 +60,25 @@ app.whenReady().then(async () => {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 layout = JSON.parse(native.layoutNotch(2, 0));+ assert.equal(layout.identifier, 'graff.observer-notch');+ assert.ok(layout.width >= 52 && layout.height > 64);+ native.updateNotch(JSON.stringify({ sessions: [+ { id: 1, title: 'Live', caption: 'bash', state: 'working', label: 'Working for 12s', detail: 'Running 1 tool…' },+ { id: 2, title: 'Ask', caption: 'ask', state: 'waiting', label: 'Waiting for your answer', detail: '' },+ ] }));+ let observer;+ await wait(() => {+ observer = JSON.parse(native.inspectNotch());+ return observer.visible && observer.cells === 2 && observer.width >= 52;+ }, 'The observer notch did not present');+ assert.equal(observer.key, false, 'The observer must not become the key window');+ assert.equal(observer.main, false, 'The observer must not become the main window');+ assert.equal(observer.hidesOnDeactivate, false);+ assert.equal(inspect().key, true, 'Presenting the observer must leave the app window key');+ native.hideNotch();+ await wait(() => !JSON.parse(native.inspectNotch()).visible, 'The observer notch did not hide');+ report.passed.push('SwiftUI observer notch stays non-activating and visible while unfocused');const computer = new ComputerUse(resources, win);const permissions = computer.status();report.permissions = { accessibility: permissions.accessibility, screenRecording: permissions.screenRecording };diff --git a/apps/native/electron/native/NotchLayout.swift b/apps/native/electron/native/NotchLayout.swiftnew file mode 100644index 00000000..dc685b95--- /dev/null+++ b/apps/native/electron/native/NotchLayout.swift@@ -0,0 +1,63 @@+import CoreGraphics+import Foundation++/// Geometry for the right-edge observer. Inverse flares sit in the extra+/// height so the pill reads as welded to the bezel, not a floating card.+enum NotchLayout {+ static let cellWidth: CGFloat = 52+ static let cellHeight: CGFloat = 64+ static let hoverWidth: CGFloat = 220+ static let curl: CGFloat = 12+ static let corner: CGFloat = 24+ static let maxCells = 6+ static let identifier = "graff.observer-notch"++ static func cellCount(_ count: Int) -> Int {+ max(1, min(count, maxCells))+ }++ static func size(cells: Int, hovering: Bool) -> CGSize {+ let n = cellCount(cells)+ let width = cellWidth + (hovering ? hoverWidth : 0)+ let height = CGFloat(n) * cellHeight + curl * 2+ return CGSize(width: width, height: height)+ }++ /// Right edge of `screen`, vertically centred in `visible`.+ static func frame(screen: CGRect, visible: CGRect, cells: Int, hovering: Bool) -> CGRect {+ let size = size(cells: cells, hovering: hovering)+ let x = screen.maxX - size.width+ let minY = visible.minY + curl+ let maxY = visible.maxY - size.height - curl+ let y = min(max(visible.midY - size.height / 2, minY), max(minY, maxY))+ return CGRect(x: x, y: y, width: size.width, height: size.height)+ }++ static func contains(_ point: CGPoint, in bounds: CGRect, hovering: Bool) -> Bool {+ let pill = CGRect(+ x: bounds.maxX - cellWidth,+ y: bounds.minY + curl,+ width: cellWidth,+ height: max(0, bounds.height - curl * 2)+ )+ if pill.contains(point) { return true }+ if hovering {+ let card = CGRect(x: bounds.minX, y: bounds.minY + curl, width: hoverWidth, height: bounds.height - curl * 2)+ return card.contains(point)+ }+ return false+ }+}++@_cdecl("graff_notch_layout_json")+public func graffNotchLayoutJSON(_ cells: Int32, _ hovering: Int32) -> UnsafeMutablePointer<CChar>? {+ let size = NotchLayout.size(cells: Int(cells), hovering: hovering != 0)+ let payload: [String: Any] = [+ "width": size.width, "height": size.height,+ "cellWidth": NotchLayout.cellWidth, "curl": NotchLayout.curl,+ "maxCells": NotchLayout.maxCells, "identifier": NotchLayout.identifier,+ ]+ guard let data = try? JSONSerialization.data(withJSONObject: payload),+ let text = String(data: data, encoding: .utf8) else { return nil }+ return strdup(text)+}diff --git a/apps/native/electron/native/NotchPanel.swift b/apps/native/electron/native/NotchPanel.swiftnew file mode 100644index 00000000..8eb14883--- /dev/null+++ b/apps/native/electron/native/NotchPanel.swift@@ -0,0 +1,144 @@+import AppKit+import SwiftUI++/// Non-activating so glancing at a chat never steals the key app.+final class ObserverPanel: NSPanel {+ override var canBecomeKey: Bool { false }+ override var canBecomeMain: Bool { false }++ convenience init() {+ self.init(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)+ identifier = NSUserInterfaceItemIdentifier(NotchLayout.identifier)+ level = .statusBar+ collectionBehavior = [.canJoinAllSpaces, .stationary, .fullScreenAuxiliary, .ignoresCycle]+ isOpaque = false+ backgroundColor = .clear+ hasShadow = false+ isMovable = false+ hidesOnDeactivate = false+ becomesKeyOnlyIfNeeded = true+ isReleasedWhenClosed = false+ ignoresMouseEvents = false+ sharingType = .readOnly+ }+}++final class NotchHost: NSHostingView<NotchRootView> {+ var hovering: Bool = false++ override func hitTest(_ point: NSPoint) -> NSView? {+ NotchLayout.contains(point, in: bounds, hovering: hovering) ? super.hitTest(point) : nil+ }+}++private struct Snapshot: Decodable {+ var sessions: [NotchSession]?+}++enum NotchController {+ private static var panel: ObserverPanel?+ private static var host: NotchHost?+ private static let store = NotchStore()+ private static var screenObserver: NSObjectProtocol?++ static func update(_ json: String) {+ let sessions: [NotchSession]+ if let data = json.data(using: .utf8), let parsed = try? JSONDecoder().decode(Snapshot.self, from: data) {+ sessions = Array((parsed.sessions ?? []).prefix(NotchLayout.maxCells))+ } else {+ sessions = []+ }+ store.sessions = sessions.isEmpty+ ? [NotchSession(id: 0, title: "Codegraff", caption: "idle", state: .idle, label: "Idle", detail: "")]+ : sessions+ show()+ }++ static func hide() {+ panel?.orderOut(nil)+ }++ static func inspectJSON() -> String {+ let panel = panel+ let payload: [String: Any] = [+ "visible": panel?.isVisible ?? false,+ "key": panel?.isKeyWindow ?? false,+ "main": panel?.isMainWindow ?? false,+ "hidesOnDeactivate": panel?.hidesOnDeactivate ?? true,+ "level": panel?.level.rawValue ?? 0,+ "cells": store.sessions.count,+ "identifier": NotchLayout.identifier,+ "width": panel?.frame.width ?? 0,+ "height": panel?.frame.height ?? 0,+ ]+ guard let data = try? JSONSerialization.data(withJSONObject: payload),+ let text = String(data: data, encoding: .utf8) else { return "{}" }+ return text+ }++ private static func show() {+ if panel == nil {+ let panel = ObserverPanel()+ let host = NotchHost(rootView: root())+ panel.contentView = host+ self.panel = panel+ self.host = host+ screenObserver = NotificationCenter.default.addObserver(+ forName: NSApplication.didChangeScreenParametersNotification,+ object: nil, queue: .main+ ) { _ in NotchController.reposition() }+ }+ host?.rootView = root()+ reposition()+ panel?.orderFrontRegardless()+ }++ private static func root() -> NotchRootView {+ NotchRootView(store: store, onSelect: { id in graff_notch_emit_click(Int32(id)) }, onHover: { hovering in+ host?.hovering = hovering+ reposition()+ })+ }++ private static func reposition() {+ guard let panel else { return }+ let hovering = store.hovering != nil+ host?.hovering = hovering+ let screen = NSScreen.main ?? NSScreen.screens.first+ let frame = screen.map {+ NotchLayout.frame(screen: $0.frame, visible: $0.visibleFrame, cells: store.sessions.count, hovering: hovering)+ } ?? .zero+ panel.setFrame(frame, display: true)+ host?.frame = CGRect(origin: .zero, size: frame.size)+ }+}++public typealias NotchClickFn = @convention(c) (Int32) -> Void+private var notchClick: NotchClickFn = { _ in }++@_cdecl("graff_notch_set_click")+public func graffNotchSetClick(_ handler: NotchClickFn?) {+ notchClick = handler ?? { _ in }+}++private func graff_notch_emit_click(_ id: Int32) {+ notchClick(id)+}++@_cdecl("graff_notch_update")+public func graffNotchUpdate(_ json: UnsafePointer<CChar>?) {+ guard Thread.isMainThread, let json else { return }+ NotchController.update(String(cString: json))+}++@_cdecl("graff_notch_hide")+public func graffNotchHide() {+ guard Thread.isMainThread else { return }+ NotchController.hide()+}++@_cdecl("graff_notch_inspect")+public func graffNotchInspect() -> UnsafeMutablePointer<CChar>? {+ guard Thread.isMainThread else { return nil }+ return strdup(NotchController.inspectJSON())+}diff --git a/apps/native/electron/native/NotchView.swift b/apps/native/electron/native/NotchView.swiftnew file mode 100644index 00000000..a7ea57ad--- /dev/null+++ b/apps/native/electron/native/NotchView.swift@@ -0,0 +1,182 @@+import SwiftUI++enum NotchSessionState: String, Codable {+ case working, waiting, idle, error+}++struct NotchSession: Codable, Identifiable, Equatable {+ var id: Int+ var title: String+ var caption: String?+ var state: NotchSessionState+ var label: String+ var detail: String+ var kind: String?+ var percent: Int?+}++final class NotchStore: ObservableObject {+ @Published var sessions: [NotchSession] = [+ NotchSession(id: 0, title: "Codegraff", state: .idle, label: "Idle", detail: ""),+ ]+ @Published var hovering: Int?+}++/// Emerald is the working ring; coral is errors only. Waiting is a warm sand+/// so it is not an error and not CodeNotch's yellow.+private let accent = Color(red: 5 / 255, green: 150 / 255, blue: 105 / 255)+private let waiting = Color(red: 196 / 255, green: 148 / 255, blue: 58 / 255)+private let fill = Color(red: 0.09, green: 0.09, blue: 0.09)++struct NotchRootView: View {+ @ObservedObject var store: NotchStore+ var onSelect: (Int) -> Void+ var onHover: (Bool) -> Void++ var body: some View {+ HStack(spacing: 0) {+ if let id = store.hovering, let session = store.sessions.first(where: { $0.id == id }) {+ hoverCard(session)+ .frame(width: NotchLayout.hoverWidth)+ }+ VStack(spacing: 0) {+ ForEach(store.sessions.prefix(NotchLayout.maxCells)) { session in+ cell(session)+ .frame(width: NotchLayout.cellWidth, height: NotchLayout.cellHeight)+ .onHover { inside in+ store.hovering = inside ? session.id : (store.hovering == session.id ? nil : store.hovering)+ onHover(store.hovering != nil)+ }+ .onTapGesture { onSelect(session.id) }+ .accessibilityLabel("\(session.caption ?? session.title), \(session.label)")+ }+ }+ }+ .padding(.vertical, NotchLayout.curl)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)+ .background(NotchShape().fill(fill))+ }++ private func cell(_ session: NotchSession) -> some View {+ VStack(spacing: 4) {+ NotchRing(state: session.state, percent: session.percent)+ .frame(width: 28, height: 28)+ Text(session.caption ?? session.title)+ .font(.system(size: 9, weight: .semibold))+ .foregroundStyle(.white)+ .lineLimit(1)+ .frame(width: 44)+ }+ .frame(maxHeight: .infinity)+ }++ private func hoverCard(_ session: NotchSession) -> some View {+ VStack(alignment: .leading, spacing: 4) {+ Text(session.title)+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(.white)+ .lineLimit(2)+ Text(session.label)+ .font(.system(size: 11))+ .foregroundStyle(.white.opacity(0.72))+ if !session.detail.isEmpty {+ Text(session.detail)+ .font(.system(size: 11))+ .foregroundStyle(.white.opacity(0.55))+ .lineLimit(3)+ }+ }+ .padding(12)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)+ }+}++struct NotchRing: View {+ let state: NotchSessionState+ var percent: Int? = nil++ var body: some View {+ Group {+ if percent != nil {+ ring(at: Date())+ } else if state == .working || state == .waiting {+ TimelineView(.animation) { timeline in ring(at: timeline.date) }+ } else {+ ring(at: Date())+ }+ }+ }++ private func ring(at date: Date) -> some View {+ let t = date.timeIntervalSinceReferenceDate+ let used = percent.map { min(1, max(0, Double($0) / 100)) }+ return ZStack {+ Circle().stroke(color.opacity(0.22), lineWidth: 2.5)+ if let used {+ Circle()+ .trim(from: 0, to: used)+ .stroke(color, style: StrokeStyle(lineWidth: 2.5, lineCap: .round))+ .rotationEffect(.degrees(-90))+ } else if state == .working {+ Circle()+ .trim(from: 0, to: 0.28)+ .stroke(color, style: StrokeStyle(lineWidth: 2.5, lineCap: .round))+ .rotationEffect(.degrees(t.truncatingRemainder(dividingBy: 1) * 360))+ } else {+ Circle()+ .trim(from: 0, to: state == .idle ? 0.08 : 1)+ .stroke(color.opacity(state == .waiting ? 0.55 + 0.35 * sin(t * 3) : 1), style: StrokeStyle(lineWidth: 2.5, lineCap: .round))+ .rotationEffect(.degrees(-90))+ }+ if used == nil {+ Image(systemName: glyph)+ .font(.system(size: 9, weight: .bold))+ .foregroundStyle(.white.opacity(state == .working ? 0.9 : 0.75))+ }+ }+ }++ private var color: Color {+ switch state {+ case .working: return accent+ case .waiting: return waiting+ case .error: return Color(red: 0.82, green: 0.28, blue: 0.26)+ case .idle: return Color.white.opacity(0.45)+ }+ }++ private var glyph: String {+ switch state {+ case .working: return "arrow.clockwise"+ case .waiting: return "pause.fill"+ case .error: return "xmark"+ case .idle: return "checkmark"+ }+ }+}++struct NotchShape: Shape {+ func path(in rect: CGRect) -> Path {+ let curl = min(NotchLayout.curl, rect.height / 4, rect.width / 2)+ let corner = min(NotchLayout.corner, (rect.height - 2 * curl) / 2, rect.width / 2)+ var path = Path()+ path.move(to: CGPoint(x: rect.maxX, y: rect.minY))+ if curl > 0 {+ path.addArc(center: CGPoint(x: rect.maxX - curl, y: rect.minY), radius: curl,+ startAngle: .degrees(0), endAngle: .degrees(90), clockwise: false)+ }+ path.addLine(to: CGPoint(x: rect.minX + corner, y: rect.minY + curl))+ path.addArc(center: CGPoint(x: rect.minX + corner, y: rect.minY + curl + corner), radius: corner,+ startAngle: .degrees(270), endAngle: .degrees(180), clockwise: true)+ path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY - curl - corner))+ path.addArc(center: CGPoint(x: rect.minX + corner, y: rect.maxY - curl - corner), radius: corner,+ startAngle: .degrees(180), endAngle: .degrees(90), clockwise: true)+ path.addLine(to: CGPoint(x: rect.maxX - curl, y: rect.maxY - curl))+ if curl > 0 {+ path.addArc(center: CGPoint(x: rect.maxX - curl, y: rect.maxY), radius: curl,+ startAngle: .degrees(270), endAngle: .degrees(360), clockwise: false)+ }+ path.closeSubpath()+ return path+ }+}diff --git a/apps/native/electron/native/activity.c b/apps/native/electron/native/activity.cindex 4f241505..14a5e6e7 100644--- a/apps/native/electron/native/activity.c+++ b/apps/native/electron/native/activity.c@@ -5,6 +5,23 @@extern void graff_show_activity(void *view, const char *json);extern int graff_install_pane_glass(void *view);+extern void graff_notch_update(const char *json);+extern void graff_notch_hide(void);+extern char *graff_notch_inspect(void);+extern char *graff_notch_layout_json(int cells, int hovering);+extern void graff_notch_set_click(void (*handler)(int));++static napi_threadsafe_function notch_click = NULL;+void graff_notch_emit_click(int id) {+ if (notch_click) napi_call_threadsafe_function(notch_click, (void *)(intptr_t)id, napi_tsfn_nonblocking);+}+static void notch_click_js(napi_env env, napi_value js_cb, void *ctx, void *data) {+ napi_value argv, recv;+ if (!env || !js_cb) return;+ napi_create_int32(env, (int)(intptr_t)data, &argv);+ napi_get_undefined(env, &recv);+ napi_call_function(env, recv, js_cb, 1, &argv, NULL);+}static napi_value show(napi_env env, napi_callback_info info) {size_t argc = 2, handle_size = 0, json_size = 0;@@ -59,7 +76,63 @@ static napi_value glass(napi_env env, napi_callback_info info) {napi_create_int32(env, graff_install_pane_glass(view), &result);return result;}+static napi_value take_string(napi_env env, char *text) {+ napi_value result;+ if (text) { napi_create_string_utf8(env, text, NAPI_AUTO_LENGTH, &result); free(text); }+ else napi_get_null(env, &result);+ return result;+}+static napi_value update_notch(napi_env env, napi_callback_info info) {+ size_t argc = 1, size = 0;+ napi_value arg, result;+ napi_get_undefined(env, &result);+ if (napi_get_cb_info(env, info, &argc, &arg, NULL, NULL) != napi_ok || argc != 1 ||+ napi_get_value_string_utf8(env, arg, NULL, 0, &size) != napi_ok || size > 16000) {+ napi_throw_type_error(env, NULL, "Expected bounded observer JSON"); return result;+ }+ char *json = calloc(size + 1, 1);+ if (!json) { napi_throw_error(env, NULL, "Out of memory"); return result; }+ napi_get_value_string_utf8(env, arg, json, size + 1, &size);+ graff_notch_update(json);+ free(json);+ return result;+}+static napi_value hide_notch(napi_env env, napi_callback_info info) {+ napi_value result;+ napi_get_undefined(env, &result);+ graff_notch_hide();+ return result;+}+static napi_value inspect_notch(napi_env env, napi_callback_info info) {+ return take_string(env, graff_notch_inspect());+}+static napi_value layout_notch(napi_env env, napi_callback_info info) {+ size_t argc = 2;+ napi_value args[2];+ int32_t cells = 1, hovering = 0;+ if (napi_get_cb_info(env, info, &argc, args, NULL, NULL) != napi_ok) {+ napi_value result; napi_get_null(env, &result); return result;+ }+ if (argc > 0) napi_get_value_int32(env, args[0], &cells);+ if (argc > 1) napi_get_value_int32(env, args[1], &hovering);+ return take_string(env, graff_notch_layout_json(cells, hovering));+}+static napi_value on_notch_click(napi_env env, napi_callback_info info) {+ size_t argc = 1;+ napi_value arg, result, name;+ napi_get_undefined(env, &result);+ napi_valuetype type;+ if (napi_get_cb_info(env, info, &argc, &arg, NULL, NULL) != napi_ok || argc != 1 ||+ napi_typeof(env, arg, &type) != napi_ok || type != napi_function) {+ napi_throw_type_error(env, NULL, "Expected a click callback"); return result;+ }+ if (notch_click) { napi_release_threadsafe_function(notch_click, napi_tsfn_abort); notch_click = NULL; }+ napi_create_string_utf8(env, "graff-notch-click", NAPI_AUTO_LENGTH, &name);+ napi_create_threadsafe_function(env, arg, NULL, name, 0, 1, NULL, NULL, NULL, notch_click_js, ¬ch_click);+ return result;+}NAPI_MODULE_INIT() {+ graff_notch_set_click(graff_notch_emit_click);napi_value fn;napi_create_function(env, "show", NAPI_AUTO_LENGTH, show, NULL, &fn);napi_set_named_property(env, exports, "show", fn);@@ -67,5 +140,15 @@ NAPI_MODULE_INIT() {napi_set_named_property(env, exports, "computer", fn);napi_create_function(env, "glass", NAPI_AUTO_LENGTH, glass, NULL, &fn);napi_set_named_property(env, exports, "glass", fn);+ napi_create_function(env, "updateNotch", NAPI_AUTO_LENGTH, update_notch, NULL, &fn);+ napi_set_named_property(env, exports, "updateNotch", fn);+ napi_create_function(env, "hideNotch", NAPI_AUTO_LENGTH, hide_notch, NULL, &fn);+ napi_set_named_property(env, exports, "hideNotch", fn);+ napi_create_function(env, "inspectNotch", NAPI_AUTO_LENGTH, inspect_notch, NULL, &fn);+ napi_set_named_property(env, exports, "inspectNotch", fn);+ napi_create_function(env, "layoutNotch", NAPI_AUTO_LENGTH, layout_notch, NULL, &fn);+ napi_set_named_property(env, exports, "layoutNotch", fn);+ napi_create_function(env, "onNotchClick", NAPI_AUTO_LENGTH, on_notch_click, NULL, &fn);+ napi_set_named_property(env, exports, "onNotchClick", fn);return exports;}diff --git a/apps/native/electron/notch-usage.cjs b/apps/native/electron/notch-usage.cjsnew file mode 100644index 00000000..f2b9a7b5--- /dev/null+++ b/apps/native/electron/notch-usage.cjs@@ -0,0 +1,84 @@+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');++const CODEX_USAGE = 'https://chatgpt.com/backend-api/wham/usage';++function clip(text, limit) {+ const trimmed = String(text || '').trim();+ if (trimmed.length <= limit) return trimmed;+ return `${trimmed.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;+}++function usedPercent(window) {+ const n = window?.used_percent;+ if (typeof n !== 'number' || !Number.isFinite(n)) return null;+ return Math.max(0, Math.min(100, Math.round(n)));+}++function resetDetail(window) {+ const seconds = Number(window?.reset_after_seconds);+ if (!Number.isFinite(seconds) || seconds <= 0) return '';+ if (seconds < 60) return `resets in ${Math.round(seconds)}s`;+ if (seconds < 3600) return `resets in ${Math.round(seconds / 60)}m`;+ return `resets in ${Math.round(seconds / 3600)}h`;+}++function usageCell(id, title, percent, detail) {+ const used = Math.max(0, Math.min(100, Math.round(percent)));+ const state = used >= 100 ? 'error' : used >= 80 ? 'waiting' : 'working';+ return {+ id: hash(`usage:${id}`),+ title,+ caption: `${used}%`,+ state,+ label: `${title} ${used}%`,+ detail: clip(detail, 120),+ kind: 'usage',+ percent: used,+ };+}++function hash(key) {+ let value = 0;+ for (let i = 0; i < key.length; i++) value = (Math.imul(value, 31) + key.charCodeAt(i)) | 0;+ if (value === 0) return -1;+ return value > 0 ? -value : value;+}++/** Map a Codex `/wham/usage` body to notch cells. Tokens never leave this module. */+function cellsFromCodexUsage(json) {+ const primary = usedPercent(json?.rate_limit?.primary_window);+ if (primary == null) return [];+ return [usageCell('codex', 'Codex', primary, resetDetail(json.rate_limit.primary_window))];+}++function readCodexAuth(home = os.homedir()) {+ try {+ const raw = JSON.parse(fs.readFileSync(path.join(home, '.codex', 'auth.json'), 'utf8'));+ const token = raw?.tokens?.access_token;+ const account = raw?.tokens?.account_id || raw?.account_id;+ if (typeof token === 'string' && token.length > 0) {+ return { token, account: typeof account === 'string' ? account : '' };+ }+ } catch { /* unsigned-in Codex is a missing cell, not an error */ }+ return null;+}++async function pollCodexUsage({ home, fetchImpl } = {}) {+ const auth = readCodexAuth(home);+ if (!auth) return [];+ const headers = { Authorization: `Bearer ${auth.token}`, Accept: 'application/json', 'Cache-Control': 'no-cache' };+ if (auth.account) headers['ChatGPT-Account-Id'] = auth.account;+ const fetchFn = fetchImpl || globalThis.fetch;+ if (!fetchFn) return [];+ try {+ const res = await fetchFn(CODEX_USAGE, { method: 'GET', headers });+ if (!res || !res.ok) return [];+ return cellsFromCodexUsage(await res.json());+ } catch {+ return [];+ }+}++module.exports = { cellsFromCodexUsage, readCodexAuth, pollCodexUsage, usageCell };diff --git a/apps/native/electron/notch-usage.test.cjs b/apps/native/electron/notch-usage.test.cjsnew file mode 100644index 00000000..70238abb--- /dev/null+++ b/apps/native/electron/notch-usage.test.cjs@@ -0,0 +1,40 @@+const { test, expect } = require('bun:test');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { cellsFromCodexUsage, pollCodexUsage, readCodexAuth } = require('./notch-usage.cjs');++test('Codex primary window becomes a percent cell without leftover tokens', () => {+ const cells = cellsFromCodexUsage({+ rate_limit: { primary_window: { used_percent: 42.4, reset_after_seconds: 3600 } },+ });+ expect(cells).toHaveLength(1);+ expect(cells[0]).toMatchObject({ title: 'Codex', caption: '42%', kind: 'usage', percent: 42, detail: 'resets in 1h' });+ expect(JSON.stringify(cells)).not.toMatch(/Bearer|access_token/);+});++test('missing or unreadable usage windows yield no cells', () => {+ expect(cellsFromCodexUsage({})).toEqual([]);+ expect(cellsFromCodexUsage({ rate_limit: { primary_window: { used_percent: null } } })).toEqual([]);+});++test('unsigned Codex auth is a missing cell, and fetch never sees a token dump', async () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-codex-'));+ expect(readCodexAuth(home)).toBe(null);+ expect(await pollCodexUsage({ home, fetchImpl: () => { throw new Error('should not fetch'); } })).toEqual([]);+ fs.mkdirSync(path.join(home, '.codex'));+ fs.writeFileSync(path.join(home, '.codex', 'auth.json'), JSON.stringify({+ tokens: { access_token: 'secret-token', account_id: 'acct' },+ }));+ const headers = [];+ const cells = await pollCodexUsage({+ home,+ fetchImpl: async (_url, init) => {+ headers.push(init.headers);+ return { ok: true, json: async () => ({ rate_limit: { primary_window: { used_percent: 9 } } }) };+ },+ });+ expect(cells[0]).toMatchObject({ caption: '9%', kind: 'usage' });+ expect(headers[0].Authorization).toBe('Bearer secret-token');+ expect(JSON.stringify(cells)).not.toContain('secret-token');+});diff --git a/apps/native/electron/notch.cjs b/apps/native/electron/notch.cjsnew file mode 100644index 00000000..b0699ca0--- /dev/null+++ b/apps/native/electron/notch.cjs@@ -0,0 +1,64 @@+const fs = require('node:fs');+const path = require('node:path');++function notchStore(directory) {+ const file = path.join(directory, 'observer-notch.json');+ return {+ load() {+ try {+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));+ return data.enabled === true;+ } catch {+ return false;+ }+ },+ save(enabled) {+ fs.mkdirSync(directory, { recursive: true });+ fs.writeFileSync(file, JSON.stringify({ enabled: !!enabled }), { mode: 0o600 });+ },+ };+}++function createNotch({ native, store, activate, allow = true }) {+ let enabled = allow && store.load();+ let last = { sessions: [] };+ let extra = [];+ const apply = () => {+ if (!native) return;+ if (!enabled) {+ native.hideNotch();+ return;+ }+ native.updateNotch(JSON.stringify({ sessions: [...(last.sessions || []), ...extra].slice(0, 6) }));+ };+ if (enabled) apply();+ return {+ enabled: () => enabled,+ setEnabled(on) {+ if (!allow) return false;+ enabled = !!on;+ store.save(enabled);+ if (enabled) apply();+ else native?.hideNotch();+ return enabled;+ },+ update(snapshot) {+ last = snapshot && typeof snapshot === 'object' ? snapshot : { sessions: [] };+ apply();+ },+ setExtra(cells) {+ extra = Array.isArray(cells) ? cells : [];+ apply();+ },+ hide() { native?.hideNotch(); },+ inspect() {+ if (!native?.inspectNotch) return null;+ try { return JSON.parse(native.inspectNotch()); } catch { return null; }+ },+ clicked(id) {+ activate?.(id);+ },+ };+}++module.exports = { notchStore, createNotch };diff --git a/apps/native/electron/notch.test.cjs b/apps/native/electron/notch.test.cjsnew file mode 100644index 00000000..a2b870c8--- /dev/null+++ b/apps/native/electron/notch.test.cjs@@ -0,0 +1,90 @@+const { test, expect } = require('bun:test');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { notchStore, createNotch } = require('./notch.cjs');++function fixture() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'graff-notch-'));+}++test('missing preference defaults off without creating files', () => {+ const directory = path.join(fixture(), 'nested');+ expect(notchStore(directory).load()).toBe(false);+ expect(fs.existsSync(directory)).toBe(false);+});++test('corrupt preference defaults off, and save roundtrips', () => {+ const directory = fixture();+ fs.writeFileSync(path.join(directory, 'observer-notch.json'), '{');+ const store = notchStore(directory);+ expect(store.load()).toBe(false);+ store.save(true);+ expect(JSON.parse(fs.readFileSync(path.join(directory, 'observer-notch.json'), 'utf8'))).toEqual({ enabled: true });+ expect(store.load()).toBe(true);+ store.save(false);+ expect(JSON.parse(fs.readFileSync(path.join(directory, 'observer-notch.json'), 'utf8'))).toEqual({ enabled: false });+ expect(store.load()).toBe(false);+});++test('a missing preference never presents the notch', () => {+ const calls = [];+ const notch = createNotch({+ native: { updateNotch: json => calls.push(['update', json]), hideNotch: () => calls.push(['hide']) },+ store: notchStore(fixture()),+ });+ expect(notch.enabled()).toBe(false);+ notch.update({ sessions: [{ id: 1, title: 'Live', state: 'working', label: 'Working', detail: '' }] });+ expect(calls).toEqual([['hide']]);+});++test('packaged checks never show the notch on the host desktop', () => {+ const calls = [];+ const notch = createNotch({+ native: { updateNotch: json => calls.push(json), hideNotch: () => calls.push('hide') },+ store: { load: () => true, save: () => {} },+ allow: false,+ });+ expect(notch.enabled()).toBe(false);+ expect(notch.setEnabled(true)).toBe(false);+ notch.update({ sessions: [] });+ expect(calls).toEqual(['hide']);+});++test('updates are dropped while hidden and clicks still activate', () => {+ const calls = [];+ const native = {+ updateNotch: json => calls.push(['update', json]),+ hideNotch: () => calls.push(['hide']),+ inspectNotch: () => '{"visible":false,"key":false}',+ };+ const selected = [];+ const notch = createNotch({+ native,+ store: { load: () => true, save: () => {} },+ activate: id => selected.push(id),+ });+ notch.update({ sessions: [{ id: 2, title: 'Live', state: 'working', label: 'Working', detail: '' }] });+ expect(calls[0][0]).toBe('update');+ notch.setEnabled(false);+ expect(calls.at(-1)).toEqual(['hide']);+ const before = calls.length;+ notch.update({ sessions: [{ id: 2, title: 'Live', state: 'waiting', label: 'Waiting', detail: '' }] });+ expect(calls.length).toBe(before + 1);+ expect(calls.at(-1)).toEqual(['hide']);+ notch.clicked(2);+ expect(selected).toEqual([2]);+ expect(notch.inspect()).toMatchObject({ visible: false, key: false });+});++test('usage cells merge in the main process and never replace live sessions', () => {+ const calls = [];+ const notch = createNotch({+ native: { updateNotch: json => calls.push(JSON.parse(json)), hideNotch: () => {} },+ store: { load: () => true, save: () => {} },+ });+ notch.update({ sessions: [{ id: 2, title: 'Live', caption: 'bash', state: 'working', label: 'Working', detail: '', kind: 'session' }] });+ notch.setExtra([{ id: -3, title: 'Codex', caption: '42%', state: 'working', label: 'Codex 42%', detail: '', kind: 'usage', percent: 42 }]);+ const last = calls.at(-1);+ expect(last.sessions.map(cell => cell.caption)).toEqual(['bash', '42%']);+});diff --git a/apps/native/electron/preload.cjs b/apps/native/electron/preload.cjsindex f7d77917..0b10fffa 100644--- a/apps/native/electron/preload.cjs+++ b/apps/native/electron/preload.cjs@@ -22,6 +22,13 @@ contextBridge.exposeInMainWorld('graffDesktop', {return () => ipcRenderer.removeListener('terminal-event', listener);},activity: () => ipcRenderer.invoke('activity'),+ notch: snapshot => ipcRenderer.send('notch', snapshot),+ notchSettings: (action, value) => ipcRenderer.invoke('notch-settings', action, value),+ notchSubscribe: callback => {+ const listener = (_event, id) => callback(id);+ ipcRenderer.on('notch-select', listener);+ return () => ipcRenderer.removeListener('notch-select', listener);+ },windowControl: action => ipcRenderer.invoke('window-control', action),subscribe: callback => {const listener = (_event, message) => callback(message);diff --git a/apps/native/lib/desktop.ts b/apps/native/lib/desktop.tsindex b9d55243..b5d35b8e 100644--- a/apps/native/lib/desktop.ts+++ b/apps/native/lib/desktop.ts@@ -16,6 +16,9 @@ export type DesktopBridge = {windowControl?(action: "fullscreen" | "zoom-in" | "zoom-out" | "reset-zoom"): Promise<void>;browser<T = PageInfo | null>(chat: string, method: string, params?: Record<string, unknown>): Promise<T>;activity(): Promise<{ rssMiB: number; cpuPercent: number; processes: number; browsers: number }>;+ notch?(snapshot: { sessions: Array<{ id: number; title: string; caption?: string; state: string; label: string; detail: string; kind?: string; percent?: number }> }): void;+ notchSettings?(action: 'load' | 'save', value?: boolean): Promise<boolean | null>;+ notchSubscribe?(callback: (id: number) => void): () => void;subscribe(callback: (event: DesktopEvent) => void): () => void;};declare global { interface Window { graffDesktop?: DesktopBridge } }diff --git a/apps/native/lib/notch-snapshot.test.ts b/apps/native/lib/notch-snapshot.test.tsnew file mode 100644index 00000000..c3c9e392--- /dev/null+++ b/apps/native/lib/notch-snapshot.test.ts@@ -0,0 +1,94 @@+import { expect, test } from "bun:test";+import { emptyTurn } from "./acp";+import { NOTCH_ACTIVITY_LIMIT, agentCells, notchCell, notchSnapshot, usageCell } from "./notch-snapshot";++test("an empty workspace still has one idle cell so the notch is findable", () => {+ expect(notchSnapshot([], new Set(), 0)).toEqual([+ { id: 0, title: "Codegraff", caption: "idle", state: "idle", label: "Idle", detail: "", kind: "session" },+ ]);+});++test("ask and stalled live turns both read as waiting", () => {+ const ask = { id: 1, title: "Review", messages: [{ role: "assistant", turn: { ...emptyTurn(), status: "ask" as const } }] };+ expect(notchCell(ask, false, 0)).toMatchObject({ state: "waiting", caption: "ask" });+ const stalled = {+ id: 2,+ title: "Build",+ messages: [{+ role: "assistant",+ turn: { ...emptyTurn(), status: "streaming" as const, connected: true, startedAt: 1000, lastUpdateAt: 4000 },+ }],+ };+ expect(notchCell(stalled, false, 25000)).toMatchObject({ state: "waiting", caption: "ask", label: expect.stringMatching(/^Working for /) });+});++test("idle chats leave the notch; live work and errors stay", () => {+ const chats = [+ { id: 3, title: "Starting a casual conversation", messages: [{ role: "assistant", turn: { ...emptyTurn(), status: "done" as const, startedAt: 1, endedAt: 2 } }] },+ { id: 1, title: "Live", messages: [{ role: "assistant", turn: { ...emptyTurn(), status: "thinking" as const, connected: true, startedAt: 1, lastUpdateAt: 2, activityKind: "agent_thought_chunk" as const } }] },+ { id: 2, title: "Broke", messages: [{ role: "assistant", turn: { ...emptyTurn(), status: "error" as const, startedAt: 1 } }] },+ ];+ expect(notchSnapshot(chats, new Set(), 3).map((cell) => cell.id)).toEqual([1, 2]);+ expect(notchSnapshot(chats, new Set(), 3).map((cell) => cell.caption)).toEqual(["think", "err"]);+});++test("busy without a turn is starting only when nobody has spoken", () => {+ expect(notchCell({ id: 4, title: null, messages: [] }, true, 0)).toMatchObject({+ title: "Chat 4",+ caption: "work",+ state: "working",+ label: "Starting…",+ });+ expect(notchCell({+ id: 5,+ title: "Starting a casual conversation",+ messages: [{ role: "user", text: "hey there" }],+ }, true, 0)).toMatchObject({ caption: "work", label: "Working" });+});++test("a running tool caption is the tool, not the chat title", () => {+ const chat = {+ id: 8,+ title: "Starting a casual conversation",+ messages: [{+ role: "assistant" as const,+ turn: {+ ...emptyTurn(),+ status: "streaming" as const,+ connected: true,+ startedAt: 1,+ lastUpdateAt: 2,+ tools: [{ id: "1", name: "bash", icon: "run" as const, chip: "bash", status: "running" as const, detail: [] }],+ },+ }],+ };+ expect(notchCell(chat, true, 3)).toMatchObject({ caption: "bash", state: "working" });+});++test("the notch keeps at most four live chats, then usage", () => {+ const chats = Array.from({ length: 8 }, (_, i) => ({+ id: i + 1,+ title: `Chat ${i + 1}`,+ messages: [{ role: "assistant" as const, turn: { ...emptyTurn(), status: "thinking" as const, connected: true, startedAt: 1, lastUpdateAt: 1 } }],+ }));+ const usage = [usageCell("codex", "Codex", 42, "5h"), usageCell("grok", "Grok", 11, "3h")];+ const cells = notchSnapshot(chats, new Set(), 2, [], usage);+ expect(cells).toHaveLength(NOTCH_ACTIVITY_LIMIT + 2);+ expect(cells.slice(0, NOTCH_ACTIVITY_LIMIT).every((cell) => cell.kind === "session")).toBe(true);+ expect(cells.slice(NOTCH_ACTIVITY_LIMIT).map((cell) => cell.caption)).toEqual(["42%", "11%"]);+});++test("working ACP agents share the notch; idle ones do not", () => {+ const cells = agentCells([+ { session: "native-a", pid: 1, title: "Fix notch", task: "running bash", status: "working", workspace: "/tmp" },+ { session: "native-b", pid: 2, title: "Idle", task: "", status: "idle" },+ ]);+ expect(cells).toHaveLength(1);+ expect(cells[0]).toMatchObject({ caption: "running", state: "working", kind: "agent" });+});++test("long titles are clipped so the hover card stays a label", () => {+ const title = "x".repeat(120);+ expect(notchCell({ id: 1, title, messages: [] }, false, 0).title.length).toBeLessThanOrEqual(80);+ expect(notchCell({ id: 1, title, messages: [] }, false, 0).title.endsWith("…")).toBe(true);+});diff --git a/apps/native/lib/notch-snapshot.ts b/apps/native/lib/notch-snapshot.tsnew file mode 100644index 00000000..19a265c3--- /dev/null+++ b/apps/native/lib/notch-snapshot.ts@@ -0,0 +1,146 @@+import { turnActivity } from "./turn-activity";+import type { AssistantTurn } from "./graff-events";++export type NotchState = "working" | "waiting" | "idle" | "error";+export type NotchKind = "session" | "agent" | "usage";+export type NotchCell = {+ id: number;+ title: string;+ caption: string;+ state: NotchState;+ label: string;+ detail: string;+ kind: NotchKind;+ percent?: number;+};+export type NotchChat = {+ id: number;+ title: string | null;+ snapshot?: boolean;+ messages: Array<{ role: string; turn?: AssistantTurn; text?: string }>;+};+export type NotchAgent = { session: string; pid: number; title: string; task: string; status: string; workspace?: string };++export const NOTCH_CELL_LIMIT = 6;+export const NOTCH_ACTIVITY_LIMIT = 4;+export const NOTCH_TITLE_LIMIT = 80;++const RANK: Record<NotchState, number> = { waiting: 0, working: 1, error: 2, idle: 3 };++function clip(text: string, limit: number): string {+ const trimmed = text.trim();+ if (trimmed.length <= limit) return trimmed;+ return `${trimmed.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;+}++function shortName(raw: string): string {+ const text = raw.replace(/^mcp__/, "").replace(/__/g, " ").replace(/[_-]+/g, " ").trim();+ const word = text.split(/\s+/)[0] || "work";+ return clip(word.toLowerCase(), 8);+}++function runningTool(turn: AssistantTurn): string | null {+ const row = turn.tools.find((tool) => tool.status === "running");+ if (!row) return null;+ return shortName(row.chip || row.name || "tool");+}++export function notchCaption(state: NotchState, detail: string, tool: string | null): string {+ if (tool) return tool;+ if (state === "waiting") return "ask";+ if (state === "error") return "err";+ if (state === "idle") return "idle";+ if (/thinking/i.test(detail)) return "think";+ if (/writing/i.test(detail)) return "write";+ return "work";+}++export function notchCell(chat: NotchChat, busy: boolean, now: number): NotchCell {+ const title = clip(chat.title || `Chat ${chat.id}`, NOTCH_TITLE_LIMIT);+ const last = [...chat.messages].reverse().find((message) => message.role === "assistant" && message.turn);+ const spoke = chat.messages.some((message) => message.role === "user" || message.role === "assistant");+ if (!last?.turn) {+ const state: NotchState = busy ? "working" : "idle";+ const label = busy ? (spoke ? "Working" : "Starting…") : "Idle";+ return {+ id: chat.id, title, caption: notchCaption(state, label, null), state, label, detail: "", kind: "session",+ };+ }+ const activity = turnActivity(last.turn, now, { snapshot: chat.snapshot });+ let state: NotchState = "idle";+ if (activity.state === "error") state = "error";+ else if (activity.state === "input" || activity.state === "waiting") state = "waiting";+ else if (activity.state === "working" || busy) state = "working";+ const tool = state === "working" ? runningTool(last.turn) : null;+ const detail = [activity.detail, tool ? `ACP ${tool}` : ""].filter(Boolean).join(" · ");+ return {+ id: chat.id,+ title,+ caption: notchCaption(state, activity.detail, tool),+ state,+ label: clip(activity.label, 48),+ detail: clip(detail, 120),+ kind: "session",+ };+}++export function agentCells(agents: NotchAgent[]): NotchCell[] {+ return agents+ .filter((agent) => agent.status === "working")+ .map((agent) => {+ const title = clip(agent.title || agent.session || "Agent", NOTCH_TITLE_LIMIT);+ const task = clip(agent.task || "Working", 120);+ return {+ id: cellId(agent.session || String(agent.pid)),+ title,+ caption: shortName(agent.task || "work"),+ state: "working" as const,+ label: task || "Working",+ detail: clip(agent.workspace || "", 120),+ kind: "agent" as const,+ };+ });+}++export function usageCell(id: string, title: string, percent: number, detail: string): NotchCell {+ const used = Math.max(0, Math.min(100, Math.round(percent)));+ const state: NotchState = used >= 100 ? "error" : used >= 80 ? "waiting" : "working";+ return {+ id: cellId(`usage:${id}`),+ title,+ caption: `${used}%`,+ state,+ label: `${title} ${used}%`,+ detail: clip(detail, 120),+ kind: "usage",+ percent: used,+ };+}++function cellId(key: string): number {+ let hash = 0;+ for (let i = 0; i < key.length; i++) hash = (Math.imul(hash, 31) + key.charCodeAt(i)) | 0;+ if (hash === 0) return -1;+ return hash > 0 ? -hash : hash;+}++/** Live ACP work first. Idle chats do not occupy the notch. */+export function notchSnapshot(+ chats: NotchChat[],+ busy: ReadonlySet<number>,+ now: number,+ agents: NotchAgent[] = [],+ usage: NotchCell[] = [],+): NotchCell[] {+ const live = chats+ .map((chat) => notchCell(chat, busy.has(chat.id), now))+ .filter((cell) => cell.state !== "idle")+ .sort((a, b) => RANK[a.state] - RANK[b.state] || a.id - b.id);+ const activity = [...live, ...agentCells(agents)].slice(0, NOTCH_ACTIVITY_LIMIT);+ const limits = usage.filter((cell) => cell.kind === "usage").slice(0, NOTCH_CELL_LIMIT - activity.length);+ const cells = [...activity, ...limits].slice(0, NOTCH_CELL_LIMIT);+ if (cells.length === 0) {+ return [{ id: 0, title: "Codegraff", caption: "idle", state: "idle", label: "Idle", detail: "", kind: "session" }];+ }+ return cells;+}diff --git a/apps/native/scripts/test-native.mjs b/apps/native/scripts/test-native.mjsindex ba5453e2..68ce86f2 100644--- a/apps/native/scripts/test-native.mjs+++ b/apps/native/scripts/test-native.mjs@@ -22,12 +22,15 @@ const run = async (command, args) => {};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', 'electron/native/Glass.swift', '-o', path.join(native, 'libGraffActivity.dylib'),+ 'electron/native/Activity.swift', 'electron/native/ComputerUse.swift', 'electron/native/Glass.swift',+ 'electron/native/NotchLayout.swift', 'electron/native/NotchView.swift', 'electron/native/NotchPanel.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')]);+console.log(`Native bridge exports verified: ${require('../electron/check-native-symbols.cjs').checkNativeSymbols(native)}`);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.');diff --git a/docs/adr/0141-observer-notch-is-a-nonactivating-panel.md b/docs/adr/0141-observer-notch-is-a-nonactivating-panel.mdnew file mode 100644index 00000000..54642693--- /dev/null+++ b/docs/adr/0141-observer-notch-is-a-nonactivating-panel.md@@ -0,0 +1,41 @@+# 0141. The session observer is a non-activating SwiftUI edge panel++Status: accepted++## Context++ADR 0070 limited SwiftUI to the Activity sheet. Codegraff already runs several+chats at once; once the window is behind Xcode or a browser, there is no+glanceable answer to "is it still working, or waiting on me?"++[Codenotch](https://github.com/vinzdg/codenotch) solved the same glance+problem for other coding tools with a borderless `NSPanel` welded to a+screen edge: `.nonactivatingPanel`, `hidesOnDeactivate = false`,+`.statusBar` level, all Spaces. Copying that *panel contract* is the+feature. Copying its usage meters, palette, or provider stack is not.++An Electron `alwaysOnTop` `BrowserWindow` would still activate the app on+click and is a Chromium surface, not a bezel.++## Decision++The desktop hosts a right-edge SwiftUI observer through the existing+Node-API dylib (`updateNotch` / `hideNotch`). Cells show live ACP work+(tool / think / write / ask), not chat titles. Idle chats leave the+notch. Working ACP agents share the four activity slots. Usage rings+(`kind: "usage"` plus a percent) are merged in the main process; tokens+never go to Swift or the renderer. At most six cells. Hovering expands a+label; clicking focuses the main window and that chat. The panel cannot+become key or main. It is off until Settings or View → Session observer+turns it on. Smoke and hidden GUI tests pass `allow: false` so the notch+never appears on the host desktop.++SwiftUI is therefore the Activity sheet **and** this observer. The+renderer only publishes a bounded snapshot; graff still owns coding.++## Consequences++A rebuild of the native dylib is required before the notch is visible.+The preference lives in `observer-notch.json`. Visual screenshots of the+Chromium window are unchanged because the notch is a separate AppKit+panel.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 93fb3fbb..27b5fbe7 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -160,6 +160,7 @@ record only when you need the evidence or the edge cases.| [0138](0138-unselected-splits-use-glass-overlay.md) | Unselected split panes keep their transcript under a light wash; the focused pane stays the working surface. || [0139](0139-bounced-answers-stay-turn-local.md) | Retain a bounced answer only in the current turn, before unfinished-work reconciliation; never recover it from persisted history. || [0140](0140-rlm-is-listed-when-available.md) | `rlm` is on the catalog whenever it is available. No batch-size or compactAt gate. `--old` still hides it. |+| [0141](0141-observer-notch-is-a-nonactivating-panel.md) | The desktop session observer is a non-activating SwiftUI edge panel; cells are live ACP work, opt-in from Settings. |## When to write one