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

DesktopApp.ts

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