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

DesktopApp.ts

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