@devries-cameron20 / t3code Mirror · read-only / commits / 41fce9ea17
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 00:30 UTC

fix(server): `t3 update` and `t3 service restart` run from inside T3 no longer leave the service stopped (#14361)

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Rookmate committed Oct 20, 2026 at 06:05 UTC 41fce9ea17d23f284d89cabb65edb5582074cdf7
8 files changed +475 -83
apps/server/src/cli/connect.test.ts
+71 -3
@@ -1,3 +1,5 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import * as HostProcess from "@t3tools/shared/HostProcess";
3 import * as RelayClient from "@t3tools/shared/relayClient";
4 import { assert, it } from "@effect/vitest";
5 import * as Cause from "effect/Cause";
@@ -7,6 +9,7 @@ import * as Effect from "effect/Effect";
9 import * as Exit from "effect/Exit";
10 import * as Logger from "effect/Logger";
11 import * as Option from "effect/Option";
12 +import * as Queue from "effect/Queue";
13 import * as References from "effect/References";
14 import * as Terminal from "effect/Terminal";
15
@@ -15,8 +18,9 @@ import {
18 acquireRelayClientForLink,
19 headlessSessionConfig,
20 reportCloudDisconnectResults,
21 + reportServiceOnboarding,
22 } from "./connect.ts";
19 -import { recoverServiceOnboardingOffer } from "./service.ts";
23 +import { offerServiceDuringOnboarding, recoverServiceOnboardingOffer } from "./service.ts";
24
25 const readHeadlessSessionConfig = (env: Record<string, string>) =>
26 headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))));
@@ -40,7 +44,7 @@ it.effect("detects headless operation from individual SSH config values", () =>
44 it.effect("treats cancelling optional background setup as a successful skip", () =>
45 Effect.gen(function* () {
46 const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
43 - assert.isFalse(result);
47 + assert.equal(result, "skipped");
48 }),
49 );
50
@@ -49,10 +53,74 @@ it.effect("keeps a successful connection when a remote service update is pending
53 const result = yield* recoverServiceOnboardingOffer(
54 Effect.fail(new BootService.BootServiceUpdatePendingError()),
55 );
52 - assert.isFalse(result);
56 + assert.equal(result, "skipped");
57 }),
58 );
59
60 +it.effect("reports pending onboarding until the handed-off service is ready", () =>
61 + Effect.gen(function* () {
62 + const input = yield* Queue.make<Terminal.UserInput>();
63 + yield* Queue.offer(input, {
64 + input: Option.some("\r"),
65 + key: { name: "return", ctrl: false, meta: false, shift: false },
66 + });
67 + const terminal = Terminal.make({
68 + columns: Effect.succeed(80),
69 + rows: Effect.succeed(24),
70 + readInput: Effect.succeed(Queue.asDequeue(input)),
71 + readLine: Effect.die("unexpected line input"),
72 + display: () => Effect.void,
73 + });
74 + const plan = {
75 + program: ["/test/t3", "__service-launcher"],
76 + baseDir: "/test",
77 + unitPath: "/test/t3code.service",
78 + logPath: "/test/boot-service.log",
79 + handedOff: true,
80 + };
81 + let current = false;
82 + const service = BootService.BootService.of({
83 + status: Effect.sync(() => ({
84 + supported: true,
85 + installed: true,
86 + current,
87 + unitPath: plan.unitPath,
88 + logPath: plan.logPath,
89 + })),
90 + install: () => Effect.succeed(plan),
91 + restart: Effect.die("unexpected restart"),
92 + uninstall: Effect.die("unexpected uninstall"),
93 + withStopped: () => Effect.die("unexpected maintenance"),
94 + });
95 + const lines: string[] = [];
96 + const onboard = recoverServiceOnboardingOffer(offerServiceDuringOnboarding).pipe(
97 + Effect.flatMap(reportServiceOnboarding),
98 + Effect.provideService(BootService.BootService, service),
99 + Effect.provideService(Terminal.Terminal, terminal),
100 + Effect.provideService(HostProcess.Platform, "linux"),
101 + Effect.provideService(Console.Console, {
102 + ...globalThis.console,
103 + log: (...args) => {
104 + lines.push(args.map(String).join(" "));
105 + },
106 + }),
107 + );
108 +
109 + yield* onboard;
110 + const output = lines.join("\n");
111 + assert.notInclude(output, "Background service ready");
112 + assert.notInclude(output, "Start the server");
113 + assert.include(output, "Background service restarting");
114 + assert.include(output, plan.logPath);
115 +
116 + current = true;
117 + lines.length = 0;
118 + yield* onboard;
119 + assert.include(lines.join("\n"), "Background service ready");
120 + assert.notInclude(lines.join("\n"), "restarting");
121 + }).pipe(Effect.provide(NodeServices.layer)),
122 +);
123 +
124 it.effect("does not install the relay client when the user declines the managed download", () =>
125 Effect.gen(function* () {
126 let installCalls = 0;
apps/server/src/cli/connect.ts
+26 -14
@@ -45,7 +45,6 @@ import * as ExternalLauncher from "../process/externalLauncher.ts";
45 import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
46 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
47 import { resolveCliCommand } from "./invocation.ts";
48 -import { offerServiceDuringOnboarding, recoverServiceOnboardingOffer } from "./service.ts";
48 import * as CliService from "./service.ts";
49
50 const jsonFlag = Flag.Boolean("json").pipe(
@@ -685,6 +684,30 @@ const connectLogoutCommand = Command.make("logout", {
684 ),
685 );
686
687 +export const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onboarding")(
688 + function* (outcome: CliService.ServiceOnboardingOutcome) {
689 + if (outcome === "pending") {
690 + yield* Console.log(
691 + "\nBackground service restarting\n\nThe server establishes the T3 Connect link once it is back. Check the log above if it does not come back.",
692 + );
693 + return;
694 + }
695 + if (outcome === "ready") {
696 + const platform = yield* HostProcess.Platform;
697 + yield* Console.log(
698 + platform === "darwin"
699 + ? "\n✓ Background service ready\n\nT3 Code is set to run while you are logged in to this Mac. The server establishes the T3 Connect link on startup."
700 + : "\n✓ Background service ready\n\nT3 Code is set to keep running after you log out. The server establishes the T3 Connect link on startup.",
701 + );
702 + return;
703 + }
704 + const serveCommand = yield* resolveCliCommand("serve");
705 + yield* Console.log(
706 + `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
707 + );
708 + },
709 +);
710 +
711 export const connectCommand = Command.make("connect", {
712 ...projectLocationFlags,
713 headless: headlessFlag,
@@ -701,19 +724,8 @@ export const connectCommand = Command.make("connect", {
724 }
725 yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
726
704 - const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
705 - if (background) {
706 - const platform = yield* HostProcess.Platform;
707 - yield* Console.log(
708 - platform === "darwin"
709 - ? "\n✓ Background service ready\n\nT3 Code is set to run while you are logged in to this Mac. The server establishes the T3 Connect link on startup."
710 - : "\n✓ Background service ready\n\nT3 Code is set to keep running after you log out. The server establishes the T3 Connect link on startup.",
711 - );
712 - return;
713 - }
714 - const serveCommand = yield* resolveCliCommand("serve");
715 - yield* Console.log(
716 - `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
727 + yield* reportServiceOnboarding(
728 + yield* CliService.recoverServiceOnboardingOffer(CliService.offerServiceDuringOnboarding),
729 );
730 }),
731 ),
apps/server/src/cli/service.test.ts
+77 -5
@@ -3,6 +3,7 @@ import { assert, expect, it } from "@effect/vitest";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as NetService from "@t3tools/shared/Net";
5 import * as ConfigProvider from "effect/ConfigProvider";
6 +import * as Console from "effect/Console";
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
@@ -97,7 +98,10 @@ it("reports a newer installed service and tells the CLI to catch up to it", () =
98
99 const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };
100
100 -function makeTestService(serviceStatus: BootService.BootServiceStatus) {
101 +function makeTestService(
102 + serviceStatus: BootService.BootServiceStatus,
103 + restartOutcome: "restarted" | "queued" = "restarted",
104 +) {
105 const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
106 const restarts: Array<true> = [];
107 const service = BootService.BootService.of({
@@ -105,7 +109,7 @@ function makeTestService(serviceStatus: BootService.BootServiceStatus) {
109 withStopped: (operation) => operation,
110 restart: Effect.sync(() => {
111 restarts.push(true);
108 - return serviceStatus.installed;
112 + return serviceStatus.installed ? restartOutcome : "skipped";
113 }),
114 install: (options) =>
115 Effect.sync(() => {
@@ -146,6 +150,74 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands
150 }),
151 );
152
153 + it.effect("restart from inside the service says the restart is only queued", () =>
154 + Effect.gen(function* () {
155 + const fs = yield* FileSystem.FileSystem;
156 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
157 + const { service } = makeTestService({ ...status, installedVersion: "0.0.30" }, "queued");
158 + vi.spyOn(BootService, "layer").mockReturnValue(
159 + Layer.succeed(BootService.BootService, service),
160 + );
161 + const lines: Array<string> = [];
162 + const testConsole = {
163 + ...globalThis.console,
164 + log: (...args: ReadonlyArray<unknown>) => {
165 + lines.push(args.map(String).join(" "));
166 + },
167 + } satisfies Console.Console;
168 +
169 + yield* Command.runWith(serviceCommand, { version: packageJson.version })([
170 + "restart",
171 + "--base-dir",
172 + baseDir,
173 + ]).pipe(
174 + Effect.provideService(HostProcess.Environment, {}),
175 + Effect.provideService(Console.Console, testConsole),
176 + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
177 + );
178 +
179 + const output = lines.join("\n");
180 + expect(output).not.toContain("Restarted");
181 + expect(output).toContain("Queued a restart of the T3 Code service on t3@0.0.30");
182 + expect(output).toContain(`Logs: ${status.logPath}`);
183 + }),
184 + );
185 +
186 + it.effect("install reports a handed-off switch as pending", () =>
187 + Effect.gen(function* () {
188 + const fs = yield* FileSystem.FileSystem;
189 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
190 + const { service } = makeTestService({ ...status, current: false });
191 + vi.spyOn(BootService, "layer").mockReturnValue(
192 + Layer.succeed(BootService.BootService, {
193 + ...service,
194 + install: (options) =>
195 + service.install(options).pipe(Effect.map((plan) => ({ ...plan, handedOff: true }))),
196 + }),
197 + );
198 + const lines: string[] = [];
199 + yield* Command.runWith(serviceCommand, { version: packageJson.version })([
200 + "install",
201 + "--base-dir",
202 + baseDir,
203 + ]).pipe(
204 + Effect.provideService(HostProcess.Environment, {}),
205 + Effect.provideService(Console.Console, {
206 + ...globalThis.console,
207 + log: (...args) => {
208 + lines.push(args.map(String).join(" "));
209 + },
210 + }),
211 + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
212 + );
213 +
214 + const output = lines.join("\n");
215 + expect(output).not.toMatch(/(?:Installed|Updated) T3 Code service/);
216 + expect(output).toContain("separate systemd unit");
217 + expect(output).toContain(status.logPath);
218 + }),
219 + );
220 +
221 it.effect.each(["install", "update"] as const)(
222 "%s refuses a downgrade before changing the service",
223 (command) =>
@@ -247,7 +319,7 @@ it.effect("leaves a newer service unchanged during onboarding without prompting"
319 Effect.provide(NodeServices.layer),
320 );
321
250 - expect(ready).toBe(false);
322 + expect(ready).toBe("skipped");
323 expect(installOptions).toEqual([]);
324 }),
325 );
@@ -263,7 +335,7 @@ it.effect("keeps onboarding successful when a newer version appears before insta
335 ),
336 );
337
266 - expect(ready).toBe(false);
338 + expect(ready).toBe("skipped");
339 }),
340 );
341
@@ -272,6 +344,6 @@ it.effect("keeps the manual-server fallback when background prerequisites fail",
344 const ready = yield* recoverServiceOnboardingOffer(
345 Effect.fail(new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" })),
346 );
275 - expect(ready).toBe(false);
347 + expect(ready).toBe("skipped");
348 }),
349 );
apps/server/src/cli/service.ts
+50 -29
@@ -58,6 +58,15 @@ export const reconcileService = Effect.fn("cli.service.reconcile")(function* (op
58 } satisfies ServiceReconcileResult;
59 });
60
61 +function formatServiceChange(
62 + result: Extract<ServiceReconcileResult, { readonly changed: true }>,
63 +): string {
64 + if (result.plan.handedOff === true) {
65 + return `Handed the T3 Code service switch to t3@${packageJson.version} to a separate systemd unit, since this session runs inside the service and disconnects when it restarts.\nResult: ${result.plan.logPath}`;
66 + }
67 + return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;
68 +}
69 +
70 export function formatServiceStatus(
71 status: BootService.BootServiceStatus,
72 cliVersion: string,
@@ -126,9 +135,7 @@ const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pip
135 );
136 return;
137 }
129 - yield* Console.log(
130 - `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
131 - );
138 + yield* Console.log(formatServiceChange(result));
139 }),
140 ),
141 ),
@@ -149,9 +156,7 @@ const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
156 yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
157 return;
158 }
152 - yield* Console.log(
153 - `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
154 - );
159 + yield* Console.log(formatServiceChange(result));
160 }),
161 ),
162 ),
@@ -167,11 +172,15 @@ const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe
172 Effect.gen(function* () {
173 const service = yield* BootService.BootService;
174 const status = yield* service.status;
170 - const restarted = yield* service.restart;
175 + const outcome = yield* service.restart;
176 + const onVersion =
177 + status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`;
178 yield* Console.log(
172 - restarted
173 - ? `Restarted the T3 Code service${status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`}.`
174 - : "T3 Code service is not installed.",
179 + outcome === "restarted"
180 + ? `Restarted the T3 Code service${onVersion}.`
181 + : outcome === "queued"
182 + ? `Queued a restart of the T3 Code service${onVersion}. This session runs inside the service and disconnects when it goes down.\nLogs: ${status.logPath}`
183 + : "T3 Code service is not installed.",
184 );
185 }),
186 ),
@@ -207,16 +216,18 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
216 ),
217 );
218
219 +export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped";
220 +
221 export const offerServiceDuringOnboarding = Effect.gen(function* () {
222 const service = yield* BootService.BootService;
223 const status = yield* service.status;
224 const { supported, installed, current } = status;
225 if (!supported) {
215 - return false;
226 + return "skipped" as const;
227 }
228 if (installed && current) {
229 yield* Console.log("T3 Code is already set up to run in the background on this machine.");
219 - return true;
230 + return "ready" as const;
231 }
232 for (const problem of status.problems ?? []) {
233 yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);
@@ -229,7 +240,7 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
240 yield* Console.log(
241 `A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,
242 );
232 - return false;
243 + return "skipped" as const;
244 }
245 const platform = yield* HostProcess.Platform;
246 const wanted = yield* Prompt.run(
@@ -245,35 +256,45 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
256 }),
257 );
258 if (!wanted) {
248 - return false;
259 + return "skipped" as const;
260 }
261 const result = yield* reconcileService();
262 if (result.changed) {
263 yield* Console.log(
253 - `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
264 + result.plan.handedOff === true
265 + ? formatServiceChange(result)
266 + : `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
267 );
268 }
256 - return true;
269 + return result.changed && result.plan.handedOff === true
270 + ? ("pending" as const)
271 + : ("ready" as const);
272 });
273
274 +const reportServiceSetupFailure = (error: BootService.BootServiceError) =>
275 + Console.warn(`Background setup did not finish: ${error.message}`).pipe(
276 + Effect.as("skipped" as const),
277 + );
278 +
279 export const recoverServiceOnboardingOffer = <R>(
260 - offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
280 + offer: Effect.Effect<
281 + ServiceOnboardingOutcome,
282 + BootService.BootServiceError | Terminal.QuitError,
283 + R
284 + >,
285 ) =>
286 offer.pipe(
287 Effect.catchTags({
264 - QuitError: () => Effect.succeed(false),
288 + QuitError: () => Effect.succeed("skipped" as const),
289 BootServiceUnsupportedError: (error) =>
266 - Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
267 - BootServiceCommandError: (error) =>
268 - Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
269 - BootServiceInstallError: (error) =>
270 - Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
271 - BootServicePrerequisiteError: (error) =>
272 - Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
273 - BootServiceUpdatePendingError: (error) =>
274 - Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
275 - BootServiceDowngradeRefusedError: (error) =>
276 - Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
290 + Console.log(`Skipping background setup: ${error.message}`).pipe(
291 + Effect.as("skipped" as const),
292 + ),
293 + BootServiceCommandError: reportServiceSetupFailure,
294 + BootServiceInstallError: reportServiceSetupFailure,
295 + BootServicePrerequisiteError: reportServiceSetupFailure,
296 + BootServiceUpdatePendingError: reportServiceSetupFailure,
297 + BootServiceDowngradeRefusedError: reportServiceSetupFailure,
298 }),
299 );
300
apps/server/src/cli/update.test.ts
+89 -3
@@ -1,12 +1,23 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 -import { assert, it } from "@effect/vitest";
2 +import { assert, expect, it } from "@effect/vitest";
3 +import * as HostProcess from "@t3tools/shared/HostProcess";
4 +import * as NetService from "@t3tools/shared/Net";
5 +import * as ConfigProvider from "effect/ConfigProvider";
6 +import * as Console from "effect/Console";
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 +import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Path from "effect/Path";
7 -import * as HostProcess from "@t3tools/shared/HostProcess";
12 +import { Command } from "effect/cli";
13 +import { afterEach, vi } from "vite-plus/test";
14
9 -import { repointLauncher, resolveLauncherPath } from "./update.ts";
15 +import packageJson from "../../package.json" with { type: "json" };
16 +import * as BootService from "../cloud/bootService.ts";
17 +import { pinnedRuntimePaths } from "../cloud/pinnedRuntime.ts";
18 +import { repointLauncher, resolveLauncherPath, updateCommand } from "./update.ts";
19 +
20 +afterEach(() => vi.restoreAllMocks());
21
22 it.layer(NodeServices.layer)("t3 update launcher", (it) => {
23 it.effect("repoints a symlink that lives in a runtime versions tree", () =>
@@ -101,3 +112,78 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
112 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
113 );
114 });
115 +
116 +it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 update service", (it) => {
117 + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
118 + "reports the service switch as pending after installing the target runtime",
119 + () =>
120 + Effect.gen(function* () {
121 + const fs = yield* FileSystem.FileSystem;
122 + const path = yield* Path.Path;
123 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-service-" });
124 + const targetVersion = "999.0.0";
125 + const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");
126 + yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
127 + yield* fs.writeFileString(
128 + runtime.entryPath,
129 + `#!/bin/sh\nprintf 't3 v${targetVersion}\\n'\n`,
130 + );
131 + yield* fs.chmod(runtime.entryPath, 0o755);
132 + yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);
133 + const logPath = path.join(baseDir, "userdata/logs/boot-service.log");
134 + const unitPath = path.join(baseDir, "t3code.service");
135 + const installs: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
136 + vi.spyOn(BootService, "layer").mockReturnValue(
137 + Layer.succeed(BootService.BootService, {
138 + status: Effect.succeed({
139 + supported: true,
140 + installed: true,
141 + current: true,
142 + installedVersion: packageJson.version,
143 + installedBaseDir: baseDir,
144 + logPath,
145 + unitPath,
146 + }),
147 + install: (options) =>
148 + Effect.sync(() => {
149 + installs.push(options);
150 + return {
151 + program: [runtime.entryPath],
152 + baseDir,
153 + logPath,
154 + unitPath,
155 + handedOff: true,
156 + };
157 + }),
158 + restart: Effect.die("unexpected restart"),
159 + uninstall: Effect.die("unexpected uninstall"),
160 + withStopped: () => Effect.die("unexpected maintenance"),
161 + }),
162 + );
163 + const lines: string[] = [];
164 + yield* Command.runWith(updateCommand, { version: packageJson.version })([
165 + targetVersion,
166 + "--yes",
167 + "--base-dir",
168 + baseDir,
169 + ]).pipe(
170 + Effect.provideService(HostProcess.Platform, "linux"),
171 + Effect.provideService(HostProcess.IsExecutable, false),
172 + Effect.provideService(HostProcess.Environment, {}),
173 + Effect.provideService(Console.Console, {
174 + ...globalThis.console,
175 + log: (...args) => {
176 + lines.push(args.map(String).join(" "));
177 + },
178 + }),
179 + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
180 + );
181 +
182 + expect(installs).toEqual([{ allowDowngrade: false, start: true }]);
183 + const output = lines.join("\n");
184 + expect(output).not.toContain("Background service restarted");
185 + expect(output).toContain(`Background service switching to ${targetVersion}`);
186 + expect(output).toContain(logPath);
187 + }),
188 + );
189 +});
apps/server/src/cli/update.ts
+9 -8
@@ -490,18 +490,16 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
490 targetEntryPath: runtime.entryPath,
491 });
492
493 - // The service switch runs in this process against the target version: the downloaded runtime
494 - // has already proven it runs (the `--version` check above), and doing it here rather than
495 - // through the target's own CLI means a downgrade to a version without today's commands still
496 - // works.
497 - let serviceUpdated = false;
493 + // Use today's service manager for the target version. Inside the service it hands off to
494 + // the target CLI, so stopping this process cannot interrupt the switch.
495 + let servicePlan: BootService.BootServicePlan | undefined;
496 if (serviceInstalled && !serviceCurrent) {
497 yield* Console.log(
498 restartService
499 ? "Restarting the background service..."
500 : "Updating the background service...",
501 );
504 - yield* BootService.BootService.pipe(
502 + servicePlan = yield* BootService.BootService.pipe(
503 Effect.flatMap((target) =>
504 target.install({ allowDowngrade: input.allowDowngrade, start: restartService }),
505 ),
@@ -519,7 +517,6 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
517 }),
518 ),
519 );
522 - serviceUpdated = restartService;
520 }
521
522 progress.success(`Installed T3 Code ${targetVersion}`);
@@ -528,7 +525,11 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
525 } else {
526 yield* Console.log(` Run ${runtime.entryPath}\n`);
527 }
531 - if (serviceUpdated) {
528 + if (servicePlan?.handedOff === true) {
529 + yield* Console.log(
530 + ` Background service switching to ${targetVersion} from a separate systemd unit, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,
531 + );
532 + } else if (servicePlan !== undefined && restartService) {
533 yield* Console.log(` Background service restarted on ${targetVersion}`);
534 } else if (serviceInstalled && serviceCurrent) {
535 yield* Console.log(` Background service already on ${targetVersion}`);
apps/server/src/cloud/bootService.test.ts
+90 -5
@@ -140,6 +140,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
140 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
141
142 const commands: string[] = [];
143 + const invocations: ProcessRunner.ProcessRunInput[] = [];
144 const timeouts = new Map<string, unknown>();
145 const control: {
146 failCommand: string | undefined;
@@ -159,6 +160,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
160 ) {
161 const command = `${input.command} ${input.args.join(" ")}`;
162 commands.push(command);
163 + invocations.push(input);
164 timeouts.set(command, input.timeout);
165 const failed = command === control.failCommand;
166 if (!failed && command === "loginctl enable-linger --no-ask-password 501")
@@ -205,6 +207,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
207 environmentPath: string | undefined = installerPath,
208 cliVersion = "1.2.3",
209 serviceBaseDir = baseDir,
210 + insideService = false,
211 ) =>
212 Effect.gen(function* () {
213 const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
@@ -235,6 +238,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
238 ...(environmentPath === undefined || environmentPath === ""
239 ? {}
240 : { PATH: environmentPath }),
241 + ...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}),
242 },
243 }),
244 ),
@@ -242,7 +246,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
246 ),
247 );
248 const service = yield* makeService();
245 - return { service, makeService, fs, statePath, commands, timeouts, control, runtime };
249 + return { service, makeService, fs, statePath, commands, invocations, timeouts, control, runtime };
250 });
251
252 it.layer(NodeServices.layer)("boot service install", (it) => {
@@ -507,7 +511,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
511 expect(status.problems).toContain("restart-pending");
512
513 commands.length = 0;
510 - expect(yield* newer.restart).toBe(true);
514 + expect(yield* newer.restart).toBe("restarted");
515 expect((yield* newer.status).problems).not.toContain("restart-pending");
516 expect((yield* newer.status).current).toBe(true);
517 }),
@@ -625,11 +629,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
629 it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
630 Effect.gen(function* () {
631 const { service, commands } = yield* makeHarness();
628 - expect(yield* service.restart).toBe(false);
632 + expect(yield* service.restart).toBe("skipped");
633 yield* service.install();
634 commands.length = 0;
635
632 - expect(yield* service.restart).toBe(true);
636 + expect(yield* service.restart).toBe("restarted");
637 expect(
638 commands.filter(
639 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
@@ -652,7 +656,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
656 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
657
658 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
655 - expect(yield* other.restart).toBe(false);
659 + expect(yield* other.restart).toBe("skipped");
660 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);
661 }),
662 );
@@ -678,6 +682,87 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
682 }),
683 );
684
685 + it.effect("hands the whole install to systemd without changing the running service", () =>
686 + Effect.gen(function* () {
687 + const { fs, commands, invocations, control, makeService } = yield* makeHarness();
688 + const path = yield* Path.Path;
689 + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-handoff-" });
690 + const baseDir = path.join(home, "T3 Data 100%", "${UNSET}", "$literal");
691 + const outside = yield* makeService(undefined, "1.2.3", baseDir);
692 + const plan = yield* outside.install();
693 + const statePath = path.join(baseDir, "runtime", "service-state.json");
694 + const state = yield* fs.readFileString(statePath);
695 + const unit = yield* fs.readFileString(plan.unitPath);
696 + const inside = yield* makeService(undefined, "1.2.4", baseDir, true);
697 + commands.length = 0;
698 + invocations.length = 0;
699 +
700 + const result = yield* inside.install({ allowDowngrade: true });
701 +
702 + expect(yield* fs.readFileString(statePath)).toBe(state);
703 + expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
704 + expect(commands).not.toContain("systemctl --user stop t3code.service");
705 + expect(result).toMatchObject({ handedOff: true, logPath: plan.logPath });
706 + const handoffs = invocations.filter(({ command }) => command === "systemd-run");
707 + expect(handoffs).toHaveLength(1);
708 + expect(handoffs[0]?.args).toEqual([
709 + "--user",
710 + "--collect",
711 + "--quiet",
712 + `--property=StandardOutput=append:${plan.logPath}`,
713 + `--property=StandardError=append:${plan.logPath}`,
714 + "--setenv=T3_BOOT_SERVICE_UNIT=",
715 + pinnedRuntimePaths(path, baseDir, "1.2.4", "linux").entryPath,
716 + "service",
717 + "install",
718 + "--base-dir",
719 + path.join(home, "T3 Data 100%", "$${UNSET}", "$$literal"),
720 + "--allow-downgrade",
721 + ]);
722 +
723 + const handoff = handoffs[0]!;
724 + control.failCommand = `${handoff.command} ${handoff.args.join(" ")}`;
725 + const error = yield* inside.install({ allowDowngrade: true }).pipe(Effect.flip);
726 + expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
727 + expect(yield* fs.readFileString(statePath)).toBe(state);
728 + expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
729 + expect(control.active).toBe(true);
730 + expect(commands).not.toContain("systemctl --user stop t3code.service");
731 + }),
732 + );
733 +
734 + it.effect(
735 + "queues an in-service restart without stopping the caller, even on handoff failure",
736 + () =>
737 + Effect.gen(function* () {
738 + const { service, fs, statePath, commands, control, makeService } = yield* makeHarness();
739 + const plan = yield* service.install();
740 + const state = yield* fs.readFileString(statePath);
741 + const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`;
742 + yield* fs.writeFileString(marker, "1.2.3\n");
743 + const inside = yield* makeService(undefined, "1.2.3", undefined, true);
744 + commands.length = 0;
745 + control.failCommand = "systemctl --user daemon-reload";
746 +
747 + const error = yield* inside.restart.pipe(Effect.flip);
748 + expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
749 + expect(commands).toEqual(["systemctl --user daemon-reload"]);
750 + expect(control.active).toBe(true);
751 +
752 + control.failCommand = undefined;
753 + commands.length = 0;
754 + const outcome = yield* inside.restart;
755 + expect(commands).toEqual([
756 + "systemctl --user daemon-reload",
757 + "systemctl --user enable t3code.service",
758 + "systemctl --user restart --no-block t3code.service",
759 + ]);
760 + expect(outcome).toBe("queued");
761 + expect(yield* fs.readFileString(statePath)).toBe(state);
762 + expect(yield* fs.readFileString(marker)).toBe("1.2.3\n");
763 + }),
764 + );
765 +
766 it.effect("restarts an installed service when repair fails", () =>
767 Effect.gen(function* () {
768 const { service, commands, control } = yield* makeHarness();
apps/server/src/cloud/bootService.ts
+63 -16
@@ -75,6 +75,8 @@ export interface BootServicePlan {
75 readonly baseDir: string;
76 readonly logPath: string;
77 readonly unitPath: string;
78 + /** The manager accepted a detached install; its outcome is written to `logPath`. */
79 + readonly handedOff?: boolean;
80 }
81
82 /** Pure renderer: service units cannot rely on the user's shell or PATH. */
@@ -206,6 +208,8 @@ export interface BootServiceManager {
208 readonly stop: ReadonlyArray<BootServiceStep>;
209 readonly activate: ReadonlyArray<BootServiceStep>;
210 readonly restart: ReadonlyArray<BootServiceStep>;
211 + /** Queue a restart owned by the manager, since stopping would kill the caller. */
212 + readonly handoff?: ReadonlyArray<BootServiceStep>;
213 readonly deactivate: ReadonlyArray<BootServiceStep>;
214 readonly finalize: ReadonlyArray<BootServiceStep>;
215 }
@@ -221,6 +225,18 @@ function systemdManager(input: {
225 "user",
226 BOOT_SERVICE_UNIT_FILE,
227 );
228 + const prepareActivation = [
229 + {
230 + step: "reloading systemd user units",
231 + command: "systemctl",
232 + args: ["--user", "daemon-reload"],
233 + },
234 + {
235 + step: "enabling the service",
236 + command: "systemctl",
237 + args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
238 + },
239 + ];
240 return {
241 kind: "systemd",
242 unitPath,
@@ -234,16 +250,7 @@ function systemdManager(input: {
250 },
251 ],
252 activate: [
237 - {
238 - step: "reloading systemd user units",
239 - command: "systemctl",
240 - args: ["--user", "daemon-reload"],
241 - },
242 - {
243 - step: "enabling the service",
244 - command: "systemctl",
245 - args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
246 - },
253 + ...prepareActivation,
254 {
255 step: "starting the service",
256 command: "systemctl",
@@ -257,6 +264,14 @@ function systemdManager(input: {
264 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
265 },
266 ],
267 + handoff: [
268 + ...prepareActivation,
269 + {
270 + step: "restarting the service",
271 + command: "systemctl",
272 + args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
273 + },
274 + ],
275 deactivate: [
276 {
277 step: "stopping the service",
@@ -494,10 +509,11 @@ export class BootService extends Context.Service<
509 }) => Effect.Effect<BootServicePlan, BootServiceError>;
510 /**
511 * Only when the unit serves this base dir: the unit name is per user, so
497 - * another home's service is left alone. Resolves false when nothing was
498 - * restarted.
512 + * another home's service is left alone, which resolves `skipped`. From
513 + * inside the service the restart can only be `queued` with the service
514 + * manager, since the stop ends this process.
515 */
500 - readonly restart: Effect.Effect<boolean, BootServiceError>;
516 + readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
517 /**
518 * Run `operation` while this home's installed service is stopped, then
519 * start it again when it was enabled (systemd) or loaded (launchd)
@@ -533,6 +549,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
549 );
550 const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
551 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
552 + const runningInsideService =
553 + (yield* Config.String(BOOT_SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
554 + BOOT_SERVICE_UNIT_FILE;
555 const fs = yield* FileSystem.FileSystem;
556 const path = yield* Path.Path;
557 const runner = yield* ProcessRunner.ProcessRunner;
@@ -781,6 +800,28 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
800 // middle of a remote update, which is the one time it writes the state file
801 // itself.
802 const start = options?.start !== false;
803 + if (installed && start && runningInsideService && manager.kind === "systemd") {
804 + // Stopping the unit from inside it kills this process before the start.
805 + // A transient unit runs the same install from outside, stop first, so it
806 + // still serialises with a remote update the launcher may be starting.
807 + yield* runStep("handing the install to a transient unit", "systemd-run", [
808 + "--user",
809 + "--collect",
810 + "--quiet",
811 + // Transient properties reach systemd literally, unlike unit-file specifiers.
812 + `--property=StandardOutput=append:${logPath}`,
813 + `--property=StandardError=append:${logPath}`,
814 + `--setenv=${BOOT_SERVICE_UNIT_ENV}=`,
815 + runtimePaths.entryPath,
816 + "service",
817 + "install",
818 + "--base-dir",
819 + // systemd expands $VAR in arguments (not in the executable path).
820 + input.baseDir.replaceAll("$", () => "$$"),
821 + ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
822 + ]);
823 + return { ...plan, handedOff: true };
824 + }
825 if (installed && start) {
826 yield* runSteps(manager.stop);
827 }
@@ -856,20 +897,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
897 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
898 const manager = yield* requireManager;
899 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
859 - if (Option.isNone(unit)) return false;
900 + if (Option.isNone(unit)) return "skipped" as const;
901 const installedBaseDir = bootServiceBaseDirOf(unit.value);
902 if (
903 installedBaseDir === undefined ||
904 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
905 ) {
865 - return false;
906 + return "skipped" as const;
907 + }
908 + // Writes no state, and the launcher lets an update transition in flight
909 + // finish before the queued stop tears it down.
910 + if (runningInsideService && manager.handoff !== undefined) {
911 + yield* runSteps(manager.handoff);
912 + return "queued" as const;
913 }
914 yield* runSteps(manager.stop);
915 yield* runSteps(manager.activate).pipe(
916 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
917 );
918 yield* fs.remove(restartPendingPath, { force: true });
872 - return true;
919 + return "restarted" as const;
920 }).pipe(
921 Effect.mapError((cause) =>
922 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,