graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(native): cap the sidecar browser's memory, MCP toggle per workspace, pin editor fixes
justrachcd99d0ac7d9d
diff --git a/apps/native/README.md b/apps/native/README.mdindex f5d7d8f8..40662d16 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -91,8 +91,12 @@ server only validates a root it is handed) with the active one checked:level at a time, marks git roots, takes a typed or pasted path) andswitches 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.+ model new tabs spawn with, whether tools are auto-approved+ (`graff acp --yolo`), and whether each tab's agent starts the MCP+ servers from `~/.codegraff/mcp.json` (off runs it with `GRAFF_MCP_CONFIG`+ pointing at an empty config: with a typical config every tab otherwise+ costs a gigabyte or more of server processes). *Forget* removes it+ from the switcher only.- Switching workspaces changes the sidebar's session list and where newtabs open. A tab's agent is spawned in the workspace that was activewhen the tab opened and stays there — the folder chip in the tab bar@@ -110,7 +114,11 @@ opens a pane showing a live Chrome tab that belongs to the chat. It isover `/api/browser`; install Kuri (`curl -fsSL https://kuri.trilok.ai/download | sh`)or set `KURI_BIN`. Nothing runs until a pane is opened, and a browser thatsees no requests for `GRAFF_BROWSER_IDLE_MINS` (default 20, `0` = never) is-stopped again.+stopped again. Its footprint is capped: when Kuri and its Chrome tree pass+`GRAFF_BROWSER_MAX_RSS_MB` (default 3072, `0` = no cap) they are stopped+and the next request starts a fresh browser. Kuri is started with+`KURI_ALLOW_LOCAL=1` so dev servers on this machine open; a Kuri older+than that flag refuses localhost.- **Browse** forwards clicks, scrolling and typing to the page.- **Annotate** pins the element under a click, instantly: the page'sdiff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex 058f8400..b4d93e7c 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -1,5 +1,5 @@import { spawn, type ChildProcessByStdio } from "node:child_process";-import { existsSync } from "node:fs";+import { existsSync, mkdirSync, writeFileSync } from "node:fs";import os from "node:os";import path from "node:path";import type { Readable, Writable } from "node:stream";@@ -22,10 +22,24 @@ type Slot = {/** The workspace the agent was spawned in: its cwd, where its sessions save. */cwd: string;yolo: boolean;+ /** Whether the configured MCP servers were started with it. */+ mcp: boolean;};-type SpawnOpts = { model?: string; resume?: string; cwd: string; yolo: boolean };-type BootstrapOpts = { model?: string; reset?: boolean; resume?: string; cwd?: string; yolo?: boolean };+type SpawnOpts = { model?: string; resume?: string; cwd: string; yolo: boolean; mcp: boolean };+type BootstrapOpts = { model?: string; reset?: boolean; resume?: string; cwd?: string; yolo?: boolean; mcp?: boolean };++/** An empty MCP config graff accepts as "no servers" (`GRAFF_MCP_CONFIG`):+ * every chat's agent otherwise starts every server in ~/.codegraff/mcp.json,+ * a gigabyte or more of processes per tab with a typical config. */+function mcpOffPath(): string {+ const file = path.join(os.homedir(), ".codegraff", "native", "mcp-off.json");+ if (!existsSync(file)) {+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, '{"mcpServers":{}}\n');+ }+ return file;+}// 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@@ -97,7 +111,7 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {const child = spawn(graffBin(), args, {stdio: ["pipe", "pipe", "inherit"],cwd: opts.cwd,- env: process.env,+ env: opts.mcp ? process.env : { ...process.env, GRAFF_MCP_CONFIG: mcpOffPath() },});const slot: Slot = {child,@@ -108,6 +122,7 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {resume: opts.resume ?? null,cwd: opts.cwd,yolo: opts.yolo,+ mcp: opts.mcp,};child.on("exit", () => {if (slots.get(chat) === slot) slots.delete(chat);@@ -173,13 +188,15 @@ async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {(!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);+ (opts.yolo === undefined || live.yolo === opts.yolo) &&+ (opts.mcp === undefined || live.mcp === opts.mcp);if (!opts.reset && same) return live;const slot = spawnAgent(chat, {model: opts.model,resume: opts.resume,cwd: opts.cwd ?? defaultRoot(),yolo: opts.yolo ?? defaultYolo(),+ mcp: opts.mcp ?? true,});await rpc(slot, "initialize", { protocolVersion: 1, clientCapabilities: { fs: {} } });const created = (await rpc(slot, "session/new", { cwd: slot.cwd })) as {@@ -235,12 +252,14 @@ export async function POST(req: NextRequest) {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 mcp = typeof body.params?.mcp === "boolean" ? body.params.mcp : undefined;const slot = await bootstrap(chat, {model,reset: body.params?.reset === true,resume,cwd: cwdParam ? resolved.root : undefined,yolo,+ mcp,});return Response.json({ sessionId: slot.sessionId, cwd: slot.cwd });}diff --git a/apps/native/components/site/BrowserPane.tsx b/apps/native/components/site/BrowserPane.tsxindex 266abddc..777aeb76 100644--- a/apps/native/components/site/BrowserPane.tsx+++ b/apps/native/components/site/BrowserPane.tsx@@ -385,7 +385,17 @@ export default function BrowserPane({const pageH = info?.height ?? 1;const samePage = (p: BrowserPin) => !info || p.url === info.url;const editingPin = editing !== null ? (pins.find((p) => p.id === editing) ?? null) : null;- const editingAt = editingPin ? markerAt(editingPin, map) : null;+ // Anchor the note editor to the marker, but never unmount it while a pin is+ // being edited: a map refresh can report the marker off screen for one tick+ // (or the pin can really be scrolled away), and unmounting mid-typing drops+ // the input's focus and everything typed after it. Fall back to the pin's+ // last known point, clamped into the frame.+ const editingAt = editingPin+ ? (markerAt(editingPin, map) ?? { x: Math.min(pageW - 1, Math.max(0, editingPin.point.x)), y: Math.min(pageH - 1, Math.max(0, editingPin.point.y)) })+ : null;+ // Open the editor above the marker in the lower part of the frame so it is+ // not clipped by the frame's bottom edge or hidden behind the pin list.+ const editorAbove = !!editingAt && editingAt.y > pageH * 0.55;return (<aside@@ -537,7 +547,9 @@ export default function BrowserPane({className="absolute z-10 flex w-[280px] flex-col gap-1.5 rounded-[10px] bg-surface p-2 shadow-overlay"style={{left: `min(calc(${pct(editingAt.x, pageW)} + 14px), calc(100% - 290px))`,- top: `min(calc(${pct(editingAt.y, pageH)} + 14px), calc(100% - 110px))`,+ ...(editorAbove+ ? { bottom: `min(calc(100% - ${pct(editingAt.y, pageH)} + 14px), calc(100% - 110px))` }+ : { top: `min(calc(${pct(editingAt.y, pageH)} + 14px), calc(100% - 110px))` }),animation: "pop-in 160ms cubic-bezier(0.23,1,0.32,1) both",}}onSubmit={(e) => {diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex bef44df3..070ff211 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -180,6 +180,7 @@ export default function GraffHarness() {resume: sessionNamesRef.current.get(chatId),cwd,yolo: ws?.yolo,+ mcp: ws?.mcp,});sessionsRef.current.set(chatId, id);setSessionIds((current) => ({ ...current, [chatId]: id }));diff --git a/apps/native/components/site/WorkspaceDialog.tsx b/apps/native/components/site/WorkspaceDialog.tsxindex 23ba21bd..a7ca7c83 100644--- a/apps/native/components/site/WorkspaceDialog.tsx+++ b/apps/native/components/site/WorkspaceDialog.tsx@@ -285,8 +285,9 @@ function SettingsForm({const [name, setName] = useState(workspace.name);const [model, setModel] = useState(workspace.model ?? "");const [yolo, setYolo] = useState(workspace.yolo ?? true);+ const [mcp, setMcp] = useState(workspace.mcp ?? true);const [confirmForget, setConfirmForget] = useState(false);- const save = () => onSave({ ...workspace, name: name.trim() || basename(workspace.path), model: model || undefined, yolo });+ const save = () => onSave({ ...workspace, name: name.trim() || basename(workspace.path), model: model || undefined, yolo, mcp });return (<>@@ -335,6 +336,16 @@ function SettingsForm({</div><Switch checked={yolo} onChange={setYolo} label="Auto-approve tools" /></div>+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <div className="text-[12.5px] font-medium text-ink">Start MCP servers</div>+ <div className="mt-1 text-[11.5px] text-ink-3">+ Each chat's agent starts every MCP server in <span className="font-mono text-ink-2">~/.codegraff/mcp.json</span>, which can+ cost a gigabyte or more per tab. Off, the agent has its built-in tools only.+ </div>+ </div>+ <Switch checked={mcp} onChange={setMcp} label="Start MCP servers" />+ </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>diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsindex f553577f..f894e3c3 100644--- a/apps/native/lib/acp-client.ts+++ b/apps/native/lib/acp-client.ts@@ -83,6 +83,8 @@ export type SessionOpts = {cwd?: string;/** Auto-approve tools; absent, the server's default. */yolo?: boolean;+ /** Start the configured MCP servers with the agent; absent, yes. */+ mcp?: boolean;};/** The tab's agent, spawned on first use and reused while it still matchesdiff --git a/apps/native/lib/browser/kuri-supervisor.ts b/apps/native/lib/browser/kuri-supervisor.tsindex 8ce6dea7..87500a14 100644--- a/apps/native/lib/browser/kuri-supervisor.ts+++ b/apps/native/lib/browser/kuri-supervisor.ts@@ -19,6 +19,9 @@ export type KuriState = {lastUsedMs: number | null;bin: string | null;idleMs: number;+ /** Last measured RSS of Kuri and its Chrome tree (MB), and the cap. */+ rssMb: number | null;+ maxRssMb: number;};type Live = {@@ -28,6 +31,9 @@ type Live = {startedMs: number;lastUsedMs: number;idleTimer: NodeJS.Timeout | null;+ rssTimer: NodeJS.Timeout | null;+ /** Last measured RSS of Kuri and its Chrome tree, MB. */+ rssMb: number | null;ready: Promise<void>;};@@ -61,6 +67,69 @@ export function idleMs(): number {return Math.min(mins, 7 * 24 * 60) * 60_000;}+/** Resident memory (MB) the sidecar, Kuri plus its whole Chrome tree, may use+ * before it is stopped; the next request starts a fresh, small one. A headless+ * Chrome with a couple of tabs sits around 1.5 GB, so the default leaves room+ * for a heavy page without letting a leak run away. 0 disables the cap. */+export function maxRssMb(): number {+ const raw = process.env.GRAFF_BROWSER_MAX_RSS_MB;+ const mb = raw === undefined || raw === "" ? 3072 : Number(raw);+ if (!Number.isFinite(mb) || mb < 0) return 3072;+ return mb;+}++/** RSS of a process and everything under it, in MB; 0 where `ps` cannot say. */+export function treeRssMb(rootPid: number): number {+ if (process.platform === "win32") return 0;+ let out: ReturnType<typeof spawnSync>;+ try {+ out = spawnSync("ps", ["-axo", "pid=,ppid=,rss="], { encoding: "utf8", timeout: 2_000 });+ } catch {+ return 0;+ }+ if (out.status !== 0 || typeof out.stdout !== "string") return 0;+ const children = new Map<number, number[]>();+ const rss = new Map<number, number>();+ for (const line of out.stdout.split("\n")) {+ const [pid, ppid, kb] = line.trim().split(/\s+/).map(Number);+ if (!pid) continue;+ rss.set(pid, kb || 0);+ const list = children.get(ppid);+ if (list) list.push(pid);+ else children.set(ppid, [pid]);+ }+ let total = 0;+ const stack = [rootPid];+ while (stack.length) {+ const pid = stack.pop() as number;+ total += rss.get(pid) ?? 0;+ for (const child of children.get(pid) ?? []) stack.push(child);+ }+ return Math.round(total / 1024);+}++const RSS_CHECK_MS = 30_000;++/** Watch the sidecar's footprint while it runs and stop it past the cap. */+function armRssGuard(live: Live): void {+ const cap = maxRssMb();+ if (cap === 0 || !live.child.pid) return;+ const pid = live.child.pid;+ live.rssTimer = setInterval(() => {+ if (state.live !== live || live.child.exitCode !== null) {+ if (live.rssTimer) clearInterval(live.rssTimer);+ return;+ }+ const mb = treeRssMb(pid);+ live.rssMb = mb;+ if (mb > cap) {+ console.error(`[browser] the sidecar browser is using ${mb} MB (cap ${cap} MB, GRAFF_BROWSER_MAX_RSS_MB): stopping it; the next request starts a fresh one`);+ stopKuri();+ }+ }, RSS_CHECK_MS);+ live.rssTimer.unref();+}+function portFree(port: number): Promise<boolean> {return new Promise((resolve) => {const probe = net.createServer();@@ -178,6 +247,9 @@ async function spawnKuri(): Promise<{ port: number; token: string }> {STATE_DIR: path.join(STATE_DIR, "state"),KURI_API_TOKEN: token,KURI_NO_TELEMETRY: "1",+ // The pane exists to look at dev servers on this machine; Kuri blocks+ // localhost/private targets by default (SSRF guard for its crawler).+ KURI_ALLOW_LOCAL: "1",},// Kuri's own log goes to the dev server's terminal like the agents' do.stdio: ["ignore", "ignore", "inherit"],@@ -189,6 +261,8 @@ async function spawnKuri(): Promise<{ port: number; token: string }> {startedMs: Date.now(),lastUsedMs: Date.now(),idleTimer: null,+ rssTimer: null,+ rssMb: null,ready: Promise.resolve(),};next.ready = waitHealthy(port, token, child);@@ -196,6 +270,7 @@ async function spawnKuri(): Promise<{ port: number; token: string }> {const mine = state.live === next;if (mine) state.live = null;if (next.idleTimer) clearTimeout(next.idleTimer);+ if (next.rssTimer) clearInterval(next.rssTimer);// A Kuri that died on its own (not our stop) leaves its Chrome behind.if (mine) {console.error(`[browser] kuri exited unexpectedly (code=${code ?? "?"} signal=${signal ?? "none"}); the next request respawns it`);@@ -205,6 +280,7 @@ async function spawnKuri(): Promise<{ port: number; token: string }> {state.live = next;hookExit();armIdle(next);+ armRssGuard(next);try {await next.ready;} catch (err) {@@ -225,6 +301,7 @@ export function stopKuri(): void {if (!live) return;state.live = null;if (live.idleTimer) clearTimeout(live.idleTimer);+ if (live.rssTimer) clearInterval(live.rssTimer);try {live.child.kill("SIGTERM");} catch {@@ -256,6 +333,8 @@ export function kuriState(): KuriState {lastUsedMs: live?.lastUsedMs ?? null,bin: kuriBin(),idleMs: idleMs(),+ rssMb: live?.rssMb ?? null,+ maxRssMb: maxRssMb(),};}diff --git a/apps/native/lib/workspaces.ts b/apps/native/lib/workspaces.tsindex a43e4737..3885962a 100644--- a/apps/native/lib/workspaces.ts+++ b/apps/native/lib/workspaces.ts@@ -16,6 +16,9 @@ export type Workspace = {model?: string;/** Auto-approve tools (`graff acp --yolo`); unset = the server's default. */yolo?: boolean;+ /** Start the configured MCP servers with each chat's agent; unset = yes.+ * Off, the agent runs with `GRAFF_MCP_CONFIG` pointing at an empty config. */+ mcp?: boolean;};/** Last path segment: `/Users/me/repo/` → `repo`; `/` stays `/`. */diff --git a/plans/2026-09-03-browser-sidecar.md b/plans/2026-09-03-browser-sidecar.mdindex faab1ae1..0d36704d 100644--- a/plans/2026-09-03-browser-sidecar.md+++ b/plans/2026-09-03-browser-sidecar.md@@ -119,3 +119,31 @@ a later step.Frame polling too heavy on a laptop, or the pane too narrow to be useful at1:1, or the annotation block not moving the agent's behaviour in practice.Any of those, and the branch goes; the release branch is untouched.++## Memory profile (2026-09-04)++Sampled every 5 s over 14 minutes of real use on macOS: a demo landing page+served locally, opened in the pane, four elements pinned in Annotate mode,+the pins sent to graff, which edited the files and verified them against+the live tab through Kuri.++| process group | start | peak | notes |+|---|---|---|---|+| Kuri | 4 MB | 5 MB | flat |+| Kuri's Chrome tree | 1.4 GB | 1.7 GB | 10 processes for 3 tabs: 6 renderers, browser, GPU, utilities |+| `next dev` server | 4.9 GB | 5.5 GB | hours-old dev server; 60 s at 14 frames/s added 159 MB and idling 30 s gave back 501 MB, so frame polling is churn the GC reclaims, not a leak |+| `graff acp` (per chat) | ~100 MB | ~100 MB | |+| MCP servers (per chat) | 1.5 GB | 1.5 GB | 21 processes per agent: every server in `~/.codegraff/mcp.json` starts with every tab |++What changed because of it:++- `GRAFF_BROWSER_MAX_RSS_MB` (default 3072): the supervisor measures Kuri+ plus its Chrome tree every 30 s and stops it past the cap; the next+ request starts a fresh browser. `kuriState()` reports `rssMb`.+- Workspace setting **Start MCP servers**: off, each tab's agent gets+ `GRAFF_MCP_CONFIG` pointing at an empty config, the single biggest+ per-tab saving.+- Kuri: `KURI_ALLOW_LOCAL=1` (its SSRF guard refused localhost, which is+ the whole point of the pane), and the note editor stays mounted while a+ pin is edited and flips above low markers (a map refresh could unmount+ it mid-typing and lose the note).