feat: service-managed UI self-update (#1210)

* feat: add service-managed self-update

* chore: add temporary self-update test scripts

* chore: simplify temporary script markdown fences

* chore: run frontend in temporary self-update scripts

* fix: show self-update job progress after apply

* chore: add real npm self-update test script

* fix: isolate npm self-update prefix

* fix: detect npm service installs from bin shim

* chore: reset service before real npm update test

* chore: expand real npm status diagnostics

* fix: preserve service home during self-update

* fix(cli): tee self-update helper output to a log file

* fix(cli): avoid launchd bootstrap race when reloading the macOS service

* fix(backend): run macOS self-update helper once via transient launchd plist

* fix(web): show self-update progress and lock the apply button until the update lands

* fix(cli): reinstall via the kandev wrapper on Homebrew self-update

* chore: remove temp self-update test scripts

* fix(web): drop unused apply path from useUpdates hook

* fix(backend): snapshot install state once in apply preflight

* docs: align self-update docs with transient LaunchAgent flow

* chore(release): run cli bundle from apps workspace root

* fix(backend): guard against concurrent self-update applies

* fix(backend): check scheme and helper paths in self-update apply

* fix(backend): drop duplicate binary name from npx manual command

* fix(cli): allow --help for service self-update without --intent

* fix(cli): harden self-update dir perms and darwin uid resolution

* fix(web): set required POST fields last in applyUpdate

* docs: use JSON body notation for the apply endpoint

* fix(backend): expire self-update guard so a stuck helper cannot wedge apply

* refactor(cli): collapse redundant writeSync branch in self-update log
This commit is contained in:
José Almeida
2026-06-01 17:49:15 +01:00
committed by GitHub
parent 58dd2773a2
commit 041a19f060
44 changed files with 3630 additions and 136 deletions
+35
View File
@@ -0,0 +1,35 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
KANDEV_HOME_DIR,
resolveCacheDir,
resolveDataDir,
resolveDatabasePath,
resolveKandevHomeDir,
} from "./constants";
describe("runtime data paths", () => {
it("defaults to the user's kandev home", () => {
expect(resolveKandevHomeDir({})).toBe(KANDEV_HOME_DIR);
});
it("honors KANDEV_HOME_DIR for service-managed launches", () => {
const env = { KANDEV_HOME_DIR: "/srv/kandev-test" };
expect(resolveKandevHomeDir(env)).toBe("/srv/kandev-test");
expect(resolveCacheDir(env)).toBe(path.join("/srv/kandev-test", "bin"));
expect(resolveDataDir(env)).toBe(path.join("/srv/kandev-test", "data"));
expect(resolveDatabasePath(env)).toBe(path.join("/srv/kandev-test", "data", "kandev.db"));
});
it("lets an explicit KANDEV_DATABASE_PATH override the home-derived path", () => {
expect(
resolveDatabasePath({
KANDEV_HOME_DIR: "/srv/kandev-test",
KANDEV_DATABASE_PATH: "/tmp/custom.db",
}),
).toBe("/tmp/custom.db");
});
});
+16
View File
@@ -28,6 +28,22 @@ export const KANDEV_TASKS_DIR = path.join(KANDEV_HOME_DIR, "tasks");
export const CACHE_DIR = path.join(KANDEV_HOME_DIR, "bin");
export const DATA_DIR = path.join(KANDEV_HOME_DIR, "data");
export function resolveKandevHomeDir(env: NodeJS.ProcessEnv = process.env): string {
return env.KANDEV_HOME_DIR?.trim() || KANDEV_HOME_DIR;
}
export function resolveDataDir(env: NodeJS.ProcessEnv = process.env): string {
return path.join(resolveKandevHomeDir(env), "data");
}
export function resolveCacheDir(env: NodeJS.ProcessEnv = process.env): string {
return path.join(resolveKandevHomeDir(env), "bin");
}
export function resolveDatabasePath(env: NodeJS.ProcessEnv = process.env): string {
return env.KANDEV_DATABASE_PATH?.trim() || path.join(resolveDataDir(env), "kandev.db");
}
// Dev-mode root: an isolated kandev home inside the repo so that running
// `make dev` from inside a kandev-spawned task workspace does not touch the
// user's production state.
+3
View File
@@ -13,7 +13,10 @@ vi.mock("./constants", () => ({
get CACHE_DIR() {
return mockCacheDir.value;
},
resolveCacheDir: () => mockCacheDir.value,
DATA_DIR: "/tmp/kandev-test-data",
resolveDataDir: () => "/tmp/kandev-test-data",
resolveDatabasePath: () => "/tmp/kandev-test-data/kandev.db",
DEFAULT_BACKEND_PORT: 38429,
DEFAULT_WEB_PORT: 37429,
DEFAULT_AGENTCTL_PORT: 39429,
+17 -13
View File
@@ -4,12 +4,13 @@ import path from "node:path";
import { ensureExtracted, findBundleRoot, resolveWebServerPath } from "./bundle";
import {
CACHE_DIR,
DATA_DIR,
DEFAULT_AGENTCTL_PORT,
DEFAULT_BACKEND_PORT,
DEFAULT_WEB_PORT,
HEALTH_TIMEOUT_MS_RELEASE,
resolveCacheDir,
resolveDataDir,
resolveDatabasePath,
} from "./constants";
import { ensureAsset, getRelease } from "./github";
import { resolveHealthTimeoutMs, waitForHealth, waitForUrlReady } from "./health";
@@ -56,8 +57,9 @@ export function findCachedRelease(
platformDir: string,
version?: string,
): { cacheDir: string; tag: string } | null {
const rootCacheDir = resolveCacheDir();
if (version) {
const cacheDir = path.join(CACHE_DIR, version, platformDir);
const cacheDir = path.join(rootCacheDir, version, platformDir);
const bundleDir = path.join(cacheDir, "kandev");
const backendBin = path.join(bundleDir, "bin", getBinaryName("kandev"));
if (fs.existsSync(backendBin)) {
@@ -67,15 +69,15 @@ export function findCachedRelease(
}
// No version specified — scan for cached tags and pick the latest.
if (!fs.existsSync(CACHE_DIR)) return null;
if (!fs.existsSync(rootCacheDir)) return null;
const entries = fs.readdirSync(CACHE_DIR).filter((d) => d.startsWith("v"));
const entries = fs.readdirSync(rootCacheDir).filter((d) => d.startsWith("v"));
if (entries.length === 0) return null;
const sorted = sortVersionsDesc(entries);
for (const tag of sorted) {
const cacheDir = path.join(CACHE_DIR, tag, platformDir);
const cacheDir = path.join(rootCacheDir, tag, platformDir);
const bundleDir = path.join(cacheDir, "kandev");
const backendBin = path.join(bundleDir, "bin", getBinaryName("kandev"));
if (fs.existsSync(backendBin)) {
@@ -92,9 +94,10 @@ export function findCachedRelease(
* The previous version is kept as a fallback for offline use.
*/
export function cleanOldReleases(currentTag: string) {
const rootCacheDir = resolveCacheDir();
try {
if (!fs.existsSync(CACHE_DIR)) return;
const entries = fs.readdirSync(CACHE_DIR).filter((d) => d.startsWith("v"));
if (!fs.existsSync(rootCacheDir)) return;
const entries = fs.readdirSync(rootCacheDir).filter((d) => d.startsWith("v"));
if (entries.length <= 2) return;
const sorted = sortVersionsDesc(entries);
@@ -103,7 +106,7 @@ export function cleanOldReleases(currentTag: string) {
const keep = new Set<string>([currentTag, sorted[0], sorted[1]]);
for (const entry of entries) {
if (!keep.has(entry)) {
fs.rmSync(path.join(CACHE_DIR, entry), { recursive: true, force: true });
fs.rmSync(path.join(rootCacheDir, entry), { recursive: true, force: true });
}
}
} catch {
@@ -120,7 +123,7 @@ async function downloadRuntimeVersion(runtimeVersion: string): Promise<string> {
const release = await getRelease(runtimeVersion);
const tag = release.tag_name;
const assetName = `kandev-${platformDir}.tar.gz`;
const cacheDir = path.join(CACHE_DIR, tag, platformDir);
const cacheDir = path.join(resolveCacheDir(), tag, platformDir);
const archivePath = await ensureAsset(tag, assetName, cacheDir, (downloaded, total) => {
const percent = total ? Math.round((downloaded / total) * 100) : 0;
@@ -156,7 +159,7 @@ async function prepareBundleForLaunch({
} else {
try {
tag = await downloadRuntimeVersion(runtimeVersion);
const cacheDir = path.join(CACHE_DIR, tag, platformDir);
const cacheDir = path.join(resolveCacheDir(), tag, platformDir);
bundleDir = findBundleRoot(cacheDir);
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
@@ -186,8 +189,9 @@ async function prepareBundleForLaunch({
const logLevel =
process.env.KANDEV_LOG_LEVEL?.trim() || (debug ? "debug" : verbose ? "info" : "warn");
fs.mkdirSync(DATA_DIR, { recursive: true });
const dbPath = path.join(DATA_DIR, "kandev.db");
const dataDir = resolveDataDir();
fs.mkdirSync(dataDir, { recursive: true });
const dbPath = resolveDatabasePath();
const backendBin = path.join(bundleDir, "bin", getBinaryName("kandev"));
+24
View File
@@ -96,4 +96,28 @@ describe("parseServiceArgs", () => {
// happy path
expect(parseServiceArgs(["install", "--port=9000"]).port).toBe(9000);
});
it("parses hidden self-update helper flags", () => {
const args = parseServiceArgs(["self-update", "--intent", "/tmp/intent.json", "--dry-run"]);
expect(args.action).toBe("self-update");
expect(args.intent).toBe("/tmp/intent.json");
expect(args.dryRun).toBe(true);
});
it("requires --intent for self-update", () => {
expect(() => parseServiceArgs(["self-update"])).toThrow(/requires --intent/);
});
it("allows --help for self-update without --intent", () => {
const r = parseServiceArgs(["self-update", "--help"]);
expect(r.action).toBe("self-update");
expect(r.showHelp).toBe(true);
});
it("rejects self-update-only flags elsewhere", () => {
expect(() => parseServiceArgs(["install", "--intent=/tmp/intent.json"])).toThrow(
/--intent only applies/,
);
expect(() => parseServiceArgs(["install", "--dry-run"])).toThrow(/--dry-run only applies/);
});
});
+35 -1
View File
@@ -8,7 +8,8 @@ export type ServiceAction =
| "restart"
| "status"
| "logs"
| "config";
| "config"
| "self-update";
export type ServiceArgs = {
action: ServiceAction;
@@ -24,6 +25,10 @@ export type ServiceArgs = {
follow?: boolean;
/** Print help and exit. */
showHelp?: boolean;
/** Intent JSON path consumed by the hidden self-update helper. */
intent?: string;
/** Print the self-update command plan without mutating the install. */
dryRun?: boolean;
};
const VALID_ACTIONS = new Set<ServiceAction>([
@@ -35,6 +40,7 @@ const VALID_ACTIONS = new Set<ServiceAction>([
"status",
"logs",
"config",
"self-update",
]);
export function parseServiceArgs(argv: string[]): ServiceArgs {
@@ -66,6 +72,21 @@ export function parseServiceArgs(argv: string[]): ServiceArgs {
out.follow = true;
continue;
}
if (arg === "--dry-run") {
out.dryRun = true;
continue;
}
if (arg === "--intent") {
out.intent = takeValue(argv, i, "--intent");
i += 1;
continue;
}
if (arg.startsWith("--intent=")) {
const value = arg.slice("--intent=".length);
if (value.length === 0) throw new ParseError("--intent requires a value");
out.intent = value;
continue;
}
if (arg === "--port") {
out.port = parsePort(takeValue(argv, i, "--port"), "--port");
i += 1;
@@ -102,6 +123,19 @@ function validateActionFlags(args: ServiceArgs): void {
if (args.follow && args.action !== "logs") {
throw new ParseError(`--follow only applies to 'kandev service logs', not '${args.action}'`);
}
if (args.dryRun && args.action !== "self-update") {
throw new ParseError(
`--dry-run only applies to 'kandev service self-update', not '${args.action}'`,
);
}
if (args.intent && args.action !== "self-update") {
throw new ParseError(
`--intent only applies to 'kandev service self-update', not '${args.action}'`,
);
}
if (args.action === "self-update" && !args.showHelp && !args.intent) {
throw new ParseError("kandev service self-update requires --intent <path>");
}
const installOnly: Array<keyof ServiceArgs> = ["port", "homeDir", "noBootStart"];
if (args.action !== "install") {
for (const flag of installOnly) {
+7
View File
@@ -2,6 +2,7 @@ import { parseServiceArgs } from "./args";
import { printServiceConfig } from "./config";
import { runLinuxService } from "./linux";
import { runMacosService } from "./macos";
import { runSelfUpdateCommand } from "./self_update";
export function printServiceHelp(): void {
console.log(`kandev service — install kandev as an OS-managed service
@@ -49,6 +50,12 @@ export async function runServiceCommand(argv: string[]): Promise<void> {
printServiceConfig(args);
return;
}
// Hidden helper entrypoint used by the backend self-update endpoint. It is
// intentionally absent from help output.
if (args.action === "self-update") {
runSelfUpdateCommand(args);
return;
}
switch (process.platform) {
case "linux":
return runLinuxService(args);
+122
View File
@@ -0,0 +1,122 @@
import { describe, expect, it, vi } from "vitest";
import {
bootoutAndWait,
bootstrapWithRetry,
reloadService,
type LaunchctlResult,
} from "./launchctl";
type Call = { args: string[]; stdio: string };
function recordingRun(statusFor: (call: Call, index: number) => number | null): {
run: (args: string[], stdio: "inherit" | "ignore") => LaunchctlResult;
calls: Call[];
} {
const calls: Call[] = [];
const run = (args: string[], stdio: "inherit" | "ignore"): LaunchctlResult => {
const call = { args, stdio };
const status = statusFor(call, calls.length);
calls.push(call);
return { status };
};
return { run, calls };
}
describe("bootoutAndWait", () => {
it("polls `print` until the job is gone before returning", () => {
// print returns 0 (still loaded) twice, then non-zero (gone).
let printCount = 0;
const { run, calls } = recordingRun((call) => {
if (call.args[0] === "bootout") return 0;
if (call.args[0] === "print") {
printCount += 1;
return printCount <= 2 ? 0 : 1;
}
return 0;
});
const sleep = vi.fn();
bootoutAndWait("gui/501/com.kdlbs.kandev", { run, sleep });
expect(calls[0].args).toEqual(["bootout", "gui/501/com.kdlbs.kandev"]);
expect(calls.filter((c) => c.args[0] === "print")).toHaveLength(3);
expect(sleep).toHaveBeenCalledTimes(2);
});
it("returns immediately when nothing is loaded", () => {
const { run, calls } = recordingRun((call) => (call.args[0] === "print" ? 1 : 0));
const sleep = vi.fn();
bootoutAndWait("gui/501/com.kdlbs.kandev", { run, sleep });
expect(calls.filter((c) => c.args[0] === "print")).toHaveLength(1);
expect(sleep).not.toHaveBeenCalled();
});
});
describe("bootstrapWithRetry", () => {
it("retries through the transient EIO and succeeds", () => {
// Reproduces the launchd teardown race: bootstrap returns 5 twice, then 0.
let bootstrapCount = 0;
const { run, calls } = recordingRun(() => {
bootstrapCount += 1;
return bootstrapCount < 3 ? 5 : 0;
});
const sleep = vi.fn();
expect(() =>
bootstrapWithRetry("gui/501", "/Users/a/Library/LaunchAgents/x.plist", { run, sleep }),
).not.toThrow();
expect(calls).toHaveLength(3);
expect(sleep).toHaveBeenCalledTimes(2);
});
it("throws with the last exit code after exhausting retries", () => {
const { run, calls } = recordingRun(() => 5);
const sleep = vi.fn();
expect(() =>
bootstrapWithRetry("gui/501", "/Users/a/Library/LaunchAgents/x.plist", { run, sleep }),
).toThrow(/failed with code 5/);
expect(calls).toHaveLength(5);
});
it("succeeds on the first attempt without sleeping", () => {
const { run, calls } = recordingRun(() => 0);
const sleep = vi.fn();
bootstrapWithRetry("gui/501", "/x.plist", { run, sleep });
expect(calls).toHaveLength(1);
expect(sleep).not.toHaveBeenCalled();
});
});
describe("reloadService", () => {
it("waits for teardown, then bootstraps — surviving an EIO mid-reload", () => {
// Live-service reload: print stays loaded once, bootstrap hits EIO once.
let printCount = 0;
let bootstrapCount = 0;
const { run, calls } = recordingRun((call) => {
if (call.args[0] === "print") {
printCount += 1;
return printCount <= 1 ? 0 : 1;
}
if (call.args[0] === "bootstrap") {
bootstrapCount += 1;
return bootstrapCount < 2 ? 5 : 0;
}
return 0;
});
const sleep = vi.fn();
reloadService("gui/501/com.kdlbs.kandev", "gui/501", "/x.plist", { run, sleep });
const order = calls.map((c) => c.args[0]);
expect(order[0]).toBe("bootout");
// bootout precedes the first bootstrap
expect(order.indexOf("bootout")).toBeLessThan(order.indexOf("bootstrap"));
expect(calls.filter((c) => c.args[0] === "bootstrap")).toHaveLength(2);
});
});
+106
View File
@@ -0,0 +1,106 @@
import { spawnSync } from "node:child_process";
/**
* launchd's `bootout` is asynchronous: the command returns as soon as launchd
* accepts the request, but the job (and, for a live service, its process) may
* still be tearing down. Issuing `bootstrap` for the same label before that
* teardown finishes races launchd and surfaces as:
*
* Bootstrap failed: 5: Input/output error
*
* This is invisible on a fresh install (nothing to tear down) and in unit tests
* (no live launchctl), but it reliably breaks self-update — there the service is
* actively running when `kandev service install` reloads it. The helpers below
* make the bootout→bootstrap dance robust: wait for the old job to actually
* disappear, then retry the bootstrap through the brief residual EIO window.
*/
export type LaunchctlResult = { status: number | null };
export type LaunchctlStdio = "inherit" | "ignore";
export type LaunchctlRunner = (args: string[], stdio: LaunchctlStdio) => LaunchctlResult;
export type SleepFn = (ms: number) => void;
export type LaunchctlDeps = {
run?: LaunchctlRunner;
sleep?: SleepFn;
};
const BOOTOUT_POLL_INTERVAL_MS = 100;
const BOOTOUT_POLL_ATTEMPTS = 50; // ~5s ceiling waiting for teardown
const BOOTSTRAP_MAX_ATTEMPTS = 5;
const BOOTSTRAP_RETRY_BASE_MS = 300;
export function spawnLaunchctl(args: string[], stdio: LaunchctlStdio): LaunchctlResult {
const res = spawnSync("launchctl", args, { stdio });
return { status: res.status };
}
// Block the current thread for `ms`. The launchctl orchestration runs in the
// synchronous `service install`/`start`/`restart` paths, so we can't await a
// timer — Atomics.wait gives a dependency-free blocking sleep.
export function sleepSync(ms: number): void {
if (ms <= 0) return;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
function isLoaded(target: string, run: LaunchctlRunner): boolean {
// `launchctl print <target>` exits non-zero once the label is gone.
return run(["print", target], "ignore").status === 0;
}
/**
* Boot out a launchd job and wait until launchd has fully removed it. A no-op
* (returns promptly) when the label isn't loaded, so fresh installs aren't
* slowed down.
*/
export function bootoutAndWait(target: string, deps: LaunchctlDeps = {}): void {
const run = deps.run ?? spawnLaunchctl;
const sleep = deps.sleep ?? sleepSync;
run(["bootout", target], "ignore");
for (let attempt = 0; attempt < BOOTOUT_POLL_ATTEMPTS; attempt += 1) {
if (!isLoaded(target, run)) {
return;
}
sleep(BOOTOUT_POLL_INTERVAL_MS);
}
}
/**
* Bootstrap a launchd job, retrying through the transient EIO that launchd
* returns while a previous instance of the same label finishes tearing down.
* Throws with the last exit code if every attempt fails.
*/
export function bootstrapWithRetry(
domain: string,
plistPath: string,
deps: LaunchctlDeps = {},
): void {
const run = deps.run ?? spawnLaunchctl;
const sleep = deps.sleep ?? sleepSync;
let lastStatus: number | null = null;
for (let attempt = 1; attempt <= BOOTSTRAP_MAX_ATTEMPTS; attempt += 1) {
lastStatus = run(["bootstrap", domain, plistPath], "inherit").status;
if (lastStatus === 0) {
return;
}
if (attempt < BOOTSTRAP_MAX_ATTEMPTS) {
sleep(BOOTSTRAP_RETRY_BASE_MS * attempt);
}
}
throw new Error(`launchctl bootstrap ${domain} ${plistPath} failed with code ${lastStatus}`);
}
/**
* Reload a launchd job: fully unload (waiting for teardown) then bootstrap with
* retry. This is the safe sequence whenever the target might currently be
* running — installs that refresh a live service, and `start`.
*/
export function reloadService(
target: string,
domain: string,
plistPath: string,
deps: LaunchctlDeps = {},
): void {
bootoutAndWait(target, deps);
bootstrapWithRetry(domain, plistPath, deps);
}
+27 -2
View File
@@ -5,6 +5,11 @@ import path from "node:path";
import type { ServiceArgs } from "./args";
import { dumpJournalctlLogs, waitForServiceHealth } from "./health_check";
import { commandExists, writeUnitFile } from "./install_helpers";
import {
buildServiceInstallMetadata,
serviceMetadataPath,
writeServiceInstallMetadata,
} from "./metadata";
import {
captureLauncher,
currentUsername,
@@ -59,6 +64,9 @@ export async function runLinuxService(args: ServiceArgs): Promise<void> {
case "config":
// Handled by the dispatcher in index.ts before reaching the platform layer.
throw new Error("unreachable: config action handled in service/index.ts");
case "self-update":
// Handled by the dispatcher in index.ts before reaching the platform layer.
throw new Error("unreachable: self-update action handled in service/index.ts");
default: {
const _exhaustive: never = args.action;
throw new Error(`unhandled service action: ${_exhaustive as string}`);
@@ -77,17 +85,34 @@ function installSync(ctx: Ctx): void {
const launcher = captureLauncher();
const homeDir = resolveHomeDir(ctx.args.homeDir, ctx.isSystem);
const logDir = resolveLogDir(homeDir);
const metadataPath = serviceMetadataPath(homeDir);
const mode = ctx.isSystem ? "system" : "user";
const systemUser = ctx.isSystem ? resolveServiceUser(true) : undefined;
const unit = renderSystemdUnit({
launcher,
homeDir,
logDir,
port: ctx.args.port,
systemUser: ctx.isSystem ? resolveServiceUser(true) : undefined,
mode: ctx.isSystem ? "system" : "user",
systemUser,
mode,
serviceMetadataPath: metadataPath,
});
fs.mkdirSync(path.dirname(ctx.unitPath), { recursive: true });
const outcome = writeUnitFile(ctx.unitPath, unit);
writeServiceInstallMetadata(
metadataPath,
buildServiceInstallMetadata({
manager: "systemd",
mode,
launcher,
homeDir,
logDir,
servicePath: ctx.unitPath,
port: ctx.args.port,
systemUser,
}),
);
runSystemctl(ctx, ["daemon-reload"]);
// Always run enable --now so 'install' is fully idempotent: if the user
+40 -8
View File
@@ -6,6 +6,12 @@ import path from "node:path";
import type { ServiceArgs } from "./args";
import { dumpLaunchdLogs, waitForServiceHealth } from "./health_check";
import { commandExists, writeUnitFile } from "./install_helpers";
import { reloadService } from "./launchctl";
import {
buildServiceInstallMetadata,
serviceMetadataPath,
writeServiceInstallMetadata,
} from "./metadata";
import {
captureLauncher,
LAUNCHD_LABEL,
@@ -64,6 +70,9 @@ export async function runMacosService(args: ServiceArgs): Promise<void> {
case "config":
// Handled by the dispatcher in index.ts before reaching the platform layer.
throw new Error("unreachable: config action handled in service/index.ts");
case "self-update":
// Handled by the dispatcher in index.ts before reaching the platform layer.
throw new Error("unreachable: self-update action handled in service/index.ts");
default: {
const _exhaustive: never = args.action;
throw new Error(`unhandled service action: ${_exhaustive as string}`);
@@ -80,6 +89,9 @@ function installSync(ctx: Ctx): { logDir: string } {
const launcher = captureLauncher();
const homeDir = resolveHomeDir(ctx.args.homeDir, ctx.isSystem);
const logDir = resolveLogDir(homeDir);
const metadataPath = serviceMetadataPath(homeDir);
const mode = ctx.isSystem ? "system" : "user";
const systemUser = ctx.isSystem ? resolveServiceUser(true) : undefined;
fs.mkdirSync(logDir, { recursive: true });
const plist = renderLaunchdPlist({
@@ -87,19 +99,37 @@ function installSync(ctx: Ctx): { logDir: string } {
homeDir,
logDir,
port: ctx.args.port,
systemUser: ctx.isSystem ? resolveServiceUser(true) : undefined,
mode: ctx.isSystem ? "system" : "user",
systemUser,
mode,
serviceMetadataPath: metadataPath,
});
fs.mkdirSync(path.dirname(ctx.plistPath), { recursive: true });
const outcome = writeUnitFile(ctx.plistPath, plist);
writeServiceInstallMetadata(
metadataPath,
buildServiceInstallMetadata({
manager: "launchd",
mode,
launcher,
homeDir,
logDir,
servicePath: ctx.plistPath,
port: ctx.args.port,
systemUser,
}),
);
// launchctl bootstrap fails if the label is already loaded — bootout first
// (ignoring its error if nothing was loaded). This means 'install' is
// idempotent: re-running it reloads the unit even if the file is unchanged,
// which is how we recover from a user manually unloading the service.
spawnSync("launchctl", ["bootout", ctx.target], { stdio: "ignore" });
runLaunchctl(["bootstrap", ctx.domain, ctx.plistPath]);
//
// `reloadService` waits for bootout's async teardown before bootstrapping and
// retries the transient EIO ("Bootstrap failed: 5") that launchd returns while
// a still-running instance is torn down — the failure that broke self-update,
// where this install runs against a live service. See launchctl.ts.
reloadService(ctx.target, ctx.domain, ctx.plistPath);
runLaunchctl(["enable", ctx.target], { allowFailure: true });
console.log(
outcome === "unchanged"
@@ -131,9 +161,9 @@ function uninstall(ctx: Ctx): void {
// so each begins with a bootout-then-bootstrap dance similar to installSync.
function startService(ctx: Ctx): void {
// Idempotent: if the label is already loaded, bootstrap would fail. Bootout
// first so start works whether the service was previously running or stopped.
spawnSync("launchctl", ["bootout", ctx.target], { stdio: "ignore" });
runLaunchctl(["bootstrap", ctx.domain, ctx.plistPath]);
// first (waiting for teardown) so start works whether the service was
// previously running or stopped.
reloadService(ctx.target, ctx.domain, ctx.plistPath);
}
function stopService(ctx: Ctx): void {
@@ -146,7 +176,9 @@ function stopService(ctx: Ctx): void {
function restartService(ctx: Ctx): void {
const res = spawnSync("launchctl", ["kickstart", "-k", ctx.target], { stdio: "inherit" });
if (res.status === 0) return;
runLaunchctl(["bootstrap", ctx.domain, ctx.plistPath]);
// kickstart fails when the job isn't loaded — reload it (waiting for any
// residual teardown and retrying the transient bootstrap EIO).
reloadService(ctx.target, ctx.domain, ctx.plistPath);
}
function showStatus(ctx: Ctx): void {
+66
View File
@@ -0,0 +1,66 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
buildServiceInstallMetadata,
serviceMetadataPath,
writeServiceInstallMetadata,
} from "./metadata";
describe("service metadata", () => {
it("builds the install metadata written beside service units", () => {
const metadata = buildServiceInstallMetadata({
manager: "systemd",
mode: "user",
launcher: {
nodePath: "/usr/bin/node",
cliEntry: "/usr/lib/node_modules/kandev/bin/cli.js",
kind: "npm",
},
homeDir: "/home/alice/.kandev",
logDir: "/home/alice/.kandev/logs",
servicePath: "/home/alice/.config/systemd/user/kandev.service",
port: 38429,
now: new Date("2026-05-29T00:00:00.000Z"),
});
expect(metadata).toMatchObject({
version: 1,
manager: "systemd",
mode: "user",
kind: "npm",
home_dir: "/home/alice/.kandev",
service_path: "/home/alice/.config/systemd/user/kandev.service",
node_path: "/usr/bin/node",
cli_entry: "/usr/lib/node_modules/kandev/bin/cli.js",
port: 38429,
installed_at: "2026-05-29T00:00:00.000Z",
});
});
it("writes metadata JSON under <home>/service/install.json", () => {
const tmp = fs.mkdtempSync(path.join(process.cwd(), "metadata-test-"));
try {
const target = serviceMetadataPath(tmp);
writeServiceInstallMetadata(target, {
version: 1,
manager: "launchd",
mode: "user",
kind: "homebrew",
home_dir: tmp,
log_dir: path.join(tmp, "logs"),
service_path: "/Users/alice/Library/LaunchAgents/com.kdlbs.kandev.plist",
node_path: "/opt/homebrew/bin/node",
cli_entry: "/opt/homebrew/opt/kandev/libexec/cli/bin/cli.js",
installed_at: "2026-05-29T00:00:00.000Z",
});
const parsed = JSON.parse(fs.readFileSync(target, "utf8")) as { manager: string };
expect(parsed.manager).toBe("launchd");
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});
});
+76
View File
@@ -0,0 +1,76 @@
import fs from "node:fs";
import path from "node:path";
import type { LauncherInfo } from "./paths";
export type ServiceManager = "systemd" | "launchd";
export type ServiceMode = "user" | "system";
export type ServiceInstallMetadata = {
version: 1;
manager: ServiceManager;
mode: ServiceMode;
kind: LauncherInfo["kind"];
home_dir: string;
log_dir: string;
service_path: string;
node_path: string;
cli_entry: string;
bundle_dir?: string;
launcher_version?: string;
port?: number;
system_user?: string;
installed_at: string;
};
export type BuildServiceInstallMetadataInput = {
manager: ServiceManager;
mode: ServiceMode;
launcher: LauncherInfo;
homeDir: string;
logDir: string;
servicePath: string;
port?: number;
systemUser?: string;
now?: Date;
};
export function serviceMetadataPath(homeDir: string): string {
return path.join(homeDir, "service", "install.json");
}
export function buildServiceInstallMetadata(
input: BuildServiceInstallMetadataInput,
): ServiceInstallMetadata {
const out: ServiceInstallMetadata = {
version: 1,
manager: input.manager,
mode: input.mode,
kind: input.launcher.kind,
home_dir: input.homeDir,
log_dir: input.logDir,
service_path: input.servicePath,
node_path: input.launcher.nodePath,
cli_entry: input.launcher.cliEntry,
installed_at: (input.now ?? new Date()).toISOString(),
};
if (input.launcher.bundleDir) out.bundle_dir = input.launcher.bundleDir;
if (input.launcher.version) out.launcher_version = input.launcher.version;
if (input.port !== undefined) out.port = input.port;
if (input.systemUser) out.system_user = input.systemUser;
return out;
}
export function writeServiceInstallMetadata(
metadataPath: string,
metadata: ServiceInstallMetadata,
): void {
const dir = path.dirname(metadataPath);
// `mode` on mkdir/writeFile only applies when the path is created. chmod after
// so a pre-existing service dir / install.json is tightened to owner-only too
// (it can hold launcher paths and the metadata that gates self-update).
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
fs.chmodSync(dir, 0o700);
fs.writeFileSync(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, { mode: 0o600 });
fs.chmodSync(metadataPath, 0o600);
}
+32
View File
@@ -5,6 +5,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { captureLauncher, homebrewShimPath, resolveHomeDir, resolveServiceUser } from "./paths";
const originalArgv = [...process.argv];
const originalBundleDir = process.env.KANDEV_BUNDLE_DIR;
const originalVersion = process.env.KANDEV_VERSION;
describe("resolveServiceUser", () => {
const originalSudoUser = process.env.SUDO_USER;
@@ -68,6 +72,32 @@ describe("resolveServiceUser", () => {
});
});
describe("captureLauncher", () => {
afterEach(() => {
process.argv.splice(0, process.argv.length, ...originalArgv);
if (originalBundleDir === undefined) delete process.env.KANDEV_BUNDLE_DIR;
else process.env.KANDEV_BUNDLE_DIR = originalBundleDir;
if (originalVersion === undefined) delete process.env.KANDEV_VERSION;
else process.env.KANDEV_VERSION = originalVersion;
vi.restoreAllMocks();
});
it("resolves npm global bin symlinks before detecting the install kind", () => {
delete process.env.KANDEV_BUNDLE_DIR;
delete process.env.KANDEV_VERSION;
process.argv[1] = "/tmp/kandev-test/npm-global/bin/kandev";
vi.spyOn(fs, "existsSync").mockReturnValue(true);
vi.spyOn(fs, "realpathSync").mockReturnValue(
"/tmp/kandev-test/npm-global/lib/node_modules/kandev/bin/cli.js",
);
expect(captureLauncher()).toMatchObject({
cliEntry: "/tmp/kandev-test/npm-global/lib/node_modules/kandev/bin/cli.js",
kind: "npm",
});
});
});
describe("resolveHomeDir", () => {
afterEach(() => {
vi.restoreAllMocks();
@@ -138,6 +168,7 @@ describe("captureLauncher shim resolution", () => {
vi.stubEnv("KANDEV_BUNDLE_DIR", "/opt/homebrew/Cellar/kandev/1.2.3/libexec");
// Both the cli.js entry and the shim resolve on disk.
vi.spyOn(fs, "existsSync").mockImplementation((p) => p === cliEntry || p === shim);
vi.spyOn(fs, "realpathSync").mockReturnValue(cliEntry);
const info = captureLauncher();
expect(info.kind).toBe("homebrew");
@@ -150,6 +181,7 @@ describe("captureLauncher shim resolution", () => {
vi.stubEnv("KANDEV_BUNDLE_DIR", "/opt/homebrew/Cellar/kandev/1.2.3/libexec");
// The cli.js entry resolves, but the floating shim does not exist.
vi.spyOn(fs, "existsSync").mockImplementation((p) => p === cliEntry);
vi.spyOn(fs, "realpathSync").mockReturnValue(cliEntry);
const info = captureLauncher();
expect(info.kind).toBe("homebrew");
+13 -7
View File
@@ -34,7 +34,7 @@ export function macosSystemPlistPath(): string {
return path.join(MACOS_SYSTEM_DAEMON_DIR, `${LAUNCHD_LABEL}.plist`);
}
export type LauncherKind = "homebrew" | "npm" | "unknown";
export type LauncherKind = "homebrew" | "npm" | "npx" | "unknown";
export type LauncherInfo = {
/** Absolute path to node executable (process.execPath at install time). */
@@ -87,8 +87,8 @@ export function homebrewShimPath(cliEntry: string): string | undefined {
*
* The unit file hard-codes absolute paths because systemd/launchd start with an
* empty PATH and may not see the user's `node` or `kandev` shim. By recording
* `process.execPath` (node) and `process.argv[1]` (cli.js) at install time we
* avoid any PATH lookups at service-run time.
* `process.execPath` (node) and the resolved CLI entry at install time we avoid
* any PATH lookups at service-run time.
*/
export function captureLauncher(): LauncherInfo {
const nodePath = process.execPath;
@@ -97,9 +97,11 @@ export function captureLauncher(): LauncherInfo {
const version = process.env.KANDEV_VERSION;
const kind: LauncherKind = bundleDir
? "homebrew"
: cliEntry.includes(`${path.sep}node_modules${path.sep}`)
? "npm"
: "unknown";
: looksLikeNpxEntry(cliEntry)
? "npx"
: cliEntry.includes(`${path.sep}node_modules${path.sep}`)
? "npm"
: "unknown";
// For Homebrew installs, prefer the floating bin shim so the unit survives
// `brew upgrade` (which deletes the versioned Cellar dir baked into nodePath
// /cliEntry). Only adopt it when the shim actually exists on disk; otherwise
@@ -112,10 +114,14 @@ export function captureLauncher(): LauncherInfo {
return { nodePath, cliEntry, kind, bundleDir, version, shimPath };
}
function looksLikeNpxEntry(cliEntry: string): boolean {
return cliEntry.includes(`${path.sep}_npx${path.sep}`);
}
function resolveCliEntry(): string {
const argvEntry = process.argv[1];
if (argvEntry && fs.existsSync(argvEntry)) {
return path.resolve(argvEntry);
return path.resolve(fs.realpathSync(argvEntry));
}
throw new Error(
"could not resolve the kandev CLI entry path from process.argv[1]; " +
+191
View File
@@ -0,0 +1,191 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { planSelfUpdate, runSelfUpdateCommand, type SelfUpdateIntent } from "./self_update";
function intent(kind: "homebrew" | "npm" | "npx" = "npm"): SelfUpdateIntent {
return {
version: 1,
target_tag: "v1.2.3",
target_version: "1.2.3",
latest_url: "https://example/v1.2.3",
created_at: "2026-05-29T00:00:00.000Z",
install: {
version: 1,
manager: "systemd",
mode: "user",
kind,
home_dir: "/home/alice/.kandev",
log_dir: "/home/alice/.kandev/logs",
service_path: "/home/alice/.config/systemd/user/kandev.service",
node_path: "/usr/bin/node",
cli_entry: "/usr/lib/node_modules/kandev/bin/cli.js",
port: 38429,
installed_at: "2026-05-29T00:00:00.000Z",
},
};
}
describe("planSelfUpdate", () => {
it("plans npm upgrade, service reinstall, then user-service restart", () => {
expect(planSelfUpdate(intent("npm"), { platform: "linux" })).toEqual([
{ command: "npm", args: ["install", "-g", "--prefix", "/usr", "kandev@1.2.3"] },
{
command: "/usr/bin/node",
args: [
"/usr/lib/node_modules/kandev/bin/cli.js",
"service",
"install",
"--home-dir",
"/home/alice/.kandev",
"--port",
"38429",
],
},
{ command: "systemctl", args: ["--user", "restart", "kandev"] },
]);
});
it("keeps npm updates inside the original global prefix", () => {
const npm = intent("npm");
npm.install.cli_entry = "/tmp/kandev-test/npm-global/lib/node_modules/kandev/bin/cli.js";
expect(planSelfUpdate(npm, { platform: "linux" })[0]).toEqual({
command: "npm",
args: ["install", "-g", "--prefix", "/tmp/kandev-test/npm-global", "kandev@1.2.3"],
});
});
it("falls back to npm's configured prefix when the cli path is non-standard", () => {
const npm = intent("npm");
npm.install.cli_entry = "/opt/kandev/bin/cli.js";
expect(planSelfUpdate(npm, { platform: "linux" })[0]).toEqual({
command: "npm",
args: ["install", "-g", "kandev@1.2.3"],
});
});
it("plans homebrew upgrade then reinstall via the kandev wrapper (not node <cli_entry>)", () => {
const brew = intent("homebrew");
// A real Homebrew install records a version-pinned Cellar cli_entry.
brew.install.cli_entry = "/opt/homebrew/Cellar/kandev/1.2.2/libexec/cli/bin/cli.js";
brew.install.node_path = "/opt/homebrew/bin/node";
const commands = planSelfUpdate(brew, { platform: "linux" });
expect(commands[0]).toEqual({ command: "brew", args: ["upgrade", "kandev"] });
// Step 2 must use the upgraded `kandev` wrapper (version-stable, re-sets
// KANDEV_BUNDLE_DIR), never `node` on the stale version-pinned cli_entry.
expect(commands[1]).toEqual({
command: "kandev",
args: ["service", "install", "--home-dir", "/home/alice/.kandev", "--port", "38429"],
});
expect(commands[1].command).not.toBe("/opt/homebrew/bin/node");
});
it("plans npx reinstall without mutating global npm packages", () => {
const commands = planSelfUpdate(intent("npx"), { platform: "linux" });
expect(commands[0]).toEqual({
command: "npx",
args: [
"-y",
"kandev@1.2.3",
"service",
"install",
"--home-dir",
"/home/alice/.kandev",
"--port",
"38429",
],
});
});
it("plans launchd restart on macOS", () => {
const mac = intent("homebrew");
mac.install.manager = "launchd";
mac.install.service_path = "/Users/alice/Library/LaunchAgents/com.kdlbs.kandev.plist";
mac.install.home_dir = "/Users/alice/.kandev";
mac.install.log_dir = "/Users/alice/.kandev/logs";
const commands = planSelfUpdate(mac, { platform: "darwin", uid: 501 });
expect(commands.at(-1)).toEqual({
command: "launchctl",
args: ["kickstart", "-k", "gui/501/com.kdlbs.kandev"],
});
});
});
describe("runSelfUpdateCommand", () => {
it("does not run commands in dry-run mode", () => {
const tmp = fs.mkdtempSync(path.join(process.cwd(), "self-update-test-"));
const intentPath = path.join(tmp, "intent.json");
fs.writeFileSync(intentPath, JSON.stringify(intent("npm")));
const runner = vi.fn();
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
try {
runSelfUpdateCommand({ action: "self-update", intent: intentPath, dryRun: true }, runner);
expect(runner).not.toHaveBeenCalled();
expect(log).toHaveBeenCalledWith(expect.stringContaining('"dry_run": true'));
} finally {
log.mockRestore();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
function readLog(logDir: string): string {
const file = fs.readdirSync(logDir).find((name) => name.startsWith("self-update-"));
expect(file, "a self-update log file should be written").toBeTruthy();
return fs.readFileSync(path.join(logDir, file as string), "utf8");
}
it("tees each command, its output, and exit status to a log file", () => {
const tmp = fs.mkdtempSync(path.join(process.cwd(), "self-update-test-"));
const logDir = path.join(tmp, "logs");
const it_ = intent("npm");
it_.install.log_dir = logDir;
const intentPath = path.join(tmp, "intent.json");
fs.writeFileSync(intentPath, JSON.stringify(it_));
const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
const runner = vi.fn().mockReturnValue({ status: 0, stdout: Buffer.from("ok output") });
try {
runSelfUpdateCommand({ action: "self-update", intent: intentPath }, runner);
const contents = readLog(logDir);
expect(contents).toContain("npm install -g");
expect(contents).toContain("service install");
expect(contents).toContain("ok output");
expect(contents).toContain("exit 0");
expect(contents).toContain("self-update completed successfully");
} finally {
stdout.mockRestore();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
it("logs the failing command and its code before throwing", () => {
const tmp = fs.mkdtempSync(path.join(process.cwd(), "self-update-test-"));
const logDir = path.join(tmp, "logs");
const it_ = intent("npm");
it_.install.log_dir = logDir;
const intentPath = path.join(tmp, "intent.json");
fs.writeFileSync(intentPath, JSON.stringify(it_));
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
const runner = vi.fn().mockReturnValue({ status: 7, stderr: Buffer.from("npm boom") });
try {
expect(() =>
runSelfUpdateCommand({ action: "self-update", intent: intentPath }, runner),
).toThrow(/failed with code 7/);
const contents = readLog(logDir);
expect(contents).toContain("npm boom");
expect(contents).toContain("exited with code 7");
expect(contents).not.toContain("self-update completed successfully");
} finally {
stdout.mockRestore();
stderr.mockRestore();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
});
+281
View File
@@ -0,0 +1,281 @@
import { spawnSync, type SpawnSyncReturns } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { ServiceArgs } from "./args";
import type { ServiceInstallMetadata } from "./metadata";
import { LAUNCHD_LABEL, SERVICE_NAME } from "./paths";
export type SelfUpdateIntent = {
version: 1;
target_tag: string;
target_version: string;
latest_url?: string;
install: ServiceInstallMetadata;
created_at: string;
};
export type PlannedCommand = {
command: string;
args: string[];
};
export type PlanSelfUpdateOptions = {
platform?: NodeJS.Platform;
uid?: number;
};
export type CommandResult = Pick<SpawnSyncReturns<Buffer>, "status" | "error"> & {
stdout?: Buffer | string | null;
stderr?: Buffer | string | null;
};
export type CommandRunner = (command: string, args: string[]) => CommandResult;
export function readSelfUpdateIntent(intentPath: string): SelfUpdateIntent {
return JSON.parse(fs.readFileSync(intentPath, "utf8")) as SelfUpdateIntent;
}
export function planSelfUpdate(
intent: SelfUpdateIntent,
opts: PlanSelfUpdateOptions = {},
): PlannedCommand[] {
const platform = opts.platform ?? process.platform;
const target = npmVersion(intent.target_version || intent.target_tag);
const install = intent.install;
const installArgs = serviceInstallArgs(install);
const commands: PlannedCommand[] = [];
if (install.kind === "homebrew") {
// `brew upgrade` installs the tap formula's current version; it can't be
// pinned to intent.target_version the way npm/npx can (Homebrew has no
// stable "install version X" without a separate versioned formula). In
// practice both target_version and the formula derive from the same latest
// GitHub release, so they match. If the formula lags, the restarted backend
// reports the older version and the frontend progress poll (which waits for
// info.version === target_version) times out gracefully rather than
// reporting a false success.
commands.push({ command: "brew", args: ["upgrade", "kandev"] });
// Re-run service install via the upgraded `kandev` wrapper (resolved on
// PATH), NOT `node <cli_entry>`. Homebrew installs into version-pinned
// Cellar dirs, so the recorded cli_entry still points at the OLD bundle
// after `brew upgrade`; worse, invoking node on it directly runs without
// KANDEV_BUNDLE_DIR/KANDEV_VERSION, so the install is mis-detected as
// kind "unknown" and the regenerated unit loses the bundle env — the
// restarted backend then can't find its runtime and the service stays down.
// The wrapper is version-stable and re-sets the bundle env. (Mirrors the
// manual `kandev service install` we already document for Homebrew.)
commands.push({ command: "kandev", args: installArgs });
} else if (install.kind === "npm") {
commands.push({ command: "npm", args: npmInstallArgs(install.cli_entry, target) });
commands.push({ command: install.node_path, args: [install.cli_entry, ...installArgs] });
} else if (install.kind === "npx") {
commands.push({ command: "npx", args: ["-y", `kandev@${target}`, ...installArgs] });
} else {
throw new Error(`unsupported install kind "${install.kind}"`);
}
commands.push(restartCommand(install, platform, opts.uid));
return commands;
}
export function runSelfUpdateCommand(
args: ServiceArgs,
runner: CommandRunner = spawnCommand,
): void {
if (!args.intent) {
throw new Error("kandev service self-update requires --intent <path>");
}
const intent = readSelfUpdateIntent(args.intent);
const commands = planSelfUpdate(intent);
if (args.dryRun || process.env.KANDEV_E2E_MOCK === "true") {
console.log(
JSON.stringify(
{
dry_run: !!args.dryRun,
fake: process.env.KANDEV_E2E_MOCK === "true",
target_version: intent.target_version,
commands,
},
null,
2,
),
);
return;
}
const log = openSelfUpdateLog(intent);
try {
log?.line(`self-update target ${intent.target_tag} (${intent.target_version})`);
log?.line(`install kind=${intent.install.kind} manager=${intent.install.manager}`);
log?.line(`planned ${commands.length} command(s):`);
commands.forEach((step, i) =>
log?.line(` [${i + 1}/${commands.length}] ${formatCommand(step)}`),
);
runSelfUpdateSteps(commands, runner, log);
log?.line("self-update completed successfully");
} finally {
log?.close();
}
}
function runSelfUpdateSteps(
commands: PlannedCommand[],
runner: CommandRunner,
log: SelfUpdateLog | null,
): void {
for (const [i, step] of commands.entries()) {
log?.line(`\n[${i + 1}/${commands.length}] $ ${formatCommand(step)}`);
const res = runner(step.command, step.args);
teeCommandOutput(log, res);
if (res.error) {
log?.line(`! spawn error: ${res.error.message}`);
throw res.error;
}
if (res.status !== 0) {
log?.line(`! exited with code ${res.status}`);
throw new Error(`${formatCommand(step)} failed with code ${res.status}`);
}
log?.line(" exit 0");
}
}
function formatCommand(step: PlannedCommand): string {
return [step.command, ...step.args].join(" ");
}
function serviceInstallArgs(install: ServiceInstallMetadata): string[] {
const args = ["service", "install"];
if (install.mode === "system") args.push("--system");
args.push("--home-dir", install.home_dir);
if (install.port !== undefined) {
args.push("--port", String(install.port));
}
return args;
}
function npmInstallArgs(cliEntry: string, target: string): string[] {
const args = ["install", "-g"];
const prefix = npmPrefixFromCliEntry(cliEntry);
if (prefix) {
args.push("--prefix", prefix);
}
args.push(`kandev@${target}`);
return args;
}
function npmPrefixFromCliEntry(cliEntry: string): string | undefined {
const marker = `${path.sep}lib${path.sep}node_modules${path.sep}kandev${path.sep}`;
const index = cliEntry.indexOf(marker);
if (index < 0) {
return undefined;
}
return index === 0 ? path.sep : cliEntry.slice(0, index);
}
function restartCommand(
install: ServiceInstallMetadata,
platform: NodeJS.Platform,
uid?: number,
): PlannedCommand {
if (platform === "linux") {
return install.mode === "system"
? { command: "systemctl", args: ["restart", SERVICE_NAME] }
: { command: "systemctl", args: ["--user", "restart", SERVICE_NAME] };
}
if (platform === "darwin") {
// Resolve the uid lazily inside the darwin branch — Linux never needs it, so
// os.userInfo() shouldn't run there.
const resolvedUid = uid ?? os.userInfo().uid;
const domain = install.mode === "system" ? "system" : `gui/${resolvedUid}`;
return { command: "launchctl", args: ["kickstart", "-k", `${domain}/${LAUNCHD_LABEL}`] };
}
throw new Error(`unsupported platform "${platform}"`);
}
function npmVersion(versionOrTag: string): string {
const stripped = versionOrTag.replace(/^v/, "");
return stripped || "latest";
}
function spawnCommand(command: string, args: string[]): CommandResult {
// Capture stdout/stderr (rather than inheriting) so the self-update log can
// tee each step's output. The helper runs detached under launchd/systemd, so
// its console output would otherwise go nowhere visible — the log file is the
// only forensic trail when an update fails mid-flight. maxBuffer is bumped
// well above the 1 MiB default because `npm install -g` is chatty.
return spawnSync(command, args, { maxBuffer: 64 * 1024 * 1024 });
}
type SelfUpdateLog = {
path: string;
line: (message: string) => void;
raw: (chunk: Buffer | string) => void;
close: () => void;
};
/**
* Open a timestamped log file under the service's log dir for this self-update
* run. The helper is spawned outside the service process (so a restart doesn't
* kill it mid-update), which means it has no service log of its own — without
* this file a failed update on macOS/launchd is nearly invisible. Best-effort:
* if the log dir can't be created we return null and the update still runs.
*/
function openSelfUpdateLog(intent: SelfUpdateIntent): SelfUpdateLog | null {
const dir = intent.install.log_dir || logDirFromHome(intent.install.home_dir);
if (!dir) {
return null;
}
try {
fs.mkdirSync(dir, { recursive: true });
// Self-update logs can contain install paths/env; keep the dir owner-only
// even if it pre-existed with looser perms.
fs.chmodSync(dir, 0o700);
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const filePath = path.join(dir, `self-update-${stamp}.log`);
const fd = fs.openSync(filePath, "a");
const write = (chunk: Buffer | string): void => {
try {
// The `Buffer | string` union matches neither writeSync overload
// directly; the cast picks one — both write the runtime value correctly.
fs.writeSync(fd, chunk as string);
} catch {
// A write failure mid-update must not abort the update itself.
}
};
process.stdout.write(`[kandev] self-update log: ${filePath}\n`);
write(`# kandev self-update ${new Date().toISOString()}\n`);
return {
path: filePath,
line: (message) => write(`${message}\n`),
raw: (chunk) => write(chunk),
close: () => {
try {
fs.closeSync(fd);
} catch {
// already closed / never opened
}
},
};
} catch {
return null;
}
}
function logDirFromHome(homeDir: string): string {
return homeDir ? path.join(homeDir, "logs") : "";
}
// Mirror a command's captured output to both the helper log and the process's
// own stdout/stderr, so whatever does manage to capture the helper's streams
// (e.g. launchd's StandardOut/ErrorPath, systemd's journal) still sees it.
function teeCommandOutput(log: SelfUpdateLog | null, res: CommandResult): void {
if (res.stdout && res.stdout.length) {
process.stdout.write(res.stdout);
log?.raw(res.stdout);
}
if (res.stderr && res.stderr.length) {
process.stderr.write(res.stderr);
log?.raw(res.stderr);
}
}
+37
View File
@@ -124,6 +124,23 @@ describe("renderSystemdUnit", () => {
expect(unit).toContain("Environment=KANDEV_SERVER_PORT=9000");
});
it("bakes service-state env when metadata path is set", () => {
const unit = renderSystemdUnit({
launcher: NPM_LAUNCHER,
homeDir: "/home/alice/.kandev",
logDir: "/home/alice/.kandev/logs",
mode: "user",
serviceMetadataPath: "/home/alice/.kandev/service/install.json",
} as Parameters<typeof renderSystemdUnit>[0]);
expect(unit).toContain("Environment=KANDEV_RUNNING_AS_SERVICE=true");
expect(unit).toContain("Environment=KANDEV_SERVICE_MODE=user");
expect(unit).toContain("Environment=KANDEV_SERVICE_MANAGER=systemd");
expect(unit).toContain("Environment=KANDEV_INSTALL_KIND=npm");
expect(unit).toContain(
"Environment=KANDEV_SERVICE_METADATA=/home/alice/.kandev/service/install.json",
);
});
it("prepends launcher node bin dir to PATH so npx-based agents resolve under fnm/nvm/asdf/volta/mise", () => {
const unit = renderSystemdUnit({
launcher: FNM_LAUNCHER,
@@ -409,6 +426,26 @@ describe("renderLaunchdPlist", () => {
expect(plist).toContain("KANDEV_VERSION");
});
it("bakes service-state env when metadata path is set", () => {
const plist = renderLaunchdPlist({
launcher: NPM_LAUNCHER,
homeDir: "/Users/alice/.kandev",
logDir: "/Users/alice/.kandev/logs",
mode: "user",
serviceMetadataPath: "/Users/alice/.kandev/service/install.json",
} as Parameters<typeof renderLaunchdPlist>[0]);
expect(plist).toContain("<key>KANDEV_RUNNING_AS_SERVICE</key>");
expect(plist).toContain("<string>true</string>");
expect(plist).toContain("<key>KANDEV_SERVICE_MODE</key>");
expect(plist).toContain("<string>user</string>");
expect(plist).toContain("<key>KANDEV_SERVICE_MANAGER</key>");
expect(plist).toContain("<string>launchd</string>");
expect(plist).toContain("<key>KANDEV_INSTALL_KIND</key>");
expect(plist).toContain("<string>npm</string>");
expect(plist).toContain("<key>KANDEV_SERVICE_METADATA</key>");
expect(plist).toContain("<string>/Users/alice/.kandev/service/install.json</string>");
});
it("quotes Environment= lines when value contains a space (greptile P1 regression)", () => {
const unit = renderSystemdUnit({
launcher: NPM_LAUNCHER,
+26
View File
@@ -17,6 +17,8 @@ export type UnitInputs = {
systemUser?: string;
/** Mode controls WantedBy and User= directives. */
mode: "user" | "system";
/** Absolute path to service install metadata, baked into managed units. */
serviceMetadataPath?: string;
};
// User-mode PATH includes ~/.local/bin and ~/.bun/bin so user-installed agent
@@ -96,6 +98,9 @@ export function renderSystemdUnit(input: UnitInputs): string {
if (!shimPath && input.launcher.version) {
env.push(envLine("KANDEV_VERSION", input.launcher.version));
}
if (input.serviceMetadataPath) {
env.push(...serviceEnvLines(input, "systemd"));
}
const wantedBy = input.mode === "system" ? "multi-user.target" : "default.target";
const userLine = input.mode === "system" && input.systemUser ? `User=${input.systemUser}\n` : "";
@@ -151,6 +156,9 @@ export function renderLaunchdPlist(input: UnitInputs): string {
if (!shimPath && input.launcher.version) {
envEntries.push(["KANDEV_VERSION", input.launcher.version]);
}
if (input.serviceMetadataPath) {
envEntries.push(...serviceEnvEntries(input, "launchd"));
}
const envXml = envEntries
.map(([k, v]) => ` <key>${escapeXml(k)}</key>\n <string>${escapeXml(v)}</string>`)
@@ -229,3 +237,21 @@ function envLine(key: string, value: string): string {
const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return `Environment="${key}=${escaped}"`;
}
function serviceEnvLines(input: UnitInputs, manager: "systemd" | "launchd"): string[] {
return serviceEnvEntries(input, manager).map(([key, value]) => envLine(key, value));
}
function serviceEnvEntries(
input: UnitInputs,
manager: "systemd" | "launchd",
): Array<[string, string]> {
if (!input.serviceMetadataPath) return [];
return [
["KANDEV_RUNNING_AS_SERVICE", "true"],
["KANDEV_SERVICE_MODE", input.mode],
["KANDEV_SERVICE_MANAGER", manager],
["KANDEV_INSTALL_KIND", input.launcher.kind],
["KANDEV_SERVICE_METADATA", input.serviceMetadataPath],
];
}
+6 -2
View File
@@ -15,7 +15,7 @@ import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { DATA_DIR, HEALTH_TIMEOUT_MS_RELEASE } from "./constants";
import { HEALTH_TIMEOUT_MS_RELEASE, resolveDataDir, resolveDatabasePath } from "./constants";
import { resolveHealthTimeoutMs, waitForHealth, waitForUrlReady } from "./health";
import { getBinaryName } from "./platform";
import { createProcessSupervisor } from "./process";
@@ -154,7 +154,11 @@ export async function runStart({
// Production mode: use warn log level for clean output unless verbose/debug
const showOutput = verbose || debug;
const dbPath = process.env.KANDEV_DATABASE_PATH || path.join(DATA_DIR, "kandev.db");
fs.mkdirSync(resolveDataDir(), { recursive: true });
// The data dir holds the SQLite DB; keep it owner-only even if it pre-existed
// with a looser umask-derived mode.
fs.chmodSync(resolveDataDir(), 0o700);
const dbPath = resolveDatabasePath();
const logLevel =
process.env.KANDEV_LOG_LEVEL?.trim() || (debug ? "debug" : verbose ? "info" : "warn");
const backendEnv = buildBackendEnv({