Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import { vi } from "vite-plus/test";
10
11import type * as Electron from "electron";
12
13const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({
14 focusedWebContents: vi.fn(),
15 ownerWindow: vi.fn(),
16}));
17vi.mock("electron", () => ({
18 webContents: { getFocusedWebContents: focusedWebContents },
19 BrowserWindow: { fromWebContents: ownerWindow },
20}));
21
22import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
23import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
24import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
25import * as ElectronDialog from "../../electron/ElectronDialog.ts";
26import * as ElectronWindow from "../../electron/ElectronWindow.ts";
27import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
28import {
29 getLocalEnvironmentBootstraps,
30 getRelayTelemetryEnabled,
31 getWindowFullscreenState,
32 pasteAsText,
33 pickProjectFavicon,
34 probeRemoteEditors,
35 revealWindow,
36} from "./window.ts";
37
38const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
39 executablePath: "wsl.exe",
40 args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
41 entryPath: "/app/bin.mjs",
42 cwd: "/app",
43 env: {},
44 extendEnv: false,
45 bootstrap: {
46 mode: "desktop",
47 noBrowser: true,
48 port: 3774,
49 host: "0.0.0.0",
50 desktopBootstrapToken: "bootstrap-token",
51 tailscaleServeEnabled: false,
52 tailscaleServePort: 443,
53 },
54 bootstrapDelivery: "stdin",
55 httpBaseUrl: new URL("http://127.0.0.1:3774"),
56 captureOutput: true,
57 preflightFailure: Option.none(),
58 runningDistro: "Ubuntu",
59};
60
61const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
62 id: DesktopBackendManager.BackendInstanceId("wsl:default"),
63 label: Effect.succeed("WSL (default distro)"),
64 start: Effect.void,
65 stop: () => Effect.void,
66 currentConfig: Effect.succeedSome(readyWslConfig),
67 snapshot: Effect.succeed({
68 desiredRunning: true,
69 ready: true,
70 activePid: Option.some(123),
71 restartAttempt: 0,
72 restartScheduled: false,
73 }),
74 waitForReady: () => Effect.succeed(true),
75};
76
77const backendConfigurationLayer = Layer.succeed(
78 DesktopBackendConfiguration.DesktopBackendConfiguration,
79 {
80 resolvePrimary: Effect.die("unexpected resolvePrimary"),
81 resolvePrimaryLabel: Effect.succeed("Windows"),
82 resolveWsl: () => Effect.die("unexpected resolveWsl"),
83 currentBootstrapToken: Effect.succeed("current-window-token"),
84 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
85);
86
87const bootstrapsLayer = (instances: ReadonlyArray<DesktopBackendManager.DesktopBackendInstance>) =>
88 Layer.merge(DesktopBackendPool.layerTest([...instances]), backendConfigurationLayer);
89
90describe("getLocalEnvironmentBootstraps", () => {
91 it.effect("publishes the concrete running distro without replacing the stable instance id", () =>
92 Effect.gen(function* () {
93 const result = yield* getLocalEnvironmentBootstraps.handler();
94
95 assert.deepEqual(result, [
96 {
97 id: "wsl:default",
98 label: "WSL (Ubuntu)",
99 runningDistro: "Ubuntu",
100 httpBaseUrl: "http://127.0.0.1:3774/",
101 wsBaseUrl: "ws://127.0.0.1:3774/",
102 bootstrapToken: "bootstrap-token",
103 },
104 ]);
105 }).pipe(Effect.provide(bootstrapsLayer([defaultWslInstance]))),
106 );
107
108 it.effect("hands out the current window's token to a backend launched with the secret", () =>
109 Effect.gen(function* () {
110 const result = yield* getLocalEnvironmentBootstraps.handler();
111
112 assert.deepEqual(result, [
113 {
114 id: "wsl:default",
115 label: "WSL (Ubuntu)",
116 runningDistro: "Ubuntu",
117 httpBaseUrl: "http://127.0.0.1:3774/",
118 wsBaseUrl: "ws://127.0.0.1:3774/",
119 bootstrapToken: "current-window-token",
120 },
121 ]);
122 }).pipe(
123 Effect.provide(
124 bootstrapsLayer([
125 {
126 ...defaultWslInstance,
127 currentConfig: Effect.succeedSome({
128 ...readyWslConfig,
129 bootstrap: {
130 ...readyWslConfig.bootstrap,
131 desktopBootstrapSecret: "desktop-secret",
132 },
133 }),
134 },
135 ]),
136 ),
137 ),
138 );
139
140 it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
141 const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
142 ...readyWslConfig,
143 preflightFailure: Option.some({
144 reason: "WSL probe timed out",
145 fatal: false,
146 retryLimit: 12,
147 }),
148 };
149 const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
150 ...defaultWslInstance,
151 currentConfig: Effect.succeedSome(retryingConfig),
152 snapshot: Effect.succeed({
153 desiredRunning: true,
154 ready: false,
155 activePid: Option.none(),
156 restartAttempt: 2,
157 restartScheduled: true,
158 }),
159 };
160
161 return Effect.gen(function* () {
162 const result = yield* getLocalEnvironmentBootstraps.handler();
163 assert.deepEqual(result, [
164 {
165 id: "wsl:default",
166 label: "WSL (default distro)",
167 runningDistro: null,
168 httpBaseUrl: null,
169 wsBaseUrl: null,
170 },
171 ]);
172 }).pipe(Effect.provide(bootstrapsLayer([retryingInstance])));
173 });
174
175 it.effect("omits a bounded transient bootstrap after retries stop", () => {
176 const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
177 ...defaultWslInstance,
178 currentConfig: Effect.succeedSome({
179 ...readyWslConfig,
180 preflightFailure: Option.some({
181 reason: "WSL probe timed out",
182 fatal: false,
183 retryLimit: 12,
184 }),
185 }),
186 snapshot: Effect.succeed({
187 desiredRunning: false,
188 ready: false,
189 activePid: Option.none(),
190 restartAttempt: 12,
191 restartScheduled: false,
192 }),
193 };
194
195 return Effect.gen(function* () {
196 const result = yield* getLocalEnvironmentBootstraps.handler();
197 assert.deepEqual(result, []);
198 }).pipe(Effect.provide(bootstrapsLayer([stoppedInstance])));
199 });
200});
201
202describe("getRelayTelemetryEnabled", () => {
203 it.effect("reads the desktop host opt-out before returning the renderer policy", () =>
204 Effect.gen(function* () {
205 assert.isFalse(
206 yield* getRelayTelemetryEnabled.handler().pipe(
207 Effect.provideService(HostProcess.Environment, {
208 T3CODE_TELEMETRY_ENABLED: "false",
209 }),
210 ),
211 );
212 assert.isTrue(
213 yield* getRelayTelemetryEnabled
214 .handler()
215 .pipe(Effect.provideService(HostProcess.Environment, {})),
216 );
217 }),
218 );
219});
220
221describe("getWindowFullscreenState", () => {
222 it.effect("reads the current native window state", () => {
223 const window = { isFullScreen: () => true } as Electron.BrowserWindow;
224
225 return Effect.gen(function* () {
226 assert.isTrue(yield* getWindowFullscreenState.handler());
227 }).pipe(
228 Effect.provide(
229 Layer.mock(ElectronWindow.ElectronWindow)({
230 currentMainOrFirst: Effect.succeedSome(window),
231 }),
232 ),
233 );
234 });
235});
236
237describe("pasteAsText", () => {
238 it.effect(
239 "pastes into the focused guest only after the main renderer acknowledges the menu action",
240 () => {
241 const paste = vi.fn();
242 const mainPaste = vi.fn();
243 const window = {
244 webContents: { id: 42, paste: mainPaste },
245 isDestroyed: () => false,
246 } as unknown as Electron.BrowserWindow;
247 focusedWebContents.mockReturnValue({ paste, isDestroyed: () => false });
248 ownerWindow.mockReturnValue(window);
249
250 return Effect.gen(function* () {
251 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
252 assert.equal(paste.mock.calls.length, 1);
253 assert.equal(mainPaste.mock.calls.length, 0);
254
255 yield* pasteAsText.handler(undefined, { sender: { id: 99 } });
256 assert.equal(paste.mock.calls.length, 1);
257 ownerWindow.mockReturnValue({}); // A focused PiP/other BrowserWindow.
258 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
259 assert.equal(paste.mock.calls.length, 1);
260 ownerWindow.mockReturnValue(null); // Detached contents.
261 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
262 assert.equal(paste.mock.calls.length, 1);
263 ownerWindow.mockReturnValue(window);
264 focusedWebContents.mockReturnValue({ paste, isDestroyed: () => true });
265 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
266 assert.equal(paste.mock.calls.length, 1);
267 focusedWebContents.mockReturnValue(null);
268 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
269 assert.equal(paste.mock.calls.length, 1);
270 }).pipe(
271 Effect.provide(
272 Layer.mock(ElectronWindow.ElectronWindow)({
273 main: Effect.succeedSome(window),
274 }),
275 ),
276 );
277 },
278 );
279});
280
281describe("revealWindow", () => {
282 it.effect("reveals the main window only when it asks", () => {
283 const window = { webContents: { id: 42 } } as unknown as Electron.BrowserWindow;
284 const reveal = vi.fn(() => Effect.void);
285 return Effect.gen(function* () {
286 yield* revealWindow.handler(undefined, { sender: { id: 99 } });
287 assert.equal(reveal.mock.calls.length, 0);
288 yield* revealWindow.handler(undefined, { sender: { id: 42 } });
289 assert.deepEqual(reveal.mock.calls, [[window]]);
290 }).pipe(
291 Effect.provide(
292 Layer.mock(ElectronWindow.ElectronWindow)({
293 main: Effect.succeedSome(window),
294 reveal,
295 }),
296 ),
297 );
298 });
299});
300
301describe("pickProjectFavicon", () => {
302 const pickerLayer = (
303 pickFiles: () => Effect.Effect<Array<string>>,
304 settings?: DesktopAppSettings.DesktopSettings,
305 ) =>
306 Layer.mergeAll(
307 Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),
308 Layer.mock(ElectronWindow.ElectronWindow)({
309 focusedMainOrFirst: Effect.succeedNone,
310 }),
311 DesktopAppSettings.layerTest(settings),
312 );
313
314 it.effect("opens a single-image picker from the project directory", () =>
315 Effect.gen(function* () {
316 const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
317 const result = yield* pickProjectFavicon
318 .handler("/project")
319 .pipe(Effect.provide(pickerLayer(pickFiles)));
320
321 assert.strictEqual(result, "/pictures/icon.png");
322 assert.deepEqual(pickFiles.mock.calls, [
323 [
324 {
325 owner: Option.none(),
326 defaultPath: Option.some("/project"),
327 multiple: false,
328 filters: [
329 {
330 name: "Images",
331 extensions: ["avif", "gif", "ico", "jpeg", "jpg", "png", "svg", "webp", "icns"],
332 },
333 ],
334 },
335 ],
336 ]);
337 }),
338 );
339
340 it.effect("does not open a picker while the local environment is off", () =>
341 Effect.gen(function* () {
342 const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
343 const result = yield* pickProjectFavicon.handler("/project").pipe(
344 Effect.provide(
345 pickerLayer(pickFiles, {
346 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
347 localEnvironmentEnabled: false,
348 }),
349 ),
350 );
351
352 assert.strictEqual(result, null);
353 assert.strictEqual(pickFiles.mock.calls.length, 0);
354 }),
355 );
356});
357
358it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
359 "finds remote editors installed without PATH launchers",
360 () =>
361 Effect.gen(function* () {
362 const fs = yield* FileSystem.FileSystem;
363 const path = yield* Path.Path;
364 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-remote-editors-" });
365 for (const app of ["Cursor", "Visual Studio Code", "WebStorm"]) {
366 const executable = path.join(
367 home,
368 "Applications",
369 `${app}.app`,
370 app === "WebStorm" ? "Contents/MacOS/webstorm" : "Contents/Resources/app/bin/code",
371 );
372 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
373 yield* fs.writeFileString(executable, "#!/bin/sh\n");
374 yield* fs.chmod(executable, 0o755);
375 }
376 const editors = yield* probeRemoteEditors.handler(undefined).pipe(
377 Effect.provideService(HostProcess.Environment, {
378 HOME: home,
379 PATH: path.join(home, "empty"),
380 }),
381 Effect.provideService(HostProcess.Platform, "darwin"),
382 );
383 assert.include(editors, "cursor");
384 assert.include(editors, "vscode");
385 assert.include(editors, "webstorm");
386 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
387);