Skip to content

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

Python

feat(gui): check saved cache compatibility before continuation

justrach5aed8d82572c
diff --git a/apps/native/app/api/sessions/route.ts b/apps/native/app/api/sessions/route.ts
index 7ca6cb91..a272e03d 100644
--- a/apps/native/app/api/sessions/route.ts
+++ b/apps/native/app/api/sessions/route.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync } from "node:fs";
import path from "node:path";
import { NextRequest } from "next/server";
import { resolveRoot } from "@/lib/server-root";
@@ -37,6 +37,12 @@ function parseScope(raw: string | null): ListScope {
return "all";
}
+function cacheWorkspaceMatches(saved: string | null, target: string): boolean | null {
+ if (!saved) return null;
+ try { return realpathSync(saved) === realpathSync(target); }
+ catch { return null; }
+}
+
export async function GET(req: NextRequest) {
// `?root=` is the workspace whose sessions are wanted (each workspace keeps
// its own .graff/sessions); absent, the agent's default workspace.
@@ -75,12 +81,15 @@ export async function GET(req: NextRequest) {
// payload as a snapshot with unknown execution (#839).
view: "snapshot",
execution: "unknown",
+ ...(req.nextUrl.searchParams.get("view") === "metadata"
+ ? { cacheWorkspaceMatches: cacheWorkspaceMatches(str(parsed.workspace) ?? str(header?.workspace), root) } : {}),
...(Array.isArray(parsed.todos) ? { todos: parsed.todos } : {}),
// The desktop never displayed raw provider history. Avoid allocating
// its tool bodies and image payloads again in Chromium just to drop them.
...(req.nextUrl.searchParams.get("view") === "transcript"
? { presentation: "transcript-v1", transcript: transcriptFromMessages(Array.isArray(parsed.messages) ? parsed.messages : [], str(parsed.model) ?? undefined, parsed.todos) }
- : { messages: Array.isArray(parsed.messages) ? parsed.messages : [] }),
+ : req.nextUrl.searchParams.get("view") === "metadata" ? {}
+ : { messages: Array.isArray(parsed.messages) ? parsed.messages : [] }),
});
} catch (err) {
return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 502 });
diff --git a/apps/native/components/site/ChatColumn.tsx b/apps/native/components/site/ChatColumn.tsx
index 9361ca7e..82bd734f 100644
--- a/apps/native/components/site/ChatColumn.tsx
+++ b/apps/native/components/site/ChatColumn.tsx
@@ -32,7 +32,7 @@ export default function ChatColumn({ thread, compact, following, register, onOpe
onOpenPath={onOpenPath} onReview={onReview} snapshot={thread.snapshot} />
<div data-chat-composer className={`shrink-0 bg-page px-4 ${compact ? "py-2" : "pt-3 pb-6 sm:px-8"}`}>
<div className="mx-auto max-w-[720px]">
- {thread.snapshot && thread.session ? <SavedSnapshot name={thread.session} cwd={thread.cwd}
+ {thread.snapshot && thread.session ? <SavedSnapshot name={thread.session} cwd={thread.cwd} model={prompt.modelKey}
onRefresh={onRefresh} onContinue={onContinue} /> : <>
{pins > 0 && <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">
<span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Pinned</span>
diff --git a/apps/native/components/site/SavedCacheCheck.tsx b/apps/native/components/site/SavedCacheCheck.tsx
new file mode 100644
index 00000000..5dd16760
--- /dev/null
+++ b/apps/native/components/site/SavedCacheCheck.tsx
@@ -0,0 +1,44 @@
+"use client";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { checkSavedCache, type CacheCheck } from "@/lib/saved-cache-check";
+
+export default function SavedCacheCheck({ name, cwd, model, disabled, onContinue }: {
+ name: string; cwd?: string; model?: string; disabled: boolean; onContinue: () => void;
+}) {
+ const key = JSON.stringify([name, cwd, model]);
+ const pending = useRef<AbortController | null>(null);
+ const [state, setState] = useState<{ key: string; result?: CacheCheck; error?: boolean; busy: boolean }>({ key, busy: true });
+ const run = useCallback(async (continueAfter: boolean, previous?: CacheCheck) => {
+ pending.current?.abort();
+ const controller = new AbortController(); pending.current = controller;
+ setState({ key, result: previous, busy: true });
+ try {
+ const result = await checkSavedCache(name, { cwd, model }, controller.signal);
+ if (controller.signal.aborted) return;
+ setState({ key, result, busy: false });
+ // If the freshly read save changes the assessment, show it before proceeding.
+ if (continueAfter && JSON.stringify(result) === JSON.stringify(previous)) onContinue();
+ } catch {
+ if (!controller.signal.aborted) setState({ key, busy: false, error: true });
+ }
+ }, [key, name, cwd, model, onContinue]);
+ const runRef = useRef(run); runRef.current = run;
+ useEffect(() => {
+ void runRef.current(false);
+ return () => pending.current?.abort();
+ }, [key]);
+ const current = state.key === key ? state : { key, busy: true };
+ return <div data-saved-cache-check className="mt-3 border-t border-line pt-3">
+ <p role="status" className="font-medium text-ink">{current.busy ? "Checking saved cache compatibility…" : current.error ? "Prompt cache check unavailable" : current.result?.summary}</p>
+ {current.result && <details className="mt-1">
+ <summary className="cursor-pointer">Check details</summary>
+ <ul className="mt-1 list-disc pl-4">{current.result.reasons.map(reason => <li key={reason}>{reason}</li>)}</ul>
+ <p className="mt-1">This checks saved settings only. Changes to instructions, tools, provider routing, or cache expiry cannot be verified here. Confirm reuse from provider-reported cache usage after a request.</p>
+ </details>}
+ {current.error && <p role="alert" className="mt-1 text-red">Could not read the save. Retry before continuing.</p>}
+ <div className="mt-2 flex gap-2">
+ <button type="button" disabled={disabled || current.busy} onClick={() => void run(false)} className="rounded-control px-3 py-1.5 hover:bg-hover disabled:opacity-50">Recheck cache</button>
+ <button type="button" data-continue-snapshot disabled={disabled || current.busy || !current.result} onClick={() => void run(true, current.result)} className="rounded-control bg-hover-2 px-3 py-1.5 text-ink disabled:opacity-50">Continue here</button>
+ </div>
+ </div>;
+}
diff --git a/apps/native/components/site/SavedSnapshot.tsx b/apps/native/components/site/SavedSnapshot.tsx
index 4178f784..7af88966 100644
--- a/apps/native/components/site/SavedSnapshot.tsx
+++ b/apps/native/components/site/SavedSnapshot.tsx
@@ -1,9 +1,10 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import SavedCacheCheck from "./SavedCacheCheck";
import { loadSession } from "@/lib/sessions";
-export default function SavedSnapshot({ name, cwd, onRefresh, onContinue }: {
- name: string; cwd?: string;
+export default function SavedSnapshot({ name, cwd, model, onRefresh, onContinue }: {
+ name: string; cwd?: string; model?: string;
onRefresh: (loaded: Awaited<ReturnType<typeof loadSession>>) => void;
onContinue: () => void;
}) {
@@ -31,7 +32,7 @@ export default function SavedSnapshot({ name, cwd, onRefresh, onContinue }: {
{error && <p role="alert" className="mt-2 text-red">Could not refresh the snapshot. Try again.</p>}
<div className="mt-3 flex flex-wrap gap-2">
<button type="button" data-refresh-snapshot disabled={refreshing} onClick={() => void refresh()} className="rounded-control px-3 py-1.5 hover:bg-hover disabled:opacity-50">{refreshing ? "Refreshing…" : "Refresh snapshot"}</button>
- <button type="button" data-continue-snapshot disabled={refreshing} onClick={onContinue} className="rounded-control bg-hover-2 px-3 py-1.5 text-ink disabled:opacity-50">Continue here</button>
</div>
+ <SavedCacheCheck name={name} cwd={cwd} model={model} disabled={refreshing} onContinue={onContinue} />
</section>;
}
diff --git a/apps/native/lib/saved-cache-check.test.ts b/apps/native/lib/saved-cache-check.test.ts
new file mode 100644
index 00000000..e2b15e93
--- /dev/null
+++ b/apps/native/lib/saved-cache-check.test.ts
@@ -0,0 +1,48 @@
+import { test, expect } from "bun:test";
+import { assessSavedCache, checkSavedCache } from "./saved-cache-check";
+
+test("matching saved settings never promise a cache hit", () => {
+ const result = assessSavedCache({ model: "demo", workspace: "/work/" }, { model: "demo", cwd: "/work" });
+ expect(result.status).toBe("unknown");
+ expect(result.summary).toContain("unverified");
+ expect(result.reasons).toEqual(["The selected model matches the save.", "The workspace matches the save."]);
+});
+
+test("model and workspace changes flag risk; absent legacy metadata stays unknown", () => {
+ expect(assessSavedCache({ model: "old", workspace: "/work" }, { model: "new", cwd: "/work" }).status).toBe("changed");
+ expect(assessSavedCache({ model: "demo", workspace: "/old" }, { model: "demo", cwd: "/new" }).status).toBe("changed");
+ const legacy = assessSavedCache({ model: null }, {});
+ expect(legacy.status).toBe("unknown");
+ expect(legacy.reasons).toEqual(["Model comparison unavailable.", "Workspace comparison unavailable."]);
+});
+
+test("preflight reads uncached metadata with cancellation and never bootstraps an agent", async () => {
+ const original = globalThis.fetch;
+ const controller = new AbortController();
+ const calls: string[] = [];
+ globalThis.fetch = (async (url, options) => {
+ calls.push(String(url));
+ expect(options?.cache).toBe("no-store");
+ expect(options?.signal).toBe(controller.signal);
+ const parsed = new URL(String(url), "http://localhost");
+ expect(parsed.pathname).toBe("/api/sessions");
+ expect(parsed.searchParams.get("view")).toBe("metadata");
+ expect(parsed.searchParams.get("name")).toBe("saved");
+ expect(parsed.searchParams.get("root")).toBe("/work");
+ return Response.json({ model: "demo", workspace: "/work" });
+ }) as typeof fetch;
+ try {
+ expect((await checkSavedCache("saved", { model: "demo", cwd: "/work" }, controller.signal)).status).toBe("unknown");
+ expect(calls.length).toBe(1);
+ globalThis.fetch = (async () => new Response("missing", { status: 404 })) as typeof fetch;
+ await expect(checkSavedCache("saved", {})).rejects.toThrow("Could not read");
+ } finally { globalThis.fetch = original; }
+});
+
+
+test("server-resolved workspace identity overrides spelling; unavailable identity is not a mismatch", () => {
+ expect(assessSavedCache({ model: "demo", workspace: "/private/tmp/work", cacheWorkspaceMatches: true }, { model: "demo", cwd: "/tmp/work" }).status).toBe("unknown");
+ const missing = assessSavedCache({ model: "demo", workspace: "/gone", cacheWorkspaceMatches: null }, { model: "demo", cwd: "/work" });
+ expect(missing.status).toBe("unknown");
+ expect(missing.reasons).toContain("Workspace comparison unavailable.");
+});
diff --git a/apps/native/lib/saved-cache-check.ts b/apps/native/lib/saved-cache-check.ts
new file mode 100644
index 00000000..ec937cb4
--- /dev/null
+++ b/apps/native/lib/saved-cache-check.ts
@@ -0,0 +1,32 @@
+import type { StoredSession } from "./sessions";
+
+export type CacheCheck = { status: "changed" | "unknown"; summary: string; reasons: string[] };
+const normalized = (path: string) => path.replace(/\/+$/, "") || "/";
+
+/** Local compatibility only. Matching metadata cannot prove provider cache retention
+ * or equality of the actual system prompt, tool schemas, or request prefix. */
+export function assessSavedCache(saved: Pick<StoredSession, "model" | "workspace"> & { cacheWorkspaceMatches?: boolean | null }, target: { model?: string; cwd?: string }): CacheCheck {
+ const reasons: string[] = [];
+ let changed = false;
+ if (!saved.model || !target.model) reasons.push("Model comparison unavailable.");
+ else if (saved.model !== target.model) {
+ changed = true; reasons.push("The selected model differs from the saved model.");
+ } else reasons.push("The selected model matches the save.");
+ const workspaceMatches = saved.cacheWorkspaceMatches === undefined
+ ? (saved.workspace && target.cwd ? normalized(saved.workspace) === normalized(target.cwd) : null)
+ : saved.cacheWorkspaceMatches;
+ if (workspaceMatches === null) reasons.push("Workspace comparison unavailable.");
+ else if (!workspaceMatches) {
+ changed = true; reasons.push("The workspace differs; prompt context and cache routing may change.");
+ } else reasons.push("The workspace matches the save.");
+ return { status: changed ? "changed" : "unknown", summary: changed ? "Prompt cache: reuse at risk" : "Prompt cache: reuse unverified", reasons };
+}
+
+/** Read a fresh save without bootstrapping an agent or sending a model prompt. */
+export async function checkSavedCache(name: string, target: { model?: string; cwd?: string }, signal?: AbortSignal): Promise<CacheCheck> {
+ const params = new URLSearchParams({ name, view: "metadata" });
+ if (target.cwd) params.set("root", target.cwd);
+ const response = await fetch(`/api/sessions?${params}`, { cache: "no-store", signal });
+ if (!response.ok) throw new Error("Could not read the saved conversation.");
+ return assessSavedCache(await response.json() as StoredSession, target);
+}
diff --git a/apps/native/lib/session-projection.test.ts b/apps/native/lib/session-projection.test.ts
index 558173d4..7168ae5c 100644
--- a/apps/native/lib/session-projection.test.ts
+++ b/apps/native/lib/session-projection.test.ts
@@ -1,5 +1,5 @@
import { test, expect } from "bun:test";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { NextRequest } from "next/server";
@@ -186,3 +186,32 @@ test("#912: generated notices survive raw and projected loads without claiming m
}
} finally { file.cleanup(); }
});
+
+
+test("cache preflight metadata reads omit the transcript without changing raw session responses", async () => {
+ const file = fixture();
+ try {
+ const response = await GET(new NextRequest(file.url("metadata")));
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body.model).toBe("demo");
+ expect(body.workspace).toBe(file.root);
+ expect(body.messages).toBeUndefined();
+ expect(body.transcript).toBeUndefined();
+ expect(body.execution).toBe("unknown");
+ } finally { file.cleanup(); }
+});
+
+
+test("cache workspace comparison resolves aliases and leaves missing saved paths unknown", async () => {
+ const file = fixture();
+ try {
+ const alias = path.join(file.root, "alias");
+ symlinkSync(file.root, alias);
+ for (const [workspace, expected] of [[alias, true], [undefined, null], [path.join(file.root, "missing"), null]] as const) {
+ writeFileSync(path.join(file.root, ".graff/sessions/example.session.json"), JSON.stringify({ model: "demo", messages: raw, workspace }));
+ const body = await (await GET(new NextRequest(file.url("metadata")))).json();
+ expect(body.cacheWorkspaceMatches).toBe(expected);
+ }
+ } finally { file.cleanup(); }
+});
diff --git a/docs/adr/0099-gui-saved-sessions-are-snapshots.md b/docs/adr/0099-gui-saved-sessions-are-snapshots.md
index d42d5090..0d5ae1a8 100644
--- a/docs/adr/0099-gui-saved-sessions-are-snapshots.md
+++ b/docs/adr/0099-gui-saved-sessions-are-snapshots.md
@@ -35,6 +35,11 @@ The GUI renders these as expandable session notices and excludes them from promp
recall and title recovery. Text prefixes are not evidence of notification origin;
older unmarked job notices retain their historical presentation.
+Before enabling continuation, the GUI reads fresh saved metadata and compares
+the selected model and workspace. Changes flag cache reuse as at risk; matching
+metadata remains unverified. No agent or model request is started by this check.
+Saved settings cannot establish prefix equality or provider cache retention.
+
## Consequences
Opening and refreshing history never bootstrap an ACP session. The composer