Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
Fix daemon session lease reconnect (#494)
Gustavo Ye734da5d725f1
diff --git a/.env.example b/.env.exampleindex 7b889e14f..8be7b87f5 100644--- a/.env.example+++ b/.env.example@@ -128,8 +128,9 @@# WebSocket Durable Object port (dev only, must match src/ws-do/wrangler.toml)# NEXT_PUBLIC_WS_DO_PORT=8789-# The community pair sheet's copyable `npx @alook/daemon daemon start-# --server-url <...> --ws-url <...>` command derives both URLs from the+# The community pair sheet's copyable `npm exec --yes+# --package=@alook/daemon@latest -- alook-daemon daemon start --server-url <...>+# --ws-url <...>` command derives both URLs from the# browser's own location.origin (same pattern as use-user-ws.ts) — ws-do routes# community-daemon connections by their `Authorization: Bearer cmk_...`# header, not by host, so there's no dedicated env var for it. Seediff --git a/src/daemon/README.md b/src/daemon/README.mdindex e47c92b9a..5fdfec440 100644--- a/src/daemon/README.md+++ b/src/daemon/README.md@@ -25,6 +25,42 @@ is what's reusable — plug in whatever host you like.---+## Daemon lifecycle commands++The web Machines sheet generates the full command, including the correct HTTP+and WebSocket endpoints. Published-package commands use the package's explicit+binary so npm never guesses the wrong executable:++```sh+npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon start \+ --machine-key '<cmt_pair_token>' --server-url '<https_url>' --ws-url '<wss_url>'+```++Restart a previously paired machine without rotating its credential:++```sh+npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon start --id '<machine_id>'+```++Reconnect/rotate only with the command generated for that exact machine:++```sh+npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon reconnect \+ --id '<machine_id>' --machine-key '<cmt_reconnect_token>'+```++Reconnect first takes replacement ownership and stops only the matching saved+PID, then activates the token. A proven pre-commit rejection resumes the prior+launch record. If a committed response is received and local launch then fails,+the newly persisted record remains offline and is recovered with+`daemon start --id '<machine_id>'`. A network error, timeout, 5xx, or otherwise+ambiguous activation response never restarts the possibly revoked old credential;+because the new credential was not received, mint a fresh reconnect token in the+UI and run `daemon reconnect` again. Never paste pairing or machine credentials+into logs, bug reports, or chat.++---+## The big ideaThe daemon never speaks a runtime's native protocol directly. Each runtime isdiff --git a/src/daemon/src/cli/daemonStart.lifecycle.test.ts b/src/daemon/src/cli/daemonStart.lifecycle.test.tsindex f4b0c3c1d..d9ea0bb81 100644--- a/src/daemon/src/cli/daemonStart.lifecycle.test.ts+++ b/src/daemon/src/cli/daemonStart.lifecycle.test.ts@@ -16,7 +16,14 @@ vi.mock("../discovery", async (importOriginal) => ({resolveAlookCliPathWithFallback: vi.fn(() => undefined),}));-import { daemonRunFromIpc, daemonStart, daemonStartById } from "./daemonStart";+import {+ acquireDaemonReplacementLock,+ daemonReconnect,+ daemonRunFromIpc,+ daemonStart,+ daemonStartById,+ removeReplacementLockIfMatches,+} from "./daemonStart";import { readDaemonVersion } from "../version";describe("daemon lifecycle ownership cleanup", () => {@@ -33,10 +40,216 @@ describe("daemon lifecycle ownership cleanup", () => {});afterEach(() => {+ delete process.env.ALOOK_DAEMON_TEST_FAIL_AFTER_ACTIVATE;+ vi.useRealTimers();vi.restoreAllMocks();fs.rmSync(baseDir, { recursive: true, force: true });});+ function writeReconnectState(machineId = "cm_machine_reconnect") {+ const daemonDir = path.join(baseDir, "daemons", machineId);+ fs.mkdirSync(daemonDir, { recursive: true });+ fs.writeFileSync(path.join(baseDir, "daemons", `${machineId}.credential.json`), JSON.stringify({+ schemaVersion: 1,+ credential: "cmk_old",+ machineId,+ serverUrl: "http://server",+ wsUrl: "ws://server",+ daemonVersion: readDaemonVersion(),+ }), { mode: 0o600 });+ fs.writeFileSync(path.join(daemonDir, "daemon.pid"), JSON.stringify({+ pid: 424_242,+ machineId,+ startedAt: "2026-08-18T00:00:00.000Z",+ ownerToken: "old-owner",+ }), { mode: 0o600 });+ return { machineId, daemonDir };+ }++ it("fails exact-machine ownership before activation when replacement is already owned", async () => {+ const { machineId, daemonDir } = writeReconnectState();+ fs.writeFileSync(path.join(daemonDir, "daemon.replace.lock"), JSON.stringify({+ pid: process.pid,+ machineId,+ startedAt: new Date().toISOString(),+ ownerToken: "other-owner",+ requestId: "other_request_123456",+ }), { mode: 0o600 });+ const stop = vi.fn(async () => {});++ await expect(daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {+ isProcessAlive: () => true,+ stopExactDaemonPid: stop,+ })).rejects.toThrow("replacement already in progress");++ expect(fetch).not.toHaveBeenCalled();+ expect(stop).not.toHaveBeenCalled();+ });++ it("ignores an unrelated first-pair coarse owner during exact-machine reconnect", async () => {+ const { machineId } = writeReconnectState();+ const coarsePath = path.join(baseDir, "daemons", ".start.lock");+ fs.writeFileSync(coarsePath, JSON.stringify({+ pid: process.pid,+ machineId: "coarse",+ startedAt: new Date().toISOString(),+ ownerToken: "unrelated-first-pair-owner",+ }), { mode: 0o600 });+ vi.mocked(globalThis.fetch).mockResolvedValue(new Response(JSON.stringify({+ credential: "cmk_rotated",+ machineId,+ expiresAt: null,+ sessionOutcome: "committed",+ }), { status: 200, headers: { "content-type": "application/json" } }));+ mockRunPreparedDaemon.mockResolvedValue(undefined);++ await expect(daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {+ isProcessAlive: () => true,+ stopExactDaemonPid: vi.fn(async () => {}),+ start: (opts) => daemonStart({ ...opts, foreground: true }),+ })).resolves.toBeUndefined();++ expect(globalThis.fetch).toHaveBeenCalledOnce();+ expect(mockRunPreparedDaemon).toHaveBeenCalledOnce();+ expect(JSON.parse(fs.readFileSync(coarsePath, "utf8"))).toMatchObject({+ ownerToken: "unrelated-first-pair-owner",+ });+ });++ it("restores the old epoch only for an explicit pre-commit 4xx", async () => {+ const { machineId } = writeReconnectState();+ vi.mocked(globalThis.fetch).mockResolvedValue(new Response(+ JSON.stringify({ error: "token mismatch", sessionOutcome: "not_committed" }),+ { status: 409, headers: { "content-type": "application/json" } },+ ));+ const stop = vi.fn(async () => {});+ const resume = vi.fn(async () => {});++ await expect(daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {+ isProcessAlive: () => true,+ stopExactDaemonPid: stop,+ resume,+ })).rejects.toThrow("token mismatch");++ expect(stop).toHaveBeenCalledWith(424_242);+ expect(resume).toHaveBeenCalledOnce();+ expect(stop.mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(globalThis.fetch).mock.invocationCallOrder[0]!);+ });++ it.each([+ ["HTTP 500 after a possible commit", () => Promise.resolve(new Response(+ JSON.stringify({ error: "ambiguous", sessionOutcome: "not_committed" }),+ { status: 500, headers: { "content-type": "application/json" } },+ ))],+ ["response loss", () => Promise.reject(new Error("socket reset"))],+ ["retry after a lost committed response", () => Promise.resolve(new Response(+ JSON.stringify({ error: "token already revoked", sessionOutcome: "unknown" }),+ { status: 409, headers: { "content-type": "application/json" } },+ ))],+ ])("never restores a revoked old epoch after %s", async (_name, response) => {+ const { machineId } = writeReconnectState();+ vi.mocked(globalThis.fetch).mockImplementation(response as typeof fetch);+ const resume = vi.fn(async () => {});++ await expect(daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {+ isProcessAlive: () => true,+ stopExactDaemonPid: vi.fn(async () => {}),+ resume,+ })).rejects.toThrow();++ expect(resume).not.toHaveBeenCalled();+ expect(JSON.parse(fs.readFileSync(+ path.join(baseDir, "daemons", `${machineId}.credential.json`),+ "utf8",+ ))).toMatchObject({ credential: "cmk_old", machineId });+ });++ it("bounds an unresponsive activation, never resumes the old epoch, and releases replacement ownership", async () => {+ vi.useFakeTimers();+ const { machineId } = writeReconnectState();+ vi.mocked(globalThis.fetch).mockImplementation((_input, init) => new Promise((_resolve, reject) => {+ const signal = init?.signal;+ expect(signal).toBeInstanceOf(AbortSignal);+ signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));+ }));+ const resume = vi.fn(async () => {});++ const reconnect = daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {+ isProcessAlive: () => true,+ stopExactDaemonPid: vi.fn(async () => {}),+ resume,+ });+ const rejected = expect(reconnect).rejects.toThrow("activation timed out");+ await vi.advanceTimersByTimeAsync(30_000);+ await rejected;++ expect(resume).not.toHaveBeenCalled();+ const replacement = acquireDaemonReplacementLock({+ baseDir,+ machineId,+ requestId: "timeout_recovery_probe",+ });+ removeReplacementLockIfMatches(replacement.path, replacement.lock);+ });++ it("persists the rotated epoch offline after local start failure and recovers that exact epoch by id", async () => {+ const { machineId, daemonDir } = writeReconnectState();+ const credentialPath = path.join(baseDir, "daemons", `${machineId}.credential.json`);+ const resume = vi.fn(async () => {});+ const stop = vi.fn(async () => {});+ const server = {+ status: "online" as "online" | "offline",+ credential: "cmk_old",+ rotations: 0,+ };++ vi.mocked(globalThis.fetch).mockImplementation(async (_input, init) => {+ const body = JSON.parse(String(init?.body)) as { expectedMachineId?: string };+ expect(body.expectedMachineId).toBe(machineId);+ server.rotations += 1;+ server.status = "offline";+ server.credential = "cmk_rotated";+ return new Response(JSON.stringify({+ credential: server.credential,+ machineId,+ expiresAt: null,+ sessionOutcome: "committed",+ }), { status: 200, headers: { "content-type": "application/json" } });+ });++ process.env.ALOOK_DAEMON_TEST_FAIL_AFTER_ACTIVATE = "1";+ await expect(daemonReconnect({ id: machineId, machineKey: "cmt_first_rotation", baseDir }, {+ isProcessAlive: () => true,+ stopExactDaemonPid: stop,+ resume,+ })).rejects.toThrow("start failure after activation");++ expect(server).toMatchObject({ status: "offline", credential: "cmk_rotated", rotations: 1 });+ expect(JSON.parse(fs.readFileSync(credentialPath, "utf8"))).toMatchObject({+ credential: "cmk_rotated",+ machineId,+ });+ expect(fs.existsSync(path.join(daemonDir, "daemon.pid"))).toBe(false);+ expect(resume).not.toHaveBeenCalled();+ expect(stop).toHaveBeenCalledOnce();++ delete process.env.ALOOK_DAEMON_TEST_FAIL_AFTER_ACTIVATE;+ mockRunPreparedDaemon.mockImplementationOnce(async (prepared) => {+ expect(prepared.machineKey).toBe("cmk_rotated");+ expect(prepared.machineId).toBe(machineId);+ server.status = "online";+ });+ await expect(daemonStartById({ id: machineId, baseDir, foreground: true })).resolves.toBeUndefined();++ expect(server).toEqual({ status: "online", credential: "cmk_rotated", rotations: 1 });+ expect(JSON.parse(fs.readFileSync(credentialPath, "utf8"))).toMatchObject({+ credential: "cmk_rotated",+ machineId,+ });+ expect(resume).not.toHaveBeenCalled();+ expect(stop).toHaveBeenCalledOnce();+ });+it("compare-deletes foreground final ownership and launch lock when runner init fails", async () => {const opts = {machineKey: "cmk_test",diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.tsindex 3929eb0b0..2ba041e53 100644--- a/src/daemon/src/cli/daemonStart.ts+++ b/src/daemon/src/cli/daemonStart.ts@@ -15,7 +15,11 @@ 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";+import {+ CommunityDaemonActivateErrorResponseSchema,+ CommunityDaemonActivateResponseSchema,+ parseReleaseVersion,+} from "@alook/shared";/*** Grace window for a daemon to exit on SIGTERM before we escalate to SIGKILL.@@ -28,6 +32,7 @@ const STOP_KILL_GRACE_MS = 2_000;/** How often `daemonStop` polls `isProcessAlive` while waiting on SIGTERM. */const POLL_MS = 100;const START_RECEIPT_TIMEOUT_MS = 15_000;+const PAIRING_ACTIVATION_TIMEOUT_MS = 30_000;const RUNNER_TERM_GRACE_MS = 2_000;const RUNNER_KILL_GRACE_MS = 2_000;const MACHINE_ID_PATTERN = /^cm_[A-Za-z0-9_-]{8,64}$/;@@ -401,11 +406,10 @@ export function acquireDaemonReplacementLock(args: {}/**- * 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- * start during the activate window (when a human is most likely to fire `start`- * twice). Handed off to the final machineId lock — acquire-final-THEN-release-- * coarse, never a naked gap (Claudette 架构#499). `.start.lock` holds the pid.+ * COARSE start-lock for first pairing only: the machineId isn't known until+ * after async `/activate`, so this baseDir-level lock blocks a duplicate local+ * start during that window. Exact-machine reconnect already owns its replacement+ * request and goes straight to the per-machine launch lock.*/function coarseStartLockPath(baseDir: string): string {return path.join(daemonsDir(baseDir), ".start.lock");@@ -754,6 +758,25 @@ export interface DaemonStartOpts {foreground?: boolean;/** Internal-only replacement lock bypass. Never exposed on normal start. */resumeRequestId?: string;+ /** Internal reconnect guard sent to /activate before any credential rotate. */+ expectedMachineId?: string;+ /** Internal reconnect state hook; never logs or exposes the pairing token. */+ onActivationAttempt?: () => void;+}++export interface DaemonReconnectOpts {+ id: string;+ machineKey: string;+ serverUrl?: string;+ wsUrl?: string;+ baseDir?: string;+}++export interface DaemonReconnectDeps {+ isProcessAlive?: (pid: number) => boolean;+ stopExactDaemonPid?: (pid: number) => Promise<void>;+ start?: typeof daemonStart;+ resume?: typeof daemonResume;}export interface DaemonLaunchRecord {@@ -861,24 +884,70 @@ async function activatePairingToken(osRelease: string,daemonVersion: string,runtimeReport: Array<{ id: string; version?: string; status?: "healthy" | "unhealthy"; lastError?: string; lastErrorAt?: string }>,+ expectedMachineId?: string,): Promise<{ credential: string; machineId: string }> {- const res = await fetch(`${serverUrl}/api/community/daemon/activate`, {- method: "POST",- headers: {- "content-type": "application/json",- authorization: `Bearer ${tokenId}`,- },- body: JSON.stringify({ hostname, platform, arch, osRelease, daemonVersion, runtimeReport }),- });- const json = (await res.json().catch(() => ({}))) as {- credential?: string;- machineId?: string;- error?: string;- };- if (!res.ok || !json.credential || !json.machineId) {- throw new Error(json.error ?? `activate failed (${res.status})`);+ let res: Response;+ let json: unknown;+ let timedOut = false;+ const controller = new AbortController();+ const timeout = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, PAIRING_ACTIVATION_TIMEOUT_MS);+ timeout.unref?.();+ try {+ res = await fetch(`${serverUrl}/api/community/daemon/activate`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${tokenId}`,+ },+ body: JSON.stringify({+ hostname,+ platform,+ arch,+ osRelease,+ daemonVersion,+ runtimeReport,+ ...(expectedMachineId ? { expectedMachineId } : {}),+ }),+ signal: controller.signal,+ });+ json = await res.json().catch(() => null);+ } catch (error) {+ throw new PairingActivationError(+ timedOut+ ? "activation timed out before commit status was known"+ : error instanceof Error ? error.message : String(error),+ "unknown",+ );+ } finally {+ clearTimeout(timeout);+ }+ if (!res.ok) {+ const parsed = CommunityDaemonActivateErrorResponseSchema.safeParse(json);+ throw new PairingActivationError(+ parsed.success ? parsed.data.error : `activate failed (${res.status})`,+ res.status >= 400 && res.status < 500 && parsed.success+ ? parsed.data.sessionOutcome+ : "unknown",+ );+ }+ const parsed = CommunityDaemonActivateResponseSchema.safeParse(json);+ if (!parsed.success) {+ throw new PairingActivationError("activate returned an invalid response", "unknown");+ }+ return { credential: parsed.data.credential, machineId: parsed.data.machineId };+}++class PairingActivationError extends Error {+ constructor(+ message: string,+ readonly sessionOutcome: "not_committed" | "unknown",+ ) {+ super(message);+ this.name = "PairingActivationError";}- return { credential: json.credential, machineId: json.machineId };}async function resolveMachineIdentity(serverUrl: string, credential: string): Promise<string> {@@ -912,12 +981,19 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>const persisted = opts.machineKey.startsWith("cmk_")? findExistingCredentialForBearer(baseDir, opts.machineKey): null;+ const reconnectMachineId = opts.machineKey.startsWith("cmt_")+ && opts.expectedMachineId+ && opts.resumeRequestId+ ? validateMachineId(opts.expectedMachineId)+ : undefined;let coarseLockPath: string | null = null;let launchLockPath: string | null = null;try {let machineKey = persisted?.credential;- let machineId = persisted ? validateMachineId(persisted.machineId) : undefined;- if (machineKey && machineId) {+ let machineId = persisted+ ? validateMachineId(persisted.machineId)+ : reconnectMachineId;+ if (machineId) {launchLockPath = acquireLaunchLock(baseDir, machineId, ownerToken, opts.resumeRequestId);} else {coarseLockPath = acquireCoarseLock(baseDir, ownerToken);@@ -930,6 +1006,7 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>.filter((runtime) => runtime.status === "healthy").map((runtime) => runtime.id);if (opts.machineKey.startsWith("cmt_")) {+ opts.onActivationAttempt?.();const activated = await activatePairingToken(serverUrl,opts.machineKey,@@ -939,9 +1016,16 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>os.release(),daemonVersion,runtimeReport,+ opts.expectedMachineId,);machineKey = activated.credential;machineId = validateMachineId(activated.machineId);+ if (+ opts.expectedMachineId &&+ machineId !== validateMachineId(opts.expectedMachineId)+ ) {+ throw new Error("activate returned a different machine identity");+ }} else {machineKey ??= opts.machineKey;machineId ??= validateMachineId(await resolveMachineIdentity(serverUrl, opts.machineKey));@@ -955,6 +1039,13 @@ async function prepareDaemonStart(opts: DaemonStartOpts): Promise<PreparedStart>wsUrl,daemonVersion,});+ if (+ process.env.NODE_ENV === "test" &&+ process.env.ALOOK_DAEMON_TEST_FAIL_AFTER_ACTIVATE === "1" &&+ opts.expectedMachineId+ ) {+ throw new Error("test-gated daemon start failure after activation");+ }if (coarseLockPath) removeOwnedFile(coarseLockPath, process.pid, ownerToken);const startedAt = new Date().toISOString();return {@@ -1025,6 +1116,84 @@ export async function daemonStartById(opts: {});}+function pidOwnershipEqual(a: DaemonPidFile | null, b: DaemonPidFile | null): boolean {+ if (!a || !b) return a === b;+ return a.pid === b.pid+ && a.machineId === b.machineId+ && a.startedAt === b.startedAt+ && a.ownerToken === b.ownerToken;+}++/**+ * Exact-machine reconnect. Replacement ownership is acquired before the old+ * PID is touched and held through activation plus replacement readiness.+ */+export async function daemonReconnect(+ opts: DaemonReconnectOpts,+ deps: DaemonReconnectDeps = {},+): Promise<void> {+ if (!opts.machineKey.startsWith("cmt_")) {+ throw new Error("daemon reconnect requires a cmt_ pairing token");+ }+ const machineId = validateMachineId(opts.id);+ const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;+ const launch = readDaemonLaunchRecord(baseDir, machineId);+ const pidPath = pidfilePathById(baseDir, machineId);+ const before = readPidFile(pidPath);+ if (+ before &&+ (before.machineId !== machineId || !before.startedAt || !before.ownerToken)+ ) {+ throw new Error("daemon reconnect cannot verify the current pid ownership tuple");+ }++ const requestId = crypto.randomUUID();+ const replacement = acquireDaemonReplacementLock({ baseDir, machineId, requestId });+ let oldStopped = false;+ let activationAttempted = false;+ try {+ const owned = readPidFile(pidPath);+ if (!pidOwnershipEqual(before, owned)) {+ throw new Error("daemon ownership changed after reconnect lock acquisition");+ }+ if (owned && (deps.isProcessAlive ?? isProcessAlive)(owned.pid)) {+ await (deps.stopExactDaemonPid ?? stopExactDaemonPid)(owned.pid);+ oldStopped = true;+ removePidFileIfMatches(pidPath, owned);+ } else if (owned) {+ removePidFileIfMatches(pidPath, owned);+ }++ try {+ await (deps.start ?? daemonStart)({+ machineKey: opts.machineKey,+ serverUrl: opts.serverUrl ?? launch.serverUrl,+ wsUrl: opts.wsUrl ?? launch.wsUrl,+ baseDir,+ resumeRequestId: requestId,+ expectedMachineId: machineId,+ onActivationAttempt: () => { activationAttempted = true; },+ });+ } catch (error) {+ const canRestoreOldEpoch = !activationAttempted+ || (error instanceof PairingActivationError && error.sessionOutcome === "not_committed");+ if (oldStopped && canRestoreOldEpoch) {+ try {+ await (deps.resume ?? daemonResume)({ id: machineId, baseDir, requestId });+ } catch (rollbackError) {+ throw new AggregateError(+ [error, rollbackError],+ "reconnect failed before rotation and the prior daemon could not be resumed",+ );+ }+ }+ throw error;+ }+ } finally {+ removeReplacementLockIfMatches(replacement.path, replacement.lock);+ }+}+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/index.test.ts b/src/daemon/src/cli/index.test.tsindex c381d3707..9d1d9e2f3 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -3,6 +3,7 @@ import { Readable } from "node:stream";const mockDaemonStart = vi.hoisted(() => vi.fn(async () => {}));const mockDaemonStartById = vi.hoisted(() => vi.fn(async () => {}));+const mockDaemonReconnect = vi.hoisted(() => vi.fn(async () => {}));const mockDaemonList = vi.hoisted(() => vi.fn(() => [{ id: "cm_saved_machine", pid: 42, alive: true, agents: 1, running: 0, lastActiveMs: 1 }]));const mockDaemonRunFromIpc = vi.hoisted(() => vi.fn(async () => new Promise<never>(() => {})));const mockArmMessageReminder = vi.hoisted(() => vi.fn(async () => ({ armed: true as const, dueAt: 123456 })));@@ -10,6 +11,7 @@ vi.mock("./daemonStart", async (importOriginal) => ({...await importOriginal<typeof import("./daemonStart")>(),daemonStart: mockDaemonStart,daemonStartById: mockDaemonStartById,+ daemonReconnect: mockDaemonReconnect,daemonList: mockDaemonList,daemonRunFromIpc: mockDaemonRunFromIpc,}));@@ -93,6 +95,7 @@ beforeEach(() => {cap = captureStdout();mockDaemonStart.mockClear();mockDaemonStartById.mockClear();+ mockDaemonReconnect.mockClear();mockDaemonRunFromIpc.mockClear();mockDaemonList.mockClear();process.env.ALOOK_AGENT_ID = "agent_test";@@ -138,6 +141,26 @@ describe("daemon command contract", () => {expect(mockDaemonStart).not.toHaveBeenCalled();});+ it("reconnects only with an explicit machine id and cmt token", async () => {+ await main([+ "daemon",+ "reconnect",+ "--id",+ "cm_saved_machine",+ "--machine-key",+ "cmt_reconnect",+ "--base-dir",+ "/tmp/alook-daemon",+ ]);+ expect(mockDaemonReconnect).toHaveBeenCalledWith({+ id: "cm_saved_machine",+ machineKey: "cmt_reconnect",+ baseDir: "/tmp/alook-daemon",+ serverUrl: undefined,+ wsUrl: undefined,+ });+ });+it("keeps missing and unknown arguments in the canonical Commander parser", async () => {await main(["daemon", "start"]);expect(parseEnvelope(cap.lines())).toEqual(expect.objectContaining({ error: expect.stringContaining("exactly one") }));diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 9284f4cae..9a3fea34b 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -21,7 +21,7 @@ import { pathToFileURL } from "node:url";import type { ServerApi, Cursor, Message, AckFailure } from "../server/contract.js";import { parseRef } from "../server/contract.js";import { proxyServerApiFromEnv } from "./proxyServerApi.js";-import { daemonResume, daemonRunFromIpc, daemonStart, daemonStartById, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";+import { daemonReconnect, daemonResume, daemonRunFromIpc, daemonStart, daemonStartById, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";import { daemonReplace } from "./daemonUpdate.js";import { armMessageReminderFromEnv, parseRemindAfter } from "./messageReminderClient.js";import { parseInviteToken } from "@alook/shared/lib/invite-link";@@ -1070,6 +1070,27 @@ function buildProgram(stdin: CliInputStream): Command {await daemonRunFromIpc();});+ daemon+ .command("reconnect")+ .description("rotate and reconnect one previously paired machine")+ .requiredOption("--id <machineId>", "machine id shown by daemon list")+ .requiredOption("--machine-key <key>", "cmt_ reconnect token")+ .option("--server-url <url>", "server HTTP URL (defaults to the saved launch record)")+ .option("--ws-url <url>", "server WebSocket URL (defaults to the saved launch record)")+ .option("--base-dir <path>", "data directory for agent workspaces and pidfile")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ await daemonReconnect({+ id: localOpts.id as string,+ machineKey: localOpts.machineKey as string,+ serverUrl: localOpts.serverUrl as string | undefined,+ wsUrl: localOpts.wsUrl as string | undefined,+ baseDir: localOpts.baseDir as string | undefined,+ });+ });+daemon.command("resume", { hidden: true }).requiredOption("--id <machineId>")diff --git a/src/desktop/src-tauri/src/commands.rs b/src/desktop/src-tauri/src/commands.rsindex 14837c9dd..ee7bf5b2c 100644--- a/src/desktop/src-tauri/src/commands.rs+++ b/src/desktop/src-tauri/src/commands.rs@@ -82,8 +82,14 @@ fn daemon_config_for(is_debug: bool) -> DaemonConfig {}} else {DaemonConfig {- command: "npx",- base_args: &["--yes", "@alook/daemon"],+ command: "npm",+ base_args: &[+ "exec",+ "--yes",+ "--package=@alook/daemon@latest",+ "--",+ "alook-daemon",+ ],cwd: None,}}@@ -91,7 +97,7 @@ fn daemon_config_for(is_debug: bool) -> DaemonConfig {#[cfg(desktop)]fn executable_for_platform(command: &str, is_windows: bool) -> String {- if is_windows && matches!(command, "npm" | "npx" | "pnpm") {+ if is_windows && matches!(command, "npm" | "pnpm") {format!("{command}.cmd")} else {command.to_string()@@ -225,8 +231,7 @@ async fn resolve_path() -> String {#[cfg(desktop)]async fn run_daemon(extra_args: &[String]) -> Result<DaemonOutput, String> {let cfg = daemon_config();- let mut args: Vec<String> = cfg.base_args.iter().map(|arg| (*arg).to_string()).collect();- args.extend_from_slice(extra_args);+ let args = daemon_argv(&cfg, extra_args);let mut command = Command::new(executable(cfg.command));command.env("PATH", resolve_path().await);@@ -242,6 +247,15 @@ async fn run_daemon(extra_args: &[String]) -> Result<DaemonOutput, String> {.await}+#[cfg(desktop)]+fn daemon_argv(cfg: &DaemonConfig, extra_args: &[String]) -> Vec<String> {+ cfg.base_args+ .iter()+ .map(|arg| (*arg).to_string())+ .chain(extra_args.iter().cloned())+ .collect()+}+#[cfg(desktop)]fn valid_machine_key(machine_key: &str) -> bool {let value = machine_key@@ -257,28 +271,57 @@ fn valid_machine_key(machine_key: &str) -> bool {}#[cfg(desktop)]-fn daemon_pair_args(machine_key: &str, is_debug: bool) -> Result<Vec<String>, String> {+fn valid_machine_id(machine_id: &str) -> bool {+ let Some(value) = machine_id.strip_prefix("cm_") else {+ return false;+ };+ (8..=64).contains(&value.len())+ && value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')+}++#[cfg(desktop)]+fn daemon_pair_args(+ machine_key: &str,+ machine_id: Option<&str>,+ is_debug: bool,+) -> Result<Vec<String>, String> {if !valid_machine_key(machine_key) {return Err("invalid Community machine key".to_string());}+ if let Some(machine_id) = machine_id {+ if !machine_key.starts_with("cmt_") || !valid_machine_id(machine_id) {+ return Err("invalid Community reconnect identity".to_string());+ }+ }let (server_url, ws_url) = daemon_endpoints_for(is_debug);- Ok(vec![+ let mut args = vec!["daemon".to_string(),- "start".to_string(),+ if machine_id.is_some() {+ "reconnect".to_string()+ } else {+ "start".to_string()+ },+ ];+ if let Some(machine_id) = machine_id {+ args.extend(["--id".to_string(), machine_id.to_string()]);+ }+ args.extend(["--machine-key".to_string(),machine_key.to_string(),"--server-url".to_string(),server_url.to_string(),"--ws-url".to_string(),ws_url.to_string(),- ])+ ]);+ Ok(args)}#[cfg(desktop)]fn evaluate_runtime_capability(node: Result<String, String>,npm: Result<String, String>,- npx: Result<String, String>,) -> DaemonRuntimeCapability {let node_output = match node {Ok(output) => output,@@ -290,16 +333,14 @@ fn evaluate_runtime_capability(};}};- for result in [npm, npx] {- if let Err(reason) = result {- return DaemonRuntimeCapability {- available: false,- reason: Some(format!(- "Node.js is available, but {reason}. Install npm with Node.js and try again."- )),- node_version: (!node_output.is_empty()).then_some(node_output),- };- }+ if let Err(reason) = npm {+ return DaemonRuntimeCapability {+ available: false,+ reason: Some(format!(+ "Node.js is available, but {reason}. Install npm with Node.js and try again."+ )),+ node_version: (!node_output.is_empty()).then_some(node_output),+ };}DaemonRuntimeCapability {available: true,@@ -466,18 +507,20 @@ pub fn close_splashscreen(app: AppHandle) {#[tauri::command]pub async fn daemon_runtime_capability() -> DaemonRuntimeCapability {let path = resolve_path().await;- let (node, npm, npx) = tokio::join!(+ let (node, npm) = tokio::join!(probe_runtime_command("node", path.clone()),- probe_runtime_command("npm", path.clone()),- probe_runtime_command("npx", path),+ probe_runtime_command("npm", path),);- evaluate_runtime_capability(node, npm, npx)+ evaluate_runtime_capability(node, npm)}#[cfg(desktop)]#[tauri::command]-pub async fn daemon_pair(machine_key: String) -> Result<CommandResult, String> {- let args = daemon_pair_args(&machine_key, cfg!(debug_assertions))?;+pub async fn daemon_pair(+ machine_key: String,+ machine_id: Option<String>,+) -> Result<CommandResult, String> {+ let args = daemon_pair_args(&machine_key, machine_id.as_deref(), cfg!(debug_assertions))?;let output = run_daemon(&args).await?;if output.success {Ok(CommandResult {@@ -832,30 +875,21 @@ mod tests {use super::*;#[test]- fn runtime_capability_requires_node_npm_and_npx() {+ fn runtime_capability_requires_node_and_npm() {let ok = || Ok("10.9.3".to_string());- let old = evaluate_runtime_capability(Ok("v16.0.0".to_string()), ok(), ok());+ let old = evaluate_runtime_capability(Ok("v16.0.0".to_string()), ok());assert!(old.available);assert_eq!(old.node_version.as_deref(), Some("v16.0.0"));- let unrecognized = evaluate_runtime_capability(Ok("not-a-version".to_string()), ok(), ok());+ let unrecognized = evaluate_runtime_capability(Ok("not-a-version".to_string()), ok());assert!(unrecognized.available);let missing_npm = evaluate_runtime_capability(Ok("v22.0.0".to_string()),Err("npm was not found".to_string()),- ok(),);assert!(!missing_npm.available);assert!(missing_npm.reason.unwrap().contains("npm was not found"));-- let missing_npx = evaluate_runtime_capability(- Ok("v22.0.0".to_string()),- ok(),- Err("npx was not found".to_string()),- );- assert!(!missing_npx.available);- assert!(missing_npx.reason.unwrap().contains("npx was not found"));}#[test]@@ -882,18 +916,53 @@ mod tests {assert!(debug.cwd.is_some());let release = daemon_config_for(false);- assert_eq!(release.command, "npx");- assert_eq!(release.base_args, &["--yes", "@alook/daemon"]);+ assert_eq!(release.command, "npm");+ assert_eq!(+ release.base_args,+ &[+ "exec",+ "--yes",+ "--package=@alook/daemon@latest",+ "--",+ "alook-daemon",+ ]+ );assert!(release.cwd.is_none());}+ #[test]+ fn release_pairing_uses_the_exact_published_bin_argv() {+ let key = "cmt_abcdefghijklmnopqrstuvwxyz012345";+ let extra = daemon_pair_args(key, Some("cm_abcdefgh"), false).unwrap();+ let cfg = daemon_config_for(false);+ assert_eq!(+ daemon_argv(&cfg, &extra),+ vec![+ "exec",+ "--yes",+ "--package=@alook/daemon@latest",+ "--",+ "alook-daemon",+ "daemon",+ "reconnect",+ "--id",+ "cm_abcdefgh",+ "--machine-key",+ key,+ "--server-url",+ "https://alook.ai",+ "--ws-url",+ "wss://alook.ai/api/ws/community-daemon",+ ]+ );+ }+#[test]fn windows_uses_command_shims_for_node_package_tools() {assert_eq!(executable_for_platform("node", true), "node");assert_eq!(executable_for_platform("npm", true), "npm.cmd");- assert_eq!(executable_for_platform("npx", true), "npx.cmd");assert_eq!(executable_for_platform("pnpm", true), "pnpm.cmd");- assert_eq!(executable_for_platform("npx", false), "npx");+ assert_eq!(executable_for_platform("npm", false), "npm");}#[test]@@ -914,7 +983,7 @@ mod tests {"cmt_abcdefghijklmnopqrstuvwxyz012345","cmk_abcDEF0123456789_-abcdefghijklmn",] {- let args = daemon_pair_args(key, false).unwrap();+ let args = daemon_pair_args(key, None, false).unwrap();assert_eq!(args,vec![@@ -937,13 +1006,37 @@ mod tests {"cm_machine_1234","--server-url=https://example.com",] {- assert!(daemon_pair_args(invalid, false).is_err());+ assert!(daemon_pair_args(invalid, None, false).is_err());}}+ #[test]+ fn reconnect_builds_exact_machine_arguments_and_rejects_invalid_ids() {+ let key = "cmt_abcdefghijklmnopqrstuvwxyz012345";+ let args = daemon_pair_args(key, Some("cm_abcdefgh"), false).unwrap();+ assert_eq!(+ &args[..6],+ [+ "daemon",+ "reconnect",+ "--id",+ "cm_abcdefgh",+ "--machine-key",+ key,+ ]+ );+ assert!(daemon_pair_args(key, Some("bad"), false).is_err());+ assert!(daemon_pair_args(+ "cmk_abcDEF0123456789_-abcdefghijklmn",+ Some("cm_abcdefgh"),+ false,+ )+ .is_err());+ }+#[test]fn development_pairing_uses_only_fixed_local_endpoints() {- let args = daemon_pair_args("cmt_abcdefghijklmnopqrstuvwxyz012345", true).unwrap();+ let args = daemon_pair_args("cmt_abcdefghijklmnopqrstuvwxyz012345", None, true).unwrap();assert_eq!(args[5], "http://localhost:3000");assert_eq!(args[7], "ws://localhost:8789");assert_eq!(args.len(), 8);diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex af4cc9304..83ef2d1ef 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -53,6 +53,7 @@ export * as communityNotificationEligibility from "./queries/community/notificatexport * as communityServerFolder from "./queries/community/server-folder";export * as communityInbox from "./queries/community/inbox";export * as communityMachine from "./queries/community/machine";+export * as communityMachineSession from "./queries/community/machine-session-epoch";export * as communityBot from "./queries/community/bot";export * as communityAgentInbox from "./queries/community/agent-inbox";export * as communityBotAuditLog from "./queries/community/bot-audit-log";diff --git a/src/shared/src/db/queries/community/machine-session-epoch.ts b/src/shared/src/db/queries/community/machine-session-epoch.tsnew file mode 100644index 000000000..cc4fb6242--- /dev/null+++ b/src/shared/src/db/queries/community/machine-session-epoch.ts@@ -0,0 +1,418 @@+import { and, eq, inArray, isNull } from "drizzle-orm";+import {+ communityAgentRunnerKey,+ communityMachine,+ communityMachineCredential,+ communityMachineToken,+} from "../../community-machine-schema";+import type { Database } from "../../index";+import {+ doNameFromHash,+ hashCredential,+ type MachineMetadataInput,+ type MachineRow,+} from "./machine";++const CREDENTIAL_PREFIX = "cmk_";++export type MachineSessionEpochCommand =+ | {+ type: "rotate";+ tokenId: string;+ expectedMachineId?: string;+ metadata: MachineMetadataInput;+ }+ | {+ type: "ready";+ epoch: MachineSessionEpoch;+ metadata: MachineMetadataInput;+ }+ | { type: "renew"; epoch: MachineSessionEpoch }+ | { type: "close"; epoch: MachineSessionEpoch }+ | { type: "expire"; epoch: MachineSessionEpoch };++export interface MachineSessionEpoch {+ userId: string;+ machineId: string;+ credentialHash: string;+}++export type MachineSessionEpochResult =+ | {+ type: "rotated";+ credential: string;+ machineId: string;+ userId: string;+ revokedDoNames: string[];+ }+ | {+ type: "transitioned";+ machine: MachineRow;+ priorLastSeenAt: string | null;+ priorAvailableRuntimes: MachineRow["availableRuntimes"];+ priorDaemonVersion: string;+ priorStatus: "online" | "offline";+ }+ | { type: "stale_epoch" };++/**+ * The sole state-transition boundary for a daemon's server-side session.+ * Rotation replaces the credential epoch atomically; every live-lease write+ * is fenced by that epoch, so delayed work from a revoked DO is a no-op.+ */+export function transitionMachineSessionEpoch(+ db: Database,+ command: Extract<MachineSessionEpochCommand, { type: "rotate" }>,+): Promise<Extract<MachineSessionEpochResult, { type: "rotated" }>>;+export function transitionMachineSessionEpoch(+ db: Database,+ command: Exclude<MachineSessionEpochCommand, { type: "rotate" }>,+): Promise<Exclude<MachineSessionEpochResult, { type: "rotated" }>>;+export async function transitionMachineSessionEpoch(+ db: Database,+ command: MachineSessionEpochCommand,+): Promise<MachineSessionEpochResult> {+ if (command.type === "rotate") return rotateMachineSessionEpoch(db, command);+ return transitionLiveLease(db, command);+}++async function transitionLiveLease(+ db: Database,+ command: Exclude<MachineSessionEpochCommand, { type: "rotate" }>,+): Promise<MachineSessionEpochResult> {+ const { epoch } = command;+ const existing = await db+ .select()+ .from(communityMachine)+ .where(+ and(+ eq(communityMachine.userId, epoch.userId),+ eq(communityMachine.id, epoch.machineId),+ ),+ )+ .limit(1);+ if (existing.length === 0) return { type: "stale_epoch" };++ const prior = existing[0]!;+ const nowIso = new Date().toISOString();+ const values = command.type === "ready"+ ? {+ hostname: command.metadata.hostname ?? prior.hostname,+ displayName: command.metadata.hostname ?? prior.hostname,+ platform: command.metadata.platform ?? prior.platform,+ arch: command.metadata.arch ?? prior.arch,+ osRelease: command.metadata.osRelease ?? prior.osRelease,+ daemonVersion: command.metadata.daemonVersion ?? prior.daemonVersion,+ metadata: command.metadata.metadata !== undefined+ ? command.metadata.metadata+ : prior.metadata,+ availableRuntimes: command.metadata.availableRuntimes !== undefined+ ? command.metadata.availableRuntimes+ : prior.availableRuntimes,+ status: "online" as const,+ lastSeenAt: nowIso,+ updatedAt: nowIso,+ }+ : command.type === "renew"+ ? { status: "online" as const, lastSeenAt: nowIso, updatedAt: nowIso }+ : { status: "offline" as const, lastSeenAt: nowIso, updatedAt: nowIso };+ const statusGuard = command.type === "close" || command.type === "expire"+ ? eq(communityMachine.status, "online")+ : undefined;+ const currentEpochMachineIds = db+ .select({ machineId: communityMachineCredential.machineId })+ .from(communityMachineCredential)+ .where(+ and(+ eq(communityMachineCredential.credentialHash, epoch.credentialHash),+ isNull(communityMachineCredential.revokedAt),+ ),+ );+ const rows = await db+ .update(communityMachine)+ .set(values)+ .where(+ and(+ eq(communityMachine.id, prior.id),+ statusGuard,+ inArray(communityMachine.id, currentEpochMachineIds),+ ),+ )+ .returning();+ if (rows.length === 0) return { type: "stale_epoch" };++ return {+ type: "transitioned",+ machine: rows[0] as MachineRow,+ priorLastSeenAt: prior.lastSeenAt,+ priorAvailableRuntimes: prior.availableRuntimes,+ priorDaemonVersion: prior.daemonVersion,+ priorStatus: (prior.status as "online" | "offline") ?? "offline",+ };+}++async function rotateMachineSessionEpoch(+ db: Database,+ command: Extract<MachineSessionEpochCommand, { type: "rotate" }>,+): Promise<Extract<MachineSessionEpochResult, { type: "rotated" }>> {+ const nowIso = new Date().toISOString();+ const tokenRows = await db+ .select({+ id: communityMachineToken.id,+ userId: communityMachineToken.userId,+ machineId: communityMachineToken.machineId,+ status: communityMachineToken.status,+ expiresAt: communityMachineToken.expiresAt,+ })+ .from(communityMachineToken)+ .where(eq(communityMachineToken.id, command.tokenId))+ .limit(1);+ if (tokenRows.length === 0) {+ throw new MachineSessionRotationError("unknown", "unknown token", "not_committed");+ }+ const token = tokenRows[0]!;+ if (token.status === "revoked") {+ throw new MachineSessionRotationError("revoked", "token already revoked", "unknown");+ }+ if (token.status === "active") {+ throw new MachineSessionRotationError("already_active", "token already activated", "unknown");+ }+ if (token.expiresAt <= nowIso) {+ throw new MachineSessionRotationError("expired", "token expired", "not_committed");+ }+ if (token.machineId && !command.expectedMachineId) {+ throw new MachineSessionRotationError(+ "expected_machine_required",+ "reconnect requires an explicit expected machine id; update @alook/daemon and retry",+ "not_committed",+ );+ }+ if (command.expectedMachineId !== undefined && token.machineId !== command.expectedMachineId) {+ throw new MachineSessionRotationError(+ "machine_mismatch",+ "reconnect token does not match the expected machine",+ "not_committed",+ );+ }++ const claimed = await db+ .update(communityMachineToken)+ .set({ status: "revoked", lastUsedAt: nowIso })+ .where(+ and(+ eq(communityMachineToken.id, command.tokenId),+ eq(communityMachineToken.status, "pending"),+ ),+ )+ .returning({ id: communityMachineToken.id });+ if (claimed.length === 0) {+ throw new MachineSessionRotationError(+ "already_active",+ "token no longer claimable",+ "unknown",+ );+ }++ let credential: Awaited<ReturnType<typeof mintCredential>>;+ try {+ credential = await mintCredential();+ } catch (error) {+ await restoreClaimedToken(db, command.tokenId);+ throw error;+ }++ if (!token.machineId) {+ let machine: MachineRow;+ try {+ machine = await insertOfflineMachine(db, token.userId, command.metadata, nowIso);+ await db.insert(communityMachineCredential).values({+ userId: token.userId,+ machineId: machine.id,+ credentialHash: credential.hash,+ doName: credential.doName,+ createdAt: nowIso,+ });+ } catch (error) {+ await restoreClaimedToken(db, command.tokenId);+ throw error;+ }+ return {+ type: "rotated",+ credential: credential.bearer,+ machineId: machine.id,+ userId: token.userId,+ revokedDoNames: [],+ };+ }++ let prior: MachineRow;+ let revokedDoNames: string[];+ try {+ const existing = await db+ .select()+ .from(communityMachine)+ .where(+ and(+ eq(communityMachine.userId, token.userId),+ eq(communityMachine.id, token.machineId),+ ),+ )+ .limit(1);+ if (existing.length === 0) {+ throw new MachineSessionRotationError(+ "unknown",+ "reconnect token references missing machine",+ "unknown",+ );+ }+ prior = existing[0] as MachineRow;+ const priorCredentials = await db+ .select({ doName: communityMachineCredential.doName })+ .from(communityMachineCredential)+ .where(+ and(+ eq(communityMachineCredential.machineId, token.machineId),+ isNull(communityMachineCredential.revokedAt),+ ),+ );+ revokedDoNames = priorCredentials.map((row) => row.doName);+ } catch (error) {+ if (error instanceof MachineSessionRotationError && error.sessionOutcome === "unknown") {+ throw error;+ }+ await restoreClaimedToken(db, command.tokenId);+ throw error;+ }++ const hostname = command.metadata.hostname ?? prior.hostname;+ const updateMachine = db+ .update(communityMachine)+ .set({+ hostname,+ displayName: hostname,+ platform: command.metadata.platform ?? prior.platform,+ arch: command.metadata.arch ?? prior.arch,+ osRelease: command.metadata.osRelease ?? prior.osRelease,+ daemonVersion: command.metadata.daemonVersion ?? prior.daemonVersion,+ metadata: command.metadata.metadata !== undefined ? command.metadata.metadata : prior.metadata,+ availableRuntimes: command.metadata.availableRuntimes !== undefined+ ? command.metadata.availableRuntimes+ : prior.availableRuntimes,+ status: "offline",+ lastSeenAt: null,+ updatedAt: nowIso,+ })+ .where(+ and(+ eq(communityMachine.userId, token.userId),+ eq(communityMachine.id, token.machineId),+ ),+ )+ .returning();+ const revokeCredentials = db+ .update(communityMachineCredential)+ .set({ revokedAt: nowIso })+ .where(+ and(+ eq(communityMachineCredential.machineId, token.machineId),+ isNull(communityMachineCredential.revokedAt),+ ),+ );+ const insertCredential = db.insert(communityMachineCredential).values({+ userId: token.userId,+ machineId: token.machineId,+ credentialHash: credential.hash,+ doName: credential.doName,+ createdAt: nowIso,+ });+ const revokeRunnerKeys = db+ .update(communityAgentRunnerKey)+ .set({ revokedAt: nowIso })+ .where(+ and(+ eq(communityAgentRunnerKey.machineId, token.machineId),+ isNull(communityAgentRunnerKey.revokedAt),+ ),+ );+ // Once the batch is dispatched, a binding rejection is ambiguous: D1 may+ // have committed and the Worker may only have lost the response. Never+ // reopen the one-time token after dispatch; the client must fail closed and+ // mint a fresh reconnect token.+ await db.batch([+ updateMachine,+ revokeCredentials,+ insertCredential,+ revokeRunnerKeys,+ ]);++ // Commit boundary: after the batch resolves, do not await or inspect any+ // fallible result before reporting the newly committed epoch.+ return {+ type: "rotated",+ credential: credential.bearer,+ machineId: token.machineId,+ userId: token.userId,+ revokedDoNames,+ };+}++async function restoreClaimedToken(db: Database, tokenId: string): Promise<void> {+ await db+ .update(communityMachineToken)+ .set({ status: "pending", lastUsedAt: null })+ .where(eq(communityMachineToken.id, tokenId));+}++async function mintCredential(): Promise<{ bearer: string; hash: string; doName: string }> {+ const { nanoid } = await import("nanoid");+ const bearer = CREDENTIAL_PREFIX + nanoid(32);+ const hash = await hashCredential(bearer);+ return { bearer, hash, doName: doNameFromHash(hash) };+}++async function insertOfflineMachine(+ db: Database,+ userId: string,+ metadata: MachineMetadataInput,+ nowIso: string,+): Promise<MachineRow> {+ const hostname = metadata.hostname ?? "";+ const rows = await db+ .insert(communityMachine)+ .values({+ userId,+ displayName: hostname,+ hostname,+ platform: metadata.platform ?? "",+ arch: metadata.arch ?? "",+ osRelease: metadata.osRelease ?? "",+ daemonVersion: metadata.daemonVersion ?? "",+ metadata: metadata.metadata ?? null,+ availableRuntimes: metadata.availableRuntimes ?? [],+ status: "offline",+ lastSeenAt: null,+ createdAt: nowIso,+ updatedAt: nowIso,+ })+ .returning();+ return rows[0] as MachineRow;+}++export type MachineSessionRotationErrorKind =+ | "unknown"+ | "expired"+ | "revoked"+ | "already_active"+ | "expected_machine_required"+ | "machine_mismatch";++export class MachineSessionRotationError extends Error {+ constructor(+ public readonly kind: MachineSessionRotationErrorKind,+ message: string,+ public readonly sessionOutcome: "not_committed" | "unknown",+ ) {+ super(message);+ this.name = "MachineSessionRotationError";+ }+}diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.tsindex 8352f564d..d78373929 100644--- a/src/shared/src/db/queries/community/machine.ts+++ b/src/shared/src/db/queries/community/machine.ts@@ -1,4 +1,4 @@-import { and, eq, gt, desc, isNull, inArray, sql } from "drizzle-orm";+import { and, eq, gt, desc, isNull, inArray } from "drizzle-orm";import {communityMachineToken,communityMachine,@@ -239,142 +239,6 @@ export interface MachineRow {updatedAt: string;}-/**- * Upsert-by-machine-id — the runtime path used by every `ready` frame and- * every /activate reconnect. First-pair /activate calls `insertMachineRow`- * instead (below) so the machine.id is minted by the insert.- *- * `markOnline` (default true) gates the `status: "online"` / `lastSeenAt`- * write. The WS `ready`-frame handler is the only caller that actually KNOWS- * there's a live socket, so it uses the default. /activate reconnect calls- * this with `markOnline: false` — HTTP activation happens before the- * daemon's WS connects, so flipping status here would make the row already- * "online" by the time the real `ready` frame lands, and the DO's- * `priorStatus !== 'online'` broadcast guard (which gates the bot-presence- * fan-out, see `ws-durable.ts` `notifyUserDO`) would silently skip the- * notification. Leaving status untouched here mirrors `insertMachineRow`,- * which already withholds `lastSeenAt` for the same reason on first pair.- */-export async function upsertMachineByMachineId(- db: Database,- userId: string,- machineId: string,- meta: MachineMetadataInput,- opts: { markOnline?: boolean } = {}-): Promise<{- machine: MachineRow;- priorLastSeenAt: string | null;- priorAvailableRuntimes: CommunityMachineRuntime[];- priorDaemonVersion: string;- priorStatus: "online" | "offline";-} | null> {- const markOnline = opts.markOnline ?? true;- const existing = await db- .select()- .from(communityMachine)- .where(- and(- eq(communityMachine.userId, userId),- eq(communityMachine.id, machineId)- )- )- .limit(1);- if (existing.length === 0) return null;-- const prior = existing[0]!;- const hostname = meta.hostname ?? prior.hostname;- const nowIso = new Date().toISOString();- const rows = await db- .update(communityMachine)- .set({- hostname,- displayName: hostname,- platform: meta.platform ?? prior.platform,- arch: meta.arch ?? prior.arch,- osRelease: meta.osRelease ?? prior.osRelease,- daemonVersion: meta.daemonVersion ?? prior.daemonVersion,- metadata: meta.metadata !== undefined ? meta.metadata : prior.metadata,- availableRuntimes:- meta.availableRuntimes !== undefined- ? meta.availableRuntimes- : prior.availableRuntimes,- ...(markOnline ? { status: "online" as const, lastSeenAt: nowIso } : {}),- updatedAt: nowIso,- })- .where(eq(communityMachine.id, prior.id))- .returning();- return {- machine: rows[0] as MachineRow,- priorLastSeenAt: prior.lastSeenAt,- priorAvailableRuntimes: prior.availableRuntimes,- priorDaemonVersion: prior.daemonVersion,- priorStatus: (prior.status as "online" | "offline") ?? "offline",- };-}--/**- * Insert a brand-new community_machine row and return it. Used by /activate- * when the pairing token isn't bound to an existing machine.- */-async function insertMachineRow(- db: Database,- userId: string,- meta: MachineMetadataInput-): Promise<MachineRow> {- const hostname = meta.hostname ?? "";- const nowIso = new Date().toISOString();- const rows = await db- .insert(communityMachine)- .values({- userId,- displayName: hostname,- hostname,- platform: meta.platform ?? "",- arch: meta.arch ?? "",- osRelease: meta.osRelease ?? "",- daemonVersion: meta.daemonVersion ?? "",- metadata: meta.metadata ?? null,- availableRuntimes: meta.availableRuntimes ?? [],- // `lastSeenAt` stays null until the daemon's WS `ready` frame lands.- // Setting it to `nowIso` here would flash a green "online" chip for- // ~90s even if the daemon dies between HTTP activate and WS connect.- lastSeenAt: null,- createdAt: nowIso,- updatedAt: nowIso,- })- .returning();- return rows[0] as MachineRow;-}--/**- * Bump `last_seen_at` for a paired machine. Scopes by `machineId` (the- * primary key), matching the Bearer-credential dial path.- */-export async function touchMachineHeartbeat(- db: Database,- userId: string,- machineId: string-): Promise<{ lastSeenAt: string; priorLastSeenAt: string | null } | null> {- const existing = await db- .select({ id: communityMachine.id, lastSeenAt: communityMachine.lastSeenAt })- .from(communityMachine)- .where(- and(- eq(communityMachine.userId, userId),- eq(communityMachine.id, machineId)- )- )- .limit(1);- if (existing.length === 0) return null;- const prior = existing[0]!;- const nowIso = new Date().toISOString();- await db- .update(communityMachine)- .set({ lastSeenAt: nowIso, updatedAt: nowIso })- .where(eq(communityMachine.id, prior.id));- return { lastSeenAt: nowIso, priorLastSeenAt: prior.lastSeenAt };-}-// ---------------------------------------------------------------------------// Bot activity telemetry — see plans/community-bot-status-telemetry.md.//@@ -442,159 +306,6 @@ export async function reconcileBotActivityFromRunningAgents(// Credential helpers — long-lived `cmk_` tokens the daemon dials with.// ----------------------------------------------------------------------------export interface ActivateMachineCredentialResult {- credential: string;- machineId: string;- userId: string;-}--/**- * Atomically exchange a pending pairing token for a long-lived credential.- *- * D1 has no interactive transactions, so operations are ordered so a- * mid-way failure leaves recoverable state:- * 1. verify token is pending + unexpired.- * 2. atomically flip pending → revoked (racing activates get zero rows).- * 3. resolve the machine row: reconnect (token.machineId set) reuses the- * existing row and revokes prior credentials; first-pair inserts a new- * row.- * 4. insert a new community_machine_credential row, storing sha256(cmk_)- * and its first-32-hex do_name prefix. The plaintext `cmk_` is- * returned to the caller and never persisted.- *- * On any post-flip failure, the token is rolled back to `pending` so the- * user can retry without regenerating.- */-export async function activateMachineCredential(- db: Database,- tokenId: string,- meta: MachineMetadataInput-): Promise<ActivateMachineCredentialResult> {- const nowIso = new Date().toISOString();-- const tokenRows = await db- .select({- id: communityMachineToken.id,- userId: communityMachineToken.userId,- machineId: communityMachineToken.machineId,- status: communityMachineToken.status,- expiresAt: communityMachineToken.expiresAt,- })- .from(communityMachineToken)- .where(eq(communityMachineToken.id, tokenId))- .limit(1);- if (tokenRows.length === 0) {- throw new ActivateCredentialError("unknown", "unknown token");- }- const tok = tokenRows[0]!;- if (tok.status === "revoked") {- throw new ActivateCredentialError("revoked", "token already revoked");- }- if (tok.status === "active") {- throw new ActivateCredentialError("already_active", "token already activated");- }- if (tok.expiresAt <= nowIso) {- throw new ActivateCredentialError("expired", "token expired");- }-- const flipped = await db- .update(communityMachineToken)- .set({ status: "revoked", lastUsedAt: nowIso })- .where(- and(- eq(communityMachineToken.id, tokenId),- eq(communityMachineToken.status, "pending")- )- )- .returning({ id: communityMachineToken.id });- if (flipped.length === 0) {- throw new ActivateCredentialError("already_active", "token no longer claimable");- }-- try {- let machine: MachineRow;- if (tok.machineId) {- // `markOnline: false` — this runs before the daemon's WS connects, so- // the real `ready` frame (not this HTTP call) must be the one that- // flips status and fires the online/bot-presence broadcast. See- // `upsertMachineByMachineId`'s doc comment.- const existing = await upsertMachineByMachineId(db, tok.userId, tok.machineId, meta, {- markOnline: false,- });- if (!existing) {- // Machine was deleted between mint and activate. Don't roll the- // token back to `pending` — that would loop the daemon forever and- // the pending-token unique index blocks the user from minting a- // fresh pair token for 15 min. Leave it `revoked` and surface a- // terminal error so the user re-pairs from the UI.- throw new ReconnectMachineMissingError();- }- // Reconnect — revoke every prior credential for this machine so the old- // daemon dial fails on next upgrade. The new credential inserted below- // becomes the sole valid one.- await db- .update(communityMachineCredential)- .set({ revokedAt: nowIso })- .where(- and(- eq(communityMachineCredential.machineId, tok.machineId),- isNull(communityMachineCredential.revokedAt)- )- );- machine = existing.machine;- } else {- machine = await insertMachineRow(db, tok.userId, meta);- }-- // Mint the plaintext bearer, hash it, store the row, return the plaintext.- const { nanoid } = await import("nanoid");- const bearer = CREDENTIAL_PREFIX + nanoid(32);- const credentialHash = await hashCredential(bearer);- const doName = doNameFromHash(credentialHash);- await db.insert(communityMachineCredential).values({- userId: tok.userId,- machineId: machine.id,- credentialHash,- doName,- createdAt: nowIso,- });-- return { credential: bearer, machineId: machine.id, userId: tok.userId };- } catch (err) {- // Terminal errors (machine deleted mid-reconnect) leave the token- // revoked so the user can mint a new one immediately. Everything else- // rolls the token back to `pending` so the caller can retry.- if (err instanceof ReconnectMachineMissingError) {- throw new ActivateCredentialError("unknown", err.message);- }- await db- .update(communityMachineToken)- .set({ status: "pending", lastUsedAt: null })- .where(eq(communityMachineToken.id, tokenId));- throw err;- }-}--class ReconnectMachineMissingError extends Error {- constructor() {- super("reconnect token references missing machine");- this.name = "ReconnectMachineMissingError";- }-}--export type ActivateCredentialErrorKind =- | "unknown"- | "expired"- | "revoked"- | "already_active";--export class ActivateCredentialError extends Error {- constructor(public readonly kind: ActivateCredentialErrorKind, message: string) {- super(message);- this.name = "ActivateCredentialError";- }-}-/*** Look up a credential by its sha256 hash (full 64 hex chars). Returns* null if unknown or revoked. Bumps `last_used_at` on hit (best-effort).@@ -939,34 +650,6 @@ export function toSummary(row: MachineRow): CommunityMachineSummary {};}-/**- * Flip a machine `online → offline` on WS close, scoped by the credential- * hash that owns the closing connection. If the credential has been revoked- * (rotation happened and a new DO instance is now authoritative), the guard- * subquery trips and this is a no-op — the old DO's late close cannot clobber- * the freshly-online row written by the new DO. Also a no-op when the row is- * already offline (idempotent close handler) or belongs to a different user.- */-export async function markMachineOffline(- db: Database,- args: { userId: string; machineId: string; credentialHash: string }-): Promise<MachineRow | null> {- const nowIso = new Date().toISOString();- const rows = await db- .update(communityMachine)- .set({ status: "offline", lastSeenAt: nowIso, updatedAt: nowIso })- .where(- and(- eq(communityMachine.userId, args.userId),- eq(communityMachine.id, args.machineId),- eq(communityMachine.status, "online"),- sql`EXISTS (SELECT 1 FROM ${communityMachineCredential} c WHERE c.machine_id = ${communityMachine.id} AND c.credential_hash = ${args.credentialHash} AND c.revoked_at IS NULL)`- )- )- .returning();- return rows.length ? (rows[0] as MachineRow) : null;-}-/*** Read-path counterpart to `listBotsForMachine` (`bot.ts`) — given a bot's* `user.id`, answer whether it's currently online by following its@@ -999,31 +682,3 @@ export async function isBotOnline(db: Database, botUserId: string): Promise<bool.limit(1);return rows.length > 0 && isPresenceOnline(rows[0]!.status);}--/**- * Safety-net used by the DO's alarm live-WS branch. If we observe a live- * community-machine socket for a machine whose row is stale-offline (e.g.- * hibernated across a deploy where the daemon never re-emitted `ready`),- * flip it back online so /community reflects reality. Same credential-hash- * scope as `markMachineOffline` so a revoked-credential DO can't clobber- * the new DO's state.- */-export async function markMachineOnlineIfOffline(- db: Database,- args: { userId: string; machineId: string; credentialHash: string }-): Promise<MachineRow | null> {- const nowIso = new Date().toISOString();- const rows = await db- .update(communityMachine)- .set({ status: "online", lastSeenAt: nowIso, updatedAt: nowIso })- .where(- and(- eq(communityMachine.userId, args.userId),- eq(communityMachine.id, args.machineId),- eq(communityMachine.status, "offline"),- sql`EXISTS (SELECT 1 FROM ${communityMachineCredential} c WHERE c.machine_id = ${communityMachine.id} AND c.credential_hash = ${args.credentialHash} AND c.revoked_at IS NULL)`- )- )- .returning();- return rows.length ? (rows[0] as MachineRow) : null;-}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 20fbd894a..a8aa26aa7 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -261,6 +261,7 @@ export {CommunityPairTokenResponseSchema,CommunityDaemonActivateRequestSchema,CommunityDaemonActivateResponseSchema,+ CommunityDaemonActivateErrorResponseSchema,CommunityDaemonEnrollAgentRequestSchema,CommunityDaemonEnrollAgentResponseSchema,HostReadyMessageSchema,@@ -362,6 +363,7 @@ export type {CommunityPairTokenResponse,CommunityDaemonActivateRequest,CommunityDaemonActivateResponse,+ CommunityDaemonActivateErrorResponse,CommunityDaemonEnrollAgentRequest,CommunityDaemonEnrollAgentResponse,HostReadyMessage,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex eb6f73cf2..63707fa66 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1033,6 +1033,7 @@ export const CommunityDaemonActivateRequestSchema = z.object({hostname: z.string(),platform: z.string(),arch: z.string(),+ expectedMachineId: z.string().min(1).optional(),osRelease: z.string().optional(),daemonVersion: z.string().optional(),runtimeReport: CommunityMachineRuntimeListSchema.optional(),@@ -1043,9 +1044,16 @@ export const CommunityDaemonActivateResponseSchema = z.object({credential: z.string(),machineId: z.string(),expiresAt: z.string().nullable(),+ sessionOutcome: z.literal("committed"),});export type CommunityDaemonActivateResponse = z.infer<typeof CommunityDaemonActivateResponseSchema>;+export const CommunityDaemonActivateErrorResponseSchema = z.object({+ error: z.string(),+ sessionOutcome: z.enum(["not_committed", "unknown"]),+});+export type CommunityDaemonActivateErrorResponse = z.infer<typeof CommunityDaemonActivateErrorResponseSchema>;+export const CommunityDaemonEnrollAgentRequestSchema = z.object({agentId: z.string().min(1).max(128),});diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.tsindex ad3020ece..cb0d304db 100644--- a/src/shared/test/queries/community-machine.test.ts+++ b/src/shared/test/queries/community-machine.test.ts@@ -1,5 +1,39 @@import { describe, it, expect, vi } from "vitest";import * as q from "../../src/db/queries/community/machine";+import * as sessionEpoch from "../../src/db/queries/community/machine-session-epoch";++async function readyEpoch(db: any, userId: string, machineId: string, metadata: q.MachineMetadataInput, credentialHash: string) {+ const result = await sessionEpoch.transitionMachineSessionEpoch(db, {+ type: "ready",+ epoch: { userId, machineId, credentialHash },+ metadata,+ });+ return result.type === "stale_epoch" ? null : result;+}++async function renewEpoch(db: any, epoch: sessionEpoch.MachineSessionEpoch) {+ const result = await sessionEpoch.transitionMachineSessionEpoch(db, { type: "renew", epoch });+ return result.type === "stale_epoch" ? null : result.machine;+}++async function closeEpoch(db: any, epoch: sessionEpoch.MachineSessionEpoch) {+ const result = await sessionEpoch.transitionMachineSessionEpoch(db, { type: "close", epoch });+ return result.type === "stale_epoch" ? null : result.machine;+}++function rotateEpoch(+ db: any,+ tokenId: string,+ metadata: q.MachineMetadataInput,+ options: { expectedMachineId?: string } = {},+) {+ return sessionEpoch.transitionMachineSessionEpoch(db, {+ type: "rotate",+ tokenId,+ metadata,+ expectedMachineId: options.expectedMachineId,+ });+}describe("community/machine exports", () => {it("exports the documented helpers", () => {@@ -10,15 +44,11 @@ describe("community/machine exports", () => {expect(typeof q.findTokenById).toBe("function");expect(typeof q.touchTokenLastUsed).toBe("function");expect(typeof q.revokeToken).toBe("function");- expect(typeof q.upsertMachineByMachineId).toBe("function");- expect(typeof q.touchMachineHeartbeat).toBe("function");expect(typeof q.getMachineByIdForUser).toBe("function");expect(typeof q.listMachinesForUser).toBe("function");expect(typeof q.deleteMachineForUser).toBe("function");expect(typeof q.toSummary).toBe("function");- expect(typeof q.markMachineOffline).toBe("function");- expect(typeof q.markMachineOnlineIfOffline).toBe("function");- expect(typeof q.activateMachineCredential).toBe("function");+ expect(typeof sessionEpoch.transitionMachineSessionEpoch).toBe("function");expect(typeof q.hashCredential).toBe("function");expect(typeof q.doNameFromHash).toBe("function");expect(typeof q.findCredentialByHash).toBe("function");@@ -36,6 +66,11 @@ describe("community/machine exports", () => {expect((q as any).rotatePairingTokenForMachine).toBeUndefined();expect((q as any).findActiveCredential).toBeUndefined();expect((q as any).findActiveAgentRunnerKey).toBeUndefined();+ expect((q as any).upsertMachineByMachineId).toBeUndefined();+ expect((q as any).touchMachineHeartbeat).toBeUndefined();+ expect((q as any).markMachineOffline).toBeUndefined();+ expect((q as any).markMachineOnlineIfOffline).toBeUndefined();+ expect((q as any).activateMachineCredential).toBeUndefined();});});@@ -132,11 +167,30 @@ describe("toSummary", () => {});// ----------------------------------------------------------------------------// markMachineOffline / markMachineOnlineIfOffline+// session close and renew// ----------------------------------------------------------------------------function makeUpdateChain(returningRows: unknown[]) {+function makeUpdateChain(returningRows: unknown[], priorStatus: "online" | "offline") {const chain: any = {};+ const prior = {+ id: "cm_1",+ userId: "u_1",+ displayName: "host",+ hostname: "host",+ platform: "darwin",+ arch: "arm64",+ osRelease: "23",+ daemonVersion: "0.1.0",+ metadata: null,+ availableRuntimes: [],+ status: priorStatus,+ lastSeenAt: "earlier",+ createdAt: "earlier",+ updatedAt: "earlier",+ };+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve([prior]));chain.update = vi.fn(() => chain);chain.set = vi.fn(() => chain);chain.where = vi.fn(() => chain);@@ -144,11 +198,11 @@ function makeUpdateChain(returningRows: unknown[]) {return chain;}-describe("markMachineOffline", () => {+describe("session close", () => {it("flips status='online' → 'offline' when the row matches + credential is active (returns updated row)", async () => {const flipped = { id: "cm_1", userId: "u_1", status: "offline", lastSeenAt: "now" };- const chain = makeUpdateChain([flipped]);- const out = await q.markMachineOffline(chain, {+ const chain = makeUpdateChain([flipped], "online");+ const out = await closeEpoch(chain, {userId: "u_1",machineId: "cm_1",credentialHash: "abc",@@ -159,8 +213,8 @@ describe("markMachineOffline", () => {);});it("returns null when the row is already offline / credential revoked / wrong user (guarded UPDATE returned zero rows)", async () => {- const chain = makeUpdateChain([]);- const out = await q.markMachineOffline(chain, {+ const chain = makeUpdateChain([], "online");+ const out = await closeEpoch(chain, {userId: "u_1",machineId: "cm_1",credentialHash: "revoked",@@ -169,11 +223,11 @@ describe("markMachineOffline", () => {});});-describe("markMachineOnlineIfOffline", () => {+describe("session renew", () => {it("flips offline → online when guarded row + credential are active", async () => {const flipped = { id: "cm_1", userId: "u_1", status: "online", lastSeenAt: "now" };- const chain = makeUpdateChain([flipped]);- const out = await q.markMachineOnlineIfOffline(chain, {+ const chain = makeUpdateChain([flipped], "offline");+ const out = await renewEpoch(chain, {userId: "u_1",machineId: "cm_1",credentialHash: "abc",@@ -184,8 +238,8 @@ describe("markMachineOnlineIfOffline", () => {);});it("returns null when the row is already online or credential revoked", async () => {- const chain = makeUpdateChain([]);- const out = await q.markMachineOnlineIfOffline(chain, {+ const chain = makeUpdateChain([], "offline");+ const out = await renewEpoch(chain, {userId: "u_1",machineId: "cm_1",credentialHash: "abc",@@ -444,10 +498,10 @@ describe("createReconnectPairingToken", () => {});// ----------------------------------------------------------------------------// upsertMachineByMachineId+// session ready transition// ----------------------------------------------------------------------------describe("upsertMachineByMachineId", () => {+describe("session ready transition", () => {const priorRow = {id: "cm_1",userId: "u_1",@@ -472,7 +526,7 @@ describe("upsertMachineByMachineId", () => {chain.where = vi.fn(() => chain);chain.limit = vi.fn(() => Promise.resolve([]));expect(- await q.upsertMachineByMachineId(chain, "u_1", "cm_missing", {})+ await readyEpoch(chain, "u_1", "cm_missing", {}, "hash")).toBeNull();});@@ -486,9 +540,9 @@ describe("upsertMachineByMachineId", () => {chain.update = vi.fn(() => chain);chain.set = vi.fn(() => chain);chain.returning = vi.fn(() => Promise.resolve([updated]));- const res = await q.upsertMachineByMachineId(chain, "u_1", "cm_1", {+ const res = await readyEpoch(chain, "u_1", "cm_1", {availableRuntimes: [{ id: "claude" }, { id: "codex" }],- });+ }, "hash");expect(res?.priorAvailableRuntimes).toEqual([{ id: "claude" }]);expect(res?.priorDaemonVersion).toBe("0.1.0");expect(res?.machine.availableRuntimes).toEqual([{ id: "claude" }, { id: "codex" }]);@@ -508,7 +562,7 @@ describe("upsertMachineByMachineId", () => {chain.update = vi.fn(() => chain);chain.set = vi.fn(() => chain);chain.returning = vi.fn(() => Promise.resolve([priorRow]));- await q.upsertMachineByMachineId(chain, "u_1", "cm_1", { hostname: "host2" });+ await readyEpoch(chain, "u_1", "cm_1", { hostname: "host2" }, "hash");expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ availableRuntimes: [{ id: "claude" }] }));@@ -525,7 +579,7 @@ describe("upsertMachineByMachineId", () => {chain.returning = vi.fn(() =>Promise.resolve([{ ...priorRow, status: "online", lastSeenAt: "now" }]));- await q.upsertMachineByMachineId(chain, "u_1", "cm_1", { hostname: "host2" });+ await readyEpoch(chain, "u_1", "cm_1", { hostname: "host2" }, "hash");expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ status: "online" }));});@@ -540,7 +594,7 @@ describe("upsertMachineByMachineId", () => {chain.returning = vi.fn(() =>Promise.resolve([{ ...priorRow, status: "online", lastSeenAt: "now" }]));- const res = await q.upsertMachineByMachineId(chain, "u_1", "cm_1", {});+ const res = await readyEpoch(chain, "u_1", "cm_1", {}, "hash");expect(res?.priorStatus).toBe("offline");});@@ -554,16 +608,11 @@ describe("upsertMachineByMachineId", () => {chain.update = vi.fn(() => chain);chain.set = vi.fn(() => chain);chain.returning = vi.fn(() => Promise.resolve([onlinePrior]));- const res = await q.upsertMachineByMachineId(chain, "u_1", "cm_1", {});+ const res = await readyEpoch(chain, "u_1", "cm_1", {}, "hash");expect(res?.priorStatus).toBe("online");});- it("leaves status/lastSeenAt untouched when markOnline=false (HTTP /activate reconnect)", async () => {- // /activate runs before the daemon's WS connects — it must not flip- // status itself, or the later `ready`-frame's `priorStatus !== 'online'`- // guard would wrongly see 'online' and skip the broadcast (incl. bot- // presence fan-out). Only the real ready-frame call (default- // markOnline=true) may set status.+ it("returns null when the ready frame credential is no longer current", async () => {const chain: any = {};chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);@@ -571,31 +620,23 @@ describe("upsertMachineByMachineId", () => {chain.limit = vi.fn(() => Promise.resolve([priorRow]));chain.update = vi.fn(() => chain);chain.set = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([priorRow]));- const res = await q.upsertMachineByMachineId(+ chain.returning = vi.fn(() => Promise.resolve([]));+ const res = await readyEpoch(chain,"u_1","cm_1",{ hostname: "host2" },- { markOnline: false }- );- expect(chain.set).toHaveBeenCalledWith(- expect.not.objectContaining({ status: expect.anything() })+ "revoked-hash");- const setArg = chain.set.mock.calls[0][0];- expect(setArg).not.toHaveProperty("status");- expect(setArg).not.toHaveProperty("lastSeenAt");- // priorStatus still reflects the pre-upsert row (offline), unaffected- // by markOnline — it's purely about what gets WRITTEN.- expect(res?.priorStatus).toBe("offline");+ expect(res).toBeNull();});});// ----------------------------------------------------------------------------// activateMachineCredential+// session epoch rotation// ----------------------------------------------------------------------------describe("activateMachineCredential — validation", () => {+describe("session epoch rotation — validation", () => {it("throws 'unknown' when the token is not in the DB", async () => {const chain: any = {};chain.select = vi.fn(() => chain);@@ -603,12 +644,13 @@ describe("activateMachineCredential — validation", () => {chain.where = vi.fn(() => chain);chain.limit = vi.fn(() => Promise.resolve([]));await expect(- q.activateMachineCredential(chain, "cmt_unknown", { hostname: "" })- ).rejects.toBeInstanceOf(q.ActivateCredentialError);+ rotateEpoch(chain, "cmt_unknown", { hostname: "" })+ ).rejects.toBeInstanceOf(sessionEpoch.MachineSessionRotationError);try {- await q.activateMachineCredential(chain, "cmt_unknown", { hostname: "" });+ await rotateEpoch(chain, "cmt_unknown", { hostname: "" });} catch (err) {- expect((err as q.ActivateCredentialError).kind).toBe("unknown");+ expect((err as sessionEpoch.MachineSessionRotationError).kind).toBe("unknown");+ expect((err as sessionEpoch.MachineSessionRotationError).sessionOutcome).toBe("not_committed");}});@@ -629,10 +671,11 @@ describe("activateMachineCredential — validation", () => {]));try {- await q.activateMachineCredential(chain, "cmt_x", { hostname: "" });+ await rotateEpoch(chain, "cmt_x", { hostname: "" });throw new Error("should have thrown");} catch (err) {- expect((err as q.ActivateCredentialError).kind).toBe("revoked");+ expect((err as sessionEpoch.MachineSessionRotationError).kind).toBe("revoked");+ expect((err as sessionEpoch.MachineSessionRotationError).sessionOutcome).toBe("unknown");}});@@ -653,10 +696,11 @@ describe("activateMachineCredential — validation", () => {]));try {- await q.activateMachineCredential(chain, "cmt_x", { hostname: "" });+ await rotateEpoch(chain, "cmt_x", { hostname: "" });throw new Error("should have thrown");} catch (err) {- expect((err as q.ActivateCredentialError).kind).toBe("already_active");+ expect((err as sessionEpoch.MachineSessionRotationError).kind).toBe("already_active");+ expect((err as sessionEpoch.MachineSessionRotationError).sessionOutcome).toBe("unknown");}});@@ -677,22 +721,99 @@ describe("activateMachineCredential — validation", () => {]));try {- await q.activateMachineCredential(chain, "cmt_x", { hostname: "" });+ await rotateEpoch(chain, "cmt_x", { hostname: "" });throw new Error("should have thrown");} catch (err) {- expect((err as q.ActivateCredentialError).kind).toBe("expired");+ expect((err as sessionEpoch.MachineSessionRotationError).kind).toBe("expired");+ expect((err as sessionEpoch.MachineSessionRotationError).sessionOutcome).toBe("not_committed");}});++ it("classifies a concurrent claim loser as ambiguous", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve([{+ id: "cmt_x",+ userId: "u_1",+ machineId: "cm_existing",+ status: "pending",+ expiresAt: "9999",+ }]));+ chain.update = vi.fn(() => chain);+ chain.set = vi.fn(() => chain);+ chain.returning = vi.fn(() => Promise.resolve([]));++ await expect(rotateEpoch(+ chain,+ "cmt_x",+ { hostname: "" },+ { expectedMachineId: "cm_existing" },+ )).rejects.toMatchObject({+ kind: "already_active",+ sessionOutcome: "unknown",+ });+ });++ it("fails reconnect without expectedMachineId before claiming the token", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve([{+ id: "cmt_x",+ userId: "u_1",+ machineId: "cm_existing",+ status: "pending",+ expiresAt: "9999",+ }]));+ chain.update = vi.fn(() => chain);+ await expect(+ rotateEpoch(chain, "cmt_x", { hostname: "" })+ ).rejects.toMatchObject({+ kind: "expected_machine_required",+ sessionOutcome: "not_committed",+ });+ expect(chain.update).not.toHaveBeenCalled();+ });++ it("fails expectedMachineId mismatch before claiming the token", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve([{+ id: "cmt_x",+ userId: "u_1",+ machineId: "cm_existing",+ status: "pending",+ expiresAt: "9999",+ }]));+ chain.update = vi.fn(() => chain);+ await expect(+ rotateEpoch(+ chain,+ "cmt_x",+ { hostname: "" },+ { expectedMachineId: "cm_other" },+ )+ ).rejects.toMatchObject({+ kind: "machine_mismatch",+ sessionOutcome: "not_committed",+ });+ expect(chain.update).not.toHaveBeenCalled();+ });});/**- * activateMachineCredential success paths use a scripted mock that returns+ * session epoch rotation success paths use a scripted mock that returns* different results per call. Kept minimal — the interesting behavior is:* (1) new-pair path creates a machine row via insert;* (2) reconnect path (token.machineId set) reuses via update;* (3) either path stores credential_hash + do_name and returns the plaintext.*/-describe("activateMachineCredential — success paths", () => {+describe("session epoch rotation — success paths", () => {function scriptChain(script: Array<() => Promise<any>>) {let step = 0;const chain: any = {};@@ -754,7 +875,7 @@ describe("activateMachineCredential — success paths", () => {() => Promise.resolve([insertedMachine]),]);- const r = await q.activateMachineCredential(chain, "cmt_x", {+ const r = await rotateEpoch(chain, "cmt_x", {hostname: "host",});expect(r.userId).toBe("u_1");@@ -773,7 +894,7 @@ describe("activateMachineCredential — success paths", () => {expect(credInsert.credentialHash).toBe(expectedHash);});- it("reconnect path — reuses existing machine row and revokes prior credentials", async () => {+ it("reconnect path atomically rotates credential + runner keys and projects offline", async () => {const existingMachine = {id: "cm_existing",userId: "u_1",@@ -790,48 +911,143 @@ describe("activateMachineCredential — success paths", () => {updatedAt: "earlier",};- // Scripted (limit / returning) in call order:- // 1. select token row → pending, machineId set- // 2. flip token returning- // 3. select machine row inside upsertMachineByMachineId → prior- // 4. update machine returning → updated- // 5. update prior credentials revokedAt — no returning- const chain = scriptChain([- // (1) find token- () =>- Promise.resolve([- {+ let selectCount = 0;+ let updateCount = 0;+ let mode = "";+ const chain: any = {};+ chain.select = vi.fn(() => {+ mode = "select";+ selectCount++;+ return chain;+ });+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => {+ if (mode === "select" && selectCount === 3) {+ return Promise.resolve([{ doName: "old-do" }]);+ }+ return chain;+ });+ chain.limit = vi.fn(() => Promise.resolve(+ selectCount === 1+ ? [{id: "cmt_x",userId: "u_1",machineId: "cm_existing",status: "pending",expiresAt: "9999",- },- ]),- // (2) flip returning- () => Promise.resolve([{ id: "cmt_x" }]),- // (3) upsertMachineByMachineId select prior- () => Promise.resolve([existingMachine]),- // (4) upsertMachineByMachineId update returning- () => Promise.resolve([existingMachine]),- ]);-- const r = await q.activateMachineCredential(chain, "cmt_x", {- hostname: "host",+ }]+ : [existingMachine],+ ));+ chain.update = vi.fn(() => {+ mode = "update";+ updateCount++;+ return chain;});+ chain.set = vi.fn(() => chain);+ chain.returning = vi.fn(() => updateCount === 1+ ? Promise.resolve([{ id: "cmt_x" }])+ : { statement: "update-machine" });+ chain.insert = vi.fn(() => {+ mode = "insert";+ return chain;+ });+ chain._insertValues = [] as any[];+ chain.values = vi.fn((value: any) => {+ chain._insertValues.push(value);+ return chain;+ });+ chain.batch = vi.fn(async () => [[{+ ...existingMachine,+ status: "offline",+ lastSeenAt: null,+ }], [], [], []]);++ const r = await rotateEpoch(+ chain,+ "cmt_x",+ { hostname: "host" },+ { expectedMachineId: "cm_existing" },+ );expect(r.machineId).toBe("cm_existing");- // Update was called at least twice — once for machine, once for revoking- // prior credentials.- expect(chain.update).toHaveBeenCalled();- // Reconnect activation must not flip status/lastSeenAt itself — that's- // reserved for the real WS `ready` frame (see upsertMachineByMachineId's- // markOnline doc comment). Find the machine-row `.set()` call (the one- // touching `hostname`) and assert it carries no status.+ expect(r.revokedDoNames).toEqual(["old-do"]);+ expect(chain.batch).toHaveBeenCalledTimes(1);+ expect(chain.batch.mock.calls[0]![0]).toHaveLength(4);const machineSetCall = chain.set.mock.calls.find((args: any[]) => args[0] && "hostname" in args[0]);- expect(machineSetCall?.[0]).not.toHaveProperty("status");- expect(machineSetCall?.[0]).not.toHaveProperty("lastSeenAt");+ expect(machineSetCall?.[0]).toEqual(expect.objectContaining({+ status: "offline",+ lastSeenAt: null,+ }));+ });++ it("keeps the token consumed when the reconnect batch rejects ambiguously", async () => {+ const machine = {+ id: "cm_existing",+ userId: "u_1",+ displayName: "host",+ hostname: "host",+ platform: "darwin",+ arch: "arm64",+ osRelease: "23",+ daemonVersion: "0.1.0",+ metadata: null,+ availableRuntimes: [],+ status: "online",+ lastSeenAt: "earlier",+ createdAt: "earlier",+ updatedAt: "earlier",+ };+ let selectCount = 0;+ let updateCount = 0;+ let mode = "";+ const chain: any = {};+ chain.select = vi.fn(() => {+ mode = "select";+ selectCount++;+ return chain;+ });+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => {+ if (mode === "select" && selectCount === 3) return Promise.resolve([]);+ return chain;+ });+ chain.limit = vi.fn(() => Promise.resolve(+ selectCount === 1+ ? [{+ id: "cmt_x",+ userId: "u_1",+ machineId: machine.id,+ status: "pending",+ expiresAt: "9999",+ }]+ : [machine],+ ));+ chain.update = vi.fn(() => {+ mode = "update";+ updateCount++;+ return chain;+ });+ chain.set = vi.fn(() => chain);+ chain.returning = vi.fn(() => updateCount === 1+ ? Promise.resolve([{ id: "cmt_x" }])+ : { statement: "update-machine" });+ chain.insert = vi.fn(() => {+ mode = "insert";+ return chain;+ });+ chain.values = vi.fn(() => chain);+ chain.batch = vi.fn(async () => { throw new Error("D1 batch failed"); });++ await expect(rotateEpoch(+ chain,+ "cmt_x",+ { hostname: "host" },+ { expectedMachineId: machine.id },+ )).rejects.toThrow("D1 batch failed");++ expect(chain.batch).toHaveBeenCalledOnce();+ expect(chain.set.mock.calls.some(([value]: any[]) => value?.status === "pending")).toBe(false);});it("leaves the token revoked (not rolled back) when the reconnect target machine is missing", async () => {@@ -858,7 +1074,7 @@ describe("activateMachineCredential — success paths", () => {},]);}- if (idx === 2) return Promise.resolve([]); // upsert → missing machine+ if (idx === 1) return Promise.resolve([]); // reconnect target missingreturn Promise.resolve([]);});chain.update = vi.fn(() => chain);@@ -868,8 +1084,17 @@ describe("activateMachineCredential — success paths", () => {chain.values = vi.fn(() => chain);await expect(- q.activateMachineCredential(chain, "cmt_x", { hostname: "" })- ).rejects.toMatchObject({ name: "ActivateCredentialError", kind: "unknown" });+ rotateEpoch(+ chain,+ "cmt_x",+ { hostname: "" },+ { expectedMachineId: "cm_bad" },+ )+ ).rejects.toMatchObject({+ name: "MachineSessionRotationError",+ kind: "unknown",+ sessionOutcome: "unknown",+ });const setPayloads = chain.set.mock.calls.map((c: any[]) => c[0]);const rolledBack = setPayloads.some((p: any) => p.status === "pending");diff --git a/src/shared/test/queries/machine-session-epoch.integration.test.ts b/src/shared/test/queries/machine-session-epoch.integration.test.tsnew file mode 100644index 000000000..7b56ff49e--- /dev/null+++ b/src/shared/test/queries/machine-session-epoch.integration.test.ts@@ -0,0 +1,195 @@+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { hashCredential } from "../../src/db/queries/community/machine";+import { transitionMachineSessionEpoch } from "../../src/db/queries/community/machine-session-epoch";++const OLD_HASH = "a".repeat(64);+const OLD_DO = "a".repeat(32);++describe("machine session epoch SQL transaction", () => {+ let sqlite: Sqlite.Database;+ let db: ReturnType<typeof drizzle>;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE community_machine_token (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ machine_id TEXT,+ status TEXT NOT NULL DEFAULT 'pending',+ expires_at TEXT NOT NULL,+ created_at TEXT NOT NULL,+ last_used_at TEXT+ );+ CREATE TABLE community_machine (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ display_name TEXT NOT NULL DEFAULT '',+ hostname TEXT NOT NULL DEFAULT '',+ platform TEXT NOT NULL DEFAULT '',+ arch TEXT NOT NULL DEFAULT '',+ os_release TEXT NOT NULL DEFAULT '',+ daemon_version TEXT NOT NULL DEFAULT '',+ metadata TEXT,+ available_runtimes TEXT NOT NULL DEFAULT '[]',+ status TEXT NOT NULL DEFAULT 'offline',+ last_seen_at TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+ );+ CREATE TABLE community_machine_credential (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ machine_id TEXT NOT NULL,+ credential_hash TEXT NOT NULL UNIQUE,+ do_name TEXT NOT NULL UNIQUE,+ created_at TEXT NOT NULL,+ last_used_at TEXT,+ revoked_at TEXT+ );+ CREATE TABLE community_agent_runner_key (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ machine_id TEXT NOT NULL,+ agent_id TEXT NOT NULL,+ runner_key_hash TEXT NOT NULL UNIQUE,+ do_name TEXT NOT NULL UNIQUE,+ created_at TEXT NOT NULL,+ revoked_at TEXT+ );+ `);+ db = drizzle(sqlite);+ // Match D1's all-or-nothing batch contract using real generated SQL.+ (db as any).batch = (statements: Array<{ toSQL: () => { sql: string; params: unknown[] } }>) =>+ sqlite.transaction(() => statements.map((statement) => {+ const query = statement.toSQL();+ const prepared = sqlite.prepare(query.sql);+ return prepared.reader ? prepared.all(...query.params) : prepared.run(...query.params);+ }))();+ seedCurrentEpoch();+ });++ afterEach(() => sqlite.close());++ function seedCurrentEpoch() {+ sqlite.prepare(`+ INSERT INTO community_machine+ (id, user_id, display_name, hostname, platform, arch, os_release,+ daemon_version, metadata, available_runtimes, status, last_seen_at,+ created_at, updated_at)+ VALUES+ ('cm_machine', 'u_1', 'old-host', 'old-host', 'darwin', 'arm64', '23',+ '0.1.0', NULL, '[]', 'online', '2026-08-18T00:00:00.000Z',+ '2026-08-18T00:00:00.000Z', '2026-08-18T00:00:00.000Z')+ `).run();+ sqlite.prepare(`+ INSERT INTO community_machine_token+ (id, user_id, machine_id, status, expires_at, created_at)+ VALUES ('cmt_rotate', 'u_1', 'cm_machine', 'pending', '9999-01-01', '2026-08-18')+ `).run();+ sqlite.prepare(`+ INSERT INTO community_machine_credential+ (id, user_id, machine_id, credential_hash, do_name, created_at)+ VALUES ('cred_old', 'u_1', 'cm_machine', ?, ?, '2026-08-18')+ `).run(OLD_HASH, OLD_DO);+ sqlite.prepare(`+ INSERT INTO community_agent_runner_key+ (id, user_id, machine_id, agent_id, runner_key_hash, do_name, created_at)+ VALUES ('runner_old', 'u_1', 'cm_machine', 'bot_1', ?, ?, '2026-08-18')+ `).run("b".repeat(64), "b".repeat(32));+ }++ async function rotate() {+ return transitionMachineSessionEpoch(db as never, {+ type: "rotate",+ tokenId: "cmt_rotate",+ expectedMachineId: "cm_machine",+ metadata: {+ hostname: "new-host",+ platform: "darwin",+ arch: "arm64",+ daemonVersion: "0.1.12",+ availableRuntimes: [],+ },+ });+ }++ it("commits credential, runner, and offline projection together and fences the old epoch", async () => {+ const result = await rotate();+ const newHash = await hashCredential(result.credential);++ expect(sqlite.prepare(`+ SELECT status, last_seen_at AS lastSeenAt, hostname+ FROM community_machine WHERE id = 'cm_machine'+ `).get()).toEqual({ status: "offline", lastSeenAt: null, hostname: "new-host" });+ expect(sqlite.prepare(`+ SELECT credential_hash AS credentialHash, revoked_at AS revokedAt+ FROM community_machine_credential ORDER BY id+ `).all()).toEqual(expect.arrayContaining([+ { credentialHash: OLD_HASH, revokedAt: expect.any(String) },+ { credentialHash: newHash, revokedAt: null },+ ]));+ expect(sqlite.prepare(`+ SELECT revoked_at AS revokedAt FROM community_agent_runner_key WHERE id = 'runner_old'+ `).get()).toEqual({ revokedAt: expect.any(String) });+ expect(sqlite.prepare(`+ SELECT status FROM community_machine_token WHERE id = 'cmt_rotate'+ `).get()).toEqual({ status: "revoked" });++ const oldEpoch = { userId: "u_1", machineId: "cm_machine", credentialHash: OLD_HASH };+ await expect(transitionMachineSessionEpoch(db as never, {+ type: "ready",+ epoch: oldEpoch,+ metadata: { hostname: "stale-host" },+ })).resolves.toEqual({ type: "stale_epoch" });++ const currentEpoch = { userId: "u_1", machineId: "cm_machine", credentialHash: newHash };+ await expect(transitionMachineSessionEpoch(db as never, {+ type: "ready",+ epoch: currentEpoch,+ metadata: { hostname: "current-host" },+ })).resolves.toMatchObject({ type: "transitioned", machine: { status: "online" } });+ for (const type of ["renew", "close", "expire"] as const) {+ await expect(transitionMachineSessionEpoch(db as never, {+ type,+ epoch: oldEpoch,+ })).resolves.toEqual({ type: "stale_epoch" });+ }+ expect(sqlite.prepare(`+ SELECT status, hostname FROM community_machine WHERE id = 'cm_machine'+ `).get()).toEqual({ status: "online", hostname: "current-host" });+ });++ it("rolls back DB state but keeps the token consumed when a dispatched batch rejects", async () => {+ sqlite.exec(`+ CREATE TRIGGER reject_new_machine_credential+ BEFORE INSERT ON community_machine_credential+ BEGIN+ SELECT RAISE(ABORT, 'injected credential insert failure');+ END;+ `);++ await expect(rotate()).rejects.toThrow("injected credential insert failure");++ expect(sqlite.prepare(`+ SELECT status, last_seen_at AS lastSeenAt, hostname+ FROM community_machine WHERE id = 'cm_machine'+ `).get()).toEqual({+ status: "online",+ lastSeenAt: "2026-08-18T00:00:00.000Z",+ hostname: "old-host",+ });+ expect(sqlite.prepare(`+ SELECT credential_hash AS credentialHash, revoked_at AS revokedAt+ FROM community_machine_credential+ `).all()).toEqual([{ credentialHash: OLD_HASH, revokedAt: null }]);+ expect(sqlite.prepare(`+ SELECT revoked_at AS revokedAt FROM community_agent_runner_key WHERE id = 'runner_old'+ `).get()).toEqual({ revokedAt: null });+ expect(sqlite.prepare(`+ SELECT status, last_used_at AS lastUsedAt FROM community_machine_token WHERE id = 'cmt_rotate'+ `).get()).toEqual({ status: "revoked", lastUsedAt: expect.any(String) });+ });+});diff --git a/src/web/src/app/api/community/daemon/activate/route.test.ts b/src/web/src/app/api/community/daemon/activate/route.test.tsindex 1529e59ae..5fd54c857 100644--- a/src/web/src/app/api/community/daemon/activate/route.test.ts+++ b/src/web/src/app/api/community/daemon/activate/route.test.ts@@ -1,6 +1,9 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"+const mockBroadcast = vi.hoisted(() => vi.fn(async () => { }))+const mockForceClose = vi.hoisted(() => vi.fn(async () => { }))+vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),}))@@ -9,7 +12,11 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))// The activate route also broadcasts machine.created — stub that.vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn(async () => { }),+ broadcastToUser: mockBroadcast,+}))++vi.mock("@/lib/community/machine-disconnect", () => ({+ forceCloseCommunityMachinesByDoNames: mockForceClose,}))const mockActivate = vi.fn()@@ -17,19 +24,21 @@ const mockGetMachine = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<any>("@alook/shared")- class MockActivateError extends Error {- constructor(public readonly kind: string, message: string) {+ class MockRotationError extends Error {+ constructor(+ public readonly kind: string,+ message: string,+ public readonly sessionOutcome: "not_committed" | "unknown",+ ) {super(message)- this.name = "ActivateCredentialError"+ this.name = "MachineSessionRotationError"}}return {...actual,queries: {communityMachine: {- activateMachineCredential: (...a: unknown[]) => mockActivate(...a),getMachineByIdForUser: (...a: unknown[]) => mockGetMachine(...a),- ActivateCredentialError: MockActivateError,toSummary: (row: any) => ({id: row.id,hostname: row.hostname ?? "",@@ -45,14 +54,18 @@ vi.mock("@alook/shared", async () => {updatedAt: "t",}),},+ communityMachineSession: {+ transitionMachineSessionEpoch: (...a: unknown[]) => mockActivate(...a),+ MachineSessionRotationError: MockRotationError,+ },},}})-// Retrieve the MockActivateError constructor after mocks have been hoisted.+// Retrieve the mocked domain error constructor after mocks have been hoisted.async function getMockError(): Promise<any> {const { queries } = await import("@alook/shared")- return (queries as any).communityMachine.ActivateCredentialError+ return (queries as any).communityMachineSession.MachineSessionRotationError}import { POST } from "./route"@@ -66,7 +79,11 @@ function jsonReq(body: object, headers: Record<string, string> = {}): NextReques}describe("POST /api/community/daemon/activate", () => {- beforeEach(() => vi.clearAllMocks())+ beforeEach(() => {+ vi.clearAllMocks()+ mockBroadcast.mockResolvedValue(undefined)+ mockForceClose.mockResolvedValue(undefined)+ })const goodBody = {hostname: "myhost",@@ -95,6 +112,7 @@ describe("POST /api/community/daemon/activate", () => {})const res = await POST(req)expect(res.status).toBe(400)+ expect(await res.json()).toMatchObject({ sessionOutcome: "not_committed" })})it("returns 200 + credential/machineId on happy path", async () => {@@ -102,6 +120,7 @@ describe("POST /api/community/daemon/activate", () => {credential: "cmk_alpha",machineId: "cm_alpha",userId: "u_1",+ revokedDoNames: [],})mockGetMachine.mockResolvedValue({ id: "cm_alpha", hostname: "myhost", displayName: "myhost" })const res = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_pending" }))@@ -110,33 +129,90 @@ describe("POST /api/community/daemon/activate", () => {credential: "cmk_alpha",machineId: "cm_alpha",expiresAt: null,+ sessionOutcome: "committed",})- expect(mockActivate).toHaveBeenCalledWith({}, "cmt_pending", expect.objectContaining({ hostname: "myhost" }))+ expect(mockActivate).toHaveBeenCalledWith(+ {},+ expect.objectContaining({+ type: "rotate",+ tokenId: "cmt_pending",+ metadata: expect.objectContaining({ hostname: "myhost" }),+ expectedMachineId: undefined,+ }),+ )})it("404 when the token is unknown", async () => {const Err = await getMockError()- mockActivate.mockRejectedValue(new Err("unknown", "unknown token"))+ mockActivate.mockRejectedValue(new Err("unknown", "unknown token", "not_committed"))const res = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_unknown" }))expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "unknown token", sessionOutcome: "not_committed" })})it("409 when the token is already revoked / active", async () => {const Err = await getMockError()- mockActivate.mockRejectedValue(new Err("revoked", "revoked"))+ mockActivate.mockRejectedValue(new Err("revoked", "revoked", "unknown"))const res = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_r" }))expect(res.status).toBe(409)+ expect(await res.json()).toEqual({ error: "revoked", sessionOutcome: "unknown" })- mockActivate.mockRejectedValue(new Err("already_active", "already active"))+ mockActivate.mockRejectedValue(new Err("already_active", "already active", "unknown"))const res2 = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_a" }))expect(res2.status).toBe(409)+ expect(await res2.json()).toEqual({ error: "already active", sessionOutcome: "unknown" })})it("410 when the token is expired", async () => {const Err = await getMockError()- mockActivate.mockRejectedValue(new Err("expired", "expired"))+ mockActivate.mockRejectedValue(new Err("expired", "expired", "not_committed"))const res = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_old" }))expect(res.status).toBe(410)+ expect(await res.json()).toEqual({ error: "expired", sessionOutcome: "not_committed" })+ })++ it("returns a committed response without waiting for historical DO close", async () => {+ mockForceClose.mockImplementation(() => new Promise(() => { }))+ mockActivate.mockResolvedValue({+ credential: "cmk_rotated",+ machineId: "cm_alpha",+ userId: "u_1",+ revokedDoNames: ["old-do"],+ })+ mockGetMachine.mockResolvedValue({ id: "cm_alpha", hostname: "myhost", displayName: "myhost" })++ const response = await Promise.race([+ POST(jsonReq(goodBody, { Authorization: "Bearer cmt_pending" })),+ new Promise<"timed-out">((resolve) => setTimeout(() => resolve("timed-out"), 50)),+ ])++ expect(response).not.toBe("timed-out")+ expect((response as Response).status).toBe(200)+ expect(await (response as Response).json()).toMatchObject({ sessionOutcome: "committed" })+ await vi.waitFor(() => expect(mockBroadcast).toHaveBeenCalledOnce())+ })++ it("passes expectedMachineId to reconnect activation", async () => {+ mockActivate.mockResolvedValue({+ credential: "cmk_alpha",+ machineId: "cm_alpha",+ userId: "u_1",+ revokedDoNames: ["old-do"],+ })+ mockGetMachine.mockResolvedValue(null)+ const res = await POST(jsonReq(+ { ...goodBody, expectedMachineId: "cm_alpha" },+ { Authorization: "Bearer cmt_pending" },+ ))+ expect(res.status).toBe(200)+ expect(mockActivate).toHaveBeenCalledWith(+ {},+ expect.objectContaining({+ type: "rotate",+ tokenId: "cmt_pending",+ expectedMachineId: "cm_alpha",+ }),+ )})it("500 body includes the underlying exception's message for an unhandled failure", async () => {diff --git a/src/web/src/app/api/community/daemon/activate/route.ts b/src/web/src/app/api/community/daemon/activate/route.tsindex 21d38b23a..0de048210 100644--- a/src/web/src/app/api/community/daemon/activate/route.ts+++ b/src/web/src/app/api/community/daemon/activate/route.ts@@ -9,6 +9,7 @@ import {} from "@alook/shared"import { getDb } from "@/lib/db"import { broadcastToUser } from "@/lib/broadcast"+import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"import { withCommunityPairingToken } from "@/lib/middleware/community-pairing-token"const log = createLogger({ service: "community/daemon/activate" })@@ -28,12 +29,12 @@ export const POST = withCommunityPairingToken(async (req, ctx) => {try {raw = await req.json()} catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ return NextResponse.json({ error: "invalid JSON body", sessionOutcome: "not_committed" }, { status: 400 })}const parsed = CommunityDaemonActivateRequestSchema.safeParse(raw)if (!parsed.success) {return NextResponse.json(- { error: "invalid payload", details: parsed.error.flatten() },+ { error: "invalid payload", details: parsed.error.flatten(), sessionOutcome: "not_committed" },{ status: 400 })}@@ -46,52 +47,77 @@ export const POST = withCommunityPairingToken(async (req, ctx) => {// runtimes. Without this the row is inserted with `[]` and no chips// appear until the WS `ready` frame lands (which never arrives if the// daemon dies between HTTP activate and WS connect).- const { runtimeReport, ...rest } = parsed.data- const result = await queries.communityMachine.activateMachineCredential(db, tokenId, {- ...rest,- availableRuntimes: runtimeReport,+ const { runtimeReport, expectedMachineId, ...rest } = parsed.data+ const result = await queries.communityMachineSession.transitionMachineSessionEpoch(db, {+ type: "rotate",+ tokenId,+ metadata: {+ ...rest,+ availableRuntimes: runtimeReport,+ },+ expectedMachineId,})- // Broadcast machine.created carrying the pairing token so the client- // side (which is waiting on that specific `cmt_` to resolve) can- // reconcile its pending state. The WS DO's later `ready`-frame handler- // does NOT re-emit machine.created — activation is the single source- // of the create event.- const machine = await queries.communityMachine.getMachineByIdForUser(- db,- result.userId,- result.machineId- )- if (machine) {- const summary = queries.communityMachine.toSummary(machine)- const event: CommunityMachineCreated = {- type: WS_EVENTS.MACHINE_CREATED,- machine: summary,- tokenId,- }- broadcastToUser(result.userId, event).catch((err) => {- log.warn("broadcast after activate failed", {+ // Rotation already committed. Cleanup and the user-visible event are+ // independent post-commit branches: neither delays the response, and a+ // stuck historical DO close cannot suppress machine.created.+ const cleanup = Promise.resolve()+ .then(() => forceCloseCommunityMachinesByDoNames(ctx.env, result.revokedDoNames))+ .catch((err) => {+ log.warn("post-commit machine cleanup failed", {err: err instanceof Error ? err.message : String(err),})})+ const publish = (async () => {+ const machine = await queries.communityMachine.getMachineByIdForUser(+ db,+ result.userId,+ result.machineId+ )+ if (machine) {+ const summary = queries.communityMachine.toSummary(machine)+ const event: CommunityMachineCreated = {+ type: WS_EVENTS.MACHINE_CREATED,+ machine: summary,+ tokenId,+ }+ await broadcastToUser(result.userId, event)+ }+ })().catch((err) => {+ log.warn("post-commit machine event failed", {+ err: err instanceof Error ? err.message : String(err),+ })+ })+ for (const work of [cleanup, publish]) {+ try {+ ctx.waitUntil?.(work)+ } catch (err) {+ log.warn("failed to register post-commit activation work", {+ err: err instanceof Error ? err.message : String(err),+ })+ }}const body: CommunityDaemonActivateResponse = {credential: result.credential,machineId: result.machineId,expiresAt: null,+ sessionOutcome: "committed",}return NextResponse.json(body)} catch (err) {- if (err instanceof queries.communityMachine.ActivateCredentialError) {+ if (err instanceof queries.communityMachineSession.MachineSessionRotationError) {+ const errorBody = { error: err.message, sessionOutcome: err.sessionOutcome }switch (err.kind) {case "unknown":- return NextResponse.json({ error: err.message }, { status: 404 })+ return NextResponse.json(errorBody, { status: 404 })case "expired":- return NextResponse.json({ error: err.message }, { status: 410 })+ return NextResponse.json(errorBody, { status: 410 })case "revoked":case "already_active":- return NextResponse.json({ error: err.message }, { status: 409 })+ case "expected_machine_required":+ case "machine_mismatch":+ return NextResponse.json(errorBody, { status: 409 })}}log.error("activate failed", { err: err instanceof Error ? err.message : String(err) })diff --git a/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts b/src/web/src/app/api/community/machines/[id]/reconnect/route.test.tsnew file mode 100644index 000000000..1d04de612--- /dev/null+++ b/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mockCreateReconnectPairingToken = vi.fn()+const mockRevokeRunnerKeysForMachine = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", () => ({+ queries: {+ communityMachine: {+ createReconnectPairingToken: (...args: unknown[]) =>+ mockCreateReconnectPairingToken(...args),+ revokeRunnerKeysForMachine: (...args: unknown[]) =>+ mockRevokeRunnerKeysForMachine(...args),+ },+ },+}))++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any, ctx?: any) =>+ handler(req, {+ env: { DB: {} },+ userId: "u_1",+ email: "[email protected]",+ params: ctx?.params,+ }),+}))++vi.mock("@/lib/middleware/helpers", async () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) =>+ NextResponse.json({ error: message }, { status }),+ }+})++import { POST } from "./route"++describe("POST /api/community/machines/[id]/reconnect", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockCreateReconnectPairingToken.mockResolvedValue({+ tokenId: "cmt_reconnect",+ expiresAt: "2026-08-18T12:00:00.000Z",+ })+ })++ it("mints a bound token without disrupting runner keys or the current epoch", async () => {+ const response = await POST({} as any, { params: { id: "cm_abcdefgh" } } as any)++ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({+ tokenId: "cmt_reconnect",+ expiresAt: "2026-08-18T12:00:00.000Z",+ })+ expect(mockCreateReconnectPairingToken).toHaveBeenCalledWith(+ {},+ "u_1",+ "cm_abcdefgh",+ )+ expect(mockRevokeRunnerKeysForMachine).not.toHaveBeenCalled()+ })++ it("maps a cross-owner machine to 404", async () => {+ mockCreateReconnectPairingToken.mockRejectedValue(+ new Error("createReconnectPairingToken: machine not owned by user"),+ )++ const response = await POST({} as any, { params: { id: "cm_other" } } as any)+ expect(response.status).toBe(404)+ })+})diff --git a/src/web/src/app/api/community/machines/[id]/reconnect/route.ts b/src/web/src/app/api/community/machines/[id]/reconnect/route.tsindex 2d674189f..3006b623c 100644--- a/src/web/src/app/api/community/machines/[id]/reconnect/route.ts+++ b/src/web/src/app/api/community/machines/[id]/reconnect/route.ts@@ -4,10 +4,9 @@ import { withAuth } from "@/lib/middleware/auth"import { writeError, writeJSON } from "@/lib/middleware/helpers"// Reconnect: mint a new pending pairing token bound to the existing-// machineId. No `cmk_` rotation happens here — the daemon runs-// `alook daemon start --machine-key <new cmt_>`, and /activate reuses the-// same machine row while inserting a fresh credential and revoking the-// prior one (which force-closes the live DO).+// machineId. Minting is deliberately non-disruptive: credential and runner+// rotation happens only when the exact-machine reconnect command activates+// this token.export const POST = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)const id = ctx.params?.id as string@@ -19,11 +18,6 @@ export const POST = withAuth(async (_req, ctx) => {ctx.userId,id)- // Reconnect rotates `cmk_` on next /activate. Runner keys are tied to- // the machine but authorized by `cmk_`, so stale `crk_` rows would- // outlive the credential that authorized them. Revoke them here so the- // daemon re-enrolls after reconnect.- await queries.communityMachine.revokeRunnerKeysForMachine(db, id)return writeJSON({ tokenId: token.tokenId, expiresAt: token.expiresAt })} catch (err) {if (err instanceof Error && /not owned by user/.test(err.message)) {diff --git a/src/web/src/components/community/machines/pair-machine-sheet.test.ts b/src/web/src/components/community/machines/pair-machine-sheet.test.tsindex be741cc00..0037368ea 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.test.ts+++ b/src/web/src/components/community/machines/pair-machine-sheet.test.ts@@ -83,6 +83,7 @@ describe("PairMachineSheet desktop daemon integration", () => {expect(mocks.invoke).toHaveBeenCalledWith("daemon_runtime_capability")expect(mocks.invoke).toHaveBeenCalledWith("daemon_pair", {machineKey: "cmt_desktop_token",+ machineId: null,})expect(mocks.invoke.mock.calls.filter(([command]) => command === "daemon_pair")).toHaveLength(1)expect(mocks.toastSuccess).toHaveBeenCalledWith("This computer is connecting")@@ -91,6 +92,34 @@ describe("PairMachineSheet desktop daemon integration", () => {.toContain("@alook/daemon")})+ it("uses the explicit exact-machine reconnect command in terminal and native paths", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PairMachineSheet, {+ open: true,+ onOpenChange: vi.fn(),+ pendingTokenId: "cmt_reconnect_token",+ setPendingTokenId: vi.fn(),+ connectedHostname: null,+ mode: { kind: "reconnect", machineId: "cm_abcdefgh", hostname: "host" },+ }))+ })++ const command = renderer.root+ .findByProps({ "data-testid": tid.machinePairCommand })+ .children.join("")+ expect(command).toContain("npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon reconnect")+ expect(command).toContain("--id cm_abcdefgh --machine-key cmt_reconnect_token")++ await act(async () => {+ await renderer.root.findByProps({ "data-testid": tid.machinePairDesktopConnect }).props.onClick()+ })+ expect(mocks.invoke).toHaveBeenCalledWith("daemon_pair", {+ machineKey: "cmt_reconnect_token",+ machineId: "cm_abcdefgh",+ })+ })+it("surfaces a daemon launch error without removing command and copy fallback", async () => {mocks.invoke.mockImplementation((command: string) => {if (command === "daemon_runtime_capability") {@@ -150,7 +179,7 @@ describe("PairMachineSheet desktop daemon integration", () => {it("keeps the command fallback and explains an unavailable Desktop runtime", async () => {mocks.invoke.mockResolvedValue({available: false,- reason: "npx was not found. Install npm with Node.js and try again.",+ reason: "npm was not found. Install npm with Node.js and try again.",nodeVersion: "v16.0.0",})let renderer!: TestRenderer.ReactTestRenderer@@ -166,7 +195,7 @@ describe("PairMachineSheet desktop daemon integration", () => {expect(renderer.root.findAllByProps({ "data-testid": tid.machinePairDesktopConnect })).toHaveLength(0)expect(renderer.root.findByProps({ "data-testid": tid.machinePairRuntimeHint }).children.join(""))- .toContain("npx was not found")+ .toContain("npm was not found")expect(renderer.root.findByProps({ "data-testid": tid.machinePairCommand })).toBeTruthy()expect(renderer.root.findByProps({ "data-testid": tid.machinePairCopy })).toBeTruthy()})@@ -194,7 +223,7 @@ describe("PairMachineSheet desktop daemon integration", () => {let renderer!: TestRenderer.ReactTestRendereract(() => {renderer = TestRenderer.create(React.createElement(PairMachineSteps, {- command: "npx @alook/daemon daemon start",+ command: "npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon start",generating: false,onCopy: vi.fn(),connectedHostname: null,diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsxindex e993c3edb..6280fcc30 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx@@ -30,10 +30,15 @@ const isLocal = isLocalMode()// Only ever called once `pendingTokenId` is set, which happens from a// client-only effect — safe to touch `location` here (never runs during SSR).-function buildPairCommand(machineKey: string): string {+function buildPairCommand(machineKey: string, machineId?: string): string {const { serverUrl, wsUrl } = pairEndpoints()- const bin = isLocal ? "pnpm daemon" : "npx @alook/daemon daemon"- return `${bin} start --machine-key ${machineKey} --server-url ${serverUrl} --ws-url ${wsUrl}`+ const bin = isLocal+ ? "pnpm daemon"+ : "npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon"+ const action = machineId+ ? `reconnect --id ${machineId} --machine-key ${machineKey}`+ : `start --machine-key ${machineKey}`+ return `${bin} ${action} --server-url ${serverUrl} --ws-url ${wsUrl}`}function pairEndpoints(): { serverUrl: string; wsUrl: string } {@@ -144,7 +149,7 @@ export function PairMachineSheet({available: false,reason: nativeErrorMessage(error,- "Alook couldn't check Node.js, npm, and npx on this computer.",+ "Alook couldn't check Node.js and npm on this computer.",),nodeVersion: null,})@@ -157,7 +162,12 @@ export function PairMachineSheet({}}, [open, desktopNative])- const command = pendingTokenId ? buildPairCommand(pendingTokenId) : ""+ const command = pendingTokenId+ ? buildPairCommand(+ pendingTokenId,+ mode.kind === "reconnect" ? mode.machineId : undefined,+ )+ : ""const copyCommand = useCallback(async () => {if (!command) return@@ -177,6 +187,7 @@ export function PairMachineSheet({try {const result = await tauriInvoke<{ success: boolean; message: string }>("daemon_pair", {machineKey: pendingTokenId,+ machineId: mode.kind === "reconnect" ? mode.machineId : null,})if (!result.success) throw new Error(result.message || "The daemon did not start")setStarted(true)@@ -192,7 +203,7 @@ export function PairMachineSheet({connectingRef.current = falsesetConnecting(false)}- }, [pendingTokenId, runtimeCapability?.available, isReconnect])+ }, [pendingTokenId, runtimeCapability?.available, isReconnect, mode])return (<Sheet open={open} onOpenChange={onOpenChange}>@@ -206,7 +217,7 @@ export function PairMachineSheet({</SheetTitle><SheetDescription>{isReconnect- ? "We rotated the key. Run the new command before it expires — the old one is no longer accepted."+ ? "Run this command before it expires. It safely replaces the running daemon, then rotates its key.": "Run this on the computer you want to connect. The key is good for 15 minutes."}</SheetDescription></SheetHeader>@@ -331,7 +342,7 @@ function Step1({</header><p className="text-sm text-muted-foreground">Open a terminal on the computer you want to connect, paste the command,- and hit enter. Node.js with npm and npx is required.+ and hit enter. Node.js with npm is required.</p>{generating ? (<div className="flex items-center gap-2 rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">@@ -362,8 +373,8 @@ function Step1({{launchError? `${launchError} The terminal command remains available below.`: checkingRuntime- ? "Checking this computer for Node.js, npm, and npx…"- : runtimeCapability?.reason ?? "Node.js, npm, and npx are required for one-click connection."}+ ? "Checking this computer for Node.js and npm…"+ : runtimeCapability?.reason ?? "Node.js and npm are required for one-click connection."}</p>)}</div>diff --git a/src/web/src/components/home/landing-content.test.ts b/src/web/src/components/home/landing-content.test.tsindex 16f42c72c..2be6340b9 100644--- a/src/web/src/components/home/landing-content.test.ts+++ b/src/web/src/components/home/landing-content.test.ts@@ -133,6 +133,10 @@ describe("landing content contract", () => {)expect(shellSource).not.toMatch(/<h[1-6]\b/)+ expect(shellSource).toContain(+ "npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon start",+ )+ expect(shellSource).not.toMatch(/npx(?: --yes)? @alook\/daemon/)expect(shellSource.match(/<DmHeader dm=\{DMS\[0\]\} titleAs="div" \/>/g)).toHaveLength(2)expect(shellSource).toContain('headingAs="div"')expect(dmHeaderSource).toContain('titleAs: Title = "h1"')diff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsxindex c8dce1846..b6e943d25 100644--- a/src/web/src/components/home/landing-shell-motion.tsx+++ b/src/web/src/components/home/landing-shell-motion.tsx@@ -507,7 +507,7 @@ const BOT_AVATAR_DRAFT: AvatarDraft = {}const PAIR_COMMAND =- "npx @alook/daemon daemon start --machine-key cmk_demo --server-url https://alook.ai --ws-url wss://alook.ai/api/ws/community-daemon"+ "npm exec --yes --package=@alook/daemon@latest -- alook-daemon daemon start --machine-key cmk_demo --server-url https://alook.ai --ws-url wss://alook.ai/api/ws/community-daemon"function useReducedMotion() {const [reduced, setReduced] = useState(false)diff --git a/src/web/src/lib/middleware/community-pairing-token.test.ts b/src/web/src/lib/middleware/community-pairing-token.test.tsindex a710ccf0c..6a6d024c0 100644--- a/src/web/src/lib/middleware/community-pairing-token.test.ts+++ b/src/web/src/lib/middleware/community-pairing-token.test.ts@@ -18,13 +18,14 @@ const pairingQuerySpies = {createReconnectPairingToken: vi.fn(),touchTokenLastUsed: vi.fn(),revokeToken: vi.fn(),- activateMachineCredential: vi.fn(),findActiveCredentialByBearer: vi.fn(),findCredentialByHash: vi.fn(),}+const sessionTransitionSpy = vi.fn()vi.mock("@alook/shared", () => ({queries: {communityMachine: pairingQuerySpies,+ communityMachineSession: { transitionMachineSessionEpoch: sessionTransitionSpy },},}))@@ -120,5 +121,6 @@ describe("withCommunityPairingToken", () => {for (const [name, spy] of Object.entries(pairingQuerySpies)) {expect(spy, `middleware should not have called communityMachine.${name}`).not.toHaveBeenCalled()}+ expect(sessionTransitionSpy).not.toHaveBeenCalled()})})diff --git a/src/web/src/lib/middleware/community-pairing-token.ts b/src/web/src/lib/middleware/community-pairing-token.tsindex bde38927f..d6a138a57 100644--- a/src/web/src/lib/middleware/community-pairing-token.ts+++ b/src/web/src/lib/middleware/community-pairing-token.ts@@ -4,6 +4,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"interface CommunityPairingTokenContext {env: EnvrawTokenId: string+ waitUntil?: (promise: Promise<unknown>) => void}export type CommunityPairingTokenAuthenticatedHandler = (@@ -41,12 +42,13 @@ export function withCommunityPairingToken(handler: CommunityPairingTokenAuthentireturn NextResponse.json({ error: "invalid pairing token" }, { status: 401 })}- const { env } = await getCloudflareContext({ async: true })+ const { env, ctx } = await getCloudflareContext({ async: true })const cloudflareEnv = env as Envreturn handler(req, {env: cloudflareEnv,rawTokenId,+ waitUntil: ctx ? ctx.waitUntil.bind(ctx) : undefined,params: resolvedParams,})}diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.tsindex 91715e40a..1b4f1ce71 100644--- a/src/ws-do/src/ws-durable/machine-frames.test.ts+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts@@ -160,6 +160,7 @@ describe("WebSocketDurableObject", () => {const frame = JSON.stringify({type: "ready",runtimeReport: [{ id: "claude", version: "1.0.0" }],+ capabilities: ["control-heartbeat-v1"],runningAgents: [],hostname: "my-mac",platform: "darwin",@@ -170,7 +171,7 @@ describe("WebSocketDurableObject", () => {await durable.webSocketMessage(ws as any, frame)expect(mockUpsertMachineByMachineId).toHaveBeenCalledTimes(1)- const [, userId, machineId, meta] = mockUpsertMachineByMachineId.mock.calls[0]+ const [, userId, machineId, meta, credentialHash] = mockUpsertMachineByMachineId.mock.calls[0]expect(userId).toBe("u_1")expect(machineId).toBe("cm_1")expect(meta).toMatchObject({@@ -181,6 +182,7 @@ describe("WebSocketDurableObject", () => {daemonVersion: "0.1.0",availableRuntimes: [{ id: "claude", version: "1.0.0" }],})+ expect(credentialHash).toBe("0".repeat(64))})it.each([@@ -201,6 +203,21 @@ describe("WebSocketDurableObject", () => {userId: "u_1",authenticated: true,})+ if (expected) {+ mockUpsertMachineByMachineId.mockResolvedValueOnce({+ machine: {+ id: "cm_1",+ hostname: "host",+ availableRuntimes: [],+ status: "online",+ lastSeenAt: "now",+ },+ priorLastSeenAt: "before",+ priorAvailableRuntimes: [],+ priorDaemonVersion: "0.1.0",+ priorStatus: "online",+ })+ }await durable.webSocketMessage(ws as any, JSON.stringify({type: "ready",@@ -210,8 +227,14 @@ describe("WebSocketDurableObject", () => {}))expect(ws._attachment).toMatchObject({ controlHeartbeat: expected })- if (expected) expect((ws._attachment as any).lastHeartbeatAckAt).toBe(9_000_000)- else expect((ws._attachment as any).lastHeartbeatAckAt).toBeUndefined()+ if (expected) {+ expect((ws._attachment as any).lastHeartbeatAckAt).toBe(9_000_000)+ expect(ws.close).not.toHaveBeenCalled()+ } else {+ expect((ws._attachment as any).lastHeartbeatAckAt).toBeUndefined()+ expect(ws.close).toHaveBeenCalledWith(1008, "Daemon upgrade required")+ expect(mockUpsertMachineByMachineId).not.toHaveBeenCalled()+ }})it("silently drops a wrapped `{ready:{...}}` frame (legacy shape — regression guard)", async () => {@@ -317,6 +340,7 @@ describe("WebSocketDurableObject", () => {const frame = JSON.stringify({type: "ready",runtimeReport: [],+ capabilities: ["control-heartbeat-v1"],runningAgents: [],})await durable.webSocketMessage(ws as any, frame)@@ -362,7 +386,12 @@ describe("WebSocketDurableObject", () => {authenticated: true,})- const frame = JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] })+ const frame = JSON.stringify({+ type: "ready",+ runtimeReport: [],+ capabilities: ["control-heartbeat-v1"],+ runningAgents: [],+ })await durable.webSocketMessage(ws as any, frame)const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/community-broadcast"))@@ -483,7 +512,12 @@ describe("WebSocketDurableObject", () => {await durable.webSocketMessage(machineWs() as any,- JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] }),+ JSON.stringify({+ type: "ready",+ runtimeReport: [],+ capabilities: ["control-heartbeat-v1"],+ runningAgents: [],+ }),)expect(mockReconcileBotActivityFromRunningAgents).not.toHaveBeenCalled()@@ -499,7 +533,12 @@ describe("WebSocketDurableObject", () => {await durable.webSocketMessage(ws as any,- JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] }),+ JSON.stringify({+ type: "ready",+ runtimeReport: [],+ capabilities: ["control-heartbeat-v1"],+ runningAgents: [],+ }),)expect(ws.close).not.toHaveBeenCalled()@@ -535,6 +574,7 @@ describe("WebSocketDurableObject", () => {const driftFrame = JSON.stringify({type: "ready",runtimeReport: [{ id: "codex", version: "1", status: "unhealthy", lastError: "ENOENT" }],+ capabilities: ["control-heartbeat-v1"],runningAgents: [],})await durable.webSocketMessage(machineWs() as any, driftFrame)@@ -582,6 +622,7 @@ describe("WebSocketDurableObject", () => {JSON.stringify({type: "ready",runtimeReport: [],+ capabilities: ["control-heartbeat-v1"],runningAgents: [],daemonVersion: "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.tsindex 896b78268..b550d81b3 100644--- a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts+++ b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts@@ -202,6 +202,7 @@ describe("WebSocketDurableObject", () => {JSON.stringify({type: "ready",runtimeReport: [],+ capabilities: ["control-heartbeat-v1"],runningAgents: [],daemonVersion: "0.1.7",}),@@ -312,6 +313,13 @@ describe("WebSocketDurableObject", () => {lastHeartbeatAckAt: 9_940_000,})getWebSockets.mockReturnValue([ws])+ mockTouchMachineHeartbeat.mockResolvedValueOnce({+ machine: { id: "cm_1", status: "online", lastSeenAt: "now" },+ priorLastSeenAt: "before",+ priorAvailableRuntimes: [],+ priorDaemonVersion: "0.1.0",+ priorStatus: "online",+ })await durable.alarm()@@ -411,6 +419,37 @@ describe("WebSocketDurableObject", () => {expect(store.has("community-machine-identity")).toBe(false)})+ it("fails closed when an authenticated socket lacks the heartbeat capability", async () => {+ const { durable, store, getWebSockets } = createDO()+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "hash",+ })+ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })+ getWebSockets.mockReturnValue([ws])+ mockMarkMachineOffline.mockResolvedValueOnce({+ id: "cm_1",+ status: "offline",+ lastSeenAt: "now",+ })++ await durable.alarm()++ expect(ws.close).toHaveBeenCalledWith(1008, "Daemon upgrade required")+ expect(mockTouchMachineHeartbeat).not.toHaveBeenCalled()+ expect(mockMarkMachineOffline).toHaveBeenCalledOnce()+ expect(store.has("community-machine-handle")).toBe(false)+ expect(store.has("community-machine-identity")).toBe(false)+ })+it("machine-keyed deadline owner expires D1 without a socket, poll, or daemon reconnect", async () => {vi.spyOn(Date, "now").mockReturnValue(30_000_000)const { durable, store, getWebSockets } = createDO()@@ -430,7 +469,7 @@ describe("WebSocketDurableObject", () => {expect(store.has("community-machine-diagnostic-alarm-hint")).toBe(false)})- it("live-WS + status=offline row: markMachineOnlineIfOffline flips it back online and broadcasts (post-deploy backfill)", async () => {+ it("current-epoch heartbeat projects an offline row online and broadcasts", async () => {const { durable, store, getWebSockets, ctx } = createDO()store.set("community-machine-identity", {userId: "u_1",@@ -445,25 +484,25 @@ describe("WebSocketDurableObject", () => {machineId: "cm_1",userId: "u_1",authenticated: true,+ controlHeartbeat: true,+ lastHeartbeatAckAt: Date.now(),})getWebSockets.mockReturnValue([ws])mockTouchMachineHeartbeat.mockResolvedValueOnce({- lastSeenAt: "now",+ machine: { id: "cm_1", status: "online", lastSeenAt: "now" },priorLastSeenAt: "earlier",- })- mockMarkMachineOnlineIfOffline.mockResolvedValueOnce({- id: "cm_1",- userId: "u_1",- status: "online",- lastSeenAt: "now",+ priorAvailableRuntimes: [],+ priorDaemonVersion: "0.1.0",+ priorStatus: "offline",})mockStubFetch.mockClear()await durable.alarm()expect(mockTouchMachineHeartbeat).toHaveBeenCalledTimes(1)- expect(mockMarkMachineOnlineIfOffline).toHaveBeenCalledTimes(1)+ expect(mockTouchMachineHeartbeat).toHaveBeenCalledWith({}, "u_1", "cm_1", "abc")+ expect(mockMarkMachineOnlineIfOffline).not.toHaveBeenCalled()// Broadcast fired for the offline→online transition.expect(mockStubFetch).toHaveBeenCalled()// Alarm rescheduled for the next heartbeat tick.@@ -484,21 +523,24 @@ describe("WebSocketDurableObject", () => {machineId: "cm_1",userId: "u_1",authenticated: true,+ controlHeartbeat: true,+ lastHeartbeatAckAt: Date.now(),})getWebSockets.mockReturnValue([ws])mockTouchMachineHeartbeat.mockResolvedValueOnce({- lastSeenAt: "now",+ machine: { id: "cm_1", status: "online", lastSeenAt: "now" },priorLastSeenAt: "earlier",+ priorAvailableRuntimes: [],+ priorDaemonVersion: "0.1.0",+ priorStatus: "online",})- // Guarded UPDATE returns zero rows — row is already online.- mockMarkMachineOnlineIfOffline.mockResolvedValueOnce(null)mockStubFetch.mockClear()await durable.alarm()expect(mockTouchMachineHeartbeat).toHaveBeenCalledTimes(1)- // No broadcast — the guarded UPDATE returned zero rows.+ expect(mockMarkMachineOnlineIfOffline).not.toHaveBeenCalled()expect(mockStubFetch).not.toHaveBeenCalled()// Alarm rescheduled.expect(ctx.storage.setAlarm).toHaveBeenCalled()@@ -658,13 +700,20 @@ describe("WebSocketDurableObject", () => {it("reschedules the exact heartbeat when live heartbeat touch rejects", async () => {vi.spyOn(Date, "now").mockReturnValue(4_000_000)- const { durable, getWebSockets, storage } = createDO()+ const { durable, getWebSockets, store, storage } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "hash",+ })const ws = createMockWebSocket()ws.serializeAttachment({type: "community-machine",machineId: "cm_1",userId: "u_1",authenticated: true,+ controlHeartbeat: true,+ lastHeartbeatAckAt: 4_000_000,})getWebSockets.mockReturnValue([ws])mockTouchMachineHeartbeat.mockRejectedValueOnce(new Error("d1 unavailable"))@@ -673,7 +722,7 @@ describe("WebSocketDurableObject", () => {expect(storage.setAlarm).toHaveBeenCalledWith(4_060_000)})- it("reschedules the exact heartbeat when live online backfill rejects", async () => {+ it("reschedules without broadcasting when current-epoch heartbeat is a guarded no-op", async () => {vi.spyOn(Date, "now").mockReturnValue(5_000_000)const { durable, getWebSockets, store, storage } = createDO()store.set("community-machine-identity", {@@ -687,13 +736,15 @@ describe("WebSocketDurableObject", () => {machineId: "cm_1",userId: "u_1",authenticated: true,+ controlHeartbeat: true,+ lastHeartbeatAckAt: 5_000_000,})getWebSockets.mockReturnValue([ws])- mockTouchMachineHeartbeat.mockResolvedValueOnce({ lastSeenAt: "now", priorLastSeenAt: "before" })- mockMarkMachineOnlineIfOffline.mockRejectedValueOnce(new Error("d1 unavailable"))+ mockTouchMachineHeartbeat.mockResolvedValueOnce(null)await expect(durable.alarm()).resolves.toBeUndefined()expect(storage.setAlarm).toHaveBeenCalledWith(5_060_000)+ expect(mockStubFetch).not.toHaveBeenCalled()})it("retains lifecycle storage and retries when a stale offline flip rejects", async () => {diff --git a/src/ws-do/src/ws-durable/machine-lifecycle.ts b/src/ws-do/src/ws-durable/machine-lifecycle.tsindex cdfef1167..3720a3d96 100644--- a/src/ws-do/src/ws-durable/machine-lifecycle.ts+++ b/src/ws-do/src/ws-durable/machine-lifecycle.ts@@ -113,19 +113,19 @@ export function handleDiagnosticCommandAck(async function markIdentityOffline(context: WsDurableContext,identity: CommunityMachineIdentity,+ cause: "close" | "expire",): Promise<boolean> {const db = createDb(context.env.DB)- const flipped = await queries.communityMachine.markMachineOffline(db, {- userId: identity.userId,- machineId: identity.machineId,- credentialHash: identity.credentialHash,+ const result = await queries.communityMachineSession.transitionMachineSessionEpoch(db, {+ type: cause,+ epoch: identity,})- if (!flipped) return false+ if (result.type === "stale_epoch") return falseawait notifyUserDO(context, identity.userId, {type: WS_EVENTS.MACHINE_STATUS,machineId: identity.machineId,status: "offline",- lastSeenAt: flipped.lastSeenAt ?? new Date().toISOString(),+ lastSeenAt: result.machine.lastSeenAt ?? new Date().toISOString(),}).catch(() => { })await context.ctx.storage.delete(HANDLE_KEY)await context.ctx.storage.delete(IDENTITY_KEY)@@ -179,7 +179,7 @@ export async function handleCommunityMachineClose(})if (replacementIsLive) returntry {- const flipped = await markIdentityOffline(context, identity)+ const flipped = await markIdentityOffline(context, identity, "close")if (!flipped) {// The guarded row belongs to a newer credential (or is already// offline), so this close is terminal for the old DO identity.@@ -188,7 +188,7 @@ export async function handleCommunityMachineClose(return}} catch (err) {- context.log.warn("markMachineOffline failed on webSocketClose", { err: String(err) })+ context.log.warn("session close transition failed", { err: String(err) })await context.ctx.storage.setAlarm(Date.now() + COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS)}await scheduleHeartbeatAlarm(context)@@ -199,59 +199,74 @@ export async function handleMachineAlarm(context: WsDurableContext): Promise<voiawait sweepDiagnosticDeadlines(context, now)const liveMachines: Array<{ userId: string; machineId: string }> = []- let expiredCapableSocket = false+ let expiredMachineSocket = falsefor (const ws of authenticatedMachineSockets(context)) {const state = ws.deserializeAttachment() as CommunityMachineConnectionState- if (state.controlHeartbeat === true) {- const lastAckAt = state.lastHeartbeatAckAt ?? 0- if (now - lastAckAt >= COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS) {- expiredCapableSocket = true- try { ws.close(1011, "Heartbeat lease expired") } catch { }- continue- }- const nonce = state.pendingHeartbeatNonce ?? crypto.randomUUID()- ws.serializeAttachment({ ...state, pendingHeartbeatNonce: nonce })- try { ws.send(JSON.stringify({ type: "machine:heartbeat", nonce })) } catch { }+ if (state.controlHeartbeat !== true) {+ expiredMachineSocket = true+ try { ws.close(1008, "Daemon upgrade required") } catch { }+ continue+ }+ const lastAckAt = state.lastHeartbeatAckAt ?? 0+ if (now - lastAckAt >= COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS) {+ expiredMachineSocket = true+ try { ws.close(1011, "Heartbeat lease expired") } catch { }+ continue}+ const nonce = state.pendingHeartbeatNonce ?? crypto.randomUUID()+ ws.serializeAttachment({ ...state, pendingHeartbeatNonce: nonce })+ try { ws.send(JSON.stringify({ type: "machine:heartbeat", nonce })) } catch { }liveMachines.push({ userId: state.userId, machineId: state.machineId })}if (liveMachines.length > 0) {const db = createDb(context.env.DB)const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)+ let currentLeaseCount = 0+ let heartbeatUnavailable = falsefor (const machine of liveMachines) {- try {- await queries.communityMachine.touchMachineHeartbeat(db, machine.userId, machine.machineId)- } catch { }if (identity && identity.userId === machine.userId && identity.machineId === machine.machineId) {try {- const backfilled = await queries.communityMachine.markMachineOnlineIfOffline(db, {- userId: identity.userId,- machineId: identity.machineId,- credentialHash: identity.credentialHash,+ const heartbeat = await queries.communityMachineSession.transitionMachineSessionEpoch(db, {+ type: "renew",+ epoch: identity,})- if (backfilled) {+ if (heartbeat.type === "stale_epoch") {+ expiredMachineSocket = true+ for (const ws of authenticatedMachineSockets(context)) {+ const state = ws.deserializeAttachment() as CommunityMachineConnectionState+ if (state.userId === machine.userId && state.machineId === machine.machineId) {+ try { ws.close(1008, "Credential no longer current") } catch { }+ }+ }+ continue+ }+ currentLeaseCount+++ if (heartbeat.priorStatus === "offline") {await notifyUserDO(context, identity.userId, {type: WS_EVENTS.MACHINE_STATUS,machineId: identity.machineId,status: "online",- lastSeenAt: backfilled.lastSeenAt ?? new Date().toISOString(),+ lastSeenAt: heartbeat.machine.lastSeenAt ?? new Date().toISOString(),}).catch(() => { })}} catch (err) {- context.log.warn("markMachineOnlineIfOffline (alarm fresh-WS) failed", { err: String(err) })+ heartbeatUnavailable = true+ context.log.warn("current-epoch heartbeat failed", { err: String(err) })}}}- await scheduleHeartbeatAlarm(context)- return+ if (currentLeaseCount > 0 || heartbeatUnavailable) {+ await scheduleHeartbeatAlarm(context)+ return+ }}const stored = await context.ctx.storage.get<CommunityMachineHandle>(HANDLE_KEY)const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)- if (expiredCapableSocket && identity) {+ if (expiredMachineSocket && identity) {try {- const flipped = await markIdentityOffline(context, identity)+ const flipped = await markIdentityOffline(context, identity, "expire")if (!flipped) {// A guarded no-op means this credential no longer owns the D1 row// (or another actor already won the offline transition). Forget only@@ -261,7 +276,7 @@ export async function handleMachineAlarm(context: WsDurableContext): Promise<voiawait context.ctx.storage.delete(IDENTITY_KEY)}} catch (err) {- context.log.warn("markMachineOffline (heartbeat lease) failed", { err: String(err) })+ context.log.warn("session expiry transition failed", { err: String(err) })await context.ctx.storage.setAlarm(now + COMMUNITY_MACHINE_HEARTBEAT_MS)return}@@ -287,9 +302,9 @@ export async function handleMachineAlarm(context: WsDurableContext): Promise<voiif (identity) {let flipped: booleantry {- flipped = await markIdentityOffline(context, identity)+ flipped = await markIdentityOffline(context, identity, "expire")} catch (err) {- context.log.warn("markMachineOffline (alarm stale-flip) failed", { err: String(err) })+ context.log.warn("stale session expiry transition failed", { err: String(err) })await context.ctx.storage.setAlarm(now + COMMUNITY_MACHINE_HEARTBEAT_MS)return}diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.tsindex 8cb3067d0..3b5a95c00 100644--- a/src/ws-do/src/ws-durable/machine-ready.ts+++ b/src/ws-do/src/ws-durable/machine-ready.ts@@ -65,6 +65,7 @@ export async function handleReadyFrame(const readyParse = HostReadyMessageSchema.safeParse(parsed)if (!readyParse.success) return falseconst ready = readyParse.data+ const controlHeartbeat = ready.capabilities.includes(CONTROL_HEARTBEAT_CAPABILITY)const state = ws.deserializeAttachment() as import("./internal").ConnectionStateif (state?.type === "community-machine" &&@@ -72,7 +73,6 @@ export async function handleReadyFrame(state.userId === identity.userId &&state.machineId === identity.machineId) {- const controlHeartbeat = (ready.capabilities ?? []).includes(CONTROL_HEARTBEAT_CAPABILITY)ws.serializeAttachment({...state,controlHeartbeat,@@ -80,6 +80,17 @@ export async function handleReadyFrame(pendingHeartbeatNonce: undefined,})}+ if (!controlHeartbeat) {+ try {+ ws.send(JSON.stringify({+ type: "error",+ code: "UPGRADE_REQUIRED",+ reason: "daemon does not support the required heartbeat lease",+ }))+ } catch { }+ try { ws.close(1008, "Daemon upgrade required") } catch { }+ return true+ }try {const hostname = ready.hostname ?? ""const platform = ready.platform ?? ""@@ -89,14 +100,17 @@ export async function handleReadyFrame(const availableRuntimes: CommunityMachineRuntime[] = ready.runtimeReportconst db = createDb(context.env.DB)- const result = await queries.communityMachine.upsertMachineByMachineId(- db,- identity.userId,- identity.machineId,- { hostname, platform, arch, daemonVersion, osRelease, availableRuntimes }- )- if (!result) {- context.log.warn("community machine row missing on ready", { machineId: identity.machineId })+ const result = await queries.communityMachineSession.transitionMachineSessionEpoch(db, {+ type: "ready",+ epoch: identity,+ metadata: { hostname, platform, arch, daemonVersion, osRelease, availableRuntimes },+ })+ if (result.type === "stale_epoch") {+ context.log.warn("community machine epoch rejected on ready", { machineId: identity.machineId })+ try {+ ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))+ } catch { }+ try { ws.close(1008, "Credential no longer current") } catch { }return true}const { machine, priorAvailableRuntimes, priorDaemonVersion, priorStatus } = resultdiff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex f448fb183..c8c7bc646 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -384,15 +384,45 @@ vi.mock("@alook/shared", async () => {hashCredential: (bearer: string) => mockHashCredential(bearer),findCredentialByHash: (...a: any[]) => mockFindCredentialByHash(...a),getMachineByIdForUser: (...a: any[]) => mockGetMachineByIdForUser(...a),- upsertMachineByMachineId: (...a: any[]) => mockUpsertMachineByMachineId(...a),- touchMachineHeartbeat: (...a: any[]) => mockTouchMachineHeartbeat(...a),- markMachineOffline: (...a: any[]) => mockMarkMachineOffline(...a),- markMachineOnlineIfOffline: (...a: any[]) => mockMarkMachineOnlineIfOffline(...a),toSummary: (row: any) => mockToSummary(row),isBotOnline: (...a: [unknown, string]) => mockIsBotOnline(...a),reconcileBotActivityFromRunningAgents: (...a: any[]) =>mockReconcileBotActivityFromRunningAgents(...(a as [unknown, string, string[]])),},+ communityMachineSession: {+ transitionMachineSessionEpoch: async (db: unknown, command: any) => {+ if (command.type === "ready") {+ const result = await mockUpsertMachineByMachineId(+ db,+ command.epoch.userId,+ command.epoch.machineId,+ command.metadata,+ command.epoch.credentialHash,+ )+ return result ? { type: "transitioned", ...result } : { type: "stale_epoch" }+ }+ if (command.type === "renew") {+ const result = await mockTouchMachineHeartbeat(+ db,+ command.epoch.userId,+ command.epoch.machineId,+ command.epoch.credentialHash,+ )+ return result ? { type: "transitioned", ...result } : { type: "stale_epoch" }+ }+ const machine = await mockMarkMachineOffline(db, command.epoch)+ return machine+ ? {+ type: "transitioned",+ machine,+ priorLastSeenAt: machine.lastSeenAt ?? null,+ priorAvailableRuntimes: machine.availableRuntimes ?? [],+ priorDaemonVersion: machine.daemonVersion ?? "",+ priorStatus: "online",+ }+ : { type: "stale_epoch" }+ },+ },communityDiagnosticReport: {timeoutPendingDiagnosticReportsForMachine: (...a: any[]) => mockTimeoutPendingDiagnosticReportsForMachine(...a),getNextPendingDiagnosticDeadlineForMachine: (...a: any[]) => mockGetNextPendingDiagnosticDeadlineForMachine(...a),diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.tsindex 4af945129..b89d1ae79 100644--- a/tests/integration/daemon/control-plane.test.ts+++ b/tests/integration/daemon/control-plane.test.ts@@ -128,7 +128,12 @@ describe("daemon control plane — real ws-do wake round-trip", () => {receivedCommands.push(cmd)})channel.onResync(() => ({- ready: { runtimeReport: [{ id: "claude" }], runningAgents: [], daemonVersion: "0.1.7" },+ ready: {+ runtimeReport: [{ id: "claude" }],+ runningAgents: [],+ daemonVersion: "0.1.7",+ capabilities: ["control-heartbeat-v1"],+ },sessions: [],activities: [],}))