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