graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Merge release lifecycle and navigation fixes into clipboard cleanup
justrach5c51a2963e14
diff --cc apps/native/app/api/acp/route.tsindex eeb97c9f,1ae25bdb..a3d7f925--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@@ -95,23 -94,28 +96,29 @@@ function defaultYolo(): booleanreturn true;}+ // A closed tab's agent gets stdin EOF first: `graff acp` leaves its read loop+ // on EOF and writes the session's exit save on the way out, which a SIGTERM+ // would skip. The signal is the fallback for an agent that does not wind down.+ const EXIT_GRACE_MS = 5_000;+function killSlot(chat: string): Promise<void> {const slot = slots.get(chat);- if (!slot) return Promise.resolve();+ if (!slot) return retirements.get(chat) ?? Promise.resolve();slots.delete(chat);- return closeSessionWriter(slot.child);- const pending = retireWorker(slot.child, EXIT_GRACE_MS, "eof");++ const pending = closeSessionWriter(slot.child, EXIT_GRACE_MS);+ retirements.set(chat, pending);+ const forget = () => { if (retirements.get(chat) === pending) retirements.delete(chat); };+ void pending.then(forget, forget);+ return pending;}- function killPage(page: string) {+ async function killPage(page: string) {const prefix = `${page}:`;- for (const chat of [...slots.keys()]) {- if (chat.startsWith(prefix)) void killSlot(chat).catch(() => undefined);- }+ await Promise.all([...new Set([...slots.keys(), ...retirements.keys()])].filter(chat => chat.startsWith(prefix)).map(killSlot));}function spawnAgent(chat: string, opts: SpawnOpts): Slot {+ if (opts.resume) assertSessionWritable(sessionFile(opts.cwd, opts.resume));- void killSlot(chat).catch(() => undefined);const args = ["acp"];if (opts.yolo) args.push("--yolo");if (opts.model) args.push("--model", opts.model);@@@ -149,9 -153,6 +156,9 @@@if (slots.get(chat) === slot && !slot.restart) slots.delete(chat);});slots.set(chat, slot);+ if (slot.resume) registerSessionWriter(sessionFile(slot.cwd, slot.resume), child, () => {- if (slots.get(chat) === slot) slots.delete(chat);++ if (slots.get(chat) === slot) void killSlot(chat).catch(() => undefined);+ });return slot;}@@@ -228,9 -235,6 +241,9 @@@ async function bootstrapNow(chat: strintry { await slot.restartReady; }finally { if (slots.get(chat) === slot) slots.delete(chat); }}, HANDSHAKE_MS);+ if (!slot.resume) registerSessionWriter(sessionFile(slot.cwd, slot.sessionId), slot.child, () => {- if (slots.get(chat) === slot) slots.delete(chat);++ if (slots.get(chat) === slot) void killSlot(chat).catch(() => undefined);+ });await drainCommands(slot);if (slots.get(chat) !== slot) throw new Error("ACP startup was disposed. Retry to start a new worker.");return slot;diff --cc apps/native/electron/attachment-lifetime-frontend.cjsindex e76c669a,00000000..55774b29mode 100644,000000..100644--- a/apps/native/electron/attachment-lifetime-frontend.cjs+++ b/apps/native/electron/attachment-lifetime-frontend.cjs@@@ -1,95 -1,0 +1,98 @@@+// Exercise the actual paste handler, upload route and ACP image staging.+const assert = require('node:assert/strict');+const fs = require('node:fs'), path = require('node:path');+const { nativeImage } = require('electron');+async function runAttachments({win,origin,temp,output,requests,workspace,send,click,until,report}) {+ const wc = win.webContents, js = code => wc.executeJavaScript(code);+ if(await js(`!!document.querySelector('[aria-label="Close browser"]')`))await click('[aria-label="Close browser"]');+ const directory = path.join(temp, 'graff-native-attachments');+ const pixels = Buffer.alloc(64*48*4);+ for(let i=0;i<pixels.length;i+=4) { pixels[i]=180;pixels[i+1]=120;pixels[i+2]=30;pixels[i+3]=255; }+ const png = nativeImage.createFromBitmap(pixels,{width:64,height:48}).toPNG().toString('base64');+ const paste = async name => {+ await click('textarea[aria-label="Prompt"]');+ await js(`(()=>{+ const bytes=Uint8Array.from(atob(${JSON.stringify(png)}),c=>c.charCodeAt(0));+ const data=new DataTransfer();data.items.add(new File([bytes],${JSON.stringify(name)},{type:'image/png'}));+ document.querySelector('textarea[aria-label="Prompt"]').dispatchEvent(new ClipboardEvent('paste',{clipboardData:data,bubbles:true,cancelable:true}));+ })()`);+ await until(()=>js(`!!document.querySelector(${JSON.stringify(`[aria-label="Preview ${name}"]`)})`),'uploaded paste '+name);+ const found=fs.readdirSync(directory).find(file=>file.endsWith('-'+name));+ assert.ok(found,'Paste must write a real owned file');return path.join(directory,found);+ };+ await send('/model lmstudio mock-vision');+ await until(()=>js(`document.body.textContent.includes('mock-vision') && !document.querySelector('article[aria-busy="true"]')`),'vision model selected');+ const aged=await paste('aged.png');+ const old=new Date(Date.now()-48*60*60*1000);fs.utimesSync(aged,old,old);+ const removed=await paste('remove.png');+ assert.ok(fs.existsSync(aged),'Another upload must preserve an aged active draft');+ await click('[aria-label="Preview aged.png"]');+ await until(()=>js(`!!document.querySelector('dialog img')?.complete`),'draft preview pixels');+ fs.writeFileSync(path.join(output,'attachment-aged-draft.png'),(await wc.capturePage()).toPNG());+ await click('[aria-label="Close image preview"]');+ await click('[aria-label="Remove remove.png"]');+ await until(()=>!fs.existsSync(removed),'discarded paste file cleanup');+ await send('Describe the pasted image in one sentence.');+ await until(()=>js(`document.body.textContent.includes('The pasted image was received.') && !document.querySelector('article[aria-busy="true"]')`),'real image turn completion',25000);+ const calls=JSON.parse(fs.readFileSync(requests,'utf8'));+ fs.writeFileSync(path.join(output,'attachment-requests.json'),JSON.stringify(calls,null,2));+ assert.ok(JSON.stringify(calls).includes(png),'Actual model requests must contain the pasted PNG bytes');+ const record=JSON.parse(fs.readFileSync(path.join(directory,'.ownership',path.basename(aged)+'.json'),'utf8'));+ assert.equal(record.retained,true,'ACP acceptance must retain replay pixels');+ await fetch(origin+'/api/attach',{method:'DELETE',headers:{'content-type':'application/json'},body:JSON.stringify({paths:[aged]})});+ assert.ok(fs.existsSync(aged),'Discard cannot delete pixels retained by an accepted message');+ assert.equal((await fetch(origin+'/api/attach?name='+encodeURIComponent(path.basename(aged)))).status,200);+ fs.writeFileSync(path.join(output,'attachment-sent-retained.png'),(await wc.capturePage()).toPNG());+ await click('[title="New chat (⌘T)"]');+ const focused=await js(`document.querySelector('[data-chat][data-focused="true"]').dataset.chat`);+ const closed=await paste('closed.png');+ await click(`[data-tab-members="${focused}"] [aria-label="Close tab"]`);+ await until(()=>!fs.existsSync(closed),'closed draft file cleanup');+ for (const name of ['sessions','traces']) {+ const source=path.join(workspace,'.graff',name);+ if(fs.existsSync(source))fs.cpSync(source,path.join(output,'attachment-'+name),{recursive:true});+ }+ const savedDirectory=path.join(workspace,'.graff','sessions');+ const savedName=fs.readdirSync(savedDirectory).find(name=>name.endsWith('.session.json') && fs.readFileSync(path.join(savedDirectory,name),'utf8').includes(path.basename(aged)));+ assert.ok(savedName,'Find the actual saved image conversation before deleting it');+ const savedFile=path.join(savedDirectory,savedName);+ const transcriptFile=savedFile.replace(/\.session\.json$/,'.transcript.jsonl');+ assert.ok(fs.existsSync(transcriptFile),'The real harness must have written its companion transcript');+ // Seed a rotated generation from the real transcript; rotation itself is covered by harness tests.+ const rotatedFile=savedFile.replace(/\.session\.json$/,'.transcript.1.jsonl');+ fs.copyFileSync(transcriptFile,rotatedFile);+ const archiveName='attachment-archive-check';+ fs.copyFileSync(savedFile,path.join(savedDirectory,archiveName+'.session.json'));+ fs.copyFileSync(transcriptFile,path.join(savedDirectory,archiveName+'.transcript.jsonl'));+ fs.copyFileSync(rotatedFile,path.join(savedDirectory,archiveName+'.transcript.1.jsonl'));+ const archiveResponse=await fetch(origin+'/api/sessions?'+new URLSearchParams({root:workspace,name:archiveName}),{method:'DELETE'});+ assert.equal(archiveResponse.status,200,'Archive the copied real checkpoint through the production route');+ assert.equal(fs.existsSync(path.join(savedDirectory,archiveName+'.transcript.jsonl')),false);+ assert.equal(fs.existsSync(path.join(savedDirectory,archiveName+'.transcript.1.jsonl')),false);+ const archivedRotated=path.join(savedDirectory,'archived',archiveName+'.transcript.1.jsonl');+ assert.ok(fs.readFileSync(archivedRotated,'utf8').includes(path.basename(aged)));+ const archivedTranscript=path.join(savedDirectory,'archived',archiveName+'.transcript.jsonl');+ assert.ok(fs.readFileSync(archivedTranscript,'utf8').includes(path.basename(aged)),'Archived replay must retain its image reference');+ assert.ok(fs.existsSync(path.join(savedDirectory,'archived',archiveName+'.session.json')));- await until(()=>js(`!!document.querySelector('#sidebar-chat-list button[data-row].bg-hover-2')`),'selected saved sidebar row');- await js(`document.querySelector('#sidebar-chat-list button[data-row].bg-hover-2').parentElement.querySelector('button[aria-label^="Actions for "]').setAttribute('data-audit-delete-menu','true')`);++ await click('[data-tab-id]:has(button[aria-pressed="true"]) [aria-label="Close tab"]');++ if(await js(`!!document.querySelector('[aria-label="Expand sidebar"]')?.checkVisibility()`))await click('[aria-label="Expand sidebar"]');++ else if(await js(`!!document.querySelector('[aria-label="Open navigation"]')?.checkVisibility()`))await click('[aria-label="Open navigation"]');++ await until(()=>js(`!!document.querySelector('#sidebar-chat-list button[data-row]')`),'closed image conversation in History');++ await js(`document.querySelector('#sidebar-chat-list button[data-row]').parentElement.querySelector('button[aria-label^="Actions for "]').setAttribute('data-audit-delete-menu','true')`);+ await click('[data-audit-delete-menu="true"]');+ await until(()=>js(`!!document.querySelector('button[aria-label^="Delete "]')`),'saved conversation delete action');+ await click('button[aria-label^="Delete "]');+ await until(()=>!fs.existsSync(savedFile),'session removed after its writer exits');+ assert.equal(fs.existsSync(transcriptFile),false,'Deleting a saved chat must also remove its full transcript');+ assert.equal(fs.existsSync(rotatedFile),false,'Deleting a saved chat must remove its rotated transcript');+ await new Promise(resolve=>setTimeout(resolve,250));+ assert.equal(fs.existsSync(savedFile),false,'An exiting chat worker must not recreate its deleted session');+ fs.writeFileSync(path.join(output,'attachment-session-deleted.png'),(await wc.capturePage()).toPNG());+ assert.ok(fs.existsSync(archivedTranscript),'Deleting the original chat must preserve its independent archive');+ assert.ok(fs.existsSync(archivedRotated),'Deleting the original must preserve the archived rotated transcript');+ assert.ok(fs.existsSync(aged),'An independent archived replay still needs the original image pixels');+ report.passed.push('real sidebar delete retires its writer and removes checkpoint plus both transcript generations; production archive preserves all replay files');+ report.passed.push('synthetic clipboard event through real GUI paste/upload/ACP: aged draft survives, removed and closed drafts release files, sent PNG reaches model and stays available for replay');+ fs.writeFileSync(path.join(output,'attachment-requests.json'),JSON.stringify(calls,null,2));+}+module.exports={runAttachments};diff --cc apps/native/electron/frontend-runtime.cjsindex e6d1f4ad,90a81f62..486f0b4f--- a/apps/native/electron/frontend-runtime.cjs+++ b/apps/native/electron/frontend-runtime.cjs@@@ -100,7 -112,7 +113,7 @@@ app.whenReady().then(async () =>const area = screen.getPrimaryDisplay().workArea;// Exercise the handoff with Browser open on a small desktop: the initial// project context can put the composer below the scroll viewport.- const size = (process.env.GRAFF_NARROW_NAV_TEST || process.env.GRAFF_FRONTEND_NARROW) ? { width: 1004, height: 657 } : process.env.GRAFF_CLI_TEST || process.env.GRAFF_SPLIT_STRESS ? { width: 1024, height: 664 } : { width: 1320, height: 900 };- const size = process.env.GRAFF_NARROW_NAV_TEST || process.env.GRAFF_SMALL_DESKTOP_TEST ? { width: 1004, height: 657 } : process.env.GRAFF_CLI_TEST || process.env.GRAFF_SPLIT_STRESS ? { width: 1024, height: 664 } : { width: 1320, height: 900 };++ const size = process.env.GRAFF_NARROW_NAV_TEST || process.env.GRAFF_SMALL_DESKTOP_TEST || process.env.GRAFF_FRONTEND_NARROW ? { width: 1004, height: 657 } : process.env.GRAFF_CLI_TEST || process.env.GRAFF_SPLIT_STRESS ? { width: 1024, height: 664 } : { width: 1320, height: 900 };const bounds = desktop.foreground ? { x: area.x+10, y: area.y+10, width: Math.min(size.width, area.width-20), height: Math.min(size.height, area.height-20) } : size;win = desktop.createWindow({ ...bounds, webPreferences: {preload: path.join(__dirname, 'preload.cjs'), sandbox: true, contextIsolation: true, backgroundThrottling: false,diff --cc apps/native/lib/session-writers.tsindex fd3662c4,00000000..6045ebeamode 100644,000000..100644--- a/apps/native/lib/session-writers.ts+++ b/apps/native/lib/session-writers.ts@@@ -1,77 -1,0 +1,62 @@@+import type { ChildProcess } from "node:child_process";++import { retireWorker } from "./acp-retire";+import { realpathSync } from "node:fs";+import path from "node:path";++type Writer = { child: ChildProcess; detach: () => void };+type Registry = { writers: Map<string, Set<Writer>>; mutations: Set<string>; closing: WeakMap<ChildProcess, Promise<void>> };+const globalRegistry = globalThis as typeof globalThis & { __graffSessionWriters?: Registry };+const registry = globalRegistry.__graffSessionWriters ??= {+ writers: new Map(), mutations: new Set(), closing: new WeakMap(),+};++function key(file: string): string {+ try { return path.join(realpathSync(path.dirname(file)), path.basename(file)); }+ catch { return path.resolve(file); }+}+export function sessionFile(cwd: string, name: string): string {+ // Resolve cwd before adding the not-yet-created sessions directory.+ let root = cwd;+ try { root = realpathSync(cwd); } catch {}+ return path.join(root, ".graff", "sessions", `${name}.session.json`);+}+export function assertSessionWritable(file: string): void {+ if (registry.mutations.has(key(file))) throw new Error("This saved session is being removed; retry after it finishes");+}++/** Track closing writers until actual exit, not merely until their tab closes. */+export function registerSessionWriter(file: string, child: ChildProcess, detach: () => void): void {+ assertSessionWritable(file);+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;+ const name = key(file), entry = { child, detach };+ const set = registry.writers.get(name) ?? new Set<Writer>();+ set.add(entry); registry.writers.set(name, set);+ child.once("exit", () => {+ set.delete(entry);+ if (!set.size && registry.writers.get(name) === set) registry.writers.delete(name);+ });+}++/** EOF allows the final save; escalation is only for a worker that won't exit. */+export function closeSessionWriter(child: ChildProcess, graceMs = 5000): Promise<void> {+ const pending = registry.closing.get(child);+ if (pending) return pending;+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) return Promise.resolve();- const promise = new Promise<void>((resolve, reject) => {- let killTimer: ReturnType<typeof setTimeout> | undefined;- const cleanup = () => {- clearTimeout(termTimer); clearTimeout(killTimer);- child.off("exit", exited); child.off("error", failed);- };- const exited = () => { cleanup(); resolve(); };- const failed = (error: Error) => { cleanup(); reject(error); };- const termTimer = setTimeout(() => {- child.kill("SIGTERM");- killTimer = setTimeout(() => child.kill("SIGKILL"), 1000);- killTimer.unref();- }, graceMs);- termTimer.unref();- child.once("exit", exited); child.once("error", failed);- try { child.stdin?.end(); } catch { /* Exit remains the completion signal. */ }- });++ const promise = retireWorker(child, graceMs, "eof");+ registry.closing.set(child, promise);+ return promise;+}++/** Hold the mutation gate until the file operation completes. A new writer+ * cannot slip in between the old writer's final save and deletion/archive. */+export async function withSessionWritersStopped<T>(file: string, mutate: () => T | Promise<T>): Promise<T> {+ const name = key(file);+ assertSessionWritable(file);+ registry.mutations.add(name);+ try {+ const writers = [...(registry.writers.get(name) ?? [])];+ for (const writer of writers) writer.detach();+ await Promise.all(writers.map(({ child }) => closeSessionWriter(child)));+ return await mutate();+ } finally { registry.mutations.delete(name); }+}diff --cc apps/native/package.jsonindex e403ed22,dc69d5a2..562ecba0--- a/apps/native/package.json+++ b/apps/native/package.json@@@ -48,8 -49,9 +49,10 @@@"test:cli": "GRAFF_CLI_TEST=1 bun scripts/test-frontend.mjs","install:cli": "bun scripts/install-cli.mjs","test:packaged-html": "bun scripts/test-packaged-html.mjs",+ "test:workspace-history": "GRAFF_WORKSPACE_HISTORY_TEST=1 bun scripts/test-frontend.mjs","test:narrow-navigation": "GRAFF_NARROW_NAV_TEST=1 bun scripts/test-frontend.mjs",- "test:packaged-titles": "bun scripts/test-packaged-titles.mjs"++ "test:packaged-titles": "bun scripts/test-packaged-titles.mjs",+ "test:clipboard-narrow": "GRAFF_FRONTEND_NARROW=1 bun scripts/test-frontend.mjs"},"dependencies": {"@streamdown/code": "^1.1.1",diff --cc docs/adr/README.mdindex 89b51d46,f5ae19d9..b967028c--- a/docs/adr/README.md+++ b/docs/adr/README.md@@@ -126,7 -126,21 +126,22 @@@ record only when you need the evidence| [0113](0113-clipboard-errors-need-evidence.md) | Direct AppKit clipboard failures need typed evidence; generic helper failures never imply Automation permission. || [0114](0114-live-citations-are-terminal-presentation.md) | Live terminal citations use per-stream display filters with independent reasoning state; structured JSON/ACP output stays unchanged. || [0116](0116-informational-turns-have-bounded-scope.md) | Summary turns gather bounded evidence; coding completion requirements apply to requested changes. |+| [0117](0117-clipboard-files-follow-consumer-ownership.md) | Clipboard cleanup requires file ownership and released consumers; age alone never deletes active or saved attachments. |+ | [0118](0118-file-edits-check-target-worktree.md) | File edits checkpoint the target Git worktree; unresolved paths retain the caller checkpoint. |+ | [0119](0119-computer-tools-receive-caller-context.md) | Computer-use MCP requests receive opaque caller-owned session and turn context. |+ | [0120](0120-draft-publication-does-not-complete-verification.md) | Draft PRs cannot satisfy verified completion; only a user control scoped to this conversation and goal permits an unverified draft handoff. |+ | [0121](0121-claims-include-repository-identity.md) | Claims include repository identity; literal PR mutations compare the observed repository, PR number and branch, while unknown scopes stay conservative. |++ | [0122](0122-one-session-navigation-surface.md) | Open chats use the expanded sidebar or collapsed top tabs, preserving drafts and groups; focused mode keeps a compact composer and accessible settings. |++ | [0123](0123-pr-check-observations-retain-the-rollup.md) | PR completion retains named current-head check observations locally; diagnostic receipts never replace fresh verification. |++ | [0124](0124-review-checkpoints-preserve-unfinished-scope.md) | Explicit reviews request a findings checkpoint every twenty calls without forcing completion or changing authority. |++ | [0125](0125-review-deadlines-belong-to-one-turn.md) | Opt-in review deadlines use joined turn-owned watchers, preserve user cancellation, and cannot validate late results. |++ | [0126](0126-publication-retains-observed-check-failures.md) | Observed failed checks survive resumes; non-draft publication waits for successful reruns and occupies its own tool batch. |+## When to write one