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