graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Wait for session writers before deleting saved chats
justrache6a328ea49ea
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex 4b17e299..6983025d 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -1,3 +1,4 @@+import { assertSessionWritable, closeSessionWriter, registerSessionWriter, sessionFile } from "@/lib/session-writers";import { spawn, type ChildProcessByStdio } from "node:child_process";import { existsSync, mkdirSync, writeFileSync } from "node:fs";import os from "node:os";@@ -93,40 +94,23 @@ function defaultYolo(): boolean {return 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) {+function killSlot(chat: string): Promise<void> {const slot = slots.get(chat);- if (!slot) return;+ if (!slot) return Promise.resolve();slots.delete(chat);- try {- slot.child.stdin.end();- } catch {- // already closed- }- const timer = setTimeout(() => {- try {- slot.child.kill("SIGTERM");- } catch {- // already gone- }- }, EXIT_GRACE_MS);- timer.unref();- slot.child.once("exit", () => clearTimeout(timer));+ return closeSessionWriter(slot.child);}function killPage(page: string) {const prefix = `${page}:`;for (const chat of [...slots.keys()]) {- if (chat.startsWith(prefix)) killSlot(chat);+ if (chat.startsWith(prefix)) void killSlot(chat).catch(() => undefined);}}function spawnAgent(chat: string, opts: SpawnOpts): Slot {- killSlot(chat);+ 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);@@ -164,6 +148,9 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {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);+ });return slot;}@@ -230,6 +217,9 @@ async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {try { 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);+ });await drainCommands(slot);return slot;}@@ -265,7 +255,7 @@ export async function POST(req: NextRequest) {const model = typeof body.params?.model === "string" ? body.params.model : undefined;try {if (method === "dispose") {- killSlot(chat);+ await killSlot(chat);return Response.json({ ok: true });}if (method === "dispose-page") {diff --git a/apps/native/app/api/sessions/route.ts b/apps/native/app/api/sessions/route.tsindex a272e03d..1fbfeb84 100644--- a/apps/native/app/api/sessions/route.ts+++ b/apps/native/app/api/sessions/route.ts@@ -1,3 +1,4 @@+import { withSessionWritersStopped } from "@/lib/session-writers";import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync } from "node:fs";import path from "node:path";import { NextRequest } from "next/server";@@ -117,17 +118,19 @@ export async function DELETE(req: NextRequest) {if (!found) return Response.json({ error: "no such session" }, { status: 404 });const archive = req.nextUrl.searchParams.get("archive") !== "0";try {- if (!archive) {- unlinkSync(found.file);- return Response.json({ ok: true, name, archived: false });- }- const target = path.join(path.dirname(found.file), ARCHIVE_SUBDIR);- mkdirSync(target, { recursive: true });- let dest = path.join(target, `${name}${SESSION_EXT}`);- // Never overwrite an earlier archive of the same name.- if (existsSync(dest)) dest = path.join(target, `${name}.${Date.now()}${SESSION_EXT}`);- renameSync(found.file, dest);- return Response.json({ ok: true, name, archived: true });+ return await withSessionWritersStopped(found.file, () => {+ if (!archive) {+ unlinkSync(found.file);+ return Response.json({ ok: true, name, archived: false });+ }+ const target = path.join(path.dirname(found.file), ARCHIVE_SUBDIR);+ mkdirSync(target, { recursive: true });+ let dest = path.join(target, `${name}${SESSION_EXT}`);+ // Never overwrite an earlier archive of the same name.+ if (existsSync(dest)) dest = path.join(target, `${name}.${Date.now()}${SESSION_EXT}`);+ renameSync(found.file, dest);+ return Response.json({ ok: true, name, archived: true });+ });} catch (err) {return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 502 });}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 11649ce9..78e54f4d 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -352,8 +352,8 @@ export default function GraffHarness() {* and the row goes at once rather than after the next poll. */const dropStored = (name: string, archive: boolean) => {const cwd = activePathRef.current ?? undefined;- const open = chatsRef.current.find((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));- if (open) closeChat(open.id);+ const open = chatsRef.current.filter((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));+ if (open.length) closeChats(open.map(chat => chat.id));setStored((current) => current.filter((s) => s.name !== name));void removeSession(name, { root: cwd, archive }).catch(() => undefined)diff --git a/apps/native/electron/attachment-lifetime-frontend.cjs b/apps/native/electron/attachment-lifetime-frontend.cjsindex be4b0b65..ff4afd99 100644--- a/apps/native/electron/attachment-lifetime-frontend.cjs+++ b/apps/native/electron/attachment-lifetime-frontend.cjs@@ -52,6 +52,20 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,clconst 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);+ 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-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');+ 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());+ report.passed.push('real sidebar delete retires the saved conversation writer before removing its session file');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));}diff --git a/apps/native/lib/session-writers.test.ts b/apps/native/lib/session-writers.test.tsnew file mode 100644index 00000000..405a7564--- /dev/null+++ b/apps/native/lib/session-writers.test.ts@@ -0,0 +1,88 @@+import { test, expect } from "bun:test";+import { spawn } from "node:child_process";+import { once } from "node:events";+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, existsSync, renameSync, rmSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { assertSessionWritable, closeSessionWriter, registerSessionWriter, sessionFile, withSessionWritersStopped } from "./session-writers";++async function fixture() {+ const root = mkdtempSync(path.join(os.tmpdir(), "session-writers-"));+ const file = sessionFile(root, "saved");+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, "initial");+ const child = spawn(process.execPath, ["-e", `+ const fs = require('node:fs');+ process.stdin.resume();+ process.stdin.on('end', () => setTimeout(() => {+ fs.writeFileSync(process.argv[1], 'final save'); process.exit(0);+ }, 100));+ console.log('ready');+ `, file], { stdio: ["pipe", "pipe", "inherit"] });+ await once(child.stdout!, "data");+ return { root, file, child, async dispose() {+ if (child.exitCode === null && child.signalCode === null) {+ const exited = once(child, "exit"); child.kill("SIGKILL"); await exited;+ }+ rmSync(root, { recursive: true, force: true });+ } };+}++test("deletion waits for a closing tab's final save instead of resurrecting its session", async () => {+ const f = await fixture();+ try {+ let detached = false;+ registerSessionWriter(f.file, f.child, () => { detached = true; });+ const closing = closeSessionWriter(f.child);+ await withSessionWritersStopped(f.file, () => {+ expect(f.child.exitCode).toBe(0);+ expect(readFileSync(f.file, "utf8")).toBe("final save");+ unlinkSync(f.file);+ });+ await closing;+ expect(detached).toBe(true);+ expect(existsSync(f.file)).toBe(false);+ } finally { await f.dispose(); }+});++test("archive includes the final save and prevents new writers until mutation completes", async () => {+ const f = await fixture();+ try {+ registerSessionWriter(f.file, f.child, () => {});+ const archive = path.join(f.root, "archived.session.json");+ await withSessionWritersStopped(f.file, async () => {+ expect(() => assertSessionWritable(f.file)).toThrow("being removed");+ await expect(withSessionWritersStopped(f.file, () => {})).rejects.toThrow("being removed");+ renameSync(f.file, archive);+ await Promise.resolve();+ expect(() => assertSessionWritable(f.file)).toThrow("being removed");+ });+ expect(() => assertSessionWritable(f.file)).not.toThrow();+ expect(readFileSync(archive, "utf8")).toBe("final save");+ expect(existsSync(f.file)).toBe(false);+ } finally { await f.dispose(); }+});++test("deleting one saved session retires all its writers and leaves unrelated sessions running", async () => {+ const first = await fixture(), second = await fixture(), unrelated = await fixture();+ try {+ registerSessionWriter(first.file, first.child, () => {});+ registerSessionWriter(first.file, second.child, () => {});+ registerSessionWriter(unrelated.file, unrelated.child, () => {});+ await withSessionWritersStopped(first.file, () => unlinkSync(first.file));+ expect(first.child.exitCode).toBe(0);+ expect(second.child.exitCode).toBe(0);+ expect(unrelated.child.exitCode).toBeNull();+ expect(readFileSync(unrelated.file, "utf8")).toBe("initial");+ } finally { await first.dispose(); await second.dispose(); await unrelated.dispose(); }+});++test("a failed mutation releases the gate without claiming file removal", async () => {+ const f = await fixture();+ try {+ registerSessionWriter(f.file, f.child, () => {});+ await expect(withSessionWritersStopped(f.file, () => { throw new Error("write denied"); })).rejects.toThrow("write denied");+ expect(existsSync(f.file)).toBe(true);+ expect(() => assertSessionWritable(f.file)).not.toThrow();+ } finally { await f.dispose(); }+});diff --git a/apps/native/lib/session-writers.ts b/apps/native/lib/session-writers.tsnew file mode 100644index 00000000..fd3662c4--- /dev/null+++ b/apps/native/lib/session-writers.ts@@ -0,0 +1,77 @@+import type { ChildProcess } from "node:child_process";+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. */ }+ });+ 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 --git a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md b/docs/adr/0117-clipboard-files-follow-consumer-ownership.mdindex e610b8cf..10b8e8a1 100644--- a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md+++ b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md@@ -32,6 +32,12 @@ a chip releases it only after other draft trays stop referencing it; uploadsthat finish after their composer is disposed are discarded. Cleanup requires adurable file identity, and remains conservative on platforms without one.+Saved-session deletion or archiving waits for every registered writer to exit,+including writers already closing after tab disposal. EOF gives the worker its+final save; a mutation gate prevents replacement writers until the file operation+finishes. Otherwise exit autosave can recreate a deleted reference and invalidate+the evidence used to decide that an attachment has no remaining consumers.+## ConsequencesConservative retention can keep files when their last consumer cannot be proved