Skip to content

Commit 07d6090

Browse files
committed
fix(desktop): reuse a running local server
1 parent 5211acf commit 07d6090

32 files changed

Lines changed: 701 additions & 184 deletions

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
528528
"3",
529529
],
530530
entryPath: environment.backendEntryPath,
531+
stateDir: environment.stateDir,
531532
cwd: environment.backendCwd,
532533
env: {
533534
...backendChildEnvPatch(),

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

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
2828
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
2929
import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
3030
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
31+
import serverPackageJson from "../../../server/package.json" with { type: "json" };
3132

3233
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
3334
Schema.fromJsonString(DesktopBackendBootstrap),
@@ -117,6 +118,7 @@ function decodeBootstrap(raw: string) {
117118
}
118119

119120
interface MakeInstanceInput {
121+
readonly fileSystemLayer?: Layer.Layer<FileSystem.FileSystem>;
120122
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
121123
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
122124
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
@@ -151,9 +153,10 @@ function makeTestInstance(input: MakeInstanceInput) {
151153
...input.backendOutputLog,
152154
};
153155
const layerServices = Layer.mergeAll(
154-
FileSystem.layerNoop({
155-
exists: () => Effect.succeed(true),
156-
}),
156+
input.fileSystemLayer ??
157+
FileSystem.layerNoop({
158+
exists: () => Effect.succeed(true),
159+
}),
157160
input.spawnerLayer,
158161
input.httpClientLayer ?? layerHealthyHttpClient,
159162
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
@@ -192,6 +195,86 @@ function makeTestInstance(input: MakeInstanceInput) {
192195
}
193196

194197
describe("DesktopBackendManager", () => {
198+
it.effect("connects to the same-home server without supervising or stopping it", () =>
199+
Effect.scoped(
200+
Effect.gen(function* () {
201+
const ready = yield* Deferred.make<void>();
202+
const commands: ChildProcess.Command[] = [];
203+
let kills = 0;
204+
const origin = "http://127.0.0.1:4888";
205+
const config = { ...baseConfig, stateDir: "/tmp/t3/userdata" };
206+
const instance = yield* makeTestInstance({
207+
config,
208+
fileSystemLayer: FileSystem.layerNoop({
209+
exists: () => Effect.succeed(true),
210+
readFileString: (path) =>
211+
Effect.succeed(
212+
path.endsWith("environment-id")
213+
? "local-environment"
214+
: JSON.stringify({
215+
version: 1,
216+
pid: process.pid,
217+
ownerId: "owner",
218+
port: 4888,
219+
origin,
220+
serverVersion: serverPackageJson.version,
221+
startedAt: "2026-10-28T00:00:00Z",
222+
}),
223+
),
224+
}),
225+
httpClientLayer: layerHttpClient((request) =>
226+
Effect.succeed(
227+
HttpClientResponse.fromWeb(
228+
request,
229+
Response.json({
230+
environmentId: "local-environment",
231+
platform: { os: "darwin", arch: "arm64" },
232+
label: "Local",
233+
serverVersion: serverPackageJson.version,
234+
capabilities: {},
235+
auth: { policy: "loopback-browser", bootstrapMethods: ["one-time-token"] },
236+
}),
237+
),
238+
),
239+
),
240+
spawnerLayer: Layer.succeed(
241+
ChildProcessSpawner.ChildProcessSpawner,
242+
ChildProcessSpawner.make((command) => {
243+
commands.push(command);
244+
return Effect.succeed(
245+
makeProcess({
246+
stdout: Stream.make(
247+
new TextEncoder().encode(JSON.stringify({ token: "existing-bearer" })),
248+
),
249+
exitCode:
250+
command._tag === "StandardCommand" && command.args.includes("issue")
251+
? Effect.succeed(ChildProcessSpawner.ExitCode(0))
252+
: Effect.never,
253+
kill: () =>
254+
Effect.sync(() => {
255+
kills += 1;
256+
}),
257+
}),
258+
);
259+
}),
260+
),
261+
onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
262+
});
263+
yield* instance.start;
264+
yield* Deferred.await(ready);
265+
assert.lengthOf(commands, 1);
266+
const command = commands[0]!;
267+
assert.equal(command._tag, "StandardCommand");
268+
if (command._tag === "StandardCommand") assert.include(command.args, "issue");
269+
assert.equal(Option.getOrThrow(yield* instance.currentConfig).httpBaseUrl.origin, origin);
270+
assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
271+
yield* instance.stop();
272+
assert.equal(kills, 0);
273+
assert.isFalse((yield* instance.snapshot).restartScheduled);
274+
}),
275+
),
276+
);
277+
195278
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
196279
Effect.scoped(
197280
Effect.gen(function* () {

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
3030
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
3131
import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
3232
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
33+
import { connectExistingServer } from "./DesktopExistingServer.ts";
3334

3435
const INITIAL_RESTART_DELAY = Duration.millis(500);
3536
const MAX_RESTART_DELAY = Duration.seconds(10);
@@ -63,6 +64,8 @@ export interface BackendProcessContext {
6364
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
6465

6566
export interface DesktopBackendStartConfig extends BackendProcessContext {
67+
readonly stateDir?: string;
68+
readonly externalServer?: { readonly token: string };
6669
readonly args: ReadonlyArray<string>;
6770
readonly env: Record<string, string | undefined>;
6871
/** False passes env verbatim, preventing the Windows T3CODE_HOME from leaking into WSL. */
@@ -244,7 +247,7 @@ export interface BackendInstanceSpec {
244247
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
245248
readonly onShutdown?: () => Effect.Effect<void>;
246249
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
247-
readonly onStateDirOwned?: () => Effect.Effect<void>;
250+
readonly onStateDirOwned?: (reason?: string) => Effect.Effect<void>;
248251
/** Fires on each repeated crash or readiness timeout until the backend becomes ready. */
249252
readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect<void>;
250253
}
@@ -721,6 +724,30 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
721724
}));
722725

723726
const preflightFailure = config.value.preflightFailure;
727+
if (Option.isNone(preflightFailure)) {
728+
const existing = yield* connectExistingServer(config.value).pipe(
729+
Effect.provideService(FileSystem.FileSystem, fileSystem),
730+
Effect.provideService(HttpClient.HttpClient, httpClient),
731+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
732+
Effect.result,
733+
);
734+
if (existing._tag === "Failure") {
735+
yield* Ref.update(state, (latest) => ({ ...latest, desiredRunning: false }));
736+
yield* spec.onStateDirOwned?.(existing.failure.message) ?? Effect.void;
737+
return;
738+
}
739+
if (Option.isSome(existing.success)) {
740+
const attached = existing.success.value;
741+
yield* Ref.update(state, (latest) => ({
742+
...latest,
743+
config: Option.some(attached),
744+
ready: true,
745+
restartAttempt: 0,
746+
}));
747+
yield* spec.onReady?.(attached.httpBaseUrl) ?? Effect.void;
748+
return;
749+
}
750+
}
724751
if (Option.isSome(preflightFailure)) {
725752
const { reason, fatal, retryLimit } = preflightFailure.value;
726753
if (!fatal && retryLimit === undefined) {

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,11 +173,12 @@ export const layer = Layer.effect(
173173
SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),
174174
onShutdown: () => desktopWindow.handleBackendNotReady,
175175
onPreflightFailed: handlePrimaryPreflightFailure,
176-
onStateDirOwned: () =>
176+
onStateDirOwned: (reason) =>
177177
electronDialog
178178
.showErrorBox(
179179
"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.",
180+
reason ??
181+
"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.",
181182
)
182183
.pipe(Effect.andThen(electronApp.quit)),
183184
});
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
import { assert, describe, it } from "@effect/vitest";
2+
import * as Effect from "effect/Effect";
3+
import * as FileSystem from "effect/FileSystem";
4+
import * as Layer from "effect/Layer";
5+
import * as Option from "effect/Option";
6+
import { HttpClient, HttpClientResponse } from "effect/http";
7+
import { ChildProcessSpawner } from "effect/process";
8+
9+
import serverPackageJson from "../../../server/package.json" with { type: "json" };
10+
import { connectExistingServer } from "./DesktopExistingServer.ts";
11+
import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
12+
13+
const config: DesktopBackendStartConfig = {
14+
executablePath: "/electron",
15+
args: ["/server/bin.mjs"],
16+
entryPath: "/server/bin.mjs",
17+
cwd: "/server",
18+
stateDir: "/selected-home/userdata",
19+
env: {},
20+
extendEnv: true,
21+
bootstrap: {
22+
mode: "desktop",
23+
t3Home: "/selected-home",
24+
noBrowser: true,
25+
port: 3773,
26+
host: "127.0.0.1",
27+
desktopBootstrapToken: "launch-token",
28+
tailscaleServeEnabled: false,
29+
tailscaleServePort: 443,
30+
},
31+
bootstrapDelivery: "fd3",
32+
httpBaseUrl: new URL("http://127.0.0.1:3773"),
33+
captureOutput: true,
34+
preflightFailure: Option.none(),
35+
};
36+
37+
describe("connectExistingServer", () => {
38+
it.effect("refuses incompatible or mismatched servers before issuing a credential", () =>
39+
Effect.gen(function* () {
40+
for (const scenario of ["older", "legacy", "dev", "different-home", "unreachable"] as const) {
41+
const result = yield* connectExistingServer(config).pipe(
42+
Effect.provide(
43+
Layer.mergeAll(
44+
FileSystem.layerNoop({
45+
readFileString: (path) =>
46+
Effect.succeed(
47+
path.endsWith("environment-id")
48+
? "selected-environment"
49+
: JSON.stringify({
50+
version: 1,
51+
pid: process.pid,
52+
port: 4888,
53+
origin: "http://127.0.0.1:4888",
54+
startedAt: "2026-10-28T00:00:00Z",
55+
ownerId: scenario === "legacy" ? undefined : "owner",
56+
serverVersion: scenario === "older" ? "0.0.1" : serverPackageJson.version,
57+
...(scenario === "dev" ? { devUrl: "http://localhost:5173" } : {}),
58+
}),
59+
),
60+
}),
61+
Layer.succeed(
62+
HttpClient.HttpClient,
63+
HttpClient.make((request) =>
64+
Effect.succeed(
65+
HttpClientResponse.fromWeb(
66+
request,
67+
Response.json(
68+
{
69+
environmentId:
70+
scenario === "different-home"
71+
? "other-environment"
72+
: "selected-environment",
73+
label: "Local",
74+
platform: { os: "darwin", arch: "arm64" },
75+
serverVersion: serverPackageJson.version,
76+
capabilities: {},
77+
},
78+
{ status: scenario === "unreachable" ? 503 : 200 },
79+
),
80+
),
81+
),
82+
),
83+
),
84+
Layer.succeed(
85+
ChildProcessSpawner.ChildProcessSpawner,
86+
ChildProcessSpawner.make(() =>
87+
Effect.die("must not issue a credential for an unverified server"),
88+
),
89+
),
90+
),
91+
),
92+
Effect.result,
93+
);
94+
assert.equal(result._tag, "Failure", scenario);
95+
}
96+
}),
97+
);
98+
99+
it.effect("ignores a dead server record without probing its reused port", () =>
100+
Effect.gen(function* () {
101+
assert.isTrue(Option.isNone(yield* connectExistingServer(config)));
102+
}).pipe(
103+
Effect.provide(
104+
Layer.mergeAll(
105+
FileSystem.layerNoop({
106+
readFileString: () =>
107+
Effect.succeed(
108+
JSON.stringify({
109+
version: 1,
110+
pid: 2_147_483_647,
111+
ownerId: "stale",
112+
port: 4888,
113+
origin: "http://127.0.0.1:4888",
114+
startedAt: "2026-10-28T00:00:00Z",
115+
serverVersion: serverPackageJson.version,
116+
}),
117+
),
118+
}),
119+
Layer.succeed(
120+
HttpClient.HttpClient,
121+
HttpClient.make(() => Effect.die("must not probe a stale port")),
122+
),
123+
Layer.succeed(
124+
ChildProcessSpawner.ChildProcessSpawner,
125+
ChildProcessSpawner.make(() => Effect.die("must not issue a session")),
126+
),
127+
),
128+
),
129+
),
130+
);
131+
});

0 commit comments

Comments
 (0)