From 4eda2b942014f684170050d7f3774f68d99e0e07 Mon Sep 17 00:00:00 2001 From: yuez Date: Thu, 29 Oct 2026 14:00:41 +0800 Subject: [PATCH] feat(cli): add `pi2 service status|start|stop|enable|disable` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `install-service` only renders the unit file; nothing in the CLI talked to systemd/launchd. The editor plugin had no supported way to start a service-managed daemon (it would have had to shell out to `systemctl` itself), so add the explicit control surface ADR 0002 §2.2 assumes: pi2 service status [--json] manager, unit path, installed/enabled/active, linger pi2 service start|stop systemctl --user start|stop / launchctl kickstart|kill pi2 service enable|disable systemctl --user enable|disable --now / launchctl bootstrap|bootout `status` never fails: no manager, no unit and a dead service are reports, and `--json` carries the same shape the plugin decodes. The four mutating actions exit 1 with the manager's first stderr line, and refuse to run when the unit file is missing. Every probe is injectable (exec/exists/platform/paths/uid/user) so the tests never touch a real service manager. --- src/cli/pi2.ts | 45 ++++ src/cli/service-control.ts | 378 +++++++++++++++++++++++++++++++ test/cli/service-control.test.ts | 346 ++++++++++++++++++++++++++++ 3 files changed, 769 insertions(+) create mode 100644 src/cli/service-control.ts create mode 100644 test/cli/service-control.test.ts diff --git a/src/cli/pi2.ts b/src/cli/pi2.ts index 9d09176..f195ab7 100644 --- a/src/cli/pi2.ts +++ b/src/cli/pi2.ts @@ -10,6 +10,7 @@ * pi2 pairing create a pairing code for another device * pi2 install-service render/install a systemd user unit or LaunchAgent * pi2 uninstall-service remove it again + * pi2 service … status/start/stop/enable/disable that unit * * Everything is discovered from the runtime dir: `daemon.json` carries the * bound port, `cli.token` the local admin token (see docs/deployment.md). @@ -48,10 +49,27 @@ import { import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js"; import { runStop, STOP_USAGE, type StopOptions } from "./stop.js"; import { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js"; +import { + parseServiceArgs, + runServiceCommand, + SERVICE_USAGE, + type ExecResult as ServiceExecResult, + type ServiceAction, +} from "./service-control.js"; export { CliError } from "./util.js"; export { runStop, STOP_USAGE, type StopOptions } from "./stop.js"; export { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js"; +export { + SERVICE_ACTIONS, + SERVICE_USAGE, + parseServiceArgs, + runServiceCommand, + serviceArgv, + serviceStatus, + type ServiceStatus, + type ServiceAction, +} from "./service-control.js"; export const USAGE = `pi2 — pi2 client @@ -67,6 +85,7 @@ Usage: pi2 pairing [--base ] create a pairing code (URL + code + QR) pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent pi2 uninstall-service [--dry-run|--write] remove the unit + pi2 service status|start|stop|enable|disable control that unit (status [--json]) pi2 --version | --help \`pi2 stop\` / \`pi2 daemon stop\` flags: -f, --force sends SIGKILL if the daemon @@ -699,6 +718,12 @@ export interface Pi2Options { isPidAlive?: (pid: number) => boolean; kill?: (pid: number, signal: NodeJS.Signals) => void; sleep?: (ms: number) => Promise; + /** Injected service manager runner (defaults to `spawnSync`). */ + serviceExec?: (argv: string[]) => ServiceExecResult; + /** Injected unit-file existence probe (defaults to `fs.existsSync`). */ + serviceExists?: (path: string) => boolean; + serviceUid?: number; + serviceUser?: string; } export async function main(argv: readonly string[], options: Pi2Options = {}): Promise { @@ -845,6 +870,26 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P }; return command === "install-service" ? runInstallService(serviceOptions) : runUninstallService(serviceOptions); } + case "service": { + const parsed = parseServiceArgs(rest); + if (parsed.help) { + out(SERVICE_USAGE); + return 0; + } + const platform = options.platform ?? (osPlatform() === "darwin" ? "darwin" : "linux"); + const paths = options.servicePaths ?? defaultServicePaths(); + return await runServiceCommand(parsed.action as ServiceAction, { + platform, + paths, + print: out, + json: parsed.json, + ...(options.env === undefined ? {} : { env: options.env }), + ...(options.serviceExec === undefined ? {} : { exec: options.serviceExec }), + ...(options.serviceExists === undefined ? {} : { exists: options.serviceExists }), + ...(options.serviceUid === undefined ? {} : { uid: options.serviceUid }), + ...(options.serviceUser === undefined ? {} : { user: options.serviceUser }), + }); + } default: err(`pi2: unknown command "${command}"`); err(USAGE); diff --git a/src/cli/service-control.ts b/src/cli/service-control.ts new file mode 100644 index 0000000..ea0b9e8 --- /dev/null +++ b/src/cli/service-control.ts @@ -0,0 +1,378 @@ +/** + * `pi2 service status|start|stop|enable|disable` — user-service control. + * + * `pi2 install-service --write` renders the unit file and stops there + * (`src/cli/service.ts` is pure string generation). This module is the explicit + * counterpart: it talks to systemd / launchd, but only when the user asks for it + * (ADR 0002 §2.2). The Neovim plugin never shells out to a service manager + * itself — it calls `pi2 service …`, so the platform knowledge stays here. + * + * Two properties the callers depend on: + * 1. `status` never fails: no manager, no unit and a dead service are all + * reports, not errors (`--json` is the machine-readable form). + * 2. `start|stop|enable|disable` are the only paths that mutate state, and a + * manager refusal becomes a `CliError` with the manager's own first line. + * + * Everything is injected (`exec`, `exists`, `platform`, `paths`, `uid`, `user`, + * `env`) so the tests stay hermetic: nothing here runs a real systemctl. + */ +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { userInfo } from "node:os"; +import { join } from "node:path"; +import { + defaultServicePaths, + LAUNCHD_LABEL, + LAUNCHD_PLIST_NAME, + launchAgentDir, + SYSTEMD_UNIT_NAME, + systemdUserDir, + type ServicePaths, + type ServicePlatform, +} from "./service.js"; +import { CliError, parseArgs, type FlagValue, UsageError } from "./util.js"; + +export type ServiceAction = "status" | "start" | "stop" | "enable" | "disable"; + +/** Every action the dispatcher accepts, in help order. */ +export const SERVICE_ACTIONS: readonly ServiceAction[] = ["status", "start", "stop", "enable", "disable"]; + +export const SERVICE_USAGE = `pi2 service — control the user service that runs the daemon + +Usage: + pi2 service status [--json] report the unit, enablement, activity and linger + pi2 service start start the installed unit + pi2 service stop stop it (disable the unit to keep it down) + pi2 service enable enable it (systemd: --now; launchd: bootstrap+enable) + pi2 service disable disable it (systemd: --now; launchd: bootout) + +The unit is the one \`pi2 install-service --write\` renders +(\`pi2.service\` on Linux, \`com.pi2.daemon.plist\` on macOS). +\`--json\` is only valid for \`service status\`.`; + +export interface ExecResult { + code: number; + stdout: string; + stderr: string; +} + +/** One `systemctl`/`launchctl` invocation, injectable in tests. */ +export type ServiceExec = (argv: string[]) => ExecResult; + +export interface ServiceStatus { + platform: ServicePlatform; + manager: "systemd" | "launchd" | "none"; + unit: { name: string; path: string; installed: boolean }; + enabled: boolean | null; + active: boolean | null; + linger: boolean | null; + error: string | null; +} + +export interface ServiceContext { + platform: ServicePlatform; + paths: ServicePaths; + uid: number; + user: string; + env: Record; +} + +export interface ServiceControlOptions { + platform?: ServicePlatform; + paths?: ServicePaths; + exec?: ServiceExec; + exists?: (path: string) => boolean; + uid?: number; + user?: string; + env?: Record; + print?: (line: string) => void; + json?: boolean; +} + +/** `spawnSync` wrapper: a missing binary is `code 127`, never a throw. */ +export function defaultServiceExec(argv: string[]): ExecResult { + const [command, ...args] = argv; + if (command === undefined) { + return { code: 127, stdout: "", stderr: "empty command" }; + } + const result = spawnSync(command, args, { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }); + if (result.error !== undefined) { + return { code: 127, stdout: "", stderr: result.error.message }; + } + return { + code: result.status ?? (result.signal === null ? 1 : 1), + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; +} + +/** Resolve the platform-specific bits once, honouring every injection point. */ +export function serviceContext(options: ServiceControlOptions = {}): ServiceContext { + const platform = + options.platform ?? ((process.platform === "darwin" ? "darwin" : "linux") as ServicePlatform); + const paths = options.paths ?? defaultServicePaths(); + const uid = options.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0); + const user = options.user ?? (process.env.USER ?? process.env.LOGNAME ?? safeUserInfo()); + const env = options.env ?? process.env; + return { platform, paths, uid, user, env }; +} + +function safeUserInfo(): string { + try { + return userInfo().username; + } catch { + return "user"; + } +} + +/** Unit name + absolute path for the platform (the file `install-service` writes). */ +export function serviceUnit(ctx: ServiceContext): { name: string; path: string } { + if (ctx.platform === "darwin") { + return { name: LAUNCHD_PLIST_NAME, path: join(launchAgentDir(ctx.paths), LAUNCHD_PLIST_NAME) }; + } + return { name: SYSTEMD_UNIT_NAME, path: join(systemdUserDir(ctx.paths), SYSTEMD_UNIT_NAME) }; +} + +/** `gui//com.pi2.daemon` — the launchd job target. */ +function launchdTarget(ctx: ServiceContext): string { + return `gui/${ctx.uid}/${LAUNCHD_LABEL}`; +} + +/** + * The commands one action runs, in order. Pure: no process is started here, so + * the tests assert argv directly. `status` is a probe set, not a command list, + * and therefore returns `[]`. + */ +export function serviceArgv(action: ServiceAction, ctx: ServiceContext): string[][] { + if (action === "status") { + return []; + } + const unit = serviceUnit(ctx); + if (ctx.platform === "darwin") { + switch (action) { + case "start": + return [["launchctl", "kickstart", "-k", launchdTarget(ctx)]]; + case "stop": + return [["launchctl", "kill", "TERM", launchdTarget(ctx)]]; + case "enable": + // `bootstrap` registers a plist that is not loaded yet; the + // second call makes sure the job is also enabled at login. + return [ + ["launchctl", "bootstrap", `gui/${ctx.uid}`, unit.path], + ["launchctl", "enable", launchdTarget(ctx)], + ]; + case "disable": + return [["launchctl", "bootout", `gui/${ctx.uid}`]]; + } + } + switch (action) { + case "start": + return [["systemctl", "--user", "start", unit.name]]; + case "stop": + return [["systemctl", "--user", "stop", unit.name]]; + case "enable": + return [["systemctl", "--user", "enable", "--now", unit.name]]; + case "disable": + return [["systemctl", "--user", "disable", "--now", unit.name]]; + } +} + +/** First non-empty line of stderr, else stdout, else a generic message. */ +function firstLine(...texts: string[]): string { + for (const text of texts) { + const line = text + .split("\n") + .map((entry) => entry.trim()) + .find((entry) => entry !== ""); + if (line !== undefined) { + return line; + } + } + return ""; +} + +function shellLine(argv: string[]): string { + return argv.join(" "); +} + +/** `Linger=yes` → true, `Linger=no` → false, anything else → null. */ +function parseLinger(result: ExecResult): boolean | null { + if (result.code !== 0) { + return null; + } + const match = /^Linger=(yes|no)$/m.exec(result.stdout); + if (match === null) { + return null; + } + return match[1] === "yes"; +} + +/** + * Probe the unit without mutating anything. Never throws: an unavailable + * service manager yields `manager: "none"`, `null` flags and a one-line error. + */ +export function serviceStatus(options: ServiceControlOptions = {}): ServiceStatus { + const ctx = serviceContext(options); + const exec = options.exec ?? defaultServiceExec; + const exists = options.exists ?? existsSync; + const unit = serviceUnit(ctx); + const installed = exists(unit.path); + + if (ctx.platform === "darwin") { + const probe = exec(["launchctl", "print", launchdTarget(ctx)]); + const managerMissing = probe.code === 127; + return { + platform: "darwin", + manager: managerMissing ? "none" : "launchd", + unit: { ...unit, installed }, + enabled: managerMissing ? null : installed, + active: managerMissing ? null : probe.code === 0, + linger: null, + error: managerMissing ? firstLine(probe.stderr) || "launchctl not found on PATH" : null, + }; + } + + const available = exec(["systemctl", "--version"]); + if (available.code !== 0) { + return { + platform: "linux", + manager: "none", + unit: { ...unit, installed }, + enabled: null, + active: null, + linger: null, + error: firstLine(available.stderr) || "systemctl not found on PATH", + }; + } + + const enabledProbe = exec(["systemctl", "--user", "is-enabled", unit.name]); + const activeProbe = exec(["systemctl", "--user", "is-active", unit.name]); + const lingerProbe = exec(["loginctl", "show-user", ctx.user, "-p", "Linger"]); + return { + platform: "linux", + manager: "systemd", + unit: { ...unit, installed }, + // is-enabled exits 0 for enabled, non-zero for disabled/static/masked; + // a 127 here would mean systemd vanished between the two calls. + enabled: enabledProbe.code === 127 ? null : enabledProbe.code === 0, + active: activeProbe.code === 127 ? null : activeProbe.code === 0, + linger: parseLinger(lingerProbe), + error: null, + }; +} + +/** Human-readable `service status` report, one fact per line. */ +export function formatServiceStatus(status: ServiceStatus): string[] { + const lines: string[] = []; + const manager = status.manager === "none" ? "none (no service manager available)" : status.manager; + lines.push(`manager ${manager}`); + lines.push(`unit ${status.unit.path}${status.unit.installed ? "" : " (missing)"}`); + const flag = (value: boolean | null): string => (value === null ? "unknown" : value ? "yes" : "no"); + lines.push(`installed ${status.unit.installed ? "yes" : "no"}`); + lines.push(`enabled ${flag(status.enabled)}`); + lines.push(`active ${flag(status.active)}`); + if (status.platform === "linux") { + lines.push(`linger ${flag(status.linger)}`); + } + if (status.error !== null) { + lines.push(`error ${status.error}`); + } + if (!status.unit.installed) { + lines.push("# next: pi2 install-service --write, then pi2 service enable"); + } else if (status.enabled !== true || status.active !== true) { + lines.push("# next: pi2 service enable"); + } + return lines; +} + +/** Machine-readable `service status --json` body. */ +export function formatServiceStatusJson(status: ServiceStatus): string { + return JSON.stringify(status, null, 2); +} + +/** + * Run one action. + * + * `status` prints a report and returns 0 whatever the state of the world. + * The four mutating actions return 0 on success and throw a `CliError` when a + * manager command fails (with that manager's first stderr line). + */ +export async function runServiceCommand( + action: ServiceAction, + options: ServiceControlOptions = {}, +): Promise { + const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`)); + const ctx = serviceContext(options); + + if (action === "status") { + const status = serviceStatus(options); + if (options.json === true) { + print(formatServiceStatusJson(status)); + } else { + for (const line of formatServiceStatus(status)) { + print(line); + } + } + return 0; + } + + const unit = serviceUnit(ctx); + const exists = options.exists ?? existsSync; + if (!exists(unit.path)) { + throw new CliError( + `no service unit at ${unit.path} — run \`pi2 install-service --write\` first`, + ); + } + + const exec = options.exec ?? defaultServiceExec; + const argvList = serviceArgv(action, ctx); + for (const argv of argvList) { + const result = exec(argv); + if (result.code !== 0) { + const detail = firstLine(result.stderr, result.stdout); + throw new CliError( + detail !== "" + ? `${shellLine(argv)} failed: ${detail}` + : `${shellLine(argv)} failed (exit ${result.code})`, + ); + } + } + + print(`service ${action}: ${argvList.map(shellLine).join(" && ")}`); + if (action === "stop") { + print("# the unit is still enabled; run `pi2 service disable` to keep it down"); + } + return 0; +} + +// --------------------------------------------------------------------------- +// dispatcher glue +// --------------------------------------------------------------------------- + +/** Parse `pi2 service …` argv into an action + flags. Throws `UsageError`. */ +export function parseServiceArgs(argv: readonly string[]): { action: ServiceAction; json: boolean; help: boolean } { + const parsed = parseArgs(argv, { + booleans: ["--json", "--help"], + aliases: { "-h": "--help" }, + }); + const flags: Record = parsed.flags; + const help = flags["--help"] === true; + const json = flags["--json"] === true; + if (help) { + return { action: "status", json, help }; + } + const raw = parsed.positionals[0] ?? "status"; + if (!SERVICE_ACTIONS.includes(raw as ServiceAction)) { + throw new UsageError(`unknown service action "${raw}"`, SERVICE_USAGE); + } + if (parsed.positionals.length > 1) { + throw new UsageError(`unexpected argument "${parsed.positionals[1]}"`, SERVICE_USAGE); + } + if (json && raw !== "status") { + throw new UsageError("--json is only valid for `pi2 service status`", SERVICE_USAGE); + } + return { action: raw as ServiceAction, json, help }; +} diff --git a/test/cli/service-control.test.ts b/test/cli/service-control.test.ts new file mode 100644 index 0000000..e982bb6 --- /dev/null +++ b/test/cli/service-control.test.ts @@ -0,0 +1,346 @@ +import { describe, expect, it } from "vitest"; +import { join } from "node:path"; +import { + formatServiceStatus, + parseServiceArgs, + runServiceCommand, + serviceArgv, + serviceContext, + serviceStatus, + serviceUnit, + type ExecResult, + type ServiceControlOptions, +} from "../../src/cli/service-control.js"; +import { LAUNCHD_LABEL, SYSTEMD_UNIT_NAME, type ServicePaths } from "../../src/cli/service.js"; +import { main } from "../../src/cli/pi2.js"; +import { CliError, UsageError } from "../../src/cli/util.js"; + +const paths: ServicePaths = { + bundled: true, + execPath: "/usr/local/bin/pi2", + envFile: "-%h/.config/pi2/env", + stateDir: "/home/u/.local/state/pi2", + homeDir: "/home/u", + pathEnv: "/usr/local/bin:/usr/bin:/bin", +}; + +const linux = serviceContext({ platform: "linux", paths, uid: 1000, user: "u" }); +const darwin = serviceContext({ platform: "darwin", paths, uid: 501, user: "u" }); + +const OK: ExecResult = { code: 0, stdout: "", stderr: "" }; + +/** `exec` stub: a map from the exact argv (joined by spaces) to a result. */ +function execMap(map: Record): (argv: string[]) => ExecResult { + return (argv: string[]) => { + const key = argv.join(" "); + const hit = map[key]; + if (hit !== undefined) { + return hit; + } + throw new Error(`unexpected command: ${key}`); + }; +} + +describe("serviceArgv", () => { + it("maps every action on systemd", () => { + expect(serviceArgv("start", linux)).toEqual([["systemctl", "--user", "start", SYSTEMD_UNIT_NAME]]); + expect(serviceArgv("stop", linux)).toEqual([["systemctl", "--user", "stop", SYSTEMD_UNIT_NAME]]); + expect(serviceArgv("enable", linux)).toEqual([ + ["systemctl", "--user", "enable", "--now", SYSTEMD_UNIT_NAME], + ]); + expect(serviceArgv("disable", linux)).toEqual([ + ["systemctl", "--user", "disable", "--now", SYSTEMD_UNIT_NAME], + ]); + expect(serviceArgv("status", linux)).toEqual([]); + }); + + it("maps every action on launchd", () => { + const target = `gui/501/${LAUNCHD_LABEL}`; + const plist = join(paths.homeDir, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`); + expect(serviceArgv("start", darwin)).toEqual([["launchctl", "kickstart", "-k", target]]); + expect(serviceArgv("stop", darwin)).toEqual([["launchctl", "kill", "TERM", target]]); + expect(serviceArgv("enable", darwin)).toEqual([ + ["launchctl", "bootstrap", "gui/501", plist], + ["launchctl", "enable", target], + ]); + expect(serviceArgv("disable", darwin)).toEqual([["launchctl", "bootout", "gui/501"]]); + }); + + it("puts the unit under the platform config dir", () => { + expect(serviceUnit(linux)).toEqual({ + name: SYSTEMD_UNIT_NAME, + path: join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME), + }); + expect(serviceUnit(darwin).path).toBe( + join(paths.homeDir, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`), + ); + }); +}); + +describe("serviceStatus", () => { + const unitPath = join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME); + const base: ServiceControlOptions = { + platform: "linux", + paths, + uid: 1000, + user: "u", + exists: () => true, + }; + + it("reports an enabled, active unit with linger on", () => { + const status = serviceStatus({ + ...base, + exec: execMap({ + "systemctl --version": { code: 0, stdout: "systemd 255", stderr: "" }, + [`systemctl --user is-enabled ${SYSTEMD_UNIT_NAME}`]: { code: 0, stdout: "enabled", stderr: "" }, + [`systemctl --user is-active ${SYSTEMD_UNIT_NAME}`]: { code: 0, stdout: "active", stderr: "" }, + "loginctl show-user u -p Linger": { code: 0, stdout: "Linger=yes\n", stderr: "" }, + }), + }); + expect(status).toEqual({ + platform: "linux", + manager: "systemd", + unit: { name: SYSTEMD_UNIT_NAME, path: unitPath, installed: true }, + enabled: true, + active: true, + linger: true, + error: null, + }); + }); + + it("reports a disabled, inactive unit and keeps exit 0 semantics", async () => { + const status = serviceStatus({ + ...base, + exec: execMap({ + "systemctl --version": { code: 0, stdout: "systemd 255", stderr: "" }, + [`systemctl --user is-enabled ${SYSTEMD_UNIT_NAME}`]: { code: 1, stdout: "disabled", stderr: "" }, + [`systemctl --user is-active ${SYSTEMD_UNIT_NAME}`]: { code: 3, stdout: "inactive", stderr: "" }, + "loginctl show-user u -p Linger": { code: 0, stdout: "Linger=no\n", stderr: "" }, + }), + }); + expect(status.enabled).toBe(false); + expect(status.active).toBe(false); + expect(status.linger).toBe(false); + + const out: string[] = []; + const code = await runServiceCommand("status", { + ...base, + print: (line) => out.push(line), + json: true, + }); + expect(code).toBe(0); + const decoded = JSON.parse(out.join("\n")) as Record; + expect(decoded.manager).toBe("systemd"); + expect(decoded.unit).toMatchObject({ name: SYSTEMD_UNIT_NAME, path: unitPath }); + }); + + it("degrades to manager \"none\" when systemctl is unavailable", () => { + const status = serviceStatus({ + ...base, + exists: () => false, + exec: () => ({ code: 127, stdout: "", stderr: "spawnSync systemctl ENOENT" }), + }); + expect(status.manager).toBe("none"); + expect(status.enabled).toBeNull(); + expect(status.active).toBeNull(); + expect(status.linger).toBeNull(); + expect(status.error).toContain("ENOENT"); + expect(status.unit.installed).toBe(false); + }); + + it("probes launchd through `launchctl print`", () => { + const plist = join(paths.homeDir, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`); + const status = serviceStatus({ + platform: "darwin", + paths, + uid: 501, + exists: (path) => path === plist, + exec: execMap({ + [`launchctl print gui/501/${LAUNCHD_LABEL}`]: { code: 0, stdout: "state = running", stderr: "" }, + }), + }); + expect(status.manager).toBe("launchd"); + expect(status.unit.installed).toBe(true); + expect(status.enabled).toBe(true); + expect(status.active).toBe(true); + expect(status.linger).toBeNull(); + }); +}); + +describe("formatServiceStatus", () => { + it("suggests install then enable when the unit is missing", () => { + const lines = formatServiceStatus({ + platform: "linux", + manager: "systemd", + unit: { name: SYSTEMD_UNIT_NAME, path: "/home/u/.config/systemd/user/pi2.service", installed: false }, + enabled: null, + active: null, + linger: null, + error: null, + }); + expect(lines.join("\n")).toContain("pi2 install-service --write, then pi2 service enable"); + expect(lines.join("\n")).toContain("(missing)"); + }); + + it("suggests enable when the unit exists but is not running", () => { + const lines = formatServiceStatus({ + platform: "darwin", + manager: "launchd", + unit: { name: `${LAUNCHD_LABEL}.plist`, path: "/x.plist", installed: true }, + enabled: true, + active: false, + linger: null, + error: null, + }); + const text = lines.join("\n"); + expect(text).toContain("# next: pi2 service enable"); + expect(text).not.toContain("linger"); + }); +}); + +describe("runServiceCommand", () => { + const unitPath = join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME); + const out: string[] = []; + + it("refuses to start a service that was never installed", async () => { + await expect( + runServiceCommand("start", { + platform: "linux", + paths, + print: () => {}, + exists: () => false, + }), + ).rejects.toBeInstanceOf(CliError); + }); + + it("runs the mapped commands for `enable`", async () => { + const ran: string[][] = []; + const code = await runServiceCommand("enable", { + platform: "linux", + paths, + print: (line) => out.push(line), + exists: () => true, + exec: (argv) => { + ran.push(argv); + return OK; + }, + }); + expect(code).toBe(0); + expect(ran).toEqual([["systemctl", "--user", "enable", "--now", SYSTEMD_UNIT_NAME]]); + expect(out.join("\n")).toContain("service enable: systemctl --user enable --now pi2.service"); + }); + + it("turns a manager refusal into a CliError with its own first line", async () => { + const error = await runServiceCommand("start", { + platform: "linux", + paths, + print: () => {}, + exists: () => true, + exec: () => ({ + code: 1, + stdout: "", + stderr: "Failed to start pi2.service: Unit pi2.service not found.\nmore", + }), + }).catch((err: unknown) => err); + expect(error).toBeInstanceOf(CliError); + expect((error as CliError).message).toContain("Unit pi2.service not found."); + expect((error as CliError).message).toContain("systemctl --user start pi2.service"); + }); + + it("mentions the still-enabled unit after a stop", async () => { + const notes: string[] = []; + await runServiceCommand("stop", { + platform: "linux", + paths, + print: (line) => notes.push(line), + exists: () => true, + exec: () => OK, + }); + expect(notes.join("\n")).toContain("pi2 service disable"); + }); +}); + +describe("parseServiceArgs", () => { + it("defaults to status and accepts --json", () => { + expect(parseServiceArgs([])).toEqual({ action: "status", json: false, help: false }); + expect(parseServiceArgs(["--json"])).toEqual({ action: "status", json: true, help: false }); + expect(parseServiceArgs(["start"]).action).toBe("start"); + }); + + it("rejects unknown actions, extra positionals and --json on a mutating action", () => { + expect(() => parseServiceArgs(["frobnicate"])).toThrow(UsageError); + expect(() => parseServiceArgs(["start", "extra"])).toThrow(UsageError); + expect(() => parseServiceArgs(["start", "--json"])).toThrow(UsageError); + }); +}); + +describe("pi2 service (dispatch)", () => { + function collect(): { out: string[]; err: string[] } { + return { out: [], err: [] }; + } + + it("prints the JSON report and exits 0 with no unit installed", async () => { + const sink = collect(); + const unit = join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME); + const code = await main(["service", "status", "--json"], { + out: (line) => sink.out.push(line), + err: (line) => sink.err.push(line), + platform: "linux", + servicePaths: paths, + serviceUid: 1000, + serviceUser: "u", + serviceExists: () => false, + serviceExec: (argv) => { + const key = argv.join(" "); + if (key === "systemctl --version") { + return { code: 0, stdout: "systemd 255", stderr: "" }; + } + if (key.startsWith("systemctl --user is-enabled")) { + return { code: 1, stdout: "disabled", stderr: "" }; + } + if (key.startsWith("systemctl --user is-active")) { + return { code: 3, stdout: "inactive", stderr: "" }; + } + if (key.startsWith("loginctl show-user")) { + return { code: 0, stdout: "Linger=no", stderr: "" }; + } + throw new Error(`unexpected: ${key}`); + }, + }); + expect(code).toBe(0); + const decoded = JSON.parse(sink.out.join("\n")) as { unit: { path: string; installed: boolean } }; + expect(decoded.unit).toEqual({ name: SYSTEMD_UNIT_NAME, path: unit, installed: false }); + }); + + it("maps a failing start to exit code 1", async () => { + const sink = collect(); + const code = await main(["service", "start"], { + out: (line) => sink.out.push(line), + err: (line) => sink.err.push(line), + platform: "linux", + servicePaths: paths, + serviceExists: () => true, + serviceExec: () => ({ code: 1, stdout: "", stderr: "Job failed. See system logs." }), + }); + expect(code).toBe(1); + expect(sink.err.join("\n")).toContain("Job failed. See system logs."); + }); + + it("prints usage for an unknown action (exit 2)", async () => { + const sink = collect(); + const code = await main(["service", "wat"], { + out: (line) => sink.out.push(line), + err: (line) => sink.err.push(line), + platform: "linux", + servicePaths: paths, + }); + expect(code).toBe(2); + expect(sink.err.join("\n")).toContain("unknown service action"); + }); + + it("documents itself in `pi2 --help`", async () => { + const sink = collect(); + await main(["--help"], { out: (line) => sink.out.push(line), err: (line) => sink.err.push(line) }); + expect(sink.out.join("\n")).toContain("pi2 service status|start|stop|enable|disable"); + }); +});