Open History to see the last commit
1import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
2import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, describe, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
11
12import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
13import * as DesktopConfig from "../app/DesktopConfig.ts";
14import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
15import * as DesktopServerExposure from "./DesktopServerExposure.ts";
16import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
17
18const encoder = new TextEncoder();
19
20const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
21const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
22 en0: [
23 {
24 address: "192.168.1.20",
25 family: "IPv4",
26 internal: false,
27 },
28 ],
29};
30
31const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
32 tailscale0: [
33 {
34 address: "100.90.1.2",
35 family: "IPv4",
36 internal: false,
37 },
38 ],
39};
40
41function mockSpawnerLayer(statusJson = "{}") {
42 return Layer.succeed(
43 ChildProcessSpawner.ChildProcessSpawner,
44 ChildProcessSpawner.make(() =>
45 Effect.succeed(
46 ChildProcessSpawner.makeHandle({
47 pid: ChildProcessSpawner.ProcessId(1),
48 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
49 isRunning: Effect.succeed(false),
50 kill: () => Effect.void,
51 unref: Effect.succeed(Effect.void),
52 stdin: Sink.drain,
53 stdout: Stream.make(encoder.encode(statusJson)),
54 stderr: Stream.empty,
55 all: Stream.empty,
56 getInputFd: () => Sink.drain,
57 getOutputFd: () => Stream.empty,
58 }),
59 ),
60 ),
61 );
62}
63
64function dieOnSpawnLayer() {
65 return Layer.succeed(
66 ChildProcessSpawner.ChildProcessSpawner,
67 ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
68 );
69}
70
71function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
72 return DesktopEnvironment.layer({
73 dirname: "/repo/apps/desktop/src",
74 homeDirectory: baseDir,
75 platform: "darwin",
76 processArch: "x64",
77 appVersion: "1.2.3",
78 appPath: "/repo",
79 isPackaged: true,
80 resourcesPath: "/missing/resources",
81 runningUnderArm64Translation: false,
82 }).pipe(
83 Layer.provide(
84 Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir, ...env })),
85 ),
86 );
87}
88
89function makeLayer(input: {
90 readonly baseDir: string;
91 readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
92 readonly env?: Record<string, string | undefined>;
93 readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
94 readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
95}) {
96 const env = { T3CODE_HOME: input.baseDir, ...input.env };
97 const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
98 const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
99 read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
100 });
101
102 return DesktopServerExposure.layer.pipe(
103 Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
104 Layer.provideMerge(NodeFileSystem.layer),
105 Layer.provideMerge(NodeHttpClient.layerUndici),
106 Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
107 Layer.provideMerge(networkLayer),
108 Layer.provideMerge(DesktopConfig.layerTest(env)),
109 Layer.provideMerge(environmentLayer),
110 );
111}
112
113const withHarness = <A, E, R>(
114 networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
115 effect: Effect.Effect<
116 A,
117 E,
118 | R
119 | DesktopEnvironment.DesktopEnvironment
120 | FileSystem.FileSystem
121 | DesktopServerExposure.DesktopServerExposure
122 | DesktopAppSettings.DesktopAppSettings
123 >,
124 env: Record<string, string | undefined> = {},
125 spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
126 desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
127) =>
128 Effect.gen(function* () {
129 const fileSystem = yield* FileSystem.FileSystem;
130 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
131 prefix: "t3-desktop-server-exposure-test-",
132 });
133 return yield* effect.pipe(
134 Effect.provide(
135 makeLayer({
136 baseDir,
137 networkInterfaces,
138 env,
139 ...(spawnerLayer ? { spawnerLayer } : {}),
140 ...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
141 }),
142 ),
143 );
144 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
145
146describe("DesktopServerExposure", () => {
147 it.effect("falls back to local-only without losing the requested network preference", () =>
148 withHarness(
149 emptyNetworkInterfaces,
150 Effect.gen(function* () {
151 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
152 const settings = yield* DesktopAppSettings.DesktopAppSettings;
153
154 yield* settings.setServerExposureMode("network-accessible");
155
156 const state = yield* serverExposure.configureFromSettings({ port: 4173 });
157 assert.equal(state.mode, "local-only");
158 assert.equal(state.endpointUrl, null);
159 assert.equal((yield* settings.get).serverExposureMode, "network-accessible");
160
161 const backendConfig = yield* serverExposure.backendConfig;
162 assert.equal(backendConfig.bindHost, "127.0.0.1");
163 assert.equal(backendConfig.httpBaseUrl.href, "http://127.0.0.1:4173/");
164 }),
165 ),
166 );
167
168 it.effect("returns a typed error when network access is explicitly unavailable", () =>
169 withHarness(
170 emptyNetworkInterfaces,
171 Effect.gen(function* () {
172 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
173 yield* serverExposure.configureFromSettings({ port: 4173 });
174
175 const error = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
176 assert.ok(error._tag === "DesktopServerExposureNoNetworkAddressError");
177 assert.equal(error.port, 4173);
178 }),
179 ),
180 );
181
182 it.effect("persists network-accessible mode and updates backend binding state", () =>
183 withHarness(
184 lanNetworkInterfaces,
185 Effect.gen(function* () {
186 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
187 const settings = yield* DesktopAppSettings.DesktopAppSettings;
188
189 yield* settings.load;
190 yield* serverExposure.configureFromSettings({ port: 4173 });
191
192 const change = yield* serverExposure.setMode("network-accessible");
193 assert.equal(change.requiresRelaunch, true);
194 assert.deepEqual(change.state, {
195 mode: "network-accessible",
196 endpointUrl: "http://192.168.1.20:4173",
197 advertisedHost: "192.168.1.20",
198 tailscaleServeEnabled: false,
199 tailscaleServePort: 443,
200 });
201
202 const backendConfig = yield* serverExposure.backendConfig;
203 assert.equal(backendConfig.bindHost, "0.0.0.0");
204 assert.equal(backendConfig.httpBaseUrl.href, "http://127.0.0.1:4173/");
205
206 const persisted = yield* settings.get;
207 assert.equal(persisted.serverExposureMode, "network-accessible");
208 }),
209 ),
210 );
211
212 it.effect("persists tailscale serve preferences atomically and reports no-op updates", () =>
213 withHarness(
214 emptyNetworkInterfaces,
215 Effect.gen(function* () {
216 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
217 const settings = yield* DesktopAppSettings.DesktopAppSettings;
218
219 yield* settings.load;
220 yield* serverExposure.configureFromSettings({ port: 4173 });
221
222 const changed = yield* serverExposure.setTailscaleServeEnabled({
223 enabled: true,
224 port: 8443,
225 });
226 assert.equal(changed.requiresRelaunch, true);
227 assert.equal(changed.state.tailscaleServeEnabled, true);
228 assert.equal(changed.state.tailscaleServePort, 8443);
229
230 const unchanged = yield* serverExposure.setTailscaleServeEnabled({
231 enabled: true,
232 port: 8443,
233 });
234 assert.equal(unchanged.requiresRelaunch, false);
235
236 const persisted = yield* settings.get;
237 assert.equal(persisted.tailscaleServeEnabled, true);
238 assert.equal(persisted.tailscaleServePort, 8443);
239 }),
240 ),
241 );
242
243 it.effect("preserves persistence request context and the settings failure chain", () => {
244 const diskFailure = new Error("disk exploded");
245 const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
246 operation: "replace-settings-file",
247 path: "/tmp/desktop-settings.json",
248 cause: diskFailure,
249 });
250 const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
251 get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
252 load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
253 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
254 setServerExposureMode: () => Effect.fail(settingsFailure),
255 setTailscaleServe: () => Effect.fail(settingsFailure),
256 setUpdateChannel: () => Effect.die("unexpected update channel change"),
257 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
258 setWslDistro: () => Effect.die("unexpected WSL distro change"),
259 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
260 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
261 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
262 } satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
263
264 return withHarness(
265 lanNetworkInterfaces,
266 Effect.gen(function* () {
267 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
268 yield* serverExposure.configureFromSettings({ port: 4173 });
269
270 const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
271 assert.instanceOf(
272 modeError,
273 DesktopServerExposure.DesktopServerExposureModePersistenceError,
274 );
275 assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
276 assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
277 assert.equal(modeError.mode, "network-accessible");
278 assert.strictEqual(modeError.cause, settingsFailure);
279 assert.strictEqual(modeError.cause.cause, diskFailure);
280 assert.equal(
281 modeError.message,
282 "Failed to persist desktop server exposure mode network-accessible.",
283 );
284 assert.notInclude(modeError.message, diskFailure.message);
285
286 const tailscaleError = yield* serverExposure
287 .setTailscaleServeEnabled({ enabled: true, port: 8443 })
288 .pipe(Effect.flip);
289 assert.instanceOf(
290 tailscaleError,
291 DesktopServerExposure.DesktopTailscaleServePersistenceError,
292 );
293 assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
294 assert.equal(tailscaleError.enabled, true);
295 assert.equal(tailscaleError.port, 8443);
296 assert.strictEqual(tailscaleError.cause, settingsFailure);
297 assert.strictEqual(tailscaleError.cause.cause, diskFailure);
298 assert.equal(
299 tailscaleError.message,
300 "Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
301 );
302 assert.notInclude(tailscaleError.message, diskFailure.message);
303 }),
304 {},
305 undefined,
306 settingsLayer,
307 );
308 });
309
310 it.effect("resolves advertised endpoints from the scoped runtime state", () =>
311 withHarness(
312 { ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
313 Effect.gen(function* () {
314 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
315 yield* serverExposure.configureFromSettings({ port: 4173 });
316 yield* serverExposure.setMode("network-accessible");
317
318 const endpoints = yield* serverExposure.getAdvertisedEndpoints;
319 assert.deepEqual(
320 endpoints.map((endpoint) => endpoint.httpBaseUrl),
321 ["http://127.0.0.1:4173/", "http://192.168.1.20:4173/", "http://100.90.1.2:4173/"],
322 );
323 }),
324 ),
325 );
326
327 it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
328 withHarness(
329 lanNetworkInterfaces,
330 Effect.gen(function* () {
331 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
332 yield* serverExposure.configureFromSettings({ port: 4173 });
333 // mode stays at default "local-only", tailscaleServeEnabled stays false.
334
335 const endpoints = yield* serverExposure.getAdvertisedEndpoints;
336 // Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
337 // would have crashed the test if the gate was missing.
338 assert.deepEqual(
339 endpoints.map((endpoint) => endpoint.httpBaseUrl),
340 ["http://127.0.0.1:4173/"],
341 );
342 }),
343 {},
344 dieOnSpawnLayer(),
345 ),
346 );
347
348 it.effect("uses ConfigProvider desktop exposure overrides", () =>
349 withHarness(
350 lanNetworkInterfaces,
351 Effect.gen(function* () {
352 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
353 yield* serverExposure.configureFromSettings({ port: 4173 });
354 const change = yield* serverExposure.setMode("network-accessible");
355
356 assert.equal(change.state.advertisedHost, "10.0.0.7");
357 assert.equal(change.state.endpointUrl, "http://10.0.0.7:4173");
358
359 const endpoints = yield* serverExposure.getAdvertisedEndpoints;
360 assert.deepEqual(
361 endpoints.map((endpoint) => endpoint.httpBaseUrl),
362 ["http://127.0.0.1:4173/", "http://10.0.0.7:4173/", "https://public.example.test/"],
363 );
364 }),
365 {
366 T3CODE_DESKTOP_LAN_HOST: "10.0.0.7",
367 T3CODE_DESKTOP_HTTPS_ENDPOINTS: "https://public.example.test",
368 },
369 ),
370 );
371
372 it.effect("advertises loopback, LAN, and configured manual endpoints from runtime state", () =>
373 withHarness(
374 lanNetworkInterfaces,
375 Effect.gen(function* () {
376 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
377 yield* serverExposure.configureFromSettings({ port: 3773 });
378 yield* serverExposure.setMode("network-accessible");
379
380 const endpoints = yield* serverExposure.getAdvertisedEndpoints;
381 assert.deepEqual(endpoints, [
382 {
383 id: "desktop-loopback:3773",
384 label: "This machine",
385 provider: {
386 id: "desktop-core",
387 label: "Desktop",
388 kind: "core",
389 isAddon: false,
390 },
391 httpBaseUrl: "http://127.0.0.1:3773/",
392 wsBaseUrl: "ws://127.0.0.1:3773/",
393 reachability: "loopback",
394 compatibility: {
395 hostedHttpsApp: "mixed-content-blocked",
396 desktopApp: "compatible",
397 },
398 source: "desktop-core",
399 status: "available",
400 description: "Loopback endpoint for this desktop app.",
401 },
402 {
403 id: "desktop-lan:http://192.168.1.20:3773",
404 label: "Local network",
405 provider: {
406 id: "desktop-core",
407 label: "Desktop",
408 kind: "core",
409 isAddon: false,
410 },
411 httpBaseUrl: "http://192.168.1.20:3773/",
412 wsBaseUrl: "ws://192.168.1.20:3773/",
413 reachability: "lan",
414 compatibility: {
415 hostedHttpsApp: "mixed-content-blocked",
416 desktopApp: "compatible",
417 },
418 source: "desktop-core",
419 status: "available",
420 isDefault: true,
421 description: "Reachable from devices on the same network.",
422 },
423 {
424 id: "manual:https://desktop.example.ts.net",
425 label: "Custom HTTPS",
426 provider: {
427 id: "manual",
428 label: "Manual",
429 kind: "manual",
430 isAddon: false,
431 },
432 httpBaseUrl: "https://desktop.example.ts.net/",
433 wsBaseUrl: "wss://desktop.example.ts.net/",
434 reachability: "public",
435 compatibility: {
436 hostedHttpsApp: "compatible",
437 desktopApp: "compatible",
438 },
439 source: "user",
440 status: "unknown",
441 description: "User-configured HTTPS endpoint for this desktop backend.",
442 },
443 {
444 id: "manual:http://desktop.example.test:3773",
445 label: "Custom endpoint",
446 provider: {
447 id: "manual",
448 label: "Manual",
449 kind: "manual",
450 isAddon: false,
451 },
452 httpBaseUrl: "http://desktop.example.test:3773/",
453 wsBaseUrl: "ws://desktop.example.test:3773/",
454 reachability: "public",
455 compatibility: {
456 hostedHttpsApp: "mixed-content-blocked",
457 desktopApp: "compatible",
458 },
459 source: "user",
460 status: "unknown",
461 description: "User-configured endpoint for this desktop backend.",
462 },
463 ]);
464 }),
465 {
466 T3CODE_DESKTOP_HTTPS_ENDPOINTS:
467 "https://desktop.example.ts.net,http://desktop.example.test:3773,not-a-url",
468 },
469 ),
470 );
471});