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, 16:00 UTC
perf(desktop): provider checks no longer compete with server startup (#35712)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Nov 13, 2026 at 16:25 UTC
88d4d06ea325513d54879e956c311d21cffa7b29
14 files changed
+259
-67
apps/desktop/src/app/DesktopApp.test.ts
+15
-3
@@ -86,6 +86,7 @@ it.effect.each([false, true])(
86
const historyStarted = yield* Deferred.make<void>();
87
const releaseHistory = yield* Deferred.make<void>();
88
const quitting = yield* Ref.make(false);
89
+ const tokenRequested = yield* Deferred.make<void>();
90
const events: string[] = [];
91
const record = (event: string) =>
92
Effect.sync(() => {
@@ -144,7 +145,7 @@ it.effect.each([false, true])(
145
configure: Effect.void,
146
} as PreviewPasskeys.PreviewPasskeys["Service"]),
147
Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, {
147
- configure: Effect.void,
148
+ configure: record("menu"),
149
}),
150
Effect.provideService(DesktopUpdates.DesktopUpdates, {
151
configure: Effect.void,
@@ -222,7 +223,12 @@ it.effect.each([false, true])(
223
Layer.mock(DesktopClientSettings.DesktopClientSettings, {}),
224
Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}),
225
Layer.mock(DesktopIpc.DesktopIpc, {}),
225
- Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, {}),
226
+ Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, {
227
+ getBearerToken: record("token").pipe(
228
+ Effect.andThen(Deferred.succeed(tokenRequested, undefined)),
229
+ Effect.as("token"),
230
+ ),
231
+ }),
232
Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}),
233
Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }),
234
Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}),
@@ -253,7 +259,13 @@ it.effect.each([false, true])(
259
);
260
yield* Deferred.await(registrationStarted);
261
yield* Deferred.await(windowStarted);
256
- assert.deepEqual(events, ["identity", "ready", "identity", "backend", "window"]);
262
+ yield* Deferred.await(tokenRequested);
263
+ // The backend spawns before menus, and its token is minted without waiting for the renderer.
264
+ assert.deepEqual(
265
+ events.filter((event) => event !== "token"),
266
+ ["identity", "ready", "identity", "backend", "menu", "window"],
267
+ );
268
+ assert.isAbove(events.indexOf("token"), events.indexOf("backend"));
269
assert.isFalse(yield* Deferred.isDone(registrationStopped));
270
const shutdown = yield* DesktopShutdown.DesktopShutdown;
271
yield* shutdown.request;
apps/desktop/src/app/DesktopApp.ts
+81
-49
@@ -22,6 +22,7 @@ import * as PreviewPasskeys from "../preview/Passkeys.ts";
22
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
23
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
24
import * as DesktopHomeOwner from "../backend/DesktopHomeOwner.ts";
25
+import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts";
26
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
27
import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
28
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
@@ -168,13 +169,12 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")(
169
},
170
);
171
171
-const bootstrap = Effect.gen(function* () {
172
+// Spawns the local backend as soon as the protocol, IPC, and legacy storage that every window needs exist.
173
+const startLocalBackend = Effect.gen(function* () {
174
const state = yield* DesktopState.DesktopState;
175
const environment = yield* DesktopEnvironment.DesktopEnvironment;
176
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
177
const desktopWindow = yield* DesktopWindow.DesktopWindow;
176
- const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
177
- const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
178
yield* logBootstrapInfo("bootstrap start");
179
180
const settings = yield* desktopSettings.get;
@@ -193,32 +193,13 @@ const bootstrap = Effect.gen(function* () {
193
yield* (yield* DesktopAppIdentity.DesktopAppIdentity).resolveUserDataPath,
194
);
195
196
- yield* snapShot.initialize;
197
- // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has
198
- // no cached one. Without it, the command is left to Settings.
199
- const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch;
200
- yield* Effect.forkScoped(
201
- (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe(
202
- Effect.flatMap((found) =>
203
- found || environment.platform === "win32"
204
- ? installCli
205
- : logBootstrapInfo("skipped installing the t3 command without the shell PATH"),
206
- ),
207
- ),
208
- );
209
-
196
if (!settings.localEnvironmentEnabled) {
197
yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)");
212
- if (!(yield* Ref.get(state.quitting))) {
213
- yield* desktopWindow.createMainIfBackendReady;
214
- }
215
- return;
198
+ return false;
199
}
200
218
- const pool = yield* DesktopBackendPool.DesktopBackendPool;
219
- const primaryBackend = yield* pool.primary;
201
+ const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
202
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
221
- const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
203
204
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
205
return yield* new DesktopDevelopmentBackendPortRequiredError();
@@ -237,7 +218,8 @@ const bootstrap = Effect.gen(function* () {
218
"This T3 home is unavailable",
219
DesktopHomeOwner.homeOwnedMessage(owner),
220
);
240
- return yield* (yield* ElectronApp.ElectronApp).quit;
221
+ yield* (yield* ElectronApp.ElectronApp).quit;
222
+ return false;
223
}
224
225
const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
@@ -275,29 +257,73 @@ const bootstrap = Effect.gen(function* () {
257
);
258
}
259
278
- if (!(yield* Ref.get(state.quitting))) {
279
- if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
280
- yield* desktopWindow.showConnectingSplash;
281
- }
282
- yield* primaryBackend.start;
283
- yield* logBootstrapInfo("bootstrap backend start requested");
284
- // WSL-only fallback can change the primary endpoint before readiness.
285
- const config = yield* primaryBackend.currentConfig;
286
- if (
287
- !environment.isDevelopment &&
288
- !settings.wslOnly &&
289
- Option.isSome(config) &&
290
- Option.isNone(config.value.preflightFailure)
291
- ) {
292
- yield* desktopWindow.ensureMain;
260
+ if (yield* Ref.get(state.quitting)) {
261
+ return false;
262
+ }
263
+ if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
264
+ yield* desktopWindow.showConnectingSplash;
265
+ }
266
+ yield* primaryBackend.start;
267
+ yield* logBootstrapInfo("bootstrap backend start requested");
268
+ // The renderer asks for this token first; minting it at readiness saves a round trip.
269
+ yield* Effect.forkScoped(
270
+ (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe(
271
+ Effect.ignore,
272
+ ),
273
+ );
274
+ return true;
275
+}).pipe(Effect.withSpan("desktop.startLocalBackend"));
276
+
277
+const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: boolean) {
278
+ const state = yield* DesktopState.DesktopState;
279
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
280
+ const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
281
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
282
+ const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
283
+ const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
284
+ const settings = yield* desktopSettings.get;
285
+ if (settings.localEnvironmentEnabled && (!backendStarted || (yield* Ref.get(state.quitting)))) {
286
+ return;
287
+ }
288
+
289
+ yield* snapShot.initialize;
290
+ // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has
291
+ // no cached one. Without it, the command is left to Settings.
292
+ const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch;
293
+ yield* Effect.forkScoped(
294
+ (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe(
295
+ Effect.flatMap((found) =>
296
+ found || environment.platform === "win32"
297
+ ? installCli
298
+ : logBootstrapInfo("skipped installing the t3 command without the shell PATH"),
299
+ ),
300
+ ),
301
+ );
302
+
303
+ if (!settings.localEnvironmentEnabled) {
304
+ if (!(yield* Ref.get(state.quitting))) {
305
+ yield* desktopWindow.createMainIfBackendReady;
306
}
294
- yield* appActivation.start.pipe(
295
- Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
296
- Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
297
- );
298
- yield* Effect.forkScoped(wslBackend.reconcile);
307
+ return;
308
}
300
-}).pipe(Effect.withSpan("desktop.bootstrap"));
309
+
310
+ const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
311
+ // WSL-only fallback can change the primary endpoint before readiness.
312
+ const config = yield* primaryBackend.currentConfig;
313
+ if (
314
+ !environment.isDevelopment &&
315
+ !settings.wslOnly &&
316
+ Option.isSome(config) &&
317
+ Option.isNone(config.value.preflightFailure)
318
+ ) {
319
+ yield* desktopWindow.ensureMain;
320
+ }
321
+ yield* appActivation.start.pipe(
322
+ Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
323
+ Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
324
+ );
325
+ yield* Effect.forkScoped((yield* DesktopWslBackend.DesktopWslBackend).reconcile);
326
+});
327
328
const startup = Effect.gen(function* () {
329
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
@@ -369,14 +395,20 @@ const startup = Effect.gen(function* () {
395
});
396
}
397
yield* appIdentity.configure;
372
- yield* previewPasskeys.configure;
373
- yield* applicationMenu.configure;
398
+ // Sets canInstallUpdates, which the backend bootstrap payload reads.
399
yield* updates.configure;
400
yield* DesktopRemoteUpdates.listen;
401
yield* DesktopStartupRecovery.listen;
402
+ const backendStarted = yield* startLocalBackend.pipe(
403
+ Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)),
404
+ );
405
+ yield* previewPasskeys.configure;
406
+ yield* applicationMenu.configure;
407
// Portal identity is prepared pre-ready; MIME helpers must not gate the backend or window.
408
yield* linuxUrlHandler.register.pipe(Effect.forkScoped);
379
- yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
409
+ yield* bootstrap(backendStarted).pipe(
410
+ Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)),
411
+ );
412
}).pipe(Effect.withSpan("desktop.startup"));
413
414
const scopedProgram = Effect.scoped(
apps/desktop/src/backend/DesktopBackendManager.test.ts
+36
@@ -378,6 +378,42 @@ describe("DesktopBackendManager", () => {
378
}),
379
);
380
381
+ it.effect("becomes ready from the server ready line while HTTP probes stall", () =>
382
+ Effect.scoped(
383
+ Effect.gen(function* () {
384
+ const probeStarted = yield* Deferred.make<void>();
385
+ const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
386
+ const readyLine = encodeDesktopTelemetryControl({ version: 1, type: "serverReady" });
387
+ const instance = yield* makeTestInstance({
388
+ spawnerLayer: Layer.succeed(
389
+ ChildProcessSpawner.ChildProcessSpawner,
390
+ ChildProcessSpawner.make(() =>
391
+ Effect.succeed(
392
+ makeProcess({
393
+ getOutputFd: (fd) =>
394
+ fd === 5
395
+ ? Stream.fromEffect(Deferred.await(probeStarted)).pipe(
396
+ Stream.flatMap(() => Stream.encodeText(Stream.make(`${readyLine}\n`))),
397
+ )
398
+ : Stream.empty,
399
+ exitCode: Deferred.await(exit),
400
+ kill: () =>
401
+ Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
402
+ }),
403
+ ),
404
+ ),
405
+ ),
406
+ httpClientLayer: layerHttpClient(() =>
407
+ Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)),
408
+ ),
409
+ });
410
+
411
+ yield* instance.start;
412
+ assert.isTrue(yield* instance.waitForReady(Duration.seconds(15)));
413
+ }),
414
+ ),
415
+ );
416
+
417
it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
418
Effect.gen(function* () {
419
const handled = yield* Deferred.make<boolean>();
apps/desktop/src/backend/DesktopBackendManager.ts
+20
-13
@@ -1,5 +1,6 @@
1
import * as Brand from "effect/Brand";
2
import * as Cause from "effect/Cause";
3
+import * as Deferred from "effect/Deferred";
4
import * as Duration from "effect/Duration";
5
import * as Effect from "effect/Effect";
6
import * as Exit from "effect/Exit";
@@ -484,21 +485,23 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
485
),
486
);
487
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
488
+ const serverReady = yield* Deferred.make<void>();
489
490
yield* options.onStarted?.(handle.pid) ?? Effect.void;
489
- if (
490
- options.bootstrap.desktopTelemetryControlFd !== undefined &&
491
- options.onDesktopTelemetryControl !== undefined
492
- ) {
491
+ if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
492
const controlFd = options.bootstrap.desktopTelemetryControlFd;
494
- const handleControl = options.onDesktopTelemetryControl;
493
+ const handleControl = options.onDesktopTelemetryControl ?? (() => Effect.void);
494
yield* handle.getOutputFd(controlFd).pipe(
495
Stream.decodeText(),
496
Stream.splitLines,
497
Stream.filter((line) => line.trim().length > 0),
498
Stream.runForEach((line) =>
499
decodeDesktopTelemetryControlLine(line).pipe(
501
- Effect.flatMap(handleControl),
500
+ Effect.flatMap((message) =>
501
+ message.type === "serverReady"
502
+ ? Deferred.succeed(serverReady, undefined)
503
+ : handleControl(message),
504
+ ),
505
Effect.catchCause((cause) =>
506
logBackendProcessWarning("ignored invalid desktop telemetry control message", {
507
fd: controlFd,
@@ -570,14 +573,18 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
573
);
574
}
575
// Cold WSL boots across /mnt/c can exceed one probe budget; retry while the backend is alive.
576
+ // HTTP polling stays as the fallback for backends without the control fd, such as WSL.
577
const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() =>
574
- waitForHttpReady({
575
- executablePath: options.executablePath,
576
- entryPath: options.entryPath,
577
- cwd: options.cwd,
578
- httpBaseUrl: options.httpBaseUrl,
579
- timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
580
- }).pipe(
578
+ Effect.raceFirst(
579
+ waitForHttpReady({
580
+ executablePath: options.executablePath,
581
+ entryPath: options.entryPath,
582
+ cwd: options.cwd,
583
+ httpBaseUrl: options.httpBaseUrl,
584
+ timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
585
+ }),
586
+ Deferred.await(serverReady),
587
+ ).pipe(
588
Effect.flatMap(() => options.onReady?.(handle.pid) ?? Effect.void),
589
Effect.as(true),
590
Effect.catchTags({
apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts
+2
@@ -352,6 +352,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
352
return Queue.offer(updateCommitQueue, message).pipe(Effect.asVoid);
353
case "cancelDesktopUpdate":
354
return Queue.offer(updateCancellationQueue, message).pipe(Effect.asVoid);
355
+ case "serverReady":
356
+ return Effect.void;
357
}
358
};
359
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts
+1
@@ -363,6 +363,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => {
363
}).pipe(
364
Effect.provide(
365
Layer.mock(ProviderHost.ProviderHost)({
366
+ awaitServerReady: Effect.void,
367
paths: {
368
cwd: f.directory,
369
baseDir: f.directory,
apps/server/src/provider/ProviderHostLive.ts
+10
@@ -4,11 +4,13 @@ import * as Digest from "effect/crypto/Digest";
4
import * as Effect from "effect/Effect";
5
import * as FileSystem from "effect/FileSystem";
6
import * as Layer from "effect/Layer";
7
+import * as Option from "effect/Option";
8
9
import { resolveAttachmentPath } from "../attachmentStore.ts";
10
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
11
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
12
import * as ServerConfig from "../config.ts";
13
+import * as ServerLifecycleEvents from "../serverLifecycleEvents.ts";
14
import * as ServerSettings from "../serverSettings.ts";
15
import * as DocumentText from "./DocumentText.ts";
16
import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
@@ -22,6 +24,10 @@ export const layer = Layer.effect(
24
const secrets = yield* ServerSecretStore.ServerSecretStore;
25
const digest = yield* Digest.Digest;
26
const fileSystem = yield* FileSystem.FileSystem;
27
+ // Optional so standalone provider layers in tests probe at once.
28
+ const lifecycleEvents = yield* Effect.serviceOption(
29
+ ServerLifecycleEvents.ServerLifecycleEvents,
30
+ );
31
return ProviderHost.ProviderHost.of({
32
paths: {
33
cwd: config.cwd,
@@ -37,6 +43,10 @@ export const layer = Layer.effect(
43
subscribe: serverSettings.subscribeChanges,
44
},
45
shouldRunBackgroundWork: backgroundPolicy.shouldRunScopeWork,
46
+ ...Option.match(lifecycleEvents, {
47
+ onNone: () => ({}),
48
+ onSome: (events) => ({ awaitServerReady: events.awaitReady }),
49
+ }),
50
resolveAttachmentPath: (attachment) =>
51
resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment }),
52
// DocumentText owns the path-resolution span.
apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts
+6
@@ -187,6 +187,8 @@ export class DesktopTelemetryReceiver extends Context.Service<
187
readonly setDiagnosticsDemand: (
188
enabled: boolean,
189
) => Effect.Effect<void, DesktopTelemetryControlError>;
190
+ /** Tells the desktop parent that the server accepts requests, so it can skip readiness polling. */
191
+ readonly announceServerReady: Effect.Effect<void, DesktopTelemetryControlError>;
192
readonly requestDesktopUpdate: (
193
requestId: string,
194
trackSwitch?: DesktopTrackSwitch,
@@ -717,6 +719,9 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
719
health: Ref.get(health),
720
subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
721
setDiagnosticsDemand,
722
+ announceServerReady: sendControlMessage({ version: 1, type: "serverReady" }).pipe(
723
+ Effect.withSpan("DesktopTelemetryReceiver.announceServerReady"),
724
+ ),
725
requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(
726
function (requestId, trackSwitch) {
727
return sendControlMessage({
@@ -787,6 +792,7 @@ export const layerTest = (
792
setDiagnosticsDemand: Effect.fn("DesktopTelemetryReceiver.setDiagnosticsDemand")(function () {
793
return Effect.void;
794
}),
795
+ announceServerReady: Effect.void,
796
requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(function () {
797
return Effect.void;
798
}),
apps/server/src/server.ts
+12
@@ -899,6 +899,17 @@ const layerMakeServer = Layer.unwrap(
899
yield* startup.markHttpListening;
900
}),
901
);
902
+ const layerDesktopReadySignal = Layer.effectDiscard(
903
+ Effect.gen(function* () {
904
+ const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
905
+ const receiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
906
+ yield* startup.awaitCommandReady.pipe(
907
+ Effect.andThen(receiver.announceServerReady),
908
+ Effect.ignore,
909
+ Effect.forkScoped,
910
+ );
911
+ }),
912
+ );
913
const layerRuntimeState = Layer.effectDiscard(
914
Effect.gen(function* () {
915
yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
@@ -1279,6 +1290,7 @@ const layerMakeServer = Layer.unwrap(
1290
const layerServerApplication = Layer.mergeAll(
1291
layerRoutes,
1292
layerHttpListening,
1293
+ layerDesktopReadySignal,
1294
layerRuntimeState.pipe(Layer.provide(layerLauncher)),
1295
layerTailscaleServe,
1296
layerCloudDesiredLinkReconcile,
apps/server/src/serverLifecycleEvents.ts
+11
-1
@@ -1,5 +1,6 @@
1
import type { ServerLifecycleStreamEvent } from "@t3tools/contracts";
2
import * as Context from "effect/Context";
3
+import * as Deferred from "effect/Deferred";
4
import * as Effect from "effect/Effect";
5
import * as Layer from "effect/Layer";
6
import * as PubSub from "effect/PubSub";
@@ -22,11 +23,14 @@ export class ServerLifecycleEvents extends Context.Service<
23
readonly publish: (event: LifecycleEventInput) => Effect.Effect<ServerLifecycleStreamEvent>;
24
readonly snapshot: Effect.Effect<SnapshotState>;
25
readonly stream: Stream.Stream<ServerLifecycleStreamEvent>;
26
+ /** Completes once the first ready event is published. */
27
+ readonly awaitReady: Effect.Effect<void>;
28
}
29
>()("t3/serverLifecycleEvents") {}
30
31
const make = Effect.gen(function* () {
32
const pubsub = yield* PubSub.unbounded<ServerLifecycleStreamEvent>();
33
+ const ready = yield* Deferred.make<void>();
34
const state = yield* Ref.make<SnapshotState>({
35
sequence: 0,
36
events: [],
@@ -45,8 +49,14 @@ const make = Effect.gen(function* () {
49
...current.events.filter((entry) => entry.type !== nextEvent.type),
50
];
51
return [nextEvent, { sequence: nextSequence, events: nextEvents }] as const;
48
- }).pipe(Effect.tap((event) => PubSub.publish(pubsub, event))),
52
+ }).pipe(
53
+ Effect.tap((event) => PubSub.publish(pubsub, event)),
54
+ Effect.tap((event) =>
55
+ event.type === "ready" ? Deferred.succeed(ready, undefined) : Effect.void,
56
+ ),
57
+ ),
58
snapshot: Ref.get(state),
59
+ awaitReady: Deferred.await(ready),
60
get stream() {
61
return Stream.fromPubSub(pubsub);
62
},
packages/contracts/src/resourceTelemetry.ts
+8
@@ -383,7 +383,15 @@ export const DesktopTelemetryCancelDesktopUpdate = Schema.Struct({
383
});
384
export type DesktopTelemetryCancelDesktopUpdate = typeof DesktopTelemetryCancelDesktopUpdate.Type;
385
386
+/** The server accepts requests; the desktop treats this as backend readiness. */
387
+export const DesktopTelemetryServerReady = Schema.Struct({
388
+ version: Schema.Literal(1),
389
+ type: Schema.Literal("serverReady"),
390
+});
391
+export type DesktopTelemetryServerReady = typeof DesktopTelemetryServerReady.Type;
392
+
393
export const DesktopTelemetryControlMessage = Schema.Union([
394
+ DesktopTelemetryServerReady,
395
DesktopTelemetrySetDiagnosticsDemand,
396
DesktopTelemetrySetHostPowerIntervals,
397
DesktopTelemetryRequestDesktopUpdate,
packages/provider-core/src/server/ProviderHost.ts
+2
@@ -44,6 +44,8 @@ export class ProviderHost extends Context.Service<
44
readonly subscribe: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;
45
};
46
readonly shouldRunBackgroundWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
47
+ /** Completes once server startup finishes; first provider checks wait for it. */
48
+ readonly awaitServerReady?: Effect.Effect<void>;
49
/** Absolute attachment path, or null if the ID does not resolve inside attachmentsDir. */
50
readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
51
readonly resolveExtractedTextPath?: (path: string) => Effect.Effect<string | undefined>;
packages/provider-core/src/server/managedProvider.test.ts
+45
@@ -100,6 +100,7 @@ const refreshedSnapshotSecond: ServerProvider = {
100
function layerProviderHost(input: {
101
readonly runBackgroundWork: boolean;
102
readonly settings?: Pick<ProviderHost.ProviderHost["Service"], "settings">["settings"];
103
+ readonly awaitServerReady?: Effect.Effect<void>;
104
}) {
105
return Layer.succeed(
106
ProviderHost.ProviderHost,
@@ -118,6 +119,7 @@ function layerProviderHost(input: {
119
subscribe: Effect.succeed(Stream.empty),
120
},
121
shouldRunBackgroundWork: () => Effect.succeed(input.runBackgroundWork),
122
+ ...(input.awaitServerReady ? { awaitServerReady: input.awaitServerReady } : {}),
123
resolveAttachmentPath: () => null,
124
credentials: () => Effect.die("unused"),
125
}),
@@ -294,6 +296,49 @@ describe("makeManagedServerProvider", () => {
296
).pipe(Effect.provide(layerAlwaysRunTest)),
297
);
298
299
+ it.effect("holds the first provider check until server startup finishes", () =>
300
+ Effect.gen(function* () {
301
+ const serverReady = yield* Deferred.make<void>();
302
+ const checkStarted = yield* Deferred.make<void>();
303
+ const checkCalls = yield* Ref.make(0);
304
+ yield* Effect.scoped(
305
+ Effect.gen(function* () {
306
+ const provider = yield* makeManagedServerProvider<TestSettings>({
307
+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
308
+ getSettings: Effect.succeed({ enabled: true }),
309
+ streamSettings: Stream.empty,
310
+ haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
311
+ initialSnapshot: () => Effect.succeed(initialSnapshot),
312
+ checkProvider: Ref.update(checkCalls, (count) => count + 1).pipe(
313
+ Effect.andThen(Deferred.succeed(checkStarted, undefined)),
314
+ Effect.as(refreshedSnapshot),
315
+ ),
316
+ refreshInterval: "1 hour",
317
+ });
318
+
319
+ yield* TestClock.adjust("10 seconds");
320
+ assert.strictEqual(yield* Ref.get(checkCalls), 0);
321
+ assert.deepStrictEqual(yield* provider.getSnapshot, initialSnapshot);
322
+ assert.isTrue(yield* provider.isAwaitingFirstCheck!);
323
+
324
+ yield* Deferred.succeed(serverReady, undefined);
325
+ yield* Deferred.await(checkStarted);
326
+ assert.strictEqual(yield* Ref.get(checkCalls), 1);
327
+ }),
328
+ ).pipe(
329
+ Effect.provide(
330
+ Layer.mergeAll(
331
+ layerProviderHost({
332
+ runBackgroundWork: false,
333
+ awaitServerReady: Deferred.await(serverReady),
334
+ }),
335
+ TestClock.layer(),
336
+ ),
337
+ ),
338
+ );
339
+ }),
340
+ );
341
+
342
it.effect("skips periodic provider refreshes without foreground provider-status demand", () =>
343
Effect.scoped(
344
Effect.gen(function* () {
packages/provider-core/src/server/managedProvider.ts
+10
-1
@@ -437,7 +437,16 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
437
),
438
).pipe(Effect.forkScoped);
439
440
- yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
440
+ // Probes spawn provider CLIs; starting them during server startup slows the first client load.
441
+ yield* (host.awaitServerReady ?? Effect.void).pipe(
442
+ Effect.andThen(
443
+ // Read under the lock, so a settings check in flight cannot be overwritten with older settings.
444
+ refreshSemaphore.withPermits(1)(
445
+ Ref.get(settingsRef).pipe(
446
+ Effect.flatMap((settings) => applySnapshotBase(settings, { forceRefresh: true })),
447
+ ),
448
+ ),
449
+ ),
450
Effect.ignoreCause({ log: true }),
451
Effect.forkScoped,
452
);