Open History to see the last commit
1import {
2 DesktopServerExposureModeSchema,
3 DesktopUpdateChannelSchema,
4 type DesktopServerExposureMode,
5 type DesktopUpdateChannel,
6} from "@t3tools/contracts";
7import { fromLenientJson } from "@t3tools/shared/schemaJson";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import * as SynchronizedRef from "effect/SynchronizedRef";
17
18import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
20import { isValidDistroName } from "../wsl/wslPathParsing.ts";
21
22export interface DesktopSettings {
23 readonly serverExposureMode: DesktopServerExposureMode;
24 readonly tailscaleServeEnabled: boolean;
25 readonly tailscaleServePort: number;
26 readonly updateChannel: DesktopUpdateChannel;
27 readonly updateChannelConfiguredByUser: boolean;
28 // Was a "local" | "wsl" swap mode in an earlier iteration of the WSL
29 // integration. We now run Windows and WSL backends side by side, so the
30 // setting is just whether the WSL backend should be running alongside the
31 // primary. Persisted documents that still carry the legacy `wslMode: "wsl"`
32 // value are migrated to `wslBackendEnabled: true` on load.
33 readonly wslBackendEnabled: boolean;
34 readonly wslDistro: string | null;
35 // When true (and wslBackendEnabled is also true) the desktop runs only
36 // the WSL backend as the primary, and the Windows-side Node backend is
37 // not started. Designed for users who develop entirely inside WSL and
38 // don't want a second backend process running. Defaults to false so
39 // existing setups stay on the parallel-backends behavior. Changing
40 // this requires a desktop restart because the pool's primary spec is
41 // chosen once at layer init.
42 readonly wslOnly: boolean;
43}
44
45export interface DesktopSettingsChange {
46 readonly settings: DesktopSettings;
47 readonly changed: boolean;
48}
49
50export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
51
52export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
53 serverExposureMode: "local-only",
54 tailscaleServeEnabled: false,
55 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
56 updateChannel: "latest",
57 updateChannelConfiguredByUser: false,
58 wslBackendEnabled: false,
59 wslDistro: null,
60 wslOnly: false,
61};
62
63const DesktopSettingsDocument = Schema.Struct({
64 serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
65 tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
66 tailscaleServePort: Schema.optionalKey(Schema.Number),
67 updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
68 updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
69 // Newer form of the WSL toggle. `wslMode` is still accepted on load so
70 // existing on-disk settings keep working; on the next persist we write the
71 // new boolean and the legacy key drops out.
72 wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
73 wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
74 wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
75 wslOnly: Schema.optionalKey(Schema.Boolean),
76});
77
78type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
79type Mutable<T> = { -readonly [K in keyof T]: T[K] };
80
81const DesktopSettingsJson = fromLenientJson(DesktopSettingsDocument);
82const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson);
83const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson);
84
85const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({
86 settings,
87 changed,
88});
89
90const DesktopSettingsWriteOperation = Schema.Literals([
91 "create-temporary-file-name",
92 "encode-document",
93 "create-directory",
94 "write-temporary-file",
95 "replace-settings-file",
96]);
97type DesktopSettingsWriteOperation = typeof DesktopSettingsWriteOperation.Type;
98
99export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSettingsWriteError>()(
100 "DesktopSettingsWriteError",
101 {
102 operation: DesktopSettingsWriteOperation,
103 path: Schema.String,
104 cause: Schema.Defect(),
105 },
106) {
107 override get message(): string {
108 return `Desktop settings write failed during ${this.operation} at ${this.path}.`;
109 }
110}
111
112export class DesktopAppSettings extends Context.Service<
113 DesktopAppSettings,
114 {
115 readonly load: Effect.Effect<DesktopSettings>;
116 readonly get: Effect.Effect<DesktopSettings>;
117 readonly setServerExposureMode: (
118 mode: DesktopServerExposureMode,
119 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
120 readonly setTailscaleServe: (input: {
121 readonly enabled: boolean;
122 readonly port: Option.Option<number>;
123 }) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
124 readonly setUpdateChannel: (
125 channel: DesktopUpdateChannel,
126 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
127 readonly setWslBackendEnabled: (
128 enabled: boolean,
129 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
130 readonly setWslDistro: (
131 distro: string | null,
132 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
133 readonly setWslOnly: (
134 enabled: boolean,
135 ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
136 readonly applyWslWindowsFallback: Effect.Effect<
137 DesktopSettingsChange,
138 DesktopSettingsWriteError
139 >;
140 readonly applyWslWindowsFallbackInMemory: Effect.Effect<DesktopSettingsChange>;
141 }
142>()("@t3tools/desktop/settings/DesktopAppSettings") {}
143
144export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
145 return {
146 ...DEFAULT_DESKTOP_SETTINGS,
147 updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
148 };
149}
150
151function normalizeTailscaleServePort(value: unknown): number {
152 return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
153 ? value
154 : DEFAULT_TAILSCALE_SERVE_PORT;
155}
156
157function normalizeWslDistro(value: unknown): string | null {
158 return typeof value === "string" && isValidDistroName(value) ? value : null;
159}
160
161function normalizeDesktopSettingsDocument(
162 parsed: DesktopSettingsDocument,
163 appVersion: string,
164): DesktopSettings {
165 const defaultSettings = resolveDefaultDesktopSettings(appVersion);
166 const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel);
167 const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
168 const updateChannelConfiguredByUser =
169 parsed.updateChannelConfiguredByUser === true ||
170 (isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
171
172 // Newer form wins when both are present; otherwise fall back to the legacy
173 // `wslMode === "wsl"` signal so users coming off the swap-mode build keep
174 // their WSL backend enabled.
175 const wslBackendEnabled =
176 parsed.wslBackendEnabled === true ||
177 (parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
178
179 return {
180 serverExposureMode:
181 parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
182 tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
183 tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
184 updateChannel: updateChannelConfiguredByUser
185 ? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
186 : defaultSettings.updateChannel,
187 updateChannelConfiguredByUser,
188 wslBackendEnabled,
189 wslDistro: normalizeWslDistro(parsed.wslDistro),
190 wslOnly: parsed.wslOnly === true,
191 };
192}
193
194function toDesktopSettingsDocument(
195 settings: DesktopSettings,
196 defaults: DesktopSettings,
197): DesktopSettingsDocument {
198 const document: Mutable<DesktopSettingsDocument> = {};
199
200 if (settings.serverExposureMode !== defaults.serverExposureMode) {
201 document.serverExposureMode = settings.serverExposureMode;
202 }
203 if (settings.tailscaleServeEnabled !== defaults.tailscaleServeEnabled) {
204 document.tailscaleServeEnabled = settings.tailscaleServeEnabled;
205 }
206 if (settings.tailscaleServePort !== defaults.tailscaleServePort) {
207 document.tailscaleServePort = settings.tailscaleServePort;
208 }
209 if (settings.updateChannel !== defaults.updateChannel) {
210 document.updateChannel = settings.updateChannel;
211 }
212 if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
213 document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
214 }
215 if (settings.wslBackendEnabled !== defaults.wslBackendEnabled) {
216 document.wslBackendEnabled = settings.wslBackendEnabled;
217 }
218 if (settings.wslDistro !== defaults.wslDistro) {
219 document.wslDistro = settings.wslDistro;
220 }
221 if (settings.wslOnly !== defaults.wslOnly) {
222 document.wslOnly = settings.wslOnly;
223 }
224
225 return document;
226}
227
228function setServerExposureMode(
229 settings: DesktopSettings,
230 requestedMode: DesktopServerExposureMode,
231): DesktopSettings {
232 return settings.serverExposureMode === requestedMode
233 ? settings
234 : {
235 ...settings,
236 serverExposureMode: requestedMode,
237 };
238}
239
240function setTailscaleServe(
241 settings: DesktopSettings,
242 input: { readonly enabled: boolean; readonly port: Option.Option<number> },
243): DesktopSettings {
244 const port = Option.match(input.port, {
245 onNone: () => settings.tailscaleServePort,
246 onSome: normalizeTailscaleServePort,
247 });
248 return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
249 ? settings
250 : {
251 ...settings,
252 tailscaleServeEnabled: input.enabled,
253 tailscaleServePort: port,
254 };
255}
256
257function setUpdateChannel(
258 settings: DesktopSettings,
259 requestedChannel: DesktopUpdateChannel,
260): DesktopSettings {
261 return settings.updateChannel === requestedChannel
262 ? settings
263 : {
264 ...settings,
265 updateChannel: requestedChannel,
266 updateChannelConfiguredByUser: true,
267 };
268}
269
270function setWslBackendEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings {
271 return settings.wslBackendEnabled === enabled
272 ? settings
273 : {
274 ...settings,
275 wslBackendEnabled: enabled,
276 };
277}
278
279function setWslDistro(settings: DesktopSettings, distro: string | null): DesktopSettings {
280 const normalized = normalizeWslDistro(distro);
281 return settings.wslDistro === normalized
282 ? settings
283 : {
284 ...settings,
285 wslDistro: normalized,
286 };
287}
288
289function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSettings {
290 return settings.wslOnly === enabled
291 ? settings
292 : {
293 ...settings,
294 wslOnly: enabled,
295 };
296}
297
298function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings {
299 return setWslOnly(setWslBackendEnabled(settings, false), false);
300}
301
302function readSettings(
303 fileSystem: FileSystem.FileSystem,
304 settingsPath: string,
305 appVersion: string,
306): Effect.Effect<DesktopSettings> {
307 const defaultSettings = resolveDefaultDesktopSettings(appVersion);
308
309 return fileSystem.readFileString(settingsPath).pipe(
310 Effect.option,
311 Effect.flatMap(
312 Option.match({
313 onNone: () => Effect.succeed(defaultSettings),
314 onSome: (raw) =>
315 decodeDesktopSettingsJson(raw).pipe(
316 Effect.map((parsed) => normalizeDesktopSettingsDocument(parsed, appVersion)),
317 Effect.orElseSucceed(() => defaultSettings),
318 ),
319 }),
320 ),
321 );
322}
323
324const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (input: {
325 readonly fileSystem: FileSystem.FileSystem;
326 readonly path: Path.Path;
327 readonly settingsPath: string;
328 readonly settings: DesktopSettings;
329 readonly defaultSettings: DesktopSettings;
330 readonly suffix: string;
331}): Effect.fn.Return<void, DesktopSettingsWriteError> {
332 const directory = input.path.dirname(input.settingsPath);
333 const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
334 const encoded = yield* encodeDesktopSettingsJson(
335 toDesktopSettingsDocument(input.settings, input.defaultSettings),
336 ).pipe(
337 Effect.mapError(
338 (cause) =>
339 new DesktopSettingsWriteError({
340 operation: "encode-document",
341 path: input.settingsPath,
342 cause,
343 }),
344 ),
345 );
346 yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
347 Effect.mapError(
348 (cause) =>
349 new DesktopSettingsWriteError({
350 operation: "create-directory",
351 path: directory,
352 cause,
353 }),
354 ),
355 );
356 yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
357 Effect.mapError(
358 (cause) =>
359 new DesktopSettingsWriteError({
360 operation: "write-temporary-file",
361 path: tempPath,
362 cause,
363 }),
364 ),
365 );
366 yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
367 Effect.mapError(
368 (cause) =>
369 new DesktopSettingsWriteError({
370 operation: "replace-settings-file",
371 path: input.settingsPath,
372 cause,
373 }),
374 ),
375 );
376});
377
378export const make = Effect.gen(function* () {
379 const environment = yield* DesktopEnvironment.DesktopEnvironment;
380 const fileSystem = yield* FileSystem.FileSystem;
381 const path = yield* Path.Path;
382 const crypto = yield* Crypto.Crypto;
383 const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
384
385 const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) =>
386 SynchronizedRef.modify(settingsRef, (settings) => {
387 const nextSettings = update(settings);
388 return [settingsChange(nextSettings, nextSettings !== settings), nextSettings] as const;
389 });
390
391 const persist = (
392 update: (settings: DesktopSettings) => DesktopSettings,
393 ): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
394 SynchronizedRef.modifyEffect(settingsRef, (settings) => {
395 const nextSettings = update(settings);
396 if (nextSettings === settings) {
397 return Effect.succeed([settingsChange(settings, false), settings] as const);
398 }
399
400 return crypto.randomUUIDv4.pipe(
401 Effect.map((uuid) => uuid.replace(/-/g, "")),
402 Effect.mapError(
403 (cause) =>
404 new DesktopSettingsWriteError({
405 operation: "create-temporary-file-name",
406 path: environment.desktopSettingsPath,
407 cause,
408 }),
409 ),
410 Effect.flatMap((suffix) =>
411 writeSettings({
412 fileSystem,
413 path,
414 settingsPath: environment.desktopSettingsPath,
415 settings: nextSettings,
416 defaultSettings: environment.defaultDesktopSettings,
417 suffix,
418 }),
419 ),
420 Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
421 );
422 });
423
424 return DesktopAppSettings.of({
425 get: SynchronizedRef.get(settingsRef),
426 load: Effect.gen(function* () {
427 const settings = yield* readSettings(
428 fileSystem,
429 environment.desktopSettingsPath,
430 environment.appVersion,
431 );
432 return yield* SynchronizedRef.setAndGet(settingsRef, settings);
433 }).pipe(Effect.withSpan("desktop.settings.load")),
434 setServerExposureMode: (mode) =>
435 persist((settings) => setServerExposureMode(settings, mode)).pipe(
436 Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
437 ),
438 setTailscaleServe: (input) =>
439 persist((settings) => setTailscaleServe(settings, input)).pipe(
440 Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
441 ),
442 setUpdateChannel: (channel) =>
443 persist((settings) => setUpdateChannel(settings, channel)).pipe(
444 Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
445 ),
446 setWslBackendEnabled: (enabled) =>
447 persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
448 Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
449 ),
450 setWslDistro: (distro) =>
451 persist((settings) => setWslDistro(settings, distro)).pipe(
452 Effect.withSpan("desktop.settings.setWslDistro", {
453 attributes: { distro: distro ?? null },
454 }),
455 ),
456 setWslOnly: (enabled) =>
457 persist((settings) => setWslOnly(settings, enabled)).pipe(
458 Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
459 ),
460 applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
461 Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
462 ),
463 applyWslWindowsFallbackInMemory: updateInMemory(applyWslWindowsFallback).pipe(
464 Effect.withSpan("desktop.settings.applyWslWindowsFallbackInMemory"),
465 ),
466 });
467});
468
469export const layer = Layer.effect(DesktopAppSettings, make);
470
471export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SETTINGS) =>
472 Layer.effect(
473 DesktopAppSettings,
474 Effect.gen(function* () {
475 const settingsRef = yield* SynchronizedRef.make(initialSettings);
476 const update = (f: (settings: DesktopSettings) => DesktopSettings) =>
477 SynchronizedRef.modify(settingsRef, (settings) => {
478 const nextSettings = f(settings);
479 return [
480 {
481 settings: nextSettings,
482 changed: nextSettings !== settings,
483 },
484 nextSettings,
485 ] as const;
486 });
487
488 return DesktopAppSettings.of({
489 get: SynchronizedRef.get(settingsRef),
490 load: SynchronizedRef.get(settingsRef),
491 setServerExposureMode: (mode) =>
492 update((settings) => setServerExposureMode(settings, mode)),
493 setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
494 setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
495 setWslBackendEnabled: (enabled) =>
496 update((settings) => setWslBackendEnabled(settings, enabled)),
497 setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
498 setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
499 applyWslWindowsFallback: update(applyWslWindowsFallback),
500 applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
501 });
502 }),
503 );