@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 427 lines 17.5 KB
Raw
1 import {
2 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
3 DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
4 } from "@t3tools/contracts";
5 import * as Context from "effect/Context";
6 import * as Deferred from "effect/Deferred";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Exit from "effect/Exit";
10 import * as FiberHandle from "effect/FiberHandle";
11 import * as Layer from "effect/Layer";
12 import * as Option from "effect/Option";
13 import * as Path from "effect/Path";
14 import * as Schedule from "effect/Schedule";
15 import * as Schema from "effect/Schema";
16 import * as Scope from "effect/Scope";
17 import * as SubscriptionRef from "effect/SubscriptionRef";
18 import * as SynchronizedRef from "effect/SynchronizedRef";
19 import { msg } from "gt-i18n";
20
21 import * as FileSystem from "effect/FileSystem";
22 import { HttpClient } from "effect/http";
23 import { ChildProcessSpawner } from "effect/process";
24
25 import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
26 import * as DesktopBackendManager from "./DesktopBackendManager.ts";
27 import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
28 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
29 import * as DesktopObservability from "../app/DesktopObservability.ts";
30 import * as DesktopState from "../app/DesktopState.ts";
31 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
32 import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
33 import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
34 import * as DesktopWindow from "../window/DesktopWindow.ts";
35 import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
36 import * as ElectronDialog from "../electron/ElectronDialog.ts";
37 import * as ElectronApp from "../electron/ElectronApp.ts";
38 import { m } from "../i18n/messages.ts";
39
40 const { logWarning: logBackendPoolWarning } =
41 DesktopObservability.makeComponentLogger("desktop-backend-pool");
42
43 const decodeServerRuntime = Schema.decodeUnknownEffect(
44 Schema.fromJsonString(Schema.Struct({ pid: Schema.Number, port: Schema.Number })),
45 );
46
47 export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
48 export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
49 export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
50 export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
51 export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
52
53 export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
54 "DesktopBackendPoolInstanceAlreadyRegisteredError",
55 {
56 id: Schema.String,
57 },
58 ) {
59 override get message() {
60 return `Backend instance "${this.id}" is already registered in the pool.`;
61 }
62 }
63
64 export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError<DesktopBackendPoolCannotUnregisterPrimaryError>()(
65 "DesktopBackendPoolCannotUnregisterPrimaryError",
66 {},
67 ) {
68 override get message() {
69 return "Refusing to unregister the primary backend from the pool.";
70 }
71 }
72
73 export class DesktopBackendPool extends Context.Service<
74 DesktopBackendPool,
75 {
76 readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
77 readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
78 readonly primary: Effect.Effect<DesktopBackendInstance>;
79 readonly register: (
80 spec: BackendInstanceSpec,
81 ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
82 readonly unregister: (
83 id: BackendInstanceId,
84 ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
85 }
86 >()("@t3tools/desktop/backend/DesktopBackendPool") {}
87
88 export type BackendInstanceFactoryRequirements =
89 | FileSystem.FileSystem
90 | ChildProcessSpawner.ChildProcessSpawner
91 | HttpClient.HttpClient
92 | DesktopObservability.DesktopBackendOutputLogFactory
93 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
94 | DesktopBrowserHost.DesktopBrowserHost
95 | DesktopWslEnvironment.DesktopWslEnvironment;
96
97 interface ActiveRegisteredInstance {
98 readonly _tag: "Active";
99 readonly instance: DesktopBackendInstance;
100 readonly scope: Option.Option<Scope.Closeable>;
101 }
102
103 interface ClosingRegisteredInstance {
104 readonly _tag: "Closing";
105 readonly done: Deferred.Deferred<void>;
106 }
107
108 type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
109
110 type RegisterAction =
111 | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
112 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
113
114 type UnregisterAction =
115 | { readonly _tag: "Absent" }
116 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
117 | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
118
119 export const layer = Layer.effect(
120 DesktopBackendPool,
121 Effect.gen(function* () {
122 const environment = yield* DesktopEnvironment.DesktopEnvironment;
123 const fileSystem = yield* FileSystem.FileSystem;
124 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
125 const desktopWindow = yield* DesktopWindow.DesktopWindow;
126 const electronDialog = yield* ElectronDialog.ElectronDialog;
127 const electronApp = yield* ElectronApp.ElectronApp;
128 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
129 const { primaryBackendStartup } = yield* DesktopState.DesktopState;
130 // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.
131 const layerScope = yield* Scope.Scope;
132 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
133 const homeOwnerContext = yield* Effect.context<
134 FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment
135 >();
136
137 const updateMarkerPath = environment.path.join(
138 environment.baseDir,
139 "runtime",
140 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
141 );
142 const serverRuntimePath = environment.path.join(environment.stateDir, "server-runtime.json");
143 // The server publishes its runtime after HTTP readiness. Until then an SSH launcher
144 // finds nothing to adopt, so dropping the marker earlier lets it start a competing server.
145 const releaseUpdateMarker = Effect.fn("desktop.backendPool.releaseUpdateMarker")(function* (
146 httpBaseUrl: URL,
147 pid: number,
148 ) {
149 const marker = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option);
150 if (Option.isNone(marker)) {
151 return;
152 }
153 yield* fileSystem.readFileString(serverRuntimePath).pipe(
154 Effect.flatMap(decodeServerRuntime),
155 Effect.map((runtime) => runtime.pid === pid && runtime.port === Number(httpBaseUrl.port)),
156 Effect.orElseSucceed(() => false),
157 Effect.repeat({
158 until: (published) => published,
159 schedule: Schedule.spaced(Duration.millis(100)),
160 }),
161 Effect.timeoutOption(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)),
162 );
163 // A later update may have replaced the marker; that handoff is not ours to end.
164 const current = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option);
165 if (Option.isSome(current) && current.value === marker.value) {
166 yield* fileSystem.remove(updateMarkerPath, { force: true }).pipe(Effect.ignore);
167 }
168 });
169 // One wait at a time: each run's shutdown or readiness ends the previous run's wait.
170 const updateMarkerWait = yield* FiberHandle.make<void>();
171
172 // The main window loads during startup and reads the primary endpoint once; a Windows fallback
173 // before the first readiness replaces the WSL endpoint it read.
174 let primaryWasReady = false;
175 let reloadMainOnReady = false;
176 const reloadStaleMain = Effect.suspend(() => {
177 primaryWasReady = true;
178 if (!reloadMainOnReady) return Effect.void;
179 reloadMainOnReady = false;
180 return desktopWindow.runMainContentsCommand("reload");
181 });
182
183 // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
184 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
185 function* (failure: DesktopBackendManager.PreflightFailure) {
186 const { reason, fatal } = failure;
187 if (!primaryWasReady) reloadMainOnReady = true;
188 if (!fatal) {
189 yield* logBackendPoolWarning(
190 "primary WSL preflight retry window exhausted; using Windows for this launch",
191 { reason },
192 );
193 yield* electronDialog.showErrorBox(
194 m(msg("WSL backend is still unavailable")),
195 `${reason}\n\n${m(msg("T3 Code will use the Windows backend for this launch and retry WSL the next time the app starts."))}`,
196 );
197 yield* appSettings.applyWslWindowsFallbackInMemory;
198 return true;
199 }
200
201 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
202 reason,
203 });
204 yield* electronDialog.showErrorBox(
205 m(msg("WSL backend couldn't start")),
206 `${reason}\n\n${m(msg("Falling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Sharing & access once the WSL distro is fixed."))}`,
207 );
208 // Clear wslOnly too so enabling WSL cannot restore a failed mode.
209 // Keep the in-memory fallback if persistence fails.
210 yield* appSettings.applyWslWindowsFallback.pipe(
211 Effect.catch((error) =>
212 logBackendPoolWarning(
213 "failed to persist Windows fallback after WSL preflight failure",
214 {
215 error: error.message,
216 },
217 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
218 ),
219 );
220 return true;
221 },
222 );
223
224 const primary = yield* DesktopBackendManager.makeBackendInstance({
225 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
226 // Resolve lazily: startup loads persisted settings after pool initialization.
227 label: configuration.resolvePrimaryLabel,
228 configResolve: configuration.resolvePrimary,
229 // Absorb window errors so readiness can reset restartAttempt.
230 onReady: (httpBaseUrl, pid) =>
231 FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe(
232 Effect.andThen(reloadStaleMain),
233 Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)),
234 // Only once the main window exists, so the recovery window never closes into nothing.
235 Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
236 Effect.catch((error) =>
237 logBackendPoolWarning("failed to open main window after backend readiness", {
238 error: error.message,
239 }),
240 ),
241 ),
242 onStartupFailure: (failure) =>
243 SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),
244 onShutdown: () =>
245 FiberHandle.clear(updateMarkerWait).pipe(
246 Effect.andThen(desktopWindow.handleBackendNotReady),
247 ),
248 onPreflightFailed: handlePrimaryPreflightFailure,
249 onStateDirOwned: () =>
250 DesktopHomeOwner.readLiveHomeOwner().pipe(
251 Effect.flatMap((owner) =>
252 electronDialog.showErrorBox(
253 m(msg("This T3 home is unavailable")),
254 DesktopHomeOwner.homeOwnedMessage(owner),
255 ),
256 ),
257 Effect.provideContext(homeOwnerContext),
258 Effect.andThen(electronApp.quit),
259 ),
260 });
261
262 const instancesRef = yield* SynchronizedRef.make<
263 ReadonlyMap<BackendInstanceId, RegisteredInstance>
264 >(
265 new Map([
266 [
267 DesktopBackendManager.PRIMARY_INSTANCE_ID,
268 { _tag: "Active", instance: primary, scope: Option.none() },
269 ],
270 ]),
271 );
272
273 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
274 Effect.suspend(() =>
275 SynchronizedRef.modifyEffect(
276 instancesRef,
277 (
278 current,
279 ): Effect.Effect<
280 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
281 DesktopBackendPoolInstanceAlreadyRegisteredError
282 > => {
283 const existing = current.get(spec.id);
284 if (existing?._tag === "Active") {
285 return Effect.fail(
286 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
287 );
288 }
289 if (existing?._tag === "Closing") {
290 return Effect.succeed([
291 { _tag: "Wait", done: existing.done } as const,
292 current,
293 ] as const);
294 }
295 return Effect.gen(function* () {
296 // Provide the child Scope last so the captured pool Scope cannot shadow it and orphan stop/restart finalizers.
297 const instanceScope = yield* Scope.fork(layerScope, "sequential");
298 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
299 Scope.provide(instanceScope),
300 Effect.provide(factoryContext),
301 );
302 const next = new Map(current);
303 next.set(spec.id, {
304 _tag: "Active",
305 instance,
306 scope: Option.some(instanceScope),
307 });
308 return [
309 { _tag: "Registered", instance } as const,
310 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
311 ] as const;
312 });
313 },
314 ).pipe(
315 Effect.flatMap((result) =>
316 result._tag === "Registered"
317 ? Effect.succeed(result.instance)
318 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
319 ),
320 ),
321 );
322
323 const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn(
324 "DesktopBackendPool.unregister",
325 )(function* (id) {
326 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
327 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
328 }
329 const done = yield* Deferred.make<void>();
330 const action = yield* SynchronizedRef.modifyEffect(
331 instancesRef,
332 (
333 current,
334 ): Effect.Effect<
335 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
336 > => {
337 const entry = current.get(id);
338 if (entry === undefined) {
339 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
340 }
341 if (entry._tag === "Closing") {
342 return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const);
343 }
344 const next = new Map(current);
345 next.set(id, { _tag: "Closing", done });
346 return Effect.succeed([
347 { _tag: "Close", entry } as const,
348 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
349 ] as const);
350 },
351 );
352
353 if (action._tag === "Absent") return;
354 if (action._tag === "Wait") {
355 yield* Deferred.await(action.done);
356 return;
357 }
358
359 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
360 const closing = current.get(id);
361 if (closing?._tag !== "Closing" || closing.done !== done) {
362 return Effect.succeed([undefined, current] as const);
363 }
364 const next = new Map(current);
365 next.delete(id);
366 return Effect.succeed([
367 undefined,
368 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
369 ] as const);
370 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
371 yield* Option.match(action.entry.scope, {
372 onNone: () => Effect.void,
373 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
374 }).pipe(Effect.ensuring(finish));
375 });
376
377 return DesktopBackendPool.of({
378 get: Effect.fn("DesktopBackendPool.get")(function (id) {
379 return SynchronizedRef.get(instancesRef).pipe(
380 Effect.map((instances) => {
381 const entry = instances.get(id);
382 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
383 }),
384 );
385 }),
386 list: SynchronizedRef.get(instancesRef).pipe(
387 Effect.map((instances) =>
388 Array.from(instances.values()).flatMap((entry) =>
389 entry._tag === "Active" ? [entry.instance] : [],
390 ),
391 ),
392 ),
393 primary: Effect.succeed(primary),
394 register,
395 unregister,
396 });
397 }),
398 );
399
400 export const layerTest = (
401 instances: readonly DesktopBackendInstance[],
402 ): Layer.Layer<DesktopBackendPool> =>
403 Layer.effect(
404 DesktopBackendPool,
405 Effect.gen(function* () {
406 if (instances.length === 0) {
407 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
408 }
409 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
410 instances.map((instance) => [instance.id, instance] as const),
411 );
412 const primary = instances[0]!;
413 return DesktopBackendPool.of({
414 get: Effect.fn("DesktopBackendPool.get")(function (id) {
415 return Effect.succeed(Option.fromNullishOr(byId.get(id)));
416 }),
417 list: Effect.succeed(Array.from(byId.values())),
418 primary: Effect.succeed(primary),
419 register: Effect.fn("DesktopBackendPool.register")(function () {
420 return Effect.die("DesktopBackendPool.layerTest does not support register");
421 }),
422 unregister: Effect.fn("DesktopBackendPool.unregister")(function () {
423 return Effect.die("DesktopBackendPool.layerTest does not support unregister");
424 }),
425 });
426 }),
427 );