Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Keep ACP session enrollment on the requested workspace

Cursor Agent7cd182a84121
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index d1600d6b..c6f71321 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -15,7 +15,7 @@ import { attachmentStore } from "@/lib/attachment-store";
import { retireWorker } from "@/lib/acp-retire";
import { rememberAnswer, validateAnswer } from "@/lib/ask-answer";
import { formatTermination, recordTermination, type TerminateReason } from "@/lib/acp-terminate";
-import { initializeWorker, serializeBootstrap } from "@/lib/acp-bootstrap";
+import { bindSessionCwd, initializeWorker, serializeBootstrap } from "@/lib/acp-bootstrap";
import { finishCancelledPrompt } from "@/lib/acp-cancel";
import { armIdle, cancelIdle, forgetPark, forgetParkMatching, keepPark, parkedChats, takeParked, type ParkedWorker } from "@/lib/acp-idle";
@@ -170,7 +170,9 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {
const child = spawn(graffBin(), args, {
stdio: ["pipe", "pipe", "inherit"],
cwd: opts.cwd,
- env: { ...env, GRAFF_DESKTOP_CHAT: chat, ...(!opts.mcp ? { GRAFF_MCP_CONFIG: mcpOffPath() } : {}) },
+ // Inherited PWD is the Next host (apps/native). Graff's display cwd
+ // falls back to PWD when Io realPath misses; pin it to the spawn root.
+ env: { ...env, GRAFF_DESKTOP_CHAT: chat, GRAFF_CWD: opts.cwd, PWD: opts.cwd, ...(!opts.mcp ? { GRAFF_MCP_CONFIG: mcpOffPath() } : {}) },
});
const slot: Slot = {
child,
@@ -288,7 +290,8 @@ async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {
finally { if (slots.get(chat) === slot) slots.delete(chat); }
}, HANDSHAKE_MS);
slot.sessionId = created.sessionId;
- if (created.cwd) slot.cwd = created.cwd;
+ slot.cwd = bindSessionCwd(slot.cwd, created.cwd);
+ attachmentStore().enrollSession(path.dirname(sessionFile(slot.cwd, slot.resume ?? slot.sessionId)), slot.child.pid);
if (!slot.resume) registerSessionWriter(sessionFile(slot.cwd, slot.sessionId), slot.child, () => {
if (slots.get(chat) === slot) void killSlot(chat, undefined, "session-writer").catch(() => undefined);
});
diff --git a/apps/native/lib/acp-bootstrap.test.ts b/apps/native/lib/acp-bootstrap.test.ts
index 1d290177..67817647 100644
--- a/apps/native/lib/acp-bootstrap.test.ts
+++ b/apps/native/lib/acp-bootstrap.test.ts
@@ -2,7 +2,7 @@ import { test, expect } from "bun:test";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { AcpTransport } from "./acp-transport";
-import { initializeWorker, serializeBootstrap } from "./acp-bootstrap";
+import { bindSessionCwd, initializeWorker, serializeBootstrap } from "./acp-bootstrap";
import { retireWorker } from "./acp-retire";
async function worker(mode: string) {
@@ -45,6 +45,19 @@ for (const mode of ["initialize", "session/new", "invalid"]) {
}
+test("bindSessionCwd keeps the spawn workspace when session/new reports the host cwd", () => {
+ const workspace = "/private/tmp/graff-frontend/workspace";
+ const host = "/Users/runner/work/codegraff/codegraff/apps/native";
+ expect(bindSessionCwd(workspace, ".", host)).toBe(workspace);
+ expect(bindSessionCwd(workspace, "", host)).toBe(workspace);
+ expect(bindSessionCwd(workspace, undefined, host)).toBe(workspace);
+ expect(bindSessionCwd(workspace, host, host)).toBe(workspace);
+ expect(bindSessionCwd(workspace, workspace, host)).toBe(workspace);
+ expect(bindSessionCwd(workspace, "/repo/.graff/worktrees/session-1", host))
+ .toBe("/repo/.graff/worktrees/session-1");
+ expect(bindSessionCwd(host, host, host)).toBe(host);
+});
+
test("session/new checkout binds the worker to its isolated worktree", async () => {
const isolated = await worker("isolated");
try {
diff --git a/apps/native/lib/acp-bootstrap.ts b/apps/native/lib/acp-bootstrap.ts
index 49687ab1..1dbecb22 100644
--- a/apps/native/lib/acp-bootstrap.ts
+++ b/apps/native/lib/acp-bootstrap.ts
@@ -1,5 +1,22 @@
+import path from "node:path";
import type { AcpTransport } from "./acp-transport";
+/** Keep the spawn workspace unless session/new named a real absolute checkout
+ * that is not the host process cwd. A relative "." (g_cwd_display default) or
+ * inherited PWD from `next start` in apps/native would otherwise enroll
+ * `apps/native/.graff/sessions` instead of the fixture workspace. Isolated
+ * worktrees stay adopted. */
+export function bindSessionCwd(requested: string, reported?: string, hostCwd = process.cwd()): string {
+ if (!reported) return requested;
+ const checkout = reported.trim();
+ if (!checkout || !path.isAbsolute(checkout)) return requested;
+ const resolved = path.resolve(checkout);
+ const spawned = path.resolve(requested);
+ const host = path.resolve(hostCwd);
+ if (resolved === host && resolved !== spawned) return requested;
+ return resolved;
+}
+
/** A failed handshake cannot recover from a late reply. Retire its worker
* before reporting failure so a retry starts with a fresh transport. */
export async function initializeWorker(
diff --git a/apps/native/lib/acp-route.test.ts b/apps/native/lib/acp-route.test.ts
index 0d7f5e30..5889686b 100644
--- a/apps/native/lib/acp-route.test.ts
+++ b/apps/native/lib/acp-route.test.ts
@@ -1,5 +1,5 @@
import { test, expect } from "bun:test";
-import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
+import { mkdtempSync, writeFileSync, readFileSync, rmSync, readdirSync, realpathSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { NextRequest } from "next/server";
@@ -366,3 +366,60 @@ require('node:readline').createInterface({input:process.stdin}).on('line',line=>
rmSync(temp, { recursive: true, force: true });
}
}, 15000);
+
+test("ACP enrolls the requested workspace when session/new reports the host cwd", async () => {
+ const temp = mkdtempSync(path.join(os.tmpdir(), "graff-acp-enroll-"));
+ const isolated = path.join(temp, ".graff", "worktrees", "session-1");
+ const binary = path.join(temp, "agent.cjs");
+ const host = process.cwd();
+ const oldBin = process.env.GRAFF_BIN;
+ writeFileSync(binary, `#!/usr/bin/env node
+const fs = require('node:fs');
+fs.writeFileSync('spawn.env', JSON.stringify({ cwd: process.cwd(), pwd: process.env.PWD, graffCwd: process.env.GRAFF_CWD }));
+const send = value => console.log(JSON.stringify(value));
+require('node:readline').createInterface({input:process.stdin}).on('line', line => {
+ const req = JSON.parse(line);
+ if (req.method === 'initialize') send({id:req.id,result:{}});
+ if (req.method === 'session/new') {
+ const checkout = process.env.GRAFF_REPORT_CWD || ${JSON.stringify(host)};
+ send({id:req.id,result:{sessionId:'enroll',cwd:checkout}});
+ send({method:'session/update',params:{update:{sessionUpdate:'available_commands_update',availableCommands:[]}}});
+ }
+ if (req.method === 'session/prompt') send({id:req.id,result:{stopReason:'end_turn'}});
+}).on('close',()=>process.exit(0));
+`, { mode: 0o700 });
+ const chat = `enroll-${path.basename(temp)}`;
+ const call = (method: string, params = {}) => deadline(POST(new NextRequest("http://localhost/api/acp", {
+ method: "POST", body: JSON.stringify({ chat, method, params }),
+ })), method);
+ const { attachmentStore } = await import("./attachment-store");
+ try {
+ process.env.GRAFF_BIN = binary;
+ delete process.env.GRAFF_REPORT_CWD;
+ const hostReport = await call("bootstrap", { cwd: temp, model: "fixture", yolo: false, mcp: false });
+ expect(hostReport.status).toBe(200);
+ expect(await hostReport.json()).toMatchObject({ sessionId: "enroll", cwd: path.resolve(temp) });
+ const spawned = JSON.parse(readFileSync(path.join(temp, "spawn.env"), "utf8"));
+ expect(path.resolve(spawned.cwd)).toBe(path.resolve(temp));
+ expect(path.resolve(spawned.pwd)).toBe(path.resolve(temp));
+ expect(path.resolve(spawned.graffCwd)).toBe(path.resolve(temp));
+ const store = attachmentStore();
+ const image = store.create("enroll.png", new Uint8Array([1, 2, 3]));
+ const prompted = await call("session/prompt", { prompt: [{ type: "text", text: `See @[${image}]` }] });
+ expect(prompted.status).toBe(200);
+ await deadline(prompted.text(), "image prompt");
+ const scope = path.join(realpathSync(temp), ".graff", "sessions");
+ const refs = path.join(store.directory, ".ownership", "references", path.basename(image));
+ const scopes = readdirSync(refs).map(name => JSON.parse(readFileSync(path.join(refs, name), "utf8")).directory);
+ expect(scopes).toEqual([scope]);
+ process.env.GRAFF_REPORT_CWD = isolated;
+ const tree = await call("bootstrap", { cwd: temp, model: "fixture", reset: true, yolo: false, mcp: false });
+ expect(tree.status).toBe(200);
+ expect(await tree.json()).toMatchObject({ sessionId: "enroll", cwd: isolated });
+ } finally {
+ await call("dispose");
+ if (oldBin === undefined) delete process.env.GRAFF_BIN; else process.env.GRAFF_BIN = oldBin;
+ delete process.env.GRAFF_REPORT_CWD;
+ rmSync(temp, { recursive: true, force: true });
+ }
+}, 15000);
diff --git a/src/acp.zig b/src/acp.zig
index 8f212e27..1168d08e 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -200,7 +200,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
.bind_session = liveBind,
.meter = liveMeter,
.extra = liveModels,
- .cwd = main_mod.g_cwd_display,
+ .cwd = if (std.fs.path.isAbsolute(main_mod.g_cwd_display)) main_mod.g_cwd_display else "",
};
while (true) {
const event = (inbox.wait(arena) catch break) orelse break;
diff --git a/src/session_start.zig b/src/session_start.zig
index d30c0bbe..f7767a0b 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -164,13 +164,18 @@ pub fn setupWorktreeAndBanner(
.autocommit = main_mod.g_worktree_autocommit,
} });
}
- var cwd_buf: [4096]u8 = undefined;
+ var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;
main_mod.g_cwd_display = if (flags.worktree_flag) |wt|
// After chdir into the worktree, realPath(AT_FDCWD) is unreliable; derive from the launch dir.
std.fmt.allocPrint(arena, "{s}/.graff/worktrees/{s}", .{ environ_map.get("PWD") orelse ".", wt }) catch try arena.dupe(u8, environ_map.get("PWD") orelse ".")
else if (isolated) |wt|
try arena.dupe(u8, wt.path)
- else if (Io.Dir.cwd().realPath(io, &cwd_buf)) |n|
+ else if (std.process.currentPath(io, &cwd_buf)) |n|
+ // Posix cwd is the spawn root. Io.Dir.cwd().realPath can name the
+ // parent host via inherited PWD (Next's apps/native) while sessions
+ // still write to the requested workspace.
+ try arena.dupe(u8, cwd_buf[0..n])
+ else |_| if (Io.Dir.cwd().realPath(io, &cwd_buf)) |n|
try arena.dupe(u8, cwd_buf[0..n])
else |_|
try arena.dupe(u8, environ_map.get("PWD") orelse ".");
diff --git a/src/tui_acp.zig b/src/tui_acp.zig
index 5f1a9ba0..8b1a0c4b 100644
--- a/src/tui_acp.zig
+++ b/src/tui_acp.zig
@@ -161,7 +161,7 @@ pub const Session = struct {
.ctx = @ptrCast(self),
.seed = seed,
.bind_session = bindSession,
- .cwd = main_mod.g_cwd_display,
+ .cwd = if (std.fs.path.isAbsolute(main_mod.g_cwd_display)) main_mod.g_cwd_display else "",
},
};
}