Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/desktop/src/backend/DesktopBackendConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
"3",
],
entryPath: environment.backendEntryPath,
stateDir: environment.stateDir,
cwd: environment.backendCwd,
env: {
...backendChildEnvPatch(),
Expand Down
89 changes: 86 additions & 3 deletions apps/desktop/src/backend/DesktopBackendManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
import serverPackageJson from "../../../server/package.json" with { type: "json" };

const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
Expand Down Expand Up @@ -117,6 +118,7 @@ function decodeBootstrap(raw: string) {
}

interface MakeInstanceInput {
readonly fileSystemLayer?: Layer.Layer<FileSystem.FileSystem>;
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
Expand Down Expand Up @@ -151,9 +153,10 @@ function makeTestInstance(input: MakeInstanceInput) {
...input.backendOutputLog,
};
const layerServices = Layer.mergeAll(
FileSystem.layerNoop({
exists: () => Effect.succeed(true),
}),
input.fileSystemLayer ??
FileSystem.layerNoop({
exists: () => Effect.succeed(true),
}),
input.spawnerLayer,
input.httpClientLayer ?? layerHealthyHttpClient,
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
Expand Down Expand Up @@ -192,6 +195,86 @@ function makeTestInstance(input: MakeInstanceInput) {
}

describe("DesktopBackendManager", () => {
it.effect("connects to the same-home server without supervising or stopping it", () =>
Effect.scoped(
Effect.gen(function* () {
const ready = yield* Deferred.make<void>();
const commands: ChildProcess.Command[] = [];
let kills = 0;
const origin = "http://127.0.0.1:4888";
const config = { ...baseConfig, stateDir: "/tmp/t3/userdata" };
const instance = yield* makeTestInstance({
config,
fileSystemLayer: FileSystem.layerNoop({
exists: () => Effect.succeed(true),
readFileString: (path) =>
Effect.succeed(
path.endsWith("environment-id")
? "local-environment"
: JSON.stringify({
version: 1,
pid: process.pid,
ownerId: "owner",
port: 4888,
origin,
serverVersion: serverPackageJson.version,
startedAt: "2026-10-28T00:00:00Z",
}),
),
}),
httpClientLayer: layerHttpClient((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
Response.json({
environmentId: "local-environment",
platform: { os: "darwin", arch: "arm64" },
label: "Local",
serverVersion: serverPackageJson.version,
capabilities: {},
auth: { policy: "loopback-browser", bootstrapMethods: ["one-time-token"] },
}),
),
),
),
spawnerLayer: Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
commands.push(command);
return Effect.succeed(
makeProcess({
stdout: Stream.make(
new TextEncoder().encode(JSON.stringify({ token: "existing-bearer" })),
),
exitCode:
command._tag === "StandardCommand" && command.args.includes("issue")
? Effect.succeed(ChildProcessSpawner.ExitCode(0))
: Effect.never,
kill: () =>
Effect.sync(() => {
kills += 1;
}),
}),
);
}),
),
onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
});
yield* instance.start;
yield* Deferred.await(ready);
assert.lengthOf(commands, 1);
const command = commands[0]!;
assert.equal(command._tag, "StandardCommand");
if (command._tag === "StandardCommand") assert.include(command.args, "issue");
assert.equal(Option.getOrThrow(yield* instance.currentConfig).httpBaseUrl.origin, origin);
assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
yield* instance.stop();
assert.equal(kills, 0);
assert.isFalse((yield* instance.snapshot).restartScheduled);
}),
),
);

it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
Effect.scoped(
Effect.gen(function* () {
Expand Down
29 changes: 28 additions & 1 deletion apps/desktop/src/backend/DesktopBackendManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
import { connectExistingServer } from "./DesktopExistingServer.ts";

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

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

const preflightFailure = config.value.preflightFailure;
if (Option.isNone(preflightFailure)) {
const existing = yield* connectExistingServer(config.value).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.result,
);
if (existing._tag === "Failure") {
yield* Ref.update(state, (latest) => ({ ...latest, desiredRunning: false }));
yield* spec.onStateDirOwned?.(existing.failure.message) ?? Effect.void;
return;
}
if (Option.isSome(existing.success)) {
const attached = existing.success.value;
yield* Ref.update(state, (latest) => ({
...latest,
config: Option.some(attached),
ready: true,
restartAttempt: 0,
}));
yield* spec.onReady?.(attached.httpBaseUrl) ?? Effect.void;
return;
}
}
if (Option.isSome(preflightFailure)) {
const { reason, fatal, retryLimit } = preflightFailure.value;
if (!fatal && retryLimit === undefined) {
Expand Down
5 changes: 3 additions & 2 deletions apps/desktop/src/backend/DesktopBackendPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,12 @@ export const layer = Layer.effect(
SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),
onShutdown: () => desktopWindow.handleBackendNotReady,
onPreflightFailed: handlePrimaryPreflightFailure,
onStateDirOwned: () =>
onStateDirOwned: (reason) =>
electronDialog
.showErrorBox(
"This T3 home is unavailable",
"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.",
reason ??
"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.",
)
.pipe(Effect.andThen(electronApp.quit)),
});
Expand Down
162 changes: 162 additions & 0 deletions apps/desktop/src/backend/DesktopExistingServer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import { HttpClient, HttpClientResponse } from "effect/http";
import { ChildProcessSpawner } from "effect/process";

import serverPackageJson from "../../../server/package.json" with { type: "json" };
import { connectExistingServer } from "./DesktopExistingServer.ts";
import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts";

const config: DesktopBackendStartConfig = {
executablePath: "/electron",
args: ["/server/bin.mjs"],
entryPath: "/server/bin.mjs",
cwd: "/server",
stateDir: "/selected-home/userdata",
env: {},
extendEnv: true,
bootstrap: {
mode: "desktop",
t3Home: "/selected-home",
noBrowser: true,
port: 3773,
host: "127.0.0.1",
desktopBootstrapToken: "launch-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
bootstrapDelivery: "fd3",
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
preflightFailure: Option.none(),
};

describe("connectExistingServer", () => {
it.effect("reports recovery advice for the failed attachment step", () =>
Effect.gen(function* () {
const spawnError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "spawn",
cause: new Error("Permission denied"),
});
for (const scenario of [
"older",
"legacy",
"dev",
"different-home",
"unreachable",
"session",
] as const) {
const result = yield* connectExistingServer(config).pipe(
Effect.provide(
Layer.mergeAll(
FileSystem.layerNoop({
readFileString: (path) =>
Effect.succeed(
path.endsWith("environment-id")
? "selected-environment"
: JSON.stringify({
version: 1,
pid: process.pid,
port: 4888,
origin: "http://127.0.0.1:4888",
startedAt: "2026-10-28T00:00:00Z",
ownerId: scenario === "legacy" ? undefined : "owner",
serverVersion: scenario === "older" ? "0.0.1" : serverPackageJson.version,
...(scenario === "dev" ? { devUrl: "http://localhost:5173" } : {}),
}),
),
}),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
Response.json(
{
environmentId:
scenario === "different-home"
? "other-environment"
: "selected-environment",
label: "Local",
platform: { os: "darwin", arch: "arm64" },
serverVersion: serverPackageJson.version,
capabilities: {},
},
{ status: scenario === "unreachable" ? 503 : 200 },
),
),
),
),
),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
scenario === "session"
? Effect.fail(spawnError)
: Effect.die("must not issue a credential for an unverified server"),
),
),
),
),
Effect.result,
);
assert.equal(result._tag, "Failure", scenario);
if (result._tag === "Failure") {
if (scenario === "unreachable" || scenario === "session") {
assert.notInclude(result.failure.message, "Update or stop");
}
if (scenario === "session") {
assert.include(result.failure.message, "session");
assert.strictEqual(result.failure.cause, spawnError);
}
if (scenario === "older") {
assert.include(result.failure.message, "Update or stop");
}
if (scenario === "different-home") {
assert.include(result.failure.message, "different environment");
}
}
}
}),
);

it.effect("ignores a dead server record without probing its reused port", () =>
Effect.gen(function* () {
assert.isTrue(Option.isNone(yield* connectExistingServer(config)));
}).pipe(
Effect.provide(
Layer.mergeAll(
FileSystem.layerNoop({
readFileString: () =>
Effect.succeed(
JSON.stringify({
version: 1,
pid: 2_147_483_647,
ownerId: "stale",
port: 4888,
origin: "http://127.0.0.1:4888",
startedAt: "2026-10-28T00:00:00Z",
serverVersion: serverPackageJson.version,
}),
),
}),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("must not probe a stale port")),
),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("must not issue a session")),
),
),
),
),
);
});
Loading
Loading