Skip to content

Commit 915ae9a

Browse files
t3dotggclaude
andcommitted
perf(desktop): reach a usable app sooner after launch
- Spawn the local backend right after the updater sets canInstallUpdates, before menus, passkeys, and SnapShot setup. - The server writes a serverReady line on the desktop control fd once it accepts requests. The desktop races it against the HTTP poll, which stays as the fallback for WSL and other backends without the fd. - Mint the local bearer token as soon as the backend is ready, before the renderer asks for it. - Hold each provider's first status check until server startup finishes, so provider CLIs do not compete with the first client load. The cached status shows until then. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2e741fc commit 915ae9a

13 files changed

Lines changed: 251 additions & 67 deletions

File tree

‎apps/desktop/src/app/DesktopApp.test.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ it.effect.each([false, true])(
8686
const historyStarted = yield* Deferred.make<void>();
8787
const releaseHistory = yield* Deferred.make<void>();
8888
const quitting = yield* Ref.make(false);
89+
const tokenRequested = yield* Deferred.make<void>();
8990
const events: string[] = [];
9091
const record = (event: string) =>
9192
Effect.sync(() => {
@@ -144,7 +145,7 @@ it.effect.each([false, true])(
144145
configure: Effect.void,
145146
} as PreviewPasskeys.PreviewPasskeys["Service"]),
146147
Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, {
147-
configure: Effect.void,
148+
configure: record("menu"),
148149
}),
149150
Effect.provideService(DesktopUpdates.DesktopUpdates, {
150151
configure: Effect.void,
@@ -222,7 +223,12 @@ it.effect.each([false, true])(
222223
Layer.mock(DesktopClientSettings.DesktopClientSettings, {}),
223224
Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}),
224225
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+
}),
226232
Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}),
227233
Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }),
228234
Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}),
@@ -253,7 +259,13 @@ it.effect.each([false, true])(
253259
);
254260
yield* Deferred.await(registrationStarted);
255261
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"));
257269
assert.isFalse(yield* Deferred.isDone(registrationStopped));
258270
const shutdown = yield* DesktopShutdown.DesktopShutdown;
259271
yield* shutdown.request;

‎apps/desktop/src/app/DesktopApp.ts‎

Lines changed: 81 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import * as PreviewPasskeys from "../preview/Passkeys.ts";
2222
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
2323
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
2424
import * as DesktopHomeOwner from "../backend/DesktopHomeOwner.ts";
25+
import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts";
2526
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
2627
import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
2728
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
@@ -168,13 +169,12 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")(
168169
},
169170
);
170171

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* () {
172174
const state = yield* DesktopState.DesktopState;
173175
const environment = yield* DesktopEnvironment.DesktopEnvironment;
174176
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
175177
const desktopWindow = yield* DesktopWindow.DesktopWindow;
176-
const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
177-
const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
178178
yield* logBootstrapInfo("bootstrap start");
179179

180180
const settings = yield* desktopSettings.get;
@@ -193,32 +193,13 @@ const bootstrap = Effect.gen(function* () {
193193
yield* (yield* DesktopAppIdentity.DesktopAppIdentity).resolveUserDataPath,
194194
);
195195

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-
210196
if (!settings.localEnvironmentEnabled) {
211197
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;
216199
}
217200

218-
const pool = yield* DesktopBackendPool.DesktopBackendPool;
219-
const primaryBackend = yield* pool.primary;
201+
const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
220202
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
221-
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
222203

223204
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
224205
return yield* new DesktopDevelopmentBackendPortRequiredError();
@@ -237,7 +218,8 @@ const bootstrap = Effect.gen(function* () {
237218
"This T3 home is unavailable",
238219
DesktopHomeOwner.homeOwnedMessage(owner),
239220
);
240-
return yield* (yield* ElectronApp.ElectronApp).quit;
221+
yield* (yield* ElectronApp.ElectronApp).quit;
222+
return false;
241223
}
242224

243225
const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
@@ -275,29 +257,73 @@ const bootstrap = Effect.gen(function* () {
275257
);
276258
}
277259

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;
293306
}
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;
299308
}
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+
});
301327

302328
const startup = Effect.gen(function* () {
303329
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
@@ -369,14 +395,20 @@ const startup = Effect.gen(function* () {
369395
});
370396
}
371397
yield* appIdentity.configure;
372-
yield* previewPasskeys.configure;
373-
yield* applicationMenu.configure;
398+
// Sets canInstallUpdates, which the backend bootstrap payload reads.
374399
yield* updates.configure;
375400
yield* DesktopRemoteUpdates.listen;
376401
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;
377407
// Portal identity is prepared pre-ready; MIME helpers must not gate the backend or window.
378408
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+
);
380412
}).pipe(Effect.withSpan("desktop.startup"));
381413

