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

DesktopApp.ts

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