Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(window): remember the window's size, position and maximized state

Shogun37d9315aeae6
diff --git a/CLAUDE.md b/CLAUDE.md
index 420fcd56d..3d7a28a04 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3112,6 +3112,44 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
- **Shortcuts** (`ShortcutsPanel.tsx`, ? / ⌘/): shown once on first launch (`seenShortcuts`).
**Derived from the registry, never hand-listed** — see the Keybindings invariant below.
- **Welcome** (`WelcomeScreen.tsx`): shown when no projects exist.
+- **Window geometry is REMEMBERED** (`main/window-state.ts`, `<userData>/window-state.json`) — size,
+ position and maximized state, restored at the next launch. Before this the window opened at a
+ hard-coded 1400x900 every time, on every platform, so a user who works maximized re-maximized it
+ on every launch; Electron persists nothing on its own and no platform does it for us. The module
+ is Electron-free in the `keydown-intercept.ts` shape (pure decisions over plain rectangles,
+ structural window interfaces), so the refusals below can be pressed by a test instead of only by
+ someone with two monitors — `screen.getAllDisplays()` is called at the seam in `index.ts` and its
+ **work areas** (not full display bounds) are passed in. The refusals ARE the feature, because each
+ is a way the naive version is worse than the fixed size it replaces:
+ - **`getNormalBounds()`, never `getBounds()`.** While maximized the latter returns the MAXIMIZED
+ rectangle, so saving it makes the next un-maximize hand back a screen-sized window — state that
+ looks right and behaves wrong, and only for the users who maximize.
+ - **A position that is no longer reachable is DROPPED, not clamped.** A laptop undocked from the
+ monitor its window was on would otherwise reopen the app off-screen: running, focusable from the
+ dock, visible nowhere, with no gesture that rescues it. Reachable means a real overlap with some
+ work area (`MIN_VISIBLE_WIDTH`/`HEIGHT`), judged against the CLAMPED size — a few pixels on
+ screen is not a title bar anyone can grab. Dropping keeps the user's size and lets the platform
+ place a window it knows how to place; inventing a corner for it is the guess.
+ - **No capture while minimized or fullscreen.** `isMaximized()` is FALSE while a macOS window is
+ fullscreen, so capturing there records `maximized: false` and erases exactly the preference this
+ exists to remember. The last non-fullscreen state stands, which also means the app never reopens
+ INTO fullscreen — deliberate: a fullscreen window is usually a temporary mode and is much harder
+ to escape on first launch than a maximized one.
+ - **Maximize before the first paint**, while the window is still `show: false`; maximizing after
+ `show()` is a visible jump from the restored size on every launch.
+ - Every field is **re-validated as a number on read** — the file is hand-editable and its values
+ reach the `BrowserWindow` constructor before there is a window in which to report a failure.
+ - Saves are debounced (`resize`/`move` fire continuously through a drag) and flushed
+ **synchronously** on `close`: that is the only moment guaranteed to see the final state, and an
+ awaited write there races the process exit. Published through `renameAtomicSync` with a
+ per-call unique temp, like every other store.
+ - **NT_MULTI is excluded**: a throwaway dev sandbox may share the real app's userData, and it must
+ not move the window of the app being developed.
+ - Desktop only, and genuinely so — a browser tab's geometry is the browser's, and the mobile
+ companion has no window. Nothing here belongs in `src/core`. **Wayland caveat**: a native-Wayland
+ client cannot set its own position (the compositor owns placement), so x/y is honoured under
+ XWayland and quietly ignored otherwise. Size and maximized restore either way, which is what the
+ drop-don't-clamp rule already degrades to.
- **Window chrome**: macOS integrated title bar (`titleBarStyle: 'hiddenInset'`); the tab
bar (`TabBar.tsx`) is the drag region with the `nodeterm` logo + a rounded pill of project
tabs. The New-project `+` is a **sibling** of `.tabbar__tabs`, not its last child — inside
diff --git a/src/main/index.ts b/src/main/index.ts
index d2c1f4202..84a81d41a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -7,7 +7,7 @@ import { readFile, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWrit
import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync } from 'fs'
import { homedir, hostname } from 'os'
import { randomUUID } from 'crypto'
-import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, Notification, powerMonitor, safeStorage, shell, systemPreferences, webContents } from 'electron'
+import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, Notification, powerMonitor, safeStorage, screen, shell, systemPreferences, webContents } from 'electron'
import { IPC } from '../shared/ipc'
// Debug log ring (issue #78): capture the process console from the first line — a packaged app
@@ -227,6 +227,12 @@ import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control
import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'
import { initTelemetry } from './telemetry'
import { initClaudeUsage } from './claude-usage'
+import {
+ readWindowState,
+ resolveWindowBounds,
+ trackWindowState,
+ writeWindowState
+} from './window-state'
import { remoteUsageTargets } from '../core/usage/remote-claude-usage'
import { initLicense, isPremium, getStoredEntitlement } from '../core/license'
import { WhisperModelStore } from '../core/speech/whisper-models'
@@ -930,9 +936,19 @@ function createWindow(): BrowserWindow {
? join(process.resourcesPath, 'icon.png')
: join(__dirname, '../../build/icon.png')
: undefined
+ // Reopen where the user left off (issue: the window forgot its size/position every launch).
+ // A throwaway NT_MULTI sandbox is deliberately excluded: it may share the real app's userData,
+ // and a dev instance must not move the window of the app being developed.
+ const windowStateDir = NT_MULTI ? null : app.getPath('userData')
+ const restored = resolveWindowBounds(
+ windowStateDir ? readWindowState(windowStateDir) : null,
+ // Work areas, not full display bounds: a saved position is checked against the space a window
+ // can actually occupy, which excludes the macOS menu bar, a GNOME top bar and any dock.
+ screen.getAllDisplays().map((d) => d.workArea),
+ { width: 1400, height: 900 }
+ )
const win = new BrowserWindow({
- width: 1400,
- height: 900,
+ ...restored.bounds,
show: false,
backgroundColor: '#1e1e1e',
// NT_MULTI instances are throwaway dev sandboxes: label the window so a second instance is
@@ -960,6 +976,21 @@ function createWindow(): BrowserWindow {
}
})
+ // Maximize BEFORE the first paint. The window is `show: false` until `ready-to-show`, so doing it
+ // here means it is simply born maximized — maximizing after `show()` is a visible jump from the
+ // restored size to full screen on every single launch.
+ if (restored.maximize) win.maximize()
+ // Track from here on. The saves are debounced through ordinary resizing and flushed on `close`,
+ // so an ordinary quit always records the final state and a crash costs at most one gesture.
+ if (windowStateDir) {
+ const stopTrackingWindowState = trackWindowState(win, (state) =>
+ // Best-effort by contract: a window geometry that failed to save is not worth a dialog, and
+ // the previous record stands.
+ void writeWindowState(windowStateDir, state)
+ )
+ win.on('closed', stopTrackingWindowState)
+ }
+
// Register as the live main window (send-time resolution via getMainWindow/sendToMain).
setMainWindow(win)
diff --git a/src/main/window-state.test.ts b/src/main/window-state.test.ts
new file mode 100644
index 000000000..78171af97
--- /dev/null
+++ b/src/main/window-state.test.ts
@@ -0,0 +1,378 @@
+// The window forgot its size, position and maximized state on every launch. What is pinned here is
+// mostly the REFUSALS, because each of them is a way the naive version of this feature makes things
+// worse than the hard-coded 1400x900 it replaces: a window restored onto a monitor that is gone, a
+// maximized session whose un-maximize gives back a screen-sized window, and a macOS fullscreen quit
+// that erases the preference the user actually set.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import {
+ MIN_HEIGHT,
+ MIN_WIDTH,
+ WINDOW_STATE_FILE,
+ captureWindowState,
+ parseWindowState,
+ readWindowState,
+ resolveWindowBounds,
+ trackWindowState,
+ writeWindowState,
+ type Rect,
+ type TrackableWindow,
+ type WindowState
+} from './window-state'
+
+/** A single 1920x1080 display whose work area starts below a 27px top bar. */
+const ONE_SCREEN: Rect[] = [{ x: 0, y: 27, width: 1920, height: 1053 }]
+/** A laptop with a second monitor to its left, the shape that produces negative coordinates. */
+const TWO_SCREENS: Rect[] = [...ONE_SCREEN, { x: -2560, y: 0, width: 2560, height: 1440 }]
+const DEFAULTS = { width: 1400, height: 900 }
+
+function source(over: Partial<{ destroyed: boolean; minimized: boolean; fullScreen: boolean; maximized: boolean; bounds: Rect }> = {}) {
+ return {
+ isDestroyed: () => over.destroyed ?? false,
+ isMinimized: () => over.minimized ?? false,
+ isFullScreen: () => over.fullScreen ?? false,
+ isMaximized: () => over.maximized ?? false,
+ getNormalBounds: () => over.bounds ?? { x: 100, y: 200, width: 1000, height: 700 }
+ }
+}
+
+describe('parseWindowState', () => {
+ it('reads a full record', () => {
+ expect(parseWindowState('{"x":1,"y":2,"width":800,"height":600,"maximized":true}')).toEqual({
+ x: 1,
+ y: 2,
+ width: 800,
+ height: 600,
+ maximized: true
+ })
+ })
+
+ it('refuses non-finite numbers rather than passing them to a BrowserWindow constructor', () => {
+ // The file is hand-editable and these values reach Electron before there is a window in which
+ // to report a failure, so they are re-validated here as numbers, not trusted from a type.
+ expect(parseWindowState('{"width":null,"height":600}')).toBeNull()
+ expect(parseWindowState('{"width":"800","height":600}')).toBeNull()
+ expect(parseWindowState('{"width":0,"height":600}')).toBeNull()
+ expect(parseWindowState('{"width":-10,"height":600}')).toBeNull()
+ // JSON has no NaN/Infinity literal, so `typeof === 'number'` LOOKS sufficient — but an
+ // overflowing exponent parses to Infinity, and `Number.isFinite` is the only thing between
+ // that and the constructor. A mutation dropping it survived the first version of this suite.
+ expect(parseWindowState('{"width":1e999,"height":600}')).toBeNull()
+ expect(parseWindowState('{"width":800,"height":1e999}')).toBeNull()
+ expect(parseWindowState('{"x":1e999,"y":0,"width":800,"height":600}')!.x).toBeUndefined()
+ })
+
+ it('refuses garbage and non-objects without throwing', () => {
+ for (const raw of ['', 'not json', 'null', '[]', '42', '"x"']) {
+ expect(parseWindowState(raw), raw).toBeNull()
+ }
+ })
+
+ it('drops a half-known position — x without y is not a place', () => {
+ const s = parseWindowState('{"x":5,"width":800,"height":600}')
+ expect(s).not.toBeNull()
+ expect(s!.x).toBeUndefined()
+ expect(s!.y).toBeUndefined()
+ })
+
+ it('keeps a legitimate negative position (a monitor left of the primary)', () => {
+ expect(parseWindowState('{"x":-2000,"y":100,"width":800,"height":600}')).toMatchObject({
+ x: -2000,
+ y: 100
+ })
+ })
+
+ it('treats a missing or non-true `maximized` as false, never as truthy', () => {
+ expect(parseWindowState('{"width":800,"height":600}')!.maximized).toBe(false)
+ expect(parseWindowState('{"width":800,"height":600,"maximized":"yes"}')!.maximized).toBe(false)
+ })
+})
+
+describe('resolveWindowBounds', () => {
+ it('falls back to the defaults, unpositioned and unmaximized, with no saved record', () => {
+ expect(resolveWindowBounds(null, ONE_SCREEN, DEFAULTS)).toEqual({
+ bounds: { width: 1400, height: 900 },
+ maximize: false
+ })
+ })
+
+ it('restores a position that is reachable on a live display', () => {
+ const saved: WindowState = { x: 200, y: 100, width: 1000, height: 700, maximized: false }
+ expect(resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS).bounds).toEqual({
+ x: 200,
+ y: 100,
+ width: 1000,
+ height: 700
+ })
+ })
+
+ it('carries the maximized flag through', () => {
+ const saved: WindowState = { width: 1000, height: 700, maximized: true }
+ expect(resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS).maximize).toBe(true)
+ })
+
+ it('DROPS a position on a display that is gone, and keeps the size', () => {
+ // The undocked-laptop case. Restoring this would open the app off-screen: running, focusable
+ // from the dock, visible nowhere, with no gesture that brings it back.
+ const saved: WindowState = { x: -2000, y: 300, width: 1000, height: 700, maximized: false }
+ expect(resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS).bounds).toEqual({
+ width: 1000,
+ height: 700
+ })
+ // Same record, monitor still attached: the position is honoured.
+ expect(resolveWindowBounds(saved, TWO_SCREENS, DEFAULTS).bounds).toMatchObject({ x: -2000 })
+ })
+
+ it('drops a position that only clips the display by a sliver', () => {
+ // Reachable is not the same as "touches": a few pixels of window on screen is not a title bar
+ // the user can grab.
+ const saved: WindowState = { x: 1900, y: 1040, width: 1000, height: 700, maximized: false }
+ expect(resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS).bounds).toEqual({
+ width: 1000,
+ height: 700
+ })
+ })
+
+ it('never clamps a dropped position into a corner — the platform places it instead', () => {
+ const saved: WindowState = { x: 99999, y: 99999, width: 1000, height: 700, maximized: false }
+ const { bounds } = resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS)
+ expect(bounds.x).toBeUndefined()
+ expect(bounds.y).toBeUndefined()
+ })
+
+ it('clamps a size saved on a bigger display down to what this one can show', () => {
+ const saved: WindowState = { width: 5000, height: 2800, maximized: false }
+ expect(resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS).bounds).toEqual({
+ width: 1920,
+ height: 1053
+ })
+ })
+
+ it('floors a degenerate saved size', () => {
+ const saved: WindowState = { width: 1, height: 1, maximized: false }
+ expect(resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS).bounds).toEqual({
+ width: MIN_WIDTH,
+ height: MIN_HEIGHT
+ })
+ })
+
+ it('applies only the floor when no display information is available', () => {
+ // Inventing a ceiling out of nothing would be a guess; the floor is the half that still
+ // protects against a degenerate stored value.
+ expect(resolveWindowBounds({ width: 5000, height: 2800, maximized: false }, [], DEFAULTS).bounds)
+ .toEqual({ width: 5000, height: 2800 })
+ expect(resolveWindowBounds({ width: 1, height: 1, maximized: false }, [], DEFAULTS).bounds)
+ .toEqual({ width: MIN_WIDTH, height: MIN_HEIGHT })
+ })
+
+ it('checks reachability against the CLAMPED size, not the saved one', () => {
+ // A huge saved size shrinks to the screen, so the question "can the user reach this window?"
+ // has to be asked of the rectangle that will actually be opened. The fixture has to be able to
+ // TELL THE TWO APART: at x:-1850 the saved 5000px width still crosses the whole screen, while
+ // the clamped 1920px one leaves 70px showing — under the threshold. Judged on the saved size
+ // this position looks fine and the window opens almost entirely off the left edge.
+ const saved: WindowState = { x: -1850, y: 100, width: 5000, height: 2800, maximized: false }
+ expect(resolveWindowBounds(saved, ONE_SCREEN, DEFAULTS).bounds).toEqual({
+ width: 1920,
+ height: 1053
+ })
+ // Same clamped width, moved right far enough to leave a grabbable strip: now it is kept.
+ const reachable: WindowState = { ...saved, x: -1700 }
+ expect(resolveWindowBounds(reachable, ONE_SCREEN, DEFAULTS).bounds).toMatchObject({ x: -1700 })
+ })
+})
+
+describe('captureWindowState', () => {
+ it('reads the restored bounds and the maximized flag', () => {
+ expect(captureWindowState(source({ maximized: true }))).toEqual({
+ x: 100,
+ y: 200,
+ width: 1000,
+ height: 700,
+ maximized: true
+ })
+ })
+
+ it('uses getNormalBounds, so un-maximizing later restores the pre-maximize size', () => {
+ // getBounds() on a maximized window returns the MAXIMIZED rect. Saving that would make the
+ // next un-maximize hand back a screen-sized window — right-looking state, wrong behaviour,
+ // and only for the users who maximize.
+ const win = {
+ ...source({ maximized: true, bounds: { x: 40, y: 60, width: 1024, height: 768 } }),
+ getBounds: (): Rect => ({ x: 0, y: 27, width: 1920, height: 1053 })
+ }
+ expect(captureWindowState(win)).toMatchObject({ width: 1024, height: 768, x: 40, y: 60 })
+ })
+
+ it('refuses while minimized — the platform owns that geometry, not the user', () => {
+ expect(captureWindowState(source({ minimized: true }))).toBeNull()
+ })
+
+ it('refuses while fullscreen, so a fullscreen quit cannot erase `maximized`', () => {
+ // isMaximized() is false while a macOS window is fullscreen. Capturing here would record
+ // maximized:false and forget exactly the preference this feature exists to remember.
+ expect(captureWindowState(source({ fullScreen: true, maximized: false }))).toBeNull()
+ })
+
+ it('refuses a destroyed window', () => {
+ expect(captureWindowState(source({ destroyed: true }))).toBeNull()
+ })
+
+ it('refuses a degenerate measurement instead of persisting it', () => {
+ expect(captureWindowState(source({ bounds: { x: 0, y: 0, width: 0, height: 0 } }))).toBeNull()
+ expect(
+ captureWindowState(source({ bounds: { x: 0, y: 0, width: NaN, height: 700 } }))
+ ).toBeNull()
+ })
+
+ it('keeps the size when the position is unknowable (Wayland reports no usable x/y)', () => {
+ const s = captureWindowState(
+ source({ bounds: { x: NaN, y: NaN, width: 1200, height: 800 }, maximized: true })
+ )
+ expect(s).toEqual({ width: 1200, height: 800, maximized: true })
+ })
+
+ it('rounds — a fractional device-pixel-ratio bound is not a window size', () => {
+ const s = captureWindowState(source({ bounds: { x: 10.4, y: 20.6, width: 999.5, height: 700.2 } }))
+ expect(s).toEqual({ x: 10, y: 21, width: 1000, height: 700, maximized: false })
+ })
+})
+
+describe('read/write round trip', () => {
+ let dir = ''
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'nt-winstate-'))
+ })
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('writes and reads back', () => {
+ const state: WindowState = { x: 5, y: 6, width: 1200, height: 800, maximized: true }
+ expect(writeWindowState(dir, state)).toBe(true)
+ expect(readWindowState(dir)).toEqual(state)
+ })
+
+ it('leaves no temp litter behind', () => {
+ writeWindowState(dir, { width: 800, height: 600, maximized: false })
+ expect(readFileSync(join(dir, WINDOW_STATE_FILE), 'utf8')).toContain('"width":800')
+ expect(readdirSync(dir)).toEqual([WINDOW_STATE_FILE])
+ })
+
+ it('reads null for a missing file rather than throwing', () => {
+ expect(readWindowState(join(dir, 'nope'))).toBeNull()
+ })
+
+ it('reads null for a corrupt file, and the next write repairs it', () => {
+ writeFileSync(join(dir, WINDOW_STATE_FILE), '{ this is not json')
+ expect(readWindowState(dir)).toBeNull()
+ expect(writeWindowState(dir, { width: 800, height: 600, maximized: false })).toBe(true)
+ expect(readWindowState(dir)).toMatchObject({ width: 800 })
+ })
+
+ it('reports a failed write instead of throwing', () => {
+ expect(writeWindowState(join(dir, 'no', 'such', 'dir'), { width: 1, height: 1, maximized: false })).toBe(false)
+ })
+})
+
+describe('trackWindowState', () => {
+ function harness(over: Parameters<typeof source>[0] = {}) {
+ const listeners = new Map<string, () => void>()
+ const win: TrackableWindow = {
+ ...source(over),
+ on: (event: string, fn: () => void) => listeners.set(event, fn)
+ }
+ const saved: WindowState[] = []
+ // Every timer is kept, not just the latest. A harness that overwrites a single slot cannot see
+ // a MISSING cancel — the stale timers are still armed in production and each one fires its own
+ // save, but the fake has already forgotten them. That mutation survived the first version.
+ const timers = new Map<number, () => void>()
+ let next = 1
+ const stop = trackWindowState(win, (s) => saved.push(s), {
+ debounceMs: 400,
+ setTimer: (fn) => {
+ const id = next++
+ timers.set(id, fn)
+ return id
+ },
+ clearTimer: (h) => {
+ timers.delete(h as number)
+ }
+ })
+ return {
+ saved,
+ stop,
+ fire: (e: string) => listeners.get(e)?.(),
+ /** Fire every timer still armed — exactly what the event loop would do. */
+ tick: () => [...timers.values()].forEach((fn) => fn()),
+ pending: () => timers.size > 0,
+ armed: () => timers.size,
+ events: () => [...listeners.keys()]
+ }
+ }
+
+ it('subscribes to every geometry event plus close', () => {
+ expect(harness().events()).toEqual(['resize', 'move', 'maximize', 'unmaximize', 'close'])
+ })
+
+ it('debounces a burst of resizes into ONE save, leaving ONE timer armed', () => {
+ const h = harness()
+ for (let i = 0; i < 20; i++) h.fire('resize')
+ expect(h.saved).toHaveLength(0)
+ // The count is the real assertion: 20 armed timers would still collapse to "one save" in a
+ // harness that fires only the last one, and would be 20 disk writes in production.
+ expect(h.armed()).toBe(1)
+ h.tick()
+ expect(h.saved).toHaveLength(1)
+ })
+
+ it('a move following a resize replaces its timer rather than adding one', () => {
+ const h = harness()
+ h.fire('resize')
+ h.fire('move')
+ h.fire('maximize')
+ expect(h.armed()).toBe(1)
+ })
+
+ it('saves IMMEDIATELY on close — an awaited save would race the process exit', () => {
+ const h = harness({ maximized: true })
+ h.fire('close')
+ expect(h.saved).toEqual([{ x: 100, y: 200, width: 1000, height: 700, maximized: true }])
+ })
+
+ it('close cancels a pending debounce rather than saving twice', () => {
+ const h = harness()
+ h.fire('resize')
+ h.fire('close')
+ expect(h.saved).toHaveLength(1)
+ expect(h.pending()).toBe(false)
+ })
+
+ it('records the maximize gesture itself', () => {
+ const h = harness({ maximized: true })
+ h.fire('maximize')
+ h.tick()
+ expect(h.saved[0].maximized).toBe(true)
+ })
+
+ it('writes nothing when the window refuses to answer (minimized / fullscreen)', () => {
+ for (const over of [{ minimized: true }, { fullScreen: true }]) {
+ const h = harness(over)
+ h.fire('resize')
+ h.tick()
+ h.fire('close')
+ expect(h.saved).toEqual([])
+ }
+ })
+
+ it('the disposer cancels a pending save', () => {
+ const h = harness()
+ h.fire('resize')
+ expect(h.pending()).toBe(true)
+ h.stop()
+ expect(h.pending()).toBe(false)
+ expect(h.saved).toEqual([])
+ })
+})
diff --git a/src/main/window-state.ts b/src/main/window-state.ts
new file mode 100644
index 000000000..4a57506f1
--- /dev/null
+++ b/src/main/window-state.ts
@@ -0,0 +1,298 @@
+import { readFileSync, rmSync, writeFileSync } from 'fs'
+import path from 'path'
+import { renameAtomicSync, tempNameFor } from '../core/fs-atomic'
+
+/**
+ * Remember the main window's size, position and maximized state across launches.
+ *
+ * The window was created at a hard-coded 1400x900 on every launch, so a user who works maximized
+ * re-maximized it every single time. Electron persists nothing on its own — there is no platform
+ * that does this for us (macOS's NSWindow frame autosave is not wired up by Electron either), so
+ * it is ours to store.
+ *
+ * Everything here is Electron-free on purpose, in the same shape as `keydown-intercept.ts`: the
+ * decisions are pure functions over plain rectangles and the glue takes a structural window, so the
+ * refusals below can be pressed by a test instead of only by a person with two monitors. The one
+ * `electron` call this feature needs — `screen.getAllDisplays()` — is made at the call site in
+ * `index.ts` and passed in as work areas.
+ *
+ * DESKTOP ONLY, and genuinely so: the Server Edition renders into a browser tab whose geometry is
+ * the browser's business, and the mobile companion has no window concept. Nothing here belongs in
+ * `src/core`.
+ */
+
+/** A plain rectangle — a `BrowserWindow` bounds object and an Electron display work area both fit. */
+export interface Rect {
+ x: number
+ y: number
+ width: number
+ height: number
+}
+
+export interface WindowState {
+ width: number
+ height: number
+ /** Absent when the position was never known, or was dropped as unreachable (see below). */
+ x?: number
+ y?: number
+ maximized: boolean
+}
+
+export const WINDOW_STATE_FILE = 'window-state.json'
+
+/** Floor for a restored size. A stored 1x1 is not a window the user can do anything with. */
+export const MIN_WIDTH = 480
+export const MIN_HEIGHT = 360
+
+/**
+ * How much of the window must land on some display's work area for the saved position to be
+ * reusable. The height matters more than the width: a title bar the user cannot reach is a window
+ * they cannot move, and on a stored position from a monitor that is now gone there is no gesture
+ * left that rescues it.
+ */
+export const MIN_VISIBLE_WIDTH = 120
+export const MIN_VISIBLE_HEIGHT = 80
+
+/** The debounce on save. `resize`/`move` fire continuously through a drag. */
+export const SAVE_DEBOUNCE_MS = 400
+
+function finite(v: unknown): number | null {
+ return typeof v === 'number' && Number.isFinite(v) ? v : null
+}
+
+/**
+ * Parse the stored file. `window-state.json` sits in userData, which is hand-editable, and its
+ * numbers go straight into a `BrowserWindow` constructor — a NaN width there throws before the app
+ * has a window to report the failure in. So every field is re-validated as a number here rather
+ * than trusted from its type, the same rule the permission-mode table follows.
+ *
+ * A partial record is refused whole rather than half-adopted: the pair `x`/`y` is meaningless
+ * alone, and a size without both dimensions is not a size.
+ */
+export function parseWindowState(raw: string): WindowState | null {
+ let j: unknown
+ try {
+ j = JSON.parse(raw)
+ } catch {
+ return null
+ }
+ if (!j || typeof j !== 'object') return null
+ const o = j as Record<string, unknown>
+ const width = finite(o.width)
+ const height = finite(o.height)
+ if (width === null || height === null || width <= 0 || height <= 0) return null
+ const x = finite(o.x)
+ const y = finite(o.y)
+ const state: WindowState = { width, height, maximized: o.maximized === true }
+ if (x !== null && y !== null) {
+ state.x = x
+ state.y = y
+ }
+ return state
+}
+
+/** Visible overlap between a window rect and one display's work area. */
+function reachableOn(r: Rect, area: Rect): boolean {
+ const w = Math.min(r.x + r.width, area.x + area.width) - Math.max(r.x, area.x)
+ const h = Math.min(r.y + r.height, area.y + area.height) - Math.max(r.y, area.y)
+ return w >= MIN_VISIBLE_WIDTH && h >= MIN_VISIBLE_HEIGHT
+}
+
+function clamp(v: number, lo: number, hi: number): number {
+ return Math.min(Math.max(v, lo), hi)
+}
+
+/**
+ * Turn a saved record into the constructor options to open with.
+ *
+ * The rule that matters is the one about POSITION: a saved `x`/`y` is only reused when the window
+ * would land somewhere the user can actually reach it. A laptop undocked from the monitor its
+ * window was on would otherwise reopen off-screen, with the app running, focusable from the dock,
+ * and not visible anywhere — and with no way back short of deleting the file. When the position
+ * fails that test it is DROPPED rather than clamped into the nearest display: the size is still
+ * the user's, and letting the platform place a window it knows how to place beats inventing a
+ * corner for it.
+ *
+ * Size is clamped to the largest work area, so a record written on a 5K display does not open a
+ * window taller than the laptop screen reading it. With no display information at all (an empty
+ * list — not a state Electron produces, but the parameter permits it) only the floor applies:
+ * inventing a ceiling from nothing would be a guess, and the floor is the half that protects
+ * against a degenerate stored value.
+ */
+export function resolveWindowBounds(
+ saved: WindowState | null,
+ workAreas: ReadonlyArray<Rect>,
+ defaults: { width: number; height: number }
+): { bounds: { width: number; height: number; x?: number; y?: number }; maximize: boolean } {
+ if (!saved) return { bounds: { ...defaults }, maximize: false }
+
+ const widest = workAreas.reduce((m, a) => Math.max(m, a.width), 0)
+ const tallest = workAreas.reduce((m, a) => Math.max(m, a.height), 0)
+ const width = clamp(saved.width, MIN_WIDTH, widest > 0 ? Math.max(widest, MIN_WIDTH) : Infinity)
+ const height = clamp(
+ saved.height,
+ MIN_HEIGHT,
+ tallest > 0 ? Math.max(tallest, MIN_HEIGHT) : Infinity
+ )
+
+ const placed =
+ saved.x !== undefined &&
+ saved.y !== undefined &&
+ workAreas.some((a) => reachableOn({ x: saved.x!, y: saved.y!, width, height }, a))
+
+ return {
+ bounds: placed ? { x: saved.x, y: saved.y, width, height } : { width, height },
+ maximize: saved.maximized
+ }
+}
+
+/** The window facts a capture needs. Structural so a test can supply a plain object. */
+export interface WindowStateSource {
+ isDestroyed(): boolean
+ isMinimized(): boolean
+ isFullScreen(): boolean
+ isMaximized(): boolean
+ /** The RESTORED bounds — see the note in `captureWindowState`. */
+ getNormalBounds(): Rect
+}
+
+/**
+ * Read the current state, or `null` when the window cannot answer for it.
+ *
+ * Two refusals, and both of them protect the value the user actually set:
+ *
+ * - **Minimized.** A minimized window's geometry is the platform's business, not the user's
+ * choice, and on some window managers it is not the restored rectangle at all.
+ * - **Fullscreen.** `isMaximized()` is FALSE while a macOS window is fullscreen, so capturing here
+ * would record `maximized: false` and quietly forget that the user works maximized — the exact
+ * complaint this feature exists to answer. Skipping keeps the last non-fullscreen state, which
+ * also means the app never reopens into fullscreen; that is deliberate, not an oversight. A
+ * fullscreen window is usually a temporary mode, and restoring one is much harder to escape from
+ * on first launch than restoring a maximized one.
+ *
+ * In both cases the previously saved record stands, which is the honest outcome: "we could not
+ * observe a new preference", never "the preference is gone".
+ *
+ * The bounds come from `getNormalBounds()`, never `getBounds()`. While maximized the latter returns
+ * the MAXIMIZED rectangle, so saving it would make the next un-maximize restore to a window the
+ * size of the screen — the state would look right and behave wrong, and only for the users who
+ * maximize.
+ */
+export function captureWindowState(win: WindowStateSource): WindowState | null {
+ if (win.isDestroyed() || win.isMinimized() || win.isFullScreen()) return null
+ const b = win.getNormalBounds()
+ if (!Number.isFinite(b.width) || !Number.isFinite(b.height) || b.width <= 0 || b.height <= 0) {
+ return null
+ }
+ const state: WindowState = {
+ width: Math.round(b.width),
+ height: Math.round(b.height),
+ maximized: win.isMaximized()
+ }
+ if (Number.isFinite(b.x) && Number.isFinite(b.y)) {
+ state.x = Math.round(b.x)
+ state.y = Math.round(b.y)
+ }
+ return state
+}
+
+/** Read the saved record. Any failure — missing, unreadable, corrupt — is "no record". */
+export function readWindowState(userDataDir: string): WindowState | null {
+ try {
+ return parseWindowState(readFileSync(path.join(userDataDir, WINDOW_STATE_FILE), 'utf8'))
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Publish the record. Synchronous because the last and most important write happens on `close`,
+ * where an awaited one races the process exit and loses.
+ *
+ * Atomic through `renameAtomicSync` with a per-call unique temp, like every other store here — the
+ * file is tiny and rewritten often, which is exactly the shape that loses data to a bare rename on
+ * Windows (see docs/atomic-writes.md). Returns whether it landed; a caller cannot do anything
+ * useful with a failure except not crash, so nothing throws out of here.
+ */
+export function writeWindowState(userDataDir: string, state: WindowState): boolean {
+ const file = path.join(userDataDir, WINDOW_STATE_FILE)
+ const tmp = tempNameFor(file)
+ try {
+ writeFileSync(tmp, `${JSON.stringify(state)}\n`, { encoding: 'utf8', flag: 'wx' })
+ renameAtomicSync(tmp, file)
+ return true
+ } catch {
+ return false
+ } finally {
+ try {
+ rmSync(tmp, { force: true })
+ } catch {
+ /* already renamed into place */
+ }
+ }
+}
+
+/** The window events a tracker subscribes to. Structural, so a test needs no BrowserWindow. */
+export interface TrackableWindow extends WindowStateSource {
+ on(
+ event: 'resize' | 'move' | 'maximize' | 'unmaximize' | 'close',
+ listener: () => void
+ ): unknown
+}
+
+export interface TrackWindowStateOptions {
+ /** Test seam; production uses `SAVE_DEBOUNCE_MS`. */
+ debounceMs?: number
+ /** Test seam for the timer pair. */
+ setTimer?: (fn: () => void, ms: number) => unknown
+ clearTimer?: (handle: unknown) => void
+}
+
+/**
+ * Save the window's state as the user changes it, and once more as it closes.
+ *
+ * `close` is the load-bearing subscription: it is the only moment guaranteed to see the final
+ * state, and it fires on every exit path — the native ×, ⌘Q, and the macOS hide-instead-of-close
+ * branch, which preventDefaults the event but still emits it. The debounced saves during ordinary
+ * use are what make a crash or a `SIGKILL` cost at most one gesture rather than the whole session.
+ *
+ * Returns a disposer that cancels a pending save. It does NOT unsubscribe: the listeners live as
+ * long as the window does, and a window that is closing has already had its final `close` save.
+ */
+export function trackWindowState(
+ win: TrackableWindow,
+ save: (state: WindowState) => void,
+ opts: TrackWindowStateOptions = {}
+): () => void {
+ const delay = opts.debounceMs ?? SAVE_DEBOUNCE_MS
+ const setTimer =
+ opts.setTimer ??
+ ((fn: () => void, ms: number): unknown => {
+ const t = setTimeout(fn, ms)
+ // A pending save must never be the reason the process is still alive at quit.
+ ;(t as { unref?: () => void }).unref?.()
+ return t
+ })
+ const clearTimer = opts.clearTimer ?? ((h: unknown): void => clearTimeout(h as NodeJS.Timeout))
+
+ let pending: unknown = null
+ const cancel = (): void => {
+ if (pending !== null) {
+ clearTimer(pending)
+ pending = null
+ }
+ }
+ const flush = (): void => {
+ cancel()
+ const state = captureWindowState(win)
+ if (state) save(state)
+ }
+ const schedule = (): void => {
+ cancel()
+ pending = setTimer(flush, delay)
+ }
+
+ for (const event of ['resize', 'move', 'maximize', 'unmaximize'] as const) win.on(event, schedule)
+ win.on('close', flush)
+ return cancel
+}