Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): restore window state
Kyou964b9269ded5
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 0006a3412e..2e9da73c28 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -1,4 +1,4 @@-import { app, BrowserWindow, dialog, ipcMain, nativeImage, Notification } from "electron";+import { app, BrowserWindow, dialog, ipcMain, nativeImage, Notification, screen } from "electron";import { homedir } from "os";import { join } from "path";import { pathToFileURL } from "url";@@ -30,6 +30,13 @@ import {readAndClearFreezeBreadcrumb,clearFreezeBreadcrumb,} from "./freeze-breadcrumb";+import {+ loadWindowState,+ resolveWindowOptions,+ saveWindowStateToFile,+ snapshotWindowState,+ windowStateFilePath,+} from "./window-state";import {encodeIssueWindowArgument,parseIssueWindowRequest,@@ -299,9 +306,23 @@ function createWindow(): BrowserWindow {lastKnownSystemLocale = systemLocale;mainRendererMessages.resetReady();++ // Restore prior size/position/maximized/fullscreen (#5244), constraining+ // bounds to the work area of the display the window will land on.+ const stateFile = windowStateFilePath(app.getPath("userData"));+ const savedWindowState = loadWindowState(stateFile);+ const windowOpts = resolveWindowOptions(+ savedWindowState,+ screen.getAllDisplays().map((d) => d.workArea),+ screen.getPrimaryDisplay().workArea,+ );+mainWindow = new BrowserWindow({- width: 1280,- height: 800,+ width: windowOpts.width,+ height: windowOpts.height,+ ...(windowOpts.x != null && windowOpts.y != null+ ? { x: windowOpts.x, y: windowOpts.y }+ : {}),minWidth: 900,minHeight: 600,titleBarStyle: "hiddenInset",@@ -320,6 +341,25 @@ function createWindow(): BrowserWindow {});const window = mainWindow;+ // Persist bounds on resize/move (debounced) and on close so the next+ // launch restores size/position and max/fullscreen flags. getNormalBounds+ // is used so maximized/fullscreen still saves the restore size.+ let persistTimer: ReturnType<typeof setTimeout> | null = null;+ const persistWindowState = () => {+ const snap = snapshotWindowState(window);+ if (snap) saveWindowStateToFile(stateFile, snap);+ };+ const schedulePersistWindowState = () => {+ if (persistTimer) clearTimeout(persistTimer);+ persistTimer = setTimeout(persistWindowState, 400);+ };+ window.on("resize", schedulePersistWindowState);+ window.on("move", schedulePersistWindowState);+ window.on("close", () => {+ if (persistTimer) clearTimeout(persistTimer);+ persistWindowState();+ });+window.on("closed", () => {if (mainWindow === window) {mainWindow = null;@@ -338,6 +378,12 @@ function createWindow(): BrowserWindow {);window.on("ready-to-show", () => {+ // Restore max/fullscreen after normal bounds are applied.+ if (windowOpts.isFullScreen) {+ window.setFullScreen(true);+ } else if (windowOpts.isMaximized) {+ window.maximize();+ }window.show();});diff --git a/apps/desktop/src/main/window-state.node-test.mjs b/apps/desktop/src/main/window-state.node-test.mjsnew file mode 100644index 0000000000..f3210ef10f--- /dev/null+++ b/apps/desktop/src/main/window-state.node-test.mjs@@ -0,0 +1,268 @@+/**+ * Standalone node:test harness for window-state (no vitest/pnpm required).+ * Mirrors the vitest suite so CI and offline environments can both verify #5244.+ *+ * Run: node --experimental-strip-types --test src/main/window-state.node-test.mjs+ */+import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";++const modUrl = pathToFileURL(join(import.meta.dirname, "window-state.ts")).href;+const {+ parseWindowState,+ loadWindowState,+ saveWindowStateToFile,+ isVisibleOnSomeDisplay,+ resolveWindowOptions,+ snapshotWindowState,+ windowStateFilePath,+ DEFAULT_WINDOW_WIDTH,+ DEFAULT_WINDOW_HEIGHT,+ MIN_WINDOW_WIDTH,+ WINDOW_STATE_FILENAME,+} = await import(modUrl);++const dirs = [];+function tempDir() {+ const dir = mkdtempSync(join(tmpdir(), "window-state-"));+ dirs.push(dir);+ return dir;+}+function cleanup() {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+}++describe("parseWindowState", () => {+ test("returns empty object on corrupt JSON", () => {+ assert.deepEqual(parseWindowState("{ not json"), {});+ });+ test("keeps only finite numbers and booleans", () => {+ assert.deepEqual(+ parseWindowState(+ JSON.stringify({+ x: 10.6,+ y: 20,+ width: 1400,+ height: 900,+ isMaximized: true,+ isFullScreen: false,+ junk: "nope",+ }),+ ),+ {+ x: 11,+ y: 20,+ width: 1400,+ height: 900,+ isMaximized: true,+ isFullScreen: false,+ },+ );+ });+});++describe("load/save window state file", () => {+ test("round-trips through disk", () => {+ try {+ const file = join(tempDir(), WINDOW_STATE_FILENAME);+ saveWindowStateToFile(file, {+ x: 1,+ y: 2,+ width: 1000,+ height: 700,+ isMaximized: true,+ });+ assert.equal(existsSync(file), true);+ assert.deepEqual(loadWindowState(file), {+ x: 1,+ y: 2,+ width: 1000,+ height: 700,+ isMaximized: true,+ });+ } finally {+ cleanup();+ }+ });+ test("load returns {} when file is missing", () => {+ try {+ assert.deepEqual(loadWindowState(join(tempDir(), "missing.json")), {});+ } finally {+ cleanup();+ }+ });+ test("load returns {} on corrupt file", () => {+ try {+ const file = join(tempDir(), "bad.json");+ writeFileSync(file, "{ broken", "utf8");+ assert.deepEqual(loadWindowState(file), {});+ } finally {+ cleanup();+ }+ });+});++describe("isVisibleOnSomeDisplay", () => {+ const displays = [{ x: 0, y: 0, width: 1920, height: 1080 }];+ test("false when position missing", () => {+ assert.equal(isVisibleOnSomeDisplay({ width: 100, height: 100 }, displays), false);+ });+ test("true when bounds intersect", () => {+ assert.equal(+ isVisibleOnSomeDisplay({ x: 100, y: 100, width: 800, height: 600 }, displays),+ true,+ );+ });+ test("false when off-screen", () => {+ assert.equal(+ isVisibleOnSomeDisplay({ x: 5000, y: 0, width: 800, height: 600 }, displays),+ false,+ );+ });+});++describe("resolveWindowOptions", () => {+ const displays = [{ x: 0, y: 0, width: 1920, height: 1080 }];++ test("defaults when empty", () => {+ assert.deepEqual(resolveWindowOptions({}, displays), {+ width: DEFAULT_WINDOW_WIDTH,+ height: DEFAULT_WINDOW_HEIGHT,+ isMaximized: false,+ isFullScreen: false,+ });+ });+ test("clamps below-minimum sizes", () => {+ const opts = resolveWindowOptions({ width: 100, height: 50 }, displays);+ assert.equal(opts.width, MIN_WINDOW_WIDTH);+ assert.ok(opts.height >= 600);+ });+ test("keeps an intersecting saved position", () => {+ const opts = resolveWindowOptions({ x: 40, y: 50, width: 1200, height: 800 }, displays);+ assert.equal(opts.x, 40);+ assert.equal(opts.y, 50);+ });+ test("clamps a one-pixel intersection fully inside the work area", () => {+ const opts = resolveWindowOptions(+ { x: 1919, y: 1079, width: 1200, height: 800 },+ displays,+ );+ assert.deepEqual(+ { x: opts.x, y: opts.y, width: opts.width, height: opts.height },+ { x: 720, y: 280, width: 1200, height: 800 },+ );+ });+ test("clamps position when restoring onto a smaller display", () => {+ const opts = resolveWindowOptions(+ { x: 500, y: 300, width: 900, height: 600 },+ [{ x: 0, y: 0, width: 1024, height: 768 }],+ );+ assert.deepEqual(+ { x: opts.x, y: opts.y, width: opts.width, height: opts.height },+ { x: 124, y: 168, width: 900, height: 600 },+ );+ });+ test("shrinks saved dimensions to fit the selected work area", () => {+ const opts = resolveWindowOptions(+ { x: 100, y: 100, width: 1600, height: 1000 },+ [{ x: 0, y: 0, width: 1024, height: 768 }],+ );+ assert.deepEqual(+ { x: opts.x, y: opts.y, width: opts.width, height: opts.height },+ { x: 0, y: 0, width: 1024, height: 768 },+ );+ });+ test("selects the work area with the largest intersection", () => {+ const opts = resolveWindowOptions(+ { x: 1800, y: 100, width: 1000, height: 800 },+ [+ { x: 0, y: 0, width: 1920, height: 1080 },+ { x: 1920, y: 0, width: 1280, height: 1024 },+ ],+ );+ assert.deepEqual(+ { x: opts.x, y: opts.y, width: opts.width, height: opts.height },+ { x: 1920, y: 100, width: 1000, height: 800 },+ );+ });+ test("omits coordinates when saved bounds are completely off-screen", () => {+ assert.deepEqual(+ resolveWindowOptions(+ { x: 5000, y: 0, width: 1200, height: 800, isMaximized: true },+ displays,+ ),+ {+ width: 1200,+ height: 800,+ isMaximized: true,+ isFullScreen: false,+ },+ );+ });+});++describe("snapshotWindowState", () => {+ test("null for destroyed windows", () => {+ assert.equal(+ snapshotWindowState({+ isDestroyed: () => true,+ getNormalBounds: () => ({ x: 0, y: 0, width: 1, height: 1 }),+ isMaximized: () => false,+ isFullScreen: () => false,+ }),+ null,+ );+ });+ test("captures normal bounds and flags", () => {+ assert.deepEqual(+ snapshotWindowState({+ isDestroyed: () => false,+ getNormalBounds: () => ({ x: 12, y: 34, width: 1100, height: 720 }),+ isMaximized: () => true,+ isFullScreen: () => false,+ }),+ {+ x: 12,+ y: 34,+ width: 1100,+ height: 720,+ isMaximized: true,+ isFullScreen: false,+ },+ );+ });+});++describe("windowStateFilePath", () => {+ test("joins userData with filename", () => {+ assert.equal(+ windowStateFilePath("/tmp/user-data"),+ join("/tmp/user-data", WINDOW_STATE_FILENAME),+ );+ });+});++describe("end-to-end persistence shape", () => {+ test("serializes a snapshot the loader accepts", () => {+ try {+ const file = join(tempDir(), WINDOW_STATE_FILENAME);+ const snap = snapshotWindowState({+ isDestroyed: () => false,+ getNormalBounds: () => ({ x: 5, y: 6, width: 1300, height: 850 }),+ isMaximized: () => false,+ isFullScreen: () => true,+ });+ assert.ok(snap);+ saveWindowStateToFile(file, snap);+ const raw = readFileSync(file, "utf8");+ assert.deepEqual(JSON.parse(raw), snap);+ assert.deepEqual(loadWindowState(file), snap);+ } finally {+ cleanup();+ }+ });+});diff --git a/apps/desktop/src/main/window-state.test.ts b/apps/desktop/src/main/window-state.test.tsnew file mode 100644index 0000000000..9cbca9aa53--- /dev/null+++ b/apps/desktop/src/main/window-state.test.ts@@ -0,0 +1,295 @@+import { afterEach, describe, expect, it } from "vitest";+import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ parseWindowState,+ loadWindowState,+ saveWindowStateToFile,+ isVisibleOnSomeDisplay,+ resolveWindowOptions,+ snapshotWindowState,+ windowStateFilePath,+ DEFAULT_WINDOW_WIDTH,+ DEFAULT_WINDOW_HEIGHT,+ MIN_WINDOW_WIDTH,+ WINDOW_STATE_FILENAME,+} from "./window-state";++const dirs: string[] = [];+function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), "window-state-"));+ dirs.push(dir);+ return dir;+}++afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("parseWindowState", () => {+ it("returns empty object on corrupt JSON", () => {+ expect(parseWindowState("{ not json")).toEqual({});+ });++ it("returns empty object on non-object JSON", () => {+ expect(parseWindowState("[]")).toEqual({});+ expect(parseWindowState("null")).toEqual({});+ });++ it("keeps only finite numbers and booleans", () => {+ expect(+ parseWindowState(+ JSON.stringify({+ x: 10.6,+ y: 20,+ width: 1400,+ height: 900,+ isMaximized: true,+ isFullScreen: false,+ junk: "nope",+ }),+ ),+ ).toEqual({+ x: 11,+ y: 20,+ width: 1400,+ height: 900,+ isMaximized: true,+ isFullScreen: false,+ });+ });+});++describe("load/save window state file", () => {+ it("round-trips through disk", () => {+ const file = join(tempDir(), WINDOW_STATE_FILENAME);+ saveWindowStateToFile(file, { x: 1, y: 2, width: 1000, height: 700, isMaximized: true });+ expect(existsSync(file)).toBe(true);+ expect(loadWindowState(file)).toEqual({+ x: 1,+ y: 2,+ width: 1000,+ height: 700,+ isMaximized: true,+ });+ });++ it("load returns {} when file is missing", () => {+ expect(loadWindowState(join(tempDir(), "missing.json"))).toEqual({});+ });++ it("load returns {} on corrupt file", () => {+ const file = join(tempDir(), "bad.json");+ writeFileSync(file, "{ broken", "utf8");+ expect(loadWindowState(file)).toEqual({});+ });+});++describe("isVisibleOnSomeDisplay", () => {+ const displays = [{ x: 0, y: 0, width: 1920, height: 1080 }];++ it("is false when position is missing", () => {+ expect(isVisibleOnSomeDisplay({ width: 100, height: 100 }, displays)).toBe(false);+ });++ it("is true when bounds intersect a display", () => {+ expect(isVisibleOnSomeDisplay({ x: 100, y: 100, width: 800, height: 600 }, displays)).toBe(+ true,+ );+ });++ it("is false when bounds are entirely off-screen (disconnected monitor)", () => {+ expect(+ isVisibleOnSomeDisplay({ x: 5000, y: 0, width: 800, height: 600 }, displays),+ ).toBe(false);+ });+});++describe("resolveWindowOptions", () => {+ const displays = [{ x: 0, y: 0, width: 1920, height: 1080 }];++ it("uses defaults when saved state is empty", () => {+ expect(resolveWindowOptions({}, displays)).toEqual({+ width: DEFAULT_WINDOW_WIDTH,+ height: DEFAULT_WINDOW_HEIGHT,+ isMaximized: false,+ isFullScreen: false,+ });+ });++ it("clamps below-minimum sizes", () => {+ const opts = resolveWindowOptions({ width: 100, height: 50 }, displays);+ expect(opts.width).toBe(MIN_WINDOW_WIDTH);+ expect(opts.height).toBeGreaterThanOrEqual(600);+ });++ it("keeps an intersecting saved position", () => {+ const opts = resolveWindowOptions({ x: 40, y: 50, width: 1200, height: 800 }, displays);+ expect(opts.x).toBe(40);+ expect(opts.y).toBe(50);+ });++ it("clamps a one-pixel intersection fully inside the work area", () => {+ const opts = resolveWindowOptions(+ { x: 1919, y: 1079, width: 1200, height: 800 },+ displays,+ );+ expect(opts).toMatchObject({ x: 720, y: 280, width: 1200, height: 800 });+ });++ it("clamps position when restoring onto a smaller display", () => {+ const opts = resolveWindowOptions(+ { x: 500, y: 300, width: 900, height: 600 },+ [{ x: 0, y: 0, width: 1024, height: 768 }],+ );+ expect(opts).toMatchObject({ x: 124, y: 168, width: 900, height: 600 });+ });++ it("shrinks saved dimensions to fit the selected work area", () => {+ const opts = resolveWindowOptions(+ { x: 100, y: 100, width: 1600, height: 1000 },+ [{ x: 0, y: 0, width: 1024, height: 768 }],+ );+ expect(opts).toMatchObject({ x: 0, y: 0, width: 1024, height: 768 });+ });++ it("selects the work area with the largest intersection", () => {+ const opts = resolveWindowOptions(+ { x: 1800, y: 100, width: 1000, height: 800 },+ [+ { x: 0, y: 0, width: 1920, height: 1080 },+ { x: 1920, y: 0, width: 1280, height: 1024 },+ ],+ );+ expect(opts).toMatchObject({ x: 1920, y: 100, width: 1000, height: 800 });+ });++ it("omits coordinates when saved bounds are completely off-screen", () => {+ const opts = resolveWindowOptions(+ { x: 5000, y: 0, width: 1200, height: 800, isMaximized: true },+ displays,+ );+ expect(opts).toEqual({+ width: 1200,+ height: 800,+ isMaximized: true,+ isFullScreen: false,+ });+ });++ it("shrinks completely off-screen bounds to the primary work area", () => {+ const opts = resolveWindowOptions(+ { x: 5000, y: 0, width: 2000, height: 1200 },+ [{ x: 0, y: 0, width: 1440, height: 900 }],+ );+ // Size collapses onto the current work area; coordinates stay omitted so+ // Electron centers the window instead of restoring it off-screen.+ expect(opts).toEqual({+ width: 1440,+ height: 900,+ isMaximized: false,+ isFullScreen: false,+ });+ });++ it("clamps off-screen bounds to the supplied primary display, not just displays[0]", () => {+ const opts = resolveWindowOptions(+ { x: 9000, y: 9000, width: 2560, height: 1600 },+ [+ { x: 0, y: 0, width: 1920, height: 1080 },+ { x: 1920, y: 0, width: 1280, height: 800 },+ ],+ { x: 1920, y: 0, width: 1280, height: 800 },+ );+ expect(opts).toEqual({+ width: 1280,+ height: 800,+ isMaximized: false,+ isFullScreen: false,+ });+ });++ it("shrinks default dimensions when the work area is smaller than the default", () => {+ const opts = resolveWindowOptions({}, [{ x: 0, y: 0, width: 1024, height: 768 }]);+ expect(opts).toMatchObject({ width: 1024, height: 768 });+ });++ it("keeps saved size when no displays are reported", () => {+ const opts = resolveWindowOptions({ x: 0, y: 0, width: 1500, height: 950 }, []);+ expect(opts).toMatchObject({ width: 1500, height: 950 });+ });++ it("ignores degenerate work areas when picking the off-screen clamp target", () => {+ const opts = resolveWindowOptions(+ { x: 5000, y: 0, width: 2000, height: 1200 },+ [+ { x: 0, y: 0, width: 0, height: 0 },+ { x: 0, y: 0, width: 1366, height: 768 },+ ],+ );+ expect(opts).toMatchObject({ width: 1366, height: 768 });+ });++ it("restores maximized / fullscreen flags", () => {+ const opts = resolveWindowOptions({ isMaximized: true, isFullScreen: true }, displays);+ expect(opts.isMaximized).toBe(true);+ expect(opts.isFullScreen).toBe(true);+ });+});++describe("snapshotWindowState", () => {+ it("returns null for destroyed windows", () => {+ expect(+ snapshotWindowState({+ isDestroyed: () => true,+ getNormalBounds: () => ({ x: 0, y: 0, width: 1, height: 1 }),+ isMaximized: () => false,+ isFullScreen: () => false,+ }),+ ).toBeNull();+ });++ it("captures normal bounds and flags", () => {+ expect(+ snapshotWindowState({+ isDestroyed: () => false,+ getNormalBounds: () => ({ x: 12, y: 34, width: 1100, height: 720 }),+ isMaximized: () => true,+ isFullScreen: () => false,+ }),+ ).toEqual({+ x: 12,+ y: 34,+ width: 1100,+ height: 720,+ isMaximized: true,+ isFullScreen: false,+ });+ });+});++describe("windowStateFilePath", () => {+ it("joins userData with the canonical filename", () => {+ expect(windowStateFilePath("/tmp/user-data")).toBe(join("/tmp/user-data", WINDOW_STATE_FILENAME));+ });+});++// Sanity: write + re-parse via the real JSON format used on disk.+describe("end-to-end persistence shape", () => {+ it("serializes a snapshot the loader accepts", () => {+ const file = join(tempDir(), WINDOW_STATE_FILENAME);+ const snap = snapshotWindowState({+ isDestroyed: () => false,+ getNormalBounds: () => ({ x: 5, y: 6, width: 1300, height: 850 }),+ isMaximized: () => false,+ isFullScreen: () => true,+ });+ expect(snap).not.toBeNull();+ saveWindowStateToFile(file, snap!);+ const raw = readFileSync(file, "utf8");+ expect(JSON.parse(raw)).toEqual(snap);+ expect(loadWindowState(file)).toEqual(snap);+ });+});diff --git a/apps/desktop/src/main/window-state.ts b/apps/desktop/src/main/window-state.tsnew file mode 100644index 0000000000..ce358c58b1--- /dev/null+++ b/apps/desktop/src/main/window-state.ts@@ -0,0 +1,220 @@+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";++/** Persisted main-window geometry for the next launch (#5244). */+export type WindowState = {+ x?: number;+ y?: number;+ width?: number;+ height?: number;+ isMaximized?: boolean;+ isFullScreen?: boolean;+};++export type Rectangle = {+ x: number;+ y: number;+ width: number;+ height: number;+};++export type DisplayWorkArea = {+ x: number;+ y: number;+ width: number;+ height: number;+};++export const DEFAULT_WINDOW_WIDTH = 1280;+export const DEFAULT_WINDOW_HEIGHT = 800;+export const MIN_WINDOW_WIDTH = 900;+export const MIN_WINDOW_HEIGHT = 600;++export const WINDOW_STATE_FILENAME = "window-state.json";++export function windowStateFilePath(userDataPath: string): string {+ return join(userDataPath, WINDOW_STATE_FILENAME);+}++/**+ * Parse a previously saved window-state JSON blob. Returns `{}` on any+ * failure so a corrupt file never blocks app launch.+ */+export function parseWindowState(raw: string): WindowState {+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return {};+ }+ const obj = parsed as Record<string, unknown>;+ const out: WindowState = {};+ for (const key of ["x", "y", "width", "height"] as const) {+ const v = obj[key];+ if (typeof v === "number" && Number.isFinite(v)) {+ out[key] = Math.round(v);+ }+ }+ if (typeof obj.isMaximized === "boolean") out.isMaximized = obj.isMaximized;+ if (typeof obj.isFullScreen === "boolean") out.isFullScreen = obj.isFullScreen;+ return out;+ } catch {+ return {};+ }+}++export function loadWindowState(filePath: string): WindowState {+ try {+ return parseWindowState(readFileSync(filePath, "utf8"));+ } catch {+ return {};+ }+}++export function saveWindowStateToFile(filePath: string, state: WindowState): void {+ try {+ writeFileSync(filePath, JSON.stringify(state), "utf8");+ } catch {+ // Disk full / permissions — drop silently; next launch uses defaults.+ }+}++/**+ * True when the rectangle intersects at least one display work area.+ * Prevents restoring a window onto a disconnected external monitor.+ */+export function isVisibleOnSomeDisplay(+ bounds: { x?: number; y?: number; width?: number; height?: number },+ displays: DisplayWorkArea[],+): boolean {+ if (+ bounds.x == null ||+ bounds.y == null ||+ bounds.width == null ||+ bounds.height == null ||+ bounds.width <= 0 ||+ bounds.height <= 0+ ) {+ return false;+ }+ const b = {+ x: bounds.x,+ y: bounds.y,+ width: bounds.width,+ height: bounds.height,+ };+ return displays.some((wa) => rectanglesIntersect(b, wa));+}++export function rectanglesIntersect(a: Rectangle, b: Rectangle): boolean {+ return intersectionArea(a, b) > 0;+}++function intersectionArea(a: Rectangle, b: Rectangle): number {+ const width = Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x));+ const height = Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));+ return width * height;+}++function isUsableWorkArea(wa: DisplayWorkArea | undefined | null): wa is DisplayWorkArea {+ return wa != null && wa.width > 0 && wa.height > 0;+}++/**+ * Resolve persisted geometry against the connected display work areas.+ * Intersecting bounds are resized and repositioned to remain fully visible;+ * disconnected bounds keep their size and state flags but omit coordinates.+ *+ * Size is always clamped to the work area the window will actually land on.+ * When saved bounds intersect no display, Electron centers the window on the+ * primary display, so `primaryWorkArea` is the clamp target for that path.+ * It falls back to the first usable entry in `displays` when not supplied.+ */+export function resolveWindowOptions(+ saved: WindowState,+ displays: DisplayWorkArea[],+ primaryWorkArea?: DisplayWorkArea,+): {+ width: number;+ height: number;+ x?: number;+ y?: number;+ isMaximized: boolean;+ isFullScreen: boolean;+} {+ const width = Math.max(+ MIN_WINDOW_WIDTH,+ typeof saved.width === "number" && saved.width > 0 ? saved.width : DEFAULT_WINDOW_WIDTH,+ );+ const height = Math.max(+ MIN_WINDOW_HEIGHT,+ typeof saved.height === "number" && saved.height > 0 ? saved.height : DEFAULT_WINDOW_HEIGHT,+ );++ const savedBounds =+ saved.x != null &&+ saved.y != null &&+ saved.width != null &&+ saved.height != null &&+ saved.width > 0 &&+ saved.height > 0+ ? { x: saved.x, y: saved.y, width: saved.width, height: saved.height }+ : null;+ const workArea = savedBounds+ ? displays.reduce<DisplayWorkArea | null>((best, candidate) => {+ if (candidate.width <= 0 || candidate.height <= 0) return best;+ const candidateArea = intersectionArea(savedBounds, candidate);+ if (candidateArea === 0) return best;+ return !best || candidateArea > intersectionArea(savedBounds, best) ? candidate : best;+ }, null)+ : null;++ // Clamp size against the display the window lands on: the intersected one+ // when the saved bounds are still visible, otherwise the primary display+ // Electron will center on. Without this the off-screen and no-saved-state+ // paths could restore a window larger than the current work area (#5244).+ const clampTarget = workArea ?? [primaryWorkArea, ...displays].find(isUsableWorkArea) ?? null;++ const resolvedWidth = clampTarget ? Math.min(width, clampTarget.width) : width;+ const resolvedHeight = clampTarget ? Math.min(height, clampTarget.height) : height;+ return {+ width: resolvedWidth,+ height: resolvedHeight,+ ...(workArea && savedBounds+ ? {+ x: Math.min(+ Math.max(savedBounds.x, workArea.x),+ workArea.x + workArea.width - resolvedWidth,+ ),+ y: Math.min(+ Math.max(savedBounds.y, workArea.y),+ workArea.y + workArea.height - resolvedHeight,+ ),+ }+ : {}),+ isMaximized: saved.isMaximized === true,+ isFullScreen: saved.isFullScreen === true,+ };+}++/** Snapshot used when writing window-state.json from a live BrowserWindow. */+export function snapshotWindowState(win: {+ isDestroyed: () => boolean;+ getNormalBounds: () => Rectangle;+ isMaximized: () => boolean;+ isFullScreen: () => boolean;+}): WindowState | null {+ if (!win || win.isDestroyed()) return null;+ try {+ const bounds = win.getNormalBounds();+ return {+ x: bounds.x,+ y: bounds.y,+ width: bounds.width,+ height: bounds.height,+ isMaximized: win.isMaximized(),+ isFullScreen: win.isFullScreen(),+ };+ } catch {+ return null;+ }+}