TypeScript
fix(server): prevent accidental service downgrades (#5302)
Theo Browne0e77fbd3d0d7
diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.tsindex 08980faf790..b442d46df36 100644--- a/apps/server/src/cli/service.test.ts+++ b/apps/server/src/cli/service.test.ts@@ -1,6 +1,26 @@-import { assert, it } from "@effect/vitest";+import * as NodeServices from "@effect/platform-node/NodeServices";+import { assert, expect, it } from "@effect/vitest";+import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";+import * as NetService from "@t3tools/shared/Net";+import * as ConfigProvider from "effect/ConfigProvider";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Terminal from "effect/Terminal";+import { Command } from "effect/unstable/cli";+import { afterEach, vi } from "vite-plus/test";-import { formatServiceStatus } from "./service.ts";+import packageJson from "../../package.json" with { type: "json" };+import * as BootService from "../cloud/bootService.ts";+import {+ formatServiceStatus,+ offerServiceDuringOnboarding,+ reconcileService,+ recoverServiceOnboardingOffer,+ serviceCommand,+} from "./service.ts";++afterEach(() => vi.restoreAllMocks());const status = {supported: true,@@ -35,3 +55,149 @@ it("explains where the service is supported", () => {"Supported on: Linux with systemd, macOS with launchd",);});++it("reports a newer installed service and gives an exact-version repair command", () => {+ const output = formatServiceStatus(+ { ...status, current: false, installedVersion: "0.0.32-nightly.1" },+ "0.0.31",+ );++ assert.include(output, "[email protected] (newer than this [email protected] CLI)");+ assert.include(output, "npx [email protected] service update");+ assert.notInclude(output, "npx t3@latest service update");+});++const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };++function makeTestService(serviceStatus: BootService.BootServiceStatus) {+ const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];+ const service = BootService.BootService.of({+ status: Effect.succeed(serviceStatus),+ install: (options) =>+ Effect.sync(() => {+ installOptions.push(options);+ return {+ nodePath: "/test/node",+ launcherPath: "/test/service-launcher.mjs",+ baseDir: "/test/t3",+ unitPath: serviceStatus.unitPath,+ logPath: serviceStatus.logPath,+ };+ }),+ uninstall: Effect.succeed(false),+ });+ return { service, installOptions };+}++it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands", (it) => {+ it.effect.each(["install", "update"] as const)(+ "%s refuses a downgrade before changing the service",+ (command) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });+ const { service, installOptions } = makeTestService(newerServiceStatus);+ vi.spyOn(BootService, "layer").mockReturnValue(+ Layer.succeed(BootService.BootService, service),+ );++ const error = yield* Command.runWith(serviceCommand, { version: packageJson.version })([+ command,+ "--base-dir",+ baseDir,+ ]).pipe(+ Effect.provideService(HostProcessEnvironment, {}),+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),+ Effect.flip,+ );++ expect(error).toMatchObject({+ _tag: "BootServiceDowngradeRefusedError",+ installedVersion: "999.0.0",+ targetVersion: packageJson.version,+ });+ expect(installOptions).toEqual([]);+ }),+ );++ it.effect.each(["install", "update"] as const)("%s allows an explicit downgrade", (command) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });+ const { service, installOptions } = makeTestService(newerServiceStatus);+ vi.spyOn(BootService, "layer").mockReturnValue(+ Layer.succeed(BootService.BootService, service),+ );++ yield* Command.runWith(serviceCommand, { version: packageJson.version })([+ command,+ "--base-dir",+ baseDir,+ "--allow-downgrade",+ ]).pipe(+ Effect.provideService(HostProcessEnvironment, {}),+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),+ );++ expect(installOptions).toEqual([{ allowDowngrade: true }]);+ }),+ );+});++it.effect.each([+ { name: "a new service", state: { ...status, installed: false, current: false } },+ { name: "an older service", state: { ...status, current: false, installedVersion: "0.0.0" } },+ {+ name: "the same version",+ state: { ...status, current: false, installedVersion: packageJson.version },+ },+ { name: "an unknown version", state: { ...status, current: false } },+])("installs or repairs $name without an override", ({ state }) =>+ Effect.gen(function* () {+ const { service, installOptions } = makeTestService(state);++ const result = yield* reconcileService().pipe(+ Effect.provideService(BootService.BootService, service),+ );++ expect(result.changed).toBe(true);+ expect(installOptions).toEqual([undefined]);+ }),+);++it.effect("leaves a newer service unchanged during onboarding without prompting", () =>+ Effect.gen(function* () {+ const { service, installOptions } = makeTestService(newerServiceStatus);+ const terminal = Terminal.make({+ columns: Effect.succeed(80),+ rows: Effect.succeed(24),+ readInput: Effect.die("Onboarding must not prompt to replace a newer service."),+ readLine: Effect.die("Onboarding must not prompt to replace a newer service."),+ display: () => Effect.die("Onboarding must not prompt to replace a newer service."),+ });++ const ready = yield* offerServiceDuringOnboarding.pipe(+ Effect.provideService(BootService.BootService, service),+ Effect.provideService(Terminal.Terminal, terminal),+ Effect.provide(NodeServices.layer),+ );++ expect(ready).toBe(false);+ expect(installOptions).toEqual([]);+ }),+);++it.effect("keeps onboarding successful when a newer version appears before install", () =>+ Effect.gen(function* () {+ const ready = yield* recoverServiceOnboardingOffer(+ Effect.fail(+ new BootService.BootServiceDowngradeRefusedError({+ installedVersion: "999.0.0",+ targetVersion: packageJson.version,+ }),+ ),+ );++ expect(ready).toBe(false);+ }),+);diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.tsindex 74d220610ef..3e2e893334f 100644--- a/apps/server/src/cli/service.ts+++ b/apps/server/src/cli/service.ts@@ -3,10 +3,11 @@ import * as Console from "effect/Console";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Terminal from "effect/Terminal";-import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";+import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";import packageJson from "../../package.json" with { type: "json" };import * as BootService from "../cloud/bootService.ts";+import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";import type * as ServerConfig from "../config.ts";import * as ProcessRunner from "../processRunner.ts";import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";@@ -30,13 +31,25 @@ export type ServiceReconcileResult =};/** Install, update, or repair the service using the CLI version running this command. */-export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {+export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {+ readonly allowDowngrade?: boolean;+}) {const service = yield* BootService.BootService;const status = yield* service.status;if (status.installed && status.current) {return { changed: false, status } satisfies ServiceReconcileResult;}- const plan = yield* service.install;+ if (+ status.installedVersion !== undefined &&+ options?.allowDowngrade !== true &&+ compareExactServiceVersions(packageJson.version, status.installedVersion) < 0+ ) {+ return yield* new BootService.BootServiceDowngradeRefusedError({+ installedVersion: status.installedVersion,+ targetVersion: packageJson.version,+ });+ }+ const plan = yield* service.install(options);return {changed: true,previouslyInstalled: status.installed,@@ -54,9 +67,23 @@ export function formatServiceStatus(if (!status.installed) {return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";}+ const installedVersion = status.installedVersion ?? cliVersion;+ if (+ !status.current &&+ status.installedVersion !== undefined &&+ compareExactServiceVersions(status.installedVersion, cliVersion) > 0+ ) {+ return [+ "T3 Code service",+ ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,+ ` Unit: ${status.unitPath}`,+ ` Logs: ${status.logPath}`,+ ` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,+ ].join("\n");+ }return ["T3 Code service",- ` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,+ ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,` Unit: ${status.unitPath}`,` Logs: ${status.logPath}`,...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),@@ -72,13 +99,21 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(return yield* run.pipe(Effect.provide(bootServiceLayer(config)));});-const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(+const serviceReconcileFlags = {+ ...projectLocationFlags,+ allowDowngrade: Flag.boolean("allow-downgrade").pipe(+ Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),+ Flag.withDefault(false),+ ),+};++const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(Command.withDescription("Install T3 Code as a background service for this user."),Command.withHandler((flags) =>runServiceCommand(flags,Effect.gen(function* () {- const result = yield* reconcileService();+ const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });if (!result.changed) {yield* Console.log(`T3 Code service is already installed with t3@${packageJson.version}.`,@@ -93,7 +128,7 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe),);-const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(+const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(Command.withDescription("Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",),@@ -101,7 +136,7 @@ const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(runServiceCommand(flags,Effect.gen(function* () {- const result = yield* reconcileService();+ const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });if (!result.changed) {yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);return;@@ -145,7 +180,8 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(export const offerServiceDuringOnboarding = Effect.gen(function* () {const service = yield* BootService.BootService;- const { supported, installed, current } = yield* service.status;+ const status = yield* service.status;+ const { supported, installed, current } = status;if (!supported) {return false;}@@ -153,6 +189,17 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {yield* Console.log("T3 Code is already set up to run in the background on this machine.");return true;}+ if (+ installed &&+ status.installedVersion !== undefined &&+ compareExactServiceVersions(status.installedVersion, packageJson.version) > 0+ ) {+ yield* Console.log(+ `A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,+ );+ // This CLI cannot verify the newer service. Keep the manual fallback available.+ return false;+ }// A LaunchAgent starts at login and dies at logout; there is no// enable-linger equivalent on macOS. Do not promise more than that.const platform = yield* HostProcessPlatform;@@ -194,6 +241,8 @@ export const recoverServiceOnboardingOffer = <R>(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)),}),);diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.tsindex a999f81b289..3e31ab3f637 100644--- a/apps/server/src/cloud/bootService.test.ts+++ b/apps/server/src/cloud/bootService.test.ts@@ -127,24 +127,34 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (const commands: string[] = [];const timeouts = new Map<string, unknown>();- const control: { failCommand: string | undefined } = { failCommand: undefined };+ const control: { failCommand: string | undefined; stateAfterStop?: string } = {+ failCommand: undefined,+ };const runner = ProcessRunner.ProcessRunner.of({- run: (input) =>- Effect.sync(() => {- const command = `${input.command} ${input.args.join(" ")}`;- commands.push(command);- timeouts.set(command, input.timeout);- return {- stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",- stderr: "",- code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),- timedOut: false,- stdoutTruncated: false,- stderrTruncated: false,- stdoutInvalidUtf8: false,- stderrInvalidUtf8: false,- };- }),+ run: Effect.fn("test.run_boot_service_command")(function* (+ input: ProcessRunner.ProcessRunInput,+ ) {+ const command = `${input.command} ${input.args.join(" ")}`;+ commands.push(command);+ timeouts.set(command, input.timeout);+ if (+ control.stateAfterStop !== undefined &&+ (command === "systemctl --user stop t3code.service" ||+ command.startsWith("launchctl bootout --wait "))+ ) {+ yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);+ }+ return {+ stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",+ stderr: "",+ code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),+ timedOut: false,+ stdoutTruncated: false,+ stderrTruncated: false,+ stdoutInvalidUtf8: false,+ stderrInvalidUtf8: false,+ };+ }),});const makeService = (environmentPath = installerPath) =>BootService.make({@@ -179,14 +189,17 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("installs, reports current state, and uninstalls", () =>Effect.gen(function* () {const { service, fs, statePath, commands, timeouts } = yield* makeHarness();- const plan = yield* service.install;+ const plan = yield* service.install();expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({protocol: SERVICE_LAUNCHER_PROTOCOL,activeVersion: "1.2.3",});expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");- expect((yield* service.status).current).toBe(true);+ expect(yield* service.status).toMatchObject({+ current: true,+ installedVersion: "1.2.3",+ });// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.const pendingState = JSON.stringify({protocol: SERVICE_LAUNCHER_PROTOCOL,@@ -212,10 +225,116 @@ it.layer(NodeServices.layer)("boot service install", (it) => {}),);+ it.effect.each(["linux", "darwin"] as const)(+ "reports the installed version across launcher protocols on %s",+ (platform) =>+ Effect.gen(function* () {+ const { service, fs, statePath } = yield* makeHarness(platform);+ yield* service.install();++ for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {+ yield* fs.writeFileString(+ statePath,+ `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,+ );+ expect(yield* service.status).toMatchObject({+ current: false,+ installedVersion: "1.2.4-nightly.1",+ });+ }+ }),+ );++ it.effect("reports an unknown version for invalid service state", () =>+ Effect.gen(function* () {+ const { service, fs, statePath } = yield* makeHarness();+ yield* service.install();++ for (const stateText of [+ "{",+ '{"activeVersion":"latest"}',+ '{"activeVersion":"1.2"}',+ '{"activeVersion":123}',+ ]) {+ yield* fs.writeFileString(statePath, stateText);+ const status = yield* service.status;+ expect(status.current).toBe(false);+ expect(status.installedVersion).toBeUndefined();+ }+ }),+ );++ it.effect.each(["linux", "darwin"] as const)(+ "preserves a newer version that finishes updating during stop on %s",+ (platform) =>+ Effect.gen(function* () {+ const { service, fs, statePath, commands, control } = yield* makeHarness(platform);+ const plan = yield* service.install();+ const launcher = yield* fs.readFileString(plan.launcherPath);+ const unit = yield* fs.readFileString(plan.unitPath);+ control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;+ commands.length = 0;++ const error = yield* service.install().pipe(Effect.flip);++ expect(error).toMatchObject({+ _tag: "BootServiceDowngradeRefusedError",+ installedVersion: "1.2.4",+ targetVersion: "1.2.3",+ });+ expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);+ expect(yield* fs.readFileString(plan.launcherPath)).toBe(launcher);+ expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);+ expect(+ commands.filter((command) =>+ command.startsWith(platform === "linux" ? "systemctl " : "launchctl "),+ ),+ ).toEqual(+ platform === "linux"+ ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]+ : [+ "launchctl bootout --wait gui/501/com.t3tools.t3code.service",+ `launchctl bootstrap gui/501 ${plan.unitPath}`,+ ],+ );+ }),+ );++ it.effect("allows an explicit downgrade", () =>+ Effect.gen(function* () {+ const { service, fs, statePath } = yield* makeHarness();+ yield* service.install();+ yield* fs.writeFileString(+ statePath,+ `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,+ );++ yield* service.install({ allowDowngrade: true });++ expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");+ expect((yield* service.status).current).toBe(true);+ }),+ );++ it.effect("repairs versions with equal SemVer precedence without an override", () =>+ Effect.gen(function* () {+ const { service, fs, statePath } = yield* makeHarness();+ yield* service.install();+ yield* fs.writeFileString(+ statePath,+ `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,+ );++ yield* service.install();++ expect((yield* service.status).current).toBe(true);+ }),+ );+it.effect("copies the launcher from the prepared pinned runtime", () =>Effect.gen(function* () {const { service, fs } = yield* makeHarness("linux", true);- const plan = yield* service.install;+ const plan = yield* service.install();expect(yield* fs.readFileString(plan.launcherPath)).toBe("export const source = 'pinned runtime';\n",@@ -226,11 +345,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("restarts an installed service when repair fails", () =>Effect.gen(function* () {const { service, commands, control } = yield* makeHarness();- yield* service.install;+ yield* service.install();commands.length = 0;control.failCommand = "systemctl --user daemon-reload";- const error = yield* service.install.pipe(Effect.flip);+ const error = yield* service.install().pipe(Effect.flip);expect(error._tag).toBe("BootServiceCommandError");expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual(["systemctl --user stop t3code.service",@@ -243,7 +362,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("restarts without overwriting a pending remote update", () =>Effect.gen(function* () {const { service, fs, statePath, commands } = yield* makeHarness();- yield* service.install;+ yield* service.install();// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.const pendingState = JSON.stringify({protocol: SERVICE_LAUNCHER_PROTOCOL - 1,@@ -256,14 +375,18 @@ it.layer(NodeServices.layer)("boot service install", (it) => {},});yield* fs.writeFileString(statePath, pendingState);- commands.length = 0;-- expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");- expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);- expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([- "systemctl --user stop t3code.service",- "systemctl --user restart t3code.service",- ]);+ for (const allowDowngrade of [false, true]) {+ commands.length = 0;++ expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(+ "BootServiceUpdatePendingError",+ );+ expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);+ expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([+ "systemctl --user stop t3code.service",+ "systemctl --user restart t3code.service",+ ]);+ }}),);@@ -271,14 +394,14 @@ it.layer(NodeServices.layer)("boot service install", (it) => {Effect.gen(function* () {const { service } = yield* makeHarness("win32");expect((yield* service.status).supported).toBe(false);- expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");+ expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");}),);it.effect("installs, reports current state, and uninstalls on macOS", () =>Effect.gen(function* () {const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");- const plan = yield* service.install;+ const plan = yield* service.install();expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(true,@@ -291,7 +414,10 @@ it.layer(NodeServices.layer)("boot service install", (it) => {activeVersion: "1.2.3",});expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");- expect((yield* service.status).current).toBe(true);+ expect(yield* service.status).toMatchObject({+ current: true,+ installedVersion: "1.2.3",+ });expect(yield* service.uninstall).toBe(true);expect((yield* service.status).installed).toBe(false);expect(commands.some((command) => command.startsWith("npm "))).toBe(false);@@ -307,12 +433,12 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("restarts the launch agent when repair fails", () =>Effect.gen(function* () {const { service, commands, control } = yield* makeHarness("darwin");- yield* service.install;+ yield* service.install();const plistPath = (yield* service.status).unitPath;commands.length = 0;control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;- const error = yield* service.install.pipe(Effect.flip);+ const error = yield* service.install().pipe(Effect.flip);expect(error._tag).toBe("BootServiceCommandError");expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual(["launchctl bootout --wait gui/501/com.t3tools.t3code.service",@@ -326,7 +452,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>Effect.gen(function* () {const { service, fs } = yield* makeHarness("darwin", false, "");- const plan = yield* service.install;+ const plan = yield* service.install();expect(yield* fs.readFileString(plan.unitPath)).toContain(" <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",@@ -338,7 +464,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("adds missing provider directories to a minimal installer PATH", () =>Effect.gen(function* () {const { service, fs } = yield* makeHarness("darwin", false, "/usr/bin:/bin");- const plan = yield* service.install;+ const plan = yield* service.install();expect(yield* fs.readFileString(plan.unitPath)).toContain(" <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",@@ -350,7 +476,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("keeps an installed launch agent current when the process PATH changes", () =>Effect.gen(function* () {const { service, makeService } = yield* makeHarness("darwin");- yield* service.install;+ yield* service.install();const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");expect((yield* restartedService.status).current).toBe(true);@@ -364,7 +490,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {false,"/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",);- const plan = yield* service.install;+ const plan = yield* service.install();const plist = yield* fs.readFileString(plan.unitPath);expect(plist).toContain(@@ -378,10 +504,10 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("ignores a bootout for an agent that is not loaded", () =>Effect.gen(function* () {const { service, control } = yield* makeHarness("darwin");- yield* service.install;+ yield* service.install();control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";- yield* service.install;+ yield* service.install();expect((yield* service.status).current).toBe(true);}),);@@ -389,7 +515,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("restarts without overwriting a pending remote update on macOS", () =>Effect.gen(function* () {const { service, fs, statePath, commands } = yield* makeHarness("darwin");- yield* service.install;+ yield* service.install();const plistPath = (yield* service.status).unitPath;// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.const pendingState = JSON.stringify({@@ -403,14 +529,18 @@ it.layer(NodeServices.layer)("boot service install", (it) => {},});yield* fs.writeFileString(statePath, pendingState);- commands.length = 0;-- expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");- expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);- expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([- "launchctl bootout --wait gui/501/com.t3tools.t3code.service",- `launchctl bootstrap gui/501 ${plistPath}`,- ]);+ for (const allowDowngrade of [false, true]) {+ commands.length = 0;++ expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(+ "BootServiceUpdatePendingError",+ );+ expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);+ expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([+ "launchctl bootout --wait gui/501/com.t3tools.t3code.service",+ `launchctl bootstrap gui/501 ${plistPath}`,+ ]);+ }}),);});diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.tsindex 969f45e6780..59530498076 100644--- a/apps/server/src/cloud/bootService.ts+++ b/apps/server/src/cloud/bootService.ts@@ -24,7 +24,9 @@ import {SERVICE_LAUNCHER_FILE,SERVICE_LAUNCHER_PROTOCOL,SERVICE_STATE_FILE,+ compareExactServiceVersions,parseServiceState,+ serviceStateActiveVersion,serviceStateHasPendingUpdate,type ServiceState,} from "./serviceProtocol.ts";@@ -416,16 +418,30 @@ export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootS}}+export class BootServiceDowngradeRefusedError extends Schema.TaggedErrorClass<BootServiceDowngradeRefusedError>()(+ "BootServiceDowngradeRefusedError",+ {+ installedVersion: Schema.String,+ targetVersion: Schema.String,+ },+) {+ override get message(): string {+ return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;+ }+}+export type BootServiceError =| BootServiceUnsupportedError| BootServiceCommandError| BootServiceInstallError- | BootServiceUpdatePendingError;+ | BootServiceUpdatePendingError+ | BootServiceDowngradeRefusedError;export interface BootServiceStatus {readonly supported: boolean;readonly installed: boolean;readonly current: boolean;+ readonly installedVersion?: string;readonly unitPath: string;readonly logPath: string;}@@ -433,7 +449,9 @@ export interface BootServiceStatus {export class BootService extends Context.Service<BootService,{- readonly install: Effect.Effect<BootServicePlan, BootServiceError>;+ readonly install: (options?: {+ readonly allowDowngrade?: boolean;+ }) => Effect.Effect<BootServicePlan, BootServiceError>;readonly uninstall: Effect.Effect<boolean, BootServiceError>;readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;}@@ -569,7 +587,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {{ discard: true },);- const install: BootService["Service"]["install"] = Effect.gen(function* () {+ const install = Effect.fn("cloud.boot_service.install")(function* (options?: {+ readonly allowDowngrade?: boolean;+ }) {const manager = yield* requireManager;yield* fs.makeDirectory(input.logsDir, { recursive: true })@@ -638,11 +658,23 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {yield* Effect.gen(function* () {if (installed) {const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);- if (- Option.isSome(previousStateText) &&- serviceStateHasPendingUpdate(previousStateText.value)- ) {- return yield* new BootServiceUpdatePendingError();+ if (Option.isSome(previousStateText)) {+ if (serviceStateHasPendingUpdate(previousStateText.value)) {+ return yield* new BootServiceUpdatePendingError();+ }+ // A remote update can finish after the CLI checks status. Read its+ // final version after the launcher stops and before changing files.+ const installedVersion = serviceStateActiveVersion(previousStateText.value);+ if (+ installedVersion !== undefined &&+ options?.allowDowngrade !== true &&+ compareExactServiceVersions(input.cliVersion, installedVersion) < 0+ ) {+ return yield* new BootServiceDowngradeRefusedError({+ installedVersion,+ targetVersion: input.cliVersion,+ });+ }}}yield* fs@@ -670,7 +702,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {),);return plan;- }).pipe(Effect.withSpan("cloud.boot_service.install"));+ });const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {const manager = yield* requireManager;@@ -704,6 +736,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {fs.readFileString(statePath).pipe(Effect.option),]);const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;+ const installedVersion = Option.isSome(stateText)+ ? serviceStateActiveVersion(stateText.value)+ : undefined;const normalizeUnit = (contents: string) =>detectedManager.kind === "launchd"? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")@@ -711,6 +746,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {return {supported: true,installed: true,+ ...(installedVersion === undefined ? {} : { installedVersion }),current:normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&launcherExists &&diff --git a/apps/server/src/cloud/serviceProtocol.ts b/apps/server/src/cloud/serviceProtocol.tsindex 0faf8894837..af94c9b4b5c 100644--- a/apps/server/src/cloud/serviceProtocol.ts+++ b/apps/server/src/cloud/serviceProtocol.ts@@ -184,6 +184,20 @@ export function serviceStateHasPendingUpdate(value: string): boolean {}}+/** Reads the active version across launcher protocol revisions for downgrade protection. */+export function serviceStateActiveVersion(value: string): string | undefined {+ try {+ const parsed: unknown = JSON.parse(value);+ return isRecord(parsed) &&+ typeof parsed.activeVersion === "string" &&+ isExactServiceVersion(parsed.activeVersion)+ ? parsed.activeVersion+ : undefined;+ } catch {+ return undefined;+ }+}+export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {let parsed: unknown;try {diff --git a/docs/user/background-service.md b/docs/user/background-service.mdindex 17de5777ba0..23ac07cee0d 100644--- a/docs/user/background-service.md+++ b/docs/user/background-service.md@@ -23,6 +23,22 @@ Update or repair it:npx t3@latest service update```+The service uses the same T3 Code version as the CLI you run. To install a nightly or an exact+version, use that version of the CLI:++```sh+npx t3@nightly service update+npx [email protected] service update+```++The install and update commands refuse to replace a newer service with an older version. Setup+through T3 Connect leaves a newer service unchanged. To downgrade, select the exact older version+and pass `--allow-downgrade`:++```sh+npx [email protected] service update --allow-downgrade+```+Stop it and remove it from startup:```sh