graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Wire session observer settings and live ACP work into the notch
justrach5e223d34b7c0
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/useNotchObserver.ts b/apps/native/components/site/useNotchObserver.tsindex d271ac60..cdb297f3 100644--- a/apps/native/components/site/useNotchObserver.ts+++ b/apps/native/components/site/useNotchObserver.ts@@ -1,14 +1,25 @@"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";-/** Push open-chat status to the edge observer. The panel itself never takes focus. */+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;@@ -17,18 +28,29 @@ export function useNotchObserver(chats: Chat[], busyIds: ReadonlySet<number>, foconst bridge = desktop();if (!bridge?.notch) return undefined;const publish = () => {- void bridge.notch?.({ sessions: notchSnapshot(chatsRef.current, busyRef.current, Date.now()) });+ 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()) });+ void desktop()?.notch?.({ sessions: notchSnapshot(chats, busyIds, Date.now(), agentsRef.current) });}, [chats, busyIds]);useEffect(() => {diff --git a/apps/native/electron/README.md b/apps/native/electron/README.mdindex 1a28fad8..49279432 100644--- a/apps/native/electron/README.md+++ b/apps/native/electron/README.md@@ -46,10 +46,10 @@ 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.-**View → Session observer** pins a SwiftUI notch to the right screen edge while-the app is in the background. Each cell is an open chat (working, waiting on-you, idle, or error). Hover for the title; click to focus that chat. The panel-never becomes the key window. Turn it off from the same menu.+**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`:diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjsindex a2921878..0da21e7b 100644--- a/apps/native/electron/main.cjs+++ b/apps/native/electron/main.cjs@@ -213,6 +213,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 = require('electron').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 });diff --git a/apps/native/electron/native/NotchPanel.swift b/apps/native/electron/native/NotchPanel.swiftindex e6b02f66..8eb14883 100644--- a/apps/native/electron/native/NotchPanel.swift+++ b/apps/native/electron/native/NotchPanel.swift@@ -49,7 +49,7 @@ enum NotchController {sessions = []}store.sessions = sessions.isEmpty- ? [NotchSession(id: 0, title: "Codegraff", state: .idle, label: "Idle", detail: "")]+ ? [NotchSession(id: 0, title: "Codegraff", caption: "idle", state: .idle, label: "Idle", detail: "")]: sessionsshow()}diff --git a/apps/native/electron/native/NotchView.swift b/apps/native/electron/native/NotchView.swiftindex 779f273a..a7ea57ad 100644--- a/apps/native/electron/native/NotchView.swift+++ b/apps/native/electron/native/NotchView.swift@@ -7,9 +7,12 @@ enum NotchSessionState: String, Codable {struct NotchSession: Codable, Identifiable, Equatable {var id: Intvar title: String+ var caption: String?var state: NotchSessionStatevar label: Stringvar detail: String+ var kind: String?+ var percent: Int?}final class NotchStore: ObservableObject {@@ -45,7 +48,7 @@ struct NotchRootView: View {onHover(store.hovering != nil)}.onTapGesture { onSelect(session.id) }- .accessibilityLabel("\(session.title), \(session.label)")+ .accessibilityLabel("\(session.caption ?? session.title), \(session.label)")}}}@@ -56,9 +59,9 @@ struct NotchRootView: View {private func cell(_ session: NotchSession) -> some View {VStack(spacing: 4) {- NotchRing(state: session.state)+ NotchRing(state: session.state, percent: session.percent).frame(width: 28, height: 28)- Text(session.title)+ Text(session.caption ?? session.title).font(.system(size: 9, weight: .semibold)).foregroundStyle(.white).lineLimit(1)@@ -90,10 +93,13 @@ struct NotchRootView: View {struct NotchRing: View {let state: NotchSessionState+ var percent: Int? = nilvar body: some View {Group {- if state == .working || state == .waiting {+ if percent != nil {+ ring(at: Date())+ } else if state == .working || state == .waiting {TimelineView(.animation) { timeline in ring(at: timeline.date) }} else {ring(at: Date())@@ -103,9 +109,15 @@ struct NotchRing: View {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 state == .working {+ 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))@@ -116,9 +128,11 @@ struct NotchRing: View {.stroke(color.opacity(state == .waiting ? 0.55 + 0.35 * sin(t * 3) : 1), style: StrokeStyle(lineWidth: 2.5, lineCap: .round)).rotationEffect(.degrees(-90))}- Image(systemName: glyph)- .font(.system(size: 9, weight: .bold))- .foregroundStyle(.white.opacity(state == .working ? 0.9 : 0.75))+ if used == nil {+ Image(systemName: glyph)+ .font(.system(size: 9, weight: .bold))+ .foregroundStyle(.white.opacity(state == .working ? 0.9 : 0.75))+ }}}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.cjsindex 73b83874..b0699ca0 100644--- a/apps/native/electron/notch.cjs+++ b/apps/native/electron/notch.cjs@@ -7,9 +7,9 @@ function notchStore(directory) {load() {try {const data = JSON.parse(fs.readFileSync(file, 'utf8'));- return data.enabled !== false;+ return data.enabled === true;} catch {- return true;+ return false;}},save(enabled) {@@ -21,26 +21,35 @@ function notchStore(directory) {function createNotch({ native, store, activate, allow = true }) {let enabled = allow && store.load();- const apply = snapshot => {+ let last = { sessions: [] };+ let extra = [];+ const apply = () => {if (!native) return;if (!enabled) {native.hideNotch();return;}- native.updateNotch(JSON.stringify(snapshot || { sessions: [] }));+ native.updateNotch(JSON.stringify({ sessions: [...(last.sessions || []), ...extra].slice(0, 6) }));};- if (enabled) apply({ sessions: [] });+ if (enabled) apply();return {enabled: () => enabled,setEnabled(on) {if (!allow) return false;enabled = !!on;store.save(enabled);- if (enabled) apply({ sessions: [] });+ if (enabled) apply();else native?.hideNotch();return enabled;},- update: apply,+ 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;diff --git a/apps/native/electron/notch.test.cjs b/apps/native/electron/notch.test.cjsindex 74089815..a2b870c8 100644--- a/apps/native/electron/notch.test.cjs+++ b/apps/native/electron/notch.test.cjs@@ -8,22 +8,36 @@ function fixture() {return fs.mkdtempSync(path.join(os.tmpdir(), 'graff-notch-'));}-test('missing preference defaults on without creating files', () => {+test('missing preference defaults off without creating files', () => {const directory = path.join(fixture(), 'nested');- expect(notchStore(directory).load()).toBe(true);+ expect(notchStore(directory).load()).toBe(false);expect(fs.existsSync(directory)).toBe(false);});-test('corrupt preference defaults on, and save roundtrips', () => {+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({@@ -62,3 +76,15 @@ test('updates are dropped while hidden and clicks still activate', () => {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 51e16eab..0b10fffa 100644--- a/apps/native/electron/preload.cjs+++ b/apps/native/electron/preload.cjs@@ -23,6 +23,7 @@ contextBridge.exposeInMainWorld('graffDesktop', {},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);diff --git a/apps/native/lib/desktop.ts b/apps/native/lib/desktop.tsindex 2e4945c3..b5d35b8e 100644--- a/apps/native/lib/desktop.ts+++ b/apps/native/lib/desktop.ts@@ -16,7 +16,8 @@ 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; state: string; label: string; detail: string }> }): void;+ 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;};diff --git a/apps/native/lib/notch-snapshot.test.ts b/apps/native/lib/notch-snapshot.test.tsindex aba66b94..c3c9e392 100644--- a/apps/native/lib/notch-snapshot.test.ts+++ b/apps/native/lib/notch-snapshot.test.ts@@ -1,16 +1,16 @@import { expect, test } from "bun:test";import { emptyTurn } from "./acp";-import { NOTCH_CELL_LIMIT, notchCell, notchSnapshot } from "./notch-snapshot";+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", state: "idle", label: "Idle", detail: "" },+ { 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).state).toBe("waiting");+ expect(notchCell(ask, false, 0)).toMatchObject({ state: "waiting", caption: "ask" });const stalled = {id: 2,title: "Build",@@ -19,38 +19,72 @@ test("ask and stalled live turns both read as waiting", () => {turn: { ...emptyTurn(), status: "streaming" as const, connected: true, startedAt: 1000, lastUpdateAt: 4000 },}],};- expect(notchCell(stalled, false, 25000)).toMatchObject({ state: "waiting", label: expect.stringMatching(/^Working for /) });+ expect(notchCell(stalled, false, 25000)).toMatchObject({ state: "waiting", caption: "ask", label: expect.stringMatching(/^Working for /) });});-test("a running turn beats idle siblings and errors stay visible", () => {+test("idle chats leave the notch; live work and errors stay", () => {const chats = [- { id: 3, title: "Done", 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 } }] },+ { 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, 3]);- expect(notchSnapshot(chats, new Set(), 3).map((cell) => cell.state)).toEqual(["working", "error", "idle"]);+ 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, and untitled chats keep a stable name", () => {+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("the notch keeps at most six cells, live first", () => {+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: i === 7- ? [{ role: "assistant" as const, turn: { ...emptyTurn(), status: "thinking" as const, connected: true, startedAt: 1, lastUpdateAt: 1 } }]- : [],+ messages: [{ role: "assistant" as const, turn: { ...emptyTurn(), status: "thinking" as const, connected: true, startedAt: 1, lastUpdateAt: 1 } }],}));- const cells = notchSnapshot(chats, new Set(), 2);- expect(cells).toHaveLength(NOTCH_CELL_LIMIT);- expect(cells[0]).toMatchObject({ id: 8, state: "working" });+ 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", () => {diff --git a/apps/native/lib/notch-snapshot.ts b/apps/native/lib/notch-snapshot.tsindex 9337ea36..19a265c3 100644--- a/apps/native/lib/notch-snapshot.ts+++ b/apps/native/lib/notch-snapshot.ts@@ -2,21 +2,27 @@ 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 }>;+ 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 };@@ -27,16 +33,37 @@ function clip(text: string, limit: number): string {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,- state: busy ? "working" : "idle",- label: busy ? "Starting…" : "Idle",- detail: "",+ id: chat.id, title, caption: notchCaption(state, label, null), state, label, detail: "", kind: "session",};}const activity = turnActivity(last.turn, now, { snapshot: chat.snapshot });@@ -44,22 +71,76 @@ export function notchCell(chat: NotchChat, busy: boolean, now: number): NotchCelif (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(activity.detail, 120),+ detail: clip(detail, 120),+ kind: "session",};}-/** Open chats for the edge observer, live work first, at most six cells. */-export function notchSnapshot(chats: NotchChat[], busy: ReadonlySet<number>, now: number): NotchCell[] {- if (chats.length === 0) {- return [{ id: 0, title: "Codegraff", state: "idle", label: "Idle", detail: "" }];- }- return chats+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))- .sort((a, b) => RANK[a.state] - RANK[b.state] || a.id - b.id)- .slice(0, NOTCH_CELL_LIMIT);+ .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/examples/edge-worker/src/remote.ts b/examples/edge-worker/src/remote.tsindex 5faa01ba..d8ec93de 100644--- a/examples/edge-worker/src/remote.ts+++ b/examples/edge-worker/src/remote.ts@@ -10,7 +10,7 @@export const HARNESS_VERSION = "0.13";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemini-3-flash-preview" | "gemini-3.1-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3.5-flash" | "gemini-3.5-flash-lite" | "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash" | "gemma-4-26b-a4b-it" | "gemma-4-31b" | "gemma-4-31b-it" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5.3-flash" | "glm-5v-turbo" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-6-astra" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k3" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "muse-spark-1.2" | "muse-spark-1.2-contributor" | "openai/gpt-oss-120b" | (string & {});-export type ToolName = "shell" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen" | "rlm";+export type ToolName = "shell" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "agent_message" | "learn_candidate" | "peer_message" | "workspace" | "imagegen" | "rlm";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).@@ -522,4 +522,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemma-4-26b-a4b-it", "gemma-4-31b", "gemma-4-31b-it", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5.3-flash", "glm-5v-turbo", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-k2.7-code", "kimi-k3", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "muse-spark-1.2", "muse-spark-1.2-contributor", "openai/gpt-oss-120b"];-export const TOOLS: ToolName[] = ["shell", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "render_html", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen", "rlm"];+export const TOOLS: ToolName[] = ["shell", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "render_html", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "agent_message", "learn_candidate", "peer_message", "workspace", "imagegen", "rlm"];