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

DesktopApp.ts

329 lines13.4 KB

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