Skip to content

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

Python

feat(native): workspaces — switcher, folder picker, settings; a tab's agent runs in its own workspace

justrach62ebfe0efe4e
diff --git a/apps/native/.gitignore b/apps/native/.gitignore
index 7c83d812..d9424ee3 100644
--- a/apps/native/.gitignore
+++ b/apps/native/.gitignore
@@ -1,4 +1,4 @@
-node_modules/
+node_modules
.next/
out/
*.tsbuildinfo
diff --git a/apps/native/README.md b/apps/native/README.md
index 84f85e36..72058a88 100644
--- a/apps/native/README.md
+++ b/apps/native/README.md
@@ -75,12 +75,35 @@ tab's agent with `--resume`, so a follow-up continues the conversation with
the model's memory intact.
The workspace itself is walkable: `/api/fs` (list/read, plus macOS
-`open`/`open -R` passthroughs) is sandboxed to the agent's cwd and backs
+`open`/`open -R` passthroughs) is sandboxed to the tab's cwd and backs
a files pane — the folder chip in the tab bar or the sidebar's
Workspace item opens it. Tool-row chips and path-looking inline code in
answers (`src/acp.zig`) jump straight to that file; markdown files
render, code shows mono, binaries hand off to Open.
+## Workspaces
+
+A workspace is a folder graff runs in. The switcher at the top of the
+sidebar lists every workspace this browser knows (`localStorage`; the
+server only validates a root it is handed) with the active one checked:
+
+- **New workspace…** opens a folder picker (`/api/workspaces` walks one
+ level at a time, marks git roots, takes a typed or pasted path) and
+ switches to the folder you pick.
+- **Workspace settings…** edits the active workspace: display name, the
+ model new tabs spawn with, and whether tools are auto-approved
+ (`graff acp --yolo`). *Forget* removes it from the switcher only.
+- Switching workspaces changes the sidebar's session list and where new
+ tabs open. A tab's agent is spawned in the workspace that was active
+ when the tab opened and stays there — the folder chip in the tab bar
+ names the tab's own workspace, the switcher names the active one.
+
+`/api/acp` bootstrap, `/api/sessions`, `/api/fs` and `/api/git` all take
+the workspace root (`cwd` / `?root=`) and fall back to the default from
+`GRAFF_CWD` or the repo root. The sidebar footer names the tab's graff
+session (`native-…`, the `--resume` target); clicking it copies the
+command that continues the same conversation in a terminal.
+
## Run
```bash
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index d2cc494d..058f8400 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -1,8 +1,10 @@
import { spawn, type ChildProcessByStdio } from "node:child_process";
import { existsSync } from "node:fs";
+import os from "node:os";
import path from "node:path";
import type { Readable, Writable } from "node:stream";
import { NextRequest } from "next/server";
+import { defaultRoot, resolveRoot } from "@/lib/server-root";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -17,8 +19,14 @@ type Slot = {
model: string | null;
/** graff session name (`--resume`): the file this agent autosaves to. */
resume: string | null;
+ /** The workspace the agent was spawned in: its cwd, where its sessions save. */
+ cwd: string;
+ yolo: boolean;
};
+type SpawnOpts = { model?: string; resume?: string; cwd: string; yolo: boolean };
+type BootstrapOpts = { model?: string; reset?: boolean; resume?: string; cwd?: string; yolo?: boolean };
+
// One `graff acp` child per chat tab. The agent holds exactly one live
// session per process (`session/load` is not implemented), so a tab's
// conversation memory *is* its child: when every tab shared one child, each
@@ -42,15 +50,7 @@ function graffBin(): string {
return "graff";
}
-function workspace(): string {
- if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;
- if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;
- const fromApp = path.resolve(process.cwd(), "../..");
- if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;
- return process.cwd();
-}
-
-function yolo(): boolean {
+function defaultYolo(): boolean {
const raw = process.env.GRAFF_YOLO;
if (raw === "0" || raw === "false" || raw === "off" || raw === "no") return false;
return true;
@@ -88,18 +88,27 @@ function killPage(page: string) {
}
}
-function spawnAgent(chat: string, model?: string, resume?: string): Slot {
+function spawnAgent(chat: string, opts: SpawnOpts): Slot {
killSlot(chat);
const args = ["acp"];
- if (yolo()) args.push("--yolo");
- if (model) args.push("--model", model);
- if (resume) args.push("--resume", resume);
+ if (opts.yolo) args.push("--yolo");
+ if (opts.model) args.push("--model", opts.model);
+ if (opts.resume) args.push("--resume", opts.resume);
const child = spawn(graffBin(), args, {
stdio: ["pipe", "pipe", "inherit"],
- cwd: workspace(),
+ cwd: opts.cwd,
env: process.env,
});
- const slot: Slot = { child, buf: "", nextId: 1, sessionId: null, model: model ?? null, resume: resume ?? null };
+ const slot: Slot = {
+ child,
+ buf: "",
+ nextId: 1,
+ sessionId: null,
+ model: opts.model ?? null,
+ resume: opts.resume ?? null,
+ cwd: opts.cwd,
+ yolo: opts.yolo,
+ };
child.on("exit", () => {
if (slots.get(chat) === slot) slots.delete(chat);
});
@@ -153,14 +162,27 @@ async function rpc(slot: Slot, method: string, params?: unknown): Promise<unknow
}
}
-async function bootstrap(chat: string, model?: string, reset = false, resume?: string): Promise<Slot> {
+/** The tab's live agent when it still matches what was asked for (model,
+ * session file, workspace, approval mode); otherwise a fresh spawn. A
+ * request that leaves a field out accepts whatever the live agent has. */
+async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
const live = slots.get(chat);
- if (!reset && live && (!model || live.model === model) && (!resume || live.resume === resume) && live.sessionId) {
- return live;
- }
- const slot = spawnAgent(chat, model, resume);
+ const same =
+ live !== undefined &&
+ live.sessionId !== null &&
+ (!opts.model || live.model === opts.model) &&
+ (!opts.resume || live.resume === opts.resume) &&
+ (!opts.cwd || live.cwd === opts.cwd) &&
+ (opts.yolo === undefined || live.yolo === opts.yolo);
+ if (!opts.reset && same) return live;
+ const slot = spawnAgent(chat, {
+ model: opts.model,
+ resume: opts.resume,
+ cwd: opts.cwd ?? defaultRoot(),
+ yolo: opts.yolo ?? defaultYolo(),
+ });
await rpc(slot, "initialize", { protocolVersion: 1, clientCapabilities: { fs: {} } });
- const created = (await rpc(slot, "session/new", { cwd: workspace() })) as {
+ const created = (await rpc(slot, "session/new", { cwd: slot.cwd })) as {
sessionId?: string;
};
if (!created?.sessionId) throw new Error("session/new returned no sessionId");
@@ -184,7 +206,7 @@ export async function GET() {
{ status: 502 },
);
}
- return Response.json({ ok: true, sessions: slots.size, cwd: workspace() });
+ return Response.json({ ok: true, sessions: slots.size, cwd: defaultRoot(), home: os.homedir(), yolo: defaultYolo() });
}
export async function POST(req: NextRequest) {
@@ -209,10 +231,20 @@ export async function POST(req: NextRequest) {
if (method === "bootstrap") {
const resume =
typeof body.params?.resume === "string" && SESSION_NAME_RE.test(body.params.resume) ? body.params.resume : undefined;
- const slot = await bootstrap(chat, model, body.params?.reset === true, resume);
- return Response.json({ sessionId: slot.sessionId });
+ const cwdParam = typeof body.params?.cwd === "string" && body.params.cwd.trim() ? body.params.cwd : undefined;
+ const resolved = resolveRoot(cwdParam);
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const yolo = typeof body.params?.yolo === "boolean" ? body.params.yolo : undefined;
+ const slot = await bootstrap(chat, {
+ model,
+ reset: body.params?.reset === true,
+ resume,
+ cwd: cwdParam ? resolved.root : undefined,
+ yolo,
+ });
+ return Response.json({ sessionId: slot.sessionId, cwd: slot.cwd });
}
- const slot = await bootstrap(chat, model);
+ const slot = await bootstrap(chat, { model });
if (method === "session/cancel") {
writeLine(slot, { jsonrpc: "2.0", method: "session/cancel", params: body.params });
return Response.json({ ok: true });
diff --git a/apps/native/app/api/fs/route.ts b/apps/native/app/api/fs/route.ts
index 68b8571d..c50e03af 100644
--- a/apps/native/app/api/fs/route.ts
+++ b/apps/native/app/api/fs/route.ts
@@ -1,20 +1,12 @@
import { spawn } from "node:child_process";
-import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { readdirSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import { NextRequest } from "next/server";
+import { resolveRoot } from "@/lib/server-root";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-/** Same resolution as /api/acp: the workspace the agent itself runs in. */
-function workspaceRoot(): string {
- if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;
- if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;
- const fromApp = path.resolve(process.cwd(), "../..");
- if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;
- return process.cwd();
-}
-
/** Heavy or generated trees that only bury the folders people navigate to. */
const HIDDEN = new Set([".git", "node_modules", ".next", ".zig-cache", "zig-out", ".DS_Store"]);
@@ -40,7 +32,10 @@ function resolveInRoot(root: string, rel: string): string | null {
}
export async function GET(req: NextRequest) {
- const root = workspaceRoot();
+ // `?root=` picks the workspace (a tab's own cwd); paths stay inside it.
+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const root = resolved.root;
const rel = req.nextUrl.searchParams.get("path") ?? "";
const target = resolveInRoot(root, rel);
if (!target) return Response.json({ error: "path escapes the workspace" }, { status: 400 });
@@ -93,8 +88,10 @@ export async function GET(req: NextRequest) {
}
export async function POST(req: NextRequest) {
- const root = workspaceRoot();
- const body = (await req.json()) as { action?: string; path?: string };
+ const body = (await req.json()) as { action?: string; path?: string; root?: string };
+ const resolved = resolveRoot(body.root);
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const root = resolved.root;
const target = resolveInRoot(root, body.path ?? "");
if (!target) return Response.json({ error: "path escapes the workspace" }, { status: 400 });
if (process.platform !== "darwin") {
diff --git a/apps/native/app/api/git/route.ts b/apps/native/app/api/git/route.ts
index 06541ab2..6776353d 100644
--- a/apps/native/app/api/git/route.ts
+++ b/apps/native/app/api/git/route.ts
@@ -1,22 +1,14 @@
import { execFile } from "node:child_process";
-import { existsSync } from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
+import { NextRequest } from "next/server";
+import { resolveRoot } from "@/lib/server-root";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const run = promisify(execFile);
-/** Same resolution as /api/acp: the workspace the agent itself runs in. */
-function workspaceRoot(): string {
- if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;
- if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;
- const fromApp = path.resolve(process.cwd(), "../..");
- if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;
- return process.cwd();
-}
-
async function git(args: string[], cwd: string): Promise<string> {
const { stdout } = await run("git", args, { cwd, maxBuffer: 8 * 1024 * 1024 });
return stdout;
@@ -24,8 +16,10 @@ async function git(args: string[], cwd: string): Promise<string> {
/** The working tree's uncommitted story, Codex-review shaped: per-file
* +adds/−dels plus the unified diff, untracked files included. */
-export async function GET() {
- const root = workspaceRoot();
+export async function GET(req: NextRequest) {
+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const root = resolved.root;
try {
const [numstat, untrackedRaw] = await Promise.all([
git(["diff", "--numstat"], root),
@@ -70,8 +64,10 @@ export async function GET() {
/** POST {path} → the unified diff for one file (or its full content when untracked). */
export async function POST(req: Request) {
- const root = workspaceRoot();
- const body = (await req.json()) as { path?: string };
+ const body = (await req.json()) as { path?: string; root?: string };
+ const resolved = resolveRoot(body.root);
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const root = resolved.root;
const file = body.path ?? "";
const target = path.resolve(root, file);
if (target !== root && !target.startsWith(root + path.sep)) {
diff --git a/apps/native/app/api/sessions/route.ts b/apps/native/app/api/sessions/route.ts
index 80e3e4de..ecb0859e 100644
--- a/apps/native/app/api/sessions/route.ts
+++ b/apps/native/app/api/sessions/route.ts
@@ -1,19 +1,11 @@
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
import path from "node:path";
import { NextRequest } from "next/server";
+import { resolveRoot } from "@/lib/server-root";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-/** Same resolution as /api/acp: the workspace the agent itself runs in. */
-function workspaceRoot(): string {
- if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;
- if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;
- const fromApp = path.resolve(process.cwd(), "../..");
- if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;
- return process.cwd();
-}
-
// graff autosaves every conversation to `<cwd>/.graff/sessions/<name>.session.json`
// (src/session_index.zig owns the layout). The header — provider, model, title,
// updated_ms — is written before the (possibly multi-MB) messages array, so the
@@ -87,7 +79,11 @@ function rowFor(dir: string, entry: string): StoredSessionRow | null {
}
export async function GET(req: NextRequest) {
- const root = workspaceRoot();
+ // `?root=` is the workspace whose sessions are wanted (each workspace
+ // keeps its own .graff/sessions); absent, the agent's default workspace.
+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
+ const root = resolved.root;
const dir = path.join(root, SESSIONS_DIR);
const name = req.nextUrl.searchParams.get("name");
if (name !== null) {
diff --git a/apps/native/app/api/workspaces/route.ts b/apps/native/app/api/workspaces/route.ts
new file mode 100644
index 00000000..fd453cc1
--- /dev/null
+++ b/apps/native/app/api/workspaces/route.ts
@@ -0,0 +1,54 @@
+import { existsSync, readdirSync, statSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+import { defaultRoot, expandHome } from "@/lib/server-root";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+/** Folder browser behind the "New workspace" picker: one directory level
+ * at a time, folders only. Dot-folders and dependency trees are hidden —
+ * nobody makes `node_modules` a workspace — and git roots are marked so a
+ * repo stands out among its siblings. */
+
+const HIDDEN = new Set(["node_modules", "zig-out", "target", "__pycache__"]);
+
+export type FolderEntry = { name: string; path: string; git: boolean };
+
+function isDir(p: string): boolean {
+ try {
+ return statSync(p).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+export async function GET(req: NextRequest) {
+ const raw = req.nextUrl.searchParams.get("path");
+ const home = os.homedir();
+ const target = path.resolve(expandHome(raw && raw.trim() ? raw.trim() : home));
+ if (!isDir(target)) return Response.json({ error: `not a directory: ${target}` }, { status: 404 });
+ try {
+ const entries: FolderEntry[] = [];
+ for (const entry of readdirSync(target, { withFileTypes: true })) {
+ if (entry.name.startsWith(".") || HIDDEN.has(entry.name)) continue;
+ const full = path.join(target, entry.name);
+ if (!(entry.isDirectory() || (entry.isSymbolicLink() && isDir(full)))) continue;
+ entries.push({ name: entry.name, path: full, git: existsSync(path.join(full, ".git")) });
+ }
+ entries.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
+ const parent = path.dirname(target);
+ return Response.json({
+ ok: true,
+ path: target,
+ parent: parent === target ? null : parent,
+ git: existsSync(path.join(target, ".git")),
+ home,
+ default: defaultRoot(),
+ entries,
+ });
+ } catch (err) {
+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });
+ }
+}
diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsx
index ddcf2116..baec1029 100644
--- a/apps/native/components/primitives/SidebarNav.tsx
+++ b/apps/native/components/primitives/SidebarNav.tsx
@@ -3,7 +3,6 @@
import { Fragment, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { createPortal } from "react-dom";
import {
- IconArrowBoxLeft,
IconCheckmark1Small,
IconChevronDownSmall,
IconCrossSmall,
@@ -15,9 +14,10 @@ import {
IconPopsicle2,
IconSettingsGear1,
IconSidebarLeftArrow,
- IconUserAdd,
+ IconSidebarLeftOpen,
} from "@/lib/icons";
import GlideMenu from "@/components/primitives/GlideMenu";
+import { monogram } from "@/lib/workspaces";
/* ─────────────────────────────────────────────────────────
* SIDEBAR NAV
@@ -65,10 +65,21 @@ type SidebarNavProps = {
footerLabel?: string;
footerIcon?: ReactNode;
onFooterClick?: () => void;
+ /** Tooltip on the footer control. */
+ footerTitle?: string;
recents?: SidebarRecent[];
variant?: string;
+ /** The active workspace (the folder graff runs in); the demo shows a placeholder. */
+ workspace?: SidebarWorkspace;
+ /** Every workspace the switcher offers, the active one included. */
+ workspaces?: SidebarWorkspace[];
+ onSwitchWorkspace?: (path: string) => void;
+ onNewWorkspace?: () => void;
+ onWorkspaceSettings?: () => void;
};
+export type SidebarWorkspace = { path: string; name: string };
+
const SIDEBAR_MOTION = {
expandedWidth: 224,
collapsedWidth: 52,
@@ -140,13 +151,32 @@ function RailButton({
);
}
+/** The switcher: every known workspace (check on the active one), then the
+ * two actions that lead somewhere — a folder picker and the settings sheet.
+ * The demo (no workspaces wired) shows the placeholder row alone. */
function WorkspaceMenu({
position,
+ current,
+ rows,
+ onSwitch,
+ onNew,
+ onSettings,
onClose,
}: {
position: { top: number; left: number };
+ current?: string;
+ rows: SidebarWorkspace[];
+ onSwitch?: (path: string) => void;
+ onNew?: () => void;
+ onSettings?: () => void;
onClose: () => void;
}) {
+ const list: SidebarWorkspace[] = rows.length > 0 ? rows : [{ path: WORKSPACE.key, name: WORKSPACE.name }];
+ const active = current ?? list[0]?.path;
+ const pick = (action?: () => void) => () => {
+ onClose();
+ action?.();
+ };
return createPortal(
<div
data-workspace-menu
@@ -159,45 +189,43 @@ function WorkspaceMenu({
}}
>
<GlideMenu className="flex flex-col gap-px" highlightClassName="inset-x-0 rounded-[8px] bg-hover-2">
- <button
- data-menu-row
- type="button"
- onClick={onClose}
- className="relative z-10 flex h-10 w-full items-center gap-1.5 rounded-[8px] px-2 text-left"
- >
- <span className="flex size-6 shrink-0 items-center justify-center rounded-[7px] bg-ink text-[11px] font-semibold text-surface">
- {WORKSPACE.monogram}
- </span>
- <span className="min-w-0 flex-1 truncate text-[13.5px] font-medium text-ink">{WORKSPACE.name}</span>
- <span className="shrink-0 text-ink"><IconCheckmark1Small size={18} /></span>
- </button>
+ {list.map((row) => (
+ <button
+ key={row.path}
+ data-menu-row
+ type="button"
+ title={row.path}
+ aria-current={row.path === active ? "true" : undefined}
+ onClick={pick(row.path === active ? undefined : () => onSwitch?.(row.path))}
+ className="relative z-10 flex h-10 w-full items-center gap-1.5 rounded-[8px] px-2 text-left"
+ >
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-[7px] bg-ink text-[11px] font-semibold text-surface">
+ {monogram(row.name)}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-[13.5px] font-medium text-ink">{row.name}</span>
+ {row.path === active && (
+ <span className="shrink-0 text-ink">
+ <IconCheckmark1Small size={18} />
+ </span>
+ )}
+ </button>
+ ))}
<div className="my-1 h-px bg-line" />
{[
- { label: "New workspace", icon: <IconPlusMedium size={16} /> },
- { label: "Workspace settings", icon: <IconSettingsGear1 size={16} /> },
- { label: "Invite team members", icon: <IconUserAdd size={16} /> },
+ { label: "New workspace…", icon: <IconPlusMedium size={16} />, action: onNew },
+ { label: "Workspace settings…", icon: <IconSettingsGear1 size={16} />, action: onSettings },
].map((item) => (
<button
key={item.label}
data-menu-row
type="button"
- onClick={onClose}
+ onClick={pick(item.action)}
className="relative z-10 flex h-9 w-full items-center gap-1.5 rounded-[8px] px-2 text-left"
>
<span className="flex size-5 shrink-0 items-center justify-center text-ink-2">{item.icon}</span>
<span className="min-w-0 flex-1 truncate text-[13.5px] text-ink">{item.label}</span>
</button>
))}
- <div className="my-1 h-px bg-line" />
- <button
- data-menu-row
- type="button"
- onClick={onClose}
- className="relative z-10 flex h-9 w-full items-center gap-1.5 rounded-[8px] px-2 text-left"
- >
- <span className="flex size-5 shrink-0 items-center justify-center text-ink-2"><IconArrowBoxLeft size={16} /></span>
- <span className="min-w-0 flex-1 truncate text-[13.5px] text-ink">Sign out</span>
- </button>
</GlideMenu>
</div>,
document.body,
@@ -216,7 +244,13 @@ export default function SidebarNav({
footerLabel = "Upgrade",
footerIcon,
onFooterClick,
+ footerTitle,
recents = DEFAULT_RECENTS,
+ workspace,
+ workspaces = [],
+ onSwitchWorkspace,
+ onNewWorkspace,
+ onWorkspaceSettings,
}: SidebarNavProps) {
const [collapsed, setCollapsed] = useState(false);
const [internalNav, setInternalNav] = useState("chats");
@@ -294,15 +328,25 @@ export default function SidebarNav({
<span className="sidebar-logo flex size-5 shrink-0 items-center justify-center text-ink">
<IconPopsicle2 size={18} />
</span>
- <span className="sidebar-copy ml-1.5 min-w-0 flex-1 truncate text-[14px] font-medium text-ink-2">
- {WORKSPACE.name}
+ <span className="sidebar-copy ml-1.5 min-w-0 flex-1 truncate text-[14px] font-medium text-ink-2" title={workspace?.path}>
+ {workspace?.name ?? WORKSPACE.name}
</span>
<span className="sidebar-copy ml-1 flex shrink-0 text-ink-3">
<IconChevronDownSmall size={16} />
</span>
</button>
- {workspaceOpen && <WorkspaceMenu position={workspacePosition} onClose={() => setWorkspaceOpen(false)} />}
+ {workspaceOpen && (
+ <WorkspaceMenu
+ position={workspacePosition}
+ current={workspace?.path}
+ rows={workspaces}
+ onSwitch={onSwitchWorkspace}
+ onNew={onNewWorkspace}
+ onSettings={onWorkspaceSettings}
+ onClose={() => setWorkspaceOpen(false)}
+ />
+ )}
<button
type="button"
@@ -322,7 +366,7 @@ export default function SidebarNav({
onClick={() => setCollapsed(false)}
className="sidebar-expand-control absolute left-2 top-0.5 flex size-9 items-center justify-center rounded-[8px] text-ink-3 transition-[opacity,background-color,color] duration-150 hover:bg-hover-2 hover:text-ink"
>
- <IconSidebarLeftArrow size={18} className="rotate-180" />
+ <IconSidebarLeftOpen size={18} />
</button>
</div>
@@ -450,10 +494,11 @@ export default function SidebarNav({
<button
type="button"
onClick={onFooterClick ?? onNewChat}
- className="flex h-8 w-full items-center justify-center gap-1.5 rounded-control bg-hover-2 text-[12.5px] font-medium text-ink transition-[background-color,transform] duration-150 hover:bg-line-strong active:scale-[0.98]"
+ title={footerTitle}
+ className="flex h-8 w-full items-center justify-center gap-1.5 rounded-control bg-hover-2 px-2 text-[12.5px] font-medium text-ink transition-[background-color,transform] duration-150 hover:bg-line-strong active:scale-[0.98]"
>
{footerIcon}
- {footerLabel}
+ <span className="min-w-0 flex-1 truncate text-center">{footerLabel}</span>
</button>
</div>
</div>
diff --git a/apps/native/components/site/ChatEmpty.tsx b/apps/native/components/site/ChatEmpty.tsx
index c11dc4ab..bd340334 100644
--- a/apps/native/components/site/ChatEmpty.tsx
+++ b/apps/native/components/site/ChatEmpty.tsx
@@ -39,6 +39,7 @@ export default function EmptyState({
modelKey,
onModelChange,
history,
+ cwd,
}: {
onSend: (text: string) => void;
health: Health | null;
@@ -49,7 +50,10 @@ export default function EmptyState({
onModelChange: (key: string) => void;
/** Earlier prompts for ArrowUp recall in the composer. */
history?: readonly string[];
+ /** This tab's workspace; absent, the server's default from `health`. */
+ cwd?: string;
}) {
+ const where = cwd ?? health?.cwd;
const shown = [0, 1, 2].map((i) => STARTER_PROMPTS[(offset + i) % STARTER_PROMPTS.length]);
const [stage, setStage] = useState(0);
useEffect(() => {
@@ -111,10 +115,10 @@ export default function EmptyState({
</button>
))}
<div className="mt-1 flex items-center gap-5 pl-0.5 text-[13px] text-ink-3">
- <span className="flex items-center gap-2 py-1" title={health?.cwd}>
+ <span className="flex items-center gap-2 py-1" title={where}>
<span className={`size-1.5 rounded-full ${health?.ok ? "bg-green" : "bg-orange"}`} />
{health?.ok
- ? `Connected · ${health.cwd ? (health.cwd.split("/").pop() ?? health.cwd) : "over ACP"}`
+ ? `Connected · ${where ? (where.split("/").pop() || where) : "over ACP"}`
: "Waiting for graff acp"}
</span>
<button type="button" onClick={shuffle} className="flex items-center gap-2 py-1 transition-colors duration-150 hover:text-ink">
diff --git a/apps/native/components/site/FilesPane.tsx b/apps/native/components/site/FilesPane.tsx
index f78e81ea..e1049f2a 100644
--- a/apps/native/components/site/FilesPane.tsx
+++ b/apps/native/components/site/FilesPane.tsx
@@ -132,9 +132,12 @@ function DiffView({ text }: { text: string }) {
}
export default function FilesPane({
+ root,
requested,
onClose,
}: {
+ /** The workspace to walk (the active tab's cwd); absent, the server default. */
+ root?: string;
/** A path the harness wants shown (e.g. a clicked tool chip), or the
* changes review when `changes` is set. */
requested?: { path: string; n: number; changes?: boolean } | null;
@@ -149,12 +152,12 @@ export default function FilesPane({
const loadChanges = useCallback(async () => {
try {
- setChanges(await gitChanges());
+ setChanges(await gitChanges(root));
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
- }, []);
+ }, [root]);
const openChangesView = useCallback(() => {
setView("changes");
@@ -164,7 +167,7 @@ export default function FilesPane({
const show = useCallback(async (path: string, keepView = false) => {
try {
- const res = await fsStat(path);
+ const res = await fsStat(path, root);
setError(null);
if (!keepView) {
setView("files");
@@ -179,11 +182,13 @@ export default function FilesPane({
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
- }, []);
+ }, [root]);
useEffect(() => {
// Preload the root listing without stealing the view — a Review click
- // can land before this resolves, and changes must win that race.
+ // can land before this resolves, and changes must win that race. A
+ // workspace switch re-runs this (new `show`) and lands on its root.
+ setFile(null);
void show("", true);
}, [show]);
@@ -195,12 +200,12 @@ export default function FilesPane({
const openFileDiff = useCallback(async (path: string) => {
try {
- setDiff({ path, text: await gitFileDiff(path) });
+ setDiff({ path, text: await gitFileDiff(path, root) });
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
- }, []);
+ }, [root]);
const here = file ? file.path : (dir?.path ?? "");
const crumbs = here ? here.split("/") : [];
@@ -236,8 +241,8 @@ export default function FilesPane({
</span>
)}
</button>
- <ActionButton label="Reveal" onClick={() => void fsReveal(here)} />
- {view === "files" && file && <ActionButton label="Open" onClick={() => void fsOpen(file.path)} />}
+ <ActionButton label="Reveal" onClick={() => void fsReveal(here, root)} />
+ {view === "files" && file && <ActionButton label="Open" onClick={() => void fsOpen(file.path, root)} />}
<button
type="button"
aria-label="Close files"
@@ -340,7 +345,7 @@ export default function FilesPane({
{isImage ? (
<figure>
<img
- src={fsRawUrl(file.path)}
+ src={fsRawUrl(file.path, root)}
alt={file.path}
className="max-w-full rounded-[10px] bg-inset shadow-hairline"
style={{ animation: "fade-in 250ms ease both" }}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 42a763b3..aba1f93e 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -27,14 +27,28 @@ import { isFollowingTail, pinScrollerTail } from "@/lib/follow-scroll";
import { dropQueuedPrompt, enqueuePrompt, shiftQueuedPrompt, type QueuedPrompt } from "@/lib/prompt-queue";
import { dateGroup, listSessions, loadSession, relativeTime, type StoredSession } from "@/lib/sessions";
import { loadHistory, mergeHistory, pushHistory, saveHistory } from "@/lib/prompt-history";
+import WorkspaceDialog from "@/components/site/WorkspaceDialog";
+import {
+ basename,
+ findWorkspace,
+ loadActiveWorkspace,
+ loadWorkspaces,
+ removeWorkspace,
+ saveActiveWorkspace,
+ saveWorkspaces,
+ shellQuote,
+ upsertWorkspace,
+ type Workspace,
+} from "@/lib/workspaces";
type Msg =
| { id: number; role: "user"; text: string }
| { id: number; role: "assistant"; turn: AssistantTurn };
/** `model` is what this tab's own agent was spawned with; the harness-level
- * model is only the default a new tab inherits. */
-type Chat = { id: number; title: string | null; messages: Msg[]; model?: string; session?: string };
+ * 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. */
+type Chat = { id: number; title: string | null; messages: Msg[]; model?: string; session?: string; cwd?: string };
function newPageToken(): string {
return Math.random().toString(36).slice(2, 10);
@@ -74,6 +88,16 @@ export default function GraffHarness() {
useEffect(() => {
setHistory(loadHistory(window.localStorage));
}, []);
+ // Workspaces are the folders graff runs in. The list and the active pick
+ // live in this browser; the server only validates a root it is handed.
+ // Refs mirror the state for the async paths (spawn, session list) that
+ // must not read a stale closure.
+ const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
+ const [activePath, setActivePath] = useState<string | null>(null);
+ const workspacesRef = useRef<Workspace[]>([]);
+ const activePathRef = useRef<string | null>(null);
+ const [dialog, setDialog] = useState<null | { mode: "new" } | { mode: "settings" }>(null);
+ const [copiedResume, setCopiedResume] = useState(false);
const chatIdRef = useRef(1);
const msgIdRef = useRef(0);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -132,8 +156,19 @@ export default function GraffHarness() {
const requireSession = async (chatId: number, reset = false, key?: string): Promise<string> => {
const live = sessionsRef.current.get(chatId);
if (!reset && live) return live;
- const spawnModel = key ?? chats.find((c) => c.id === chatId)?.model ?? model ?? undefined;
- const id = await ensureSession(handleOf(chatId), spawnModel, reset, sessionNamesRef.current.get(chatId));
+ const chat = chatsRef.current.find((c) => c.id === chatId);
+ // 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 spawnModel = key ?? chat?.model ?? ws?.model ?? model ?? undefined;
+ const id = await ensureSession(handleOf(chatId), {
+ model: spawnModel,
+ reset,
+ resume: sessionNamesRef.current.get(chatId),
+ cwd,
+ yolo: ws?.yolo,
+ });
sessionsRef.current.set(chatId, id);
setSessionIds((current) => ({ ...current, [chatId]: id }));
setHealth({ ok: true });
@@ -147,6 +182,20 @@ export default function GraffHarness() {
if (cancelled) return;
setHealth(h);
if (!h.ok) return;
+ // The server's default workspace is always a row; the remembered pick
+ // wins when it is still listed, else the default is active.
+ const root = h.cwd ?? "";
+ let list = loadWorkspaces(window.localStorage);
+ if (root && !findWorkspace(list, root)) list = upsertWorkspace(list, { path: root, name: basename(root) });
+ const remembered = loadActiveWorkspace(window.localStorage);
+ const active = findWorkspace(list, remembered)?.path ?? findWorkspace(list, root)?.path ?? list[0]?.path ?? null;
+ workspacesRef.current = list;
+ activePathRef.current = active;
+ setWorkspaces(list);
+ setActivePath(active);
+ saveWorkspaces(window.localStorage, list);
+ if (active) setChats((current) => current.map((c) => (c.id === 1 && !c.cwd ? { ...c, cwd: active } : c)));
+ void refreshStored();
try {
const session = newSessionName();
sessionNamesRef.current.set(1, session);
@@ -175,10 +224,11 @@ export default function GraffHarness() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- /** Re-read graff's session directory; tabs adopt the titles graff saved. */
+ /** Re-read the active workspace's session directory; tabs adopt the
+ * titles graff saved. */
const refreshStored = async () => {
try {
- const list = await listSessions();
+ const list = await listSessions(activePathRef.current ?? undefined);
setStored(list);
setChats((current) =>
current.map((c) => {
@@ -305,7 +355,9 @@ export default function GraffHarness() {
const openChat = (id: number) => {
const session = newSessionName();
sessionNamesRef.current.set(id, session);
- setChats((current) => [...current, { id, title: null, messages: [], model: model ?? undefined, session }]);
+ const cwd = activePathRef.current ?? undefined;
+ const ws = findWorkspace(workspacesRef.current, cwd);
+ setChats((current) => [...current, { id, title: null, messages: [], model: ws?.model ?? model ?? undefined, session, cwd }]);
setActiveId(id);
setFilesOpen(false);
setFollowing(true);
@@ -316,7 +368,10 @@ export default function GraffHarness() {
/** Open a saved graff session: its transcript renders from the file at once,
* and the tab's agent starts with `--resume` so a follow-up remembers it. */
const openStored = async (name: string) => {
- const existing = chats.find((c) => c.session === name);
+ // The sidebar lists the active workspace, so the session lives there;
+ // the same name in another workspace is a different conversation.
+ const cwd = activePathRef.current ?? undefined;
+ const existing = chats.find((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));
if (existing) {
setActiveId(existing.id);
setFilesOpen(false);
@@ -324,9 +379,9 @@ export default function GraffHarness() {
}
let loaded: Awaited<ReturnType<typeof loadSession>>;
try {
- loaded = await loadSession(name);
+ loaded = await loadSession(name, cwd);
} catch (err) {
- setHealth({ ok: true, detail: err instanceof Error ? err.message : String(err) });
+ setHealth((current) => ({ ...(current ?? { ok: true }), detail: err instanceof Error ? err.message : String(err) }));
return;
}
const id = (chatIdRef.current += 1);
@@ -334,7 +389,7 @@ export default function GraffHarness() {
sessionNamesRef.current.set(id, name);
setChats((current) => [
...current,
- { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name },
+ { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name, cwd },
]);
setActiveId(id);
setFilesOpen(false);
@@ -373,6 +428,77 @@ export default function GraffHarness() {
void openStored(id);
};
+ /* ── workspaces ── */
+
+ const persistWorkspaces = (list: Workspace[]) => {
+ workspacesRef.current = list;
+ setWorkspaces(list);
+ saveWorkspaces(window.localStorage, list);
+ };
+
+ const activate = (path: string | null) => {
+ activePathRef.current = path;
+ setActivePath(path);
+ saveActiveWorkspace(window.localStorage, path);
+ void refreshStored();
+ };
+
+ /** Switch the sidebar to a workspace and land on a tab that runs there:
+ * an empty tab of its own if one is open, else a fresh one. Tabs already
+ * running elsewhere keep their agents — a workspace is fixed at spawn. */
+ const switchWorkspace = (path: string) => {
+ if (path === activePathRef.current) return;
+ activate(path);
+ const empty = chatsRef.current.find((c) => c.cwd === path && c.messages.length === 0);
+ if (empty) {
+ setActiveId(empty.id);
+ setFilesOpen(false);
+ return;
+ }
+ openChat((chatIdRef.current += 1));
+ };
+
+ const addWorkspace = (path: string) => {
+ const list = upsertWorkspace(workspacesRef.current, { path, name: basename(path) });
+ persistWorkspaces(list);
+ setDialog(null);
+ const added = findWorkspace(list, path);
+ if (added) switchWorkspace(added.path);
+ };
+
+ const saveWorkspace = (ws: Workspace) => {
+ persistWorkspaces(upsertWorkspace(workspacesRef.current, ws));
+ setDialog(null);
+ };
+
+ /** Drop a workspace from the switcher (nothing on disk changes). If it
+ * was active, the next row — or the server default — takes over. */
+ const forgetWorkspace = (path: string) => {
+ const list = removeWorkspace(workspacesRef.current, path);
+ persistWorkspaces(list);
+ setDialog(null);
+ if (activePathRef.current === path) {
+ const next = list[0]?.path ?? health?.cwd ?? null;
+ if (next) switchWorkspace(next);
+ else activate(null);
+ }
+ };
+
+ /** The footer names the tab's own graff session; clicking it copies the
+ * command that continues the same conversation in a terminal. */
+ const copyResume = () => {
+ const name = chatThread.session;
+ if (!name || typeof navigator === "undefined" || !navigator.clipboard) return;
+ const cmd = chatThread.cwd ? `cd ${shellQuote(chatThread.cwd)} && graff --resume ${name}` : `graff --resume ${name}`;
+ void navigator.clipboard
+ .writeText(cmd)
+ .then(() => {
+ setCopiedResume(true);
+ window.setTimeout(() => setCopiedResume(false), 1400);
+ })
+ .catch(() => undefined);
+ };
+
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
@@ -400,7 +526,17 @@ export default function GraffHarness() {
hint: [s.model, relativeTime(s.updatedMs, now)].filter(Boolean).join(" · "),
}));
- const workspaceName = health?.cwd ? (health.cwd.split("/").pop() || health.cwd) : "workspace";
+ // The tab bar's folder chip is the *tab's* workspace; the sidebar's
+ // switcher is the *active* one (where new tabs open). They differ only
+ // after a switch, and each says so on hover.
+ const chatCwd = chatThread.cwd ?? health?.cwd;
+ const chatWorkspace = findWorkspace(workspaces, chatCwd);
+ const workspaceName = chatWorkspace?.name ?? (chatCwd ? basename(chatCwd) : "workspace");
+ const activeWorkspace = findWorkspace(workspaces, activePath);
+ const sidebarWorkspace = activeWorkspace ?? (activePath ? { path: activePath, name: basename(activePath) } : undefined);
+ const footerTitle = chatThread.session
+ ? `graff session ${chatThread.session}${sessionId ? ` · ACP ${sessionId}` : ""}${chatCwd ? ` · ${chatCwd}` : ""}\nClick to copy the command that resumes it in a terminal.`
+ : undefined;
const tabBar = (
<div className="flex h-11 shrink-0 items-center gap-1 overflow-x-auto border-b border-line px-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
@@ -448,7 +584,7 @@ export default function GraffHarness() {
type="button"
aria-pressed={filesOpen}
onClick={() => setFilesOpen((open) => !open)}
- title={health?.cwd ?? "Workspace files"}
+ title={chatCwd ?? "Workspace files"}
className={`flex h-7 items-center gap-1.5 rounded-[7px] px-2 text-[12px] font-medium transition-colors duration-100 ${
filesOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"
}`}
@@ -475,8 +611,14 @@ export default function GraffHarness() {
onNewChat={newChat}
activeNav={filesOpen ? "workspace" : "chats"}
onNavigate={(key) => setFilesOpen(key === "workspace")}
- footerLabel={sessionId ? `Session ${sessionId.slice(0, 8)}` : "Connecting…"}
- onFooterClick={() => undefined}
+ workspace={sidebarWorkspace}
+ workspaces={workspaces.map((w) => ({ path: w.path, name: w.name }))}
+ onSwitchWorkspace={switchWorkspace}
+ onNewWorkspace={() => setDialog({ mode: "new" })}
+ onWorkspaceSettings={() => setDialog(sidebarWorkspace ? { mode: "settings" } : { mode: "new" })}
+ footerLabel={copiedResume ? "Copied resume command" : (chatThread.session ?? "Connecting…")}
+ footerTitle={footerTitle}
+ onFooterClick={copyResume}
/>
<div className="flex min-w-0 flex-1 flex-col gap-2.5">
@@ -552,6 +694,7 @@ export default function GraffHarness() {
onSend={send}
health={health}
history={composerHistory}
+ cwd={chatThread.cwd}
offset={offset}
shuffle={() => setOffset((current) => (current + 3) % STARTER_PROMPTS.length)}
models={models}
@@ -562,7 +705,7 @@ export default function GraffHarness() {
)}
</section>
- {filesOpen && <FilesPane requested={fileRequest} onClose={() => setFilesOpen(false)} />}
+ {filesOpen && <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />}
{!filesOpen && active && paneTodos.length > 0 && (
<aside
@@ -586,6 +729,19 @@ export default function GraffHarness() {
)}
</div>
</div>
+
+ {dialog && (
+ <WorkspaceDialog
+ mode={dialog.mode}
+ workspace={dialog.mode === "settings" ? sidebarWorkspace : undefined}
+ startPath={activePath ?? health?.home ?? undefined}
+ models={models}
+ onClose={() => setDialog(null)}
+ onPick={addWorkspace}
+ onSave={saveWorkspace}
+ onForget={forgetWorkspace}
+ />
+ )}
</main>
);
}
diff --git a/apps/native/components/site/WorkspaceDialog.tsx b/apps/native/components/site/WorkspaceDialog.tsx
new file mode 100644
index 00000000..23ba21bd
--- /dev/null
+++ b/apps/native/components/site/WorkspaceDialog.tsx
@@ -0,0 +1,402 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { Switch } from "@/components/atoms/Switch";
+import type { PromptModel } from "@/components/primitives/PromptBar";
+import { browseFolders, fsReveal, type FolderListing } from "@/lib/fs-client";
+import { IconCrossSmall, IconFolder } from "@/lib/icons";
+import { basename, type Workspace } from "@/lib/workspaces";
+
+/* ─────────────────────────────────────────────────────────
+ * WORKSPACE DIALOG
+ * The two faces of the sidebar's workspace menu. "New workspace" walks
+ * the machine's folders one level at a time (or takes a typed path) and
+ * hands back the folder graff should run in. "Workspace settings" edits
+ * how new tabs in a workspace spawn: its name, default model and whether
+ * tools are auto-approved.
+ * ───────────────────────────────────────────────────────── */
+
+type Props = {
+ mode: "new" | "settings";
+ /** The workspace being edited (settings). */
+ workspace?: Workspace;
+ /** Where the folder picker opens (new). */
+ startPath?: string;
+ models: PromptModel[];
+ onClose: () => void;
+ onPick: (path: string) => void;
+ onSave: (ws: Workspace) => void;
+ onForget: (path: string) => void;
+};
+
+const FIELD =
+ "h-8 w-full rounded-[8px] bg-field px-2.5 text-[13px] text-ink shadow-hairline outline-none placeholder:text-ink-3 focus:bg-hover";
+
+function Frame({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape") onClose();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [onClose]);
+ return createPortal(
+ <div
+ className="fixed inset-0 z-[60] flex items-center justify-center p-4"
+ style={{ background: "color-mix(in oklab, var(--ink) 22%, transparent)", animation: "fade-in 160ms ease both" }}
+ onPointerDown={(event) => {
+ if (event.target === event.currentTarget) onClose();
+ }}
+ >
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-label={title}
+ className="flex w-full max-w-[560px] flex-col overflow-hidden rounded-[14px] bg-surface shadow-overlay"
+ style={{ maxHeight: "min(680px, calc(100dvh - 32px))", animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both" }}
+ >
+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-4">
+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-ink">{title}</span>
+ <button
+ type="button"
+ aria-label="Close"
+ onClick={onClose}
+ className="flex size-7 items-center justify-center rounded-[6px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"
+ >
+ <IconCrossSmall size={16} />
+ </button>
+ </div>
+ {children}
+ </div>
+ </div>,
+ document.body,
+ );
+}
+
+function Chip({ active, onClick, children }: { active?: boolean; onClick: () => void; children: ReactNode }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`h-6 shrink-0 rounded-full px-2 text-[11.5px] font-medium transition-colors ${
+ active ? "bg-hover-2 text-ink" : "bg-field text-ink-2 shadow-hairline hover:bg-hover hover:text-ink"
+ }`}
+ >
+ {children}
+ </button>
+ );
+}
+
+function GitBadge() {
+ return <span className="shrink-0 rounded-full bg-field px-1.5 font-mono text-[10px] text-ink-2 shadow-hairline">git</span>;
+}
+
+function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPick: (path: string) => void; onClose: () => void }) {
+ const [listing, setListing] = useState<FolderListing | null>(null);
+ const [typed, setTyped] = useState(startPath ?? "~");
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ // Only the newest navigation may land: a slow listing of a big folder
+ // must not overwrite the one the user has already moved on to.
+ const seq = useRef(0);
+ const go = useCallback(async (target: string) => {
+ const n = (seq.current += 1);
+ setBusy(true);
+ try {
+ const next = await browseFolders(target);
+ if (n !== seq.current) return;
+ setListing(next);
+ setTyped(next.path);
+ setError(null);
+ } catch (err) {
+ if (n !== seq.current) return;
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ if (n === seq.current) setBusy(false);
+ }
+ }, []);
+ useEffect(() => {
+ void go(startPath ?? "~");
+ }, [go, startPath]);
+
+ const crumbs = listing ? listing.path.split("/").filter(Boolean) : [];
+ const crumbPath = (i: number) => `/${crumbs.slice(0, i + 1).join("/")}`;
+ const home = listing?.home;
+ const repo = listing?.default;
+
+ return (
+ <>
+ <div className="flex shrink-0 flex-col gap-2 border-b border-line px-4 py-3">
+ <form
+ className="flex items-center gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void go(typed);
+ }}
+ >
+ <span className="flex size-5 shrink-0 items-center justify-center text-ink-2">
+ <IconFolder size={16} />
+ </span>
+ <input
+ value={typed}
+ onChange={(event) => setTyped(event.target.value)}
+ spellCheck={false}
+ autoFocus
+ aria-label="Folder path"
+ placeholder="/path/to/project"
+ className={`${FIELD} font-mono text-[12.5px]`}
+ />
+ <button
+ type="submit"
+ className="h-8 shrink-0 rounded-[8px] bg-hover-2 px-3 text-[12.5px] font-medium text-ink transition-colors hover:bg-line-strong"
+ >
+ Go
+ </button>
+ </form>
+ <div className="flex items-center gap-1.5 text-[11.5px] text-ink-3">
+ <Chip onClick={() => void go("~")} active={listing?.path === home}>
+ Home
+ </Chip>
+ {repo && (
+ <Chip onClick={() => void go(repo)} active={listing?.path === repo}>
+ {basename(repo)}
+ </Chip>
+ )}
+ <span className="ml-1 min-w-0 flex-1 truncate">Pick the folder graff should read and edit.</span>
+ </div>
+ </div>
+
+ <div className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-b border-line px-3 text-[12px] whitespace-nowrap text-ink-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ <button type="button" onClick={() => void go("/")} className="rounded px-1 py-0.5 font-medium transition-colors hover:bg-hover hover:text-ink">
+ /
+ </button>
+ {crumbs.map((seg, i) => (
+ <span key={crumbPath(i)} className="flex items-center gap-1">
+ {i > 0 && <span className="text-line-strong">/</span>}
+ <button
+ type="button"
+ onClick={() => void go(crumbPath(i))}
+ className={`rounded px-1 py-0.5 transition-colors hover:bg-hover hover:text-ink ${i === crumbs.length - 1 ? "font-medium text-ink" : ""}`}
+ >
+ {seg}
+ </button>
+ </span>
+ ))}
+ {listing?.git && (
+ <span className="ml-1">
+ <GitBadge />
+ </span>
+ )}
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto" style={{ minHeight: 200 }}>
+ {error && <p className="px-4 py-3 text-[12.5px] text-red">{error}</p>}
+ {listing && (
+ <div className="flex flex-col px-2 py-1.5">
+ {listing.parent && (
+ <button
+ type="button"
+ onClick={() => void go(listing.parent as string)}
+ className="flex h-8 items-center gap-2 rounded-[7px] px-2 text-left text-[13px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"
+ >
+ <span className="flex size-4 shrink-0 items-center justify-center">…</span>
+ <span>Up one level</span>
+ </button>
+ )}
+ {listing.entries.map((entry) => (
+ <div
+ key={entry.path}
+ className="group flex h-8 items-center gap-2 rounded-[7px] px-2 transition-colors duration-100 hover:bg-hover"
+ >
+ <button
+ type="button"
+ onClick={() => void go(entry.path)}
+ title={entry.path}
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ >
+ <span className={`flex size-4 shrink-0 items-center justify-center ${entry.git ? "text-accent-ink" : "text-ink-3"}`}>
+ <IconFolder size={14} />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-[13px] text-ink">{entry.name}</span>
+ </button>
+ {entry.git && <GitBadge />}
+ <button
+ type="button"
+ onClick={() => onPick(entry.path)}
+ className="h-6 shrink-0 rounded-[6px] px-1.5 text-[11.5px] font-medium text-ink-3 opacity-0 transition-[opacity,background-color,color] duration-100 group-hover:opacity-100 hover:bg-hover-2 hover:text-ink focus:opacity-100"
+ >
+ Use
+ </button>
+ </div>
+ ))}
+ {listing.entries.length === 0 && <p className="px-2 py-2 text-[12.5px] text-ink-3">No folders here</p>}
+ </div>
+ )}
+ </div>
+
+ <div className="flex shrink-0 items-center gap-2 border-t border-line px-4 py-3">
+ <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-ink-3" title={listing?.path}>
+ {listing?.path ?? ""}
+ </span>
+ <button
+ type="button"
+ onClick={onClose}
+ className="h-8 rounded-full px-3 text-[12.5px] font-medium text-ink-2 transition-colors hover:bg-hover hover:text-ink"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ disabled={listing === null || busy}
+ onClick={() => listing && onPick(listing.path)}
+ className="h-8 rounded-full bg-ink px-3.5 text-[12.5px] font-medium text-canvas transition-opacity hover:opacity-90 disabled:opacity-50"
+ >
+ Use this folder
+ </button>
+ </div>
+ </>
+ );
+}
+
+function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
+ return (
+ <label className="flex flex-col gap-1.5">
+ <span className="text-[12.5px] font-medium text-ink">{label}</span>
+ {children}
+ {hint && <span className="text-[11.5px] text-ink-3">{hint}</span>}
+ </label>
+ );
+}
+
+function SettingsForm({
+ workspace,
+ models,
+ onSave,
+ onForget,
+ onClose,
+}: {
+ workspace: Workspace;
+ models: PromptModel[];
+ onSave: (ws: Workspace) => void;
+ onForget: (path: string) => void;
+ onClose: () => void;
+}) {
+ const [name, setName] = useState(workspace.name);
+ const [model, setModel] = useState(workspace.model ?? "");
+ const [yolo, setYolo] = useState(workspace.yolo ?? true);
+ const [confirmForget, setConfirmForget] = useState(false);
+ const save = () => onSave({ ...workspace, name: name.trim() || basename(workspace.path), model: model || undefined, yolo });
+
+ return (
+ <>
+ <form
+ className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ save();
+ }}
+ >
+ <Field label="Name" hint="How the switcher and the tab bar label this folder.">
+ <input value={name} onChange={(event) => setName(event.target.value)} autoFocus className={FIELD} />
+ </Field>
+ <Field label="Folder" hint="graff's working directory. Sessions save to .graff/sessions inside it.">
+ <div className="flex items-center gap-2">
+ <span className="min-w-0 flex-1 truncate rounded-[8px] bg-inset px-2.5 py-1.5 font-mono text-[12px] text-ink-2 shadow-hairline" title={workspace.path}>
+ {workspace.path}
+ </span>
+ <button
+ type="button"
+ onClick={() => void fsReveal("", workspace.path)}
+ className="h-8 shrink-0 rounded-[8px] bg-hover-2 px-2.5 text-[12px] font-medium text-ink transition-colors hover:bg-line-strong"
+ >
+ Reveal
+ </button>
+ </div>
+ </Field>
+ <Field label="Default model" hint="What a new tab here spawns with. The composer's picker still changes it per tab.">
+ <select value={model} onChange={(event) => setModel(event.target.value)} className={FIELD}>
+ <option value="">Harness default</option>
+ {models.map((m) => (
+ <option key={m.key} value={m.key}>
+ {m.name}
+ {m.tag ? ` · ${m.tag}` : ""}
+ </option>
+ ))}
+ </select>
+ </Field>
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <div className="text-[12.5px] font-medium text-ink">Auto-approve tools</div>
+ <div className="mt-1 text-[11.5px] text-ink-3">
+ Runs <span className="font-mono text-ink-2">graff acp --yolo</span>: tools execute without asking. Off, tools are denied — the
+ native app has no approval prompt yet.
+ </div>
+ </div>
+ <Switch checked={yolo} onChange={setYolo} label="Auto-approve tools" />
+ </div>
+ <p className="text-[11.5px] text-ink-3">Changes apply to new tabs. A running tab keeps the agent it spawned with.</p>
+ </form>
+
+ <div className="flex shrink-0 items-center gap-2 border-t border-line px-4 py-3">
+ {confirmForget ? (
+ <>
+ <span className="min-w-0 truncate text-[12px] text-ink-2">Remove it from the switcher? Nothing on disk changes.</span>
+ <button
+ type="button"
+ onClick={() => onForget(workspace.path)}
+ className="h-8 shrink-0 rounded-full px-3 text-[12.5px] font-medium text-red transition-colors hover:bg-hover"
+ >
+ Forget
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirmForget(false)}
+ className="h-8 shrink-0 rounded-full px-3 text-[12.5px] font-medium text-ink-2 transition-colors hover:bg-hover hover:text-ink"
+ >
+ Keep
+ </button>
+ </>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setConfirmForget(true)}
+ className="h-8 rounded-full px-3 text-[12.5px] font-medium text-red transition-colors hover:bg-hover"
+ >
+ Forget workspace
+ </button>
+ )}
+ <span className="flex-1" />
+ <button
+ type="button"
+ onClick={onClose}
+ className="h-8 rounded-full px-3 text-[12.5px] font-medium text-ink-2 transition-colors hover:bg-hover hover:text-ink"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={save}
+ className="h-8 rounded-full bg-ink px-3.5 text-[12.5px] font-medium text-canvas transition-opacity hover:opacity-90"
+ >
+ Save
+ </button>
+ </div>
+ </>
+ );
+}
+
+export default function WorkspaceDialog({ mode, workspace, startPath, models, onClose, onPick, onSave, onForget }: Props) {
+ if (mode === "settings" && workspace) {
+ return (
+ <Frame title={`Workspace settings · ${workspace.name}`} onClose={onClose}>
+ <SettingsForm workspace={workspace} models={models} onSave={onSave} onForget={onForget} onClose={onClose} />
+ </Frame>
+ );
+ }
+ return (
+ <Frame title="New workspace" onClose={onClose}>
+ <FolderPicker startPath={startPath} onPick={onPick} onClose={onClose} />
+ </Frame>
+ );
+}
diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.ts
index 02bc9e3f..f553577f 100644
--- a/apps/native/lib/acp-client.ts
+++ b/apps/native/lib/acp-client.ts
@@ -2,7 +2,16 @@ import { parseRpcLine, type AcpUpdate, type JsonRpcLine } from "./acp";
const BASE = "/api/acp";
-export type Health = { ok: boolean; detail?: string; cwd?: string };
+export type Health = {
+ ok: boolean;
+ detail?: string;
+ /** The default workspace: where an agent runs when a tab names none. */
+ cwd?: string;
+ /** The user's home directory, the folder picker's starting point. */
+ home?: string;
+ /** The server's auto-approve default (`GRAFF_YOLO`). */
+ yolo?: boolean;
+};
/** Server-side key for a chat tab's own `graff acp` child: `<page>:<chat>`.
* The page half is minted per load so a reload never inherits the previous
@@ -63,10 +72,23 @@ export async function checkHealth(): Promise<Health> {
}
}
-/** `resume` names the graff session file the tab's agent autosaves to (and
- * restores from, when it already exists) — `graff acp --resume <name>`. */
-export async function ensureSession(chat: ChatHandle, model?: string, reset = false, resume?: string): Promise<string> {
- const res = await rpc(chat, "bootstrap", { model, reset, resume });
+export type SessionOpts = {
+ model?: string;
+ /** Respawn even if the live agent matches. */
+ reset?: boolean;
+ /** The graff session file the tab's agent autosaves to (and restores
+ * from, when it already exists) — `graff acp --resume <name>`. */
+ resume?: string;
+ /** The workspace to run in; absent, the server's default. */
+ cwd?: string;
+ /** Auto-approve tools; absent, the server's default. */
+ yolo?: boolean;
+};
+
+/** The tab's agent, spawned on first use and reused while it still matches
+ * the options; a changed model, workspace or approval mode respawns it. */
+export async function ensureSession(chat: ChatHandle, opts: SessionOpts = {}): Promise<string> {
+ const res = await rpc(chat, "bootstrap", opts);
const body = (await res.json()) as { sessionId?: string; error?: string };
if (!body.sessionId) throw new Error(body.error ?? "ACP session/new failed");
return body.sessionId;
diff --git a/apps/native/lib/fs-client.ts b/apps/native/lib/fs-client.ts
index 8243a101..506649ea 100644
--- a/apps/native/lib/fs-client.ts
+++ b/apps/native/lib/fs-client.ts
@@ -1,4 +1,7 @@
-/** Browser side of /api/fs — workspace listing, file reads, open/reveal. */
+/** Browser side of /api/fs, /api/git and /api/workspaces — workspace
+ * listing, file reads, open/reveal, the uncommitted-changes review and the
+ * folder browser. Every call takes the workspace `root` it is about; absent,
+ * the server's default workspace answers. */
const BASE = "/api/fs";
@@ -16,31 +19,38 @@ export type FsFile = {
text: string;
};
-export async function fsStat(path: string): Promise<FsDir | FsFile> {
- const res = await fetch(`${BASE}?path=${encodeURIComponent(path)}`, { cache: "no-store" });
+function query(params: Record<string, string | undefined>): string {
+ const q = new URLSearchParams();
+ for (const [k, v] of Object.entries(params)) if (v !== undefined) q.set(k, v);
+ const s = q.toString();
+ return s ? `?${s}` : "";
+}
+
+export async function fsStat(path: string, root?: string): Promise<FsDir | FsFile> {
+ const res = await fetch(`${BASE}${query({ path, root })}`, { cache: "no-store" });
const body = (await res.json()) as (FsDir | FsFile) & { error?: string };
if (!res.ok) throw new Error(body.error ?? `fs ${res.status}`);
return body;
}
-async function act(action: "open" | "reveal", path: string): Promise<void> {
+async function act(action: "open" | "reveal", path: string, root?: string): Promise<void> {
await fetch(BASE, {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ action, path }),
+ body: JSON.stringify({ action, path, root }),
}).catch(() => {});
}
/** Reveal in Finder. */
-export const fsReveal = (path: string) => act("reveal", path);
+export const fsReveal = (path: string, root?: string) => act("reveal", path, root);
/** Open with the default app (editor for code, Preview for images…). */
-export const fsOpen = (path: string) => act("open", path);
+export const fsOpen = (path: string, root?: string) => act("open", path, root);
export const IMAGE_RE = /\.(png|jpe?g|gif|webp|svg|ico|bmp|avif)$/i;
/** Byte URL for a workspace file — <img src=…> in the pane. */
-export const fsRawUrl = (path: string) => `${BASE}?path=${encodeURIComponent(path)}&raw=1`;
+export const fsRawUrl = (path: string, root?: string) => `${BASE}${query({ path, raw: "1", root })}`;
export function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
@@ -54,20 +64,41 @@ export type GitFile = { path: string; add: number; del: number; untracked: boole
export type GitChanges = { root: string; files: GitFile[]; totalAdd: number; totalDel: number };
-export async function gitChanges(): Promise<GitChanges> {
- const res = await fetch("/api/git", { cache: "no-store" });
+export async function gitChanges(root?: string): Promise<GitChanges> {
+ const res = await fetch(`/api/git${query({ root })}`, { cache: "no-store" });
const body = (await res.json()) as GitChanges & { error?: string };
if (!res.ok) throw new Error(body.error ?? `git ${res.status}`);
return body;
}
-export async function gitFileDiff(path: string): Promise<string> {
+export async function gitFileDiff(path: string, root?: string): Promise<string> {
const res = await fetch("/api/git", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ path }),
+ body: JSON.stringify({ path, root }),
});
const body = (await res.json()) as { diff?: string; error?: string };
if (!res.ok) throw new Error(body.error ?? `git ${res.status}`);
return body.diff ?? "";
}
+
+/* ── folder browser (New workspace) ── */
+
+export type FolderEntry = { name: string; path: string; git: boolean };
+
+export type FolderListing = {
+ path: string;
+ parent: string | null;
+ git: boolean;
+ home: string;
+ default: string;
+ entries: FolderEntry[];
+};
+
+/** One level of the machine's folders; `~` is the home directory. */
+export async function browseFolders(path: string): Promise<FolderListing> {
+ const res = await fetch(`/api/workspaces${query({ path })}`, { cache: "no-store" });
+ const body = (await res.json()) as FolderListing & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `workspaces ${res.status}`);
+ return body;
+}
diff --git a/apps/native/lib/server-root.ts b/apps/native/lib/server-root.ts
new file mode 100644
index 00000000..10661574
--- /dev/null
+++ b/apps/native/lib/server-root.ts
@@ -0,0 +1,42 @@
+import { existsSync, statSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+/** Server side of workspaces. Every API route that touches the disk — the
+ * ACP spawner, the session list, the files pane, git — resolves its root
+ * here, so a `root` the browser hands over is checked in exactly one place. */
+
+/** The workspace used when a request names none: the env pin, else the
+ * repo root above `apps/native`, else the dev server's own cwd. */
+export function defaultRoot(): string {
+ if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;
+ if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;
+ const fromApp = path.resolve(process.cwd(), "../..");
+ if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;
+ return process.cwd();
+}
+
+/** `~` and `~/x` mean the home directory; anything else is returned as is. */
+export function expandHome(p: string): string {
+ if (p === "~") return os.homedir();
+ if (p.startsWith("~/")) return path.join(os.homedir(), p.slice(2));
+ return p;
+}
+
+export type RootResolution = { root: string } | { error: string; status: number };
+
+/** A caller-chosen workspace root (`?root=` or `body.root`): absolute and
+ * an existing directory, normalised (no trailing slash) so path-escape
+ * checks can compare prefixes. Empty or missing means the default. */
+export function resolveRoot(raw: string | null | undefined): RootResolution {
+ if (raw === null || raw === undefined || raw.trim() === "") return { root: defaultRoot() };
+ const expanded = expandHome(raw.trim());
+ if (!path.isAbsolute(expanded)) return { error: "workspace root must be an absolute path", status: 400 };
+ const root = path.resolve(expanded);
+ try {
+ if (!statSync(root).isDirectory()) return { error: "workspace root is not a directory", status: 400 };
+ } catch {
+ return { error: `no such workspace directory: ${root}`, status: 404 };
+ }
+ return { root };
+}
diff --git a/apps/native/lib/sessions.ts b/apps/native/lib/sessions.ts
index f1c1a3d3..13726b64 100644
--- a/apps/native/lib/sessions.ts
+++ b/apps/native/lib/sessions.ts
@@ -25,15 +25,23 @@ export type TranscriptMsg =
const BASE = "/api/sessions";
-export async function listSessions(): Promise<StoredSession[]> {
- const res = await fetch(BASE, { cache: "no-store" });
+function withRoot(params: Record<string, string | undefined>): string {
+ const q = new URLSearchParams();
+ for (const [k, v] of Object.entries(params)) if (v !== undefined) q.set(k, v);
+ const s = q.toString();
+ return s ? `?${s}` : "";
+}
+
+/** Sessions saved under `<root>/.graff/sessions`; absent root = the default workspace. */
+export async function listSessions(root?: string): Promise<StoredSession[]> {
+ const res = await fetch(`${BASE}${withRoot({ root })}`, { cache: "no-store" });
if (!res.ok) throw new Error(`sessions → ${res.status}`);
const body = (await res.json()) as { sessions?: StoredSession[] };
return body.sessions ?? [];
}
-export async function loadSession(name: string): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {
- const res = await fetch(`${BASE}?name=${encodeURIComponent(name)}`, { cache: "no-store" });
+export async function loadSession(name: string, root?: string): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {
+ const res = await fetch(`${BASE}${withRoot({ name, root })}`, { cache: "no-store" });
if (!res.ok) {
const detail = await res.text().catch(() => "");
throw new Error(`session ${name} → ${res.status}: ${detail.slice(0, 200)}`);
diff --git a/apps/native/lib/workspaces.test.ts b/apps/native/lib/workspaces.test.ts
new file mode 100644
index 00000000..90335668
--- /dev/null
+++ b/apps/native/lib/workspaces.test.ts
@@ -0,0 +1,100 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import {
+ basename,
+ findWorkspace,
+ loadActiveWorkspace,
+ loadWorkspaces,
+ monogram,
+ removeWorkspace,
+ saveActiveWorkspace,
+ saveWorkspaces,
+ shellQuote,
+ upsertWorkspace,
+ type Workspace,
+} from "./workspaces.ts";
+
+function memoryStorage(seed: Record<string, string> = {}) {
+ const map = new Map(Object.entries(seed));
+ return {
+ getItem: (k: string) => map.get(k) ?? null,
+ setItem: (k: string, v: string) => void map.set(k, v),
+ removeItem: (k: string) => void map.delete(k),
+ dump: () => Object.fromEntries(map),
+ };
+}
+
+describe("basename / monogram", () => {
+ it("takes the last segment and survives trailing slashes", () => {
+ assert.equal(basename("/Users/me/repo"), "repo");
+ assert.equal(basename("/Users/me/repo/"), "repo");
+ assert.equal(basename("/"), "/");
+ });
+ it("badges on the first letter or digit", () => {
+ assert.equal(monogram("codegraff"), "C");
+ assert.equal(monogram(".hidden-thing"), "H");
+ assert.equal(monogram("2fast"), "2");
+ assert.equal(monogram(" "), "?");
+ });
+});
+
+describe("upsertWorkspace", () => {
+ it("adds a row, defaulting the name to the folder", () => {
+ const list = upsertWorkspace([], { path: "/a/b/", name: " " });
+ assert.deepEqual(list, [{ path: "/a/b", name: "b" }]);
+ });
+ it("updates in place when the path is already listed", () => {
+ const one: Workspace[] = [{ path: "/a/b", name: "b" }, { path: "/c", name: "c" }];
+ const next = upsertWorkspace(one, { path: "/a/b/", name: "Renamed", model: "grok-4.6", yolo: false });
+ assert.equal(next.length, 2);
+ assert.deepEqual(next[0], { path: "/a/b", name: "Renamed", model: "grok-4.6", yolo: false });
+ assert.equal(next[1].path, "/c");
+ });
+ it("caps from the oldest end", () => {
+ let list: Workspace[] = [];
+ for (let i = 0; i < 5; i += 1) list = upsertWorkspace(list, { path: `/w${i}`, name: "" }, 3);
+ assert.deepEqual(list.map((w) => w.path), ["/w2", "/w3", "/w4"]);
+ });
+ it("ignores an empty path", () => {
+ assert.deepEqual(upsertWorkspace([{ path: "/x", name: "x" }], { path: " ", name: "" }), [{ path: "/x", name: "x" }]);
+ });
+});
+
+describe("remove / find", () => {
+ const list: Workspace[] = [{ path: "/a", name: "a" }, { path: "/b", name: "b" }];
+ it("removes by normalised path", () => {
+ assert.deepEqual(removeWorkspace(list, "/a/"), [{ path: "/b", name: "b" }]);
+ });
+ it("finds by normalised path and tolerates null", () => {
+ assert.equal(findWorkspace(list, "/b/")?.name, "b");
+ assert.equal(findWorkspace(list, null), undefined);
+ assert.equal(findWorkspace(list, "/zzz"), undefined);
+ });
+});
+
+describe("storage", () => {
+ it("round-trips the list and drops junk rows", () => {
+ const store = memoryStorage();
+ saveWorkspaces(store, [{ path: "/a", name: "a", yolo: true }]);
+ assert.deepEqual(loadWorkspaces(store), [{ path: "/a", name: "a", yolo: true }]);
+ const junk = memoryStorage({ "graff.native.workspaces": JSON.stringify([{ nope: 1 }, { path: "/ok", name: "ok" }, { path: "/ok/", name: "dupe" }, 42]) });
+ assert.deepEqual(loadWorkspaces(junk), [{ path: "/ok", name: "dupe" }]);
+ assert.deepEqual(loadWorkspaces(memoryStorage({ "graff.native.workspaces": "{not json" })), []);
+ assert.deepEqual(loadWorkspaces(null), []);
+ });
+ it("remembers and forgets the active pick", () => {
+ const store = memoryStorage();
+ saveActiveWorkspace(store, "/a/b/");
+ assert.equal(loadActiveWorkspace(store), "/a/b");
+ saveActiveWorkspace(store, null);
+ assert.equal(loadActiveWorkspace(store), null);
+ });
+});
+
+describe("shellQuote", () => {
+ it("leaves plain paths alone and quotes the rest", () => {
+ assert.equal(shellQuote("/Users/me/repo"), "/Users/me/repo");
+ assert.equal(shellQuote("/Users/me/my repo"), "'/Users/me/my repo'");
+ assert.equal(shellQuote("/it's"), "'/it'\\''s'");
+ });
+});
diff --git a/apps/native/lib/workspaces.ts b/apps/native/lib/workspaces.ts
new file mode 100644
index 00000000..a43e4737
--- /dev/null
+++ b/apps/native/lib/workspaces.ts
@@ -0,0 +1,115 @@
+/** Workspaces the native app knows about: the folders graff runs in. The
+ * list and the active pick live in this browser (localStorage); the server
+ * only validates a root it is handed. Pure helpers here so the list rules
+ * are testable without a DOM. */
+
+export const WORKSPACES_KEY = "graff.native.workspaces";
+export const ACTIVE_WORKSPACE_KEY = "graff.native.workspace";
+export const WORKSPACES_MAX = 50;
+
+export type Workspace = {
+ /** Absolute directory — the row's identity. */
+ path: string;
+ /** Display name; defaults to the folder's basename. */
+ name: string;
+ /** Model new tabs in this workspace spawn with; unset = the harness pick. */
+ model?: string;
+ /** Auto-approve tools (`graff acp --yolo`); unset = the server's default. */
+ yolo?: boolean;
+};
+
+/** Last path segment: `/Users/me/repo/` → `repo`; `/` stays `/`. */
+export function basename(p: string): string {
+ const trimmed = p.replace(/\/+$/, "");
+ const last = trimmed.split("/").pop();
+ return last && last.length > 0 ? last : trimmed || "/";
+}
+
+/** One-letter badge for the switcher: first letter or digit, upper-cased. */
+export function monogram(name: string): string {
+ const ch = name.trim().replace(/^[^A-Za-z0-9]+/, "")[0] ?? name.trim()[0];
+ return (ch ?? "?").toUpperCase();
+}
+
+/** Trailing slashes are noise: `/a/b/` and `/a/b` are the same workspace. */
+export function normalizePath(p: string): string {
+ const t = p.trim();
+ return t.length > 1 ? t.replace(/\/+$/, "") : t;
+}
+
+/** Add or update a workspace; the path is its identity, so re-adding a
+ * folder updates its row in place instead of listing it twice. New rows
+ * go last; the list is capped from the oldest end. */
+export function upsertWorkspace(list: readonly Workspace[], ws: Workspace, max = WORKSPACES_MAX): Workspace[] {
+ const path = normalizePath(ws.path);
+ if (!path) return [...list];
+ const name = ws.name.trim() || basename(path);
+ const next: Workspace = { ...ws, path, name };
+ const idx = list.findIndex((w) => w.path === path);
+ const out = idx >= 0 ? list.map((w, i) => (i === idx ? { ...w, ...next } : w)) : [...list, next];
+ return out.length > max ? out.slice(out.length - max) : out;
+}
+
+export function removeWorkspace(list: readonly Workspace[], path: string): Workspace[] {
+ const p = normalizePath(path);
+ return list.filter((w) => w.path !== p);
+}
+
+export function findWorkspace(list: readonly Workspace[], path: string | null | undefined): Workspace | undefined {
+ if (!path) return undefined;
+ const p = normalizePath(path);
+ return list.find((w) => w.path === p);
+}
+
+type ReadStore = Pick<Storage, "getItem">;
+type WriteStore = Pick<Storage, "setItem" | "removeItem">;
+
+function isWorkspace(value: unknown): value is Workspace {
+ if (!value || typeof value !== "object") return false;
+ const rec = value as Record<string, unknown>;
+ return typeof rec.path === "string" && rec.path.length > 0 && typeof rec.name === "string";
+}
+
+export function loadWorkspaces(storage: ReadStore | null | undefined): Workspace[] {
+ try {
+ const raw = storage?.getItem(WORKSPACES_KEY);
+ if (!raw) return [];
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter(isWorkspace).reduce<Workspace[]>((acc, ws) => upsertWorkspace(acc, ws), []);
+ } catch {
+ return [];
+ }
+}
+
+export function saveWorkspaces(storage: WriteStore | null | undefined, list: readonly Workspace[]): void {
+ try {
+ storage?.setItem(WORKSPACES_KEY, JSON.stringify(list.slice(-WORKSPACES_MAX)));
+ } catch {
+ // Private mode or a full quota: the list is a convenience, never a failure.
+ }
+}
+
+export function loadActiveWorkspace(storage: ReadStore | null | undefined): string | null {
+ try {
+ const raw = storage?.getItem(ACTIVE_WORKSPACE_KEY);
+ return raw ? normalizePath(raw) : null;
+ } catch {
+ return null;
+ }
+}
+
+export function saveActiveWorkspace(storage: WriteStore | null | undefined, path: string | null): void {
+ try {
+ if (path) storage?.setItem(ACTIVE_WORKSPACE_KEY, normalizePath(path));
+ else storage?.removeItem(ACTIVE_WORKSPACE_KEY);
+ } catch {
+ // see saveWorkspaces
+ }
+}
+
+/** Shell-safe form of a path for the "continue in the terminal" command. */
+export function shellQuote(p: string): string {
+ if (/^[A-Za-z0-9_./~@:+=-]+$/.test(p)) return p;
+ return `'${p.replace(/'/g, "'\\''")}'`;
+}
diff --git a/apps/native/next.config.ts b/apps/native/next.config.ts
index 2b67d098..9b16116c 100644
--- a/apps/native/next.config.ts
+++ b/apps/native/next.config.ts
@@ -2,6 +2,9 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: { unoptimized: true },
+ // `npm run dev` is how the native app runs; Next's dev button defaults to
+ // the bottom-left corner, on top of the sidebar's session control.
+ devIndicators: { position: "bottom-right" },
experimental: {
optimizePackageImports: ["iconoir-react"],
},
diff --git a/apps/native/package.json b/apps/native/package.json
index bbd7075c..5bcd6909 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -10,7 +10,7 @@
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000",
"mock-serve": "node scripts/mock-serve.mjs",
"lint": "next lint",
- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts"
+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/workspaces.test.ts"
},
"dependencies": {
"@streamdown/code": "^1.1.1",