@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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