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

window.test.ts

388 lines13.3 KB

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