Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix(desktop): preserve main window bounds (#3851)

Anirudh Coontoor2c199aacac32
diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts
index c5264332b..f8e059157 100644
--- a/apps/desktop/src/app/DesktopLifecycle.ts
+++ b/apps/desktop/src/app/DesktopLifecycle.ts
@@ -73,8 +73,14 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
}
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
- function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
+ function* (): Effect.fn.Return<
+ void,
+ never,
+ DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow
+ > {
const shutdown = yield* DesktopShutdown.DesktopShutdown;
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.flushMainWindowBounds;
yield* shutdown.request;
yield* shutdown.awaitComplete;
},
diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts
index 5e6a3f516..fa0811d5d 100644
--- a/apps/desktop/src/backend/DesktopBackendPool.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts
@@ -76,6 +76,7 @@ function makePoolLayer(
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
+ flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
diff --git a/apps/desktop/src/backend/DesktopServerExposure.test.ts b/apps/desktop/src/backend/DesktopServerExposure.test.ts
index 1a107c5c8..dcfee9377 100644
--- a/apps/desktop/src/backend/DesktopServerExposure.test.ts
+++ b/apps/desktop/src/backend/DesktopServerExposure.test.ts
@@ -250,6 +250,7 @@ describe("DesktopServerExposure", () => {
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
+ setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
setServerExposureMode: () => Effect.fail(settingsFailure),
setTailscaleServe: () => Effect.fail(settingsFailure),
setUpdateChannel: () => Effect.die("unexpected update channel change"),
diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts
index 70b267982..3878b0e36 100644
--- a/apps/desktop/src/settings/DesktopAppSettings.test.ts
+++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts
@@ -11,6 +11,17 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
+ mainWindowBounds: Schema.optionalKey(
+ Schema.NullOr(
+ Schema.Struct({
+ x: Schema.Number,
+ y: Schema.Number,
+ width: Schema.Number,
+ height: Schema.Number,
+ }),
+ ),
+ ),
+ mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])),
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
tailscaleServePort: Schema.optionalKey(Schema.Number),
@@ -91,6 +102,8 @@ describe("DesktopSettings", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
+ mainWindowBounds: null,
+ mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
@@ -116,6 +129,8 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
+ mainWindowBounds: null,
+ mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
@@ -215,10 +230,13 @@ describe("DesktopSettings", () => {
"serverExposureMode": "network-accessible",
"tailscaleServeEnabled": true,
"tailscaleServePort": 8443,
+ "mainWindowBounds": { "x": 120, "y": 80, "width": 1280, "height": 900 },
}\n`,
);
assert.deepEqual(yield* settings.load, {
+ mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
+ mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
@@ -232,6 +250,24 @@ describe("DesktopSettings", () => {
),
);
+ it.effect("rejects window bounds that do not satisfy the domain schema", () =>
+ withSettings(
+ Effect.gen(function* () {
+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
+ yield* writeSettingsPatch({
+ mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 },
+ mainWindowMaximized: true,
+ serverExposureMode: "network-accessible",
+ });
+
+ const loaded = yield* settings.load;
+ assert.isNull(loaded.mainWindowBounds);
+ assert.isFalse(loaded.mainWindowMaximized);
+ assert.equal(loaded.serverExposureMode, "network-accessible");
+ }),
+ ),
+ );
+
it.effect("persists sparse desktop settings documents", () =>
withSettings(
Effect.gen(function* () {
@@ -239,12 +275,15 @@ describe("DesktopSettings", () => {
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
+ yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true);
yield* settings.setServerExposureMode("network-accessible");
const persisted = yield* decodeDesktopSettingsPatch(
yield* fileSystem.readFileString(environment.desktopSettingsPath),
);
assert.deepEqual(persisted, {
+ mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 },
+ mainWindowMaximized: true,
serverExposureMode: "network-accessible",
} satisfies typeof DesktopSettingsPatch.Type);
}),
@@ -261,6 +300,8 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
+ mainWindowBounds: null,
+ mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
@@ -286,6 +327,8 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
+ mainWindowBounds: null,
+ mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
@@ -310,6 +353,8 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
+ mainWindowBounds: null,
+ mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 443,
diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts
index 6a26bf5a6..466c9a9b5 100644
--- a/apps/desktop/src/settings/DesktopAppSettings.ts
+++ b/apps/desktop/src/settings/DesktopAppSettings.ts
@@ -20,6 +20,8 @@ import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
+ readonly mainWindowBounds: DesktopWindowBounds | null;
+ readonly mainWindowMaximized: boolean;
readonly serverExposureMode: DesktopServerExposureMode;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
@@ -48,8 +50,25 @@ export interface DesktopSettingsChange {
}
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
+const MIN_MAIN_WINDOW_SIZE = {
+ width: 840,
+ height: 620,
+} as const;
+export const DesktopWindowBoundsSchema = Schema.Struct({
+ x: Schema.Int,
+ y: Schema.Int,
+ width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.width)),
+ height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_MAIN_WINDOW_SIZE.height)),
+});
+export type DesktopWindowBounds = typeof DesktopWindowBoundsSchema.Type;
+export const DEFAULT_MAIN_WINDOW_SIZE = {
+ width: 1100,
+ height: 780,
+} as const;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
+ mainWindowBounds: null,
+ mainWindowMaximized: false,
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
@@ -60,7 +79,16 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
wslOnly: false,
};
+const DesktopWindowBoundsDocument = Schema.Struct({
+ x: Schema.Number,
+ y: Schema.Number,
+ width: Schema.Number,
+ height: Schema.Number,
+});
+
const DesktopSettingsDocument = Schema.Struct({
+ mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
+ mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
tailscaleServePort: Schema.optionalKey(Schema.Number),
@@ -81,6 +109,8 @@ type Mutable<T> = { -readonly [K in keyof T]: T[K] };
const DesktopSettingsJson = fromLenientJson(DesktopSettingsDocument);
const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson);
const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson);
+const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema);
+const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema);
const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({
settings,
@@ -114,6 +144,10 @@ export class DesktopAppSettings extends Context.Service<
{
readonly load: Effect.Effect<DesktopSettings>;
readonly get: Effect.Effect<DesktopSettings>;
+ readonly setMainWindowBounds: (
+ bounds: DesktopWindowBounds,
+ isMaximized: boolean,
+ ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setServerExposureMode: (
mode: DesktopServerExposureMode,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
@@ -158,11 +192,16 @@ function normalizeWslDistro(value: unknown): string | null {
return typeof value === "string" && isValidDistroName(value) ? value : null;
}
+export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | null {
+ return Option.getOrNull(decodeDesktopWindowBounds(value));
+}
+
function normalizeDesktopSettingsDocument(
parsed: DesktopSettingsDocument,
appVersion: string,
): DesktopSettings {
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
+ const mainWindowBounds = normalizeMainWindowBounds(parsed.mainWindowBounds);
const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
const updateChannelConfiguredByUser =
@@ -177,6 +216,8 @@ function normalizeDesktopSettingsDocument(
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
+ mainWindowBounds,
+ mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
@@ -197,6 +238,12 @@ function toDesktopSettingsDocument(
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
+ if (settings.mainWindowBounds !== null) {
+ document.mainWindowBounds = settings.mainWindowBounds;
+ }
+ if (settings.mainWindowMaximized) {
+ document.mainWindowMaximized = true;
+ }
if (settings.serverExposureMode !== defaults.serverExposureMode) {
document.serverExposureMode = settings.serverExposureMode;
}
@@ -237,6 +284,22 @@ function setServerExposureMode(
};
}
+function setMainWindowBounds(
+ settings: DesktopSettings,
+ bounds: DesktopWindowBounds,
+ isMaximized: boolean,
+): DesktopSettings {
+ return settings.mainWindowBounds !== null &&
+ desktopWindowBoundsEquivalence(settings.mainWindowBounds, bounds) &&
+ settings.mainWindowMaximized === isMaximized
+ ? settings
+ : {
+ ...settings,
+ mainWindowBounds: bounds,
+ mainWindowMaximized: isMaximized,
+ };
+}
+
function setTailscaleServe(
settings: DesktopSettings,
input: { readonly enabled: boolean; readonly port: Option.Option<number> },
@@ -431,6 +494,18 @@ export const make = Effect.gen(function* () {
);
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
}).pipe(Effect.withSpan("desktop.settings.load")),
+ setMainWindowBounds: (bounds, isMaximized) =>
+ persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)).pipe(
+ Effect.withSpan("desktop.settings.setMainWindowBounds", {
+ attributes: {
+ x: bounds.x,
+ y: bounds.y,
+ width: bounds.width,
+ height: bounds.height,
+ isMaximized,
+ },
+ }),
+ ),
setServerExposureMode: (mode) =>
persist((settings) => setServerExposureMode(settings, mode)).pipe(
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
@@ -488,6 +563,8 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
return DesktopAppSettings.of({
get: SynchronizedRef.get(settingsRef),
load: SynchronizedRef.get(settingsRef),
+ setMainWindowBounds: (bounds, isMaximized) =>
+ update((settings) => setMainWindowBounds(settings, bounds, isMaximized)),
setServerExposureMode: (mode) =>
update((settings) => setServerExposureMode(settings, mode)),
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts
index 5ae92bbee..32224c7a5 100644
--- a/apps/desktop/src/updates/DesktopUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts
@@ -158,6 +158,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
+ setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
index ba77292fd..168846466 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
@@ -76,6 +76,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
+ flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index 492ef1ad5..587da8d44 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -1,12 +1,17 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
+import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
+import * as References from "effect/References";
+import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
-import type * as Electron from "electron";
+import * as Electron from "electron";
import { vi } from "vite-plus/test";
vi.mock("electron", async (importOriginal) => ({
@@ -18,12 +23,20 @@ vi.mock("electron", async (importOriginal) => ({
setUserAgent: vi.fn(),
})),
},
+ screen: {
+ getAllDisplays: vi.fn(() => [
+ {
+ bounds: { x: 0, y: 0, width: 1920, height: 1080 },
+ },
+ ]),
+ },
}));
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopState from "../app/DesktopState.ts";
+import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
@@ -66,15 +79,21 @@ function makeFakeBrowserWindow() {
const window = {
close: vi.fn(),
focus: vi.fn(),
+ getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
+ getNormalBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })),
isDestroyed: vi.fn(() => false),
isFullScreen: vi.fn(() => false),
+ isMaximized: vi.fn(() => false),
isMinimized: vi.fn(() => false),
isVisible: vi.fn(() => true),
loadURL: vi.fn(() => Promise.resolve()),
+ maximize: vi.fn(),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
windowListeners.set(eventName, listener);
}),
- once: vi.fn(),
+ once: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
+ windowListeners.set(eventName, listener);
+ }),
restore: vi.fn(),
setBackgroundColor: vi.fn(),
setAutoHideCursor: vi.fn(),
@@ -86,7 +105,14 @@ function makeFakeBrowserWindow() {
return {
window: window as unknown as Electron.BrowserWindow,
+ getBounds: window.getBounds,
+ getNormalBounds: window.getNormalBounds,
+ isDestroyed: window.isDestroyed,
+ isFullScreen: window.isFullScreen,
+ isMaximized: window.isMaximized,
+ isMinimized: window.isMinimized,
loadURL: window.loadURL,
+ maximize: window.maximize,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
send: webContents.send,
@@ -144,13 +170,57 @@ const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
),
);
+const desktopWindowBoundsEquivalence = Schema.toEquivalence(
+ DesktopAppSettings.DesktopWindowBoundsSchema,
+);
+
function makeTestLayer(input: {
readonly window: Electron.BrowserWindow;
readonly createCount: Ref.Ref<number>;
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
+ readonly desktopSettings?: DesktopAppSettings.DesktopSettings;
+ readonly mainWindowBoundsUpdates?: DesktopAppSettings.DesktopWindowBounds[];
+ readonly mainWindowMaximizedUpdates?: boolean[];
+ readonly beforeMainWindowBoundsUpdate?: (
+ bounds: DesktopAppSettings.DesktopWindowBounds,
+ ) => Effect.Effect<void>;
readonly openedExternalUrls?: unknown[];
}) {
+ let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
+ const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
+ get: Effect.sync(() => desktopSettings),
+ load: Effect.sync(() => desktopSettings),
+ setMainWindowBounds: (bounds, isMaximized) =>
+ Effect.gen(function* () {
+ if (input.beforeMainWindowBoundsUpdate) {
+ yield* input.beforeMainWindowBoundsUpdate(bounds);
+ }
+ const changed =
+ desktopSettings.mainWindowBounds === null ||
+ !desktopWindowBoundsEquivalence(desktopSettings.mainWindowBounds, bounds) ||
+ desktopSettings.mainWindowMaximized !== isMaximized;
+ if (changed) {
+ desktopSettings = {
+ ...desktopSettings,
+ mainWindowBounds: bounds,
+ mainWindowMaximized: isMaximized,
+ };
+ input.mainWindowBoundsUpdates?.push(bounds);
+ input.mainWindowMaximizedUpdates?.push(isMaximized);
+ }
+ return { settings: desktopSettings, changed };
+ }),
+ setServerExposureMode: () => Effect.die("unexpected server exposure update"),
+ setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
+ setUpdateChannel: () => Effect.die("unexpected update channel change"),
+ setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
+ setWslDistro: () => Effect.die("unexpected WSL distro change"),
+ setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
+ applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
+ applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
+ } satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
+
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: (options) =>
Effect.sync(() => {
@@ -175,6 +245,7 @@ function makeTestLayer(input: {
Layer.mergeAll(
desktopAssetsLayer,
desktopEnvironmentLayer,
+ desktopAppSettingsLayer,
desktopServerExposureLayer,
DesktopState.layer,
electronMenuLayer,
@@ -272,6 +343,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
Layer.mergeAll(
desktopAssetsLayer,
desktopEnvironmentLayer,
+ DesktopAppSettings.layerTest(),
desktopServerExposureLayer,
electronMenuLayer,
Layer.succeed(ElectronShell.ElectronShell, {
@@ -294,6 +366,23 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
});
describe("DesktopWindow", () => {
+ it("restores bounds only when the window fits within a connected display", () => {
+ const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
+ const displays = [
+ { x: 0, y: 0, width: 1920, height: 1080 },
+ { x: 1920, y: 0, width: 2560, height: 1440 },
+ ];
+
+ assert.deepEqual(
+ DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, displays),
+ persistedBounds,
+ );
+ assert.deepEqual(
+ DesktopWindow.resolveInitialMainWindowBounds(persistedBounds, [displays[0]!]),
+ DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE,
+ );
+ });
+
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
@@ -335,6 +424,10 @@ describe("DesktopWindow", () => {
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
assert.equal(yield* Ref.get(createCount), 1);
+ assert.equal(createdWindowOptions[0]?.width, 1100);
+ assert.equal(createdWindowOptions[0]?.height, 780);
+ assert.isUndefined(createdWindowOptions[0]?.x);
+ assert.isUndefined(createdWindowOptions[0]?.y);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
@@ -343,6 +436,427 @@ describe("DesktopWindow", () => {
}),
);
+ it.effect("uses the persisted main window bounds when opening the window", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ createdWindowOptions,
+ desktopSettings: {
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
+ },
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ assert.equal(createdWindowOptions[0]?.width, 1320);
+ assert.equal(createdWindowOptions[0]?.height, 880);
+ assert.equal(createdWindowOptions[0]?.x, 120);
+ assert.equal(createdWindowOptions[0]?.y, 80);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("restores the persisted maximized state", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ desktopSettings: {
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
+ mainWindowMaximized: true,
+ },
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ assert.equal(fakeWindow.maximize.mock.calls.length, 0);
+ const readyToShow = fakeWindow.windowListeners.get("ready-to-show");
+ if (!readyToShow) {
+ return yield* Effect.die("window ready-to-show listener was not registered");
+ }
+ readyToShow();
+ assert.equal(fakeWindow.maximize.mock.calls.length, 1);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("debounces move and resize bounds updates", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const move = fakeWindow.windowListeners.get("move");
+ const resize = fakeWindow.windowListeners.get("resize");
+ if (!move || !resize) {
+ return yield* Effect.die("window bounds listeners were not registered");
+ }
+
+ fakeWindow.getBounds.mockReturnValue({ x: 120, y: 80, width: 1280, height: 840 });
+ move();
+ yield* TestClock.adjust(250);
+
+ fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
+ resize();
+ yield* TestClock.adjust(499);
+ assert.deepEqual(mainWindowBoundsUpdates, []);
+
+ yield* TestClock.adjust(1);
+ yield* Effect.promise(() => Promise.resolve());
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("persists normal bounds and state for a maximized window", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ fakeWindow.isMaximized.mockReturnValue(true);
+ fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
+ fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const mainWindowMaximizedUpdates: boolean[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ mainWindowMaximizedUpdates,
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const close = fakeWindow.windowListeners.get("close");
+ if (!close) {
+ return yield* Effect.die("window close listener was not registered");
+ }
+ close();
+ yield* Effect.promise(() => Promise.resolve());
+
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
+ assert.deepEqual(mainWindowMaximizedUpdates, [true]);
+ assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
+ assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("persists normal bounds and state from the native maximize event", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const mainWindowMaximizedUpdates: boolean[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ mainWindowMaximizedUpdates,
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const maximize = fakeWindow.windowListeners.get("maximize");
+ if (!maximize) {
+ return yield* Effect.die("window maximize listener was not registered");
+ }
+
+ fakeWindow.isMaximized.mockReturnValue(true);
+ fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
+ fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 });
+ maximize();
+ yield* TestClock.adjust(500);
+ yield* Effect.promise(() => Promise.resolve());
+
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]);
+ assert.deepEqual(mainWindowMaximizedUpdates, [true]);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("does not persist bounds that fail the domain schema", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const resize = fakeWindow.windowListeners.get("resize");
+ if (!resize) {
+ return yield* Effect.die("window resize listener was not registered");
+ }
+ resize();
+ yield* TestClock.adjust(500);
+ yield* Effect.promise(() => Promise.resolve());
+
+ assert.deepEqual(mainWindowBoundsUpdates, []);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("preserves unrestorable bounds until the user changes the window", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ desktopSettings: {
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 },
+ },
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const close = fakeWindow.windowListeners.get("close");
+ const move = fakeWindow.windowListeners.get("move");
+ if (!close || !move) {
+ return yield* Effect.die("window lifecycle listeners were not registered");
+ }
+
+ close();
+ yield* Effect.promise(() => Promise.resolve());
+ assert.deepEqual(mainWindowBoundsUpdates, []);
+
+ fakeWindow.getBounds.mockReturnValue({ x: 80, y: 60, width: 1280, height: 840 });
+ move();
+ yield* TestClock.adjust(500);
+ yield* Effect.promise(() => Promise.resolve());
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 80, y: 60, width: 1280, height: 840 }]);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("flushes normal bounds when fullscreen before the debounce completes", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 });
+ fakeWindow.getNormalBounds.mockReturnValue({ x: 200, y: 130, width: 1400, height: 940 });
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const resize = fakeWindow.windowListeners.get("resize");
+ if (!resize) {
+ return yield* Effect.die("window resize listener was not registered");
+ }
+ resize();
+ yield* TestClock.adjust(250);
+ fakeWindow.isFullScreen.mockReturnValue(true);
+
+ yield* desktopWindow.flushMainWindowBounds;
+
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 200, y: 130, width: 1400, height: 940 }]);
+ assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
+ assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("flushes normal bounds when minimized before the debounce completes", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 });
+ fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 });
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const resize = fakeWindow.windowListeners.get("resize");
+ if (!resize) {
+ return yield* Effect.die("window resize listener was not registered");
+ }
+ resize();
+ yield* TestClock.adjust(250);
+ fakeWindow.isMinimized.mockReturnValue(true);
+
+ yield* desktopWindow.flushMainWindowBounds;
+
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]);
+ assert.equal(fakeWindow.getBounds.mock.calls.length, 0);
+ assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
+ it.effect("logs display lookup failures before falling back to the default size", () =>
+ Effect.gen(function* () {
+ const displayLookupFailure = new Error("screen API unavailable");
+ vi.mocked(Electron.screen.getAllDisplays).mockImplementationOnce(() => {
+ throw displayLookupFailure;
+ });
+ const logRecords: Array<{
+ readonly message: unknown;
+ readonly annotations: Readonly<Record<string, unknown>>;
+ }> = [];
+ const logger = Logger.make(({ fiber, message }) => {
+ logRecords.push({
+ message,
+ annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
+ });
+ });
+ const fakeWindow = makeFakeBrowserWindow();
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ createdWindowOptions,
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+ }).pipe(
+ Effect.provide(Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false }))),
+ );
+
+ const warning = logRecords.find(
+ (record) =>
+ Array.isArray(record.message) &&
+ record.message[0] === "failed to read connected displays; using defaults",
+ );
+ assert.isDefined(warning);
+ assert.strictEqual(warning.annotations.cause, displayLookupFailure);
+ assert.equal(createdWindowOptions[0]?.width, 1100);
+ assert.equal(createdWindowOptions[0]?.height, 780);
+ assert.isUndefined(createdWindowOptions[0]?.x);
+ assert.isUndefined(createdWindowOptions[0]?.y);
+ }),
+ );
+
+ it.effect("persists the current main window bounds before the window closes", () =>
+ Effect.gen(function* () {
+ const fakeWindow = makeFakeBrowserWindow();
+ fakeWindow.getBounds.mockReturnValue({ x: 240, y: 160, width: 1410, height: 930 });
+ const createCount = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
+ const writeStarted = yield* Deferred.make<void>();
+ const allowWrite = yield* Deferred.make<void>();
+ const flushCompleted = yield* Deferred.make<void>();
+ const layer = makeTestLayer({
+ window: fakeWindow.window,
+ createCount,
+ mainWindow,
+ mainWindowBoundsUpdates,
+ beforeMainWindowBoundsUpdate: () =>
+ Deferred.succeed(writeStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(allowWrite)),
+ Effect.asVoid,
+ ),
+ });
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
+
+ const close = fakeWindow.windowListeners.get("close");
+ if (!close) {
+ return yield* Effect.die("window close listener was not registered");
+ }
+ close();
+ yield* Deferred.await(writeStarted);
+ fakeWindow.isDestroyed.mockReturnValue(true);
+
+ const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe(
+ Effect.andThen(Deferred.succeed(flushCompleted, undefined)),
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* Effect.yieldNow;
+ assert.isFalse(yield* Deferred.isDone(flushCompleted));
+
+ yield* Deferred.succeed(allowWrite, undefined);
+ yield* Fiber.join(flushFiber);
+ assert.isTrue(yield* Deferred.isDone(flushCompleted));
+
+ assert.deepEqual(mainWindowBoundsUpdates, [
+ {
+ x: 240,
+ y: 160,
+ width: 1410,
+ height: 930,
+ },
+ ]);
+ }).pipe(Effect.provide(layer));
+ }),
+ );
+
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index c808c77e5..db4b69843 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
-import type * as Electron from "electron";
+import * as Electron from "electron";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -17,11 +17,13 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
+import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
+const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
@@ -41,6 +43,7 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
+ | DesktopAppSettings.DesktopAppSettings
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
@@ -75,6 +78,7 @@ export class DesktopWindow extends Context.Service<
// window so a "macOS dock click" while the backend is down doesn't
// produce a stranded window pointing at nothing.
readonly handleBackendNotReady: Effect.Effect<void>;
+ readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
@@ -99,6 +103,45 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
}
+type DisplayBounds = Pick<Electron.Rectangle, "x" | "y" | "width" | "height">;
+
+function windowFitsWithinDisplay(
+ windowBounds: DesktopAppSettings.DesktopWindowBounds,
+ displayBounds: DisplayBounds,
+): boolean {
+ return (
+ windowBounds.x >= displayBounds.x &&
+ windowBounds.y >= displayBounds.y &&
+ windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width &&
+ windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height
+ );
+}
+
+function windowBoundsEqual(
+ left: DesktopAppSettings.DesktopWindowBounds,
+ right: DesktopAppSettings.DesktopWindowBounds,
+): boolean {
+ return (
+ left.x === right.x &&
+ left.y === right.y &&
+ left.width === right.width &&
+ left.height === right.height
+ );
+}
+
+export function resolveInitialMainWindowBounds(
+ persistedBounds: DesktopAppSettings.DesktopWindowBounds | null,
+ displays: readonly DisplayBounds[],
+): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE {
+ if (
+ persistedBounds !== null &&
+ displays.some((display) => windowFitsWithinDisplay(persistedBounds, display))
+ ) {
+ return persistedBounds;
+ }
+ return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
+}
+
// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
@@ -202,6 +245,7 @@ export const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
+ const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
// Window-side latch for the primary backend's readiness. Set by
// handleBackendReady (driven by the pool's onReady callback), cleared
// by handleBackendNotReady (driven by onShutdown). Only consumed by
@@ -214,6 +258,7 @@ export const make = Effect.gen(function* () {
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runFork = Effect.runForkWith(context);
const runPromise = Effect.runPromiseWith(context);
+ let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
const dismissConnectingSplash = Effect.gen(function* () {
const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
@@ -250,9 +295,31 @@ export const make = Effect.gen(function* () {
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths, environment.platform);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
+ const persistedSettings = yield* desktopSettings.get;
+ const persistedBounds = persistedSettings.mainWindowBounds;
+ const displayBoundsResult = yield* Effect.sync(() => {
+ try {
+ return {
+ _tag: "Success" as const,
+ bounds: Electron.screen.getAllDisplays().map((display) => display.bounds),
+ };
+ } catch (cause) {
+ return { _tag: "Failure" as const, cause };
+ }
+ });
+ const displayBounds =
+ displayBoundsResult._tag === "Success"
+ ? displayBoundsResult.bounds
+ : yield* logWindowWarning("failed to read connected displays; using defaults", {
+ cause: displayBoundsResult.cause,
+ }).pipe(Effect.as<readonly Electron.Rectangle[]>([]));
+ const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds);
+ const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds;
+ if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
+ yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
+ }
const window = yield* electronWindow.create({
- width: 1100,
- height: 780,
+ ...initialBounds,
minWidth: 840,
minHeight: 620,
show: false,
@@ -274,6 +341,92 @@ export const make = Effect.gen(function* () {
if (environment.platform === "darwin") {
window.setAutoHideCursor(false);
}
+ let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
+ let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
+ let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
+ const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => {
+ if (window.isDestroyed()) {
+ return null;
+ }
+ const bounds =
+ window.isFullScreen() || window.isMaximized() || window.isMinimized()
+ ? window.getNormalBounds()
+ : window.getBounds();
+ return DesktopAppSettings.normalizeMainWindowBounds({
+ x: Math.round(bounds.x),
+ y: Math.round(bounds.y),
+ width: Math.round(bounds.width),
+ height: Math.round(bounds.height),
+ });
+ };
+ const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds();
+ const fallbackWindowMaximized = persistedSettings.mainWindowMaximized;
+ const persistCurrentBounds = (): Fiber.Fiber<void, never> | undefined => {
+ if (!boundsPersistenceEnabled) {
+ return pendingBoundsPersistFiber;
+ }
+ const bounds = readPersistableBounds();
+ if (bounds === null) {
+ return pendingBoundsPersistFiber;
+ }
+ pendingBoundsPersistFiber = runFork(
+ desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe(
+ Effect.asVoid,
+ Effect.catch((error) =>
+ logWindowWarning("failed to persist main window bounds", {
+ message: error.message,
+ }),
+ ),
+ ),
+ );
+ return pendingBoundsPersistFiber;
+ };
+ const scheduleBoundsPersist = () => {
+ if (!boundsPersistenceEnabled) {
+ const currentBounds = readPersistableBounds();
+ if (
+ currentBounds === null ||
+ (fallbackWindowBounds !== null &&
+ windowBoundsEqual(currentBounds, fallbackWindowBounds) &&
+ window.isMaximized() === fallbackWindowMaximized)
+ ) {
+ return;
+ }
+ }
+ boundsPersistenceEnabled = true;
+ if (boundsPersistFiber !== undefined) {
+ const fiber = boundsPersistFiber;
+ boundsPersistFiber = undefined;
+ runFork(Fiber.interrupt(fiber));
+ }
+ boundsPersistFiber = runFork(
+ Effect.sleep(MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS).pipe(
+ Effect.andThen(
+ Effect.sync(() => {
+ boundsPersistFiber = undefined;
+ void persistCurrentBounds();
+ }),
+ ),
+ ),
+ );
+ };
+ const clearBoundsPersist = () => {
+ if (boundsPersistFiber === undefined) {
+ return;
+ }
+ const fiber = boundsPersistFiber;
+ boundsPersistFiber = undefined;
+ runFork(Fiber.interrupt(fiber));
+ };
+ const flushBoundsPersist = Effect.sync(() => {
+ clearBoundsPersist();
+ return persistCurrentBounds();
+ }).pipe(
+ Effect.flatMap((fiber) =>
+ fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid),
+ ),
+ );
+ flushMainWindowBounds = flushBoundsPersist;
yield* previewManager.setMainWindow(window);
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
@@ -364,6 +517,13 @@ export const make = Effect.gen(function* () {
event.preventDefault();
window.setTitle(environment.displayName);
});
+ window.on("resize", scheduleBoundsPersist);
+ window.on("move", scheduleBoundsPersist);
+ window.on("maximize", scheduleBoundsPersist);
+ window.on("unmaximize", scheduleBoundsPersist);
+ window.on("close", () => {
+ runFork(flushBoundsPersist);
+ });
if (environment.platform === "darwin") {
window.on("enter-full-screen", () => {
@@ -472,6 +632,9 @@ export const make = Effect.gen(function* () {
bindFirstRevealTrigger(revealSubscribers, () => {
// Reveal the real window, then close the connecting splash (if any) so the
// two don't overlap and there's no blank gap between them.
+ if (persistedSettings.mainWindowMaximized) {
+ window.maximize();
+ }
void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
});
@@ -482,6 +645,7 @@ export const make = Effect.gen(function* () {
window.on("closed", () => {
clearDevelopmentLoadRetry();
+ clearBoundsPersist();
void runPromise(electronWindow.clearMain(Option.some(window)));
});
@@ -598,6 +762,9 @@ export const make = Effect.gen(function* () {
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
Effect.withSpan("desktop.window.handleBackendNotReady"),
),
+ flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe(
+ Effect.withSpan("desktop.window.flushMainWindowBounds"),
+ ),
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
yield* Effect.annotateCurrentSpan({ action });
const existingWindow = yield* focusedMainWindow;
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx
index ee56858bc..6c692dc3d 100644
--- a/apps/web/src/components/AppSidebarLayout.tsx
+++ b/apps/web/src/components/AppSidebarLayout.tsx
@@ -1,13 +1,22 @@
import { useAtomValue } from "@effect/atom-react";
+import * as Schema from "effect/Schema";
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
+import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import ThreadSidebar from "./Sidebar";
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
+import {
+ resolveInitialThreadSidebarWidth,
+ resolveThreadSidebarMaximumWidth,
+ THREAD_MAIN_CONTENT_MIN_WIDTH,
+ THREAD_SIDEBAR_MIN_WIDTH,
+ THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
+} from "./threadSidebarWidth";
import {
Sidebar,
SidebarProvider,
@@ -18,11 +27,20 @@ import {
} from "./ui/sidebar";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
-const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
-const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
-const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
+function readInitialThreadSidebarWidth(): number {
+ try {
+ return resolveInitialThreadSidebarWidth(
+ getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
+ window.innerWidth,
+ );
+ } catch (error) {
+ console.error("Could not read persisted thread sidebar width.", error);
+ return resolveInitialThreadSidebarWidth(null, window.innerWidth);
+ }
+}
+
function SidebarControl() {
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const { toggleSidebar } = useSidebar();
@@ -82,16 +100,20 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const pathname = useLocation({ select: (location) => location.pathname });
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
+ const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
+ const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(window.innerWidth);
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
return isMacosDesktop && typeof getWindowFullscreenState === "function"
? getWindowFullscreenState()
: false;
});
- const macosWindowControlsStyle =
- isMacosDesktop && !isWindowFullscreen
- ? ({ "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } as CSSProperties)
- : undefined;
+ const sidebarProviderStyle = {
+ "--sidebar-width": `${sidebarWidth}px`,
+ ...(isMacosDesktop && !isWindowFullscreen
+ ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
+ : {}),
+ } as CSSProperties;
useEffect(() => {
if (!isMacosDesktop) return;
@@ -131,17 +153,19 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
}, [navigate, pathname]);
return (
- <SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={macosWindowControlsStyle}>
+ <SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={sidebarProviderStyle}>
<Sidebar
side="left"
collapsible="offcanvas"
className="border-r border-border bg-card text-foreground"
resizable={{
+ maxWidth: sidebarMaximumWidth,
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
nextWidth <= currentWidth ||
wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
+ onResize: setSidebarWidth,
}}
>
<ThreadSidebar />
diff --git a/apps/web/src/components/threadSidebarWidth.test.ts b/apps/web/src/components/threadSidebarWidth.test.ts
new file mode 100644
index 000000000..12aef63bd
--- /dev/null
+++ b/apps/web/src/components/threadSidebarWidth.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ resolveInitialThreadSidebarWidth,
+ THREAD_MAIN_CONTENT_MIN_WIDTH,
+ THREAD_SIDEBAR_DEFAULT_WIDTH,
+ THREAD_SIDEBAR_MIN_WIDTH,
+} from "./threadSidebarWidth";
+
+describe("thread sidebar width", () => {
+ it("uses the default width when no preference is stored", () => {
+ expect(resolveInitialThreadSidebarWidth(null, 1200)).toBe(THREAD_SIDEBAR_DEFAULT_WIDTH);
+ });
+
+ it("uses a stored width in the initial render", () => {
+ expect(resolveInitialThreadSidebarWidth(360, 1200)).toBe(360);
+ });
+
+ it("clamps a stored width to the sidebar minimum", () => {
+ expect(resolveInitialThreadSidebarWidth(120, 1200)).toBe(THREAD_SIDEBAR_MIN_WIDTH);
+ });
+
+ it("leaves enough room for the main content on a smaller window", () => {
+ const viewportWidth = 1000;
+
+ expect(resolveInitialThreadSidebarWidth(900, viewportWidth)).toBe(
+ viewportWidth - THREAD_MAIN_CONTENT_MIN_WIDTH,
+ );
+ });
+
+ it("keeps the sidebar minimum when the whole layout is narrower than its minimums", () => {
+ expect(resolveInitialThreadSidebarWidth(900, 700)).toBe(THREAD_SIDEBAR_MIN_WIDTH);
+ });
+});
diff --git a/apps/web/src/components/threadSidebarWidth.ts b/apps/web/src/components/threadSidebarWidth.ts
new file mode 100644
index 000000000..93dd196e8
--- /dev/null
+++ b/apps/web/src/components/threadSidebarWidth.ts
@@ -0,0 +1,22 @@
+export const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
+export const THREAD_SIDEBAR_DEFAULT_WIDTH = 16 * 16;
+export const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
+export const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
+
+export function resolveThreadSidebarMaximumWidth(viewportWidth: number): number {
+ return Math.max(
+ THREAD_SIDEBAR_MIN_WIDTH,
+ Math.floor(viewportWidth) - THREAD_MAIN_CONTENT_MIN_WIDTH,
+ );
+}
+
+export function resolveInitialThreadSidebarWidth(
+ storedWidth: number | null,
+ viewportWidth: number,
+): number {
+ const preferredWidth =
+ storedWidth === null
+ ? THREAD_SIDEBAR_DEFAULT_WIDTH
+ : Math.max(THREAD_SIDEBAR_MIN_WIDTH, storedWidth);
+ return Math.min(preferredWidth, resolveThreadSidebarMaximumWidth(viewportWidth));
+}
diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx
index 50fb652a4..51335d1a6 100644
--- a/apps/web/src/components/ui/sidebar.tsx
+++ b/apps/web/src/components/ui/sidebar.tsx
@@ -555,16 +555,24 @@ function SidebarRail({
[onClick, open, resolvedResizable, toggleSidebar],
);
- React.useEffect(() => {
+ React.useLayoutEffect(() => {
if (!resolvedResizable?.storageKey || typeof window === "undefined") return;
const rail = railRef.current;
if (!rail) return;
const wrapper = rail.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
if (!wrapper) return;
- const storedWidth = getLocalStorageItem(resolvedResizable.storageKey, Schema.Finite);
+ let storedWidth: number | null;
+ try {
+ storedWidth = getLocalStorageItem(resolvedResizable.storageKey, Schema.Finite);
+ } catch (error) {
+ console.error("Could not restore persisted sidebar width.", error);
+ return;
+ }
if (storedWidth === null) return;
const clampedWidth = clampSidebarWidth(storedWidth, resolvedResizable);
+ // Hydrate the CSS variable before the browser paints so a restored sidebar
+ // never flashes at the default width first.
wrapper.style.setProperty("--sidebar-width", `${clampedWidth}px`);
resolvedResizable.onResize?.(clampedWidth);
}, [resolvedResizable]);