Skip to content

Commit 79daf43

Browse files
fix(desktop): an SSH reconnect during a desktop update no longer locks the updated app out of its T3 home (#26191)
Co-authored-by: Julius Marminge <[email protected]>
1 parent b54dad1 commit 79daf43

15 files changed

Lines changed: 923 additions & 45 deletions

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,5 @@ node_modules/
4949

5050
# pnpm content-addressable store; never belongs in the repo.
5151
.pnpm-store/
52+
53+
/packages/ssh/.ssh-launcher-test-*/

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ interface RunBackendProcessOptions extends DesktopBackendStartConfig {
205205
readonly outputDrainTimeout?: Duration.Duration;
206206
readonly onStarted?: (pid: number) => Effect.Effect<void>;
207207
readonly onExitObserved?: () => Effect.Effect<void>;
208-
readonly onReady?: () => Effect.Effect<void>;
208+
readonly onReady?: (pid: number) => Effect.Effect<void>;
209209
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
210210
readonly onOutput?: (
211211
streamName: BackendProcessOutputStream,
@@ -252,8 +252,8 @@ export interface BackendInstanceSpec {
252252
readonly id: BackendInstanceId;
253253
readonly label: Effect.Effect<string>;
254254
readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
255-
/** Receives the ready run's resolved URL; reading current config could race a subsequent restart. */
256-
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
255+
/** Receives the ready run's URL and pid; reading current config could race a subsequent restart. */
256+
readonly onReady?: (httpBaseUrl: URL, pid: number) => Effect.Effect<void>;
257257
readonly onShutdown?: () => Effect.Effect<void>;
258258
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
259259
readonly onStateDirOwned?: () => Effect.Effect<void>;
@@ -578,7 +578,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
578578
httpBaseUrl: options.httpBaseUrl,
579579
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
580580
}).pipe(
581-
Effect.flatMap(() => options.onReady?.() ?? Effect.void),
581+
Effect.flatMap(() => options.onReady?.(handle.pid) ?? Effect.void),
582582
Effect.as(true),
583583
Effect.catchTags({
584584
BackendReadinessTimeoutError: (error) =>
@@ -939,7 +939,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
939939
...run,
940940
exitObserved: true,
941941
})),
942-
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
942+
onReady: Effect.fn("desktop.backendInstance.onReady")(function* (pid) {
943943
const isCurrentRun = yield* SubscriptionRef.modify(state, (latest) => {
944944
const activeRun = Option.getOrUndefined(latest.active);
945945
if (activeRun?.id !== runId) {
@@ -959,7 +959,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
959959
return;
960960
}
961961

962-
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
962+
yield* spec.onReady?.(config.value.httpBaseUrl, pid) ?? Effect.void;
963963
if (
964964
config.value.runningDistro !== undefined &&
965965
config.value.wslRuntimeId !== undefined

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

Lines changed: 234 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import * as NodeServices from "@effect/platform-node/NodeServices";
21
import { assert, describe, it } from "@effect/vitest";
2+
import { DESKTOP_UPDATE_IN_PROGRESS_TTL_MS } from "@t3tools/contracts";
33
import * as Deferred from "effect/Deferred";
44
import * as Duration from "effect/Duration";
55
import * as Effect from "effect/Effect";
@@ -110,27 +110,52 @@ const runningConfig = {
110110

111111
function layerPool(
112112
labelRef: Ref.Ref<string>,
113-
backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>,
113+
options: {
114+
readonly config?: DesktopBackendStartConfig;
115+
readonly fileSystem?: Partial<FileSystem.FileSystem>;
116+
readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
117+
readonly httpClient?: HttpClient.HttpClient;
118+
readonly onReady?: Effect.Effect<void>;
119+
readonly backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>;
120+
} = {},
114121
): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
115122
return DesktopBackendPool.layer.pipe(
116123
Layer.provideMerge(
117124
Layer.mergeAll(
118-
FileSystem.layerNoop({ exists: () => Effect.succeed(true) }),
125+
DesktopEnvironment.layer({
126+
dirname: "/repo/apps/desktop/src",
127+
homeDirectory: "/test-home",
128+
platform: "linux",
129+
processArch: "x64",
130+
appVersion: "1.2.3",
131+
appPath: "/repo",
132+
isPackaged: true,
133+
resourcesPath: "/missing/resources",
134+
runningUnderArm64Translation: false,
135+
}).pipe(
136+
Layer.provide(
137+
Layer.mergeAll(Path.layer, DesktopConfig.layerTest({ T3CODE_HOME: "/test-home" })),
138+
),
139+
Layer.orDie,
140+
),
141+
FileSystem.layerNoop(options.fileSystem ?? { exists: () => Effect.succeed(true) }),
119142
Path.layer,
120-
backend?.layer ??
143+
options.backend?.layer ??
121144
Layer.succeed(
122145
ChildProcessSpawner.ChildProcessSpawner,
123-
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
146+
options.spawner ??
147+
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
124148
),
125149
Layer.succeed(
126150
HttpClient.HttpClient,
127-
HttpClient.make((request) =>
128-
backend === undefined
129-
? Effect.die("unexpected HTTP request")
130-
: Effect.succeed(
131-
HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
132-
),
133-
),
151+
options.httpClient ??
152+
HttpClient.make((request) =>
153+
options.backend === undefined
154+
? Effect.die("unexpected HTTP request")
155+
: Effect.succeed(
156+
HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
157+
),
158+
),
134159
),
135160
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
136161
forInstance: () =>
@@ -155,26 +180,14 @@ function layerPool(
155180
}),
156181
DesktopBrowserHost.layer,
157182
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
158-
resolvePrimary: Effect.die("unexpected primary config resolve"),
183+
resolvePrimary: options.config
184+
? Effect.succeed(options.config)
185+
: Effect.die("unexpected primary config resolve"),
159186
resolvePrimaryLabel: Ref.get(labelRef),
160187
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
161188
currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
162189
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
163190
DesktopAppSettings.layerTest(),
164-
DesktopEnvironment.layer({
165-
dirname: "/repo/apps/desktop/src",
166-
homeDirectory: "/home/test",
167-
platform: "linux",
168-
processArch: "x64",
169-
appVersion: "0.0.0",
170-
appPath: "/repo",
171-
isPackaged: true,
172-
resourcesPath: "/missing/resources",
173-
runningUnderArm64Translation: false,
174-
}).pipe(
175-
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
176-
Layer.orDie,
177-
),
178191
DesktopState.layer,
179192
DesktopWslEnvironment.layerTest(),
180193
ElectronDialog.layer,
@@ -186,7 +199,7 @@ function layerPool(
186199
activate: Effect.die("unexpected window activate"),
187200
createMainIfBackendReady: Effect.die("unexpected window create"),
188201
showConnectingSplash: Effect.void,
189-
handleBackendReady: () => Effect.void,
202+
handleBackendReady: () => options.onReady ?? Effect.void,
190203
handleBackendNotReady: Effect.void,
191204
flushMainWindowBounds: Effect.void,
192205
prepareCaptureReveal: Effect.void,
@@ -201,7 +214,199 @@ function layerPool(
201214
);
202215
}
203216

217+
const markerPath = "/test-home/runtime/desktop-update-in-progress";
218+
const runtimePath = "/test-home/userdata/server-runtime.json";
219+
220+
const makeUpdateMarkerFixture = () =>
221+
Effect.gen(function* () {
222+
const allowReady = yield* Deferred.make<void>();
223+
const runtimeChecked = yield* Deferred.make<void>();
224+
const markerRemoved = yield* Deferred.make<void>();
225+
const readyRuns = yield* Queue.unbounded<void>();
226+
let nextPid = 123;
227+
const files = new Map([[markerPath, JSON.stringify({ startedAt: 0, expiresAt: 60_000 })]]);
228+
const removed: string[] = [];
229+
const config: DesktopBackendStartConfig = {
230+
executablePath: "/electron",
231+
args: [],
232+
entryPath: "/server/bin.mjs",
233+
cwd: "/server",
234+
env: {},
235+
bootstrap: {
236+
mode: "desktop",
237+
noBrowser: true,
238+
port: 3774,
239+
t3Home: "/test-home",
240+
host: "127.0.0.1",
241+
desktopBootstrapToken: "token",
242+
tailscaleServeEnabled: false,
243+
tailscaleServePort: 443,
244+
},
245+
bootstrapDelivery: "fd3",
246+
extendEnv: true,
247+
httpBaseUrl: new URL("http://127.0.0.1:3774"),
248+
captureOutput: false,
249+
preflightFailure: Option.none(),
250+
};
251+
const layer = layerPool(Ref.makeUnsafe("Local"), {
252+
config,
253+
fileSystem: {
254+
exists: (path) => Effect.succeed(files.has(path) || path === config.entryPath),
255+
readFileString: (path) =>
256+
(path === runtimePath ? Deferred.succeed(runtimeChecked, undefined) : Effect.void).pipe(
257+
Effect.andThen(Effect.sync(() => files.get(path) ?? "")),
258+
),
259+
remove: (path) =>
260+
Effect.sync(() => {
261+
removed.push(path);
262+
files.delete(path);
263+
}).pipe(
264+
Effect.andThen(
265+
path === markerPath ? Deferred.succeed(markerRemoved, undefined) : Effect.void,
266+
),
267+
Effect.asVoid,
268+
),
269+
},
270+
spawner: ChildProcessSpawner.make(() =>
271+
Effect.gen(function* () {
272+
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
273+
const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
274+
Effect.asVoid,
275+
);
276+
// Like the real spawner, closing the run's scope ends the process.
277+
yield* Effect.addFinalizer(() => exit);
278+
return ChildProcessSpawner.makeHandle({
279+
pid: ChildProcessSpawner.ProcessId(nextPid++),
280+
stdout: Stream.empty,
281+
stderr: Stream.empty,
282+
all: Stream.empty,
283+
exitCode: Deferred.await(exited),
284+
isRunning: Effect.succeed(true),
285+
kill: () => exit,
286+
stdin: Sink.drain,
287+
getInputFd: () => Sink.drain,
288+
getOutputFd: () => Stream.empty,
289+
unref: Effect.succeed(Effect.void),
290+
});
291+
}),
292+
),
293+
httpClient: HttpClient.make((request) =>
294+
Deferred.await(allowReady).pipe(
295+
Effect.as(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }))),
296+
),
297+
),
298+
onReady: Queue.offer(readyRuns, undefined).pipe(Effect.asVoid),
299+
});
300+
const publishRuntime = (pid: number) =>
301+
files.set(
302+
runtimePath,
303+
JSON.stringify({
304+
version: 1,
305+
pid,
306+
port: 3774,
307+
origin: "http://127.0.0.1:3774",
308+
startedAt: "2026-10-27T00:00:00.000Z",
309+
}),
310+
);
311+
return {
312+
layer,
313+
files,
314+
removed,
315+
allowReady,
316+
readyRuns,
317+
runtimeChecked,
318+
markerRemoved,
319+
publishRuntime,
320+
};
321+
});
322+
204323
describe("DesktopBackendPool", () => {
324+
it.effect(
325+
"keeps the update marker after HTTP readiness until the backend publishes its runtime",
326+
() =>
327+
Effect.scoped(
328+
Effect.gen(function* () {
329+
const fixture = yield* makeUpdateMarkerFixture();
330+
yield* Effect.gen(function* () {
331+
const pool = yield* DesktopBackendPool.DesktopBackendPool;
332+
const primary = yield* pool.primary;
333+
yield* primary.start;
334+
yield* Deferred.succeed(fixture.allowReady, undefined);
335+
yield* Queue.take(fixture.readyRuns);
336+
assert.isTrue(
337+
fixture.files.has(markerPath),
338+
"a launcher could neither wait nor adopt between readiness and publication",
339+
);
340+
yield* Deferred.await(fixture.runtimeChecked);
341+
yield* TestClock.adjust(Duration.seconds(5));
342+
assert.isTrue(fixture.files.has(markerPath));
343+
fixture.publishRuntime(456);
344+
yield* TestClock.adjust(Duration.seconds(1));
345+
assert.isTrue(
346+
fixture.files.has(markerPath),
347+
"another process's runtime is not the replacement",
348+
);
349+
fixture.publishRuntime(123);
350+
yield* TestClock.adjust(Duration.seconds(1));
351+
yield* Deferred.await(fixture.markerRemoved);
352+
assert.deepEqual(fixture.removed, [markerPath]);
353+
}).pipe(Effect.provide(fixture.layer));
354+
}),
355+
),
356+
);
357+
358+
it.effect("leaves a replacement update marker written while an earlier wait is pending", () =>
359+
Effect.scoped(
360+
Effect.gen(function* () {
361+
const fixture = yield* makeUpdateMarkerFixture();
362+
yield* Effect.gen(function* () {
363+
const pool = yield* DesktopBackendPool.DesktopBackendPool;
364+
const primary = yield* pool.primary;
365+
yield* primary.start;
366+
yield* Deferred.succeed(fixture.allowReady, undefined);
367+
yield* Queue.take(fixture.readyRuns);
368+
yield* Deferred.await(fixture.runtimeChecked);
369+
yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000));
370+
const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 });
371+
fixture.files.set(markerPath, replacement);
372+
yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS));
373+
assert.equal(fixture.files.get(markerPath), replacement);
374+
assert.deepEqual(fixture.removed, []);
375+
}).pipe(Effect.provide(fixture.layer));
376+
}),
377+
),
378+
);
379+
380+
it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () =>
381+
Effect.scoped(
382+
Effect.gen(function* () {
383+
const fixture = yield* makeUpdateMarkerFixture();
384+
yield* Effect.gen(function* () {
385+
const pool = yield* DesktopBackendPool.DesktopBackendPool;
386+
const primary = yield* pool.primary;
387+
yield* primary.start;
388+
yield* Deferred.succeed(fixture.allowReady, undefined);
389+
yield* Queue.take(fixture.readyRuns);
390+
yield* Deferred.await(fixture.runtimeChecked);
391+
yield* TestClock.adjust(Duration.seconds(30));
392+
yield* primary.stop();
393+
yield* primary.start;
394+
yield* Queue.take(fixture.readyRuns);
395+
yield* TestClock.adjust(Duration.seconds(31));
396+
assert.isTrue(
397+
fixture.files.has(markerPath),
398+
"the earlier run's wait must not end the later run's handoff",
399+
);
400+
assert.deepEqual(fixture.removed, []);
401+
fixture.publishRuntime(124);
402+
yield* TestClock.adjust(Duration.millis(100));
403+
yield* Deferred.await(fixture.markerRemoved);
404+
assert.deepEqual(fixture.removed, [markerPath]);
405+
}).pipe(Effect.provide(fixture.layer));
406+
}),
407+
),
408+
);
409+
205410
it.effect("unregister during pool quit does not interrupt sibling stops", () =>
206411
Effect.scoped(
207412
Effect.gen(function* () {
@@ -253,7 +458,7 @@ describe("DesktopBackendPool", () => {
253458
assert.isFalse(yield* backend.isRunning);
254459
assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
255460
assert.isTrue(Option.isNone(yield* pool.get(id)));
256-
}).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), backend)));
461+
}).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend })));
257462
}),
258463
),
259464
);

0 commit comments

Comments
 (0)