Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add daemon self-update

Gus970d7f7331d4
diff --git a/src/daemon/src/cli/daemonRunner.ts b/src/daemon/src/cli/daemonRunner.ts
index 3aca41655..edffe7097 100644
--- a/src/daemon/src/cli/daemonRunner.ts
+++ b/src/daemon/src/cli/daemonRunner.ts
@@ -22,6 +22,7 @@ import { createLogger, type Logger } from "../logger.js";
import { UnknownRuntimeError } from "../manager/agentRouter.js";
import { scrubRuntimeErrorDiagnosticText } from "../runtime/errorDiagnostics.js";
import { createRotatingFileSink, type RotatingFileSink } from "../util/rotatingFileSink.js";
+import { createDaemonSelfUpdateHandler } from "./daemonUpdate.js";
const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach", "friend"];
export const DAEMON_LOG_MAX_BYTES = 8 * 1024 * 1024;
@@ -327,6 +328,13 @@ export async function runPreparedDaemon(
try {
logDaemonStartup(log, prepared);
+ const handleSelfUpdate = createDaemonSelfUpdateHandler({
+ machineId: prepared.machineId,
+ baseDir: prepared.baseDir,
+ pid: process.pid,
+ startedAt: prepared.startedAt,
+ ownerToken: prepared.ownerToken,
+ }, { logger: log });
daemon = await createDaemon({
machineKey: prepared.machineKey,
serverUrl: prepared.serverUrl,
@@ -352,6 +360,7 @@ export async function runPreparedDaemon(
osRelease: prepared.osRelease,
daemonVersion: prepared.daemonVersion,
logger: log,
+ handleSelfUpdate,
handleDiagnosticCommand,
reportDiagnosticFailure,
onDiagnosticSources: ({ fsmTraceSource, statusFilePath }) => {
diff --git a/src/daemon/src/cli/daemonSelfUpdate.real.test.ts b/src/daemon/src/cli/daemonSelfUpdate.real.test.ts
new file mode 100644
index 000000000..958b8b829
--- /dev/null
+++ b/src/daemon/src/cli/daemonSelfUpdate.real.test.ts
@@ -0,0 +1,345 @@
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { execFile, execFileSync } from "node:child_process";
+import * as fs from "node:fs";
+import * as http from "node:http";
+import * as os from "node:os";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+import { WebSocket, WebSocketServer } from "ws";
+
+const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
+const machineId = "cm_self_update_real_123456";
+const credential = "cmk_REAL_SELF_UPDATE_SECRET";
+const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "daemon-self-update-fixtures-"));
+const baseDirs = new Set<string>();
+let oldTgz = "";
+let newTgz = "";
+
+interface ReadyObservation {
+ socket: WebSocket;
+ frame: { type: "ready"; daemonVersion: string };
+}
+
+interface ControlServer {
+ serverUrl: string;
+ wsUrl: string;
+ ready: ReadyObservation[];
+ close(): Promise<void>;
+}
+
+function packFixture(version: string): string {
+ const dir = path.join(fixtureRoot, `fixture-${version}`);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.cpSync(path.join(packageRoot, "dist"), path.join(dir, "dist"), { recursive: true });
+ const sourcePackage = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
+ fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({
+ name: "@alook/daemon",
+ version,
+ type: "module",
+ main: "./dist/index.js",
+ bin: { "alook-daemon": "dist/cli/index.js" },
+ files: ["dist"],
+ engines: sourcePackage.engines,
+ dependencies: sourcePackage.dependencies,
+ }, null, 2));
+ const packed = JSON.parse(execFileSync("npm", [
+ "pack",
+ "--json",
+ "--ignore-scripts",
+ "--pack-destination",
+ fixtureRoot,
+ ], { cwd: dir, encoding: "utf8" })) as Array<{ filename: string }>;
+ return path.join(fixtureRoot, packed[0]!.filename);
+}
+
+function runNpmPackage(
+ tgz: string,
+ args: string[],
+ env: NodeJS.ProcessEnv = {},
+): Promise<{ code: number | null; output: string }> {
+ return new Promise((resolve, reject) => {
+ execFile("npm", ["exec", "--yes", `--package=${tgz}`, "--", "alook-daemon", ...args], {
+ env: { ...process.env, ...env },
+ maxBuffer: 10 * 1024 * 1024,
+ }, (error, stdout, stderr) => {
+ if (error && typeof (error as NodeJS.ErrnoException & { code?: unknown }).code !== "number") {
+ reject(error);
+ return;
+ }
+ resolve({
+ code: error && typeof (error as NodeJS.ErrnoException & { code?: unknown }).code === "number"
+ ? (error as unknown as { code: number }).code
+ : 0,
+ output: `${stdout}${stderr}`,
+ });
+ });
+ });
+}
+
+async function createControlServer(): Promise<ControlServer> {
+ const ready: ReadyObservation[] = [];
+ const sockets = new Set<WebSocket>();
+ const wss = new WebSocketServer({ noServer: true });
+ const server = http.createServer((request, response) => {
+ response.statusCode = 200;
+ response.setHeader("content-type", "application/json");
+ if (request.url?.includes("/api/community/daemon/bots")) {
+ response.end(JSON.stringify({ bots: [] }));
+ return;
+ }
+ if (request.url?.includes("/api/community/daemon/wakes/resync")) {
+ response.end(JSON.stringify({ woken: 0 }));
+ return;
+ }
+ response.end(JSON.stringify({}));
+ });
+ server.on("upgrade", (request, socket, head) => {
+ wss.handleUpgrade(request, socket, head, (ws) => wss.emit("connection", ws, request));
+ });
+ wss.on("connection", (socket, request) => {
+ expect(request.headers.authorization).toBe(`Bearer ${credential}`);
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ socket.on("message", (raw) => {
+ const frame = JSON.parse(String(raw)) as { type?: string; daemonVersion?: string };
+ if (frame.type === "ready" && typeof frame.daemonVersion === "string") {
+ ready.push({ socket, frame: frame as ReadyObservation["frame"] });
+ }
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("control server did not bind");
+ return {
+ serverUrl: `http://127.0.0.1:${address.port}`,
+ wsUrl: `ws://127.0.0.1:${address.port}/control`,
+ ready,
+ close: async () => {
+ for (const socket of sockets) socket.terminate();
+ await new Promise<void>((resolve) => wss.close(() => resolve()));
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ },
+ };
+}
+
+function makeBaseDir(control: ControlServer, latestPath: string): string {
+ const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "daemon-self-update-real-"));
+ baseDirs.add(baseDir);
+ const daemons = path.join(baseDir, "daemons");
+ const daemonDir = path.join(daemons, machineId);
+ fs.mkdirSync(daemonDir, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(
+ path.join(daemons, `${machineId}.credential.json`),
+ JSON.stringify({ credential, machineId }),
+ { mode: 0o600 },
+ );
+ fs.writeFileSync(
+ path.join(daemonDir, "update-package-map.json"),
+ JSON.stringify({ latest: latestPath, "9.9.0": oldTgz }),
+ { mode: 0o600 },
+ );
+ fs.writeFileSync(path.join(baseDir, "control.json"), JSON.stringify(control), { mode: 0o600 });
+ return baseDir;
+}
+
+function pidfile(baseDir: string): string {
+ return path.join(baseDir, "daemons", machineId, "daemon.pid");
+}
+
+function daemonDir(baseDir: string): string {
+ return path.dirname(pidfile(baseDir));
+}
+
+function readOwner(baseDir: string): { pid: number; machineId: string; startedAt: string; ownerToken: string } {
+ return JSON.parse(fs.readFileSync(pidfile(baseDir), "utf8"));
+}
+
+function alive(pid: number): boolean {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+}
+
+async function waitFor<T>(read: () => T | undefined | false, timeoutMs = 90_000): Promise<T> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const value = read();
+ if (value) return value;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ throw new Error("self-update condition timed out");
+}
+
+async function startOld(baseDir: string, control: ControlServer): Promise<ReadyObservation> {
+ const result = await runNpmPackage(oldTgz, [
+ "daemon", "start",
+ "--machine-key", credential,
+ "--server-url", control.serverUrl,
+ "--ws-url", control.wsUrl,
+ "--base-dir", baseDir,
+ ], { NODE_ENV: "test" });
+ expect(result.code).toBe(0);
+ expect(result.output).toContain("started in background");
+ return await waitFor(() => control.ready.find((entry) => entry.frame.daemonVersion === "9.9.0"));
+}
+
+async function terminateCurrent(baseDir: string): Promise<void> {
+ if (!fs.existsSync(pidfile(baseDir))) return;
+ const owner = readOwner(baseDir);
+ if (alive(owner.pid)) {
+ try { process.kill(owner.pid, "SIGTERM"); } catch { /* best effort */ }
+ await waitFor(() => !alive(owner.pid), 15_000).catch(() => {
+ try { process.kill(owner.pid, "SIGKILL"); } catch { /* best effort */ }
+ return true;
+ });
+ }
+}
+
+function updateEvents(baseDir: string): string[] {
+ const logPath = path.join(daemonDir(baseDir), "update.log");
+ if (!fs.existsSync(logPath)) return [];
+ return fs.readFileSync(logPath, "utf8").split("\n").filter(Boolean).flatMap((line) => {
+ try {
+ const parsed = JSON.parse(line) as { event?: string };
+ return parsed.event ? [parsed.event] : [];
+ } catch {
+ return [];
+ }
+ });
+}
+
+async function waitForUpdateSettled(baseDir: string, timeoutMs = 45_000): Promise<void> {
+ const intent = path.join(daemonDir(baseDir), "update-intent.json");
+ const lock = path.join(daemonDir(baseDir), "daemon.replace.lock");
+ try {
+ await waitFor(() => !fs.existsSync(intent) && !fs.existsSync(lock), timeoutMs);
+ } catch {
+ throw new Error(JSON.stringify({
+ error: "self-update helper did not settle",
+ intentPresent: fs.existsSync(intent),
+ replacementLockPresent: fs.existsSync(lock),
+ events: updateEvents(baseDir),
+ pidfilePresent: fs.existsSync(pidfile(baseDir)),
+ }));
+ }
+}
+
+beforeAll(() => {
+ execFileSync("pnpm", ["run", "build"], { cwd: packageRoot, stdio: "pipe" });
+ oldTgz = packFixture("9.9.0");
+ newTgz = packFixture("9.9.1");
+}, 120_000);
+
+afterEach(async () => {
+ for (const baseDir of baseDirs) await waitForUpdateSettled(baseDir);
+ for (const baseDir of baseDirs) await terminateCurrent(baseDir);
+ for (const baseDir of baseDirs) fs.rmSync(baseDir, { recursive: true, force: true });
+ baseDirs.clear();
+});
+
+afterAll(() => {
+ fs.rmSync(fixtureRoot, { recursive: true, force: true });
+});
+
+describe("daemon self-update real package/process handoff", () => {
+ it("upgrades 9.9.0 to 9.9.1 with a new PID and the same local identity", async () => {
+ const control = await createControlServer();
+ try {
+ const baseDir = makeBaseDir(control, newTgz);
+ const firstReady = await startOld(baseDir, control);
+ const oldOwner = readOwner(baseDir);
+
+ firstReady.socket.send(JSON.stringify({ type: "machine:update" }));
+
+ const nextReady = await waitFor(() => control.ready.find((entry) => entry.frame.daemonVersion === "9.9.1"));
+ expect(nextReady.frame.daemonVersion).toBe("9.9.1");
+ const newOwner = await waitFor(() => {
+ if (!fs.existsSync(pidfile(baseDir))) return false;
+ const owner = readOwner(baseDir);
+ return owner.pid !== oldOwner.pid ? owner : false;
+ });
+ expect(alive(oldOwner.pid)).toBe(false);
+ expect(alive(newOwner.pid)).toBe(true);
+ expect(newOwner.machineId).toBe(oldOwner.machineId);
+ const record = JSON.parse(fs.readFileSync(path.join(baseDir, "daemons", `${machineId}.credential.json`), "utf8"));
+ expect(record).toMatchObject({
+ schemaVersion: 1,
+ credential,
+ machineId,
+ serverUrl: control.serverUrl,
+ wsUrl: control.wsUrl,
+ daemonVersion: "9.9.1",
+ });
+ expect(updateEvents(baseDir)).toContain("replacement_ready");
+ expect(fs.readFileSync(path.join(daemonDir(baseDir), "update.log"), "utf8")).not.toContain(credential);
+ } finally {
+ await control.close();
+ }
+ }, 120_000);
+
+ it("keeps the old PID and socket live when latest maps to a missing tgz", async () => {
+ const control = await createControlServer();
+ try {
+ const baseDir = makeBaseDir(control, path.join(fixtureRoot, "missing-latest.tgz"));
+ const firstReady = await startOld(baseDir, control);
+ const owner = readOwner(baseDir);
+
+ firstReady.socket.send(JSON.stringify({ type: "machine:update" }));
+
+ await waitFor(() => updateEvents(baseDir).includes("helper_spawn_requested"));
+ await waitForUpdateSettled(baseDir);
+ expect(readOwner(baseDir)).toEqual(owner);
+ expect(alive(owner.pid)).toBe(true);
+ expect(firstReady.socket.readyState).toBe(WebSocket.OPEN);
+ expect(control.ready.filter((entry) => entry.frame.daemonVersion === "9.9.1")).toHaveLength(0);
+ } finally {
+ await control.close();
+ }
+ }, 120_000);
+
+ it("rolls back exactly once to 9.9.0 when the new daemon cannot start", async () => {
+ const control = await createControlServer();
+ try {
+ const baseDir = makeBaseDir(control, newTgz);
+ const firstReady = await startOld(baseDir, control);
+ const oldOwner = readOwner(baseDir);
+ fs.writeFileSync(path.join(daemonDir(baseDir), "test-fail-start-9.9.1"), "1", { mode: 0o600 });
+
+ firstReady.socket.send(JSON.stringify({ type: "machine:update" }));
+
+ await waitFor(() => updateEvents(baseDir).includes("rollback_ready"));
+ const rollbackReady = await waitFor(() => control.ready.filter((entry) => entry.frame.daemonVersion === "9.9.0")[1]);
+ expect(rollbackReady.frame.daemonVersion).toBe("9.9.0");
+ const rollbackOwner = readOwner(baseDir);
+ expect(rollbackOwner.pid).not.toBe(oldOwner.pid);
+ expect(alive(oldOwner.pid)).toBe(false);
+ expect(alive(rollbackOwner.pid)).toBe(true);
+ expect(updateEvents(baseDir).filter((event) => event === "replacement_start_failed")).toHaveLength(1);
+ expect(updateEvents(baseDir).filter((event) => event === "rollback_ready")).toHaveLength(1);
+ } finally {
+ await control.close();
+ }
+ }, 120_000);
+
+ it("bounds rollback to one attempt when both new start and rollback fail", async () => {
+ const control = await createControlServer();
+ try {
+ const baseDir = makeBaseDir(control, newTgz);
+ const firstReady = await startOld(baseDir, control);
+ const oldOwner = readOwner(baseDir);
+ fs.writeFileSync(path.join(daemonDir(baseDir), "test-fail-start-9.9.1"), "1", { mode: 0o600 });
+ fs.writeFileSync(path.join(daemonDir(baseDir), "test-fail-start-9.9.0"), "1", { mode: 0o600 });
+
+ firstReady.socket.send(JSON.stringify({ type: "machine:update" }));
+
+ await waitFor(() => updateEvents(baseDir).includes("replacement_terminal_failure"));
+ await waitFor(() => !fs.existsSync(path.join(daemonDir(baseDir), "daemon.replace.lock")));
+ expect(alive(oldOwner.pid)).toBe(false);
+ expect(fs.existsSync(pidfile(baseDir))).toBe(false);
+ expect(updateEvents(baseDir).filter((event) => event === "replacement_start_failed")).toHaveLength(1);
+ expect(updateEvents(baseDir).filter((event) => event === "replacement_terminal_failure")).toHaveLength(1);
+ expect(control.ready.filter((entry) => entry.frame.daemonVersion === "9.9.1")).toHaveLength(0);
+ expect(control.ready.filter((entry) => entry.frame.daemonVersion === "9.9.0")).toHaveLength(1);
+ } finally {
+ await control.close();
+ }
+ }, 120_000);
+});
diff --git a/src/daemon/src/cli/daemonStart.lifecycle.test.ts b/src/daemon/src/cli/daemonStart.lifecycle.test.ts
index b785d7ea4..50f205369 100644
--- a/src/daemon/src/cli/daemonStart.lifecycle.test.ts
+++ b/src/daemon/src/cli/daemonStart.lifecycle.test.ts
@@ -17,6 +17,7 @@ vi.mock("../discovery", async (importOriginal) => ({
}));
import { daemonRunFromIpc, daemonStart } from "./daemonStart";
+import { readDaemonVersion } from "../version";
describe("daemon lifecycle ownership cleanup", () => {
let baseDir: string;
@@ -151,6 +152,77 @@ describe("daemon lifecycle ownership cleanup", () => {
expect(mockRunPreparedDaemon).toHaveBeenCalledOnce();
});
+ it("upgrades a legacy two-field credential record to a private resumable launch record", async () => {
+ const machineId = "cm_machine_init_failure";
+ const recordPath = path.join(baseDir, "daemons", `${machineId}.credential.json`);
+ fs.mkdirSync(path.dirname(recordPath), { recursive: true });
+ fs.writeFileSync(recordPath, JSON.stringify({ credential: "cmk_test", machineId }), { mode: 0o644 });
+
+ await expect(daemonStart({
+ machineKey: "cmk_test",
+ serverUrl: "http://server",
+ wsUrl: "ws://server",
+ baseDir,
+ foreground: true,
+ })).rejects.toThrow("runner init failed");
+
+ expect(JSON.parse(fs.readFileSync(recordPath, "utf8"))).toEqual({
+ schemaVersion: 1,
+ credential: "cmk_test",
+ machineId,
+ serverUrl: "http://server",
+ wsUrl: "ws://server",
+ daemonVersion: readDaemonVersion(),
+ });
+ if (process.platform !== "win32") expect(fs.statSync(recordPath).mode & 0o777).toBe(0o600);
+ });
+
+ it("blocks normal start during replacement and lets only the matching resume request bypass", async () => {
+ const machineId = "cm_machine_init_failure";
+ const daemonsDir = path.join(baseDir, "daemons");
+ const daemonDir = path.join(daemonsDir, machineId);
+ fs.mkdirSync(daemonDir, { recursive: true });
+ fs.writeFileSync(path.join(daemonsDir, `${machineId}.credential.json`), JSON.stringify({
+ schemaVersion: 1,
+ credential: "cmk_test",
+ machineId,
+ serverUrl: "http://server",
+ wsUrl: "ws://server",
+ daemonVersion: readDaemonVersion(),
+ }), { mode: 0o600 });
+ fs.writeFileSync(path.join(daemonDir, "daemon.replace.lock"), JSON.stringify({
+ pid: process.pid,
+ machineId,
+ startedAt: new Date().toISOString(),
+ ownerToken: "replace-owner",
+ requestId: "request_1234567890",
+ }), { mode: 0o600 });
+
+ await expect(daemonStart({
+ machineKey: "cmk_test",
+ serverUrl: "http://server",
+ wsUrl: "ws://server",
+ baseDir,
+ foreground: true,
+ })).rejects.toThrow("replacement already in progress");
+ await expect(daemonStart({
+ machineKey: "cmk_test",
+ serverUrl: "http://server",
+ wsUrl: "ws://server",
+ baseDir,
+ foreground: true,
+ resumeRequestId: "wrong_request_123456",
+ })).rejects.toThrow("replacement already in progress");
+ await expect(daemonStart({
+ machineKey: "cmk_test",
+ serverUrl: "http://server",
+ wsUrl: "ws://server",
+ baseDir,
+ foreground: true,
+ resumeRequestId: "request_1234567890",
+ })).rejects.toThrow("runner init failed");
+ });
+
it.each([
"../../escape",
"/absolute",
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index dfd5fd299..9f2f4c225 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -15,6 +15,7 @@ import { createLogger } from "../logger.js";
import { readDaemonVersion } from "../version.js";
import { runPreparedDaemon, type DaemonReadyReceipt, type PreparedDaemon } from "./daemonRunner.js";
import { spawn, type ChildProcess } from "node:child_process";
+import { parseReleaseVersion } from "@alook/shared";
/**
* Grace window for a daemon to exit on SIGTERM before we escalate to SIGKILL.
@@ -63,7 +64,7 @@ function daemonsDir(baseDir: string): string {
* `daemon list` shows / `daemon stop <id>` takes. See
* plans/daemon-c01-machineid-anchor.md.
*/
-function daemonDirById(baseDir: string, id: string): string {
+export function daemonDirById(baseDir: string, id: string): string {
return path.join(daemonsDir(baseDir), validateDaemonId(id));
}
@@ -81,7 +82,7 @@ function validateDaemonId(id: string): string {
return id;
}
-function pidfilePathById(baseDir: string, id: string): string {
+export function pidfilePathById(baseDir: string, id: string): string {
return path.join(daemonDirById(baseDir, id), "daemon.pid");
}
@@ -116,6 +117,14 @@ export interface DaemonPidFile {
key?: string;
}
+export interface DaemonReplacementLock {
+ pid: number;
+ machineId: string;
+ startedAt: string;
+ ownerToken: string;
+ requestId: string;
+}
+
function parsePidFileContent(raw: string): DaemonPidFile | null {
try {
const content = JSON.parse(raw);
@@ -160,7 +169,7 @@ function syncDirectory(dir: string): void {
}
}
-function writeExclusive(filePath: string, value: Record<string, unknown>): void {
+function writeExclusive(filePath: string, value: object): void {
const dir = path.dirname(filePath);
ensurePrivateDir(dir);
const tempPath = path.join(
@@ -184,6 +193,30 @@ function writeExclusive(filePath: string, value: Record<string, unknown>): void
}
}
+function writePrivateJsonAtomic(filePath: string, value: object): void {
+ const dir = path.dirname(filePath);
+ ensurePrivateDir(dir);
+ const tempPath = path.join(
+ dir,
+ `.${path.basename(filePath)}.${process.pid}.${crypto.randomBytes(12).toString("hex")}.tmp`,
+ );
+ let fd: number | null = fs.openSync(tempPath, "wx", 0o600);
+ try {
+ fs.writeFileSync(fd, JSON.stringify(value));
+ fs.fsyncSync(fd);
+ fs.closeSync(fd);
+ fd = null;
+ fs.chmodSync(tempPath, 0o600);
+ fs.renameSync(tempPath, filePath);
+ syncDirectory(dir);
+ } finally {
+ if (fd !== null) {
+ try { fs.closeSync(fd); } catch { /* best effort */ }
+ }
+ try { fs.unlinkSync(tempPath); } catch { /* best effort */ }
+ }
+}
+
function secureExistingFile(filePath: string): void {
if (!fs.existsSync(filePath)) return;
const stat = fs.lstatSync(filePath);
@@ -256,6 +289,117 @@ function clearStaleOwnership(filePath: string, liveError: (pid: number) => Error
} catch { /* best effort */ }
}
+export function replacementLockPathById(baseDir: string, machineId: string): string {
+ return path.join(daemonDirById(baseDir, machineId), "daemon.replace.lock");
+}
+
+export function readReplacementLock(filePath: string): DaemonReplacementLock | null {
+ if (!fs.existsSync(filePath)) return null;
+ try {
+ const stat = fs.lstatSync(filePath);
+ if (!stat.isFile()) throw new Error("unsafe daemon replacement lock type");
+ fs.chmodSync(filePath, 0o600);
+ const content = JSON.parse(fs.readFileSync(filePath, "utf8")) as Partial<DaemonReplacementLock>;
+ if (
+ !Number.isInteger(content.pid)
+ || (content.pid ?? 0) <= 0
+ || typeof content.machineId !== "string"
+ || typeof content.startedAt !== "string"
+ || typeof content.ownerToken !== "string"
+ || typeof content.requestId !== "string"
+ ) return null;
+ return content as DaemonReplacementLock;
+ } catch (error) {
+ if (error instanceof SyntaxError) return null;
+ throw error;
+ }
+}
+
+function replacementLocksEqual(a: DaemonReplacementLock, b: DaemonReplacementLock): boolean {
+ return a.pid === b.pid
+ && a.machineId === b.machineId
+ && a.startedAt === b.startedAt
+ && a.ownerToken === b.ownerToken
+ && a.requestId === b.requestId;
+}
+
+export function removeReplacementLockIfMatches(
+ filePath: string,
+ expected: DaemonReplacementLock,
+): void {
+ try {
+ const current = readReplacementLock(filePath);
+ if (current && replacementLocksEqual(current, expected)) fs.unlinkSync(filePath);
+ } catch { /* best effort */ }
+}
+
+function checkReplacementLock(
+ baseDir: string,
+ machineId: string,
+ resumeRequestId?: string,
+): void {
+ const lockPath = replacementLockPathById(baseDir, machineId);
+ if (!fs.existsSync(lockPath)) return;
+ const lock = readReplacementLock(lockPath);
+ if (!lock) {
+ let before: fs.Stats;
+ let raw: string;
+ try {
+ before = fs.statSync(lockPath);
+ raw = fs.readFileSync(lockPath, "utf8");
+ const afterRead = fs.statSync(lockPath);
+ if (
+ afterRead.dev !== before.dev
+ || afterRead.ino !== before.ino
+ || afterRead.size !== before.size
+ || afterRead.mtimeMs !== before.mtimeMs
+ ) throw new Error(`daemon '${machineId}' replacement lock changed during recovery`);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return;
+ throw error;
+ }
+ const pid = malformedPidHint(raw);
+ if (pid && isProcessAlive(pid)) {
+ throw new Error(`daemon '${machineId}' replacement lock is malformed but owned by live pid ${pid}`);
+ }
+ try {
+ const current = fs.statSync(lockPath);
+ if (
+ current.dev === before.dev
+ && current.ino === before.ino
+ && current.size === before.size
+ && current.mtimeMs === before.mtimeMs
+ ) fs.unlinkSync(lockPath);
+ } catch { /* best effort */ }
+ return;
+ }
+ if (!isProcessAlive(lock.pid)) {
+ removeReplacementLockIfMatches(lockPath, lock);
+ return;
+ }
+ if (resumeRequestId && lock.requestId === resumeRequestId) return;
+ throw new Error(`daemon '${machineId}' replacement already in progress (pid ${lock.pid})`);
+}
+
+export function acquireDaemonReplacementLock(args: {
+ baseDir: string;
+ machineId: string;
+ requestId: string;
+}): { path: string; lock: DaemonReplacementLock } {
+ const lockPath = replacementLockPathById(args.baseDir, args.machineId);
+ ensurePrivateDir(path.dirname(lockPath));
+ checkReplacementLock(args.baseDir, args.machineId);
+ const lock: DaemonReplacementLock = {
+ pid: process.pid,
+ machineId: args.machineId,
+ startedAt: new Date().toISOString(),
+ ownerToken: crypto.randomBytes(24).toString("base64url"),
+ requestId: args.requestId,
+ };
+ writeExclusive(lockPath, lock);
+ return { path: lockPath, lock };
+}
+
/**
* COARSE start-lock for the `cmt_` path (C0.1): the machineId isn't known until
* after async `/activate`, so this baseDir-level lock blocks a concurrent local
@@ -275,11 +419,17 @@ function acquireCoarseLock(baseDir: string, ownerToken: string): string {
return lf;
}
-function acquireLaunchLock(baseDir: string, machineId: string, ownerToken: string): string {
+function acquireLaunchLock(
+ baseDir: string,
+ machineId: string,
+ ownerToken: string,
+ resumeRequestId?: string,
+): string {
const daemonDir = daemonDirById(baseDir, machineId);
ensurePrivateDir(daemonDir);
const lockPath = path.join(daemonDir, "daemon.launch.lock");
const finalPath = pidfilePathById(baseDir, machineId);
+ checkReplacementLock(baseDir, machineId, resumeRequestId);
secureExistingFile(lockPath);
secureExistingFile(finalPath);
clearStaleOwnership(finalPath, (pid) => new Error(`daemon '${machineId}' already running (pid ${pid})`));
@@ -523,6 +673,30 @@ export interface DaemonStopOpts {
* UNCHANGED by stop-by-id (plans/daemon-cli-humanize-charter.md red line 3) —
* only HOW the daemon is addressed changed (its list id, not a machine key).
*/
+async function stopExactPid(pid: number): Promise<void> {
+ try {
+ process.kill(pid, "SIGTERM");
+ } catch (error) {
+ if (isProcessAlive(pid)) throw error;
+ }
+
+ if (!await waitForPidExit(pid, STOP_GRACE_MS)) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch (error) {
+ if (isProcessAlive(pid)) throw error;
+ }
+ if (!await waitForPidExit(pid, STOP_KILL_GRACE_MS)) {
+ throw new Error(`daemon (pid ${pid}) is still running after SIGKILL`);
+ }
+ }
+}
+
+export async function stopExactDaemonPid(pid: number): Promise<void> {
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error("invalid daemon pid");
+ await stopExactPid(pid);
+}
+
async function stopByPidfile(pf: string, notFoundHint: string): Promise<void> {
const data = readPidFile(pf);
@@ -537,23 +711,7 @@ async function stopByPidfile(pf: string, notFoundHint: string): Promise<void> {
}
log.info(`sending SIGTERM to daemon (pid ${data.pid})…`);
- try {
- process.kill(data.pid, "SIGTERM");
- } catch (error) {
- if (isProcessAlive(data.pid)) throw error;
- }
-
- if (!await waitForPidExit(data.pid, STOP_GRACE_MS)) {
- log.error(`daemon (pid ${data.pid}) did not exit in ${STOP_GRACE_MS / 1000}s — sending SIGKILL`);
- try {
- process.kill(data.pid, "SIGKILL");
- } catch (error) {
- if (isProcessAlive(data.pid)) throw error;
- }
- if (!await waitForPidExit(data.pid, STOP_KILL_GRACE_MS)) {
- throw new Error(`daemon (pid ${data.pid}) is still running after SIGKILL`);
- }
- }
+ await stopExactPid(data.pid);
log.info("daemon stopped");
removePidFileIfMatches(pf, data);
}
@@ -579,6 +737,17 @@ export interface DaemonStartOpts {
wsUrl?: string;
baseDir?: string;
foreground?: boolean;
+ /** Internal-only replacement lock bypass. Never exposed on normal start. */
+ resumeRequestId?: string;
+}
+
+export interface DaemonLaunchRecord {
+ schemaVersion: 1;
+ credential: string;
+ machineId: string;
+ serverUrl: string;
+ wsUrl: string;
+ daemonVersion: string;
}
/**
@@ -591,7 +760,7 @@ export function credentialFilePathByMachineId(baseDir: string, machineId: string
return path.join(daemonsDir(baseDir), `${validateMachineId(machineId)}.credential.json`);
}
-function readCredentialFile(filePath: string): { credential: string; machineId: string } | null {
+function readCredentialFile(filePath: string): (DaemonLaunchRecord | { credential: string; machineId: string }) | null {
if (!fs.existsSync(filePath)) return null;
const stat = fs.lstatSync(filePath);
if (!stat.isFile()) throw new Error("unsafe daemon credential file type");
@@ -603,34 +772,44 @@ function readCredentialFile(filePath: string): { credential: string; machineId:
content.credential.startsWith("cmk_") &&
typeof content.machineId === "string"
) {
+ if (
+ content.schemaVersion === 1
+ && typeof content.serverUrl === "string"
+ && typeof content.wsUrl === "string"
+ && typeof content.daemonVersion === "string"
+ ) {
+ return {
+ schemaVersion: 1,
+ credential: content.credential,
+ machineId: content.machineId,
+ serverUrl: content.serverUrl,
+ wsUrl: content.wsUrl,
+ daemonVersion: content.daemonVersion,
+ };
+ }
return { credential: content.credential, machineId: content.machineId };
}
} catch { /* malformed */ }
return null;
}
-function writeCredentialFile(filePath: string, credential: string, machineId: string): void {
- const dir = path.dirname(filePath);
- ensurePrivateDir(dir);
- const tempPath = path.join(
- dir,
- `.${path.basename(filePath)}.${process.pid}.${crypto.randomBytes(12).toString("hex")}.tmp`,
- );
- let fd: number | null = fs.openSync(tempPath, "wx", 0o600);
- try {
- fs.writeFileSync(fd, JSON.stringify({ credential, machineId }));
- fs.fsyncSync(fd);
- fs.closeSync(fd);
- fd = null;
- fs.chmodSync(tempPath, 0o600);
- fs.renameSync(tempPath, filePath);
- syncDirectory(dir);
- } finally {
- if (fd !== null) {
- try { fs.closeSync(fd); } catch { /* best effort */ }
- }
- try { fs.unlinkSync(tempPath); } catch { /* best effort */ }
+function writeCredentialFile(filePath: string, record: DaemonLaunchRecord): void {
+ writePrivateJsonAtomic(filePath, record);
+}
+
+export function readDaemonLaunchRecord(baseDir: string, machineId: string): DaemonLaunchRecord {
+ const record = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
+ if (
+ !record
+ || !("schemaVersion" in record)
+ || record.schemaVersion !== 1
+ || !parseReleaseVersion(record.daemonVersion)
+ ) {
+ throw new Error("daemon launch record is missing or requires a manual start upgrade");
}
+ validateMachineId(record.machineId);
+ if (record.machineId !== machineId) throw new Error("daemon launch record machine mismatch");
+ return record;
}
/**
@@ -712,6 +891,8 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>
throw new Error("invalid machine key format — expected `cmt_` or `cmk_`");
}
const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
+ const daemonVersion = readDaemonVersion();
+ if (!parseReleaseVersion(daemonVersion)) throw new Error("daemon package version is not a strict release version");
const ownerToken = crypto.randomBytes(24).toString("base64url");
const persisted = opts.machineKey.startsWith("cmk_")
? findExistingCredentialForBearer(baseDir, opts.machineKey)
@@ -722,7 +903,7 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>
let machineKey = persisted?.credential;
let machineId = persisted ? validateMachineId(persisted.machineId) : undefined;
if (machineKey && machineId) {
- launchLockPath = acquireLaunchLock(baseDir, machineId, ownerToken);
+ launchLockPath = acquireLaunchLock(baseDir, machineId, ownerToken, opts.resumeRequestId);
} else {
coarseLockPath = acquireCoarseLock(baseDir, ownerToken);
if (opts.machineKey.startsWith("cmk_")) {
@@ -741,7 +922,7 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>
process.platform,
process.arch,
os.release(),
- readDaemonVersion(),
+ daemonVersion,
runtimeReport,
);
machineKey = activated.credential;
@@ -750,8 +931,15 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>
machineKey ??= opts.machineKey;
machineId ??= validateMachineId(await resolveMachineIdentity(serverUrl, opts.machineKey));
}
- writeCredentialFile(credentialFilePathByMachineId(baseDir, machineId), machineKey, machineId);
- launchLockPath ??= acquireLaunchLock(baseDir, machineId, ownerToken);
+ launchLockPath ??= acquireLaunchLock(baseDir, machineId, ownerToken, opts.resumeRequestId);
+ writeCredentialFile(credentialFilePathByMachineId(baseDir, machineId), {
+ schemaVersion: 1,
+ credential: machineKey,
+ machineId,
+ serverUrl,
+ wsUrl,
+ daemonVersion,
+ });
if (coarseLockPath) removeOwnedFile(coarseLockPath, process.pid, ownerToken);
const startedAt = new Date().toISOString();
return {
@@ -771,7 +959,7 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>
platform: process.platform,
arch: process.arch,
osRelease: os.release(),
- daemonVersion: readDaemonVersion(),
+ daemonVersion,
ownerToken,
startedAt,
},
@@ -783,6 +971,29 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>
}
}
+export async function daemonResume(opts: {
+ id: string;
+ baseDir?: string;
+ requestId: string;
+}): Promise<void> {
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(opts.requestId)) throw new Error("invalid replacement request id");
+ const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
+ const record = readDaemonLaunchRecord(baseDir, opts.id);
+ if (
+ process.env.NODE_ENV === "test"
+ && fs.existsSync(path.join(daemonDirById(baseDir, opts.id), `test-fail-start-${readDaemonVersion()}`))
+ ) {
+ throw new Error("test-gated daemon resume failure");
+ }
+ await daemonStart({
+ machineKey: record.credential,
+ serverUrl: record.serverUrl,
+ wsUrl: record.wsUrl,
+ baseDir,
+ resumeRequestId: opts.requestId,
+ });
+}
+
function runnerArguments(): string[] {
const command = process.env.ALOOK_DAEMON_PACKAGE_WRAPPER === "1" ? ["run"] : ["daemon", "run"];
return [...process.execArgv, process.argv[1]!, ...command];
diff --git a/src/daemon/src/cli/daemonUpdate.test.ts b/src/daemon/src/cli/daemonUpdate.test.ts
new file mode 100644
index 000000000..378d8a666
--- /dev/null
+++ b/src/daemon/src/cli/daemonUpdate.test.ts
@@ -0,0 +1,205 @@
+import { EventEmitter } from "node:events";
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+import type { ChildProcess } from "node:child_process";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { readDaemonVersion } from "../version";
+import { createDaemonSelfUpdateHandler, daemonReplace } from "./daemonUpdate";
+
+const machineId = "cm_update_unit_123456";
+
+function fakeChild(): ChildProcess {
+ const child = new EventEmitter() as ChildProcess;
+ Object.assign(child, {
+ exitCode: null,
+ signalCode: null,
+ unref: vi.fn(),
+ });
+ return child;
+}
+
+describe("daemon self-update lifecycle", () => {
+ let baseDir: string;
+ let daemonDir: string;
+ let npmPath: string;
+
+ beforeEach(() => {
+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "daemon-update-unit-"));
+ daemonDir = path.join(baseDir, "daemons", machineId);
+ fs.mkdirSync(daemonDir, { recursive: true, mode: 0o700 });
+ npmPath = path.join(baseDir, "npm-cli.js");
+ fs.writeFileSync(npmPath, "", { mode: 0o600 });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ fs.rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ function writePid(ownerToken = "owner-secret") {
+ const owner = {
+ pid: 424_242,
+ machineId,
+ startedAt: "2026-08-13T08:00:00.000Z",
+ ownerToken,
+ };
+ fs.writeFileSync(path.join(daemonDir, "daemon.pid"), JSON.stringify(owner), { mode: 0o600 });
+ return owner;
+ }
+
+ function writeLaunch(version: string) {
+ fs.writeFileSync(
+ path.join(baseDir, "daemons", `${machineId}.credential.json`),
+ JSON.stringify({
+ schemaVersion: 1,
+ credential: "cmk_UNIT_TEST_SECRET",
+ machineId,
+ serverUrl: "http://server",
+ wsUrl: "ws://server",
+ daemonVersion: version,
+ }),
+ { mode: 0o600 },
+ );
+ }
+
+ it("spawns one fixed latest helper, persists the full tuple, and becomes retryable after early exit", () => {
+ const owner = writePid();
+ const children = [fakeChild(), fakeChild()];
+ const spawnProcess = vi.fn(() => children.shift()!);
+ const handle = createDaemonSelfUpdateHandler({
+ machineId,
+ baseDir,
+ pid: owner.pid,
+ startedAt: owner.startedAt,
+ ownerToken: owner.ownerToken,
+ }, { spawnProcess: spawnProcess as typeof import("node:child_process").spawn, npmExecPath: npmPath });
+
+ handle();
+ handle();
+
+ expect(spawnProcess).toHaveBeenCalledTimes(1);
+ const [command, args, options] = spawnProcess.mock.calls[0]!;
+ expect(command).toBe(process.execPath);
+ expect(args).toEqual([
+ npmPath,
+ "exec",
+ "--yes",
+ "--package=@alook/daemon@latest",
+ "--",
+ "alook-daemon",
+ "daemon",
+ "replace",
+ "--id",
+ machineId,
+ "--base-dir",
+ baseDir,
+ "--request-id",
+ expect.stringMatching(/^[A-Za-z0-9_-]{16,128}$/),
+ ]);
+ expect(options).toMatchObject({ detached: true, shell: false });
+ const serializedInvocation = JSON.stringify([command, args, options]);
+ expect(serializedInvocation).not.toContain("cmk_UNIT_TEST_SECRET");
+ expect(serializedInvocation).not.toContain(owner.ownerToken);
+
+ const intentPath = path.join(daemonDir, "update-intent.json");
+ const intent = JSON.parse(fs.readFileSync(intentPath, "utf8"));
+ expect(intent).toMatchObject({ schemaVersion: 1, ...owner });
+ if (process.platform !== "win32") expect(fs.statSync(intentPath).mode & 0o777).toBe(0o600);
+
+ const first = spawnProcess.mock.results[0]!.value as ChildProcess;
+ first.emit("exit", 1, null);
+ handle();
+ expect(spawnProcess).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not spawn when only the pidfile ownerToken differs from the running owner", () => {
+ const diskOwner = writePid("replacement-owner");
+ const spawnProcess = vi.fn(() => fakeChild());
+ const kill = vi.spyOn(process, "kill");
+ const handle = createDaemonSelfUpdateHandler({
+ machineId,
+ baseDir,
+ pid: diskOwner.pid,
+ startedAt: diskOwner.startedAt,
+ ownerToken: "original-running-owner",
+ }, { spawnProcess: spawnProcess as typeof import("node:child_process").spawn, npmExecPath: npmPath });
+
+ handle();
+
+ expect(spawnProcess).not.toHaveBeenCalled();
+ expect(kill).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(daemonDir, "update-intent.json"))).toBe(false);
+ });
+
+ it("keeps ownership untouched when the npm launch context is unavailable", () => {
+ const owner = writePid();
+ const spawnProcess = vi.fn(() => fakeChild());
+ const handle = createDaemonSelfUpdateHandler({
+ machineId,
+ baseDir,
+ pid: owner.pid,
+ startedAt: owner.startedAt,
+ ownerToken: owner.ownerToken,
+ }, {
+ spawnProcess: spawnProcess as typeof import("node:child_process").spawn,
+ npmExecPath: path.join(baseDir, "missing-npm-cli.js"),
+ });
+
+ handle();
+
+ expect(spawnProcess).not.toHaveBeenCalled();
+ expect(JSON.parse(fs.readFileSync(path.join(daemonDir, "daemon.pid"), "utf8"))).toEqual(owner);
+ expect(fs.existsSync(path.join(daemonDir, "update-intent.json"))).toBe(false);
+ });
+
+ it.each([
+ ["pid", { pid: 424_243 }],
+ ["machineId", { machineId: "cm_update_other_123456" }],
+ ["startedAt", { startedAt: "2026-08-13T08:01:00.000Z" }],
+ ["ownerToken", { ownerToken: "new-owner" }],
+ ])("refuses a late helper whose %s tuple field changed without signaling", async (_field, change) => {
+ const intentOwner = writePid("old-owner");
+ writeLaunch("0.0.1");
+ const requestId = "request_1234567890";
+ fs.writeFileSync(path.join(daemonDir, "update-intent.json"), JSON.stringify({
+ schemaVersion: 1,
+ requestId,
+ ...intentOwner,
+ }), { mode: 0o600 });
+ fs.writeFileSync(path.join(daemonDir, "daemon.pid"), JSON.stringify({
+ ...intentOwner,
+ ...change,
+ }), { mode: 0o600 });
+ vi.stubEnv("npm_execpath", npmPath);
+ const kill = vi.spyOn(process, "kill");
+
+ await expect(daemonReplace({ id: machineId, baseDir, requestId })).rejects.toThrow(
+ "ownership changed before replacement",
+ );
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["same", readDaemonVersion()],
+ ["older", "99.0.0"],
+ ])("keeps the old daemon alive when the loaded helper is %s", async (_case, recordedVersion) => {
+ const owner = writePid();
+ writeLaunch(recordedVersion);
+ const requestId = "request_1234567890";
+ fs.writeFileSync(path.join(daemonDir, "update-intent.json"), JSON.stringify({
+ schemaVersion: 1,
+ requestId,
+ ...owner,
+ }), { mode: 0o600 });
+ vi.stubEnv("npm_execpath", npmPath);
+ const kill = vi.spyOn(process, "kill");
+
+ await daemonReplace({ id: machineId, baseDir, requestId });
+
+ expect(kill).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(daemonDir, "daemon.pid"))).toBe(true);
+ expect(fs.existsSync(path.join(daemonDir, "update-intent.json"))).toBe(false);
+ });
+});
diff --git a/src/daemon/src/cli/daemonUpdate.ts b/src/daemon/src/cli/daemonUpdate.ts
new file mode 100644
index 000000000..61f5f1350
--- /dev/null
+++ b/src/daemon/src/cli/daemonUpdate.ts
@@ -0,0 +1,394 @@
+import * as crypto from "node:crypto";
+import * as fs from "node:fs";
+import * as path from "node:path";
+import { spawn, type ChildProcess } from "node:child_process";
+import { parseReleaseVersion, releaseVersionGte } from "@alook/shared";
+import { readDaemonVersion } from "../version.js";
+import type { Logger } from "../logger.js";
+import {
+ acquireDaemonReplacementLock,
+ daemonDirById,
+ daemonResume,
+ pidfilePathById,
+ readDaemonLaunchRecord,
+ readPidFile,
+ removeReplacementLockIfMatches,
+ stopExactDaemonPid,
+ type DaemonPidFile,
+} from "./daemonStart.js";
+
+const UPDATE_INTENT_SCHEMA_VERSION = 1;
+const UPDATE_LOG_MAX_BYTES = 512 * 1024;
+const UPDATE_LOG_KEEP_BYTES = 256 * 1024;
+const REQUEST_ID_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
+
+export interface DaemonUpdateIntent {
+ schemaVersion: 1;
+ requestId: string;
+ pid: number;
+ machineId: string;
+ startedAt: string;
+ ownerToken: string;
+}
+
+export interface DaemonSelfUpdateContext {
+ machineId: string;
+ baseDir: string;
+ pid: number;
+ startedAt: string;
+ ownerToken: string;
+}
+
+export interface SelfUpdateDeps {
+ spawnProcess?: typeof spawn;
+ npmExecPath?: string;
+ logger?: Pick<Logger, "info" | "warn">;
+}
+
+function intentPath(baseDir: string, machineId: string): string {
+ return path.join(daemonDirById(baseDir, machineId), "update-intent.json");
+}
+
+export function updateLogPath(baseDir: string, machineId: string): string {
+ return path.join(daemonDirById(baseDir, machineId), "update.log");
+}
+
+export function updatePackageMapPath(baseDir: string, machineId: string): string {
+ return path.join(daemonDirById(baseDir, machineId), "update-package-map.json");
+}
+
+function ensurePrivateDir(dir: string): void {
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ fs.chmodSync(dir, 0o700);
+}
+
+function writePrivateJsonAtomic(filePath: string, value: object): void {
+ const dir = path.dirname(filePath);
+ ensurePrivateDir(dir);
+ const tempPath = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`);
+ let fd: number | null = fs.openSync(tempPath, "wx", 0o600);
+ try {
+ fs.writeFileSync(fd, JSON.stringify(value));
+ fs.fsyncSync(fd);
+ fs.closeSync(fd);
+ fd = null;
+ fs.chmodSync(tempPath, 0o600);
+ fs.renameSync(tempPath, filePath);
+ } finally {
+ if (fd !== null) {
+ try { fs.closeSync(fd); } catch { /* best effort */ }
+ }
+ try { fs.unlinkSync(tempPath); } catch { /* best effort */ }
+ }
+}
+
+function scrub(value: unknown): string {
+ return (value instanceof Error ? value.message : String(value))
+ .replace(/\b(?:cmk|cmt)_[A-Za-z0-9_-]+\b/g, "[redacted-token]")
+ .replace(/[\r\n]+/g, " ")
+ .slice(0, 1_024);
+}
+
+function appendUpdateLog(baseDir: string, machineId: string, event: string, fields: Record<string, unknown> = {}): void {
+ const filePath = updateLogPath(baseDir, machineId);
+ ensurePrivateDir(path.dirname(filePath));
+ try {
+ if (fs.existsSync(filePath) && fs.statSync(filePath).size > UPDATE_LOG_MAX_BYTES) {
+ const data = fs.readFileSync(filePath);
+ fs.writeFileSync(filePath, data.subarray(Math.max(0, data.length - UPDATE_LOG_KEEP_BYTES)), { mode: 0o600 });
+ }
+ const safeFields = Object.fromEntries(Object.entries(fields).map(([key, value]) => [key, scrub(value)]));
+ fs.appendFileSync(filePath, `${JSON.stringify({ time: new Date().toISOString(), event, ...safeFields })}\n`, { mode: 0o600 });
+ fs.chmodSync(filePath, 0o600);
+ } catch {
+ // Update logging is diagnostic only and cannot own process correctness.
+ }
+}
+
+function pidTuple(value: DaemonPidFile | null): Omit<DaemonUpdateIntent, "schemaVersion" | "requestId"> | null {
+ if (
+ !value
+ || typeof value.machineId !== "string"
+ || typeof value.startedAt !== "string"
+ || typeof value.ownerToken !== "string"
+ ) return null;
+ return {
+ pid: value.pid,
+ machineId: value.machineId,
+ startedAt: value.startedAt,
+ ownerToken: value.ownerToken,
+ };
+}
+
+function tuplesEqual(
+ value: ReturnType<typeof pidTuple>,
+ expected: Pick<DaemonUpdateIntent, "pid" | "machineId" | "startedAt" | "ownerToken">,
+): boolean {
+ return value?.pid === expected.pid
+ && value.machineId === expected.machineId
+ && value.startedAt === expected.startedAt
+ && value.ownerToken === expected.ownerToken;
+}
+
+function readIntent(baseDir: string, machineId: string): DaemonUpdateIntent {
+ const filePath = intentPath(baseDir, machineId);
+ const stat = fs.lstatSync(filePath);
+ if (!stat.isFile()) throw new Error("unsafe daemon update intent type");
+ fs.chmodSync(filePath, 0o600);
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8")) as Partial<DaemonUpdateIntent>;
+ if (
+ value.schemaVersion !== UPDATE_INTENT_SCHEMA_VERSION
+ || typeof value.requestId !== "string"
+ || !REQUEST_ID_PATTERN.test(value.requestId)
+ || !Number.isInteger(value.pid)
+ || (value.pid ?? 0) <= 0
+ || typeof value.machineId !== "string"
+ || typeof value.startedAt !== "string"
+ || typeof value.ownerToken !== "string"
+ ) throw new Error("invalid daemon update intent");
+ return value as DaemonUpdateIntent;
+}
+
+function removeIntentIfMatches(baseDir: string, machineId: string, requestId: string): void {
+ try {
+ const current = readIntent(baseDir, machineId);
+ if (current.requestId === requestId) fs.unlinkSync(intentPath(baseDir, machineId));
+ } catch { /* best effort */ }
+}
+
+function npmExecPath(explicit?: string): string {
+ const value = explicit ?? process.env.npm_execpath;
+ if (!value || !path.isAbsolute(value) || !fs.existsSync(value)) {
+ throw new Error("npm launch context unavailable; daemon remains online");
+ }
+ return value;
+}
+
+function readTestPackageMap(baseDir: string, machineId: string): Record<string, string> | null {
+ if (process.env.NODE_ENV !== "test") return null;
+ const filePath = updatePackageMapPath(baseDir, machineId);
+ if (!fs.existsSync(filePath)) return null;
+ const stat = fs.lstatSync(filePath);
+ if (!stat.isFile()) throw new Error("unsafe daemon update package map type");
+ if (process.platform !== "win32" && (stat.mode & 0o077) !== 0) {
+ throw new Error("daemon update package map must be mode 0600");
+ }
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8")) as unknown;
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("invalid daemon update package map");
+ const result: Record<string, string> = {};
+ for (const [key, value] of Object.entries(parsed)) {
+ if (key !== "latest" && !parseReleaseVersion(key)) throw new Error("invalid daemon update package map key");
+ if (typeof value !== "string" || !path.isAbsolute(value)) throw new Error("invalid daemon update package map value");
+ result[key] = value;
+ }
+ return result;
+}
+
+function packageSpec(baseDir: string, machineId: string, version: "latest" | string): string {
+ const mapped = readTestPackageMap(baseDir, machineId)?.[version];
+ if (mapped) return mapped;
+ return `@alook/daemon@${version}`;
+}
+
+function fixedNpmArgs(args: {
+ npmPath: string;
+ packageSpec: string;
+ command: "replace" | "resume";
+ machineId: string;
+ baseDir: string;
+ requestId: string;
+}): string[] {
+ return [
+ args.npmPath,
+ "exec",
+ "--yes",
+ `--package=${args.packageSpec}`,
+ "--",
+ "alook-daemon",
+ "daemon",
+ args.command,
+ "--id",
+ args.machineId,
+ "--base-dir",
+ args.baseDir,
+ "--request-id",
+ args.requestId,
+ ];
+}
+
+function openUpdateLog(baseDir: string, machineId: string): number {
+ appendUpdateLog(baseDir, machineId, "helper_spawn_requested");
+ const filePath = updateLogPath(baseDir, machineId);
+ const fd = fs.openSync(filePath, "a", 0o600);
+ fs.chmodSync(filePath, 0o600);
+ return fd;
+}
+
+export function createDaemonSelfUpdateHandler(
+ context: DaemonSelfUpdateContext,
+ deps: SelfUpdateDeps = {},
+): () => void {
+ let updateInFlight: ChildProcess | null = null;
+ return () => {
+ if (updateInFlight && updateInFlight.exitCode === null && updateInFlight.signalCode === null) return;
+ let requestId = "";
+ try {
+ const current = pidTuple(readPidFile(pidfilePathById(context.baseDir, context.machineId)));
+ if (
+ !current
+ || current.pid !== context.pid
+ || current.machineId !== context.machineId
+ || current.startedAt !== context.startedAt
+ || current.ownerToken !== context.ownerToken
+ ) throw new Error("daemon ownership changed before update launch");
+ const npmPath = npmExecPath(deps.npmExecPath);
+ requestId = crypto.randomUUID();
+ const intent: DaemonUpdateIntent = {
+ schemaVersion: UPDATE_INTENT_SCHEMA_VERSION,
+ requestId,
+ ...current,
+ };
+ writePrivateJsonAtomic(intentPath(context.baseDir, context.machineId), intent);
+ const logFd = openUpdateLog(context.baseDir, context.machineId);
+ try {
+ const child = (deps.spawnProcess ?? spawn)(process.execPath, fixedNpmArgs({
+ npmPath,
+ packageSpec: packageSpec(context.baseDir, context.machineId, "latest"),
+ command: "replace",
+ machineId: context.machineId,
+ baseDir: context.baseDir,
+ requestId,
+ }), {
+ detached: true,
+ shell: false,
+ stdio: ["ignore", logFd, logFd],
+ });
+ updateInFlight = child;
+ const clear = (event: string, fields: Record<string, unknown>): void => {
+ appendUpdateLog(context.baseDir, context.machineId, event, fields);
+ if (updateInFlight === child) updateInFlight = null;
+ removeIntentIfMatches(context.baseDir, context.machineId, requestId);
+ };
+ child.once("exit", (code, signal) => clear("helper_exited", { code, signal }));
+ child.once("error", (error) => clear("helper_process_error", { error }));
+ child.unref();
+ deps.logger?.info("daemon self-update helper launched", { machineId: context.machineId });
+ } finally {
+ fs.closeSync(logFd);
+ }
+ } catch (error) {
+ if (requestId) removeIntentIfMatches(context.baseDir, context.machineId, requestId);
+ appendUpdateLog(context.baseDir, context.machineId, "helper_spawn_failed", { error });
+ deps.logger?.warn("daemon self-update helper launch failed", { machineId: context.machineId, error: scrub(error) });
+ }
+ };
+}
+
+function currentPidTuple(baseDir: string, machineId: string): ReturnType<typeof pidTuple> {
+ return pidTuple(readPidFile(pidfilePathById(baseDir, machineId)));
+}
+
+function removeOldPidfileIfMatches(baseDir: string, intent: DaemonUpdateIntent): void {
+ const filePath = pidfilePathById(baseDir, intent.machineId);
+ if (!tuplesEqual(currentPidTuple(baseDir, intent.machineId), intent)) return;
+ try { fs.unlinkSync(filePath); } catch { /* best effort */ }
+}
+
+async function runPinnedResume(args: {
+ npmPath: string;
+ version: string;
+ machineId: string;
+ baseDir: string;
+ requestId: string;
+}): Promise<void> {
+ const fd = openUpdateLog(args.baseDir, args.machineId);
+ try {
+ const child = spawn(process.execPath, fixedNpmArgs({
+ npmPath: args.npmPath,
+ packageSpec: packageSpec(args.baseDir, args.machineId, args.version),
+ command: "resume",
+ machineId: args.machineId,
+ baseDir: args.baseDir,
+ requestId: args.requestId,
+ }), {
+ shell: false,
+ stdio: ["ignore", fd, fd],
+ });
+ await new Promise<void>((resolve, reject) => {
+ child.once("error", reject);
+ child.once("exit", (code, signal) => {
+ if (code === 0) resolve();
+ else reject(new Error(`rollback resume exited ${signal ?? code}`));
+ });
+ });
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+export async function daemonReplace(opts: {
+ id: string;
+ baseDir?: string;
+ requestId: string;
+}): Promise<void> {
+ if (!REQUEST_ID_PATTERN.test(opts.requestId)) throw new Error("invalid replacement request id");
+ const baseDir = opts.baseDir ?? process.env.ALOOK_DATA_DIR;
+ if (!baseDir) throw new Error("daemon replace requires --base-dir");
+ const intent = readIntent(baseDir, opts.id);
+ if (intent.machineId !== opts.id || intent.requestId !== opts.requestId) {
+ throw new Error("daemon update intent mismatch");
+ }
+ const launch = readDaemonLaunchRecord(baseDir, opts.id);
+ const currentVersion = readDaemonVersion();
+ if (!parseReleaseVersion(currentVersion) || !parseReleaseVersion(launch.daemonVersion)) {
+ throw new Error("daemon replacement version is invalid");
+ }
+ if (currentVersion === launch.daemonVersion || !releaseVersionGte(currentVersion, launch.daemonVersion)) {
+ appendUpdateLog(baseDir, opts.id, "replacement_not_newer", {
+ currentVersion,
+ priorVersion: launch.daemonVersion,
+ });
+ removeIntentIfMatches(baseDir, opts.id, opts.requestId);
+ return;
+ }
+ if (!tuplesEqual(currentPidTuple(baseDir, opts.id), intent)) {
+ removeIntentIfMatches(baseDir, opts.id, opts.requestId);
+ throw new Error("daemon ownership changed before replacement");
+ }
+
+ const npmPath = npmExecPath();
+ const acquired = acquireDaemonReplacementLock({ baseDir, machineId: opts.id, requestId: opts.requestId });
+ let oldStopped = false;
+ try {
+ if (!tuplesEqual(currentPidTuple(baseDir, opts.id), intent)) {
+ throw new Error("daemon ownership changed after replacement lock");
+ }
+ appendUpdateLog(baseDir, opts.id, "replacement_started", {
+ priorVersion: launch.daemonVersion,
+ nextVersion: currentVersion,
+ });
+ await stopExactDaemonPid(intent.pid);
+ oldStopped = true;
+ removeOldPidfileIfMatches(baseDir, intent);
+ try {
+ await daemonResume({ id: opts.id, baseDir, requestId: opts.requestId });
+ appendUpdateLog(baseDir, opts.id, "replacement_ready", { version: currentVersion });
+ } catch (error) {
+ appendUpdateLog(baseDir, opts.id, "replacement_start_failed", { error });
+ await runPinnedResume({
+ npmPath,
+ version: launch.daemonVersion,
+ machineId: opts.id,
+ baseDir,
+ requestId: opts.requestId,
+ });
+ appendUpdateLog(baseDir, opts.id, "rollback_ready", { version: launch.daemonVersion });
+ }
+ } catch (error) {
+ appendUpdateLog(baseDir, opts.id, oldStopped ? "replacement_terminal_failure" : "replacement_aborted", { error });
+ throw error;
+ } finally {
+ removeIntentIfMatches(baseDir, opts.id, opts.requestId);
+ removeReplacementLockIfMatches(acquired.path, acquired.lock);
+ }
+}
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 49100fa4d..08e88fc4a 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -21,7 +21,8 @@ import { pathToFileURL } from "node:url";
import type { ServerApi, Cursor, Message } from "../server/contract.js";
import { parseRef } from "../server/contract.js";
import { proxyServerApiFromEnv } from "./proxyServerApi.js";
-import { daemonRunFromIpc, daemonStart, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";
+import { daemonResume, daemonRunFromIpc, daemonStart, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";
+import { daemonReplace } from "./daemonUpdate.js";
import { parseInviteToken } from "@alook/shared/lib/invite-link";
import {
MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
@@ -994,6 +995,38 @@ function buildProgram(): Command {
await daemonRunFromIpc();
});
+ daemon
+ .command("resume", { hidden: true })
+ .requiredOption("--id <machineId>")
+ .requiredOption("--base-dir <path>")
+ .requiredOption("--request-id <id>")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const localOpts = this.opts();
+ await daemonResume({
+ id: localOpts.id as string,
+ baseDir: localOpts.baseDir as string,
+ requestId: localOpts.requestId as string,
+ });
+ });
+
+ daemon
+ .command("replace", { hidden: true })
+ .requiredOption("--id <machineId>")
+ .requiredOption("--base-dir <path>")
+ .requiredOption("--request-id <id>")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const localOpts = this.opts();
+ await daemonReplace({
+ id: localOpts.id as string,
+ baseDir: localOpts.baseDir as string,
+ requestId: localOpts.requestId as string,
+ });
+ });
+
daemon
.command("stop")
.argument("<id>", "daemon id from `alook daemon list` (the ID column)")
@@ -1058,6 +1091,7 @@ function buildProgram(): Command {
export async function main(argv = process.argv.slice(2)): Promise<number> {
const program = buildProgram();
+ let internalExitCode = 0;
try {
await program.parseAsync(argv, { from: "user" });
} catch (err) {
@@ -1085,8 +1119,14 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {
hint: (err as { hint?: string }).hint,
});
}
+ // Public agent-facing commands keep their JSON-only result contract. The
+ // two hidden replacement primitives additionally need a process status so
+ // the parent helper can distinguish ready from bounded rollback failure.
+ if (argv[0] === "daemon" && (argv[1] === "resume" || argv[1] === "replace")) {
+ internalExitCode = 1;
+ }
}
- return 0;
+ return internalExitCode;
}
function getHelpText(program: Command, argv: string[]): string {
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 94072027a..d47b1d944 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -218,6 +218,30 @@ describe("createDaemon", () => {
await daemon.stop();
});
+ it("consumes machine:update before bot observers and AgentRouter", async () => {
+ const sockets: FakeSocket[] = [];
+ const routerEntry = spyOnRouterCommandEntry();
+ const handleSelfUpdate = vi.fn(async () => {});
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ bots: [] })));
+ const daemon = await createDaemon({
+ machineKey: "cmk_self_update",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ capabilities: [],
+ handleSelfUpdate,
+ } as Parameters<typeof createDaemon>[0]);
+ sockets[0].emit("open");
+
+ sockets[0].emit("message", JSON.stringify({ type: "machine:update" }));
+
+ await vi.waitFor(() => expect(handleSelfUpdate).toHaveBeenCalledOnce());
+ expect(routerEntry).not.toHaveBeenCalledWith(expect.objectContaining({ type: "machine:update" }));
+ await daemon.stop();
+ });
+
it.each([
["missing", undefined],
["sync throw", vi.fn(() => { throw new Error("private sync detail"); })],
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index f9acc9fab..7c0a9c2bb 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -45,6 +45,7 @@ import {
createDiagnosticsCommandListener,
type DiagnosticFailureReport,
} from "./diagnosticsCommand.js";
+import { createSelfUpdateCommandListener } from "./selfUpdateCommand.js";
// Cold-start warmup backoff schedule (ms).
const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;
@@ -297,6 +298,8 @@ export interface CreateDaemonOptions {
logger?: Logger;
/** B2b interception seam; B2c supplies the local collector/uploader. */
handleDiagnosticCommand?: (command: DiagnosticCollectCommand) => void | Promise<void>;
+ /** Machine-level lifecycle command; consumed before bot observers/router. */
+ handleSelfUpdate?: () => void | Promise<void>;
/** Fixed-code failure callback used when diagnostics is not available. */
reportDiagnosticFailure?: (failure: DiagnosticFailureReport) => void | Promise<void>;
/** Supplies only the bounded default FSM snapshot source and status snapshot path. */
@@ -875,10 +878,10 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
`You have unread messages in channel ${notice.channel}.`,
});
- // Register the diagnostics consumer first: its synchronous channel-owned
- // sentinel claims diagnostics before either the bot-cache observer or the
- // AgentRouter can see them. The bot-cache observer remains immediately
- // before router.start()'s listener for ordinary bot:* frames.
+ // Machine lifecycle commands are claimed before diagnostics, bot observers,
+ // and AgentRouter; updates never enter agent lifecycle routing.
+ channel.onCommand(createSelfUpdateCommandListener(opts.handleSelfUpdate));
+ // Diagnostics likewise claims its machine-level command before bot/router.
channel.onCommand(createDiagnosticsCommandListener({
handleDiagnosticCommand: opts.handleDiagnosticCommand,
reportDiagnosticFailure: opts.reportDiagnosticFailure,
diff --git a/src/daemon/src/daemon/selfUpdateCommand.ts b/src/daemon/src/daemon/selfUpdateCommand.ts
new file mode 100644
index 000000000..fdd01ef6a
--- /dev/null
+++ b/src/daemon/src/daemon/selfUpdateCommand.ts
@@ -0,0 +1,18 @@
+import type { HostCommand } from "../server/contract.js";
+import { WS_CONTROL_COMMAND_CONSUMED } from "../server/wsControlChannel.js";
+
+export function createSelfUpdateCommandListener(
+ handleSelfUpdate?: () => void | Promise<void>,
+) {
+ return (command: HostCommand): void | typeof WS_CONTROL_COMMAND_CONSUMED => {
+ if (command.type !== "machine:update") return;
+ if (handleSelfUpdate) {
+ try {
+ Promise.resolve(handleSelfUpdate()).catch(() => { });
+ } catch {
+ // The lifecycle helper records its own scrubbed failure and remains retryable.
+ }
+ }
+ return WS_CONTROL_COMMAND_CONSUMED;
+ };
+}
diff --git a/src/daemon/src/version.packed.test.ts b/src/daemon/src/version.packed.test.ts
new file mode 100644
index 000000000..986489969
--- /dev/null
+++ b/src/daemon/src/version.packed.test.ts
@@ -0,0 +1,84 @@
+import { execFile } from "node:child_process";
+import { mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+
+const execFileAsync = promisify(execFile);
+const packageRoot = fileURLToPath(new URL("../", import.meta.url));
+const packageVersion = (JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")) as {
+ version: string;
+}).version;
+const tempRoots: string[] = [];
+const servers: Server[] = [];
+
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+describe("packed daemon version", () => {
+ it("reports the root package version from the real dist/cli bin", { timeout: 120_000 }, async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-daemon-version-pack-"));
+ tempRoots.push(root);
+ const npmExecPath = process.env.npm_execpath;
+ if (!npmExecPath) throw new Error("npm_execpath is required to build the packed daemon fixture");
+
+ await execFileAsync(
+ process.execPath,
+ [npmExecPath, "pack", "--pack-destination", root],
+ { cwd: packageRoot, maxBuffer: 10 * 1024 * 1024 },
+ );
+ const tarball = readdirSync(root).find((name) => name.endsWith(".tgz"));
+ if (!tarball) throw new Error("daemon pack did not produce a tarball");
+ await execFileAsync("tar", ["-xzf", join(root, tarball), "-C", root]);
+ symlinkSync(join(packageRoot, "node_modules"), join(root, "package", "node_modules"), "junction");
+
+ let activationBody: unknown;
+ const server = createServer((request, response) => {
+ const chunks: Buffer[] = [];
+ request.on("data", (chunk: Buffer) => chunks.push(chunk));
+ request.on("end", () => {
+ activationBody = JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ response.writeHead(400, { "content-type": "application/json" });
+ response.end(JSON.stringify({ error: "stop after version capture" }));
+ });
+ });
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("test server did not bind a TCP port");
+
+ const baseDir = join(root, "daemon-data");
+ await execFileAsync(
+ process.execPath,
+ [
+ join(root, "package", "dist", "cli", "index.js"),
+ "daemon",
+ "start",
+ "--machine-key",
+ "cmt_packed_version_test",
+ "--server-url",
+ `http://127.0.0.1:${address.port}`,
+ "--ws-url",
+ `ws://127.0.0.1:${address.port}`,
+ "--base-dir",
+ baseDir,
+ ],
+ {
+ env: {
+ ...process.env,
+ ALOOK_DATA_DIR: baseDir,
+ ALOOK_PROJECT_ROOT: root,
+ },
+ maxBuffer: 10 * 1024 * 1024,
+ },
+ );
+
+ expect(activationBody).toEqual(expect.objectContaining({ daemonVersion: packageVersion }));
+ expect(packageVersion.length).toBeGreaterThan(0);
+ });
+});
diff --git a/src/daemon/src/version.ts b/src/daemon/src/version.ts
index c481d5ee3..dfc1c1219 100644
--- a/src/daemon/src/version.ts
+++ b/src/daemon/src/version.ts
@@ -1,24 +1,28 @@
/**
* Daemon version + client-info helpers.
*
- * These are read from `@alook/daemon`'s own `package.json` (the file loaded
- * via `createRequire` at `../package.json`, i.e. this workspace's package
- * manifest). Everything on the wire that identifies the daemon to a remote
- * runtime CLI (Kimi's `initialize.client`, Codex's `initialize.clientInfo`)
+ * These are read from `@alook/daemon`'s own `package.json` across the source,
+ * library bundle, and nested CLI bundle layouts. Everything on the wire that
+ * identifies the daemon to a remote runtime CLI (Kimi's `initialize.client`,
+ * Codex's `initialize.clientInfo`)
* flows through `getDaemonClientInfo()` so nobody hand-types the pre-alook
* daemon-identity strings anymore.
*/
import { createRequire } from "module";
const requireFromHere = createRequire(import.meta.url);
+const PACKAGE_JSON_CANDIDATES = ["../package.json", "../../package.json"] as const;
export function readDaemonVersion(): string {
- try {
- const pkg = requireFromHere("../package.json") as { version?: string };
- return pkg.version ?? "";
- } catch {
- return "";
+ for (const candidate of PACKAGE_JSON_CANDIDATES) {
+ try {
+ const pkg = requireFromHere(candidate) as { version?: unknown };
+ if (typeof pkg.version === "string" && pkg.version.length > 0) return pkg.version;
+ } catch {
+ continue;
+ }
}
+ return "";
}
export interface DaemonClientInfo {
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index bcef2f049..c8fc211fd 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -786,6 +786,7 @@ export type HostCommand =
* `agentRouter` and plans/daemon-batch-reset.md.
*/
| { type: "machine:reset_all"; resets: Array<{ agentId: AgentId; config: RuntimeConfig; launchId: string }> }
+ | { type: "machine:update" }
// ─── Bot lifecycle events (server → daemon) ────────────────────────────
// Colon-namespaced to match the agent:* naming convention. Delivered to
// the specific machine's daemon connection via the WS DO. On the daemon,
@@ -1421,6 +1422,9 @@ export const HostCommandSchema = z.discriminatedUnion("type", [
}),
),
}),
+ z.strictObject({
+ type: z.literal("machine:update"),
+ }),
// The `bot:*` arms are NOT what #6 targets — the daemon acts on `agent:*`;
// `bot:*` merely mutate/evict the `botsById` cache at the createDaemon layer.
// Per the CTO scope ("bot:* covered for union-completeness, no bespoke
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index 6dd1754e0..b4c30a672 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -93,6 +93,8 @@ export const MAX_INBOX_PAGE_SIZE = 200
// (the web route only issues a single bulk request per poll).
export const PRESENCE_MEMBER_CAP = 500
+export const SELF_UPDATE_MIN_DAEMON_VERSION = "0.1.7"
+
// Banner color — accepts hex (#RRGGBB / #RGB) only
export const BANNER_COLOR_REGEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.ts
index 5653ddb0e..8352f564d 100644
--- a/src/shared/src/db/queries/community/machine.ts
+++ b/src/shared/src/db/queries/community/machine.ts
@@ -265,6 +265,7 @@ export async function upsertMachineByMachineId(
machine: MachineRow;
priorLastSeenAt: string | null;
priorAvailableRuntimes: CommunityMachineRuntime[];
+ priorDaemonVersion: string;
priorStatus: "online" | "offline";
} | null> {
const markOnline = opts.markOnline ?? true;
@@ -306,6 +307,7 @@ export async function upsertMachineByMachineId(
machine: rows[0] as MachineRow,
priorLastSeenAt: prior.lastSeenAt,
priorAvailableRuntimes: prior.availableRuntimes,
+ priorDaemonVersion: prior.daemonVersion,
priorStatus: (prior.status as "online" | "offline") ?? "offline",
};
}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 20a573f4a..0b4cba613 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -158,6 +158,7 @@ export {
DEFAULT_INBOX_PAGE_SIZE,
MAX_INBOX_PAGE_SIZE,
PRESENCE_MEMBER_CAP,
+ SELF_UPDATE_MIN_DAEMON_VERSION,
BANNER_COLOR_REGEX,
NOTIFICATION_LEVEL_VALUES,
TYPING_INDICATOR_TIMEOUT_MS,
@@ -656,6 +657,7 @@ export { isPublic, isPrivate } from "./utils/visibility";
export type { AgentVisibility } from "./utils/visibility";
export { extractMentionedUserIds, MENTION_TYPES, isMentionType } from "./utils/community-mentions";
export type { MentionCandidate, MentionType } from "./utils/community-mentions";
-export { semverGte } from "./semver";
+export { parseReleaseVersion, releaseVersionGte, semverGte } from "./semver";
+export type { ReleaseVersion } from "./semver";
export { resolveMode, cliCommand, cliPackageName, updateCommand, daemonCommand, getBaseUrl, isTauri, isDesktop, isMobile, tauriInvoke } from "./mode";
export type { AlookMode, ModeSignals, BaseUrlSignals } from "./mode";
diff --git a/src/shared/src/semver.test.ts b/src/shared/src/semver.test.ts
index 6455a2050..f1f61df57 100644
--- a/src/shared/src/semver.test.ts
+++ b/src/shared/src/semver.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { semverGte } from "./semver";
+import { parseReleaseVersion, releaseVersionGte, semverGte } from "./semver";
describe("semverGte", () => {
it("returns true when a > b", () => {
@@ -27,3 +27,40 @@ describe("semverGte", () => {
expect(semverGte("1.0.0", "1.0.1")).toBe(false);
});
});
+
+describe("strict release versions", () => {
+ it("parses exactly three non-negative safe integer components", () => {
+ expect(parseReleaseVersion("0.1.7")).toEqual([0, 1, 7]);
+ expect(parseReleaseVersion("12.34.56")).toEqual([12, 34, 56]);
+ });
+
+ it.each([
+ "",
+ "abc",
+ "1",
+ "1.2",
+ "1.2.3.4",
+ "-1.2.3",
+ "1.-2.3",
+ "01.2.3",
+ "1.02.3",
+ "1.2.03",
+ "1.2.3-alpha",
+ "v1.2.3",
+ "9007199254740992.0.0",
+ ])("rejects unsupported release version %j", (value) => {
+ expect(parseReleaseVersion(value)).toBeNull();
+ });
+
+ it("compares valid releases and fails closed for invalid input", () => {
+ expect(releaseVersionGte("0.1.7", "0.1.7")).toBe(true);
+ expect(releaseVersionGte("0.2.0", "0.1.7")).toBe(true);
+ expect(releaseVersionGte("0.1.6", "0.1.7")).toBe(false);
+ expect(releaseVersionGte("abc", "0.1.7")).toBe(false);
+ expect(releaseVersionGte("0.1.7", "latest")).toBe(false);
+ });
+
+ it("does not change the loose legacy comparator", () => {
+ expect(semverGte("1.2", "1.2.0")).toBe(true);
+ });
+});
diff --git a/src/shared/src/semver.ts b/src/shared/src/semver.ts
index db5887ea2..89a11d858 100644
--- a/src/shared/src/semver.ts
+++ b/src/shared/src/semver.ts
@@ -9,3 +9,28 @@ export function semverGte(a: string, b: string): boolean {
}
return true;
}
+
+export type ReleaseVersion = readonly [major: number, minor: number, patch: number];
+
+const RELEASE_VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
+
+export function parseReleaseVersion(value: string): ReleaseVersion | null {
+ const match = RELEASE_VERSION_PATTERN.exec(value);
+ if (!match) return null;
+ const major = Number(match[1]);
+ const minor = Number(match[2]);
+ const patch = Number(match[3]);
+ if (![major, minor, patch].every(Number.isSafeInteger)) return null;
+ return [major, minor, patch];
+}
+
+export function releaseVersionGte(a: string, b: string): boolean {
+ const parsedA = parseReleaseVersion(a);
+ const parsedB = parseReleaseVersion(b);
+ if (!parsedA || !parsedB) return false;
+ for (let i = 0; i < parsedA.length; i++) {
+ if (parsedA[i]! > parsedB[i]!) return true;
+ if (parsedA[i]! < parsedB[i]!) return false;
+ }
+ return true;
+}
diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.ts
index d9f976208..a47a6fc59 100644
--- a/src/shared/test/community-cli-contract.test.ts
+++ b/src/shared/test/community-cli-contract.test.ts
@@ -312,3 +312,22 @@ describe("HostCommand diagnostics contract", () => {
);
});
});
+
+describe("HostCommand machine update contract", () => {
+ it("keeps the no-payload arm in the type and strict runtime schema", () => {
+ type UpdateCommand = { type: "machine:update" };
+ expectTypeOf<Extract<HostCommand, { type: "machine:update" }>>()
+ .toEqualTypeOf<UpdateCommand>();
+ expect(HostCommandSchema.safeParse({ type: "machine:update" })).toEqual(
+ expect.objectContaining({ success: true }),
+ );
+ });
+
+ it.each(["package", "version", "url", "command"])(
+ "rejects an extra %s field instead of stripping it",
+ (field) => {
+ expect(HostCommandSchema.safeParse({ type: "machine:update", [field]: "attacker" }).success)
+ .toBe(false);
+ },
+ );
+});
diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.ts
index 6df729adf..ad3020ece 100644
--- a/src/shared/test/queries/community-machine.test.ts
+++ b/src/shared/test/queries/community-machine.test.ts
@@ -490,6 +490,7 @@ describe("upsertMachineByMachineId", () => {
availableRuntimes: [{ id: "claude" }, { id: "codex" }],
});
expect(res?.priorAvailableRuntimes).toEqual([{ id: "claude" }]);
+ expect(res?.priorDaemonVersion).toBe("0.1.0");
expect(res?.machine.availableRuntimes).toEqual([{ id: "claude" }, { id: "codex" }]);
expect(chain.set).toHaveBeenCalledWith(
expect.objectContaining({
diff --git a/src/web/src/app/api/community/machines/[id]/update/route.test.ts b/src/web/src/app/api/community/machines/[id]/update/route.test.ts
new file mode 100644
index 000000000..1a7cce4ac
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/update/route.test.ts
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetMachineByIdForUser = vi.fn()
+const mockPushMachineUpdate = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityMachine: {
+ ...actual.queries.communityMachine,
+ getMachineByIdForUser: (...args: unknown[]) => mockGetMachineByIdForUser(...args),
+ },
+ },
+ }
+})
+vi.mock("@/lib/community/bot-push", () => ({
+ pushMachineUpdate: (...args: unknown[]) => mockPushMachineUpdate(...args),
+}))
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (request: any, context?: any) => {
+ const params = context?.params instanceof Promise ? await context.params : context?.params
+ return handler(request, {
+ env: { DB: {} },
+ userId: context?.actor ?? "owner_1",
+ email: "[email protected]",
+ params,
+ })
+ },
+}))
+
+import { POST } from "./route"
+
+const context = { params: { id: "cm_1" } } as any
+const request = () => new NextRequest("http://localhost/api/community/machines/cm_1/update", {
+ method: "POST",
+})
+const machine = (overrides: Record<string, unknown> = {}) => ({
+ id: "cm_1",
+ userId: "owner_1",
+ status: "online",
+ daemonVersion: "0.1.7",
+ ...overrides,
+})
+
+describe("POST /api/community/machines/[id]/update", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it("returns 404 before delivery for a missing or foreign machine", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue(null)
+
+ const response = await POST(request(), context)
+
+ expect(response.status).toBe(404)
+ expect(mockGetMachineByIdForUser).toHaveBeenCalledWith({}, "owner_1", "cm_1")
+ expect(mockPushMachineUpdate).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["offline", "0.1.7"],
+ ["online", "0.1.6"],
+ ["online", ""],
+ ["online", "abc"],
+ ["online", "0.1.7-alpha"],
+ ])("returns 409 without delivery for status=%s version=%s", async (status, daemonVersion) => {
+ mockGetMachineByIdForUser.mockResolvedValue(machine({ status, daemonVersion }))
+
+ const response = await POST(request(), context)
+
+ expect(response.status).toBe(409)
+ expect(mockPushMachineUpdate).not.toHaveBeenCalled()
+ })
+
+ it("maps an authenticated but absent socket to 409", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue(machine())
+ mockPushMachineUpdate.mockResolvedValue({ sent: 0, deliveryError: false })
+
+ const response = await POST(request(), context)
+
+ expect(response.status).toBe(409)
+ expect(mockPushMachineUpdate).toHaveBeenCalledWith(expect.anything(), "cm_1")
+ })
+
+ it("maps control-plane failure to 503 instead of claiming the machine is offline", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue(machine())
+ mockPushMachineUpdate.mockResolvedValue({ sent: 0, deliveryError: true })
+
+ const response = await POST(request(), context)
+
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "could not deliver the daemon update" })
+ })
+
+ it("returns dispatch-level success when at least one live socket receives the frame", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue(machine({ daemonVersion: "0.2.0" }))
+ mockPushMachineUpdate.mockResolvedValue({ sent: 1, deliveryError: false })
+
+ const response = await POST(request(), context)
+
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ dispatched: true })
+ })
+})
diff --git a/src/web/src/app/api/community/machines/[id]/update/route.ts b/src/web/src/app/api/community/machines/[id]/update/route.ts
new file mode 100644
index 000000000..974052bd1
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/update/route.ts
@@ -0,0 +1,37 @@
+import {
+ SELF_UPDATE_MIN_DAEMON_VERSION,
+ queries,
+ releaseVersionGte,
+} from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { pushMachineUpdate } from "@/lib/community/bot-push"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeError, writeJSON } from "@/lib/middleware/helpers"
+
+export const POST = withAuth(async (_request, ctx) => {
+ const machineId = ctx.params?.id as string
+ if (!machineId) return writeError("machine id is required", 400)
+
+ const db = getDb(ctx.env.DB)
+ const machine = await queries.communityMachine.getMachineByIdForUser(
+ db,
+ ctx.userId,
+ machineId,
+ )
+ if (!machine) return writeError("machine not found", 404)
+ if (machine.status !== "online") {
+ return writeError("machine is offline — bring its daemon online before updating", 409)
+ }
+ if (!releaseVersionGte(machine.daemonVersion, SELF_UPDATE_MIN_DAEMON_VERSION)) {
+ return writeError("daemon must be updated manually before remote updates are available", 409)
+ }
+
+ const result = await pushMachineUpdate(ctx.env, machineId)
+ if (result.deliveryError) {
+ return writeError("could not deliver the daemon update", 503)
+ }
+ if (result.sent === 0) {
+ return writeError("machine is offline — bring its daemon online before updating", 409)
+ }
+ return writeJSON({ dispatched: true })
+})
diff --git a/src/web/src/components/community/machines/machine-card.tsx b/src/web/src/components/community/machines/machine-card.tsx
index 8888c0a52..bb230af1f 100644
--- a/src/web/src/components/community/machines/machine-card.tsx
+++ b/src/web/src/components/community/machines/machine-card.tsx
@@ -15,16 +15,19 @@ import {
} from "@/components/ui/dropdown-menu"
import { timeAgo } from "@/lib/time"
import { machineName } from "@/lib/community/machine-name"
+import { tid } from "@/lib/community/testids"
import { MachineRuntimes } from "./machine-runtimes"
export function MachineCard({
machine,
onDelete,
onReconnect,
+ onUpdate,
}: {
machine: CommunityMachineSummary
onDelete: () => void
onReconnect: () => void
+ onUpdate?: () => void
}) {
const isOnline = isPresenceOnline(machine.status)
const lastSeenLabel = useMemo(
@@ -95,6 +98,7 @@ export function MachineCard({
render={
<button
aria-label="Machine actions"
+ data-testid={tid.machineActions(machine.id)}
className="grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
>
<MoreVertical className="size-4" />
@@ -102,6 +106,14 @@ export function MachineCard({
}
/>
<DropdownMenuContent align="end">
+ {onUpdate && (
+ <DropdownMenuItem
+ data-testid={tid.machineUpdate(machine.id)}
+ onClick={onUpdate}
+ >
+ Update daemon…
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={onReconnect}>
Reconnect…
</DropdownMenuItem>
diff --git a/src/web/src/components/community/machines/machine-list.test.ts b/src/web/src/components/community/machines/machine-list.test.ts
new file mode 100644
index 000000000..9eff4c8e8
--- /dev/null
+++ b/src/web/src/components/community/machines/machine-list.test.ts
@@ -0,0 +1,172 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ apiFetch: vi.fn(),
+ toastSuccess: vi.fn(),
+ toastError: vi.fn(),
+}))
+
+vi.mock("sonner", () => ({
+ toast: {
+ success: mocks.toastSuccess,
+ error: mocks.toastError,
+ },
+}))
+
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: mocks.apiFetch,
+ getErrorMessage: (error: unknown, fallback: string) =>
+ error instanceof Error && error.message ? error.message : fallback,
+}))
+
+vi.mock("@/components/ui/alert-dialog", () => ({
+ AlertDialog: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>
+ React.createElement("dialog", props, children),
+ AlertDialogContent: ({ children }: React.PropsWithChildren) =>
+ React.createElement("section", {}, children),
+ AlertDialogHeader: ({ children }: React.PropsWithChildren) =>
+ React.createElement("header", {}, children),
+ AlertDialogTitle: ({ children }: React.PropsWithChildren) =>
+ React.createElement("h2", {}, children),
+ AlertDialogDescription: ({ children }: React.PropsWithChildren) =>
+ React.createElement("p", {}, children),
+ AlertDialogFooter: ({ children }: React.PropsWithChildren) =>
+ React.createElement("footer", {}, children),
+ AlertDialogAction: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>
+ React.createElement("button", { ...props, "data-kind": "confirm" }, children),
+ AlertDialogCancel: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>
+ React.createElement("button", { ...props, "data-kind": "cancel" }, children),
+}))
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+ useSearchParams: () => new URLSearchParams(),
+}))
+
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ setQueryData: vi.fn() }),
+}))
+
+vi.mock("@/components/ui/button", () => ({ Button: () => null }))
+vi.mock("@/components/ui/card", () => ({ Card: () => null }))
+vi.mock("@/components/ui/skeleton", () => ({ Skeleton: () => null }))
+vi.mock("@/components/avatar", () => ({ GeneratedAvatar: () => null }))
+vi.mock("./machine-card", () => ({ MachineCard: () => null }))
+vi.mock("./pair-machine-sheet", () => ({ PairMachineSheet: () => null }))
+vi.mock("@/components/community/onboarding-tiles/connect-tile", () => ({ ConnectTile: () => null }))
+vi.mock("@/hooks/community/use-machines", () => ({ useMachines: () => ({ machines: [], isLoading: false }) }))
+vi.mock("@/hooks/community/use-bots", () => ({ useBots: () => ({ bots: [] }) }))
+vi.mock("@/stores/community", () => ({
+ usePendingMachineTokenId: () => null,
+ useCommunityStore: { getState: () => ({ setPendingMachineTokenId: vi.fn() }) },
+}))
+vi.mock("@/lib/community-onboarding", () => ({
+ advanceCommunityOnboarding: vi.fn(),
+ readCommunityOnboardingState: vi.fn(() => null),
+ startCommunityOnboarding: vi.fn(),
+ updateCommunityOnboardingResources: vi.fn(),
+ useCommunityOnboarding: () => "done",
+}))
+vi.mock("@/lib/api/config", () => ({ fetchLatestCliVersion: vi.fn() }))
+vi.mock("@/lib/utils", () => ({ getAppMode: () => "production" }))
+
+import type { CommunityMachineSummary } from "@alook/shared"
+import {
+ canUpdateMachine,
+ MachineUpdateDialog,
+ requestMachineUpdate,
+} from "./machine-list"
+
+function machine(overrides: Partial<CommunityMachineSummary> = {}): CommunityMachineSummary {
+ return {
+ id: "machine-1",
+ hostname: "Studio Mac",
+ status: "online",
+ daemonVersion: "0.1.7",
+ availableRuntimes: [],
+ ...overrides,
+ } as CommunityMachineSummary
+}
+
+describe("machine daemon update UI", () => {
+ beforeEach(() => {
+ mocks.apiFetch.mockReset()
+ mocks.toastSuccess.mockReset()
+ mocks.toastError.mockReset()
+ })
+
+ it("allows every remote controller mode and hides Update only in dev", () => {
+ for (const mode of ["production", "app", "desktop", "mobile"] as const) {
+ expect(canUpdateMachine(machine(), "0.1.8", mode)).toBe(true)
+ }
+ expect(canUpdateMachine(machine(), "0.1.8", "dev")).toBe(false)
+ })
+
+ it("requires an online, outdated, supported daemon with a valid latest version", () => {
+ expect(canUpdateMachine(machine({ status: "offline" }), "0.1.8", "production")).toBe(false)
+ expect(canUpdateMachine(machine({ daemonVersion: "0.1.8" }), "0.1.8", "production")).toBe(false)
+ expect(canUpdateMachine(machine({ daemonVersion: "0.1.6" }), "0.1.8", "production")).toBe(false)
+ expect(canUpdateMachine(machine({ daemonVersion: "invalid" }), "0.1.8", "production")).toBe(false)
+ expect(canUpdateMachine(machine(), "invalid", "production")).toBe(false)
+ })
+
+ it("cancels without dispatch and confirms exactly once", async () => {
+ const onOpenChange = vi.fn()
+ mocks.apiFetch.mockResolvedValue({ dispatched: true })
+ const onConfirm = vi.fn((target: CommunityMachineSummary) =>
+ requestMachineUpdate(target.id),
+ )
+ const target = machine()
+ let renderer!: TestRenderer.ReactTestRenderer
+
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MachineUpdateDialog, {
+ machine: target,
+ onOpenChange,
+ onConfirm,
+ }),
+ )
+ })
+
+ const cancel = renderer.root.findByProps({ "data-kind": "cancel" })
+ const confirm = renderer.root.findByProps({ "data-kind": "confirm" })
+ act(() => cancel.props.onClick())
+ expect(onOpenChange).toHaveBeenCalledWith(false)
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(mocks.apiFetch).not.toHaveBeenCalled()
+
+ await act(async () => {
+ await confirm.props.onClick()
+ })
+ expect(onConfirm).toHaveBeenCalledOnce()
+ expect(onConfirm).toHaveBeenCalledWith(target)
+ expect(mocks.apiFetch).toHaveBeenCalledOnce()
+ })
+
+ it("reports successful dispatch as requested, not completed", async () => {
+ mocks.apiFetch.mockResolvedValue({ dispatched: true })
+
+ await expect(requestMachineUpdate("machine-1")).resolves.toBe(true)
+
+ expect(mocks.apiFetch).toHaveBeenCalledWith(
+ "/api/community/machines/machine-1/update",
+ { method: "POST" },
+ )
+ expect(mocks.toastSuccess).toHaveBeenCalledOnce()
+ const successMessage = String(mocks.toastSuccess.mock.calls[0]?.[0]).toLowerCase()
+ expect(successMessage).not.toContain("completed")
+ expect(successMessage).not.toContain("completion")
+ })
+
+ it("preserves the API error message", async () => {
+ mocks.apiFetch.mockRejectedValue(new Error("Machine is offline"))
+
+ await expect(requestMachineUpdate("machine-1")).resolves.toBe(false)
+
+ expect(mocks.toastError).toHaveBeenCalledWith("Machine is offline")
+ expect(mocks.toastSuccess).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index 760bb9a66..0102ae1ba 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -5,8 +5,12 @@ import { useRouter, useSearchParams } from "next/navigation"
import { toast } from "sonner"
import { ChevronLeft } from "lucide-react"
import { useQueryClient } from "@tanstack/react-query"
-import type { CommunityMachineSummary } from "@alook/shared"
-import { isPresenceOnline } from "@alook/shared"
+import type { AlookMode, CommunityMachineSummary } from "@alook/shared"
+import {
+ isPresenceOnline,
+ releaseVersionGte,
+ SELF_UPDATE_MIN_DAEMON_VERSION,
+} from "@alook/shared"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
@@ -21,7 +25,10 @@ import {
AlertDialogAction,
AlertDialogCancel,
} from "@/components/ui/alert-dialog"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, getErrorMessage } from "@/lib/api/client"
+import { fetchLatestCliVersion } from "@/lib/api/config"
+import { getAppMode } from "@/lib/utils"
+import { machineName } from "@/lib/community/machine-name"
import { MachineCard } from "./machine-card"
import { PairMachineSheet, type PairMachineSheetMode } from "./pair-machine-sheet"
import { ConnectTile } from "@/components/community/onboarding-tiles/connect-tile"
@@ -59,6 +66,70 @@ function MachineCardSkeleton() {
)
}
+export function canUpdateMachine(
+ machine: Pick<CommunityMachineSummary, "status" | "daemonVersion">,
+ latestVersion: string | null,
+ controllerMode: AlookMode,
+): boolean {
+ const currentVersion = machine.daemonVersion
+ if (controllerMode === "dev" || !isPresenceOnline(machine.status) || !currentVersion || !latestVersion) {
+ return false
+ }
+ return (
+ releaseVersionGte(currentVersion, SELF_UPDATE_MIN_DAEMON_VERSION) &&
+ releaseVersionGte(latestVersion, currentVersion) &&
+ !releaseVersionGte(currentVersion, latestVersion)
+ )
+}
+
+export async function requestMachineUpdate(machineId: string): Promise<boolean> {
+ try {
+ await apiFetch<{ dispatched: true }>(`/api/community/machines/${machineId}/update`, {
+ method: "POST",
+ })
+ toast.success("Update requested — the machine will restart and reconnect")
+ return true
+ } catch (error) {
+ toast.error(getErrorMessage(error, "Couldn't request the daemon update"))
+ return false
+ }
+}
+
+export function MachineUpdateDialog({
+ machine,
+ onOpenChange,
+ onConfirm,
+}: {
+ machine: CommunityMachineSummary | null
+ onOpenChange: (open: boolean) => void
+ onConfirm: (machine: CommunityMachineSummary) => void
+}) {
+ return (
+ <AlertDialog open={!!machine} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ Update daemon on {machine ? machineName(machine) : "machine"}?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ The daemon will restart, and any agents currently running on this machine will stop.
+ The machine will reconnect automatically when the update is ready.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel onClick={() => onOpenChange(false)}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ data-testid={tid.machineUpdateConfirm}
+ onClick={() => machine && onConfirm(machine)}
+ >
+ Update daemon
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
+
export function MachineList({ onBack }: { onBack?: () => void } = {}) {
const router = useRouter()
const searchParams = useSearchParams()
@@ -71,13 +142,31 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
const [pendingTokenId, setPendingTokenId] = useState<string | null>(null)
const [connectedHostname, setConnectedHostname] = useState<string | null>(null)
const [confirmDelete, setConfirmDelete] = useState<CommunityMachineSummary | null>(null)
+ const [confirmUpdate, setConfirmUpdate] = useState<CommunityMachineSummary | null>(null)
+ const [latestVersion, setLatestVersion] = useState<string | null>(null)
const [guideAvatarSeed, setGuideAvatarSeed] = useState("alook-guide")
const onboardingState = useCommunityOnboarding()
+ const controllerMode = getAppMode()
useEffect(() => {
setGuideAvatarSeed(`alook-guide-${crypto.randomUUID()}`)
}, [])
+ useEffect(() => {
+ if (controllerMode === "dev") return
+ let active = true
+ void fetchLatestCliVersion()
+ .then(({ version }) => {
+ if (active) setLatestVersion(version)
+ })
+ .catch(() => {
+ if (active) setLatestVersion(null)
+ })
+ return () => {
+ active = false
+ }
+ }, [controllerMode])
+
// When the WS layer announces a machine for our pending token, flip the sheet.
useEffect(() => {
if (!pendingTokenId) return
@@ -187,6 +276,11 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
useCommunityStore.getState().setPendingMachineTokenId(tokenId)
}, [])
+ const onConfirmUpdate = useCallback((machine: CommunityMachineSummary) => {
+ setConfirmUpdate(null)
+ void requestMachineUpdate(machine.id)
+ }, [])
+
const botsToDelete = confirmDelete
? bots.filter((b) => b.machineId === confirmDelete.id)
: []
@@ -295,6 +389,11 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
machine={m}
onDelete={() => setConfirmDelete(m)}
onReconnect={() => openReconnect(m)}
+ onUpdate={
+ canUpdateMachine(m, latestVersion, controllerMode)
+ ? () => setConfirmUpdate(m)
+ : undefined
+ }
/>
))}
</div>
@@ -307,6 +406,11 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
connectedHostname={connectedHostname}
mode={pairMode}
/>
+ <MachineUpdateDialog
+ machine={confirmUpdate}
+ onOpenChange={(open) => !open && setConfirmUpdate(null)}
+ onConfirm={onConfirmUpdate}
+ />
<AlertDialog
open={!!confirmDelete}
onOpenChange={(o) => !o && setConfirmDelete(null)}
diff --git a/src/web/src/lib/community/bot-push.test.ts b/src/web/src/lib/community/bot-push.test.ts
index 2efad7b5d..2a00cad85 100644
--- a/src/web/src/lib/community/bot-push.test.ts
+++ b/src/web/src/lib/community/bot-push.test.ts
@@ -9,10 +9,56 @@ import {
pushAgentResetToMachine,
pushAgentModelSwitchToMachine,
pushAgentProviderSwitchToMachine,
+ pushMachineUpdate,
} from "./bot-push"
const FAKE_ENV = { WS_DO_WORKER: {}, DEV_WS_DO_URL: undefined } as unknown as Env
+describe("pushMachineUpdate", () => {
+ beforeEach(() => {
+ wsDoFetch.mockReset()
+ })
+
+ it("POSTs the fixed update route without a caller payload", async () => {
+ wsDoFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+
+ await expect(pushMachineUpdate(FAKE_ENV, "machine/1")).resolves.toEqual({
+ sent: 1,
+ deliveryError: false,
+ })
+ const [, path, init, meta] = wsDoFetch.mock.calls[0]!
+ expect(path).toBe("/community-machine/by-id/machine%2F1/forward-update")
+ expect(init).toEqual({ method: "POST" })
+ expect(meta).toEqual({ label: "machine/1", type: "machine:update" })
+ })
+
+ it("distinguishes offline from non-ok, malformed, and thrown delivery failures", async () => {
+ wsDoFetch.mockResolvedValueOnce(new Response(JSON.stringify({ sent: 0 }), { status: 200 }))
+ await expect(pushMachineUpdate(FAKE_ENV, "m")).resolves.toEqual({
+ sent: 0,
+ deliveryError: false,
+ })
+
+ wsDoFetch.mockResolvedValueOnce(new Response("down", { status: 503 }))
+ await expect(pushMachineUpdate(FAKE_ENV, "m")).resolves.toEqual({
+ sent: 0,
+ deliveryError: true,
+ })
+
+ wsDoFetch.mockResolvedValueOnce(new Response(JSON.stringify({ sent: "one" }), { status: 200 }))
+ await expect(pushMachineUpdate(FAKE_ENV, "m")).resolves.toEqual({
+ sent: 0,
+ deliveryError: true,
+ })
+
+ wsDoFetch.mockRejectedValueOnce(new Error("network"))
+ await expect(pushMachineUpdate(FAKE_ENV, "m")).resolves.toEqual({
+ sent: 0,
+ deliveryError: true,
+ })
+ })
+})
+
describe("pushAgentResetToMachine", () => {
beforeEach(() => {
wsDoFetch.mockReset()
diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.ts
index cd0a62127..2073d6bef 100644
--- a/src/web/src/lib/community/bot-push.ts
+++ b/src/web/src/lib/community/bot-push.ts
@@ -11,6 +11,42 @@ const log = createLogger({ service: "community-bot-push" })
type BotEventFrame = BotAddedFrame | BotUpdatedFrame | BotRemovedFrame
+export type MachineUpdatePushResult =
+ | { sent: number; deliveryError: false }
+ | { sent: 0; deliveryError: true }
+
+export async function pushMachineUpdate(
+ env: Env,
+ machineId: string,
+): Promise<MachineUpdatePushResult> {
+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-update`
+ try {
+ const response = await wsDoFetch(
+ env,
+ path,
+ { method: "POST" },
+ { label: machineId, type: "machine:update" },
+ )
+ if (!response.ok) {
+ log.warn("machine:update push non-ok", { machineId, status: response.status })
+ return { sent: 0, deliveryError: true }
+ }
+ const data = await response.json() as { sent?: unknown }
+ if (
+ typeof data.sent !== "number"
+ || !Number.isSafeInteger(data.sent)
+ || data.sent < 0
+ ) {
+ log.warn("machine:update push malformed", { machineId })
+ return { sent: 0, deliveryError: true }
+ }
+ return { sent: data.sent, deliveryError: false }
+ } catch (err) {
+ log.warn("machine:update push threw", { machineId, err: String(err) })
+ return { sent: 0, deliveryError: true }
+ }
+}
+
/**
* Push a bot event (bot:added / bot:updated / bot:removed) to the machine's
* daemon connection via the WS Durable Object.
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index eab1bf3b5..a38bc2ad5 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -21,6 +21,9 @@ export const tid = {
machinePairOpen: "community-machine-pair-open",
machinePairCommand: "community-machine-pair-command",
machinePairCopy: "community-machine-pair-copy",
+ machineActions: (id: string) => `machine-actions-${id}`,
+ machineUpdate: (id: string) => `machine-update-${id}`,
+ machineUpdateConfirm: "machine-update-confirm",
homeButton: "community-home-button",
alookLogo: "community-alook-logo",
botReportProblemItem: "bot-report-problem-item",
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
index 8f9770635..ca48d4d49 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -87,6 +87,7 @@ describe("ws-do router", () => {
"handleMachineWake",
"handleMachineDiagnostics",
"handleMachineReset",
+ "handleMachineUpdate",
"handleMachineBatchReset",
"handleMachineModelSwitch",
"handleMachineProviderSwitch",
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index e623c9ee0..1ff2b67bd 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -13,6 +13,7 @@ import {
handleMachineForceClose,
handleMachineNap,
handleMachineReset,
+ handleMachineUpdate,
} from "./routes/community-machine-lifecycle"
import { handleMachineModelSwitch, handleMachineProviderSwitch } from "./routes/community-machine-switch"
import { handleHealth } from "./routes/health"
@@ -66,6 +67,8 @@ export default {
if (response) return response
response = await handleMachineReset(context)
if (response) return response
+ response = await handleMachineUpdate(context)
+ if (response) return response
response = await handleMachineBatchReset(context)
if (response) return response
response = await handleMachineModelSwitch(context)
diff --git a/src/ws-do/src/routes/community-machine-lifecycle.test.ts b/src/ws-do/src/routes/community-machine-lifecycle.test.ts
index e2682a711..937007d27 100644
--- a/src/ws-do/src/routes/community-machine-lifecycle.test.ts
+++ b/src/ws-do/src/routes/community-machine-lifecycle.test.ts
@@ -43,6 +43,62 @@ describe("ws-do router", () => {
handler = undefined as unknown as RouterHandler
})
+ describe("POST /community-machine/by-id/:machineId/forward-update", () => {
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset().mockResolvedValue([])
+ })
+
+ it("returns sent:0 when the machine has no active credential DO", async () => {
+ const response = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-update",
+ { method: "POST" },
+ ), env as any)
+
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("constructs only the exact machine:update frame and aggregates live delivery", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ doMock.stubFetch
+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: 2 }), { status: 200 }))
+
+ const response = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-update",
+ { method: "POST", body: JSON.stringify({ command: "ignored" }) },
+ ), env as any)
+
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ sent: 3 })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(2)
+ for (const [request] of doMock.stubFetch.mock.calls) {
+ expect(await (request as Request).clone().json()).toEqual({ type: "machine:update" })
+ }
+ })
+
+ it("returns 503 when resolution fails or every live DO delivery is transiently inconclusive", async () => {
+ mockGetActiveDoNamesForMachine.mockRejectedValueOnce(new Error("D1 down"))
+ const resolutionFailure = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-update",
+ { method: "POST" },
+ ), env as any)
+ expect(resolutionFailure.status).toBe(503)
+
+ mockGetActiveDoNamesForMachine.mockResolvedValueOnce(["do-a", "do-b"])
+ doMock.stubFetch
+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: "invalid" }), { status: 200 }))
+ .mockRejectedValueOnce(new Error("network"))
+ const deliveryFailure = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-update",
+ { method: "POST" },
+ ), env as any)
+ expect(deliveryFailure.status).toBe(503)
+ expect(await deliveryFailure.json()).toEqual({ error: "failed to forward machine update" })
+ })
+ })
+
describe("POST /community-machine/by-id/:machineId/forward-agent-reset", () => {
const validBody = {
agentId: "bot-1",
diff --git a/src/ws-do/src/routes/community-machine-lifecycle.ts b/src/ws-do/src/routes/community-machine-lifecycle.ts
index 277c44a40..24c28903c 100644
--- a/src/ws-do/src/routes/community-machine-lifecycle.ts
+++ b/src/ws-do/src/routes/community-machine-lifecycle.ts
@@ -1,6 +1,61 @@
import { queries } from "@alook/shared"
import type { RouterContext } from "../router-context"
+export async function handleMachineUpdate({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ const forwardUpdate = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-update$/)
+ if (!forwardUpdate || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(forwardUpdate[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding machine:update to machine")
+
+ let doNames: string[]
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for update", { err })
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })
+ }
+ if (doNames.length === 0) return Response.json({ sent: 0 })
+
+ const frame = JSON.stringify({ type: "machine:update" })
+ let delivered = 0
+ let transientFailure = false
+ for (const doName of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + doName)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const response = await stub.fetch(new Request("http://internal/push", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: frame,
+ }))
+ if (!response.ok) {
+ transientFailure = true
+ continue
+ }
+ const data = await response.json() as { sent?: unknown }
+ if (
+ typeof data.sent !== "number"
+ || !Number.isSafeInteger(data.sent)
+ || data.sent < 0
+ ) {
+ transientFailure = true
+ continue
+ }
+ delivered += data.sent
+ } catch {
+ transientFailure = true
+ }
+ }
+ if (delivered === 0 && transientFailure) {
+ return Response.json({ error: "failed to forward machine update" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+}
+
export async function handleMachineReset({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
// POST /community-machine/by-id/<machineId>/forward-agent-reset — owner-
// triggered `agent:reset` push. Same shape as `/forward-agent-wake`: build
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index 9fa3a17b3..dd22b7fe5 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -117,7 +117,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {
await handleWebSocketClose(
this.domainContext(),
ws,
- (state) => handleCommunityMachineClose(this.domainContext(), state),
+ (state) => handleCommunityMachineClose(this.domainContext(), state, ws),
)
}
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index 206355d67..e76554864 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -454,7 +454,7 @@ describe("WebSocketDurableObject", () => {
)
})
- it("emits machine.updated for status or lastError drift and emits nothing for steady runtimes", async () => {
+ it("emits machine.updated for status or lastError drift and emits nothing for steady metadata", async () => {
const { durable, store } = createDO()
seedIdentity(store)
const baseMachine = {
@@ -468,6 +468,7 @@ describe("WebSocketDurableObject", () => {
machine: baseMachine,
priorLastSeenAt: "2026-08-07T00:00:00.000Z",
priorAvailableRuntimes: [{ id: "codex", version: "1", status: "healthy" }],
+ priorDaemonVersion: "",
priorStatus: "online",
})
@@ -489,6 +490,7 @@ describe("WebSocketDurableObject", () => {
machine: baseMachine,
priorLastSeenAt: "2026-08-08T00:00:00.000Z",
priorAvailableRuntimes: baseMachine.availableRuntimes,
+ priorDaemonVersion: "",
priorStatus: "online",
})
@@ -496,5 +498,40 @@ describe("WebSocketDurableObject", () => {
expect(mockStubFetch).not.toHaveBeenCalled()
})
+
+ it("emits machine.updated when daemonVersion alone changes", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ daemonVersion: "0.1.7",
+ availableRuntimes: [],
+ status: "online",
+ lastSeenAt: "2026-08-08T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-08-07T00:00:00.000Z",
+ priorAvailableRuntimes: [],
+ priorDaemonVersion: "0.1.6",
+ priorStatus: "online",
+ })
+
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({
+ type: "ready",
+ runtimeReport: [],
+ runningAgents: [],
+ daemonVersion: "0.1.7",
+ }),
+ )
+
+ const bodies = await Promise.all(
+ mockStubFetch.mock.calls.map((call: any[]) => (call[0] as Request).clone().json() as Promise<any>),
+ )
+ expect(bodies.filter((body) => body.type === "community:machine.updated")).toHaveLength(1)
+ expect(bodies.find((body) => body.type === "community:machine.updated")?.machine.daemonVersion).toBe("0.1.7")
+ })
})
})
diff --git a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
index c17e99a09..fac7a3866 100644
--- a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
+++ b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
@@ -152,6 +152,140 @@ describe("WebSocketDurableObject", () => {
// the alarm has no state to act on either.
expect(ctx.storage.setAlarm).not.toHaveBeenCalled()
})
+
+ it("keeps online state and DO identity when a replacement socket becomes ready before the old socket closes", async () => {
+ const { durable, store, getWebSockets, ctx } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "same-cmk",
+ })
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ await ctx.storage.setAlarm(Date.now() + 90_000)
+
+ const oldSocket = createMockWebSocket()
+ oldSocket.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ const newSocket = createMockWebSocket()
+ newSocket.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([oldSocket, newSocket])
+
+ mockUpsertMachineByMachineId.mockResolvedValueOnce({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ daemonVersion: "0.1.7",
+ availableRuntimes: [],
+ status: "online",
+ lastSeenAt: "2026-08-13T08:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-08-13T07:59:00.000Z",
+ priorAvailableRuntimes: [],
+ priorDaemonVersion: "0.1.6",
+ priorStatus: "online",
+ })
+ await durable.webSocketMessage(
+ newSocket as any,
+ JSON.stringify({
+ type: "ready",
+ runtimeReport: [],
+ runningAgents: [],
+ daemonVersion: "0.1.7",
+ }),
+ )
+ expect(mockUpsertMachineByMachineId).toHaveBeenCalledTimes(1)
+
+ mockStubFetch.mockClear()
+ ;(ctx.storage.deleteAlarm as any).mockClear?.()
+ await durable.webSocketClose(oldSocket as any)
+
+ expect(mockMarkMachineOffline).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ expect(ctx.storage.deleteAlarm).not.toHaveBeenCalled()
+ expect(store.get("community-machine-identity")).toEqual({
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "same-cmk",
+ })
+ expect(store.get("community-machine-handle")).toEqual({
+ userId: "u_1",
+ machineId: "cm_1",
+ })
+ })
+
+ it("does not count the closing socket itself as a live replacement", async () => {
+ const { durable, store, getWebSockets } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "credential",
+ })
+ const closing = createMockWebSocket()
+ closing.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([closing])
+ mockMarkMachineOffline.mockResolvedValueOnce(null)
+
+ await durable.webSocketClose(closing as any)
+
+ expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
+ })
+
+ it("does not let different-user, different-machine, or unauthenticated sockets suppress offline", async () => {
+ const { durable, store, getWebSockets } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "credential",
+ })
+ const closing = createMockWebSocket()
+ closing.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ const otherMachine = createMockWebSocket()
+ otherMachine.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_2",
+ userId: "u_1",
+ authenticated: true,
+ })
+ const otherUser = createMockWebSocket()
+ otherUser.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_2",
+ authenticated: true,
+ })
+ const unauthenticated = createMockWebSocket()
+ unauthenticated.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: false,
+ })
+ getWebSockets.mockReturnValue([closing, otherMachine, otherUser, unauthenticated])
+ mockMarkMachineOffline.mockResolvedValueOnce(null)
+
+ await durable.webSocketClose(closing as any)
+
+ expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
+ })
})
describe("community-machine — alarm presence + backfill", () => {
diff --git a/src/ws-do/src/ws-durable/machine-lifecycle.ts b/src/ws-do/src/ws-durable/machine-lifecycle.ts
index 5a2e4f020..0adde6d26 100644
--- a/src/ws-do/src/ws-durable/machine-lifecycle.ts
+++ b/src/ws-do/src/ws-durable/machine-lifecycle.ts
@@ -26,10 +26,20 @@ export async function scheduleHeartbeatAlarm(context: WsDurableContext): Promise
export async function handleCommunityMachineClose(
context: WsDurableContext,
state: CommunityMachineConnectionState,
+ closingSocket: WebSocket,
): Promise<void> {
context.log.info("community machine websocket closed", { machineId: state.machineId, userId: state.userId })
const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
if (!identity) return
+ const replacementIsLive = context.ctx.getWebSockets().some((socket) => {
+ if (socket === closingSocket) return false
+ const candidate = socket.deserializeAttachment() as ConnectionState
+ return candidate?.type === "community-machine"
+ && candidate.authenticated
+ && candidate.userId === state.userId
+ && candidate.machineId === state.machineId
+ })
+ if (replacementIsLive) return
try {
const db = createDb(context.env.DB)
const flipped = await queries.communityMachine.markMachineOffline(db, {
diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.ts
index 752b79fc0..b17d90a04 100644
--- a/src/ws-do/src/ws-durable/machine-ready.ts
+++ b/src/ws-do/src/ws-durable/machine-ready.ts
@@ -82,7 +82,7 @@ export async function handleReadyFrame(
context.log.warn("community machine row missing on ready", { machineId: identity.machineId })
return true
}
- const { machine, priorAvailableRuntimes, priorStatus } = result
+ const { machine, priorAvailableRuntimes, priorDaemonVersion, priorStatus } = result
// Reconciliation is the coarse safety net for an activity frame lost
// during disconnect. It clears only stale system-owned activity pills;
@@ -126,7 +126,7 @@ export async function handleReadyFrame(
const nextCanonical = canonicalRuntimes(availableRuntimes)
// Runtime status/lastError drift is machine metadata drift and must reach
// open clients even when the runtime set and versions are unchanged.
- if (priorCanonical !== nextCanonical) {
+ if (priorCanonical !== nextCanonical || priorDaemonVersion !== daemonVersion) {
await notifyUserDO(context, identity.userId, {
type: WS_EVENTS.MACHINE_UPDATED,
machine: summary,
diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.ts
index bc3481094..1cb76d910 100644
--- a/tests/integration/daemon/control-plane.test.ts
+++ b/tests/integration/daemon/control-plane.test.ts
@@ -128,7 +128,7 @@ describe("daemon control plane — real ws-do wake round-trip", () => {
receivedCommands.push(cmd)
})
channel.onResync(() => ({
- ready: { runtimeReport: [{ id: "claude" }], runningAgents: [] },
+ ready: { runtimeReport: [{ id: "claude" }], runningAgents: [], daemonVersion: "0.1.7" },
sessions: [],
activities: [],
}))
@@ -204,6 +204,26 @@ describe("daemon control plane — real ws-do wake round-trip", () => {
await waitForChannelReply(fixture.channelId, cookie, replyText)
}, 30_000)
+ it("forwards the owner-scoped update API through the real ws-do as the exact machine:update command", async () => {
+ expect(channel).toBeDefined()
+ const received: HostCommand[] = []
+ channel!.onCommand((command) => received.push(command))
+
+ const response = await sessionRequest(
+ `/api/community/machines/${fixture.paired.machineId}/update`,
+ cookie,
+ { method: "POST" },
+ )
+
+ await assertResOk(response, "machine update dispatch")
+ expect(await response.json()).toEqual({ dispatched: true })
+ const update = await waitFor(
+ () => received.find((command) => command.type === "machine:update"),
+ 15_000,
+ )
+ expect(update).toEqual({ type: "machine:update" })
+ }, 30_000)
+
it("reports agent_activity over the real WsControlChannel and the profile route reflects running, then idle after the stub session ends its turn", async () => {
// Reuses the already-open `channel` from the first test — asserts the
// wire-level `agent_activity` frame this plan adds actually persists and