Skip to content

Commit c3ffcff

Browse files
feat(cli): make t3 update ask before restarting and point out a manual server
t3 update restarted the background service unconditionally and said nothing about a server the user had started by hand, which kept running the old version with no hint. Now the command states what it will touch before downloading, asks for consent to restart the service (a restart interrupts agent turns, terminals, and remote clients), and from a non-interactive shell leaves the service alone unless --yes is passed. A server started by hand is never touched; the summary names its origin and pid so the user can restart it themselves. The server records whether it is supervised by the boot service in server-runtime.json so a CLI can tell the two cases apart; servers from before that field are recognised by lineage (the unit's cgroup on Linux, the launcher as parent on macOS). Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent b845e84 commit c3ffcff

5 files changed

Lines changed: 161 additions & 20 deletions

File tree

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

Lines changed: 119 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import * as Layer from "effect/Layer";
2323
import * as Option from "effect/Option";
2424
import * as Path from "effect/Path";
2525
import * as Schema from "effect/Schema";
26-
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
26+
import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
2727
import {
2828
FetchHttpClient,
2929
HttpClient,
@@ -41,6 +41,7 @@ import {
4141
} from "../cloud/pinnedRuntime.ts";
4242
import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
4343
import * as ProcessRunner from "../processRunner.ts";
44+
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
4445
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
4546
import { bootServiceLayer } from "./service.ts";
4647

@@ -160,6 +161,13 @@ const updateFlags = {
160161
Flag.withDescription("Allow moving to an older version than the one running."),
161162
Flag.withDefault(false),
162163
),
164+
yes: Flag.boolean("yes").pipe(
165+
Flag.withAlias("y"),
166+
Flag.withDescription(
167+
"Restart the background service without asking. Required to restart it from a script, where there is no prompt.",
168+
),
169+
Flag.withDefault(false),
170+
),
163171
};
164172

165173
const versionArgument = Argument.string("version").pipe(
@@ -182,9 +190,11 @@ export const updateCommand = Command.make("update", {
182190
const config = yield* resolveCliAuthConfig(flags, logLevel);
183191
return yield* runUpdate({
184192
baseDir: config.baseDir,
193+
serverRuntimeStatePath: config.serverRuntimeStatePath,
185194
channel: Option.getOrUndefined(flags.channel),
186195
requestedVersion: Option.getOrUndefined(flags.version),
187196
allowDowngrade: flags.allowDowngrade,
197+
assumeYes: flags.yes,
188198
}).pipe(
189199
Effect.provide(
190200
Layer.mergeAll(bootServiceLayer(config), ProcessRunner.layer, FetchHttpClient.layer),
@@ -194,11 +204,67 @@ export const updateCommand = Command.make("update", {
194204
),
195205
);
196206

207+
/**
208+
* A `t3 serve` or `t3` someone started by hand, as opposed to the one the
209+
* background service supervises. The server records its pid on startup; a
210+
* stale file from a crashed server is ignored by checking the pid is alive.
211+
*
212+
* Servers from before `serviceManaged` was recorded cannot be told apart by
213+
* the file alone, so the launcher-supervised case is also recognised by
214+
* lineage: a service server's parent is the launcher, and on Linux that
215+
* launcher runs inside the unit's cgroup.
216+
*/
217+
const findForegroundServer = Effect.fn("cli.update.find_foreground_server")(function* (input: {
218+
readonly serverRuntimeStatePath: string;
219+
readonly serviceInstalled: boolean;
220+
}) {
221+
const state = yield* readPersistedServerRuntimeState(input.serverRuntimeStatePath);
222+
if (Option.isNone(state) || state.value.serviceManaged || !isProcessAlive(state.value.pid)) {
223+
return undefined;
224+
}
225+
if (input.serviceInstalled && (yield* belongsToBootService(state.value.pid))) return undefined;
226+
return state.value;
227+
});
228+
229+
const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(function* (
230+
pid: number,
231+
) {
232+
const platform = yield* HostProcessPlatform;
233+
const fs = yield* FileSystem.FileSystem;
234+
const runner = yield* ProcessRunner.ProcessRunner;
235+
if (platform === "linux") {
236+
const cgroup = yield* fs.readFileString(`/proc/${pid}/cgroup`).pipe(Effect.option);
237+
return Option.isSome(cgroup) && cgroup.value.includes("/t3code.service");
238+
}
239+
if (platform === "darwin") {
240+
// The service server's parent is the launcher process.
241+
const parent = yield* runner
242+
.run({
243+
command: "ps",
244+
args: ["-o", "ppid=", "-p", String(pid)],
245+
timeout: Duration.seconds(5),
246+
})
247+
.pipe(Effect.option);
248+
const ppid = Option.isSome(parent) && parent.value.code === 0 ? parent.value.stdout.trim() : "";
249+
if (!/^\d+$/.test(ppid)) return false;
250+
const command = yield* runner
251+
.run({ command: "ps", args: ["-o", "command=", "-p", ppid], timeout: Duration.seconds(5) })
252+
.pipe(
253+
Effect.map((result) => (result.code === 0 ? result.stdout : "")),
254+
Effect.orElseSucceed(() => ""),
255+
);
256+
return /__service-launcher|service-launcher\.mjs/.test(command);
257+
}
258+
return false;
259+
});
260+
197261
const runUpdate = Effect.fn("cli.update.run")(function* (input: {
198262
readonly baseDir: string;
263+
readonly serverRuntimeStatePath: string;
199264
readonly channel: CliReleaseChannel | undefined;
200265
readonly requestedVersion: string | undefined;
201266
readonly allowDowngrade: boolean;
267+
readonly assumeYes: boolean;
202268
}) {
203269
const fs = yield* FileSystem.FileSystem;
204270
const path = yield* Path.Path;
@@ -244,11 +310,48 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
244310
Effect.map((sentinel) => sentinel.trim() === targetVersion),
245311
Effect.orElseSucceed(() => false),
246312
);
313+
314+
// Work out everything that will be touched before touching anything, so the
315+
// user sees one plan and one question rather than a surprise restart.
316+
const status = yield* service.status;
317+
// The unit name is per user, not per T3 home. Only touch the service when it
318+
// serves the home this update targets; otherwise it belongs to another
319+
// install on this machine and restarting it would take that server down.
320+
const servesThisHome =
321+
status.installedBaseDir !== undefined &&
322+
path.resolve(status.installedBaseDir) === path.resolve(input.baseDir);
323+
const serviceInstalled = status.supported && status.installed && servesThisHome;
324+
const foreground = yield* findForegroundServer({
325+
serverRuntimeStatePath: input.serverRuntimeStatePath,
326+
serviceInstalled,
327+
});
328+
247329
yield* Console.log(
248330
alreadyOnDisk
249-
? `Switching t3 ${currentVersion} -> ${targetVersion} (${targetChannel}, already downloaded)...`
250-
: `Updating t3 ${currentVersion} -> ${targetVersion} (${targetChannel})...`,
331+
? `Switching t3 ${currentVersion} -> ${targetVersion} (${targetChannel}, already downloaded).`
332+
: `Updating t3 ${currentVersion} -> ${targetVersion} (${targetChannel}).`,
251333
);
334+
let restartService = false;
335+
if (serviceInstalled) {
336+
yield* Console.log(
337+
" A background service is installed for this T3 home. Restarting it interrupts anything running in it: agent turns, terminals, remote clients.",
338+
);
339+
if (input.assumeYes) {
340+
restartService = true;
341+
} else if (process.stdin.isTTY && process.stdout.isTTY) {
342+
restartService = yield* Prompt.run(
343+
Prompt.confirm({
344+
message: "Restart the background service once the download is verified?",
345+
initial: true,
346+
}),
347+
).pipe(Effect.catchTag("QuitError", () => Effect.succeed(false)));
348+
} else {
349+
yield* Console.log(
350+
" Not a terminal, so the service is left on its current version. Rerun with --yes to restart it, or run `t3 service update` later.",
351+
);
352+
}
353+
}
354+
252355
const runtime = yield* ensurePinnedRuntimeInstalled({
253356
baseDir: input.baseDir,
254357
version: targetVersion,
@@ -309,15 +412,8 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
309412

310413
// The new executable owns the service switch: it verifies itself, writes its
311414
// own version into the unit, and restarts the service on it.
312-
const status = yield* service.status;
313415
let serviceUpdated = false;
314-
// The unit name is per user, not per T3 home. Only touch the service when it
315-
// serves the home this update targets; otherwise it belongs to another
316-
// install on this machine and restarting it would take that server down.
317-
const servesThisHome =
318-
status.installedBaseDir !== undefined &&
319-
path.resolve(status.installedBaseDir) === path.resolve(input.baseDir);
320-
if (status.supported && status.installed && servesThisHome) {
416+
if (restartService) {
321417
const result = yield* runner.run({
322418
command: runtime.entryPath,
323419
args: [
@@ -337,17 +433,27 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
337433
serviceUpdated = true;
338434
}
339435

340-
yield* Console.log(`t3 ${targetVersion} is at ${runtime.entryPath}`);
436+
yield* Console.log("");
437+
yield* Console.log(`t3 ${targetVersion} is installed at ${runtime.entryPath}`);
341438
if (Option.isSome(repointed)) {
342439
yield* Console.log(` ${repointed.value} now runs ${targetVersion}`);
343440
} else {
344441
yield* Console.log(` Run it as ${runtime.entryPath}, or point your \`t3\` launcher at it.`);
345442
}
346443
if (serviceUpdated) {
347-
yield* Console.log(` Background service updated to ${targetVersion}`);
444+
yield* Console.log(` Background service restarted on ${targetVersion}`);
445+
} else if (serviceInstalled) {
446+
yield* Console.log(
447+
` Background service still running ${status.installedVersion ?? currentVersion}. Run \`t3 service update\` when you are ready to restart it.`,
448+
);
348449
} else if (status.installed && !servesThisHome) {
349450
yield* Console.log(
350451
` The background service serves ${status.installedBaseDir ?? "another T3 home"} and was left unchanged.`,
351452
);
352453
}
454+
if (foreground !== undefined) {
455+
yield* Console.log(
456+
` A server started by hand is still running ${currentVersion} at ${foreground.origin} (pid ${foreground.pid}). Stop it and start it again to pick up ${targetVersion}.`,
457+
);
458+
}
353459
});

‎apps/server/src/server.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -566,9 +566,11 @@ const makeServerLayer = Layer.unwrap(
566566
return;
567567
}
568568

569+
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
569570
const state = yield* makePersistedServerRuntimeState({
570571
config,
571572
port: address.port,
573+
serviceManaged: launcher.managed,
572574
});
573575
yield* persistServerRuntimeState({
574576
path: config.serverRuntimeStatePath,
@@ -728,7 +730,7 @@ const makeServerLayer = Layer.unwrap(
728730
const serverApplicationLayer = Layer.mergeAll(
729731
routesLayer,
730732
httpListeningLayer,
731-
runtimeStateLayer,
733+
runtimeStateLayer.pipe(Layer.provide(launcherLayer)),
732734
tailscaleServeLayer,
733735
cloudDesiredLinkReconcileLayer,
734736
);

‎apps/server/src/serverRuntimeState.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,25 @@ describe("serverRuntimeState", () => {
6262
}),
6363
);
6464

65+
it.effect("marks a service-supervised server so CLIs can tell it from a manual one", () =>
66+
Effect.gen(function* () {
67+
const managed = yield* ServerRuntimeState.makePersistedServerRuntimeState({
68+
config: { host: undefined, devUrl: undefined },
69+
port: 13_773,
70+
serviceManaged: true,
71+
});
72+
const manual = yield* ServerRuntimeState.makePersistedServerRuntimeState({
73+
config: { host: undefined, devUrl: undefined },
74+
port: 13_773,
75+
});
76+
77+
assert.isTrue(managed.serviceManaged);
78+
// Older readers decode the file without the field, so it is omitted
79+
// rather than written as false.
80+
assert.isFalse("serviceManaged" in manual);
81+
}),
82+
);
83+
6584
it.effect("treats a missing runtime state file as absent", () =>
6685
Effect.gen(function* () {
6786
const fileSystem = yield* FileSystem.FileSystem;

‎apps/server/src/serverRuntimeState.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@ export const PersistedServerRuntimeState = Schema.Struct({
1818
// Dev is single-origin: browsers must pair through this URL, not `origin`.
1919
devUrl: Schema.optional(Schema.String),
2020
startedAt: Schema.String,
21+
/**
22+
* Set when the boot-service launcher supervises this server. Lets a CLI
23+
* tell a service-managed server apart from one started by hand, which is
24+
* the difference between "restart the service" and "stop your terminal".
25+
*/
26+
serviceManaged: Schema.optional(Schema.Boolean),
2127
});
2228
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
2329

@@ -50,6 +56,7 @@ const runtimeOriginForConfig = (
5056
export const makePersistedServerRuntimeState = (input: {
5157
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
5258
readonly port: number;
59+
readonly serviceManaged?: boolean;
5360
}): Effect.Effect<PersistedServerRuntimeState> =>
5461
Effect.map(DateTime.now, (now) => ({
5562
version: 1,
@@ -59,6 +66,7 @@ export const makePersistedServerRuntimeState = (input: {
5966
origin: runtimeOriginForConfig(input.config, input.port),
6067
...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
6168
startedAt: DateTime.formatIso(now),
69+
...(input.serviceManaged ? { serviceManaged: true } : {}),
6270
}));
6371

6472
export const persistServerRuntimeState = (input: {

‎docs/user/background-service.md‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,18 @@ run `t3 service install`. Set `T3CODE_VERSION` to pin an exact version, or
4242

4343
Once a self-contained `t3` is installed, `t3 update` moves the machine to a
4444
newer one without npm: it downloads the newest release on the channel the
45-
running `t3` came from, verifies it, points the `t3` launcher at it, and
46-
updates the background service when one is installed for the same T3 home.
47-
Pass an exact version (`t3 update 0.0.41-preview.20260912.1595`) to pin one,
48-
`--channel` to follow a different release train, or `--allow-downgrade` to
49-
move backwards. Versions published only to npm cannot be installed this way;
50-
the command says so and names the `npm install` to run instead.
45+
running `t3` came from, verifies it, and points the `t3` launcher at it. When
46+
a background service is installed for the same T3 home it asks before
47+
restarting it, since a restart interrupts running agent turns, terminals, and
48+
remote clients; answer no and the service keeps the old version until you run
49+
`t3 service update`. From a script there is no prompt, so pass `--yes` to
50+
restart the service. A server you started by hand is never touched; the
51+
command tells you it is still on the old version so you can restart it
52+
yourself. Pass an exact version (`t3 update 0.0.41-preview.20260912.1595`) to
53+
pin one, `--channel` to follow a different release train, or
54+
`--allow-downgrade` to move backwards. Versions published only to npm cannot
55+
be installed this way; the command says so and names the `npm install` to run
56+
instead.
5157

5258
## Platform support
5359

0 commit comments

Comments
 (0)