Skip to content

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

Python

Fix new-chat project roots and worktree isolation

Rach Pradhan8e7b312bf575
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 5343337a..064937af 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -50,7 +50,7 @@ import { usePromptQueue, steerOrInterrupt } from "./usePromptQueue";
import { useChatClose } from "./useChatClose";
import { type StoredSession } from "@/lib/sessions";
import { loadHistory, mergeHistory } from "@/lib/prompt-history";
-import { basename, displayWorkspace, findWorkspace, type Workspace } from "@/lib/workspaces";
+import { basename, chatProject, displayWorkspace, findWorkspace, type Workspace } from "@/lib/workspaces";
export default function GraffHarness() {
const navigation = useResponsiveNavigation();
@@ -238,7 +238,7 @@ export default function GraffHarness() {
sessionNamesRef.current.set(id, session);
const cwd = folder ?? activePathRef.current ?? undefined;
const ws = findWorkspace(workspacesRef.current, cwd);
- const next = [...chatsRef.current, { id, title: null, messages: [], model: ws?.model ?? model ?? undefined, session, cwd }];
+ const next = [...chatsRef.current, { id, title: null, messages: [], model: ws?.model ?? model ?? undefined, session, cwd, project: cwd }];
chatsRef.current = next; setChats(next);
setZoomedPane(null);
activateChat(id);
@@ -270,7 +270,7 @@ export default function GraffHarness() {
const openStored = (name: string, cwd = activePathRef.current ?? undefined) => savedConversation.open(name, cwd);
const newChat = () => {
- const folder = chatsRef.current.find(c => c.id === activeIdRef.current)?.cwd;
+ const folder = chatProject(chatsRef.current.find(c => c.id === activeIdRef.current) ?? {}, activePathRef.current, workspacesRef.current);
if (folder && folder !== activePathRef.current) activateWorkspace(folder);
openChat((chatIdRef.current += 1), folder ?? activePathRef.current ?? undefined);
};
@@ -280,7 +280,7 @@ export default function GraffHarness() {
if (id !== activeIdRef.current) setBrowserOpen(false);
setProjectsOpen(false); setAgentsOpen(false);
setConversationsOpen(false);
- const folder = chatsRef.current.find(chat => chat.id === id)?.cwd;
+ const folder = chatProject(chatsRef.current.find(chat => chat.id === id) ?? {}, activePathRef.current, workspacesRef.current);
if (folder && folder !== activePathRef.current) activateWorkspace(folder);
if (!columnIds.includes(id) || (zoomedPane !== null && zoomedPane !== id)) setZoomedPane(null);
setActiveId(id);
@@ -303,12 +303,10 @@ export default function GraffHarness() {
if (!next) { if (!source.some(pane => columnIds.includes(pane)) && columnIds.length + source.length > MAX_COLUMNS) setSplitNotice(SPLIT_LIMIT_MESSAGE); return; }
setSplitNotice(null); setZoomedPane(null);
groups.split(sourceId, drop.id, drop.edge); setActiveId(sourceId);
- const folder = chatsRef.current.find(chat => chat.id === sourceId)?.cwd;
+ const folder = chatProject(chatsRef.current.find(chat => chat.id === sourceId) ?? {}, activePathRef.current, workspacesRef.current);
if (folder && folder !== activePathRef.current) activateWorkspace(folder);
});
- /** Another chat beside the ones on screen, in the workspace the active
- * chat is in. Up to four columns; past that they are too narrow to read. */
const addPane = (direction: "row" | "column" = splitDirection) => {
if (splitLimitReached(columnIds.length)) {
setSplitNotice(SPLIT_LIMIT_MESSAGE);
@@ -316,7 +314,7 @@ export default function GraffHarness() {
}
setSplitNotice(null);
const id = (chatIdRef.current += 1);
- openChat(id, chatsRef.current.find(c => c.id === activeIdRef.current)?.cwd ?? activePathRef.current ?? undefined);
+ openChat(id, chatProject(chatsRef.current.find(c => c.id === activeIdRef.current) ?? {}, activePathRef.current, workspacesRef.current));
groups.split(id,activeId,direction === "row" ? "right" : "bottom");
};
@@ -352,7 +350,7 @@ export default function GraffHarness() {
// Display the project separately from the checkout where this chat runs.
const cwdOf = (thread: Chat) => thread.cwd ?? activePath ?? health?.cwd;
- const workspaceOf = (thread: Chat) => displayWorkspace(cwdOf(thread), workspaces);
+ const workspaceOf = (thread: Chat) => displayWorkspace(cwdOf(thread), workspaces, chatProject(thread, activePath, workspaces));
const chatCwd = cwdOf(chatThread);
useEffect(() => {
let alive = true;
diff --git a/apps/native/components/site/harness-types.ts b/apps/native/components/site/harness-types.ts
index 219db342..9aa2edea 100644
--- a/apps/native/components/site/harness-types.ts
+++ b/apps/native/components/site/harness-types.ts
@@ -7,6 +7,8 @@ export type Msg =
* model is only the default a new tab inherits. `cwd` is the workspace the
* tab's agent runs in — fixed at spawn, like the model. */
export type Chat = { id: number; title: string | null; messages: Msg[]; model?: string; nextModel?: string; preparingModel?: string; session?: string; cwd?: string;
+ /** Folder chosen for new chats and project settings; cwd may be an isolated checkout. */
+ project?: string;
/** The model named this tab from its first prompt: the session poller,
* which reads graff's own saved title, must leave it alone. */
titledByModel?: boolean;
@@ -23,4 +25,3 @@ export function newPageToken(): string {
export function newSessionName(): string {
return `native-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
}
-
diff --git a/apps/native/components/site/harness-workspace-actions.ts b/apps/native/components/site/harness-workspace-actions.ts
index 3976641c..1f922b36 100644
--- a/apps/native/components/site/harness-workspace-actions.ts
+++ b/apps/native/components/site/harness-workspace-actions.ts
@@ -34,7 +34,7 @@ export function workspaceActions({workspacesRef, activePathRef, chatsRef, chatId
* there, and a conversation would lose the ground it was standing on. */
const moveChatTo = (chatId: number, path: string) => {
const ws = findWorkspace(workspacesRef.current, path);
- const next = chatsRef.current.map((c) => (c.id === chatId ? { ...c, cwd: path, model: c.model ?? ws?.model } : c));
+ const next = chatsRef.current.map((c) => (c.id === chatId ? { ...c, cwd: path, project: path, model: c.model ?? ws?.model } : c));
// requireSession reads the chat from this ref in the same tick, before
// React has re-rendered with the new cwd.
chatsRef.current = next;
diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.ts
index bca0bc31..fffca05a 100644
--- a/apps/native/components/site/useHarnessSessions.ts
+++ b/apps/native/components/site/useHarnessSessions.ts
@@ -9,7 +9,7 @@ import type { AcpCommand } from "@/lib/acp";
import type { PromptModel } from "@/components/primitives/PromptBar";
import { listSessionsPage, type StoredSession } from "@/lib/sessions";
import { restoreProjects, persistProjects } from "@/lib/project-preferences";
-import { findWorkspace, mergeWorkspaceActivity, restoreWorkspaceSelection, type Workspace } from "@/lib/workspaces";
+import { chatProject, findWorkspace, mergeWorkspaceActivity, restoreWorkspaceSelection, type Workspace } from "@/lib/workspaces";
import { newSessionName, type Chat } from "./harness-types";
type Ref<T> = MutableRefObject<T>;
type Setter<T> = Dispatch<SetStateAction<T>>;
@@ -134,7 +134,7 @@ export function useHarnessSessions({onPermission, sessionsRef, sessionNamesRef,
// A tab spawns where it was opened; the first tab, opened before the
// workspace list loaded, takes the active workspace.
const cwd = chat?.cwd ?? activePathRef.current ?? undefined;
- const ws = findWorkspace(workspacesRef.current, cwd);
+ const ws = findWorkspace(workspacesRef.current, chatProject(chat ?? {}, activePathRef.current, workspacesRef.current));
const spawnModel = key ?? chat?.model ?? ws?.model ?? model ?? undefined;
const cached = catalogForSpawn.current[chatId];
const { sessionId: id, commands, cwd: checkout } = await startWithSelectedModel(spawnModel,
diff --git a/apps/native/lib/workspaces.test.ts b/apps/native/lib/workspaces.test.ts
index ea0c9346..09fee08c 100644
--- a/apps/native/lib/workspaces.test.ts
+++ b/apps/native/lib/workspaces.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import {
basename,
displayWorkspace,
+ chatProject,
restoreWorkspaceSelection,
findWorkspace,
loadActiveWorkspace,
@@ -49,6 +50,7 @@ describe("displayWorkspace", () => {
assert.deepEqual(displayWorkspace("/repo", workspaces), { project: "Codegraff", worktree: false });
assert.deepEqual(displayWorkspace("/repo/.graff/worktrees/session-one", workspaces), { project: "Codegraff", worktree: true });
assert.deepEqual(displayWorkspace("/repo/.graff/worktrees/session-one/.graff/worktrees/session-two", workspaces), { project: "Codegraff", worktree: true });
+ assert.deepEqual(displayWorkspace("/repo/.graff/worktrees/session-one", workspaces, "/repo/.graff/worktrees/session-one"), { project: "session-one", worktree: true });
});
it("keeps ordinary folders and fallback names unchanged", () => {
assert.deepEqual(displayWorkspace("/other/project", workspaces), { project: "project", worktree: false });
@@ -90,6 +92,21 @@ describe("remove / find", () => {
});
});
+describe("chat project identity", () => {
+ const root = "/repo";
+ const checkout = `${root}/.graff/worktrees/session-42`;
+ it("starts a new chat in the project after auto-isolation", () => {
+ assert.equal(chatProject({ cwd: checkout, project: root }, checkout, []), root);
+ assert.equal(chatProject({ cwd: checkout }, checkout, []), root);
+ assert.equal(chatProject({ cwd: `${checkout}/.graff/worktrees/session-43` }, checkout, []), root);
+ });
+ it("keeps explicitly selected linked worktrees", () => {
+ assert.equal(chatProject({ cwd: checkout, project: checkout }, root, []), checkout);
+ assert.equal(chatProject({ cwd: checkout }, root, [{ path: checkout, name: "selected", source: "saved" }]), checkout);
+ assert.equal(chatProject({ cwd: "/repo/.graff/worktrees/feature" }, root, []), "/repo/.graff/worktrees/feature");
+ });
+});
+
describe("storage", () => {
it("round-trips the list and drops junk rows", () => {
const store = memoryStorage();
diff --git a/apps/native/lib/workspaces.ts b/apps/native/lib/workspaces.ts
index 21cacd22..73cfa2c6 100644
--- a/apps/native/lib/workspaces.ts
+++ b/apps/native/lib/workspaces.ts
@@ -74,17 +74,33 @@ export type WorkspaceDisplay = { project: string; worktree: boolean };
/** Generated checkouts are still separate working folders, but their GUI label
* names the owning project rather than a session-shaped directory. */
-export function displayWorkspace(cwd: string | null | undefined, list: readonly Workspace[]): WorkspaceDisplay {
- if (!cwd) return { project: "workspace", worktree: false };
- const path = normalizePath(cwd);
+export function displayWorkspace(cwd: string | null | undefined, list: readonly Workspace[], selectedProject?: string): WorkspaceDisplay {
+ if (!cwd && !selectedProject) return { project: "workspace", worktree: false };
+ const path = normalizePath(cwd ?? selectedProject ?? "");
const checkout = /[/\\]\.graff[/\\]worktrees[/\\][^/\\]+(?=$|[/\\])/.exec(path);
- const projectPath = checkout ? path.slice(0, checkout.index) || path[0] : path;
+ const projectPath = selectedProject ? normalizePath(selectedProject) : checkout ? path.slice(0, checkout.index) || path[0] : path;
return {
project: findWorkspace(list, projectPath)?.name ?? basename(projectPath.replace(/\\/g, "/")),
worktree: checkout !== null,
};
}
+/** A generated checkout belongs to the project that contains .graff. An
+ * explicitly selected folder wins, even if it has the same path shape. */
+export function chatProject(
+ chat: { cwd?: string; project?: string }, fallback: string | null | undefined,
+ workspaces: readonly Workspace[],
+): string | undefined {
+ if (chat.project) return chat.project;
+ const cwd = chat.cwd;
+ if (!cwd) return fallback ?? undefined;
+ if (findWorkspace(workspaces, cwd)?.source === "saved") return cwd;
+ const marker = "/.graff/worktrees/";
+ const at = cwd.indexOf(marker);
+ if (at > 0 && /^session-[^/]+(?:\/\.graff\/worktrees\/session-[^/]+)*$/.test(cwd.slice(at + marker.length))) return cwd.slice(0, at);
+ return cwd;
+}
+
/** Preserve chosen rows, including a full list, when showing startup context. */
export function restoreWorkspaceSelection(saved: readonly Workspace[], remembered: string | null, root: string) {
const list = [...saved];
diff --git a/docs/adr/0198-project-choice-survives-session-isolation.md b/docs/adr/0198-project-choice-survives-session-isolation.md
new file mode 100644
index 00000000..b56e737a
--- /dev/null
+++ b/docs/adr/0198-project-choice-survives-session-isolation.md
@@ -0,0 +1,27 @@
+# 0198. Project choice survives session isolation
+
+Status: accepted 2026-09-24
+
+## Context
+
+Auto-isolation changes a chat's working checkout after ACP `session/new`.
+Using that checkout as the folder for a new chat or split reused the previous
+session's files (#1229). Isolation from an inherited worktree could then mint
+a nested checkout (#1235).
+
+## Decision
+
+- A chat keeps its chosen project folder separate from the checkout reported
+ by ACP. New chats and splits start from the chosen folder. A worktree the
+ user explicitly selected remains that folder.
+- ACP continues to report the actual checkout so file tools, resume, and
+ conversation storage follow the running session.
+- Auto-isolation resolves Git's common directory and creates generated
+ checkouts under the main checkout of that repository, even when launched
+ from a linked worktree.
+
+## Consequences
+
+Project settings follow the chosen folder while running tools use the ACP
+checkout. Restored chats without an explicit in-memory choice recover the
+project from a generated `session-*` checkout path; a saved folder choice wins.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index e3a5db5e..980d1b52 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -220,6 +220,7 @@ record only when you need the evidence or the edge cases.
| [0192](0192-mimo-thinking-is-a-binary-setting.md) | MiMo exposes Off/On, preserves legacy positive settings as On, and uses the documented thinking control on each wire. |
| [0193](0193-jev-selects-effort-only.md) | Optional Jev selects only supported session effort at the next request boundary; arbitrary judgments are not exposed. |
| [0195](0195-embedded-browser-replaces-kuri.md) | Desktop browser uses embedded Chromium, web preview uses the paired extension, and CLI fetch uses built-in HTTP without a sidecar. |
+| [0198](0198-project-choice-survives-session-isolation.md) | New chats inherit the chosen project while ACP reports each worker checkout; generated worktrees are rooted at the main checkout. |
## When to write one
diff --git a/src/task_workspace.zig b/src/task_workspace.zig
index 44424847..81096ada 100644
--- a/src/task_workspace.zig
+++ b/src/task_workspace.zig
@@ -103,6 +103,14 @@ pub fn gitDirAt(gpa: Allocator, io: Io, arena: Allocator, checkout: []const u8)
return lease.identityAt(gpa, io, arena, checkout).id;
}
+/// Auto-isolation always writes under the owning main checkout, even when
+/// the new session was launched from another linked worktree.
+pub fn autoIsolationRoot(gpa: Allocator, io: Io, arena: Allocator, checkout: []const u8) ?[]const u8 {
+ const common = lease.gitCommonDirAt(gpa, io, arena, checkout);
+ const root = worktree_prune.mainWorktreePath(common);
+ return if (root.len > 0) root else null;
+}
+
fn isGitAt(gpa: Allocator, io: Io, cwd: []const u8) bool {
const r = runCapped(gpa, io, &.{ "git", "-C", cwd, "rev-parse", "--is-inside-work-tree" }, 4096, 4096, 15_000) catch return false;
defer {
@@ -397,7 +405,8 @@ pub fn maybeAutoIsolate(gpa: Allocator, io: Io, arena: Allocator, home: []const
io.random(&raw);
const nonce = std.fmt.bytesToHex(raw, .lower);
const slug = autoSlug(arena, proc_identity.selfPid(), nonce[0..8]) catch return .{ .failed = error.CreateFailed };
- const wt = create(gpa, io, arena, .{ .slug = slug, .unique = true }) catch |err| return .{ .failed = err };
+ const project = autoIsolationRoot(gpa, io, arena, ".") orelse return .{ .failed = error.CreateFailed };
+ const wt = create(gpa, io, arena, .{ .slug = slug, .cwd = project, .unique = true }) catch |err| return .{ .failed = err };
enter(io, arena, wt) catch |err| return .{ .failed = err };
return .{ .isolated = wt };
}
diff --git a/src/task_workspace_tests.zig b/src/task_workspace_tests.zig
index dba797e1..c0244c39 100644
--- a/src/task_workspace_tests.zig
+++ b/src/task_workspace_tests.zig
@@ -77,7 +77,11 @@ test "create: two task workspaces get distinct checkouts and index.lock paths" {
defer arena.deinit();
const ar = arena.allocator();
const one = try ws.create(a, io, ar, .{ .slug = "agent-one", .cwd = root });
- const two = try ws.create(a, io, ar, .{ .slug = "agent-two", .cwd = root });
+ const project = ws.autoIsolationRoot(a, io, ar, one.path) orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqualStrings(root, project);
+ const two = try ws.create(a, io, ar, .{ .slug = "agent-two", .cwd = project });
+ const expected_two = try std.fs.path.join(ar, &.{ root, ".graff", "worktrees", "agent-two" });
+ try std.testing.expectEqualStrings(expected_two, two.path);
try std.testing.expect(!std.mem.eql(u8, one.path, two.path));
try std.testing.expect(!std.mem.eql(u8, one.branch, two.branch));
try std.testing.expectEqualStrings("main", @import("worktree_base.zig").read(a, io, ar, root, one.branch));