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

DesktopApp.ts

471 lines19.2 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 yield* DesktopBackendPool.recoverLocalBackend;
238 // A backend started while another server holds this home's lock can only exit with code 78.
239 if (
240 !(settings.wslOnly && settings.wslBackendEnabled) &&
241 !(yield* DesktopHomeOwner.awaitHomeOwnershipRelease())
242 ) {
243 const owner = yield* DesktopHomeOwner.readLiveHomeOwner();
244 yield* logBootstrapWarning("bootstrap found another server owning the T3 home", {
245 owner: Option.getOrNull(owner),
246 });
247 yield* (yield* ElectronDialog.ElectronDialog).showErrorBox(
248 m(msg("This T3 home is unavailable")),
249 DesktopHomeOwner.homeOwnedMessage(owner),
250 );
251 yield* (yield* ElectronApp.ElectronApp).quit;
252 return false;
253 }
254​
255 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
256 const backendPort = backendPortSelection.port;
257 yield* logBootstrapInfo(
258 backendPortSelection.selectedByScan
259 ? "selected backend port via sequential scan"
260 : "using configured backend port",
261 {
262 port: backendPort,
263 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
264 },
265 );
266​
267 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
268 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
269 mode: settings.serverExposureMode,
270 });
271 }
272 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
273 const backendConfig = yield* serverExposure.backendConfig;
274 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
275 baseUrl: backendConfig.httpBaseUrl.href,
276 });
277 if (serverExposureState.endpointUrl) {
278 yield* logBootstrapInfo("bootstrap enabled network access", {
279 endpointUrl: serverExposureState.endpointUrl,
280 });
281 } else if (
282 settings.serverExposureMode === "network-accessible" &&
283 serverExposureState.mode === "local-only"
284 ) {
285 yield* logBootstrapWarning(
286 "bootstrap fell back to local-only because no advertised network host was available",
287 );
288 }
289​
290 if (yield* Ref.get(state.quitting)) {
291 return false;
292 }
293 if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
294 yield* desktopWindow.showConnectingSplash;
295 }
296 yield* primaryBackend.start;
297 yield* logBootstrapInfo("bootstrap backend start requested");
298 yield* Effect.forkScoped(restartOnFeatureFlagChange(primaryBackend));
299 // The renderer asks for this token first; minting it at readiness saves a round trip.
300 yield* Effect.forkScoped(
301 (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe(
302 Effect.ignore,
303 ),
304 );
305 return true;
306}).pipe(Effect.withSpan("desktop.startLocalBackend"));
307​
308const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: boolean) {
309 const state = yield* DesktopState.DesktopState;
310 const environment = yield* DesktopEnvironment.DesktopEnvironment;
311 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
312 const desktopWindow = yield* DesktopWindow.DesktopWindow;
313 const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
314 const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
315 const settings = yield* desktopSettings.get;
316 const startAppActivation = appActivation.start.pipe(
317 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
318 Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
319 );
320 if (settings.localEnvironmentEnabled && (!backendStarted || (yield* Ref.get(state.quitting)))) {
321 return;
322 }
323​
324 yield* snapShot.initialize;
325 // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has
326 // no cached one. Without it, the command is left to Settings.
327 const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch;
328 yield* Effect.forkScoped(
329 (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe(
330 Effect.flatMap((found) =>
331 found || environment.platform === "win32"
332 ? installCli
333 : logBootstrapInfo("skipped installing the t3 command without the shell PATH"),
334 ),
335 ),
336 );
337​
338 if (!settings.localEnvironmentEnabled) {
339 // The backend config refreshes the launcher when the local environment runs; an update may move the app.
340 yield* DesktopCliShim.install;
341 if (!(yield* Ref.get(state.quitting))) {
342 yield* desktopWindow.createMainIfBackendReady;
343 }
344 // `t3 <dir>` still reaches the renderer, which opens it on this machine's connected service.
345 yield* startAppActivation;
346 return;
347 }
348​
349 const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
350 const config = yield* primaryBackend.currentConfig;
351 if (
352 !environment.isDevelopment &&
353 Option.isSome(config) &&
354 Option.isNone(config.value.preflightFailure)
355 ) {
356 yield* desktopWindow.ensureMain;
357 }
358 yield* startAppActivation;
359 yield* Effect.forkScoped((yield* DesktopWslBackend.DesktopWslBackend).reconcile);
360});
361​
362const startup = Effect.gen(function* () {
363 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
364 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
365 const electronApp = yield* ElectronApp.ElectronApp;
366 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
367 const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
368 const clerk = yield* DesktopClerk.DesktopClerk;
369 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
370 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
371 const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
372 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
373 const updates = yield* DesktopUpdates.DesktopUpdates;
374 const environment = yield* DesktopEnvironment.DesktopEnvironment;
375 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
376​
377 yield* shellEnvironment.installIntoProcess;
378 const hasCommandLinePasswordStore =
379 preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
380 const linuxElectronOptions =
381 environment.platform === "linux" && !hasCommandLinePasswordStore
382 ? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess(
383 yield* HostProcess.HomeDirectory,
384 )
385 : preReadyElectronOptions.linux;
386 if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
387 if (
388 linuxElectronOptions.passwordStore !== null ||
389 preReadyElectronOptions.linux?.passwordStore !== null
390 ) {
391 yield* electronApp.removeCommandLineSwitch("password-store");
392 }
393 if (linuxElectronOptions.passwordStore !== null) {
394 yield* electronApp.appendCommandLineSwitch(
395 "password-store",
396 linuxElectronOptions.passwordStore,
397 );
398 }
399 }
400 const userDataPath = yield* appIdentity.resolveUserDataPath;
401 yield* electronApp.setPath("userData", userDataPath);
402 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
403 yield* desktopSettings.load;
404​
405 if (linuxElectronOptions !== null) {
406 const xdgDesktop = yield* LinuxDesktopSessionConfig;
407 yield* logStartupInfo("linux password store configured", {
408 passwordStore: hasCommandLinePasswordStore
409 ? "command-line"
410 : (linuxElectronOptions.passwordStore ?? "electron-default"),
411 xdgCurrentDesktop: Option.getOrNull(xdgDesktop.current),
412 xdgSessionDesktop: Option.getOrNull(xdgDesktop.session),
413 });
414 }
415​
416 yield* appIdentity.configure;
417 yield* lifecycle.register;
418 yield* clerk.configure;
419​
420 yield* electronApp.whenReady.pipe(
421 Effect.withSpan("desktop.electron.whenReady"),
422 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
423 );
424 yield* logStartupInfo("app ready");
425 if (environment.platform === "linux") {
426 const selectedBackend = yield* safeStorage.selectedStorageBackend;
427 yield* logStartupInfo("safe storage ready", {
428 backend: Option.getOrElse(selectedBackend, () => "unknown"),
429 });
430 }
431 yield* appIdentity.configure;
432 // Sets canInstallUpdates, which the backend bootstrap payload reads.
433 yield* updates.configure;
434 yield* DesktopRemoteUpdates.listen;
435 yield* DesktopStartupRecovery.listen;
436 const backendStarted = yield* startLocalBackend.pipe(
437 Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)),
438 );
439 yield* previewPasskeys.configure;
440 yield* applicationMenu.configure;
441 // Portal identity is prepared pre-ready; MIME helpers must not gate the backend or window.
442 yield* linuxUrlHandler.register.pipe(Effect.forkScoped);
443 yield* bootstrap(backendStarted).pipe(
444 Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)),
445 );
446}).pipe(Effect.withSpan("desktop.startup"));
447​
448const scopedProgram = Effect.scoped(
449 Effect.gen(function* () {
450 const runId = yield* makeDesktopRunId;
451 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
452 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
453​
454 const shutdown = yield* DesktopShutdown.DesktopShutdown;
455 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
456​
457 yield* Effect.addFinalizer(() =>
458 // Quit can outrun layer finalizers; stop pooled backends here so they receive SIGTERM before OS teardown.
459 stopAllPoolInstances().pipe(
460 Effect.ensuring(rendererHistory.shutdown),
461 Effect.ensuring(shutdown.markComplete),
462 Effect.withSpan("desktop.app.shutdown"),
463 ),
464 );
465​
466 yield* startup;
467 yield* shutdown.awaitRequest;
468 }),
469);
470​
471export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));