TypeScript
fix(server): `t3 update` and `t3 service restart` run from inside T3 no longer leave the service stopped (#14361)
Rookmate41fce9ea17d2
diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.tsindex f7bbcd23e67..72a17f56e93 100644--- a/apps/server/src/cli/connect.test.ts+++ b/apps/server/src/cli/connect.test.ts@@ -1,3 +1,5 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as HostProcess from "@t3tools/shared/HostProcess";import * as RelayClient from "@t3tools/shared/relayClient";import { assert, it } from "@effect/vitest";import * as Cause from "effect/Cause";@@ -7,6 +9,7 @@ import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as Logger from "effect/Logger";import * as Option from "effect/Option";+import * as Queue from "effect/Queue";import * as References from "effect/References";import * as Terminal from "effect/Terminal";@@ -15,8 +18,9 @@ import {acquireRelayClientForLink,headlessSessionConfig,reportCloudDisconnectResults,+ reportServiceOnboarding,} from "./connect.ts";-import { recoverServiceOnboardingOffer } from "./service.ts";+import { offerServiceDuringOnboarding, recoverServiceOnboardingOffer } from "./service.ts";const readHeadlessSessionConfig = (env: Record<string, string>) =>headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))));@@ -40,7 +44,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* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));- assert.isFalse(result);+ assert.equal(result, "skipped");}),);@@ -49,10 +53,74 @@ it.effect("keeps a successful connection when a remote service update is pendingconst result = yield* recoverServiceOnboardingOffer(Effect.fail(new BootService.BootServiceUpdatePendingError()),);- assert.isFalse(result);+ assert.equal(result, "skipped");}),);+it.effect("reports pending onboarding until the handed-off service is ready", () =>+ Effect.gen(function* () {+ const input = yield* Queue.make<Terminal.UserInput>();+ yield* Queue.offer(input, {+ input: Option.some("\r"),+ key: { name: "return", ctrl: false, meta: false, shift: false },+ });+ const terminal = Terminal.make({+ columns: Effect.succeed(80),+ rows: Effect.succeed(24),+ readInput: Effect.succeed(Queue.asDequeue(input)),+ readLine: Effect.die("unexpected line input"),+ display: () => Effect.void,+ });+ const plan = {+ program: ["/test/t3", "__service-launcher"],+ baseDir: "/test",+ unitPath: "/test/t3code.service",+ logPath: "/test/boot-service.log",+ handedOff: true,+ };+ let current = false;+ const service = BootService.BootService.of({+ status: Effect.sync(() => ({+ supported: true,+ installed: true,+ current,+ unitPath: plan.unitPath,+ logPath: plan.logPath,+ })),+ install: () => Effect.succeed(plan),+ restart: Effect.die("unexpected restart"),+ uninstall: Effect.die("unexpected uninstall"),+ withStopped: () => Effect.die("unexpected maintenance"),+ });+ const lines: string[] = [];+ const onboard = recoverServiceOnboardingOffer(offerServiceDuringOnboarding).pipe(+ Effect.flatMap(reportServiceOnboarding),+ Effect.provideService(BootService.BootService, service),+ Effect.provideService(Terminal.Terminal, terminal),+ Effect.provideService(HostProcess.Platform, "linux"),+ Effect.provideService(Console.Console, {+ ...globalThis.console,+ log: (...args) => {+ lines.push(args.map(String).join(" "));+ },+ }),+ );++ yield* onboard;+ const output = lines.join("\n");+ assert.notInclude(output, "Background service ready");+ assert.notInclude(output, "Start the server");+ assert.include(output, "Background service restarting");+ assert.include(output, plan.logPath);++ current = true;+ lines.length = 0;+ yield* onboard;+ assert.include(lines.join("\n"), "Background service ready");+ assert.notInclude(lines.join("\n"), "restarting");+ }).pipe(Effect.provide(NodeServices.layer)),+);+it.effect("does not install the relay client when the user declines the managed download", () =>Effect.gen(function* () {let installCalls = 0;diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.tsindex 9de28623c31..9cc59335115 100644--- a/apps/server/src/cli/connect.ts+++ b/apps/server/src/cli/connect.ts@@ -45,7 +45,6 @@ import * as ExternalLauncher from "../process/externalLauncher.ts";import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";import { resolveCliCommand } from "./invocation.ts";-import { offerServiceDuringOnboarding, recoverServiceOnboardingOffer } from "./service.ts";import * as CliService from "./service.ts";const jsonFlag = Flag.Boolean("json").pipe(@@ -685,6 +684,30 @@ const connectLogoutCommand = Command.make("logout", {),);+export const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onboarding")(+ function* (outcome: CliService.ServiceOnboardingOutcome) {+ if (outcome === "pending") {+ yield* Console.log(+ "\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.",+ );+ return;+ }+ if (outcome === "ready") {+ const platform = yield* HostProcess.Platform;+ yield* Console.log(+ platform === "darwin"+ ? "\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."+ : "\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.",+ );+ return;+ }+ const serveCommand = yield* resolveCliCommand("serve");+ yield* Console.log(+ `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,+ );+ },+);+export const connectCommand = Command.make("connect", {...projectLocationFlags,headless: headlessFlag,@@ -701,19 +724,8 @@ export const connectCommand = Command.make("connect", {}yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);- const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);- if (background) {- const platform = yield* HostProcess.Platform;- yield* Console.log(- platform === "darwin"- ? "\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."- : "\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.",- );- return;- }- const serveCommand = yield* resolveCliCommand("serve");- yield* Console.log(- `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,+ yield* reportServiceOnboarding(+ yield* CliService.recoverServiceOnboardingOffer(CliService.offerServiceDuringOnboarding),);}),),diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.tsindex 1f1b70dce8a..dbd0653647b 100644--- a/apps/server/src/cli/service.test.ts+++ b/apps/server/src/cli/service.test.ts@@ -3,6 +3,7 @@ import { assert, expect, it } from "@effect/vitest";import * as HostProcess from "@t3tools/shared/HostProcess";import * as NetService from "@t3tools/shared/Net";import * as ConfigProvider from "effect/ConfigProvider";+import * as Console from "effect/Console";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";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", () =const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };-function makeTestService(serviceStatus: BootService.BootServiceStatus) {+function makeTestService(+ serviceStatus: BootService.BootServiceStatus,+ restartOutcome: "restarted" | "queued" = "restarted",+) {const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];const restarts: Array<true> = [];const service = BootService.BootService.of({@@ -105,7 +109,7 @@ function makeTestService(serviceStatus: BootService.BootServiceStatus) {withStopped: (operation) => operation,restart: Effect.sync(() => {restarts.push(true);- return serviceStatus.installed;+ return serviceStatus.installed ? restartOutcome : "skipped";}),install: (options) =>Effect.sync(() => {@@ -146,6 +150,74 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands}),);+ it.effect("restart from inside the service says the restart is only queued", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });+ const { service } = makeTestService({ ...status, installedVersion: "0.0.30" }, "queued");+ vi.spyOn(BootService, "layer").mockReturnValue(+ Layer.succeed(BootService.BootService, service),+ );+ const lines: Array<string> = [];+ const testConsole = {+ ...globalThis.console,+ log: (...args: ReadonlyArray<unknown>) => {+ lines.push(args.map(String).join(" "));+ },+ } satisfies Console.Console;++ yield* Command.runWith(serviceCommand, { version: packageJson.version })([+ "restart",+ "--base-dir",+ baseDir,+ ]).pipe(+ Effect.provideService(HostProcess.Environment, {}),+ Effect.provideService(Console.Console, testConsole),+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),+ );++ const output = lines.join("\n");+ expect(output).not.toContain("Restarted");+ expect(output).toContain("Queued a restart of the T3 Code service on [email protected]");+ expect(output).toContain(`Logs: ${status.logPath}`);+ }),+ );++ it.effect("install reports a handed-off switch as pending", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });+ const { service } = makeTestService({ ...status, current: false });+ vi.spyOn(BootService, "layer").mockReturnValue(+ Layer.succeed(BootService.BootService, {+ ...service,+ install: (options) =>+ service.install(options).pipe(Effect.map((plan) => ({ ...plan, handedOff: true }))),+ }),+ );+ const lines: string[] = [];+ yield* Command.runWith(serviceCommand, { version: packageJson.version })([+ "install",+ "--base-dir",+ baseDir,+ ]).pipe(+ Effect.provideService(HostProcess.Environment, {}),+ Effect.provideService(Console.Console, {+ ...globalThis.console,+ log: (...args) => {+ lines.push(args.map(String).join(" "));+ },+ }),+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),+ );++ const output = lines.join("\n");+ expect(output).not.toMatch(/(?:Installed|Updated) T3 Code service/);+ expect(output).toContain("separate systemd unit");+ expect(output).toContain(status.logPath);+ }),+ );+it.effect.each(["install", "update"] as const)("%s refuses a downgrade before changing the service",(command) =>@@ -247,7 +319,7 @@ it.effect("leaves a newer service unchanged during onboarding without prompting"Effect.provide(NodeServices.layer),);- expect(ready).toBe(false);+ expect(ready).toBe("skipped");expect(installOptions).toEqual([]);}),);@@ -263,7 +335,7 @@ it.effect("keeps onboarding successful when a newer version appears before insta),);- expect(ready).toBe(false);+ expect(ready).toBe("skipped");}),);@@ -272,6 +344,6 @@ it.effect("keeps the manual-server fallback when background prerequisites fail",const ready = yield* recoverServiceOnboardingOffer(Effect.fail(new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" })),);- expect(ready).toBe(false);+ expect(ready).toBe("skipped");}),);diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.tsindex abb9fb1b711..352fa86756c 100644--- a/apps/server/src/cli/service.ts+++ b/apps/server/src/cli/service.ts@@ -58,6 +58,15 @@ export const reconcileService = Effect.fn("cli.service.reconcile")(function* (op} satisfies ServiceReconcileResult;});+function formatServiceChange(+ result: Extract<ServiceReconcileResult, { readonly changed: true }>,+): string {+ if (result.plan.handedOff === true) {+ 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}`;+ }+ return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;+}+export function formatServiceStatus(status: BootService.BootServiceStatus,cliVersion: string,@@ -126,9 +135,7 @@ const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pip);return;}- yield* Console.log(- `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,- );+ yield* Console.log(formatServiceChange(result));}),),),@@ -149,9 +156,7 @@ const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(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}`,- );+ yield* Console.log(formatServiceChange(result));}),),),@@ -167,11 +172,15 @@ const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipeEffect.gen(function* () {const service = yield* BootService.BootService;const status = yield* service.status;- const restarted = yield* service.restart;+ const outcome = yield* service.restart;+ const onVersion =+ status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`;yield* Console.log(- restarted- ? `Restarted the T3 Code service${status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`}.`- : "T3 Code service is not installed.",+ outcome === "restarted"+ ? `Restarted the T3 Code service${onVersion}.`+ : outcome === "queued"+ ? `Queued a restart of the T3 Code service${onVersion}. This session runs inside the service and disconnects when it goes down.\nLogs: ${status.logPath}`+ : "T3 Code service is not installed.",);}),),@@ -207,16 +216,18 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(),);+export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped";+export const offerServiceDuringOnboarding = Effect.gen(function* () {const service = yield* BootService.BootService;const status = yield* service.status;const { supported, installed, current } = status;if (!supported) {- return false;+ return "skipped" as const;}if (installed && current) {yield* Console.log("T3 Code is already set up to run in the background on this machine.");- return true;+ return "ready" as const;}for (const problem of status.problems ?? []) {yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);@@ -229,7 +240,7 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {yield* Console.log(`A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,);- return false;+ return "skipped" as const;}const platform = yield* HostProcess.Platform;const wanted = yield* Prompt.run(@@ -245,35 +256,45 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {}),);if (!wanted) {- return false;+ return "skipped" as const;}const result = yield* reconcileService();if (result.changed) {yield* Console.log(- `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,+ result.plan.handedOff === true+ ? formatServiceChange(result)+ : `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,);}- return true;+ return result.changed && result.plan.handedOff === true+ ? ("pending" as const)+ : ("ready" as const);});+const reportServiceSetupFailure = (error: BootService.BootServiceError) =>+ Console.warn(`Background setup did not finish: ${error.message}`).pipe(+ Effect.as("skipped" as const),+ );+export const recoverServiceOnboardingOffer = <R>(- offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,+ offer: Effect.Effect<+ ServiceOnboardingOutcome,+ BootService.BootServiceError | Terminal.QuitError,+ R+ >,) =>offer.pipe(Effect.catchTags({- QuitError: () => Effect.succeed(false),+ QuitError: () => Effect.succeed("skipped" as const),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)),- BootServicePrerequisiteError: (error) =>- Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),- BootServiceUpdatePendingError: (error) =>- Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),- BootServiceDowngradeRefusedError: (error) =>- Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),+ Console.log(`Skipping background setup: ${error.message}`).pipe(+ Effect.as("skipped" as const),+ ),+ BootServiceCommandError: reportServiceSetupFailure,+ BootServiceInstallError: reportServiceSetupFailure,+ BootServicePrerequisiteError: reportServiceSetupFailure,+ BootServiceUpdatePendingError: reportServiceSetupFailure,+ BootServiceDowngradeRefusedError: reportServiceSetupFailure,}),);diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.tsindex 4d784f04c42..67ae3bfa532 100644--- a/apps/server/src/cli/update.test.ts+++ b/apps/server/src/cli/update.test.ts@@ -1,12 +1,23 @@import * as NodeServices from "@effect/platform-node/NodeServices";-import { assert, it } from "@effect/vitest";+import { assert, expect, it } from "@effect/vitest";+import * as HostProcess from "@t3tools/shared/HostProcess";+import * as NetService from "@t3tools/shared/Net";+import * as ConfigProvider from "effect/ConfigProvider";+import * as Console from "effect/Console";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Path from "effect/Path";-import * as HostProcess from "@t3tools/shared/HostProcess";+import { Command } from "effect/cli";+import { afterEach, vi } from "vite-plus/test";-import { repointLauncher, resolveLauncherPath } from "./update.ts";+import packageJson from "../../package.json" with { type: "json" };+import * as BootService from "../cloud/bootService.ts";+import { pinnedRuntimePaths } from "../cloud/pinnedRuntime.ts";+import { repointLauncher, resolveLauncherPath, updateCommand } from "./update.ts";++afterEach(() => vi.restoreAllMocks());it.layer(NodeServices.layer)("t3 update launcher", (it) => {it.effect("repoints a symlink that lives in a runtime versions tree", () =>@@ -101,3 +112,78 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),);});++it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 update service", (it) => {+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(+ "reports the service switch as pending after installing the target runtime",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-service-" });+ const targetVersion = "999.0.0";+ const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");+ yield* fs.makeDirectory(runtime.versionDir, { recursive: true });+ yield* fs.writeFileString(+ runtime.entryPath,+ `#!/bin/sh\nprintf 't3 v${targetVersion}\\n'\n`,+ );+ yield* fs.chmod(runtime.entryPath, 0o755);+ yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);+ const logPath = path.join(baseDir, "userdata/logs/boot-service.log");+ const unitPath = path.join(baseDir, "t3code.service");+ const installs: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];+ vi.spyOn(BootService, "layer").mockReturnValue(+ Layer.succeed(BootService.BootService, {+ status: Effect.succeed({+ supported: true,+ installed: true,+ current: true,+ installedVersion: packageJson.version,+ installedBaseDir: baseDir,+ logPath,+ unitPath,+ }),+ install: (options) =>+ Effect.sync(() => {+ installs.push(options);+ return {+ program: [runtime.entryPath],+ baseDir,+ logPath,+ unitPath,+ handedOff: true,+ };+ }),+ restart: Effect.die("unexpected restart"),+ uninstall: Effect.die("unexpected uninstall"),+ withStopped: () => Effect.die("unexpected maintenance"),+ }),+ );+ const lines: string[] = [];+ yield* Command.runWith(updateCommand, { version: packageJson.version })([+ targetVersion,+ "--yes",+ "--base-dir",+ baseDir,+ ]).pipe(+ Effect.provideService(HostProcess.Platform, "linux"),+ Effect.provideService(HostProcess.IsExecutable, false),+ Effect.provideService(HostProcess.Environment, {}),+ Effect.provideService(Console.Console, {+ ...globalThis.console,+ log: (...args) => {+ lines.push(args.map(String).join(" "));+ },+ }),+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),+ );++ expect(installs).toEqual([{ allowDowngrade: false, start: true }]);+ const output = lines.join("\n");+ expect(output).not.toContain("Background service restarted");+ expect(output).toContain(`Background service switching to ${targetVersion}`);+ expect(output).toContain(logPath);+ }),+ );+});diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.tsindex 0014f7bd6ce..3d18f8015a2 100644--- a/apps/server/src/cli/update.ts+++ b/apps/server/src/cli/update.ts@@ -490,18 +490,16 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {targetEntryPath: runtime.entryPath,});- // The service switch runs in this process against the target version: the downloaded runtime- // has already proven it runs (the `--version` check above), and doing it here rather than- // through the target's own CLI means a downgrade to a version without today's commands still- // works.- let serviceUpdated = false;+ // Use today's service manager for the target version. Inside the service it hands off to+ // the target CLI, so stopping this process cannot interrupt the switch.+ let servicePlan: BootService.BootServicePlan | undefined;if (serviceInstalled && !serviceCurrent) {yield* Console.log(restartService? "Restarting the background service...": "Updating the background service...",);- yield* BootService.BootService.pipe(+ servicePlan = yield* BootService.BootService.pipe(Effect.flatMap((target) =>target.install({ allowDowngrade: input.allowDowngrade, start: restartService }),),@@ -519,7 +517,6 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {}),),);- serviceUpdated = restartService;}progress.success(`Installed T3 Code ${targetVersion}`);@@ -528,7 +525,11 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {} else {yield* Console.log(` Run ${runtime.entryPath}\n`);}- if (serviceUpdated) {+ if (servicePlan?.handedOff === true) {+ yield* Console.log(+ ` Background service switching to ${targetVersion} from a separate systemd unit, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,+ );+ } else if (servicePlan !== undefined && restartService) {yield* Console.log(` Background service restarted on ${targetVersion}`);} else if (serviceInstalled && serviceCurrent) {yield* Console.log(` Background service already on ${targetVersion}`);diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.tsindex 4fb6d93babd..bbaf441383f 100644--- a/apps/server/src/cloud/bootService.test.ts+++ b/apps/server/src/cloud/bootService.test.ts@@ -140,6 +140,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");const commands: string[] = [];+ const invocations: ProcessRunner.ProcessRunInput[] = [];const timeouts = new Map<string, unknown>();const control: {failCommand: string | undefined;@@ -159,6 +160,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* () {const command = `${input.command} ${input.args.join(" ")}`;commands.push(command);+ invocations.push(input);timeouts.set(command, input.timeout);const failed = command === control.failCommand;if (!failed && command === "loginctl enable-linger --no-ask-password 501")@@ -205,6 +207,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (environmentPath: string | undefined = installerPath,cliVersion = "1.2.3",serviceBaseDir = baseDir,+ insideService = false,) =>Effect.gen(function* () {const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);@@ -235,6 +238,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (...(environmentPath === undefined || environmentPath === ""? {}: { PATH: environmentPath }),+ ...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}),},}),),@@ -242,7 +246,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (),);const service = yield* makeService();- return { service, makeService, fs, statePath, commands, timeouts, control, runtime };+ return { service, makeService, fs, statePath, commands, invocations, timeouts, control, runtime };});it.layer(NodeServices.layer)("boot service install", (it) => {@@ -507,7 +511,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {expect(status.problems).toContain("restart-pending");commands.length = 0;- expect(yield* newer.restart).toBe(true);+ expect(yield* newer.restart).toBe("restarted");expect((yield* newer.status).problems).not.toContain("restart-pending");expect((yield* newer.status).current).toBe(true);}),@@ -625,11 +629,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>Effect.gen(function* () {const { service, commands } = yield* makeHarness();- expect(yield* service.restart).toBe(false);+ expect(yield* service.restart).toBe("skipped");yield* service.install();commands.length = 0;- expect(yield* service.restart).toBe(true);+ expect(yield* service.restart).toBe("restarted");expect(commands.filter((command) => command.startsWith("systemctl ") && !command.includes("show-environment"),@@ -652,7 +656,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));- expect(yield* other.restart).toBe(false);+ expect(yield* other.restart).toBe("skipped");expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);}),);@@ -678,6 +682,87 @@ it.layer(NodeServices.layer)("boot service install", (it) => {}),);+ it.effect("hands the whole install to systemd without changing the running service", () =>+ Effect.gen(function* () {+ const { fs, commands, invocations, control, makeService } = yield* makeHarness();+ const path = yield* Path.Path;+ const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-handoff-" });+ const baseDir = path.join(home, "T3 Data 100%", "${UNSET}", "$literal");+ const outside = yield* makeService(undefined, "1.2.3", baseDir);+ const plan = yield* outside.install();+ const statePath = path.join(baseDir, "runtime", "service-state.json");+ const state = yield* fs.readFileString(statePath);+ const unit = yield* fs.readFileString(plan.unitPath);+ const inside = yield* makeService(undefined, "1.2.4", baseDir, true);+ commands.length = 0;+ invocations.length = 0;++ const result = yield* inside.install({ allowDowngrade: true });++ expect(yield* fs.readFileString(statePath)).toBe(state);+ expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);+ expect(commands).not.toContain("systemctl --user stop t3code.service");+ expect(result).toMatchObject({ handedOff: true, logPath: plan.logPath });+ const handoffs = invocations.filter(({ command }) => command === "systemd-run");+ expect(handoffs).toHaveLength(1);+ expect(handoffs[0]?.args).toEqual([+ "--user",+ "--collect",+ "--quiet",+ `--property=StandardOutput=append:${plan.logPath}`,+ `--property=StandardError=append:${plan.logPath}`,+ "--setenv=T3_BOOT_SERVICE_UNIT=",+ pinnedRuntimePaths(path, baseDir, "1.2.4", "linux").entryPath,+ "service",+ "install",+ "--base-dir",+ path.join(home, "T3 Data 100%", "$${UNSET}", "$$literal"),+ "--allow-downgrade",+ ]);++ const handoff = handoffs[0]!;+ control.failCommand = `${handoff.command} ${handoff.args.join(" ")}`;+ const error = yield* inside.install({ allowDowngrade: true }).pipe(Effect.flip);+ expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });+ expect(yield* fs.readFileString(statePath)).toBe(state);+ expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);+ expect(control.active).toBe(true);+ expect(commands).not.toContain("systemctl --user stop t3code.service");+ }),+ );++ it.effect(+ "queues an in-service restart without stopping the caller, even on handoff failure",+ () =>+ Effect.gen(function* () {+ const { service, fs, statePath, commands, control, makeService } = yield* makeHarness();+ const plan = yield* service.install();+ const state = yield* fs.readFileString(statePath);+ const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`;+ yield* fs.writeFileString(marker, "1.2.3\n");+ const inside = yield* makeService(undefined, "1.2.3", undefined, true);+ commands.length = 0;+ control.failCommand = "systemctl --user daemon-reload";++ const error = yield* inside.restart.pipe(Effect.flip);+ expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });+ expect(commands).toEqual(["systemctl --user daemon-reload"]);+ expect(control.active).toBe(true);++ control.failCommand = undefined;+ commands.length = 0;+ const outcome = yield* inside.restart;+ expect(commands).toEqual([+ "systemctl --user daemon-reload",+ "systemctl --user enable t3code.service",+ "systemctl --user restart --no-block t3code.service",+ ]);+ expect(outcome).toBe("queued");+ expect(yield* fs.readFileString(statePath)).toBe(state);+ expect(yield* fs.readFileString(marker)).toBe("1.2.3\n");+ }),+ );+it.effect("restarts an installed service when repair fails", () =>Effect.gen(function* () {const { service, commands, control } = yield* makeHarness();diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.tsindex 00ab464bea4..ac82b3bb828 100644--- a/apps/server/src/cloud/bootService.ts+++ b/apps/server/src/cloud/bootService.ts@@ -75,6 +75,8 @@ export interface BootServicePlan {readonly baseDir: string;readonly logPath: string;readonly unitPath: string;+ /** The manager accepted a detached install; its outcome is written to `logPath`. */+ readonly handedOff?: boolean;}/** Pure renderer: service units cannot rely on the user's shell or PATH. */@@ -206,6 +208,8 @@ export interface BootServiceManager {readonly stop: ReadonlyArray<BootServiceStep>;readonly activate: ReadonlyArray<BootServiceStep>;readonly restart: ReadonlyArray<BootServiceStep>;+ /** Queue a restart owned by the manager, since stopping would kill the caller. */+ readonly handoff?: ReadonlyArray<BootServiceStep>;readonly deactivate: ReadonlyArray<BootServiceStep>;readonly finalize: ReadonlyArray<BootServiceStep>;}@@ -221,6 +225,18 @@ function systemdManager(input: {"user",BOOT_SERVICE_UNIT_FILE,);+ const prepareActivation = [+ {+ step: "reloading systemd user units",+ command: "systemctl",+ args: ["--user", "daemon-reload"],+ },+ {+ step: "enabling the service",+ command: "systemctl",+ args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],+ },+ ];return {kind: "systemd",unitPath,@@ -234,16 +250,7 @@ function systemdManager(input: {},],activate: [- {- step: "reloading systemd user units",- command: "systemctl",- args: ["--user", "daemon-reload"],- },- {- step: "enabling the service",- command: "systemctl",- args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],- },+ ...prepareActivation,{step: "starting the service",command: "systemctl",@@ -257,6 +264,14 @@ function systemdManager(input: {args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],},],+ handoff: [+ ...prepareActivation,+ {+ step: "restarting the service",+ command: "systemctl",+ args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],+ },+ ],deactivate: [{step: "stopping the service",@@ -494,10 +509,11 @@ export class BootService extends Context.Service<}) => Effect.Effect<BootServicePlan, BootServiceError>;/*** Only when the unit serves this base dir: the unit name is per user, so- * another home's service is left alone. Resolves false when nothing was- * restarted.+ * another home's service is left alone, which resolves `skipped`. From+ * inside the service the restart can only be `queued` with the service+ * manager, since the stop ends this process.*/- readonly restart: Effect.Effect<boolean, BootServiceError>;+ readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;/*** Run `operation` while this home's installed service is stopped, then* 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: {);const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));+ const runningInsideService =+ (yield* Config.String(BOOT_SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===+ BOOT_SERVICE_UNIT_FILE;const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;const runner = yield* ProcessRunner.ProcessRunner;@@ -781,6 +800,28 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {// middle of a remote update, which is the one time it writes the state file// itself.const start = options?.start !== false;+ if (installed && start && runningInsideService && manager.kind === "systemd") {+ // Stopping the unit from inside it kills this process before the start.+ // A transient unit runs the same install from outside, stop first, so it+ // still serialises with a remote update the launcher may be starting.+ yield* runStep("handing the install to a transient unit", "systemd-run", [+ "--user",+ "--collect",+ "--quiet",+ // Transient properties reach systemd literally, unlike unit-file specifiers.+ `--property=StandardOutput=append:${logPath}`,+ `--property=StandardError=append:${logPath}`,+ `--setenv=${BOOT_SERVICE_UNIT_ENV}=`,+ runtimePaths.entryPath,+ "service",+ "install",+ "--base-dir",+ // systemd expands $VAR in arguments (not in the executable path).+ input.baseDir.replaceAll("$", () => "$$"),+ ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),+ ]);+ return { ...plan, handedOff: true };+ }if (installed && start) {yield* runSteps(manager.stop);}@@ -856,20 +897,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {const restart: BootService["Service"]["restart"] = Effect.gen(function* () {const manager = yield* requireManager;const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);- if (Option.isNone(unit)) return false;+ if (Option.isNone(unit)) return "skipped" as const;const installedBaseDir = bootServiceBaseDirOf(unit.value);if (installedBaseDir === undefined ||path.resolve(installedBaseDir) !== path.resolve(input.baseDir)) {- return false;+ return "skipped" as const;+ }+ // Writes no state, and the launcher lets an update transition in flight+ // finish before the queued stop tears it down.+ if (runningInsideService && manager.handoff !== undefined) {+ yield* runSteps(manager.handoff);+ return "queued" as const;}yield* runSteps(manager.stop);yield* runSteps(manager.activate).pipe(Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),);yield* fs.remove(restartPendingPath, { force: true });- return true;+ return "restarted" as const;}).pipe(Effect.mapError((cause) =>cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,