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