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

DesktopApp.ts

365 lines14.9 KB

1import * as Cause from "effect/Cause";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7​
8import * as NetService from "@t3tools/shared/Net";
9import * as Crypto from "effect/Crypto";
10import * as ElectronApp from "../electron/ElectronApp.ts";
11import * as ElectronDialog from "../electron/ElectronDialog.ts";
12import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
13import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
14import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
15import * as DesktopAppActivation from "./DesktopAppActivation.ts";
16import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
17import * as DesktopClerk from "./DesktopClerk.ts";
18import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
19import * as DesktopWindow from "../window/DesktopWindow.ts";
20import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
21import * as DesktopEnvironment from "./DesktopEnvironment.ts";
22import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
23import * as DesktopLifecycle from "./DesktopLifecycle.ts";
24import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
25import * as DesktopObservability from "./DesktopObservability.ts";
26import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
27import * as DesktopShutdown from "./DesktopShutdown.ts";
28import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
29import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
30import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
31import * as DesktopState from "./DesktopState.ts";
32import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
33import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
34import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts";
35import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
36import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
37​
38const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
39const MAX_TCP_PORT = 65_535;
40const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
41​
42const makeDesktopRunId = Crypto.Crypto.pipe(
43 Effect.flatMap((crypto) => crypto.randomUUIDv4),
44 Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
45);
46​
47export class DesktopBackendPortUnavailableError extends Schema.TaggedError<DesktopBackendPortUnavailableError>()(
48 "DesktopBackendPortUnavailableError",
49 {
50 startPort: Schema.Int,
51 maxPort: Schema.Int,
52 hosts: Schema.Array(Schema.String),
53 },
54) {
55 override get message(): string {
56 return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
57 }
59​
60export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedError<DesktopDevelopmentBackendPortRequiredError>()(
61 "DesktopDevelopmentBackendPortRequiredError",
62 {},
63) {
64 override get message(): string {
65 return "T3CODE_PORT is required in desktop development.";
66 }
68​
69const { logInfo: logBootstrapInfo, logWarning: logBootstrapWarning } =
70 DesktopObservability.makeComponentLogger("desktop-bootstrap");
71​
72const { logInfo: logStartupInfo, logError: logStartupError } =
73 DesktopObservability.makeComponentLogger("desktop-startup");
74​
75const resolveDesktopBackendPort = Effect.fn("resolveDesktopBackendPort")(function* (
76 configuredPort: Option.Option<number>,
77) {
78 if (Option.isSome(configuredPort)) {
79 return {
80 port: configuredPort.value,
81 selectedByScan: false,
82 } as const;
83 }
84​
85 const net = yield* NetService.NetService;
86 for (let port = DEFAULT_DESKTOP_BACKEND_PORT; port <= MAX_TCP_PORT; port += 1) {
87 let availableOnEveryHost = true;
88​
89 for (const host of DESKTOP_BACKEND_PORT_PROBE_HOSTS) {
90 if (!(yield* net.canListenOnHost(port, host))) {
91 availableOnEveryHost = false;
92 break;
93 }
94 }
95​
96 if (availableOnEveryHost) {
97 return {
98 port,
99 selectedByScan: true,
100 } as const;
101 }
102 }
103​
104 return yield* new DesktopBackendPortUnavailableError({
105 startPort: DEFAULT_DESKTOP_BACKEND_PORT,
106 maxPort: MAX_TCP_PORT,
107 hosts: DESKTOP_BACKEND_PORT_PROBE_HOSTS,
108 });
109});
110​
111const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupError")(function* (
112 stage: string,
113 error: unknown,
114): Effect.fn.Return<
115 void,
116 never,
117 | DesktopShutdown.DesktopShutdown
118 | DesktopState.DesktopState
119 | ElectronApp.ElectronApp
120 | ElectronDialog.ElectronDialog
121> {
122 const shutdown = yield* DesktopShutdown.DesktopShutdown;
123 const state = yield* DesktopState.DesktopState;
124 const electronApp = yield* ElectronApp.ElectronApp;
125 const electronDialog = yield* ElectronDialog.ElectronDialog;
126 const message = error instanceof Error ? error.message : String(error);
127 const detail =
128 error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
129 yield* logStartupError("fatal startup error", {
130 stage,
131 message,
132 ...(detail.length > 0 ? { detail } : {}),
133 });
134 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
135 if (!wasQuitting) {
136 yield* electronDialog.showErrorBox(
137 "T3 Code failed to start",
138 `Stage: ${stage}\n${message}${detail}`,
139 );
140 }
141 yield* shutdown.request;
142 yield* electronApp.quit;
143});
144​
145const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
146 handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
147​
148export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")(
149 function* (): Effect.fn.Return<void, never, DesktopBackendPool.DesktopBackendPool> {
150 // Stop every backend in the pool with a timeout to guarantee the quit
151 // path makes progress even if a backend hangs during teardown.
152 const pool = yield* DesktopBackendPool.DesktopBackendPool;
153 const instances = yield* pool.list;
154 yield* Effect.forEach(
155 instances,
156 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
157 { concurrency: "unbounded" },
158 );
159 },
160);
161​
162const bootstrap = Effect.gen(function* () {
163 const state = yield* DesktopState.DesktopState;
164 const environment = yield* DesktopEnvironment.DesktopEnvironment;
165 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
166 const desktopWindow = yield* DesktopWindow.DesktopWindow;
167 const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
168 const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
169 yield* logBootstrapInfo("bootstrap start");
170​
171 const settings = yield* desktopSettings.get;
172 // The renderer is served from the bundled client (or Vite in development)
173 // rather than through the local backend, so the window can open without one.
174 const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
175 yield* electronProtocol.registerDesktopProtocol({
176 scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
177 ...(environment.isDevelopment
178 ? { targetOrigin: Option.getOrThrow(environment.devServerUrl) }
179 : { assetDirectory: environment.clientAssetsDir }),
180 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
181 });
182 yield* installDesktopIpcHandlers();
183 yield* logBootstrapInfo("bootstrap ipc handlers registered");
184 // Before any window: the preload merges these items before the app reads storage.
185 yield* (yield* DesktopLegacyLocalStorage.DesktopLegacyLocalStorage).load(
186 yield* (yield* DesktopAppIdentity.DesktopAppIdentity).resolveUserDataPath,
187 );
188​
189 yield* snapShot.initialize;
190​
191 if (!settings.localEnvironmentEnabled) {
192 yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)");
193 if (!(yield* Ref.get(state.quitting))) {
194 yield* desktopWindow.createMainIfBackendReady;
195 }
196 return;
197 }
198​
199 const pool = yield* DesktopBackendPool.DesktopBackendPool;
200 const primaryBackend = yield* pool.primary;
201 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
202 const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
203​
204 if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
205 return yield* new DesktopDevelopmentBackendPortRequiredError();
206 }
207​
208 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
209 const backendPort = backendPortSelection.port;
210 yield* logBootstrapInfo(
211 backendPortSelection.selectedByScan
212 ? "selected backend port via sequential scan"
213 : "using configured backend port",
214 {
215 port: backendPort,
216 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
217 },
218 );
219​
220 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
221 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
222 mode: settings.serverExposureMode,
223 });
224 }
225 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
226 const backendConfig = yield* serverExposure.backendConfig;
227 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
228 baseUrl: backendConfig.httpBaseUrl.href,
229 });
230 if (serverExposureState.endpointUrl) {
231 yield* logBootstrapInfo("bootstrap enabled network access", {
232 endpointUrl: serverExposureState.endpointUrl,
233 });
234 } else if (
235 settings.serverExposureMode === "network-accessible" &&
236 serverExposureState.mode === "local-only"
237 ) {
238 yield* logBootstrapWarning(
239 "bootstrap fell back to local-only because no advertised network host was available",
240 );
241 }
242​
243 if (!(yield* Ref.get(state.quitting))) {
244 // The main window waits for the primary backend. In wsl-only mode that is
245 // the WSL backend, which can be slow to cold-boot — show a "Connecting to
246 // WSL" splash immediately so the app feels responsive instead of presenting
247 // no window until WSL is ready. (Dual mode opens fast off the Windows
248 // primary, so no splash there.)
249 if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
250 yield* desktopWindow.showConnectingSplash;
251 }
252 yield* primaryBackend.start;
253 yield* logBootstrapInfo("bootstrap backend start requested");
254 yield* appActivation.start.pipe(
255 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
256 Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
257 );
258 // Bring up the WSL backend if the user previously enabled it. The
259 // primary is already starting; reconcile fires off the WSL register
260 // in parallel rather than blocking primary readiness on a possibly
261 // slow first wsl.exe spawn.
262 yield* Effect.forkScoped(wslBackend.reconcile);
263 }
264}).pipe(Effect.withSpan("desktop.bootstrap"));
265​
266const startup = Effect.gen(function* () {
267 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
268 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
269 const electronApp = yield* ElectronApp.ElectronApp;
270 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
271 const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
272 const clerk = yield* DesktopClerk.DesktopClerk;
273 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
274 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
275 const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
276 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
277 const updates = yield* DesktopUpdates.DesktopUpdates;
278 const environment = yield* DesktopEnvironment.DesktopEnvironment;
279​
280 yield* shellEnvironment.installIntoProcess;
281 const hasCommandLinePasswordStore =
282 preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
283 const linuxElectronOptions =
284 environment.platform === "linux" && !hasCommandLinePasswordStore
285 ? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
286 : preReadyElectronOptions.linux;
287 if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
288 if (
289 linuxElectronOptions.passwordStore !== null ||
290 preReadyElectronOptions.linux?.passwordStore !== null
291 ) {
292 yield* electronApp.removeCommandLineSwitch("password-store");
293 }
294 if (linuxElectronOptions.passwordStore !== null) {
295 yield* electronApp.appendCommandLineSwitch(
296 "password-store",
297 linuxElectronOptions.passwordStore,
298 );
299 }
300 }
301 const userDataPath = yield* appIdentity.resolveUserDataPath;
302 yield* electronApp.setPath("userData", userDataPath);
303 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
304 yield* desktopSettings.load;
305​
306 if (linuxElectronOptions !== null) {
307 yield* logStartupInfo("linux password store configured", {
308 passwordStore: hasCommandLinePasswordStore
309 ? "command-line"
310 : (linuxElectronOptions.passwordStore ?? "electron-default"),
311 xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
312 xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
313 });
314 }
315​
316 yield* appIdentity.configure;
317 yield* lifecycle.register;
318 yield* clerk.configure;
319​
320 yield* electronApp.whenReady.pipe(
321 Effect.withSpan("desktop.electron.whenReady"),
322 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
323 );
324 yield* logStartupInfo("app ready");
325 if (environment.platform === "linux") {
326 const selectedBackend = yield* safeStorage.selectedStorageBackend;
327 yield* logStartupInfo("safe storage ready", {
328 backend: Option.getOrElse(selectedBackend, () => "unknown"),
329 });
330 }
331 yield* appIdentity.configure;
332 yield* applicationMenu.configure;
333 yield* updates.configure;
334 yield* DesktopRemoteUpdates.listen;
335 yield* linuxUrlHandler.register;
336 yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
337}).pipe(Effect.withSpan("desktop.startup"));
338​
339const scopedProgram = Effect.scoped(
340 Effect.gen(function* () {
341 const runId = yield* makeDesktopRunId;
342 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
343 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
344​
345 const shutdown = yield* DesktopShutdown.DesktopShutdown;
346 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
347​
348 yield* Effect.addFinalizer(() =>
349 // Stop every backend in the pool, not just the primary. The
350 // electronApp.quit() path can race ahead of the layer-scope
351 // cascade, so leaving the WSL instance for its parent scope
352 // finalizer means it gets hard-killed by the OS instead of
353 // receiving SIGTERM + grace.
354 stopAllPoolInstances().pipe(
355 Effect.ensuring(rendererHistory.shutdown),
356 Effect.ensuring(shutdown.markComplete),
357 ),
358 );
359​
360 yield* startup;
361 yield* shutdown.awaitRequest;
362 }),
363);
364​
365export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));