TypeScript
fix(server): t3 service install no longer moves a --base-dir service onto an empty ~/.t3 (#23878)
shivam33f85846be8b
diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.tsindex 7ab52e82a39..900c41e6617 100644--- a/apps/server/src/cli/service.test.ts+++ b/apps/server/src/cli/service.test.ts@@ -59,13 +59,33 @@ function makeTestService(}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) =>+ it.effect.each(+ (["install", "update"] as const).flatMap((command) => [+ {+ command,+ label: "a downgrade",+ status: newerServiceStatus,+ error: {+ _tag: "BootServiceDowngradeRefusedError",+ installedVersion: "999.0.0",+ targetVersion: packageJson.version,+ },+ },+ // This home's newer state must not ask for --allow-downgrade first.+ {+ command,+ label: "another home's service",+ status: { ...newerServiceStatus, otherBaseDir: "/srv/t3" },+ error: { _tag: "BootServiceOtherBaseDirError", installedBaseDir: "/srv/t3" },+ },+ ]),+ )(+ "$command refuses $label before changing the service",+ ({ command, status: serviceStatus, error: expected }) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });- const { service, installOptions } = makeTestService(newerServiceStatus);+ const { service, installOptions } = makeTestService(serviceStatus);vi.spyOn(BootService, "layer").mockReturnValue(Layer.succeed(BootService.BootService, service),);@@ -80,11 +100,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commandsEffect.flip,);- expect(error).toMatchObject({- _tag: "BootServiceDowngradeRefusedError",- installedVersion: "999.0.0",- targetVersion: packageJson.version,- });+ expect(error).toMatchObject(expected);expect(installOptions).toEqual([]);}),);@@ -239,7 +255,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands),);expect(uninstalls).toEqual(input.removed);- expect(output).toContain(input.otherHome ? "another T3 home" : "Removed");+ expect(output).toContain(input.otherHome ? "--base-dir '/home/me/.t3'" : "Removed");}),);});diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.tsindex 4ba17aa17c6..ce43154116b 100644--- a/apps/server/src/cli/service.ts+++ b/apps/server/src/cli/service.ts@@ -92,6 +92,13 @@ export const reconcileService = Effect.fn("cli.service.reconcile")(function* (opconst { baseDir } = yield* ServerConfig.ServerConfig;const service = yield* BootService.BootService;const status = yield* service.status;+ // Before the downgrade check, which reads this home's state, not the service's.+ if (status.otherBaseDir !== undefined) {+ return yield* new BootService.BootServiceOtherBaseDirError({+ installedBaseDir: status.otherBaseDir,+ baseDir,+ });+ }if (status.installed && status.current) {return { changed: false, status } satisfies ServiceReconcileResult;}@@ -152,6 +159,14 @@ function formatServiceStatus(if (!status.installed) {return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";}+ if (status.otherBaseDir !== undefined) {+ return [+ "T3 Code service",+ " Status: installed for another T3 home",+ ` Base dir: ${status.otherBaseDir}`,+ ` Next: Pass \`${BootService.formatBootServiceBaseDirOption(status.otherBaseDir)}\` to manage it.`,+ ].join("\n");+ }const installedVersion = status.installedVersion ?? cliVersion;const problems = (status.problems ?? []).map((problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem)}`,@@ -264,7 +279,9 @@ const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe? `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.",+ : status.otherBaseDir !== undefined+ ? `The T3 Code service serves ${status.otherBaseDir}, so it was not restarted. Pass \`${BootService.formatBootServiceBaseDirOption(status.otherBaseDir)}\` to restart it.`+ : "T3 Code service is not installed.",);}),),@@ -290,7 +307,7 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).path.resolve(installedBaseDir) !== path.resolve(baseDir)) {yield* Console.log(- "The installed service runs another T3 home, so it was not removed. Pass its --base-dir.",+ `The T3 Code service serves ${installedBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(installedBaseDir)}\` to remove it.`,);return;}diff --git a/apps/server/src/cli/up.connect.test.ts b/apps/server/src/cli/up.connect.test.tsindex 09917097308..d7cfe68a6ce 100644--- a/apps/server/src/cli/up.connect.test.ts+++ b/apps/server/src/cli/up.connect.test.ts@@ -126,5 +126,55 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe("T3CODE_LAN=false\n");}),);++ it.effect("--connect signs in to nothing for another home's service", () =>+ Effect.gen(function* () {+ events.length = 0;+ link.desired = false;+ link.mode = "managed";+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-up-connect-test-" });+ vi.spyOn(BootService, "layer").mockReturnValue(+ Layer.succeed(+ BootService.BootService,+ BootService.BootService.of({+ status: Effect.succeed({+ supported: true,+ installed: true,+ current: false,+ otherBaseDir: "/srv/t3",+ unitPath: "/home/me/.config/systemd/user/t3code.service",+ logPath: "/home/me/.t3/userdata/logs/boot-service.log",+ }),+ withStopped: (operation) => operation,+ restart: Effect.sync(() => events.push("restart")).pipe(+ Effect.as("skipped" as const),+ ),+ install: () => Effect.die("another home's service is not reinstalled"),+ uninstall: Effect.succeed(false),+ }),+ ),+ );++ const error = yield* Command.runWith(upCommand, { version: packageJson.version })([+ "--base-dir",+ baseDir,+ "--connect",+ ]).pipe(+ Effect.provideService(HostProcess.Environment, {}),+ Effect.provide(+ Layer.mergeAll(+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),+ Layer.fresh(TestConsole.layer),+ ),+ ),+ Effect.flip,+ );++ expect(error).toMatchObject({ _tag: "BootServiceOtherBaseDirError" });+ expect(events).toEqual([]);+ expect(link).toEqual({ desired: false, mode: "managed" });+ }),+ );},);diff --git a/apps/server/src/cli/up.test.ts b/apps/server/src/cli/up.test.tsindex fb1e88fc61e..659edc2e3fd 100644--- a/apps/server/src/cli/up.test.ts+++ b/apps/server/src/cli/up.test.ts@@ -18,7 +18,7 @@ import { afterEach, vi } from "vite-plus/test";import packageJson from "../../package.json" with { type: "json" };import * as BootService from "../cloud/bootService.ts";import { upsertServiceEnv } from "./service.ts";-import { connectEnabled, planRoutes, upCommand } from "./up.ts";+import { connectEnabled, planRoutes, statusCommand, upCommand } from "./up.ts";const none = Option.none<boolean>();@@ -162,6 +162,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))readonly status?: Partial<BootService.BootServiceStatus>;readonly installFails?: boolean;readonly restartFails?: boolean;+ readonly fails?: boolean;+ readonly reportStatus?: boolean;/** Runs as if in a terminal, answering each question with this text. */readonly answer?: string;readonly prints?: string;@@ -252,6 +254,29 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))restarts: 0,envAfter: "T3CODE_LAN=false\n",},+ {+ label: "a service for another home is refused without a restart",+ installed: true,+ status: { current: false, otherBaseDir: "/srv/t3 home" },+ fails: true,+ answer: "y",+ env: "T3CODE_LAN=false\n",+ args: ["--lan"],+ installs: 0,+ restarts: 0,+ envAfter: "T3CODE_LAN=false\n",+ },+ {+ label: "another home's service supplies no local network default",+ installed: true,+ status: { current: false, otherBaseDir: "/srv/t3 home" },+ reportStatus: true,+ env: "",+ args: ["--json"],+ installs: 0,+ restarts: 0,+ envAfter: "",+ },{label: "no service manager still records the choice",installed: false,@@ -271,7 +296,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))restarts: 0,envAfter: "T3CODE_LAN=true\n",},- ])("restarts the service only when it must: $label", (input) =>+ ])("keeps service changes and access settings consistent: $label", (input) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-up-test-" });@@ -298,30 +323,36 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))),),install: () =>- input.installFails === true+ status.otherBaseDir !== undefined? Effect.fail(- new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" }),- )- : Effect.sync(() => {- installs++;- return {- program: ["t3"],+ new BootService.BootServiceOtherBaseDirError({+ installedBaseDir: status.otherBaseDir,baseDir,- unitPath: status.unitPath,- logPath: status.logPath,- };- }),+ }),+ )+ : input.installFails === true+ ? Effect.fail(+ new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" }),+ )+ : Effect.sync(() => {+ installs++;+ return {+ program: ["t3"],+ baseDir,+ unitPath: status.unitPath,+ logPath: status.logPath,+ };+ }),uninstall: Effect.succeed(false),}),),);if (input.answer !== undefined) yield* asTerminal;- const { exit, lines } = yield* Command.runWith(upCommand, { version: packageJson.version })([- "--base-dir",- baseDir,- ...input.args,- ]).pipe(+ const run = input.reportStatus+ ? Command.runWith(statusCommand, { version: packageJson.version })+ : Command.runWith(upCommand, { version: packageJson.version });+ const { exit, lines } = yield* run(["--base-dir", baseDir, ...input.args]).pipe(Effect.provideService(HostProcess.Environment, {}),input.answer === undefined? (effect) => effect@@ -340,7 +371,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))if (input.prints !== undefined) {expect(lines.join("\n")).toContain(input.prints.replace("<baseDir>", baseDir));}- expect(exit._tag).toBe(input.restartFails === true ? "Failure" : "Success");+ if (input.reportStatus) {+ expect(JSON.parse(lines.join("\n"))).toMatchObject({+ service: { otherBaseDir: "/srv/t3 home" },+ lan: { enabled: false, inheritedDefault: false },+ });+ }+ expect(exit._tag).toBe(+ input.restartFails === true || input.fails === true ? "Failure" : "Success",+ );expect({ installs, restarts }).toEqual({installs: input.installs,restarts: input.restarts,diff --git a/apps/server/src/cli/up.ts b/apps/server/src/cli/up.tsindex 318a2849a6d..9bd0409f6ef 100644--- a/apps/server/src/cli/up.ts+++ b/apps/server/src/cli/up.ts@@ -79,12 +79,14 @@ const readSetup = Effect.fn("cli.up.read_setup")(function* () {revoked: connectRevoked,}): null;+ // Another home's service doesn't read this home's service.env.+ const servesThisHome = service.installed && service.otherBaseDir === undefined;return {service,connect,connectRevoked,- lan: Option.getOrElse(lan, () => service.installed),- lanFromOldDefault: Option.isNone(lan) && service.installed,+ lan: Option.getOrElse(lan, () => servesThisHome),+ lanFromOldDefault: Option.isNone(lan) && servesThisHome,host: entries.T3CODE_HOST,} satisfies Setup;});@@ -125,6 +127,14 @@ const CHOICES = {const formatSetup = (setup: Setup) => {const { service } = setup;+ // This home's access settings reach no service, so only the service is shown.+ if (service.otherBaseDir !== undefined) {+ return [+ ` ${"Service".padEnd(15)}installed for another T3 home · ${service.otherBaseDir}`,+ "",+ `Pass \`${BootService.formatBootServiceBaseDirOption(service.otherBaseDir)}\` to manage it.`,+ ].join("\n");+ }const rows: ReadonlyArray<readonly [string, string]> = [["Service",@@ -203,6 +213,13 @@ const setUp = Effect.fn("cli.up")(function* (flags: {});const { command: pairCommand } = yield* resolveHostCliCommand("pair", baseDirArgs);const before = yield* readSetup();+ // Before any question or write: install would refuse only after both.+ if (before.service.otherBaseDir !== undefined) {+ return yield* new BootService.BootServiceOtherBaseDirError({+ installedBaseDir: before.service.otherBaseDir,+ baseDir,+ });+ }if (before.connect === null && Option.getOrElse(flags.connect, () => false)) {return yield* new CliError.UserError({cause: "connect",@@ -400,7 +417,7 @@ const setUp = Effect.fn("cli.up")(function* (flags: {}if (outcome === "skipped") {yield* Console.log(- "The installed service runs another T3 home, so it was not restarted. Pass its --base-dir.",+ "The installed service was not restarted. Run `t3 service status` to see why.",);}started = outcome === "restarted";@@ -480,6 +497,7 @@ const setupJson = (setup: Setup) =>supported: setup.service.supported,installed: setup.service.installed,installedVersion: setup.service.installedVersion ?? null,+ otherBaseDir: setup.service.otherBaseDir ?? null,},connect:setup.connect === null ? null : { enabled: setup.connect, revoked: setup.connectRevoked },@@ -521,7 +539,9 @@ export const statusCommand = Command.make("status", {yield* Console.log(flags.json? setupJson(setup)- : `This machine\n${formatSetup(setup)}\n\nChange access: \`t3 up\`.`,+ : setup.service.otherBaseDir !== undefined+ ? `This machine\n${formatSetup(setup)}`+ : `This machine\n${formatSetup(setup)}\n\nChange access: \`t3 up\`.`,);}),),diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.tsindex 6809e764550..814d470cad4 100644--- a/apps/server/src/cloud/bootService.test.ts+++ b/apps/server/src/cloud/bootService.test.ts@@ -7,6 +7,7 @@ import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Path from "effect/Path";+import { CliError } from "effect/cli";import { HttpClient } from "effect/http";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";@@ -679,17 +680,24 @@ it.layer(NodeServices.layer)("boot service install", (it) => {}),);- it.effect("restart leaves a service that serves another T3 home alone", () =>+ it.effect("restart and install leave a service that serves another T3 home alone", () =>Effect.gen(function* () {- const { service, fs, commands, makeService } = yield* makeHarness();- yield* service.install();- commands.length = 0;+ const { service, fs, baseDir, commands, makeService } = yield* makeHarness();+ const plan = yield* service.install();+ const unit = yield* fs.readFileString(plan.unitPath);const path = yield* Path.Path;const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));+ commands.length = 0;expect(yield* other.restart).toBe("skipped");- expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);+ const refused = yield* other.install().pipe(Effect.flip);+ expect(refused._tag).toBe("BootServiceOtherBaseDirError");+ // The CLI prints a user message without a stack trace.+ expect(CliError.getUserMessage(refused)).toBe(refused.message);+ expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);+ expect(commands).toEqual([]);+ expect((yield* other.status).otherBaseDir).toBe(baseDir);}),);diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.tsindex 1e0537707da..88d477974ae 100644--- a/apps/server/src/cloud/bootService.ts+++ b/apps/server/src/cloud/bootService.ts@@ -9,6 +9,7 @@ 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 { CliError } from "effect/cli";import { HttpClient } from "effect/http";import * as Schema from "effect/Schema";@@ -514,8 +515,29 @@ export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootSer}}+export const formatBootServiceBaseDirOption = (baseDir: string) =>+ `--base-dir '${baseDir.replaceAll("'", `'"'"'`)}'`;++export class BootServiceOtherBaseDirError extends Schema.TaggedError<BootServiceOtherBaseDirError>()(+ "BootServiceOtherBaseDirError",+ {+ installedBaseDir: Schema.String,+ baseDir: Schema.String,+ },+) {+ override get message(): string {+ return `The T3 Code service on this machine serves ${this.installedBaseDir}, not ${this.baseDir}. Pass ${formatBootServiceBaseDirOption(this.installedBaseDir)} to manage it, or run \`t3 service uninstall ${formatBootServiceBaseDirOption(this.installedBaseDir)}\` first to move it; both data directories are kept.`;+ }++ // A refusal the user fixes by rerunning, so the CLI prints the message, not a stack trace.+ override get [CliError.userMessage]() {+ return this.message;+ }+}+export type BootServiceError =| BootServiceUnsupportedError+ | BootServiceOtherBaseDirError| BootServiceCommandError| BootServiceInstallError| BootServicePrerequisiteError@@ -528,6 +550,8 @@ export interface BootServiceStatus {readonly current: boolean;readonly installedVersion?: string;readonly installedBaseDir?: string;+ /** Set when the installed unit serves a different T3 home than this CLI. */+ readonly otherBaseDir?: string;readonly problems?: ReadonlyArray<BootServiceProblem>;readonly unitPath: string;readonly logPath: string;@@ -631,6 +655,13 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);+ const otherBaseDirOf = (unit: string) => {+ const installedBaseDir = bootServiceBaseDirOf(unit);+ return installedBaseDir !== undefined &&+ path.resolve(installedBaseDir) !== path.resolve(input.baseDir)+ ? installedBaseDir+ : undefined;+ };const writeDurably = (filePath: string, contents: string) =>Effect.scoped(Effect.gen(function* () {@@ -773,6 +804,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {readonly start?: boolean;}) {const manager = yield* requireManager;+ // The unit is per user. Rewriting one that serves another home moves the+ // service onto this home's data, which looks like every thread vanished.+ const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option);+ const installedBaseDir = Option.isSome(existingUnit)+ ? otherBaseDirOf(existingUnit.value)+ : undefined;+ if (installedBaseDir !== undefined) {+ return yield* new BootServiceOtherBaseDirError({ installedBaseDir, baseDir: input.baseDir });+ }yield* fs.makeDirectory(input.logsDir, { recursive: true }).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));@@ -1040,6 +1080,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {? serviceStateActiveVersion(stateText.value): undefined;const installedBaseDir = bootServiceBaseDirOf(unit);+ const otherBaseDir = otherBaseDirOf(unit);const normalizeUnit = (contents: string) =>detectedManager.kind === "launchd"? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")@@ -1052,6 +1093,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {installed: true,...(installedVersion === undefined ? {} : { installedVersion }),...(installedBaseDir === undefined ? {} : { installedBaseDir }),+ ...(otherBaseDir === undefined ? {} : { otherBaseDir }),problems,current:problems.length === 0 &&