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

DesktopApp.ts

362 lines14.7 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 PreviewPasskeys from "../preview/Passkeys.ts";
21import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
22import * as DesktopEnvironment from "./DesktopEnvironment.ts";
23import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
24import * as DesktopLifecycle from "./DesktopLifecycle.ts";
25import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
26import * as DesktopObservability from "./DesktopObservability.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 const pool = yield* DesktopBackendPool.DesktopBackendPool;
151 const instances = yield* pool.list;
152 yield* Effect.forEach(
153 instances,
154 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
155 { concurrency: "unbounded" },
156 );
157 },
158);
159​
160const bootstrap = Effect.gen(function* () {
161 const state = yield* DesktopState.DesktopState;
162 const environment = yield* DesktopEnvironment.DesktopEnvironment;
163 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
164 const desktopWindow = yield* DesktopWindow.DesktopWindow;
165 const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
166 const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
167 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
168 const shutdown = yield* DesktopShutdown.DesktopShutdown;
169 // A quit during shell startup must prevent subsequent bootstrap work.
170 const awaitShellEnvironment = Effect.raceFirst(
171 shellEnvironment.installIntoProcess.pipe(Effect.as(true)),
172 shutdown.awaitRequest.pipe(Effect.as(false)),
173 );
174 yield* logBootstrapInfo("bootstrap start");
175​
176 const settings = yield* desktopSettings.get;
177 const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
178 yield* electronProtocol.registerDesktopProtocol({
179 scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
180 ...(environment.isDevelopment
181 ? { targetOrigin: Option.getOrThrow(environment.devServerUrl) }
182 : { assetDirectory: environment.clientAssetsDir }),
183 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
184 });
185 yield* installDesktopIpcHandlers();
186 yield* logBootstrapInfo("bootstrap ipc handlers registered");
187 // Before any window: the preload merges these items before the app reads storage.
188 yield* (yield* DesktopLegacyLocalStorage.DesktopLegacyLocalStorage).load(
189 yield* (yield* DesktopAppIdentity.DesktopAppIdentity).resolveUserDataPath,
190 );
191​
192 if (!settings.localEnvironmentEnabled) {
193 yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)");
194 if (!(yield* Ref.get(state.quitting))) {
195 yield* desktopWindow.createMainIfBackendReady;
196 }
197 // Snap Shot reads the desktop session variables the login shell provides.
198 if (!(yield* awaitShellEnvironment)) return;
199 yield* snapShot.initialize;
200 return;
201 }
202​
203 const pool = yield* DesktopBackendPool.DesktopBackendPool;
204 const primaryBackend = yield* pool.primary;
205 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
206 const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
207​
208 if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
209 return yield* new DesktopDevelopmentBackendPortRequiredError();
210 }
211​
212 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
213 const backendPort = backendPortSelection.port;
214 yield* logBootstrapInfo(
215 backendPortSelection.selectedByScan
216 ? "selected backend port via sequential scan"
217 : "using configured backend port",
218 {
219 port: backendPort,
220 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
221 },
222 );
223​
224 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
225 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
226 mode: settings.serverExposureMode,
227 });
228 }
229 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
230 const backendConfig = yield* serverExposure.backendConfig;
231 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
232 baseUrl: backendConfig.httpBaseUrl.href,
233 });
234 if (serverExposureState.endpointUrl) {
235 yield* logBootstrapInfo("bootstrap enabled network access", {
236 endpointUrl: serverExposureState.endpointUrl,
237 });
238 } else if (
239 settings.serverExposureMode === "network-accessible" &&
240 serverExposureState.mode === "local-only"
241 ) {
242 yield* logBootstrapWarning(
243 "bootstrap fell back to local-only because no advertised network host was available",
244 );
245 }
246​
247 if (!(yield* Ref.get(state.quitting))) {
248 const wslOnly = settings.wslOnly === true && settings.wslBackendEnabled === true;
249 // The main window waits for the primary backend. In wsl-only mode that is
250 // the WSL backend, which can be slow to cold-boot — show a "Connecting to
251 // WSL" splash immediately so the app feels responsive instead of presenting
252 // no window until WSL is ready. (Dual mode opens fast off the Windows
253 // primary, so no splash there.)
254 if (wslOnly) {
255 yield* desktopWindow.showConnectingSplash;
256 // Resolving the WSL primary's config runs wsl.exe.
257 if (!(yield* awaitShellEnvironment)) return;
258 }
259 yield* primaryBackend.start;
260 yield* logBootstrapInfo("bootstrap backend start requested");
261 // Publish the endpoint and token before preload reads them. Backend readiness
262 // retries a failed window open; WSL keeps its splash until then.
263 if (!wslOnly) {
264 yield* desktopWindow.ensureMain.pipe(
265 Effect.catch((error) =>
266 logBootstrapWarning("failed to open main window while the backend starts", {
267 error: error.message,
268 }),
269 ),
270 );
271 }
272 // Snap Shot reads the desktop session variables the login shell provides.
273 if (!(yield* awaitShellEnvironment)) return;
274 yield* snapShot.initialize;
275 yield* appActivation.start.pipe(
276 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
277 Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
278 );
279 yield* Effect.forkScoped(wslBackend.reconcile);
280 }
281}).pipe(Effect.withSpan("desktop.bootstrap"));
282​
283const startup = Effect.gen(function* () {
284 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
285 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
286 const electronApp = yield* ElectronApp.ElectronApp;
287 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
288 const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
289 const clerk = yield* DesktopClerk.DesktopClerk;
290 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
291 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
292 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
293 const updates = yield* DesktopUpdates.DesktopUpdates;
294 const environment = yield* DesktopEnvironment.DesktopEnvironment;
295 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
296 const state = yield* DesktopState.DesktopState;
297​
298 // Open the window while the shell loads; spawning work awaits the same run.
299 yield* Effect.forkScoped(shellEnvironment.installIntoProcess);
300 const userDataPath = yield* appIdentity.resolveUserDataPath;
301 yield* electronApp.setPath("userData", userDataPath);
302 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
303 yield* desktopSettings.load;
304​
305 yield* appIdentity.configure;
306 yield* lifecycle.register;
307 yield* clerk.configure;
308​
309 yield* electronApp.whenReady.pipe(
310 Effect.withSpan("desktop.electron.whenReady"),
311 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
312 );
313 yield* logStartupInfo("app ready");
314 if (environment.platform === "linux") {
315 yield* Effect.forkScoped(
316 shellEnvironment.secretStorageReady.pipe(
317 Effect.andThen(safeStorage.selectedStorageBackend),
318 Effect.flatMap((selectedBackend) =>
319 logStartupInfo("safe storage ready", {
320 backend: Option.getOrElse(selectedBackend, () => "unknown"),
321 }),
322 ),
323 ),
324 );
325 }
326 yield* appIdentity.configure;
327 yield* previewPasskeys.configure;
328 yield* applicationMenu.configure;
329 yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
330 if (yield* Ref.get(state.quitting)) return;
331 yield* updates.configure;
332 yield* DesktopRemoteUpdates.listen;
333 yield* linuxUrlHandler.register;
334}).pipe(Effect.withSpan("desktop.startup"));
335​
336const scopedProgram = Effect.scoped(
337 Effect.gen(function* () {
338 const runId = yield* makeDesktopRunId;
339 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
340 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
341​
342 const shutdown = yield* DesktopShutdown.DesktopShutdown;
343 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
344​
345 yield* Effect.addFinalizer(() =>
346 // Stop every backend in the pool, not just the primary. The
347 // electronApp.quit() path can race ahead of the layer-scope
348 // cascade, so leaving the WSL instance for its parent scope
349 // finalizer means it gets hard-killed by the OS instead of
350 // receiving SIGTERM + grace.
351 stopAllPoolInstances().pipe(
352 Effect.ensuring(rendererHistory.shutdown),
353 Effect.ensuring(shutdown.markComplete),
354 ),
355 );
356​
357 yield* startup;
358 yield* shutdown.awaitRequest;
359 }),
360);
361​
362export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));