Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: multi-workspace token for cli
Gus7841db370c99
diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.tsindex 27b8cd74e..406074460 100644--- a/src/cli/commands/register.ts+++ b/src/cli/commands/register.ts@@ -2,7 +2,7 @@ import { Command } from "commander";import { execSync } from "child_process";import { hostname } from "os";import { APIClient } from "../lib/client.js";-import { saveCLIConfigForProfile } from "../lib/config.js";+import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";import { cmdPrefix } from "../lib/env.js";interface MeResponse {@@ -141,10 +141,20 @@ export function registerCommand(): Command {process.exit(1);}+ // Load existing config to preserve other workspaces+ const existing = loadCLIConfigForProfile(profile);+ const watched = existing.watched_workspaces || [];+ const idx = watched.findIndex((w) => w.id === ws.id);+ if (idx >= 0) {+ watched[idx] = { id: ws.id, name: ws.name, token };+ } else {+ watched.push({ id: ws.id, name: ws.name, token });+ }+saveCLIConfigForProfile(profile, {- token,+ token: "",server_url: serverUrl,- watched_workspaces: [{ id: ws.id, name: ws.name }],+ watched_workspaces: watched,});console.log(`\nRegistered as ${me.email}`);diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.tsindex 38c773cf0..3dafc6366 100644--- a/src/cli/daemon/client.test.ts+++ b/src/cli/daemon/client.test.ts@@ -81,21 +81,41 @@ describe("DaemonClient.poll() with mocked fetch", () => {globalThis.fetch = originalFetch;});- it("sends correct POST body to /api/daemon/tasks/poll", async () => {+ it("sends correct POST body with daemon_id to /api/daemon/tasks/poll", async () => {globalThis.fetch = vi.fn().mockResolvedValue({ok: true,status: 200,json: () => Promise.resolve({ tasks: [] }),});- const client = new DaemonClient("http://localhost:8080", "tok");- await client.poll(["r1", "r2"], 3);+ const client = new DaemonClient("http://localhost:8080");+ await client.poll("tok", "d1", 3);expect(globalThis.fetch).toHaveBeenCalledWith("http://localhost:8080/api/daemon/tasks/poll",expect.objectContaining({method: "POST",- body: JSON.stringify({ runtime_ids: ["r1", "r2"], max_tasks: 3 }),+ body: JSON.stringify({ daemon_id: "d1", max_tasks: 3 }),+ }),+ );+ });++ it("passes token in Authorization header per-call", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ tasks: [] }),+ });++ const client = new DaemonClient("http://localhost:8080");+ await client.poll("my_token_123", "d1", 1);++ expect(globalThis.fetch).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: "Bearer my_token_123",+ }),}),);});@@ -107,8 +127,8 @@ describe("DaemonClient.poll() with mocked fetch", () => {json: () => Promise.resolve(validPollResponse()),});- const client = new DaemonClient("http://localhost:8080", "tok");- const tasks = await client.poll(["r1"], 1);+ const client = new DaemonClient("http://localhost:8080");+ const tasks = await client.poll("tok", "d1", 1);expect(tasks).toHaveLength(1);expect(tasks[0].id).toBe("t1");});@@ -120,8 +140,8 @@ describe("DaemonClient.poll() with mocked fetch", () => {json: () => Promise.resolve({ tasks: [] }),});- const client = new DaemonClient("http://localhost:8080", "tok");- const tasks = await client.poll(["r1"], 1);+ const client = new DaemonClient("http://localhost:8080");+ const tasks = await client.poll("tok", "d1", 1);expect(tasks).toEqual([]);});@@ -132,13 +152,13 @@ describe("DaemonClient.poll() with mocked fetch", () => {json: () => Promise.resolve({ unexpected: "data" }),});- const client = new DaemonClient("http://localhost:8080", "tok");- await expect(client.poll(["r1"], 1)).rejects.toThrow();+ const client = new DaemonClient("http://localhost:8080");+ await expect(client.poll("tok", "d1", 1)).rejects.toThrow();});});// ----------------------------------------------------------------------------// DaemonClient.register() tests (unchanged)+// DaemonClient.register() tests// ---------------------------------------------------------------------------describe("DaemonClient.register() with mocked fetch", () => {@@ -155,8 +175,8 @@ describe("DaemonClient.register() with mocked fetch", () => {json: () => Promise.resolve({ runtimes: [{ id: "rt1" }] }),});- const client = new DaemonClient("http://localhost:8080", "tok");- const resp = await client.register({+ const client = new DaemonClient("http://localhost:8080");+ const resp = await client.register("tok", {workspace_id: "w1",daemon_id: "d1",device_name: "mac",@@ -165,6 +185,62 @@ describe("DaemonClient.register() with mocked fetch", () => {});expect(resp.runtimes[0].id).toBe("rt1");});++ it("passes token in Authorization header", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ runtimes: [{ id: "rt1" }] }),+ });++ const client = new DaemonClient("http://localhost:8080");+ await client.register("my_ws_token", {+ workspace_id: "w1",+ daemon_id: "d1",+ device_name: "mac",+ cli_version: "1.0",+ runtimes: [{ name: "claude", type: "claude", version: "1.0", status: "online" }],+ });++ expect(globalThis.fetch).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: "Bearer my_ws_token",+ }),+ }),+ );+ });+});++// ---------------------------------------------------------------------------+// DaemonClient.deregister() tests+// ---------------------------------------------------------------------------++describe("DaemonClient.deregister() with mocked fetch", () => {+ const originalFetch = globalThis.fetch;++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ it("sends daemon_id in body", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ status: 204,+ });++ const client = new DaemonClient("http://localhost:8080");+ await client.deregister("tok", "d1");++ expect(globalThis.fetch).toHaveBeenCalledWith(+ "http://localhost:8080/api/daemon/deregister",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ daemon_id: "d1" }),+ }),+ );+ });});// ---------------------------------------------------------------------------@@ -173,12 +249,12 @@ describe("DaemonClient.register() with mocked fetch", () => {describe("DaemonClient removed methods", () => {it("does not have heartbeat method", () => {- const client = new DaemonClient("http://localhost:8080", "tok");+ const client = new DaemonClient("http://localhost:8080");expect((client as any).heartbeat).toBeUndefined();});it("does not have claimTask method", () => {- const client = new DaemonClient("http://localhost:8080", "tok");+ const client = new DaemonClient("http://localhost:8080");expect((client as any).claimTask).toBeUndefined();});});diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.tsindex 00ae93a0f..f837c598b 100644--- a/src/cli/daemon/client.ts+++ b/src/cli/daemon/client.ts@@ -7,19 +7,17 @@ import {} from "@alook/shared";export class DaemonClient {- constructor(- private baseURL: string,- private token: string,- ) {}+ constructor(private baseURL: string) {}private async request<T>(method: string,path: string,+ token: string,body?: unknown,): Promise<T> {const headers: Record<string, string> = {"Content-Type": "application/json",- Authorization: `Bearer ${this.token}`,+ Authorization: `Bearer ${token}`,};const res = await fetch(this.baseURL + path, {method,@@ -31,47 +29,53 @@ export class DaemonClient {return res.json();}- async register(body: {- workspace_id: string;- daemon_id: string;- device_name: string;- cli_version: string;- runtimes: {- name: string;- type: string;- version: string;- status: string;- }[];- }): Promise<RegisterResponse> {+ async register(+ token: string,+ body: {+ workspace_id: string;+ daemon_id: string;+ device_name: string;+ cli_version: string;+ runtimes: {+ name: string;+ type: string;+ version: string;+ status: string;+ }[];+ },+ ): Promise<RegisterResponse> {const raw = await this.request<unknown>("POST","/api/daemon/register",+ token,body,);return RegisterResponseSchema.parse(raw);}- deregister(runtimeIds: string[]) {- return this.request("POST", "/api/daemon/deregister", {- runtime_ids: runtimeIds,+ deregister(token: string, daemonId: string) {+ return this.request("POST", "/api/daemon/deregister", token, {+ daemon_id: daemonId,});}- async poll(runtimeIds: string[], maxTasks: number): Promise<TaskApi[]> {+ async poll(token: string, daemonId: string, maxTasks: number): Promise<TaskApi[]> {const raw = await this.request<unknown>("POST","/api/daemon/tasks/poll",- { runtime_ids: runtimeIds, max_tasks: maxTasks },+ token,+ { daemon_id: daemonId, max_tasks: maxTasks },);const resp: PollResponse = PollResponseSchema.parse(raw);return resp.tasks;}- startTask(taskId: string) {- return this.request("POST", `/api/daemon/tasks/${taskId}/start`);+ startTask(token: string, taskId: string) {+ return this.request("POST", `/api/daemon/tasks/${taskId}/start`, token);}completeTask(+ token: string,taskId: string,body: {output: string;@@ -82,17 +86,19 @@ export class DaemonClient {return this.request("POST",`/api/daemon/tasks/${taskId}/complete`,+ token,body,);}- failTask(taskId: string, error: string) {- return this.request("POST", `/api/daemon/tasks/${taskId}/fail`, {+ failTask(token: string, taskId: string, error: string) {+ return this.request("POST", `/api/daemon/tasks/${taskId}/fail`, token, {error,});}reportMessages(+ token: string,taskId: string,messages: {seq: number;@@ -107,6 +113,7 @@ export class DaemonClient {return this.request("POST",`/api/daemon/tasks/${taskId}/messages`,+ token,{ messages },);}diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex b31e6e371..1bff02979 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -48,9 +48,9 @@ vi.mock("./agent/index.js", () => ({vi.mock("../lib/config.js", () => ({loadCLIConfigForProfile: vi.fn(() => ({- token: "al_test_token",+ token: "",server_url: null,- watched_workspaces: [{ id: "ws1", name: "Test WS" }],+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],})),}));@@ -133,6 +133,7 @@ vi.spyOn(globalThis, "clearInterval").mockImplementation(((timer: any) => {}) as any);import { createBackend } from "./agent/index.js";+import { loadCLIConfigForProfile } from "../lib/config.js";import { startDaemon } from "./daemon.js";describe("daemon timeline integration", () => {@@ -250,11 +251,10 @@ describe("daemon timeline integration", () => {// Should have been called for each text messageconst textCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {- // The updater is the third argument, but we check it was called for stepsconst updater = call[2];- const testEntry = { steps: [] as string[], response: null };+ const testEntry = { agent_responses: [] as string[] };updater(testEntry);- return testEntry.steps.length > 0;+ return testEntry.agent_responses.length > 0;});expect(textCalls.length).toBe(2);@@ -277,15 +277,13 @@ describe("daemon timeline integration", () => {const calls = mockUpdateEntry.mock.calls;const lastCall = calls[calls.length - 1];const testEntry = {- steps: [] as string[],- response: null as string | null,+ agent_responses: [] as string[],session_id: null as string | null,pid: process.pid as number | null,status: "running" as string,errmsg: null as string | null,};lastCall[2](testEntry);- expect(testEntry.response).toBe("All done!");expect(testEntry.session_id).toBe("s3");expect(testEntry.pid).toBeNull();expect(testEntry.status).toBe("completed");@@ -311,8 +309,7 @@ describe("daemon timeline integration", () => {const calls = mockUpdateEntry.mock.calls;const lastCall = calls[calls.length - 1];const testEntry = {- steps: [] as string[],- response: null as string | null,+ agent_responses: [] as string[],pid: process.pid as number | null,status: "running" as string,errmsg: null as string | null,@@ -321,7 +318,148 @@ describe("daemon timeline integration", () => {expect(testEntry.pid).toBeNull();expect(testEntry.status).toBe("failed");expect(testEntry.errmsg).toBe("something went wrong");- expect(testEntry.response).toBeNull();+ });++ it("passes workspace token to poll and task API calls", async () => {+ setupTaskClaim();+ setupBackend([], {+ status: "completed",+ output: "Done",+ error: "",+ durationMs: 1000,+ sessionId: "s1",+ });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 50));++ // poll should be called with the workspace token+ expect(mockClientInstance.poll).toHaveBeenCalledWith(+ "al_test_token",+ "d1",+ expect.any(Number),+ );++ // startTask should be called with the workspace token+ expect((mockClientInstance as any).startTask).toHaveBeenCalledWith(+ "al_test_token",+ "t1",+ );++ // completeTask should be called with the workspace token+ expect((mockClientInstance as any).completeTask).toHaveBeenCalledWith(+ "al_test_token",+ "t1",+ expect.any(Object),+ );+ });+});++describe("daemon with multi-workspace config", () => {+ beforeEach(() => {+ signalHandlers.clear();+ intervalTimers.length = 0;+ clearedTimers.length = 0;+ vi.clearAllMocks();+ mockProcessExit.mockImplementation((() => {}) as any);++ // Configure two workspaces+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ token: "",+ server_url: "",+ watched_workspaces: [+ { id: "ws1", name: "Personal", token: "al_tok_ws1" },+ { id: "ws2", name: "Team", token: "al_tok_ws2" },+ ],+ });++ // Register returns different runtime IDs for each workspace+ let registerCall = 0;+ mockClientInstance.register.mockImplementation(async () => {+ registerCall++;+ return { runtimes: [{ id: `rt${registerCall}` }] };+ });+ });++ afterEach(() => {+ for (const t of intervalTimers) realClearInterval(t);+ });++ it("polls each workspace with its own token", async () => {+ mockClientInstance.poll.mockResolvedValue([]);++ await startDaemon();++ // poll should have been called twice — once per workspace+ expect(mockClientInstance.poll).toHaveBeenCalledTimes(2);+ expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws1", "d1", 20);+ expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 20);+ });++ it("registers each workspace with its own token", async () => {+ await startDaemon();++ expect(mockClientInstance.register).toHaveBeenCalledTimes(2);+ expect(mockClientInstance.register).toHaveBeenCalledWith(+ "al_tok_ws1",+ expect.objectContaining({ workspace_id: "ws1" }),+ );+ expect(mockClientInstance.register).toHaveBeenCalledWith(+ "al_tok_ws2",+ expect.objectContaining({ workspace_id: "ws2" }),+ );+ });++ it("concurrency accounting: W1 claims reduce W2 max_tasks", async () => {+ const fakeTask = {+ id: "t1",+ agent_id: "a1",+ runtime_id: "rt1",+ conversation_id: "c1",+ workspace_id: "ws1",+ prompt: "do stuff",+ status: "dispatched",+ priority: 0,+ dispatched_at: null,+ started_at: null,+ completed_at: null,+ created_at: "2026-01-01T00:00:00Z",+ type: "user_dm_message",+ result: null,+ error: null,+ agent: { name: "Agent 1", instructions: "be helpful" },+ };++ // W1 returns 3 tasks, W2 should get remaining (20 - 3 = 17)+ let pollCall = 0;+ mockClientInstance.poll.mockImplementation(async () => {+ pollCall++;+ if (pollCall === 1) return [fakeTask, { ...fakeTask, id: "t2" }, { ...fakeTask, id: "t3" }];+ return [];+ });++ // Mock task handling methods so they don't fail+ (mockClientInstance as any).startTask = vi.fn(async () => ({}));+ (mockClientInstance as any).completeTask = vi.fn(async () => ({}));+ (mockClientInstance as any).failTask = vi.fn(async () => ({}));+ (mockClientInstance as any).reportMessages = vi.fn(async () => ({}));++ const mockBackend = {+ name: "claude",+ execute: vi.fn(() => ({+ pid: 12345,+ messages: (async function* () {})(),+ sessionId: Promise.resolve("s1"),+ result: Promise.resolve({ status: "completed", output: "done", error: "", sessionId: "s1" }),+ })),+ };+ vi.mocked(createBackend).mockReturnValue(mockBackend);++ await startDaemon();+ await new Promise((r) => setTimeout(r, 50));++ // W2 should be called with max_tasks = 20 - 3 = 17+ expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 17);});});@@ -374,4 +512,33 @@ describe("daemon shutdown", () => {// clearInterval should have been called before deregisterexpect(deregisterCalledAt).toBe(1); // clearInterval call happened before deregister});++ it("deregisters each workspace with correct token on shutdown", async () => {+ // Configure two workspaces+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ token: "",+ server_url: "",+ watched_workspaces: [+ { id: "ws1", name: "Personal", token: "al_tok_ws1" },+ { id: "ws2", name: "Team", token: "al_tok_ws2" },+ ],+ });++ let registerCall = 0;+ mockClientInstance.register.mockImplementation(async () => {+ registerCall++;+ return { runtimes: [{ id: `rt${registerCall}` }] };+ });++ await startDaemon();++ // Trigger shutdown+ const shutdownHandler = signalHandlers.get("SIGTERM");+ expect(shutdownHandler).toBeDefined();+ await shutdownHandler!();++ // Should deregister both workspaces with their tokens+ expect(mockClientInstance.deregister).toHaveBeenCalledWith("al_tok_ws1", "d1");+ expect(mockClientInstance.deregister).toHaveBeenCalledWith("al_tok_ws2", "d1");+ });});diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex d8d59d789..4ef8ed18a 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -14,6 +14,7 @@ import { execSync } from "child_process";interface WorkspaceState {workspaceId: string;+ token: string;runtimeIds: string[];}@@ -40,14 +41,6 @@ export async function startDaemon(if (serverUrl) config.serverURL = serverUrl;const cliConfig = loadCLIConfigForProfile(profile);- if (!cliConfig.token) {- log.error(`Not registered. Run '${cmdPrefix()} register' first.`);- process.exit(1);- }- if (cliConfig.server_url) config.serverURL = cliConfig.server_url;-- const client = new DaemonClient(config.serverURL, cliConfig.token);- const health = createHealthServer();const workspaces = cliConfig.watched_workspaces || [];if (workspaces.length === 0) {@@ -55,6 +48,21 @@ export async function startDaemon(process.exit(1);}+ // Validate: each workspace must have its own token+ const hasPerWorkspaceTokens = workspaces.every((ws) => !!ws.token);+ if (!hasPerWorkspaceTokens) {+ log.error(+ `Config uses old format. Run '${cmdPrefix()} register --token <token>' for each workspace to upgrade.`,+ );+ process.exit(1);+ }++ // Use server_url from first workspace's config if available+ if (cliConfig.server_url) config.serverURL = cliConfig.server_url;++ const client = new DaemonClient(config.serverURL);+ const health = createHealthServer();+const providers: { type: string; path: string; version: string }[] = [];for (const [type, path] of [["claude", config.claudePath],@@ -87,7 +95,7 @@ export async function startDaemon(status: "online",}));- const resp = await client.register({+ const resp = await client.register(ws.token, {workspace_id: ws.id,daemon_id: config.daemonId,device_name: config.deviceName,@@ -96,7 +104,7 @@ export async function startDaemon(});const runtimeIds = resp.runtimes.map((r: { id: string }) => r.id);- workspaceStates.push({ workspaceId: ws.id, runtimeIds });+ workspaceStates.push({ workspaceId: ws.id, token: ws.token, runtimeIds });for (let i = 0; i < runtimeIds.length; i++) {runtimeIndex.set(runtimeIds[i], {@@ -115,25 +123,39 @@ export async function startDaemon(const activeTasks = new Set<string>();- const poll = async () => {- const remaining = config.maxConcurrentTasks - activeTasks.size;+ // Staggered per-workspace polling+ const pollCycle = async () => {+ let remaining = config.maxConcurrentTasks - activeTasks.size;if (remaining <= 0) return;- try {- const tasks = await client.poll(allRuntimeIds, remaining);- for (const apiTask of tasks) {- const task = fromApiTask(apiTask);- activeTasks.add(task.id);- handleTask(client, config, runtimeIndex, task)- .catch((e) => log.error("Task error", e))- .finally(() => activeTasks.delete(task.id));+ const N = workspaceStates.length;+ const staggerMs = N > 1 ? Math.floor(config.pollInterval / N) : 0;++ for (let i = 0; i < N; i++) {+ if (remaining <= 0) break;+ const ws = workspaceStates[i];++ if (i > 0 && staggerMs > 0) {+ await new Promise((r) => setTimeout(r, staggerMs));+ }++ try {+ const tasks = await client.poll(ws.token, config.daemonId, remaining);+ for (const apiTask of tasks) {+ const task = fromApiTask(apiTask);+ activeTasks.add(task.id);+ remaining--;+ handleTask(client, config, runtimeIndex, task, ws.token)+ .catch((e) => log.error("Task error", e))+ .finally(() => activeTasks.delete(task.id));+ }+ } catch (e) {+ log.debug("Poll error", e);}- } catch (e) {- log.debug("Poll error", e);}};- const pollTimer = setInterval(poll, config.pollInterval);+ const pollTimer = setInterval(pollCycle, config.pollInterval);const shutdown = async () => {log.info("Shutting down...");@@ -141,7 +163,9 @@ export async function startDaemon(const shutdownMs = Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000;const timeout = setTimeout(() => process.exit(1), shutdownMs);try {- await client.deregister(allRuntimeIds);+ for (const ws of workspaceStates) {+ await client.deregister(ws.token, config.daemonId);+ }} catch {// best-effort deregister}@@ -151,7 +175,7 @@ export async function startDaemon(};process.on("SIGTERM", shutdown);process.on("SIGINT", shutdown);- await poll();+ await pollCycle();}async function handleTask(@@ -159,18 +183,19 @@ async function handleTask(config: DaemonConfig,runtimeIndex: Map<string, RuntimeData>,task: Task,+ token: string,): Promise<void> {log.info(`Task ${task.id} claimed agent=${task.agentId}`);try {- await client.startTask(task.id);+ await client.startTask(token, task.id);} catch (e) {- await client.failTask(task.id, `start failed: ${e}`);+ await client.failTask(token, task.id, `start failed: ${e}`);return;}try {- const result = await runTask(client, config, runtimeIndex, task);+ const result = await runTask(client, config, runtimeIndex, task, token);if (result.status === "completed") {const body: {output: string;@@ -179,14 +204,14 @@ async function handleTask(} = { output: result.comment };if (result.sessionId) body.session_id = result.sessionId;if (result.branchName) body.branch_name = result.branchName;- await client.completeTask(task.id, body);+ await client.completeTask(token, task.id, body);log.info(`Task ${task.id} completed`);} else {- await client.failTask(task.id, result.comment);+ await client.failTask(token, task.id, result.comment);log.warn(`Task ${task.id} failed — ${result.comment}`);}} catch (e) {- await client.failTask(task.id, `${e}`);+ await client.failTask(token, task.id, `${e}`);log.error(`Task ${task.id} error`, e);}}@@ -196,6 +221,7 @@ async function runTask(config: DaemonConfig,runtimeIndex: Map<string, RuntimeData>,task: Task,+ token: string,): Promise<TaskResult> {const runtimeData = runtimeIndex.get(task.runtimeId);if (!runtimeData) throw new Error(`unknown runtime: ${task.runtimeId}`);@@ -257,7 +283,7 @@ async function runTask(if (pendingMessages.length === 0) return;const batch = pendingMessages.splice(0);try {- await client.reportMessages(task.id, batch);+ await client.reportMessages(token, task.id, batch);} catch (e) {log.debug(`Task ${task.id} message report failed`, e);}diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex 456b9dea5..ca935cfd9 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -14,8 +14,7 @@ import type { Task } from "../types.js";export const CANONICAL_FILE = "AGENTS.md";export const SYMLINK_ALIASES = ["CLAUDE.md"];-const SYSTEM_PROMPT = `-## Memory Management+const SYSTEM_PROMPT = `## Memory Management- Your memory directory is ./, don't write ANY EXTERNAL memory file.- Write ESSENTIAL yet SHORT memory to ./memory.md- For SPECIFIC yet LONG rules or pattern, write to experiences/[NAME].md, and add index to ./memory.md for later recall.@@ -35,8 +34,9 @@ SPECIFIC means you think you just need to use it conditionally, long means you n## Context TimelineYou're a working branch of a powerful personal agent in Alook platform.-Your current context is only a fraction of the full picture, the full picture is inside .context_timeline/YYYY-MM-DD.jsonl-Each line is a JSON object with these fields:+Your current context is only a fraction of the full picture.+The full picture is inside \`./.context_timeline/YYYY-MM-DD.jsonl\`+Each line of a timeline JSONL is a JSON object with these fields:- "task_id" — unique task identifier- "session_id" — agent session identifier (null until completion)- "pid" — daemon process ID (present while running, null when done)@@ -46,10 +46,11 @@ Each line is a JSON object with these fields:- "prompt" — what the user asked- "agent_responses" — assistant text outputs during execution- "errmsg" — error message (null unless status is "failed")+those json are sorted by datetime in asc order.## RULES- Read @memory.md(if exists) before your action.-- When you start a new task, read the last ~20 lines of today's timeline to understand what has been asked and done recently.+- When you start a new task, read the last ~10 lines of today's timeline to understand what has been asked and done recently.- if you don't know the current datetime, obtain the current datetime first.- When user ask you something you don't have in your current context, try to read the timeline jsonl files for answer (today or previous days).`;diff --git a/src/cli/lib/config.ts b/src/cli/lib/config.tsindex 3fb320066..9f95cfbca 100644--- a/src/cli/lib/config.ts+++ b/src/cli/lib/config.ts@@ -6,6 +6,7 @@ import { isDev } from "./env.js";interface WatchedWorkspace {id: string;name: string;+ token: string;}interface ProfileConfig {diff --git a/src/shared/schemas.test.ts b/src/shared/schemas.test.tsindex f26d8543c..10b2ffa2f 100644--- a/src/shared/schemas.test.ts+++ b/src/shared/schemas.test.ts@@ -158,22 +158,27 @@ describe("TaskAgentDataApiSchema", () => {// ---------------------------------------------------------------------------describe("PollRequestSchema", () => {- it("rejects empty runtime_ids array", () => {- expect(() => PollRequestSchema.parse({ runtime_ids: [] })).toThrow();+ it("accepts daemon_id and defaults max_tasks to 1", () => {+ const parsed = PollRequestSchema.parse({ daemon_id: "d1" });+ expect(parsed.daemon_id).toBe("d1");+ expect(parsed.max_tasks).toBe(1);});- it("accepts valid array and defaults max_tasks to 1", () => {- const parsed = PollRequestSchema.parse({ runtime_ids: ["r1"] });- expect(parsed.runtime_ids).toEqual(["r1"]);- expect(parsed.max_tasks).toBe(1);+ it("rejects missing daemon_id", () => {+ expect(() => PollRequestSchema.parse({})).toThrow();+ });++ it("rejects empty daemon_id", () => {+ expect(() => PollRequestSchema.parse({ daemon_id: "" })).toThrow();});it("rejects max_tasks: 0", () => {- expect(() => PollRequestSchema.parse({ runtime_ids: ["r1"], max_tasks: 0 })).toThrow();+ expect(() => PollRequestSchema.parse({ daemon_id: "d1", max_tasks: 0 })).toThrow();});- it("rejects array with empty strings", () => {- expect(() => PollRequestSchema.parse({ runtime_ids: [""] })).toThrow();+ it("rejects old-format body with runtime_ids", () => {+ // runtime_ids is no longer recognized — daemon_id is required+ expect(() => PollRequestSchema.parse({ runtime_ids: ["r1"] })).toThrow();});});@@ -255,9 +260,17 @@ describe("DaemonRuntimeItemSchema", () => {// ---------------------------------------------------------------------------describe("DeregisterRequestSchema", () => {- it("requires runtime_ids as a string array", () => {- const parsed = DeregisterRequestSchema.parse({ runtime_ids: ["r1", "r2"] });- expect(parsed.runtime_ids).toEqual(["r1", "r2"]);+ it("accepts daemon_id (string, min 1)", () => {+ const parsed = DeregisterRequestSchema.parse({ daemon_id: "d1" });+ expect(parsed.daemon_id).toBe("d1");+ });++ it("rejects missing daemon_id", () => {+ expect(() => DeregisterRequestSchema.parse({})).toThrow();+ });++ it("rejects empty daemon_id", () => {+ expect(() => DeregisterRequestSchema.parse({ daemon_id: "" })).toThrow();});});diff --git a/src/shared/src/db/queries/runtime.ts b/src/shared/src/db/queries/runtime.tsindex 0b1430411..5c154663b 100644--- a/src/shared/src/db/queries/runtime.ts+++ b/src/shared/src/db/queries/runtime.ts@@ -129,6 +129,23 @@ export async function deleteRuntimesByDaemonId();}+export async function getRuntimeIdsByDaemon(+ db: Database,+ daemonId: string,+ workspaceId: string+) {+ const rows = await db+ .select({ id: agentRuntime.id })+ .from(agentRuntime)+ .where(+ and(+ eq(agentRuntime.daemonId, daemonId),+ eq(agentRuntime.workspaceId, workspaceId)+ )+ );+ return rows.map((r) => r.id);+}+export async function updateRuntimesLastSeen(db: Database,ids: string[],diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex bb3f3859f..025107ef3 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -86,7 +86,7 @@ export type TaskApi = z.infer<typeof TaskApiSchema>;// ---------------------------------------------------------------------------export const PollRequestSchema = z.object({- runtime_ids: z.array(z.string().min(1)).min(1),+ daemon_id: z.string().min(1),max_tasks: z.number().int().min(1).default(1),});export type PollRequest = z.infer<typeof PollRequestSchema>;@@ -143,7 +143,7 @@ export const RegisterDaemonRequestSchema = z.object({export type RegisterDaemonRequest = z.infer<typeof RegisterDaemonRequestSchema>;export const DeregisterRequestSchema = z.object({- runtime_ids: z.array(z.string()).default([]),+ daemon_id: z.string().min(1),});export type DeregisterRequest = z.infer<typeof DeregisterRequestSchema>;diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex fd8992337..90d11cf11 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -147,8 +147,7 @@ export interface CreateAgentRequest {/** WebSocket event types — single source of truth for the WS protocol. */export type WsMessage =| { type: "runtime.registered"; daemonId: string; hostname: string }- | { type: "runtime.status"; runtimeId: string; status: string }- | { type: "runtime.status"; runtimeIds: string[]; status: string }+ | { type: "runtime.status"; daemonId: string; workspaceId: string; status: string }| { type: "runtime.deleted"; daemonId: string }| { type: "task.updated"; taskId: string; status: string }| { type: "email.received"; agentId: string }diff --git a/src/web/src/app/api/daemon/deregister/route.test.ts b/src/web/src/app/api/daemon/deregister/route.test.tsindex ddf07d7aa..b870c1f46 100644--- a/src/web/src/app/api/daemon/deregister/route.test.ts+++ b/src/web/src/app/api/daemon/deregister/route.test.ts@@ -1,8 +1,9 @@import { describe, it, expect, vi, beforeEach } from "vitest";import { NextRequest } from "next/server";-const mockGetAgentRuntimeForWorkspace = vi.fn();+const mockGetRuntimeIdsByDaemon = vi.fn();const mockSetAgentRuntimeOffline = vi.fn();+const mockBroadcastToUser = vi.fn();function sharedMocks() {return {@@ -13,8 +14,8 @@ function sharedMocks() {createDb: vi.fn(() => ({})),queries: {runtime: {- getAgentRuntimeForWorkspace: (...a: any[]) =>- mockGetAgentRuntimeForWorkspace(...a),+ getRuntimeIdsByDaemon: (...a: any[]) =>+ mockGetRuntimeIdsByDaemon(...a),setAgentRuntimeOffline: (...a: any[]) =>mockSetAgentRuntimeOffline(...a),},@@ -25,6 +26,9 @@ function sharedMocks() {"@/lib/logger": {log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },},+ "@/lib/broadcast": {+ broadcastToUser: (...a: any[]) => mockBroadcastToUser(...a),+ },};}@@ -47,6 +51,7 @@ describe("POST /api/daemon/deregister", () => {vi.doMock("@opennextjs/cloudflare", () => mocks["@opennextjs/cloudflare"]);vi.doMock("@alook/shared", mocks["@alook/shared"]);vi.doMock("@/lib/logger", () => mocks["@/lib/logger"]);+ vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);vi.doMock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params =@@ -67,57 +72,60 @@ describe("POST /api/daemon/deregister", () => {const daemonAuth = { userId: "u1", email: "[email protected]", workspaceId: "w1" };const jwtAuth = { userId: "u1", email: "[email protected]" };- it("sets owned runtimes offline", async () => {+ it("sets all runtimes for daemon offline", async () => {const POST = await loadRoute(daemonAuth);- mockGetAgentRuntimeForWorkspace- .mockResolvedValueOnce({ id: "rt1" })- .mockResolvedValueOnce({ id: "rt2" });+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["rt1", "rt2"]);mockSetAgentRuntimeOffline.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);- const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));+ const res = await POST(makeReq({ daemon_id: "d1" }));const body = await res.json();expect(res.status).toBe(200);expect(body).toEqual({ status: "ok" });+ expect(mockGetRuntimeIdsByDaemon).toHaveBeenCalledWith({}, "d1", "w1");expect(mockSetAgentRuntimeOffline).toHaveBeenCalledTimes(2);expect(mockSetAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");expect(mockSetAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt2");});- it("skips unowned runtimes", async () => {+ it("sends single broadcast with daemonId and workspaceId", async () => {const POST = await loadRoute(daemonAuth);- mockGetAgentRuntimeForWorkspace- .mockResolvedValueOnce({ id: "rt1" })- .mockResolvedValueOnce(null); // rt2 not owned+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["rt1", "rt2"]);mockSetAgentRuntimeOffline.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);- const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));- const body = await res.json();+ await POST(makeReq({ daemon_id: "d1" }));- expect(res.status).toBe(200);- expect(body).toEqual({ status: "ok" });- expect(mockSetAgentRuntimeOffline).toHaveBeenCalledTimes(1);- expect(mockSetAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {+ type: "runtime.status",+ daemonId: "d1",+ workspaceId: "w1",+ status: "offline",+ });});- it("returns 200 with empty runtime_ids (no-op)", async () => {+ it("returns 200 with no broadcast when daemon has no runtimes", async () => {const POST = await loadRoute(daemonAuth);- const res = await POST(makeReq({ runtime_ids: [] }));+ mockGetRuntimeIdsByDaemon.mockResolvedValue([]);++ const res = await POST(makeReq({ daemon_id: "d1" }));const body = await res.json();expect(res.status).toBe(200);expect(body).toEqual({ status: "ok" });- expect(mockGetAgentRuntimeForWorkspace).not.toHaveBeenCalled();expect(mockSetAgentRuntimeOffline).not.toHaveBeenCalled();+ expect(mockBroadcastToUser).not.toHaveBeenCalled();});it("returns 403 when called without workspaceId", async () => {const POST = await loadRoute(jwtAuth);- const res = await POST(makeReq({ runtime_ids: ["rt1"] }));+ const res = await POST(makeReq({ daemon_id: "d1" }));const body = await res.json();expect(res.status).toBe(403);@@ -127,14 +135,13 @@ describe("POST /api/daemon/deregister", () => {it("continues processing remaining runtimes after DB error on one", async () => {const POST = await loadRoute(daemonAuth);- mockGetAgentRuntimeForWorkspace- .mockResolvedValueOnce({ id: "rt1" })- .mockResolvedValueOnce({ id: "rt2" });+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["rt1", "rt2"]);mockSetAgentRuntimeOffline.mockRejectedValueOnce(new Error("DB connection lost")).mockResolvedValueOnce(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);- const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));+ const res = await POST(makeReq({ daemon_id: "d1" }));const body = await res.json();expect(res.status).toBe(200);diff --git a/src/web/src/app/api/daemon/deregister/route.ts b/src/web/src/app/api/daemon/deregister/route.tsindex 4a5c5c9f9..79245b5a3 100644--- a/src/web/src/app/api/daemon/deregister/route.ts+++ b/src/web/src/app/api/daemon/deregister/route.ts@@ -18,14 +18,14 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- for (const id of body.runtime_ids) {- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(- db,- id,- ctx.workspaceId- );- if (!runtime) continue;+ // Look up all runtimes by (daemonId, workspaceId)+ const runtimeIds = await queries.runtime.getRuntimeIdsByDaemon(+ db,+ body.daemon_id,+ ctx.workspaceId,+ );+ for (const id of runtimeIds) {try {await queries.runtime.setAgentRuntimeOffline(db, id);} catch (e) {@@ -33,11 +33,15 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}}- broadcastToUser(ctx.userId, {- type: "runtime.status",- runtimeIds: body.runtime_ids,- status: "offline",- }).catch(() => {});+ // Single broadcast at daemon level+ if (runtimeIds.length > 0) {+ broadcastToUser(ctx.userId, {+ type: "runtime.status",+ daemonId: body.daemon_id,+ workspaceId: ctx.workspaceId,+ status: "offline",+ }).catch(() => {});+ }return writeJSON({ status: "ok" });});diff --git a/src/web/src/app/api/daemon/routes.test.ts b/src/web/src/app/api/daemon/routes.test.tsindex e73dd0f7b..082d6d147 100644--- a/src/web/src/app/api/daemon/routes.test.ts+++ b/src/web/src/app/api/daemon/routes.test.ts@@ -241,6 +241,7 @@ describe("daemon route body validation", () => {createDb: vi.fn(() => ({})),queries: {runtime: {+ getRuntimeIdsByDaemon: vi.fn().mockResolvedValue(["r1"]),updateRuntimesLastSeen: vi.fn().mockResolvedValue(["r1"]),},agent: {@@ -264,18 +265,18 @@ describe("daemon route body validation", () => {return (await import("./tasks/poll/route")).POST;}- it("returns 400 when runtime_ids is empty array", async () => {+ it("returns 400 when daemon_id is missing", async () => {const POST = await loadPoll();const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: [] })+ postReq("http://localhost/api/daemon/tasks/poll", {}));expect(res.status).toBe(400);});- it("returns 400 when runtime_ids is missing", async () => {+ it("returns 400 when daemon_id is empty string", async () => {const POST = await loadPoll();const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", {})+ postReq("http://localhost/api/daemon/tasks/poll", { daemon_id: "" }));expect(res.status).toBe(400);});@@ -283,15 +284,15 @@ describe("daemon route body validation", () => {it("returns 400 when max_tasks is 0", async () => {const POST = await loadPoll();const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: ["r1"], max_tasks: 0 })+ postReq("http://localhost/api/daemon/tasks/poll", { daemon_id: "d1", max_tasks: 0 }));expect(res.status).toBe(400);});- it("returns 400 when runtime_ids contains empty strings", async () => {+ it("rejects old-format body with runtime_ids", async () => {const POST = await loadPoll();const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: [""] })+ postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: ["r1"] }));expect(res.status).toBe(400);});@@ -326,21 +327,32 @@ describe("daemon route body validation", () => {createDb: vi.fn(() => ({})),queries: {runtime: {- getAgentRuntimeForWorkspace: vi.fn().mockResolvedValue({ id: "rt1" }),+ getRuntimeIdsByDaemon: vi.fn().mockResolvedValue(["rt1"]),setAgentRuntimeOffline: vi.fn(),},},};});+ vi.doMock("@/lib/broadcast", () => ({+ broadcastToUser: vi.fn().mockResolvedValue(undefined),+ }));return (await import("./deregister/route")).POST;}- it("returns 400 when runtime_ids contains non-strings", async () => {+ it("returns 400 when daemon_id is missing", async () => {+ const POST = await loadDeregister();+ const res = await POST(+ postReq("http://localhost/api/daemon/deregister", {})+ );+ expect(res.status).toBe(400);+ });++ it("returns 400 when daemon_id is empty", async () => {const POST = await loadDeregister();const res = await POST(postReq("http://localhost/api/daemon/deregister", {- runtime_ids: [123, true],+ daemon_id: "",}));expect(res.status).toBe(400);diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsindex 66d505284..e91753823 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest";import { NextRequest } from "next/server";+const mockGetRuntimeIdsByDaemon = vi.fn();const mockUpdateRuntimesLastSeen = vi.fn();const mockGetAgent = vi.fn();const mockClaimTasksForRuntimes = vi.fn();@@ -18,6 +19,7 @@ vi.mock("@alook/shared", async () => {createDb: vi.fn(() => ({})),queries: {runtime: {+ getRuntimeIdsByDaemon: (...args: unknown[]) => mockGetRuntimeIdsByDaemon(...args),updateRuntimesLastSeen: (...args: unknown[]) => mockUpdateRuntimesLastSeen(...args),},agent: {@@ -80,20 +82,33 @@ function postReq(body: unknown) {describe("POST /api/daemon/tasks/poll", () => {beforeEach(() => vi.clearAllMocks());- it("returns empty tasks array when no pending tasks", async () => {- mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);+ it("returns empty tasks array when daemon has no runtimes", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue([]);- const res = await POST(postReq({ runtime_ids: ["r1"] }));+ const res = await POST(postReq({ daemon_id: "d1" }));const body = await res.json();expect(res.status).toBe(200);expect(body.tasks).toEqual([]);+ expect(mockUpdateRuntimesLastSeen).not.toHaveBeenCalled();+ expect(mockBroadcastToUser).not.toHaveBeenCalled();+ });++ it("resolves runtime IDs from daemon_id and updates last_seen_at", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2"]);+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1", "r2"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);++ await POST(postReq({ daemon_id: "d1" }));++ expect(mockGetRuntimeIdsByDaemon).toHaveBeenCalledWith({}, "d1", "w1");+ expect(mockUpdateRuntimesLastSeen).toHaveBeenCalledWith({}, ["r1", "r2"], "w1");});it("returns tasks with agent data for claimed tasks", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2"]);mockUpdateRuntimesLastSeen.mockResolvedValue(["r1", "r2"]);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);@@ -106,7 +121,7 @@ describe("POST /api/daemon/tasks/poll", () => {runtimeConfig: { model: "gpt-4" },});- const res = await POST(postReq({ runtime_ids: ["r1", "r2"], max_tasks: 3 }));+ const res = await POST(postReq({ daemon_id: "d1", max_tasks: 3 }));const body = await res.json();expect(res.status).toBe(200);@@ -119,65 +134,74 @@ describe("POST /api/daemon/tasks/poll", () => {});});- it("updates last_seen_at for all runtimes", async () => {- mockUpdateRuntimesLastSeen.mockResolvedValue(["r1", "r2"]);+ it("broadcasts single runtime.status with daemonId and workspaceId", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2", "r3"]);+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1", "r2", "r3"]);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);- await POST(postReq({ runtime_ids: ["r1", "r2"] }));-- expect(mockUpdateRuntimesLastSeen).toHaveBeenCalledWith({}, ["r1", "r2"], "w1");- });-- it("broadcasts runtime.status only for verified runtime IDs", async () => {- mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]); // only r1 verified- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- await POST(postReq({ runtime_ids: ["r1", "r2"] }));+ await POST(postReq({ daemon_id: "d1" }));+ // Single broadcast, not per-runtimeexpect(mockBroadcastToUser).toHaveBeenCalledTimes(1);expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {type: "runtime.status",- runtimeId: "r1",+ daemonId: "d1",+ workspaceId: "w1",status: "online",});});it("calls sweepStaleState", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);- await POST(postReq({ runtime_ids: ["r1"] }));+ await POST(postReq({ daemon_id: "d1" }));expect(mockSweepStaleState).toHaveBeenCalledWith({}, "w1");});- // 403 without workspaceId is covered in routes.test.ts (cross-route validation suite)-it("respects max_tasks parameter", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);- await POST(postReq({ runtime_ids: ["r1"], max_tasks: 5 }));+ await POST(postReq({ daemon_id: "d1", max_tasks: 5 }));expect(mockClaimTasksForRuntimes).toHaveBeenCalledWith(["r1"], 5, "w1");});it("defaults max_tasks to 1", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);- await POST(postReq({ runtime_ids: ["r1"] }));+ await POST(postReq({ daemon_id: "d1" }));expect(mockClaimTasksForRuntimes).toHaveBeenCalledWith(["r1"], 1, "w1");});++ it("logs warning when some runtimes not found", async () => {+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2"]);+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]); // only 1 of 2 found+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);++ await POST(postReq({ daemon_id: "d1" }));++ const { log } = await import("@/lib/logger");+ expect(log.warn).toHaveBeenCalledWith("Some runtime IDs not found in workspace", {+ expected: 2,+ updated: 1,+ });+ });});diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex f564fda7c..59a9c6add 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -20,38 +20,48 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- // 1. Liveness: bulk-update last_seen_at for all runtime IDs+ // 1. Resolve runtime IDs from daemon_id + workspaceId+ const runtimeIds = await queries.runtime.getRuntimeIdsByDaemon(+ db,+ body.daemon_id,+ ctx.workspaceId,+ );++ if (runtimeIds.length === 0) {+ return writeJSON({ tasks: [] });+ }++ // 2. Liveness: bulk-update last_seen_at for all runtime IDsconst updatedIds = await queries.runtime.updateRuntimesLastSeen(db,- body.runtime_ids,- ctx.workspaceId+ runtimeIds,+ ctx.workspaceId,);- if (updatedIds.length < body.runtime_ids.length) {+ if (updatedIds.length < runtimeIds.length) {log.warn("Some runtime IDs not found in workspace", {- expected: body.runtime_ids.length,+ expected: runtimeIds.length,updated: updatedIds.length,});}- // Broadcast runtime status only for verified IDs- for (const rid of updatedIds) {- broadcastToUser(ctx.userId, {- type: "runtime.status",- runtimeId: rid,- status: "online",- }).catch(() => {});- }+ // Single broadcast at daemon level+ broadcastToUser(ctx.userId, {+ type: "runtime.status",+ daemonId: body.daemon_id,+ workspaceId: ctx.workspaceId,+ status: "online",+ }).catch(() => {});- // 2. Housekeeping: sweep stale state+ // 3. Housekeeping: sweep stale stateawait sweepStaleState(db, ctx.workspaceId);- // 3. Task claiming+ // 4. Task claimingconst taskService = new TaskService(db);const claimed = await taskService.claimTasksForRuntimes(- body.runtime_ids,+ runtimeIds,body.max_tasks,- ctx.workspaceId!+ ctx.workspaceId!,);const tasks = [];diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsxindex 752b28c0f..81dafae62 100644--- a/src/web/src/contexts/agent-context.tsx+++ b/src/web/src/contexts/agent-context.tsx@@ -92,6 +92,23 @@ export function AgentProvider({reload();}, [reload]);+ // Debounced reload for runtime.status events+ const statusDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const debouncedReload = useCallback(() => {+ if (statusDebounceRef.current) clearTimeout(statusDebounceRef.current);+ statusDebounceRef.current = setTimeout(() => {+ statusDebounceRef.current = null;+ reload();+ }, 300);+ }, [reload]);++ // Cleanup debounce timer on unmount+ useEffect(() => {+ return () => {+ if (statusDebounceRef.current) clearTimeout(statusDebounceRef.current);+ };+ }, []);+// Listen for real-time WS eventsconst handleWsMessage = useCallback((msg: WsMessage) => {@@ -101,13 +118,17 @@ export function AgentProvider({// AgentProvider only reloads agents/runtimes for runtime eventsswitch (msg.type) {case "runtime.registered":- case "runtime.status":case "runtime.deleted":reload();break;+ case "runtime.status":+ // Filter by workspaceId — ignore messages from other workspaces+ if (msg.workspaceId !== workspaceId) break;+ debouncedReload();+ break;}},- [reload]+ [reload, debouncedReload, workspaceId]);useUserWs(handleWsMessage);diff --git a/src/web/src/test/e2e/daemon-lifecycle.test.ts b/src/web/src/test/e2e/daemon-lifecycle.test.tsindex ecb3b7422..02fc3bef0 100644--- a/src/web/src/test/e2e/daemon-lifecycle.test.ts+++ b/src/web/src/test/e2e/daemon-lifecycle.test.ts@@ -72,7 +72,7 @@ describe("daemon lifecycle", () => {const res = await tokenRequest("/api/daemon/tasks/poll", seed.machineToken, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ runtime_ids: [registeredRuntimeId] }),+ body: JSON.stringify({ daemon_id: daemonId }),})expect(res.status).toBe(200)const data = await res.json() as { tasks: unknown[] }@@ -90,7 +90,7 @@ describe("daemon lifecycle", () => {const res = await fetch(`${APP_URL}/api/daemon/tasks/poll`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ runtime_ids: [registeredRuntimeId] }),+ body: JSON.stringify({ daemon_id: daemonId }),})expect(res.status).toBe(401)})@@ -99,7 +99,7 @@ describe("daemon lifecycle", () => {const res = await tokenRequest("/api/daemon/deregister", seed.machineToken, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ runtime_ids: [registeredRuntimeId] }),+ body: JSON.stringify({ daemon_id: daemonId }),})expect(res.status).toBe(200)diff --git a/src/web/src/test/e2e/task-lifecycle.test.ts b/src/web/src/test/e2e/task-lifecycle.test.tsindex d28fa4b62..b50cee260 100644--- a/src/web/src/test/e2e/task-lifecycle.test.ts+++ b/src/web/src/test/e2e/task-lifecycle.test.ts@@ -52,7 +52,7 @@ describe("task lifecycle", () => {{method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ runtime_ids: [seed.runtimeId], max_tasks: 1 }),+ body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),},)expect(res.status).toBe(200)@@ -151,7 +151,7 @@ describe("task lifecycle", () => {{method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ runtime_ids: [seed.runtimeId], max_tasks: 1 }),+ body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),},)expect(res.status).toBe(200)@@ -197,7 +197,7 @@ describe("task failure", () => {{method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ runtime_ids: [seed.runtimeId], max_tasks: 1 }),+ body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),},)await tokenRequest(diff --git a/src/web/src/test/helpers/seed.ts b/src/web/src/test/helpers/seed.tsindex b3c468251..254e330b0 100644--- a/src/web/src/test/helpers/seed.ts+++ b/src/web/src/test/helpers/seed.ts@@ -6,6 +6,7 @@ export interface TestSeed {workspaceId: stringmemberId: stringruntimeId: string+ daemonId: stringagentId: string/** Raw machine token (starts with al_) */machineToken: string@@ -26,6 +27,7 @@ export function seedTestData(): TestSeed {const memberId = `mb_${nanoid()}`const runtimeId = `rt_${nanoid()}`const agentId = `ag_${nanoid()}`+ const daemonId = `daemon_${nanoid()}`const machineTokenId = `mt_${nanoid()}`const rawToken = `al_${randomUUID().replace(/-/g, "")}`@@ -35,11 +37,11 @@ export function seedTestData(): TestSeed {sql(`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES ('${userId}', 'Test User', '${userId}@test.local', 1, '${now}', '${now}')`)sql(`INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES ('${workspaceId}', 'Test Workspace', '${slug}', '${now}', '${now}')`)sql(`INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES ('${memberId}', '${workspaceId}', '${userId}', 'owner', '${now}')`)- sql(`INSERT INTO agent_runtime (id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES ('${runtimeId}', '${workspaceId}', 'daemon_${nanoid()}', 'Test Runtime', 'local', 'claude', 'online', 'test-device', '${now}', '${now}')`)+ sql(`INSERT INTO agent_runtime (id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES ('${runtimeId}', '${workspaceId}', '${daemonId}', 'Test Runtime', 'local', 'claude', 'online', 'test-device', '${now}', '${now}')`)sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, created_at, updated_at) VALUES ('${agentId}', '${workspaceId}', 'Test Agent', '${runtimeId}', '${now}', '${now}')`)sql(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${machineTokenId}', '${userId}', '${workspaceId}', '${rawToken}', 'test-token', 'active', '${now}')`)- return { userId, workspaceId, memberId, runtimeId, agentId, machineToken: rawToken, machineTokenId }+ return { userId, workspaceId, memberId, runtimeId, daemonId, agentId, machineToken: rawToken, machineTokenId }}/**diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex 4bd47d8d4..358aa75e5 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -23,7 +23,7 @@ describe("ws-do router", () => {doMock.stubFetch.mockResolvedValue(new Response("ok"))const req = new Request("http://localhost/broadcast/user/user-123", {method: "POST",- body: JSON.stringify({ type: "runtime.status", runtimeId: "r1", status: "online" }),+ body: JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }),})const res = await handler.fetch(req, env as any)diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex 72b2a6bef..40f278587 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -147,14 +147,14 @@ describe("WebSocketDurableObject", () => {const req = new Request("http://internal/broadcast", {method: "POST",- body: JSON.stringify({ type: "runtime.status", runtimeId: "r1", status: "online" }),+ body: JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }),})const res = await durable.fetch(req)expect(res.status).toBe(200)expect(wsAuth.send).toHaveBeenCalledWith(- JSON.stringify({ type: "runtime.status", runtimeId: "r1", status: "online" })+ JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }))expect(wsUnauth.send).not.toHaveBeenCalled()})