Skip to content

Commit 3298c83

Browse files
feat(cli): add t3 service restart and make t3 update repoint the service eagerly
t3 update now rewrites the service unit to the new version whether or not the user agrees to a restart, so declining and running t3 service restart later lands on the new version. service restart is the new way to apply a deferred update or kick a stuck service. service update did what service install does and is deprecated: hidden from help, prints where to go, still repairs. The status hints stop suggesting npx. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 73b206f commit 3298c83

5 files changed

Lines changed: 202 additions & 28 deletions

File tree

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

Lines changed: 66 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ it("reports the installed service version and host paths", () => {
4545
it("gives a direct repair command for a stale service", () => {
4646
assert.include(
4747
formatServiceStatus({ ...status, current: false }, "0.0.29"),
48-
"Next: Run `npx [email protected] service update`.",
48+
"Next: Run `t3 service install` to repair it.",
4949
);
5050
});
5151

@@ -64,17 +64,17 @@ it("explains an incomplete nightly installation and keeps repair on its installe
6464
expect(output).toContain("last login session ends");
6565
expect(output).toContain('sudo loginctl enable-linger "$(id -un)"');
6666
expect(output).toContain("[service-stopped]");
67-
expect(output).toContain("npx [email protected] service update");
68-
expect(output).not.toContain("t3@latest");
67+
expect(output).toContain("Run `t3 service install` to repair it.");
68+
expect(output).not.toContain("npx");
6969
});
7070

71-
it("suggests the newer CLI version when the installed service needs an update", () => {
71+
it("points an older service at a repair, never at npx", () => {
7272
const output = formatServiceStatus(
7373
{ ...status, current: false, installedVersion: "0.0.28" },
7474
"0.0.29",
7575
);
76-
expect(output).toContain("npx [email protected] service update");
77-
expect(output).not.toContain("npx [email protected] service update");
76+
expect(output).toContain("Run `t3 service install` to repair it.");
77+
expect(output).not.toContain("npx");
7878
});
7979

8080
it("explains where the service is supported", () => {
@@ -84,23 +84,28 @@ it("explains where the service is supported", () => {
8484
);
8585
});
8686

87-
it("reports a newer installed service and gives an exact-version repair command", () => {
87+
it("reports a newer installed service and tells the CLI to catch up to it", () => {
8888
const output = formatServiceStatus(
8989
{ ...status, current: false, installedVersion: "0.0.32-nightly.1" },
9090
"0.0.31",
9191
);
9292

9393
assert.include(output, "[email protected] (newer than this [email protected] CLI)");
94-
assert.include(output, "npx t3@0.0.32-nightly.1 service update");
95-
assert.notInclude(output, "npx t3@latest service update");
94+
assert.include(output, "Run `t3 update 0.0.32-nightly.1` to match it");
95+
assert.notInclude(output, "npx");
9696
});
9797

9898
const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };
9999

100100
function makeTestService(serviceStatus: BootService.BootServiceStatus) {
101101
const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
102+
const restarts: Array<true> = [];
102103
const service = BootService.BootService.of({
103104
status: Effect.succeed(serviceStatus),
105+
restart: Effect.sync(() => {
106+
restarts.push(true);
107+
return serviceStatus.installed;
108+
}),
104109
install: (options) =>
105110
Effect.sync(() => {
106111
installOptions.push(options);
@@ -113,10 +118,61 @@ function makeTestService(serviceStatus: BootService.BootServiceStatus) {
113118
}),
114119
uninstall: Effect.succeed(false),
115120
});
116-
return { service, installOptions };
121+
return { service, installOptions, restarts };
117122
}
118123

119124
it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands", (it) => {
125+
it.effect("restart restarts the installed service", () =>
126+
Effect.gen(function* () {
127+
const fs = yield* FileSystem.FileSystem;
128+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
129+
const { service, installOptions, restarts } = makeTestService(status);
130+
vi.spyOn(BootService, "layer").mockReturnValue(
131+
Layer.succeed(BootService.BootService, service),
132+
);
133+
134+
yield* Command.runWith(serviceCommand, { version: packageJson.version })([
135+
"restart",
136+
"--base-dir",
137+
baseDir,
138+
]).pipe(
139+
Effect.provideService(HostProcessEnvironment, {}),
140+
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
141+
);
142+
143+
expect(restarts).toEqual([true]);
144+
expect(installOptions).toEqual([]);
145+
}),
146+
);
147+
148+
it.effect("__reconcile --no-start writes the unit without starting the service", () =>
149+
Effect.gen(function* () {
150+
const fs = yield* FileSystem.FileSystem;
151+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
152+
const { service, installOptions, restarts } = makeTestService({
153+
...status,
154+
current: false,
155+
installedVersion: "0.0.0",
156+
});
157+
vi.spyOn(BootService, "layer").mockReturnValue(
158+
Layer.succeed(BootService.BootService, service),
159+
);
160+
161+
yield* Command.runWith(serviceCommand, { version: packageJson.version })([
162+
"__reconcile",
163+
"--no-start",
164+
"--base-dir",
165+
baseDir,
166+
]).pipe(
167+
Effect.provideService(HostProcessEnvironment, {}),
168+
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
169+
);
170+
171+
expect(installOptions).toEqual([{ allowDowngrade: false, start: false }]);
172+
expect(restarts).toEqual([]);
173+
}),
174+
);
175+
120176
it.effect.each(["install", "update"] as const)(
121177
"%s refuses a downgrade before changing the service",
122178
(command) =>

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

Lines changed: 53 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ export type ServiceReconcileResult =
3838
/** Install, update, or repair the service using the CLI version running this command. */
3939
export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
4040
readonly allowDowngrade?: boolean;
41+
readonly start?: boolean;
4142
}) {
4243
const service = yield* BootService.BootService;
4344
const status = yield* service.status;
@@ -87,7 +88,7 @@ export function formatServiceStatus(
8788
` Unit: ${status.unitPath}`,
8889
` Logs: ${status.logPath}`,
8990
...problems,
90-
` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,
91+
` Next: Run \`t3 update ${installedVersion}\` to match it, or pass \`--allow-downgrade\` to \`t3 service install\` explicitly.`,
9192
].join("\n");
9293
}
9394
return [
@@ -96,7 +97,7 @@ export function formatServiceStatus(
9697
` Unit: ${status.unitPath}`,
9798
` Logs: ${status.logPath}`,
9899
...problems,
99-
...(status.current ? [] : [` Next: Run \`npx t3@${cliVersion} service update\`.`]),
100+
...(status.current ? [] : [" Next: Run `t3 service install` to repair it."]),
100101
].join("\n");
101102
}
102103

@@ -138,14 +139,18 @@ const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pip
138139
),
139140
);
140141

142+
// Kept one release for muscle memory and old docs. It did what `t3 service
143+
// install` does; the way to move to a newer release is `t3 update`.
141144
const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
142-
Command.withDescription(
143-
"Update or repair the background service using this CLI version. Use `t3 update` to move to a newer release first.",
144-
),
145+
Command.withDescription("Deprecated. Run `t3 update` to move to a newer release."),
146+
Command.unlisted,
145147
Command.withHandler((flags) =>
146148
runServiceCommand(
147149
flags,
148150
Effect.gen(function* () {
151+
yield* Console.log(
152+
"`t3 service update` is deprecated: run `t3 update` to move to a newer release, or `t3 service install` to repair the service. Repairing now.",
153+
);
149154
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
150155
if (!result.changed) {
151156
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
@@ -159,6 +164,46 @@ const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
159164
),
160165
);
161166

167+
// Run by `t3 update` through the newly installed executable, so the version
168+
// written into the unit is one that has proven it runs. `--no-start` writes
169+
// the files and leaves the current service running for a later restart.
170+
const serviceReconcileCommand = Command.make("__reconcile", {
171+
...serviceReconcileFlags,
172+
noStart: Flag.boolean("no-start").pipe(Flag.withDefault(false)),
173+
}).pipe(
174+
Command.withDescription("Point the service unit at this t3, optionally without restarting."),
175+
Command.unlisted,
176+
Command.withHandler((flags) =>
177+
runServiceCommand(
178+
flags,
179+
reconcileService({ allowDowngrade: flags.allowDowngrade, start: !flags.noStart }).pipe(
180+
Effect.asVoid,
181+
),
182+
),
183+
),
184+
);
185+
186+
const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe(
187+
Command.withDescription(
188+
"Restart the background service. Picks up a version installed by `t3 update` that was not restarted at the time.",
189+
),
190+
Command.withHandler((flags) =>
191+
runServiceCommand(
192+
flags,
193+
Effect.gen(function* () {
194+
const service = yield* BootService.BootService;
195+
const status = yield* service.status;
196+
const restarted = yield* service.restart;
197+
yield* Console.log(
198+
restarted
199+
? `Restarted the T3 Code service${status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`}.`
200+
: "T3 Code service is not installed.",
201+
);
202+
}),
203+
),
204+
),
205+
);
206+
162207
const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
163208
Command.withDescription("Stop and remove the T3 Code background service."),
164209
Command.withHandler((flags) =>
@@ -265,8 +310,10 @@ export const serviceCommand = Command.make("service").pipe(
265310
Command.withDescription("Manage the T3 Code background service."),
266311
Command.withSubcommands([
267312
serviceInstallCommand,
313+
serviceRestartCommand,
268314
serviceUninstallCommand,
269-
serviceUpdateCommand,
270315
serviceStatusCommand,
316+
serviceUpdateCommand,
317+
serviceReconcileCommand,
271318
]),
272319
);

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

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
459459
).pipe(Effect.catchTag("QuitError", () => Effect.succeed(false)));
460460
} else {
461461
yield* Console.log(
462-
" Not a terminal, so the service is left on its current version. Rerun with --yes to restart it, or run `t3 service update` later.",
462+
" Not a terminal, so the service keeps running its current version. Rerun with --yes to restart it now, or run `t3 service restart` later.",
463463
);
464464
}
465465
}
@@ -519,27 +519,30 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
519519
targetEntryPath: runtime.entryPath,
520520
});
521521

522-
// The new executable owns the service switch: it verifies itself, writes its
523-
// own version into the unit, and restarts the service on it.
522+
// The new executable owns the service switch: it verifies itself and writes
523+
// its own version into the unit. The unit is rewritten either way so a
524+
// later `t3 service restart` lands on the new version; only the restart
525+
// itself waits for the user's answer.
524526
let serviceUpdated = false;
525-
if (restartService) {
527+
if (serviceInstalled && !serviceCurrent) {
526528
const result = yield* runner.run({
527529
command: runtime.entryPath,
528530
args: [
529531
"service",
530-
"update",
532+
"__reconcile",
531533
"--base-dir",
532534
input.baseDir,
533535
...(input.allowDowngrade ? ["--allow-downgrade"] : []),
536+
...(restartService ? [] : ["--no-start"]),
534537
],
535538
timeout: Duration.minutes(5),
536539
});
537540
if (result.code !== 0) {
538541
return yield* new CliUpdateError({
539-
reason: `t3@${targetVersion} is installed but the background service could not be updated (exit ${String(result.code)}).\n${result.stderr.trim() || result.stdout.trim()}`,
542+
reason: `t3@${targetVersion} is installed but the background service could not be ${restartService ? "updated" : "pointed at it"} (exit ${String(result.code)}).\n${result.stderr.trim() || result.stdout.trim()}`,
540543
});
541544
}
542-
serviceUpdated = true;
545+
serviceUpdated = restartService;
543546
}
544547

545548
yield* Console.log("");
@@ -555,7 +558,7 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
555558
yield* Console.log(` Background service already on ${targetVersion}`);
556559
} else if (serviceInstalled) {
557560
yield* Console.log(
558-
` Background service still running ${serviceVersion ?? "an unknown version"}. Run \`t3 service update\` when you are ready to restart it.`,
561+
` Background service still running ${serviceVersion ?? "an unknown version"}. Run \`t3 service restart\` when you are ready to switch it to ${targetVersion}.`,
559562
);
560563
} else if (status.installed && !servesThisHome) {
561564
yield* Console.log(

‎apps/server/src/cloud/bootService.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,48 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
469469
}),
470470
);
471471

472+
it.effect("install with start=false rewrites the files and leaves the service alone", () =>
473+
Effect.gen(function* () {
474+
const { service, fs, statePath, commands } = yield* makeHarness();
475+
yield* service.install();
476+
commands.length = 0;
477+
478+
const plan = yield* service.install({ start: false });
479+
480+
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
481+
protocol: SERVICE_LAUNCHER_PROTOCOL,
482+
activeVersion: "1.2.3",
483+
});
484+
expect(yield* fs.exists(plan.unitPath)).toBe(true);
485+
expect(
486+
commands.filter(
487+
(command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
488+
),
489+
).toEqual([]);
490+
}),
491+
);
492+
493+
it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
494+
Effect.gen(function* () {
495+
const { service, commands } = yield* makeHarness();
496+
expect(yield* service.restart).toBe(false);
497+
yield* service.install();
498+
commands.length = 0;
499+
500+
expect(yield* service.restart).toBe(true);
501+
expect(
502+
commands.filter(
503+
(command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
504+
),
505+
).toEqual([
506+
"systemctl --user stop t3code.service",
507+
"systemctl --user daemon-reload",
508+
"systemctl --user enable t3code.service",
509+
"systemctl --user restart t3code.service",
510+
]);
511+
}),
512+
);
513+
472514
it.effect("restarts an installed service when repair fails", () =>
473515
Effect.gen(function* () {
474516
const { service, commands, control } = yield* makeHarness();

0 commit comments

Comments
 (0)