graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Track resumed workspace image consumers
justrach0d4761e5f62a
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex 405d5d45..68b0c507 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -119,6 +119,8 @@ async function killPage(page: string) {function spawnAgent(chat: string, opts: SpawnOpts): Slot {if (opts.resume) assertSessionWritable(sessionFile(opts.cwd, opts.resume));+ const imageScope = path.dirname(sessionFile(opts.cwd, opts.resume ?? "pending"));+ attachmentStore().enrollSession(imageScope, process.pid);const args = ["acp"];if (opts.yolo) args.push("--yolo");if (opts.model) args.push("--model", opts.model);@@ -156,6 +158,8 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {if (slots.get(chat) === slot && !slot.restart) slots.delete(chat);});slots.set(chat, slot);+ try { attachmentStore().enrollSession(imageScope, child.pid); }+ catch (error) { void killSlot(chat).catch(() => undefined); throw error; }if (slot.resume) registerSessionWriter(sessionFile(slot.cwd, slot.resume), child, () => {if (slots.get(chat) === slot) void killSlot(chat).catch(() => undefined);});diff --git a/apps/native/electron/attachment-lifetime-frontend.cjs b/apps/native/electron/attachment-lifetime-frontend.cjsindex 2fb4ec94..6e639ed6 100644--- a/apps/native/electron/attachment-lifetime-frontend.cjs+++ b/apps/native/electron/attachment-lifetime-frontend.cjs@@ -5,6 +5,10 @@ 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"]');+ if(await js(`!!document.querySelector('[aria-label="Collapse sidebar"]')?.checkVisibility()`)) {+ await click('[aria-label="Collapse sidebar"]');+ await until(()=>js(`!!document.querySelector('[data-session-navigation="tabs"]')`),'attachment tab navigation');+ }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; }@@ -80,6 +84,26 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,clfs.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 scopeKey=require('node:crypto').createHash('sha256').update(path.join(fs.realpathSync(workspace),'.graff','sessions')).digest('hex');+ const scopeConsumers=path.join(directory,'.ownership','session-consumers',scopeKey);+ const readConsumers=()=>fs.readdirSync(scopeConsumers).map(name=>JSON.parse(fs.readFileSync(path.join(scopeConsumers,name),'utf8')).pid);+ const beforeResume=new Set(readConsumers());+ const resumeChat='attachment-resume-audit';+ try {+ const resumed=await fetch(origin+'/api/acp',{method:'POST',headers:{'content-type':'application/json'},+ body:JSON.stringify({method:'bootstrap',chat:resumeChat,params:{cwd:workspace,resume:archiveName,mcp:false}})});+ assert.equal(resumed.status,200,'Resume an actual saved image session without submitting a new prompt');+ const added=readConsumers().filter(pid=>!beforeResume.has(pid));+ assert.equal(added.length,1,'Resumed worker must enroll even without a new image prompt');+ process.kill(added[0],0);+ const disposed=await fetch(origin+'/api/acp',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({method:'dispose',chat:resumeChat})});+ assert.equal(disposed.status,200);+ await until(()=>{try{process.kill(added[0],0);return false;}catch(error){return error.code==='ESRCH';}},'resumed image worker exited');+ process.kill(consumers[0],0); // Closing the resumed copy must not close the original consumer.+ fs.writeFileSync(path.join(output,'attachment-resume-consumers.json'),JSON.stringify({resumedWorker:added[0],registeredWithoutPrompt:true,exitedOnDispose:true,originalStillAlive:true},null,2));+ } finally {+ await fetch(origin+'/api/acp',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({method:'dispose',chat:resumeChat})});+ }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);@@ -110,6 +134,7 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,classert.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('edited clipboard export remains on disk after its draft chip is removed');+ report.passed.push('resumed saved-image worker enrolls before any new prompt; disposing it preserves the original worker');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/attachment-consumers.test.ts b/apps/native/lib/attachment-consumers.test.tsindex 1f7998c5..b4e0a4fb 100644--- a/apps/native/lib/attachment-consumers.test.ts+++ b/apps/native/lib/attachment-consumers.test.ts@@ -57,3 +57,32 @@ test("unknown, malformed and unenrolled consumers never prove inactivity", () =>expect(attachmentConsumers(root, 12345, () => false)).toBe("unknown");} finally { rmSync(root, { recursive: true, force: true }); }});++test("a resumed workspace worker protects old images without a new image prompt", async () => {+ const root=mkdtempSync(path.join(os.tmpdir(),"graff-resumed-image-consumers-"));+ const child=spawn(process.execPath,["-e","setInterval(() => {}, 1000)"]);+ const exited=once(child,"exit");+ const alive=(pid:number)=>{+ if(pid===2147483647)return false;+ try{process.kill(pid,0);return true;}catch(error){return (error as NodeJS.ErrnoException).code!=="ESRCH";}+ };+ const store=new AttachmentStore(root,2147483647,alive);+ try {+ await once(child,"spawn");+ const scope=path.join(root,"sessions");mkdirSync(scope);+ const image=store.create("old.png",new Uint8Array([1]));+ store.retainPrompt({prompt:[{type:"text",text:`@[${image}]`}]},scope,2147483647);+ expect(store.consumers(image)).toBe("inactive");+ store.enrollSession(scope,child.pid); // Resume loads history, not a new pasted-image turn.+ const restarted=new AttachmentStore(root,2147483647,alive);+ try {+ expect(restarted.references(image)).toBe("absent");+ expect(restarted.consumers(image)).toBe("active");+ child.kill();await exited;+ expect(restarted.consumers(image)).toBe("inactive");+ } finally {restarted.close();}+ } finally {+ if(child.exitCode===null && child.signalCode===null)child.kill();+ await exited;store.close();rmSync(root,{recursive:true,force:true});+ }+});diff --git a/apps/native/lib/attachment-store.ts b/apps/native/lib/attachment-store.tsindex 80f371b6..0738a8fb 100644--- a/apps/native/lib/attachment-store.ts+++ b/apps/native/lib/attachment-store.ts@@ -68,6 +68,27 @@ export class AttachmentStore {try { writeFileSync(path.join(root, key + ".json"), JSON.stringify({ directory: scope }), { flag: "wx", mode: 0o600 }); }catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }}+ /** Register before spawn as well as after it: resume can load an old image+ * without a new prompt containing its path. Scope leases overapproximate use. */+ enrollSession(directory: string, pid?: number) {+ if (!path.isAbsolute(directory)) throw new Error("Attachment session scope must be absolute");+ const key = createHash("sha256").update(path.resolve(directory)).digest("hex");+ enrollAttachmentConsumer(path.join(this.records, "session-consumers", key), pid);+ }+ private scopes(name: string): string[] | null {+ const root = path.join(this.records, "references", name), names = readdirSync(root);+ if (!names.length || names.length > 64 || names.includes("unknown.json")) return null;+ const scopes: string[] = [];+ for (const name of names) {+ const file = path.join(root, name), stat = lstatSync(file);+ if (!stat.isFile() || stat.size > 16 * 1024) return null;+ const { directory } = JSON.parse(readFileSync(file, "utf8"));+ if (typeof directory !== "string" || !path.isAbsolute(directory) ||+ name !== createHash("sha256").update(directory).digest("hex") + ".json") return null;+ scopes.push(directory);+ }+ return scopes;+ }/** Read-only evidence within enrolled scopes; not authorization to delete.* A future collector must also exclude every active consumer. */references(target: string): ReferenceState {@@ -75,26 +96,28 @@ export class AttachmentStore {const record = this.read(path.basename(target));if (!record?.retained || record.referenceVersion !== 1) return "unknown";try {- const root = path.join(this.records, "references", record.name);- const names = readdirSync(root);- if (!names.length || names.length > 64 || names.includes("unknown.json")) return "unknown";- const scopes: string[] = [];- for (const name of names) {- const file = path.join(root, name), stat = lstatSync(file);- if (!stat.isFile() || stat.size > 16 * 1024) return "unknown";- const { directory } = JSON.parse(readFileSync(file, "utf8"));- if (typeof directory !== "string" || !path.isAbsolute(directory) ||- name !== createHash("sha256").update(directory).digest("hex") + ".json") return "unknown";- scopes.push(directory);- }- return attachmentReferences(scopes, target);+ const scopes = this.scopes(record.name);+ return scopes ? attachmentReferences(scopes, target) : "unknown";} catch { return "unknown"; }}consumers(target: string): ConsumerState {if (path.dirname(target) !== this.directory) return "unknown";const record = this.read(path.basename(target));if (!record?.retained || record.consumerVersion !== 1) return "unknown";- return attachmentConsumers(path.join(this.records, "consumers", record.name), record.owner, this.alive);+ const direct = attachmentConsumers(path.join(this.records, "consumers", record.name), record.owner, this.alive);+ if (direct === "active") return direct;+ try {+ const scopes = this.scopes(record.name);+ if (!scopes) return "unknown";+ let unknown = direct === "unknown";+ for (const scope of scopes) {+ const key = createHash("sha256").update(path.resolve(scope)).digest("hex");+ const state = attachmentConsumers(path.join(this.records, "session-consumers", key), record.owner, this.alive);+ if (state === "active") return state;+ if (state === "unknown") unknown = true;+ }+ return unknown ? "unknown" : "inactive";+ } catch { return "unknown"; }}retainPrompt(params: unknown, sessionDirectory?: string, workerPid?: number) {const prompt = (params as { prompt?: unknown } | undefined)?.prompt;@@ -105,6 +128,7 @@ export class AttachmentStore {if (path.dirname(match[1]) !== this.directory) continue;const record = this.read(path.basename(match[1]));if (record) {+ if (sessionDirectory) this.enrollSession(sessionDirectory, workerPid);enrollAttachmentConsumer(path.join(this.records, "consumers", record.name), workerPid);this.enroll(record.name, sessionDirectory);if (!record.retained) this.save({ ...record, retained: true });diff --git a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md b/docs/adr/0117-clipboard-files-follow-consumer-ownership.mdindex af5ae057..d0815a2e 100644--- a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md+++ b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md@@ -56,6 +56,13 @@ identifiers preserve files. Older exports cannot gain complete consumer knowledgretroactively. This process inventory still requires cross-surface enrollmentand collection serialization before it can authorize submitted-file cleanup.+Native worker startup enrolls its canonical session-directory scope, including+resumes that load image history without submitting a new attachment. The backend+registers before spawn and the worker registers before bootstrap completes.+Every scoped live process conservatively protects that workspace's retained+images; unknown or absent scope records cannot prove inactivity. This may retain+extra images while another chat in the same workspace is open.+The legacy desktop keeps clipboard exports in a private owner directory withan operating-system file lease. Recovery takes a nonblocking exclusive leasebefore removing recorded unsent exports from a stopped owner. Its prompt