Skip to content

Commit f9248df

Browse files
fix(web,server): the server update banner copies a command that works under systemd
When a server cannot update itself, the banner copied `npx t3@<version>` and said to relaunch "using the same subcommand and options". The command dropped the subcommand, gave no hint that the old server must finish exiting first, and could never work when a systemd unit restarts the server on its pinned version. The server now reports whether it runs headless (`serve`) and which systemd unit, if any, holds it. The client copies the command that fits: switching a user unit to T3 Code's own service, restarting a system unit after its version is changed, or relaunching with the right subcommand. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6490a9e commit f9248df

9 files changed

Lines changed: 179 additions & 44 deletions

File tree

‎apps/server/src/cli/invocation.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,30 @@ import * as Path from "effect/Path";
77

88
import packageJson from "../../package.json" with { type: "json" };
99
import {
10+
parseSystemdUnit,
1011
resolveHostCliCommand,
1112
resolveRootCliCommand,
1213
resolveServerInstallation,
1314
} from "./invocation.ts";
1415

16+
it("names only the service unit that would restart a stopped server", () => {
17+
for (const [cgroup, expected] of [
18+
[
19+
"0::/user.slice/user-1000.slice/[email protected]/app.slice/t3.service\n",
20+
{ name: "t3.service", scope: "user" },
21+
],
22+
[
23+
"12:cpu,cpuacct:/system.slice/t3.service\n1:name=systemd:/system.slice/t3.service\n",
24+
{ name: "t3.service", scope: "system" },
25+
],
26+
["0::/user.slice/user-1000.slice/session-4.scope", null],
27+
["0::/user.slice/user-1000.slice/[email protected]", null],
28+
["0::/", null],
29+
] as const) {
30+
expect(parseSystemdUnit(cgroup)).toEqual(expected);
31+
}
32+
});
33+
1534
it.layer(NodeServices.layer)("root CLI commands", (it) => {
1635
const rootCommand = (input: {
1736
readonly node: string;

‎apps/server/src/cli/invocation.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import * as Option from "effect/Option";
44
import * as Path from "effect/Path";
55
import * as Schema from "effect/Schema";
66

7-
import type { ServerInstallation } from "@t3tools/contracts";
7+
import type { ServerInstallation, ServerSystemdUnit } from "@t3tools/contracts";
88
import * as HostProcess from "@t3tools/shared/HostProcess";
99
import { isCommandAvailable } from "@t3tools/shared/shell";
1010

@@ -100,6 +100,28 @@ export const resolveServerInstallation = Effect.gen(function* () {
100100
return { kind: "npm-global", prefix } satisfies ServerInstallation;
101101
}).pipe(Effect.orElseSucceed(() => null));
102102

103+
/**
104+
* The service unit whose cgroup holds this process. Terminals, SSH and tmux
105+
* place what they start in `.scope` units, so only a supervisor that restarts
106+
* the server on exit leaves it directly under a `.service`.
107+
*/
108+
export function parseSystemdUnit(cgroup: string): ServerSystemdUnit | null {
109+
const path = cgroup
110+
.split("\n")
111+
.map((line) => /^(?:0::|\d+:name=systemd:)(\/.*)$/.exec(line.trim())?.[1])
112+
.find((match) => match !== undefined);
113+
const name = path?.split("/").at(-1);
114+
if (path === undefined || name === undefined || !name.endsWith(".service")) return null;
115+
if (/^user@\d+\.service$/.test(name)) return null;
116+
return { name, scope: /\/user@\d+\.service\//.test(path) ? "user" : "system" };
117+
}
118+
119+
export const resolveSystemdUnit = Effect.gen(function* () {
120+
if ((yield* HostProcess.Platform) !== "linux") return null;
121+
const fs = yield* FileSystem.FileSystem;
122+
return parseSystemdUnit(yield* fs.readFileString("/proc/self/cgroup"));
123+
}).pipe(Effect.orElseSucceed(() => null));
124+
103125
/**
104126
* The literal spec the user typed (e.g. `t3@nightly`) is resolved away before
105127
* our process starts, so re-derive it from the running version: nightly builds

‎apps/server/src/environment/ServerEnvironment.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,16 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
106106
Effect.provideService(HostProcess.Platform, "linux"),
107107
Effect.provideService(HostProcess.Environment, {}),
108108
);
109-
expect(descriptor.capabilities.serverInstallation).toEqual(
110-
mode === "web" ? { kind: "npm-global", prefix } : undefined,
111-
);
109+
// The real /proc/self/cgroup decides systemdUnit, so CI runners may add one.
110+
if (mode === "web") {
111+
expect(descriptor.capabilities.serverInstallation).toMatchObject({
112+
kind: "npm-global",
113+
prefix,
114+
});
115+
expect(descriptor.capabilities.serverInstallation).not.toHaveProperty("subcommand");
116+
} else {
117+
expect(descriptor.capabilities.serverInstallation).toBeUndefined();
118+
}
112119
expect(descriptor.capabilities.serverSelfUpdate).toBe(
113120
mode === "web" ? undefined : "desktop-managed",
114121
);

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import * as Schema from "effect/Schema";
1515

1616
import packageJson from "../../package.json" with { type: "json" };
1717
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
18-
import { resolveServerInstallation } from "../cli/invocation.ts";
18+
import { resolveServerInstallation, resolveSystemdUnit } from "../cli/invocation.ts";
1919
import { readAgentActivityPublishingActive } from "../cloud/config.ts";
2020
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
2121
import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
@@ -197,7 +197,18 @@ export const make = Effect.gen(function* () {
197197
desktopManaged: serverConfig.mode === "desktop",
198198
launcherManaged: launcher.managed,
199199
});
200-
const serverInstallation = serverSelfUpdate === null ? yield* resolveServerInstallation : null;
200+
const installation = serverSelfUpdate === null ? yield* resolveServerInstallation : null;
201+
const systemdUnit = installation === null ? null : yield* resolveSystemdUnit;
202+
const serverInstallation =
203+
installation === null
204+
? null
205+
: {
206+
...installation,
207+
...(serverConfig.startupPresentation === "headless"
208+
? { subcommand: "serve" as const }
209+
: {}),
210+
...(systemdUnit === null ? {} : { systemdUnit }),
211+
};
201212
// Static is correct: the control fd is known at bootstrap, and the desktop
202213
// app and its bundled server ship in one artifact, so a present fd means the
203214
// app speaks the requestDesktopUpdate protocol.

‎apps/web/src/components/ServerUpdateAction.tsx‎

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import { useEnvironmentSettings } from "~/hooks/useSettings";
2626
import { serverEnvironment, updateOutdatedServer } from "~/state/server";
2727
import { appAtomRegistry } from "~/rpc/atomRegistry";
2828
import { useAtomCommand } from "~/state/use-atom-command";
29-
import { manualServerUpdateCommand } from "~/versionSkew";
29+
import { type ManualServerUpdate, manualServerUpdate } from "~/versionSkew";
3030
import { Button } from "./ui/button";
3131
import { toastManager } from "./ui/toast";
3232
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -224,18 +224,12 @@ export function ServerUpdateAction({
224224
(settings) => settings.continueThreadsAfterServerUpdate,
225225
);
226226
const update = useServerUpdate();
227-
const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
228-
target: installation?.kind === "npm-global" ? "update command" : "relaunch command",
229-
onCopy: ({ command }) => {
230-
toastManager.add({
231-
type: "success",
232-
title:
233-
installation?.kind === "npm-global" ? "Update command copied" : "Relaunch command copied",
234-
description:
235-
installation?.kind === "npm-global"
236-
? `Run \`${command}\` on ${serverLabel}, then restart t3 with your usual options.`
237-
: `Stop t3 on ${serverLabel}, then relaunch with \`${command}\` using the same subcommand and options. This does not update an installed t3 command.`,
238-
});
227+
const manual =
228+
selfUpdate === null ? manualServerUpdate(targetVersion, serverLabel, installation) : null;
229+
const { copyToClipboard } = useCopyToClipboard<ManualServerUpdate>({
230+
target: "update command",
231+
onCopy: ({ title, description }) => {
232+
toastManager.add({ type: "success", title, description });
239233
},
240234
onError: (error) => {
241235
toastManager.add({
@@ -282,18 +276,9 @@ export function ServerUpdateAction({
282276
);
283277
}
284278

285-
const manualCommand =
286-
selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
287-
const actionLabel =
288-
manualCommand !== null
289-
? installation?.kind === "npm-global"
290-
? "Copy update command"
291-
: "Copy relaunch command"
292-
: label;
279+
const actionLabel = manual !== null ? manual.label : label;
293280
const onClick =
294-
manualCommand !== null
295-
? () => copyToClipboard(manualCommand, { command: manualCommand })
296-
: () => void handleUpdate();
281+
manual !== null ? () => copyToClipboard(manual.command, manual) : () => void handleUpdate();
297282

298283
if (appearance === "icon") {
299284
return (
@@ -305,7 +290,7 @@ export function ServerUpdateAction({
305290
variant="ghost-muted"
306291
className={className}
307292
aria-label={`${actionLabel} for ${serverLabel}`}
308-
disabled={manualCommand === null && !canUpdate}
293+
disabled={manual === null && !canUpdate}
309294
onClick={onClick}
310295
/>
311296
}
@@ -322,7 +307,7 @@ export function ServerUpdateAction({
322307
size={size}
323308
variant={variant}
324309
className={className}
325-
disabled={manualCommand === null && !canUpdate}
310+
disabled={manual === null && !canUpdate}
326311
onClick={onClick}
327312
>
328313
{actionLabel}

‎apps/web/src/versionSkew.test.ts‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { EnvironmentId } from "@t3tools/contracts";
1+
import { EnvironmentId, type ServerInstallation } from "@t3tools/contracts";
22
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
33
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
44

@@ -12,21 +12,48 @@ import {
1212
dismissVersionMismatch,
1313
isServerUpdateFailureDismissed,
1414
isVersionMismatchDismissed,
15-
manualServerUpdateCommand,
15+
manualServerUpdate,
1616
resolveVersionMismatch,
1717
} from "./versionSkew";
1818

1919
const MISMATCH_HINT =
2020
"Version mismatch. Try syncing the client and server to the same T3 Code version.";
2121

2222
describe("versionSkew", () => {
23+
const command = (installation?: ServerInstallation) =>
24+
manualServerUpdate("0.0.45", "vm", installation).command;
25+
const userUnit = { name: "t3.service", scope: "user" } as const;
26+
2327
it("updates only the proven npm prefix and safely quotes its path", () => {
24-
expect(manualServerUpdateCommand("0.0.45", { kind: "npm-global", prefix: "/opt/node" })).toBe(
28+
expect(command({ kind: "npm-global", prefix: "/opt/node" })).toBe(
2529
"npm install --global --prefix '/opt/node' [email protected]",
2630
);
31+
expect(command({ kind: "npm-global", prefix: "/opt/maria's node" })).toBe(
32+
"npm install --global --prefix '/opt/maria'\\''s node' [email protected]",
33+
);
34+
});
35+
36+
it("relaunches with the subcommand the server runs", () => {
37+
expect(command()).toBe("npx [email protected]");
38+
expect(command({ kind: "bunx", subcommand: "serve" })).toBe("bunx [email protected] serve");
39+
});
40+
41+
it("goes through the systemd unit that would restart the old version", () => {
42+
expect(command({ kind: "npx", subcommand: "serve", systemdUnit: userUnit })).toBe(
43+
"systemctl --user disable --now t3.service && npx [email protected] service install",
44+
);
45+
expect(command({ kind: "npm-global", prefix: "/opt/node", systemdUnit: userUnit })).toBe(
46+
"npm install --global --prefix '/opt/node' [email protected] && systemctl --user restart t3.service",
47+
);
2748
expect(
28-
manualServerUpdateCommand("0.0.45", { kind: "npm-global", prefix: "/opt/maria's node" }),
29-
).toBe("npm install --global --prefix '/opt/maria'\\''s node' [email protected]");
49+
manualServerUpdate("0.0.45", "vm", {
50+
kind: "npx",
51+
systemdUnit: { name: "t3.service", scope: "system" },
52+
}),
53+
).toMatchObject({
54+
command: "sudo systemctl restart t3.service",
55+
description: expect.stringContaining("ExecStart"),
56+
});
3057
});
3158
beforeEach(() => {
3259
branding.APP_VERSION = "0.0.34";

‎apps/web/src/versionSkew.ts‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,17 +101,61 @@ export function supportsServerUpdateThreadContinuation(
101101
return serverConfig?.environment.capabilities.serverUpdateThreadContinuation === true;
102102
}
103103

104-
export function manualServerUpdateCommand(
104+
export interface ManualServerUpdate {
105+
readonly command: string;
106+
readonly label: string;
107+
readonly title: string;
108+
readonly description: string;
109+
}
110+
111+
/**
112+
* A server's supervisor restarts it at the version it pins, so a relaunch typed
113+
* by hand only collides with it; the command has to go through that unit.
114+
*/
115+
export function manualServerUpdate(
105116
targetVersion: string,
117+
serverLabel: string,
106118
installation?: ServerInstallation,
107-
): string {
119+
): ManualServerUpdate {
120+
const unit = installation?.systemdUnit;
121+
const systemctl = unit?.scope === "user" ? "systemctl --user" : "sudo systemctl";
108122
if (installation?.kind === "npm-global") {
109123
const prefix = `'${installation.prefix.replaceAll("'", "'\\''")}'`;
110-
return `npm install --global --prefix ${prefix} t3@${targetVersion}`;
124+
const install = `npm install --global --prefix ${prefix} t3@${targetVersion}`;
125+
return {
126+
command: unit ? `${install} && ${systemctl} restart ${unit.name}` : install,
127+
label: "Copy update command",
128+
title: "Update command copied",
129+
description: unit
130+
? `Run it on ${serverLabel}. It also restarts ${unit.name}, which runs this server.`
131+
: `Run it on ${serverLabel}, then restart t3 there with your usual options.`,
132+
};
111133
}
112134
const runner =
113135
installation?.kind === "pnpm-dlx" ? "pnpm dlx" : installation?.kind === "bunx" ? "bunx" : "npx";
114-
return `${runner} t3@${targetVersion}`;
136+
const launch = `${runner} t3@${targetVersion}`;
137+
if (unit?.scope === "user") {
138+
return {
139+
command: `${systemctl} disable --now ${unit.name} && ${launch} service install`,
140+
label: "Copy update command",
141+
title: "Update command copied",
142+
description: `${unit.name} on ${serverLabel} keeps restarting this server on its old version. Run the command there: it turns ${unit.name} off and installs T3 Code's own service on t3@${targetVersion}, which updates in one click next time. Running agents stop.`,
143+
};
144+
}
145+
if (unit) {
146+
return {
147+
command: `${systemctl} restart ${unit.name}`,
148+
label: "Copy restart command",
149+
title: "Restart command copied",
150+
description: `The system service ${unit.name} runs this server on ${serverLabel}. Change the t3 version in its ExecStart to t3@${targetVersion}, then run the command.`,
151+
};
152+
}
153+
return {
154+
command: installation?.subcommand ? `${launch} ${installation.subcommand}` : launch,
155+
label: "Copy relaunch command",
156+
title: "Relaunch command copied",
157+
description: `On ${serverLabel}, stop t3 (Ctrl+C where it runs) and wait for it to exit, then run the command, adding any options you started it with. This does not update an installed t3 command.`,
158+
};
115159
}
116160

117161
export function serverUpdateGuidance(capability: ServerSelfUpdateCapability): string {

‎packages/contracts/src/environment.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@ const descriptor = {
1616
describe("ExecutionEnvironmentDescriptor", () => {
1717
it("decodes old, recognized and future manual installation descriptors", () => {
1818
expect(decodeDescriptor(descriptor).capabilities.serverInstallation).toBeUndefined();
19-
for (const installation of [{ kind: "npx" }, { kind: "npm-global", prefix: "/opt/node" }]) {
19+
for (const installation of [
20+
{ kind: "npx" },
21+
{ kind: "npx", subcommand: "serve", systemdUnit: { name: "t3.service", scope: "user" } },
22+
{ kind: "npm-global", prefix: "/opt/node" },
23+
]) {
2024
expect(
2125
decodeDescriptor({
2226
...descriptor,

‎packages/contracts/src/environment.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,25 @@ export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.T
5858
export const ServerSelfUpdateMethod = Schema.Literals(["boot-service", "respawn", "desktop-app"]);
5959
export type ServerSelfUpdateMethod = typeof ServerSelfUpdateMethod.Type;
6060

61+
/** A systemd unit other than T3 Code's own service, which restarts the server if it is stopped by hand. */
62+
export const ServerSystemdUnit = Schema.Struct({
63+
name: TrimmedNonEmptyString,
64+
scope: Schema.Literals(["user", "system"]),
65+
});
66+
export type ServerSystemdUnit = typeof ServerSystemdUnit.Type;
67+
68+
const serverLaunchFields = {
69+
subcommand: Schema.optionalKey(Schema.Literal("serve")),
70+
systemdUnit: Schema.optionalKey(ServerSystemdUnit),
71+
};
72+
6173
export const ServerInstallation = Schema.Union([
62-
Schema.Struct({ kind: Schema.Literals(["npx", "pnpm-dlx", "bunx"]) }),
63-
Schema.Struct({ kind: Schema.Literal("npm-global"), prefix: TrimmedNonEmptyString }),
74+
Schema.Struct({ kind: Schema.Literals(["npx", "pnpm-dlx", "bunx"]), ...serverLaunchFields }),
75+
Schema.Struct({
76+
kind: Schema.Literal("npm-global"),
77+
prefix: TrimmedNonEmptyString,
78+
...serverLaunchFields,
79+
}),
6480
]);
6581
export type ServerInstallation = typeof ServerInstallation.Type;
6682

0 commit comments

Comments
 (0)