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

DesktopAppSettings.ts

580 lines20.8 KB

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