Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9import * as SubscriptionRef from "effect/SubscriptionRef";
10import * as SynchronizedRef from "effect/SynchronizedRef";
11
12import * as FileSystem from "effect/FileSystem";
13import { HttpClient } from "effect/http";
14import { ChildProcessSpawner } from "effect/process";
15
16import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
17import * as DesktopBackendManager from "./DesktopBackendManager.ts";
18import * as DesktopObservability from "../app/DesktopObservability.ts";
19import * as DesktopState from "../app/DesktopState.ts";
20import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
21import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
22import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
23import * as DesktopWindow from "../window/DesktopWindow.ts";
24import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
25import * as ElectronDialog from "../electron/ElectronDialog.ts";
26import * as ElectronApp from "../electron/ElectronApp.ts";
27
28const { logWarning: logBackendPoolWarning } =
29 DesktopObservability.makeComponentLogger("desktop-backend-pool");
30
31export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
32export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
33export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
34export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
35export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
36
37export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
38 "DesktopBackendPoolInstanceAlreadyRegisteredError",
39 {
40 id: Schema.String,
41 },
42) {
43 override get message() {
44 return `Backend instance "${this.id}" is already registered in the pool.`;
45 }
46}
47
48export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError<DesktopBackendPoolCannotUnregisterPrimaryError>()(
49 "DesktopBackendPoolCannotUnregisterPrimaryError",
50 {},
51) {
52 override get message() {
53 return "Refusing to unregister the primary backend from the pool.";
54 }
55}
56
57export class DesktopBackendPool extends Context.Service<
58 DesktopBackendPool,
59 {
60 readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
61 readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
62 readonly primary: Effect.Effect<DesktopBackendInstance>;
63 readonly register: (
64 spec: BackendInstanceSpec,
65 ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
66 readonly unregister: (
67 id: BackendInstanceId,
68 ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
69 }
70>()("@t3tools/desktop/backend/DesktopBackendPool") {}
71
72export type BackendInstanceFactoryRequirements =
73 | FileSystem.FileSystem
74 | ChildProcessSpawner.ChildProcessSpawner
75 | HttpClient.HttpClient
76 | DesktopObservability.DesktopBackendOutputLogFactory
77 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
78 | DesktopBrowserHost.DesktopBrowserHost
79 | DesktopWslEnvironment.DesktopWslEnvironment;
80
81interface ActiveRegisteredInstance {
82 readonly _tag: "Active";
83 readonly instance: DesktopBackendInstance;
84 readonly scope: Option.Option<Scope.Closeable>;
85}
86
87interface ClosingRegisteredInstance {
88 readonly _tag: "Closing";
89 readonly done: Deferred.Deferred<void>;
90}
91
92type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
93
94type RegisterAction =
95 | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
96 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
97
98type UnregisterAction =
99 | { readonly _tag: "Absent" }
100 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
101 | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
102
103export const layer = Layer.effect(
104 DesktopBackendPool,
105 Effect.gen(function* () {
106 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
107 const desktopWindow = yield* DesktopWindow.DesktopWindow;
108 const electronDialog = yield* ElectronDialog.ElectronDialog;
109 const electronApp = yield* ElectronApp.ElectronApp;
110 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
111 const { primaryBackendStartup } = yield* DesktopState.DesktopState;
112 // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.
113 const layerScope = yield* Scope.Scope;
114 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
115
116 // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
117 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
118 function* (failure: DesktopBackendManager.PreflightFailure) {
119 const { reason, fatal } = failure;
120 if (!fatal) {
121 yield* logBackendPoolWarning(
122 "primary WSL preflight retry window exhausted; using Windows for this launch",
123 { reason },
124 );
125 yield* electronDialog.showErrorBox(
126 "WSL backend is still unavailable",
127 `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
128 );
129 yield* appSettings.applyWslWindowsFallbackInMemory;
130 return true;
131 }
132
133 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
134 reason,
135 });
136 yield* electronDialog.showErrorBox(
137 "WSL backend couldn't start",
138 `${reason}\n\nFalling 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.`,
139 );
140 // Clear wslOnly too so enabling WSL cannot restore a failed mode.
141 // Keep the in-memory fallback if persistence fails.
142 yield* appSettings.applyWslWindowsFallback.pipe(
143 Effect.catch((error) =>
144 logBackendPoolWarning(
145 "failed to persist Windows fallback after WSL preflight failure",
146 {
147 error: error.message,
148 },
149 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
150 ),
151 );
152 return true;
153 },
154 );
155
156 const primary = yield* DesktopBackendManager.makeBackendInstance({
157 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
158 // Resolve lazily: startup loads persisted settings after pool initialization.
159 label: configuration.resolvePrimaryLabel,
160 configResolve: configuration.resolvePrimary,
161 // Absorb window errors so readiness can reset restartAttempt.
162 onReady: (httpBaseUrl) =>
163 desktopWindow.handleBackendReady(httpBaseUrl).pipe(
164 // Only once the main window exists, so the recovery window never closes into nothing.
165 Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
166 Effect.catch((error) =>
167 logBackendPoolWarning("failed to open main window after backend readiness", {
168 error: error.message,
169 }),
170 ),
171 ),
172 onStartupFailure: (failure) =>
173 SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),
174 onShutdown: () => desktopWindow.handleBackendNotReady,
175 onPreflightFailed: handlePrimaryPreflightFailure,
176 onStateDirOwned: () =>
177 electronDialog
178 .showErrorBox(
179 "This T3 home is unavailable",
180 "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.",
181 )
182 .pipe(Effect.andThen(electronApp.quit)),
183 });
184
185 const instancesRef = yield* SynchronizedRef.make<
186 ReadonlyMap<BackendInstanceId, RegisteredInstance>
187 >(
188 new Map([
189 [
190 DesktopBackendManager.PRIMARY_INSTANCE_ID,
191 { _tag: "Active", instance: primary, scope: Option.none() },
192 ],
193 ]),
194 );
195
196 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
197 Effect.suspend(() =>
198 SynchronizedRef.modifyEffect(
199 instancesRef,
200 (
201 current,
202 ): Effect.Effect<
203 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
204 DesktopBackendPoolInstanceAlreadyRegisteredError
205 > => {
206 const existing = current.get(spec.id);
207 if (existing?._tag === "Active") {
208 return Effect.fail(
209 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
210 );
211 }
212 if (existing?._tag === "Closing") {
213 return Effect.succeed([
214 { _tag: "Wait", done: existing.done } as const,
215 current,
216 ] as const);
217 }
218 return Effect.gen(function* () {
219 // Provide the child Scope last so the captured pool Scope cannot shadow it and orphan stop/restart finalizers.
220 const instanceScope = yield* Scope.fork(layerScope, "sequential");
221 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
222 Scope.provide(instanceScope),
223 Effect.provide(factoryContext),
224 );
225 const next = new Map(current);
226 next.set(spec.id, {
227 _tag: "Active",
228 instance,
229 scope: Option.some(instanceScope),
230 });
231 return [
232 { _tag: "Registered", instance } as const,
233 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
234 ] as const;
235 });
236 },
237 ).pipe(
238 Effect.flatMap((result) =>
239 result._tag === "Registered"
240 ? Effect.succeed(result.instance)
241 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
242 ),
243 ),
244 );
245
246 const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn(
247 "DesktopBackendPool.unregister",
248 )(function* (id) {
249 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
250 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
251 }
252 const done = yield* Deferred.make<void>();
253 const action = yield* SynchronizedRef.modifyEffect(
254 instancesRef,
255 (
256 current,
257 ): Effect.Effect<
258 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
259 > => {
260 const entry = current.get(id);
261 if (entry === undefined) {
262 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
263 }
264 if (entry._tag === "Closing") {
265 return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const);
266 }
267 const next = new Map(current);
268 next.set(id, { _tag: "Closing", done });
269 return Effect.succeed([
270 { _tag: "Close", entry } as const,
271 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
272 ] as const);
273 },
274 );
275
276 if (action._tag === "Absent") return;
277 if (action._tag === "Wait") {
278 yield* Deferred.await(action.done);
279 return;
280 }
281
282 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
283 const closing = current.get(id);
284 if (closing?._tag !== "Closing" || closing.done !== done) {
285 return Effect.succeed([undefined, current] as const);
286 }
287 const next = new Map(current);
288 next.delete(id);
289 return Effect.succeed([
290 undefined,
291 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
292 ] as const);
293 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
294 yield* Option.match(action.entry.scope, {
295 onNone: () => Effect.void,
296 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
297 }).pipe(Effect.ensuring(finish));
298 });
299
300 return DesktopBackendPool.of({
301 get: Effect.fn("DesktopBackendPool.get")(function (id) {
302 return SynchronizedRef.get(instancesRef).pipe(
303 Effect.map((instances) => {
304 const entry = instances.get(id);
305 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
306 }),
307 );
308 }),
309 list: SynchronizedRef.get(instancesRef).pipe(
310 Effect.map((instances) =>
311 Array.from(instances.values()).flatMap((entry) =>
312 entry._tag === "Active" ? [entry.instance] : [],
313 ),
314 ),
315 ),
316 primary: Effect.succeed(primary),
317 register,
318 unregister,
319 });
320 }),
321);
322
323export const layerTest = (
324 instances: readonly DesktopBackendInstance[],
325): Layer.Layer<DesktopBackendPool> =>
326 Layer.effect(
327 DesktopBackendPool,
328 Effect.gen(function* () {
329 if (instances.length === 0) {
330 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
331 }
332 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
333 instances.map((instance) => [instance.id, instance] as const),
334 );
335 const primary = instances[0]!;
336 return DesktopBackendPool.of({
337 get: Effect.fn("DesktopBackendPool.get")(function (id) {
338 return Effect.succeed(Option.fromNullishOr(byId.get(id)));
339 }),
340 list: Effect.succeed(Array.from(byId.values())),
341 primary: Effect.succeed(primary),
342 register: Effect.fn("DesktopBackendPool.register")(function () {
343 return Effect.die("DesktopBackendPool.layerTest does not support register");
344 }),
345 unregister: Effect.fn("DesktopBackendPool.unregister")(function () {
346 return Effect.die("DesktopBackendPool.layerTest does not support unregister");
347 }),
348 });
349 }),
350 );