graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Preserve desktop chats through reloads and group workspace history
Rach Pradhan8acfd7610eec
diff --git a/apps/native/app/api/workspace-history/route.ts b/apps/native/app/api/workspace-history/route.tsindex 0714b965..8fa52ee2 100644--- a/apps/native/app/api/workspace-history/route.ts+++ b/apps/native/app/api/workspace-history/route.ts@@ -4,5 +4,6 @@ import { defaultRoot } from "@/lib/server-root";export const runtime = "nodejs";export const dynamic = "force-dynamic";export async function GET(req: NextRequest) {- return Response.json({ workspaces: discoverWorkspaceHistory([defaultRoot(), ...req.nextUrl.searchParams.getAll("root").slice(0, 50)]) });+ const saved = req.nextUrl.searchParams.getAll("root").slice(0, 50);+ return Response.json({ workspaces: discoverWorkspaceHistory([defaultRoot(), ...saved], undefined, saved) });}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 064937af..077d92b1 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -5,6 +5,8 @@ import { useResponsiveNavigation } from "./useResponsiveNavigation";import { useNavigationPromptFocus } from "./useNavigationPromptFocus";import { useUnreadChats } from "./useUnreadChats";import { useHarnessSessions } from "./useHarnessSessions";+import { restoreOpenTabs, usePageRecovery } from "./page-recovery";+import { usePromptRecall } from "./usePromptRecall";import { resumeQueuedPrompt } from "@/lib/prompt-queue-resume";import { createPromptRunner } from "./harness-prompt-runner";import { workspaceActions } from "./harness-workspace-actions";@@ -49,7 +51,7 @@ import { enqueuePrompt } from "@/lib/prompt-queue";import { usePromptQueue, steerOrInterrupt } from "./usePromptQueue";import { useChatClose } from "./useChatClose";import { type StoredSession } from "@/lib/sessions";-import { loadHistory, mergeHistory } from "@/lib/prompt-history";+import { mergeHistory } from "@/lib/prompt-history";import { basename, chatProject, displayWorkspace, findWorkspace, type Workspace } from "@/lib/workspaces";export default function GraffHarness() {@@ -85,12 +87,7 @@ export default function GraffHarness() {const [claims, setClaims] = useState<{ kind: string; key: string; session: string }[]>([]);const [fileRequest, setFileRequest] = useState<{ path: string; n: number; changes?: boolean } | null>(null);const fileReqRef = useRef(0);- // Shell-style prompt recall (ArrowUp in the composer), kept per browser so- // a new tab or a reload still has the last prompts under the cursor.- const [history, setHistory] = useState<string[]>([]);- useEffect(() => {- setHistory(loadHistory(window.localStorage));- }, []);+ const [history, setHistory] = usePromptRecall();// Workspaces are the folders graff runs in. The list and the active pick// persist in desktop settings, with browser storage as a migration/fallback.// Refs mirror the state for the async paths (spawn, session list) that@@ -183,8 +180,9 @@ export default function GraffHarness() {const { adoptCatalog, refreshChangedCatalog, requireSession, refreshStored, projectsReady, unwatchIdle, chatCatalogs, catalogStatus, applyCatalog } = useHarnessSessions({ onPermission: permissions.update,sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal,pendingPick: () => pendingPickRef.current ?? pendingModel,+ restoreTabs: () => restoreOpenTabs({ chatsRef, sessionNamesRef, chatIdRef, msgIdRef, setChats, setActiveId, restoreGroups: groups.restore }),});-+ usePageRecovery(projectsReady, chats, activeId, groups.groups, busyIds, runningRef);const { openPath, openReference } = useReferenceNavigation({context: (id = activeIdRef.current) => ({ root: chatsRef.current.find(c => c.id === id)?.cwd ?? activePathRef.current ?? health?.cwd, chat: handleOf(id), focus: () => focusChat(id) }),hideOtherPanes: () => { setProjectsOpen(false); setAgentsOpen(false); setConversationsOpen(false); setReviewsOpen(false); },diff --git a/apps/native/components/site/page-recovery.test.ts b/apps/native/components/site/page-recovery.test.tsnew file mode 100644index 00000000..e951991d--- /dev/null+++ b/apps/native/components/site/page-recovery.test.ts@@ -0,0 +1,46 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { restoreOpenTabs } from './page-recovery';+import { TAB_RECOVERY_KEY } from '@/lib/tab-recovery';+import type { Chat } from './harness-types';++test('a new page restores saved tabs in their original workspaces and keeps a missing checkpoint visible', async () => {+ const previousWindow = globalThis.window;+ const previousFetch = globalThis.fetch;+ const tabs = [+ { id: 4, session: 'native-saved', cwd: '/repo/.graff/worktrees/a', title: 'Old title' },+ { id: 7, session: 'native-unsaved', cwd: '/repo/.graff/worktrees/b', title: null },+ ];+ Object.assign(globalThis, { window: { localStorage: { getItem: (key: string) => key === TAB_RECOVERY_KEY+ ? JSON.stringify({ tabs, activeId: 7, groups: [{ ids: [4, 7], direction: 'row' }] }) : null } } });+ const paths: string[] = [];+ globalThis.fetch = async (input) => {+ paths.push(String(input));+ return String(input).includes('native-unsaved') ? new Response('', { status: 404 })+ : Response.json({ name: 'native-saved', title: 'Saved title', model: 'test-model',+ presentation: 'transcript-v1', transcript: [{ role: 'user', text: 'Earlier prompt' }] });+ };+ let chats: Chat[] = [{ id: 1, title: null, messages: [] }], active = 1, groups: unknown;+ const chatsRef = { current: chats }, sessionNamesRef = { current: new Map<number, string>() };+ const chatIdRef = { current: 1 }, msgIdRef = { current: 0 };+ try {+ const id = await restoreOpenTabs({ chatsRef, sessionNamesRef, chatIdRef, msgIdRef,+ setChats: value => { chats = typeof value === 'function' ? value(chats) : value; },+ setActiveId: value => { active = typeof value === 'function' ? value(active) : value; },+ restoreGroups: value => { groups = value; } });+ assert.equal(id, 7);+ assert.equal(active, 7);+ assert.deepEqual(chats.map(chat => chat.id), [4, 7]);+ assert.equal(chats[0].title, 'Saved title');+ assert.equal(chats[0].messages[0].role, 'user');+ assert.equal(chats[0].snapshot, undefined);+ assert.equal(chats[1].messages.length, 0);+ assert.equal(chatIdRef.current, 7);+ assert.equal(sessionNamesRef.current.get(4), 'native-saved');+ assert.deepEqual(groups, [{ ids: [4, 7], direction: 'row' }]);+ assert.ok(paths.some(path => path.includes('root=%2Frepo%2F.graff%2Fworktrees%2Fa')));+ } finally {+ Object.assign(globalThis, { window: previousWindow });+ globalThis.fetch = previousFetch;+ }+});diff --git a/apps/native/components/site/page-recovery.ts b/apps/native/components/site/page-recovery.tsnew file mode 100644index 00000000..a4d9db6e--- /dev/null+++ b/apps/native/components/site/page-recovery.ts@@ -0,0 +1,59 @@+import { useEffect, useRef, type Dispatch, type SetStateAction } from "react";+import { loadSession } from "@/lib/sessions";+import { loadTabRecovery, saveTabRecovery, tabRecovery } from "@/lib/tab-recovery";+import type { Chat, Msg } from "./harness-types";+import type { ChatGroup } from "@/lib/chat-groups";++type Ref<T> = { current: T };+type Setter<T> = Dispatch<SetStateAction<T>>;++export async function restoreOpenTabs({ chatsRef, sessionNamesRef, chatIdRef, msgIdRef, setChats, setActiveId, restoreGroups }: {+ chatsRef: Ref<Chat[]>; sessionNamesRef: Ref<Map<number, string>>; chatIdRef: Ref<number>; msgIdRef: Ref<number>;+ setChats: Setter<Chat[]>; setActiveId: Setter<number>; restoreGroups(groups: ChatGroup[]): void;+}): Promise<number | null> {+ const saved = loadTabRecovery(window.localStorage);+ if (!saved) return null;+ const restored: Chat[] = saved.tabs.map(tab => ({ ...tab, messages: [] }));+ chatsRef.current = restored;+ setChats(restored);+ chatIdRef.current = Math.max(...restored.map(chat => chat.id));+ for (const chat of restored) sessionNamesRef.current.set(chat.id, chat.session!);+ restoreGroups(saved.groups);+ setActiveId(saved.activeId);+ const loaded = await Promise.allSettled(saved.tabs.map(tab => loadSession(tab.session!, tab.cwd, AbortSignal.timeout(10_000))));+ const checkpoint = new Map(restored.map((chat, index) => [chat.id, loaded[index]]));+ const hydrated = chatsRef.current.map(chat => {+ const result = checkpoint.get(chat.id);+ if (result?.status !== "fulfilled" || restored.find(tab => tab.id === chat.id)?.session !== chat.session) return chat;+ const messages: Msg[] = result.value.messages.map(m => ({ id: ++msgIdRef.current, ...m }));+ return { ...chat, title: result.value.meta.title ?? chat.title, messages, model: result.value.meta.model ?? chat.model };+ });+ // Missing checkpoints leave a usable tab. The next prompt starts or resumes+ // it through the ordinary ACP path, using the original session and cwd.+ chatsRef.current = hydrated;+ setChats(hydrated);+ return saved.activeId;+}++export function usePageRecovery(ready: boolean, chats: Chat[], activeId: number, groups: ChatGroup[], busy: ReadonlySet<number>, runningRef: Ref<Set<number>>) {+ const lastSaved = useRef("");+ useEffect(() => {+ if (!ready) return;+ const snapshot = tabRecovery(chats, activeId, groups);+ const signature = JSON.stringify(snapshot);+ if (signature !== lastSaved.current) {+ saveTabRecovery(window.localStorage, snapshot);+ lastSaved.current = signature;+ }+ }, [ready, chats, activeId, groups]);+ useEffect(() => { window.graffDesktop?.activeTurns?.(busy.size); }, [busy]);+ useEffect(() => {+ const warn = (event: BeforeUnloadEvent) => {+ if (!runningRef.current.size) return;+ event.preventDefault();+ event.returnValue = "";+ };+ window.addEventListener("beforeunload", warn);+ return () => window.removeEventListener("beforeunload", warn);+ }, [runningRef]);+}diff --git a/apps/native/components/site/useChatGroups.ts b/apps/native/components/site/useChatGroups.tsindex 73da414d..99cea6f0 100644--- a/apps/native/components/site/useChatGroups.ts+++ b/apps/native/components/site/useChatGroups.ts@@ -32,7 +32,7 @@ export function useChatGroups(chats: Chat[], activeId: number) {const tree=apply(group.tree??flatSplit(group.ids,group.direction));return old.map(item=>item===group?{ids:splitIds(tree),tree,direction:typeof tree==='number'?'row':tree.axis}:item);});- return { groups, tabs, panes, setPanes, tree: current?.tree, setTree: (tree:SplitTree)=>updateTree(()=>tree),+ return { groups, tabs, panes, setPanes, restore: (saved: ChatGroup[]) => setLayouts(saved), tree: current?.tree, setTree: (tree:SplitTree)=>updateTree(()=>tree),resize: (delta:number)=>updateTree(tree=>resizeChatSplit(tree,activeId,delta)), balance: ()=>updateTree(balanceSplit),split(source:number,target:number,edge:'left'|'right'|'top'|'bottom') {setLayouts(old=>{diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.tsindex fffca05a..574a2e6e 100644--- a/apps/native/components/site/useHarnessSessions.ts+++ b/apps/native/components/site/useHarnessSessions.ts@@ -25,9 +25,10 @@ type Props = {setWorkspaces: Setter<Workspace[]>; setActivePath: Setter<string | null>;setChats: Setter<Chat[]>; setStored: Setter<StoredSession[]>; setStoredTotal: Setter<number>;pendingPick(): { key: string; chatId: number } | null;+ restoreTabs(): Promise<number | null>;};const SIDEBAR_PAGE = 12;-export function useHarnessSessions({onPermission, sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal, pendingPick}: Props) {+export function useHarnessSessions({onPermission, sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal, pendingPick, restoreTabs}: Props) {const [projectsReady, setProjectsReady] = useState(false);const [chatCatalogs, setChatCatalogs] = useState<Record<number, PromptModel[]>>({});const catalogForSpawn = useRef<Record<number, { cwd?: string; models: PromptModel[] }>>({});@@ -201,6 +202,15 @@ export function useHarnessSessions({onPermission, sessionsRef, sessionNamesRef,setWorkspaces(list);setActivePath(active);persistProjects(window.localStorage, list, active);+ const restoredId = await restoreTabs();+ if (cancelled) return;+ if (restoredId !== null) {+ setProjectsReady(true);+ void refreshStored();+ if (!window.graffDesktop) await requireSession(restoredId);+ if (!cancelled) await adoptCatalog(restoredId);+ return;+ }if (active) setChats((current) => current.map((c) => (c.id === 1 && !c.cwd ? { ...c, cwd: active } : c)));void refreshStored();try {diff --git a/apps/native/components/site/usePromptRecall.ts b/apps/native/components/site/usePromptRecall.tsnew file mode 100644index 00000000..f396fa94--- /dev/null+++ b/apps/native/components/site/usePromptRecall.ts@@ -0,0 +1,8 @@+import { useEffect, useState } from "react";+import { loadHistory } from "@/lib/prompt-history";++export function usePromptRecall() {+ const [history, setHistory] = useState<string[]>([]);+ useEffect(() => { setHistory(loadHistory(window.localStorage)); }, []);+ return [history, setHistory] as const;+}diff --git a/apps/native/electron/frontend-runtime.cjs b/apps/native/electron/frontend-runtime.cjsindex cc74039c..8f2b92db 100644--- a/apps/native/electron/frontend-runtime.cjs+++ b/apps/native/electron/frontend-runtime.cjs@@ -332,6 +332,7 @@ app.whenReady().then(async () => {await require('./attachment-lifetime-frontend.cjs').runAttachments({win,origin,temp,output,requests,workspace,send,click,until,report});if (narrowNavigation) return;await require('./browser-focus-frontend.cjs').runBrowserFocus({ win, output, click, until, report });+ await require('./page-recovery-visual.cjs').runPageRecovery({ win, report });await require('./tab-drag-visual.cjs').runTabDrag({ win, origin, output });report.passed.push('trusted pointer and keyboard: tab reorder, horizontal/vertical splits, draft retention, Escape and four-pane limit');await js(`localStorage.setItem('graff.native.browser.open', '1')`);diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjsindex 14967139..25b15f3a 100644--- a/apps/native/electron/main.cjs+++ b/apps/native/electron/main.cjs@@ -108,6 +108,7 @@ app.whenReady().then(async () => {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'));+ const { preflight, reload } = require('./transition-guard.cjs').installTransitionGuard({ win, ipcMain, trusted, dialog });ipcMain.on('workspace-ready', event => { trusted(event); workspaceRequests.ready(); });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);@@ -240,7 +241,7 @@ app.whenReady().then(async () => {});win.on('minimize', () => { if (browser.visible) browser.hide(browser.visible); });win.on('restore', () => win.webContents.send('browser-event', { type: 'layout' }));- const updateMenu = require('./updates.cjs').installUpdates({ app, win, ipcMain, trusted, resources });+ const updateMenu = require('./updates.cjs').installUpdates({ app, win, ipcMain, trusted, resources, preflight });Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: appName, submenu: [{ role: 'about' }, ...updateMenu, { type: 'separator' }, { label: 'Activity…', accelerator: 'CmdOrCtrl+,', click: () => void activity().catch(error => dialog.showErrorBox('Activity', error.message)) }, { label: 'Computer use…', visible: process.platform === 'darwin', click: () => void computer.configure().catch(error => dialog.showErrorBox('Computer use', error.message)) }, { type: 'separator' }, { role: 'quit' }] },{ label: 'File', submenu: [@@ -268,7 +269,7 @@ app.whenReady().then(async () => {} }, { label: 'Browser passkey help…', click: () => void require('./webauthn.cjs').showPasskeyHelp({window: win, browser, dialog, shell: require('electron').shell, configured: passkeysConfigured,}).catch(() => dialog.showErrorBox('Browser passkeys', 'Could not open the default browser. Use another sign-in method on the site.')) }] },- { role: 'editMenu' }, { label: 'View', submenu: [{ role: 'reload' }, { role: 'toggleDevTools' }, { role: 'togglefullscreen' }, { label: 'Session observer', type: 'checkbox', checked: !!notch?.enabled(), visible: process.platform === 'darwin', click: item => { item.checked = notch?.setEnabled(item.checked) ?? false; } }, { label: 'Release browser pages', click: () => { browser.closeAll(); win.webContents.send('browser-event', { type: 'released' }); } }] },+ { role: 'editMenu' }, { label: 'View', submenu: [{ label: 'Reload', accelerator: 'CmdOrCtrl+R', click: () => void reload() }, { role: 'toggleDevTools' }, { role: 'togglefullscreen' }, { label: 'Session observer', type: 'checkbox', checked: !!notch?.enabled(), visible: process.platform === 'darwin', click: item => { item.checked = notch?.setEnabled(item.checked) ?? false; } }, { label: 'Release browser pages', click: () => { browser.closeAll(); win.webContents.send('browser-event', { type: 'released' }); } }] },{ label: 'Performance', submenu: [{ label: 'Start recording', click: () => void profiler.start() },{ label: 'Mark candidate phase', click: () => profiler.mark('candidate') },diff --git a/apps/native/electron/page-recovery-visual.cjs b/apps/native/electron/page-recovery-visual.cjsnew file mode 100644index 00000000..7a12d7df--- /dev/null+++ b/apps/native/electron/page-recovery-visual.cjs@@ -0,0 +1,31 @@+const assert = require('node:assert/strict');++async function runPageRecovery({ win, report }) {+ const wc = win.webContents;+ const read = () => wc.executeJavaScript(`(() => ({+ tabs: [...document.querySelectorAll('[data-tab-id]')].map(node => Number(node.dataset.tabId)),+ active: Number(document.querySelector('[data-tab-id] button[aria-pressed="true"]')?.closest('[data-tab-id]')?.dataset.tabId),+ record: JSON.parse(localStorage.getItem('graff.native.open-tabs.v1') || 'null'),+ ready: !!document.querySelector('[data-workspace-ready="true"]'),+ }))()`);+ const wait = async predicate => {+ for (let attempt = 0; attempt < 100; attempt++) {+ const state = await read();+ if (predicate(state)) return state;+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ throw Error('Open tabs did not recover after reload');+ };+ const initial = await wait(state => state.ready && state.tabs.length > 0 && state.record?.tabs?.length > 0);+ await wc.executeJavaScript(`window.dispatchEvent(new CustomEvent('graff-desktop-action', {detail:'new'}))`);+ const before = await wait(state => state.tabs.length === initial.tabs.length + 1 && state.record?.tabs?.length === state.tabs.length);+ assert.equal(before.record.activeId, before.active);+ await wc.reload();+ const after = await wait(state => state.ready && state.tabs.length === before.tabs.length && state.active === before.active);+ assert.deepEqual(after.tabs, before.tabs);+ assert.deepEqual(after.record.tabs.map(tab => [tab.id, tab.session, tab.cwd]),+ before.record.tabs.map(tab => [tab.id, tab.session, tab.cwd]));+ report.passed.push('reload restores open tab references, selected tab and original session workspaces');+}++module.exports = { runPageRecovery };diff --git a/apps/native/electron/preload.cjs b/apps/native/electron/preload.cjsindex c5c33a36..d27e6100 100644--- a/apps/native/electron/preload.cjs+++ b/apps/native/electron/preload.cjs@@ -11,6 +11,7 @@ contextBridge.exposeInMainWorld('graffDesktop', {projects: (action, value) => ipcRenderer.invoke('projects', { action, value }),linkSettings: (action, value) => ipcRenderer.invoke('link-settings', action, value),updates: (action, value) => ipcRenderer.invoke('updates', action, value),+ activeTurns: count => ipcRenderer.send('active-turns', count),updateSubscribe: callback => {const listener = (_event, state) => callback(state);ipcRenderer.on('update-state', listener);diff --git a/apps/native/electron/smoke-titles.cjs b/apps/native/electron/smoke-titles.cjsindex 3e702b20..6084ca5b 100644--- a/apps/native/electron/smoke-titles.cjs+++ b/apps/native/electron/smoke-titles.cjs@@ -47,6 +47,7 @@ async function run({win, backend}) {fs.writeFileSync(path.join(directory,'named-title.session.json'),JSON.stringify(named));report.passed.push('packaged GUI text prompt creates real file and meaningful saved title','image-bearing prompt reaches bundled harness as pixels and saves meaningful title');} else {+ await until(()=>js(`document.querySelectorAll('[data-tab-id]').length===2 && document.querySelector('[data-tab-id] button[aria-pressed="true"]')?.textContent.includes('image of retained work')`),'open tabs restored after packaged restart');await until(()=>js(`document.querySelector('#sidebar-chat-list')?.textContent.includes('Recover a legacy conversation title') && document.querySelector('#sidebar-chat-list')?.textContent.includes('My explicit project title')`),'fresh packaged process recovers legacy and preserves explicit titles');assert.equal(await js(`document.querySelector('#sidebar-chat-list').textContent.includes('Untitled session')`),false);await js(`Array.from(document.querySelectorAll('#sidebar-chat-list button[data-row]')).find(e=>e.textContent.includes('Recover a legacy conversation title')).setAttribute('data-title-recovery','true')`);@@ -54,7 +55,7 @@ async function run({win, backend}) {await until(()=>js(`document.querySelector('[data-tab-id] button[aria-pressed=\"true\"]')?.textContent.includes('Recover a legacy')`),'legacy snapshot opens');await until(()=>js(`document.querySelector('[data-chat][data-focused=\"true\"]')?.textContent.includes('Recover a legacy conversation title')`),'recovered transcript renders');await shot('packaged-recovered-titles.png');- report.passed.push('fresh packaged process recovers saved input_text placeholder title','explicit saved title remains unchanged','recovered saved conversation opens through real sidebar');+ report.passed.push('packaged restart restores open tabs and selected saved conversation','fresh packaged process recovers saved input_text placeholder title','explicit saved title remains unchanged','recovered saved conversation opens through real sidebar');}report.desktop=desktop.assertSafe();fs.writeFileSync(path.join(output,`titles-${phase}.json`),JSON.stringify(report,null,2));}diff --git a/apps/native/electron/tab-drag-visual.cjs b/apps/native/electron/tab-drag-visual.cjsindex e302d63e..8e1aa684 100644--- a/apps/native/electron/tab-drag-visual.cjs+++ b/apps/native/electron/tab-drag-visual.cjs@@ -87,6 +87,9 @@ async function runTabDrag({win, origin, output, injectMissedCollapseClick=false}};const up=to=>desktop.testInput(wc,{type:'mouseUp',button:'left',clickCount:1,...to});const drag=async(id,to)=>{await move(await down(id),to);await up(to);};+ // This fixture starts a new layout. Earlier frontend legs now leave their+ // open tabs recoverable across navigation, so clear that one test record.+ await js(`localStorage.removeItem('graff.native.open-tabs.v1')`);await wc.loadURL(origin);win.setSize(1320,850);await ready();await click('[aria-label="New chat"]');@@ -140,6 +143,7 @@ async function runTabDrag({win, origin, output, injectMissedCollapseClick=false}await wait(`!!document.querySelector('[data-split-limit]')`);assert.deepEqual(await panes(),before);// A fresh single pane can split vertically; mixed trees have separate stress coverage.+ await js(`localStorage.removeItem('graff.native.open-tabs.v1')`);await wc.loadURL(origin);await ready();if(await js(`!!document.querySelector('[aria-label="Close browser"]')`))await click('[aria-label="Close browser"]');await wait(`!document.querySelector('[aria-label="Close browser"]')`);@@ -179,6 +183,7 @@ async function runTabDrag({win, origin, output, injectMissedCollapseClick=false}desktop.attachTestDebugger(wc);await wc.debugger.sendCommand('Emulation.setEmulatedMedia',{features:[{name:'prefers-reduced-motion',value:'reduce'}]});try {+ await js(`localStorage.removeItem('graff.native.open-tabs.v1')`);await wc.loadURL(origin);await ready();await click('[aria-label="New chat"]');await wait(`document.querySelectorAll('[data-tab-id]').length===2`);const [source]=await tabs();diff --git a/apps/native/electron/transition-guard.cjs b/apps/native/electron/transition-guard.cjsnew file mode 100644index 00000000..759dce4e--- /dev/null+++ b/apps/native/electron/transition-guard.cjs@@ -0,0 +1,42 @@+function transitionOptions(action, activeTurns) {+ if (activeTurns < 1) return null;+ const count = activeTurns === 1 ? 'One chat has' : `${activeTurns} chats have`;+ return {+ type: 'warning', title: `${action} Codegraff?`,+ message: `${count} a turn in progress.`,+ detail: 'Continuing will interrupt the running turn. Open chat tabs and saved conversation checkpoints will be available when Codegraff returns.',+ buttons: [`${action} and interrupt`, 'Keep working'], defaultId: 1, cancelId: 1, noLink: true,+ };+}++async function confirmTransition(win, dialog, action, activeTurns) {+ const options = transitionOptions(action, activeTurns);+ if (!options) return true;+ const { response } = await dialog.showMessageBox(win, options);+ return response === 0;+}++function installTransitionGuard({ win, ipcMain, trusted, dialog }) {+ let activeTurns = 0, approvedUnload = false;+ ipcMain.on('active-turns', (event, count) => {+ trusted(event);+ if (Number.isSafeInteger(count) && count >= 0 && count <= 50) activeTurns = count;+ });+ const preflight = async action => {+ if (!await confirmTransition(win, dialog, action, activeTurns)) return false;+ if (activeTurns > 0) {+ approvedUnload = true;+ setTimeout(() => { approvedUnload = false; }, 10_000).unref();+ }+ return true;+ };+ const reload = async () => { if (await preflight('Reload') && !win.isDestroyed()) win.webContents.reload(); };+ win.webContents.on('will-prevent-unload', event => {+ if (approvedUnload) { approvedUnload = false; event.preventDefault(); return; }+ const options = transitionOptions('Leave', activeTurns);+ if (!options || dialog.showMessageBoxSync(win, options) === 0) event.preventDefault();+ });+ return { preflight, reload };+}++module.exports = { transitionOptions, confirmTransition, installTransitionGuard };diff --git a/apps/native/electron/transition-guard.test.cjs b/apps/native/electron/transition-guard.test.cjsnew file mode 100644index 00000000..3dd5c249--- /dev/null+++ b/apps/native/electron/transition-guard.test.cjs@@ -0,0 +1,46 @@+const { test, expect } = require('bun:test');+const { EventEmitter } = require('node:events');+const { confirmTransition, transitionOptions, installTransitionGuard } = require('./transition-guard.cjs');++test('reload and restart preflight can cancel an active turn', async () => {+ const shown = [];+ const dialog = { showMessageBox: async (_win, options) => { shown.push(options); return { response: 1 }; } };+ expect(await confirmTransition({}, dialog, 'Reload', 2)).toBe(false);+ expect(await confirmTransition({}, dialog, 'Restart', 1)).toBe(false);+ expect(shown.map(value => value.title)).toEqual(['Reload Codegraff?', 'Restart Codegraff?']);+ expect(shown[0].detail).toMatch(/interrupt.*turn/);+ expect(shown[0].detail).toMatch(/Open chat tabs.*saved conversation checkpoints/);+ expect(shown[0].defaultId).toBe(1);+ dialog.showMessageBox = async () => ({ response: 0 });+ expect(await confirmTransition({}, dialog, 'Reload', 1)).toBe(true);+ expect(transitionOptions('Reload', 0)).toBe(null);+});++test('renderer active-turn report gates reload and the next unload', async () => {+ const ipcMain = new EventEmitter(), webContents = new EventEmitter();+ let reloads = 0, asyncResponse = 1, syncResponse = 1, prompts = 0;+ webContents.reload = () => { reloads++; };+ const dialog = {+ showMessageBox: async () => { prompts++; return { response: asyncResponse }; },+ showMessageBoxSync: () => { prompts++; return syncResponse; },+ };+ const win = { webContents, isDestroyed: () => false };+ const { preflight, reload } = installTransitionGuard({ win, ipcMain, trusted: () => {}, dialog });+ ipcMain.emit('active-turns', {}, 2);+ await reload();+ expect(reloads).toBe(0);+ expect(prompts).toBe(1);+ expect(await preflight('Restart')).toBe(false);+ asyncResponse = 0;+ await reload();+ expect(reloads).toBe(1);+ let allowed = false;+ webContents.emit('will-prevent-unload', { preventDefault: () => { allowed = true; } });+ expect(allowed).toBe(true);+ allowed = false;+ webContents.emit('will-prevent-unload', { preventDefault: () => { allowed = true; } });+ expect(allowed).toBe(false);+ syncResponse = 0;+ webContents.emit('will-prevent-unload', { preventDefault: () => { allowed = true; } });+ expect(allowed).toBe(true);+});diff --git a/apps/native/electron/updates.cjs b/apps/native/electron/updates.cjsindex 7b6e13df..fc62518b 100644--- a/apps/native/electron/updates.cjs+++ b/apps/native/electron/updates.cjs@@ -118,7 +118,7 @@ function writePrefs(file, patch) {fs.writeFileSync(file, JSON.stringify(next));}-function installUpdates({ app, win, ipcMain, trusted, resources }) {+function installUpdates({ app, win, ipcMain, trusted, resources, preflight = async () => true }) {const { dialog } = require('electron');const prefs = path.join(app.getPath('userData'), 'updates.json');const loaded = readPrefs(prefs);@@ -147,8 +147,8 @@ function installUpdates({ app, win, ipcMain, trusted, resources }) {message: `Codegraff ${readyVersion} is ready to install.`,detail: 'Restart to apply the update now, or keep working — Codegraff offers the restart again at next launch.',buttons: ['Restart to update', 'Later'], defaultId: 0, cancelId: 1,- }).then(({ response }) => {- if (response === 0 && !win.isDestroyed()) { try { controller.restart(); } catch {} }+ }).then(async ({ response }) => {+ if (response === 0 && !win.isDestroyed() && await preflight('Restart') && !win.isDestroyed()) { try { controller.restart(); } catch {} }}).catch(() => {});},});@@ -157,7 +157,10 @@ function installUpdates({ app, win, ipcMain, trusted, resources }) {ipcMain.handle('updates', async (event, action, value) => {trusted(event);if (action === 'check') await controller.check(true);- else if (action === 'restart') controller.restart();+ else if (action === 'restart') {+ if (controller.state().status !== 'ready') controller.restart(); // preserve the unavailable-state error+ if (await preflight('Restart')) controller.restart();+ }else if (action === 'automatic') controller.setAutomatic(!!value);else if (action !== 'state') throw Error('Unknown update action');return controller.state();diff --git a/apps/native/lib/desktop.ts b/apps/native/lib/desktop.tsindex e4a5fd24..88baf039 100644--- a/apps/native/lib/desktop.ts+++ b/apps/native/lib/desktop.ts@@ -12,6 +12,7 @@ export type DesktopBridge = {linkSettings?(action: 'load' | 'save', value?: LinkDestination): Promise<LinkDestination>;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' | 'automatic', value?: boolean): Promise<UpdateState>;+ activeTurns?(count: number): void;updateSubscribe?(callback: (state: UpdateState) => void): () => void;terminal?(action: string, params?: Record<string, unknown>): Promise<{id: string; seq: number; history: string; exit: number | null}>;terminalSubscribe?(callback: (event: TerminalEvent) => void): () => void;diff --git a/apps/native/lib/session-store.test.ts b/apps/native/lib/session-store.test.tsindex 13453bf3..0e5ad4b5 100644--- a/apps/native/lib/session-store.test.ts+++ b/apps/native/lib/session-store.test.ts@@ -54,6 +54,29 @@ describe("listSessionRows", () => {} finally { rmSync(temp, { recursive: true, force: true }); }});+ it("finds sibling and nested registered checkouts after startup in a generated checkout", () => {+ const temp = realpathSync(mkdtempSync(path.join(tmpdir(), "graff-nested-session-")));+ const main = path.join(temp, "main"), home = path.join(temp, "home");+ const first = path.join(main, ".graff/worktrees/first");+ const nested = path.join(first, ".graff/worktrees/nested");+ const sibling = path.join(main, ".graff/worktrees/sibling");+ mkdirSync(main); mkdirSync(home);+ const git = (...args: string[]) => execFileSync("git", ["-C", main, ...args], { stdio: "pipe" });+ try {+ git("init");+ git("-c", "user.name=Test", "-c", "[email protected]", "commit", "--allow-empty", "-m", "fixture");+ git("worktree", "add", "--detach", first);+ git("worktree", "add", "--detach", nested);+ git("worktree", "add", "--detach", sibling);+ writeSession(nested, "nested-chat", { title: "Nested", updated_ms: 2, workspace: nested });+ writeSession(sibling, "sibling-chat", { title: "Sibling", updated_ms: 3, workspace: sibling });+ const rows = listSessionRows(first, home);+ assert.equal(rows.find(row => row.name === "nested-chat")?.workspace, nested);+ assert.equal(rows.find(row => row.name === "sibling-chat")?.workspace, sibling);+ assert.equal(findSessionFile(first, "nested-chat", home)?.workspace, nested);+ } finally { rmSync(temp, { recursive: true, force: true }); }+ });+it("lists cwd, then home, and cwd wins on the same name", () => {const cwd = mkdtempSync(path.join(tmpdir(), "graff-cwd-"));const home = mkdtempSync(path.join(tmpdir(), "graff-home-"));diff --git a/apps/native/lib/tab-recovery.test.ts b/apps/native/lib/tab-recovery.test.tsnew file mode 100644index 00000000..87f71aaf--- /dev/null+++ b/apps/native/lib/tab-recovery.test.ts@@ -0,0 +1,20 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { loadTabRecovery, saveTabRecovery, tabRecovery, TAB_RECOVERY_KEY } from './tab-recovery.ts';++test('open tab references and split groups survive a new page without saving transcripts', () => {+ const store = new Map<string, string>();+ const storage = { getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { store.set(key, value); } };+ const state = tabRecovery([+ { id: 3, session: 'native-first', cwd: '/repo/.graff/worktrees/first', title: 'First', messages: [{ id: 1, role: 'user', text: 'private prompt' }] },+ { id: 8, session: 'native-second', cwd: '/repo/.graff/worktrees/second', title: 'Second', messages: [] },+ ], 8, [{ ids: [3, 8], direction: 'column' }]);+ saveTabRecovery(storage, state);+ assert.deepEqual(loadTabRecovery(storage), state);+ assert.equal(store.get(TAB_RECOVERY_KEY)?.includes('private prompt'), false);+});++test('malformed or obsolete tab references do not replace the new chat', () => {+ const storage = { getItem: () => JSON.stringify({ tabs: [{ id: 1, session: '../escape' }], activeId: 1 }) };+ assert.equal(loadTabRecovery(storage), null);+});diff --git a/apps/native/lib/tab-recovery.ts b/apps/native/lib/tab-recovery.tsnew file mode 100644index 00000000..7d46c31b--- /dev/null+++ b/apps/native/lib/tab-recovery.ts@@ -0,0 +1,51 @@+import type { ChatGroup } from "./chat-groups";+import type { Chat } from "@/components/site/harness-types";++export const TAB_RECOVERY_KEY = "graff.native.open-tabs.v1";+export type TabReference = Pick<Chat, "id" | "session" | "cwd" | "title" | "model">;+export type TabRecovery = { tabs: TabReference[]; activeId: number; groups: ChatGroup[] };++/** Keep only references and layout. Transcripts remain in the engine's saved+ * sessions; drafts and live tool state must never be mistaken for a checkpoint. */+export function tabRecovery(chats: readonly Chat[], activeId: number, groups: readonly ChatGroup[]): TabRecovery {+ return {+ tabs: chats.slice(0, 50).map(({ id, session, cwd, title, model }) => ({ id, session, cwd, title, model })),+ activeId,+ groups: groups.map(group => ({ ids: [...group.ids], direction: group.direction, ...(group.tree ? { tree: group.tree } : {}) })),+ };+}++export function loadTabRecovery(storage: Pick<Storage, "getItem"> | null): TabRecovery | null {+ try {+ const raw = storage?.getItem(TAB_RECOVERY_KEY);+ if (!raw || raw.length > 64_000) return null;+ const value: unknown = JSON.parse(raw);+ if (!value || typeof value !== "object") return null;+ const obj = value as Record<string, unknown>;+ if (!Array.isArray(obj.tabs) || !obj.tabs.length || obj.tabs.length > 50) return null;+ const seen = new Set<number>();+ const tabs: TabReference[] = [];+ for (const item of obj.tabs) {+ if (!item || typeof item !== "object") return null;+ const tab = item as Record<string, unknown>;+ if (!Number.isSafeInteger(tab.id) || (tab.id as number) < 1 || seen.has(tab.id as number) ||+ typeof tab.session !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(tab.session)) return null;+ if (tab.cwd !== undefined && (typeof tab.cwd !== "string" || !tab.cwd.startsWith("/"))) return null;+ seen.add(tab.id as number);+ tabs.push({ id: tab.id as number, session: tab.session, cwd: tab.cwd as string | undefined,+ title: typeof tab.title === "string" ? tab.title : null,+ model: typeof tab.model === "string" ? tab.model : undefined });+ }+ const activeId = seen.has(obj.activeId as number) ? obj.activeId as number : tabs[0].id;+ const groups: ChatGroup[] = Array.isArray(obj.groups) ? obj.groups.filter((item): item is ChatGroup =>+ !!item && typeof item === "object" && Array.isArray(item.ids) && item.ids.length <= 4 &&+ item.ids.every((id: unknown) => seen.has(id as number)) && (item.direction === "row" || item.direction === "column")) : [];+ // A saved split tree is advisory; ids and direction are enough to rebuild+ // it safely after a format change or a partially written browser value.+ return { tabs, activeId, groups: groups.map(({ ids, direction }) => ({ ids, direction })) };+ } catch { return null; }+}++export function saveTabRecovery(storage: Pick<Storage, "setItem"> | null, value: TabRecovery): void {+ try { storage?.setItem(TAB_RECOVERY_KEY, JSON.stringify(value)); } catch { /* Browser storage is best effort. */ }+}diff --git a/apps/native/lib/workspace-history.test.ts b/apps/native/lib/workspace-history.test.tsindex 44916e9f..504be4e3 100644--- a/apps/native/lib/workspace-history.test.ts+++ b/apps/native/lib/workspace-history.test.ts@@ -43,3 +43,23 @@ test("suggestions retain saved settings without consuming choices and sort by acassert.equal(mergeWorkspaceActivity(result, activity).length, 51);assert.equal(mergeWorkspaceActivity([{ path: "/terminal-only", name: "terminal", source: "startup" }], activity)[0].source, "history");});++test("generated nested session checkouts roll up to their project unless explicitly saved", () => {+ const home = realpathSync(mkdtempSync(path.join(os.tmpdir(), "workspace-history-checkouts-")));+ const project = path.join(home, "project");+ const outer = path.join(project, ".graff/worktrees/outer");+ const nested = path.join(outer, ".graff/worktrees/nested");+ try {+ const registry = path.join(home, ".graff/workspace-history"); mkdirSync(registry, { recursive: true });+ const register = (root: string, time: number) => {+ const folder = path.join(root, ".graff/sessions"); mkdirSync(folder, { recursive: true });+ writeFileSync(path.join(folder, "one.session.json"), JSON.stringify({ updated_ms: time, messages: [] }));+ writeFileSync(path.join(registry, createHash("sha256").update(root).digest("hex") + ".json"), JSON.stringify({ version: 1, path: root }));+ };+ register(project, 10); register(outer, 20); register(nested, 30);+ assert.deepEqual(discoverWorkspaceHistory([nested], home, []), [{ path: project, lastActivityMs: 30 }]);+ assert.deepEqual(discoverWorkspaceHistory([nested], home, [nested]), [+ { path: nested, lastActivityMs: 30 }, { path: project, lastActivityMs: 20 },+ ]);+ } finally { rmSync(home, { recursive: true, force: true }); }+});diff --git a/apps/native/lib/workspace-history.ts b/apps/native/lib/workspace-history.tsindex 1b4fb9a5..251c1ea6 100644--- a/apps/native/lib/workspace-history.ts+++ b/apps/native/lib/workspace-history.ts@@ -15,10 +15,14 @@ function entries(folder: string): string[] {}/** Registry entries are hints. Only an existing, readable session header makes- * a folder an activity suggestion; never infer a parent repository. */-export function discoverWorkspaceHistory(known: string[] = [], home = homeDir()): WorkspaceActivity[] {+ * activity; generated checkout activity is attributed to its outer project. */+export function discoverWorkspaceHistory(known: string[] = [], home = homeDir(), saved: string[] = known): WorkspaceActivity[] {const roots = new Set<string>();const knownNames = new Map<string, string>();+ const savedRoots = new Set<string>();+ for (const root of saved) {+ try { if (path.isAbsolute(root)) savedRoots.add(realpathSync(root)); } catch {}+ }for (const root of known) {try { if (path.isAbsolute(root)) knownNames.set(realpathSync(root), path.normalize(root)); } catch {}}@@ -37,7 +41,7 @@ export function discoverWorkspaceHistory(known: string[] = [], home = homeDir())if (row.version === 1) add(row.path);} catch { /* Partial, obsolete and malformed hints are ignored. */ }}- const rows: WorkspaceActivity[] = [];+ const activity = new Map<string, number>();for (const root of roots) {let latest = 0;for (const folder of [path.join(root, SESSIONS_DIR), path.join(root, SESSIONS_DIR, "archived")]) {@@ -54,7 +58,16 @@ export function discoverWorkspaceHistory(known: string[] = [], home = homeDir())} catch { /* A concurrent save/delete must not break other projects. */ }}}- if (latest > 0) rows.push({ path: knownNames.get(root) ?? root, lastActivityMs: latest });+ if (latest > 0) {+ // Generated session checkouts belong to the outer project. A folder+ // explicitly saved by the user remains an independent choice.+ const marker = `${path.sep}.graff${path.sep}worktrees${path.sep}`;+ const index = savedRoots.has(root) ? -1 : root.indexOf(marker);+ const owner = index > 0 ? root.slice(0, index) : root;+ const label = knownNames.get(owner) ?? owner;+ activity.set(label, Math.max(activity.get(label) ?? 0, latest));+ }}- return rows.sort((a, b) => b.lastActivityMs - a.lastActivityMs || a.path.localeCompare(b.path));+ return [...activity].map(([path, lastActivityMs]) => ({ path, lastActivityMs }))+ .sort((a, b) => b.lastActivityMs - a.lastActivityMs || a.path.localeCompare(b.path));}diff --git a/docs/adr/0198-desktop-page-transitions-preserve-tabs.md b/docs/adr/0198-desktop-page-transitions-preserve-tabs.mdnew file mode 100644index 00000000..8a217187--- /dev/null+++ b/docs/adr/0198-desktop-page-transitions-preserve-tabs.md@@ -0,0 +1,28 @@+# 0198. Desktop page transitions preserve chat references++Status: accepted 2026-09-24++## Context++A desktop reload or update restart destroys the renderer and its per-chat ACP+processes. Saved conversations can be reopened, but the open tabs and their+selection existed only in renderer memory. An active turn could be interrupted+without a decision from the user (#1237).++## Decision++Persist the open tab session names, workspaces, order, split groups, and active+tab in the desktop browser store. On a new page, rebuild those tabs and read+their saved transcripts from the session store. A restored tab may resume its+ACP session in its original workspace on the next prompt; replayed transcript+rows do not rerun tools. Do not persist live transcript text, tool state, or+drafts in the tab record.++Before a user reloads or restarts for an update with active turns, confirm that+the turns will be interrupted. Page unload still reaps the old page's agents.++## Consequences++The browser record can restore navigation even when one checkpoint is missing.+Work after the last engine checkpoint may be lost when an active turn is+interrupted. Closing the page does not make its agents detached workers.diff --git a/docs/adr/0199-generated-checkouts-belong-to-project-history.md b/docs/adr/0199-generated-checkouts-belong-to-project-history.mdnew file mode 100644index 00000000..11cc8cbc--- /dev/null+++ b/docs/adr/0199-generated-checkouts-belong-to-project-history.md@@ -0,0 +1,22 @@+# 0199. Generated checkouts belong to project history++Status: accepted 2026-09-24++## Context++The workspace history registry includes every folder with a saved session.+Automatically generated session checkouts therefore appeared as independent+project suggestions, including nested checkouts (#1230).++## Decision++Group the activity of folders under `.graff/worktrees/` into the outer project+when preparing automatic workspace suggestions. Keep a checkout as its own row+when the user explicitly saved that folder. This grouping changes suggestions+only; session discovery and resume continue to use the linked checkout as the+conversation's working directory (ADR 0155).++## Consequences++Project activity reflects generated session work without flooding the switcher.+An explicitly saved checkout remains selectable with its own settings.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 980d1b52..67a9515e 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -221,6 +221,8 @@ record only when you need the evidence or the edge cases.| [0193](0193-jev-selects-effort-only.md) | Optional Jev selects only supported session effort at the next request boundary; arbitrary judgments are not exposed. || [0195](0195-embedded-browser-replaces-kuri.md) | Desktop browser uses embedded Chromium, web preview uses the paired extension, and CLI fetch uses built-in HTTP without a sidecar. || [0198](0198-project-choice-survives-session-isolation.md) | New chats inherit the chosen project while ACP reports each worker checkout; generated worktrees are rooted at the main checkout. |+| [0198](0198-desktop-page-transitions-preserve-tabs.md) | Desktop restart/reload confirms active-turn interruption and restores tab references from saved sessions in their workspaces. |+| [0199](0199-generated-checkouts-belong-to-project-history.md) | Generated worktree activity rolls up to the owning project in automatic suggestions; explicitly saved checkouts stay selectable. |## When to write one