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

DesktopApp.ts

357 lines14.3 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 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 DesktopState from "./DesktopState.ts";
33import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
34import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
35import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts";
36import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
37import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
38import * as HostProcess from "@t3tools/shared/HostProcess";
39​
40const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
41const MAX_TCP_PORT = 65_535;
42const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
43​
44const makeDesktopRunId = Crypto.Crypto.pipe(
45 Effect.flatMap((crypto) => crypto.randomUUIDv4()),
46 Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
47);
48​
49export class DesktopBackendPortUnavailableError extends Schema.TaggedError<DesktopBackendPortUnavailableError>()(
50 "DesktopBackendPortUnavailableError",
51 {
52 startPort: Schema.Int,
53 maxPort: Schema.Int,
54 hosts: Schema.Array(Schema.String),
55 },
56) {
57 override get message(): string {
58 return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
59 }
61​
62export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedError<DesktopDevelopmentBackendPortRequiredError>()(
63 "DesktopDevelopmentBackendPortRequiredError",
64 {},
65) {
66 override get message(): string {
67 return "T3CODE_PORT is required in desktop development.";
68 }
70​
71const { logInfo: logBootstrapInfo, logWarning: logBootstrapWarning } =
72 DesktopObservability.makeComponentLogger("desktop-bootstrap");
73​
74const { logInfo: logStartupInfo, logError: logStartupError } =
75 DesktopObservability.makeComponentLogger("desktop-startup");
76​
77const resolveDesktopBackendPort = Effect.fn("resolveDesktopBackendPort")(function* (
78 configuredPort: Option.Option<number>,
79) {
80 if (Option.isSome(configuredPort)) {
81 return {
82 port: configuredPort.value,
83 selectedByScan: false,
84 } as const;
85 }
86​
87 const net = yield* NetService.NetService;
88 for (let port = DEFAULT_DESKTOP_BACKEND_PORT; port <= MAX_TCP_PORT; port += 1) {
89 let availableOnEveryHost = true;
90​
91 for (const host of DESKTOP_BACKEND_PORT_PROBE_HOSTS) {
92 if (!(yield* net.canListenOnHost(port, host))) {
93 availableOnEveryHost = false;
94 break;
95 }
96 }
97​
98 if (availableOnEveryHost) {
99 return {
100 port,
101 selectedByScan: true,
102 } as const;
103 }
104 }
105​
106 return yield* new DesktopBackendPortUnavailableError({
107 startPort: DEFAULT_DESKTOP_BACKEND_PORT,
108 maxPort: MAX_TCP_PORT,
109 hosts: DESKTOP_BACKEND_PORT_PROBE_HOSTS,
110 });
111});
112​
113const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupError")(function* (
114 stage: string,
115 error: unknown,
116): Effect.fn.Return<
117 void,
118 never,
119 | DesktopShutdown.DesktopShutdown
120 | DesktopState.DesktopState
121 | ElectronApp.ElectronApp
122 | ElectronDialog.ElectronDialog
123> {
124 const shutdown = yield* DesktopShutdown.DesktopShutdown;
125 const state = yield* DesktopState.DesktopState;
126 const electronApp = yield* ElectronApp.ElectronApp;
127 const electronDialog = yield* ElectronDialog.ElectronDialog;
128 const message = error instanceof Error ? error.message : String(error);
129 const detail =
130 error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
131 yield* logStartupError("fatal startup error", {
132 stage,
133 message,
134 ...(detail.length > 0 ? { detail } : {}),
135 });
136 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
137 if (!wasQuitting) {
138 yield* electronDialog.showErrorBox(
139 "T3 Code failed to start",
140 `Stage: ${stage}\n${message}${detail}`,
141 );
142 }
143 yield* shutdown.request;
144 yield* electronApp.quit;
145});
146​
147const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
148 handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
149​
150export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")(
151 function* (): Effect.fn.Return<void, never, DesktopBackendPool.DesktopBackendPool> {
152 const pool = yield* DesktopBackendPool.DesktopBackendPool;
153 const instances = yield* pool.list;
154 yield* Effect.forEach(
155 instances,
156 // Exceeds the backend's 30s graceful termination and output drain budget.
157 (instance) => instance.stop({ timeout: Duration.seconds(45) }),
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 yield* desktopWindow.showConnectingSplash;
244 yield* primaryBackend.start;
245 yield* logBootstrapInfo("bootstrap backend start requested");
246 yield* appActivation.start.pipe(
247 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
248 Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
249 );
250 yield* Effect.forkScoped(wslBackend.reconcile);
251 }
252}).pipe(Effect.withSpan("desktop.bootstrap"));
253​
254const startup = Effect.gen(function* () {
255 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
256 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
257 const electronApp = yield* ElectronApp.ElectronApp;
258 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
259 const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
260 const clerk = yield* DesktopClerk.DesktopClerk;
261 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
262 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
263 const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
264 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
265 const updates = yield* DesktopUpdates.DesktopUpdates;
266 const environment = yield* DesktopEnvironment.DesktopEnvironment;
267 const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
268​
269 yield* shellEnvironment.installIntoProcess;
270 const hasCommandLinePasswordStore =
271 preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
272 const linuxElectronOptions =
273 environment.platform === "linux" && !hasCommandLinePasswordStore
274 ? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess(
275 yield* HostProcess.HomeDirectory,
276 )
277 : preReadyElectronOptions.linux;
278 if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
279 if (
280 linuxElectronOptions.passwordStore !== null ||
281 preReadyElectronOptions.linux?.passwordStore !== null
282 ) {
283 yield* electronApp.removeCommandLineSwitch("password-store");
284 }
285 if (linuxElectronOptions.passwordStore !== null) {
286 yield* electronApp.appendCommandLineSwitch(
287 "password-store",
288 linuxElectronOptions.passwordStore,
289 );
290 }
291 }
292 const userDataPath = yield* appIdentity.resolveUserDataPath;
293 yield* electronApp.setPath("userData", userDataPath);
294 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
295 yield* desktopSettings.load;
296​
297 if (linuxElectronOptions !== null) {
298 yield* logStartupInfo("linux password store configured", {
299 passwordStore: hasCommandLinePasswordStore
300 ? "command-line"
301 : (linuxElectronOptions.passwordStore ?? "electron-default"),
302 xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
303 xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
304 });
305 }
306​
307 yield* appIdentity.configure;
308 yield* lifecycle.register;
309 yield* clerk.configure;
310​
311 yield* electronApp.whenReady.pipe(
312 Effect.withSpan("desktop.electron.whenReady"),
313 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
314 );
315 yield* logStartupInfo("app ready");
316 if (environment.platform === "linux") {
317 const selectedBackend = yield* safeStorage.selectedStorageBackend;
318 yield* logStartupInfo("safe storage ready", {
319 backend: Option.getOrElse(selectedBackend, () => "unknown"),
320 });
321 }
322 yield* appIdentity.configure;
323 yield* previewPasskeys.configure;
324 yield* applicationMenu.configure;
325 yield* updates.configure;
326 yield* DesktopRemoteUpdates.listen;
327 yield* linuxUrlHandler.register;
328 yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
329}).pipe(Effect.withSpan("desktop.startup"));
330​
331const scopedProgram = Effect.scoped(
332 Effect.gen(function* () {
333 const runId = yield* makeDesktopRunId;
334 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
335 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
336​
337 const shutdown = yield* DesktopShutdown.DesktopShutdown;
338 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
339​
340 yield* Effect.addFinalizer(() =>
341 // Stop every backend in the pool, not just the primary. The
342 // electronApp.quit() path can race ahead of the layer-scope
343 // cascade, so leaving the WSL instance for its parent scope
344 // finalizer means it gets hard-killed by the OS instead of
345 // receiving SIGTERM + grace.
346 stopAllPoolInstances().pipe(
347 Effect.ensuring(rendererHistory.shutdown),
348 Effect.ensuring(shutdown.markComplete),
349 ),
350 );
351​
352 yield* startup;
353 yield* shutdown.awaitRequest;
354 }),
355);
356​
357export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));