The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 01:45 UTC
fix(desktop): stop window setup once the app starts quitting (#18380)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Alex Southwell committed
Oct 20, 2026 at 07:24 UTC
6846cb8cc01b37f41fb8cf920c01338e72aa670b
4 files changed
+258
-12
apps/desktop/src/preview/Manager.test.ts
+71
@@ -2791,6 +2791,77 @@ describe("PreviewManager", () => {
2791
),
2792
);
2793
2794
+ effectIt.effect("keeps frame capture closed when a replacement is destroyed during cleanup", () =>
2795
+ withManager((manager) =>
2796
+ Effect.gen(function* () {
2797
+ const windowEvents = new Map<string, () => void>();
2798
+ const host = makeTestHostWebContents();
2799
+ const capturePage = vi.fn(async () => ({
2800
+ toJPEG: () => Buffer.from("recording-frame"),
2801
+ getSize: () => ({ width: 1280, height: 720 }),
2802
+ }));
2803
+ const guest = makeTestPreviewWebContents(capturePage, 42, host);
2804
+ fromId.mockReturnValue(guest);
2805
+ yield* manager.createTab("tab_shutdown");
2806
+ yield* manager.registerWebview("tab_shutdown", 42);
2807
+ yield* manager.setMainWindow({
2808
+ isDestroyed: () => false,
2809
+ once: (event: string, listener: () => void) => windowEvents.set(event, listener),
2810
+ webContents: { setBackgroundThrottling: vi.fn() },
2811
+ } as never);
2812
+ yield* manager.startRecording("tab_shutdown");
2813
+ const pip = makeTestPictureInPictureWindow();
2814
+ browserWindowConstructor.mockImplementation(function () {
2815
+ return pip.pictureInPictureWindow;
2816
+ });
2817
+ yield* manager.openPictureInPicture("tab_shutdown");
2818
+ const capturesBeforeClose = capturePage.mock.calls.length;
2819
+ const cleanupStarted = yield* Deferred.make<void>();
2820
+ const releaseCleanup = yield* Deferred.make<void>();
2821
+ yield* manager.subscribeStateChanges((_tabId, state) =>
2822
+ state.pictureInPicture
2823
+ ? Effect.void
2824
+ : Deferred.succeed(cleanupStarted, undefined).pipe(
2825
+ Effect.andThen(Deferred.await(releaseCleanup)),
2826
+ ),
2827
+ );
2828
+
2829
+ windowEvents.get("closed")!();
2830
+ yield* Deferred.await(cleanupStarted);
2831
+ let destroyed = false;
2832
+ const replacement = yield* manager
2833
+ .setMainWindow({
2834
+ isDestroyed: () => destroyed,
2835
+ once: vi.fn(),
2836
+ webContents: { setBackgroundThrottling: vi.fn() },
2837
+ } as never)
2838
+ .pipe(Effect.forkChild({ startImmediately: true }));
2839
+ try {
2840
+ expect(replacement.pollUnsafe()).toBeUndefined();
2841
+ destroyed = true;
2842
+ } finally {
2843
+ yield* Deferred.succeed(releaseCleanup, undefined);
2844
+ }
2845
+ yield* Fiber.join(replacement);
2846
+
2847
+ const restart = yield* Effect.exit(manager.startRecording("tab_shutdown"));
2848
+ expect(Exit.isFailure(restart)).toBe(true);
2849
+ if (Exit.isFailure(restart)) {
2850
+ expect(Option.getOrThrow(Cause.findErrorOption(restart.cause))).toMatchObject({
2851
+ _tag: "PreviewMainWindowClosedError",
2852
+ tabId: "tab_shutdown",
2853
+ });
2854
+ }
2855
+ expect(capturePage).toHaveBeenCalledTimes(capturesBeforeClose);
2856
+ expect(pip.pictureInPictureWindow.isDestroyed()).toBe(true);
2857
+ expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2858
+ const grants: Array<{ video?: unknown }> = [];
2859
+ host.displayMediaHandler()?.({ frame: host.mainFrame }, (value) => grants.push(value));
2860
+ expect(grants).toEqual([{}]);
2861
+ }),
2862
+ ),
2863
+ );
2864
+
2865
effectIt.effect("ignores close events from replaced main windows", () =>
2866
withManager((manager) =>
2867
Effect.gen(function* () {
apps/desktop/src/preview/Manager.ts
+2
@@ -1664,6 +1664,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
1664
}
1665
yield* SynchronizedRef.modifyEffect(frameCaptureSessionsRef, (sessions) =>
1666
Effect.gen(function* () {
1667
+ // Cleanup or lock acquisition can outlive the replacement window.
1668
+ if (window.isDestroyed()) return [undefined, sessions] as const;
1669
if (sessions.size > 0) {
1670
yield* setWindowBackgroundThrottling(window, false);
1671
}
apps/desktop/src/window/DesktopWindow.test.ts
+143
-2
@@ -3,6 +3,7 @@ import { assert, describe, it } from "@effect/vitest";
3
import * as Deferred from "effect/Deferred";
4
import { DesktopSnapShotId } from "@t3tools/contracts";
5
import * as Effect from "effect/Effect";
6
+import * as Exit from "effect/Exit";
7
import * as Fiber from "effect/Fiber";
8
import * as Layer from "effect/Layer";
9
import * as Logger from "effect/Logger";
@@ -227,6 +228,9 @@ function layerTest(input: {
228
readonly beforeMainWindowBoundsUpdate?: (
229
bounds: DesktopAppSettings.DesktopWindowBounds,
230
) => Effect.Effect<void>;
231
+ readonly setPreviewMainWindow?: (window: Electron.BrowserWindow) => Effect.Effect<void>;
232
+ readonly destroyAll?: Effect.Effect<void>;
233
+ readonly onWindowCreate?: Effect.Effect<void>;
234
readonly openedExternalUrls?: unknown[];
235
readonly copiedTexts?: string[];
236
readonly onPopupTemplate?: (input: ElectronMenu.ElectronMenuTemplateInput) => Effect.Effect<void>;
@@ -275,6 +279,7 @@ function layerTest(input: {
279
input.createdWindowOptions?.push(options);
280
}).pipe(
281
Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
282
+ Effect.andThen(input.onWindowCreate ?? Effect.void),
283
Effect.as(input.window),
284
),
285
main: Ref.get(input.mainWindow),
@@ -288,7 +293,7 @@ function layerTest(input: {
293
prepareReveal: () => Effect.succeed(false),
294
reveal: (window) => Effect.sync(() => input.onReveal?.(window)),
295
sendAll: () => Effect.void,
291
- destroyAll: Effect.void,
296
+ destroyAll: input.destroyAll ?? Effect.void,
297
syncAllAppearance: (sync) => sync(input.window),
298
} satisfies ElectronWindow.ElectronWindow["Service"]);
299
@@ -333,7 +338,7 @@ function layerTest(input: {
338
}),
339
Layer.mock(PreviewManager.PreviewManager)({
340
getBrowserSession: () => Effect.succeed({} as Electron.Session),
336
- setMainWindow: () => Effect.void,
341
+ setMainWindow: input.setPreviewMainWindow ?? (() => Effect.void),
342
prepareWebview: () => Effect.void,
343
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
344
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
@@ -344,6 +349,7 @@ function layerTest(input: {
349
}),
350
),
351
),
352
+ Layer.merge(DesktopState.layer),
353
);
354
}
355
@@ -425,6 +431,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
431
DesktopAppSettings.layerTest(),
432
layerDesktopClientSettings,
433
layerDesktopServerExposure,
434
+ DesktopState.layer,
435
layerElectronApp,
436
layerElectronMenu,
437
Layer.succeed(ElectronShell.ElectronShell, {
@@ -924,6 +931,140 @@ describe("DesktopWindow", () => {
931
}),
932
);
933
934
+ it.effect("does not open main or splash windows once quitting has started", () =>
935
+ Effect.gen(function* () {
936
+ const fake = makeFakeBrowserWindow();
937
+ const createCount = yield* Ref.make(0);
938
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
939
+ yield* Effect.gen(function* () {
940
+ const windows = yield* DesktopWindow.DesktopWindow;
941
+ const state = yield* DesktopState.DesktopState;
942
+ yield* Ref.set(state.quitting, true);
943
+
944
+ yield* windows.showConnectingSplash;
945
+ yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773"));
946
+ yield* windows.activate;
947
+ yield* windows.dispatchMenuAction("open-settings");
948
+ for (const creation of [
949
+ windows.createMain,
950
+ windows.ensureMain,
951
+ windows.revealOrCreateMain,
952
+ ]) {
953
+ assert.isTrue(Exit.isFailure(yield* Effect.exit(creation)));
954
+ }
955
+
956
+ assert.equal(yield* Ref.get(createCount), 0);
957
+ assert.isTrue(Option.isNone(yield* Ref.get(mainWindow)));
958
+ assert.equal(fake.send.mock.calls.length, 0);
959
+ }).pipe(Effect.provide(layerTest({ window: fake.window, createCount, mainWindow })));
960
+ }),
961
+ );
962
+
963
+ it.effect.each(["main", "splash"] as const)(
964
+ "destroys a %s window when quit races native creation without loading or revealing it",
965
+ (kind) =>
966
+ Effect.gen(function* () {
967
+ const fake = makeFakeBrowserWindow();
968
+ const createCount = yield* Ref.make(0);
969
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
970
+ const creationStarted = yield* Deferred.make<void>();
971
+ const releaseCreation = yield* Deferred.make<void>();
972
+ const reveal = vi.fn();
973
+ const layer = layerTest({
974
+ window: fake.window,
975
+ createCount,
976
+ mainWindow,
977
+ onWindowCreate: Deferred.succeed(creationStarted, undefined).pipe(
978
+ Effect.andThen(Deferred.await(releaseCreation)),
979
+ ),
980
+ destroyAll: Effect.sync(() => fake.isDestroyed.mockReturnValue(true)),
981
+ onReveal: reveal,
982
+ });
983
+
984
+ yield* Effect.gen(function* () {
985
+ const windows = yield* DesktopWindow.DesktopWindow;
986
+ const state = yield* DesktopState.DesktopState;
987
+ const fiber = yield* (
988
+ kind === "splash"
989
+ ? windows.showConnectingSplash
990
+ : windows.handleBackendReady(new URL("http://127.0.0.1:3773"))
991
+ ).pipe(Effect.forkChild({ startImmediately: true }));
992
+ yield* Deferred.await(creationStarted);
993
+ yield* Ref.set(state.quitting, true);
994
+ yield* Deferred.succeed(releaseCreation, undefined);
995
+ assert.isTrue(Exit.isSuccess(yield* Fiber.await(fiber)));
996
+ assert.equal(yield* Ref.get(createCount), 1);
997
+ assert.isTrue(fake.window.isDestroyed());
998
+ assert.isTrue(Option.isNone(yield* Ref.get(mainWindow)));
999
+ assert.equal(fake.loadURL.mock.calls.length, 0);
1000
+ assert.equal(fake.openDevTools.mock.calls.length, 0);
1001
+ assert.equal(reveal.mock.calls.length, 0);
1002
+ }).pipe(Effect.provide(layer));
1003
+ }),
1004
+ );
1005
+
1006
+ it.effect.each(["backend ready", "activation", "renderer event"] as const)(
1007
+ "quietly cancels %s when quit races preview cleanup",
1008
+ (entry) =>
1009
+ Effect.gen(function* () {
1010
+ const fake = makeFakeBrowserWindow();
1011
+ const createCount = yield* Ref.make(0);
1012
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
1013
+ const previewStarted = yield* Deferred.make<void>();
1014
+ const releasePreview = yield* Deferred.make<void>();
1015
+ const reveal = vi.fn();
1016
+ const warnings: unknown[] = [];
1017
+ const logger = Logger.make(({ logLevel, message }) => {
1018
+ if (logLevel === "Warn" || logLevel === "Error") warnings.push(message);
1019
+ });
1020
+ const layer = layerTest({
1021
+ window: fake.window,
1022
+ createCount,
1023
+ mainWindow,
1024
+ desktopSettings: {
1025
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
1026
+ localEnvironmentEnabled: false,
1027
+ },
1028
+ setPreviewMainWindow: () =>
1029
+ Deferred.succeed(previewStarted, undefined).pipe(
1030
+ Effect.andThen(Deferred.await(releasePreview)),
1031
+ ),
1032
+ destroyAll: Effect.sync(() => fake.isDestroyed.mockReturnValue(true)),
1033
+ onReveal: reveal,
1034
+ });
1035
+
1036
+ yield* Effect.gen(function* () {
1037
+ const windows = yield* DesktopWindow.DesktopWindow;
1038
+ const state = yield* DesktopState.DesktopState;
1039
+ const creation =
1040
+ entry === "backend ready"
1041
+ ? windows.handleBackendReady(new URL("http://127.0.0.1:3773"))
1042
+ : entry === "activation"
1043
+ ? windows.activate
1044
+ : windows.dispatchMenuAction("open-settings");
1045
+ const fiber = yield* creation.pipe(Effect.forkChild({ startImmediately: true }));
1046
+ yield* Deferred.await(previewStarted);
1047
+ yield* Ref.set(state.quitting, true);
1048
+ // Cover both an already-destroyed window and one shutdown has yet to destroy.
1049
+ fake.isDestroyed.mockReturnValue(entry !== "backend ready");
1050
+ yield* Deferred.succeed(releasePreview, undefined);
1051
+
1052
+ assert.isTrue(Exit.isSuccess(yield* Fiber.await(fiber)));
1053
+ assert.isTrue(fake.window.isDestroyed());
1054
+ assert.isTrue(Option.isNone(yield* Ref.get(mainWindow)));
1055
+ assert.equal(fake.loadURL.mock.calls.length, 0);
1056
+ assert.equal(fake.openDevTools.mock.calls.length, 0);
1057
+ assert.equal(fake.send.mock.calls.length, 0);
1058
+ assert.equal(reveal.mock.calls.length, 0);
1059
+ assert.deepEqual(warnings, []);
1060
+ }).pipe(
1061
+ Effect.provide(
1062
+ Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false })),
1063
+ ),
1064
+ );
1065
+ }),
1066
+ );
1067
+
1068
it.effect("restores the persisted maximized state", () =>
1069
Effect.gen(function* () {
1070
const fakeWindow = makeFakeBrowserWindow();
apps/desktop/src/window/DesktopWindow.ts
+42
-10
@@ -13,6 +13,7 @@ import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/con
13
import * as DesktopAssets from "../app/DesktopAssets.ts";
14
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15
import { makeComponentLogger } from "../app/DesktopObservability.ts";
16
+import * as DesktopState from "../app/DesktopState.ts";
17
import * as ElectronMenu from "../electron/ElectronMenu.ts";
18
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
19
import * as ElectronShell from "../electron/ElectronShell.ts";
@@ -69,6 +70,7 @@ type WindowTitleBarOptions = Pick<
70
71
type DesktopWindowRuntimeServices =
72
| DesktopEnvironment.DesktopEnvironment
73
+ | DesktopState.DesktopState
74
| DesktopAssets.DesktopAssets
75
| DesktopAppSettings.DesktopAppSettings
76
| DesktopClientSettings.DesktopClientSettings
@@ -287,6 +289,7 @@ function bindFirstRevealTrigger(
289
/** @public Service construction is part of the canonical Effect module API. */
290
export const make = Effect.gen(function* () {
291
const environment = yield* DesktopEnvironment.DesktopEnvironment;
292
+ const desktopState = yield* DesktopState.DesktopState;
293
const assets = yield* DesktopAssets.DesktopAssets;
294
const electronMenu = yield* ElectronMenu.ElectronMenu;
295
const electronShell = yield* ElectronShell.ElectronShell;
@@ -345,9 +348,10 @@ export const make = Effect.gen(function* () {
348
});
349
350
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
348
- Electron.BrowserWindow,
351
+ Option.Option<Electron.BrowserWindow>,
352
DesktopWindowError
353
> {
354
+ if (yield* Ref.get(desktopState.quitting)) return Option.none();
355
yield* previewManager.getBrowserSession();
356
const applicationUrl = getDesktopUrl(environment.isDevelopment);
357
const iconPaths = yield* assets.iconPaths;
@@ -376,6 +380,7 @@ export const make = Effect.gen(function* () {
380
if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) {
381
yield* logWindowWarning("saved main window bounds could not be restored; using defaults");
382
}
383
+ if (yield* Ref.get(desktopState.quitting)) return Option.none();
384
const window = yield* electronWindow.create({
385
...initialBounds,
386
minWidth: 840,
@@ -404,6 +409,10 @@ export const make = Effect.gen(function* () {
409
disableHtmlFullscreenWindowResize: true,
410
},
411
});
412
+ if (yield* Ref.get(desktopState.quitting)) {
413
+ yield* electronWindow.destroyAll;
414
+ return Option.none();
415
+ }
416
417
yield* rendererHistory.register(window.webContents, { surface: "main" });
418
if (environment.platform === "darwin") {
@@ -497,6 +506,10 @@ export const make = Effect.gen(function* () {
506
flushMainWindowBounds = flushBoundsPersist;
507
508
yield* previewManager.setMainWindow(window);
509
+ if (yield* Ref.get(desktopState.quitting)) {
510
+ yield* electronWindow.destroyAll;
511
+ return Option.none();
512
+ }
513
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
514
if (
515
typeof params.partition !== "string" ||
@@ -835,26 +848,35 @@ export const make = Effect.gen(function* () {
848
void runPromise(electronWindow.clearMain(Option.some(window)));
849
});
850
838
- return window;
851
+ return Option.some(window);
852
});
853
854
const createMain = Effect.gen(function* () {
855
const window = yield* createWindow();
843
- yield* electronWindow.setMain(window);
844
- yield* logWindowInfo("main window created");
856
+ if (Option.isSome(window)) {
857
+ yield* electronWindow.setMain(window.value);
858
+ yield* logWindowInfo("main window created");
859
+ }
860
return window;
861
}).pipe(Effect.withSpan("desktop.window.createMain"));
862
863
const ensureMain = Effect.gen(function* () {
864
+ if (yield* Ref.get(desktopState.quitting)) return Option.none<Electron.BrowserWindow>();
865
const existingWindow = yield* currentMainWindow;
866
if (Option.isSome(existingWindow)) {
851
- return existingWindow.value;
867
+ return existingWindow;
868
}
869
return yield* createMain;
870
}).pipe(Effect.withSpan("desktop.window.ensureMain"));
871
872
+ const requireWindow = (window: Option.Option<Electron.BrowserWindow>) =>
873
+ Option.match(window, {
874
+ onNone: () => Effect.interrupt,
875
+ onSome: Effect.succeed,
876
+ });
877
+
878
const revealOrCreateMain = Effect.gen(function* () {
857
- const window = yield* ensureMain;
879
+ const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow));
880
yield* electronWindow.reveal(window);
881
return window;
882
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
@@ -865,6 +887,7 @@ export const make = Effect.gen(function* () {
887
});
888
889
const createMainIfBackendReady = Effect.gen(function* () {
890
+ if (yield* Ref.get(desktopState.quitting)) return;
891
if (yield* waitingForBackend) return;
892
const existingWindow = yield* currentMainWindow;
893
if (Option.isSome(existingWindow)) return;
@@ -872,12 +895,14 @@ export const make = Effect.gen(function* () {
895
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
896
897
const showConnectingSplash = Effect.gen(function* () {
898
+ if (yield* Ref.get(desktopState.quitting)) return;
899
const existingSplash = yield* Ref.get(splashWindowRef);
900
if (Option.isSome(existingSplash)) return;
901
const existingWindow = yield* electronWindow.currentMainOrFirst;
902
if (Option.isSome(existingWindow)) return;
903
904
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
905
+ if (yield* Ref.get(desktopState.quitting)) return;
906
const splash = yield* electronWindow.create({
907
width: 360,
908
height: 220,
@@ -897,6 +922,10 @@ export const make = Effect.gen(function* () {
922
sandbox: true,
923
},
924
});
925
+ if (yield* Ref.get(desktopState.quitting)) {
926
+ yield* electronWindow.destroyAll;
927
+ return;
928
+ }
929
yield* rendererHistory.register(splash.webContents, { surface: "splash" });
930
yield* Ref.set(splashWindowRef, Option.some(splash));
931
splash.once("closed", () => {
@@ -921,10 +950,12 @@ export const make = Effect.gen(function* () {
950
payload: unknown,
951
{ reveal = true }: { readonly reveal?: boolean } = {},
952
) {
953
+ if (yield* Ref.get(desktopState.quitting)) return;
954
const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main;
955
if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return;
926
- const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
927
- if (targetWindow.isDestroyed()) return;
956
+ const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain;
957
+ if (Option.isNone(window) || window.value.isDestroyed()) return;
958
+ const targetWindow = window.value;
959
const send = Effect.sync(() => {
960
if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload);
961
});
@@ -941,8 +972,8 @@ export const make = Effect.gen(function* () {
972
});
973
974
return DesktopWindow.of({
944
- createMain,
945
- ensureMain,
975
+ createMain: createMain.pipe(Effect.flatMap(requireWindow)),
976
+ ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)),
977
revealOrCreateMain,
978
prepareCaptureReveal: Effect.gen(function* () {
979
const existingWindow = yield* currentMainWindow;
@@ -951,6 +982,7 @@ export const make = Effect.gen(function* () {
982
}
983
}),
984
activate: Effect.gen(function* () {
985
+ if (yield* Ref.get(desktopState.quitting)) return;
986
const existingWindow = yield* currentMainWindow;
987
if (Option.isSome(existingWindow)) {
988
yield* electronWindow.reveal(existingWindow.value);