Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): faithful multi-window session restore on restart (#2894)

mike-inkeepeb162047b54c
diff --git a/.changeset/faithful-session-restore.md b/.changeset/faithful-session-restore.md
new file mode 100644
index 000000000..1a47df8e2
--- /dev/null
+++ b/.changeset/faithful-session-restore.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Restore your full window set on restart, not just the last project. When you quit OpenKnowledge — or it auto-updates — with several project windows open, plus any loose files you opened via File → Open File, the next launch now reopens all of them in the same layout and brings the window you were last working in to the front. Previously a normal restart reopened only a single project and dropped loose files entirely.
+
+Loose files opened via File → Open File are also now tracked in a new File → Recent files menu, separate from Recent projects.
diff --git a/packages/desktop/src/main/boot-restore-decision.settle.test.ts b/packages/desktop/src/main/boot-restore-decision.settle.test.ts
index 58678a847..ea5ec3b4a 100644
--- a/packages/desktop/src/main/boot-restore-decision.settle.test.ts
+++ b/packages/desktop/src/main/boot-restore-decision.settle.test.ts
@@ -145,7 +145,7 @@ describe('resolveBootRestoreDecision (cold-start URL settle barrier)', () => {
const settle = manualSettle();
const decisionPromise = resolveBootRestoreDecision({
- pendingRestore: ['/projects/a'],
+ pendingRestore: [{ kind: 'project', projectPath: '/projects/a' }],
lastOpenedProject: '/projects/last',
optionHeld: false,
pathExists: () => true,
@@ -164,7 +164,7 @@ describe('resolveBootRestoreDecision (cold-start URL settle barrier)', () => {
expect(decision).toEqual({
clearSnapshot: true,
action: 'restore',
- projects: ['/projects/a'],
+ windows: [{ kind: 'project', projectPath: '/projects/a' }],
});
});
diff --git a/packages/desktop/src/main/boot-restore-decision.test.ts b/packages/desktop/src/main/boot-restore-decision.test.ts
index 1d60c7bbd..4051d27cc 100644
--- a/packages/desktop/src/main/boot-restore-decision.test.ts
+++ b/packages/desktop/src/main/boot-restore-decision.test.ts
@@ -1,11 +1,15 @@
import { describe, expect, test } from 'vitest';
-import { bootRestoreDecision } from './boot-restore-decision.ts';
+import { bootRestoreDecision, resolveRestoreActions } from './boot-restore-decision.ts';
+import type { RestoredWindow } from './state-store.ts';
function existsIn(paths: string[]): (p: string) => boolean {
const set = new Set(paths);
return (p) => set.has(p);
}
+const proj = (projectPath: string): RestoredWindow => ({ kind: 'project', projectPath });
+const file = (filePath: string): RestoredWindow => ({ kind: 'file', filePath });
+
describe('bootRestoreDecision', () => {
test('empty restore snapshot does not fall through to lastOpened', () => {
const decision = bootRestoreDecision({
@@ -20,7 +24,7 @@ describe('bootRestoreDecision', () => {
test('optionHeld with a non-empty snapshot consumes but suppresses restore', () => {
const decision = bootRestoreDecision({
- pendingRestore: ['/projects/a', '/projects/b'],
+ pendingRestore: [proj('/projects/a'), proj('/projects/b')],
lastOpenedProject: '/projects/last',
optionHeld: true,
pathExists: existsIn(['/projects/a', '/projects/b', '/projects/last']),
@@ -31,7 +35,7 @@ describe('bootRestoreDecision', () => {
test('non-empty snapshot with all paths existing restores in order', () => {
const decision = bootRestoreDecision({
- pendingRestore: ['/projects/a', '/projects/b', '/projects/c'],
+ pendingRestore: [proj('/projects/a'), proj('/projects/b'), proj('/projects/c')],
lastOpenedProject: null,
optionHeld: false,
pathExists: existsIn(['/projects/a', '/projects/b', '/projects/c']),
@@ -40,28 +44,48 @@ describe('bootRestoreDecision', () => {
expect(decision).toEqual({
clearSnapshot: true,
action: 'restore',
- projects: ['/projects/a', '/projects/b', '/projects/c'],
+ windows: [proj('/projects/a'), proj('/projects/b'), proj('/projects/c')],
+ });
+ });
+
+ test('mixed project + loose-file snapshot restores both kinds in order', () => {
+ const decision = bootRestoreDecision({
+ pendingRestore: [proj('/projects/a'), file('/notes/todo.md'), proj('/projects/b')],
+ lastOpenedProject: null,
+ optionHeld: false,
+ pathExists: existsIn(['/projects/a', '/notes/todo.md', '/projects/b']),
+ urlLaunch: false,
+ });
+ expect(decision).toEqual({
+ clearSnapshot: true,
+ action: 'restore',
+ windows: [proj('/projects/a'), file('/notes/todo.md'), proj('/projects/b')],
});
});
- test('snapshot with some missing paths restores only existing ones', () => {
+ test('missing targets are filtered by existence for BOTH kinds', () => {
const decision = bootRestoreDecision({
- pendingRestore: ['/projects/a', '/projects/gone', '/projects/c'],
+ pendingRestore: [
+ proj('/projects/a'),
+ file('/notes/gone.md'),
+ proj('/projects/gone'),
+ file('/notes/keep.md'),
+ ],
lastOpenedProject: null,
optionHeld: false,
- pathExists: existsIn(['/projects/a', '/projects/c']),
+ pathExists: existsIn(['/projects/a', '/notes/keep.md']),
urlLaunch: false,
});
expect(decision).toEqual({
clearSnapshot: true,
action: 'restore',
- projects: ['/projects/a', '/projects/c'],
+ windows: [proj('/projects/a'), file('/notes/keep.md')],
});
});
- test('snapshot with all paths missing opens the navigator', () => {
+ test('snapshot with all targets missing opens the navigator', () => {
const decision = bootRestoreDecision({
- pendingRestore: ['/projects/gone1', '/projects/gone2'],
+ pendingRestore: [proj('/projects/gone1'), file('/notes/gone2.md')],
lastOpenedProject: '/projects/last',
optionHeld: false,
pathExists: existsIn(['/projects/last']),
@@ -142,12 +166,12 @@ describe('bootRestoreDecision', () => {
expect(decision).toEqual({ clearSnapshot: false, action: 'none' });
});
- test('urlLaunch does NOT override an update-relaunch restore (snapshot wins)', () => {
+ test('urlLaunch does NOT override a snapshot restore (snapshot wins)', () => {
// A real update relaunch carries no deep-link, so this combo is theoretical
// — but the restore must never be dropped, so the snapshot ranks above
// urlLaunch.
const decision = bootRestoreDecision({
- pendingRestore: ['/projects/a', '/projects/b'],
+ pendingRestore: [proj('/projects/a'), proj('/projects/b')],
lastOpenedProject: '/projects/last',
optionHeld: false,
pathExists: existsIn(['/projects/a', '/projects/b']),
@@ -156,7 +180,87 @@ describe('bootRestoreDecision', () => {
expect(decision).toEqual({
clearSnapshot: true,
action: 'restore',
- projects: ['/projects/a', '/projects/b'],
+ windows: [proj('/projects/a'), proj('/projects/b')],
});
});
});
+
+describe('resolveRestoreActions (file→project collapse + dedup ordering)', () => {
+ // A resolver that maps loose files into projects per `fileToProject`, keeps
+ // files in `ephemeral` as loose files, and rejects everything else (→ null,
+ // the "vanished / non-markdown" skip that `prepareSingleFileOpen` throwing
+ // produces in production).
+ function resolverFrom(fileToProject: Record<string, string>, ephemeral: Set<string>) {
+ return (filePath: string): RestoredWindow | null => {
+ const root = fileToProject[filePath];
+ if (root !== undefined) return proj(root);
+ if (ephemeral.has(filePath)) return file(filePath);
+ return null;
+ };
+ }
+
+ test('project entries pass through unchanged, in order', () => {
+ const { orderedKeys, actionByKey } = resolveRestoreActions(
+ [proj('/a'), proj('/b')],
+ () => null,
+ );
+ expect(orderedKeys).toEqual(['/a', '/b']);
+ expect(actionByKey.get('/a')).toEqual(proj('/a'));
+ expect(actionByKey.get('/b')).toEqual(proj('/b'));
+ });
+
+ test('a loose file staying ephemeral keeps its file key', () => {
+ const { orderedKeys, actionByKey } = resolveRestoreActions(
+ [file('/notes/todo.md')],
+ resolverFrom({}, new Set(['/notes/todo.md'])),
+ );
+ expect(orderedKeys).toEqual(['/notes/todo.md']);
+ expect(actionByKey.get('/notes/todo.md')).toEqual(file('/notes/todo.md'));
+ });
+
+ test('two loose files under one project collapse to a single project action', () => {
+ const { orderedKeys, actionByKey } = resolveRestoreActions(
+ [file('/proj/a.md'), file('/proj/b.md')],
+ resolverFrom({ '/proj/a.md': '/proj', '/proj/b.md': '/proj' }, new Set()),
+ );
+ expect(orderedKeys).toEqual(['/proj']);
+ expect(actionByKey.size).toBe(1);
+ expect(actionByKey.get('/proj')).toEqual(proj('/proj'));
+ });
+
+ test('a loose file resolving into an already-present project entry collapses', () => {
+ const { orderedKeys, actionByKey } = resolveRestoreActions(
+ [proj('/proj'), file('/proj/inner.md')],
+ resolverFrom({ '/proj/inner.md': '/proj' }, new Set()),
+ );
+ expect(orderedKeys).toEqual(['/proj']);
+ expect(actionByKey.size).toBe(1);
+ expect(actionByKey.get('/proj')).toEqual(proj('/proj'));
+ });
+
+ test('the LATER (more-recent) duplicate wins position so the raise target is last', () => {
+ // /proj appears first (as a project), then again via a later loose file that
+ // re-derives to it — the collapsed entry must move to the END so the
+ // most-recently-focused window is the one raised.
+ const { orderedKeys } = resolveRestoreActions(
+ [proj('/proj'), proj('/other'), file('/proj/inner.md')],
+ resolverFrom({ '/proj/inner.md': '/proj' }, new Set()),
+ );
+ expect(orderedKeys).toEqual(['/other', '/proj']);
+ });
+
+ test('a file the resolver rejects (null) is skipped silently', () => {
+ const { orderedKeys, actionByKey } = resolveRestoreActions(
+ [proj('/a'), file('/gone.md'), proj('/b')],
+ resolverFrom({}, new Set()),
+ );
+ expect(orderedKeys).toEqual(['/a', '/b']);
+ expect(actionByKey.has('/gone.md')).toBe(false);
+ });
+
+ test('empty snapshot → empty result', () => {
+ const { orderedKeys, actionByKey } = resolveRestoreActions([], () => null);
+ expect(orderedKeys).toEqual([]);
+ expect(actionByKey.size).toBe(0);
+ });
+});
diff --git a/packages/desktop/src/main/boot-restore-decision.ts b/packages/desktop/src/main/boot-restore-decision.ts
index 3674fa785..b4e04108d 100644
--- a/packages/desktop/src/main/boot-restore-decision.ts
+++ b/packages/desktop/src/main/boot-restore-decision.ts
@@ -1,5 +1,7 @@
+import { type RestoredWindow, windowRestoreKey } from './state-store.ts';
+
export interface BootRestoreInput {
- pendingRestore: string[] | null;
+ pendingRestore: RestoredWindow[] | null;
lastOpenedProject: string | null;
optionHeld: boolean;
pathExists: (p: string) => boolean;
@@ -17,7 +19,7 @@ export interface BootRestoreInput {
}
export type BootRestoreDecision =
- | { clearSnapshot: boolean; action: 'restore'; projects: string[] }
+ | { clearSnapshot: boolean; action: 'restore'; windows: RestoredWindow[] }
| { clearSnapshot: boolean; action: 'lastOpened'; project: string }
| { clearSnapshot: boolean; action: 'navigator' }
| { clearSnapshot: boolean; action: 'none' };
@@ -33,11 +35,19 @@ export type BootRestoreDecision =
export function bootRestoreDecision(input: BootRestoreInput): BootRestoreDecision {
const { pendingRestore, lastOpenedProject, optionHeld, pathExists, urlLaunch } = input;
const clearSnapshot = pendingRestore !== null;
+ // Filter each entry by whether its target still exists on disk — a project
+ // folder or loose file deleted/moved since the snapshot is silently skipped
+ // (`windowRestoreKey` is the project path or the canonical file path). The
+ // file→project re-derivation + duplicate collapse happens in
+ // `resolveRestoreActions` (called at open time from `index.ts`); the pure
+ // decision only survivor-filters.
const restorable =
- pendingRestore !== null && !optionHeld ? pendingRestore.filter(pathExists) : [];
+ pendingRestore !== null && !optionHeld
+ ? pendingRestore.filter((w) => pathExists(windowRestoreKey(w)))
+ : [];
if (restorable.length > 0) {
- return { clearSnapshot, action: 'restore', projects: restorable };
+ return { clearSnapshot, action: 'restore', windows: restorable };
}
if (urlLaunch) {
return { clearSnapshot, action: 'none' };
@@ -53,6 +63,47 @@ export function bootRestoreDecision(input: BootRestoreInput): BootRestoreDecisio
return { clearSnapshot, action: 'navigator' };
}
+/**
+ * Resolve a restore snapshot into the ordered, de-duplicated set of windows to
+ * open. Each `file` entry is re-derived via `resolveFileTarget` — matching
+ * `openEphemeralFile`'s own logic, a loose file whose realpath now sits inside a
+ * project collapses onto that project (a `project` action); a file that can't be
+ * resolved (missing / non-markdown) returns null and is skipped. Entries that
+ * collapse onto the same key de-dupe, with the LATER (more recently focused)
+ * occurrence winning position, so `orderedKeys`'s last entry is the window to
+ * raise after restore.
+ *
+ * Pure: the filesystem / project derivation is injected, so the collapse +
+ * ordering — the load-bearing duplicate-window guard — is unit-testable without
+ * Electron. `index.ts` passes a `resolveFileTarget` that wraps
+ * `prepareSingleFileOpen`.
+ */
+export function resolveRestoreActions(
+ windows: readonly RestoredWindow[],
+ resolveFileTarget: (filePath: string) => RestoredWindow | null,
+): { orderedKeys: string[]; actionByKey: Map<string, RestoredWindow> } {
+ const orderedKeys: string[] = [];
+ const actionByKey = new Map<string, RestoredWindow>();
+ for (const w of windows) {
+ let action: RestoredWindow;
+ if (w.kind === 'file') {
+ const resolved = resolveFileTarget(w.filePath);
+ if (resolved === null) continue;
+ action = resolved;
+ } else {
+ action = w;
+ }
+ const key = windowRestoreKey(action);
+ // Later (more-recent) duplicate wins position: move the key to the end so
+ // the raise target stays the most-recently-focused window.
+ const existingIdx = orderedKeys.indexOf(key);
+ if (existingIdx !== -1) orderedKeys.splice(existingIdx, 1);
+ orderedKeys.push(key);
+ actionByKey.set(key, action);
+ }
+ return { orderedKeys, actionByKey };
+}
+
/**
* Coordinator input for the async boot-restore seam. Mirrors `BootRestoreInput`
* but replaces the eager `urlLaunch: boolean` with a settle-then-read pair:
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index a016c77df..00f631f24 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -155,7 +155,7 @@ import {
channelFromVersion,
type StartAutoUpdaterHandle,
} from './auto-updater.ts';
-import { resolveBootRestoreDecision } from './boot-restore-decision.ts';
+import { resolveBootRestoreDecision, resolveRestoreActions } from './boot-restore-decision.ts';
import { readBootSessionUuid } from './boot-session.ts';
import { runBootstrap } from './bootstrap.ts';
import {
@@ -333,6 +333,7 @@ import { beginRoot, childSpan, endRoot, injectTraceparent } from './startup-trac
import { type RendererMarks, StartupWaterfall } from './startup-waterfall.ts';
import {
type AppState,
+ addRecentFile,
addRecentProject,
annotateMissing,
emptyState,
@@ -407,7 +408,7 @@ import {
WindowManager,
} from './window-manager.ts';
import { WINDOW_MIN_SIZE } from './window-min-size.ts';
-import { resolveRestoredPlacement, sortByFocusSequence } from './window-placement.ts';
+import { resolveRestoredPlacement, sortWindowsByFocusSequence } from './window-placement.ts';
import {
classifyRecentGit,
classifyRecentGitAsync,
@@ -619,11 +620,18 @@ function freezeFocusTracking(reason: string): void {
getLogger('lifecycle').info({ reason }, 'project focus tracking frozen for shutdown');
}
+// Advance the focus-recency sequence for a window key (a project path, or a
+// loose-file window's canonical file path). Ordering only — never writes
+// `lastOpenedProject`.
+function recordWindowFocusSeq(key: string): void {
+ projectFocusSeqCounter += 1;
+ projectFocusSeq.set(key, projectFocusSeqCounter);
+}
+
function trackProjectWindowFocus(win: BrowserWindow, projectPath: string): void {
win.on('focus', () => {
if (focusTrackingFrozen) return;
- projectFocusSeqCounter += 1;
- projectFocusSeq.set(projectPath, projectFocusSeqCounter);
+ recordWindowFocusSeq(projectPath);
if (appState.lastOpenedProject !== projectPath) {
appState = { ...appState, lastOpenedProject: projectPath };
saveAppState(appState);
@@ -631,6 +639,45 @@ function trackProjectWindowFocus(win: BrowserWindow, projectPath: string): void
});
}
+// Focus-recency for a loose single-file (ephemeral) window, keyed by its
+// canonical file path so it joins the restore ordering + post-restore raise.
+// MUST NOT write `lastOpenedProject`: an ephemeral window's "projectPath" is the
+// file's PARENT directory, which would poison the single-project restore
+// fallback (open `~/notes` as a project) and collide two loose files in one dir.
+function trackEphemeralWindowFocus(win: BrowserWindow, fileKey: string): void {
+ win.on('focus', () => {
+ if (focusTrackingFrozen) return;
+ recordWindowFocusSeq(fileKey);
+ });
+}
+
+// Write-once guard so the richest pre-teardown snapshot wins. On the "Relaunch
+// now" path `prepareForRelaunch` snapshots first, then `quitAndInstall`
+// internally re-enters `before-quit`; on the silent install-on-quit path
+// `before-quit-for-update` snapshots before it stops servers, ahead of the
+// plain `before-quit`. Whichever hook fires first wins; later re-fires no-op.
+let windowRestoreSnapshotWritten = false;
+
+// Capture the full open-window set (projects + loose files) into
+// `pendingWindowRestore`, ordered least → most recently focused, so the next
+// boot restores everything and raises the window the user was last in. Called
+// at the earliest teardown-preceding hook of every clean-exit path (write-once).
+// Callers MUST `freezeFocusTracking` first so the close cascade can't corrupt
+// the order.
+function captureWindowRestoreSnapshot(reason: string): void {
+ if (windowRestoreSnapshotWritten) return;
+ windowRestoreSnapshotWritten = true;
+ const windows = sortWindowsByFocusSequence(wm?.getOpenWindows() ?? [], projectFocusSeq);
+ appState = { ...appState, pendingWindowRestore: windows };
+ if (!saveAppState(appState)) {
+ // Persist failed — the next boot may not reopen everything that was open.
+ console.warn('[main] failed to persist window-restore snapshot', {
+ reason,
+ windowCount: windows.length,
+ });
+ }
+}
+
/**
* Production WS-upgrade probe — opens a fresh `WebSocket(url)`, resolves
* `true` on `open`, `false` on `close` / `error` / timeout. Used by the
@@ -1205,6 +1252,10 @@ function ensureWindowManager() {
if (opts.projectPath !== undefined) {
trackProjectWindowBounds(win, opts.projectPath);
trackProjectWindowFocus(win, opts.projectPath);
+ } else if (opts.focusKey !== undefined) {
+ // Ephemeral loose-file window: focus-recency ordering only — no bounds
+ // memory, and no `lastOpenedProject` write (its key is a file path).
+ trackEphemeralWindowFocus(win, opts.focusKey);
}
attachSpellcheckMenuToWindow(win);
// Per-window PTY reap: closing the window kills its shell (no orphan).
@@ -2281,6 +2332,11 @@ async function openEphemeralFile(filePath: string): Promise<void> {
// The external-link / asset safety net is attached by the window factory
// (WindowManager.attachSafetyNet) — for ephemeral windows the asset root is
// the file's real parent (`opts.contentDir`), wired there.
+ // Track the loose file in Recent Files (durable, separate from recent
+ // projects) so File → Open Recent can reopen it. Keyed by canonical path;
+ // does NOT touch `lastOpenedProject` (a loose file is not a project).
+ appState = addRecentFile(appState, plan.canonicalFilePath, basename(plan.canonicalFilePath));
+ saveAppState(appState);
tryCloseNavigator(navigatorWindow, { projectPath: plan.contentDir });
refreshApplicationMenu();
} catch (err) {
@@ -2494,6 +2550,12 @@ async function runApplicationMenuRefresh(): Promise<void> {
saveAppState(appState);
refreshApplicationMenu();
},
+ getRecentFiles: () => appState.recentFiles,
+ clearRecentFiles: () => {
+ appState = { ...appState, recentFiles: [] };
+ saveAppState(appState);
+ refreshApplicationMenu();
+ },
// The scheme allowlist is enforced in the renderer IPC path (shell-allowlist.ts).
// Help-menu URLs are hardcoded in menu.ts (always `https://github.com/inkeep/…`),
// so they're trusted at build time — direct shell.openExternal is fine here.
@@ -6432,7 +6494,7 @@ function bootPrimaryInstance(): void {
// next boot. The existsSync filter limits the blast radius to
// projects that still exist on disk.
console.warn('[main] failed to persist cleared window-restore snapshot', {
- projectCount: decision.action === 'restore' ? decision.projects.length : 0,
+ windowCount: decision.action === 'restore' ? decision.windows.length : 0,
});
}
}
@@ -6472,28 +6534,55 @@ function bootPrimaryInstance(): void {
}
if (decision.action === 'restore') {
- // Parallel opens — the snapshot is ordered least → most recently
- // focused (see `pendingWindowRestore`), but each window's OS-level
- // `show()` is deferred behind its own dual-signal show gate, which
- // releases in nondeterministic order. `show()` steals key-window focus
- // on macOS, so the raise must wait for EVERY restored window to reveal
- // before raising the snapshot's last entry — otherwise a sibling window
- // that shows later steals focus back (the reported "active window isn't
- // the one I was working in" after a relaunch). Waiting for all reveals
- // also keeps `bringToFront`'s `show()` from bypassing the target's own
- // gate: the target is already shown by the time we raise it.
- const opens = decision.projects.map((projectPath) =>
- openProjectOrFallbackToNavigator(projectPath, 'recents'),
- );
+ // Re-derive each entry to its EFFECTIVE open target and dedupe. A loose
+ // file whose realpath now sits inside a project re-derives to that
+ // project (`prepareSingleFileOpen`, same as `openEphemeralFile`), so two
+ // entries — two loose files under one project root, or a loose file that
+ // resolves into a project already present as a `project` entry — can
+ // collapse onto one target. Deduping keeps a single ordered raise-key
+ // list and (with the WM's project in-flight reservation) prevents a
+ // duplicate window + second server. A file that vanished / became
+ // non-markdown since the snapshot throws here and is skipped silently.
+ // The file→project re-derivation + duplicate collapse + ordering lives
+ // in the pure `resolveRestoreActions` (unit-tested); here we just inject
+ // the real `prepareSingleFileOpen` (a throw → skip the vanished file).
+ const { orderedKeys, actionByKey } = resolveRestoreActions(decision.windows, (filePath) => {
+ try {
+ const plan = prepareSingleFileOpen(filePath);
+ return plan.mode === 'project'
+ ? { kind: 'project', projectPath: plan.projectRoot }
+ : { kind: 'file', filePath };
+ } catch {
+ return null;
+ }
+ });
+
+ // Parallel opens — each window's OS-level `show()` is deferred behind
+ // its own dual-signal show gate, which releases in nondeterministic
+ // order. `show()` steals key-window focus on macOS, so the raise waits
+ // for EVERY restored window to reveal before raising the last (most
+ // recently focused) entry — otherwise a sibling that shows later steals
+ // focus back. Waiting for all reveals also keeps `bringToFront`'s
+ // `show()` from bypassing the target's own gate.
+ const opens = orderedKeys.map((key) => {
+ const action = actionByKey.get(key);
+ if (action === undefined) return Promise.resolve();
+ return action.kind === 'project'
+ ? openProjectOrFallbackToNavigator(action.projectPath, 'recents')
+ : openEphemeralFile(action.filePath);
+ });
void Promise.allSettled(opens).then(() =>
raiseMostRecentlyFocusedAfterRestore({
- projects: decision.projects,
- getWindow: (projectPath) => {
- const ctx = wm?.getWindowFor(projectPath);
+ windowKeys: orderedKeys,
+ // `getWindowFor` / `focusWindowForProject` canonicalize their input,
+ // so a loose-file key (canonical file path) resolves its ephemeral
+ // window just as a project key resolves its project window.
+ getWindow: (key) => {
+ const ctx = wm?.getWindowFor(key);
return ctx ? (ctx.window as unknown as RevealableWindow) : undefined;
},
- raise: (projectPath) => {
- wm?.focusWindowForProject(projectPath);
+ raise: (key) => {
+ wm?.focusWindowForProject(key);
},
deps: {
setTimeout: (cb, ms) => setTimeout(cb, ms),
@@ -6727,25 +6816,14 @@ function bootPrimaryInstance(): void {
// those events would rewrite `lastOpenedProject` / the focus
// sequence with close-order noise after the snapshot is taken.
freezeFocusTracking('prepare-for-relaunch');
- // Snapshot every open project window so the post-update boot
- // restores all of them — not just `lastOpenedProject` — ordered
- // least → most recently focused so the boot can raise the last
- // entry and land the user in the window they were working in.
- // Persist BEFORE the server shutdown: `saveAppState` is a
- // synchronous tmp-write + rename that completes well before
- // `stopAllOwnedServers` returns or `quitAndInstall()` fires.
- const openProjects = sortByFocusSequence(
- wm?.getOpenProjectPaths() ?? [],
- projectFocusSeq,
- );
- appState = { ...appState, pendingWindowRestore: openProjects };
- if (!saveAppState(appState)) {
- // Persisting the snapshot failed, so the post-update boot may not
- // reopen all the windows that were open before the relaunch.
- console.warn('[main] failed to persist window-restore snapshot before relaunch', {
- projectCount: openProjects.length,
- });
- }
+ // Snapshot every open window (projects + loose files) so the
+ // post-update boot restores all of them — not just
+ // `lastOpenedProject` — ordered least → most recently focused so the
+ // boot can raise the last entry. Write-once + persisted BEFORE the
+ // server shutdown: `saveAppState` is a synchronous tmp-write + rename
+ // that completes well before `stopAllOwnedServers` returns or
+ // `quitAndInstall()` fires.
+ captureWindowRestoreSnapshot('prepare-for-relaunch');
// Two-phase shutdown: SIGTERM detached server pids (and SIGKILL any
// dev-path utilityProcess.fork helpers), then poll the lock files
// until they release or 10 s elapses, then escalate to SIGKILL on
@@ -6860,6 +6938,11 @@ function bootPrimaryInstance(): void {
// close re-focuses a surviving window, and recording that churn would
// overwrite `lastOpenedProject` with whichever window closed last.
freezeFocusTracking('before-quit');
+ // Snapshot the open-window set for session restore on the next launch.
+ // Write-once: the update paths (`prepareForRelaunch` / `before-quit-for-
+ // update`) already captured the richer pre-teardown set, so this no-ops
+ // there and only fires for a normal quit.
+ captureWindowRestoreSnapshot('before-quit');
// Flush pending startup telemetry before exit. `emitStartupWaterfall`
// covers a quit during the post-window-shown flush-deadline window (the
// `.unref()`'d deadline timer won't fire once the process is exiting): it
@@ -6882,6 +6965,12 @@ function bootPrimaryInstance(): void {
// silent install-on-quit path and is idempotent with the earlier
// `prepareForRelaunch` freeze on the "Relaunch now" path.
freezeFocusTracking('before-quit-for-update');
+ // Snapshot BEFORE the server teardown below: on the silent
+ // `autoInstallOnAppQuit` path there is no `prepareForRelaunch`, and this
+ // hook precedes the plain `before-quit`, so this is the only pre-teardown
+ // capture point. Write-once, so the "Relaunch now" path (already
+ // snapshotted in `prepareForRelaunch`) no-ops here.
+ captureWindowRestoreSnapshot('before-quit-for-update');
// Shut down the servers this desktop spawned BEFORE the swap completes, so
// the relaunched (new-version) app spawns fresh instead of attaching to a
// stale old-version server and showing the version-drift toast. Fires on
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 5d77c84f6..2db20bb9e 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -82,6 +82,14 @@ export interface MenuDeps {
getRecentProjects(): ReadonlyArray<{ path: string; name: string }>;
/** Clear the recent-projects list (File → Recent project → Clear menu). */
clearRecentProjects(): void;
+ /**
+ * Current recent loose-files list (top-of-LRU first). Optional — when wired
+ * (alongside `openEphemeralFile`), File → Recent files ▸ <row> reopens each
+ * loose file. Absent (unit tests) → no Recent files submenu renders.
+ */
+ getRecentFiles?(): ReadonlyArray<{ path: string; name: string }>;
+ /** Clear the recent loose-files list (File → Recent files → Clear menu). */
+ clearRecentFiles?(): void;
/** Open an external URL (Help menu). Injected so the `shell` runtime value doesn't cross the module boundary. */
openExternalUrl(url: string): void;
/**
@@ -681,6 +689,28 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
},
];
+ // Recent loose files (File → Open File). Only rendered when `getRecentFiles`
+ // is wired; each row reopens via `openEphemeralFile` (which re-derives
+ // project-vs-ephemeral). Mirrors the Recent project submenu.
+ const recentFiles = deps.getRecentFiles?.() ?? [];
+ const recentFilesSubmenu: MenuItemConstructorOptions[] =
+ recentFiles.length === 0
+ ? [{ label: 'No recent files', enabled: false }]
+ : [
+ ...recentFiles.slice(0, 10).map((row) => ({
+ label: row.name,
+ sublabel: row.path,
+ click: () => {
+ void deps.openEphemeralFile?.(row.path);
+ },
+ })),
+ { type: 'separator' as const },
+ {
+ label: 'Clear menu',
+ click: () => deps.clearRecentFiles?.(),
+ },
+ ];
+
const template: MenuItemConstructorOptions[] = [
// macOS application menu (auto-populated with the app name).
...(isMac
@@ -727,6 +757,9 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
label: 'Recent project',
submenu: recentSubmenu,
},
+ ...(deps.getRecentFiles !== undefined
+ ? [{ label: 'Recent files', submenu: recentFilesSubmenu }]
+ : []),
...leafOf('file-project'),
{ type: 'separator' },
...leafOf('file-worktree'),
diff --git a/packages/desktop/src/main/restore-focus.test.ts b/packages/desktop/src/main/restore-focus.test.ts
index 0c7f0d9d2..885c3db4e 100644
--- a/packages/desktop/src/main/restore-focus.test.ts
+++ b/packages/desktop/src/main/restore-focus.test.ts
@@ -116,7 +116,7 @@ describe('raiseMostRecentlyFocusedAfterRestore', () => {
const raised: string[] = [];
const p = raiseMostRecentlyFocusedAfterRestore({
- projects: ['/a', '/b'],
+ windowKeys: ['/a', '/b'],
getWindow: (path) => wins[path],
raise: (path) => raised.push(path),
deps,
@@ -141,7 +141,7 @@ describe('raiseMostRecentlyFocusedAfterRestore', () => {
const raised: string[] = [];
const p = raiseMostRecentlyFocusedAfterRestore({
- projects: ['/a', '/b'],
+ windowKeys: ['/a', '/b'],
getWindow: (path) => wins[path],
raise: (path) => raised.push(path),
deps,
@@ -159,7 +159,7 @@ describe('raiseMostRecentlyFocusedAfterRestore', () => {
const raised: string[] = [];
await raiseMostRecentlyFocusedAfterRestore({
- projects: ['/b'],
+ windowKeys: ['/b'],
getWindow: () => winB,
raise: (path) => raised.push(path),
deps,
@@ -172,7 +172,7 @@ describe('raiseMostRecentlyFocusedAfterRestore', () => {
const { deps } = makeTimers();
const raised: string[] = [];
await raiseMostRecentlyFocusedAfterRestore({
- projects: [],
+ windowKeys: [],
getWindow: () => undefined,
raise: (path) => raised.push(path),
deps,
@@ -188,7 +188,7 @@ describe('raiseMostRecentlyFocusedAfterRestore', () => {
const raised: string[] = [];
const p = raiseMostRecentlyFocusedAfterRestore({
- projects: ['/a', '/b'],
+ windowKeys: ['/a', '/b'],
getWindow: (path) => wins[path],
raise: (path) => raised.push(path),
deps,
@@ -200,4 +200,26 @@ describe('raiseMostRecentlyFocusedAfterRestore', () => {
await p;
expect(raised).toEqual(['/b']);
});
+
+ test('raises across kinds — a loose-file key can be the raise target', async () => {
+ // Keys are opaque (a project path OR a canonical file path); the loose-file
+ // window is focused last, so it is the one raised after every window reveals.
+ const { deps } = makeTimers();
+ const projWin = makeWindow({ visible: true });
+ const fileWin = makeWindow();
+ const wins: Record<string, FakeWindow> = { '/proj': projWin, '/notes/todo.md': fileWin };
+ const raised: string[] = [];
+
+ const p = raiseMostRecentlyFocusedAfterRestore({
+ windowKeys: ['/proj', '/notes/todo.md'],
+ getWindow: (key) => wins[key],
+ raise: (key) => raised.push(key),
+ deps,
+ });
+
+ await flush();
+ fileWin.emitShow();
+ await p;
+ expect(raised).toEqual(['/notes/todo.md']);
+ });
});
diff --git a/packages/desktop/src/main/restore-focus.ts b/packages/desktop/src/main/restore-focus.ts
index 93e533d3e..77ebf15ce 100644
--- a/packages/desktop/src/main/restore-focus.ts
+++ b/packages/desktop/src/main/restore-focus.ts
@@ -79,21 +79,23 @@ export function whenWindowRevealed(win: RevealableWindow, deps: RestoreFocusDeps
* were destroyed mid-restore are skipped; if the target itself is gone, nothing
* is raised.
*
- * @param projects Restored project paths, ordered least → most recently focused.
+ * @param windowKeys Restore keys — a project path OR a loose-file's canonical
+ * file path — ordered least → most recently focused. `getWindow` / `raise`
+ * resolve either kind (the WM lookups canonicalize their input).
*/
export async function raiseMostRecentlyFocusedAfterRestore(input: {
- projects: readonly string[];
- getWindow: (projectPath: string) => RevealableWindow | undefined;
- raise: (projectPath: string) => void;
+ windowKeys: readonly string[];
+ getWindow: (key: string) => RevealableWindow | undefined;
+ raise: (key: string) => void;
deps: RestoreFocusDeps;
}): Promise<void> {
- const { projects, getWindow, raise, deps } = input;
- const target = projects[projects.length - 1];
+ const { windowKeys, getWindow, raise, deps } = input;
+ const target = windowKeys[windowKeys.length - 1];
if (target === undefined) return;
await Promise.all(
- projects.map((projectPath) => {
- const win = getWindow(projectPath);
+ windowKeys.map((key) => {
+ const win = getWindow(key);
if (!win || win.isDestroyed?.() === true) return Promise.resolve();
return whenWindowRevealed(win, deps);
}),
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index de7350469..99ec7c547 100644
--- a/packages/desktop/src/main/state-store.ts
+++ b/packages/desktop/src/main/state-store.ts
@@ -50,6 +50,40 @@ export interface PersistedWindowBounds {
isFullScreen: boolean;
}
+/**
+ * One entry in the persisted session-restore snapshot. A restart reopens the
+ * full set of windows open at the last clean exit — each is either a project
+ * window (keyed by its resolved project path) or a loose single-file
+ * ("Open File") window (keyed by the canonical file path). Ordered least → most
+ * recently focused so the restoring boot can raise the last entry.
+ */
+export type RestoredWindow =
+ | { kind: 'project'; projectPath: string }
+ | { kind: 'file'; filePath: string };
+
+/**
+ * Stable key for a `RestoredWindow` — the string used for focus-recency
+ * ordering and for the WindowManager `getWindowFor` lookup at restore time.
+ * Projects key by their (possibly symlinked) resolved path, matching
+ * `projectFocusSeq` + `getOpenProjectPaths`; loose files key by the canonical
+ * file path (matching an ephemeral window's `canonicalKey`).
+ */
+export function windowRestoreKey(w: RestoredWindow): string {
+ return w.kind === 'project' ? w.projectPath : w.filePath;
+}
+
+/**
+ * A loose single-file ("Open File") open, tracked in a durable LRU list
+ * separate from `recentProjects`. Surfaced in File → Open Recent so a user can
+ * reopen a file they edited outside any project. `path` is the realpath-
+ * canonical file path (the LRU key); `name` is the basename shown in the menu.
+ */
+interface RecentFile {
+ path: string;
+ name: string;
+ lastOpenedAt: string;
+}
+
interface ProjectSessionState {
/** User-open tabs for this project, in visible tab order. */
openTabs: string[];
@@ -93,6 +127,13 @@ export const MAX_SUPPORTED_SCHEMA_VERSION = 1;
export interface AppState {
/** LRU-capped recent-projects, newest first. */
recentProjects: RecentProject[];
+ /**
+ * LRU-capped recent loose files opened via File → Open File, newest first.
+ * Separate from `recentProjects` — a loose file is not a project. Surfaced in
+ * File → Open Recent so a user can reopen a file they edited outside any
+ * project.
+ */
+ recentFiles: RecentFile[];
/** Most recently opened project, or null if Navigator was last visible. */
lastOpenedProject: string | null;
/**
@@ -213,15 +254,17 @@ export interface AppState {
*/
lastUsedProjectParent: string | null;
/**
- * Snapshot of every project window open at the moment the auto-updater's
- * `quitAndInstall()` was about to fire (the `prepareForRelaunch` hook).
- * The next boot restores ALL of these windows, not just `lastOpenedProject`
- * — an update relaunch should land the user back where they were.
+ * Snapshot of every window open at the last clean exit — a normal quit, a
+ * "Relaunch now" update, or the silent install-on-quit update. Captured
+ * write-once at the earliest teardown-preceding hook of each path. Each entry
+ * is a project OR a loose single-file window. The next boot restores ALL of
+ * them, not just `lastOpenedProject` — a restart should land the user back
+ * where they were.
*
- * `null` means no relaunch-restore is pending: the normal boot path opens
- * `lastOpenedProject` (or the Navigator). An empty array means a relaunch
- * happened with no project windows open (only the Navigator) — the boot
- * path consumes it and opens the Navigator rather than `lastOpenedProject`.
+ * `null` means no restore is pending: the boot path falls back to
+ * `lastOpenedProject` (or the Navigator). An empty array means the app quit
+ * with nothing open (only the Navigator) — the boot path consumes it and
+ * opens the Navigator rather than `lastOpenedProject`.
* Cleared back to `null` on the boot that consumes it, before any window
* opens, so a crash mid-restore can't loop the restore forever.
*
@@ -233,7 +276,7 @@ export interface AppState {
* actually working in. Readers must not assume the pre-ordering-era
* insertion order.
*/
- pendingWindowRestore: string[] | null;
+ pendingWindowRestore: RestoredWindow[] | null;
/**
* Whether spell check is enabled. `session.setSpellCheckerEnabled` is
* session-wide and all OK windows share the default session, so this is a
@@ -244,10 +287,12 @@ export interface AppState {
}
const RECENT_CAP = 20;
+const RECENT_FILES_CAP = 20;
export function emptyState(): AppState {
return {
recentProjects: [],
+ recentFiles: [],
lastOpenedProject: null,
versionPendingInstall: null,
attemptedInstall: null,
@@ -374,6 +419,62 @@ function parseProjectSessions(raw: unknown): Record<string, ProjectSessionState>
return sessions;
}
+/**
+ * Tolerant parse of the session-restore snapshot. Accepts BOTH the legacy
+ * `string[]` shape (each string coerced to a `{ kind: 'project' }` entry) and
+ * the current `RestoredWindow[]` object shape; unrecognized entries are
+ * dropped and duplicates de-duped. Returns `null` only for a non-array (absent
+ * / legacy-null); an empty-but-present array stays `[]` (the "quit with nothing
+ * open → Navigator" signal). No `schemaVersion` bump is needed: an older build
+ * reading a new-format array coerces the objects away via its own
+ * `sanitizeStringArray`, degrading to one Navigator open, never corruption.
+ */
+function parsePendingWindowRestore(raw: unknown): RestoredWindow[] | null {
+ if (!Array.isArray(raw)) return null;
+ const out: RestoredWindow[] = [];
+ const seen = new Set<string>();
+ for (const item of raw) {
+ let win: RestoredWindow | null = null;
+ if (typeof item === 'string') {
+ if (item.length > 0) win = { kind: 'project', projectPath: item };
+ } else if (typeof item === 'object' && item !== null) {
+ const o = item as Record<string, unknown>;
+ if (o.kind === 'project' && typeof o.projectPath === 'string' && o.projectPath.length > 0) {
+ win = { kind: 'project', projectPath: o.projectPath };
+ } else if (o.kind === 'file' && typeof o.filePath === 'string' && o.filePath.length > 0) {
+ win = { kind: 'file', filePath: o.filePath };
+ }
+ }
+ if (win === null) continue;
+ const key = `${win.kind}:${windowRestoreKey(win)}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(win);
+ }
+ return out;
+}
+
+function parseRecentFiles(raw: unknown): RecentFile[] {
+ if (!Array.isArray(raw)) return [];
+ const out: RecentFile[] = [];
+ const seen = new Set<string>();
+ for (const r of raw) {
+ if (typeof r !== 'object' || r === null) continue;
+ const item = r as Record<string, unknown>;
+ if (
+ typeof item.path === 'string' &&
+ item.path.length > 0 &&
+ typeof item.name === 'string' &&
+ typeof item.lastOpenedAt === 'string' &&
+ !seen.has(item.path)
+ ) {
+ seen.add(item.path);
+ out.push({ path: item.path, name: item.name, lastOpenedAt: item.lastOpenedAt });
+ }
+ }
+ return out;
+}
+
/**
* Add a project to the recent list (or move to front if already present).
* Returns a NEW state (immutable update — caller persists).
@@ -411,6 +512,24 @@ export function addRecentProject(
return { ...state, recentProjects: updated, lastOpenedProject: projectPath };
}
+/**
+ * Add a loose file to the Recent Files list (or move it to the front). Returns
+ * a NEW state (immutable update — caller persists). `filePath` is the realpath-
+ * canonical path (the LRU key); `name` is the basename shown in the menu.
+ * Unlike `addRecentProject`, this does NOT touch `lastOpenedProject` — a loose
+ * file is not a project and must never become the single-project restore
+ * fallback.
+ */
+export function addRecentFile(state: AppState, filePath: string, name: string): AppState {
+ const now = new Date().toISOString();
+ const filtered = state.recentFiles.filter((f) => f.path !== filePath);
+ const updated: RecentFile[] = [{ path: filePath, name, lastOpenedAt: now }, ...filtered].slice(
+ 0,
+ RECENT_FILES_CAP,
+ );
+ return { ...state, recentFiles: updated };
+}
+
/** Remove a project from the recent list. */
export function removeRecentProject(state: AppState, projectPath: string): AppState {
const projectSessions = { ...state.projectSessions };
@@ -661,18 +780,19 @@ export function parseAppState(raw: unknown): AppState | null {
typeof obj.lastUsedProjectParent === 'string' && obj.lastUsedProjectParent.length > 0
? obj.lastUsedProjectParent
: null;
- // Defensive: only an array coerces to a (deduped, string-only) restore
- // snapshot; everything else (absent key on a legacy state.json, null, wrong
- // type) returns null — the normal `lastOpenedProject` boot path.
- const pendingWindowRestore = Array.isArray(obj.pendingWindowRestore)
- ? sanitizeStringArray(obj.pendingWindowRestore)
- : null;
+ // Tolerant union parse (legacy `string[]` + new `RestoredWindow[]`); see
+ // `parsePendingWindowRestore`. A non-array (absent / legacy-null) returns
+ // null — the `lastOpenedProject` fallback path.
+ const pendingWindowRestore = parsePendingWindowRestore(obj.pendingWindowRestore);
+ // Additive field: absent / corrupt → empty list (no Recent Files yet).
+ const recentFiles = parseRecentFiles(obj.recentFiles);
// Additive field: a missing or non-boolean value coerces to the `true`
// default, so only an explicit persisted `false` keeps checking off.
const spellCheckEnabled =
typeof obj.spellCheckEnabled === 'boolean' ? obj.spellCheckEnabled : true;
return {
recentProjects,
+ recentFiles,
lastOpenedProject,
versionPendingInstall,
attemptedInstall,
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index 031db76b6..5c114c817 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -39,6 +39,7 @@ import { registerPendingDelivery } from '../shared/ipc-send.ts';
import type { AssetOpenResult } from './asset-allowlist.ts';
import { attachAssetSafetyNet } from './asset-safety-net.ts';
import type { ShowGateRegistry } from './show-gate.ts';
+import type { RestoredWindow } from './state-store.ts';
import type { ShareDeepLinkBranchSwitchPayload } from './url-scheme.ts';
import { classifyServerVersion } from './version-drift.ts';
@@ -423,11 +424,19 @@ export interface WindowManagerDeps {
* both the relaunch-restore snapshot and `removeRecentProject` cleanup
* (which deletes by this exact string — a divergent key would leak the
* bounds entry). Present only for project windows (spawn + attach);
- * ephemeral single-file windows omit it and keep cascade placement +
- * no focus tracking (their "projectPath" is the file's parent dir,
- * never a project, and file keys are never pruned from recents).
+ * ephemeral single-file windows omit it and keep cascade placement (their
+ * "projectPath" is the file's parent dir, never a project, so bounds memory
+ * and `lastOpenedProject` must not key off it). Ephemeral windows instead
+ * pass `focusKey`.
*/
projectPath?: string;
+ /**
+ * Focus-recency key for an ephemeral single-file window — the canonical
+ * file path. Wired so a loose-file window joins the restore focus ordering
+ * (and the post-restore raise) WITHOUT writing `lastOpenedProject`, which
+ * stays project-only (keyed by `projectPath`). Absent for project windows.
+ */
+ focusKey?: string;
/** Other webPreferences / window opts the manager wants to set. */
}): BrowserWindowLike;
/**
@@ -848,6 +857,19 @@ export class WindowManager {
*/
private readonly ephemeralPendingByPath = new Map<string, Promise<ProjectContext>>();
+ /**
+ * canonicalKey → in-flight `createProjectWindow` promise. The project analog
+ * of `ephemeralPendingByPath`: `createProjectWindow`'s existing dedup only
+ * matches a COMPLETED window in `windowsByPath`, but that entry lands only
+ * after the seconds-long discover + spawn + renderer load. Two concurrent
+ * opens of the same project (session restore re-deriving two loose files into
+ * one project, or a restore racing a deep-link) would both miss the completed-
+ * window dedup and spawn a duplicate window + second server. Registered
+ * synchronously before the first await; a concurrent caller awaits it and
+ * focuses the resulting window. Cleared in the work body's `finally`.
+ */
+ private readonly projectPendingByPath = new Map<string, Promise<ProjectContext>>();
+
/**
* canonicalKey → keepalive WS handle for the open project window. Opened
* by `attachToExistingServer` and closed by the window's `closed` handler
@@ -966,6 +988,27 @@ export class WindowManager {
return paths;
}
+ /**
+ * Every live window as a kinded restore descriptor — a project window keyed
+ * by its (possibly symlinked) `projectPath`, or a loose single-file window
+ * keyed by its canonical file path. The session-restore snapshot source,
+ * superseding `getOpenProjectPaths` (which flattened an ephemeral window to
+ * its parent directory, so a restored loose file reopened as a full project).
+ * Skips destroyed windows, same as `getOpenProjectPaths`.
+ */
+ getOpenWindows(): RestoredWindow[] {
+ const windows: RestoredWindow[] = [];
+ for (const ctx of this.windowsByPath.values()) {
+ if (ctx.window.isDestroyed?.() === true) continue;
+ windows.push(
+ ctx.ephemeral !== undefined
+ ? { kind: 'file', filePath: ctx.canonicalKey }
+ : { kind: 'project', projectPath: ctx.projectPath },
+ );
+ }
+ return windows;
+ }
+
windowCount(): number {
return this.windowsByPath.size;
}
@@ -1397,6 +1440,43 @@ export class WindowManager {
}
async createProjectWindow(opts: CreateProjectWindowOpts): Promise<ProjectContext> {
+ const canonicalKey = this.canonicalizeKey(resolve(opts.projectPath));
+ // In-flight reservation (mirrors `createEphemeralWindow`): the inner
+ // method's dedup only matches a COMPLETED window, so a concurrent second
+ // open of the same project — session restore collapsing two loose files
+ // into one project, or a restore racing a deep-link — would spawn a
+ // duplicate. Registered synchronously so a concurrent caller observes it.
+ const inFlight = this.projectPendingByPath.get(canonicalKey);
+ if (inFlight) {
+ const ctx = await inFlight;
+ if (ctx.window.isDestroyed?.() !== true) {
+ this.bringToFront(ctx.window);
+ return ctx;
+ }
+ // The in-flight open's window was torn down before we observed it; its
+ // `finally` cleared the reservation, so the fresh attempt starts clean.
+ }
+ // `spawnProjectWindow`'s synchronous prefix (the `tryAttachExistingServer`
+ // sync gates) still runs synchronously as `work` is created — no await
+ // precedes it here — preserving the spawn-path tests' `fire('ready')`
+ // ordering.
+ const work = (async (): Promise<ProjectContext> => {
+ try {
+ return await this.spawnProjectWindow(opts);
+ } finally {
+ this.projectPendingByPath.delete(canonicalKey);
+ }
+ })();
+ this.projectPendingByPath.set(canonicalKey, work);
+ return work;
+ }
+
+ /**
+ * The uncached body of `createProjectWindow` — never call directly (it has no
+ * in-flight reservation, so two direct calls would race). Keeps its own
+ * COMPLETED-window fast-path for sequential re-opens.
+ */
+ private async spawnProjectWindow(opts: CreateProjectWindowOpts): Promise<ProjectContext> {
const projectPath = resolve(opts.projectPath);
const canonicalKey = this.canonicalizeKey(projectPath);
const existing = this.windowsByPath.get(canonicalKey);
@@ -2116,6 +2196,9 @@ export class WindowManager {
...instanceLabelArgs(),
],
title: formatEditorTitle(projectName),
+ // Focus-recency key = canonical file path, so this loose-file window
+ // joins the restore ordering without writing `lastOpenedProject`.
+ focusKey: canonicalKey,
});
// Asset root is the file's real parent (`opts.contentDir`), NOT the throwaway
// temp projectDir — so `![[sibling]]` assets are allowlisted against the
diff --git a/packages/desktop/src/main/window-placement.test.ts b/packages/desktop/src/main/window-placement.test.ts
index 0b2e7bd18..a4fa073e5 100644
--- a/packages/desktop/src/main/window-placement.test.ts
+++ b/packages/desktop/src/main/window-placement.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, test } from 'vitest';
-import type { PersistedWindowBounds } from './state-store.ts';
+import type { PersistedWindowBounds, RestoredWindow } from './state-store.ts';
import {
MIN_VISIBLE_WIDTH_PX,
resolveRestoredPlacement,
- sortByFocusSequence,
+ sortWindowsByFocusSequence,
TITLE_BAR_REACH_PX,
} from './window-placement.ts';
@@ -129,34 +129,43 @@ describe('resolveRestoredPlacement', () => {
});
});
-describe('sortByFocusSequence', () => {
- test('orders least → most recently focused', () => {
+describe('sortWindowsByFocusSequence', () => {
+ const proj = (projectPath: string): RestoredWindow => ({ kind: 'project', projectPath });
+ const file = (filePath: string): RestoredWindow => ({ kind: 'file', filePath });
+
+ test('orders least → most recently focused, across projects and loose files', () => {
const seq = new Map([
['/a', 3],
- ['/b', 9],
+ ['/notes/todo.md', 9],
['/c', 5],
]);
- expect(sortByFocusSequence(['/a', '/b', '/c'], seq)).toEqual(['/a', '/c', '/b']);
+ expect(
+ sortWindowsByFocusSequence([proj('/a'), file('/notes/todo.md'), proj('/c')], seq),
+ ).toEqual([proj('/a'), proj('/c'), file('/notes/todo.md')]);
});
- test('never-focused paths sort first, preserving relative order', () => {
+ test('never-focused windows sort first, preserving relative order', () => {
const seq = new Map([['/focused', 4]]);
- expect(sortByFocusSequence(['/x', '/focused', '/y'], seq)).toEqual(['/x', '/y', '/focused']);
+ expect(sortWindowsByFocusSequence([proj('/x'), proj('/focused'), file('/y.md')], seq)).toEqual([
+ proj('/x'),
+ file('/y.md'),
+ proj('/focused'),
+ ]);
});
test('does not mutate the input', () => {
- const paths = ['/b', '/a'];
- sortByFocusSequence(
- paths,
+ const windows = [proj('/b'), proj('/a')];
+ sortWindowsByFocusSequence(
+ windows,
new Map([
['/a', 1],
['/b', 2],
]),
);
- expect(paths).toEqual(['/b', '/a']);
+ expect(windows).toEqual([proj('/b'), proj('/a')]);
});
test('empty input → empty output', () => {
- expect(sortByFocusSequence([], new Map())).toEqual([]);
+ expect(sortWindowsByFocusSequence([], new Map())).toEqual([]);
});
});
diff --git a/packages/desktop/src/main/window-placement.ts b/packages/desktop/src/main/window-placement.ts
index 354925b00..e6ff90cc5 100644
--- a/packages/desktop/src/main/window-placement.ts
+++ b/packages/desktop/src/main/window-placement.ts
@@ -6,7 +6,11 @@
* exercise multi-monitor topologies directly.
*/
-import type { PersistedWindowBounds } from './state-store.ts';
+import {
+ type PersistedWindowBounds,
+ type RestoredWindow,
+ windowRestoreKey,
+} from './state-store.ts';
export interface PlacementRect {
x: number;
@@ -77,15 +81,19 @@ export function resolveRestoredPlacement(input: {
}
/**
- * Stable ascending sort of project paths by focus sequence — least recently
- * focused first, MOST recently focused last. Paths with no recorded focus
- * (never focused this session) sort first, keeping their relative order.
+ * Stable ascending sort of restore-snapshot windows by focus sequence — least
+ * recently focused first, MOST recently focused last. Windows with no recorded
+ * focus (never focused this session) sort first, keeping their relative order.
* Orders the `pendingWindowRestore` snapshot so the restoring boot can raise
- * the last entry and land the user in the window they were working in.
+ * the last entry and land the user in the window they were working in. Keys
+ * each window via `windowRestoreKey` (project path or canonical file path), the
+ * same key `projectFocusSeq` records focus under.
*/
-export function sortByFocusSequence(
- paths: readonly string[],
+export function sortWindowsByFocusSequence(
+ windows: readonly RestoredWindow[],
focusSeq: ReadonlyMap<string, number>,
-): string[] {
- return [...paths].sort((a, b) => (focusSeq.get(a) ?? 0) - (focusSeq.get(b) ?? 0));
+): RestoredWindow[] {
+ return [...windows].sort(
+ (a, b) => (focusSeq.get(windowRestoreKey(a)) ?? 0) - (focusSeq.get(windowRestoreKey(b)) ?? 0),
+ );
}
diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.ts
index 46df1fc13..458a62980 100644
--- a/packages/desktop/tests/main/state-store.test.ts
+++ b/packages/desktop/tests/main/state-store.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, test, vi } from 'vitest';
import {
+ addRecentFile,
addRecentProject,
annotateMissing,
emptyState,
@@ -463,25 +464,63 @@ describe('state-store (pendingWindowRestore — post-update window restore)', ()
expect(parsed?.pendingWindowRestore).toBeNull();
});
- test('parseAppState round-trips a non-empty restore snapshot', () => {
- const state = { ...emptyState(), pendingWindowRestore: ['/tmp/a', '/tmp/b'] };
+ test('parseAppState coerces a LEGACY string[] snapshot to project entries', () => {
+ // Back-compat: a state.json written before the kinded union stored bare
+ // project paths. Each coerces to a `{ kind: 'project' }` entry — no schema
+ // bump needed.
+ const parsed = parseAppState({
+ recentProjects: [],
+ pendingWindowRestore: ['/tmp/a', '/tmp/b'],
+ });
+ expect(parsed?.pendingWindowRestore).toEqual([
+ { kind: 'project', projectPath: '/tmp/a' },
+ { kind: 'project', projectPath: '/tmp/b' },
+ ]);
+ });
+
+ test('parseAppState round-trips a kinded snapshot (project + loose file)', () => {
+ const state = {
+ recentProjects: [],
+ pendingWindowRestore: [
+ { kind: 'project', projectPath: '/tmp/a' },
+ { kind: 'file', filePath: '/notes/todo.md' },
+ ],
+ };
const parsed = parseAppState(JSON.parse(JSON.stringify(state)));
- expect(parsed?.pendingWindowRestore).toEqual(['/tmp/a', '/tmp/b']);
+ expect(parsed?.pendingWindowRestore).toEqual([
+ { kind: 'project', projectPath: '/tmp/a' },
+ { kind: 'file', filePath: '/notes/todo.md' },
+ ]);
});
test('parseAppState preserves an empty snapshot as [] — distinct from null', () => {
- // [] means "a relaunch happened with no project windows open"; the boot
- // path opens the Navigator rather than falling back to lastOpenedProject.
+ // [] means "the app quit with nothing open"; the boot path opens the
+ // Navigator rather than falling back to lastOpenedProject.
const parsed = parseAppState({ recentProjects: [], pendingWindowRestore: [] });
expect(parsed?.pendingWindowRestore).toEqual([]);
});
- test('parseAppState dedupes and drops non-string / empty entries', () => {
+ test('parseAppState dedupes and drops invalid entries (mixed legacy + kinded)', () => {
const parsed = parseAppState({
recentProjects: [],
- pendingWindowRestore: ['/tmp/a', '/tmp/a', '', 123, '/tmp/b', null],
+ pendingWindowRestore: [
+ '/tmp/a', // legacy project string
+ { kind: 'project', projectPath: '/tmp/a' }, // dup of the above → dropped
+ '', // empty → dropped
+ 123, // non-string/object → dropped
+ { kind: 'file', filePath: '/notes/x.md' },
+ { kind: 'file' }, // missing filePath → dropped
+ { kind: 'bogus', projectPath: '/tmp/z' }, // unknown kind → dropped
+ { kind: 'file', filePath: '/notes/x.md' }, // dup file → dropped
+ { kind: 'project', projectPath: '/tmp/b' },
+ null,
+ ],
});
- expect(parsed?.pendingWindowRestore).toEqual(['/tmp/a', '/tmp/b']);
+ expect(parsed?.pendingWindowRestore).toEqual([
+ { kind: 'project', projectPath: '/tmp/a' },
+ { kind: 'file', filePath: '/notes/x.md' },
+ { kind: 'project', projectPath: '/tmp/b' },
+ ]);
});
test('parseAppState coerces a non-array pendingWindowRestore to null', () => {
@@ -494,6 +533,60 @@ describe('state-store (pendingWindowRestore — post-update window restore)', ()
});
});
+describe('state-store (recentFiles — durable loose-file LRU)', () => {
+ test('emptyState seeds recentFiles as an empty list', () => {
+ expect(emptyState().recentFiles).toEqual([]);
+ });
+
+ test('addRecentFile prepends and does NOT touch lastOpenedProject', () => {
+ const withProject = addRecentProject(emptyState(), '/tmp/proj', 'proj');
+ const next = addRecentFile(withProject, '/notes/todo.md', 'todo.md');
+ expect(next.recentFiles.length).toBe(1);
+ expect(next.recentFiles[0]?.path).toBe('/notes/todo.md');
+ expect(next.recentFiles[0]?.name).toBe('todo.md');
+ // A loose file must never become the single-project restore fallback.
+ expect(next.lastOpenedProject).toBe('/tmp/proj');
+ });
+
+ test('addRecentFile moves an existing entry to the front', () => {
+ let s = addRecentFile(emptyState(), '/notes/a.md', 'a.md');
+ s = addRecentFile(s, '/notes/b.md', 'b.md');
+ s = addRecentFile(s, '/notes/a.md', 'a.md'); // re-open a
+ expect(s.recentFiles.map((f) => f.path)).toEqual(['/notes/a.md', '/notes/b.md']);
+ });
+
+ test('addRecentFile caps the list at 20 (LRU eviction)', () => {
+ let s = emptyState();
+ for (let i = 0; i < 25; i++) {
+ s = addRecentFile(s, `/notes/f${i}.md`, `f${i}.md`);
+ }
+ expect(s.recentFiles.length).toBe(20);
+ expect(s.recentFiles[0]?.path).toBe('/notes/f24.md');
+ expect(s.recentFiles.find((f) => f.path === '/notes/f0.md')).toBeUndefined();
+ });
+
+ test('parseAppState round-trips recentFiles and drops invalid entries', () => {
+ const parsed = parseAppState({
+ recentProjects: [],
+ recentFiles: [
+ { path: '/notes/a.md', name: 'a.md', lastOpenedAt: '2026-07-20T00:00:00Z' },
+ { path: '', name: 'empty', lastOpenedAt: '2026-07-20T00:00:00Z' }, // empty path → dropped
+ { path: '/notes/a.md', name: 'dup', lastOpenedAt: '2026-07-21T00:00:00Z' }, // dup → dropped
+ { path: '/notes/b.md', name: 'b.md' }, // missing lastOpenedAt → dropped
+ 'nonsense', // non-object → dropped
+ ],
+ });
+ expect(parsed?.recentFiles).toEqual([
+ { path: '/notes/a.md', name: 'a.md', lastOpenedAt: '2026-07-20T00:00:00Z' },
+ ]);
+ });
+
+ test('parseAppState defaults a legacy state.json without recentFiles to []', () => {
+ const parsed = parseAppState({ recentProjects: [], lastOpenedProject: null });
+ expect(parsed?.recentFiles).toEqual([]);
+ });
+});
+
describe('state-store (spellCheckEnabled — app-wide spell-check toggle)', () => {
test('defaults to true on a fresh state', () => {
expect(emptyState().spellCheckEnabled).toBe(true);