Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(machines): refresh daemon environment at the same version (#1152)

Gustavo Ye4a3344a66c8d
diff --git a/src/daemon/src/cli/daemonRefresh.real.test.ts b/src/daemon/src/cli/daemonRefresh.real.test.ts
new file mode 100644
index 000000000..d357ec028
--- /dev/null
+++ b/src/daemon/src/cli/daemonRefresh.real.test.ts
@@ -0,0 +1,130 @@
+import { expect, it } from "vitest";
+import { spawn } from "node:child_process";
+import { createServer } from "node:http";
+import { createRequire } from "node:module";
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { WebSocket, WebSocketServer } from "ws";
+import { readDaemonVersion } from "../version";
+
+it.runIf(process.platform !== "win32").each([100, 1000])("refreshes a real CLI runner and rolls back after a %dms startup receipt failure", async (receiptTimeoutMs) => {
+ const root = mkdtempSync(join(tmpdir(), "alook-refresh-real-"));
+ const machineId = "cm_refresh_real_1234";
+ const machineKey = "cmk_SYNTHETIC_REFRESH_TEST_ONLY";
+ const baseDir = join(root, "data");
+ const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
+ const cli = join(packageRoot, "src/cli/index.ts");
+ const loader = pathToFileURL(createRequire(import.meta.url).resolve("tsx")).href;
+ const shell = join(root, "shell");
+ const exportsFile = join(root, "exports");
+ const observationFile = join(root, "probe-observations");
+ const bin = join(root, "bin");
+ mkdirSync(bin);
+ mkdirSync(join(baseDir, "daemons"), { recursive: true });
+ writeFileSync(shell, `#!/bin/sh\n. '${exportsFile}'\nprintf '__ALOOK_ENV_V1__\\000'\nexec /usr/bin/env -0\n`, { mode: 0o700 });
+ const exportValue = (value: string) => writeFileSync(exportsFile, `export ALOOK_SYNTHETIC_REFRESH='${value}'\nexport PATH='${bin}:/usr/bin:/bin'\n`);
+ exportValue("v1");
+ writeFileSync(join(bin, "codex"), `#!/bin/sh\nprintf '%s|%s\\n' "$ALOOK_SYNTHETIC_REFRESH" "$ALOOK_OLD_ONLY" >> '${observationFile}'\necho 'codex-cli 0.70.0'\n`, { mode: 0o700 });
+ const wss = new WebSocketServer({ noServer: true });
+ const sockets: WebSocket[] = [];
+ const ready: Array<{ socket: WebSocket; frame: { daemonVersion: string; capabilities: string[] } }> = [];
+ const requests: string[] = [];
+ const server = createServer((request, response) => {
+ requests.push(request.url ?? "");
+ response.setHeader("content-type", "application/json");
+ response.end(JSON.stringify(request.url?.includes("/bots") ? { bots: [] } : { attempted: 0 }));
+ });
+ server.on("upgrade", (request, socket, head) => {
+ if (request.headers.authorization !== `Bearer ${machineKey}`) { socket.destroy(); return; }
+ wss.handleUpgrade(request, socket, head, (ws) => {
+ sockets.push(ws);
+ ws.on("message", (raw) => {
+ const frame = JSON.parse(String(raw));
+ if (frame.type === "ready") ready.push({ socket: ws, frame });
+ });
+ });
+ });
+ const cliRun = async (args: string[]) => {
+ const child = spawn(process.execPath, ["--import", loader, cli, "daemon", ...args], {
+ cwd: packageRoot, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env,
+ HOME: root, SHELL: shell, PATH: `${bin}:/usr/bin:/bin`, ALOOK_SYNTHETIC_REFRESH: "v1", ALOOK_OLD_ONLY: "stale", ALOOK_LOG_LEVEL: "warn" },
+ });
+ let output = "";
+ child.stdout.on("data", (data) => { output += String(data); });
+ child.stderr.on("data", (data) => { output += String(data); });
+ return await new Promise<{ code: number | null; output: string }>((resolve, reject) => {
+ child.once("error", reject);
+ child.once("exit", (code) => resolve({ code, output }));
+ });
+ };
+ const waitFor = async (check: () => boolean) => {
+ const deadline = Date.now() + 20000;
+ while (!check()) {
+ if (Date.now() > deadline) throw new Error("isolated refresh fixture timed out");
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ };
+ const pidfile = join(baseDir, "daemons", machineId, "daemon.pid");
+ const recordPath = join(baseDir, "daemons", `${machineId}.credential.json`);
+ const owner = () => JSON.parse(readFileSync(pidfile, "utf8")) as { pid: number; machineId: string };
+ let started = false;
+ try {
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ writeFileSync(recordPath, JSON.stringify({ schemaVersion: 1, credential: machineKey, machineId,
+ serverUrl: origin, wsUrl: origin.replace("http:", "ws:"), daemonVersion: readDaemonVersion() }), { mode: 0o600 });
+ const result = await cliRun(["start", "--machine-key", machineKey, "--server-url", origin,
+ "--ws-url", origin.replace("http:", "ws:"), "--base-dir", baseDir]);
+ expect(result.code, result.output).toBe(0);
+ started = true;
+ await waitFor(() => ready.length > 0);
+ const first = owner();
+ const originalRecord = readFileSync(recordPath, "utf8");
+ expect(ready[0].frame.capabilities).toContain("machineRefresh");
+ exportValue("v2");
+ const command = JSON.stringify({ type: "machine:refresh" });
+ sockets[0].send(command);
+ sockets[0].send(command);
+ await waitFor(() => sockets.length === 2 && ready.some((entry) => entry.socket === sockets[1]));
+ const second = owner();
+ expect(second.machineId).toBe(machineId);
+ expect(second.pid).not.toBe(first.pid);
+ expect(sockets).toHaveLength(2);
+ expect(ready.find((entry) => entry.socket === sockets[1])!.frame.daemonVersion).toBe(ready[0].frame.daemonVersion);
+ expect(readFileSync(recordPath, "utf8")).toBe(originalRecord);
+ expect(readFileSync(observationFile, "utf8").split("\n")).toContain("v2|");
+ expect(readFileSync(observationFile, "utf8").split("\n")).toContain("v1|stale");
+ expect(requests.some((url) => /activate|pair|identity/.test(url))).toBe(false);
+ writeFileSync(shell, "#!/bin/sh\necho PRIVATE_ENVIRONMENT_VALUE >&2\nexit 1\n", { mode: 0o700 });
+ sockets[1].send(command);
+ await waitFor(() => readFileSync(join(baseDir, "daemons", machineId, "daemon.log"), "utf8").includes("machine refresh failed"));
+ expect(owner().pid).toBe(second.pid);
+ expect(sockets[1].readyState).toBe(WebSocket.OPEN);
+ expect(readFileSync(join(baseDir, "daemons", machineId, "daemon.log"), "utf8")).not.toContain("PRIVATE_ENVIRONMENT_VALUE");
+ writeFileSync(shell, `#!/bin/sh\n. '${exportsFile}'\nprintf '__ALOOK_ENV_V1__\\000'\nexec /usr/bin/env -0\n`, { mode: 0o700 });
+ exportValue("v3");
+ writeFileSync(exportsFile, readFileSync(exportsFile, "utf8") + `export ALOOK_DAEMON_TEST_SKIP_READY=1\nexport ALOOK_DAEMON_TEST_RECEIPT_TIMEOUT_MS=${receiptTimeoutMs}\n`);
+ const probeOffset = readFileSync(observationFile, "utf8").trim().split("\n").length;
+ sockets[1].send(command);
+ await waitFor(() => {
+ if (existsSync(join(baseDir, "daemons", machineId, "daemon.replace.lock")) || !existsSync(pidfile)) return false;
+ const probes = readFileSync(observationFile, "utf8").trim().split("\n").slice(probeOffset);
+ return owner().pid !== second.pid && probes.includes("v3|") && probes.at(-1) === "v2|"
+ && ready.some((entry) => entry.socket !== sockets[1] && entry.socket.readyState === WebSocket.OPEN);
+ });
+ expect(owner().pid).not.toBe(second.pid);
+ expect(owner().machineId).toBe(machineId);
+ expect(readFileSync(recordPath, "utf8")).toBe(originalRecord);
+ expect(readFileSync(observationFile, "utf8").trim().split("\n").at(-1)).toBe("v2|");
+
+ } finally {
+ if (started && existsSync(pidfile)) await cliRun(["stop", machineId, "--base-dir", baseDir]);
+ for (const socket of sockets) socket.terminate();
+ await new Promise<void>((resolve) => wss.close(() => resolve()));
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ rmSync(root, { recursive: true, force: true });
+ }
+}, 60000);
diff --git a/src/daemon/src/cli/daemonRefresh.replacement.test.ts b/src/daemon/src/cli/daemonRefresh.replacement.test.ts
new file mode 100644
index 000000000..d9e8f36f6
--- /dev/null
+++ b/src/daemon/src/cli/daemonRefresh.replacement.test.ts
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { readDaemonVersion } from "../version";
+
+const boundary = vi.hoisted(() => ({
+ readPidFile: vi.fn(), readDaemonLaunchRecord: vi.fn(), acquireDaemonReplacementLock: vi.fn(),
+ stopExactDaemonPid: vi.fn(), daemonResume: vi.fn(), removeReplacementLockIfMatches: vi.fn(),
+}));
+vi.mock("./daemonStart.js", () => ({
+ ...boundary, pidfilePathById: () => "fixture.pid", daemonProcessArguments: () => [],
+}));
+import { daemonRefreshFromIpc, replaceDaemonForRefresh } from "./daemonRefresh";
+
+const requestId = "26aac14d-dfd6-4e96-821c-ebf538316f79";
+const context = { baseDir: "/fixture", machineId: "cm_fixture", pid: 424242,
+ startedAt: "2026-11-02T00:00:00Z", ownerToken: "fixture-owner" };
+const savedEnvironment = { ...process.env };
+const ipcProperties = new Map(["send", "connected", "disconnect"].map((key) => [key, Object.getOwnPropertyDescriptor(process, key)]));
+let priorMessageListeners: Set<ReturnType<typeof process.listeners>[number]>;
+const input = () => ({ context, requestId, priorEnvironment: { ...savedEnvironment, ALOOK_REFRESH_FIXTURE: "prior" } });
+
+beforeEach(() => {
+ priorMessageListeners = new Set(process.listeners("message"));
+ vi.resetAllMocks();
+ boundary.readPidFile.mockReturnValue(context);
+ boundary.readDaemonLaunchRecord.mockReturnValue({ daemonVersion: readDaemonVersion() });
+ boundary.acquireDaemonReplacementLock.mockReturnValue({ path: "fixture.lock", lock: { requestId } });
+ boundary.stopExactDaemonPid.mockResolvedValue(undefined);
+ boundary.daemonResume.mockResolvedValue(undefined);
+});
+afterEach(() => {
+ vi.useRealTimers();
+ for (const key of Object.keys(process.env)) delete process.env[key];
+ Object.assign(process.env, savedEnvironment);
+ for (const [key, descriptor] of ipcProperties) {
+ if (descriptor) Object.defineProperty(process, key, descriptor);
+ else Reflect.deleteProperty(process, key);
+ }
+ for (const listener of process.listeners("message")) if (!priorMessageListeners.has(listener)) process.removeListener("message", listener);
+});
+
+describe("Refresh replacement authority", () => {
+ it.each(["version", "owner", "after-lock"])("does not stop a daemon after %s authority changes", async (change) => {
+ if (change === "version") boundary.readDaemonLaunchRecord.mockReturnValue({ daemonVersion: "0.0.1" });
+ if (change === "owner") boundary.readPidFile.mockReturnValue({ ...context, ownerToken: "successor" });
+ if (change === "after-lock") boundary.readPidFile.mockReturnValueOnce(context).mockReturnValue({ ...context, pid: 424243 });
+ await expect(replaceDaemonForRefresh(input())).rejects.toThrow("ownership_changed");
+ expect(boundary.stopExactDaemonPid).not.toHaveBeenCalled();
+ expect(boundary.daemonResume).not.toHaveBeenCalled();
+ expect(boundary.removeReplacementLockIfMatches).toHaveBeenCalledTimes(change === "after-lock" ? 1 : 0);
+ });
+
+ it("stops only the verified PID, resumes once and releases replacement ownership", async () => {
+ await replaceDaemonForRefresh(input());
+ expect(boundary.stopExactDaemonPid).toHaveBeenCalledExactlyOnceWith(context.pid);
+ expect(boundary.daemonResume).toHaveBeenCalledExactlyOnceWith({ id: context.machineId,
+ baseDir: context.baseDir, requestId });
+ expect(boundary.removeReplacementLockIfMatches).toHaveBeenCalledExactlyOnceWith("fixture.lock", { requestId });
+ });
+
+ it("rolls back once with the previous environment after startup failure", async () => {
+ const environments: Array<NodeJS.ProcessEnv> = [];
+ process.env.ALOOK_REFRESH_FIXTURE = "fresh";
+ process.env.ALOOK_REFRESH_FRESH_ONLY = "fresh-only";
+ boundary.daemonResume.mockImplementation(async () => {
+ environments.push({ ...process.env });
+ if (environments.length === 1) throw new Error("startup failed");
+ });
+ await replaceDaemonForRefresh(input());
+ expect(environments[0].ALOOK_REFRESH_FIXTURE).toBe("fresh");
+ expect(environments[1].ALOOK_REFRESH_FIXTURE).toBe("prior");
+ expect(environments[1].ALOOK_REFRESH_FRESH_ONLY).toBeUndefined();
+ expect(boundary.daemonResume).toHaveBeenCalledTimes(2);
+ expect(boundary.removeReplacementLockIfMatches).toHaveBeenCalledOnce();
+ });
+});
+
+function parentIpc() {
+ const send = vi.fn((_message, callback) => callback());
+ const disconnect = vi.fn(() => Object.defineProperty(process, "connected", { value: false, configurable: true }));
+ Object.defineProperties(process, { send: { value: send, configurable: true },
+ connected: { value: true, configurable: true }, disconnect: { value: disconnect, configurable: true } });
+ return { send, disconnect };
+}
+
+function deliver(message: unknown): void {
+ const listener = process.listeners("message").find((candidate) => !priorMessageListeners.has(candidate));
+ if (!listener) throw new Error("missing fixture IPC listener");
+ listener.call(process, message);
+}
+
+describe("Refresh helper IPC", () => {
+ it("requires parent IPC and bounds absent input", async () => {
+ Object.defineProperty(process, "connected", { value: false, configurable: true });
+ await expect(daemonRefreshFromIpc()).rejects.toThrow("parent IPC");
+ parentIpc();
+ vi.useFakeTimers();
+ const pending = expect(daemonRefreshFromIpc()).rejects.toThrow("input unavailable");
+ await vi.advanceTimersByTimeAsync(5000);
+ await pending;
+ expect(boundary.stopExactDaemonPid).not.toHaveBeenCalled();
+ });
+
+ it.each([null, {}, { ...input(), context: { ...context, pid: 0 } }])("rejects malformed local input before replacement", async (message) => {
+ parentIpc();
+ const pending = expect(daemonRefreshFromIpc()).rejects.toThrow("invalid refresh input");
+ deliver(message);
+ await pending;
+ expect(boundary.stopExactDaemonPid).not.toHaveBeenCalled();
+ });
+
+ it.each(["success", "ownership_changed", "restart_failed"])("disconnects after %s and preserves failure status", async (outcome) => {
+ const ipc = parentIpc();
+ if (outcome === "ownership_changed") boundary.readPidFile.mockReturnValue(undefined);
+ if (outcome === "restart_failed") boundary.daemonResume.mockRejectedValue(new Error("PRIVATE_STARTUP_DETAIL"));
+ const operation = daemonRefreshFromIpc();
+ const pending = outcome === "success" ? operation : expect(operation).rejects.toThrow();
+ deliver(input());
+ await pending;
+ expect(ipc.disconnect).toHaveBeenCalledOnce();
+ expect(ipc.send).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/daemon/src/cli/daemonRefresh.test.ts b/src/daemon/src/cli/daemonRefresh.test.ts
new file mode 100644
index 000000000..146e4f7b7
--- /dev/null
+++ b/src/daemon/src/cli/daemonRefresh.test.ts
@@ -0,0 +1,89 @@
+import { EventEmitter } from "node:events";
+import type { ChildProcess } from "node:child_process";
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createDaemonRefreshHandler } from "./daemonRefresh";
+
+const directories: string[] = [];
+afterEach(() => { vi.unstubAllEnvs(); for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+function context() {
+ const baseDir = mkdtempSync(join(tmpdir(), "alook-refresh-unit-"));
+ directories.push(baseDir);
+ const value = { baseDir, machineId: "cm_refresh_unit", pid: 424242, startedAt: "2026-11-02T00:00:00Z", ownerToken: "owner-fixture" };
+ mkdirSync(join(baseDir, "daemons", value.machineId), { recursive: true });
+ writeFileSync(join(baseDir, "daemons", value.machineId, "daemon.pid"), JSON.stringify(value));
+ return value;
+}
+function helper() {
+ return Object.assign(new EventEmitter(), { send: vi.fn(), unref: vi.fn(), channel: { unref: vi.fn() } }) as unknown as ChildProcess;
+}
+
+describe("Refresh preparation", () => {
+ it("keeps the old daemon on environment failure and permits a later retry", async () => {
+ const spawnProcess = vi.fn();
+ const readEnvironment = vi.fn(async () => { throw new Error("environment failed"); });
+ const handler = createDaemonRefreshHandler(context(), { spawnProcess, readEnvironment });
+ for (let attempt = 0; attempt < 2; attempt++) await expect(handler()).rejects.toThrow("environment failed");
+ expect(readEnvironment).toHaveBeenCalledTimes(2);
+ expect(spawnProcess).not.toHaveBeenCalled();
+ });
+
+ it("coalesces commands while environment preparation is active", async () => {
+ let fail!: (error: Error) => void;
+ const readEnvironment = vi.fn(() => new Promise<NodeJS.ProcessEnv>((_resolve, reject) => { fail = reject; }));
+ const handler = createDaemonRefreshHandler(context(), { readEnvironment });
+ const pending = expect(handler()).rejects.toThrow("failed");
+ await handler();
+ expect(readEnvironment).toHaveBeenCalledOnce();
+ fail(new Error("failed"));
+ await pending;
+ });
+
+ it.each(["before", "after"])("checks ownership %s environment capture", async (stage) => {
+ const owner = context();
+ const replaceOwner = () => writeFileSync(join(owner.baseDir, "daemons", owner.machineId, "daemon.pid"), JSON.stringify({ ...owner, pid: 454545 }));
+ if (stage === "before") replaceOwner();
+ const spawnProcess = vi.fn();
+ const readEnvironment = vi.fn(async () => { replaceOwner(); return { PATH: "/bin" }; });
+ await expect(createDaemonRefreshHandler(owner, { spawnProcess, readEnvironment })()).rejects.toThrow("ownership_changed");
+ expect(readEnvironment).toHaveBeenCalledTimes(stage === "before" ? 0 : 1);
+ expect(spawnProcess).not.toHaveBeenCalled();
+ });
+
+ it("launches the current executable and sends correlation and prior environment only over local IPC", async () => {
+ const child = helper();
+ const spawnProcess = vi.fn(() => child);
+ vi.stubEnv("ALOOK_DAEMON_PACKAGE_WRAPPER", "1");
+ const handler = createDaemonRefreshHandler(context(), { spawnProcess: spawnProcess as never,
+ readEnvironment: async () => ({ HOME: "/tmp", PATH: "/bin", ALOOK_SENTINEL: "new-value" }) });
+ const pending = handler();
+ await vi.waitFor(() => expect(spawnProcess).toHaveBeenCalledOnce());
+ const [file, args, options] = spawnProcess.mock.calls[0] as unknown as [string, string[], { env: NodeJS.ProcessEnv }];
+ expect(file).toBe(process.execPath);
+ expect(args).toContain("refresh-run");
+ expect(args.some((arg) => /^(?:npm|npx|--package=|cmk_)|@latest/.test(arg))).toBe(false);
+ expect(options.env).toMatchObject({ ALOOK_SENTINEL: "new-value", ALOOK_DAEMON_PACKAGE_WRAPPER: "1", NODE_ENV: "test" });
+ expect(child.send).toHaveBeenCalledWith(expect.objectContaining({ requestId: expect.stringMatching(/^[\da-f-]{36}$/), priorEnvironment: expect.any(Object) }), expect.any(Function));
+ await handler();
+ expect(spawnProcess).toHaveBeenCalledOnce();
+ child.emit("exit", 0);
+ await pending;
+ });
+
+ it.each(["spawn", "send", "error", "exit"])("releases preparation after helper %s failure", async (stage) => {
+ const child = helper();
+ child.send = vi.fn((_message, callback) => { if (stage === "send") callback(new Error("send failed")); }) as never;
+ const spawnProcess = vi.fn(() => { if (stage === "spawn") throw new Error("spawn failed"); return child; });
+ const handler = createDaemonRefreshHandler(context(), { spawnProcess: spawnProcess as never,
+ readEnvironment: async () => ({ HOME: "/tmp", PATH: "/bin" }) });
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const pending = expect(handler()).rejects.toThrow();
+ await vi.waitFor(() => expect(spawnProcess).toHaveBeenCalledTimes(attempt + 1));
+ if (stage === "error") child.emit("error", new Error("helper failed"));
+ if (stage === "exit") child.emit("exit", 1);
+ await pending;
+ }
+ });
+});
diff --git a/src/daemon/src/cli/daemonRefresh.ts b/src/daemon/src/cli/daemonRefresh.ts
new file mode 100644
index 000000000..cbfa119e8
--- /dev/null
+++ b/src/daemon/src/cli/daemonRefresh.ts
@@ -0,0 +1,100 @@
+import { spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { readDaemonVersion } from "../version.js";
+import { readShellEnvironment } from "./shellEnvironment.js";
+import {
+ acquireDaemonReplacementLock, daemonProcessArguments, daemonResume, pidfilePathById,
+ readDaemonLaunchRecord, readPidFile, removeReplacementLockIfMatches, stopExactDaemonPid,
+} from "./daemonStart.js";
+import type { DaemonSelfUpdateContext } from "./daemonUpdate.js";
+
+type RefreshContext = DaemonSelfUpdateContext;
+
+function ownsDaemon(context: RefreshContext): boolean {
+ const current = readPidFile(pidfilePathById(context.baseDir, context.machineId));
+ return current?.pid === context.pid && current.machineId === context.machineId
+ && current.startedAt === context.startedAt && current.ownerToken === context.ownerToken;
+}
+
+export function createDaemonRefreshHandler(context: RefreshContext, options: {
+ readEnvironment?: typeof readShellEnvironment;
+ spawnProcess?: typeof spawn;
+} = {}): () => Promise<void> {
+ let active = false;
+ return async () => {
+ if (active) return;
+ if (!ownsDaemon(context)) throw new Error("ownership_changed");
+ active = true;
+ try {
+ const environment = await (options.readEnvironment ?? readShellEnvironment)();
+ if (!ownsDaemon(context)) throw new Error("ownership_changed");
+ const priorEnvironment = { ...process.env };
+ if (process.env.ALOOK_DAEMON_PACKAGE_WRAPPER) environment.ALOOK_DAEMON_PACKAGE_WRAPPER = process.env.ALOOK_DAEMON_PACKAGE_WRAPPER;
+ if (process.env.NODE_ENV === "test") {
+ for (const [key, value] of Object.entries(process.env)) {
+ if (key === "NODE_ENV" || key.startsWith("ALOOK_DAEMON_TEST_")) environment[key] = value;
+ }
+ }
+ const helper = (options.spawnProcess ?? spawn)(process.execPath, daemonProcessArguments("refresh-run"), {
+ env: environment, cwd: process.cwd(), detached: true, windowsHide: true,
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
+ });
+ await new Promise<void>((resolve, reject) => {
+ helper.once("error", reject);
+ helper.once("exit", (code) => code === 0 ? resolve() : reject(new Error("restart_failed")));
+ helper.send!({ context, requestId: randomUUID(), priorEnvironment }, (error) => { if (error) reject(error); });
+ helper.unref();
+ helper.channel?.unref();
+ });
+ } finally { active = false; }
+ };
+}
+
+export async function replaceDaemonForRefresh(input: {
+ context: RefreshContext;
+ requestId: string;
+ priorEnvironment: NodeJS.ProcessEnv;
+}): Promise<void> {
+ const { context, requestId } = input;
+ const launch = readDaemonLaunchRecord(context.baseDir, context.machineId);
+ if (launch.daemonVersion !== readDaemonVersion() || !ownsDaemon(context)) throw new Error("ownership_changed");
+ const lock = acquireDaemonReplacementLock({ baseDir: context.baseDir, machineId: context.machineId, requestId });
+ try {
+ if (!ownsDaemon(context)) throw new Error("ownership_changed");
+ await stopExactDaemonPid(context.pid);
+ try {
+ await daemonResume({ id: context.machineId, baseDir: context.baseDir, requestId });
+ } catch {
+ for (const key of Object.keys(process.env)) delete process.env[key];
+ Object.assign(process.env, input.priorEnvironment);
+ await daemonResume({ id: context.machineId, baseDir: context.baseDir, requestId });
+ }
+ } finally { removeReplacementLockIfMatches(lock.path, lock.lock); }
+}
+
+export async function daemonRefreshFromIpc(): Promise<void> {
+ if (!process.send || !process.connected) throw new Error("refresh helper requires parent IPC");
+ try {
+ const input = await new Promise<Parameters<typeof replaceDaemonForRefresh>[0]>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ process.removeListener("message", receive);
+ reject(new Error("refresh helper input unavailable"));
+ }, 5000);
+ function receive(message: unknown): void {
+ clearTimeout(timeout);
+ if (!message || typeof message !== "object") { reject(new Error("invalid refresh input")); return; }
+ const value = message as Parameters<typeof replaceDaemonForRefresh>[0];
+ if (typeof value.requestId !== "string" || !/^[A-Za-z0-9_-]{16,128}$/.test(value.requestId) || !value.context
+ || !Number.isSafeInteger(value.context.pid) || value.context.pid <= 0
+ || typeof value.context.machineId !== "string" || typeof value.context.baseDir !== "string"
+ || typeof value.context.startedAt !== "string" || typeof value.context.ownerToken !== "string"
+ || !value.priorEnvironment || typeof value.priorEnvironment !== "object") {
+ reject(new Error("invalid refresh input")); return;
+ }
+ resolve(value);
+ }
+ process.once("message", receive);
+ });
+ await replaceDaemonForRefresh(input);
+ } finally { if (process.connected) process.disconnect(); }
+}
diff --git a/src/daemon/src/cli/daemonRunner.ts b/src/daemon/src/cli/daemonRunner.ts
index de6932cf0..8eb8ee78b 100644
--- a/src/daemon/src/cli/daemonRunner.ts
+++ b/src/daemon/src/cli/daemonRunner.ts
@@ -1,5 +1,6 @@
import * as fs from "node:fs";
import * as path from "node:path";
+import { createDaemonRefreshHandler } from "./daemonRefresh.js";
import { WebSocket } from "ws";
import type { DiagnosticCollectCommand, DiagnosticReportFailureCode } from "@alook/shared";
import { createDaemon } from "../daemon/createDaemon.js";
@@ -361,6 +362,11 @@ export async function runPreparedDaemon(
daemonVersion: prepared.daemonVersion,
logger: log,
handleSelfUpdate,
+
+ handleRefresh: createDaemonRefreshHandler({
+ machineId: prepared.machineId, baseDir: prepared.baseDir, pid: process.pid,
+ startedAt: prepared.startedAt, ownerToken: prepared.ownerToken,
+ }),
onStopRequested: () => { void shutdown(0); },
handleDiagnosticCommand,
reportDiagnosticFailure,
diff --git a/src/daemon/src/cli/daemonStart.spawn.test.ts b/src/daemon/src/cli/daemonStart.spawn.test.ts
new file mode 100644
index 000000000..ef9d6add2
--- /dev/null
+++ b/src/daemon/src/cli/daemonStart.spawn.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { EventEmitter } from "node:events";
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { ChildProcess } from "node:child_process";
+
+const boundary = vi.hoisted(() => ({ spawn: vi.fn() }));
+vi.mock("node:child_process", async (original) => ({ ...await original<typeof import("node:child_process")>(), spawn: boundary.spawn }));
+vi.mock("../discovery.js", async (original) => ({ ...await original<typeof import("../discovery.js")>(),
+ detectRuntimes: vi.fn(async () => []), resolveAlookCliPathWithFallback: vi.fn(() => undefined) }));
+import { daemonResume } from "./daemonStart";
+import { readDaemonVersion } from "../version";
+
+let baseDir: string;
+beforeEach(() => { baseDir = mkdtempSync(join(tmpdir(), "alook-resume-spawn-")); boundary.spawn.mockReset(); });
+afterEach(() => { vi.unstubAllEnvs(); rmSync(baseDir, { recursive: true, force: true }); });
+
+it.each(["0", "1"])("resumes with the current executable and an owned startup receipt, wrapper=%s", async (wrapper) => {
+ const machineId = "cm_resume_spawn_fixture";
+ const machineDir = join(baseDir, "daemons", machineId);
+ mkdirSync(machineDir, { recursive: true });
+ const recordPath = join(baseDir, "daemons", `${machineId}.credential.json`);
+ const record = JSON.stringify({ schemaVersion: 1, credential: "cmk_resume_spawn_fixture", machineId,
+ serverUrl: "http://fixture.invalid", wsUrl: "ws://fixture.invalid", daemonVersion: readDaemonVersion() });
+ writeFileSync(recordPath, record, { mode: 0o600 });
+ const child = new EventEmitter() as ChildProcess;
+ Object.assign(child, { pid: 424242, exitCode: null, signalCode: null, unref: vi.fn(), kill: vi.fn(),
+ send: vi.fn((message, callback) => {
+ expect(message.type).toBe("daemon:prepared");
+ expect(JSON.parse(readFileSync(join(machineDir, "daemon.pid"), "utf8"))).toMatchObject({
+ pid: child.pid, machineId, ownerToken: message.prepared.ownerToken,
+ });
+ callback();
+ queueMicrotask(() => child.emit("message", { pid: child.pid, machineId, startedAt: message.prepared.startedAt, logPath: "fixture.log" }));
+ }) });
+ boundary.spawn.mockReturnValue(child);
+ vi.stubEnv("ALOOK_DAEMON_PACKAGE_WRAPPER", wrapper);
+ await daemonResume({ id: machineId, baseDir, requestId: "resume_spawn_fixture" });
+ expect(boundary.spawn).toHaveBeenCalledExactlyOnceWith(process.execPath,
+ [...process.execArgv, process.argv[1], ...(wrapper === "1" ? ["run"] : ["daemon", "run"])],
+ expect.objectContaining({ detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] }));
+ expect(readFileSync(recordPath, "utf8")).toBe(record);
+ expect(child.unref).toHaveBeenCalledOnce();
+ expect(child.kill).not.toHaveBeenCalled();
+});
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index 62f7ec715..481dec34d 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -1235,13 +1235,13 @@ export async function daemonReconnect(
}
}
-function runnerArguments(): string[] {
- const command = process.env.ALOOK_DAEMON_PACKAGE_WRAPPER === "1" ? ["run"] : ["daemon", "run"];
+export function daemonProcessArguments(action: "run" | "refresh-run"): string[] {
+ const command = process.env.ALOOK_DAEMON_PACKAGE_WRAPPER === "1" ? [action] : ["daemon", action];
return [...process.execArgv, process.argv[1]!, ...command];
}
function spawnBlockedRunner(): ChildProcess {
- return spawn(process.execPath, runnerArguments(), {
+ return spawn(process.execPath, daemonProcessArguments("run"), {
env: withoutNpmExecPackage(process.env),
detached: true,
stdio: ["ignore", "ignore", "ignore", "ipc"],
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 16e768552..6a6953f4b 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -6,6 +6,7 @@ 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 mockDaemonRefreshFromIpc = vi.hoisted(() => vi.fn(async () => {}));
const mockArmMessageReminder = vi.hoisted(() => vi.fn(async () => ({ armed: true as const, dueAt: 123456 })));
vi.mock("./daemonStart", async (importOriginal) => ({
...await importOriginal<typeof import("./daemonStart")>(),
@@ -19,6 +20,10 @@ vi.mock("./messageReminderClient", async (importOriginal) => ({
...await importOriginal<typeof import("./messageReminderClient")>(),
armMessageReminderFromEnv: mockArmMessageReminder,
}));
+vi.mock("./daemonRefresh.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./daemonRefresh.js")>(),
+ daemonRefreshFromIpc: mockDaemonRefreshFromIpc,
+}));
import { main, setApiForTesting, decodeTextEscapes, type CliInputStream } from "./index";
import type { ServerApi } from "../server/contract";
import { MAX_SERVER_ICON_SIZE_BYTES } from "@alook/shared/constants/community";
@@ -84,6 +89,16 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
let cap: ReturnType<typeof captureStdout>;
+it("routes the hidden refresh helper command to its local IPC entry without an API call", async () => {
+ mockDaemonRefreshFromIpc.mockClear();
+ expect(await main(["daemon", "refresh-run"])).toBe(0);
+ expect(mockDaemonRefreshFromIpc).toHaveBeenCalledOnce();
+ expect(await main(["daemon", "refresh-run", "--help"])).toBe(1);
+ expect(await main(["daemon", "refresh-run", "--unexpected"])).toBe(1);
+ mockDaemonRefreshFromIpc.mockRejectedValueOnce(new Error("local helper failed"));
+ expect(await main(["daemon", "refresh-run"])).toBe(1);
+});
+
// Env `getApi`/`proxyServerApiFromEnv` reads to build a proxy-routed ServerApi
// when no API is injected. The daemon INJECTS these into every agent's process
// (credential-proxy handoff), so when an agent runs this suite from inside a
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index d730fd0cd..03301d0ab 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+import { daemonRefreshFromIpc } from "./daemonRefresh.js";
import { registerPlatformCommands } from "./platform.js";
import { registerUseCommands } from "./use.js";
/**
@@ -1199,6 +1200,12 @@ function buildProgram(stdin: CliInputStream): Command {
});
});
+ daemon
+ .command("refresh-run", { hidden: true })
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async () => { await daemonRefreshFromIpc(); });
+
daemon
.command("replace", { hidden: true })
.requiredOption("--id <machineId>")
@@ -1317,7 +1324,7 @@ export async function main(argv = process.argv.slice(2), io: CliIo = {}): Promis
// Public agent-facing commands keep their JSON-only result contract. The
// two hidden replacement primitives additionally need a process status so
// the parent helper can distinguish ready from bounded rollback failure.
- if (argv[0] === "daemon" && (argv[1] === "resume" || argv[1] === "replace")) {
+ if (argv[0] === "daemon" && (argv[1] === "resume" || argv[1] === "replace" || argv[1] === "refresh-run")) {
internalExitCode = 1;
}
}
diff --git a/src/daemon/src/cli/shellEnvironment.test.ts b/src/daemon/src/cli/shellEnvironment.test.ts
new file mode 100644
index 000000000..f1817edbc
--- /dev/null
+++ b/src/daemon/src/cli/shellEnvironment.test.ts
@@ -0,0 +1,169 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { EventEmitter } from "node:events";
+import { mkdtempSync, writeFileSync, rmSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { spawn } from "node:child_process";
+import { parseShellEnvironment, readShellEnvironment, shellEnvironmentCommand } from "./shellEnvironment";
+
+const directories: string[] = [];
+function fixture() {
+ const dir = mkdtempSync(join(tmpdir(), "alook-shell-env-"));
+ directories.push(dir);
+ return dir;
+}
+afterEach(() => { for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+describe("fresh local shell environment", () => {
+ for (const name of ["bash", "zsh", "csh", "tcsh"]) {
+ const shell = "/bin/" + name;
+ it.runIf(process.platform === "darwin" && existsSync(shell))(`loads native ${name} login and interactive startup configuration`, async () => {
+ const dir = fixture();
+ if (name === "bash") {
+ writeFileSync(join(dir, ".bash_profile"), "export ALOOK_LOGIN_PROFILE=loaded\n. \"$HOME/.bashrc\"\n");
+ writeFileSync(join(dir, ".bashrc"), "export ALOOK_INTERACTIVE_RC=loaded\n");
+ } else if (name === "zsh") {
+ writeFileSync(join(dir, ".zprofile"), "export ALOOK_LOGIN_PROFILE=loaded\n");
+ writeFileSync(join(dir, ".zshrc"), "export ALOOK_INTERACTIVE_RC=loaded\n");
+ } else {
+ writeFileSync(join(dir, ".login"), "setenv ALOOK_LOGIN_PROFILE loaded\n");
+ for (const rc of [".cshrc", ".tcshrc"]) writeFileSync(join(dir, rc), "setenv ALOOK_INTERACTIVE_RC loaded\n");
+ }
+ const fresh = await readShellEnvironment({ env: { ...process.env, HOME: dir, ZDOTDIR: dir, SHELL: shell, ALOOK_REMOVED_EXPORT: "stale" } });
+ expect(fresh.ALOOK_LOGIN_PROFILE).toBe("loaded");
+ expect(fresh.ALOOK_INTERACTIVE_RC).toBe("loaded");
+ expect(fresh.ALOOK_REMOVED_EXPORT).toBeUndefined();
+ });
+ }
+ it.runIf(process.platform !== "win32")("reads changed exports and literal multiline values while dropping deleted inherited exports", async () => {
+ const dir = fixture();
+ const shell = join(dir, "shell");
+ const config = join(dir, "exports");
+ writeFileSync(shell, `#!/bin/sh\n. '${config}'\nprintf 'startup banner\\n__ALOOK_ENV_V1__\\000'\nexec /usr/bin/env -0\n`, { mode: 0o700 });
+ writeFileSync(config, "export ALOOK_SYNTHETIC_REFRESH='first'\n");
+ const input = { ...process.env, HOME: dir, SHELL: shell, OLD_ONLY: "stale-private-value" };
+ expect((await readShellEnvironment({ env: input })).ALOOK_SYNTHETIC_REFRESH).toBe("first");
+ writeFileSync(config, "export ALOOK_SYNTHETIC_REFRESH='second\n你好=$literal'\n");
+ const fresh = await readShellEnvironment({ env: input });
+ expect(fresh.ALOOK_SYNTHETIC_REFRESH).toBe("second\n你好=$literal");
+ expect(fresh.OLD_ONLY).toBeUndefined();
+ expect(input.OLD_ONLY).toBe("stale-private-value");
+ });
+
+ it.runIf(process.platform !== "win32")("bounds a stalled shell and never returns raw output in the error", async () => {
+ const dir = fixture();
+ const shell = join(dir, "shell");
+ writeFileSync(shell, "#!/bin/sh\necho secret-environment-value\necho private-stderr >&2\nsleep 60\n", { mode: 0o700 });
+ const before = Date.now();
+ await expect(readShellEnvironment({ env: { HOME: dir, SHELL: shell }, timeoutMs: 100 }))
+ .rejects.toThrow(/^environment_unavailable$/);
+ expect(Date.now() - before).toBeLessThan(3000);
+ });
+
+ it("rejects unframed or malformed environments", () => {
+ for (const value of ["HOME=/tmp\0PATH=/bin\0", "__ALOOK_ENV_V1__\0bad\0", "__ALOOK_ENV_V1__\0HOME=/tmp\0"]) {
+ expect(() => parseShellEnvironment(Buffer.from(value), "darwin")).toThrow();
+ }
+ });
+
+ it("rejects malformed child output without exposing its contents", async () => {
+ const spawnProcess = (() => spawn(process.execPath, ["-e", "process.stdout.write('PRIVATE_BAD_FRAME')"],
+ { stdio: ["ignore", "pipe", "ignore"] })) as typeof spawn;
+ await expect(readShellEnvironment({ spawnProcess })).rejects.toThrow(/^environment_unavailable$/);
+ });
+
+ it("rejects a missing shell executable without exposing local paths", async () => {
+ const dir = fixture();
+ await expect(readShellEnvironment({ env: { SystemRoot: dir, USERPROFILE: dir, HOME: dir, SHELL: join(dir, "missing-shell") } }))
+ .rejects.toThrow(/^environment_unavailable$/);
+ });
+
+ it("rejects oversized output even when additional buffered chunks arrive after failure", async () => {
+ const child = new EventEmitter() as ReturnType<typeof spawn>;
+ Object.assign(child, { stdout: new EventEmitter() });
+ const pending = expect(readShellEnvironment({ spawnProcess: (() => child) as typeof spawn })).rejects.toThrow(/^environment_unavailable$/);
+ child.stdout!.emit("data", Buffer.alloc(1024 * 1024 + 1));
+ child.stdout!.emit("data", Buffer.from("buffered-after-failure"));
+ child.emit("close", null);
+ await pending;
+ });
+
+ it.runIf(process.platform !== "win32")("falls back to terminating only its owned child when group termination fails", async () => {
+ const kill = vi.spyOn(process, "kill").mockImplementation(() => { throw new Error("fixture group unavailable"); });
+ let child: ReturnType<typeof spawn> | undefined;
+ try {
+ const spawnProcess = (() => { child = spawn(process.execPath, ["-e", "setInterval(()=>{},1000)"],
+ { stdio: ["ignore", "pipe", "ignore"] }); return child; }) as typeof spawn;
+ await expect(readShellEnvironment({ spawnProcess, timeoutMs: 100 })).rejects.toThrow(/^environment_unavailable$/);
+ expect(kill).toHaveBeenCalledWith(-child!.pid!, "SIGKILL");
+ expect(child!.signalCode).toBe("SIGKILL");
+ } finally { kill.mockRestore(); child?.kill("SIGKILL"); }
+ });
+
+ it("bounds the Windows process-tree cleanup path against its own child", async () => {
+ let ownedChild: ReturnType<typeof spawn> | undefined;
+ const spawnProcess = (() => {
+ ownedChild = spawn(process.execPath, ["-e", "setInterval(()=>{},1000)"], { stdio: ["ignore", "pipe", "ignore"] });
+ return ownedChild;
+ }) as typeof spawn;
+ try {
+ await expect(readShellEnvironment({ platform: "win32", spawnProcess, timeoutMs: 100 })).rejects.toThrow(/^environment_unavailable$/);
+ expect(ownedChild).toBeDefined();
+ expect(ownedChild!.exitCode !== null || ownedChild!.signalCode !== null).toBe(true);
+ } finally { ownedChild?.kill("SIGKILL"); }
+ });
+
+ it.runIf(process.platform !== "win32")("fills a missing GUI shell from the local account", () => {
+ const command = shellEnvironmentCommand({ HOME: "/tmp", SHELL: "" }, process.platform);
+ expect(command.file.startsWith("/")).toBe(true);
+ expect(command.env.SHELL).toBe(command.file);
+ });
+
+ it("normalizes Windows names and rebuilds registry environment before loading profiles", () => {
+ const command = shellEnvironmentCommand({ SystemRoot: "C:\\Windows", USERPROFILE: "C:\\Users\\test", USERNAME: "test", USERDOMAIN: "local", SECRET_OLD: "private" }, "win32");
+ expect(command.file).toBe("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
+ expect(command.env).not.toHaveProperty("SECRET_OLD");
+ expect(command.env).toMatchObject({ USERNAME: "test", USERDOMAIN: "local" });
+ expect(command.args.join(" ")).toContain("GetEnvironmentVariables('User')");
+ expect(command.args.join(" ")).toContain("[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false)");
+ const fresh = parseShellEnvironment(Buffer.from('__ALOOK_ENV_V1__{"Path":"C:\\\\Windows","UserProfile":"C:\\\\Users\\\\test","Token":"line1\\nline2"}'), "win32");
+ expect(fresh.PATH).toBe("C:\\Windows");
+ expect(fresh.TOKEN).toBe("line1\nline2");
+ });
+
+ it.runIf(process.platform === "win32")("captures real PowerShell profile Unicode through UTF-8 and removes old exports", async () => {
+ const dir = fixture();
+ const profile = join(dir, "profile.ps1");
+ writeFileSync(profile, "\ufeff$env:ALOOK_REFRESH_UNICODE='你好\nline=$literal'\n$env:Path=(Join-Path $env:SystemRoot 'System32')+';'\nWrite-Output 'profile startup banner'\n");
+ const quotedProfile = "'" + profile.replaceAll("'", "''") + "'";
+ const quotedMissing = "'" + join(dir, "missing.ps1").replaceAll("'", "''") + "'";
+ let diagnose = false;
+ let failure = "unavailable";
+ let termination = "not closed";
+ const started = Date.now();
+ const spawnProcess = ((file, args, options) => {
+ const configured = [...args];
+ configured[configured.length - 1] = "$PROFILE=[pscustomobject]@{AllUsersAllHosts=" + quotedMissing + ";AllUsersCurrentHost=" + quotedMissing + ";CurrentUserAllHosts=" + quotedProfile + ";CurrentUserCurrentHost=" + quotedMissing + "}; " + configured.at(-1);
+ if (diagnose) configured[configured.length - 1] = "try { " + configured.at(-1) + " } catch { [Console]::Error.Write('ALOOK_QA_FAILURE='+$_.Exception.GetType().Name+':'+$_.CategoryInfo.Category+':'+$_.InvocationInfo.OffsetInLine); exit 1 }";
+ const child = spawn(file, configured, { ...options, stdio: ["ignore", "pipe", "pipe"] });
+ child.once("close", (code, signal) => { termination = `exit=${code}, signal=${signal}, elapsedMs=${Date.now() - started}`; });
+ child.stderr.on("data", (chunk: Buffer) => {
+ const match = chunk.toString("utf8").match(/ALOOK_QA_FAILURE=([A-Za-z]+:[A-Za-z]+:\d+)/);
+ if (match) failure = match[1];
+ });
+ return child;
+ }) as typeof spawn;
+ const capture = () => readShellEnvironment({ env: { ...process.env, ALOOK_REFRESH_OLD_FIXTURE: "old" }, spawnProcess, timeoutMs: 10000 });
+ const fresh = await capture().catch(async () => {
+ const primaryTermination = termination;
+ diagnose = true;
+ await capture().catch(() => undefined);
+ throw new Error(`PowerShell fixture failed (${primaryTermination}; diagnostic=${failure}; ${termination})`);
+ });
+ expect(fresh.ALOOK_REFRESH_UNICODE).toBe("你好\nline=$literal");
+ expect(fresh.ALOOK_REFRESH_OLD_FIXTURE).toBeUndefined();
+ expect(fresh.USERNAME).toBe(process.env.USERNAME);
+ expect(fresh.USERPROFILE).toBe(process.env.USERPROFILE);
+ expect(fresh.PATH).not.toMatch(/;$/);
+ }, 25000);
+});
diff --git a/src/daemon/src/cli/shellEnvironment.ts b/src/daemon/src/cli/shellEnvironment.ts
new file mode 100644
index 000000000..fccd47d9f
--- /dev/null
+++ b/src/daemon/src/cli/shellEnvironment.ts
@@ -0,0 +1,85 @@
+import windowsShellEnvironment from "./windows-shell-environment.json";
+import { spawn } from "node:child_process";
+import * as path from "node:path";
+import { userInfo } from "node:os";
+
+const MARKER = "__ALOOK_ENV_V1__";
+const MAX_BYTES = 1024 * 1024;
+const BASE_KEYS = ["HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "LC_CTYPE", "TZ", "TERM", "ZDOTDIR", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR", "DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "SSH_AUTH_SOCK", "SystemRoot", "WINDIR", "COMSPEC", "USERPROFILE", "USERNAME", "USERDOMAIN", "ALLUSERSPROFILE", "PUBLIC", "HOMEDRIVE", "HOMEPATH", "APPDATA", "LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)", "ProgramData"];
+
+export function shellEnvironmentCommand(env: NodeJS.ProcessEnv, platform: NodeJS.Platform) {
+ const baseline: NodeJS.ProcessEnv = {};
+ for (const [key, value] of Object.entries(env)) {
+ if (BASE_KEYS.some((allowed) => allowed.toLowerCase() === key.toLowerCase())) baseline[key] = value;
+ }
+ if (platform === "win32") {
+ const root = env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows";
+ baseline.Path = path.win32.join(root, "System32");
+ const script = windowsShellEnvironment.join("; ");
+ return { file: path.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], env: baseline };
+ }
+ baseline.PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
+ const shell = env.SHELL || userInfo().shell || "/bin/sh";
+ if (!path.isAbsolute(shell)) throw new Error("environment_unavailable");
+ baseline.SHELL = shell;
+ return { file: shell, args: ["-ic", `printf '${MARKER}\\000'; exec /usr/bin/env -0`], argv0: "-" + path.basename(shell), env: baseline };
+}
+
+export function parseShellEnvironment(stdout: Buffer, platform: NodeJS.Platform): NodeJS.ProcessEnv {
+ const marker = Buffer.from(MARKER + (platform === "win32" ? "" : "\0"));
+ const offset = stdout.lastIndexOf(marker);
+ if (offset < 0) throw new Error("environment_unavailable");
+ const data = stdout.subarray(offset + marker.length).toString("utf8");
+ const entries: Array<[string, unknown]> = platform === "win32"
+ ? Object.entries(JSON.parse(data))
+ : data.split("\0").filter(Boolean).map((entry) => {
+ const split = entry.indexOf("=");
+ if (split <= 0) throw new Error("environment_unavailable");
+ return [entry.slice(0, split), entry.slice(split + 1)];
+ });
+ const result: NodeJS.ProcessEnv = Object.create(null);
+ for (const [key, value] of entries) {
+ if (!key || /[=\0]/.test(key) || typeof value !== "string" || value.includes("\0")) throw new Error("environment_unavailable");
+ result[platform === "win32" ? key.toUpperCase() : key] = value;
+ }
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
+ if (!result.PATH || !result[platform === "win32" ? "USERPROFILE" : "HOME"]
+ || result.PATH.split(pathApi.delimiter).some((entry) => !pathApi.isAbsolute(entry.replace(/^"(.*)"$/, "$1")))) throw new Error("environment_unavailable");
+ return result;
+}
+
+export async function readShellEnvironment(options: { env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform; timeoutMs?: number; spawnProcess?: typeof spawn } = {}): Promise<NodeJS.ProcessEnv> {
+ const platform = options.platform ?? process.platform;
+ const command = shellEnvironmentCommand(options.env ?? process.env, platform);
+ return await new Promise((resolve, reject) => {
+ const child = (options.spawnProcess ?? spawn)(command.file, command.args, { env: command.env, argv0: command.argv0, detached: platform !== "win32", windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ let failed = false;
+ const fail = (): void => {
+ if (failed) return;
+ failed = true;
+ if (child.pid) {
+ if (platform === "win32") {
+ const killer = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
+ killer.on("error", () => child.kill());
+ } else {
+ try { process.kill(-child.pid, "SIGKILL"); } catch { child.kill("SIGKILL"); }
+ }
+ }
+ };
+ const timeout = setTimeout(fail, options.timeoutMs ?? 5000);
+ child.stdout.on("data", (data: Buffer) => {
+ bytes += data.length;
+ if (bytes > MAX_BYTES) fail();
+ else chunks.push(data);
+ });
+ child.once("error", () => { clearTimeout(timeout); reject(new Error("environment_unavailable")); });
+ child.once("close", (code) => {
+ clearTimeout(timeout);
+ if (failed || code !== 0) { reject(new Error("environment_unavailable")); return; }
+ try { resolve(parseShellEnvironment(Buffer.concat(chunks), platform)); }
+ catch { reject(new Error("environment_unavailable")); }
+ });
+ });
+}
diff --git a/src/daemon/src/cli/windows-shell-environment.json b/src/daemon/src/cli/windows-shell-environment.json
new file mode 100644
index 000000000..a93ac019a
--- /dev/null
+++ b/src/daemon/src/cli/windows-shell-environment.json
@@ -0,0 +1,18 @@
+[
+ "$ErrorActionPreference='Stop'",
+ "$login=@{}",
+ "foreach($k in @('USERNAME','USERDOMAIN','USERPROFILE','HOMEDRIVE','HOMEPATH','APPDATA','LOCALAPPDATA')){$v=[Environment]::GetEnvironmentVariable($k,'Process')",
+ "if($null -ne $v){$login[$k]=$v}}",
+ "$machine=[Environment]::GetEnvironmentVariables('Machine')",
+ "$user=[Environment]::GetEnvironmentVariables('User')",
+ "foreach($k in $machine.Keys){[Environment]::SetEnvironmentVariable($k,[string]$machine[$k],'Process')}",
+ "foreach($k in $user.Keys){if($k -ne 'Path'){[Environment]::SetEnvironmentVariable($k,[string]$user[$k],'Process')}}",
+ "foreach($k in $login.Keys){[Environment]::SetEnvironmentVariable($k,[string]$login[$k],'Process')}",
+ "$env:Path=[Environment]::ExpandEnvironmentVariables(([string]$machine['Path'])+';'+([string]$user['Path']))",
+ "foreach($p in @($PROFILE.AllUsersAllHosts,$PROFILE.AllUsersCurrentHost,$PROFILE.CurrentUserAllHosts,$PROFILE.CurrentUserCurrentHost)){if(Test-Path -LiteralPath $p){. $p}}",
+ "$env:Path=(($env:Path -split ';') | Where-Object {$_ -ne ''}) -join ';'",
+ "$e=@{}",
+ "Get-ChildItem Env: | ForEach-Object {$e[$_.Name]=$_.Value}",
+ "[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false)",
+ "[Console]::Out.Write('__ALOOK_ENV_V1__'+($e | ConvertTo-Json -Compress))"
+]
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 0a54192e4..f6eb47b7b 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -1517,6 +1517,25 @@ for await (const line of createInterface({ input: process.stdin })) {
await daemon.stop();
});
+ it.each(["success", "failure"] as const)("consumes machine:refresh before bot routing on %s", async (outcome) => {
+ const sockets: FakeSocket[] = [];
+ const routerEntry = spyOnRouterCommandEntry();
+ const handleRefresh = vi.fn(async () => { if (outcome === "failure") throw new Error("PRIVATE_REFRESH_DETAIL"); });
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ bots: [] })));
+ const daemon = await createDaemon({ machineKey: "cmk_refresh_fixture", serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x", webSocketFactory: factory(sockets), runtimeReport: [],
+ driverFor: () => fakeDriver, capabilities: [], handleRefresh,
+ } as Parameters<typeof createDaemon>[0]);
+ try {
+ sockets[0].emit("open");
+ sockets[0].emit("message", JSON.stringify({ type: "machine:refresh" }));
+ await vi.waitFor(() => expect(handleRefresh).toHaveBeenCalledExactlyOnceWith());
+ expect(routerEntry).not.toHaveBeenCalledWith(expect.objectContaining({ type: "machine:refresh" }));
+ expect(fakeDriver.start).not.toHaveBeenCalled();
+ expect(sockets[0].sent.join("")).not.toContain("PRIVATE_REFRESH_DETAIL");
+ } finally { await daemon.stop(); }
+ });
+
it("consumes machine:update before bot observers and AgentRouter", async () => {
const sockets: FakeSocket[] = [];
const routerEntry = spyOnRouterCommandEntry();
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 244476fe4..6a6e87768 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -328,6 +328,7 @@ export interface CreateDaemonOptions {
/** B2b interception seam; B2c supplies the local collector/uploader. */
handleDiagnosticCommand?: (command: DiagnosticCollectCommand) => void | Promise<void>;
/** Machine-level lifecycle command; consumed before bot observers/router. */
+ handleRefresh?: () => Promise<void>;
handleSelfUpdate?: () => void | Promise<void>;
onStopRequested?: () => void;
/** Fixed-code failure callback used when diagnostics is not available. */
@@ -1122,6 +1123,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
channel,
runtimeReport: opts.runtimeReport,
supportsMachineStop: typeof opts.onStopRequested === "function",
+ supportsMachineRefresh: typeof opts.handleRefresh === "function",
hostname: opts.hostname,
platform: opts.platform,
arch: opts.arch,
@@ -1190,6 +1192,11 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
})();
return WS_CONTROL_COMMAND_CONSUMED;
});
+ channel.onCommand((command) => {
+ if (command.type !== "machine:refresh") return;
+ void opts.handleRefresh?.().catch(() => { log.warn("machine refresh failed"); });
+ return WS_CONTROL_COMMAND_CONSUMED;
+ });
channel.onCommand(createSelfUpdateCommandListener(opts.handleSelfUpdate));
channel.onCommand(createMachineStopCommandListener(opts.onStopRequested));
// Diagnostics likewise claims its machine-level command before bot/router.
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index 3cb806a1f..b0ba29b6a 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -19,7 +19,7 @@
* server recovers this host's state after a dropped control connection.
*/
import type { HostCommand, HostControlChannel, HostReady, HostReadyRuntime, UnreadNotice, AgentSessionReport, SessionErrorFrame, AgentId, HostAgentActivity } from "../server/contract.js";
-import { PII_CAPABILITY, type ProviderQuotaSnapshot } from "@alook/shared";
+import { MACHINE_REFRESH_CAPABILITY, PII_CAPABILITY, type ProviderQuotaSnapshot } from "@alook/shared";
import { CONTROL_HEARTBEAT_CAPABILITY, MACHINE_STOP_CAPABILITY, RUNTIME_MODEL_DISCOVERY_CAPABILITY } from "../server/contract.js";
import { getDriver, type AgentBackend } from "../drivers/index.js";
import type { AgentProcessManager } from "./managerRuntime.js";
@@ -84,6 +84,7 @@ export interface AgentRouterOpts {
runtimeReport: HostReadyRuntime[];
discoverModels?: (runtimeId: string) => ReturnType<AgentBackend["discoverModels"]>;
supportsMachineStop?: boolean;
+ supportsMachineRefresh?: boolean;
hostname?: string;
platform?: string;
arch?: string;
@@ -252,7 +253,7 @@ export class AgentRouter {
: this.opts.timeZone;
return {
runtimeReport: [...this.runtimes.values()],
- capabilities: [...(this.opts.channel.reportPiiResult ? [PII_CAPABILITY] : []), CONTROL_HEARTBEAT_CAPABILITY, ...(this.opts.supportsMachineStop ? [MACHINE_STOP_CAPABILITY] : []), ...(this.opts.channel.reportRuntimeModels ? [RUNTIME_MODEL_DISCOVERY_CAPABILITY] : [])],
+ capabilities: [...(this.opts.supportsMachineRefresh ? [MACHINE_REFRESH_CAPABILITY] : []), ...(this.opts.channel.reportPiiResult ? [PII_CAPABILITY] : []), CONTROL_HEARTBEAT_CAPABILITY, ...(this.opts.supportsMachineStop ? [MACHINE_STOP_CAPABILITY] : []), ...(this.opts.channel.reportRuntimeModels ? [RUNTIME_MODEL_DISCOVERY_CAPABILITY] : [])],
runningAgents: [...this.running],
hostname: this.opts.hostname,
platform: this.opts.platform,
diff --git a/src/daemon/tsconfig.json b/src/daemon/tsconfig.json
index 2a9c68e26..b5e173c87 100644
--- a/src/daemon/tsconfig.json
+++ b/src/daemon/tsconfig.json
@@ -3,6 +3,7 @@
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
+ "resolveJsonModule": true,
"lib": ["ES2022"],
"types": ["node"],
"outDir": "dist",
diff --git a/src/desktop/src-tauri/src/commands.rs b/src/desktop/src-tauri/src/commands.rs
index f805b6297..650aa49fe 100644
--- a/src/desktop/src-tauri/src/commands.rs
+++ b/src/desktop/src-tauri/src/commands.rs
@@ -118,10 +118,10 @@ struct DaemonOutput {
}
#[cfg(desktop)]
-fn read_process_pipe<R: Read + Send + 'static>(mut pipe: R) -> std::thread::JoinHandle<Vec<u8>> {
+fn read_process_pipe<R: Read + Send + 'static>(pipe: R) -> std::thread::JoinHandle<Vec<u8>> {
std::thread::spawn(move || {
let mut bytes = Vec::new();
- let _ = pipe.read_to_end(&mut bytes);
+ let _ = pipe.take(1024 * 1024 + 1).read_to_end(&mut bytes);
bytes
})
}
@@ -202,21 +202,225 @@ fn parse_shell_path(stdout: &str) -> Option<String> {
}
#[cfg(desktop)]
-async fn resolve_path() -> String {
- let fallback = std::env::var("PATH").unwrap_or_default();
- let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
- let mut command = Command::new(shell);
- command.args(["-ilc", "printf '%s\\n' \"$PATH\""]);
- match run_process(
- command,
+const ENV_MARKER: &str = "__ALOOK_ENV_V1__";
+
+#[cfg(desktop)]
+fn parse_shell_environment(
+ stdout: &str,
+ is_windows: bool,
+) -> Result<Vec<(String, String)>, String> {
+ let invalid =
+ || "Could not read the shell environment. The daemon was not changed.".to_string();
+ if stdout.len() > 1024 * 1024 {
+ return Err(invalid());
+ }
+ let marker = if is_windows {
+ ENV_MARKER.to_string()
+ } else {
+ format!("{ENV_MARKER}\0")
+ };
+ let (_, data) = stdout.rsplit_once(&marker).ok_or_else(invalid)?;
+ let entries: Vec<(String, String)> = if is_windows {
+ let values: std::collections::BTreeMap<String, String> =
+ serde_json::from_str(data).map_err(|_| invalid())?;
+ values
+ .into_iter()
+ .map(|(key, value)| (key.to_uppercase(), value))
+ .collect()
+ } else {
+ data.split('\0')
+ .filter(|item| !item.is_empty())
+ .map(|item| {
+ item.split_once('=')
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .ok_or_else(invalid)
+ })
+ .collect::<Result<Vec<_>, _>>()?
+ };
+ if entries
+ .iter()
+ .any(|(key, value)| key.is_empty() || key.contains(['=', '\0']) || value.contains('\0'))
+ {
+ return Err(invalid());
+ }
+ let path = entries
+ .iter()
+ .find(|(key, _)| key == "PATH")
+ .map(|(_, value)| value.as_str());
+ let home_key = if is_windows { "USERPROFILE" } else { "HOME" };
+ if !entries
+ .iter()
+ .any(|(key, value)| key == home_key && !value.is_empty())
+ || path.and_then(parse_shell_path).is_none()
+ {
+ return Err(invalid());
+ }
+ Ok(entries)
+}
+
+#[cfg(desktop)]
+fn shell_environment_command_for(environment: Vec<(String, String)>, is_windows: bool) -> Command {
+ let allowed = [
+ "HOME",
+ "USER",
+ "LOGNAME",
+ "SHELL",
+ "TMPDIR",
+ "TMP",
+ "TEMP",
+ "LANG",
+ "LC_ALL",
+ "LC_CTYPE",
+ "TZ",
+ "TERM",
+ "ZDOTDIR",
+ "XDG_CONFIG_HOME",
+ "XDG_RUNTIME_DIR",
+ "DISPLAY",
+ "WAYLAND_DISPLAY",
+ "XAUTHORITY",
+ "DBUS_SESSION_BUS_ADDRESS",
+ "SSH_AUTH_SOCK",
+ "SYSTEMROOT",
+ "WINDIR",
+ "COMSPEC",
+ "USERPROFILE",
+ "USERNAME",
+ "USERDOMAIN",
+ "ALLUSERSPROFILE",
+ "PUBLIC",
+ "HOMEDRIVE",
+ "HOMEPATH",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "PROGRAMFILES",
+ "PROGRAMFILES(X86)",
+ "PROGRAMDATA",
+ ];
+ let baseline: Vec<_> = environment
+ .iter()
+ .cloned()
+ .filter(|(key, _)| allowed.contains(&key.to_uppercase().as_str()))
+ .collect();
+ let mut command;
+ if is_windows {
+ let root = environment
+ .iter()
+ .find(|(key, _)| key.eq_ignore_ascii_case("SystemRoot"))
+ .map(|(_, value)| value.clone())
+ .unwrap_or_else(|| r"C:\Windows".to_string());
+ command = Command::new(
+ PathBuf::from(&root).join("System32/WindowsPowerShell/v1.0/powershell.exe"),
+ );
+ command
+ .env_clear()
+ .envs(baseline)
+ .env("Path", PathBuf::from(root).join("System32"));
+ let lines: Vec<String> = serde_json::from_str(include_str!(
+ "../../../daemon/src/cli/windows-shell-environment.json"
+ ))
+ .expect("invalid bundled Windows shell script");
+ let script = lines.join("; ");
+ command.args([
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ script.as_str(),
+ ]);
+ } else {
+ let shell = environment
+ .iter()
+ .find(|(key, _)| key == "SHELL")
+ .map(|(_, value)| value.clone())
+ .unwrap_or_else(|| "/bin/sh".to_string());
+ command = Command::new(shell);
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ let name = PathBuf::from(command.get_program())
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .into_owned();
+ command.arg0(format!("-{name}"));
+ }
+ command
+ .env_clear()
+ .envs(baseline)
+ .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
+ command.args([
+ "-ic",
+ "printf '__ALOOK_ENV_V1__\\000'; exec /usr/bin/env -0",
+ ]);
+ }
+ command
+}
+
+#[cfg(desktop)]
+fn parse_configured_shell(stdout: &str, is_macos: bool) -> Option<String> {
+ let output = stdout.trim();
+ let shell = if is_macos {
+ output.strip_prefix("UserShell:")?.trim()
+ } else {
+ output.split(':').nth(6)?.trim()
+ };
+ (shell.lines().count() == 1 && PathBuf::from(shell).is_absolute()).then(|| shell.to_string())
+}
+
+#[cfg(desktop)]
+async fn configured_login_shell(environment: &[(String, String)]) -> Result<String, String> {
+ let failure = "Could not find this account's login shell.".to_string();
+ let user = environment
+ .iter()
+ .find(|(key, _)| key == "USER" || key == "LOGNAME")
+ .map(|(_, value)| value)
+ .ok_or_else(|| failure.clone())?;
+ let mut command = if cfg!(target_os = "macos") {
+ let mut command = Command::new("/usr/bin/dscl");
+ command.args([".", "-read", &format!("/Users/{user}"), "UserShell"]);
+ command
+ } else {
+ let mut command = Command::new("/usr/bin/getent");
+ command.args(["passwd", user]);
+ command
+ };
+ command.env_clear().envs(environment.iter().cloned());
+ let output = run_process(command, PATH_DISCOVERY_TIMEOUT, failure.clone())
+ .await
+ .map_err(|_| failure.clone())?;
+ if !output.success {
+ return Err(failure);
+ }
+ parse_configured_shell(&output.stdout, cfg!(target_os = "macos")).ok_or(failure)
+}
+
+#[cfg(desktop)]
+async fn resolve_environment() -> Result<Vec<(String, String)>, String> {
+ let failure = "Could not read the shell environment. The daemon was not changed.".to_string();
+ let mut environment: Vec<_> = std::env::vars().collect();
+ if !cfg!(windows)
+ && !environment
+ .iter()
+ .any(|(key, value)| key == "SHELL" && !value.is_empty())
+ {
+ let shell = configured_login_shell(&environment)
+ .await
+ .map_err(|_| failure.clone())?;
+ environment.retain(|(key, _)| key != "SHELL");
+ environment.push(("SHELL".to_string(), shell));
+ }
+ let output = run_process(
+ shell_environment_command_for(environment, cfg!(windows)),
PATH_DISCOVERY_TIMEOUT,
- "login shell PATH lookup timed out".to_string(),
+ failure.clone(),
)
.await
- {
- Ok(output) if output.success => parse_shell_path(&output.stdout).unwrap_or(fallback),
- _ => fallback,
+ .map_err(|_| failure.clone())?;
+ if !output.success {
+ return Err(failure);
}
+ parse_shell_environment(&output.stdout, cfg!(windows))
}
#[cfg(desktop)]
@@ -225,7 +429,7 @@ async fn run_daemon(extra_args: &[String]) -> Result<DaemonOutput, String> {
let args = daemon_argv(&cfg, extra_args);
let mut command = Command::new(executable(cfg.command));
- command.env("PATH", resolve_path().await);
+ command.env_clear().envs(resolve_environment().await?);
if let Some(cwd) = &cfg.cwd {
command.current_dir(cwd);
}
@@ -353,9 +557,12 @@ fn daemon_failure_message(stdout: &str, stderr: &str) -> String {
}
#[cfg(desktop)]
-async fn probe_runtime_command(command: &'static str, path: String) -> Result<String, String> {
+async fn probe_runtime_command(
+ command: &'static str,
+ environment: Vec<(String, String)>,
+) -> Result<String, String> {
let mut process = Command::new(executable(command));
- process.env("PATH", path).arg("--version");
+ process.env_clear().envs(environment).arg("--version");
let output = run_process(
process,
RUNTIME_PROBE_TIMEOUT,
@@ -745,10 +952,19 @@ pub fn close_splashscreen(app: AppHandle) {
#[cfg(desktop)]
#[tauri::command]
pub async fn daemon_runtime_capability() -> DaemonRuntimeCapability {
- let path = resolve_path().await;
+ let environment = match resolve_environment().await {
+ Ok(environment) => environment,
+ Err(reason) => {
+ return DaemonRuntimeCapability {
+ available: false,
+ reason: Some(reason),
+ node_version: None,
+ }
+ }
+ };
let (node, npm) = tokio::join!(
- probe_runtime_command("node", path.clone()),
- probe_runtime_command("npm", path),
+ probe_runtime_command("node", environment.clone()),
+ probe_runtime_command("npm", environment),
);
evaluate_runtime_capability(node, npm)
}
@@ -1358,6 +1574,148 @@ mod tests {
assert!(parse_shell_path("relative/bin").is_none());
}
+ #[cfg(unix)]
+ #[test]
+ fn shell_environment_retains_non_path_multiline_exports_without_inherited_noise() {
+ let parsed = parse_shell_environment("banner\n__ALOOK_ENV_V1__\0PATH=/usr/bin:/bin\0HOME=/tmp/test\0SYNTHETIC=line1\n你好=$literal\0", false).unwrap();
+ assert!(parsed.contains(&("SYNTHETIC".to_string(), "line1\n你好=$literal".to_string())));
+ assert!(parse_shell_environment("PATH=/usr/bin", false).is_err());
+ assert!(parse_shell_environment("__ALOOK_ENV_V1__\0PATH=/bin\0BAD\0", false).is_err());
+ }
+
+ #[test]
+ fn configured_login_shell_uses_directory_service_or_passwd_output() {
+ assert_eq!(
+ parse_configured_shell("UserShell: /bin/zsh\n", true).as_deref(),
+ Some("/bin/zsh")
+ );
+ assert_eq!(
+ parse_configured_shell("test:x:1000:1000:Test:/home/test:/bin/bash\n", false)
+ .as_deref(),
+ Some("/bin/bash")
+ );
+ assert!(parse_configured_shell("UserShell: relative", true).is_none());
+ assert!(parse_configured_shell("unexpected", false).is_none());
+ }
+
+ #[test]
+ fn windows_environment_capture_uses_utf8_after_loading_profiles() {
+ let command = shell_environment_command_for(
+ vec![
+ ("SystemRoot".into(), r"C:\Windows".into()),
+ ("PRIVATE_OLD".into(), "stale".into()),
+ ],
+ true,
+ );
+ let script = command.get_args().last().unwrap().to_str().unwrap();
+ assert!(
+ script.find("Test-Path -LiteralPath").unwrap()
+ < script
+ .find("[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false)")
+ .unwrap()
+ );
+ assert!(script.find("$machine.Keys").unwrap() < script.find("$login.Keys").unwrap());
+ assert!(
+ script.find("$login.Keys").unwrap() < script.find("Test-Path -LiteralPath").unwrap()
+ );
+ assert!(!command.get_envs().any(|(key, _)| key == "PRIVATE_OLD"));
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn native_login_shells_load_their_own_startup_configuration() {
+ for name in ["bash", "zsh", "csh", "tcsh"] {
+ let shell = PathBuf::from(format!("/bin/{name}"));
+ if !shell.exists() {
+ continue;
+ }
+ let root =
+ std::env::temp_dir().join(format!("alook-login-env-{}-{name}", std::process::id()));
+ std::fs::create_dir_all(&root).unwrap();
+ let files: Vec<(&str, &str)> = match name {
+ "bash" => vec![
+ (
+ ".bash_profile",
+ "export ALOOK_LOGIN_PROFILE=loaded\n. \"$HOME/.bashrc\"\n",
+ ),
+ (".bashrc", "export ALOOK_INTERACTIVE_RC=loaded\n"),
+ ],
+ "zsh" => vec![
+ (".zprofile", "export ALOOK_LOGIN_PROFILE=loaded\n"),
+ (".zshrc", "export ALOOK_INTERACTIVE_RC=loaded\n"),
+ ],
+ _ => vec![
+ (".login", "setenv ALOOK_LOGIN_PROFILE loaded\n"),
+ (".cshrc", "setenv ALOOK_INTERACTIVE_RC loaded\n"),
+ (".tcshrc", "setenv ALOOK_INTERACTIVE_RC loaded\n"),
+ ],
+ };
+ for (file, text) in files {
+ std::fs::write(root.join(file), text).unwrap();
+ }
+ let command = shell_environment_command_for(
+ vec![
+ ("SHELL".into(), shell.to_string_lossy().into_owned()),
+ ("HOME".into(), root.to_string_lossy().into_owned()),
+ ("ZDOTDIR".into(), root.to_string_lossy().into_owned()),
+ ("STALE_ONLY".into(), "old".into()),
+ ],
+ false,
+ );
+ let output =
+ run_process_with_timeout(command, Duration::from_secs(2), "timeout".into())
+ .unwrap();
+ assert!(output.success, "{name}");
+ let environment = parse_shell_environment(&output.stdout, false).unwrap();
+ assert!(
+ environment.contains(&("ALOOK_LOGIN_PROFILE".into(), "loaded".into())),
+ "{name}"
+ );
+ assert!(
+ environment.contains(&("ALOOK_INTERACTIVE_RC".into(), "loaded".into())),
+ "{name}"
+ );
+ assert!(!environment.iter().any(|(key, _)| key == "STALE_ONLY"));
+ std::fs::remove_dir_all(root).unwrap();
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn native_environment_capture_reaches_a_child_and_removes_stale_exports() {
+ use std::os::unix::fs::PermissionsExt;
+ let root = std::env::temp_dir().join(format!("alook-native-env-{}", std::process::id()));
+ std::fs::create_dir_all(&root).unwrap();
+ let shell = root.join("shell");
+ std::fs::write(&shell, "#!/bin/sh\nexport SYNTHETIC_FRESH='new value'\nprintf '__ALOOK_ENV_V1__\\000'\nexec /usr/bin/env -0\n").unwrap();
+ std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let command = shell_environment_command_for(
+ vec![
+ ("SHELL".to_string(), shell.to_string_lossy().to_string()),
+ ("HOME".to_string(), root.to_string_lossy().to_string()),
+ ("STALE_ONLY".to_string(), "old value".to_string()),
+ ],
+ false,
+ );
+ let output =
+ run_process_with_timeout(command, Duration::from_secs(2), "timeout".to_string())
+ .unwrap();
+ assert!(output.success);
+ let environment = parse_shell_environment(&output.stdout, false).unwrap();
+ assert!(!environment.iter().any(|(key, _)| key == "STALE_ONLY"));
+ let mut child = Command::new("/bin/sh");
+ child.env_clear().envs(environment).args([
+ "-c",
+ "test \"$SYNTHETIC_FRESH\" = 'new value' && test -z \"$STALE_ONLY\"",
+ ]);
+ assert!(
+ run_process_with_timeout(child, Duration::from_secs(2), "timeout".to_string())
+ .unwrap()
+ .success
+ );
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
#[cfg(unix)]
#[test]
fn bounded_process_kills_a_stalled_process_group_holding_output_pipes() {
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index ced0df53d..bedc2daed 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -1,3 +1,4 @@
+import { MachineRefreshCommandSchema } from "./machine-refresh-contract";
import { PiiCommandSchema, type PiiCommand, type PiiResultFrame } from "./pii-contract";
import type { PlatformMachineRequest, PlatformBotRequest } from "./community-platform";
/**
@@ -857,6 +858,7 @@ export type HostCommand =
* `agentRouter`.
*/
| { type: "machine:reset_all"; resets: Array<{ agentId: AgentId; config: RuntimeConfig; launchId: string }> }
+ | z.infer<typeof MachineRefreshCommandSchema>
| { type: "machine:update" }
| { type: "machine:stop" }
// ─── Bot lifecycle events (server → daemon) ────────────────────────────
@@ -1557,6 +1559,7 @@ export const HostCommandSchema = z.discriminatedUnion("type", [
}),
),
}),
+ MachineRefreshCommandSchema,
z.strictObject({
type: z.literal("machine:update"),
}),
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 3e1c16146..7c7591d75 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -851,3 +851,5 @@ export { CommunityInviteListItemSchema, CommunityInvitesReadSchema, type Communi
export { CommunityDmReadItemSchema, CommunityDmsReadSchema, parseCommunityDmsRead, type CommunityDmsRead } from "./community-dms";
export * from "./community-profile-reads"
+
+export * from "./machine-refresh-contract";
diff --git a/src/shared/src/machine-refresh-contract.test.ts b/src/shared/src/machine-refresh-contract.test.ts
new file mode 100644
index 000000000..46121c986
--- /dev/null
+++ b/src/shared/src/machine-refresh-contract.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+import { MachineRefreshCommandSchema } from "./machine-refresh-contract";
+import { HostCommandSchema } from "./community-cli-contract";
+
+describe("machine Refresh protocol", () => {
+ it("permits only the fixed command, never environment, executable or remote correlation", () => {
+ const command = { type: "machine:refresh" };
+ expect(HostCommandSchema.parse(command)).toEqual(command);
+ for (const field of [{ env: { SECRET: "private" } }, { command: "shell" }, { requestId: "arbitrary" }]) {
+ expect(MachineRefreshCommandSchema.safeParse({ ...command, ...field }).success).toBe(false);
+ }
+ });
+});
diff --git a/src/shared/src/machine-refresh-contract.ts b/src/shared/src/machine-refresh-contract.ts
new file mode 100644
index 000000000..bfdcfb4e4
--- /dev/null
+++ b/src/shared/src/machine-refresh-contract.ts
@@ -0,0 +1,4 @@
+import { z } from "zod";
+
+export const MACHINE_REFRESH_CAPABILITY = "machineRefresh";
+export const MachineRefreshCommandSchema = z.strictObject({ type: z.literal("machine:refresh") });
diff --git a/src/web/src/app/api/community/machines/[id]/refresh/route.test.ts b/src/web/src/app/api/community/machines/[id]/refresh/route.test.ts
new file mode 100644
index 000000000..41a318d24
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/refresh/route.test.ts
@@ -0,0 +1,71 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const getMachine = vi.fn()
+const pushRefresh = vi.fn()
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: { communityMachine: { getMachineByIdForUser: (...args: unknown[]) => getMachine(...args) } } }))
+vi.mock("@/lib/community/bot-push", () => ({ pushMachineRefresh: (...args: unknown[]) => pushRefresh(...args) }))
+vi.mock("@/lib/middleware/auth", () => ({
+ humanAuthPolicy: { resolve: async (request: NextRequest) => ({ context: { env: { DB: {} }, userId: "owner", email: "[email protected]" } }) },
+}))
+
+import { POST } from "./route"
+const request = () => new NextRequest("http://localhost/api/community/machines/m/refresh", { method: "POST" })
+const context = { params: Promise.resolve({ id: "m" }) }
+
+describe("POST /api/community/machines/[id]/refresh", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ getMachine.mockResolvedValue({ id: "m", userId: "owner", status: "online" })
+ pushRefresh.mockResolvedValue({ sent: 1, unsupported: 0, deliveryError: false })
+ })
+
+ it("requires an ID before any lookup or command", async () => {
+ expect((await POST(request(), { params: Promise.resolve({}) })).status).toBe(400)
+ expect(getMachine).not.toHaveBeenCalled()
+ expect(pushRefresh).not.toHaveBeenCalled()
+ })
+
+ it("scopes the lookup to the owner and does not send to missing or foreign machines", async () => {
+ getMachine.mockResolvedValue(null)
+ expect((await POST(request(), context)).status).toBe(404)
+ expect(getMachine).toHaveBeenCalledWith({}, "owner", "m")
+ expect(pushRefresh).not.toHaveBeenCalled()
+ })
+
+ it("does not send to an already offline machine", async () => {
+ getMachine.mockResolvedValue({ id: "m", status: "offline" })
+ expect((await POST(request(), context)).status).toBe(409)
+ expect(pushRefresh).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [{ sent: 0, unsupported: 0, deliveryError: false }, 409, "machine is offline"],
+ [{ sent: 0, unsupported: 1, deliveryError: false }, 409, "update this daemon before remote Refresh is available"],
+ [{ sent: 0, unsupported: 0, deliveryError: true }, 503, "could not deliver the daemon refresh command"],
+ ])("returns a truthful failure for %j", async (receipt, status, error) => {
+ pushRefresh.mockResolvedValue(receipt)
+ const response = await POST(request(), context)
+ expect(response.status).toBe(status)
+ expect(await response.json()).toEqual({ error })
+ })
+
+ it("returns only dispatch success and retains the machine object", async () => {
+ const machine = { id: "m", userId: "owner", status: "online" }
+ getMachine.mockResolvedValue(machine)
+ const response = await POST(request(), context)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ dispatched: true })
+ expect(machine).toEqual({ id: "m", userId: "owner", status: "online" })
+ expect(pushRefresh).toHaveBeenCalledWith({ DB: {} }, "m")
+ })
+ it("ignores supplied input and dispatches only the owner-scoped machine action", async () => {
+ const input = new NextRequest("http://localhost/api/community/machines/m/refresh", {
+ method: "POST", body: JSON.stringify({ env: { KEY: "private" }, command: "shell" }),
+ });
+ const response = await POST(input, context);
+ expect(await response.json()).toEqual({ dispatched: true });
+ expect(pushRefresh).toHaveBeenCalledExactlyOnceWith({ DB: {} }, "m");
+ });
+});
diff --git a/src/web/src/app/api/community/machines/[id]/refresh/route.ts b/src/web/src/app/api/community/machines/[id]/refresh/route.ts
new file mode 100644
index 000000000..a7345ee4f
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/refresh/route.ts
@@ -0,0 +1,20 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { queries } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { pushMachineRefresh } from "@/lib/community/bot-push"
+import { humanAuthPolicy } from "@/lib/middleware/auth"
+import { writeError, writeJSON } from "@/lib/middleware/helpers"
+
+export const POST = withAuth(humanAuthPolicy, async (_request, ctx) => {
+ const machineId = ctx.params?.id as string
+ if (!machineId) return writeError("machine id is required", 400)
+ const machine = await queries.communityMachine.getMachineByIdForUser(getDb(ctx.env.DB), ctx.userId, machineId)
+ if (!machine) return writeError("machine not found", 404)
+ if (machine.status !== "online") return writeError("machine is offline", 409)
+ const result = await pushMachineRefresh(ctx.env, machineId)
+ if (result.deliveryError) return writeError("could not deliver the daemon refresh command", 503)
+ if (result.sent === 0) return result.unsupported > 0
+ ? writeError("update this daemon before remote Refresh is available", 409)
+ : writeError("machine is offline", 409)
+ return writeJSON({ dispatched: true })
+})
diff --git a/src/web/src/components/community/machines/machine-card.dom.test.tsx b/src/web/src/components/community/machines/machine-card.dom.test.tsx
index ca1474141..02476b7b8 100644
--- a/src/web/src/components/community/machines/machine-card.dom.test.tsx
+++ b/src/web/src/components/community/machines/machine-card.dom.test.tsx
@@ -5,6 +5,32 @@ import type { MachineSummary } from "@/hooks/community/use-machines"
const stable: MachineSummary = { id: "machine", hostname: "host", displayName: "Computer", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "1", createdAt: "created", updatedAt: "updated" }
describe("restored machine observations", () => {
+ it("offers Refresh separately from Update and Stop", async () => {
+ const onRefresh = vi.fn()
+ const onUpdate = vi.fn()
+ const onStop = vi.fn()
+ const view = render(<MachineCard machine={{ ...stable, status: "online" }} onDelete={() => {}} onReconnect={() => {}} onRefresh={onRefresh} onUpdate={onUpdate} onStop={onStop} />)
+ fireEvent.click(view.getByRole("button", { name: "Machine actions" }))
+ fireEvent.click(await view.findByRole("menuitem", { name: "Refresh…" }))
+ expect(onRefresh).toHaveBeenCalledOnce()
+ expect(onUpdate).not.toHaveBeenCalled()
+ expect(onStop).not.toHaveBeenCalled()
+ })
+
+ it.each(["online", "offline"] as const)("blocks competing commands during refresh delivery while %s", async status => {
+ const action = vi.fn()
+ const view = render(<MachineCard machine={{ ...stable, status }} onDelete={action} onReconnect={action} onRefresh={action} onUpdate={action} onStop={action} refreshing />)
+ expect(view.queryByRole("status")).toBeNull()
+ expect(view.queryByRole("button", { name: "Reconnect" })).toBeNull()
+ fireEvent.click(view.getByRole("button", { name: "Machine actions" }))
+ const items = await view.findAllByRole("menuitem")
+ for (const item of items) {
+ expect(item).toHaveAttribute("aria-disabled", "true")
+ fireEvent.click(item)
+ }
+ expect(action).not.toHaveBeenCalled()
+ })
+
it("shows Stop only online and disables it during dispatch", async () => {
const onStop = vi.fn()
const view = render(<MachineCard machine={{ ...stable, status: "online" }} onDelete={() => {}} onReconnect={() => {}} onStop={onStop} />)
@@ -22,6 +48,7 @@ describe("restored machine observations", () => {
fireEvent.click(view.getByRole("button", { name: "Machine actions" }))
await view.findByRole("menuitem", { name: "Reconnect…" })
expect(view.queryByRole("menuitem", { name: "Stop" })).toBeNull()
+ expect(view.queryByRole("menuitem", { name: "Refresh…" })).toBeNull()
})
it("shows the stable card and unknown observations until live data arrives", () => {
diff --git a/src/web/src/components/community/machines/machine-card.tsx b/src/web/src/components/community/machines/machine-card.tsx
index 64b51dd84..9b3478fb6 100644
--- a/src/web/src/components/community/machines/machine-card.tsx
+++ b/src/web/src/components/community/machines/machine-card.tsx
@@ -29,6 +29,8 @@ export function MachineCard({
onUpdate,
onStop,
stopping = false,
+ onRefresh,
+ refreshing = false,
}: {
machine: MachineSummary
onDelete: () => void
@@ -36,6 +38,8 @@ export function MachineCard({
onUpdate?: () => void
onStop?: () => void
stopping?: boolean
+ onRefresh?: () => void
+ refreshing?: boolean
}) {
const isOnline = isPresenceOnline(machine.status)
const lastSeenLabel = useMemo(
@@ -107,36 +111,46 @@ export function MachineCard({
<button
aria-label="Machine actions"
data-testid={tid.machineActions(machine.id)}
- className="grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
+ className="grid size-11 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground sm:size-8"
>
<MoreVertical className="size-4" />
</button>
}
/>
<DropdownMenuContent align="end">
+ {onRefresh && (isOnline || refreshing) && (
+ <DropdownMenuItem
+ data-testid={tid.machineRefresh(machine.id)}
+ onClick={onRefresh}
+ disabled={refreshing || stopping}
+ >
+ {refreshing ? "Sending refresh…" : "Refresh…"}
+ </DropdownMenuItem>
+ )}
{onUpdate && (
<DropdownMenuItem
data-testid={tid.machineUpdate(machine.id)}
onClick={onUpdate}
+ disabled={refreshing}
>
Update daemon…
</DropdownMenuItem>
)}
{isOnline && onStop && (
- <DropdownMenuItem data-testid={tid.machineStop(machine.id)} onClick={onStop} disabled={stopping}>
+ <DropdownMenuItem data-testid={tid.machineStop(machine.id)} onClick={onStop} disabled={stopping || refreshing}>
{stopping ? "Sending stop…" : "Stop"}
</DropdownMenuItem>
)}
- <DropdownMenuItem onClick={onReconnect}>
+ <DropdownMenuItem onClick={onReconnect} disabled={refreshing}>
Reconnect…
</DropdownMenuItem>
- <DropdownMenuItem onClick={onDelete} className="text-destructive">
+ <DropdownMenuItem onClick={onDelete} disabled={refreshing} className="text-destructive">
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
- {!isOnline && (
+ {!isOnline && !refreshing && (
<div className="flex justify-end">
<Button
variant="outline"
diff --git a/src/web/src/components/community/machines/machine-list.dom.test.ts b/src/web/src/components/community/machines/machine-list.dom.test.ts
index 7567e5214..a1cfa091a 100644
--- a/src/web/src/components/community/machines/machine-list.dom.test.ts
+++ b/src/web/src/components/community/machines/machine-list.dom.test.ts
@@ -91,10 +91,17 @@ vi.mock("./guide-me-avatar-motion", () => ({
},
}))
vi.mock("./machine-card", () => ({
- MachineCard: ({ machine, onStop, stopping }: { machine: { id: string; status: string }; onStop?: () => void; stopping?: boolean }) => React.createElement("div", { "data-testid": `machine-row-${machine.id}`, "data-status": machine.status }, onStop ? React.createElement("button", { onClick: onStop, disabled: stopping }, "Stop") : null),
+ MachineCard: ({ machine, onStop, stopping, onRefresh, refreshing }: { machine: { id: string; status: string }; onStop?: () => void; stopping?: boolean; onRefresh?: () => void; refreshing?: boolean }) => React.createElement("div", { "data-testid": `machine-row-${machine.id}`, "data-status": machine.status },
+ onStop ? React.createElement("button", { onClick: onStop, disabled: stopping || refreshing }, "Stop") : null,
+ onRefresh ? React.createElement("button", { onClick: onRefresh, disabled: stopping || refreshing }, "Refresh") : null),
MachineCardFrame: ({ children }: React.PropsWithChildren) =>
React.createElement("machine-card-frame", {}, children),
}))
+vi.mock("./machine-refresh-dialog", () => ({
+ MachineRefreshDialog: ({ machine, onOpenChange, onConfirm }: { machine: unknown; onOpenChange: (open: boolean) => void; onConfirm: (machine: unknown) => void }) => machine ? React.createElement("div", {},
+ React.createElement("button", { onClick: () => onOpenChange(false) }, "Cancel refresh"),
+ React.createElement("button", { onClick: () => onConfirm(machine) }, "Confirm refresh")) : null,
+}))
vi.mock("./pair-machine-sheet", () => ({ PairMachineSheet: ({ open, onLimitReached }: { open: boolean; onLimitReached: () => void }) => open ? React.createElement("button", { "data-testid": "test-pair-sheet", onClick: onLimitReached }, "Simulate server limit") : null }))
vi.mock("@/components/community/onboarding-tiles/connect-tile", () => ({ ConnectTile: () => null }))
vi.mock("@/hooks/community/use-machines", async (importOriginal) => ({ ...await importOriginal<typeof import("@/hooks/community/use-machines")>(),
@@ -265,6 +272,63 @@ describe("machine daemon update UI", () => {
expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
})
+ it("cancels Refresh without sending a command", () => {
+ mocks.machines.current = [machine()]
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Refresh", exact: true }))
+ fireEvent.click(view.getByRole("button", { name: "Cancel refresh" }))
+ expect(view.queryByRole("button", { name: "Confirm refresh" })).toBeNull()
+ expect(mocks.apiFetch).not.toHaveBeenCalled()
+ })
+
+ it("dispatches Refresh once without a body and releases pending on delivery alone", async () => {
+ mocks.machines.current = [machine()]
+ let finish!: (value: unknown) => void
+ mocks.apiFetch.mockReturnValue(new Promise(resolve => { finish = resolve }))
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Refresh", exact: true }))
+ fireEvent.click(view.getByRole("button", { name: "Confirm refresh" }))
+ fireEvent.click(view.getByRole("button", { name: "Refresh", exact: true }))
+ await waitFor(() => expect(mocks.apiFetch).toHaveBeenCalledOnce())
+ expect(mocks.apiFetch).toHaveBeenCalledWith("/api/community/machines/machine-1/refresh", expect.objectContaining({ method: "POST" }))
+ expect(mocks.apiFetch.mock.calls[0][1].body).toBeUndefined()
+ expect(view.getByRole("button", { name: "Refresh", exact: true })).toBeDisabled()
+ expect(view.getByRole("button", { name: "Stop" })).toBeDisabled()
+ expect(mocks.toastSuccess).not.toHaveBeenCalled()
+ await act(async () => { finish({ dispatched: true }) })
+ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledExactlyOnceWith("Refresh requested"))
+ expect(view.getByRole("button", { name: "Refresh", exact: true })).toBeEnabled()
+ expect(view.getByTestId("machine-row-machine-1")).toHaveAttribute("data-status", "online")
+ })
+
+ it("allows Refresh retry after delivery failure without claiming a restart", async () => {
+ mocks.machines.current = [machine()]
+ mocks.apiFetch.mockRejectedValueOnce(new Error("could not deliver the daemon refresh command")).mockResolvedValueOnce({ dispatched: true })
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Refresh", exact: true }))
+ fireEvent.click(view.getByRole("button", { name: "Confirm refresh" }))
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("could not deliver the daemon refresh command"))
+ expect(mocks.toastSuccess).not.toHaveBeenCalled()
+ fireEvent.click(view.getByRole("button", { name: "Refresh", exact: true }))
+ fireEvent.click(view.getByRole("button", { name: "Confirm refresh" }))
+ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith("Refresh requested"))
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("does not show a Refresh receipt after leaving the view", async () => {
+ mocks.machines.current = [machine()]
+ let finish!: (value: unknown) => void
+ mocks.apiFetch.mockReturnValue(new Promise(resolve => { finish = resolve }))
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Refresh", exact: true }))
+ fireEvent.click(view.getByRole("button", { name: "Confirm refresh" }))
+ await waitFor(() => expect(mocks.apiFetch).toHaveBeenCalledOnce())
+ view.unmount()
+ await act(async () => { finish({ dispatched: true }) })
+ expect(mocks.toastSuccess).not.toHaveBeenCalled()
+ expect(mocks.toastError).not.toHaveBeenCalled()
+ })
+
it("shows Retry when the list is unknown rather than claiming no machines exist", () => {
mocks.machinesError.current = true
const view = render(React.createElement(MachineList))
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index 0f6306828..a438cf25d 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -35,6 +35,7 @@ import { fetchLatestDaemonVersion } from "@/lib/api/config"
import { getAppMode } from "@/lib/utils"
import { machineName } from "@/lib/community/machine-name"
import { MachineCard, MachineCardFrame } from "./machine-card"
+import { MachineRefreshDialog } from "./machine-refresh-dialog"
import { PairMachineSheet, type PairMachineSheetMode } from "./pair-machine-sheet"
import { ConnectTile } from "@/components/community/onboarding-tiles/connect-tile"
import { useObservedRegion } from "@/lib/observability/regions"
@@ -232,8 +233,10 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
const [connectedHostname, setConnectedHostname] = useAtom(useCreateAtom<string | null>(null))
const [deleteMachineId, setDeleteMachineId] = useAtom(useCreateAtom<string | null>(null))
const [updateMachineId, setUpdateMachineId] = useAtom(useCreateAtom<string | null>(null))
- const pendingStopsAtom = useCreateAtom(new Set<string>())
- const [pendingStops, setPendingStops] = useAtom(pendingStopsAtom)
+ const [refreshMachineId, setRefreshMachineId] = useAtom(useCreateAtom<string | null>(null))
+ const pendingCommandsAtom = useCreateAtom(new Map<string, "stop" | "refresh">())
+ const [pendingCommands, setPendingCommands] = useAtom(pendingCommandsAtom)
+ const confirmRefresh = machines.find((machine) => machine.id === refreshMachineId) ?? null
const confirmDelete = machines.find((machine) => machine.id === deleteMachineId) ?? null
const confirmUpdate = machines.find((machine) => machine.id === updateMachineId) ?? null
const setConfirmDelete = (machine: MachineSummary | null) => setDeleteMachineId(machine?.id ?? null)
@@ -248,7 +251,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
})
const latestVersion = versionQuery.data?.version ?? null
const machineCommand = useMutation({ meta: { observabilityAction: "machine.command" }, mutationKey: ["community", "machine-command"], scope: { id: "community-machine-command" },
- mutationFn: async ({ kind, id, token, assert }: { kind: "delete" | "update" | "stop"; id: string; token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {
+ mutationFn: async ({ kind, id, token, assert }: { kind: "delete" | "update" | "stop" | "refresh"; id: string; token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {
origin.assert(token)
const key = communityKeys.machines()
const original = captureMachinesPublication(queryClient)
@@ -368,20 +371,20 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
}
}
- const stopMachine = async (machine: MachineSummary) => {
- if (!isPresenceOnline(machine.status) || pendingStopsAtom.get().has(machine.id)) return
+ const dispatchMachineCommand = async (machine: MachineSummary, kind: "stop" | "refresh") => {
+ if (!isPresenceOnline(machine.status) || pendingCommandsAtom.get().has(machine.id)) return
const assert = source.capture(), token = origin.begin().token
assert()
- setPendingStops((current) => new Set(current).add(machine.id))
+ setPendingCommands((current) => new Map(current).set(machine.id, kind))
try {
- await machineCommand.mutateAsync({ kind: "stop", id: machine.id, token, assert })
+ await machineCommand.mutateAsync({ kind, id: machine.id, token, assert })
assert()
- toast.success("Stop requested")
+ toast.success(kind === "stop" ? "Stop requested" : "Refresh requested")
} catch (error) {
try { assert() } catch { return }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(getErrorMessage(error, "Couldn't request the daemon stop"))
+ if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(getErrorMessage(error, `Couldn't request the daemon ${kind}`))
} finally {
- setPendingStops((current) => { const next = new Set(current); next.delete(machine.id); return next })
+ setPendingCommands((current) => { const next = new Map(current); next.delete(machine.id); return next })
}
}
@@ -508,8 +511,10 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
machine={m}
onDelete={() => setConfirmDelete(m)}
onReconnect={() => openReconnect(m)}
- onStop={isPresenceOnline(m.status) ? () => void stopMachine(m) : undefined}
- stopping={pendingStops.has(m.id)}
+ onStop={isPresenceOnline(m.status) ? () => void dispatchMachineCommand(m, "stop") : undefined}
+ stopping={pendingCommands.get(m.id) === "stop"}
+ onRefresh={isPresenceOnline(m.status) ? () => setRefreshMachineId(m.id) : undefined}
+ refreshing={pendingCommands.get(m.id) === "refresh"}
onUpdate={
canUpdateMachine(m, latestVersion, controllerMode)
? () => setConfirmUpdate(m)
@@ -528,6 +533,14 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
connectedHostname={connectedHostname}
mode={pairMode}
/>
+ <MachineRefreshDialog
+ machine={confirmRefresh}
+ onOpenChange={(open) => !open && setRefreshMachineId(null)}
+ onConfirm={(machine) => {
+ setRefreshMachineId(null)
+ void dispatchMachineCommand(machine, "refresh")
+ }}
+ />
<MachineUpdateDialog
machine={confirmUpdate}
onOpenChange={(open) => !open && setConfirmUpdate(null)}
diff --git a/src/web/src/components/community/machines/machine-refresh-dialog.dom.test.tsx b/src/web/src/components/community/machines/machine-refresh-dialog.dom.test.tsx
new file mode 100644
index 000000000..11cd01a37
--- /dev/null
+++ b/src/web/src/components/community/machines/machine-refresh-dialog.dom.test.tsx
@@ -0,0 +1,26 @@
+import { describe, expect, it, vi } from "vitest"
+import { fireEvent, render } from "@/test/react-dom-harness"
+import type { MachineSummary } from "@/hooks/community/use-machines"
+import { MachineRefreshDialog } from "./machine-refresh-dialog"
+
+const machine = { id: "machine", hostname: "Studio Mac", displayName: "Work computer" } as MachineSummary
+
+describe("Machine Refresh confirmation", () => {
+ it("can cancel without restarting the machine", () => {
+ const onConfirm = vi.fn()
+ const onOpenChange = vi.fn()
+ const view = render(<MachineRefreshDialog machine={machine} onOpenChange={onOpenChange} onConfirm={onConfirm} />)
+ expect(view.getByRole("alertdialog")).toHaveTextContent("same daemon version")
+ fireEvent.click(view.getByRole("button", { name: "Cancel" }))
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(onOpenChange.mock.calls[0][0]).toBe(false)
+ })
+
+ it("confirms the selected machine after explaining the running-bot interruption", () => {
+ const onConfirm = vi.fn()
+ const view = render(<MachineRefreshDialog machine={machine} onOpenChange={() => {}} onConfirm={onConfirm} />)
+ expect(view.getByRole("alertdialog")).toHaveTextContent("Running bots will be interrupted")
+ fireEvent.click(view.getByRole("button", { name: "Refresh machine" }))
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(machine)
+ })
+})
diff --git a/src/web/src/components/community/machines/machine-refresh-dialog.tsx b/src/web/src/components/community/machines/machine-refresh-dialog.tsx
new file mode 100644
index 000000000..483132b5d
--- /dev/null
+++ b/src/web/src/components/community/machines/machine-refresh-dialog.tsx
@@ -0,0 +1,41 @@
+"use client"
+
+import type { MachineSummary } from "@/hooks/community/use-machines"
+import { machineName } from "@/lib/community/machine-name"
+import { tid } from "@/lib/community/testids"
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogAction,
+ AlertDialogCancel,
+} from "@/components/ui/alert-dialog"
+
+export function MachineRefreshDialog({ machine, onOpenChange, onConfirm }: {
+ machine: MachineSummary | null
+ onOpenChange: (open: boolean) => void
+ onConfirm: (machine: MachineSummary) => void
+}) {
+ return (
+ <AlertDialog open={Boolean(machine)} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Refresh {machine ? machineName(machine) : "machine"}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Restart the daemon with the latest shell environment. Running bots will be interrupted.
+ The machine will reconnect on the same daemon version.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction data-testid={tid.machineRefreshConfirm} onClick={() => machine && onConfirm(machine)}>
+ Refresh machine
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/src/web/src/lib/community/bot-push.test.ts b/src/web/src/lib/community/bot-push.test.ts
index 173c26915..c0bb75984 100644
--- a/src/web/src/lib/community/bot-push.test.ts
+++ b/src/web/src/lib/community/bot-push.test.ts
@@ -13,10 +13,36 @@ import {
pushAgentRuntimeConfigUpdateToMachine,
pushMachineUpdate,
pushMachineStop,
+ pushMachineRefresh,
} from "./bot-push"
const FAKE_ENV = { WS_DO_WORKER: {}, DEV_WS_DO_URL: undefined } as unknown as Env
+describe("pushMachineRefresh", () => {
+ beforeEach(() => wsDoFetch.mockReset())
+
+ it("preserves the dispatch receipt and sends no client command payload", async () => {
+ wsDoFetch.mockResolvedValue(Response.json({ sent: 1, unsupported: 0 }))
+ await expect(pushMachineRefresh(FAKE_ENV, "machine/1")).resolves.toEqual({ sent: 1, unsupported: 0, deliveryError: false })
+ const [, path, init] = wsDoFetch.mock.calls[0]!
+ expect(path).toBe("/community-machine/by-id/machine%2F1/forward-refresh")
+ expect(init).toEqual({ method: "POST" })
+ })
+
+ it("keeps offline and unsupported distinct from a failed delivery", async () => {
+ for (const receipt of [{ sent: 0, unsupported: 0 }, { sent: 0, unsupported: 1 }]) {
+ wsDoFetch.mockResolvedValueOnce(Response.json(receipt))
+ await expect(pushMachineRefresh(FAKE_ENV, "m")).resolves.toEqual({ ...receipt, deliveryError: false })
+ }
+ for (const receipt of [{ sent: 1 }, { sent: -1, unsupported: 0 }, { sent: 1, unsupported: "unknown" }]) {
+ wsDoFetch.mockResolvedValueOnce(Response.json(receipt))
+ await expect(pushMachineRefresh(FAKE_ENV, "m")).resolves.toEqual({ sent: 0, unsupported: 0, deliveryError: true })
+ }
+ wsDoFetch.mockRejectedValueOnce(new Error("PRIVATE_TRANSPORT_DETAILS"))
+ await expect(pushMachineRefresh(FAKE_ENV, "m")).resolves.toEqual({ sent: 0, unsupported: 0, deliveryError: true })
+ })
+})
+
describe("pushBotEventToMachine agent:event", () => {
beforeEach(() => {
wsDoFetch.mockReset()
diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.ts
index c5bf87b7b..72bcc7fbb 100644
--- a/src/web/src/lib/community/bot-push.ts
+++ b/src/web/src/lib/community/bot-push.ts
@@ -20,29 +20,46 @@ export type MachineUpdatePushResult =
| { sent: number; deliveryError: false }
| { sent: 0; deliveryError: true }
-export type MachineStopPushResult =
+export type MachineLifecyclePushResult =
| { sent: number; unsupported: number; deliveryError: false }
| { sent: 0; unsupported: 0; deliveryError: true }
-export async function pushMachineStop(env: Env, machineId: string): Promise<MachineStopPushResult> {
+async function readMachineLifecycleDelivery(response: Response): Promise<MachineLifecyclePushResult> {
+ if (!response.ok) return { sent: 0, unsupported: 0, deliveryError: true }
+ const data: unknown = await response.json()
+ if (
+ typeof data !== "object" || data === null || !("sent" in data) || !("unsupported" in data)
+ || typeof data.sent !== "number" || !Number.isSafeInteger(data.sent) || data.sent < 0
+ || typeof data.unsupported !== "number" || !Number.isSafeInteger(data.unsupported) || data.unsupported < 0
+ ) return { sent: 0, unsupported: 0, deliveryError: true }
+ return { sent: data.sent, unsupported: data.unsupported, deliveryError: false }
+}
+
+export async function pushMachineStop(env: Env, machineId: string): Promise<MachineLifecyclePushResult> {
try {
const response = await wsDoFetch(env,
`/community-machine/by-id/${encodeURIComponent(machineId)}/forward-stop`,
{ method: "POST" }, { label: machineId, type: "machine:stop" })
- if (!response.ok) return { sent: 0, unsupported: 0, deliveryError: true }
- const data: unknown = await response.json()
- if (
- typeof data !== "object" || data === null || !("sent" in data) || !("unsupported" in data)
- || typeof data.sent !== "number" || !Number.isSafeInteger(data.sent) || data.sent < 0
- || typeof data.unsupported !== "number" || !Number.isSafeInteger(data.unsupported) || data.unsupported < 0
- ) return { sent: 0, unsupported: 0, deliveryError: true }
- return { sent: data.sent, unsupported: data.unsupported, deliveryError: false }
+ return await readMachineLifecycleDelivery(response)
} catch (err) {
log.warn("machine:stop push failed", { machineId, err: String(err) })
return { sent: 0, unsupported: 0, deliveryError: true }
}
}
+export async function pushMachineRefresh(env: Env, machineId: string): Promise<MachineLifecyclePushResult> {
+ try {
+ const response = await wsDoFetch(env,
+ `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-refresh`,
+ { method: "POST" },
+ { label: machineId, type: "machine:refresh" })
+ return await readMachineLifecycleDelivery(response)
+ } catch {
+ log.warn("machine:refresh push failed", { machineId })
+ return { sent: 0, unsupported: 0, deliveryError: true }
+ }
+}
+
export async function pushMachineUpdate(
env: Env,
machineId: string,
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index f5a58ca08..79728ce01 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -150,6 +150,8 @@ export const tid = {
machineActions: (id: string) => `machine-actions-${id}`,
machineUpdate: (id: string) => `machine-update-${id}`,
machineStop: (id: string) => `machine-stop-${id}`,
+ machineRefresh: (id: string) => `machine-refresh-${id}`,
+ machineRefreshConfirm: "machine-refresh-confirm",
machineUpdateConfirm: "machine-update-confirm",
daemonUpdateNotice: "daemon-update-notice",
daemonUpdateAction: "daemon-update-action",
diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.ts
index aa238f38b..2a333e6ac 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -113,6 +113,7 @@ export const apiRoutes = [
"/api/community/machines/[id]/reconnect",
"/api/community/machines/[id]/reset-agents",
"/api/community/machines/[id]/stop",
+ "/api/community/machines/[id]/refresh",
"/api/community/machines/[id]/update",
"/api/community/machines/pair",
"/api/community/messages/[id]",
diff --git a/src/ws-do/src/routes/community-machine-lifecycle.test.ts b/src/ws-do/src/routes/community-machine-lifecycle.test.ts
index 011ca34e9..dfe919dc9 100644
--- a/src/ws-do/src/routes/community-machine-lifecycle.test.ts
+++ b/src/ws-do/src/routes/community-machine-lifecycle.test.ts
@@ -43,6 +43,20 @@ describe("ws-do router", () => {
handler = undefined as unknown as RouterHandler
})
+ describe("Refresh dispatch", () => {
+ it("constructs the fixed capability-gated command without forwarding client input", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a"])
+ doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1, unsupported: 0 }))
+ const request = new Request("http://localhost/community-machine/by-id/machine-1/forward-refresh", {
+ method: "POST", body: JSON.stringify({ env: { SECRET: "private" }, command: "shell" }),
+ })
+ expect(await (await handler.fetch(request, env as any)).json()).toEqual({ sent: 1, unsupported: 0 })
+ const forwarded = doMock.stubFetch.mock.calls[0]![0] as Request
+ expect(forwarded.url).toBe("http://internal/refresh")
+ expect(await forwarded.json()).toEqual({ type: "machine:refresh" })
+ })
+ })
+
describe("POST /community-machine/by-id/:machineId/forward-stop", () => {
beforeEach(() => mockGetActiveDoNamesForMachine.mockReset().mockResolvedValue([]))
const stopRequest = () => new Request("http://localhost/community-machine/by-id/machine-1/forward-stop", {
diff --git a/src/ws-do/src/routes/community-machine-lifecycle.ts b/src/ws-do/src/routes/community-machine-lifecycle.ts
index b00ca7b21..b36e87ba5 100644
--- a/src/ws-do/src/routes/community-machine-lifecycle.ts
+++ b/src/ws-do/src/routes/community-machine-lifecycle.ts
@@ -2,12 +2,14 @@ import { queries } from "@alook/shared"
import type { RouterContext } from "../router-context"
export async function handleMachineLifecycleCommand({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
- const route = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-(update|stop)$/)
+ const route = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-(update|stop|refresh)$/)
if (!route || request.method !== "POST") return null
const machineId = decodeURIComponent(route[1])
const stopping = route[2] === "stop"
- const command = stopping ? "machine:stop" : "machine:update"
+ const refreshing = route[2] === "refresh"
+ const gated = stopping || refreshing
+ const command = refreshing ? "machine:refresh" : stopping ? "machine:stop" : "machine:update"
const reqLog = log.child({ traceId, machineId })
reqLog.debug("forwarding machine lifecycle command", { command })
@@ -20,7 +22,7 @@ export async function handleMachineLifecycleCommand({ request, env, url, traceId
reqLog.error("failed to resolve machine doNames", { command, err })
return Response.json({ error: "failed to resolve machine" }, { status: 503 })
}
- if (doNames.length === 0) return Response.json(stopping ? { sent: 0, unsupported: 0 } : { sent: 0 })
+ if (doNames.length === 0) return Response.json(gated ? { sent: 0, unsupported: 0 } : { sent: 0 })
const frame = JSON.stringify({ type: command })
let delivered = 0
@@ -30,7 +32,7 @@ export async function handleMachineLifecycleCommand({ request, env, url, traceId
const doId = env.WS_DO.idFromName("community-machine:" + doName)
const stub = env.WS_DO.get(doId)
try {
- const response = await stub.fetch(new Request(stopping ? "http://internal/stop" : "http://internal/push", {
+ const response = await stub.fetch(new Request(refreshing ? "http://internal/refresh" : stopping ? "http://internal/stop" : "http://internal/push", {
method: "POST",
headers: { "content-type": "application/json" },
body: frame,
@@ -47,7 +49,7 @@ export async function handleMachineLifecycleCommand({ request, env, url, traceId
transientFailure = true
continue
}
- if (stopping) {
+ if (gated) {
if (!("unsupported" in data) || typeof data.unsupported !== "number" || !Number.isSafeInteger(data.unsupported) || data.unsupported < 0) {
transientFailure = true
continue
@@ -60,9 +62,9 @@ export async function handleMachineLifecycleCommand({ request, env, url, traceId
}
}
if (delivered === 0 && transientFailure) {
- return Response.json({ error: `failed to forward machine ${stopping ? "stop" : "update"}` }, { status: 503 })
+ return Response.json({ error: `failed to forward machine ${route[2]}` }, { status: 503 })
}
- return Response.json(stopping ? { sent: delivered, unsupported } : { sent: delivered })
+ return Response.json(gated ? { sent: delivered, unsupported } : { sent: delivered })
}
export async function handleMachineReset({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
diff --git a/src/ws-do/src/ws-durable/internal.ts b/src/ws-do/src/ws-durable/internal.ts
index aa2a1a05d..b16f74896 100644
--- a/src/ws-do/src/ws-durable/internal.ts
+++ b/src/ws-do/src/ws-durable/internal.ts
@@ -30,6 +30,7 @@ export type ConnectionState =
authenticated: boolean
pii?: boolean
modelDiscovery?: boolean
+ machineRefresh?: boolean
machineStop?: boolean
controlHeartbeat?: boolean
lastHeartbeatAckAt?: number
diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.ts
index 70d8dd9eb..a4a1631fb 100644
--- a/src/ws-do/src/ws-durable/machine-control.test.ts
+++ b/src/ws-do/src/ws-durable/machine-control.test.ts
@@ -68,6 +68,22 @@ describe("WebSocketDurableObject", () => {
expect(JSON.stringify([...store])).not.toContain(command.operation.text)
})
+ it("forwards the fixed Refresh command only to authenticated Refresh-capable daemon sockets", async () => {
+ const { durable, getWebSockets } = createDO()
+ const supported = createMockWebSocket(), legacy = createMockWebSocket(), unauthed = createMockWebSocket()
+ supported.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "machine", userId: "owner", machineRefresh: true })
+ legacy.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "machine", userId: "owner" })
+ unauthed.serializeAttachment({ type: "community-machine", authenticated: false, machineId: "machine", userId: "owner", machineRefresh: true })
+ getWebSockets.mockReturnValue([supported, legacy, unauthed])
+ const command = { type: "machine:refresh" }
+ const response = await durable.fetch(new Request("http://internal/refresh", { method: "POST", body: JSON.stringify(command) }))
+ expect(await response.json()).toEqual({ sent: 1, unsupported: 1 })
+ expect(supported.send).toHaveBeenCalledWith(JSON.stringify(command))
+ expect(legacy.send).not.toHaveBeenCalled()
+ expect(unauthed.send).not.toHaveBeenCalled()
+ expect((await durable.fetch(new Request("http://internal/refresh", { method: "POST", body: JSON.stringify({ ...command, env: {} }) }))).status).toBe(400)
+ })
+
describe("machine Stop dispatch", () => {
it("sends only to authenticated stop-capable machines without force-closing or clearing state", async () => {
const { durable, store, getWebSockets } = createDO()
diff --git a/src/ws-do/src/ws-durable/machine-control.ts b/src/ws-do/src/ws-durable/machine-control.ts
index a964c794e..f1f0f34ec 100644
--- a/src/ws-do/src/ws-durable/machine-control.ts
+++ b/src/ws-do/src/ws-durable/machine-control.ts
@@ -1,6 +1,6 @@
import { waitForModelDiscovery } from "./model-discovery-wait"
import { readBoundedJsonRequest } from "../community-browser-event-ingress"
-import { createDb, PII_REQUEST_MAX_BYTES, PiiCommandSchema, DiagnosticCollectCommandSchema, RuntimeModelDiscoveryCommandSchema, RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER, queries } from "@alook/shared"
+import { MachineRefreshCommandSchema, createDb, PII_REQUEST_MAX_BYTES, PiiCommandSchema, DiagnosticCollectCommandSchema, RuntimeModelDiscoveryCommandSchema, RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER, queries } from "@alook/shared"
import {
HANDLE_KEY,
IDENTITY_KEY,
@@ -54,6 +54,13 @@ export async function handleMachineControlFetch(
return new Response(JSON.stringify(forwardToCommunityMachine(context, JSON.stringify(command.data), "pii")), { headers: { "Content-Type": "application/json" } })
}
+ if (url.pathname === "/refresh" && request.method === "POST") {
+ const input = await readBoundedJsonRequest(request, 1024)
+ const command = MachineRefreshCommandSchema.safeParse(input.ok ? input.value : null)
+ if (!command.success) return Response.json({ error: "invalid refresh request" }, { status: 400 })
+ return Response.json(forwardToCommunityMachine(context, JSON.stringify(command.data), "machineRefresh"))
+ }
+
if (url.pathname === "/stop" && request.method === "POST") {
const result = forwardToCommunityMachine(context, JSON.stringify({ type: "machine:stop" }), "machineStop")
return new Response(JSON.stringify(result), { headers: { "Content-Type": "application/json" } })
@@ -289,7 +296,7 @@ function rejectCommunityMachine(ws: WebSocket, reason: string): void {
try { ws.close(1008, "Unauthorized") } catch { /* ok */ }
}
-function forwardToCommunityMachine(context: WsDurableContext, message: string, capability?: "modelDiscovery" | "machineStop" | "pii"): { sent: number; unsupported: number } {
+function forwardToCommunityMachine(context: WsDurableContext, message: string, capability?: "modelDiscovery" | "machineStop" | "machineRefresh" | "pii"): { sent: number; unsupported: number } {
let sent = 0
let unsupported = 0
for (const ws of context.ctx.getWebSockets()) {
diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.ts
index 27f2e1054..c55179c0c 100644
--- a/src/ws-do/src/ws-durable/machine-ready.ts
+++ b/src/ws-do/src/ws-durable/machine-ready.ts
@@ -2,6 +2,7 @@ import { PII_CAPABILITY } from "@alook/shared"
import {
CONTROL_HEARTBEAT_CAPABILITY,
MACHINE_STOP_CAPABILITY,
+ MACHINE_REFRESH_CAPABILITY,
RUNTIME_MODEL_DISCOVERY_CAPABILITY,
createDb,
HostReadyMessageSchema,
@@ -100,6 +101,7 @@ export async function handleReadyFrame(
pii: ready.capabilities.includes(PII_CAPABILITY),
modelDiscovery: ready.capabilities.includes(RUNTIME_MODEL_DISCOVERY_CAPABILITY),
machineStop: ready.capabilities.includes(MACHINE_STOP_CAPABILITY),
+ machineRefresh: ready.capabilities.includes(MACHINE_REFRESH_CAPABILITY),
...(controlHeartbeat ? { lastHeartbeatAckAt: Date.now() } : {}),
pendingHeartbeatNonce: undefined,
})