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

window.test.ts

300 lines10.2 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.succeed(Option.some(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.succeed(Option.some(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.succeed(
132 Option.some({
133 ...readyWslConfig,
134 preflightFailure: Option.some({
135 reason: "WSL probe timed out",
136 fatal: false,
137 retryLimit: 12,
138 }),
139 }),
140 ),
141 snapshot: Effect.succeed({
142 desiredRunning: false,
143 ready: false,
144 activePid: Option.none(),
145 restartAttempt: 12,
146 restartScheduled: false,
147 }),
148 };
149​
150 return Effect.gen(function* () {
151 const result = yield* getLocalEnvironmentBootstraps.handler();
152 assert.deepEqual(result, []);
153 }).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
154 });
155});
156​
157describe("getWindowFullscreenState", () => {
158 it.effect("reads the current native window state", () => {
159 const window = { isFullScreen: () => true } as Electron.BrowserWindow;
160​
161 return Effect.gen(function* () {
162 assert.isTrue(yield* getWindowFullscreenState.handler());
163 }).pipe(
164 Effect.provide(
165 Layer.mock(ElectronWindow.ElectronWindow)({
166 currentMainOrFirst: Effect.succeed(Option.some(window)),
167 }),
168 ),
169 );
170 });
171});
172​
173describe("pasteAsText", () => {
174 it.effect(
175 "pastes into the focused guest only after the main renderer acknowledges the menu action",
176 () => {
177 const paste = vi.fn();
178 const mainPaste = vi.fn();
179 const window = {
180 webContents: { id: 42, paste: mainPaste },
181 isDestroyed: () => false,
182 } as unknown as Electron.BrowserWindow;
183 focusedWebContents.mockReturnValue({ paste, isDestroyed: () => false });
184 ownerWindow.mockReturnValue(window);
185​
186 return Effect.gen(function* () {
187 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
188 assert.equal(paste.mock.calls.length, 1);
189 assert.equal(mainPaste.mock.calls.length, 0);
190​
191 yield* pasteAsText.handler(undefined, { sender: { id: 99 } });
192 assert.equal(paste.mock.calls.length, 1);
193 ownerWindow.mockReturnValue({}); // A focused PiP/other BrowserWindow.
194 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
195 assert.equal(paste.mock.calls.length, 1);
196 ownerWindow.mockReturnValue(null); // Detached contents.
197 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
198 assert.equal(paste.mock.calls.length, 1);
199 ownerWindow.mockReturnValue(window);
200 focusedWebContents.mockReturnValue({ paste, isDestroyed: () => true });
201 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
202 assert.equal(paste.mock.calls.length, 1);
203 focusedWebContents.mockReturnValue(null);
204 yield* pasteAsText.handler(undefined, { sender: { id: 42 } });
205 assert.equal(paste.mock.calls.length, 1);
206 }).pipe(
207 Effect.provide(
208 Layer.mock(ElectronWindow.ElectronWindow)({
209 main: Effect.succeed(Option.some(window)),
210 }),
211 ),
212 );
213 },
214 );
215});
216​
217describe("pickProjectFavicon", () => {
218 const pickerLayer = (pickFiles: () => Effect.Effect<Array<string>>, settings?: DesktopSettings) =>
219 Layer.mergeAll(
220 Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),
221 Layer.mock(ElectronWindow.ElectronWindow)({
222 focusedMainOrFirst: Effect.succeed(Option.none()),
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);