Skip to content

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

Python

feat: make desktop projects and changes easy to find

Rach Pradhan501915f24d94
diff --git a/README.md b/README.md
index 624d59aa..24a295e2 100644
--- a/README.md
+++ b/README.md
@@ -149,6 +149,9 @@ Desktop builds from v0.0.291 check for updates online and download them in the
background. Choose **Restart to update** when your work is finished, or use
**Codegraff → Check for Updates…**. Automatic downloads can be disabled in that
menu. Earlier builds need one manual installation to enable the updater.
+An app update replaces the bundled Graff engine together with the interface.
+A CLI installed separately by the command below has its own update lifecycle;
+that command downloads a CLI archive, not the notarized desktop installer.
**CLI (macOS · Linux · Windows).**
diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsx
index 69383777..a54a0149 100644
--- a/apps/native/components/primitives/SidebarNav.tsx
+++ b/apps/native/components/primitives/SidebarNav.tsx
@@ -32,8 +32,10 @@ const WORKSPACE = { key: "graff", name: "Codegraff", monogram: "G" };
const NAV_ITEMS: { key: string; label: string; icon: ReactNode; count?: string }[] = [
{ key: "home", label: "Home", icon: <IconHome size={18} /> },
+ { key: "projects", label: "Projects", icon: <IconFolder size={18} /> },
{ key: "conversations", label: "Conversations", icon: <IconChat size={18} /> },
- { key: "workspace", label: "Workspace", icon: <IconFolder size={18} /> },
+ { key: "workspace", label: "Files", icon: <IconFolder size={18} /> },
+ { key: "changes", label: "Changes", icon: <IconEditBig size={18} /> },
{ key: "browser", label: "Browser", icon: <IconGlobe size={18} /> },
];
@@ -141,6 +143,9 @@ function RailButton({
<button
data-row
type="button"
+ aria-label={label}
+ aria-current={active ? "page" : undefined}
+ title={label}
onClick={onClick}
className={`sidebar-row relative z-10 mx-2 flex h-8 items-center rounded-[8px] px-2 text-left
transition-[width,background-color,color,transform] duration-150 active:scale-[0.98]
@@ -306,6 +311,7 @@ export default function SidebarNav({
</div>
<GlideGroup>
+ {onNewWorkspace && <RailButton icon={<IconPlusMedium size={18} />} label="Open folder…" onClick={onNewWorkspace} />}
<RailButton
icon={<IconEditBig size={18} />}
label="New chat"
diff --git a/apps/native/components/primitives/WorkspaceMenu.tsx b/apps/native/components/primitives/WorkspaceMenu.tsx
index 29f6829f..b2fcabba 100644
--- a/apps/native/components/primitives/WorkspaceMenu.tsx
+++ b/apps/native/components/primitives/WorkspaceMenu.tsx
@@ -32,7 +32,7 @@ export default function WorkspaceMenu({position,current,rows,onSwitch,onNew,onSe
</div>
<div className="shrink-0 border-t border-line p-1.5">
<button type="button" onClick={pick(onNew)} className="flex w-full justify-between rounded-lg px-3 py-2 text-sm text-ink hover:bg-hover">Open a folder…<kbd className="text-xs text-ink-3">⌘O</kbd></button>
- <button type="button" onClick={pick(onSettings)} className="w-full rounded-lg px-3 py-2 text-left text-sm text-ink hover:bg-hover">Workspace settings…</button>
+ <button type="button" onClick={pick(onSettings)} className="w-full rounded-lg px-3 py-2 text-left text-sm text-ink hover:bg-hover">Project settings…</button>
</div>
</div>,document.body);
}
diff --git a/apps/native/components/site/ChatEmpty.tsx b/apps/native/components/site/ChatEmpty.tsx
index 09c07df3..dd53aa39 100644
--- a/apps/native/components/site/ChatEmpty.tsx
+++ b/apps/native/components/site/ChatEmpty.tsx
@@ -4,6 +4,7 @@ import { useEffect, useState, type CSSProperties } from "react";
import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";
import type { AcpCommand } from "@/lib/acp";
import { STARTER_PROMPTS, type Health } from "@/lib/acp-client";
+import { basename } from "@/lib/workspaces";
function greeting(): string {
const hour = new Date().getHours();
@@ -40,6 +41,7 @@ export default function EmptyState({
history,
cwd,
commands, compact = false,
+ onOpenProject, onContinue, onReview, onProjects,
}: {
onSend: (text: string) => void; onSetting?: (text: string) => Promise<void>;
health: Health | null;
@@ -53,6 +55,10 @@ export default function EmptyState({
/** The slash commands this tab's agent advertised, for the / menu. */
commands?: AcpCommand[];
compact?: boolean;
+ onOpenProject?: () => void;
+ onContinue?: () => void;
+ onReview?: () => void;
+ onProjects?: () => void;
}) {
const where = cwd ?? health?.cwd;
const [offset, setOffset] = useState(0);
@@ -80,6 +86,16 @@ export default function EmptyState({
</span>
</h1>}
+ {!compact && onOpenProject && <div className="mt-5 rounded-control border border-line bg-surface px-3 py-3" data-project-context>
+ <div className="flex items-center justify-between gap-2"><span className="truncate text-sm font-medium text-ink">{where ? basename(where) : "Choose a project folder"}</span><button type="button" onClick={onOpenProject} className="shrink-0 rounded-control px-2 py-1 text-xs text-ink-2 hover:bg-hover">Change folder…</button></div>
+ {where && <p className="mt-1 break-all font-mono text-xs text-ink-3">{where}</p>}
+ <div className="mt-2 flex flex-wrap gap-3 text-xs text-ink-2">
+ {onProjects && <button type="button" onClick={onProjects} className="rounded py-1 hover:text-ink">All projects</button>}
+ {onContinue && <button type="button" onClick={onContinue} className="rounded py-1 hover:text-ink">Continue conversation</button>}
+ {onReview && <button type="button" onClick={onReview} className="rounded py-1 hover:text-ink">Review changes</button>}
+ </div>
+ </div>}
+
<div className={`relative ${compact ? "" : "home-reveal mt-7"}`} style={compact ? undefined : homeRevealStyle(stage >= 3)}>
<PromptBar
demo={false}
diff --git a/apps/native/components/site/ConversationsPane.tsx b/apps/native/components/site/ConversationsPane.tsx
index 65c3b47e..11e7a974 100644
--- a/apps/native/components/site/ConversationsPane.tsx
+++ b/apps/native/components/site/ConversationsPane.tsx
@@ -13,7 +13,7 @@ import {
const PAGE = 24;
const SCOPES: { key: SessionScope; label: string }[] = [
{ key: "all", label: "All" },
- { key: "local", label: "This workspace" },
+ { key: "local", label: "This project" },
{ key: "elsewhere", label: "Saved elsewhere" },
];
@@ -39,7 +39,7 @@ export default function ConversationsPane({
root?: string;
}) {
const [query, setQuery] = useState("");
- const [scope, setScope] = useState<SessionScope>("all");
+ const [scope, setScope] = useState<SessionScope>("local");
const [rows, setRows] = useState<StoredSession[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
const [total, setTotal] = useState(0);
@@ -112,6 +112,7 @@ export default function ConversationsPane({
<div className="flex items-end justify-between gap-4">
<div>
<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
? "Reading saved sessions…"
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 108481ca..e023c641 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -1,5 +1,8 @@
"use client";
+import { workspaceActions } from "./harness-workspace-actions";
+import ProjectsPane from "./ProjectsPane";
+import { restoreProjects, persistProjects } from "@/lib/project-preferences";
import { createTurnPainter } from "@/lib/turn-painter";
import { useQuietSettings } from "./useQuietSettings";
import reviewStyles from "./ChangesPane.module.css";
@@ -43,11 +46,6 @@ import WorkspaceDialog from "@/components/site/WorkspaceDialog";
import {
basename,
findWorkspace,
- loadActiveWorkspace,
- loadWorkspaces,
- removeWorkspace,
- saveActiveWorkspace,
- saveWorkspaces,
shellQuote,
upsertWorkspace,
type Workspace,
@@ -97,7 +95,7 @@ export default function GraffHarness() {
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.
+ // persist in desktop settings, with browser storage as a migration/fallback.
// Refs mirror the state for the async paths (spawn, session list) that
// must not read a stale closure.
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
@@ -114,8 +112,10 @@ export default function GraffHarness() {
});
// The conversation library: every saved chat, paged and searchable. It takes
// the whole chat area, so opening it leaves the other side panes.
+ const [projectsOpen, setProjectsOpen] = useState(false);
const [conversationsOpen, setConversationsOpen] = useState(false);
const openConversations = () => {
+ setProjectsOpen(false);
setFilesOpen(false);
setBrowserOpen(false);
setConversationsOpen(true);
@@ -256,15 +256,17 @@ export default function GraffHarness() {
// 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);
+ const savedProjects = await restoreProjects(window.localStorage);
+ if (cancelled) return;
+ let list = savedProjects.list;
if (root && !findWorkspace(list, root)) list = upsertWorkspace(list, { path: root, name: basename(root) });
- const remembered = loadActiveWorkspace(window.localStorage);
+ const remembered = savedProjects.active;
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);
+ persistProjects(window.localStorage, list, active);
if (active) setChats((current) => current.map((c) => (c.id === 1 && !c.cwd ? { ...c, cwd: active } : c)));
void refreshStored();
try {
@@ -322,6 +324,7 @@ export default function GraffHarness() {
}, []);
const openChanges = useCallback(() => {
+ setProjectsOpen(false);
setAgentsOpen(false);
setBrowserOpen(false); setConversationsOpen(false);
setFilesOpen(true);
@@ -448,6 +451,7 @@ export default function GraffHarness() {
};
const openChat = (id: number) => {
+ setProjectsOpen(false);
const session = newSessionName();
sessionNamesRef.current.set(id, session);
const cwd = activePathRef.current ?? undefined;
@@ -501,6 +505,9 @@ export default function GraffHarness() {
/** Make a chat the active one. If it is already a split pane, the chat it
* replaces takes that pane, so the same two stay on screen. */
const focusChat = (id: number) => {
+ setProjectsOpen(false);
+ const folder = chatsRef.current.find(chat => chat.id === id)?.cwd;
+ if (folder && folder !== activePathRef.current) activateWorkspace(folder);
const here = activeId;
setPanes((current) => {
if (!current.includes(id)) return current.filter((pane) => pane !== id);
@@ -599,84 +606,11 @@ export default function GraffHarness() {
.then(() => refreshStored());
};
- /* ── 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();
- };
-
- /** Move a tab to another folder. Only sound for a tab with no messages:
- * an agent is bound to its folder at spawn, so this starts a fresh one
- * there, and a conversation would lose the ground it was standing on. */
- const moveChatTo = (chatId: number, path: string) => {
- const ws = findWorkspace(workspacesRef.current, path);
- const next = chatsRef.current.map((c) => (c.id === chatId ? { ...c, cwd: path, model: c.model ?? ws?.model } : c));
- // requireSession reads the chat from this ref in the same tick, before
- // React has re-rendered with the new cwd.
- chatsRef.current = next;
- setChats(next);
- setPanes((current) => current.filter((pane) => pane !== chatId));
- setActiveId(chatId);
- void requireSession(chatId, true)
- .then(() => adoptCatalog(chatId))
- .catch(() => undefined);
- };
-
- /** Switch the sidebar to a workspace and land on a tab that runs there.
- * The tab in front follows the switch when nothing has been asked in it
- * yet — picking a folder should change the folder you are looking at.
- * A tab with a conversation keeps its own folder, and says which. */
- const switchWorkspace = (path: string) => {
- if (path === activePathRef.current) return;
- activate(path);
- setFilesOpen(false);
- const here = chatsRef.current.find((c) => c.id === activeId);
- if (here && here.messages.length === 0) {
- moveChatTo(here.id, path);
- return;
- }
- const empty = chatsRef.current.find((c) => c.cwd === path && c.messages.length === 0);
- if (empty) {
- setActiveId(empty.id);
- 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);
- }
- };
+ const { switchWorkspace, addWorkspace, saveWorkspace, forgetWorkspace, newProjectChat, activateWorkspace } = workspaceActions({
+ workspacesRef, activePathRef, chatsRef, chatIdRef, activeId, root: health?.cwd,
+ setWorkspaces, setActivePath, setChats, setPanes, setActiveId, setFilesOpen, setDialog,
+ refreshStored, requireSession, adoptCatalog, openChat,
+ });
/** The footer names the tab's own graff session; clicking it copies the
* command that continues the same conversation in a terminal. */
@@ -831,6 +765,9 @@ export default function GraffHarness() {
) : (
<div className="min-h-0 flex-1 overflow-y-auto">
<EmptyState compact={compactPane}
+ onOpenProject={() => setDialog({ mode: "new" })}
+ onProjects={() => setProjectsOpen(true)}
+ onContinue={openConversations} onReview={openChanges}
onSend={(text: string) => void send(text, thread.id)} onSetting={text => settings.change(thread.id, text)}
health={health}
history={threadHistory}
@@ -1009,8 +946,11 @@ export default function GraffHarness() {
onPick={pickRecent}
onNewChat={newChat}
onSeeAll={openConversations}
- activeNav={filesOpen ? "workspace" : browserOpen ? "browser" : conversationsOpen ? "conversations" : "home"}
+ activeNav={projectsOpen ? "projects" : filesOpen ? (fileRequest?.changes ? "changes" : "workspace") : browserOpen ? "browser" : conversationsOpen ? "conversations" : "home"}
onNavigate={(key) => {
+ setProjectsOpen(key === "projects");
+ if (key === "changes") { openChanges(); return; }
+ if (key === "workspace") setFileRequest(null);
setFilesOpen(key === "workspace");
setBrowserOpen(key === "browser");
setConversationsOpen(key === "conversations");
@@ -1029,7 +969,12 @@ export default function GraffHarness() {
<div className="flex min-w-0 flex-1 flex-col gap-2.5">
<div className="flex min-h-0 flex-1 gap-2.5" style={{ flexDirection: splitDirection }}>
- {conversationsOpen ? (
+ {projectsOpen ? (
+ <ProjectsPane workspaces={workspaces} current={activePath} onOpen={() => setDialog({ mode: "new" })}
+ onClose={() => setProjectsOpen(false)}
+ onContinue={path => { switchWorkspace(path); openConversations(); }}
+ onNewChat={newProjectChat} />
+ ) : conversationsOpen ? (
<section className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">
{tabBar}
<ConversationsPane
@@ -1096,10 +1041,10 @@ export default function GraffHarness() {
</>
)}
- {agentsOpen && !filesOpen && !browserOpen && !conversationsOpen && <AgentsPane key={chatCwd} root={chatCwd} onClose={() => setAgentsOpen(false)} />}
- {filesOpen && !conversationsOpen && (fileRequest?.changes ? <ChangesPane root={chatThread.cwd} onClose={() => setFilesOpen(false)} /> : <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />)}
+ {agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && <AgentsPane key={chatCwd} root={chatCwd} onClose={() => setAgentsOpen(false)} />}
+ {filesOpen && !projectsOpen && !conversationsOpen && (fileRequest?.changes ? <ChangesPane root={chatThread.cwd} onClose={() => setFilesOpen(false)} /> : <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />)}
- {browserOpen && !conversationsOpen && (
+ {browserOpen && !projectsOpen && !conversationsOpen && (
<BrowserPane
key={chatThread.id}
chat={handleOf(chatThread.id)}
@@ -1111,7 +1056,7 @@ export default function GraffHarness() {
/>
)}
- {!filesOpen && !browserOpen && !conversationsOpen && active && paneTodos.length > 0 && (
+ {!projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && active && paneTodos.length > 0 && (
<aside
className="hidden w-[360px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"
style={{ animation: "fade-in 300ms ease both" }}
@@ -1142,7 +1087,7 @@ export default function GraffHarness() {
startPath={activePath ?? health?.home ?? undefined}
models={models}
onClose={() => setDialog(null)}
- onPick={addWorkspace}
+ onPick={path => { addWorkspace(path); setProjectsOpen(false); }}
onSave={saveWorkspace}
onForget={forgetWorkspace}
/>
diff --git a/apps/native/components/site/ProjectsPane.tsx b/apps/native/components/site/ProjectsPane.tsx
new file mode 100644
index 00000000..e9857206
--- /dev/null
+++ b/apps/native/components/site/ProjectsPane.tsx
@@ -0,0 +1,33 @@
+"use client";
+import { useState } from "react";
+import { IconFolder, IconPlusMedium } from "@/lib/icons";
+import type { Workspace } from "@/lib/workspaces";
+
+export default function ProjectsPane({ workspaces, current, onOpen, onContinue, onNewChat, onClose }: {
+ workspaces: Workspace[]; current: string | null; onOpen: () => void;
+ onContinue: (path: string) => void; onNewChat: (path: string) => void;
+ onClose: () => void;
+}) {
+ const [query, setQuery] = useState("");
+ const shown = workspaces.filter(w => `${w.name} ${w.path}`.toLowerCase().includes(query.toLowerCase()));
+ return <section aria-label="Projects" className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page">
+ <header className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-6 py-5">
+ <div><h1 className="text-xl font-semibold text-ink">Projects</h1><p className="mt-1 text-sm text-ink-3">A project is a folder on your Mac. Your files stay there.</p></div>
+ <div className="flex flex-wrap items-center gap-3"><button type="button" onClick={onClose} className="rounded-control px-2 py-2 text-sm text-ink-2 hover:bg-hover">Back to chat</button><button type="button" onClick={onOpen} className="flex items-center gap-2 rounded-control bg-ink px-4 py-2 text-sm text-page"><IconPlusMedium size={16} />Open folder…</button></div>
+ </header>
+ <div className="min-h-0 overflow-y-auto p-6">
+ <input aria-label="Search projects" placeholder="Find a project by name or folder…" value={query} onChange={e => setQuery(e.target.value)} className="mb-5 h-10 w-full rounded-control border border-line bg-field px-3 text-sm text-ink" />
+ <div className="grid gap-3 xl:grid-cols-2">
+ {shown.map(w => <article key={w.path} data-project-path={w.path} className="min-w-0 rounded-[14px] border border-line bg-surface p-4">
+ <div className="flex items-center gap-2 text-ink"><IconFolder size={19} /><h2 className="min-w-0 flex-1 truncate font-medium">{w.name}</h2>{w.path === current && <span className="text-xs text-accent">Current</span>}</div>
+ <p className="my-3 break-all font-mono text-xs text-ink-3">{w.path}</p>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={() => onContinue(w.path)} className="rounded-control bg-hover-2 px-3 py-2 text-sm text-ink">Continue conversation</button>
+ <button type="button" onClick={() => onNewChat(w.path)} className="rounded-control px-3 py-2 text-sm text-ink-2 hover:bg-hover">New chat</button>
+ </div>
+ </article>)}
+ </div>
+ {!shown.length && <p className="py-8 text-center text-sm text-ink-3">{query ? "No projects match this search." : "Open a folder to start your first project."}</p>}
+ </div>
+ </section>;
+}
diff --git a/apps/native/components/site/harness-workspace-actions.ts b/apps/native/components/site/harness-workspace-actions.ts
new file mode 100644
index 00000000..22816bae
--- /dev/null
+++ b/apps/native/components/site/harness-workspace-actions.ts
@@ -0,0 +1,98 @@
+import type { Dispatch, SetStateAction, MutableRefObject } from "react";
+import type { Chat } from "./harness-types";
+import { basename, findWorkspace, removeWorkspace, upsertWorkspace, type Workspace } from "@/lib/workspaces";
+import { persistProjects } from "@/lib/project-preferences";
+type Setter<T> = Dispatch<SetStateAction<T>>;
+type Ref<T> = MutableRefObject<T>;
+type Actions = {
+ workspacesRef: Ref<Workspace[]>; activePathRef: Ref<string | null>;
+ chatsRef: Ref<Chat[]>; chatIdRef: Ref<number>; activeId: number; root?: string;
+ setWorkspaces: Setter<Workspace[]>; setActivePath: Setter<string | null>;
+ setChats: Setter<Chat[]>; setPanes: Setter<number[]>; setActiveId: Setter<number>;
+ setFilesOpen: Setter<boolean>; setDialog: (value: null) => void;
+ refreshStored: () => Promise<void>; requireSession: (id: number, force: boolean) => Promise<string>;
+ adoptCatalog: (id: number) => Promise<unknown>; openChat: (id: number) => void;
+};
+export function workspaceActions({workspacesRef, activePathRef, chatsRef, chatIdRef, activeId, root,
+ setWorkspaces, setActivePath, setChats, setPanes, setActiveId, setFilesOpen, setDialog,
+ refreshStored, requireSession, adoptCatalog, openChat}: Actions) {
+ const persistWorkspaces = (list: Workspace[]) => {
+ workspacesRef.current = list;
+ setWorkspaces(list);
+ persistProjects(window.localStorage, list, activePathRef.current);
+ };
+
+ const activate = (path: string | null) => {
+ activePathRef.current = path;
+ setActivePath(path);
+ persistProjects(window.localStorage, workspacesRef.current, path);
+ void refreshStored();
+ };
+
+ /** Move a tab to another folder. Only sound for a tab with no messages:
+ * an agent is bound to its folder at spawn, so this starts a fresh one
+ * there, and a conversation would lose the ground it was standing on. */
+ const moveChatTo = (chatId: number, path: string) => {
+ const ws = findWorkspace(workspacesRef.current, path);
+ const next = chatsRef.current.map((c) => (c.id === chatId ? { ...c, cwd: path, model: c.model ?? ws?.model } : c));
+ // requireSession reads the chat from this ref in the same tick, before
+ // React has re-rendered with the new cwd.
+ chatsRef.current = next;
+ setChats(next);
+ setPanes((current) => current.filter((pane) => pane !== chatId));
+ setActiveId(chatId);
+ void requireSession(chatId, true)
+ .then(() => adoptCatalog(chatId))
+ .catch(() => undefined);
+ };
+
+ /** Switch the sidebar to a workspace and land on a tab that runs there.
+ * The tab in front follows the switch when nothing has been asked in it
+ * yet — picking a folder should change the folder you are looking at.
+ * A tab with a conversation keeps its own folder, and says which. */
+ const switchWorkspace = (path: string) => {
+ if (path === activePathRef.current) return;
+ activate(path);
+ setFilesOpen(false);
+ const here = chatsRef.current.find((c) => c.id === activeId);
+ if (here && here.messages.length === 0) {
+ moveChatTo(here.id, path);
+ return;
+ }
+ const empty = chatsRef.current.find((c) => c.cwd === path && c.messages.length === 0);
+ if (empty) {
+ setActiveId(empty.id);
+ 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 ?? root ?? null;
+ if (next) switchWorkspace(next);
+ else activate(null);
+ }
+ };
+
+ const newProjectChat = (path: string) => { activate(path); openChat((chatIdRef.current += 1)); };
+ return { switchWorkspace, addWorkspace, saveWorkspace, forgetWorkspace, newProjectChat, activateWorkspace: activate };
+}
diff --git a/apps/native/electron/browser-visual.cjs b/apps/native/electron/browser-visual.cjs
index 3b287c63..1130d7b6 100644
--- a/apps/native/electron/browser-visual.cjs
+++ b/apps/native/electron/browser-visual.cjs
@@ -30,6 +30,7 @@ async function runBrowserVisuals({ win: fixtureWindow, origin, output }) {
await wait(async () => !page.isLoading());
await js(`document.querySelector('button[aria-pressed]').click()`);
await wait(() => js(`document.querySelector('button[aria-pressed]').getAttribute('aria-pressed')==='true'`));
+ win.focus(); page.focus();
page.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await wait(() => js(`document.querySelector('button[aria-pressed]').getAttribute('aria-pressed')==='false'`));
await js(`document.querySelector('button[aria-pressed]').click()`); await sleep(100);
diff --git a/apps/native/electron/dev-preview-visual.cjs b/apps/native/electron/dev-preview-visual.cjs
new file mode 100644
index 00000000..c5156739
--- /dev/null
+++ b/apps/native/electron/dev-preview-visual.cjs
@@ -0,0 +1,50 @@
+const { BrowserWindow } = require('electron');
+const { BrowserTabs } = require('./browser-tabs.cjs');
+const { startAutomation } = require('./automation.cjs');
+const { callTool } = require('./desktop-tools.cjs');
+const { spawn } = require('node:child_process');
+const fs = require('node:fs');
+const path = require('node:path');
+const assert = require('node:assert/strict');
+async function runDevPreview({ output }) {
+ const root = path.join(output, 'dev-project'); fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ scripts: { dev: 'bun server.ts' } }));
+ fs.writeFileSync(path.join(root, 'server.ts'), `const server=Bun.serve({port:0,hostname:'127.0.0.1',fetch(){return new Response(Bun.file('index.html'),{headers:{'content-type':'text/html'}})}});console.log(server.url.href);`);
+ const html = title => `<!doctype html><title>${title}</title><h1>${title}</h1><input id="name" aria-label="Name"><button id="go" onclick="document.querySelector('h1').textContent='Hello '+document.querySelector('input').value">Greet</button>`;
+ fs.writeFileSync(path.join(root, 'index.html'), html('Initial preview'));
+ const bun = process.env.GRAFF_TEST_BUN || 'bun';
+ const child = spawn(bun, ['run', 'dev'], { cwd: root, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PATH: `${path.dirname(bun)}:${process.env.PATH}` } });
+ const win = new BrowserWindow({ width: 900, height: 600, show: true });
+ const events = [], browser = new BrowserTabs(win, event => events.push(event));
+ let bridge;
+ try {
+ const url = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(Error('Bun dev server did not start')), 10000);
+ let text = ''; child.stdout.on('data', chunk => { text += chunk; const match = text.match(/http:\/\/127\.0\.0\.1:\d+\//); if (match) { clearTimeout(timer); resolve(match[0]); } });
+ child.once('error', error => { clearTimeout(timer); reject(error); });
+ child.once('exit', code => { clearTimeout(timer); reject(Error(`Dev server exited: ${code}`)); });
+ });
+ bridge = await startAutomation(browser, null, null);
+ const handle = bridge.handle('preview-test');
+ const env = { GRAFF_DESKTOP_ENDPOINT: `http://127.0.0.1:${handle.port}`, GRAFF_DESKTOP_SECRET: handle.token, GRAFF_DESKTOP_CHAT: 'preview-test' };
+ const tool = args => callTool('browser', args, env);
+ await tool({ action: 'open', url });
+ browser.setBounds('preview-test', { x: 0, y: 0, width: 900, height: 550 });
+ assert.ok(events.some(e => e.type === 'show'), 'Opening a preview requests the shared browser pane');
+ assert.match(JSON.stringify(await tool({ action: 'snapshot' })), /Initial preview/);
+ await tool({ action: 'fill', selector: '#name', text: 'Codegraff' });
+ await tool({ action: 'click', selector: '#go' });
+ assert.match(JSON.stringify(await tool({ action: 'snapshot' })), /Hello Codegraff/);
+ fs.writeFileSync(path.join(root, 'index.html'), html('Updated preview'));
+ await tool({ action: 'navigate', url });
+ assert.match(JSON.stringify(await tool({ action: 'snapshot' })), /Updated preview/);
+ const shot = await tool({ action: 'screenshot' });
+ const image = shot.content.find(c => c.type === 'image'); assert.ok(image?.data);
+ fs.writeFileSync(path.join(output, 'bun-dev-preview.png'), Buffer.from(image.data, 'base64'));
+ console.log('Bun dev preview passed through desktop tool transport: open, snapshot, fill, click, edit/reload, screenshot.');
+ } finally {
+ browser.closeAll(); bridge?.server.close(); win.destroy();
+ if (child.pid) try { process.kill(-child.pid, 'SIGTERM'); } catch {}
+ }
+}
+module.exports = { runDevPreview };
diff --git a/apps/native/electron/gallery-fixture.cjs b/apps/native/electron/gallery-fixture.cjs
index 6662c40a..b9e2b843 100644
--- a/apps/native/electron/gallery-fixture.cjs
+++ b/apps/native/electron/gallery-fixture.cjs
@@ -1,6 +1,8 @@
// Synthetic content for reproducible screenshots; never reads the user's workspace.
function installGalleryFixture() {
const original = window.fetch;
+ // Page unload must use the mocked fetch path too, never a real ACP beacon.
+ navigator.sendBeacon = () => false;
localStorage.setItem('graff.native.browser.open', '0');
const root = '/demo/field-notes';
const catalog = { result: { current: { model: 'Graff', provider: '', effort: 'medium', fast: false, effortLevels: ['low', 'medium', 'high'] }, models: [{ name: 'Graff', provider: '', context: 128000, authenticated: true, cost: 'local', current: true }] } };
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index 32448836..549fe235 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -63,6 +63,8 @@ app.whenReady().then(async () => {
title: 'Codegraff', titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 14, y: 11 }, backgroundColor: '#fafaf9', show: false,
webPreferences: { preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:app',
contextIsolation: true, sandbox: true, nodeIntegration: false, backgroundThrottling: !process.env.GRAFF_ELECTRON_SMOKE } });
+ const projects = require('./project-store.cjs').projectStore(app.getPath('userData'));
+ ipcMain.handle('projects', (event, { action, value }) => { trusted(event); if (action === 'load') return projects.load(); if (action === 'save') return projects.save(value); throw Error('Unknown project action'); });
installWindowState(win);
terminals = new Terminals(path.join(resources, 'native/graff-terminal'), event => { if (!win.isDestroyed()) win.webContents.send('terminal-event', event); });
ipcMain.handle('terminal', (event, {action, params}) => { trusted(event); return terminals.command(action, params); });
diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjs
index ad4135c5..4779acae 100644
--- a/apps/native/electron/navigation-visual.cjs
+++ b/apps/native/electron/navigation-visual.cjs
@@ -6,6 +6,7 @@ const sleep=ms=>new Promise(r=>setTimeout(r,ms));
async function runNavigationVisuals({win:fixtureWindow,origin,output}) {
const win=new BrowserWindow({width:1100,height:760,show:true,titleBarStyle:'hiddenInset',webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});
installWindowState(win);ipcMain.handle('browser',()=>null);
+ ipcMain.handle('projects',()=>null);
// The demo workspace name maps to a disposable real folder for PTY checks.
const terminalRoot=path.join(output,'terminal-workspace');fs.mkdirSync(terminalRoot,{recursive:true});
const helper=path.join(output,'graff-terminal');
@@ -25,6 +26,7 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {
const commands=[{name:'compact',description:'Compact conversation context'},...Array.from({length:100},(_,i)=>({name:'command-'+i,description:'Command '+i}))];
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('./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/);
@@ -52,6 +54,6 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {
assert.equal(await js(`!!document.querySelector('[data-workspace-menu]')`),false);
if(process.platform==='darwin')await require('./terminal-visual.cjs').runTerminalVisual({win,output});
console.log('Navigation visual checks passed: command catalog/new tabs, bounded keyboard menu, new/close/reopen, splits/zoom/resize, workspace search.');
- } finally {terminals.closeAll();ipcMain.removeHandler('terminal');ipcMain.removeHandler('browser');win.destroy();fixtureWindow.show();fixtureWindow.focus();}
+ } finally {terminals.closeAll();ipcMain.removeHandler('terminal');ipcMain.removeHandler('browser');ipcMain.removeHandler('projects');win.destroy();fixtureWindow.show();fixtureWindow.focus();}
}
module.exports={runNavigationVisuals};
diff --git a/apps/native/electron/preload.cjs b/apps/native/electron/preload.cjs
index 88671eda..64178f4e 100644
--- a/apps/native/electron/preload.cjs
+++ b/apps/native/electron/preload.cjs
@@ -1,5 +1,6 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('graffDesktop', {
+ projects: (action, value) => ipcRenderer.invoke('projects', { action, value }),
updates: action => ipcRenderer.invoke('updates', action),
updateSubscribe: callback => {
const listener = (_event, state) => callback(state);
diff --git a/apps/native/electron/project-store.cjs b/apps/native/electron/project-store.cjs
new file mode 100644
index 00000000..9a319bbb
--- /dev/null
+++ b/apps/native/electron/project-store.cjs
@@ -0,0 +1,27 @@
+const fs = require('node:fs/promises');
+const path = require('node:path');
+function validate(value) {
+ if (!value || !Array.isArray(value.list) || value.list.length > 50) throw Error('Invalid project list');
+ const list = value.list.map(row => {
+ if (!row || typeof row.path !== 'string' || !path.isAbsolute(row.path) || row.path.length > 4096 || typeof row.name !== 'string' || row.name.length > 512) throw Error('Invalid project');
+ return { path: row.path, name: row.name, ...(typeof row.model === 'string' ? { model: row.model.slice(0, 256) } : {}),
+ ...(typeof row.yolo === 'boolean' ? { yolo: row.yolo } : {}), ...(typeof row.mcp === 'boolean' ? { mcp: row.mcp } : {}) };
+ });
+ return { list, active: list.some(row => row.path === value.active) ? value.active : null };
+}
+function projectStore(directory) {
+ const file = path.join(directory, 'projects.json'); let pending = Promise.resolve();
+ return {
+ async load() { await pending; try { return validate(JSON.parse(await fs.readFile(file, 'utf8'))); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } },
+ save(value) {
+ const data = validate(value);
+ const write = pending.then(async () => {
+ await fs.mkdir(directory, { recursive: true });
+ await fs.writeFile(`${file}.next`, JSON.stringify(data), { mode: 0o600 });
+ await fs.rename(`${file}.next`, file);
+ });
+ pending = write.catch(() => {}); return write;
+ },
+ };
+}
+module.exports = { projectStore };
diff --git a/apps/native/electron/project-store.test.cjs b/apps/native/electron/project-store.test.cjs
new file mode 100644
index 00000000..a33ffe85
--- /dev/null
+++ b/apps/native/electron/project-store.test.cjs
@@ -0,0 +1,14 @@
+const { test, expect } = require('bun:test');
+const { projectStore } = require('./project-store.cjs');
+const fs = require('node:fs/promises'), os = require('node:os'), path = require('node:path');
+test('project choices survive a new process/store and preserve the latest selection', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-project-store-'));
+ try {
+ const store = projectStore(root);
+ expect(await store.load()).toBeNull();
+ const list = [{ path: '/projects/one', name: 'one' }, { path: '/projects/two', name: 'two', mcp: false }];
+ await Promise.all([store.save({ list, active: list[0].path }), store.save({ list, active: list[1].path })]);
+ expect(await projectStore(root).load()).toEqual({ list, active: '/projects/two' });
+ expect(() => store.save({ list: [{ path: '../escape', name: 'bad' }] })).toThrow('Invalid project');
+ } finally { await fs.rm(root, { recursive: true }); }
+});
diff --git a/apps/native/electron/projects-visual.cjs b/apps/native/electron/projects-visual.cjs
new file mode 100644
index 00000000..653d8130
--- /dev/null
+++ b/apps/native/electron/projects-visual.cjs
@@ -0,0 +1,50 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+async function runProjectVisuals({ win, origin, output }) {
+ const wc = win.webContents, js = code => wc.executeJavaScript(code);
+ const wait = async code => { for (let i = 0; i < 100; i++) { if (await js(code)) return; await new Promise(r => setTimeout(r, 50)); } throw Error(`Project check timed out: ${code}`); };
+ await js(`window.projectRequests=[];const projectFetch=window.fetch;window.fetch=(input,options)=>{window.projectRequests.push(String(input));return projectFetch(input,options);};true`);
+ await js(`document.querySelector('button[aria-label="Projects"]').click()`);
+ await wait(`!!document.querySelector('[aria-label="Search projects"]')`);
+ await js(`(()=>{const e=document.querySelector('[aria-label="Search projects"]');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,'folder-42');e.dispatchEvent(new Event('input',{bubbles:true}));})()`);
+ await wait(`document.querySelectorAll('[data-project-path]').length===1`);
+ assert.equal(await js(`document.querySelector('[data-project-path]').dataset.projectPath`), '/demo/folder-42');
+ fs.writeFileSync(path.join(output, 'projects.png'), (await wc.capturePage()).toPNG());
+ await js(`document.querySelector('[data-project-path] button').click()`);
+ await wait(`document.querySelector('[data-conversation-project]')?.textContent==='/demo/folder-42'`);
+ await wait(`window.projectRequests.some(p=>p.includes('/api/sessions?')&&p.includes('root=%2Fdemo%2Ffolder-42')&&p.includes('scope=local'))`);
+ const before = await js(`document.querySelectorAll('[aria-label="Close tab"]').length`);
+ await js(`document.querySelector('button[aria-label="Projects"]').click()`);
+ await wait(`!!document.querySelector('[data-project-path="/demo/folder-42"]')`);
+ await js(`document.querySelector('[data-project-path="/demo/folder-42"] button:last-child').click()`);
+ await wait(`document.querySelector('[data-project-context]')?.textContent.includes('/demo/folder-42')`);
+ assert.equal(await js(`document.querySelectorAll('[aria-label="Close tab"]').length`), before + 1, 'New project chat creates exactly one tab');
+ await js(`document.querySelector('button[aria-label="Projects"]').click()`);
+ await wait(`!!document.querySelector('[data-project-path="/demo/folder-43"]')`);
+ await js(`document.querySelector('[data-project-path="/demo/folder-43"] button:last-child').click()`);
+ await wait(`document.querySelector('[data-project-context]')?.textContent.includes('/demo/folder-43')`);
+ await js(`document.querySelector('[aria-label="Close tab"]').parentElement.querySelector('button[aria-pressed]').click()`);
+ await wait(`document.querySelector('[data-project-context]')?.textContent.includes('/demo/folder-42')`);
+ await js(`document.querySelector('button[aria-label="New chat"]').click()`);
+ await wait(`document.querySelector('[data-project-context]')?.textContent.includes('/demo/folder-42')`);
+ await js(`document.querySelector('button[aria-label="Changes"]').click()`);
+ await wait(`document.querySelector('button[aria-label="Changes"]')?.getAttribute('aria-current')==='page'`);
+ await wait(`document.body.textContent.includes('palette.css')`);
+ await js(`document.querySelector('button[aria-label="Files"]').click()`);
+ await wait(`document.querySelector('button[aria-label="Files"]')?.getAttribute('aria-current')==='page'`);
+ assert.equal(await js(`document.querySelector('button[aria-label="Changes"]')?.getAttribute('aria-current')`), null);
+ await js(`document.querySelector('button[aria-label="Open folder…"]').click()`);
+ await wait(`!!document.querySelector('[role="dialog"]')`);
+ await wc.loadURL(origin);
+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
+ win.setSize(900, 680);
+ await js(`Array.from(document.querySelectorAll('button')).find(b=>b.textContent==='All projects').click()`);
+ await wait(`!!document.querySelector('[aria-label="Search projects"]')`);
+ assert.ok(await js(`(()=>{const r=document.querySelector('section[aria-label="Projects"]').getBoundingClientRect();return r.left>=0&&r.right<=innerWidth})()`));
+ await js(`Array.from(document.querySelectorAll('button')).find(b=>b.textContent==='Back to chat').click()`);
+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);
+ win.setSize(1100, 760);
+ console.log('Projects passed: search, folder identity, scoped resume, exactly one new tab, visible Changes/Files, open folder.');
+}
+module.exports = { runProjectVisuals };
diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjs
index d1df5aff..a4899a61 100644
--- a/apps/native/electron/visual-tests.cjs
+++ b/apps/native/electron/visual-tests.cjs
@@ -37,6 +37,14 @@ app.whenReady().then(async () => {
fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: ['update UI', 'update transport'], apiRequests }, null, 2));
return;
}
+ if (process.env.GRAFF_VISUAL_SUITE === 'projects') {
+ await require('./navigation-visual.cjs').runNavigationVisuals({ win, origin, output });
+ await require('./browser-visual.cjs').runBrowserVisuals({ win, origin, output });
+ await require('./dev-preview-visual.cjs').runDevPreview({ output });
+ assert.deepEqual(apiRequests, [], 'Project fixtures never call engine or model APIs');
+ fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: ['projects and navigation', 'browser'], apiRequests }, null, 2));
+ 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/desktop.ts b/apps/native/lib/desktop.ts
index df9fdc74..629359b6 100644
--- a/apps/native/lib/desktop.ts
+++ b/apps/native/lib/desktop.ts
@@ -5,6 +5,7 @@ export type DesktopEvent = { type: string; chat?: string; info?: PageInfo; pin?:
export type TerminalEvent = { id: string; seq: number; data?: string; exit?: number };
export type UpdateState = { status: 'idle' | 'unavailable' | 'checking' | 'current' | 'downloading' | 'ready' | 'installing' | 'error'; currentVersion: string; version?: string; percent?: number; automatic: boolean; interactive: boolean; message?: string };
export type DesktopBridge = {
+ projects?(action: 'load' | 'save', value?: { list: import('./workspaces').Workspace[]; active: string | null }): Promise<{ list: import('./workspaces').Workspace[]; active: string | null } | null | void>;
updates?(action: 'state' | 'check' | 'restart'): Promise<UpdateState>;
updateSubscribe?(callback: (state: UpdateState) => void): () => void;
terminal?(action: string, params?: Record<string, unknown>): Promise<{id: string; seq: number; history: string; exit: number | null}>;
diff --git a/apps/native/lib/project-preferences.ts b/apps/native/lib/project-preferences.ts
new file mode 100644
index 00000000..efee84ec
--- /dev/null
+++ b/apps/native/lib/project-preferences.ts
@@ -0,0 +1,15 @@
+import { desktop } from './desktop';
+import { loadWorkspaces, loadActiveWorkspace, saveWorkspaces, saveActiveWorkspace, type Workspace } from './workspaces';
+export async function restoreProjects(storage: Storage) {
+ try {
+ const saved = await desktop()?.projects?.('load');
+ if (saved) { saveWorkspaces(storage, saved.list); saveActiveWorkspace(storage, saved.active); return saved; }
+ } catch { /* Older desktops and damaged settings can still recover browser preferences. */ }
+ return { list: loadWorkspaces(storage), active: loadActiveWorkspace(storage) };
+}
+export function persistProjects(storage: Storage, list: Workspace[], active: string | null) {
+ saveWorkspaces(storage, list); saveActiveWorkspace(storage, active);
+ void desktop()?.projects?.('save', { list, active }).catch(() => {
+ // The browser copy remains available if the settings volume is unavailable.
+ });
+}
diff --git a/apps/native/lib/workspaces.ts b/apps/native/lib/workspaces.ts
index 3885962a..7c5242c5 100644
--- a/apps/native/lib/workspaces.ts
+++ b/apps/native/lib/workspaces.ts
@@ -1,6 +1,6 @@
/** 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
+ * list and active pick use localStorage in the web client; the desktop also
+ * persists them in its settings independently of the UI origin. Pure helpers so the list rules
* are testable without a DOM. */
export const WORKSPACES_KEY = "graff.native.workspaces";
diff --git a/apps/native/package.json b/apps/native/package.json
index a7d1fbd2..c6a6ef55 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -16,6 +16,7 @@
"test:desktop": "bun test lib ./electron/*.test.cjs",
"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: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.md
new file mode 100644
index 00000000..5acb3cc8
--- /dev/null
+++ b/docs/adr/0080-desktop-projects-are-folders.md
@@ -0,0 +1,28 @@
+# 0080. Desktop projects are folders with durable local preferences
+
+Status: accepted
+
+## Context
+
+Folder selection was hidden in a workspace menu, and the Workspace navigation
+item opened files. Project preferences lived only in browser storage, so a
+different local server port could make saved projects appear absent.
+
+## Decision
+
+Projects provides folder discovery, new chats and a route to saved conversations.
+Files and Changes have separate navigation. Conversation discovery defaults to
+the selected project; other saved conversations remain available through filters.
+Focusing a chat selects its folder for subsequent new chats.
+
+The desktop saves project preferences in its application settings through
+validated main-process IPC and serialized atomic writes. Existing browser values
+are migrated on first use and retained as a fallback. Preferences contain folder
+choices, not conversation history. The web client continues using browser storage.
+
+## Validation
+
+The project-store test covers restart persistence and ordered writes. The offline
+desktop project suite covers folder selection, scoped conversation discovery,
+new chat inheritance, and separate Files/Changes navigation. Its preview fixture
+starts Bun and exercises the browser tool transport without a model call.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8a764d5d..33e9fe8a 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -90,6 +90,7 @@ record only when you need the evidence or the edge cases.
| [0077](0077-desktop-command-parity-and-bounded-disclosure.md) | ACP shares the complete REPL catalog; desktop menus, tool disclosure and initial history rendering stay bounded. |
| [0078](0078-workspace-terminals-are-lazy-pty-sessions.md) | Desktop workspace terminals start lazily, preserve hidden shells and bound output through a trusted PTY bridge. |
| [0079](0079-desktop-updates-are-signed-and-user-restarted.md) | Signed desktop updates download in the background and install only on explicit restart; one process owns each profile. |
+| [0080](0080-desktop-projects-are-folders.md) | Desktop projects are folders; preferences survive local UI origin changes, and new chats inherit the focused project's folder. |
## When to write one