382414
const scopedProgram = Effect.scoped(

‎apps/desktop/src/backend/DesktopBackendManager.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,42 @@ describe("DesktopBackendManager", () => {
387387
),
388388
);
389389

390+
it.effect("becomes ready from the server ready line while HTTP probes stall", () =>
391+
Effect.scoped(
392+
Effect.gen(function* () {
393+
const probeStarted = yield* Deferred.make<void>();
394+
const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
395+
const readyLine = encodeDesktopTelemetryControl({ version: 1, type: "serverReady" });
396+
const instance = yield* makeTestInstance({
397+
spawnerLayer: Layer.succeed(
398+
ChildProcessSpawner.ChildProcessSpawner,
399+
ChildProcessSpawner.make(() =>
400+
Effect.succeed(
401+
makeProcess({
402+
getOutputFd: (fd) =>
403+
fd === 5
404+
? Stream.fromEffect(Deferred.await(probeStarted)).pipe(
405+
Stream.flatMap(() => Stream.encodeText(Stream.make(`${readyLine}\n`))),
406+
)
407+
: Stream.empty,
408+
exitCode: Deferred.await(exit),
409+
kill: () =>
410+
Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
411+
}),
412+
),
413+
),
414+
),
415+
httpClientLayer: layerHttpClient(() =>
416+
Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)),
417+
),
418+
});
419+
420+
yield* instance.start;
421+
assert.isTrue(yield* instance.waitForReady(Duration.seconds(15)));
422+
}),
423+
),
424+
);
425+
390426
it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
391427
Effect.scoped(
392428
Effect.gen(function* () {

‎apps/desktop/src/backend/DesktopBackendManager.ts‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as Brand from "effect/Brand";
22
import * as Cause from "effect/Cause";
3+
import * as Deferred from "effect/Deferred";
34
import * as Duration from "effect/Duration";
45
import * as Effect from "effect/Effect";
56
import * as Exit from "effect/Exit";
@@ -484,21 +485,23 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
484485
),
485486
);
486487
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
488+
const serverReady = yield* Deferred.make<void>();
487489

488490
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) {
493492
const controlFd = options.bootstrap.desktopTelemetryControlFd;
494-
const handleControl = options.onDesktopTelemetryControl;
493+
const handleControl = options.onDesktopTelemetryControl ?? (() => Effect.void);
495494
yield* handle.getOutputFd(controlFd).pipe(
496495
Stream.decodeText(),
497496
Stream.splitLines,
498497
Stream.filter((line) => line.trim().length > 0),
499498
Stream.runForEach((line) =>
500499
decodeDesktopTelemetryControlLine(line).pipe(
501-
Effect.flatMap(handleControl),
500+
Effect.flatMap((message) =>
501+
message.type === "serverReady"
502+
? Deferred.succeed(serverReady, undefined)
503+
: handleControl(message),
504+
),
502505
Effect.catchCause((cause) =>
503506
logBackendProcessWarning("ignored invalid desktop telemetry control message", {
504507
fd: controlFd,
@@ -570,14 +573,18 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
570573
);
571574
}
572575
// 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.
573577
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(
581588
Effect.flatMap(() => options.onReady?.() ?? Effect.void),
582589
Effect.as(true),
583590
Effect.catchTags({

‎apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
352352
return Queue.offer(updateCommitQueue, message).pipe(Effect.asVoid);
353353
case "cancelDesktopUpdate":
354354
return Queue.offer(updateCancellationQueue, message).pipe(Effect.asVoid);
355+
case "serverReady":
356+
return Effect.void;
355357
}
356358
};
357359
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (

‎apps/server/src/provider/ProviderHostLive.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ import * as Digest from "effect/crypto/Digest";
44
import * as Effect from "effect/Effect";
55
import * as FileSystem from "effect/FileSystem";
66
import * as Layer from "effect/Layer";
7+
import * as Option from "effect/Option";
78

89
import { resolveAttachmentPath } from "../attachmentStore.ts";
910
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
1011
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
1112
import * as ServerConfig from "../config.ts";
13+
import * as ServerLifecycleEvents from "../serverLifecycleEvents.ts";
1214
import * as ServerSettings from "../serverSettings.ts";
1315
import * as DocumentText from "./DocumentText.ts";
1416
import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
@@ -22,6 +24,10 @@ export const layer = Layer.effect(
2224
const secrets = yield* ServerSecretStore.ServerSecretStore;
2325
const digest = yield* Digest.Digest;
2426
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+
);
2531
return ProviderHost.ProviderHost.of({
2632
paths: {
2733
cwd: config.cwd,
@@ -37,6 +43,10 @@ export const layer = Layer.effect(
3743
subscribe: serverSettings.subscribeChanges,
3844
},
3945
shouldRunBackgroundWork: backgroundPolicy.shouldRunScopeWork,
46+
...Option.match(lifecycleEvents, {
47+
onNone: () => ({}),
48+
onSome: (events) => ({ awaitServerReady: events.awaitReady }),
49+
}),
4050
resolveAttachmentPath: (attachment) =>
4151
resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment }),
4252
// DocumentText owns the path-resolution span.

0 commit comments

Comments
 (0)