diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 492903139547b..d972ad2cf0b1c 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -528,6 +528,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv "3", ], entryPath: environment.backendEntryPath, + stateDir: environment.stateDir, cwd: environment.backendCwd, env: { ...backendChildEnvPatch(), diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index 54fb312ec308f..bef3a045f9314 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -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), @@ -117,6 +118,7 @@ function decodeBootstrap(raw: string) { } interface MakeInstanceInput { + readonly fileSystemLayer?: Layer.Layer; readonly spawnerLayer: Layer.Layer; readonly httpClientLayer?: Layer.Layer; readonly backendOutputLog?: Partial; @@ -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, { @@ -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(); + 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* () { diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index cbc0516509d0b..cfc9c11edd592 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -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); @@ -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; readonly env: Record; /** False passes env verbatim, preventing the Windows T3CODE_HOME from leaking into WSL. */ @@ -244,7 +247,7 @@ export interface BackendInstanceSpec { readonly onReady?: (httpBaseUrl: URL) => Effect.Effect; readonly onShutdown?: () => Effect.Effect; readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect; - readonly onStateDirOwned?: () => Effect.Effect; + readonly onStateDirOwned?: (reason?: string) => Effect.Effect; /** Fires on each repeated crash or readiness timeout until the backend becomes ready. */ readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect; } @@ -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) { diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 77a4aa998d7bc..5a5718479ff7d 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -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)), }); diff --git a/apps/desktop/src/backend/DesktopExistingServer.test.ts b/apps/desktop/src/backend/DesktopExistingServer.test.ts new file mode 100644 index 0000000000000..c9fa3a359f2b5 --- /dev/null +++ b/apps/desktop/src/backend/DesktopExistingServer.test.ts @@ -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")), + ), + ), + ), + ), + ); +}); diff --git a/apps/desktop/src/backend/DesktopExistingServer.ts b/apps/desktop/src/backend/DesktopExistingServer.ts new file mode 100644 index 0000000000000..f1b236f64ae97 --- /dev/null +++ b/apps/desktop/src/backend/DesktopExistingServer.ts @@ -0,0 +1,147 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Desktop discovery reads metadata on the native host before connecting. +import * as NodePath from "node:path"; + +import { ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import { + isProcessAlive, + readPersistedServerRuntimeState, +} from "@t3tools/shared/serverRuntimeState"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import serverPackageJson from "../../../server/package.json" with { type: "json" }; +import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts"; + +export class DesktopExistingServerError extends Schema.TaggedError()( + "DesktopExistingServerError", + { + reason: Schema.Literals([ + "incompatible-server", + "different-environment", + "session-issue-failed", + "server-replaced", + "connect-failed", + ]), + cause: Schema.optionalKey(Schema.Defect()), + }, +) { + override get message() { + switch (this.reason) { + case "incompatible-server": + return "T3 Code cannot connect to the server already using this T3 home because it is incompatible. Update or stop that server, then reopen the app."; + case "different-environment": + return "T3 Code found a different environment at the existing server address. Check the server address and T3 home, then reopen the app."; + case "session-issue-failed": + return "T3 Code could not create a desktop session for the existing server. Check the desktop logs for details, then reopen the app."; + case "server-replaced": + return "The existing T3 Code server changed while the app was connecting. Reopen the app to connect again."; + case "connect-failed": + return "T3 Code could not connect to the server already using this T3 home. Check that the server is running and inspect the desktop logs, then reopen the app."; + } + } +} + +const decodeSession = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ token: Schema.NonEmptyString })), +); +const isDesktopExistingServerError = Schema.is(DesktopExistingServerError); + +export const connectExistingServer = Effect.fn("desktop.existingServer.connect")( + function* (config: DesktopBackendStartConfig) { + const baseDir = config.bootstrap.t3Home; + if (config.stateDir === undefined || baseDir === undefined) + return Option.none(); + const statePath = NodePath.join(config.stateDir, "server-runtime.json"); + const runtime = yield* readPersistedServerRuntimeState(statePath); + if (Option.isNone(runtime) || !isProcessAlive(runtime.value.pid)) { + return Option.none(); + } + const running = runtime.value; + // The bundled CLI opens auth storage; an older server must never get newer migrations. + if (!running.ownerId || running.devUrl || running.serverVersion !== serverPackageJson.version) { + return yield* new DesktopExistingServerError({ reason: "incompatible-server" }); + } + const fs = yield* FileSystem.FileSystem; + const environmentId = (yield* fs.readFileString( + NodePath.join(config.stateDir, "environment-id"), + )).trim(); + const client = yield* HttpClient.HttpClient; + const response = yield* client.execute( + HttpClientRequest.get(new URL("/.well-known/t3/environment", running.origin).href), + ); + const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)), + ); + if ( + descriptor.environmentId !== environmentId || + descriptor.serverVersion !== running.serverVersion + ) { + return yield* new DesktopExistingServerError({ reason: "different-environment" }); + } + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const session = yield* Effect.scoped( + Effect.gen(function* () { + const process = yield* spawner.spawn( + ChildProcess.make( + config.executablePath, + [ + ...config.args.slice(0, config.args.indexOf(config.entryPath) + 1), + "auth", + "session", + "issue", + "--base-dir", + baseDir, + "--label", + "T3 Code Desktop", + "--json", + ], + { + cwd: config.cwd, + env: config.env, + extendEnv: config.extendEnv, + stdin: "ignore", + stderr: "ignore", + }, + ), + ); + const [stdout, code] = yield* Effect.all( + [process.stdout.pipe(Stream.decodeText(), Stream.mkString), process.exitCode], + { concurrency: "unbounded" }, + ); + if (code !== 0) + return yield* new DesktopExistingServerError({ + reason: "session-issue-failed", + cause: code, + }); + return yield* decodeSession(stdout); + }), + ).pipe( + Effect.mapError((cause) => + isDesktopExistingServerError(cause) + ? cause + : new DesktopExistingServerError({ reason: "session-issue-failed", cause }), + ), + ); + const latest = yield* readPersistedServerRuntimeState(statePath); + if (Option.isNone(latest) || latest.value.ownerId !== running.ownerId) { + return yield* new DesktopExistingServerError({ reason: "server-replaced" }); + } + return Option.some({ + ...config, + httpBaseUrl: new URL(running.origin), + externalServer: session, + }); + }, + Effect.timeout(Duration.minutes(1)), + Effect.mapError((cause) => + isDesktopExistingServerError(cause) + ? cause + : new DesktopExistingServerError({ reason: "connect-failed", cause }), + ), +); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index 348d3a7050f70..e5790e0f303e9 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -37,6 +37,37 @@ const config = { }; describe("DesktopLocalEnvironmentAuth", () => { + it.effect("uses the existing server session without exchanging a desktop launch token", () => + Effect.gen(function* () { + const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth; + assert.equal(yield* auth.getBearerToken, "existing-server-token"); + }).pipe( + Effect.provide( + DesktopLocalEnvironmentAuth.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(DesktopBackendPool.DesktopBackendPool, { + list: Effect.succeed([ + { + id: PRIMARY_LOCAL_ENVIRONMENT_ID, + currentConfig: Effect.succeedSome({ + ...config, + externalServer: { token: "existing-server-token" }, + }), + }, + ]), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected token exchange")), + ), + ), + ), + ), + ), + ), + ); + it.effect("exchanges the desktop bootstrap credential only once", () => Effect.gen(function* () { const requestCount = yield* Ref.make(0); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts index 6481bfd64c897..ad612eb794e0b 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -85,6 +85,7 @@ export const make = Effect.gen(function* () { return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); } const config = configOption.value; + if (config.externalServer !== undefined) return config.externalServer.token; // Secret-authenticated backends accept the current window token; the launch token may be stale. const secret = config.bootstrap.desktopBootstrapSecret; const credential = diff --git a/apps/desktop/src/ipc/methods/serverExposure.ts b/apps/desktop/src/ipc/methods/serverExposure.ts index 9a9ce768973b3..f630eb475d2d5 100644 --- a/apps/desktop/src/ipc/methods/serverExposure.ts +++ b/apps/desktop/src/ipc/methods/serverExposure.ts @@ -8,6 +8,8 @@ import * as Schema from "effect/Schema"; import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts"; import * as DesktopServerExposure from "../../backend/DesktopServerExposure.ts"; +import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; +import * as Option from "effect/Option"; import * as IpcChannels from "../channels.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; @@ -16,6 +18,26 @@ const SetTailscaleServeEnabledInput = Schema.Struct({ port: Schema.optionalKey(Schema.Number), }); +class DesktopServerExternallyManagedError extends Schema.TaggedError()( + "DesktopServerExternallyManagedError", + {}, +) { + override get message() { + return "Manage network access where the existing server was started."; + } +} + +const requireManagedPrimary = Effect.fn("desktop.ipc.serverExposure.requireManagedPrimary")( + function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primary = yield* pool.primary; + const config = yield* primary.currentConfig; + if (Option.isSome(config) && config.value.externalServer !== undefined) { + return yield* new DesktopServerExternallyManagedError(); + } + }, +); + export const getServerExposureState = DesktopIpc.makeIpcMethod({ channel: IpcChannels.GET_SERVER_EXPOSURE_STATE_CHANNEL, payload: Schema.Void, @@ -31,6 +53,7 @@ export const setServerExposureMode = DesktopIpc.makeIpcMethod({ payload: DesktopServerExposureModeSchema, result: DesktopServerExposureStateSchema, handler: Effect.fn("desktop.ipc.serverExposure.setMode")(function* (mode) { + yield* requireManagedPrimary(); const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; const change = yield* serverExposure.setMode(mode); @@ -46,6 +69,7 @@ export const setTailscaleServeEnabled = DesktopIpc.makeIpcMethod({ payload: SetTailscaleServeEnabledInput, result: DesktopServerExposureStateSchema, handler: Effect.fn("desktop.ipc.serverExposure.setTailscaleServeEnabled")(function* (input) { + yield* requireManagedPrimary(); const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; const change = yield* serverExposure.setTailscaleServeEnabled(input); diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index ed821165b40f7..37183f7e0b2dc 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -83,6 +83,38 @@ const bootstrapsLayer = (instances: ReadonlyArray { + it.effect( + "marks an existing server without exposing its session or an invalid launch token", + () => + Effect.gen(function* () { + const result = yield* getLocalEnvironmentBootstraps.handler(); + assert.deepEqual(result, [ + { + id: "primary", + label: "WSL (Ubuntu)", + runningDistro: "Ubuntu", + httpBaseUrl: "http://127.0.0.1:3774/", + wsBaseUrl: "ws://127.0.0.1:3774/", + externallyManaged: true, + }, + ]); + }).pipe( + Effect.provide( + bootstrapsLayer([ + { + ...defaultWslInstance, + id: DesktopBackendManager.PRIMARY_INSTANCE_ID, + label: Effect.succeed("Local"), + currentConfig: Effect.succeedSome({ + ...readyWslConfig, + externalServer: { token: "private-session" }, + }), + }, + ]), + ), + ), + ); + it.effect("hands out the current window's token to a backend launched with the secret", () => Effect.gen(function* () { const result = yield* getLocalEnvironmentBootstraps.handler(); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index f0d661b58bc9a..93230bcd8dac7 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -138,12 +138,15 @@ export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({ runningDistro, httpBaseUrl: httpBaseUrl.href, wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl), + ...(config.value.externalServer === undefined ? {} : { externallyManaged: true }), // Use the current window's derived token; the launch config's token may be stale. - ...(bootstrap.desktopBootstrapSecret - ? { bootstrapToken: yield* configuration.currentBootstrapToken } - : bootstrap.desktopBootstrapToken - ? { bootstrapToken: bootstrap.desktopBootstrapToken } - : {}), + ...(config.value.externalServer !== undefined + ? {} + : bootstrap.desktopBootstrapSecret + ? { bootstrapToken: yield* configuration.currentBootstrapToken } + : bootstrap.desktopBootstrapToken + ? { bootstrapToken: bootstrap.desktopBootstrapToken } + : {}), }); } return bootstraps; diff --git a/apps/server/src/cli/app.test.ts b/apps/server/src/cli/app.test.ts index b4184663625eb..aca9c24bcb583 100644 --- a/apps/server/src/cli/app.test.ts +++ b/apps/server/src/cli/app.test.ts @@ -20,7 +20,7 @@ import { Command } from "effect/cli"; import { describe, expect } from "vite-plus/test"; import { makeCli } from "../binCli.ts"; -import { PersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { PersistedServerRuntimeState } from "@t3tools/shared/serverRuntimeState"; const liveProcess = Effect.acquireRelease( Effect.promise(async () => { diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 00621e332deb9..d992433cae62d 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -25,7 +25,10 @@ import { readBootstrapEnvelope } from "../bootstrap.ts"; import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import { expandHomePath, resolveBaseDir } from "../os-jank.ts"; -import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { + isProcessAlive, + readPersistedServerRuntimeState, +} from "@t3tools/shared/serverRuntimeState"; const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe( Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."), diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 134fa17f026eb..9e89a15ed9201 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -48,7 +48,7 @@ import * as RelayTracing from "../cloud/relayTracing.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ExternalLauncher from "../process/externalLauncher.ts"; -import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { readPersistedServerRuntimeState } from "@t3tools/shared/serverRuntimeState"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import { resolveCliCommand } from "./invocation.ts"; import * as CliService from "./service.ts"; diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts index 5ad9bde0acc28..240814dad55aa 100644 --- a/apps/server/src/cli/pair.test.ts +++ b/apps/server/src/cli/pair.test.ts @@ -28,10 +28,10 @@ import { } from "../cloud/serviceProtocol.ts"; import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts"; import { - makePersistedServerRuntimeState, persistServerRuntimeState, type PersistedServerRuntimeState, -} from "../serverRuntimeState.ts"; +} from "@t3tools/shared/serverRuntimeState"; +import { makePersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { DevServerNotProxiableError, resolveTailscaleLocalTarget } from "./pair.ts"; import packageJson from "../../package.json" with { type: "json" }; diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index abec0f6c5e9c3..42799afb387f0 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -35,7 +35,7 @@ import { type PersistedServerRuntimeState, isProcessAlive, readPersistedServerRuntimeState, -} from "../serverRuntimeState.ts"; +} from "@t3tools/shared/serverRuntimeState"; import { buildPairingUrl, formatHostForUrl, diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index a5c8aa532ff3e..a81541bb42344 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -39,7 +39,7 @@ import * as ServerSettings from "../serverSettings.ts"; import { clearPersistedServerRuntimeState, readPersistedServerRuntimeState, -} from "../serverRuntimeState.ts"; +} from "@t3tools/shared/serverRuntimeState"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 777213bc9ff5f..05392c4a602b9 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -29,7 +29,7 @@ import { Argument, Command, Flag, GlobalFlag } from "effect/cli"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerConfig from "../config.ts"; import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; -import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { readPersistedServerRuntimeState } from "@t3tools/shared/serverRuntimeState"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index e35be6e4ed739..18f8583d53bef 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -31,7 +31,10 @@ import { } from "../cloud/pinnedRuntime.ts"; import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts"; import * as ProcessRunner from "../processRunner.ts"; -import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { + isProcessAlive, + readPersistedServerRuntimeState, +} from "@t3tools/shared/serverRuntimeState"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import { createUpdateProgress } from "./updateProgress.ts"; import * as CliService from "./service.ts"; diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 1959735425515..f7fb56e5cbf81 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -34,7 +34,7 @@ import { persistServerRuntimeState, readPersistedServerRuntimeState, type PersistedServerRuntimeState, -} from "./serverRuntimeState.ts"; +} from "@t3tools/shared/serverRuntimeState"; export class ServerAlreadyRunningError extends Schema.TaggedError()( "ServerAlreadyRunningError", diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.ts index abafbc7e24f62..365d7b4f4e621 100644 --- a/apps/server/src/serverRuntimeState.test.ts +++ b/apps/server/src/serverRuntimeState.test.ts @@ -14,7 +14,8 @@ import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts"; import { SERVICE_LAUNCHER_CONTEXT_ENV } from "./cloud/serviceProtocol.ts"; import * as ProcessRunner from "./processRunner.ts"; import * as ServerOwnership from "./serverOwnership.ts"; -import * as ServerRuntimeState from "./serverRuntimeState.ts"; +import * as ServerRuntimeState from "@t3tools/shared/serverRuntimeState"; +import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts"; const startBesideBootService = Effect.fn("test.startBesideBootService")(function* (input: { readonly platform: "darwin" | "linux"; @@ -139,7 +140,7 @@ describe("server ownership", () => { ), Layer.succeed(HostProcess.Environment, {}), ).pipe(Layer.provideMerge(NodeServices.layer)); - const makeState = ServerRuntimeState.makePersistedServerRuntimeState({ + const makeState = makePersistedServerRuntimeState({ config: { host: undefined, devUrl: undefined }, port: 3773, }); diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts index aca62ebb01ecf..30ccb9ecb8bd9 100644 --- a/apps/server/src/serverRuntimeState.ts +++ b/apps/server/src/serverRuntimeState.ts @@ -1,47 +1,10 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - -import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; +import type { PersistedServerRuntimeState } from "@t3tools/shared/serverRuntimeState"; import packageJson from "../package.json" with { type: "json" }; import type * as ServerConfig from "./config.ts"; import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts"; -export const PersistedServerRuntimeState = Schema.Struct({ - version: Schema.Literal(1), - pid: Schema.Int, - ownerId: Schema.optional(Schema.String), - host: Schema.optional(Schema.String), - privateNetworkOnly: Schema.optional(Schema.Boolean), - port: Schema.Int, - origin: Schema.String, - // Dev is single-origin: browsers must pair through this URL, not `origin`. - devUrl: Schema.optional(Schema.String), - startedAt: Schema.String, - serviceManaged: Schema.optional(Schema.Boolean), - serverVersion: Schema.optional(Schema.String), -}); -export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type; - -export class ServerRuntimeStateError extends Schema.TaggedError()( - "ServerRuntimeStateError", - { - operation: Schema.Literals(["persist", "read", "decode", "clear"]), - statePath: Schema.String, - cause: Schema.Defect(), - }, -) { - override get message(): string { - return `Failed to ${this.operation} server runtime state at ${this.statePath}.`; - } -} - -const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect( - Schema.fromJsonString(PersistedServerRuntimeState), -); - const runtimeOriginForConfig = ( config: Pick, port: number, @@ -71,112 +34,3 @@ export const makePersistedServerRuntimeState = (input: { ...(input.serviceManaged ? { serviceManaged: true } : {}), serverVersion: packageJson.version, })); - -export const persistServerRuntimeState = (input: { - readonly path: string; - readonly state: PersistedServerRuntimeState; -}) => - writeFileStringAtomically({ - filePath: input.path, - contents: `${JSON.stringify(input.state)}\n`, - }).pipe( - Effect.mapError( - (cause) => - new ServerRuntimeStateError({ - operation: "persist", - statePath: input.path, - cause, - }), - ), - ); - -export const clearPersistedServerRuntimeState = Effect.fn( - "serverRuntimeState.clearPersistedServerRuntimeState", -)(function* (path: string) { - const fs = yield* FileSystem.FileSystem; - yield* fs.remove(path, { force: true }).pipe( - Effect.mapError( - (cause) => - new ServerRuntimeStateError({ - operation: "clear", - statePath: path, - cause, - }), - ), - Effect.catchTags({ - ServerRuntimeStateError: (error) => - Effect.logWarning(error.message).pipe( - Effect.annotateLogs({ - operation: error.operation, - statePath: error.statePath, - cause: error, - }), - ), - }), - ); -}); - -/** Signal 0 only probes existence; EPERM still means alive. */ -export const isProcessAlive = (pid: number): boolean => { - if (!Number.isInteger(pid) || pid <= 0) return false; - try { - process.kill(pid, 0); - return true; - } catch (error) { - return error instanceof Error && "code" in error && error.code === "EPERM"; - } -}; - -export const readPersistedServerRuntimeState = Effect.fn( - "serverRuntimeState.readPersistedServerRuntimeState", -)( - function* (path: string) { - const fs = yield* FileSystem.FileSystem; - const raw = yield* fs.readFileString(path).pipe( - Effect.matchEffect({ - onFailure: (cause) => - cause.reason._tag === "NotFound" - ? Effect.succeed(Option.none()) - : Effect.fail( - new ServerRuntimeStateError({ - operation: "read", - statePath: path, - cause, - }), - ), - onSuccess: (contents) => Effect.succeedSome(contents), - }), - ); - if (Option.isNone(raw)) { - return Option.none(); - } - - const trimmed = raw.value.trim(); - if (trimmed.length === 0) { - return Option.none(); - } - - return yield* decodePersistedServerRuntimeState(trimmed).pipe( - Effect.asSome, - Effect.mapError( - (cause) => - new ServerRuntimeStateError({ - operation: "decode", - statePath: path, - cause, - }), - ), - ); - }, - Effect.catchTags({ - ServerRuntimeStateError: (error) => - Effect.logWarning(error.message).pipe( - Effect.annotateLogs({ - operation: error.operation, - statePath: error.statePath, - cause: error, - }), - Effect.as(Option.none()), - ), - }), -); diff --git a/apps/server/src/triage/triageSession.test.ts b/apps/server/src/triage/triageSession.test.ts index 6826ebd16bf1e..54c001dc92f90 100644 --- a/apps/server/src/triage/triageSession.test.ts +++ b/apps/server/src/triage/triageSession.test.ts @@ -5,10 +5,8 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import packageJson from "../../package.json" with { type: "json" }; -import { - makePersistedServerRuntimeState, - persistServerRuntimeState, -} from "../serverRuntimeState.ts"; +import { persistServerRuntimeState } from "@t3tools/shared/serverRuntimeState"; +import { makePersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { describeServerProcess } from "./triageSession.ts"; it.effect("reports the version the running server recorded, not the CLI's", () => diff --git a/apps/server/src/triage/triageSession.ts b/apps/server/src/triage/triageSession.ts index 14654cf7d28cc..554d84b6737fc 100644 --- a/apps/server/src/triage/triageSession.ts +++ b/apps/server/src/triage/triageSession.ts @@ -11,7 +11,10 @@ import * as Path from "effect/Path"; import * as BootService from "../cloud/bootService.ts"; import type * as ServerConfig from "../config.ts"; -import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { + isProcessAlive, + readPersistedServerRuntimeState, +} from "@t3tools/shared/serverRuntimeState"; import { buildTriageContext, buildTriageSeedPrompt, diff --git a/apps/web/src/browser/previewRuntime.test.ts b/apps/web/src/browser/previewRuntime.test.ts new file mode 100644 index 0000000000000..91596cae90f97 --- /dev/null +++ b/apps/web/src/browser/previewRuntime.test.ts @@ -0,0 +1,27 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +vi.mock("~/env", () => ({ isElectron: true })); +vi.mock("~/previewStateStore", () => ({ isPreviewSupportedInRuntime: () => true })); +vi.mock("~/rpc/atomRegistry", () => ({ appAtomRegistry: { get: () => null } })); +vi.mock("~/state/primaryEnvironment", () => ({ primaryEnvironmentIdAtom: {} })); +vi.mock("~/state/entities", () => ({ + readEnvironmentSupportsServerBrowser: () => true, + useEnvironmentSupportsServerBrowser: () => true, +})); + +import { rendersServerTabNatively } from "./previewRuntime"; + +it("streams browser tabs from an existing server instead of opening a separate native page", () => { + const bootstrap = { id: "primary", externallyManaged: true }; + vi.stubGlobal("window", { desktopBridge: { getLocalEnvironmentBootstraps: () => [bootstrap] } }); + try { + const environmentId = EnvironmentId.make("local"); + const snapshot = { runtime: "server", headless: false } as const; + expect(rendersServerTabNatively(environmentId, environmentId, snapshot)).toBe(false); + bootstrap.externallyManaged = false; + expect(rendersServerTabNatively(environmentId, environmentId, snapshot)).toBe(true); + } finally { + vi.unstubAllGlobals(); + } +}); diff --git a/apps/web/src/browser/previewRuntime.ts b/apps/web/src/browser/previewRuntime.ts index 7ca4a8a8f6995..f795e70b25c82 100644 --- a/apps/web/src/browser/previewRuntime.ts +++ b/apps/web/src/browser/previewRuntime.ts @@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentId, PreviewRuntime, PreviewSessionSnapshot } from "@t3tools/contracts"; import { isElectron } from "~/env"; +import { isDesktopPrimaryExternallyManaged } from "~/environments/primary/target"; import { isPreviewSupportedInRuntime } from "~/previewStateStore"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment"; @@ -48,6 +49,7 @@ export function rendersServerTabNatively( ): boolean { return ( isElectron && + !isDesktopPrimaryExternallyManaged() && snapshot?.runtime === "server" && !snapshot.headless && primaryEnvironmentId !== null && diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 502dc8c6a6e1d..da3f36d781966 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -95,6 +95,7 @@ import { } from "~/state/desktopNetworkAccess"; import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslState"; import { useDesktopUpdateState } from "~/state/desktopUpdate"; +import { isDesktopPrimaryExternallyManaged } from "~/environments/primary/target"; import { type EnvironmentPresentation, useEnvironments, @@ -283,7 +284,8 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" | const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope); const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope); const canManageRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope); - const canManageLocalBackend = !isLocalEnvironmentDisabled() && canMaintain; + const externallyManaged = isDesktopPrimaryExternallyManaged(); + const canManageLocalBackend = !isLocalEnvironmentDisabled() && canMaintain && !externallyManaged; const showsAccess = view === "access"; const authAccessChanges = useEnvironmentQuery( showsAccess && canReadAccess && primaryEnvironmentId !== null @@ -989,13 +991,15 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" | + {externallyManaged ? ( + + ) : null} {canManageLocalBackend ? ( ) : null} - ) : canManageLocalBackend ? ( + ) : canManageLocalBackend || externallyManaged ? ( <> {renderDisabledNetworkAccessRow()} {canReadRelay || canManageRelay ? ( diff --git a/apps/web/src/environments/primary/target.ts b/apps/web/src/environments/primary/target.ts index c596dcc46ef7d..a8ec110fdac39 100644 --- a/apps/web/src/environments/primary/target.ts +++ b/apps/web/src/environments/primary/target.ts @@ -83,6 +83,13 @@ function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | nu return bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID) ?? null; } +export function isDesktopPrimaryExternallyManaged(): boolean { + return ( + typeof window !== "undefined" && + getDesktopLocalEnvironmentBootstrap()?.externallyManaged === true + ); +} + function parseTargetUrl(input: { readonly rawValue: string; readonly baseUrl?: string; diff --git a/docs/user/background-service.md b/docs/user/background-service.md index be4ad66ff3ab4..4b32274e74f71 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -1,5 +1,10 @@ # Running T3 Code in the background +The desktop app connects automatically to a running server using the same T3 home and server +version. Closing the app leaves that server and its agents running. Manage the server's network +settings where you started it. If its version differs from the app's, update or stop the server +before reopening the app. + On Linux and macOS, T3 Code can run as a service for your user so you do not need to keep a terminal open. diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 89fc70f2b725a..153af2040a313 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -359,6 +359,7 @@ export interface DesktopEnvironmentBootstrap { httpBaseUrl: string | null; wsBaseUrl: string | null; bootstrapToken?: string; + externallyManaged?: boolean; } export const DesktopEnvironmentBootstrapSchema = Schema.Struct({ @@ -368,6 +369,7 @@ export const DesktopEnvironmentBootstrapSchema = Schema.Struct({ httpBaseUrl: Schema.NullOr(Schema.String), wsBaseUrl: Schema.NullOr(Schema.String), bootstrapToken: Schema.optionalKey(Schema.String), + externallyManaged: Schema.optionalKey(Schema.Boolean), }); export const DesktopSshEnvironmentTargetSchema = Schema.Struct({ diff --git a/packages/shared/package.json b/packages/shared/package.json index cc113b00fe4da..3737d628c8855 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -3,6 +3,10 @@ "private": true, "type": "module", "exports": { + "./serverRuntimeState": { + "types": "./src/serverRuntimeState.ts", + "import": "./src/serverRuntimeState.ts" + }, "./changedFileKind": { "types": "./src/changedFileKind.ts", "import": "./src/changedFileKind.ts" diff --git a/packages/shared/src/serverRuntimeState.ts b/packages/shared/src/serverRuntimeState.ts new file mode 100644 index 0000000000000..0be53a6c53a18 --- /dev/null +++ b/packages/shared/src/serverRuntimeState.ts @@ -0,0 +1,148 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; + +export const PersistedServerRuntimeState = Schema.Struct({ + version: Schema.Literal(1), + pid: Schema.Int, + ownerId: Schema.optional(Schema.String), + host: Schema.optional(Schema.String), + privateNetworkOnly: Schema.optional(Schema.Boolean), + port: Schema.Int, + origin: Schema.String, + // Dev is single-origin: browsers must pair through this URL, not `origin`. + devUrl: Schema.optional(Schema.String), + startedAt: Schema.String, + serviceManaged: Schema.optional(Schema.Boolean), + serverVersion: Schema.optional(Schema.String), +}); +export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type; + +export class ServerRuntimeStateError extends Schema.TaggedError()( + "ServerRuntimeStateError", + { + operation: Schema.Literals(["persist", "read", "decode", "clear"]), + statePath: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to ${this.operation} server runtime state at ${this.statePath}.`; + } +} + +const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect( + Schema.fromJsonString(PersistedServerRuntimeState), +); + +export const persistServerRuntimeState = (input: { + readonly path: string; + readonly state: PersistedServerRuntimeState; +}) => + writeFileStringAtomically({ + filePath: input.path, + contents: `${JSON.stringify(input.state)}\n`, + }).pipe( + Effect.mapError( + (cause) => + new ServerRuntimeStateError({ + operation: "persist", + statePath: input.path, + cause, + }), + ), + ); + +export const clearPersistedServerRuntimeState = Effect.fn( + "serverRuntimeState.clearPersistedServerRuntimeState", +)(function* (path: string) { + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(path, { force: true }).pipe( + Effect.mapError( + (cause) => + new ServerRuntimeStateError({ + operation: "clear", + statePath: path, + cause, + }), + ), + Effect.catchTags({ + ServerRuntimeStateError: (error) => + Effect.logWarning(error.message).pipe( + Effect.annotateLogs({ + operation: error.operation, + statePath: error.statePath, + cause: error, + }), + ), + }), + ); +}); + +/** Signal 0 only probes existence; EPERM still means alive. */ +export const isProcessAlive = (pid: number): boolean => { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return error instanceof Error && "code" in error && error.code === "EPERM"; + } +}; + +export const readPersistedServerRuntimeState = Effect.fn( + "serverRuntimeState.readPersistedServerRuntimeState", +)( + function* (path: string) { + const fs = yield* FileSystem.FileSystem; + const raw = yield* fs.readFileString(path).pipe( + Effect.matchEffect({ + onFailure: (cause) => + cause.reason._tag === "NotFound" + ? Effect.succeed(Option.none()) + : Effect.fail( + new ServerRuntimeStateError({ + operation: "read", + statePath: path, + cause, + }), + ), + onSuccess: (contents) => Effect.succeedSome(contents), + }), + ); + if (Option.isNone(raw)) { + return Option.none(); + } + + const trimmed = raw.value.trim(); + if (trimmed.length === 0) { + return Option.none(); + } + + return yield* decodePersistedServerRuntimeState(trimmed).pipe( + Effect.asSome, + Effect.mapError( + (cause) => + new ServerRuntimeStateError({ + operation: "decode", + statePath: path, + cause, + }), + ), + ); + }, + Effect.catchTags({ + ServerRuntimeStateError: (error) => + Effect.logWarning(error.message).pipe( + Effect.annotateLogs({ + operation: error.operation, + statePath: error.statePath, + cause: error, + }), + Effect.as(Option.none()), + ), + }), +);