graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: recover project navigation and review failures
Rach Pradhan668864f2a1eb
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.ymlindex 73016f93..41eab4a7 100644--- a/.github/workflows/desktop.yml+++ b/.github/workflows/desktop.yml@@ -22,4 +22,6 @@ jobs:- run: bun install --frozen-lockfile- run: bun run test:desktop- run: bun run build+ - run: bun run test:projects+ - run: bun run test:stress- run: bun build electron/updater-runtime.cjs --target=node --format=cjs --external electron --outfile /tmp/updater-runtime.cjsdiff --git a/apps/native/README.md b/apps/native/README.mdindex e6f131f9..1ecbc974 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -203,6 +203,12 @@ collapsed; expanded groups page their rows, and large output previews preservethe beginning and end with an explicit omission marker. Older messages load onrequest. These bounds limit rendering; they do not cap stored conversation size.+For a focused pass, `bun run test:projects` covers folder selection, conversation+and review recovery, navigation, terminals, and browser previews. `bun run+test:stress` covers long transcripts and tool output without changing macOS+Spaces. The full `test:visual` suite additionally checks native fullscreen+transitions; the stress results explicitly report fullscreen as not run.+For a separate, opt-in real coding trial, run `electron/gui-coding-smoke.cjs` withthe package's Electron executable. It uses configured credentials in a disposableworkspace, checks the resulting code independently with Bun, then runs `/compact`.diff --git a/apps/native/components/site/ChangesPane.tsx b/apps/native/components/site/ChangesPane.tsxindex 41c1df44..c2856fff 100644--- a/apps/native/components/site/ChangesPane.tsx+++ b/apps/native/components/site/ChangesPane.tsx@@ -26,25 +26,30 @@ export default function ChangesPane({ root, onClose }: { root?: string; onClose(const [wrap, setWrap] = useState(true);const [revision, setRevision] = useState(0);const [loading, setLoading] = useState(true);+ const identity = useRef("");useEffect(() => { setWorkspace(root); setSelected(""); }, [root]);useEffect(() => {setLoading(true);+ setDiff(""); setError("");+ const nextIdentity = JSON.stringify([workspace, scope]);+ if (identity.current !== nextIdentity) { identity.current = nextIdentity; setState(null); }let stopped = false, timer: ReturnType<typeof setTimeout>;const refresh = async () => {if (document.visibilityState === "hidden") { timer = setTimeout(refresh, 5000); return; }+ let listed = false;try {const query = new URLSearchParams({ scope, ...(workspace ? { root: workspace } : {}) });const response = await fetch(`/api/git?${query}`, { cache: "no-store" });- const data = await response.json(); if (!response.ok) throw Error(data.error);- if (stopped) return; setState(data); setError("");+ const data = await response.json(); if (!response.ok) throw Error(data.error || `Could not load changes (${response.status}).`);+ if (stopped) return; setState(data); setError(""); listed = true;const file = data.files.some((row: { path: string }) => row.path === selectedRef.current) ? selectedRef.current : data.files[0]?.path || "";if (file !== selectedRef.current) setSelected(file);if (file) {const reply = await fetch('/api/git', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ root: workspace, path: file, scope }) });- const content = await reply.json(); if (!reply.ok) throw Error(content.error);+ const content = await reply.json(); if (!reply.ok) throw Error(content.error || `Could not load the diff (${reply.status}).`);if (!stopped && file === selectedRef.current) setDiff(content.diff);} else setDiff("");- } catch (err) { if (!stopped) setError(err instanceof Error ? err.message : String(err)); }+ } catch (err) { if (!stopped) { setError(err instanceof Error ? err.message : String(err)); setDiff(""); if (!listed) setState(null); } }finally { if (!stopped) { setLoading(false); timer = setTimeout(refresh, 5000); } }};void refresh(); return () => { stopped = true; clearTimeout(timer); };@@ -63,7 +68,7 @@ export default function ChangesPane({ root, onClose }: { root?: string; onClose(<strong className="text-[13px] font-medium">Changes</strong><span className="rounded-md bg-hover px-1.5 py-0.5 text-[10px] tabular-nums text-ink-3">{files.length}</span><div className="min-w-0 flex-1 truncate pl-1 text-[11px] text-ink-3" title={state?.branch}>{state?.branch}</div>- <span className="size-1.5 shrink-0 rounded-full bg-green/70" title="Refreshes every five seconds while visible" aria-label="Live updates" />+ <span className={`size-1.5 shrink-0 rounded-full ${error ? "bg-orange" : "bg-green/70"}`} title={error ? "Updates unavailable; retrying every five seconds" : "Refreshes every five seconds while visible"} aria-label={error ? "Updates unavailable" : "Live updates"} /><button className={button} title="Refresh changes" aria-label="Refresh changes" onClick={() => setRevision(value => value + 1)}><Icon kind="refresh" /></button><button className={button} title="Close changes" aria-label="Close changes" onClick={onClose}><Icon kind="close" /></button></header>@@ -77,7 +82,7 @@ export default function ChangesPane({ root, onClose }: { root?: string; onClose(</div><button aria-label="Show recent commits" title="Recent commits" aria-pressed={history} onClick={() => setHistory(!history)} className={`${button} ${history ? "bg-hover text-ink" : ""}`}><Icon kind="history" /></button></div>- {error && <p role="alert" className="border-b border-line px-3 py-2 text-xs text-red">{error}</p>}+ {error && <p role="alert" className="border-b border-line px-3 py-2 text-xs text-red">{error}<button type="button" onClick={() => setRevision(value => value + 1)} className="ml-2 rounded px-2 py-1 underline">Retry</button></p>}{history && <div className="max-h-44 shrink-0 overflow-auto border-b border-line px-3 py-2">{state?.commits.length ? state.commits.map(commit => <div key={commit.hash} className="py-1.5 text-xs"><div className="truncate text-ink-2" title={commit.subject}>{commit.subject}</div><div className="mt-0.5 text-[10px] text-ink-3"><code>{commit.hash}</code> · {commit.author}</div></div>) : <p className="py-2 text-xs text-ink-3">No commits yet.</p>}</div>}{files.length > 0 && <div className="flex h-11 shrink-0 items-center gap-1.5 border-b border-line px-2"><button className={`${button} ${showFiles ? "bg-hover" : ""}`} title="Toggle file list" aria-label="Toggle changed file list" aria-pressed={showFiles} onClick={() => setShowFiles(!showFiles)}><Icon kind="files" /></button>@@ -91,9 +96,9 @@ export default function ChangesPane({ root, onClose }: { root?: string; onClose(<div className={styles.body}>{showFiles && files.length > 0 && <nav aria-label="Changed files" className={styles.files}><input aria-label="Filter changed files" placeholder="Find a file…" value={filter} onChange={event => setFilter(event.target.value)} className="mb-2 w-full rounded-md border border-line bg-field px-2 py-1.5 text-xs outline-accent" />{!filteredFiles.length && <p className="px-2 py-3 text-xs text-ink-3">No matching files.</p>}{filteredFiles.map(file => <button key={file.path} onClick={() => choose(file.path)} title={file.path} className={`mb-0.5 flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-xs ${file.path === selected ? "bg-hover text-ink" : "text-ink-3 hover:bg-hover"}`}><span className="min-w-0 flex-1"><span className="block truncate">{file.path.split('/').pop()}</span>{file.path.includes("/") && <span className="mt-0.5 block truncate font-mono text-[9px] text-ink-3">{file.path.slice(0, file.path.lastIndexOf("/"))}</span>}</span><span className="text-[9px]">{file.untracked ? "NEW" : file.status.trim()}</span></button>)}</nav>}<section ref={viewport} aria-label="File diff" aria-busy={loading} className="min-h-0 min-w-0 flex-1 overflow-auto">- {rows.length ? <ReviewDiff rows={rows} wrap={wrap} /> : <div className="flex min-h-40 h-full flex-col items-center justify-center gap-2 px-8 text-center"><span className="text-sm text-ink-2">{loading ? "Loading changes…" : selected ? "No text changes to display" : "Working tree is clean"}</span><p className="max-w-60 text-xs leading-relaxed text-ink-3">{loading ? "" : selected ? "Binary files and metadata-only changes have no line diff." : "Edits in this workspace will appear here automatically."}</p></div>}+ {rows.length ? <ReviewDiff rows={rows} wrap={wrap} /> : <div className="flex min-h-40 h-full flex-col items-center justify-center gap-2 px-8 text-center"><span className="text-sm text-ink-2">{loading ? "Loading changes…" : error ? "Changes unavailable" : selected ? "No text changes to display" : "Working tree is clean"}</span><p className="max-w-60 text-xs leading-relaxed text-ink-3">{loading ? "" : error ? "Retry to read this folder’s current changes." : selected ? "Binary files and metadata-only changes have no line diff." : "Edits in this workspace will appear here automatically."}</p></div>}</section></div>- {selected && <ReviewActions diff={diff} path={selected} root={workspace} viewport={viewport} count={rows.slice(0, 12000).filter(row => row.kind === "hunk").length} />}+ {file && !error && !loading && <ReviewActions diff={diff} path={selected} root={workspace} viewport={viewport} count={rows.slice(0, 12000).filter(row => row.kind === "hunk").length} />}</aside></ResizableReviewPane>;}diff --git a/apps/native/components/site/ConversationsPane.tsx b/apps/native/components/site/ConversationsPane.tsxindex 11e7a974..454a8bbb 100644--- a/apps/native/components/site/ConversationsPane.tsx+++ b/apps/native/components/site/ConversationsPane.tsx@@ -45,7 +45,8 @@ export default function ConversationsPane({const [total, setTotal] = useState(0);const [loading, setLoading] = useState(true);const [loadingMore, setLoadingMore] = useState(false);- const [error, setError] = useState<string | null>(null);+ const [error, setError] = useState<{ message: string; more: boolean } | null>(null);+ const [reload, setReload] = useState(0);const sentinelRef = useRef<HTMLDivElement>(null);const generation = useRef(0);const q = useDebounced(query);@@ -53,6 +54,7 @@ export default function ConversationsPane({useEffect(() => {let cancelled = false; generation.current++;setLoading(true); setLoadingMore(false);+ setRows([]); setCursor(null); setTotal(0);setError(null);void listSessionsPage({ limit: PAGE, q, scope, root }).then((page) => {@@ -62,15 +64,16 @@ export default function ConversationsPane({setTotal(page.total);}).catch((err: unknown) => {- if (!cancelled) setError(err instanceof Error ? err.message : String(err));+ if (!cancelled) setError({ message: `Could not load conversations. ${err instanceof Error ? err.message : String(err)}`, more: false });}).finally(() => {if (!cancelled) setLoading(false);});return () => {cancelled = true;+ generation.current++;};- }, [q, scope, root]);+ }, [q, scope, root, reload]);useEffect(() => {const el = sentinelRef.current;@@ -93,7 +96,7 @@ export default function ConversationsPane({setCursor(page.nextCursor);setTotal(page.total);})- .catch(() => { if (request === generation.current) setError("Could not load more conversations. Choose Retry to try again."); })+ .catch(() => { if (request === generation.current) setError({ message: "Could not load more conversations.", more: true }); }).finally(() => { if (request === generation.current) setLoadingMore(false); });},{ rootMargin: "160px" },@@ -103,10 +106,10 @@ export default function ConversationsPane({}, [cursor, loading, loadingMore, q, scope, root, error]);const groups = groupSessions(rows);- const empty = !loading && rows.length === 0;+ const empty = !loading && !error && rows.length === 0;return (- <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex min-h-0 flex-1 flex-col" data-conversation-library><header className="shrink-0 border-b border-line px-5 pt-5 pb-4 sm:px-8"><div className="mx-auto flex w-full max-w-[720px] flex-col gap-4"><div className="flex items-end justify-between gap-4">@@ -114,12 +117,12 @@ export default function ConversationsPane({<h1 className="text-[22px] font-medium tracking-[-0.02em] text-ink">Conversations</h1>{root && <p className="mt-1 break-all font-mono text-xs text-ink-3" data-conversation-project>{root}</p>}<p className="mt-0.5 text-[12.5px] text-ink-3">- {loading && rows.length === 0+ {loading? "Reading saved sessions…": total === 1? "1 saved session": `${total.toLocaleString()} saved sessions`}- {scope === "elsewhere" ? " from other workspaces" : scope === "local" ? " in this workspace" : " · this workspace and home"}+ {scope === "elsewhere" ? " from other folders" : scope === "local" ? " in this project" : " · this project and home"}</p></div>{onNewChat && (@@ -139,7 +142,7 @@ export default function ConversationsPane({<inputvalue={query}onChange={(event) => setQuery(event.target.value)}- placeholder="Search title, model, or workspace"+ placeholder="Search title, model, or folder"aria-label="Search conversations"className="min-w-0 flex-1 bg-transparent text-[13.5px] font-medium text-ink outline-none placeholder:text-ink-3"/>@@ -163,18 +166,19 @@ export default function ConversationsPane({</div></header>- <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="min-h-0 flex-1 overflow-y-auto" aria-busy={loading || loadingMore}><div className="mx-auto flex w-full max-w-[720px] flex-col gap-6 px-5 py-5 sm:px-8">- {error && <p role="alert" className="text-[13px] text-orange">{error}{rows.length > 0 && <button className="ml-2 underline" onClick={() => setError(null)}>Retry</button>}</p>}+ {loading && <p role="status" className="py-8 text-center text-sm text-ink-3">Loading conversations…</p>}+ {error && <p role="alert" className="text-[13px] text-orange">{error.message}<button type="button" className="ml-2 rounded px-2 py-1 underline" onClick={() => error.more ? setError(null) : setReload(n => n + 1)}>Retry</button></p>}{empty && (<div className="flex flex-col items-center justify-center gap-1 rounded-[14px] bg-inset px-6 py-16 text-center"><span className="text-[14px] font-medium text-ink">- {query.trim() || scope !== "all" ? "No conversations match" : "No saved conversations yet"}+ {query.trim() || scope === "elsewhere" ? "No conversations match" : scope === "local" ? "No conversations in this project yet" : "No saved conversations yet"}</span><span className="text-[12.5px] text-ink-3">- {query.trim() || scope !== "all"+ {query.trim() || scope === "elsewhere"? "Try another search or show all sessions."- : "A turn autosaves here. New chat starts a fresh one."}+ : "Start a chat in this folder. Your conversation will be saved here."}</span></div>)}@@ -200,8 +204,8 @@ export default function ConversationsPane({</span><span className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[12px] text-ink-3">{row.model && <span className="font-mono text-[11.5px]">{row.model}</span>}- {row.local === false && <span>{row.origin ?? "another workspace"}</span>}- {row.local !== false && <span>This workspace</span>}+ {row.local === false && <span>{row.origin ?? "another folder"}</span>}+ {row.local !== false && <span>This project</span>}</span></span><span className="shrink-0 pt-0.5 text-[12px] tabular-nums text-ink-3">{relativeTime(row.updatedMs)}</span>diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex e023c641..1732db02 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -2,6 +2,7 @@import { workspaceActions } from "./harness-workspace-actions";import ProjectsPane from "./ProjectsPane";+import { useSavedConversation, ConversationOpenNotice } from "./useSavedConversation";import { restoreProjects, persistProjects } from "@/lib/project-preferences";import { createTurnPainter } from "@/lib/turn-painter";import { useQuietSettings } from "./useQuietSettings";@@ -40,7 +41,7 @@ import {import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AcpCommand, type AssistantTurn } from "@/lib/acp";import { isFollowingTail, pinScrollerTail } from "@/lib/follow-scroll";import { dropQueuedPrompt, enqueuePrompt, shiftQueuedPrompt, type QueuedPrompt } from "@/lib/prompt-queue";-import { dateGroup, listSessionsPage, loadSession, relativeTime, removeSession, type StoredSession } from "@/lib/sessions";+import { dateGroup, listSessionsPage, relativeTime, removeSession, type StoredSession } from "@/lib/sessions";import { loadHistory, mergeHistory, pushHistory, saveHistory } from "@/lib/prompt-history";import WorkspaceDialog from "@/components/site/WorkspaceDialog";import {@@ -465,40 +466,25 @@ export default function GraffHarness() {if (!window.graffDesktop) void requireSession(id).catch(() => undefined);};- /** 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, atCwd?: string) => {- // The sidebar lists the active workspace, so the session lives there;- // the same name in another workspace is a different conversation. A- // reopened tab names its own workspace instead.- const cwd = atCwd ?? activePathRef.current ?? undefined;- const existing = chats.find((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));- if (existing) {- setActiveId(existing.id);- setFilesOpen(false);- setConversationsOpen(false);- return;- }- let loaded: Awaited<ReturnType<typeof loadSession>>;- try {- loaded = await loadSession(name, cwd);- } catch (err) {- setHealth((current) => ({ ...(current ?? { ok: true }), detail: err instanceof Error ? err.message : String(err) }));- return;- }- const id = (chatIdRef.current += 1);- const messages: Msg[] = loaded.messages.map((m) => ({ id: (msgIdRef.current += 1), ...m }));- sessionNamesRef.current.set(id, name);- setChats((current) => [- ...current,- { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name, cwd },- ]);- setActiveId(id);- setFilesOpen(false);- setConversationsOpen(false);- setFollowing(true);- void requireSession(id, false, loaded.meta.model ?? undefined).catch(() => undefined);+ const selectStored = (id: number, cwd?: string) => {+ if (cwd) activateWorkspace(cwd);+ setActiveId(id); setFilesOpen(false); setConversationsOpen(false); setProjectsOpen(false); setFollowing(true);};+ const savedConversation = useSavedConversation({+ context: `${activePath ?? ""}:${activeId}`,+ findOpen: (name, cwd) => chatsRef.current.find(c => c.session === name && (c.cwd ?? null) === (cwd ?? null))?.id,+ select: selectStored,+ restore: (name, cwd, loaded) => {+ const id = ++chatIdRef.current;+ const messages: Msg[] = loaded.messages.map(m => ({ id: ++msgIdRef.current, ...m }));+ sessionNamesRef.current.set(id, name);+ const next = [...chatsRef.current, { id, title: loaded.meta.title ?? name, messages, model: loaded.meta.model ?? undefined, session: name, cwd }];+ chatsRef.current = next; setChats(next);+ selectStored(id, cwd);+ void requireSession(id, false, loaded.meta.model ?? undefined).catch(() => undefined);+ },+ });+ const openStored = (name: string, cwd = activePathRef.current ?? undefined) => savedConversation.open(name, cwd);const newChat = () => openChat((chatIdRef.current += 1));@@ -968,6 +954,7 @@ export default function GraffHarness() {/><div className="flex min-w-0 flex-1 flex-col gap-2.5">+ <ConversationOpenNotice request={savedConversation.request} onCancel={savedConversation.cancel} onRetry={savedConversation.retry} /><div className="flex min-h-0 flex-1 gap-2.5" style={{ flexDirection: splitDirection }}>{projectsOpen ? (<ProjectsPane workspaces={workspaces} current={activePath} onOpen={() => setDialog({ mode: "new" })}@@ -980,10 +967,7 @@ export default function GraffHarness() {<ConversationsPaneroot={chatCwd}activeId={chatThread.session ?? null}- onPick={(name) => {- setConversationsOpen(false);- pickRecent(name);- }}+ onPick={pickRecent}onNewChat={() => {setConversationsOpen(false);newChat();diff --git a/apps/native/components/site/WorkspaceDialog.tsx b/apps/native/components/site/WorkspaceDialog.tsxindex 7b757f53..7e5a2f72 100644--- a/apps/native/components/site/WorkspaceDialog.tsx+++ b/apps/native/components/site/WorkspaceDialog.tsx@@ -100,15 +100,20 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi// 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 pickRef = useRef(onPick);+ pickRef.current = onPick;+ const go = useCallback(async (target: string, pick = false) => {const n = (seq.current += 1);setBusy(true);+ setListing(null);+ setError(null);try {const next = await browseFolders(target);if (n !== seq.current) return;setListing(next);setTyped(next.path);setError(null);+ if (pick) pickRef.current(next.path);} catch (err) {if (n !== seq.current) return;setError(err instanceof Error ? err.message : String(err));@@ -118,6 +123,7 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi}, []);useEffect(() => {void go(startPath ?? "~");+ return () => { seq.current++; };}, [go, startPath]);const crumbs = listing ? listing.path.split("/").filter(Boolean) : [];@@ -140,7 +146,7 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi</span><inputvalue={typed}- onChange={(event) => setTyped(event.target.value)}+ onChange={(event) => { seq.current++; setTyped(event.target.value); setBusy(false); setError(null); setListing(null); }}spellCheck={false}autoFocusaria-label="Folder path"@@ -191,7 +197,9 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi</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>}+ {busy && <p role="status" className="px-4 py-3 text-[12.5px] text-ink-3">Reading folder…</p>}+ {error && <p role="alert" className="px-4 py-3 text-[12.5px] text-red">{error}</p>}+ {!listing && !busy && !error && <p className="px-4 py-3 text-[12.5px] text-ink-3">Press Enter to browse, or open this folder directly.</p>}{listing && (<div className="flex flex-col px-2 py-1.5">{listing.parent && (@@ -248,11 +256,11 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi</button><buttontype="button"- disabled={listing === null || busy}- onClick={() => listing && onPick(listing.path)}+ disabled={!typed.trim() || busy}+ onClick={() => void go(typed, true)}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+ Open folder</button></div></>diff --git a/apps/native/components/site/useSavedConversation.tsx b/apps/native/components/site/useSavedConversation.tsxnew file mode 100644index 00000000..15a9e6e5--- /dev/null+++ b/apps/native/components/site/useSavedConversation.tsx@@ -0,0 +1,52 @@+import { useEffect, useRef, useState } from "react";+import { loadSession } from "@/lib/sessions";++type Request = { name: string; cwd?: string; error?: string };+type Loaded = Awaited<ReturnType<typeof loadSession>>;++/** One visible, cancellable resume request. A late result cannot steal focus. */+export function useSavedConversation({ context, findOpen, select, restore }: {+ context: string;+ findOpen: (name: string, cwd?: string) => number | undefined;+ select: (id: number, cwd?: string) => void;+ restore: (name: string, cwd: string | undefined, loaded: Loaded) => void;+}) {+ const [request, setRequest] = useState<Request | null>(null);+ const generation = useRef(0);+ const controller = useRef<AbortController | null>(null);+ const cancel = () => { generation.current++; controller.current?.abort(); setRequest(null); };+ useEffect(() => {+ cancel();+ return () => { generation.current++; controller.current?.abort(); };+ }, [context]);+ const open = async (name: string, cwd?: string) => {+ const current = ++generation.current;+ controller.current?.abort();+ const id = findOpen(name, cwd);+ if (id !== undefined) { setRequest(null); select(id, cwd); return; }+ setRequest({ name, cwd });+ const pending = new AbortController(); controller.current = pending;+ try {+ const loaded = await loadSession(name, cwd, pending.signal);+ if (current !== generation.current) return;+ restore(name, cwd, loaded);+ setRequest(null);+ } catch (error) {+ if (current === generation.current) setRequest({ name, cwd, error: error instanceof Error ? error.message : String(error) });+ }+ };+ return { open, cancel, request, retry: () => { if (request) void open(request.name, request.cwd); } };+}++export function ConversationOpenNotice({ request, onCancel, onRetry }: {+ request: Request | null; onCancel: () => void; onRetry: () => void;+}) {+ if (!request) return null;+ return <div data-conversation-open className="flex shrink-0 flex-wrap items-center gap-2 rounded-control border border-line bg-surface px-4 py-3 text-sm text-ink">+ <span className="min-w-0 flex-1" role={request.error ? "alert" : "status"} title={request.error}>+ {request.error ? "Could not open this conversation. Try again or choose another." : "Opening conversation…"}+ </span>+ {request.error && <button type="button" onClick={onRetry} className="rounded-control bg-hover-2 px-3 py-1">Retry</button>}+ <button type="button" onClick={onCancel} className="rounded-control px-3 py-1 hover:bg-hover">{request.error ? "Dismiss" : "Cancel"}</button>+ </div>;+}diff --git a/apps/native/electron/composer-visual.cjs b/apps/native/electron/composer-visual.cjsindex a04c1647..4efa985d 100644--- a/apps/native/electron/composer-visual.cjs+++ b/apps/native/electron/composer-visual.cjs@@ -6,8 +6,9 @@ async function runComposerVisual({ win, output }) {await new Promise(r => setTimeout(r, 1600));await js(`document.querySelector('[aria-label="Choose model"] span.truncate').textContent='Example model with a long display name'`);for (const width of [220, 280, 360, 420, 520]) {+ console.log('Composer geometry:', width);await js(`document.querySelector('[data-promptbar]').style.width='${width}px'`);- await js('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');+ await js('Promise.race([new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))),new Promise((_,reject)=>setTimeout(()=>reject(Error("Composer did not receive a paint frame")),3000))])');const result = await js(`(()=>{const p=document.querySelector('[data-promptbar]'),area=p.getBoundingClientRect();const labels=['Add attachments and sources','Choose model','Select effort','Start dictation','Send'];diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjsindex 4779acae..3d673911 100644--- a/apps/native/electron/navigation-visual.cjs+++ b/apps/native/electron/navigation-visual.cjs@@ -27,6 +27,8 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {const galleryFetch=window.fetch;window.fetch=async(input,options)=>{const response=await galleryFetch(input,options);if(options?.body&&JSON.parse(options.body).method==='bootstrap')return new Response(JSON.stringify({sessionId:'demo',commands}),{headers:{'content-type':'application/json'}});if(String(input).includes('/api/models')){const data=await response.json();data.result.commands=commands;data.result.current.model='example-model-with-a-long-name';data.result.models[0].name=data.result.current.model;return new Response(JSON.stringify(data),{headers:{'content-type':'application/json'}});}return response;};`});await wc.loadURL(origin);win.focus();await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);await require('./projects-visual.cjs').runProjectVisuals({win,origin,output});+ await require('./project-recovery-visual.cjs').runProjectRecovery({win,origin,output});+ await require('./review-recovery-visual.cjs').runReviewRecovery({win,origin,output});await require('./composer-visual.cjs').runComposerVisual({win,output});await require('./split-composer-visual.cjs').runSplitComposerVisual({win,output,key});await input('/compact');await wait(`!!document.querySelector('[role="option"]')`);assert.match(await js(`document.querySelector('[role="option"]').textContent`),/compact/);diff --git a/apps/native/electron/project-recovery-visual.cjs b/apps/native/electron/project-recovery-visual.cjsnew file mode 100644index 00000000..8225f0a4--- /dev/null+++ b/apps/native/electron/project-recovery-visual.cjs@@ -0,0 +1,122 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++async function runProjectRecovery({ win, origin, output }) {+ const wc = win.webContents, js = code => wc.executeJavaScript(code);+ const wait = async code => { for (let i = 0; i < 120; i++) { if (await js(code)) return; await new Promise(r => setTimeout(r, 50)); } throw Error(`Recovery check timed out: ${code}`); };+ const click = (selector, text) => js(`Array.from(document.querySelectorAll(${JSON.stringify(selector)})).find(e=>e.textContent.trim()===${JSON.stringify(text)}).click()`);+ const input = (label, value) => js(`(()=>{const e=document.querySelector('[aria-label="${label}"]');e.focus();Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,${JSON.stringify(value)});e.dispatchEvent(new Event('input',{bubbles:true}));})()`);+ const library = '[data-conversation-library]';+ await wc.loadURL(origin);+ await wait(`!!document.querySelector('[data-project-context]')`);+ await js(`(() => {+ const previous = window.fetch;+ const json = (value, status=200) => new Response(JSON.stringify(value), {status,headers:{'content-type':'application/json'}});+ window.recovery = {mode:'fail',detail:'fail',holds:{},requests:[],pageFailures:0};+ const row = name => ({name,title:name,updatedMs:Date.now(),model:null,provider:null,size:100,local:true});+ window.fetch = async (input, options) => {+ const url = new URL(String(input),location.origin), r=window.recovery;+ r.requests.push({url:String(input),body:options?.body});+ if(url.pathname==='/api/workspaces') {+ const folder=url.searchParams.get('path');+ const listing={path:folder,parent:'/demo',home:'/demo',default:'/demo/field-notes',git:false,entries:[{name:'child',path:folder+'/child',git:false}]};+ if(folder==='/demo/missing') return json({error:'Folder does not exist'},404);+ if(folder==='/demo/slow') await new Promise(resolve=>r.holds.folder=resolve);+ return json(listing);+ }+ if(url.pathname==='/api/sessions'&&url.searchParams.has('name')) {+ const name=url.searchParams.get('name');+ if(r.detail==='fail') return json({error:'Temporarily unavailable'},503);+ if(r.detail==='hold') await new Promise(resolve=>r.holds.detail=resolve);+ return json({...row(name),messages:[{role:'user',content:'Continue this saved work.'},{role:'assistant',content:'Restored test conversation.'}]});+ }+ if(url.pathname==='/api/sessions'&&url.searchParams.get('limit')==='24') {+ if(r.mode==='fail') return json({error:'Temporarily unavailable'},503);+ const q=url.searchParams.get('q');+ if(q==='pending') { await new Promise(resolve=>r.holds.list=resolve); return json({sessions:[row('stale-conversation')],total:1,nextCursor:null}); }+ if(q==='fresh') return json({sessions:[row('fresh-conversation')],total:1,nextCursor:null});+ if(r.mode==='more') {+ if(url.searchParams.has('cursor')&&r.pageFailures++===0) return json({error:'Page unavailable'},503);+ return json({sessions:[row(url.searchParams.has('cursor')?'recovery-b':'recovery-a')],total:2,nextCursor:url.searchParams.has('cursor')?null:'next'});+ }+ return json({sessions:[row('recovery-a'),row('recovery-b')],total:2,nextCursor:null});+ }+ return previous(input, options);+ };+ })()`);++ await js(`document.querySelector('button[aria-label="Conversations"]').click()`);+ await wait(`!!document.querySelector('${library} [role="alert"]')`);+ assert.equal(await js(`document.querySelector('${library}').textContent.includes('No conversations')`), false, 'Failure must not masquerade as an empty project');+ await js(`window.recovery.mode='normal'`);+ await click(`${library} button`, 'Retry');+ await wait(`document.querySelector('${library}').textContent.includes('recovery-a')`);++ await input('Search conversations', 'pending');+ await wait(`!!window.recovery.holds.list`);+ assert.equal(await js(`document.querySelector('${library}').textContent.includes('recovery-a')`), false, 'Old results cannot remain selectable during a new lookup');+ await input('Search conversations', 'fresh');+ await wait(`document.querySelector('${library}').textContent.includes('fresh-conversation')`);+ await js(`window.recovery.holds.list()`);+ await js(`new Promise(r=>setTimeout(r,100))`);+ assert.equal(await js(`document.querySelector('${library}').textContent.includes('stale-conversation')`), false, 'Late search response cannot replace the latest results');++ await js(`window.recovery.mode='more'`);+ await input('Search conversations', '');+ await wait(`!!document.querySelector('${library} [role="alert"]')`);+ assert.ok(await js(`document.querySelector('${library}').textContent.includes('recovery-a')`), 'Pagination failure keeps the loaded page');+ await click(`${library} button`, 'Retry');+ await wait(`document.querySelector('${library}').textContent.includes('recovery-b')`);++ const tabs = await js(`document.querySelectorAll('[aria-label="Close tab"]').length`);+ const pick = name => js(`Array.from(document.querySelectorAll('${library} li button')).find(e=>e.textContent.includes(${JSON.stringify(name)})).click()`);+ await pick('recovery-a');+ await wait(`!!document.querySelector('[data-conversation-open] [role="alert"]')`);+ assert.ok(await js(`!!document.querySelector('[aria-label="Search conversations"]')`), 'Failed resume keeps the conversation picker visible');+ fs.writeFileSync(path.join(output,'conversation-retry.png'),(await wc.capturePage()).toPNG());+ await js(`window.recovery.detail='normal'`);+ await click('[data-conversation-open] button', 'Retry');+ await wait(`document.body.textContent.includes('Restored test conversation.')`);+ assert.equal(await js(`document.querySelectorAll('[aria-label="Close tab"]').length`), tabs+1);+ assert.equal(await js(`!!document.querySelector('[data-conversation-open]')`),false);++ await js(`document.querySelector('button[aria-label="Conversations"]').click();window.recovery.mode='normal';window.recovery.detail='hold'`);+ await wait(`document.querySelector('${library}')?.textContent.includes('recovery-b')`);+ await pick('recovery-b');+ await wait(`!!window.recovery.holds.detail`);+ await click('[data-conversation-open] button', 'Cancel');+ await js(`window.recovery.holds.detail()`);+ await js(`new Promise(r=>setTimeout(r,100))`);+ assert.equal(await js(`document.querySelectorAll('[aria-label="Close tab"]').length`),tabs+1,'Cancelled resume cannot open a late tab');+ await js(`delete window.recovery.holds.detail`);+ await pick('recovery-b');+ await wait(`!!window.recovery.holds.detail`);+ await js(`document.querySelector('button[aria-label="New chat"]').click()`);+ await wait(`!document.querySelector('[data-conversation-open]')`);+ await js(`window.recovery.holds.detail()`);+ await js(`new Promise(r=>setTimeout(r,100))`);+ assert.equal(await js(`document.querySelectorAll('[aria-label="Close tab"]').length`),tabs+2,'Starting a new chat cancels a pending resume');++ await js(`document.querySelector('button[aria-label="Open folder…"]').click()`);+ await wait(`!!document.querySelector('[role="dialog"] button[title$="/child"]')`);+ await input('Folder path','/demo/missing');+ await click('[role="dialog"] button','Open folder');+ await wait(`!!document.querySelector('[role="dialog"] [role="alert"]')`);+ assert.equal(await js(`document.querySelectorAll('[role="dialog"] button[title$="/child"]').length`),0,'Failed path must not leave the old folder selectable');+ fs.writeFileSync(path.join(output,'folder-retry.png'),(await wc.capturePage()).toPNG());+ await input('Folder path','/demo/slow');+ await click('[role="dialog"] button','Go');+ await wait(`!!window.recovery.holds.folder`);+ await input('Folder path','/demo/recovered');+ await click('[role="dialog"] button','Open folder');+ await wait(`!document.querySelector('[role="dialog"]')&&document.querySelector('[data-project-context]')?.textContent.includes('/demo/recovered')`);+ await js(`window.recovery.holds.folder()`);+ await js(`new Promise(r=>setTimeout(r,100))`);+ assert.ok(await js(`document.querySelector('[data-project-context]').textContent.includes('/demo/recovered')`),'A late folder listing cannot replace the chosen folder');+ await wc.loadURL(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ win.show(); win.focus();+ console.log('Project recovery passed: initial/paged retry, stale searches, resume retry/cancel, navigation races, and typed folder validation.');+}+module.exports={runProjectRecovery};diff --git a/apps/native/electron/review-recovery-visual.cjs b/apps/native/electron/review-recovery-visual.cjsnew file mode 100644index 00000000..6f9bfcef--- /dev/null+++ b/apps/native/electron/review-recovery-visual.cjs@@ -0,0 +1,57 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++async function runReviewRecovery({ win, origin, output }) {+ const wc=win.webContents, js=code=>wc.executeJavaScript(code);+ const wait=async code=>{for(let i=0;i<120;i++){if(await js(code))return;await new Promise(r=>setTimeout(r,50));}throw Error(`Review recovery timed out: ${code}`);};+ await wc.loadURL(origin);+ await wait(`!!document.querySelector('button[aria-label="Changes"]')`);+ await js(`(()=>{+ const previous=window.fetch,json=value=>new Response(JSON.stringify(value),{headers:{'content-type':'application/json'}});+ window.reviewRecovery={mode:'fail',holds:[]};+ window.fetch=async(input,options)=>{+ const url=new URL(String(input),location.origin),r=window.reviewRecovery;+ if(url.pathname!=='/api/git')return previous(input,options);+ if(r.mode==='fail')return new Response(JSON.stringify({error:'Cannot read changes for this folder'}),{status:503,headers:{'content-type':'application/json'}});+ if(options?.method==='POST') {+ if(r.mode==='diff-fail')return new Response(JSON.stringify({error:'Cannot read file diff'}),{status:503,headers:{'content-type':'application/json'}});+ const body=JSON.parse(options.body);+ return json({diff:'diff --git a/'+body.path+' b/'+body.path+'\\n--- a/'+body.path+'\\n+++ b/'+body.path+'\\n@@ -1 +1 @@\\n-old\\n+content-'+body.scope+'-'+body.root+'\\n'});+ }+ const scope=url.searchParams.get('scope'),root=url.searchParams.get('root');+ r.base??=root;+ if(scope==='staged'&&r.mode==='hold')await new Promise(resolve=>r.holds.push(resolve));+ return json({root,branch:root==='/demo/other-tree'?'other-branch':'main',files:[{path:scope+'.txt',add:1,del:1,untracked:false,status:' M'}],totalAdd:1,totalDel:1,commits:[],worktrees:[{path:r.base,branch:'main'},{path:'/demo/other-tree',branch:'other-branch'}]});+ };+ })()`);+ await js(`document.querySelector('button[aria-label="Changes"]').click()`);+ await wait(`!!document.querySelector('[aria-label="Workspace changes"] [role="alert"]')`);+ assert.equal(await js(`document.querySelector('[aria-label="File diff"]').textContent.includes('Working tree is clean')`),false,'Failed Git reads are not clean worktrees');+ assert.ok(await js(`!!document.querySelector('[aria-label="Updates unavailable"]')`),'Live indicator reflects failure');+ await js(`window.reviewRecovery.mode='normal';document.querySelector('[aria-label="Workspace changes"] [role="alert"] button').click()`);+ await wait(`document.querySelector('[aria-label="File diff"]').textContent.includes('content-all-')`);+ await js(`window.reviewRecovery.mode='hold';Array.from(document.querySelectorAll('[aria-label="Changes scope"] button')).find(b=>b.textContent==='Staged').click()`);+ await wait(`window.reviewRecovery.holds.length>0`);+ assert.equal(await js(`!!document.querySelector('[aria-label="Changed file"]')`),false,'Previous filter files must not remain selectable');+ assert.equal(await js(`document.querySelector('[aria-label="File diff"]').textContent.includes('content-all-')`),false,'Previous diff disappears while loading another filter');+ await js(`window.reviewRecovery.mode='normal';Array.from(document.querySelectorAll('[aria-label="Changes scope"] button')).find(b=>b.textContent==='Unstaged').click()`);+ await wait(`document.querySelector('[aria-label="File diff"]').textContent.includes('content-unstaged-')`);+ await js(`window.reviewRecovery.holds.forEach(resolve=>resolve())`);+ await js(`new Promise(r=>setTimeout(r,100))`);+ assert.equal(await js(`document.querySelector('[aria-label="Changed file"]').value`),'unstaged.txt','Late staged response cannot overwrite the selected scope');+ await js(`window.reviewRecovery.mode='fail';const e=document.querySelector('[aria-label="Review worktree"]');e.value='/demo/other-tree';e.dispatchEvent(new Event('change',{bubbles:true}))`);+ await wait(`!!document.querySelector('[aria-label="Workspace changes"] [role="alert"]')`);+ assert.equal(await js(`document.querySelector('[aria-label="File diff"]').textContent.includes('content-')`),false,'Failed worktree switch cannot retain another folder’s diff');+ fs.writeFileSync(path.join(output,'changes-retry.png'),(await wc.capturePage()).toPNG());+ await js(`window.reviewRecovery.mode='normal';document.querySelector('[aria-label="Refresh changes"]').click()`);+ await wait(`document.querySelector('[aria-label="File diff"]').textContent.includes('content-unstaged-/demo/other-tree')`);+ await js(`window.reviewRecovery.mode='diff-fail';document.querySelector('[aria-label="Refresh changes"]').click()`);+ await wait(`!!document.querySelector('[aria-label="Workspace changes"] [role="alert"]')`);+ assert.ok(await js(`document.querySelector('[aria-label="File diff"]').textContent.includes('Changes unavailable')`),'Diff failures must not masquerade as binary files');+ await wc.loadURL(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ win.focus();+ console.log('Review recovery passed: unavailable vs clean, explicit retry, stale filters/worktrees, and diff failures.');+}+module.exports={runReviewRecovery};diff --git a/apps/native/electron/stress-visual.cjs b/apps/native/electron/stress-visual.cjsindex 6aba3e3f..cd13aa53 100644--- a/apps/native/electron/stress-visual.cjs+++ b/apps/native/electron/stress-visual.cjs@@ -4,7 +4,7 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const path = require('node:path');const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));-async function runStressVisuals({win: fixtureWindow, origin, output}) {+async function runStressVisuals({win: fixtureWindow, origin, output, fullscreen = true}) {const win = new BrowserWindow({width:1000,height:760,show:true,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});installWindowState(win);const js = code => win.webContents.executeJavaScript(code);@@ -49,15 +49,16 @@ async function runStressVisuals({win: fixtureWindow, origin, output}) {await click('[data-stream]');const titleHeight=()=>js(`document.querySelector('[data-desktop-titlebar]').getBoundingClientRect().height`);assert.equal(await titleHeight(),36);- if(process.platform==='darwin') {+ const checkedFullscreen = fullscreen && process.platform === 'darwin';+ if(checkedFullscreen) {win.setFullScreen(true);await wait(`document.documentElement.dataset.desktopFullscreen==='true'`);assert.equal(await titleHeight(),0);await bounds();fs.writeFileSync(path.join(output,'stress-fullscreen.png'),(await win.webContents.capturePage()).toPNG());await win.reload();await wait(`document.documentElement.dataset.desktopFullscreen==='true'`);assert.equal(await titleHeight(),0);win.setFullScreen(false);await wait(`document.documentElement.dataset.desktopFullscreen==='false'`);assert.equal(await titleHeight(),36);}- fs.writeFileSync(path.join(output,'stress-results.json'),JSON.stringify({passed:['5000 tools','bounded output','1000 messages','unbroken input','long markdown','stream reading position','fullscreen and reload'],metrics},null,2));- console.log('Stress visual checks passed: long tools/output/history/text, reading position, fullscreen.');+ fs.writeFileSync(path.join(output,'stress-results.json'),JSON.stringify({passed:['5000 tools','bounded output','1000 messages','unbroken input','long markdown','stream reading position',...(checkedFullscreen?['fullscreen and reload']:[])],fullscreen:checkedFullscreen?'passed':'not run',metrics},null,2));+ console.log('Stress visual checks passed: long tools/output/history/text, reading position. Fullscreen:', checkedFullscreen?'passed':'not run in this suite');} finally {win.destroy();fixtureWindow.show();fixtureWindow.focus();}}module.exports={runStressVisuals};diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjsindex a4899a61..3f28e859 100644--- a/apps/native/electron/visual-tests.cjs+++ b/apps/native/electron/visual-tests.cjs@@ -45,6 +45,11 @@ app.whenReady().then(async () => {fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: ['projects and navigation', 'browser'], apiRequests }, null, 2));return;}+ if (process.env.GRAFF_VISUAL_SUITE === 'stress') {+ await require('./stress-visual.cjs').runStressVisuals({ win, origin, output, fullscreen: false });+ assert.deepEqual(apiRequests, [], 'Stress fixtures never call engine or model APIs');+ return;+ }await win.loadURL(`${origin}/visual-tests`);const js = source => win.webContents.executeJavaScript(source);const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(50); } throw Error(`Visual check timed out: ${source}`); };diff --git a/apps/native/lib/sessions.ts b/apps/native/lib/sessions.tsindex cb719ee4..ee1e65f3 100644--- a/apps/native/lib/sessions.ts+++ b/apps/native/lib/sessions.ts@@ -92,8 +92,8 @@ export async function listSessions(root?: string): Promise<StoredSession[]> {return page.sessions;}-export async function loadSession(name: string, root?: string): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {- const res = await fetch(`${BASE}${withRoot({ name, root })}`, { cache: "no-store" });+export async function loadSession(name: string, root?: string, signal?: AbortSignal): Promise<{ meta: StoredSession; messages: TranscriptMsg[] }> {+ const res = await fetch(`${BASE}${withRoot({ name, root })}`, { cache: "no-store", signal });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/package.json b/apps/native/package.jsonindex c6a6ef55..ad2b5d0f 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -17,6 +17,7 @@"test:visual": "bun scripts/test-visual.mjs","test:updates": "GRAFF_VISUAL_SUITE=updates bun scripts/test-visual.mjs","test:projects": "GRAFF_VISUAL_SUITE=projects bun scripts/test-visual.mjs",+ "test:stress": "GRAFF_VISUAL_SUITE=stress bun scripts/test-visual.mjs","test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs"},"dependencies": {diff --git a/docs/adr/0080-desktop-projects-are-folders.md b/docs/adr/0080-desktop-projects-are-folders.mdindex 5acb3cc8..dc7cd9d3 100644--- a/docs/adr/0080-desktop-projects-are-folders.md+++ b/docs/adr/0080-desktop-projects-are-folders.md@@ -26,3 +26,8 @@ The project-store test covers restart persistence and ordered writes. The offlindesktop project suite covers folder selection, scoped conversation discovery,new chat inheritance, and separate Files/Changes navigation. Its preview fixturestarts Bun and exercises the browser tool transport without a model call.++Recovery fixtures also cover failed initial loads and pagination, stale search+results, cancellable conversation restoration, and invalid typed folder paths.+Review errors remain distinct from clean working trees, and delayed responses+cannot replace the currently selected filter or worktree.