Add remote server updates and standalone service management (#4286)
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
78a0ea55c1
commit
ab4a88386d
36 files changed
+2566
-149
No files matched your search
@@ -54,6 +54,8 @@ There's no public docs site yet, checkout the miscellaneous markdown files in [d
|
||||
## Documentation
|
||||
|
||||
- [Getting started](./docs/getting-started/quick-start.md)
|
||||
- [Remote access](./docs/user/remote-access.md)
|
||||
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
|
||||
- [Architecture overview](./docs/architecture/overview.md)
|
||||
- [Provider guides](./docs/providers/codex.md)
|
||||
- [Operations](./docs/operations/ci.md)
|
||||
|
||||
@@ -202,6 +202,18 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
|
||||
);
|
||||
|
||||
it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
|
||||
|
||||
assert.include(output, "Manage the T3 Code background service.");
|
||||
assert.include(output, "install");
|
||||
assert.include(output, "uninstall");
|
||||
assert.include(output, "update");
|
||||
assert.include(output, "status");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports fresh headless connect state without requiring local configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
@@ -305,7 +317,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(output, "Signed out of T3 Connect locally.");
|
||||
assert.equal(
|
||||
output,
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
assert.isFalse(NodeFS.existsSync(tokenPath));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
import { serviceCommand } from "./cli/service.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
@@ -47,6 +48,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
serveCommand,
|
||||
authCommand,
|
||||
projectCommand,
|
||||
serviceCommand,
|
||||
cloudEnabled ? connectCommand : connectUnavailableCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -16,9 +16,9 @@ import {
|
||||
formatRelayClientReady,
|
||||
headlessSessionConfig,
|
||||
isPublishAgentActivityEnabledValue,
|
||||
recoverBootServiceOffer,
|
||||
reportCloudDisconnectResults,
|
||||
} from "./connect.ts";
|
||||
import { recoverServiceOnboardingOffer } from "./service.ts";
|
||||
|
||||
it("explains how to complete headless authorization", () => {
|
||||
assert.equal(
|
||||
@@ -58,7 +58,7 @@ it.effect("detects headless operation from individual SSH config values", () =>
|
||||
|
||||
it.effect("treats cancelling optional background setup as a successful skip", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({})));
|
||||
const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
|
||||
assert.isFalse(result);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Config from "effect/Config";
|
||||
@@ -20,6 +19,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
} from "effect/unstable/http";
|
||||
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
@@ -45,9 +44,13 @@ import { headlessRelayClientTracingLayer } 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 * as ProcessRunner from "../processRunner.ts";
|
||||
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
import {
|
||||
bootServiceLayer,
|
||||
offerServiceDuringOnboarding,
|
||||
recoverServiceOnboardingOffer,
|
||||
} from "./service.ts";
|
||||
|
||||
const jsonFlag = Flag.boolean("json").pipe(
|
||||
Flag.withDescription("Emit JSON instead of human-readable output."),
|
||||
@@ -396,21 +399,6 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
if (options.clearAuthorization) {
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
yield* tokens.clear;
|
||||
|
||||
// uninstall itself no-ops when nothing is installed (and on non-Linux),
|
||||
// so no status pre-check that could mask a real removal failure.
|
||||
const bootService = yield* BootService.BootService;
|
||||
yield* bootService.uninstall.pipe(
|
||||
Effect.tap((removed) =>
|
||||
removed ? Console.log("Removed the T3 Code background service.") : Effect.void,
|
||||
),
|
||||
Effect.catchTag("BootServiceUnsupportedError", () => Effect.succeed(false)),
|
||||
Effect.catch((error) =>
|
||||
Console.warn(`Could not remove the background service: ${error.message}`).pipe(
|
||||
Effect.as(false),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* reportCloudDisconnectResults({
|
||||
@@ -420,7 +408,9 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
});
|
||||
|
||||
if (options.clearAuthorization) {
|
||||
yield* Console.log("Signed out of T3 Connect locally.");
|
||||
yield* Console.log(
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -457,11 +447,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
|
||||
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
|
||||
EnvironmentAuth.runtimeLayer,
|
||||
ServerEnvironment.layer,
|
||||
BootService.layer({
|
||||
baseDir: config.baseDir,
|
||||
logsDir: config.logsDir,
|
||||
cliVersion: packageJson.version,
|
||||
}).pipe(Layer.provide(ProcessRunner.layer)),
|
||||
bootServiceLayer(config),
|
||||
headlessRelayClientTracingLayer,
|
||||
).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
@@ -683,50 +669,6 @@ const connectLogoutCommand = Command.make("logout", {
|
||||
),
|
||||
);
|
||||
|
||||
const offerBootService = Effect.gen(function* () {
|
||||
const bootService = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* bootService.status;
|
||||
if (!supported) {
|
||||
// Don't prompt for something that can only fail; background setup is
|
||||
// Linux/systemd-only for now.
|
||||
return false;
|
||||
}
|
||||
if (installed && current) {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code background service is from an older setup. Update it now?"
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
if (!wanted) {
|
||||
return false;
|
||||
}
|
||||
const plan = yield* bootService.install;
|
||||
yield* Console.log(`Background service installed. Logs: ${plan.logPath}`);
|
||||
return true;
|
||||
});
|
||||
|
||||
export const recoverBootServiceOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
QuitError: () => Effect.succeed(false),
|
||||
BootServiceUnsupportedError: (error) =>
|
||||
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceCommandError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceInstallError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const connectCommand = Command.make("connect", {
|
||||
...projectLocationFlags,
|
||||
headless: headlessFlag,
|
||||
@@ -748,7 +690,7 @@ export const connectCommand = Command.make("connect", {
|
||||
|
||||
// Connect itself already succeeded; a boot-service failure must not
|
||||
// fail the command, just tell the user what happened and move on.
|
||||
const background = yield* recoverBootServiceOffer(offerBootService);
|
||||
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
|
||||
yield* Console.log(
|
||||
background
|
||||
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { formatServiceStatus } from "./service.ts";
|
||||
|
||||
const status = {
|
||||
supported: true,
|
||||
installed: true,
|
||||
current: true,
|
||||
unitPath: "/home/me/.config/systemd/user/t3code.service",
|
||||
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
|
||||
} as const;
|
||||
|
||||
it("reports the installed service version and host paths", () => {
|
||||
assert.equal(
|
||||
formatServiceStatus(status, "0.0.29"),
|
||||
[
|
||||
"T3 Code service",
|
||||
" Status: installed · [email protected]",
|
||||
" Unit: /home/me/.config/systemd/user/t3code.service",
|
||||
" Logs: /home/me/.t3/userdata/logs/boot-service.log",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("gives a direct repair command for a stale service", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, current: false }, "0.0.29"),
|
||||
"Next: Run `npx t3@latest service update`.",
|
||||
);
|
||||
});
|
||||
|
||||
it("explains service availability without systemd", () => {
|
||||
assert.include(
|
||||
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
|
||||
"Supported on: Linux with systemd",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Terminal from "effect/Terminal";
|
||||
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as BootService from "../cloud/bootService.ts";
|
||||
import type * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
export const bootServiceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
BootService.layer({
|
||||
baseDir: config.baseDir,
|
||||
logsDir: config.logsDir,
|
||||
cliVersion: packageJson.version,
|
||||
}).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
export type ServiceReconcileResult =
|
||||
| {
|
||||
readonly changed: false;
|
||||
readonly status: BootService.BootServiceStatus;
|
||||
}
|
||||
| {
|
||||
readonly changed: true;
|
||||
readonly previouslyInstalled: boolean;
|
||||
readonly plan: BootService.BootServicePlan;
|
||||
};
|
||||
|
||||
/** Install, update, or repair the service using the CLI version running this command. */
|
||||
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const status = yield* service.status;
|
||||
if (status.installed && status.current) {
|
||||
return { changed: false, status } satisfies ServiceReconcileResult;
|
||||
}
|
||||
const plan = yield* service.install;
|
||||
return {
|
||||
changed: true,
|
||||
previouslyInstalled: status.installed,
|
||||
plan,
|
||||
} satisfies ServiceReconcileResult;
|
||||
});
|
||||
|
||||
export function formatServiceStatus(
|
||||
status: BootService.BootServiceStatus,
|
||||
cliVersion: string,
|
||||
): string {
|
||||
if (!status.supported) {
|
||||
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
|
||||
}
|
||||
if (!status.installed) {
|
||||
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
|
||||
}
|
||||
return [
|
||||
"T3 Code service",
|
||||
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
|
||||
` Unit: ${status.unitPath}`,
|
||||
` Logs: ${status.logPath}`,
|
||||
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
|
||||
flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
|
||||
run: Effect.Effect<A, E, BootService.BootService>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
|
||||
});
|
||||
|
||||
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
|
||||
Command.withDescription("Install T3 Code as a background service for this user."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(
|
||||
`T3 Code service is already installed with t3@${packageJson.version}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
|
||||
Command.withDescription(
|
||||
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const result = yield* reconcileService();
|
||||
if (!result.changed) {
|
||||
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
|
||||
Command.withDescription("Stop and remove the T3 Code background service."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const removed = yield* service.uninstall;
|
||||
yield* Console.log(
|
||||
removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
|
||||
Command.withDescription("Show whether the T3 Code background service is installed."),
|
||||
Command.withHandler((flags) =>
|
||||
runServiceCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const offerServiceDuringOnboarding = Effect.gen(function* () {
|
||||
const service = yield* BootService.BootService;
|
||||
const { supported, installed, current } = yield* service.status;
|
||||
if (!supported) {
|
||||
return false;
|
||||
}
|
||||
if (installed && current) {
|
||||
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
|
||||
return true;
|
||||
}
|
||||
const wanted = yield* Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: installed
|
||||
? "The installed T3 Code service needs an update or repair. Update it now?"
|
||||
: "Run T3 Code in the background whenever this machine boots? " +
|
||||
"It stays reachable through T3 Connect even after you log out.",
|
||||
initial: true,
|
||||
}),
|
||||
);
|
||||
if (!wanted) {
|
||||
return false;
|
||||
}
|
||||
const result = yield* reconcileService();
|
||||
if (result.changed) {
|
||||
yield* Console.log(
|
||||
`Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
export const recoverServiceOnboardingOffer = <R>(
|
||||
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
|
||||
) =>
|
||||
offer.pipe(
|
||||
Effect.catchTags({
|
||||
QuitError: () => Effect.succeed(false),
|
||||
BootServiceUnsupportedError: (error) =>
|
||||
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceCommandError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
BootServiceInstallError: (error) =>
|
||||
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const serviceCommand = Command.make("service").pipe(
|
||||
Command.withDescription("Manage the T3 Code background service."),
|
||||
Command.withSubcommands([
|
||||
serviceInstallCommand,
|
||||
serviceUninstallCommand,
|
||||
serviceUpdateCommand,
|
||||
serviceStatusCommand,
|
||||
]),
|
||||
);
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import { reconcileService } from "../cli/service.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as BootService from "./bootService.ts";
|
||||
|
||||
@@ -100,7 +101,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
|
||||
unit,
|
||||
[
|
||||
"[Unit]",
|
||||
"Description=T3 Code server (T3 Connect)",
|
||||
"Description=T3 Code server",
|
||||
"StartLimitIntervalSec=300",
|
||||
"StartLimitBurst=5",
|
||||
"",
|
||||
@@ -108,6 +109,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
|
||||
"Type=simple",
|
||||
"WorkingDirectory=%h",
|
||||
"Environment=T3CODE_HOME=/home/theo/.t3",
|
||||
"Environment=T3_BOOT_SERVICE_UNIT=t3code.service",
|
||||
"ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
@@ -170,6 +172,33 @@ it("flags package-manager cache entry points as ephemeral", () => {
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
it.effect("reconciles the standalone service once and is then idempotent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs } = yield* makeTestContext();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const service = yield* BootService.make({
|
||||
baseDir: dirs.baseDir,
|
||||
logsDir: dirs.logsDir,
|
||||
cliVersion: "0.0.27",
|
||||
host: makeHost(dirs.stableEntry),
|
||||
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
|
||||
|
||||
const first = yield* reconcileService().pipe(
|
||||
Effect.provideService(BootService.BootService, service),
|
||||
);
|
||||
assert.isTrue(first.changed);
|
||||
if (!first.changed) return;
|
||||
assert.isFalse(first.previouslyInstalled);
|
||||
|
||||
const commandCount = commands.length;
|
||||
const second = yield* reconcileService().pipe(
|
||||
Effect.provideService(BootService.BootService, service),
|
||||
);
|
||||
assert.isFalse(second.changed);
|
||||
assert.lengthOf(commands, commandCount);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs the unit, enables the service, and enables linger", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs, fs, path } = yield* makeTestContext();
|
||||
@@ -311,7 +340,7 @@ it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports an installed-but-stale unit so connect can offer a repair", () =>
|
||||
it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
|
||||
Effect.gen(function* () {
|
||||
const { dirs, fs, path } = yield* makeTestContext();
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
@@ -402,8 +431,8 @@ it.layer(NodeServices.layer)("BootService", (it) => {
|
||||
|
||||
const error = yield* service.install.pipe(Effect.flip);
|
||||
assert.isTrue(isCommandError(error));
|
||||
// A leftover unit would make the next connect report "already set up"
|
||||
// even though linger never happened.
|
||||
// A leftover unit would make status report "installed" even though
|
||||
// linger never happened.
|
||||
assert.isFalse(
|
||||
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
|
||||
);
|
||||
|
||||
@@ -16,21 +16,19 @@ import {
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
|
||||
|
||||
/**
|
||||
* Installs T3 Code as a per-user boot service so a connected machine stays
|
||||
* reachable through T3 Connect after the SSH session ends. Linux-only for
|
||||
* now: systemd user unit + loginctl enable-linger. The service runs a pinned
|
||||
* runtime installed under <baseDir>/runtime — never `npx t3`, whose cache is
|
||||
* ephemeral and whose registry fetch at boot would make startup depend on
|
||||
* the network.
|
||||
* Installs T3 Code as a per-user boot service. Linux-only for now: systemd
|
||||
* user unit + loginctl enable-linger. The service runs a stable or pinned
|
||||
* runtime — never an ephemeral `npx t3` cache whose eviction could break
|
||||
* startup.
|
||||
*/
|
||||
|
||||
const BOOT_SERVICE_NAME = "t3code";
|
||||
const BOOT_RUNTIME_DIR = "runtime";
|
||||
|
||||
const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
|
||||
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
|
||||
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
|
||||
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
|
||||
|
||||
const EPHEMERAL_CACHE_SEGMENTS = [
|
||||
"/_npx/", // npx
|
||||
@@ -92,7 +90,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
// relay connection, and Restart=always covers early-boot failures.
|
||||
return [
|
||||
"[Unit]",
|
||||
"Description=T3 Code server (T3 Connect)",
|
||||
"Description=T3 Code server",
|
||||
// Give up after 5 crashes in 5 minutes so a persistently broken install
|
||||
// (deleted runtime, broken workspace) stops instead of restarting every
|
||||
// 5s forever and growing the unrotated append log without bound.
|
||||
@@ -103,6 +101,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
"Type=simple",
|
||||
"WorkingDirectory=%h",
|
||||
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
|
||||
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
|
||||
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
@@ -206,14 +205,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
const unitDir = path.join(homeDir, ".config", "systemd", "user");
|
||||
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
|
||||
const logPath = path.join(input.logsDir, "boot-service.log");
|
||||
const runtimeVersionDir = path.join(
|
||||
input.baseDir,
|
||||
BOOT_RUNTIME_DIR,
|
||||
"versions",
|
||||
input.cliVersion,
|
||||
);
|
||||
const runtimeEntryPath = path.join(runtimeVersionDir, "node_modules", "t3", "dist", "bin.mjs");
|
||||
const runtimeSentinelPath = path.join(runtimeVersionDir, ".install-complete");
|
||||
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
|
||||
|
||||
const requireSystemdLinux = Effect.gen(function* () {
|
||||
if (platform !== "linux" || homeDir === "") {
|
||||
@@ -263,52 +255,41 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
|
||||
return;
|
||||
}
|
||||
// The sentinel is written only after npm exits 0. Checking the entry
|
||||
// file alone is not enough: npm extracts files before running native
|
||||
// builds (node-pty), so a killed install leaves a plausible-looking but
|
||||
// broken tree behind.
|
||||
const alreadyPinned = yield* Effect.all([
|
||||
fs.exists(runtimeSentinelPath),
|
||||
fs.exists(runtimeEntryPath),
|
||||
]).pipe(
|
||||
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
|
||||
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
|
||||
);
|
||||
if (alreadyPinned) {
|
||||
return;
|
||||
}
|
||||
yield* fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(
|
||||
Effect.andThen(fs.makeDirectory(runtimeVersionDir, { recursive: true })),
|
||||
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
|
||||
);
|
||||
yield* runStep(
|
||||
"installing the pinned t3 runtime (this can take a few minutes)",
|
||||
"npm",
|
||||
[
|
||||
"install",
|
||||
"--prefix",
|
||||
runtimeVersionDir,
|
||||
"--no-fund",
|
||||
"--no-audit",
|
||||
`t3@${input.cliVersion}`,
|
||||
],
|
||||
// Native deps (node-pty) can compile from source on slow boxes; the
|
||||
// ProcessRunner default of 60s would kill a healthy install.
|
||||
{ timeout: PINNED_RUNTIME_INSTALL_TIMEOUT },
|
||||
).pipe(
|
||||
Effect.tapError(() =>
|
||||
fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(Effect.ignore),
|
||||
yield* ensurePinnedRuntimeInstalled({
|
||||
baseDir: input.baseDir,
|
||||
version: input.cliVersion,
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
error.step.startsWith("installing")
|
||||
? new BootServiceCommandError({
|
||||
step: error.step,
|
||||
exitCode: error.exitCode,
|
||||
stdoutLength: error.stdoutLength,
|
||||
stderrLength: error.stderrLength,
|
||||
cause: error.cause,
|
||||
})
|
||||
: new BootServiceInstallError({ cause: error }),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.flatMap((now) =>
|
||||
fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
|
||||
flag: "a",
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* fs
|
||||
.writeFileString(runtimeSentinelPath, `${input.cliVersion}\n`)
|
||||
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
|
||||
});
|
||||
|
||||
// Where the unit will point: derivable without touching the network, so
|
||||
// status can compare units purely; install materializes it first.
|
||||
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
|
||||
? runtimeEntryPath
|
||||
? runtimePaths.entryPath
|
||||
: host.cliEntryPath;
|
||||
const plan: BootServicePlan = {
|
||||
nodePath: host.execPath,
|
||||
@@ -341,8 +322,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
);
|
||||
|
||||
// If any activation step fails, remove the unit again: a leftover file
|
||||
// would make the next `t3 connect` report the service as already set up
|
||||
// even though it was never enabled or lingered.
|
||||
// would make service status report it as installed even though it was
|
||||
// never enabled or lingered.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
|
||||
yield* runStep("enabling the service", "systemctl", [
|
||||
@@ -372,7 +353,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
// fails), leave nothing behind: disable removes the enable symlink, remove
|
||||
// deletes the file, daemon-reload clears the stale definition — otherwise a
|
||||
// dangling wants/ symlink logs "Failed to load unit" at every boot and the
|
||||
// next connect misreports the state.
|
||||
// next lifecycle command misreports the state.
|
||||
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
|
||||
previousUnit: Option.Option<string>,
|
||||
) {
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
ensurePinnedRuntimeInstalled,
|
||||
pinnedRuntimePaths,
|
||||
removePinnedRuntimeInstallation,
|
||||
} from "./pinnedRuntime.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
|
||||
it.effect("serializes concurrent installs of the same runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
|
||||
const installStarted = yield* Deferred.make<void>();
|
||||
const allowInstallToFinish = yield* Deferred.make<void>();
|
||||
const paths = pinnedRuntimePaths(path, baseDir, "0.0.29");
|
||||
let npmRuns = 0;
|
||||
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (_input) =>
|
||||
Effect.gen(function* () {
|
||||
npmRuns += 1;
|
||||
yield* Deferred.succeed(installStarted, undefined);
|
||||
yield* Deferred.await(allowInstallToFinish);
|
||||
yield* fs
|
||||
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
const install = ensurePinnedRuntimeInstalled({
|
||||
baseDir,
|
||||
version: "0.0.29",
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
});
|
||||
|
||||
const first = yield* Effect.forkChild(install, { startImmediately: true });
|
||||
yield* Deferred.await(installStarted);
|
||||
const second = yield* Effect.forkChild(install, { startImmediately: true });
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(npmRuns, 1);
|
||||
|
||||
yield* Deferred.succeed(allowInstallToFinish, undefined);
|
||||
yield* Fiber.join(first);
|
||||
yield* Fiber.join(second);
|
||||
|
||||
assert.equal(npmRuns, 1);
|
||||
assert.isTrue(yield* fs.exists(paths.sentinelPath));
|
||||
assert.isTrue(yield* fs.exists(paths.entryPath));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("waits for an active install before removing its runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
|
||||
const installStarted = yield* Deferred.make<void>();
|
||||
const allowInstallToFinish = yield* Deferred.make<void>();
|
||||
const paths = pinnedRuntimePaths(path, baseDir, "0.0.30");
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (_input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Deferred.succeed(installStarted, undefined);
|
||||
yield* Deferred.await(allowInstallToFinish);
|
||||
yield* fs
|
||||
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const installFiber = yield* Effect.forkChild(
|
||||
ensurePinnedRuntimeInstalled({
|
||||
baseDir,
|
||||
version: "0.0.30",
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}),
|
||||
{ startImmediately: true },
|
||||
);
|
||||
yield* Deferred.await(installStarted);
|
||||
const removeFiber = yield* Effect.forkChild(
|
||||
removePinnedRuntimeInstallation({
|
||||
baseDir,
|
||||
version: "0.0.30",
|
||||
fs,
|
||||
path,
|
||||
}),
|
||||
{ startImmediately: true },
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(yield* fs.exists(paths.versionDir));
|
||||
|
||||
yield* Deferred.succeed(allowInstallToFinish, undefined);
|
||||
yield* Fiber.join(installFiber);
|
||||
yield* Fiber.join(removeFiber);
|
||||
assert.isFalse(yield* fs.exists(paths.versionDir));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
/**
|
||||
* A pinned runtime is an exact `t3@<version>` npm-installed into
|
||||
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
|
||||
* unit here, and server self-update installs the target version here before
|
||||
* switching over — never `npx t3`, whose cache is ephemeral and whose
|
||||
* registry fetch at boot would make startup depend on the network.
|
||||
*/
|
||||
|
||||
const PINNED_RUNTIME_DIR = "runtime";
|
||||
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
|
||||
// Boot-service setup and remote self-update share this module but can be
|
||||
// constructed in separate layers. Serialize the complete check/install/
|
||||
// sentinel transaction across all callers in this process.
|
||||
const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
|
||||
|
||||
export interface PinnedRuntimePaths {
|
||||
readonly versionDir: string;
|
||||
readonly entryPath: string;
|
||||
readonly sentinelPath: string;
|
||||
}
|
||||
|
||||
export function pinnedRuntimePaths(
|
||||
path: Path.Path,
|
||||
baseDir: string,
|
||||
version: string,
|
||||
): PinnedRuntimePaths {
|
||||
const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, "versions", version);
|
||||
return {
|
||||
versionDir,
|
||||
entryPath: path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
|
||||
sentinelPath: path.join(versionDir, ".install-complete"),
|
||||
};
|
||||
}
|
||||
|
||||
export class PinnedRuntimeInstallError extends Schema.TaggedErrorClass<PinnedRuntimeInstallError>()(
|
||||
"PinnedRuntimeInstallError",
|
||||
{
|
||||
step: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stdoutLength: Schema.optional(Schema.Number),
|
||||
stderrLength: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.exitCode === undefined
|
||||
? `Pinned runtime install failed while ${this.step}.`
|
||||
: `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs `t3@<version>` into the pinned runtime directory unless a complete
|
||||
* install is already there, and returns its paths. The sentinel is written
|
||||
* only after npm exits 0; checking the entry file alone is not enough — npm
|
||||
* extracts files before running native builds (node-pty), so a killed
|
||||
* install leaves a plausible-looking but broken tree behind.
|
||||
*/
|
||||
export const ensurePinnedRuntimeInstalled = Effect.fn("cloud.pinned_runtime.ensure_installed")(
|
||||
function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly version: string;
|
||||
readonly fs: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly runner: ProcessRunner.ProcessRunner["Service"];
|
||||
}) {
|
||||
const { fs, runner } = input;
|
||||
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
|
||||
|
||||
return yield* pinnedRuntimeInstallLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const alreadyPinned = yield* Effect.all([
|
||||
fs.exists(paths.sentinelPath),
|
||||
fs.exists(paths.entryPath),
|
||||
]).pipe(
|
||||
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
|
||||
),
|
||||
);
|
||||
if (alreadyPinned) {
|
||||
return paths;
|
||||
}
|
||||
|
||||
yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
|
||||
Effect.andThen(fs.makeDirectory(paths.versionDir, { recursive: true })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({
|
||||
step: "preparing the pinned runtime directory",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
|
||||
yield* runner
|
||||
.run({
|
||||
command: "npm",
|
||||
args: [
|
||||
"install",
|
||||
"--prefix",
|
||||
paths.versionDir,
|
||||
"--no-fund",
|
||||
"--no-audit",
|
||||
`t3@${input.version}`,
|
||||
],
|
||||
// Native deps (node-pty) can compile from source on slow boxes; the
|
||||
// ProcessRunner default of 60s would kill a healthy install.
|
||||
timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
|
||||
Effect.filterOrFail(
|
||||
(result) => result.code === 0,
|
||||
(result) =>
|
||||
new PinnedRuntimeInstallError({
|
||||
step: installStep,
|
||||
exitCode: Number(result.code),
|
||||
stdoutLength: result.stdout.length,
|
||||
stderrLength: result.stderr.length,
|
||||
}),
|
||||
),
|
||||
Effect.tapError(() =>
|
||||
fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(Effect.ignore),
|
||||
),
|
||||
);
|
||||
|
||||
yield* fs
|
||||
.writeFileString(paths.sentinelPath, `${input.version}\n`)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
return paths;
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/** Removes one pinned runtime while holding the same process-wide lock used
|
||||
* by install/check/sentinel work, so cleanup cannot race another caller that
|
||||
* is materializing or reusing the runtime tree. */
|
||||
export const removePinnedRuntimeInstallation = Effect.fn("cloud.pinned_runtime.remove")(
|
||||
function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly version: string;
|
||||
readonly fs: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
}) {
|
||||
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
|
||||
yield* pinnedRuntimeInstallLock.withPermit(
|
||||
input.fs
|
||||
.remove(paths.versionDir, { recursive: true, force: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PinnedRuntimeInstallError({ step: "removing the pinned runtime", cause }),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,589 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
HostProcessArguments,
|
||||
HostProcessEnvironment,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
BOOT_SERVICE_UNIT_ENV,
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import * as SelfUpdate from "./selfUpdate.ts";
|
||||
|
||||
const NODE_PATH = "/usr/local/bin/node";
|
||||
|
||||
interface RecordedCommand {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const makeRecordingRunnerLayer = (
|
||||
commands: Array<RecordedCommand>,
|
||||
options?: {
|
||||
readonly failWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
|
||||
readonly stdoutFor?:
|
||||
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
|
||||
| undefined;
|
||||
},
|
||||
) =>
|
||||
Layer.succeed(
|
||||
ProcessRunner.ProcessRunner,
|
||||
ProcessRunner.ProcessRunner.of({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
commands.push({ command: input.command, args: input.args });
|
||||
const failed = options?.failWhen?.(input.command, input.args) === true;
|
||||
const versionFromPath =
|
||||
input.command === NODE_PATH && input.args[1] === "--version"
|
||||
? /[/\\]runtime[/\\]versions[/\\]([^/\\]+)/.exec(input.args[0] ?? "")?.[1]
|
||||
: undefined;
|
||||
return {
|
||||
stdout:
|
||||
options?.stdoutFor?.(input.command, input.args) ??
|
||||
(versionFromPath === undefined ? "" : `${versionFromPath}\n`),
|
||||
stderr: failed ? `${input.command} exploded` : "",
|
||||
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const provideHostRefs = (input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly entryPath: string;
|
||||
}) =>
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(HostProcessPlatform, input.platform),
|
||||
Layer.succeed(HostProcessEnvironment, input.env),
|
||||
Layer.succeed(HostProcessExecutablePath, NODE_PATH),
|
||||
Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
|
||||
),
|
||||
);
|
||||
|
||||
it("recognizes published npm artifacts as swappable entry points", () => {
|
||||
assert.isTrue(SelfUpdate.isPublishedCliEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
|
||||
assert.isTrue(
|
||||
SelfUpdate.isPublishedCliEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
|
||||
);
|
||||
assert.isTrue(
|
||||
SelfUpdate.isPublishedCliEntry(
|
||||
"C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
|
||||
),
|
||||
);
|
||||
// Dev checkouts and the desktop bundle run apps/server/dist directly.
|
||||
assert.isFalse(SelfUpdate.isPublishedCliEntry("/home/theo/dev/t3/apps/server/dist/bin.mjs"));
|
||||
assert.isFalse(SelfUpdate.isPublishedCliEntry(""));
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
|
||||
const makeHome = Effect.fn("test.makeHome")(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
|
||||
return { fs, path, home };
|
||||
});
|
||||
|
||||
const writeUnitReferencing = Effect.fn("test.writeUnitReferencing")(function* (
|
||||
home: string,
|
||||
entryPath: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const unitDir = path.join(home, ".config", "systemd", "user");
|
||||
yield* fs.makeDirectory(unitDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(unitDir, "t3code.service"),
|
||||
renderBootServiceUnit({
|
||||
nodePath: NODE_PATH,
|
||||
t3EntryPath: entryPath,
|
||||
baseDir: path.join(home, ".t3"),
|
||||
logPath: path.join(home, ".t3", "userdata", "logs", "boot-service.log"),
|
||||
unitPath: path.join(unitDir, "t3code.service"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports boot-service for the systemd-spawned unit process", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
},
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "boot-service");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not claim a systemd process owned by another unit", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: { HOME: home, INVOCATION_ID: "abc123" },
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.isNull(method);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports respawn for a manual run of the pinned artifact", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
// Same unit on disk, but no INVOCATION_ID: restarting the unit would
|
||||
// not replace this process, so it must respawn itself instead.
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(provideHostRefs({ platform: "linux", env: { HOME: home }, entryPath }));
|
||||
assert.equal(method, "respawn");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports respawn for a foreground npx artifact on darwin", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home } = yield* makeHome();
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "darwin",
|
||||
env: { HOME: home },
|
||||
entryPath: `${home}/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs`,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "respawn");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports desktop-managed for desktop-supervised backends", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home, path } = yield* makeHome();
|
||||
// Desktop ownership wins over every process-shape heuristic: even a
|
||||
// systemd-looking pinned artifact belongs to the app that spawned it.
|
||||
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
yield* writeUnitReferencing(home, entryPath);
|
||||
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: true,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "linux",
|
||||
env: {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
},
|
||||
entryPath,
|
||||
}),
|
||||
);
|
||||
assert.equal(method, "desktop-managed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports no method for dev checkouts and Windows", () =>
|
||||
Effect.gen(function* () {
|
||||
const { home } = yield* makeHome();
|
||||
const devMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "darwin",
|
||||
env: { HOME: home },
|
||||
entryPath: `${home}/dev/t3/apps/server/dist/bin.mjs`,
|
||||
}),
|
||||
);
|
||||
assert.isNull(devMethod);
|
||||
const windowsMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
|
||||
desktopManaged: false,
|
||||
}).pipe(
|
||||
provideHostRefs({
|
||||
platform: "win32",
|
||||
env: { HOME: home },
|
||||
entryPath: "C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
|
||||
}),
|
||||
);
|
||||
assert.isNull(windowsMethod);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
interface RecordedSpawn {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const makeContext = Effect.fn("test.makeContext")(function* (options?: {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly bootService?: boolean;
|
||||
readonly desktopManaged?: boolean;
|
||||
readonly entryPath?: string;
|
||||
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
|
||||
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
|
||||
readonly failSpawn?: boolean;
|
||||
}) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
|
||||
const baseDir = path.join(home, ".t3");
|
||||
const entryPath =
|
||||
options?.entryPath ??
|
||||
path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
|
||||
const env: NodeJS.ProcessEnv =
|
||||
options?.bootService === true
|
||||
? {
|
||||
HOME: home,
|
||||
INVOCATION_ID: "abc123",
|
||||
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
|
||||
}
|
||||
: { HOME: home };
|
||||
if (options?.bootService === true) {
|
||||
const unitDir = path.join(home, ".config", "systemd", "user");
|
||||
yield* fs.makeDirectory(unitDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(unitDir, "t3code.service"),
|
||||
renderBootServiceUnit({
|
||||
nodePath: NODE_PATH,
|
||||
t3EntryPath: entryPath,
|
||||
baseDir,
|
||||
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
|
||||
unitPath: path.join(unitDir, "t3code.service"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const commands: Array<RecordedCommand> = [];
|
||||
const spawns: Array<RecordedSpawn> = [];
|
||||
let exited = 0;
|
||||
// layerTest always reports mode "web"; desktop-managed contexts overlay
|
||||
// the mode the desktop app's bootstrap envelope would set.
|
||||
const configLayer =
|
||||
options?.desktopManaged === true
|
||||
? Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
return { ...config, mode: "desktop" as const };
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(home, baseDir)))
|
||||
: ServerConfig.layerTest(home, baseDir);
|
||||
const service = yield* SelfUpdate.make({
|
||||
host: {
|
||||
spawnDetached: (command, args) =>
|
||||
Effect.sync(() => spawns.push({ command, args })).pipe(
|
||||
Effect.andThen(
|
||||
options?.failSpawn === true
|
||||
? Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command,
|
||||
argumentCount: args.length,
|
||||
cause: new Error("detached spawn failed"),
|
||||
}),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
exitProcess: () => {
|
||||
exited += 1;
|
||||
},
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeRecordingRunnerLayer(commands, {
|
||||
failWhen: options?.failWhen,
|
||||
stdoutFor: options?.stdoutFor,
|
||||
}),
|
||||
configLayer,
|
||||
),
|
||||
),
|
||||
provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
|
||||
);
|
||||
return {
|
||||
fs,
|
||||
path,
|
||||
home,
|
||||
baseDir,
|
||||
entryPath,
|
||||
commands,
|
||||
spawns,
|
||||
exitCount: () => exited,
|
||||
service,
|
||||
};
|
||||
});
|
||||
|
||||
it.effect("rejects dist-tags and other non-exact versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext();
|
||||
const error = yield* context.service.update({ targetVersion: "latest" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "not an exact t3 version");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to update a desktop-managed backend and points at the app", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ desktopManaged: true, bootService: true });
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "desktop app");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails without touching anything when no update method applies", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
entryPath: "/home/theo/dev/t3/apps/server/dist/bin.mjs",
|
||||
});
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "cannot update itself");
|
||||
assert.lengthOf(context.commands, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a failed npm install and never schedules a restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ failWhen: (command) => command === "npm" });
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.equal(error.reason, "Could not install the requested t3 version.");
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("reinstalls the same version after a failed preflight", () =>
|
||||
Effect.gen(function* () {
|
||||
let preflightAttempts = 0;
|
||||
const context = yield* makeContext({
|
||||
failWhen: (command) => {
|
||||
if (command !== NODE_PATH) return false;
|
||||
preflightAttempts += 1;
|
||||
return preflightAttempts === 1;
|
||||
},
|
||||
});
|
||||
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
|
||||
const entryPath = context.path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
|
||||
yield* context.fs.makeDirectory(context.path.dirname(entryPath), { recursive: true });
|
||||
yield* context.fs.writeFileString(entryPath, "export {};\n");
|
||||
yield* context.fs.writeFileString(
|
||||
context.path.join(versionDir, ".install-complete"),
|
||||
"0.0.29\n",
|
||||
);
|
||||
|
||||
const firstError = yield* context.service
|
||||
.update({ targetVersion: "0.0.29" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(firstError.reason, "failed its version check");
|
||||
assert.isFalse(yield* context.fs.exists(versionDir));
|
||||
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
[NODE_PATH, "npm", NODE_PATH],
|
||||
);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rejects and removes an installed runtime that reports the wrong version", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
stdoutFor: (command, args) =>
|
||||
command === NODE_PATH && args[1] === "--version" ? "0.0.28\n" : undefined,
|
||||
});
|
||||
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
|
||||
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
|
||||
assert.include(error.reason, "did not report the requested");
|
||||
assert.isFalse(yield* context.fs.exists(versionDir));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a detached replacement spawn failure and leaves updates retryable", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ failSpawn: true });
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Could not start the replacement");
|
||||
|
||||
const second = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(second.reason, "Could not start the replacement");
|
||||
assert.notInclude(second.reason, "already in progress");
|
||||
assert.lengthOf(context.spawns, 2);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("installs, preflights, and respawns a foreground server", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext();
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
|
||||
assert.lengthOf(context.spawns, 1);
|
||||
|
||||
const concurrentError = yield* context.service
|
||||
.update({ targetVersion: "0.0.30" })
|
||||
.pipe(Effect.flip);
|
||||
assert.include(concurrentError.reason, "already in progress");
|
||||
|
||||
const pinnedEntry = context.path.join(
|
||||
context.baseDir,
|
||||
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
|
||||
);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => [entry.command, ...entry.args].join(" ")),
|
||||
[
|
||||
`npm install --prefix ${context.path.join(context.baseDir, "runtime/versions/0.0.29")} --no-fund --no-audit [email protected]`,
|
||||
`${NODE_PATH} ${pinnedEntry} --version`,
|
||||
],
|
||||
);
|
||||
|
||||
// The restart is deferred so the RPC acknowledgement flushes first.
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 1);
|
||||
const spawn = context.spawns[0];
|
||||
assert.equal(spawn?.command, "/bin/sh");
|
||||
assert.include(spawn?.args ?? [], pinnedEntry);
|
||||
// The replacement replays the original CLI arguments.
|
||||
assert.include(spawn?.args ?? [], "serve");
|
||||
assert.equal(context.exitCount(), 1);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rewrites the systemd unit and restarts the boot service", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ bootService: true });
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
|
||||
const pinnedEntry = context.path.join(
|
||||
context.baseDir,
|
||||
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
|
||||
);
|
||||
const unit = yield* context.fs.readFileString(
|
||||
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
|
||||
);
|
||||
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
);
|
||||
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
|
||||
|
||||
assert.deepEqual(context.commands[3], {
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", "t3code.service"],
|
||||
});
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
// systemd replaces the process; the server must not exit itself.
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
|
||||
Effect.gen(function* () {
|
||||
let failRestart = true;
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command, args) => {
|
||||
if (command !== "systemctl" || args[1] !== "restart" || !failRestart) {
|
||||
return false;
|
||||
}
|
||||
failRestart = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Restarting the systemd boot service failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.slice(-2).map((entry) => entry.args),
|
||||
[
|
||||
["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
["--user", "daemon-reload"],
|
||||
],
|
||||
);
|
||||
|
||||
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
|
||||
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
failWhen: (command) => command === "systemctl",
|
||||
});
|
||||
const unitPath = context.path.join(
|
||||
context.home,
|
||||
".config",
|
||||
"systemd",
|
||||
"user",
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(error.reason, "Reloading systemd units failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.lengthOf(context.spawns, 0);
|
||||
assert.equal(context.exitCount(), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,428 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
// node:child_process directly: the foreground-server replacement must be a
|
||||
// detached fire-and-forget child that outlives this process, while Effect's
|
||||
// ChildProcessSpawner ties every child to a scope that kills it.
|
||||
import {
|
||||
ServerSelfUpdateError,
|
||||
type ServerSelfUpdateCapability,
|
||||
type ServerSelfUpdateInput,
|
||||
type ServerSelfUpdateResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
HostProcessArguments,
|
||||
HostProcessEnvironment,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
BOOT_SERVICE_UNIT_ENV,
|
||||
BOOT_SERVICE_UNIT_FILE,
|
||||
quoteSystemdValue,
|
||||
renderBootServiceUnit,
|
||||
} from "./bootService.ts";
|
||||
import { ensurePinnedRuntimeInstalled, removePinnedRuntimeInstallation } from "./pinnedRuntime.ts";
|
||||
|
||||
/**
|
||||
* Lets a connected client replace this server with another published `t3`
|
||||
* version over RPC — the only update path that works when the user is not at
|
||||
* the machine (phone against a home server, relay-managed box). The target
|
||||
* version is npm-installed into the pinned runtime and verified before
|
||||
* anything restarts, so a failed install leaves the running server untouched.
|
||||
*/
|
||||
|
||||
const PREFLIGHT_TIMEOUT = Duration.seconds(30);
|
||||
/** Grace between acknowledging the RPC and killing the process, so the
|
||||
response (and its relay hop) flushes before the socket drops. */
|
||||
const RESTART_DELAY = Duration.seconds(2);
|
||||
|
||||
/** Exact npm versions only — never dist-tags — so the acknowledgement names
|
||||
the version that was actually installed. Also keeps the value safe to
|
||||
pass to npm and embed in filesystem paths. */
|
||||
const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
|
||||
export interface ServerSelfUpdateHost {
|
||||
readonly execPath: string;
|
||||
readonly cliEntryPath: string;
|
||||
/** Original CLI arguments after the entry path, replayed on respawn. */
|
||||
readonly cliArgs: ReadonlyArray<string>;
|
||||
/** Resolves once the foreground replacement process has actually spawned. */
|
||||
readonly spawnDetached: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, ProcessRunner.ProcessSpawnError>;
|
||||
readonly exitProcess: () => void;
|
||||
}
|
||||
|
||||
function normalizeEntryPath(entryPath: string): string {
|
||||
return entryPath.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Only a published npm artifact can be swapped for another version: dev
|
||||
* checkouts (apps/server/dist) and the desktop app's bundled backend have no
|
||||
* npm identity, and the desktop manages its own updates.
|
||||
*/
|
||||
export function isPublishedCliEntry(entryPath: string): boolean {
|
||||
return normalizeEntryPath(entryPath).includes("/node_modules/t3/dist/");
|
||||
}
|
||||
|
||||
/**
|
||||
* The update path this process can offer, or null when only a manual
|
||||
* relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
|
||||
* backend and owns its version; only updating the app updates it.
|
||||
* "boot-service" — this is the systemd-supervised process from
|
||||
* bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
|
||||
* foreground POSIX process running a published artifact: replace it with a
|
||||
* detached child. Windows foreground runs are unsupported for now (no
|
||||
* equivalent of the detach-and-exec handoff below).
|
||||
*/
|
||||
export const resolveServerSelfUpdateCapability = Effect.fn(
|
||||
"cloud.server_self_update.resolve_capability",
|
||||
)(function* (input: {
|
||||
/** True when the desktop app supervises this backend (mode "desktop"). */
|
||||
readonly desktopManaged: boolean;
|
||||
}) {
|
||||
if (input.desktopManaged) {
|
||||
return "desktop-managed" as const;
|
||||
}
|
||||
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const env = yield* HostProcessEnvironment;
|
||||
const hostArguments = yield* HostProcessArguments;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const entryPath = hostArguments[1] ?? "";
|
||||
if (entryPath === "") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const homeDir = env.HOME ?? "";
|
||||
if (platform === "linux" && homeDir !== "") {
|
||||
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
|
||||
const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
|
||||
Effect.map((unit) => unit.includes(quoteSystemdValue(entryPath))),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
// INVOCATION_ID only proves that some systemd unit launched us. The
|
||||
// explicit marker written into t3code.service identifies this unit as the
|
||||
// supervisor that will replace the current process when restarted.
|
||||
if (
|
||||
unitReferencesEntry &&
|
||||
(env.INVOCATION_ID ?? "") !== "" &&
|
||||
env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE
|
||||
) {
|
||||
return "boot-service" as const;
|
||||
}
|
||||
|
||||
// A process owned by another (or a legacy unmarked) systemd unit must not
|
||||
// use the foreground respawn path: Restart=always could otherwise launch
|
||||
// the old unit beside the detached replacement.
|
||||
if ((env.INVOCATION_ID ?? "") !== "") {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if ((platform === "linux" || platform === "darwin") && isPublishedCliEntry(entryPath)) {
|
||||
return "respawn" as const;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
export class ServerSelfUpdate extends Context.Service<
|
||||
ServerSelfUpdate,
|
||||
{
|
||||
readonly update: (
|
||||
input: ServerSelfUpdateInput,
|
||||
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
|
||||
}
|
||||
>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
|
||||
|
||||
export const make = Effect.fn("cloud.server_self_update.make")(function* (options?: {
|
||||
readonly host?: Partial<ServerSelfUpdateHost>;
|
||||
}) {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const env = yield* HostProcessEnvironment;
|
||||
const hostExecPath = yield* HostProcessExecutablePath;
|
||||
const hostArguments = yield* HostProcessArguments;
|
||||
const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
});
|
||||
|
||||
const host: ServerSelfUpdateHost = {
|
||||
execPath: options?.host?.execPath ?? hostExecPath,
|
||||
cliEntryPath: options?.host?.cliEntryPath ?? hostArguments[1] ?? "",
|
||||
cliArgs: options?.host?.cliArgs ?? hostArguments.slice(2),
|
||||
spawnDetached:
|
||||
options?.host?.spawnDetached ??
|
||||
((command, args) =>
|
||||
Effect.callback<void, ProcessRunner.ProcessSpawnError>((resume) => {
|
||||
const spawnError = (cause: unknown) =>
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command,
|
||||
argumentCount: args.length,
|
||||
cause,
|
||||
});
|
||||
let child: NodeChildProcess.ChildProcess;
|
||||
try {
|
||||
child = NodeChildProcess.spawn(command, [...args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
} catch (cause) {
|
||||
resume(Effect.fail(spawnError(cause)));
|
||||
return;
|
||||
}
|
||||
|
||||
const onSpawnError = (cause: Error) => resume(Effect.fail(spawnError(cause)));
|
||||
child.once("error", onSpawnError);
|
||||
child.once("spawn", () => {
|
||||
child.removeListener("error", onSpawnError);
|
||||
// Keep asynchronous child errors from becoming uncaught after the
|
||||
// successful spawn handoff has already been acknowledged.
|
||||
child.on("error", () => undefined);
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
});
|
||||
})),
|
||||
exitProcess: options?.host?.exitProcess ?? (() => process.exit(0)),
|
||||
};
|
||||
|
||||
const inFlight = yield* Ref.make(false);
|
||||
|
||||
const failWith = (reason: string, cause?: unknown) =>
|
||||
cause === undefined
|
||||
? new ServerSelfUpdateError({ reason })
|
||||
: new ServerSelfUpdateError({ reason, cause });
|
||||
|
||||
/** Deferred so the RPC acknowledgement flushes before the process dies.
|
||||
Detached from the request scope: the triggering connection is exactly
|
||||
what the restart tears down. */
|
||||
const scheduleRestart = (restart: Effect.Effect<void>) =>
|
||||
Effect.sleep(RESTART_DELAY).pipe(
|
||||
Effect.andThen(restart),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
const writeUnitAtomically = (filePath: string, contents: string) =>
|
||||
writeFileStringAtomically({ filePath, contents }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
|
||||
"cloud.server_self_update.update",
|
||||
)(function* (input) {
|
||||
if (capability === "desktop-managed") {
|
||||
return yield* failWith(
|
||||
"This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
|
||||
);
|
||||
}
|
||||
if (capability === null) {
|
||||
return yield* failWith(
|
||||
"This server cannot update itself; relaunch it manually with the new version.",
|
||||
);
|
||||
}
|
||||
const activeMethod = capability;
|
||||
const targetVersion = input.targetVersion.trim();
|
||||
if (!EXACT_VERSION_PATTERN.test(targetVersion)) {
|
||||
return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
|
||||
}
|
||||
|
||||
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
|
||||
if (alreadyRunning) {
|
||||
return yield* failWith("A server update is already in progress.");
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const runtimePaths = yield* ensurePinnedRuntimeInstalled({
|
||||
baseDir: serverConfig.baseDir,
|
||||
version: targetVersion,
|
||||
fs,
|
||||
path,
|
||||
runner,
|
||||
}).pipe(
|
||||
Effect.mapError((error) => failWith("Could not install the requested t3 version.", error)),
|
||||
);
|
||||
|
||||
// A broken artifact (failed native build, incompatible node) must be
|
||||
// caught while the current server is still alive to report it.
|
||||
const preflight = yield* runner
|
||||
.run({
|
||||
command: host.execPath,
|
||||
args: [runtimePaths.entryPath, "--version"],
|
||||
timeout: PREFLIGHT_TIMEOUT,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
|
||||
),
|
||||
);
|
||||
const preflightVersion = preflight.stdout.trim();
|
||||
if (preflight.code !== 0 || preflightVersion !== targetVersion) {
|
||||
// A completed npm install can still be unusable under this Node or on
|
||||
// this machine. Remove its sentinel and tree so a retry of the same
|
||||
// version performs a clean install instead of reusing a known-bad one.
|
||||
yield* removePinnedRuntimeInstallation({
|
||||
baseDir: serverConfig.baseDir,
|
||||
version: targetVersion,
|
||||
fs,
|
||||
path,
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),
|
||||
),
|
||||
);
|
||||
return yield* failWith(
|
||||
preflight.code !== 0
|
||||
? `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`
|
||||
: `The installed runtime did not report the requested t3@${targetVersion} version.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (activeMethod === "boot-service") {
|
||||
const homeDir = env.HOME ?? "";
|
||||
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
|
||||
const previousUnit = yield* fs
|
||||
.readFileString(unitPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => failWith("Could not read the current systemd unit.", cause)),
|
||||
);
|
||||
// Same shape bootService.install writes, so host lifecycle commands
|
||||
// still recognize the unit as current.
|
||||
const unit = renderBootServiceUnit({
|
||||
nodePath: host.execPath,
|
||||
t3EntryPath: runtimePaths.entryPath,
|
||||
baseDir: serverConfig.baseDir,
|
||||
logPath: path.join(serverConfig.logsDir, "boot-service.log"),
|
||||
unitPath,
|
||||
});
|
||||
yield* writeUnitAtomically(unitPath, unit).pipe(
|
||||
Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
|
||||
);
|
||||
|
||||
const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
|
||||
const reload = yield* runner
|
||||
.run({ command: "systemctl", args: ["--user", "daemon-reload"] })
|
||||
.pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
|
||||
if (reload.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Reloading systemd units failed (exit code ${String(reload.code)}).`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
yield* reloadSystemd().pipe(
|
||||
Effect.catch((reloadError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.mapError((rollbackCause) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
reloadError,
|
||||
rollbackCause,
|
||||
}),
|
||||
),
|
||||
// Systemd should still have the old unit in memory after the
|
||||
// failed reload, but retry after restoring in case it applied a
|
||||
// partial update before returning an error.
|
||||
Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
|
||||
Effect.andThen(Effect.fail(reloadError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
|
||||
targetVersion,
|
||||
});
|
||||
// A successful systemd restart stops this process, so the RPC is
|
||||
// interrupted and the reconnecting client observes the new version.
|
||||
// A rejected restart returns while the old process is still alive;
|
||||
// restore the previous unit and report that failure through the RPC.
|
||||
yield* Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.andThen(reloadSystemd()),
|
||||
Effect.mapError((rollbackError) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
restartError,
|
||||
rollbackError,
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.fail(restartError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
|
||||
// other launch failures leave this server alive and return a useful
|
||||
// error. The shim itself waits until after the acknowledgement and
|
||||
// deferred exit before binding the replacement server.
|
||||
yield* host
|
||||
.spawnDetached("/bin/sh", [
|
||||
"-c",
|
||||
'sleep 3; exec "$@"',
|
||||
"t3-self-update",
|
||||
host.execPath,
|
||||
runtimePaths.entryPath,
|
||||
...host.cliArgs,
|
||||
])
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not start the replacement t3 process.", cause),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });
|
||||
yield* scheduleRestart(
|
||||
Effect.try({
|
||||
try: () => host.exitProcess(),
|
||||
catch: (cause) => failWith("Could not exit the replaced t3 process.", cause),
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError("Server self-update could not exit the replaced process.").pipe(
|
||||
Effect.annotateLogs({ targetVersion, error: error.reason }),
|
||||
Effect.ensuring(Ref.set(inFlight, false)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return { targetVersion, method: activeMethod };
|
||||
}).pipe(Effect.onError(() => Ref.set(inFlight, false)));
|
||||
});
|
||||
|
||||
return ServerSelfUpdate.of({ update });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
|
||||
Layer.provide(ProcessRunner.layer),
|
||||
);
|
||||
@@ -9,6 +9,7 @@ import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
@@ -124,6 +125,9 @@ export const make = Effect.gen(function* () {
|
||||
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
|
||||
const serverSelfUpdate = yield* resolveServerSelfUpdateCapability({
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
});
|
||||
|
||||
const descriptor: ExecutionEnvironmentDescriptor = {
|
||||
environmentId,
|
||||
@@ -137,6 +141,7 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -79,6 +79,7 @@ import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
|
||||
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
|
||||
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
|
||||
import * as CloudCliState from "./cloud/CliState.ts";
|
||||
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
@@ -361,7 +362,11 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
websocketRpcRouteLayer,
|
||||
),
|
||||
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
|
||||
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
|
||||
).pipe(
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ServerSelfUpdate.layer),
|
||||
Layer.provide(browserApiCorsLayer),
|
||||
);
|
||||
|
||||
export const makeServerLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -713,6 +713,20 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
});
|
||||
assert.equal(reusedForSshScheme, "origin");
|
||||
|
||||
const reusedForBareSshScheme = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://github.com/pingdotgg/t3code",
|
||||
});
|
||||
assert.equal(reusedForBareSshScheme, "origin");
|
||||
|
||||
const reusedForSshPort = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://[email protected]:22/pingdotgg/t3code",
|
||||
});
|
||||
assert.equal(reusedForSshPort, "origin");
|
||||
|
||||
const reusedForSshWithPort = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
|
||||
@@ -78,6 +78,7 @@ import {
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
|
||||
import * as ServerSettings from "./serverSettings.ts";
|
||||
@@ -296,6 +297,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverUpdateServer, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverUpsertKeybinding, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverRemoveKeybinding, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.serverGetSettings, AuthOrchestrationReadScope],
|
||||
@@ -418,6 +420,7 @@ const makeWsRpcLayer = (
|
||||
const portDiscovery = yield* PortScanner.PortDiscovery;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
@@ -1476,6 +1479,10 @@ const makeWsRpcLayer = (
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverUpdateServer]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.serverUpdateServer, serverSelfUpdate.update(input), {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpsertKeybinding,
|
||||
@@ -2079,6 +2086,7 @@ const makeWsRpcLayer = (
|
||||
export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
|
||||
return HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
@@ -2101,6 +2109,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
makeWsRpcLayer(session, previewAutomationBroker).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
|
||||
Layer.provide(
|
||||
SourceControlDiscovery.layer.pipe(
|
||||
Layer.provide(
|
||||
|
||||
@@ -254,11 +254,14 @@ import { RightPanelSheet } from "./RightPanelSheet";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { Button } from "./ui/button";
|
||||
import { ServerUpdateAction } from "./ServerUpdateAction";
|
||||
import {
|
||||
buildVersionMismatchDismissalKey,
|
||||
dismissVersionMismatch,
|
||||
isVersionMismatchDismissed,
|
||||
resolveServerConfigVersionMismatch,
|
||||
resolveServerSelfUpdateCapability,
|
||||
serverUpdateGuidance,
|
||||
} from "../versionSkew";
|
||||
import { useAssetUrls } from "../assets/assetUrls";
|
||||
|
||||
@@ -1784,6 +1787,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
hasMultipleRegisteredEnvironments && activeThread
|
||||
? `${environmentById.get(activeThread.environmentId)?.label ?? serverConfig?.environment.label ?? activeThread.environmentId} server`
|
||||
: "server";
|
||||
const versionMismatchEnvironmentId =
|
||||
versionMismatch && activeThread ? activeThread.environmentId : null;
|
||||
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
|
||||
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const items: ComposerBannerStackItem[] = [];
|
||||
if (activeEnvironmentUnavailableState) {
|
||||
@@ -1822,7 +1828,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
),
|
||||
});
|
||||
}
|
||||
if (showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey) {
|
||||
if (
|
||||
showVersionMismatchBanner &&
|
||||
versionMismatch &&
|
||||
versionMismatchDismissKey &&
|
||||
versionMismatchEnvironmentId
|
||||
) {
|
||||
items.push({
|
||||
id: `version-mismatch:${versionMismatchDismissKey}`,
|
||||
variant: "warning",
|
||||
@@ -1831,9 +1842,21 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
description: (
|
||||
<>
|
||||
Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "}
|
||||
{versionMismatch.serverVersion}. Sync them if RPC calls or reconnects fail.
|
||||
{versionMismatch.serverVersion}.{" "}
|
||||
{serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)}
|
||||
</>
|
||||
),
|
||||
// The desktop-managed guidance is already the description; the action
|
||||
// slot would only repeat it.
|
||||
actions:
|
||||
versionMismatchSelfUpdate === "desktop-managed" ? undefined : (
|
||||
<ServerUpdateAction
|
||||
environmentId={versionMismatchEnvironmentId}
|
||||
serverLabel={versionMismatchServerLabel}
|
||||
selfUpdate={versionMismatchSelfUpdate}
|
||||
targetVersion={versionMismatch.clientVersion}
|
||||
/>
|
||||
),
|
||||
dismissLabel: "Dismiss version mismatch warning",
|
||||
onDismiss: () => {
|
||||
dismissVersionMismatch(versionMismatchDismissKey);
|
||||
@@ -1846,9 +1869,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
activeEnvironmentUnavailableState,
|
||||
handleReconnectActiveEnvironment,
|
||||
navigate,
|
||||
setDismissedVersionMismatchKey,
|
||||
showVersionMismatchBanner,
|
||||
versionMismatch,
|
||||
versionMismatchDismissKey,
|
||||
versionMismatchEnvironmentId,
|
||||
versionMismatchSelfUpdate,
|
||||
versionMismatchServerLabel,
|
||||
]);
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import type { Dispatch, ReactElement, SetStateAction } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
updateServer: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}));
|
||||
|
||||
const hooks = vi.hoisted(() => {
|
||||
let cursor = 0;
|
||||
let slots: unknown[] = [];
|
||||
const nextIndex = () => cursor++;
|
||||
|
||||
return {
|
||||
beginRender() {
|
||||
cursor = 0;
|
||||
},
|
||||
reset() {
|
||||
cursor = 0;
|
||||
slots = [];
|
||||
},
|
||||
useEffect() {
|
||||
nextIndex();
|
||||
},
|
||||
useMemoCache(size: number): unknown[] {
|
||||
const index = nextIndex();
|
||||
if (!slots[index]) {
|
||||
slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
|
||||
}
|
||||
return slots[index] as unknown[];
|
||||
},
|
||||
useRef<T>(initialValue: T): { current: T } {
|
||||
const index = nextIndex();
|
||||
if (!slots[index]) {
|
||||
slots[index] = { current: initialValue };
|
||||
}
|
||||
return slots[index] as { current: T };
|
||||
},
|
||||
useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
|
||||
const index = nextIndex();
|
||||
if (index >= slots.length) {
|
||||
slots[index] =
|
||||
typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
|
||||
}
|
||||
const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
|
||||
const previous = slots[index] as T;
|
||||
slots[index] =
|
||||
typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
|
||||
};
|
||||
return [slots[index] as T, setValue];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react")>();
|
||||
return {
|
||||
...actual,
|
||||
useEffect: hooks.useEffect,
|
||||
useRef: hooks.useRef,
|
||||
useState: hooks.useState,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react/compiler-runtime", () => ({ c: hooks.useMemoCache }));
|
||||
vi.mock("~/hooks/useCopyToClipboard", () => ({
|
||||
useCopyToClipboard: () => ({ copyToClipboard: vi.fn() }),
|
||||
}));
|
||||
vi.mock("~/state/server", () => ({
|
||||
serverEnvironment: { updateServer: Symbol("updateServer") },
|
||||
}));
|
||||
vi.mock("~/state/use-atom-command", () => ({
|
||||
useAtomCommand: () => testState.updateServer,
|
||||
}));
|
||||
vi.mock("./ui/toast", () => ({
|
||||
toastManager: { add: testState.toast },
|
||||
}));
|
||||
|
||||
import { ServerUpdateAction } from "./ServerUpdateAction";
|
||||
|
||||
type ActionElement = ReactElement<{
|
||||
readonly disabled?: boolean;
|
||||
readonly onClick?: () => void;
|
||||
}>;
|
||||
|
||||
function renderAction(): ActionElement {
|
||||
hooks.beginRender();
|
||||
return ServerUpdateAction({
|
||||
environmentId: "env-test" as EnvironmentId,
|
||||
serverLabel: "Test server",
|
||||
selfUpdate: "boot-service",
|
||||
targetVersion: "0.0.29",
|
||||
}) as ActionElement;
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((complete) => {
|
||||
resolve = complete;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
async function flushPromises(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
describe("ServerUpdateAction", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
hooks.reset();
|
||||
testState.updateServer.mockReset();
|
||||
testState.toast.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("starts a fresh reconnect timeout after a long install succeeds", async () => {
|
||||
const update =
|
||||
deferred<
|
||||
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
|
||||
>();
|
||||
testState.updateServer.mockReturnValue(update.promise);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(11 * 60_000);
|
||||
update.resolve(
|
||||
AsyncResult.success({
|
||||
targetVersion: "0.0.29",
|
||||
method: "boot-service",
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
|
||||
// The click-based deadline would have fired by now. Success gets a fresh
|
||||
// twelve-minute reconnect window, so the action remains disabled.
|
||||
await vi.advanceTimersByTimeAsync(2 * 60_000);
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
expect(testState.toast).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Server update timed out" }),
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
expect(renderAction().props.disabled).not.toBe(true);
|
||||
expect(testState.toast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Server update timed out" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not let an expired request clear a newer retry", async () => {
|
||||
const first = deferred<ReturnType<typeof AsyncResult.failure>>();
|
||||
const retry =
|
||||
deferred<
|
||||
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
|
||||
>();
|
||||
testState.updateServer.mockReturnValueOnce(first.promise).mockReturnValueOnce(retry.promise);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
await vi.advanceTimersByTimeAsync(12 * 60_000);
|
||||
expect(renderAction().props.disabled).not.toBe(true);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
|
||||
first.resolve(AsyncResult.failure(Cause.fail(new Error("first request failed late"))));
|
||||
await flushPromises();
|
||||
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
expect(testState.updateServer).toHaveBeenCalledTimes(2);
|
||||
|
||||
retry.resolve(AsyncResult.success({ targetVersion: "0.0.29", method: "boot-service" }));
|
||||
await flushPromises();
|
||||
expect(renderAction().props.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("quietly releases the action when a restart RPC is interrupted", async () => {
|
||||
testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
await flushPromises();
|
||||
|
||||
expect(renderAction().props.disabled).not.toBe(true);
|
||||
expect(testState.toast).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Server update failed" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { serverEnvironment } from "~/state/server";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { manualServerUpdateCommand } from "~/versionSkew";
|
||||
import { Button } from "./ui/button";
|
||||
import { Spinner } from "./ui/spinner";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
/**
|
||||
* The npm install on the server side is capped at 10 minutes; expire the
|
||||
* spinner a bit beyond that so a dead transport never strands a disabled
|
||||
* button, while a legitimately slow install is never cut off.
|
||||
*/
|
||||
const UPDATE_PENDING_EXPIRY_MS = 12 * 60_000;
|
||||
|
||||
function updateFailureMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "Server update failed.";
|
||||
}
|
||||
|
||||
/**
|
||||
* The call-to-action for a version-skewed server, matched to the update path
|
||||
* it advertises: a one-click install-and-restart for servers that can update
|
||||
* themselves, an update-the-desktop-app hint for desktop-managed backends
|
||||
* (running `npx t3` there would start a second server, not update this one),
|
||||
* and copying the manual relaunch command for everything else — so the skew
|
||||
* warning always offers a way out.
|
||||
*/
|
||||
export function ServerUpdateAction({
|
||||
environmentId,
|
||||
serverLabel,
|
||||
selfUpdate,
|
||||
targetVersion,
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly serverLabel: string;
|
||||
readonly selfUpdate: ServerSelfUpdateCapability | null;
|
||||
readonly targetVersion: string;
|
||||
}) {
|
||||
const updateServer = useAtomCommand(serverEnvironment.updateServer, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [pending, setPending] = useState(false);
|
||||
const inFlightRef = useRef(false);
|
||||
const attemptRef = useRef(0);
|
||||
const expiryRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
|
||||
target: "update command",
|
||||
onCopy: ({ command }) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Update command copied",
|
||||
description: `Run \`${command}\` on ${serverLabel} to update it.`,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not copy update command",
|
||||
description: error.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (expiryRef.current !== null) {
|
||||
clearTimeout(expiryRef.current);
|
||||
expiryRef.current = null;
|
||||
}
|
||||
attemptRef.current += 1;
|
||||
inFlightRef.current = false;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleUpdate = () => {
|
||||
// Synchronous re-entry guard: setPending is async, so a rapid
|
||||
// double-click would otherwise dispatch two updates.
|
||||
if (inFlightRef.current) {
|
||||
return;
|
||||
}
|
||||
inFlightRef.current = true;
|
||||
const attempt = attemptRef.current + 1;
|
||||
attemptRef.current = attempt;
|
||||
const ownsAttempt = () => attemptRef.current === attempt;
|
||||
setPending(true);
|
||||
const armExpiry = () => {
|
||||
const expiry = setTimeout(() => {
|
||||
if (!ownsAttempt()) return;
|
||||
expiryRef.current = null;
|
||||
attemptRef.current += 1;
|
||||
inFlightRef.current = false;
|
||||
setPending(false);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update timed out",
|
||||
description: "The update may still be running on the server — check again in a minute.",
|
||||
});
|
||||
}, UPDATE_PENDING_EXPIRY_MS);
|
||||
expiryRef.current = expiry;
|
||||
return expiry;
|
||||
};
|
||||
let expiry = armExpiry();
|
||||
let restartAccepted = false;
|
||||
const keepPendingForRestart = () => {
|
||||
restartAccepted = true;
|
||||
if (expiryRef.current === expiry) {
|
||||
clearTimeout(expiry);
|
||||
expiry = armExpiry();
|
||||
}
|
||||
};
|
||||
void Promise.resolve()
|
||||
.then(() =>
|
||||
updateServer({
|
||||
environmentId,
|
||||
input: { targetVersion },
|
||||
}),
|
||||
)
|
||||
.then((result) => {
|
||||
if (!ownsAttempt()) return;
|
||||
if (result._tag === "Failure") {
|
||||
// An interrupt may be the expected boot-service disconnect, but it
|
||||
// can also be client-side cancellation before restart was accepted.
|
||||
// Release the action quietly; version sync will remove it when a
|
||||
// successful replacement reconnects.
|
||||
if (isAtomCommandInterrupted(result)) {
|
||||
return;
|
||||
}
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
description: updateFailureMessage(squashAtomCommandFailure(result)),
|
||||
});
|
||||
return;
|
||||
}
|
||||
keepPendingForRestart();
|
||||
// Installation can legitimately consume most of the request window.
|
||||
// Give restart/reconnect a fresh full window after the server accepts
|
||||
// the handoff instead of expiring based on the original click time.
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: `Updating ${serverLabel}`,
|
||||
description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,
|
||||
});
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!ownsAttempt()) return;
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
description: updateFailureMessage(error),
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
// A successful RPC only acknowledges that restart is scheduled. Keep
|
||||
// the action disabled until version sync unmounts it, or until the
|
||||
// safety expiry reports that reconnection never arrived.
|
||||
if (restartAccepted || !ownsAttempt() || expiryRef.current !== expiry) return;
|
||||
expiryRef.current = null;
|
||||
clearTimeout(expiry);
|
||||
attemptRef.current += 1;
|
||||
inFlightRef.current = false;
|
||||
setPending(false);
|
||||
});
|
||||
};
|
||||
|
||||
if (selfUpdate === "desktop-managed") {
|
||||
return (
|
||||
<span className="text-muted-foreground text-xs">
|
||||
Update the desktop app on that machine to update this server.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (selfUpdate === null) {
|
||||
const command = manualServerUpdateCommand(targetVersion);
|
||||
return (
|
||||
<Button size="xs" variant="outline" onClick={() => copyToClipboard(command, { command })}>
|
||||
Copy update command
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return pending ? (
|
||||
<Button size="xs" disabled>
|
||||
<Spinner className="size-3.5" />
|
||||
Updating...
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="xs" onClick={() => void handleUpdate()}>
|
||||
Update server
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -106,7 +106,10 @@ import {
|
||||
} from "~/environments/primary";
|
||||
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
|
||||
import { useUiStateStore } from "~/uiStateStore";
|
||||
import { resolveServerConfigVersionMismatch } from "~/versionSkew";
|
||||
import {
|
||||
resolveServerConfigVersionMismatch,
|
||||
resolveServerSelfUpdateCapability,
|
||||
} from "~/versionSkew";
|
||||
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
|
||||
import { authEnvironment } from "~/state/auth";
|
||||
@@ -129,6 +132,7 @@ import {
|
||||
} from "~/state/environments";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { ConnectionStatusDot } from "../ConnectionStatusDot";
|
||||
import { ServerUpdateAction } from "../ServerUpdateAction";
|
||||
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
|
||||
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
|
||||
|
||||
@@ -1425,11 +1429,19 @@ function SavedBackendListRow({
|
||||
<p className="text-xs text-muted-foreground">{metadataBits.join(" · ")}</p>
|
||||
) : null}
|
||||
{versionMismatch ? (
|
||||
<p className="flex items-center gap-1 text-warning text-xs">
|
||||
<TriangleAlertIcon className="size-3.5 shrink-0" />
|
||||
Version drift: client {versionMismatch.clientVersion}, server{" "}
|
||||
{versionMismatch.serverVersion}.
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="flex items-center gap-1 text-warning text-xs">
|
||||
<TriangleAlertIcon className="size-3.5 shrink-0" />
|
||||
Version drift: client {versionMismatch.clientVersion}, server{" "}
|
||||
{versionMismatch.serverVersion}.
|
||||
</p>
|
||||
<ServerUpdateAction
|
||||
environmentId={environmentId}
|
||||
serverLabel={`${environment.label} server`}
|
||||
selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)}
|
||||
targetVersion={versionMismatch.clientVersion}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{environment.connection.error ? (
|
||||
<p className="flex min-w-0 items-center gap-2 text-destructive text-xs">
|
||||
@@ -2982,6 +2994,16 @@ export function ConnectionsSettings() {
|
||||
fail.
|
||||
</span>
|
||||
}
|
||||
control={
|
||||
primaryEnvironmentId !== null ? (
|
||||
<ServerUpdateAction
|
||||
environmentId={primaryEnvironmentId}
|
||||
serverLabel={primaryEnvironment?.label ?? "this server"}
|
||||
selfUpdate={resolveServerSelfUpdateCapability(primaryServerConfig)}
|
||||
targetVersion={primaryVersionMismatch.clientVersion}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{desktopBridge ? (
|
||||
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
dismissVersionMismatch,
|
||||
isVersionMismatchDismissed,
|
||||
resolveServerConfigVersionMismatch,
|
||||
resolveServerSelfUpdateCapability,
|
||||
resolveVersionMismatch,
|
||||
serverUpdateGuidance,
|
||||
} from "./versionSkew";
|
||||
|
||||
describe("versionSkew", () => {
|
||||
@@ -75,4 +77,34 @@ describe("versionSkew", () => {
|
||||
"Socket closed. Hint: Version mismatch. Try syncing the client and server to the same T3 Code version.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reads desktop-managed update capabilities from config descriptors", () => {
|
||||
expect(
|
||||
resolveServerSelfUpdateCapability({
|
||||
environment: {
|
||||
environmentId: EnvironmentId.make("environment-desktop"),
|
||||
label: "Desktop",
|
||||
platform: { os: "darwin", arch: "arm64" },
|
||||
serverVersion: "9.9.9",
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
serverSelfUpdate: "desktop-managed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toBe("desktop-managed");
|
||||
expect(resolveServerSelfUpdateCapability(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("matches version-drift guidance to the advertised update path", () => {
|
||||
expect(serverUpdateGuidance("respawn", "Remote server")).toBe(
|
||||
"Update the Remote server so they stay in sync.",
|
||||
);
|
||||
expect(serverUpdateGuidance("desktop-managed", "Desktop server")).toBe(
|
||||
"The Desktop server is run by the T3 Code desktop app on its machine — update the desktop app there to sync them.",
|
||||
);
|
||||
expect(serverUpdateGuidance(null, "Local server")).toBe(
|
||||
"Relaunch the Local server with the copied command to sync them.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { EnvironmentId, ServerConfig } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ServerConfig, ServerSelfUpdateCapability } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { APP_VERSION } from "./branding";
|
||||
@@ -49,6 +49,36 @@ export function resolveServerConfigVersionMismatch(
|
||||
return resolveVersionMismatch(serverConfig?.environment.serverVersion);
|
||||
}
|
||||
|
||||
/** The update path the connected server offers, or null when it only
|
||||
supports a manual relaunch (older servers, dev checkouts, Windows). */
|
||||
export function resolveServerSelfUpdateCapability(
|
||||
serverConfig: Pick<ServerConfig, "environment"> | null | undefined,
|
||||
): ServerSelfUpdateCapability | null {
|
||||
return serverConfig?.environment.capabilities.serverSelfUpdate ?? null;
|
||||
}
|
||||
|
||||
/** The command to hand users whose server cannot update itself. */
|
||||
export function manualServerUpdateCommand(targetVersion: string): string {
|
||||
return `npx t3@${targetVersion}`;
|
||||
}
|
||||
|
||||
/** One sentence telling the user how to resolve version skew for a server,
|
||||
matched to the update path it offers. */
|
||||
export function serverUpdateGuidance(
|
||||
capability: ServerSelfUpdateCapability | null,
|
||||
serverLabel: string,
|
||||
): string {
|
||||
switch (capability) {
|
||||
case "boot-service":
|
||||
case "respawn":
|
||||
return `Update the ${serverLabel} so they stay in sync.`;
|
||||
case "desktop-managed":
|
||||
return `The ${serverLabel} is run by the T3 Code desktop app on its machine — update the desktop app there to sync them.`;
|
||||
default:
|
||||
return `Relaunch the ${serverLabel} with the copied command to sync them.`;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildVersionMismatchDismissalKey(
|
||||
environmentId: EnvironmentId,
|
||||
mismatch: Pick<VersionMismatch, "clientVersion" | "serverVersion">,
|
||||
|
||||
+10
-2
@@ -1,11 +1,19 @@
|
||||
# Documentation
|
||||
|
||||
- [Getting started](./getting-started/quick-start.md)
|
||||
- [Architecture](./architecture/overview.md)
|
||||
- Architecture
|
||||
- [Overview](./architecture/overview.md)
|
||||
- [Connection runtime](./architecture/connection-runtime.md)
|
||||
- [Remote environments](./architecture/remote.md)
|
||||
- [Server updates](./architecture/server-updates.md)
|
||||
- User guides
|
||||
- [Background service](./user/background-service.md)
|
||||
- [Remote access](./user/remote-access.md)
|
||||
- [Keeping T3 Code in sync](./user/server-updates.md)
|
||||
- [Keybindings](./user/keybindings.md)
|
||||
- [T3 Connect](./cloud/t3-connect-clerk.md)
|
||||
- [Integrations](./integrations/source-control-providers.md)
|
||||
- [Mobile](./mobile/app.md)
|
||||
- [Operations](./operations/ci.md)
|
||||
- [Providers](./providers/codex.md)
|
||||
- [Reference](./reference/encyclopedia.md)
|
||||
- [User guides](./user/keybindings.md)
|
||||
@@ -37,6 +37,8 @@ T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JS
|
||||
|
||||
- **Runtime signals**: The server emits lightweight typed receipts when important async milestones finish, such as checkpoint capture, diff finalization, or a turn becoming fully quiescent. Tests and orchestration code wait on these signals instead of polling internal state.
|
||||
|
||||
- **Server updates**: A connected environment advertises whether its server can replace itself. When client and server versions differ, the browser selects an automatic, desktop-managed, or manual update path without changing connection ownership. See [Server Update Architecture](./server-updates.md).
|
||||
|
||||
## Event Lifecycle
|
||||
|
||||
### Startup and client connect
|
||||
|
||||
@@ -331,6 +331,21 @@ In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
|
||||
|
||||
Only the launch and access paths differ.
|
||||
|
||||
## Version Coordination
|
||||
|
||||
Remote environments may stay online while web, desktop, or mobile clients move to a newer release.
|
||||
The environment descriptor therefore carries the running server version and may advertise a safe
|
||||
replacement path. The web and desktop UI use that information to show the appropriate action
|
||||
without making the connection transport responsible for process management.
|
||||
|
||||
Published CLI servers on supported hosts can install and hand off to the client's exact version. A
|
||||
desktop-managed backend instead points the user to the desktop app on that machine, while older or
|
||||
unsupported servers fall back to a manual relaunch. The existing connection supervisor owns the
|
||||
disconnect and reconnect just as it would for any other involuntary socket close.
|
||||
|
||||
See [Server Update Architecture](./server-updates.md) for capability detection, installation safety,
|
||||
and restart sequencing.
|
||||
|
||||
## Security model
|
||||
|
||||
Remote support must assume that some environments will be reachable over untrusted networks.
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# Server Update Architecture
|
||||
|
||||
T3 Code can update a connected server to the exact version of the client that detected version
|
||||
drift. This path exists primarily for remote environments, where the user may not have a terminal
|
||||
open on the server machine.
|
||||
|
||||
The feature has three boundaries:
|
||||
|
||||
- the server advertises whether and how it can be replaced;
|
||||
- the client chooses the matching user action;
|
||||
- the server installs and verifies the replacement before handing off the process.
|
||||
|
||||
## Detection and Presentation
|
||||
|
||||
`ExecutionEnvironmentDescriptor` includes the server version and an optional
|
||||
`capabilities.serverSelfUpdate` value. The client compares that version with `APP_VERSION` after
|
||||
loading server config.
|
||||
|
||||
The optional capability is intentionally backward compatible. An older server does not know about
|
||||
the field, so a missing value means the client must offer a manual relaunch instead of sending an
|
||||
unknown RPC.
|
||||
|
||||
The shared `ServerUpdateAction` is rendered in both user-facing version-drift surfaces:
|
||||
|
||||
- the conversation banner in `ChatView`;
|
||||
- primary and saved environment rows in **Settings** → **Connections**.
|
||||
|
||||
Both surfaces target the client's exact version. When the reconnected server reports that version,
|
||||
the mismatch and action disappear.
|
||||
|
||||
## Capability Selection
|
||||
|
||||
The server resolves its capability once at startup and publishes it in the environment descriptor.
|
||||
|
||||
| Advertised value | Process shape | Client behavior |
|
||||
| ----------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
|
||||
| `boot-service` | Linux server running under the T3-managed systemd user service | Call the update RPC; the service unit is replaced and restarted. |
|
||||
| `respawn` | Published npm CLI running in the foreground on macOS or Linux | Call the update RPC; the process hands off to a detached replacement. |
|
||||
| `desktop-managed` | Backend supervised by the desktop app | Tell the user to update the desktop app on the server machine. |
|
||||
| absent | Older server, development checkout, Windows foreground process, or an unrecognized supervisor | Offer the exact manual relaunch command. |
|
||||
|
||||
Desktop ownership takes precedence over process-shape detection. A desktop-managed backend must
|
||||
never spawn a second CLI server beside the app-owned process. Likewise, a process launched by an
|
||||
unrecognized systemd unit does not claim the foreground respawn path because its supervisor could
|
||||
bring the old version back.
|
||||
|
||||
## Update Flow
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Client detects different versions] --> B{Advertised update path}
|
||||
B -->|desktop-managed| C[Update desktop app on server machine]
|
||||
B -->|missing| D[Copy exact manual relaunch command]
|
||||
B -->|boot-service or respawn| E[server.updateServer]
|
||||
E --> F[Install exact t3 version in pinned runtime]
|
||||
F --> G[Run version preflight]
|
||||
G -->|fails| H[Remove failed runtime and keep current server]
|
||||
G -->|passes| I{Handoff method}
|
||||
I -->|boot-service| J[Rewrite and restart T3 systemd unit]
|
||||
I -->|respawn| K[Start delayed replacement and exit current process]
|
||||
J --> L[Client reconnects]
|
||||
K --> L
|
||||
```
|
||||
|
||||
`server.updateServer` requires the environment's `orchestration:operate` authorization scope. Its
|
||||
payload accepts only an exact npm version, including an exact prerelease version; dist-tags such as
|
||||
`latest` and `nightly` are rejected.
|
||||
|
||||
The update service permits one update at a time. It installs `t3@<version>` under
|
||||
`<baseDir>/runtime/versions/<version>` and writes an install-complete sentinel only after npm exits
|
||||
successfully. Boot-service setup and self-update share the same process-wide installation lock, so
|
||||
they cannot mutate a pinned runtime concurrently.
|
||||
|
||||
Before any restart, the current Node executable runs the replacement with `--version`. A failed
|
||||
install, failed preflight, or wrong reported version leaves the current server running. A failed
|
||||
preflight also removes the candidate runtime so retrying the same version performs a clean install.
|
||||
|
||||
## Host Service Lifecycle
|
||||
|
||||
The systemd user service is a host lifecycle concern, not a T3 Connect resource. The standalone
|
||||
`t3 service install`, `uninstall`, `update`, and `status` commands own it. Install and update both
|
||||
reconcile the unit through `BootService`; running `npx t3@latest service update` therefore pins and
|
||||
activates the latest CLI release without requiring a connected client.
|
||||
|
||||
The `t3 connect` onboarding flow may offer service installation, but it calls the same reconciliation
|
||||
operation as `t3 service install`. Connect logout only disables cloud access and clears its
|
||||
authorization; it does not uninstall the host service.
|
||||
|
||||
## Process Handoff
|
||||
|
||||
For `boot-service`, the server atomically rewrites the T3-managed user unit to point at the verified
|
||||
runtime, reloads systemd, and restarts the unit. Reload and restart failures restore the previous
|
||||
unit before returning an error.
|
||||
|
||||
For `respawn`, the server starts a detached, delayed replacement that replays the original CLI
|
||||
arguments. It then acknowledges the request and schedules the current process to exit. The delays
|
||||
give the acknowledgement time to cross direct or relayed connections before the socket closes.
|
||||
|
||||
There is no separate progress stream. The update request remains pending while npm installs and the
|
||||
client shows a disabled update action. A restart can interrupt the request normally; the connection
|
||||
runtime keeps the environment registered and reconnects through its usual retry path. After an
|
||||
acknowledged foreground handoff, the UI keeps the action pending until version sync removes it or a
|
||||
safety timeout releases it. If a boot-service restart closes the connection before acknowledgement,
|
||||
the UI releases the interrupted action without reporting a false update failure and lets reconnect
|
||||
and the next version check determine the result.
|
||||
|
||||
## Release Invariant
|
||||
|
||||
The exact client version must exist as the `t3` npm package before a client carrying that version is
|
||||
published. The release workflow therefore makes the GitHub release depend on CLI publication, and
|
||||
the hosted web deployment depends on that release. See [Release Checklist](../operations/release.md#server-self-update-release-invariant).
|
||||
|
||||
## Source Map
|
||||
|
||||
- Capability contract: `packages/contracts/src/environment.ts`
|
||||
- Update RPC contract: `packages/contracts/src/server.ts` and `packages/contracts/src/rpc.ts`
|
||||
- Capability detection and handoff: `apps/server/src/cloud/selfUpdate.ts`
|
||||
- Host service commands: `apps/server/src/cli/service.ts`
|
||||
- Pinned runtime installation: `apps/server/src/cloud/pinnedRuntime.ts`
|
||||
- Client version comparison: `apps/web/src/versionSkew.ts`
|
||||
- Shared update action: `apps/web/src/components/ServerUpdateAction.tsx`
|
||||
@@ -92,6 +92,9 @@ connector, and attempts to revoke the relay-side environment record. It retains
|
||||
authorization so `t3 connect link` can re-enable exposure without another browser flow. `t3 connect
|
||||
logout` performs the same cleanup and removes the stored CLI authorization.
|
||||
|
||||
The background service has an independent lifecycle. Connect setup may offer to install it, but
|
||||
logout leaves it running; manage it with `t3 service status`, `install`, `update`, and `uninstall`.
|
||||
|
||||
The current OAuth callback listener binds to loopback port `34338`. When running the CLI over SSH,
|
||||
forward that port before running `t3 connect login` or `t3 connect link`:
|
||||
|
||||
|
||||
@@ -156,6 +156,26 @@ One-time Vercel dashboard setup:
|
||||
- Publishes the CLI package (`apps/server`, npm package `t3`) to the `nightly` npm dist-tag using the same nightly version.
|
||||
- Does not commit version bumps back to `main`.
|
||||
|
||||
## Server self-update release invariant
|
||||
|
||||
Connected servers update to the client's exact version, not to an npm dist-tag. Every released
|
||||
desktop or hosted client version must therefore have a matching `t3@<version>` package available on
|
||||
npm before users can receive that client.
|
||||
|
||||
The workflow enforces this ordering:
|
||||
|
||||
1. `publish_cli` publishes the exact stable or nightly version to npm.
|
||||
2. `release` depends on `publish_cli` before exposing desktop artifacts in GitHub Releases.
|
||||
3. `deploy_web` depends on `release` before moving the hosted channel to the new client.
|
||||
|
||||
Preserve these dependencies when changing the release graph. Publishing a client first would leave
|
||||
the **Update server** action targeting a package version that does not exist yet.
|
||||
|
||||
For a release smoke test, confirm `npm view t3@<version> version` returns the expected version, then
|
||||
connect the new client to a server on the previous version and verify that the update action
|
||||
reconnects to the matching server. Test one automatic path and the manual or desktop-managed
|
||||
guidance when those environments are available.
|
||||
|
||||
## Desktop auto-update notes
|
||||
|
||||
- Runtime updater: `electron-updater` in `apps/desktop/src/main.ts`.
|
||||
@@ -293,6 +313,7 @@ Checklist:
|
||||
5. Verify workflow steps:
|
||||
- preflight passes
|
||||
- all matrix builds pass
|
||||
- `publish_cli` publishes the exact release version before the release job
|
||||
- release job uploads expected files
|
||||
6. Smoke test downloaded artifacts.
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Running T3 Code in the Background
|
||||
|
||||
On a Linux host, T3 Code can run as a background service for your user. It starts when the machine
|
||||
boots and keeps running after you log out.
|
||||
|
||||
## Manage the Service
|
||||
|
||||
Install it with the latest T3 Code release:
|
||||
|
||||
```sh
|
||||
npx t3@latest service install
|
||||
```
|
||||
|
||||
Check whether it is installed:
|
||||
|
||||
```sh
|
||||
npx t3@latest service status
|
||||
```
|
||||
|
||||
Update or repair it:
|
||||
|
||||
```sh
|
||||
npx t3@latest service update
|
||||
```
|
||||
|
||||
Stop it and remove it from startup:
|
||||
|
||||
```sh
|
||||
npx t3@latest service uninstall
|
||||
```
|
||||
|
||||
Updating restarts T3 Code briefly. Let active agent work and terminal commands finish first.
|
||||
|
||||
## Using It with T3 Connect
|
||||
|
||||
T3 Connect may offer to install the service during setup so the host stays reachable after you log
|
||||
out. This is only an onboarding shortcut: the service and T3 Connect are managed separately.
|
||||
|
||||
Signing out of T3 Connect does not remove the service. Use `t3 service uninstall` when you no longer
|
||||
want T3 Code to start in the background.
|
||||
|
||||
The background service currently requires Linux with systemd.
|
||||
@@ -152,6 +152,19 @@ With mise/asdf/fnm/nodenv, make sure the tool's shim directory is installed and
|
||||
|
||||
If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.
|
||||
|
||||
## Updating a Remote Server
|
||||
|
||||
When the T3 Code web or desktop app and a remote server use different versions, a warning appears in
|
||||
the conversation and in **Settings** → **Connections**. Follow the action shown there: T3 Code may
|
||||
be able to update and reconnect the server for you, or it may ask you to update the desktop app or
|
||||
run a copied command on the server machine.
|
||||
|
||||
Finish active work before updating because the server restarts briefly. For step-by-step guidance,
|
||||
see [Keeping T3 Code in Sync](./server-updates.md).
|
||||
|
||||
On a Linux host, you can keep the server running after logout and manage it independently of the
|
||||
connection method. See [Running T3 Code in the Background](./background-service.md).
|
||||
|
||||
## How Pairing Works
|
||||
|
||||
The remote device does not need a long-lived secret up front.
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Keeping T3 Code in Sync
|
||||
|
||||
The T3 Code web or desktop app and the server it connects to work best when they use the same
|
||||
version. If they do not match, T3 Code shows a warning with the right update option for that server.
|
||||
|
||||
## Where to Find the Update
|
||||
|
||||
You may see the warning in either of these places:
|
||||
|
||||
- above the message box in the current conversation
|
||||
- **Settings** → **Connections**, beside the affected connection
|
||||
|
||||
Dismissing the conversation warning only hides that reminder for those two versions. It does not
|
||||
update the server, and the version difference remains visible in Connections.
|
||||
|
||||
## Before You Update
|
||||
|
||||
Let active agent work and terminal commands finish first. Updating restarts the server, so the
|
||||
connection will disappear briefly and work that is still running may be interrupted.
|
||||
|
||||
The update does not remove saved threads, settings, or project files.
|
||||
|
||||
## Choose the Action You See
|
||||
|
||||
| Action | What to do |
|
||||
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Update server** | Select the button and leave T3 Code open. It prepares the matching version, restarts the server, and reconnects automatically. This can take several minutes. |
|
||||
| **Update the desktop app** | Open the T3 Code desktop app on the machine that runs the server and install the app update there. Reopen it if needed. |
|
||||
| **Copy update command** | Copy the command, open a terminal on the server machine, stop the current T3 Code server, and relaunch it with the copied command and any startup options you normally use. |
|
||||
|
||||
The available action depends on how that server was started. T3 Code does not update connected
|
||||
servers silently in the background.
|
||||
|
||||
If the server uses the T3 Code background service, you can also update it directly on the host:
|
||||
|
||||
```sh
|
||||
npx t3@latest service update
|
||||
```
|
||||
|
||||
See [Running T3 Code in the Background](./background-service.md) for install, status, and removal
|
||||
commands.
|
||||
|
||||
## After the Update
|
||||
|
||||
Keep the web or desktop app open while the server restarts. When it reconnects with the matching
|
||||
version, the warning and update action disappear.
|
||||
|
||||
If the client reports a timeout, the server may still be finishing the update. Wait a minute, then
|
||||
reconnect or open **Settings** → **Connections** again. If the warning remains:
|
||||
|
||||
1. Retry the offered action once.
|
||||
2. Make sure you updated the machine named in the warning, not only the device you are using.
|
||||
3. For a command-line server, relaunch it with `npx t3@<client-version>`, replacing
|
||||
`<client-version>` with the client version shown in the warning.
|
||||
|
||||
For remote connection setup and access troubleshooting, see [Remote Access](./remote-access.md).
|
||||
@@ -321,6 +321,12 @@ export function createServerEnvironmentAtoms<R, E>(
|
||||
scheduler: configScheduler,
|
||||
concurrency: configConcurrency,
|
||||
}),
|
||||
updateServer: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:update-server",
|
||||
tag: WS_METHODS.serverUpdateServer,
|
||||
scheduler: configScheduler,
|
||||
concurrency: configConcurrency,
|
||||
}),
|
||||
upsertKeybinding: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:upsert-keybinding",
|
||||
tag: WS_METHODS.serverUpsertKeybinding,
|
||||
|
||||
@@ -20,6 +20,23 @@ export const ExecutionEnvironmentPlatform = Schema.Struct({
|
||||
});
|
||||
export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;
|
||||
|
||||
/** How a server can replace itself with another version when asked over RPC:
|
||||
"boot-service" rewrites the systemd user unit and restarts it; "respawn"
|
||||
installs the target version and respawns the foreground process. */
|
||||
export const ServerSelfUpdateMethod = Schema.Literals(["boot-service", "respawn"]);
|
||||
export type ServerSelfUpdateMethod = typeof ServerSelfUpdateMethod.Type;
|
||||
|
||||
/** What update path a client should offer for a server: one of the RPC
|
||||
self-update methods above, or "desktop-managed" when the backend's
|
||||
version belongs to the T3 Code desktop app supervising it — updating the
|
||||
app on that machine is the only way to update the server. */
|
||||
export const ServerSelfUpdateCapability = Schema.Literals([
|
||||
"boot-service",
|
||||
"respawn",
|
||||
"desktop-managed",
|
||||
]);
|
||||
export type ServerSelfUpdateCapability = typeof ServerSelfUpdateCapability.Type;
|
||||
|
||||
export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
repositoryIdentity: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
connectionProbe: Schema.optionalKey(Schema.Boolean),
|
||||
@@ -27,6 +44,10 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
pre-settlement servers, so clients treat missing as unsupported and
|
||||
never send the commands under version skew. */
|
||||
threadSettlement: Schema.optionalKey(Schema.Boolean),
|
||||
/** The update path clients should offer for this server. Absent on
|
||||
servers that must be relaunched manually (dev checkouts, Windows
|
||||
foreground runs, pre-update servers). */
|
||||
serverSelfUpdate: Schema.optionalKey(ServerSelfUpdateCapability),
|
||||
});
|
||||
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
|
||||
|
||||
|
||||
@@ -122,6 +122,9 @@ import {
|
||||
ServerRemoveKeybindingInput,
|
||||
ServerRemoveKeybindingResult,
|
||||
ServerProviderUpdatedPayload,
|
||||
ServerSelfUpdateError,
|
||||
ServerSelfUpdateInput,
|
||||
ServerSelfUpdateResult,
|
||||
ServerTraceDiagnosticsResult,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessResourceHistoryInput,
|
||||
@@ -205,6 +208,7 @@ export const WS_METHODS = {
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverRefreshProviders: "server.refreshProviders",
|
||||
serverUpdateProvider: "server.updateProvider",
|
||||
serverUpdateServer: "server.updateServer",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
serverRemoveKeybinding: "server.removeKeybinding",
|
||||
serverGetSettings: "server.getSettings",
|
||||
@@ -279,6 +283,12 @@ export const WsServerUpdateProviderRpc = Rpc.make(WS_METHODS.serverUpdateProvide
|
||||
error: Schema.Union([ServerProviderUpdateError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsServerUpdateServerRpc = Rpc.make(WS_METHODS.serverUpdateServer, {
|
||||
payload: ServerSelfUpdateInput,
|
||||
success: ServerSelfUpdateResult,
|
||||
error: Schema.Union([ServerSelfUpdateError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {
|
||||
payload: Schema.Struct({}),
|
||||
success: ServerSettings,
|
||||
@@ -693,6 +703,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetConfigRpc,
|
||||
WsServerRefreshProvidersRpc,
|
||||
WsServerUpdateProviderRpc,
|
||||
WsServerUpdateServerRpc,
|
||||
WsServerUpsertKeybindingRpc,
|
||||
WsServerRemoveKeybindingRpc,
|
||||
WsServerGetSettingsRpc,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
|
||||
import { ExecutionEnvironmentDescriptor, ServerSelfUpdateMethod } from "./environment.ts";
|
||||
import { ServerAuthDescriptor } from "./auth.ts";
|
||||
import {
|
||||
IsoDateTime,
|
||||
@@ -574,3 +574,30 @@ export class ServerProviderUpdateError extends Schema.TaggedErrorClass<ServerPro
|
||||
return `Provider update failed for ${this.provider}: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ServerSelfUpdateInput = Schema.Struct({
|
||||
/** Exact npm version of the `t3` package to install (never a dist-tag, so
|
||||
the server and the acknowledging client agree on what was requested). */
|
||||
targetVersion: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
|
||||
|
||||
/** Acknowledgement that the update artifact is installed and the server is
|
||||
about to restart into it — the connection will drop moments later. */
|
||||
export const ServerSelfUpdateResult = Schema.Struct({
|
||||
targetVersion: TrimmedNonEmptyString,
|
||||
method: ServerSelfUpdateMethod,
|
||||
});
|
||||
export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
|
||||
|
||||
export class ServerSelfUpdateError extends Schema.TaggedErrorClass<ServerSelfUpdateError>()(
|
||||
"ServerSelfUpdateError",
|
||||
{
|
||||
reason: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server update failed: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user