Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: stop owned machines from the Machines menu (#1047)

Gustavo Yeedade5ba24ef
diff --git a/src/daemon/src/cli/daemonRunner.test.ts b/src/daemon/src/cli/daemonRunner.test.ts
index c836a355f..ef8400a9f 100644
--- a/src/daemon/src/cli/daemonRunner.test.ts
+++ b/src/daemon/src/cli/daemonRunner.test.ts
@@ -497,7 +497,7 @@ describe("daemon runner logger", () => {
}
});
- it("routes self-sleep through the existing ordered successful shutdown", async () => {
+ it.each(["onSelfSleep", "onStopRequested"] as const)("routes %s through the existing ordered successful shutdown", async (callback) => {
resetDiagnosticHarness();
vi.useFakeTimers();
const listenersBefore = processListenerSnapshot();
@@ -521,9 +521,10 @@ describe("daemon runner logger", () => {
});
await readyPromise;
- const onSelfSleep = daemonHarness.state.options?.onSelfSleep as (() => void) | undefined;
- expect(onSelfSleep).toEqual(expect.any(Function));
- onSelfSleep!();
+ const requestStop = daemonHarness.state.options?.[callback] as (() => void) | undefined;
+ expect(requestStop).toEqual(expect.any(Function));
+ requestStop!();
+ if (callback === "onStopRequested") requestStop!();
await vi.waitFor(() => {
expect(events).toEqual([
"coordinator-shutdown",
@@ -537,10 +538,14 @@ describe("daemon runner logger", () => {
.trimEnd()
.split("\n")
.map((line) => JSON.parse(line));
- expect(records).toContainEqual(expect.objectContaining({
- level: "info",
- message: "daemon self-sleep threshold reached",
- }));
+ if (callback === "onSelfSleep") {
+ expect(records).toContainEqual(expect.objectContaining({
+ level: "info",
+ message: "daemon self-sleep threshold reached",
+ }));
+ }
+ expect(runnerDiagnosticHarness.shutdown).toHaveBeenCalledOnce();
+ expect(releaseOwnership).toHaveBeenCalledOnce();
} finally {
removeNewProcessListeners(listenersBefore);
vi.clearAllTimers();
diff --git a/src/daemon/src/cli/daemonRunner.ts b/src/daemon/src/cli/daemonRunner.ts
index e2e82e542..8f1f3e233 100644
--- a/src/daemon/src/cli/daemonRunner.ts
+++ b/src/daemon/src/cli/daemonRunner.ts
@@ -361,6 +361,7 @@ export async function runPreparedDaemon(
daemonVersion: prepared.daemonVersion,
logger: log,
handleSelfUpdate,
+ onStopRequested: () => { void shutdown(0); },
handleDiagnosticCommand,
reportDiagnosticFailure,
onDiagnosticSources: ({ fsmTraceSource, statusFilePath }) => {
diff --git a/src/daemon/src/cli/daemonStop.real.test.ts b/src/daemon/src/cli/daemonStop.real.test.ts
new file mode 100644
index 000000000..1b2370e62
--- /dev/null
+++ b/src/daemon/src/cli/daemonStop.real.test.ts
@@ -0,0 +1,112 @@
+import { expect, it } from "vitest";
+import { spawn, type ChildProcess } from "node:child_process";
+import { createServer } from "node:http";
+import { createRequire } from "node:module";
+import { mkdtempSync, writeFileSync, readFileSync, 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";
+
+it("remote Stop exits the real runner successfully and retains the credential for an explicit restart", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "alook-machine-stop-"));
+ const recordPath = join(dir, "credential.json");
+ writeFileSync(recordPath, JSON.stringify({ machineId: "cm_stop_real", credential: "cmk_stop_real_fixture" }), { mode: 0o600 });
+ const originalRecord = readFileSync(recordPath, "utf8");
+ const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
+ const runner = pathToFileURL(join(packageRoot, "src/cli/daemonRunner.ts")).href;
+ const fixture = join(dir, "runner.mts");
+ writeFileSync(fixture, `
+import { runPreparedDaemon } from ${JSON.stringify(runner)};
+import { readFileSync, appendFileSync, mkdirSync } from "node:fs";
+import { join } from "node:path";
+const baseDir=process.argv[2], origin=process.argv[3];
+const record=JSON.parse(readFileSync(join(baseDir,"credential.json"),"utf8"));
+const daemonDir=join(baseDir,"daemons",record.machineId);
+mkdirSync(daemonDir,{recursive:true});
+await runPreparedDaemon({
+ machineId:record.machineId,machineKey:record.credential,serverUrl:origin,
+ wsUrl:origin.replace("http:","ws:")+"/control",baseDir,daemonDir,
+ statusFilePath:join(daemonDir,"status.json"),agentCliPath:undefined,
+ runtimeReport:[],healthyRuntimeIds:[],hostname:"stop-fixture",platform:"test",arch:"test",
+ osRelease:"test",daemonVersion:"0.1.57",ownerToken:"test-owner",startedAt:new Date().toISOString(),
+},{foreground:false,onReady:()=>process.stdout.write("RUNNER_READY\\n"),
+releaseOwnership:()=>appendFileSync(join(baseDir,"released"),"released\\n")});
+`);
+ const wss = new WebSocketServer({ noServer: true });
+ const sockets: WebSocket[] = [];
+ const ready: Array<{ socket: WebSocket; capabilities: string[] }> = [];
+ const authenticated: boolean[] = [];
+ const requests: string[] = [];
+ const children: ChildProcess[] = [];
+ 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) => {
+ authenticated.push(request.headers.authorization === "Bearer cmk_stop_real_fixture");
+ wss.handleUpgrade(request, socket, head, (ws) => wss.emit("connection", ws));
+ });
+ wss.on("connection", (socket: WebSocket) => {
+ sockets.push(socket);
+ socket.on("message", (raw) => {
+ const frame = JSON.parse(String(raw));
+ if (frame.type === "ready" && !ready.some((entry) => entry.socket === socket)) ready.push({ socket, capabilities: frame.capabilities ?? [] });
+ });
+ });
+ const waitFor = async (predicate: () => boolean) => {
+ const deadline = Date.now() + 15_000;
+ while (!predicate()) {
+ if (Date.now() >= deadline) throw new Error("Stop fixture condition timed out");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ };
+ try {
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Stop fixture did not bind");
+ const origin = `http://127.0.0.1:${address.port}`;
+ const loader = pathToFileURL(createRequire(import.meta.url).resolve("tsx")).href;
+ for (let round = 0; round < 2; round++) {
+ let runnerReady = false;
+ const child = spawn(process.execPath, ["--import", loader, fixture, dir, origin], {
+ cwd: packageRoot, env: { ...process.env, ALOOK_LOG_LEVEL: "error" }, stdio: ["ignore", "pipe", "pipe"],
+ });
+ children.push(child);
+ child.stdout?.on("data", (chunk) => { if (String(chunk).includes("RUNNER_READY")) runnerReady = true; });
+ child.stderr?.resume();
+ const exited = new Promise<number | null>((resolve, reject) => {
+ child.once("error", reject);
+ child.once("exit", resolve);
+ });
+ await waitFor(() => runnerReady && ready.length > round);
+ const connection = ready[round]!;
+ expect(connection.capabilities).toContain("machine-stop-v1");
+ connection.socket.send(JSON.stringify({ type: "machine:stop" }));
+ await waitFor(() => child.exitCode !== null);
+ expect(await exited).toBe(0);
+ await waitFor(() => connection.socket.readyState === WebSocket.CLOSED);
+ expect(readFileSync(recordPath, "utf8")).toBe(originalRecord);
+ expect(readFileSync(join(dir, "released"), "utf8").trim().split("\n")).toHaveLength(round + 1);
+ expect(sockets).toHaveLength(round + 1);
+ }
+ expect(authenticated).toEqual([true, true]);
+ expect(requests.some((url) => /activate|pair|enroll-agent/.test(url))).toBe(false);
+ } finally {
+ for (const child of children) {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill("SIGTERM");
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(() => { child.kill("SIGKILL"); }, 2000);
+ child.once("exit", () => { clearTimeout(timer); resolve(); });
+ });
+ }
+ }
+ 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(dir, { recursive: true, force: true });
+ }
+}, 40_000);
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 1b1cb9470..f326801e7 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -1489,6 +1489,31 @@ for await (const line of createInterface({ input: process.stdin })) {
await daemon.stop();
});
+ it("advertises and consumes machine:stop before bot observers and AgentRouter", async () => {
+ const sockets: FakeSocket[] = [];
+ const routerEntry = spyOnRouterCommandEntry();
+ const onStopRequested = vi.fn();
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ bots: [] })));
+ const daemon = await createDaemon({
+ machineKey: "cmk_remote_stop",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets),
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ capabilities: [],
+ onStopRequested,
+ } as Parameters<typeof createDaemon>[0]);
+ sockets[0].emit("open");
+ await vi.waitFor(() => expect(sockets[0].sent.map((frame) => JSON.parse(frame)))
+ .toContainEqual(expect.objectContaining({ type: "ready", capabilities: expect.arrayContaining(["machine-stop-v1"]) })));
+ sockets[0].emit("message", JSON.stringify({ type: "machine:stop" }));
+ await vi.waitFor(() => expect(onStopRequested).toHaveBeenCalledOnce());
+ expect(routerEntry).not.toHaveBeenCalledWith(expect.objectContaining({ type: "machine:stop" }));
+ expect(fakeDriver.start).not.toHaveBeenCalled();
+ 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 29641b3be..1ee006d93 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -49,6 +49,7 @@ import {
type DiagnosticFailureReport,
} from "./diagnosticsCommand.js";
import { createSelfUpdateCommandListener } from "./selfUpdateCommand.js";
+import { createMachineStopCommandListener } from "./machineStopCommand.js";
import {
MessageReminderScheduler,
type MessageReminderSchedulerOptions,
@@ -327,6 +328,7 @@ export interface CreateDaemonOptions {
handleDiagnosticCommand?: (command: DiagnosticCollectCommand) => void | Promise<void>;
/** Machine-level lifecycle command; consumed before bot observers/router. */
handleSelfUpdate?: () => void | Promise<void>;
+ onStopRequested?: () => void;
/** Fixed-code failure callback used when diagnostics is not available. */
reportDiagnosticFailure?: (failure: DiagnosticFailureReport) => void | Promise<void>;
/** Injectable daemon-local reminder clock; tests only, defaults to Node timers. */
@@ -1113,6 +1115,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
manager,
channel,
runtimeReport: opts.runtimeReport,
+ supportsMachineStop: typeof opts.onStopRequested === "function",
hostname: opts.hostname,
platform: opts.platform,
arch: opts.arch,
@@ -1168,6 +1171,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
// Machine lifecycle commands are claimed before diagnostics, bot observers,
// and AgentRouter; updates never enter agent lifecycle routing.
channel.onCommand(createSelfUpdateCommandListener(opts.handleSelfUpdate));
+ channel.onCommand(createMachineStopCommandListener(opts.onStopRequested));
// Diagnostics likewise claims its machine-level command before bot/router.
channel.onCommand(createDiagnosticsCommandListener({
handleDiagnosticCommand: opts.handleDiagnosticCommand,
diff --git a/src/daemon/src/daemon/machineStopCommand.ts b/src/daemon/src/daemon/machineStopCommand.ts
new file mode 100644
index 000000000..540d015f8
--- /dev/null
+++ b/src/daemon/src/daemon/machineStopCommand.ts
@@ -0,0 +1,10 @@
+import type { HostCommand } from "../server/contract.js";
+import { WS_CONTROL_COMMAND_CONSUMED } from "../server/wsControlChannel.js";
+
+export function createMachineStopCommandListener(onStopRequested?: () => void) {
+ return (command: HostCommand): void | typeof WS_CONTROL_COMMAND_CONSUMED => {
+ if (command.type !== "machine:stop") return;
+ onStopRequested?.();
+ return WS_CONTROL_COMMAND_CONSUMED;
+ };
+}
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index 5097bb412..ad78105b7 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -20,7 +20,7 @@
*/
import type { HostCommand, HostControlChannel, HostReady, HostReadyRuntime, UnreadNotice, AgentSessionReport, SessionErrorFrame, AgentId, HostAgentActivity } from "../server/contract.js";
import type { ProviderQuotaSnapshot } from "@alook/shared";
-import { CONTROL_HEARTBEAT_CAPABILITY, RUNTIME_MODEL_DISCOVERY_CAPABILITY } from "../server/contract.js";
+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";
import type { TypingScopeTracker } from "./typingScopeTracker.js";
@@ -83,6 +83,7 @@ export interface AgentRouterOpts {
/** Runtime descriptors reported in the ready handshake. Copied into a live mutable map. */
runtimeReport: HostReadyRuntime[];
discoverModels?: (runtimeId: string) => ReturnType<AgentBackend["discoverModels"]>;
+ supportsMachineStop?: boolean;
hostname?: string;
platform?: string;
arch?: string;
@@ -251,7 +252,7 @@ export class AgentRouter {
: this.opts.timeZone;
return {
runtimeReport: [...this.runtimes.values()],
- capabilities: [CONTROL_HEARTBEAT_CAPABILITY, ...(this.opts.channel.reportRuntimeModels ? [RUNTIME_MODEL_DISCOVERY_CAPABILITY] : [])],
+ capabilities: [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/src/server/contract.ts b/src/daemon/src/server/contract.ts
index c8f2621cf..8599f8010 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -92,6 +92,7 @@ export { RUNTIME_MODEL_DISCOVERY_CAPABILITY } from "@alook/shared/community-cli-
export {
CONTROL_HEARTBEAT_CAPABILITY,
+ MACHINE_STOP_CAPABILITY,
DM_SERVER,
parseRef,
formatRef,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 65a9513da..5eab4c09f 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -755,6 +755,7 @@ export interface UnreadNotice {
/* ------------------------------------------------------------------ */
export const CONTROL_HEARTBEAT_CAPABILITY = "control-heartbeat-v1";
+export const MACHINE_STOP_CAPABILITY = "machine-stop-v1";
export const AgentInterruptRequestSchema = z.strictObject({
type: z.literal("agent:interrupt"),
@@ -851,6 +852,7 @@ export type HostCommand =
*/
| { type: "machine:reset_all"; resets: Array<{ agentId: AgentId; config: RuntimeConfig; launchId: string }> }
| { type: "machine:update" }
+ | { type: "machine:stop" }
// ─── Bot lifecycle events (server → daemon) ────────────────────────────
// Colon-namespaced to match the agent:* naming convention. Delivered to
// the specific machine's daemon connection via the WS DO. On the daemon,
@@ -1550,6 +1552,9 @@ export const HostCommandSchema = z.discriminatedUnion("type", [
z.strictObject({
type: z.literal("machine:update"),
}),
+ z.strictObject({
+ type: z.literal("machine:stop"),
+ }),
// The `bot:*` arms are NOT what #6 targets — the daemon acts on `agent:*`;
// `bot:*` merely mutate/evict the `botsById` cache at the createDaemon layer.
// Per the CTO scope ("bot:* covered for union-completeness, no bespoke
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 7e529a880..af3d8b543 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -501,6 +501,7 @@ export {
AGENT_EVENT_PROMPT_MAX_LENGTH,
BOT_AUDIT_TEXT_MAX_BYTES,
CONTROL_HEARTBEAT_CAPABILITY,
+ MACHINE_STOP_CAPABILITY,
AgentInterruptRequestSchema,
DM_SERVER,
parseRef,
diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.ts
index 3204c7792..fc2e7a480 100644
--- a/src/shared/test/community-cli-contract.test.ts
+++ b/src/shared/test/community-cli-contract.test.ts
@@ -398,3 +398,15 @@ describe("HostCommand machine update contract", () => {
},
);
});
+
+
+describe("HostCommand machine stop contract", () => {
+ it("accepts only the payload-free stop command", () => {
+ expectTypeOf<Extract<HostCommand, { type: "machine:stop" }>>()
+ .toEqualTypeOf<{ type: "machine:stop" }>();
+ expect(HostCommandSchema.parse({ type: "machine:stop" })).toEqual({ type: "machine:stop" });
+ for (const field of ["machineId", "command", "force", "delete", "credential"]) {
+ expect(HostCommandSchema.safeParse({ type: "machine:stop", [field]: "extra" }).success).toBe(false);
+ }
+ });
+});
diff --git a/src/web/src/app/api/community/machines/[id]/stop/route.test.ts b/src/web/src/app/api/community/machines/[id]/stop/route.test.ts
new file mode 100644
index 000000000..547cc7d5d
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/stop/route.test.ts
@@ -0,0 +1,64 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const getMachine = vi.fn()
+const pushStop = vi.fn()
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@alook/shared", () => ({ queries: { communityMachine: { getMachineByIdForUser: (...args: unknown[]) => getMachine(...args) } } }))
+vi.mock("@/lib/community/bot-push", () => ({ pushMachineStop: (...args: unknown[]) => pushStop(...args) }))
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: (request: NextRequest, context: unknown) => Promise<Response>) => async (request: NextRequest, context: { params?: Promise<Record<string, string>> }) =>
+ handler(request, { env: { DB: {} }, userId: "owner", email: "[email protected]", params: await context.params }),
+}))
+
+import { POST } from "./route"
+const request = () => new NextRequest("http://localhost/api/community/machines/m/stop", { method: "POST" })
+const context = { params: Promise.resolve({ id: "m" }) }
+
+describe("POST /api/community/machines/[id]/stop", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ getMachine.mockResolvedValue({ id: "m", userId: "owner", status: "online" })
+ pushStop.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(pushStop).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(pushStop).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(pushStop).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 Stop is available"],
+ [{ sent: 0, unsupported: 0, deliveryError: true }, 503, "could not deliver the daemon stop command"],
+ ])("returns a truthful failure for %j", async (receipt, status, error) => {
+ pushStop.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(pushStop).toHaveBeenCalledWith({ DB: {} }, "m")
+ })
+})
diff --git a/src/web/src/app/api/community/machines/[id]/stop/route.ts b/src/web/src/app/api/community/machines/[id]/stop/route.ts
new file mode 100644
index 000000000..65493a538
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/stop/route.ts
@@ -0,0 +1,22 @@
+import { queries } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { pushMachineStop } from "@/lib/community/bot-push"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeError, writeJSON } from "@/lib/middleware/helpers"
+
+export const POST = withAuth(async (_request, ctx) => {
+ const machineId = ctx.params?.id as string
+ if (!machineId) return writeError("machine id is required", 400)
+ const 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 pushMachineStop(ctx.env, machineId)
+ if (result.deliveryError) return writeError("could not deliver the daemon stop command", 503)
+ if (result.sent === 0) {
+ return result.unsupported > 0
+ ? writeError("update this daemon before remote Stop 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 934f4274d..ca1474141 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
@@ -1,10 +1,29 @@
-import { describe, expect, it } from "vitest"
-import { render } from "@/test/react-dom-harness"
+import { describe, expect, it, vi } from "vitest"
+import { render, fireEvent } from "@/test/react-dom-harness"
import { MachineCard } from "./machine-card"
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("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} />)
+ fireEvent.click(view.getByRole("button", { name: "Machine actions" }))
+ fireEvent.click(await view.findByRole("menuitem", { name: "Stop" }))
+ expect(onStop).toHaveBeenCalledOnce()
+ view.rerender(<MachineCard machine={{ ...stable, status: "online" }} onDelete={() => {}} onReconnect={() => {}} onStop={onStop} stopping />)
+ fireEvent.click(view.getByRole("button", { name: "Machine actions" }))
+ expect(await view.findByRole("menuitem", { name: "Sending stop…" })).toHaveAttribute("aria-disabled", "true")
+ view.unmount()
+ })
+
+ it.each(["offline", undefined] as const)("omits Stop when status is %s", async status => {
+ const view = render(<MachineCard machine={{ ...stable, status }} onDelete={() => {}} onReconnect={() => {}} onStop={() => {}} />)
+ fireEvent.click(view.getByRole("button", { name: "Machine actions" }))
+ await view.findByRole("menuitem", { name: "Reconnect…" })
+ expect(view.queryByRole("menuitem", { name: "Stop" })).toBeNull()
+ })
+
it("shows the stable card and unknown observations until live data arrives", () => {
const view = render(<MachineCard machine={stable} onDelete={() => {}} onReconnect={() => {}} />)
expect(view.getByText("Computer")).toBeInTheDocument()
diff --git a/src/web/src/components/community/machines/machine-card.tsx b/src/web/src/components/community/machines/machine-card.tsx
index 7dd81602b..64b51dd84 100644
--- a/src/web/src/components/community/machines/machine-card.tsx
+++ b/src/web/src/components/community/machines/machine-card.tsx
@@ -27,11 +27,15 @@ export function MachineCard({
onDelete,
onReconnect,
onUpdate,
+ onStop,
+ stopping = false,
}: {
machine: MachineSummary
onDelete: () => void
onReconnect: () => void
onUpdate?: () => void
+ onStop?: () => void
+ stopping?: boolean
}) {
const isOnline = isPresenceOnline(machine.status)
const lastSeenLabel = useMemo(
@@ -118,6 +122,11 @@ export function MachineCard({
Update daemon…
</DropdownMenuItem>
)}
+ {isOnline && onStop && (
+ <DropdownMenuItem data-testid={tid.machineStop(machine.id)} onClick={onStop} disabled={stopping}>
+ {stopping ? "Sending stop…" : "Stop"}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={onReconnect}>
Reconnect…
</DropdownMenuItem>
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 411a780d4..a427ddba2 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,7 +91,7 @@ vi.mock("./guide-me-avatar-motion", () => ({
},
}))
vi.mock("./machine-card", () => ({
- MachineCard: () => null,
+ 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),
MachineCardFrame: ({ children }: React.PropsWithChildren) =>
React.createElement("machine-card-frame", {}, children),
}))
@@ -232,6 +232,39 @@ describe("machine daemon update UI", () => {
expect(oldIntent()).toBe(false)
})
+ it("dispatches Stop once while pending and waits for observed offline status", 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: "Stop" }))
+ fireEvent.click(view.getByRole("button", { name: "Stop" }))
+ await waitFor(() => expect(mocks.apiFetch).toHaveBeenCalledOnce())
+ expect(mocks.apiFetch).toHaveBeenCalledWith("/api/community/machines/machine-1/stop", expect.objectContaining({ method: "POST" }))
+ expect(view.getByRole("button", { name: "Stop" })).toBeDisabled()
+ await act(async () => { finish({ dispatched: true }) })
+ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith("Stop requested"))
+ expect(view.getByTestId("machine-row-machine-1")).toHaveAttribute("data-status", "online")
+ expect(view.getByRole("button", { name: "Stop" })).toBeEnabled()
+ mocks.machines.current = [machine({ status: "offline" })]
+ view.rerender(React.createElement(MachineList))
+ expect(view.getByTestId("machine-row-machine-1")).toHaveAttribute("data-status", "offline")
+ expect(view.queryByRole("button", { name: "Stop" })).toBeNull()
+ })
+
+ it.each(["update this daemon before remote Stop is available", "could not deliver the daemon stop command"])("keeps machine state and permits retry after %s", async message => {
+ mocks.machines.current = [machine()]
+ mocks.apiFetch.mockRejectedValueOnce(new Error(message)).mockResolvedValueOnce({ dispatched: true })
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Stop" }))
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith(message))
+ expect(mocks.toastSuccess).not.toHaveBeenCalled()
+ expect(view.getByTestId("machine-row-machine-1")).toHaveAttribute("data-status", "online")
+ fireEvent.click(view.getByRole("button", { name: "Stop" }))
+ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith("Stop requested"))
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ })
+
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 e1e6d1cb7..0f6306828 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -56,7 +56,6 @@ const MACHINE_LIST_HEADING_CLASS =
"flex flex-col items-stretch gap-4 sm:flex-row sm:items-center sm:justify-between"
const MACHINE_LIST_HEADING_COPY_CLASS = "flex min-w-0 flex-col gap-1"
const MACHINE_LIST_HEADING_ACTION_CLASS = "w-full sm:w-fit sm:shrink-0"
-const MACHINE_LIST_DESCRIPTION = "Your computers running the alook daemon."
// Loading placeholder shaped like a real MachineCard (size-10 rounded-xl icon +
// name row + meta lines + trailing kebab slot) so the list doesn't reflow when
@@ -124,10 +123,6 @@ export function MachineListSkeleton({
<div data-slot="community-machines-heading-copy" className={MACHINE_LIST_HEADING_COPY_CLASS}>
<Skeleton className="h-7 w-24 rounded" />
<Skeleton aria-hidden className="h-11 w-36 max-w-full rounded-sm sm:h-6" />
- <div aria-hidden className="relative w-fit max-w-full">
- <p className="invisible text-sm">{MACHINE_LIST_DESCRIPTION}</p>
- <Skeleton className="absolute inset-0 rounded" />
- </div>
</div>
<div data-slot="community-machines-heading-action" className={MACHINE_LIST_HEADING_ACTION_CLASS}>
<Skeleton className="h-11 w-full rounded-md sm:h-9 sm:w-36" />
@@ -237,6 +232,8 @@ 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 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)
@@ -251,11 +248,11 @@ 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"; id: string; token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {
+ mutationFn: async ({ kind, id, token, assert }: { kind: "delete" | "update" | "stop"; id: string; token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {
origin.assert(token)
const key = communityKeys.machines()
const original = captureMachinesPublication(queryClient)
- await origin.request(token, `/api/community/machines/${id}${kind === "update" ? "/update" : ""}`, { method: kind === "delete" ? "DELETE" : "POST", assertActive: assert })
+ await origin.request(token, `/api/community/machines/${id}${kind === "delete" ? "" : `/${kind}`}`, { method: kind === "delete" ? "DELETE" : "POST", assertActive: assert })
origin.assert(token)
if (kind === "delete" && !await publishMachines(queryClient, original, (current) => current ? replaceMachines(current, current.machines.filter((row) => row.id !== id)) : current)) return
if (queryClient.getQueryCache().get(original.query.queryHash) !== original.query) return
@@ -371,6 +368,23 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
}
}
+ const stopMachine = async (machine: MachineSummary) => {
+ if (!isPresenceOnline(machine.status) || pendingStopsAtom.get().has(machine.id)) return
+ const assert = source.capture(), token = origin.begin().token
+ assert()
+ setPendingStops((current) => new Set(current).add(machine.id))
+ try {
+ await machineCommand.mutateAsync({ kind: "stop", id: machine.id, token, assert })
+ assert()
+ toast.success("Stop requested")
+ } catch (error) {
+ try { assert() } catch { return }
+ if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(getErrorMessage(error, "Couldn't request the daemon stop"))
+ } finally {
+ setPendingStops((current) => { const next = new Set(current); next.delete(machine.id); return next })
+ }
+ }
+
const finishGuideIntro = useCallback(() => {
setGuideIntroActive(false)
}, [setGuideIntroActive])
@@ -471,9 +485,6 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
<div data-slot="community-machines-heading-copy" className={MACHINE_LIST_HEADING_COPY_CLASS}>
<h1 className="text-xl font-medium text-foreground">Machines</h1>
{usage}
- <p className="text-sm text-muted-foreground">
- {MACHINE_LIST_DESCRIPTION}
- </p>
</div>
<div
data-slot="community-machines-heading-action"
@@ -497,6 +508,8 @@ 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)}
onUpdate={
canUpdateMachine(m, latestVersion, controllerMode)
? () => setConfirmUpdate(m)
diff --git a/src/web/src/lib/community/bot-push.test.ts b/src/web/src/lib/community/bot-push.test.ts
index bfee2d2b1..173c26915 100644
--- a/src/web/src/lib/community/bot-push.test.ts
+++ b/src/web/src/lib/community/bot-push.test.ts
@@ -12,6 +12,7 @@ import {
pushAgentProviderSwitchToMachine,
pushAgentRuntimeConfigUpdateToMachine,
pushMachineUpdate,
+ pushMachineStop,
} from "./bot-push"
const FAKE_ENV = { WS_DO_WORKER: {}, DEV_WS_DO_URL: undefined } as unknown as Env
@@ -60,6 +61,31 @@ describe("pushBotEventToMachine agent:event", () => {
})
})
+describe("pushMachineStop", () => {
+ beforeEach(() => wsDoFetch.mockReset())
+
+ it.each([{ sent: 1, unsupported: 0 }, { sent: 0, unsupported: 1 }, { sent: 0, unsupported: 0 }])("preserves the supported socket receipt %j", async (receipt) => {
+ wsDoFetch.mockResolvedValue(Response.json(receipt))
+ await expect(pushMachineStop(FAKE_ENV, "machine/1")).resolves.toEqual({ ...receipt, deliveryError: false })
+ const [, path, init, meta] = wsDoFetch.mock.calls[0]!
+ expect(path).toBe("/community-machine/by-id/machine%2F1/forward-stop")
+ expect(init).toEqual({ method: "POST" })
+ expect(meta).toEqual({ label: "machine/1", type: "machine:stop" })
+ })
+
+ it.each([null, {}, { sent: 1 }, { sent: -1, unsupported: 0 }, { sent: 1, unsupported: "unknown" }, { sent: 1.5, unsupported: 0 }])("rejects malformed receipt %j", async (receipt) => {
+ wsDoFetch.mockResolvedValue(Response.json(receipt))
+ await expect(pushMachineStop(FAKE_ENV, "m")).resolves.toEqual({ sent: 0, unsupported: 0, deliveryError: true })
+ })
+
+ it("reports a service error or thrown request as delivery failure", async () => {
+ wsDoFetch.mockResolvedValueOnce(new Response("down", { status: 503 })).mockRejectedValueOnce(new Error("network"))
+ for (let index = 0; index < 2; index++) {
+ await expect(pushMachineStop(FAKE_ENV, "m")).resolves.toEqual({ sent: 0, unsupported: 0, deliveryError: true })
+ }
+ })
+})
+
describe("pushMachineUpdate", () => {
beforeEach(() => {
wsDoFetch.mockReset()
diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.ts
index af3fabf87..c5bf87b7b 100644
--- a/src/web/src/lib/community/bot-push.ts
+++ b/src/web/src/lib/community/bot-push.ts
@@ -20,6 +20,29 @@ export type MachineUpdatePushResult =
| { sent: number; deliveryError: false }
| { sent: 0; deliveryError: true }
+export type MachineStopPushResult =
+ | { sent: number; unsupported: number; deliveryError: false }
+ | { sent: 0; unsupported: 0; deliveryError: true }
+
+export async function pushMachineStop(env: Env, machineId: string): Promise<MachineStopPushResult> {
+ 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 }
+ } catch (err) {
+ log.warn("machine:stop push failed", { machineId, err: String(err) })
+ 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 a713ec0bd..7d12d7628 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -117,6 +117,7 @@ export const tid = {
onboardingStart: "community-onboarding-start",
machineActions: (id: string) => `machine-actions-${id}`,
machineUpdate: (id: string) => `machine-update-${id}`,
+ machineStop: (id: string) => `machine-stop-${id}`,
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 0ca561ccd..86b456575 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -93,6 +93,7 @@ export const apiRoutes = [
"/api/community/machines/[id]/discover-models",
"/api/community/machines/[id]/reconnect",
"/api/community/machines/[id]/reset-agents",
+ "/api/community/machines/[id]/stop",
"/api/community/machines/[id]/update",
"/api/community/machines/pair",
"/api/community/messages/[id]",
diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
index fbe3d0eb8..ab698e7b2 100644
--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
@@ -22,7 +22,7 @@ import {
} from "./_fixtures/scroll-trace"
import { tid } from "./_fixtures/testids"
import { WEB_URL } from "./_setup/paths"
-import { readCommunityDocumentSeedFromHtml } from "./_fixtures/community-ssr-frame"
+import { expectUniqueSsrCommunityFrame, readCommunityDocumentSeedFromHtml } from "./_fixtures/community-ssr-frame"
const VIEWPORT = { width: 1280, height: 800 }
@@ -1514,10 +1514,12 @@ test.describe("message scroll characterization", () => {
event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)
await alice.page.goto(`/c/channels/${serverId}/${splitThreadId}`, { waitUntil: "commit" })
- const split = alice.page.getByTestId(tid.threadSplit)
+ const frame = await expectUniqueSsrCommunityFrame(alice.page)
+ const split = frame.getByTestId(tid.threadSplit)
+ await expect(split).toHaveCount(1)
await expect(split).toHaveAttribute("data-layout", "split", { timeout: 30_000 })
- const parentPanel = alice.page.getByTestId(tid.threadSplitParent)
- const threadPanel = alice.page.getByTestId(tid.threadSplitPanel)
+ const parentPanel = split.getByTestId(tid.threadSplitParent)
+ const threadPanel = split.getByTestId(tid.threadSplitPanel)
const parentSurface = parentPanel.locator('[data-slot="community-conversation-surface"]')
const threadSurface = threadPanel.locator('[data-slot="community-conversation-surface"]')
await expect(parentSurface).toHaveAttribute("data-channel-id", composerChannelId)
diff --git a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
index d19c5a024..2e5e0678c 100644
--- a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
+++ b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
@@ -6,6 +6,7 @@ import { HostCommandSchema } from "@alook/shared/community-cli-contract"
import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "./_setup/paths"
import type { APIResponse, Page, Request, TestInfo } from "@playwright/test"
import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
+import { expectUniqueSsrCommunityFrame } from "./_fixtures/community-ssr-frame"
import { PERSIST_CACHE_PREFIX } from "@/lib/query-persister"
import { expect, test } from "./_fixtures/case-fixture"
@@ -331,20 +332,23 @@ test("a warm DM reload shows qualified RSC identity and history before browser r
])
await expectCacheFirstReload(page, async () => {
- await expect(page.getByTestId(tid.dmRow(dmId))).toBeVisible({ timeout: 10_000 })
- await expect(page.getByTestId(tid.dmHeader)).toBeVisible()
- await expect(page.getByTestId(tid.dmHeader)).toContainText(userName("bob"))
- await expect(page.locator(`main[data-slot="community-conversation-surface"][data-channel-id="${dmId}"]`)).toBeVisible()
- await expect(page.getByTestId(tid.message(messageId))).toBeVisible()
- await expect(page.getByTestId(tid.message(messageId)).getByText(body, { exact: false })).toBeVisible()
- await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ const frame = await expectUniqueSsrCommunityFrame(page)
+ await expect(frame.getByTestId(tid.dmRow(dmId))).toBeVisible({ timeout: 10_000 })
+ await expect(frame.getByTestId(tid.dmHeader)).toBeVisible()
+ await expect(frame.getByTestId(tid.dmHeader)).toContainText(userName("bob"))
+ await expect(frame.locator(`main[data-slot="community-conversation-surface"][data-channel-id="${dmId}"]`)).toBeVisible()
+ await expect(frame.getByTestId(tid.message(messageId))).toBeVisible()
+ await expect(frame.getByTestId(tid.message(messageId)).getByText(body, { exact: false })).toBeVisible()
+ await expect(frame.getByTestId(tid.composerInput)).toBeVisible()
}, async () => {
- await expect(page.getByTestId(tid.dmHeader)).toBeVisible({ timeout: 20_000 })
- await expect(page.getByTestId(tid.message(messageId))).toBeVisible()
- await expect(page.getByTestId(tid.message(messageId)).getByText(body, { exact: false })).toBeVisible()
+ const frame = await expectUniqueSsrCommunityFrame(page)
+ await expect(frame.getByTestId(tid.dmHeader)).toBeVisible({ timeout: 20_000 })
+ await expect(frame.getByTestId(tid.message(messageId))).toBeVisible()
+ await expect(frame.getByTestId(tid.message(messageId)).getByText(body, { exact: false })).toBeVisible()
}, async () => {
- await expect(page.getByTestId(tid.message(messageId))).toBeVisible()
- await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ const frame = await expectUniqueSsrCommunityFrame(page)
+ await expect(frame.getByTestId(tid.message(messageId))).toBeVisible()
+ await expect(frame.getByTestId(tid.composerInput)).toBeVisible()
}, caseResources)
})
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
index 60ec38f64..a78bde484 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -89,7 +89,7 @@ describe("ws-do router", () => {
"handleMachineWake",
"handleMachineDiagnostics",
"handleMachineReset",
- "handleMachineUpdate",
+ "handleMachineLifecycleCommand",
"handleMachineBatchReset",
"handleMachineModelSwitch",
"handleMachineProviderSwitch",
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index 2be6b8a56..39336c0d5 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -15,7 +15,7 @@ import {
handleMachineForceClose,
handleMachineNap,
handleMachineReset,
- handleMachineUpdate,
+ handleMachineLifecycleCommand,
} from "./routes/community-machine-lifecycle"
import {
handleMachineModelSwitch,
@@ -77,7 +77,7 @@ export default {
if (response) return response
response = await handleMachineReset(context)
if (response) return response
- response = await handleMachineUpdate(context)
+ response = await handleMachineLifecycleCommand(context)
if (response) return response
response = await handleMachineBatchReset(context)
if (response) return response
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 e574acad4..011ca34e9 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,40 @@ describe("ws-do router", () => {
handler = undefined as unknown as RouterHandler
})
+ 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", {
+ method: "POST", body: JSON.stringify({ type: "machine:update", command: "ignored" }),
+ })
+
+ it("returns zero when there is no active credential without changing records", async () => {
+ const response = await handler.fetch(stopRequest(), env as any)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ sent: 0, unsupported: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("constructs the stop frame and preserves supported/unsupported socket counts", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ doMock.stubFetch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0 }))
+ .mockResolvedValueOnce(Response.json({ sent: 0, unsupported: 1 }))
+ const response = await handler.fetch(stopRequest(), env as any)
+ expect(await response.json()).toEqual({ sent: 1, unsupported: 1 })
+ for (const [request] of doMock.stubFetch.mock.calls) {
+ expect((request as Request).url).toBe("http://internal/stop")
+ expect(await (request as Request).clone().json()).toEqual({ type: "machine:stop" })
+ }
+ })
+
+ it("does not claim success for malformed receipts or a failed lookup", async () => {
+ mockGetActiveDoNamesForMachine.mockRejectedValueOnce(new Error("D1 unavailable"))
+ expect((await handler.fetch(stopRequest(), env as any)).status).toBe(503)
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a"])
+ doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1 }))
+ expect((await handler.fetch(stopRequest(), env as any)).status).toBe(503)
+ })
+ })
+
describe("POST /community-machine/by-id/:machineId/forward-update", () => {
beforeEach(() => {
mockGetActiveDoNamesForMachine.mockReset().mockResolvedValue([])
diff --git a/src/ws-do/src/routes/community-machine-lifecycle.ts b/src/ws-do/src/routes/community-machine-lifecycle.ts
index 2ddc7439e..b00ca7b21 100644
--- a/src/ws-do/src/routes/community-machine-lifecycle.ts
+++ b/src/ws-do/src/routes/community-machine-lifecycle.ts
@@ -1,33 +1,36 @@
import { queries } from "@alook/shared"
import type { RouterContext } from "../router-context"
-export async function handleMachineUpdate({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
- const forwardUpdate = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-update$/)
- if (!forwardUpdate || request.method !== "POST") return null
+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)$/)
+ if (!route || request.method !== "POST") return null
- const machineId = decodeURIComponent(forwardUpdate[1])
+ const machineId = decodeURIComponent(route[1])
+ const stopping = route[2] === "stop"
+ const command = stopping ? "machine:stop" : "machine:update"
const reqLog = log.child({ traceId, machineId })
- reqLog.debug("forwarding machine:update to machine")
+ reqLog.debug("forwarding machine lifecycle command", { command })
let doNames: string[]
try {
const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ const db = shared.createDb(env.DB)
doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
} catch (err) {
- reqLog.error("failed to resolve machine doNames for update", { err })
+ 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({ sent: 0 })
+ if (doNames.length === 0) return Response.json(stopping ? { sent: 0, unsupported: 0 } : { sent: 0 })
- const frame = JSON.stringify({ type: "machine:update" })
+ const frame = JSON.stringify({ type: command })
let delivered = 0
+ let unsupported = 0
let transientFailure = false
for (const doName of doNames) {
const doId = env.WS_DO.idFromName("community-machine:" + doName)
const stub = env.WS_DO.get(doId)
try {
- const response = await stub.fetch(new Request("http://internal/push", {
+ const response = await stub.fetch(new Request(stopping ? "http://internal/stop" : "http://internal/push", {
method: "POST",
headers: { "content-type": "application/json" },
body: frame,
@@ -36,24 +39,30 @@ export async function handleMachineUpdate({ request, env, url, traceId, log }: R
transientFailure = true
continue
}
- const data = await response.json() as { sent?: unknown }
+ const data: unknown = await response.json()
if (
- typeof data.sent !== "number"
- || !Number.isSafeInteger(data.sent)
- || data.sent < 0
+ typeof data !== "object" || data === null || !("sent" in data)
+ || typeof data.sent !== "number" || !Number.isSafeInteger(data.sent) || data.sent < 0
) {
transientFailure = true
continue
}
+ if (stopping) {
+ if (!("unsupported" in data) || typeof data.unsupported !== "number" || !Number.isSafeInteger(data.unsupported) || data.unsupported < 0) {
+ transientFailure = true
+ continue
+ }
+ unsupported += data.unsupported
+ }
delivered += data.sent
} catch {
transientFailure = true
}
}
if (delivered === 0 && transientFailure) {
- return Response.json({ error: "failed to forward machine update" }, { status: 503 })
+ return Response.json({ error: `failed to forward machine ${stopping ? "stop" : "update"}` }, { status: 503 })
}
- return Response.json({ sent: delivered })
+ return Response.json(stopping ? { 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 aa3f76e53..ca7f2476c 100644
--- a/src/ws-do/src/ws-durable/internal.ts
+++ b/src/ws-do/src/ws-durable/internal.ts
@@ -28,6 +28,7 @@ export type ConnectionState =
userId: string
authenticated: boolean
modelDiscovery?: boolean
+ machineStop?: boolean
controlHeartbeat?: boolean
lastHeartbeatAckAt?: number
pendingHeartbeatNonce?: string
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 18634ef74..2584775e3 100644
--- a/src/ws-do/src/ws-durable/machine-control.test.ts
+++ b/src/ws-do/src/ws-durable/machine-control.test.ts
@@ -55,6 +55,39 @@ describe("WebSocketDurableObject", () => {
beforeEach(() => resetHarness())
afterEach(() => cleanupHarness())
+ describe("machine Stop dispatch", () => {
+ it("sends only to authenticated stop-capable machines without force-closing or clearing state", async () => {
+ const { durable, store, getWebSockets } = createDO()
+ const identity = { userId: "u_1", machineId: "cm_1", credentialHash: "epoch" }
+ store.set("community-machine-identity", identity)
+ const supported = createMockWebSocket()
+ const legacy = createMockWebSocket()
+ const unauthed = createMockWebSocket()
+ const user = createMockWebSocket()
+ supported.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "cm_1", userId: "u_1", machineStop: true })
+ legacy.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "cm_1", userId: "u_1" })
+ unauthed.serializeAttachment({ type: "community-machine", authenticated: false, machineId: "cm_1", userId: "u_1", machineStop: true })
+ user.serializeAttachment({ type: "user", authenticated: true, userId: "u_1" })
+ getWebSockets.mockReturnValue([supported, legacy, unauthed, user])
+ const response = await durable.fetch(new Request("http://internal/stop", { method: "POST" }))
+ expect(await response.json()).toEqual({ sent: 1, unsupported: 1 })
+ expect(supported.send).toHaveBeenCalledWith(JSON.stringify({ type: "machine:stop" }))
+ expect(supported.close).not.toHaveBeenCalled()
+ for (const socket of [legacy, unauthed, user]) expect(socket.send).not.toHaveBeenCalled()
+ expect(store.get("community-machine-identity")).toEqual(identity)
+ })
+
+ it("does not count a thrown send as dispatch success", async () => {
+ const { durable, getWebSockets } = createDO()
+ const socket = createMockWebSocket()
+ socket.serializeAttachment({ type: "community-machine", authenticated: true, machineStop: true })
+ socket.send.mockImplementation(() => { throw new Error("socket closed") })
+ getWebSockets.mockReturnValue([socket])
+ const response = await durable.fetch(new Request("http://internal/stop", { method: "POST" }))
+ expect(await response.json()).toEqual({ sent: 0, unsupported: 0 })
+ })
+ })
+
describe("community-machine — session.error overlay + optimistic clear", () => {
beforeEach(() => {
mockFindCredentialByHash.mockReset()
diff --git a/src/ws-do/src/ws-durable/machine-control.ts b/src/ws-do/src/ws-durable/machine-control.ts
index 952cb2449..7f356ecb3 100644
--- a/src/ws-do/src/ws-durable/machine-control.ts
+++ b/src/ws-do/src/ws-durable/machine-control.ts
@@ -38,10 +38,15 @@ export async function handleMachineControlFetch(
const input = await readBoundedJsonRequest(request, 4096)
const command = RuntimeModelDiscoveryCommandSchema.safeParse(input.ok ? input.value : null)
if (!command.success) return new Response(JSON.stringify({ error: "invalid request" }), { status: 400, headers: { "Content-Type": "application/json" } })
- const { sent, unsupported } = forwardToCommunityMachine(context, JSON.stringify(command.data), true)
+ const { sent, unsupported } = forwardToCommunityMachine(context, JSON.stringify(command.data), "modelDiscovery")
return new Response(JSON.stringify({ sent, unsupported }), { headers: { "Content-Type": "application/json" } })
}
+ 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" } })
+ }
+
if (url.pathname === "/push" && request.method === "POST") {
const body = await request.text()
const sent = forwardToCommunityMachine(context, body).sent
@@ -272,13 +277,13 @@ function rejectCommunityMachine(ws: WebSocket, reason: string): void {
try { ws.close(1008, "Unauthorized") } catch { /* ok */ }
}
-function forwardToCommunityMachine(context: WsDurableContext, message: string, requireModelDiscovery = false): { sent: number; unsupported: number } {
+function forwardToCommunityMachine(context: WsDurableContext, message: string, capability?: "modelDiscovery" | "machineStop"): { sent: number; unsupported: number } {
let sent = 0
let unsupported = 0
for (const ws of context.ctx.getWebSockets()) {
const state = ws.deserializeAttachment() as ConnectionState
if (state?.type === "community-machine" && state.authenticated) {
- if (requireModelDiscovery && !state.modelDiscovery) { unsupported++; continue }
+ if (capability && !state[capability]) { unsupported++; continue }
try {
ws.send(message)
sent++
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index 2831d621b..f405810fc 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -468,6 +468,22 @@ describe("WebSocketDurableObject", () => {
)
})
+ it.each([true, false])("retains the advertised machine Stop support=%s in the socket attachment", async (supported) => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", { userId: "u_1", machineId: "cm_1", credentialHash: "epoch" })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+ mockUpsertMachineByMachineId.mockResolvedValueOnce({
+ machine: { id: "cm_1", hostname: "host", availableRuntimes: [], status: "online", lastSeenAt: "now" },
+ priorLastSeenAt: "before", priorAvailableRuntimes: [], priorDaemonVersion: "0.1.0", priorStatus: "online",
+ })
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "ready", runtimeReport: [], runningAgents: [],
+ capabilities: ["control-heartbeat-v1", ...(supported ? ["machine-stop-v1"] : [])],
+ }))
+ expect(ws._attachment).toMatchObject({ machineStop: supported })
+ })
+
it.each([
["legacy ready", undefined, false],
["heartbeat-capable ready", ["control-heartbeat-v1"], true],
diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.ts
index 6c85d65c1..8c8a45d26 100644
--- a/src/ws-do/src/ws-durable/machine-ready.ts
+++ b/src/ws-do/src/ws-durable/machine-ready.ts
@@ -1,5 +1,6 @@
import {
CONTROL_HEARTBEAT_CAPABILITY,
+ MACHINE_STOP_CAPABILITY,
RUNTIME_MODEL_DISCOVERY_CAPABILITY,
createDb,
HostReadyMessageSchema,
@@ -96,6 +97,7 @@ export async function handleReadyFrame(
...state,
controlHeartbeat,
modelDiscovery: ready.capabilities.includes(RUNTIME_MODEL_DISCOVERY_CAPABILITY),
+ machineStop: ready.capabilities.includes(MACHINE_STOP_CAPABILITY),
...(controlHeartbeat ? { lastHeartbeatAckAt: Date.now() } : {}),
pendingHeartbeatNonce: undefined,
})