Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

window.test.ts

298 lines10.1 KB

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