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

window.test.ts

300 lines9.6 KB

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​
11const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({
12 focusedWebContents: vi.fn(),
13 ownerWindow: vi.fn(),
14}));
15vi.mock("electron", () => ({
16 webContents: { getFocusedWebContents: focusedWebContents },
17 BrowserWindow: { fromWebContents: ownerWindow },
18}));
19​
20import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
21import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
22import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
23import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
24import * as ElectronDialog from "../../electron/ElectronDialog.ts";
25import * as ElectronWindow from "../../electron/ElectronWindow.ts";
26import {
27 getLocalEnvironmentBootstraps,
28 getRelayTelemetryEnabled,
29 pickProjectFavicon,
30 probeRemoteEditors,
31} from "./window.ts";
32​
33const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
34 executablePath: "wsl.exe",
35 args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
36 entryPath: "/app/bin.mjs",
37 cwd: "/app",
38 env: {},
39 extendEnv: false,
40 bootstrap: {
41 mode: "desktop",
42 noBrowser: true,
43 port: 3774,
44 host: "0.0.0.0",
45 desktopBootstrapToken: "bootstrap-token",
46 tailscaleServeEnabled: false,
47 tailscaleServePort: 443,
48 },
49 bootstrapDelivery: "stdin",
50 httpBaseUrl: new URL("http://127.0.0.1:3774"),
51 captureOutput: true,
52 preflightFailure: Option.none(),
53 runningDistro: "Ubuntu",
54};
55​
56const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
57 id: DesktopBackendManager.BackendInstanceId("wsl:default"),
58 label: Effect.succeed("WSL (default distro)"),
59 start: Effect.void,
60 stop: () => Effect.void,
61 currentConfig: Effect.succeedSome(readyWslConfig),
62 snapshot: Effect.succeed({
63 desiredRunning: true,
64 ready: true,
65 activePid: Option.some(123),
66 restartAttempt: 0,
67 restartScheduled: false,
68 }),
69 waitForReady: () => Effect.succeed(true),
70};
71​
72const backendConfigurationLayer = Layer.succeed(
73 DesktopBackendConfiguration.DesktopBackendConfiguration,
74 {
75 resolvePrimary: Effect.die("unexpected resolvePrimary"),
76 resolvePrimaryLabel: Effect.succeed("Windows"),
77 resolveWsl: () => Effect.die("unexpected resolveWsl"),
78 currentBootstrapToken: Effect.succeed("current-window-token"),
79 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
80);
81​
82const bootstrapsLayer = (instances: ReadonlyArray<DesktopBackendManager.DesktopBackendInstance>) =>
83 Layer.merge(DesktopBackendPool.layerTest([...instances]), backendConfigurationLayer);
84​
85describe("getLocalEnvironmentBootstraps", () => {
86 it.effect("hands out the current window's token to a backend launched with the secret", () =>
87 Effect.gen(function* () {
88 const result = yield* getLocalEnvironmentBootstraps.handler();
89​
90 assert.deepEqual(result, [
91 {
92 id: "wsl:default",
93 label: "WSL (Ubuntu)",
94 runningDistro: "Ubuntu",
95 httpBaseUrl: "http://127.0.0.1:3774/",
96 wsBaseUrl: "ws://127.0.0.1:3774/",
97 bootstrapToken: "current-window-token",
98 },
99 ]);
100 }).pipe(
101 Effect.provide(
102 bootstrapsLayer([
103 {
104 ...defaultWslInstance,
105 currentConfig: Effect.succeedSome({
106 ...readyWslConfig,
107 bootstrap: {
108 ...readyWslConfig.bootstrap,
109 desktopBootstrapSecret: "desktop-secret",
110 },
111 }),
112 },
113 ]),
114 ),
115 ),
116 );
117​
118 it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
119 const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
120 ...readyWslConfig,
121 preflightFailure: Option.some({
122 reason: "WSL probe timed out",
123 fatal: false,
124 retryLimit: 12,
125 }),
126 };
127 const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
128 ...defaultWslInstance,
129 currentConfig: Effect.succeedSome(retryingConfig),
130 snapshot: Effect.succeed({
131 desiredRunning: true,
132 ready: false,
133 activePid: Option.none(),
134 restartAttempt: 2,
135 restartScheduled: true,
136 }),
137 };
138​
139 return Effect.gen(function* () {
140 const result = yield* getLocalEnvironmentBootstraps.handler();
141 assert.deepEqual(result, [
142 {
143 id: "wsl:default",
144 label: "WSL (default distro)",
145 runningDistro: null,
146 httpBaseUrl: null,
147 wsBaseUrl: null,
148 },
149 ]);
150 }).pipe(Effect.provide(bootstrapsLayer([retryingInstance])));
151 });
152​
153 it.effect("omits a bounded transient bootstrap after retries stop", () => {
154 const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
155 ...defaultWslInstance,
156 currentConfig: Effect.succeedSome({
157 ...readyWslConfig,
158 preflightFailure: Option.some({
159 reason: "WSL probe timed out",
160 fatal: false,
161 retryLimit: 12,
162 }),
163 }),
164 snapshot: Effect.succeed({
165 desiredRunning: false,
166 ready: false,
167 activePid: Option.none(),
168 restartAttempt: 12,
169 restartScheduled: false,
170 }),
171 };
172​
173 return Effect.gen(function* () {
174 const result = yield* getLocalEnvironmentBootstraps.handler();
175 assert.deepEqual(result, []);
176 }).pipe(Effect.provide(bootstrapsLayer([stoppedInstance])));
177 });
178});
179​
180describe("getRelayTelemetryEnabled", () => {
181 it.effect("reads the desktop host opt-out before returning the renderer policy", () =>
182 Effect.gen(function* () {
183 assert.isFalse(
184 yield* getRelayTelemetryEnabled.handler().pipe(
185 Effect.provideService(HostProcess.Environment, {
186 T3CODE_TELEMETRY_ENABLED: "false",
187 }),
188 ),
189 );
190 assert.isTrue(
191 yield* getRelayTelemetryEnabled
192 .handler()
193 .pipe(Effect.provideService(HostProcess.Environment, {})),
194 );
195 }),
196 );
197});
198​
199describe("pickProjectFavicon", () => {
200 const pickerLayer = (
201 pickFiles: () => Effect.Effect<Array<string>>,
202 settings?: DesktopAppSettings.DesktopSettings,
203 ) =>
204 Layer.mergeAll(
205 Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),
206 Layer.mock(ElectronWindow.ElectronWindow)({
207 focusedMainOrFirst: Effect.succeedNone,
208 }),
209 DesktopAppSettings.layerTest(settings),
210 );
211​
212 it.effect("opens a single-image picker from the project directory", () =>
213 Effect.gen(function* () {
214 const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
215 const result = yield* pickProjectFavicon
216 .handler("/project")
217 .pipe(Effect.provide(pickerLayer(pickFiles)));
218​
219 assert.strictEqual(result, "/pictures/icon.png");
220 assert.deepEqual(pickFiles.mock.calls, [
221 [
222 {
223 owner: Option.none(),
224 defaultPath: Option.some("/project"),
225 multiple: false,
226 filters: [
227 {
228 name: "Images",
229 extensions: [
230 "avif",
231 "bmp",
232 "gif",
233 "ico",
234 "heic",
235 "heif",
236 "jpeg",
237 "jpg",
238 "png",
239 "svg",
240 "tif",
241 "tiff",
242 "webp",
243 "icns",
244 ],
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(HostProcess.Platform.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(HostProcess.Environment, {
291 HOME: home,
292 PATH: path.join(home, "empty"),
293 }),
294 Effect.provideService(HostProcess.Platform, "darwin"),
295 );
296 assert.include(editors, "cursor");
297 assert.include(editors, "vscode");
298 assert.include(editors, "webstorm");
299 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
300);