Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(daemon): recover reconnect without a complete launch record (#898)

Gustavo Ye6074975a5483
diff --git a/src/daemon/src/cli/daemonLifecycle.real.test.ts b/src/daemon/src/cli/daemonLifecycle.real.test.ts
index 3b17bd549..b93f50a28 100644
--- a/src/daemon/src/cli/daemonLifecycle.real.test.ts
+++ b/src/daemon/src/cli/daemonLifecycle.real.test.ts
@@ -4,6 +4,7 @@ import * as fs from "node:fs";
import { createRequire } from "node:module";
import * as os from "node:os";
import * as path from "node:path";
+import { createServer } from "node:http";
import { fileURLToPath, pathToFileURL } from "node:url";
import { daemonStart } from "./daemonStart";
@@ -172,6 +173,48 @@ afterEach(async () => {
});
describe("daemon lifecycle real processes", () => {
+ it("reconnects without a local record, persists the exact machine, and stops the real daemon", async () => {
+ const baseDir = makeEmptyBaseDir();
+ const requests: unknown[] = [];
+ const server = createServer(async (req, res) => {
+ if (req.url !== "/api/community/daemon/activate") {
+ res.writeHead(404).end();
+ return;
+ }
+ let body = "";
+ for await (const chunk of req) body += String(chunk);
+ requests.push(JSON.parse(body));
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({
+ credential: secret, machineId, expiresAt: null, sessionOutcome: "committed",
+ }));
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address() as { port: number };
+ const serverUrl = `http://127.0.0.1:${address.port}`;
+ try {
+ const result = await runCli([
+ cli, "daemon", "reconnect", "--id", machineId,
+ "--machine-key", "cmt_synthetic_reconnect",
+ "--server-url", serverUrl, "--ws-url", "ws://127.0.0.1:9",
+ "--base-dir", baseDir,
+ ]);
+ expect(result.code, result.output).toBe(0);
+ expect(result.output).not.toContain(secret);
+ expect(requests).toEqual([expect.objectContaining({ expectedMachineId: machineId })]);
+ const owner = readOwner(baseDir);
+ expect(owner.machineId).toBe(machineId);
+ expect(alive(owner.pid)).toBe(true);
+ const record = JSON.parse(fs.readFileSync(path.join(baseDir, "daemons", `${machineId}.credential.json`), "utf8"));
+ expect(record).toMatchObject({ schemaVersion: 1, machineId, credential: secret, serverUrl });
+ await stop(baseDir);
+ await waitFor(() => !alive(owner.pid));
+ expect(fs.existsSync(pidfile(baseDir))).toBe(false);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ }, 120_000);
+
it("starts detached while offline, persists no secret, and stops by stable machine id", async () => {
const baseDir = makeBaseDir();
const started = await runCli(cliArgs(baseDir));
diff --git a/src/daemon/src/cli/daemonStart.lifecycle.test.ts b/src/daemon/src/cli/daemonStart.lifecycle.test.ts
index 5e21a20e1..8ba4c00f5 100644
--- a/src/daemon/src/cli/daemonStart.lifecycle.test.ts
+++ b/src/daemon/src/cli/daemonStart.lifecycle.test.ts
@@ -68,6 +68,98 @@ describe("daemon lifecycle ownership cleanup", () => {
return { machineId, daemonDir };
}
+ it.each(["missing", "legacy", "invalid-version", "dead-owner"])("recovers an exact machine with a %s launch record", async (kind) => {
+ const { machineId, daemonDir } = writeReconnectState();
+ const recordPath = path.join(baseDir, "daemons", `${machineId}.credential.json`);
+ if (kind === "missing" || kind === "dead-owner") fs.rmSync(recordPath);
+ if (kind === "legacy") fs.writeFileSync(recordPath, JSON.stringify({ credential: "cmk_old", machineId }));
+ if (kind === "invalid-version") {
+ const record = JSON.parse(fs.readFileSync(recordPath, "utf8"));
+ fs.writeFileSync(recordPath, JSON.stringify({ ...record, daemonVersion: "invalid" }));
+ }
+ if (kind !== "dead-owner") fs.rmSync(path.join(daemonDir, "daemon.pid"));
+ vi.mocked(fetch).mockResolvedValue(new Response(JSON.stringify({
+ credential: "cmk_rotated", machineId, expiresAt: null, sessionOutcome: "committed",
+ }), { status: 200 }));
+ mockRunPreparedDaemon.mockResolvedValue(undefined);
+ const stop = vi.fn(async () => {});
+
+ await daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {
+ isProcessAlive: () => false,
+ stopExactDaemonPid: stop,
+ start: (opts) => daemonStart({ ...opts, foreground: true }),
+ });
+
+ expect(fetch).toHaveBeenCalledOnce();
+ const [url, init] = vi.mocked(fetch).mock.calls[0]!;
+ expect(url).toBe(`${kind === "invalid-version" ? "http://server" : "https://alook.ai"}/api/community/daemon/activate`);
+ expect(JSON.parse(String(init?.body))).toMatchObject({ expectedMachineId: machineId });
+ expect(JSON.parse(fs.readFileSync(recordPath, "utf8"))).toMatchObject({
+ schemaVersion: 1, credential: "cmk_rotated", machineId, daemonVersion: readDaemonVersion(),
+ });
+ expect(mockRunPreparedDaemon).toHaveBeenCalledWith(expect.objectContaining({ machineId, machineKey: "cmk_rotated" }), expect.any(Object));
+ expect(stop).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(daemonDir, "daemon.replace.lock"))).toBe(false);
+ });
+
+ it("preserves a live daemon when its saved credential is missing", async () => {
+ const { machineId, daemonDir } = writeReconnectState();
+ fs.rmSync(path.join(baseDir, "daemons", `${machineId}.credential.json`));
+ const stop = vi.fn(async () => {});
+ const start = vi.fn(async () => {});
+
+ await expect(daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {
+ isProcessAlive: () => true, stopExactDaemonPid: stop, start,
+ })).rejects.toThrow("cannot safely reconnect a running daemon without its saved credential");
+
+ expect(stop).not.toHaveBeenCalled();
+ expect(start).not.toHaveBeenCalled();
+ expect(fetch).not.toHaveBeenCalled();
+ expect(JSON.parse(fs.readFileSync(path.join(daemonDir, "daemon.pid"), "utf8"))).toMatchObject({ ownerToken: "old-owner" });
+ expect(fs.existsSync(path.join(daemonDir, "daemon.replace.lock"))).toBe(false);
+ });
+
+ it("rejects a legacy credential belonging to another machine before reconnecting", async () => {
+ const { machineId } = writeReconnectState();
+ fs.writeFileSync(path.join(baseDir, "daemons", `${machineId}.credential.json`), JSON.stringify({
+ machineId: "cm_other_machine", credential: "cmk_other",
+ }));
+ const stop = vi.fn(async () => {});
+ await expect(daemonReconnect({ id: machineId, machineKey: "cmt_reconnect", baseDir }, {
+ isProcessAlive: () => true, stopExactDaemonPid: stop,
+ })).rejects.toThrow("daemon launch record machine mismatch");
+ expect(stop).not.toHaveBeenCalled();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("restores a legacy daemon with its credential and explicit endpoints after rejected activation", async () => {
+ const { machineId } = writeReconnectState();
+ const recordPath = path.join(baseDir, "daemons", `${machineId}.credential.json`);
+ fs.writeFileSync(recordPath, JSON.stringify({ credential: "cmk_old", machineId }));
+ vi.mocked(fetch).mockResolvedValue(new Response(JSON.stringify({
+ error: "token expired", sessionOutcome: "not_committed",
+ }), { status: 409 }));
+ mockRunPreparedDaemon.mockResolvedValue(undefined);
+ const stop = vi.fn(async () => {});
+
+ await expect(daemonReconnect({
+ id: machineId, machineKey: "cmt_reconnect", baseDir,
+ serverUrl: "http://custom", wsUrl: "ws://custom",
+ }, {
+ isProcessAlive: () => true, stopExactDaemonPid: stop,
+ start: (opts) => daemonStart({ ...opts, foreground: true }),
+ })).rejects.toThrow("token expired");
+
+ expect(fetch).toHaveBeenCalledOnce();
+ expect(stop).toHaveBeenCalledOnce();
+ expect(mockRunPreparedDaemon).toHaveBeenCalledWith(expect.objectContaining({
+ machineId, machineKey: "cmk_old", serverUrl: "http://custom", wsUrl: "ws://custom",
+ }), expect.any(Object));
+ expect(JSON.parse(fs.readFileSync(recordPath, "utf8"))).toMatchObject({
+ schemaVersion: 1, credential: "cmk_old", daemonVersion: readDaemonVersion(),
+ });
+ });
+
it("uses production endpoints when first-pair URL overrides are absent", async () => {
await expect(daemonStart({
machineKey: "cmk_test",
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index 17730dff8..8d069aa2f 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -1161,7 +1161,10 @@ export async function daemonReconnect(
}
const machineId = validateMachineId(opts.id);
const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
- const launch = readDaemonLaunchRecord(baseDir, machineId);
+ const launch = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
+ if (launch && launch.machineId !== machineId) throw new Error("daemon launch record machine mismatch");
+ const serverUrl = opts.serverUrl ?? (launch && "serverUrl" in launch ? launch.serverUrl : undefined);
+ const wsUrl = opts.wsUrl ?? (launch && "wsUrl" in launch ? launch.wsUrl : undefined);
const pidPath = pidfilePathById(baseDir, machineId);
const before = readPidFile(pidPath);
if (
@@ -1181,6 +1184,9 @@ export async function daemonReconnect(
throw new Error("daemon ownership changed after reconnect lock acquisition");
}
if (owned && (deps.isProcessAlive ?? isProcessAlive)(owned.pid)) {
+ if (!launch) {
+ throw new Error(`cannot safely reconnect a running daemon without its saved credential; run daemon stop ${machineId}, then retry the reconnect command`);
+ }
await (deps.stopExactDaemonPid ?? stopExactDaemonPid)(owned.pid);
oldStopped = true;
removePidFileIfMatches(pidPath, owned);
@@ -1191,8 +1197,8 @@ export async function daemonReconnect(
try {
await (deps.start ?? daemonStart)({
machineKey: opts.machineKey,
- serverUrl: opts.serverUrl ?? launch.serverUrl,
- wsUrl: opts.wsUrl ?? launch.wsUrl,
+ serverUrl,
+ wsUrl,
baseDir,
resumeRequestId: requestId,
expectedMachineId: machineId,
@@ -1203,7 +1209,17 @@ export async function daemonReconnect(
|| (error instanceof PairingActivationError && error.sessionOutcome === "not_committed");
if (oldStopped && canRestoreOldEpoch) {
try {
- await (deps.resume ?? daemonResume)({ id: machineId, baseDir, requestId });
+ if (deps.resume || (launch && "daemonVersion" in launch && parseReleaseVersion(launch.daemonVersion))) {
+ await (deps.resume ?? daemonResume)({ id: machineId, baseDir, requestId });
+ } else {
+ await (deps.start ?? daemonStart)({
+ machineKey: launch!.credential,
+ serverUrl,
+ wsUrl,
+ baseDir,
+ resumeRequestId: requestId,
+ });
+ }
} catch (rollbackError) {
throw new AggregateError(
[error, rollbackError],