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

DesktopApp.ts

470 lines19.1 KB

1import * as Cause from "effect/Cause";
2import * as Config from "effect/Config";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7import * as Stream from "effect/Stream";
8​
9import * as NetService from "@t3tools/shared/Net";
10import * as SecureRandom from "effect/crypto/SecureRandom";
11import * as ElectronApp from "../electron/ElectronApp.ts";
12import * as ElectronDialog from "../electron/ElectronDialog.ts";
13import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
14import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
15import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
16import * as DesktopAppActivation from "./DesktopAppActivation.ts";
17import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
18import * as DesktopClerk from "./DesktopClerk.ts";
19import * as DesktopCliShim from "./DesktopCliShim.ts";
20import * as DesktopCliCommand from "./DesktopCliCommand.ts";
21import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
22import * as DesktopWindow from "../window/DesktopWindow.ts";
23import * as PreviewPasskeys from "../preview/Passkeys.ts";
24import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
25import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
26import * as DesktopHomeOwner from "../backend/DesktopHomeOwner.ts";
27import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts";
28import * as DesktopEnvironment from "./DesktopEnvironment.ts";
29import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
30import * as DesktopLifecycle from "./DesktopLifecycle.ts";
31import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
32import * as DesktopObservability from "./DesktopObservability.ts";
33import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
34import * as DesktopShutdown from "./DesktopShutdown.ts";
35import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
36import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
37import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
38import * as DesktopStartupRecovery from "./DesktopStartupRecovery.ts";
39import * as DesktopState from "./DesktopState.ts";
40import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
41import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
42import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts";
43import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
44import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
45import * as HostProcess from "@t3tools/shared/HostProcess";
46import { msg } from "gt-i18n";
47import { m } from "../i18n/messages.ts";
48​
49const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
50const MAX_TCP_PORT = 65_535;
51const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
52​
53const LinuxDesktopSessionConfig = Config.all({
54 current: Config.String("XDG_CURRENT_DESKTOP").pipe(Config.option),
55 session: Config.String("XDG_SESSION_DESKTOP").pipe(Config.option),
56});
57​
58const makeDesktopRunId = SecureRandom.SecureRandom.pipe(
59 Effect.flatMap((random) => random.uuidV4()),
60 Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
61);
62​
63export class DesktopBackendPortUnavailableError extends Schema.TaggedError<DesktopBackendPortUnavailableError>()(
64 "DesktopBackendPortUnavailableError",
65 {
66 startPort: Schema.Int,
67 maxPort: Schema.Int,
68 hosts: Schema.Array(Schema.String),
69 },
70) {
71 override get message(): string {
72 return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
73 }
75​
76export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedError<DesktopDevelopmentBackendPortRequiredError>()(
77 "DesktopDevelopmentBackendPortRequiredError",
78 {},
79) {
80 override get message(): string {
81 return "T3CODE_PORT is required in desktop development.";
82 }
84​
85const { logInfo: logBootstrapInfo, logWarning: logBootstrapWarning } =
86 DesktopObservability.makeComponentLogger("desktop-bootstrap");
87​
88const { logInfo: logStartupInfo, logError: logStartupError } =
89 DesktopObservability.makeComponentLogger("desktop-startup");
90​
91const resolveDesktopBackendPort = Effect.fn("resolveDesktopBackendPort")(function* (
92 configuredPort: Option.Option<number>,
93) {
94 if (Option.isSome(configuredPort)) {
95 return {
96 port: configuredPort.value,
97 selectedByScan: false,
98 } as const;
99 }
100​
101 const net = yield* NetService.NetService;
102 for (let port = DEFAULT_DESKTOP_BACKEND_PORT; port <= MAX_TCP_PORT; port += 1) {
103 let availableOnEveryHost = true;
104​
105 for (const host of DESKTOP_BACKEND_PORT_PROBE_HOSTS) {
106 if (!(yield* net.canListenOnHost(port, host))) {
107 availableOnEveryHost = false;
108 break;
109 }
110 }
111​
112 if (availableOnEveryHost) {
113 return {
114 port,
115 selectedByScan: true,
116 } as const;
117 }
118 }
119​
120 return yield* new DesktopBackendPortUnavailableError({
121 startPort: DEFAULT_DESKTOP_BACKEND_PORT,
122 maxPort: MAX_TCP_PORT,
123 hosts: DESKTOP_BACKEND_PORT_PROBE_HOSTS,
124 });
125});
126​
127const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupError")(function* (
128 stage: string,
129 error: unknown,
130): Effect.fn.Return<
131 void,
132 never,
133 | DesktopShutdown.DesktopShutdown
134 | DesktopState.DesktopState
135 | ElectronApp.ElectronApp
136 | ElectronDialog.ElectronDialog
137> {
138 const shutdown = yield* DesktopShutdown.DesktopShutdown;
139 const state = yield* DesktopState.DesktopState;
140 const electronApp = yield* ElectronApp.ElectronApp;
141 const electronDialog = yield* ElectronDialog.ElectronDialog;
142 const message = error instanceof Error ? error.message : String(error);
143 const detail =
144 error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
145 yield* logStartupError("fatal startup error", {
146 stage,
147 message,
148 ...(detail.length > 0 ? { detail } : {}),
149 });
150 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
151 if (!wasQuitting) {
152 yield* electronDialog.showErrorBox(
153 m(msg("T3 Code failed to start")),
154 `Stage: ${stage}\n${message}${detail}`,
155 );
156 }
157 yield* shutdown.request;
158 yield* electronApp.quit;
159});
160​
161const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
162 handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
163​
164const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")(
165 function* (): Effect.fn.Return<void, never, DesktopBackendPool.DesktopBackendPool> {
166 const pool = yield* DesktopBackendPool.DesktopBackendPool;
167 const instances = yield* pool.list;
168 yield* Effect.forEach(
169 instances,
170 (instance) => instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }),
171 { concurrency: "unbounded" },
172 );
173 },
174);
175​
176// Spawns the local backend as soon as the protocol, IPC, and legacy storage that every window needs exist.
177/**
178 * The server reads T3CODE_FEATURE_FLAGS once at start, from the value cached at the last
179 * discovery. When the login shell now sets different flags, restart it so they apply.
180 */
181const restartOnFeatureFlagChange = Effect.fn("desktop.restartOnFeatureFlagChange")(function* (
182 backend: DesktopBackendManager.DesktopBackendInstance,
183) {
184 const state = yield* DesktopState.DesktopState;
185 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
186 let startedWith = (yield* HostProcess.Environment).T3CODE_FEATURE_FLAGS;
187 yield* shellEnvironment.updates.pipe(
188 Stream.filter((snapshot) => snapshot.discovered),
189 Stream.runForEach(
190 Effect.fnUntraced(function* (snapshot) {
191 const flags = snapshot.environment.T3CODE_FEATURE_FLAGS ?? undefined;
192 if (flags === startedWith || (yield* Ref.get(state.quitting))) return;
193 startedWith = flags;
194 yield* logBootstrapInfo("restarting backend for changed T3CODE_FEATURE_FLAGS");
195 yield* backend.stop();
196 yield* backend.start;
197 }),
198 ),
199 );
200});
201​
202const startLocalBackend = Effect.gen(function* () {
203 const state = yield* DesktopState.DesktopState;
204 const environment = yield* DesktopEnvironment.DesktopEnvironment;
205 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
206 const desktopWindow = yield* DesktopWindow.DesktopWindow;
207 yield* logBootstrapInfo("bootstrap start");
208​
209 const settings = yield* desktopSettings.get;
210 const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
211 yield* electronProtocol.registerDesktopProtocol({
212 scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
213 ...(environment.isDevelopment
214 ? { targetOrigin: Option.getOrThrow(environment.devServerUrl) }
215 : { assetDirectory: environment.clientAssetsDir }),
216 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
217 });
218 yield* installDesktopIpcHandlers();
219 yield* logBootstrapInfo("bootstrap ipc handlers registered");
220 // Before any window: the preload merges these items before the app reads storage.
221 yield* (yield* DesktopLegacyLocalStorage.DesktopLegacyLocalStorage).load(
222 yield* (yield* DesktopAppIdentity.DesktopAppIdentity).resolveUserDataPath,
223 );
224​
225 if (!settings.localEnvironmentEnabled) {
226 yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)");
227 return false;
228 }
229​
230 const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
231 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
232​
233 if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
234 return yield* new DesktopDevelopmentBackendPortRequiredError();
235 }
236​
237 // A backend started while another server holds this home's lock can only exit with code 78.
238 if (
239 !(settings.wslOnly && settings.wslBackendEnabled) &&
240 !(yield* DesktopHomeOwner.awaitHomeOwnershipRelease())
241 ) {
242 const owner = yield* DesktopHomeOwner.readLiveHomeOwner();
243 yield* logBootstrapWarning("bootstrap found another server owning the T3 home", {
244 owner: Option.getOrNull(owner),
245 });
246 yield* (yield* ElectronDialog.ElectronDialog).showErrorBox(
247 m(msg("This T3 home is unavailable")),
248 DesktopHomeOwner.homeOwnedMessage(owner),
249 );
250 yield* (yield* ElectronApp.ElectronApp).quit;
251 return false;
252 }
253​
254 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
255 const backendPort = backendPortSelection.port;
256 yield* logBootstrapInfo(
257 backendPortSelection.selectedByScan
258 ? "selected backend port via sequential scan"
259 : "using configured backend port",
260 {
261 port: backendPort,
262 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
263 },
264 );
265​
266 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
267 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
268 mode: settings.serverExposureMode,
269 });
270 }
271 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
272 const backendConfig = yield* serverExposure.backendConfig;
273 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
274 baseUrl: backendConfig.httpBaseUrl.href,
275 });
276 if (serverExposureState.endpointUrl) {
277 yield* logBootstrapInfo("bootstrap enabled network access", {
278 endpointUrl: serverExposureState.endpointUrl,
279 });
280 } else if (
281 settings.serverExposureMode === "network-accessible" &&
282 serverExposureState.mode === "local-only"
283 ) {
284 yield* logBootstrapWarning(
285 "bootstrap fell back to local-only because no advertised network host was available",
286 );
287 }
288​
289 if (yield* Ref.get(state.quitting)) {
290 return false;
291 }
292 if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
293 yield* desktopWindow.showConnectingSplash;
294 }
295 yield* primaryBackend.start;
296 yield* logBootstrapInfo("bootstrap backend start requested");
297 yield* Effect.forkScoped(restartOnFeatureFlagChange(primaryBackend));
298 // The renderer asks for this token first; minting it at readiness saves a round trip.
299 yield* Effect.forkScoped(
300 (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe(
301 Effect.ignore,
302 ),
303 );
304 return true;
305}).pipe(Effect.withSpan("desktop.startLocalBackend"));
306​
307const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: boolean) {
308 const state = yield* DesktopState.DesktopState;
309 const environment = yield* DesktopEnvironment.DesktopEnvironment;
310 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
311 const desktopWindow = yield* DesktopWindow.DesktopWindow;
312 const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
313 const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
314 const settings = yield* desktopSettings.get;
315 const startAppActivation = appActivation.start.pipe(
316 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
317 Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
318 );
319 if (settings.localEnvironmentEnabled && (!backendStarted || (yield* Ref.get(state.quitting)))) {
320 return;
321 }
322​
323 yield* snapShot.initialize;
324 // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has
325 // no cached one. Without it, the command is left to Settings.
326 const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch;
327 yield* Effect.forkScoped(
328 (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe(
329 Effect.flatMap((found) =>
330 found || environment.platform === "win32"
331 ? installCli
332 : logBootstrapInfo("skipped installing the t3 command without the shell PATH"),
333 ),
334 ),
335 );
336​
337 if (!settings.localEnvironmentEnabled) {
338 // The backend config refreshes the launcher when the local environment runs; an update may move the app.
339 yield* DesktopCliShim.install;
340 if (!(yield* Ref.get(state.quitting))) {
341 yield* desktopWindow.createMainIfBackendReady;
342 }
343 // `t3 <dir>` still reaches the renderer, which opens it on this machine's connected service.
344 yield* startAppActivation;
345 return;
346 }
347​
348 const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
349 const config = yield* primaryBackend.currentConfig;
350 if (
351 !environment.isDevelopment &&
352 Option.isSome(config) &&
353 Option.isNone(config.value.preflightFailure)
354 ) {
355 yield* desktopWindow.ensureMain;
356 }
357 yield* startAppActivation;
358 yield* Effect.forkScoped((yield* DesktopWslBackend.DesktopWslBackend).reconcile);
359});
360​
361const startup = Effect.gen(function* () {
362 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
363 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
364 const electronApp = yield* ElectronApp.ElectronApp;
365 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
366 const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
367 const clerk = yield* DesktopClerk.DesktopClerk;
368 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
369 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
370 const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
371 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
372 const updates = yield* DesktopUpdates.DesktopUpdates;
373 const environment = yield* DesktopEnvironment.DesktopEnvironment;
374 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
375​
376 yield* shellEnvironment.installIntoProcess;
377 const hasCommandLinePasswordStore =
378 preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
379 const linuxElectronOptions =
380 environment.platform === "linux" && !hasCommandLinePasswordStore
381 ? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess(
382 yield* HostProcess.HomeDirectory,
383 )
384 : preReadyElectronOptions.linux;
385 if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
386 if (
387 linuxElectronOptions.passwordStore !== null ||
388 preReadyElectronOptions.linux?.passwordStore !== null
389 ) {
390 yield* electronApp.removeCommandLineSwitch("password-store");
391 }
392 if (linuxElectronOptions.passwordStore !== null) {
393 yield* electronApp.appendCommandLineSwitch(
394 "password-store",
395 linuxElectronOptions.passwordStore,
396 );
397 }
398 }
399 const userDataPath = yield* appIdentity.resolveUserDataPath;
400 yield* electronApp.setPath("userData", userDataPath);
401 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
402 yield* desktopSettings.load;
403​
404 if (linuxElectronOptions !== null) {
405 const xdgDesktop = yield* LinuxDesktopSessionConfig;
406 yield* logStartupInfo("linux password store configured", {
407 passwordStore: hasCommandLinePasswordStore
408 ? "command-line"
409 : (linuxElectronOptions.passwordStore ?? "electron-default"),
410 xdgCurrentDesktop: Option.getOrNull(xdgDesktop.current),
411 xdgSessionDesktop: Option.getOrNull(xdgDesktop.session),
412 });
413 }
414​
415 yield* appIdentity.configure;
416 yield* lifecycle.register;
417 yield* clerk.configure;
418​
419 yield* electronApp.whenReady.pipe(
420 Effect.withSpan("desktop.electron.whenReady"),
421 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
422 );
423 yield* logStartupInfo("app ready");
424 if (environment.platform === "linux") {
425 const selectedBackend = yield* safeStorage.selectedStorageBackend;
426 yield* logStartupInfo("safe storage ready", {
427 backend: Option.getOrElse(selectedBackend, () => "unknown"),
428 });
429 }
430 yield* appIdentity.configure;
431 // Sets canInstallUpdates, which the backend bootstrap payload reads.
432 yield* updates.configure;
433 yield* DesktopRemoteUpdates.listen;
434 yield* DesktopStartupRecovery.listen;
435 const backendStarted = yield* startLocalBackend.pipe(
436 Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)),
437 );
438 yield* previewPasskeys.configure;
439 yield* applicationMenu.configure;
440 // Portal identity is prepared pre-ready; MIME helpers must not gate the backend or window.
441 yield* linuxUrlHandler.register.pipe(Effect.forkScoped);
442 yield* bootstrap(backendStarted).pipe(
443 Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)),
444 );
445}).pipe(Effect.withSpan("desktop.startup"));
446​
447const scopedProgram = Effect.scoped(
448 Effect.gen(function* () {
449 const runId = yield* makeDesktopRunId;
450 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
451 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
452​
453 const shutdown = yield* DesktopShutdown.DesktopShutdown;
454 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
455​
456 yield* Effect.addFinalizer(() =>
457 // Quit can outrun layer finalizers; stop pooled backends here so they receive SIGTERM before OS teardown.
458 stopAllPoolInstances().pipe(
459 Effect.ensuring(rendererHistory.shutdown),
460 Effect.ensuring(shutdown.markComplete),
461 Effect.withSpan("desktop.app.shutdown"),
462 ),
463 );
464​
465 yield* startup;
466 yield* shutdown.awaitRequest;
467 }),
468);
469​
470export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));