Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): remember project window positions and focus (#2619)
Andrew Mikofalvyc95f4c4f1314
diff --git a/.changeset/remember-project-window-positions.md b/.changeset/remember-project-window-positions.mdnew file mode 100644index 000000000..16679ae87--- /dev/null+++ b/.changeset/remember-project-window-positions.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Remember each project's window position across opens and relaunches. Reopening a project now restores its editor window to the exact frame it last had — same display, same position, same size, including maximized / full-screen state — instead of the cascade default; cascade remains the fallback for projects with no memory or whose remembered display is no longer connected. The desktop also tracks which project window was most recently focused: a post-update relaunch reopens every window at its old position and brings the window you were actually working in back to the front, and a normal cold start reopens the project you were last in rather than the one you happened to open last. Focus tracking freezes the moment shutdown begins, so the window-close cascade during quit or update install can't mislabel "last active" with whichever window closed last.diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 497da3088..4e1777d11 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -292,12 +292,14 @@ import {evaluateSchemaCompatibility,getProjectSessionState,MAX_SUPPORTED_SCHEMA_VERSION,+ type PersistedWindowBounds,parseAppState,removeRecentProject,type SchemaIncompatibilityDiagnostic,saveAppStateToDir,setLastUsedProjectParent,setProjectSessionState,+ setProjectWindowBounds,setSpellCheckEnabled as setSpellCheckEnabledState,type UpdateChannel,} from './state-store.ts';@@ -349,6 +351,7 @@ import {WindowManager,} from './window-manager.ts';import { WINDOW_MIN_SIZE } from './window-min-size.ts';+import { resolveRestoredPlacement, sortByFocusSequence } from './window-placement.ts';import {classifyRecentGit,classifyRecentGitAsync,@@ -443,6 +446,19 @@ function pickCascadeAnchor(): BrowserWindow | null {return null;}+/**+ * Register a window as a future cascade anchor and wire its removal. Split+ * from `applyCascadePosition` so windows restored to remembered bounds still+ * anchor later cascades without being repositioned themselves.+ */+function registerCascadeAnchor(win: BrowserWindow): void {+ cascadeOrder.push(win);+ win.on('closed', () => {+ const idx = cascadeOrder.indexOf(win);+ if (idx !== -1) cascadeOrder.splice(idx, 1);+ });+}+function applyCascadePosition(win: BrowserWindow): void {const anchor = pickCascadeAnchor();if (anchor) {@@ -455,10 +471,96 @@ function applyCascadePosition(win: BrowserWindow): void {});if (pos) win.setPosition(pos.x, pos.y);}- cascadeOrder.push(win);- win.on('closed', () => {- const idx = cascadeOrder.indexOf(win);- if (idx !== -1) cascadeOrder.splice(idx, 1);+ registerCascadeAnchor(win);+}++/**+ * Position a new editor window: the project's remembered frame when one is+ * persisted and still usable on the current display set, else the cascade+ * default. Maximize / full-screen re-entry is deferred to the window's+ * `'show'` — both `maximize()` and macOS full-screen force the native window+ * visible, which would bypass the dual-signal show gate and resurface the+ * un-themed first-paint flash the gate exists to prevent.+ */+function applyProjectWindowPlacement(win: BrowserWindow, projectPath: string | undefined): void {+ const saved = projectPath !== undefined ? appState.projectWindowBounds[projectPath] : undefined;+ const placement = resolveRestoredPlacement({+ saved,+ workAreas: screen.getAllDisplays().map((d) => d.workArea),+ minSize: WINDOW_MIN_SIZE.EDITOR,+ });+ if (!placement) {+ applyCascadePosition(win);+ return;+ }+ win.setBounds(placement.bounds);+ if (placement.maximize || placement.fullscreen) {+ win.once('show', () => {+ if (win.isDestroyed()) return;+ if (placement.fullscreen) win.setFullScreen(true);+ else win.maximize();+ });+ }+ registerCascadeAnchor(win);+}++/**+ * Persist a project window's frame so the next open of the same project+ * restores it. macOS emits `'moved'` / `'resized'` once per completed drag+ * (not continuously), and the mode events + `'close'` are one-shot, so each+ * event persists synchronously — no debounce timer whose flush could be lost+ * to a quit. `getNormalBounds()` keeps the persisted rect at the+ * un-maximized / un-fullscreened frame while the flags remember the mode.+ */+function trackProjectWindowBounds(win: BrowserWindow, projectPath: string): void {+ const persist = () => {+ if (win.isDestroyed()) return;+ const bounds: PersistedWindowBounds = {+ ...win.getNormalBounds(),+ isMaximized: win.isMaximized(),+ isFullScreen: win.isFullScreen(),+ };+ appState = setProjectWindowBounds(appState, projectPath, bounds);+ saveAppState(appState);+ };+ win.on('moved', persist);+ win.on('resized', persist);+ win.on('maximize', persist);+ win.on('unmaximize', persist);+ win.on('enter-full-screen', persist);+ win.on('leave-full-screen', persist);+ win.on('close', persist);+}++// Focus-recency tracking for project windows. The sequence map orders the+// relaunch-restore snapshot (least → most recently focused) and+// `lastOpenedProject` follows focus so a cold boot reopens the project the+// user was last IN, not the one they happened to open last. Frozen from the+// first shutdown signal onward: teardown closes windows one by one and macOS+// re-focuses a surviving window after each close, so tracking those events+// would record "whichever window closed last" as the user's last-active+// project, overwriting the truth captured before teardown began. A cancelled+// quit leaves tracking frozen — degrading to the pre-tracking behavior+// (`lastOpenedProject` still advances on every project OPEN), never worse.+let projectFocusSeqCounter = 0;+const projectFocusSeq = new Map<string, number>();+let focusTrackingFrozen = false;++function freezeFocusTracking(reason: string): void {+ if (focusTrackingFrozen) return;+ focusTrackingFrozen = true;+ getLogger('lifecycle').info({ reason }, 'project focus tracking frozen for shutdown');+}++function trackProjectWindowFocus(win: BrowserWindow, projectPath: string): void {+ win.on('focus', () => {+ if (focusTrackingFrozen) return;+ projectFocusSeqCounter += 1;+ projectFocusSeq.set(projectPath, projectFocusSeqCounter);+ if (appState.lastOpenedProject !== projectPath) {+ appState = { ...appState, lastOpenedProject: projectPath };+ saveAppState(appState);+ }});}@@ -972,7 +1074,11 @@ function ensureWindowManager() {win.on('page-title-updated', (e) => {e.preventDefault();});- applyCascadePosition(win);+ applyProjectWindowPlacement(win, opts.projectPath);+ if (opts.projectPath !== undefined) {+ trackProjectWindowBounds(win, opts.projectPath);+ trackProjectWindowFocus(win, opts.projectPath);+ }attachSpellcheckMenuToWindow(win);// Per-window PTY reap: closing the window kills its shell (no orphan).// Idempotent — the manager no-ops for a window that never opened one. The@@ -5085,9 +5191,30 @@ function bootPrimaryInstance(): void {}if (decision.action === 'restore') {- for (const projectPath of decision.projects) {- void openProjectOrFallbackToNavigator(projectPath, 'recents');- }+ // Parallel opens — the snapshot is ordered least → most recently+ // focused (see `pendingWindowRestore`), but each window shows only+ // when its own theme gate releases, so completion order (and thus+ // which window ends up focused) is nondeterministic. Raise the+ // snapshot's LAST entry once every open settles AND its window is+ // actually visible: `bringToFront` calls `show()`, so raising a+ // still-gated window would bypass the dual-signal show gate and+ // resurface the un-themed first paint.+ const opens = decision.projects.map((projectPath) =>+ openProjectOrFallbackToNavigator(projectPath, 'recents'),+ );+ const lastActiveProject = decision.projects[decision.projects.length - 1];+ void Promise.allSettled(opens).then(() => {+ if (lastActiveProject === undefined) return;+ const ctx = wm?.getWindowFor(lastActiveProject);+ // Absent context = the open failed and fell back to the Navigator;+ // nothing to raise.+ if (!ctx || ctx.window.isDestroyed?.() === true) return;+ const raise = () => {+ if (ctx.window.isDestroyed?.() !== true) wm?.focusWindowForProject(lastActiveProject);+ };+ if (ctx.window.isVisible?.() === true) raise();+ else (ctx.window as unknown as BrowserWindow).once('show', raise);+ });} else if (decision.action === 'lastOpened') {void openProjectOrFallbackToNavigator(decision.project, 'recents');} else if (decision.action === 'navigator') {@@ -5303,12 +5430,22 @@ function bootPrimaryInstance(): void {// window-close IPC isn't fast enough — Hocuspocus drain + file-watcher// teardown can outlast ShipIt's poll budget.prepareForRelaunch: async () => {+ // Freeze focus tracking BEFORE any teardown: the window-close+ // cascade below re-focuses each surviving window, and tracking+ // 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`. Persist- // BEFORE the server shutdown: `saveAppState` is a synchronous tmp-- // write + rename that completes well before `stopAllOwnedServers`- // returns or `quitAndInstall()` fires.- const openProjects = wm?.getOpenProjectPaths() ?? [];+ // 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@@ -5427,6 +5564,10 @@ function bootPrimaryInstance(): void {// survives the imminent exit.app.on('before-quit', () => {getLogger('lifecycle').info({}, 'before-quit');+ // Stop tracking focus before the quit sequence closes windows — each+ // close re-focuses a surviving window, and recording that churn would+ // overwrite `lastOpenedProject` with whichever window closed last.+ freezeFocusTracking('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@@ -5445,6 +5586,10 @@ function bootPrimaryInstance(): void {// from "the user just quit".electronAutoUpdater.on('before-quit-for-update', () => {getLogger('updater').info({}, 'before-quit-for-update — update install will relaunch the app');+ // Same focus-churn guard as `before-quit` — this event precedes it on the+ // silent install-on-quit path and is idempotent with the earlier+ // `prepareForRelaunch` freeze on the "Relaunch now" path.+ freezeFocusTracking('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 ondiff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.tsindex c4c506e5d..551338ace 100644--- a/packages/desktop/src/main/state-store.ts+++ b/packages/desktop/src/main/state-store.ts@@ -32,6 +32,24 @@ interface RecentProject {gitRemoteUrl?: string;}+/**+ * Persisted frame of a project's editor window, captured on move/resize/+ * mode-change/close and restored on the next open of the same project.+ * `x/y/width/height` always hold the NORMAL-state frame+ * (`BrowserWindow.getNormalBounds()`), so leaving maximize/full-screen+ * restores the pre-mode geometry; the two flags remember the mode itself.+ */+export interface PersistedWindowBounds {+ x: number;+ y: number;+ width: number;+ height: number;+ /** Window was maximized (macOS zoom); bounds hold the pre-maximize frame. */+ isMaximized: boolean;+ /** Window was in native full-screen; bounds hold the non-fullscreen frame. */+ isFullScreen: boolean;+}+interface ProjectSessionState {/** User-open tabs for this project, in visible tab order. */openTabs: string[];@@ -154,6 +172,24 @@ export interface AppState {dismissedRepairForBundle: string | null;/** Per-project editor session state, keyed by realpath-canonical contentDir. */projectSessions: Record<string, ProjectSessionState>;+ /**+ * Per-project editor-window frame memory, keyed by the resolved project+ * path (`ProjectContext.projectPath`) — the exact string that keys+ * `projectSessions` and `recentProjects[].path`, so the+ * `removeRecentProject` cleanup below deletes by the same key. Written on+ * every completed move/resize/mode-change and+ * on window close; read at window creation so reopening a project lands+ * its window where the user left it (same display, same position, same+ * size) instead of the cascade default. Entries whose frame no longer+ * intersects a connected display are ignored at read time (`window-+ * placement.ts`), not rewritten — so unplugging a monitor while a project+ * is CLOSED keeps its memory intact for when the monitor returns. (A+ * project whose window is open during the unplug re-persists wherever+ * macOS migrates the window — the memory tracks where the window IS.)+ * Removed alongside `projectSessions` when a project is dropped from+ * recents.+ */+ projectWindowBounds: Record<string, PersistedWindowBounds>;/*** Schema version of the persisted state, written by whichever build last* touched it. Reads default to `1` when the field is missing. The boot@@ -188,6 +224,14 @@ export interface AppState {* 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.+ *+ * Ordered least → MOST recently focused: the snapshot is sorted by the+ * focus-recency sequence at `prepareForRelaunch` time (before any window+ * closes — teardown's close cascade re-focuses surviving windows and would+ * corrupt the order), and the restoring boot raises the LAST entry once its+ * window is visible, so the user lands back in the window they were+ * actually working in. Readers must not assume the pre-ordering-era+ * insertion order.*/pendingWindowRestore: string[] | null;/**@@ -213,6 +257,7 @@ export function emptyState(): AppState {stuckHintShown: false,dismissedRepairForBundle: null,projectSessions: {},+ projectWindowBounds: {},schemaVersion: CURRENT_SCHEMA_VERSION,lastUsedProjectParent: null,pendingWindowRestore: null,@@ -285,6 +330,40 @@ function parseProjectSessionState(raw: unknown): ProjectSessionState {};}+function parsePersistedWindowBounds(raw: unknown): PersistedWindowBounds | null {+ if (typeof raw !== 'object' || raw === null) return null;+ const obj = raw as Record<string, unknown>;+ const isFiniteNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);+ if (+ !isFiniteNumber(obj.x) ||+ !isFiniteNumber(obj.y) ||+ !isFiniteNumber(obj.width) ||+ !isFiniteNumber(obj.height)+ ) {+ return null;+ }+ if (obj.width <= 0 || obj.height <= 0) return null;+ return {+ x: Math.round(obj.x),+ y: Math.round(obj.y),+ width: Math.round(obj.width),+ height: Math.round(obj.height),+ isMaximized: obj.isMaximized === true,+ isFullScreen: obj.isFullScreen === true,+ };+}++function parseProjectWindowBounds(raw: unknown): Record<string, PersistedWindowBounds> {+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return {};+ const boundsByProject: Record<string, PersistedWindowBounds> = {};+ for (const [projectKey, value] of Object.entries(raw)) {+ if (projectKey.length === 0) continue;+ const bounds = parsePersistedWindowBounds(value);+ if (bounds !== null) boundsByProject[projectKey] = bounds;+ }+ return boundsByProject;+}+function parseProjectSessions(raw: unknown): Record<string, ProjectSessionState> {if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return {};const sessions: Record<string, ProjectSessionState> = {};@@ -336,11 +415,33 @@ export function addRecentProject(export function removeRecentProject(state: AppState, projectPath: string): AppState {const projectSessions = { ...state.projectSessions };delete projectSessions[projectPath];+ const projectWindowBounds = { ...state.projectWindowBounds };+ delete projectWindowBounds[projectPath];return {...state,recentProjects: state.recentProjects.filter((p) => p.path !== projectPath),lastOpenedProject: state.lastOpenedProject === projectPath ? null : state.lastOpenedProject,projectSessions,+ projectWindowBounds,+ };+}++/**+ * Record a project window's frame. Returns a new state — caller persists.+ * `projectPath` is the resolved project path (`ProjectContext.projectPath`),+ * the same string that keys `projectSessions` / `recentProjects[].path` —+ * NOT the realpath-canonical `canonicalKey`, or `removeRecentProject` (which+ * deletes by the recents entry's path) would leak the entry for symlinked+ * projects.+ */+export function setProjectWindowBounds(+ state: AppState,+ projectPath: string,+ bounds: PersistedWindowBounds,+): AppState {+ return {+ ...state,+ projectWindowBounds: { ...state.projectWindowBounds, [projectPath]: bounds },};}@@ -550,6 +651,9 @@ export function parseAppState(raw: unknown): AppState | null {? obj.schemaVersion: 1;const projectSessions = parseProjectSessions(obj.projectSessions);+ // Additive field: a state.json predating window-bounds memory (or a+ // corrupted per-entry blob) coerces to the empty map — cascade placement.+ const projectWindowBounds = parseProjectWindowBounds(obj.projectWindowBounds);// Defensive: only string values survive; everything else (null, undefined,// wrong type from a corrupted state.json) coerces to null and the read// handler falls back to the platform default.@@ -578,6 +682,7 @@ export function parseAppState(raw: unknown): AppState | null {stuckHintShown,dismissedRepairForBundle,projectSessions,+ projectWindowBounds,schemaVersion,lastUsedProjectParent,pendingWindowRestore,diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 61d4b53f0..14891d3a4 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -403,6 +403,19 @@ export interface WindowManagerDeps {* `<title>OpenKnowledge</title>` from overwriting this after load.*/title: string;+ /**+ * Resolved user-facing project path (`ProjectContext.projectPath`) —+ * the same string that keys `recentProjects` / `projectSessions` and+ * that `getOpenProjectPaths()` returns, so the production seam keys+ * window-bounds memory and focus-recency tracking consistently with+ * 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).+ */+ projectPath?: string;/** Other webPreferences / window opts the manager wants to set. */}): BrowserWindowLike;/**@@ -1666,6 +1679,7 @@ export class WindowManager {const window = this.deps.createWindow({additionalArguments,title: formatEditorTitle(projectName),+ projectPath,});this.deps.startup?.markWindowCreated?.();@@ -2302,6 +2316,7 @@ export class WindowManager {...(freshlyCreated ? ['--ok-fresh-create=1'] : []),],title: formatEditorTitle(projectName),+ projectPath,});this.deps.startup?.markWindowCreated?.();diff --git a/packages/desktop/src/main/window-placement.test.ts b/packages/desktop/src/main/window-placement.test.tsnew file mode 100644index 000000000..80d66150e--- /dev/null+++ b/packages/desktop/src/main/window-placement.test.ts@@ -0,0 +1,162 @@+import { describe, expect, test } from 'bun:test';+import type { PersistedWindowBounds } from './state-store.ts';+import {+ MIN_VISIBLE_WIDTH_PX,+ resolveRestoredPlacement,+ sortByFocusSequence,+ TITLE_BAR_REACH_PX,+} from './window-placement.ts';++const MIN_SIZE = { width: 720, height: 480 };+const PRIMARY = { x: 0, y: 25, width: 1920, height: 1055 };+const SECONDARY_RIGHT = { x: 1920, y: 0, width: 2560, height: 1415 };++function bounds(overrides: Partial<PersistedWindowBounds> = {}): PersistedWindowBounds {+ return {+ x: 320,+ y: 152,+ width: 1280,+ height: 800,+ isMaximized: false,+ isFullScreen: false,+ ...overrides,+ };+}++describe('resolveRestoredPlacement', () => {+ test('no saved bounds → null (cascade fallback)', () => {+ expect(+ resolveRestoredPlacement({ saved: undefined, workAreas: [PRIMARY], minSize: MIN_SIZE }),+ ).toBeNull();+ });++ test('saved frame fully inside a display restores verbatim', () => {+ const placement = resolveRestoredPlacement({+ saved: bounds(),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ });+ expect(placement).toEqual({+ bounds: { x: 320, y: 152, width: 1280, height: 800 },+ maximize: false,+ fullscreen: false,+ });+ });++ test('frame on a secondary display restores there (multi-monitor)', () => {+ const placement = resolveRestoredPlacement({+ saved: bounds({ x: 2200, y: 60 }),+ workAreas: [PRIMARY, SECONDARY_RIGHT],+ minSize: MIN_SIZE,+ });+ expect(placement?.bounds).toEqual({ x: 2200, y: 60, width: 1280, height: 800 });+ });++ test('frame on an unplugged display → null (cascade fallback)', () => {+ // Saved while a display sat to the right; now only the primary remains+ // and the frame starts past its right edge.+ const placement = resolveRestoredPlacement({+ saved: bounds({ x: 2200, y: 60 }),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ });+ expect(placement).toBeNull();+ });++ test('sliver overlap below the visibility floor → null', () => {+ // Only (MIN_VISIBLE_WIDTH_PX - 1) px of the frame clips the display.+ const placement = resolveRestoredPlacement({+ saved: bounds({ x: PRIMARY.x + PRIMARY.width - (MIN_VISIBLE_WIDTH_PX - 1) }),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ });+ expect(placement).toBeNull();+ });++ test('title bar above the work area top → null (unreachable drag handle)', () => {+ const placement = resolveRestoredPlacement({+ saved: bounds({ y: PRIMARY.y - 1 }),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ });+ expect(placement).toBeNull();+ });++ test('title bar below the reachable strip at the bottom → null', () => {+ const placement = resolveRestoredPlacement({+ saved: bounds({ y: PRIMARY.y + PRIMARY.height - (TITLE_BAR_REACH_PX - 1) }),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ });+ expect(placement).toBeNull();+ });++ test('sub-minimum saved size clamps up to the window class floor', () => {+ const placement = resolveRestoredPlacement({+ saved: bounds({ width: 200, height: 100 }),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ });+ expect(placement?.bounds.width).toBe(MIN_SIZE.width);+ expect(placement?.bounds.height).toBe(MIN_SIZE.height);+ });++ test('maximize / fullscreen flags pass through', () => {+ expect(+ resolveRestoredPlacement({+ saved: bounds({ isMaximized: true }),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ })?.maximize,+ ).toBe(true);+ expect(+ resolveRestoredPlacement({+ saved: bounds({ isFullScreen: true }),+ workAreas: [PRIMARY],+ minSize: MIN_SIZE,+ })?.fullscreen,+ ).toBe(true);+ });++ test('negative coordinates on a display arranged left/above restore fine', () => {+ const LEFT_DISPLAY = { x: -1920, y: -500, width: 1920, height: 1080 };+ const placement = resolveRestoredPlacement({+ saved: bounds({ x: -1600, y: -400 }),+ workAreas: [LEFT_DISPLAY, PRIMARY],+ minSize: MIN_SIZE,+ });+ expect(placement?.bounds).toEqual({ x: -1600, y: -400, width: 1280, height: 800 });+ });+});++describe('sortByFocusSequence', () => {+ test('orders least → most recently focused', () => {+ const seq = new Map([+ ['/a', 3],+ ['/b', 9],+ ['/c', 5],+ ]);+ expect(sortByFocusSequence(['/a', '/b', '/c'], seq)).toEqual(['/a', '/c', '/b']);+ });++ test('never-focused paths sort first, preserving relative order', () => {+ const seq = new Map([['/focused', 4]]);+ expect(sortByFocusSequence(['/x', '/focused', '/y'], seq)).toEqual(['/x', '/y', '/focused']);+ });++ test('does not mutate the input', () => {+ const paths = ['/b', '/a'];+ sortByFocusSequence(+ paths,+ new Map([+ ['/a', 1],+ ['/b', 2],+ ]),+ );+ expect(paths).toEqual(['/b', '/a']);+ });++ test('empty input → empty output', () => {+ expect(sortByFocusSequence([], new Map())).toEqual([]);+ });+});diff --git a/packages/desktop/src/main/window-placement.ts b/packages/desktop/src/main/window-placement.tsnew file mode 100644index 000000000..354925b00--- /dev/null+++ b/packages/desktop/src/main/window-placement.ts@@ -0,0 +1,91 @@+/**+ * Pure placement math for restoring a project window to its persisted frame.+ * Sibling of `cascade-position.ts`: that module answers "where does a window+ * with NO memory go", this one answers "are the REMEMBERED bounds still+ * usable on the current display set". Both are Electron-free so tests can+ * exercise multi-monitor topologies directly.+ */++import type { PersistedWindowBounds } from './state-store.ts';++export interface PlacementRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++/**+ * Minimum horizontal overlap between the saved frame and a display's work+ * area for the memory to count as "still on screen". Below this, the window+ * would restore as an unreachable sliver (e.g. the display it lived on was+ * unplugged and only a corner clips the remaining arrangement).+ */+export const MIN_VISIBLE_WIDTH_PX = 100;++/**+ * Vertical strip of the frame's top edge that must sit inside a work area so+ * the title bar stays grabbable. The top edge is the load-bearing part: a+ * window whose title bar is above the screen top (or below the bottom) can't+ * be dragged back by the user, which is the classic stale-bounds failure.+ */+export const TITLE_BAR_REACH_PX = 40;++export interface RestoredPlacement {+ /** Normal-state frame to apply, min-size-clamped. */+ bounds: PlacementRect;+ /** Re-enter maximized after the window is shown. */+ maximize: boolean;+ /** Re-enter native full-screen after the window is shown. */+ fullscreen: boolean;+}++/**+ * Decide whether persisted window bounds are restorable on the current+ * display arrangement. Returns the placement to apply, or `null` when there+ * is no memory or the remembered frame is not usably visible on any display+ * — callers fall back to cascade placement. The frame is used as-persisted+ * (no clamping/translation): if it passes the visibility gate the user can+ * reach it, and silently "repairing" positions is how windows drift to+ * unexpected displays. Width/height are clamped up to the window class's+ * minimum so a corrupt-but-parseable tiny frame can't restore below the+ * `BrowserWindow` min-size floor.+ */+export function resolveRestoredPlacement(input: {+ saved: PersistedWindowBounds | undefined;+ /** Work areas of every connected display (`screen.getAllDisplays()`). */+ workAreas: readonly PlacementRect[];+ minSize: { width: number; height: number };+}): RestoredPlacement | null {+ const { saved, workAreas, minSize } = input;+ if (!saved) return null;+ const width = Math.max(saved.width, minSize.width);+ const height = Math.max(saved.height, minSize.height);+ const usable = workAreas.some((workArea) => {+ const overlapWidth =+ Math.min(saved.x + width, workArea.x + workArea.width) - Math.max(saved.x, workArea.x);+ const titleBarReachable =+ saved.y >= workArea.y && saved.y <= workArea.y + workArea.height - TITLE_BAR_REACH_PX;+ return overlapWidth >= MIN_VISIBLE_WIDTH_PX && titleBarReachable;+ });+ if (!usable) return null;+ return {+ bounds: { x: saved.x, y: saved.y, width, height },+ maximize: saved.isMaximized,+ fullscreen: saved.isFullScreen,+ };+}++/**+ * 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.+ * Orders the `pendingWindowRestore` snapshot so the restoring boot can raise+ * the last entry and land the user in the window they were working in.+ */+export function sortByFocusSequence(+ paths: readonly string[],+ focusSeq: ReadonlyMap<string, number>,+): string[] {+ return [...paths].sort((a, b) => (focusSeq.get(a) ?? 0) - (focusSeq.get(b) ?? 0));+}diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.tsindex ffcea4a23..8b001c415 100644--- a/packages/desktop/tests/main/state-store.test.ts+++ b/packages/desktop/tests/main/state-store.test.ts@@ -7,12 +7,14 @@ import {annotateMissing,emptyState,getProjectSessionState,+ type PersistedWindowBounds,parseAppState,removeRecentProject,type SaveAppStateFs,saveAppStateToDir,setLastUsedProjectParent,setProjectSessionState,+ setProjectWindowBounds,setSpellCheckEnabled,} from '../../src/main/state-store.ts';@@ -535,3 +537,95 @@ describe('state-store (spellCheckEnabled — app-wide spell-check toggle)', () =expect(reparsed?.spellCheckEnabled).toBe(true);});});++describe('state-store (projectWindowBounds — per-project window frame memory)', () => {+ const BOUNDS: PersistedWindowBounds = {+ x: 320,+ y: 152,+ width: 1280,+ height: 800,+ isMaximized: false,+ isFullScreen: false,+ };++ test('emptyState seeds an empty map', () => {+ expect(emptyState().projectWindowBounds).toEqual({});+ });++ test('setProjectWindowBounds immutably records a frame', () => {+ const original = emptyState();+ const next = setProjectWindowBounds(original, '/tmp/a', BOUNDS);+ expect(next.projectWindowBounds['/tmp/a']).toEqual(BOUNDS);+ expect(original.projectWindowBounds).toEqual({});+ });++ test('setProjectWindowBounds overwrites a prior frame for the same key', () => {+ let s = setProjectWindowBounds(emptyState(), '/tmp/a', BOUNDS);+ s = setProjectWindowBounds(s, '/tmp/a', { ...BOUNDS, x: 640, isMaximized: true });+ expect(s.projectWindowBounds['/tmp/a']).toEqual({ ...BOUNDS, x: 640, isMaximized: true });+ });++ test('round-trips through parseAppState', () => {+ const state = setProjectWindowBounds(emptyState(), '/tmp/a', {+ ...BOUNDS,+ isFullScreen: true,+ });+ const reparsed = parseAppState(JSON.parse(JSON.stringify(state)));+ expect(reparsed?.projectWindowBounds['/tmp/a']).toEqual({ ...BOUNDS, isFullScreen: true });+ });++ test('parseAppState defaults a legacy state.json without the key to {}', () => {+ const parsed = parseAppState({ recentProjects: [], lastOpenedProject: null });+ expect(parsed?.projectWindowBounds).toEqual({});+ });++ test('parseAppState drops corrupt entries and keeps valid siblings', () => {+ const parsed = parseAppState({+ recentProjects: [],+ projectWindowBounds: {+ '/tmp/valid': BOUNDS,+ '/tmp/non-numeric': { ...BOUNDS, x: 'left' },+ '/tmp/non-finite': { ...BOUNDS, y: Number.NaN },+ '/tmp/zero-size': { ...BOUNDS, width: 0 },+ '/tmp/not-an-object': 42,+ '': BOUNDS,+ },+ });+ expect(Object.keys(parsed?.projectWindowBounds ?? {})).toEqual(['/tmp/valid']);+ });++ test('parseAppState rounds fractional coordinates and coerces flags to booleans', () => {+ const parsed = parseAppState({+ recentProjects: [],+ projectWindowBounds: {+ '/tmp/a': { x: 1.5, y: -2.4, width: 1280.9, height: 800.2, isMaximized: 'yes' },+ },+ });+ expect(parsed?.projectWindowBounds['/tmp/a']).toEqual({+ x: 2,+ y: -2,+ width: 1281,+ height: 800,+ isMaximized: false,+ isFullScreen: false,+ });+ });++ test('parseAppState coerces a non-object projectWindowBounds to {}', () => {+ expect(+ parseAppState({ recentProjects: [], projectWindowBounds: ['/tmp/a'] })?.projectWindowBounds,+ ).toEqual({});+ expect(+ parseAppState({ recentProjects: [], projectWindowBounds: 'nope' })?.projectWindowBounds,+ ).toEqual({});+ });++ test('removeRecentProject drops the window-bounds entry alongside the session', () => {+ let s = addRecentProject(emptyState(), '/tmp/a', 'a');+ s = setProjectWindowBounds(s, '/tmp/a', BOUNDS);+ s = setProjectWindowBounds(s, '/tmp/b', BOUNDS);+ const next = removeRecentProject(s, '/tmp/a');+ expect(next.projectWindowBounds['/tmp/a']).toBeUndefined();+ expect(next.projectWindowBounds['/tmp/b']).toEqual(BOUNDS);+ });+});diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex 1bb4ebaf8..2137314fe 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -117,7 +117,11 @@ interface TestEnv {utilities: MockUtility[];windows: Array<ReturnType<typeof makeWindow>>;/** Opts recorded from each createWindow call, parallel to `windows`. */- createWindowOpts: Array<{ additionalArguments: string[]; title: string }>;+ createWindowOpts: Array<{+ additionalArguments: string[];+ title: string;+ projectPath?: string;+ }>;forkUtilityArgs: string[][];timers: Array<{ cb: () => void; ms: number }>;killProbe: ReturnType<typeof mock>;@@ -129,7 +133,11 @@ interface TestEnv {function buildEnv(): TestEnv {const utilities: MockUtility[] = [];const windows: Array<ReturnType<typeof makeWindow>> = [];- const createWindowOpts: Array<{ additionalArguments: string[]; title: string }> = [];+ const createWindowOpts: Array<{+ additionalArguments: string[];+ title: string;+ projectPath?: string;+ }> = [];const forkUtilityArgs: string[][] = [];const timers: Array<{ cb: () => void; ms: number }> = [];const killProbe = mock(() => {});@@ -205,6 +213,18 @@ describe('WindowManager', () => {expect(env.createWindowOpts[0]?.title).toBe('dragon-wiki — OpenKnowledge');});+ test('createProjectWindow threads project identity to the window seam (spawn path)', async () => {+ // The production seam keys per-project window-bounds memory and+ // focus-recency tracking on `projectPath` — it must arrive alongside the+ // window construction opts, and must be the SAME string+ // `getOpenProjectPaths()` returns (= `ctx.projectPath`).+ const wm = new WindowManager(env.deps);+ const promise = wm.createProjectWindow({ projectPath: '/tmp/dragon-wiki' });+ env.utilities[0]?.fire({ type: 'ready', port: 52010, apiOrigin: 'http://localhost:52010' });+ const ctx = await promise;+ expect(env.createWindowOpts[0]?.projectPath).toBe(ctx.projectPath);+ });+test('createProjectWindow injects --ok-fresh-create=1 only when freshlyCreated is set', async () => {// The renderer's onboarding card reads this flag (via preload → bridge// config) to stay visible for a first-run create-new project even when a@@ -712,6 +732,10 @@ describe('WindowManager', () => {expect(env.windows.length).toBe(1);// Title is set from projectName in the attach path too.expect(env.createWindowOpts[0]?.title).toBe('dragon — OpenKnowledge');+ // Project identity for bounds/focus memory rides the attach path too —+ // it's the production path, so omitting it here would silently disable+ // window-position restore in packaged builds.+ expect(env.createWindowOpts[0]?.projectPath).toBe(ctx.projectPath);});test('attach path injects --ok-fresh-create=1 when freshlyCreated is set (production path)', async () => {