Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7import * as TestClock from "effect/testing/TestClock";
8
9import type * as Electron from "electron";
10import { vi } from "vite-plus/test";
11
12vi.mock("electron", async (importOriginal) => ({
13 ...(await importOriginal<typeof import("electron")>()),
14 session: {
15 fromPartition: vi.fn(() => ({
16 getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/1.2.3"),
17 setPermissionRequestHandler: vi.fn(),
18 setUserAgent: vi.fn(),
19 })),
20 },
21}));
22
23import * as DesktopAssets from "../app/DesktopAssets.ts";
24import * as DesktopConfig from "../app/DesktopConfig.ts";
25import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
26import * as DesktopState from "../app/DesktopState.ts";
27import * as ElectronMenu from "../electron/ElectronMenu.ts";
28import * as ElectronShell from "../electron/ElectronShell.ts";
29import * as ElectronTheme from "../electron/ElectronTheme.ts";
30import * as ElectronWindow from "../electron/ElectronWindow.ts";
31import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
32import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
33import * as DesktopWindow from "./DesktopWindow.ts";
34import * as PreviewManager from "../preview/Manager.ts";
35
36const environmentInput = {
37 dirname: "/repo/apps/desktop/dist-electron",
38 homeDirectory: "/Users/alice",
39 platform: "darwin",
40 processArch: "arm64",
41 appVersion: "1.2.3",
42 appPath: "/repo",
43 isPackaged: false,
44 resourcesPath: "/repo/resources",
45 runningUnderArm64Translation: false,
46} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
47
48function makeFakeBrowserWindow() {
49 const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
50 const webContents = {
51 copyImageAt: vi.fn(),
52 getURL: vi.fn(() => "t3code-dev://app/"),
53 isLoadingMainFrame: vi.fn(() => false),
54 on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
55 webContentsListeners.set(eventName, listener);
56 }),
57 once: vi.fn(),
58 openDevTools: vi.fn(),
59 reload: vi.fn(),
60 replaceMisspelling: vi.fn(),
61 send: vi.fn(),
62 setWindowOpenHandler: vi.fn(),
63 };
64
65 const window = {
66 close: vi.fn(),
67 focus: vi.fn(),
68 isDestroyed: vi.fn(() => false),
69 isMinimized: vi.fn(() => false),
70 isVisible: vi.fn(() => true),
71 loadURL: vi.fn(() => Promise.resolve()),
72 on: vi.fn(),
73 once: vi.fn(),
74 restore: vi.fn(),
75 setBackgroundColor: vi.fn(),
76 setAutoHideCursor: vi.fn(),
77 setTitle: vi.fn(),
78 setTitleBarOverlay: vi.fn(),
79 show: vi.fn(),
80 webContents,
81 };
82
83 return {
84 window: window as unknown as Electron.BrowserWindow,
85 loadURL: window.loadURL,
86 openDevTools: webContents.openDevTools,
87 reload: webContents.reload,
88 send: webContents.send,
89 setAutoHideCursor: window.setAutoHideCursor,
90 webContentsListeners,
91 };
92}
93
94const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
95 iconPaths: Effect.succeed({
96 ico: Option.none<string>(),
97 icns: Option.none<string>(),
98 png: Option.none<string>(),
99 }),
100 resolveResourcePath: () => Effect.succeed(Option.none<string>()),
101} satisfies DesktopAssets.DesktopAssets["Service"]);
102
103const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
104 getState: Effect.die("unexpected getState"),
105 backendConfig: Effect.succeed({
106 port: 3773,
107 bindHost: "127.0.0.1",
108 httpBaseUrl: new URL("http://127.0.0.1:3773"),
109 tailscaleServeEnabled: false,
110 tailscaleServePort: 443,
111 }),
112 configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
113 setMode: () => Effect.die("unexpected setMode"),
114 setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
115 getAdvertisedEndpoints: Effect.die("unexpected getAdvertisedEndpoints"),
116} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
117
118const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
119 setApplicationMenu: () => Effect.void,
120 popupTemplate: () => Effect.void,
121 showContextMenu: () => Effect.succeed(Option.none()),
122} satisfies ElectronMenu.ElectronMenu["Service"]);
123
124const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
125 shouldUseDarkColors: Effect.succeed(false),
126 setSource: () => Effect.void,
127 onUpdated: () => Effect.void,
128} satisfies ElectronTheme.ElectronTheme["Service"]);
129
130const desktopEnvironmentLayer = DesktopEnvironment.layer(environmentInput).pipe(
131 Layer.provide(
132 Layer.mergeAll(
133 NodeServices.layer,
134 DesktopConfig.layerTest({
135 T3CODE_PORT: "3773",
136 VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
137 }),
138 ),
139 ),
140);
141
142function makeTestLayer(input: {
143 readonly window: Electron.BrowserWindow;
144 readonly createCount: Ref.Ref<number>;
145 readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
146 readonly createdWindowOptions?: Electron.BrowserWindowConstructorOptions[];
147 readonly openedExternalUrls?: unknown[];
148}) {
149 const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
150 create: (options) =>
151 Effect.sync(() => {
152 input.createdWindowOptions?.push(options);
153 }).pipe(
154 Effect.andThen(Ref.update(input.createCount, (count) => count + 1)),
155 Effect.as(input.window),
156 ),
157 main: Ref.get(input.mainWindow),
158 currentMainOrFirst: Ref.get(input.mainWindow),
159 focusedMainOrFirst: Ref.get(input.mainWindow),
160 setMain: (window) => Ref.set(input.mainWindow, Option.some(window)),
161 clearMain: () => Ref.set(input.mainWindow, Option.none()),
162 reveal: () => Effect.void,
163 sendAll: () => Effect.void,
164 destroyAll: Effect.void,
165 syncAllAppearance: (sync) => sync(input.window),
166 } satisfies ElectronWindow.ElectronWindow["Service"]);
167
168 return DesktopWindow.layer.pipe(
169 Layer.provide(
170 Layer.mergeAll(
171 desktopAssetsLayer,
172 desktopEnvironmentLayer,
173 desktopServerExposureLayer,
174 DesktopState.layer,
175 electronMenuLayer,
176 Layer.succeed(ElectronShell.ElectronShell, {
177 openExternal: (url) =>
178 Effect.sync(() => {
179 input.openedExternalUrls?.push(url);
180 return true;
181 }),
182 copyText: () => Effect.void,
183 } satisfies ElectronShell.ElectronShell["Service"]),
184 electronThemeLayer,
185 electronWindowLayer,
186 Layer.mock(PreviewManager.PreviewManager)({
187 getBrowserSession: () => Effect.succeed({} as Electron.Session),
188 setMainWindow: () => Effect.void,
189 isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
190 getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
191 }),
192 ),
193 ),
194 );
195}
196
197// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
198// given outcomes in order (null => simulated open failure), and whose
199// currentMainOrFirst mirrors the real fallback to the first live window (the
200// splash, before any main is registered). Reveal targets are recorded so tests
201// can assert what activation actually surfaced.
202const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
203 Effect.gen(function* () {
204 const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
205 const createCalls = yield* Ref.make(0);
206 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
207 const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
208 const fallbackWindow = createOutcomes.find(
209 (window): window is Electron.BrowserWindow => window !== null,
210 );
211
212 const currentMainOrFirst = Effect.gen(function* () {
213 const registered = yield* Ref.get(mainWindow);
214 if (Option.isSome(registered)) {
215 return registered;
216 }
217 const created = yield* Ref.get(createdWindows);
218 return Option.fromNullishOr(created[0] ?? null);
219 });
220
221 const electronWindowShape = {
222 create: () =>
223 Effect.gen(function* () {
224 const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
225 const outcome = createOutcomes[index] ?? null;
226 if (outcome === null) {
227 return yield* new ElectronWindow.ElectronWindowCreateError({
228 options: {
229 title: null,
230 width: null,
231 height: null,
232 minWidth: null,
233 minHeight: null,
234 show: null,
235 modal: null,
236 frame: null,
237 transparent: null,
238 backgroundColor: null,
239 webPreferences: {
240 preload: null,
241 partition: null,
242 sandbox: null,
243 contextIsolation: null,
244 nodeIntegration: null,
245 webviewTag: null,
246 },
247 },
248 cause: new Error("simulated window-open failure"),
249 });
250 }
251 yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
252 return outcome;
253 }),
254 main: Ref.get(mainWindow),
255 currentMainOrFirst,
256 focusedMainOrFirst: currentMainOrFirst,
257 setMain: (window) => Ref.set(mainWindow, Option.some(window)),
258 clearMain: () => Ref.set(mainWindow, Option.none()),
259 reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
260 sendAll: () => Effect.void,
261 destroyAll: Effect.void,
262 syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
263 } satisfies ElectronWindow.ElectronWindow["Service"];
264
265 const layer = DesktopWindow.layer.pipe(
266 Layer.provide(
267 Layer.mergeAll(
268 desktopAssetsLayer,
269 desktopEnvironmentLayer,
270 desktopServerExposureLayer,
271 electronMenuLayer,
272 Layer.succeed(ElectronShell.ElectronShell, {
273 openExternal: () => Effect.succeed(true),
274 copyText: () => Effect.void,
275 } satisfies ElectronShell.ElectronShell["Service"]),
276 electronThemeLayer,
277 Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
278 Layer.mock(PreviewManager.PreviewManager)({
279 getBrowserSession: () => Effect.succeed({} as Electron.Session),
280 setMainWindow: () => Effect.void,
281 isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
282 getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
283 }),
284 ),
285 ),
286 );
287
288 return { layer, createCalls, mainWindow, revealedWindows } as const;
289 });
290
291describe("DesktopWindow", () => {
292 it("recognizes only same-origin renderer navigations", () => {
293 assert.isTrue(
294 DesktopWindow.isSameOriginRendererNavigation({
295 applicationUrl: "t3code://app/",
296 navigationUrl: "t3code://app/settings/connections",
297 }),
298 );
299 assert.isFalse(
300 DesktopWindow.isSameOriginRendererNavigation({
301 applicationUrl: "t3code://app/",
302 navigationUrl: "https://accounts.microsoft.com/oauth",
303 }),
304 );
305 assert.isFalse(
306 DesktopWindow.isSameOriginRendererNavigation({
307 applicationUrl: "t3code://app/",
308 navigationUrl: "not a url",
309 }),
310 );
311 });
312
313 it.effect("does not open a development window until the backend is ready", () =>
314 Effect.gen(function* () {
315 const fakeWindow = makeFakeBrowserWindow();
316 const createCount = yield* Ref.make(0);
317 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
318 const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = [];
319 const layer = makeTestLayer({
320 window: fakeWindow.window,
321 createCount,
322 mainWindow,
323 createdWindowOptions,
324 });
325
326 yield* Effect.gen(function* () {
327 const desktopWindow = yield* DesktopWindow.DesktopWindow;
328 yield* desktopWindow.activate;
329 assert.equal(yield* Ref.get(createCount), 0);
330
331 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
332 assert.equal(yield* Ref.get(createCount), 1);
333 assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
334 assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
335 assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]);
336 assert.equal(fakeWindow.openDevTools.mock.calls.length, 1);
337 }).pipe(Effect.provide(layer));
338 }),
339 );
340
341 it.effect("recovers when the development renderer is temporarily unreachable", () =>
342 Effect.gen(function* () {
343 const fakeWindow = makeFakeBrowserWindow();
344 const createCount = yield* Ref.make(0);
345 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
346 const layer = makeTestLayer({
347 window: fakeWindow.window,
348 createCount,
349 mainWindow,
350 });
351
352 yield* Effect.gen(function* () {
353 const desktopWindow = yield* DesktopWindow.DesktopWindow;
354 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
355
356 const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
357 const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
358 if (!didFailLoad || !didFinishLoad) {
359 return yield* Effect.die("renderer load listeners were not registered");
360 }
361
362 didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
363 assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
364
365 yield* TestClock.adjust(100);
366 assert.deepEqual(fakeWindow.loadURL.mock.calls, [
367 ["t3code-dev://app/"],
368 ["t3code-dev://app/"],
369 ]);
370 assert.equal(fakeWindow.reload.mock.calls.length, 0);
371
372 didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
373 didFinishLoad();
374 yield* TestClock.adjust(250);
375 assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
376 assert.equal(fakeWindow.reload.mock.calls.length, 0);
377 }).pipe(Effect.provide(layer));
378 }),
379 );
380
381 it("retries only transient failures for the development renderer", () => {
382 assert.isTrue(
383 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
384 applicationUrl: "t3code-dev://app/",
385 errorCode: -102,
386 isMainFrame: true,
387 validatedUrl: "t3code-dev://app/",
388 }),
389 );
390 assert.isFalse(
391 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
392 applicationUrl: "t3code-dev://app/",
393 errorCode: -3,
394 isMainFrame: true,
395 validatedUrl: "t3code-dev://app/",
396 }),
397 );
398 assert.isFalse(
399 DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
400 applicationUrl: "t3code-dev://app/",
401 errorCode: -102,
402 isMainFrame: true,
403 validatedUrl: "https://example.com/",
404 }),
405 );
406 });
407
408 it.effect("opens safe off-origin renderer navigations in the system browser", () =>
409 Effect.gen(function* () {
410 const fakeWindow = makeFakeBrowserWindow();
411 const createCount = yield* Ref.make(0);
412 const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
413 const openedExternalUrls: unknown[] = [];
414 const layer = makeTestLayer({
415 window: fakeWindow.window,
416 createCount,
417 mainWindow,
418 openedExternalUrls,
419 });
420
421 yield* Effect.gen(function* () {
422 const desktopWindow = yield* DesktopWindow.DesktopWindow;
423 yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
424
425 const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
426 if (!willNavigate) {
427 return yield* Effect.die("will-navigate listener was not registered");
428 }
429 let prevented = false;
430 willNavigate(
431 {
432 preventDefault: () => {
433 prevented = true;
434 },
435 },
436 "https://accounts.microsoft.com/oauth",
437 );
438 yield* Effect.promise(() => Promise.resolve());
439
440 assert.isTrue(prevented);
441 assert.deepEqual(openedExternalUrls, ["https://accounts.microsoft.com/oauth"]);
442 }).pipe(Effect.provide(layer));
443 }),
444 );
445
446 it.effect(
447 "retries opening the real main on activate when a failed post-readiness open left only the splash",
448 () =>
449 Effect.gen(function* () {
450 const splash = makeFakeBrowserWindow();
451 const main = makeFakeBrowserWindow();
452 // create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
453 // window-open error), #3 -> the real main on activate's retry.
454 const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
455
456 yield* Effect.gen(function* () {
457 const desktopWindow = yield* DesktopWindow.DesktopWindow;
458
459 // 1. WSL-only boot shows the connecting splash.
460 yield* desktopWindow.showConnectingSplash;
461 assert.equal(yield* Ref.get(scenario.createCalls), 1);
462
463 // 2. Backend reports ready, but opening the real main fails. The pool
464 // swallows that error in production, so handleBackendReady fails
465 // here without a registered main window -- only the splash is open.
466 const readyExit = yield* Effect.exit(
467 desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
468 );
469 assert.equal(readyExit._tag, "Failure");
470 assert.equal(yield* Ref.get(scenario.createCalls), 2);
471 assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
472
473 // 3. Activating must not mistake the splash for the main window: it
474 // retries the open and brings up the real main instead of leaving
475 // the user stranded on "Connecting to WSL".
476 yield* desktopWindow.activate;
477 assert.equal(yield* Ref.get(scenario.createCalls), 3);
478 const registeredMain = yield* Ref.get(scenario.mainWindow);
479 assert.isTrue(Option.isSome(registeredMain));
480 assert.equal(Option.getOrThrow(registeredMain), main.window);
481 }).pipe(Effect.provide(scenario.layer));
482 }),
483 );
484
485 it.effect(
486 "re-reveals the connecting splash on activate while the backend is still cold-booting",
487 () =>
488 Effect.gen(function* () {
489 const splash = makeFakeBrowserWindow();
490 // Only the splash is ever created; the backend never reports ready.
491 const scenario = yield* makeSplashScenario([splash.window]);
492
493 yield* Effect.gen(function* () {
494 const desktopWindow = yield* DesktopWindow.DesktopWindow;
495
496 yield* desktopWindow.showConnectingSplash;
497 assert.equal(yield* Ref.get(scenario.createCalls), 1);
498
499 // Taskbar/dock activation during cold boot must bring the splash back
500 // rather than no-op and leave it hidden until the backend finishes.
501 yield* desktopWindow.activate;
502 assert.equal(yield* Ref.get(scenario.createCalls), 1);
503 assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
504 }).pipe(Effect.provide(scenario.layer));
505 }),
506 );
507
508 it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
509 Effect.gen(function* () {
510 const splash = makeFakeBrowserWindow();
511 const main = makeFakeBrowserWindow();
512 const scenario = yield* makeSplashScenario([splash.window, main.window]);
513
514 yield* Effect.gen(function* () {
515 const desktopWindow = yield* DesktopWindow.DesktopWindow;
516
517 yield* desktopWindow.showConnectingSplash;
518 yield* desktopWindow.dispatchMenuAction("open-settings");
519
520 assert.equal(yield* Ref.get(scenario.createCalls), 1);
521 assert.equal(splash.send.mock.calls.length, 0);
522 assert.equal(main.send.mock.calls.length, 0);
523 }).pipe(Effect.provide(scenario.layer));
524 }),
525 );
526
527 it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
528 Effect.gen(function* () {
529 const splash = makeFakeBrowserWindow();
530 const main = makeFakeBrowserWindow();
531 const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
532
533 yield* Effect.gen(function* () {
534 const desktopWindow = yield* DesktopWindow.DesktopWindow;
535
536 yield* desktopWindow.showConnectingSplash;
537 const readyExit = yield* Effect.exit(
538 desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
539 );
540 assert.equal(readyExit._tag, "Failure");
541
542 yield* desktopWindow.dispatchMenuAction("open-settings");
543
544 assert.equal(yield* Ref.get(scenario.createCalls), 3);
545 assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
546 }).pipe(Effect.provide(scenario.layer));
547 }),
548 );
549});