Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: simplify polling and heartbeat

Gus3b673acebfde
diff --git a/.env.example b/.env.example
index e38088474..4f7213712 100644
--- a/.env.example
+++ b/.env.example
@@ -74,9 +74,6 @@
# How often the daemon polls for new tasks (duration string: e.g. 3s, 500ms)
# ALOOK_DAEMON_POLL_INTERVAL=3s
-# How often the daemon sends heartbeats to the server
-# ALOOK_DAEMON_HEARTBEAT_INTERVAL=15s
-
# Maximum time a single agent task can run before being killed
# ALOOK_AGENT_TIMEOUT=2h
@@ -104,10 +101,10 @@
# =============================================================================
# Used by both web and CLI for real-time status tracking.
-# Client-side heartbeat interval (ms)
-# HEARTBEAT_INTERVAL_MS=3000
+# Client-side poll interval (ms)
+# POLL_INTERVAL_MS=3000
-# Time (ms) without heartbeat before a runtime is considered offline
+# Time (ms) without liveness update before a runtime is considered offline
# OFFLINE_THRESHOLD_MS=9000
# How often the web UI polls for new events (ms)
diff --git a/AGENTS.md b/AGENTS.md
index 0bc473bda..3cfa4f2b9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -11,7 +11,8 @@ Alook's main purpose is to make the cli agent always on, and give it a email add
## MUST
- run `pnpm typecheck`, `pnpm test`, `pnpm test:e2e` as the final check when you think the code is ready.
-
+- service must be STATELESS! All the state must be in DB or local, never put important states in memory.
+- scope the queries before, not check the ownership after. don't query data then check if the data belongs to a workspace, use workspace id ahead to query the data.
## Plan-driven Development
- You must make a markdown plan at `plans/` before you implement any my request, otherwise I will reject your implementation.
@@ -21,7 +22,7 @@ Alook's main purpose is to make the cli agent always on, and give it a email add
- A plan should at least contain `features`/`show case`, `designs overview`, `new deps`, `TODOS`, sections.
- always use the features/show case to present what you're going to build.
- in `new deps` section, you must list all the new external dependencies that will be added.
- - use checklist in `TODOS` section, for each checkbox, you must have a clear descripion of what to do and list all the files that will be modified.
+ - use checklist in `TODOS` section, for each checkbox, you must have a clear description of what to do and list all the files that will be modified.
- at the end of TODOS, you must include `test cases` sub section, use checklist format to list all the test cases that should be covered.
## Always WRITE/RUN TESTS!
diff --git a/DESIGN.md b/DESIGN.md
index bec40e711..6e2f52b32 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -13,7 +13,7 @@ Emotional goals: confidence, calm focus, quiet delight in small details.
### Aesthetic Direction
**Visual tone**: Notion-inspired warmth meets developer-tool precision. Soft neutral palette (warm grays, cream tints) with crisp typography and intentional micro-interactions. Light and airy in light mode, cozy and focused in dark mode.
-**References**: Notion (polished, warm, delightful micro-interactions)
+**References**: Notion (polished, warm, delightful micro-interactions), vintage Macintosh product photography (warm object on cool ground, generous negative space, matte textures)
**Anti-references**:
- Generic SaaS dashboards (blue buttons, card grids, cookie-cutter layouts)
@@ -42,6 +42,18 @@ Never show all options at once. Complexity exists but stays one interaction away
- **Click to expand** — sidebar tree nodes, dropdown menus, and kanban column options are collapsed by default. Expanded state is driven by user action, not by default.
- **Scrolling reveals depth** — additional features and settings appear as the user scrolls or explores. The first screen is always clean.
+## Color & Texture Philosophy
+
+Inspired by vintage Macintosh product photography — a warm cream object on a dusty periwinkle ground, matte textures, even lighting, and nothing competing for attention.
+
+### Lessons
+
+- **Temperature contrast over color variety** — One warm tone (cream/beige) against one cool tone (muted blue) creates more visual interest than five harmonious colors. Limit the palette, let temperature do the work.
+- **Desaturated > saturated** — Dusty, powdery, slightly muted tones feel confident and timeless. Fully saturated colors feel loud and cheap. When picking any accent, pull it 20-30% toward gray.
+- **Matte everything** — Avoid glossy effects, specular highlights, and glass-morphism. Matte surfaces feel tactile, calm, and honest. Shadows should be soft and diffuse, never sharp or dramatic.
+- **Generous negative space is the luxury** — One element with room to breathe feels more expensive than ten elements packed together. When in doubt, add space, not content.
+- **Nostalgia as warmth, not kitsch** — Reference the feeling of early personal computing (optimism, simplicity, human scale) without literal retro styling. Warm tints and rounded-but-not-bubbly shapes evoke this without cosplaying the past.
+
## Visual Harmony
Every pixel should reduce mental load, not add it. Whitespace, typography, and hierarchy aren't cosmetic — they're how brains process information.
diff --git a/README.md b/README.md
index 54cf7c753..539c8cfeb 100644
--- a/README.md
+++ b/README.md
@@ -111,4 +111,4 @@ pnpm dev:send <from> <to> [subject] [body] # simulate inbound email
**Task execution:** CLI receives event -> creates task record -> runs Claude/Codex agent with prompt -> streams output chunks to API -> marks complete -> dashboard updates in real time
-**Runtime registration:** CLI `register <token>` -> detects local runtimes (claude, codex) -> registers with Web API -> starts daemon (heartbeat, polling)
+**Runtime registration:** CLI `register <token>` -> detects local runtimes (claude, codex) -> registers with Web API -> starts daemon (polling)
diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.ts
index f93d737b4..38c773cf0 100644
--- a/src/cli/daemon/client.test.ts
+++ b/src/cli/daemon/client.test.ts
@@ -1,17 +1,17 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { describe, it, expect, vi, afterEach } from "vitest";
import { fromApiTask } from "./types.js";
import type { TaskApi } from "@alook/shared";
-import { ClaimTaskResponseSchema } from "@alook/shared";
+import { PollResponseSchema } from "@alook/shared";
import { DaemonClient } from "./client.js";
// ---------------------------------------------------------------------------
-// Schema-level validation tests (existing)
+// Schema-level validation tests
// ---------------------------------------------------------------------------
-describe("DaemonClient claimTask schema validation", () => {
- it("parses valid response correctly", () => {
+describe("PollResponseSchema validation", () => {
+ it("parses valid response with tasks", () => {
const raw = {
- task: {
+ tasks: [{
id: "t1",
agent_id: "a1",
runtime_id: "r1",
@@ -28,33 +28,33 @@ describe("DaemonClient claimTask schema validation", () => {
created_at: "2024-01-01T00:00:00Z",
type: "user_dm_message",
agent: { instructions: "help", name: "bot", runtime_config: {} },
- },
+ }],
};
- const parsed = ClaimTaskResponseSchema.parse(raw);
- expect(parsed.task?.id).toBe("t1");
- expect(parsed.task?.agent?.name).toBe("bot");
+ const parsed = PollResponseSchema.parse(raw);
+ expect(parsed.tasks).toHaveLength(1);
+ expect(parsed.tasks[0].id).toBe("t1");
+ expect(parsed.tasks[0].agent?.name).toBe("bot");
});
- it("throws ZodError when response is missing required fields", () => {
- const raw = {
- task: {
- id: "t1",
- // missing agent_id, runtime_id, etc.
- },
- };
+ it("parses empty tasks array", () => {
+ const parsed = PollResponseSchema.parse({ tasks: [] });
+ expect(parsed.tasks).toEqual([]);
+ });
- expect(() => ClaimTaskResponseSchema.parse(raw)).toThrow();
+ it("throws ZodError when tasks contains invalid items", () => {
+ const raw = { tasks: [{ id: "t1" }] }; // missing required fields
+ expect(() => PollResponseSchema.parse(raw)).toThrow();
});
});
// ---------------------------------------------------------------------------
-// DaemonClient integration tests with mocked fetch
+// DaemonClient.poll() integration tests with mocked fetch
// ---------------------------------------------------------------------------
-function validClaimResponse() {
+function validPollResponse() {
return {
- task: {
+ tasks: [{
id: "t1",
agent_id: "a1",
runtime_id: "r1",
@@ -70,54 +70,77 @@ function validClaimResponse() {
error: null,
created_at: "2024-01-01T00:00:00Z",
type: "user_dm_message",
- },
+ }],
};
}
-describe("DaemonClient.claimTask() with mocked fetch", () => {
+describe("DaemonClient.poll() with mocked fetch", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
- it("returns parsed ClaimTaskResponse on valid response", async () => {
+ it("sends correct POST body 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);
+
+ 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 }),
+ }),
+ );
+ });
+
+ it("returns TaskApi[] on valid response", async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
- json: () => Promise.resolve(validClaimResponse()),
+ json: () => Promise.resolve(validPollResponse()),
});
const client = new DaemonClient("http://localhost:8080", "tok");
- const resp = await client.claimTask("r1");
- expect(resp.task?.id).toBe("t1");
- expect(resp.task?.agent_id).toBe("a1");
+ const tasks = await client.poll(["r1"], 1);
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0].id).toBe("t1");
});
- it("throws ZodError when API returns response with wrong shape", async () => {
+ it("returns empty array when no tasks", async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
- json: () => Promise.resolve({ task: { id: "t1" } }), // missing required fields
+ json: () => Promise.resolve({ tasks: [] }),
});
const client = new DaemonClient("http://localhost:8080", "tok");
- await expect(client.claimTask("r1")).rejects.toThrow();
+ const tasks = await client.poll(["r1"], 1);
+ expect(tasks).toEqual([]);
});
- it("returns { task: null } when no task available", async () => {
+ it("throws ZodError when API returns wrong shape", async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
- json: () => Promise.resolve({ task: null }),
+ json: () => Promise.resolve({ unexpected: "data" }),
});
const client = new DaemonClient("http://localhost:8080", "tok");
- const resp = await client.claimTask("r1");
- expect(resp.task).toBeNull();
+ await expect(client.poll(["r1"], 1)).rejects.toThrow();
});
});
+// ---------------------------------------------------------------------------
+// DaemonClient.register() tests (unchanged)
+// ---------------------------------------------------------------------------
+
describe("DaemonClient.register() with mocked fetch", () => {
const originalFetch = globalThis.fetch;
@@ -142,29 +165,26 @@ describe("DaemonClient.register() with mocked fetch", () => {
});
expect(resp.runtimes[0].id).toBe("rt1");
});
+});
- it("throws ZodError when API returns unexpected shape", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ unexpected: "data" }),
- });
+// ---------------------------------------------------------------------------
+// DaemonClient has no heartbeat() or claimTask() methods
+// ---------------------------------------------------------------------------
+describe("DaemonClient removed methods", () => {
+ it("does not have heartbeat method", () => {
const client = new DaemonClient("http://localhost:8080", "tok");
- await expect(
- client.register({
- workspace_id: "w1",
- daemon_id: "d1",
- device_name: "mac",
- cli_version: "1.0",
- runtimes: [{ name: "claude", type: "claude", version: "1.0", status: "online" }],
- }),
- ).rejects.toThrow();
+ expect((client as any).heartbeat).toBeUndefined();
+ });
+
+ it("does not have claimTask method", () => {
+ const client = new DaemonClient("http://localhost:8080", "tok");
+ expect((client as any).claimTask).toBeUndefined();
});
});
// ---------------------------------------------------------------------------
-// fromApiTask tests
+// fromApiTask tests (unchanged)
// ---------------------------------------------------------------------------
function validApiTask(): TaskApi {
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
index 61f2a17c8..00ae93a0f 100644
--- a/src/cli/daemon/client.ts
+++ b/src/cli/daemon/client.ts
@@ -1,8 +1,9 @@
import {
- ClaimTaskResponseSchema,
+ PollResponseSchema,
RegisterResponseSchema,
- type ClaimTaskResponse,
+ type PollResponse,
type RegisterResponse,
+ type TaskApi,
} from "@alook/shared";
export class DaemonClient {
@@ -56,18 +57,14 @@ export class DaemonClient {
});
}
- heartbeat(runtimeId: string) {
- return this.request("POST", "/api/daemon/heartbeat", {
- runtime_id: runtimeId,
- });
- }
-
- async claimTask(runtimeId: string): Promise<ClaimTaskResponse> {
+ async poll(runtimeIds: string[], maxTasks: number): Promise<TaskApi[]> {
const raw = await this.request<unknown>(
"POST",
- `/api/daemon/runtimes/${runtimeId}/tasks/claim`,
+ "/api/daemon/tasks/poll",
+ { runtime_ids: runtimeIds, max_tasks: maxTasks },
);
- return ClaimTaskResponseSchema.parse(raw);
+ const resp: PollResponse = PollResponseSchema.parse(raw);
+ return resp.tasks;
}
startTask(taskId: string) {
diff --git a/src/cli/daemon/config.test.ts b/src/cli/daemon/config.test.ts
index f218cc62f..c983416a3 100644
--- a/src/cli/daemon/config.test.ts
+++ b/src/cli/daemon/config.test.ts
@@ -8,7 +8,6 @@ const DAEMON_ENV_KEYS = [
"ALOOK_SERVER_URL",
"ALOOK_PROJECT_ROOT",
"ALOOK_DAEMON_POLL_INTERVAL",
- "ALOOK_DAEMON_HEARTBEAT_INTERVAL",
"ALOOK_AGENT_TIMEOUT",
"ALOOK_DAEMON_MAX_CONCURRENT_TASKS",
"ALOOK_CLAUDE_PATH",
@@ -36,7 +35,6 @@ describe("loadDaemonConfig defaults", () => {
expect(cfg.serverURL).toBe("https://alook.ai");
expect(cfg.pollInterval).toBe(3000);
- expect(cfg.heartbeatInterval).toBe(15000);
expect(cfg.agentTimeout).toBe(7200000);
expect(cfg.maxConcurrentTasks).toBe(20);
expect(cfg.claudePath).toBe("claude");
diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.ts
index 56ad1943d..8bc3825d1 100644
--- a/src/cli/daemon/config.ts
+++ b/src/cli/daemon/config.ts
@@ -43,7 +43,6 @@ export interface DaemonConfig {
codexModel: string;
opencodeModel: string;
pollInterval: number;
- heartbeatInterval: number;
agentTimeout: number;
maxConcurrentTasks: number;
daemonId: string;
@@ -80,9 +79,6 @@ export function loadDaemonConfig(profile?: string): DaemonConfig {
pollInterval: parseDuration(
process.env.ALOOK_DAEMON_POLL_INTERVAL || "3s",
),
- heartbeatInterval: parseDuration(
- process.env.ALOOK_DAEMON_HEARTBEAT_INTERVAL || "15s",
- ),
agentTimeout: parseDuration(process.env.ALOOK_AGENT_TIMEOUT || "2h"),
maxConcurrentTasks: parseInt(
process.env.ALOOK_DAEMON_MAX_CONCURRENT_TASKS || "20",
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index e7ccc3ea2..b31e6e371 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -5,9 +5,8 @@ const mockClientInstance = {
register: vi.fn(async () => ({
runtimes: [{ id: "rt1" }],
})),
- heartbeat: vi.fn(async () => {}),
deregister: vi.fn(async () => {}),
- claimTask: vi.fn(async () => ({ task: null })),
+ poll: vi.fn(async () => []),
};
vi.mock("./client.js", () => {
function MockDaemonClient() { return mockClientInstance; }
@@ -24,7 +23,6 @@ vi.mock("./config.js", () => ({
codexModel: "",
opencodeModel: "",
pollInterval: 3000,
- heartbeatInterval: 15000,
agentTimeout: 7200000,
maxConcurrentTasks: 20,
daemonId: "d1",
@@ -171,12 +169,12 @@ describe("daemon timeline integration", () => {
};
let claimed = false;
- mockClientInstance.claimTask.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation(async () => {
if (!claimed) {
claimed = true;
- return { task: fakeTask };
+ return [fakeTask];
}
- return { task: null };
+ return [];
});
// Mock startTask and completeTask
@@ -342,13 +340,12 @@ describe("daemon shutdown", () => {
for (const t of intervalTimers) realClearInterval(t);
});
- it("clears heartbeat and poll intervals before calling deregister", async () => {
+ it("clears poll interval before calling deregister", async () => {
await startDaemon();
- // startDaemon should have created 2 intervals (heartbeat + poll)
- expect(intervalTimers.length).toBe(2);
- const heartbeatTimer = intervalTimers[0];
- const pollTimer = intervalTimers[1];
+ // startDaemon should have created 1 interval (poll only, no heartbeat)
+ expect(intervalTimers.length).toBe(1);
+ const pollTimer = intervalTimers[0];
const deregisterMock = mockClientInstance.deregister;
@@ -371,11 +368,10 @@ describe("daemon shutdown", () => {
expect(shutdownHandler).toBeDefined();
await shutdownHandler!();
- // Both intervals should have been cleared
- expect(clearedTimers).toContain(heartbeatTimer);
+ // Poll interval should have been cleared
expect(clearedTimers).toContain(pollTimer);
// clearInterval should have been called before deregister
- expect(deregisterCalledAt).toBe(2); // both clearInterval calls happened before deregister
+ expect(deregisterCalledAt).toBe(1); // clearInterval call happened before deregister
});
});
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 55e778489..ebc012587 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -116,40 +116,27 @@ export async function startDaemon(
const activeTasks = new Set<string>();
const poll = async () => {
- if (activeTasks.size >= config.maxConcurrentTasks) return;
-
- for (const rid of allRuntimeIds) {
- if (activeTasks.size >= config.maxConcurrentTasks) break;
-
- try {
- const resp = await client.claimTask(rid);
- if (resp.task) {
- const task = fromApiTask(resp.task);
- activeTasks.add(task.id);
- handleTask(client, config, runtimeIndex, task)
- .catch((e) => log.error("Task error", e))
- .finally(() => activeTasks.delete(task.id));
- }
- } catch (e) {
- log.debug("Poll error", e);
+ const 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));
}
+ } catch (e) {
+ log.debug("Poll error", e);
}
};
- const heartbeatTimer = setInterval(async () => {
- for (const rid of allRuntimeIds) {
- try {
- await client.heartbeat(rid);
- } catch (e) {
- log.debug("Heartbeat failed", e);
- }
- }
- }, config.heartbeatInterval);
const pollTimer = setInterval(poll, config.pollInterval);
const shutdown = async () => {
log.info("Shutting down...");
- clearInterval(heartbeatTimer);
clearInterval(pollTimer);
const shutdownMs = Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000;
const timeout = setTimeout(() => process.exit(1), shutdownMs);
diff --git a/src/shared/constants.ts b/src/shared/constants.ts
index 3ed192a35..38bd8e9d0 100644
--- a/src/shared/constants.ts
+++ b/src/shared/constants.ts
@@ -32,3 +32,14 @@ export const MessageRole = {
} as const;
export type MessageRoleType = (typeof MessageRole)[keyof typeof MessageRole];
+
+// Timing constants
+export const POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS) || 3_000;
+export const OFFLINE_THRESHOLD_MS = Number(process.env.OFFLINE_THRESHOLD_MS) || 9_000;
+export const EVENT_POLL_INTERVAL_MS = Number(process.env.EVENT_POLL_INTERVAL_MS) || 2_000;
+export const AGENT_HANDLE_MIN_LENGTH = 4;
+
+// Local dev URLs (used for service-binding fallbacks)
+export const DEV_WEB_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000";
+export const DEV_WS_DO_URL = process.env.DEV_WS_DO_URL || "http://localhost:8789";
+export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || "http://localhost:8788";
diff --git a/src/shared/index.ts b/src/shared/index.ts
index 35377ea73..4f2b9a943 100644
--- a/src/shared/index.ts
+++ b/src/shared/index.ts
@@ -1,3 +1,4 @@
+// Types
export type {
User,
Workspace,
@@ -9,10 +10,14 @@ export type {
TaskAgentData,
TaskMessage,
MachineToken,
+ Email,
+ EmailAttachment,
LoginResponse,
CreateAgentRequest,
+ WsMessage,
} from "./types";
+// API types
export type {
ApiResponse,
ApiListResponse,
@@ -38,11 +43,19 @@ export type {
CreateMachineTokenResponse,
} from "./api-types";
+// Constants
export {
AgentStatus,
RuntimeStatus,
TaskStatus,
MessageRole,
+ POLL_INTERVAL_MS,
+ OFFLINE_THRESHOLD_MS,
+ EVENT_POLL_INTERVAL_MS,
+ AGENT_HANDLE_MIN_LENGTH,
+ DEV_WEB_URL,
+ DEV_WS_DO_URL,
+ DEV_EMAIL_WORKER_URL,
} from "./constants";
export type {
@@ -52,20 +65,21 @@ export type {
MessageRoleType,
} from "./constants";
+// Schemas
export {
TaskStatusSchema,
ClaimedTaskRowSchema,
TaskAgentDataApiSchema,
TaskApiBaseSchema,
TaskApiSchema,
- ClaimTaskResponseSchema,
+ PollRequestSchema,
+ PollResponseSchema,
RegisterResponseSchema,
DaemonRuntimeItemSchema,
ActivateTokenRuntimeSchema,
ActivateTokenRequestSchema,
RegisterDaemonRequestSchema,
DeregisterRequestSchema,
- HeartbeatRequestSchema,
CompleteTaskRequestSchema,
FailTaskRequestSchema,
MessageItemSchema,
@@ -77,16 +91,32 @@ export type {
TaskAgentDataApi,
TaskApiBase,
TaskApi,
- ClaimTaskResponse,
+ PollRequest,
+ PollResponse,
RegisterResponse,
DaemonRuntimeItem,
ActivateTokenRuntime,
ActivateTokenRequest,
RegisterDaemonRequest,
DeregisterRequest,
- HeartbeatRequest,
CompleteTaskRequest,
FailTaskRequest,
MessageItem,
ReportMessagesRequest,
} from "./schemas";
+
+// Database
+export { createDb } from "./db/index";
+export type { Database } from "./db/index";
+export * as schema from "./db/schema";
+export * as queries from "./db/queries-index";
+
+// Logger
+export { Logger, createLogger } from "./logger"
+export type { LogLevel, LoggerOptions } from "./logger"
+
+// Utils
+export { parseEmailHandle, toAlookAddress, isValidHandle } from "./utils/email";
+export { isValidToken, isValidEmail } from "./utils/validation";
+export { isOnline, formatStatus } from "./utils/status";
+export { isUniqueConstraintError } from "./utils/db-errors";
diff --git a/src/shared/schemas.test.ts b/src/shared/schemas.test.ts
index e2ebb5e45..f26d8543c 100644
--- a/src/shared/schemas.test.ts
+++ b/src/shared/schemas.test.ts
@@ -5,11 +5,11 @@ import {
TaskApiBaseSchema,
TaskApiSchema,
TaskAgentDataApiSchema,
- ClaimTaskResponseSchema,
+ PollRequestSchema,
+ PollResponseSchema,
RegisterDaemonRequestSchema,
DaemonRuntimeItemSchema,
DeregisterRequestSchema,
- HeartbeatRequestSchema,
CompleteTaskRequestSchema,
FailTaskRequestSchema,
ReportMessagesRequestSchema,
@@ -154,20 +154,44 @@ describe("TaskAgentDataApiSchema", () => {
});
// ---------------------------------------------------------------------------
-// ClaimTaskResponseSchema
+// PollRequestSchema
// ---------------------------------------------------------------------------
-describe("ClaimTaskResponseSchema", () => {
- it("accepts { task: null }", () => {
- const parsed = ClaimTaskResponseSchema.parse({ task: null });
- expect(parsed.task).toBeNull();
+describe("PollRequestSchema", () => {
+ it("rejects empty runtime_ids array", () => {
+ expect(() => PollRequestSchema.parse({ runtime_ids: [] })).toThrow();
});
- it("accepts { task: { ...validTask } }", () => {
- const parsed = ClaimTaskResponseSchema.parse({
- task: validTaskApiBase(),
+ 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 max_tasks: 0", () => {
+ expect(() => PollRequestSchema.parse({ runtime_ids: ["r1"], max_tasks: 0 })).toThrow();
+ });
+
+ it("rejects array with empty strings", () => {
+ expect(() => PollRequestSchema.parse({ runtime_ids: [""] })).toThrow();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// PollResponseSchema
+// ---------------------------------------------------------------------------
+
+describe("PollResponseSchema", () => {
+ it("accepts empty tasks array", () => {
+ const parsed = PollResponseSchema.parse({ tasks: [] });
+ expect(parsed.tasks).toEqual([]);
+ });
+
+ it("accepts tasks with valid task objects", () => {
+ const parsed = PollResponseSchema.parse({
+ tasks: [validTaskApiBase()],
});
- expect(parsed.task?.id).toBe("t1");
+ expect(parsed.tasks[0].id).toBe("t1");
});
});
@@ -237,15 +261,6 @@ describe("DeregisterRequestSchema", () => {
});
});
-// ---------------------------------------------------------------------------
-// HeartbeatRequestSchema
-// ---------------------------------------------------------------------------
-
-describe("HeartbeatRequestSchema", () => {
- it("requires non-empty runtime_id", () => {
- expect(() => HeartbeatRequestSchema.parse({ runtime_id: "" })).toThrow();
- });
-});
// ---------------------------------------------------------------------------
// CompleteTaskRequestSchema
diff --git a/src/shared/schemas.ts b/src/shared/schemas.ts
index ca2fae31d..bb3f3859f 100644
--- a/src/shared/schemas.ts
+++ b/src/shared/schemas.ts
@@ -82,13 +82,19 @@ export const TaskApiSchema = TaskApiBaseSchema.extend({
export type TaskApi = z.infer<typeof TaskApiSchema>;
// ---------------------------------------------------------------------------
-// Claim task response
+// Poll request/response (replaces heartbeat + per-runtime claim)
// ---------------------------------------------------------------------------
-export const ClaimTaskResponseSchema = z.object({
- task: TaskApiSchema.nullable(),
+export const PollRequestSchema = z.object({
+ runtime_ids: z.array(z.string().min(1)).min(1),
+ max_tasks: z.number().int().min(1).default(1),
});
-export type ClaimTaskResponse = z.infer<typeof ClaimTaskResponseSchema>;
+export type PollRequest = z.infer<typeof PollRequestSchema>;
+
+export const PollResponseSchema = z.object({
+ tasks: z.array(TaskApiSchema),
+});
+export type PollResponse = z.infer<typeof PollResponseSchema>;
// ---------------------------------------------------------------------------
// Register response
@@ -114,6 +120,19 @@ export const DaemonRuntimeItemSchema = z.object({
});
export type DaemonRuntimeItem = z.infer<typeof DaemonRuntimeItemSchema>;
+export const ActivateTokenRuntimeSchema = z.object({
+ type: z.string().min(1),
+ version: z.string().optional().default(""),
+});
+export type ActivateTokenRuntime = z.infer<typeof ActivateTokenRuntimeSchema>;
+
+export const ActivateTokenRequestSchema = z.object({
+ token: z.string().min(1),
+ hostname: z.string().min(1),
+ runtimes: z.array(ActivateTokenRuntimeSchema).min(1),
+});
+export type ActivateTokenRequest = z.infer<typeof ActivateTokenRequestSchema>;
+
export const RegisterDaemonRequestSchema = z.object({
workspace_id: z.string().min(1),
daemon_id: z.string().min(1),
@@ -128,10 +147,6 @@ export const DeregisterRequestSchema = z.object({
});
export type DeregisterRequest = z.infer<typeof DeregisterRequestSchema>;
-export const HeartbeatRequestSchema = z.object({
- runtime_id: z.string().min(1, "runtime_id is required"),
-});
-export type HeartbeatRequest = z.infer<typeof HeartbeatRequestSchema>;
export const CompleteTaskRequestSchema = z.object({
output: z.string().optional(),
@@ -149,6 +164,7 @@ export const MessageItemSchema = z.object({
seq: z.number(),
type: z.string(),
tool: z.string().optional(),
+ call_id: z.string().optional(),
content: z.string().optional(),
input: z.record(z.string(), z.unknown()).optional(),
output: z.string().optional(),
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index 3ca67cfe9..38bd8e9d0 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -34,7 +34,7 @@ export const MessageRole = {
export type MessageRoleType = (typeof MessageRole)[keyof typeof MessageRole];
// Timing constants
-export const HEARTBEAT_INTERVAL_MS = Number(process.env.HEARTBEAT_INTERVAL_MS) || 3_000;
+export const POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS) || 3_000;
export const OFFLINE_THRESHOLD_MS = Number(process.env.OFFLINE_THRESHOLD_MS) || 9_000;
export const EVENT_POLL_INTERVAL_MS = Number(process.env.EVENT_POLL_INTERVAL_MS) || 2_000;
export const AGENT_HANDLE_MIN_LENGTH = 4;
diff --git a/src/shared/src/db/queries/conversation.ts b/src/shared/src/db/queries/conversation.ts
index b2f702b2c..9efa770d1 100644
--- a/src/shared/src/db/queries/conversation.ts
+++ b/src/shared/src/db/queries/conversation.ts
@@ -23,11 +23,11 @@ export async function createConversation(
return rows[0]!;
}
-export async function getConversation(db: Database, id: string) {
+export async function getConversation(db: Database, id: string, workspaceId: string) {
const rows = await db
.select()
.from(conversation)
- .where(eq(conversation.id, id));
+ .where(and(eq(conversation.id, id), eq(conversation.workspaceId, workspaceId)));
return rows[0] ?? null;
}
@@ -90,10 +90,10 @@ export async function updateConversationTitle(
return rows[0] ?? null;
}
-export async function deleteConversation(db: Database, id: string) {
+export async function deleteConversation(db: Database, id: string, workspaceId: string) {
const rows = await db
.delete(conversation)
- .where(eq(conversation.id, id))
+ .where(and(eq(conversation.id, id), eq(conversation.workspaceId, workspaceId)))
.returning();
return rows[0] ?? null;
}
diff --git a/src/shared/src/db/queries/email.ts b/src/shared/src/db/queries/email.ts
index 76743f1b1..c946c09f1 100644
--- a/src/shared/src/db/queries/email.ts
+++ b/src/shared/src/db/queries/email.ts
@@ -1,4 +1,4 @@
-import { eq, desc, inArray, and } from "drizzle-orm";
+import { eq, desc, and } from "drizzle-orm";
import { emails } from "../schema";
import type { Database } from "../index";
@@ -10,8 +10,8 @@ export async function createEmail(
return rows[0]!;
}
-export async function getEmailById(db: Database, id: string) {
- const rows = await db.select().from(emails).where(eq(emails.id, id));
+export async function getEmailById(db: Database, id: string, workspaceId: string) {
+ const rows = await db.select().from(emails).where(and(eq(emails.id, id), eq(emails.workspaceId, workspaceId)));
return rows[0] ?? null;
}
@@ -23,23 +23,18 @@ export async function getEmailsByAgent(db: Database, agentId: string, workspaceI
.orderBy(desc(emails.createdAt));
}
-export async function getInboxEmails(db: Database, agentId: string, agentEmail: string) {
+export async function getInboxEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string) {
return db.select().from(emails)
- .where(and(eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail)))
+ .where(and(eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId)))
.orderBy(desc(emails.createdAt));
}
-export async function getSentEmails(db: Database, agentId: string, agentEmail: string) {
+export async function getSentEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string) {
return db.select().from(emails)
- .where(and(eq(emails.agentId, agentId), eq(emails.fromEmail, agentEmail)))
+ .where(and(eq(emails.agentId, agentId), eq(emails.fromEmail, agentEmail), eq(emails.workspaceId, workspaceId)))
.orderBy(desc(emails.createdAt));
}
-export async function getEmailsByUser(db: Database, agentIds: string[]) {
- if (agentIds.length === 0) return [];
- return db.select().from(emails).where(inArray(emails.agentId, agentIds)).orderBy(desc(emails.createdAt));
-}
-
-export async function deleteEmail(db: Database, id: string) {
- return db.delete(emails).where(eq(emails.id, id));
+export async function deleteEmail(db: Database, id: string, workspaceId: string) {
+ return db.delete(emails).where(and(eq(emails.id, id), eq(emails.workspaceId, workspaceId)));
}
diff --git a/src/shared/src/db/queries/runtime.ts b/src/shared/src/db/queries/runtime.ts
index 92577168a..0b1430411 100644
--- a/src/shared/src/db/queries/runtime.ts
+++ b/src/shared/src/db/queries/runtime.ts
@@ -1,4 +1,4 @@
-import { eq, and, asc, or, lt, isNull } from "drizzle-orm";
+import { eq, and, asc, or, lt, isNull, inArray } from "drizzle-orm";
import { agentRuntime, agent, agentTaskQueue } from "../schema";
import type { Database } from "../index";
@@ -79,16 +79,6 @@ export async function getAgentRuntimeForWorkspace(
return rows[0] ?? null;
}
-export async function updateAgentRuntimeHeartbeat(db: Database, id: string) {
- const now = new Date().toISOString();
- const rows = await db
- .update(agentRuntime)
- .set({ lastSeenAt: now, status: "online", updatedAt: now })
- .where(eq(agentRuntime.id, id))
- .returning();
- return rows[0] ?? null;
-}
-
export async function setAgentRuntimeOffline(db: Database, id: string) {
await db
.update(agentRuntime)
@@ -139,6 +129,23 @@ export async function deleteRuntimesByDaemonId(
);
}
+export async function updateRuntimesLastSeen(
+ db: Database,
+ ids: string[],
+ workspaceId: string
+) {
+ if (ids.length === 0) return [];
+ const now = new Date().toISOString();
+ const result = await db
+ .update(agentRuntime)
+ .set({ lastSeenAt: now, status: "online", updatedAt: now })
+ .where(
+ and(inArray(agentRuntime.id, ids), eq(agentRuntime.workspaceId, workspaceId))
+ )
+ .returning({ id: agentRuntime.id });
+ return result.map(r => r.id);
+}
+
export async function markStaleRuntimesOffline(
db: Database,
workspaceId: string
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index 4cd7b0b63..6f99cf098 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -30,19 +30,23 @@ export async function createTask(
return rows[0]!;
}
-export async function getTask(db: Database, id: string) {
+export async function getTask(db: Database, id: string, workspaceId?: string) {
+ const conditions = [eq(agentTaskQueue.id, id)];
+ if (workspaceId) conditions.push(eq(agentTaskQueue.workspaceId, workspaceId));
const rows = await db
.select()
.from(agentTaskQueue)
- .where(eq(agentTaskQueue.id, id));
+ .where(and(...conditions));
return rows[0] ?? null;
}
-export async function getTaskStatus(db: Database, id: string) {
+export async function getTaskStatus(db: Database, id: string, workspaceId?: string) {
+ const conditions = [eq(agentTaskQueue.id, id)];
+ if (workspaceId) conditions.push(eq(agentTaskQueue.workspaceId, workspaceId));
const rows = await db
.select({ status: agentTaskQueue.status })
.from(agentTaskQueue)
- .where(eq(agentTaskQueue.id, id));
+ .where(and(...conditions));
return rows[0]?.status ?? null;
}
@@ -148,16 +152,19 @@ export async function failTask(
}
-export async function listPendingTasksByRuntime(
+export async function listPendingTasksByRuntimes(
db: Database,
- runtimeId: string
+ runtimeIds: string[],
+ workspaceId: string
) {
+ if (runtimeIds.length === 0) return [];
return db
.select()
.from(agentTaskQueue)
.where(
and(
- eq(agentTaskQueue.runtimeId, runtimeId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ inArray(agentTaskQueue.runtimeId, runtimeIds),
inArray(agentTaskQueue.status, ["queued", "dispatched"])
)
)
@@ -197,7 +204,7 @@ export async function cancelTask(db: Database, id: string) {
const DEFAULT_STALE_SECONDS = Number(process.env.ALOOK_STALE_DISPATCH_TIMEOUT_S) || 20;
-export async function failStaleDispatchedTasks(db: Database, staleSeconds = DEFAULT_STALE_SECONDS) {
+export async function failStaleDispatchedTasks(db: Database, workspaceId: string, staleSeconds = DEFAULT_STALE_SECONDS) {
const threshold = new Date(Date.now() - staleSeconds * 1000).toISOString();
const rows = await db
.update(agentTaskQueue)
@@ -208,6 +215,7 @@ export async function failStaleDispatchedTasks(db: Database, staleSeconds = DEFA
})
.where(
and(
+ eq(agentTaskQueue.workspaceId, workspaceId),
eq(agentTaskQueue.status, "dispatched"),
lt(agentTaskQueue.dispatchedAt, threshold)
)
@@ -218,11 +226,12 @@ export async function failStaleDispatchedTasks(db: Database, staleSeconds = DEFA
export async function deleteTasksByConversation(
db: Database,
- conversationId: string
+ conversationId: string,
+ workspaceId: string
) {
return db
.delete(agentTaskQueue)
- .where(eq(agentTaskQueue.conversationId, conversationId))
+ .where(and(eq(agentTaskQueue.conversationId, conversationId), eq(agentTaskQueue.workspaceId, workspaceId)))
.returning({ id: agentTaskQueue.id });
}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 8030a654c..4f2b9a943 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -49,7 +49,7 @@ export {
RuntimeStatus,
TaskStatus,
MessageRole,
- HEARTBEAT_INTERVAL_MS,
+ POLL_INTERVAL_MS,
OFFLINE_THRESHOLD_MS,
EVENT_POLL_INTERVAL_MS,
AGENT_HANDLE_MIN_LENGTH,
@@ -72,14 +72,14 @@ export {
TaskAgentDataApiSchema,
TaskApiBaseSchema,
TaskApiSchema,
- ClaimTaskResponseSchema,
+ PollRequestSchema,
+ PollResponseSchema,
RegisterResponseSchema,
DaemonRuntimeItemSchema,
ActivateTokenRuntimeSchema,
ActivateTokenRequestSchema,
RegisterDaemonRequestSchema,
DeregisterRequestSchema,
- HeartbeatRequestSchema,
CompleteTaskRequestSchema,
FailTaskRequestSchema,
MessageItemSchema,
@@ -91,14 +91,14 @@ export type {
TaskAgentDataApi,
TaskApiBase,
TaskApi,
- ClaimTaskResponse,
+ PollRequest,
+ PollResponse,
RegisterResponse,
DaemonRuntimeItem,
ActivateTokenRuntime,
ActivateTokenRequest,
RegisterDaemonRequest,
DeregisterRequest,
- HeartbeatRequest,
CompleteTaskRequest,
FailTaskRequest,
MessageItem,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 0303fda86..bb3f3859f 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -82,13 +82,19 @@ export const TaskApiSchema = TaskApiBaseSchema.extend({
export type TaskApi = z.infer<typeof TaskApiSchema>;
// ---------------------------------------------------------------------------
-// Claim task response
+// Poll request/response (replaces heartbeat + per-runtime claim)
// ---------------------------------------------------------------------------
-export const ClaimTaskResponseSchema = z.object({
- task: TaskApiSchema.nullable(),
+export const PollRequestSchema = z.object({
+ runtime_ids: z.array(z.string().min(1)).min(1),
+ max_tasks: z.number().int().min(1).default(1),
});
-export type ClaimTaskResponse = z.infer<typeof ClaimTaskResponseSchema>;
+export type PollRequest = z.infer<typeof PollRequestSchema>;
+
+export const PollResponseSchema = z.object({
+ tasks: z.array(TaskApiSchema),
+});
+export type PollResponse = z.infer<typeof PollResponseSchema>;
// ---------------------------------------------------------------------------
// Register response
@@ -141,10 +147,6 @@ export const DeregisterRequestSchema = z.object({
});
export type DeregisterRequest = z.infer<typeof DeregisterRequestSchema>;
-export const HeartbeatRequestSchema = z.object({
- runtime_id: z.string().min(1, "runtime_id is required"),
-});
-export type HeartbeatRequest = z.infer<typeof HeartbeatRequestSchema>;
export const CompleteTaskRequestSchema = z.object({
output: z.string().optional(),
diff --git a/src/shared/test/constants.test.ts b/src/shared/test/constants.test.ts
index b938c2cc9..85b6646fa 100644
--- a/src/shared/test/constants.test.ts
+++ b/src/shared/test/constants.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect } from "vitest"
-import { HEARTBEAT_INTERVAL_MS, OFFLINE_THRESHOLD_MS, EVENT_POLL_INTERVAL_MS, AGENT_HANDLE_MIN_LENGTH } from "../src/constants"
+import { POLL_INTERVAL_MS, OFFLINE_THRESHOLD_MS, EVENT_POLL_INTERVAL_MS, AGENT_HANDLE_MIN_LENGTH } from "../src/constants"
describe("constants", () => {
- it("OFFLINE_THRESHOLD_MS is 3x HEARTBEAT", () => expect(OFFLINE_THRESHOLD_MS).toBe(HEARTBEAT_INTERVAL_MS * 3))
+ it("OFFLINE_THRESHOLD_MS is 3x POLL_INTERVAL", () => expect(OFFLINE_THRESHOLD_MS).toBe(POLL_INTERVAL_MS * 3))
it("AGENT_HANDLE_MIN_LENGTH is 4", () => expect(AGENT_HANDLE_MIN_LENGTH).toBe(4))
- it("EVENT_POLL < HEARTBEAT", () => expect(EVENT_POLL_INTERVAL_MS).toBeLessThan(HEARTBEAT_INTERVAL_MS))
+ it("EVENT_POLL < POLL_INTERVAL", () => expect(EVENT_POLL_INTERVAL_MS).toBeLessThan(POLL_INTERVAL_MS))
})
diff --git a/src/web/src/app/api/agents/route.test.ts b/src/web/src/app/api/agents/route.test.ts
index 5de563310..5c6dd3ce1 100644
--- a/src/web/src/app/api/agents/route.test.ts
+++ b/src/web/src/app/api/agents/route.test.ts
@@ -46,6 +46,10 @@ vi.mock("@/lib/services/task", () => {
return { TaskService: Svc };
});
+vi.mock("@/lib/services/sweep", () => ({
+ sweepStaleState: vi.fn().mockResolvedValue(undefined),
+}));
+
import { GET, POST } from "./route";
beforeEach(() => vi.clearAllMocks());
diff --git a/src/web/src/app/api/agents/route.ts b/src/web/src/app/api/agents/route.ts
index cb9bff534..8eac493dc 100644
--- a/src/web/src/app/api/agents/route.ts
+++ b/src/web/src/app/api/agents/route.ts
@@ -6,6 +6,7 @@ import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON, writeError } from "@/lib/middleware/helpers";
import { agentToResponse } from "@/lib/api/responses";
import { TaskService } from "@/lib/services/task";
+import { sweepStaleState } from "@/lib/services/sweep";
export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
@@ -14,6 +15,9 @@ export const GET = withAuth(async (req, ctx) => {
const { env } = getCloudflareContext()
const db = createDb((env as Env).DB)
+ // Sweep stale state: catches stuck tasks even when all daemons are dead
+ await sweepStaleState(db, ws.workspaceId);
+
const agents = await queries.agent.listAgents(db, ws.workspaceId);
return writeJSON(agents.map(agentToResponse));
});
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
index ecf05fffb..3ab179f89 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
@@ -186,10 +186,14 @@ describe("POST /api/conversations/[id]/messages", () => {
expect(body.error).toBe("conversation not found");
});
- it("returns 404 when conversation workspace doesn't match", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "other", agentId: "a1" });
+ it("passes workspaceId to getConversation", async () => {
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ mockGetConversation.mockResolvedValue(conv);
+ mockCreateMessage.mockResolvedValue({ id: "m1", content: "hello" });
+ mockUpdateConversationTitle.mockResolvedValue(undefined);
+ mockEnqueueTask.mockResolvedValue({ id: "t1", status: "pending" });
- const res = await POST(
+ await POST(
new NextRequest("http://localhost/api/conversations/c1/messages", {
method: "POST",
body: JSON.stringify({ content: "hello" }),
@@ -197,9 +201,7 @@ describe("POST /api/conversations/[id]/messages", () => {
}),
withParams("c1")
);
- const body = await res.json();
- expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
+ expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
});
});
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.ts
index b63553b06..dbc791c1a 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -30,8 +30,8 @@ export const GET = withAuth(async (req, ctx) => {
return writeError("conversation id is required", 400);
}
- const conversation = await queries.conversation.getConversation(db, id);
- if (!conversation || conversation.workspaceId !== ws.workspaceId) {
+ const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
+ if (!conversation) {
return writeError("conversation not found", 404);
}
@@ -63,8 +63,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError("content is required", 400);
}
- const conversation = await queries.conversation.getConversation(db, id);
- if (!conversation || conversation.workspaceId !== ws.workspaceId) {
+ const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
+ if (!conversation) {
return writeError("conversation not found", 404);
}
diff --git a/src/web/src/app/api/conversations/[id]/route.test.ts b/src/web/src/app/api/conversations/[id]/route.test.ts
index ee1cbd9b2..1ba9d8351 100644
--- a/src/web/src/app/api/conversations/[id]/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/route.test.ts
@@ -41,7 +41,7 @@ const withParams = (id: string) => ({ params: Promise.resolve({ id }) });
describe("GET /api/conversations/[id]", () => {
beforeEach(() => vi.clearAllMocks());
- it("returns conversation", async () => {
+ it("returns conversation scoped by workspaceId", async () => {
const conv = { id: "c1", title: "Test", workspaceId: "w1" };
mockGetConversation.mockResolvedValue(conv);
@@ -53,7 +53,7 @@ describe("GET /api/conversations/[id]", () => {
expect(res.status).toBe(200);
expect(body).toEqual({ id: "c1", title: "Test" });
- expect(mockGetConversation).toHaveBeenCalledWith({}, "c1");
+ expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
});
it("returns 404 when not found", async () => {
@@ -68,25 +68,12 @@ describe("GET /api/conversations/[id]", () => {
expect(res.status).toBe(404);
expect(body.error).toBe("conversation not found");
});
-
- it("returns 404 when workspace mismatch", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "other" });
-
- const res = await GET(
- new NextRequest("http://localhost/api/conversations/c1"),
- withParams("c1")
- );
- const body = await res.json();
-
- expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
- });
});
describe("DELETE /api/conversations/[id]", () => {
beforeEach(() => vi.clearAllMocks());
- it("returns 204 and removes conversation + tasks", async () => {
+ it("returns 204 and removes conversation + tasks with workspace scoping", async () => {
mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
mockDeleteTasksByConversation.mockResolvedValue(undefined);
mockDeleteConversation.mockResolvedValue(undefined);
@@ -97,8 +84,8 @@ describe("DELETE /api/conversations/[id]", () => {
);
expect(res.status).toBe(204);
- expect(mockDeleteTasksByConversation).toHaveBeenCalled();
- expect(mockDeleteConversation).toHaveBeenCalled();
+ expect(mockDeleteTasksByConversation).toHaveBeenCalledWith({}, "c1", "w1");
+ expect(mockDeleteConversation).toHaveBeenCalledWith({}, "c1", "w1");
});
it("deletes tasks before conversation", async () => {
@@ -131,17 +118,4 @@ describe("DELETE /api/conversations/[id]", () => {
expect(res.status).toBe(404);
expect(body.error).toBe("conversation not found");
});
-
- it("returns 404 when workspace mismatch", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "other" });
-
- const res = await DELETE(
- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),
- withParams("c1")
- );
- const body = await res.json();
-
- expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
- });
});
diff --git a/src/web/src/app/api/conversations/[id]/route.ts b/src/web/src/app/api/conversations/[id]/route.ts
index 656811899..58696b787 100644
--- a/src/web/src/app/api/conversations/[id]/route.ts
+++ b/src/web/src/app/api/conversations/[id]/route.ts
@@ -17,8 +17,8 @@ export const GET = withAuth(async (req, ctx) => {
return writeError("conversation id is required", 400);
}
- const conversation = await queries.conversation.getConversation(db, id);
- if (!conversation || conversation.workspaceId !== ws.workspaceId) {
+ const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
+ if (!conversation) {
return writeError("conversation not found", 404);
}
@@ -37,15 +37,15 @@ export const DELETE = withAuth(async (req, ctx) => {
return writeError("conversation id is required", 400);
}
- const conversation = await queries.conversation.getConversation(db, id);
- if (!conversation || conversation.workspaceId !== ws.workspaceId) {
+ const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
+ if (!conversation) {
return writeError("conversation not found", 404);
}
// Delete tasks first (no cascade on FK)
- await queries.task.deleteTasksByConversation(db, id);
+ await queries.task.deleteTasksByConversation(db, id, ws.workspaceId);
// Messages cascade automatically via schema
- await queries.conversation.deleteConversation(db, id);
+ await queries.conversation.deleteConversation(db, id, ws.workspaceId);
return new Response(null, { status: 204 });
});
diff --git a/src/web/src/app/api/daemon/heartbeat/route.test.ts b/src/web/src/app/api/daemon/heartbeat/route.test.ts
deleted file mode 100644
index 802b93513..000000000
--- a/src/web/src/app/api/daemon/heartbeat/route.test.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
-
-// ---------------------------------------------------------------------------
-// Shared mock fns -- wired fresh on each test via vi.doMock
-// ---------------------------------------------------------------------------
-const mockGetAgentRuntimeForWorkspace = vi.fn();
-const mockUpdateAgentRuntimeHeartbeat = vi.fn();
-const mockMarkStaleRuntimesOffline = vi.fn();
-const mockFailStaleDispatchedTasks = vi.fn();
-const mockReconcileAgentStatus = vi.fn();
-
-function makeReq(body: unknown) {
- return new NextRequest("http://localhost/api/daemon/heartbeat", {
- method: "POST",
- body: JSON.stringify(body),
- headers: { "Content-Type": "application/json" },
- });
-}
-
-describe("POST /api/daemon/heartbeat", () => {
- beforeEach(() => vi.clearAllMocks());
-
- async function loadRoute(authCtx: Record<string, unknown>) {
- vi.resetModules();
-
- const { HeartbeatRequestSchema } = await import("@alook/shared");
-
- vi.doMock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
- }));
- vi.doMock("@alook/shared", () => ({
- createDb: vi.fn(() => ({})),
- queries: {
- runtime: {
- getAgentRuntimeForWorkspace: (...a: any[]) =>
- mockGetAgentRuntimeForWorkspace(...a),
- updateAgentRuntimeHeartbeat: (...a: any[]) =>
- mockUpdateAgentRuntimeHeartbeat(...a),
- markStaleRuntimesOffline: (...a: any[]) =>
- mockMarkStaleRuntimesOffline(...a),
- },
- task: {
- failStaleDispatchedTasks: (...a: any[]) =>
- mockFailStaleDispatchedTasks(...a),
- },
- },
- HeartbeatRequestSchema,
- }));
- vi.doMock("@/lib/services/task", () => {
- const MockTaskService = function (this: any) {
- this.reconcileAgentStatus = (...a: any[]) =>
- mockReconcileAgentStatus(...a);
- } as any;
- return { TaskService: MockTaskService };
- });
- vi.doMock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params =
- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
- return handler(req, { ...authCtx, params });
- }),
- }));
- vi.doMock("@/lib/middleware/helpers", async () => {
- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(
- "@/lib/middleware/helpers"
- );
- });
-
- const { POST } = await import("./route");
- return POST;
- }
-
- const daemonAuth = { userId: "u1", email: "[email protected]", workspaceId: "w1" };
- const jwtAuth = { userId: "u1", email: "[email protected]" }; // no workspaceId
-
- it("succeeds for runtime in caller's workspace", async () => {
- const POST = await loadRoute(daemonAuth);
-
- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });
- mockUpdateAgentRuntimeHeartbeat.mockResolvedValue(undefined);
- mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
- mockFailStaleDispatchedTasks.mockResolvedValue([]);
-
- const res = await POST(makeReq({ runtime_id: "rt1" }));
- const body = await res.json();
-
- expect(res.status).toBe(200);
- expect(body).toEqual({ status: "ok" });
- });
-
- it("returns 404 when runtime not in caller's workspace", async () => {
- const POST = await loadRoute(daemonAuth);
-
- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);
-
- const res = await POST(makeReq({ runtime_id: "rt-other" }));
- const body = await res.json();
-
- expect(res.status).toBe(404);
- expect(body.error).toBe("Runtime not found");
- });
-
- it("returns 404 when runtime ID doesn't exist", async () => {
- const POST = await loadRoute(daemonAuth);
-
- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);
-
- const res = await POST(makeReq({ runtime_id: "nonexistent" }));
- const body = await res.json();
-
- expect(res.status).toBe(404);
- expect(body.error).toBe("Runtime not found");
- });
-
- it("returns 403 when called without workspaceId (JWT auth)", async () => {
- const POST = await loadRoute(jwtAuth);
-
- const res = await POST(makeReq({ runtime_id: "rt1" }));
- const body = await res.json();
-
- expect(res.status).toBe(403);
- expect(body.error).toContain("machine token required");
- });
-
- it("does NOT call heartbeat/stale functions when ownership fails", async () => {
- const POST = await loadRoute(daemonAuth);
-
- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);
-
- await POST(makeReq({ runtime_id: "rt1" }));
-
- expect(mockUpdateAgentRuntimeHeartbeat).not.toHaveBeenCalled();
- expect(mockMarkStaleRuntimesOffline).not.toHaveBeenCalled();
- expect(mockFailStaleDispatchedTasks).not.toHaveBeenCalled();
- });
-
- it("calls markStaleRuntimesOffline with workspaceId", async () => {
- const POST = await loadRoute(daemonAuth);
-
- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });
- mockUpdateAgentRuntimeHeartbeat.mockResolvedValue(undefined);
- mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
- mockFailStaleDispatchedTasks.mockResolvedValue([]);
-
- await POST(makeReq({ runtime_id: "rt1" }));
-
- expect(mockMarkStaleRuntimesOffline).toHaveBeenCalledWith({}, "w1");
- });
-
- it("calls updateAgentRuntimeHeartbeat before markStaleRuntimesOffline", async () => {
- const POST = await loadRoute(daemonAuth);
-
- const callOrder: string[] = [];
- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });
- mockUpdateAgentRuntimeHeartbeat.mockImplementation(async () => {
- callOrder.push("heartbeat");
- });
- mockMarkStaleRuntimesOffline.mockImplementation(async () => {
- callOrder.push("stale");
- });
- mockFailStaleDispatchedTasks.mockResolvedValue([]);
-
- await POST(makeReq({ runtime_id: "rt1" }));
-
- expect(callOrder).toEqual(["heartbeat", "stale"]);
- });
-
- it("calls failStaleDispatchedTasks and reconcile on happy path", async () => {
- const POST = await loadRoute(daemonAuth);
-
- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });
- mockUpdateAgentRuntimeHeartbeat.mockResolvedValue(undefined);
- mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
- mockFailStaleDispatchedTasks.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1" },
- { agentId: "a2", workspaceId: "w1" },
- { agentId: "a1", workspaceId: "w1" },
- ]);
-
- await POST(makeReq({ runtime_id: "rt1" }));
-
- expect(mockFailStaleDispatchedTasks).toHaveBeenCalledOnce();
- // reconcile called for each unique (agentId, workspaceId) pair
- expect(mockReconcileAgentStatus).toHaveBeenCalledTimes(2);
- expect(mockReconcileAgentStatus).toHaveBeenCalledWith("a1", "w1");
- expect(mockReconcileAgentStatus).toHaveBeenCalledWith("a2", "w1");
- });
-});
diff --git a/src/web/src/app/api/daemon/heartbeat/route.ts b/src/web/src/app/api/daemon/heartbeat/route.ts
deleted file mode 100644
index ee510b09e..000000000
--- a/src/web/src/app/api/daemon/heartbeat/route.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { NextRequest } from "next/server";
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createDb, queries } from "@alook/shared"
-import { withAuth } from "@/lib/middleware/auth";
-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
-import { HeartbeatRequestSchema } from "@alook/shared";
-import { TaskService } from "@/lib/services/task";
-import { broadcastToUser } from "@/lib/broadcast";
-
-export const POST = withAuth(async (req: NextRequest, ctx) => {
- const { env } = getCloudflareContext()
- const db = createDb((env as Env).DB)
-
- const [body, err] = await parseBody(req, HeartbeatRequestSchema);
- if (err) return err;
-
- if (!ctx.workspaceId) {
- return writeError("Forbidden: machine token required", 403);
- }
-
- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(
- db,
- body.runtime_id,
- ctx.workspaceId
- );
- if (!runtime) {
- return writeError("Runtime not found", 404);
- }
-
- await queries.runtime.updateAgentRuntimeHeartbeat(db, body.runtime_id);
-
- // Notify web UI of status change
- broadcastToUser(ctx.userId, {
- type: "runtime.status",
- runtimeId: body.runtime_id,
- status: "online",
- }).catch(() => {});
-
- // Mark runtimes that haven't sent a heartbeat in >45s as offline
- await queries.runtime.markStaleRuntimesOffline(db, ctx.workspaceId);
-
- // Fail tasks stuck in "dispatched" for >20s (daemon likely crashed)
- const stale = await queries.task.failStaleDispatchedTasks(db);
- if (stale.length > 0) {
- const taskService = new TaskService(db);
- const seen = new Set<string>();
- for (const r of stale) {
- const key = `${r.agentId}:${r.workspaceId}`;
- if (seen.has(key)) continue;
- seen.add(key);
- await taskService.reconcileAgentStatus(r.agentId, r.workspaceId);
- }
- }
-
- 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.ts
index fec5577c1..e73dd0f7b 100644
--- a/src/web/src/app/api/daemon/routes.test.ts
+++ b/src/web/src/app/api/daemon/routes.test.ts
@@ -224,11 +224,11 @@ describe("daemon route body validation", () => {
});
// -----------------------------------------------------------------------
- // POST /daemon/heartbeat
+ // POST /daemon/tasks/poll
// -----------------------------------------------------------------------
- describe("POST /daemon/heartbeat", () => {
- async function loadHeartbeat() {
+ describe("POST /daemon/tasks/poll", () => {
+ async function loadPoll() {
vi.resetModules();
applyBase();
@@ -241,40 +241,71 @@ describe("daemon route body validation", () => {
createDb: vi.fn(() => ({})),
queries: {
runtime: {
- getAgentRuntimeForWorkspace: vi.fn().mockResolvedValue({ id: "rt1" }),
- updateAgentRuntimeHeartbeat: vi.fn(),
- markStaleRuntimesOffline: vi.fn(),
+ updateRuntimesLastSeen: vi.fn().mockResolvedValue(["r1"]),
},
- task: {
- failStaleDispatchedTasks: vi.fn().mockResolvedValue([]),
+ agent: {
+ getAgent: vi.fn().mockResolvedValue(null),
},
},
};
});
vi.doMock("@/lib/services/task", () => ({
TaskService: vi.fn().mockImplementation(() => ({
- reconcileAgentStatus: vi.fn(),
+ claimTasksForRuntimes: vi.fn().mockResolvedValue([]),
})),
}));
+ vi.doMock("@/lib/services/sweep", () => ({
+ sweepStaleState: vi.fn().mockResolvedValue(undefined),
+ }));
+ vi.doMock("@/lib/broadcast", () => ({
+ broadcastToUser: vi.fn().mockResolvedValue(undefined),
+ }));
- return (await import("./heartbeat/route")).POST;
+ return (await import("./tasks/poll/route")).POST;
}
- it("returns 400 when runtime_id is empty", async () => {
- const POST = await loadHeartbeat();
+ it("returns 400 when runtime_ids is empty array", async () => {
+ const POST = await loadPoll();
+ const res = await POST(
+ postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: [] })
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 400 when runtime_ids is missing", async () => {
+ const POST = await loadPoll();
+ const res = await POST(
+ postReq("http://localhost/api/daemon/tasks/poll", {})
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 400 when max_tasks is 0", async () => {
+ const POST = await loadPoll();
const res = await POST(
- postReq("http://localhost/api/daemon/heartbeat", { runtime_id: "" })
+ postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: ["r1"], max_tasks: 0 })
);
expect(res.status).toBe(400);
});
- it("returns 400 when runtime_id is missing", async () => {
- const POST = await loadHeartbeat();
+ it("returns 400 when runtime_ids contains empty strings", async () => {
+ const POST = await loadPoll();
const res = await POST(
- postReq("http://localhost/api/daemon/heartbeat", {})
+ postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: [""] })
);
expect(res.status).toBe(400);
});
+
+ it("returns 400 on malformed JSON", async () => {
+ const POST = await loadPoll();
+ const res = await POST(
+ postRaw("http://localhost/api/daemon/tasks/poll", "not json{{{")
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("invalid request body");
+ });
});
// -----------------------------------------------------------------------
diff --git a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts
deleted file mode 100644
index 29b960e10..000000000
--- a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
-
-const mockClaimTaskForRuntime = vi.fn();
-const mockGetAgent = vi.fn();
-const mockTaskToResponse = vi.fn();
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
-}));
-vi.mock("@alook/shared", () => ({
- createDb: vi.fn(() => ({})),
- queries: {
- agent: {
- getAgent: (...args: any[]) => mockGetAgent(...args),
- },
- task: {},
- },
-}));
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
- const params =
- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });
- }),
-}));
-vi.mock("@/lib/middleware/helpers", async () => {
- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(
- "@/lib/middleware/helpers"
- );
-});
-vi.mock("@/lib/services/task", () => {
- const MockTaskService = function (this: any) {
- this.claimTaskForRuntime = (...a: any[]) => mockClaimTaskForRuntime(...a);
- } as any;
- return { TaskService: MockTaskService };
-});
-vi.mock("@/lib/api/responses", () => ({
- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),
-}));
-
-import { POST } from "./route";
-
-const withParams = (runtimeId: string) => ({
- params: Promise.resolve({ runtimeId }),
-});
-
-describe("POST /api/daemon/runtimes/[runtimeId]/tasks/claim", () => {
- beforeEach(() => vi.clearAllMocks());
-
- it("returns { task: null } when no task available", async () => {
- mockClaimTaskForRuntime.mockResolvedValue(null);
-
- const res = await POST(
- new NextRequest("http://localhost/api/daemon/runtimes/rt1/tasks/claim", {
- method: "POST",
- }),
- withParams("rt1")
- );
- const body = await res.json();
-
- expect(res.status).toBe(200);
- expect(body).toEqual({ task: null });
- expect(mockClaimTaskForRuntime).toHaveBeenCalledWith("rt1");
- });
-
- it("returns task with agent data and type", async () => {
- const fakeTask = {
- id: "t1",
- agentId: "a1",
- conversationId: "conv1",
- runtimeId: "rt1",
- workspaceId: "w1",
- prompt: "do stuff",
- status: "dispatched",
- priority: 0,
- dispatchedAt: null,
- startedAt: null,
- completedAt: null,
- createdAt: new Date().toISOString(),
- };
- const fakeAgent = {
- id: "a1",
- name: "Agent 1",
- instructions: "be helpful",
- runtimeConfig: { model: "gpt-4" },
- };
-
- mockClaimTaskForRuntime.mockResolvedValue(fakeTask);
- mockGetAgent.mockResolvedValue(fakeAgent);
- mockTaskToResponse.mockReturnValue({
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "conv1",
- workspace_id: "w1",
- prompt: "do stuff",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: fakeTask.createdAt,
- type: "user_dm_message",
- });
-
- const res = await POST(
- new NextRequest("http://localhost/api/daemon/runtimes/rt1/tasks/claim", {
- method: "POST",
- }),
- withParams("rt1")
- );
- const body = await res.json();
-
- expect(res.status).toBe(200);
- expect(body.task).toBeTruthy();
- expect(body.task.agent).toEqual({
- instructions: "be helpful",
- name: "Agent 1",
- runtime_config: { model: "gpt-4" },
- });
- expect(body.task.type).toBe("user_dm_message");
- expect(mockGetAgent).toHaveBeenCalledWith({}, "a1", "w1");
- });
-});
diff --git a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts
deleted file mode 100644
index 81cbfebd7..000000000
--- a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createDb, queries } from "@alook/shared"
-import { withAuth } from "@/lib/middleware/auth";
-import { writeJSON, writeError } from "@/lib/middleware/helpers";
-import { taskToResponse } from "@/lib/api/responses";
-import { TaskService } from "@/lib/services/task";
-
-export const POST = withAuth(async (_req, ctx) => {
- const { env } = getCloudflareContext()
- const db = createDb((env as Env).DB)
-
- const runtimeId = ctx.params?.runtimeId;
- if (!runtimeId) {
- return writeError("runtime_id is required", 400);
- }
-
- const taskService = new TaskService(db);
- const task = await taskService.claimTaskForRuntime(runtimeId);
-
- if (!task) {
- return writeJSON({ task: null });
- }
-
- const agent = await queries.agent.getAgent(db, task.agentId, task.workspaceId);
-
- return writeJSON({
- task: {
- ...taskToResponse(task),
- agent: agent
- ? {
- instructions: agent.instructions,
- name: agent.name,
- runtime_config: agent.runtimeConfig || {},
- }
- : null,
- },
- });
-});
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts
index b1c4e494c..2a3156b0c 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts
@@ -47,7 +47,7 @@ describe("GET /api/daemon/tasks/[taskId]/status", () => {
expect(res.status).toBe(200);
expect(body).toEqual({ status: "running" });
- expect(mockGetTaskStatus).toHaveBeenCalledWith({}, "t1");
+ expect(mockGetTaskStatus).toHaveBeenCalledWith({}, "t1", "w1");
});
it("returns 404 when task not found", async () => {
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts
index 9413821ca..7cc005573 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts
@@ -7,12 +7,16 @@ export const GET = withAuth(async (_req, ctx) => {
const { env } = getCloudflareContext()
const db = createDb((env as Env).DB)
+ if (!ctx.workspaceId) {
+ return writeError("Forbidden: machine token required", 403);
+ }
+
const taskId = ctx.params?.taskId;
if (!taskId) {
return writeError("task_id is required", 400);
}
- const status = await queries.task.getTaskStatus(db, taskId);
+ const status = await queries.task.getTaskStatus(db, taskId, ctx.workspaceId);
if (!status) {
return writeError("task not found", 404);
}
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.ts
new file mode 100644
index 000000000..66d505284
--- /dev/null
+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
@@ -0,0 +1,183 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockUpdateRuntimesLastSeen = vi.fn();
+const mockGetAgent = vi.fn();
+const mockClaimTasksForRuntimes = vi.fn();
+const mockSweepStaleState = vi.fn();
+const mockBroadcastToUser = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@alook/shared", async () => {
+ const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...real,
+ createDb: vi.fn(() => ({})),
+ queries: {
+ runtime: {
+ updateRuntimesLastSeen: (...args: unknown[]) => mockUpdateRuntimesLastSeen(...args),
+ },
+ agent: {
+ getAgent: (...args: unknown[]) => mockGetAgent(...args),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/helpers", async () =>
+ await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
+);
+
+vi.mock("@/lib/services/task", () => ({
+ TaskService: class {
+ claimTasksForRuntimes(...args: unknown[]) { return mockClaimTasksForRuntimes(...args); }
+ },
+}));
+
+vi.mock("@/lib/services/sweep", () => ({
+ sweepStaleState: (...args: unknown[]) => mockSweepStaleState(...args),
+}));
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: (...args: unknown[]) => mockBroadcastToUser(...args),
+}));
+
+vi.mock("@/lib/logger", () => ({
+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+
+vi.mock("@/lib/api/responses", () => ({
+ taskToResponse: (t: any) => ({
+ id: t.id,
+ agent_id: t.agentId,
+ runtime_id: t.runtimeId,
+ workspace_id: t.workspaceId,
+ prompt: t.prompt,
+ status: t.status,
+ }),
+}));
+
+import { POST } from "./route";
+
+function postReq(body: unknown) {
+ return new NextRequest("http://localhost/api/daemon/tasks/poll", {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+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([]);
+
+ const res = await POST(postReq({ runtime_ids: ["r1"] }));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.tasks).toEqual([]);
+ });
+
+ it("returns tasks with agent data for claimed tasks", async () => {
+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1", "r2"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([
+ { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", prompt: "do it", status: "dispatched" },
+ ]);
+ mockGetAgent.mockResolvedValue({
+ instructions: "be helpful",
+ name: "Bot",
+ runtimeConfig: { model: "gpt-4" },
+ });
+
+ const res = await POST(postReq({ runtime_ids: ["r1", "r2"], max_tasks: 3 }));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.tasks).toHaveLength(1);
+ expect(body.tasks[0].id).toBe("t1");
+ expect(body.tasks[0].agent).toEqual({
+ instructions: "be helpful",
+ name: "Bot",
+ runtime_config: { model: "gpt-4" },
+ });
+ });
+
+ it("updates last_seen_at for all runtimes", async () => {
+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1", "r2"]);
+ 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"] }));
+
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);
+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {
+ type: "runtime.status",
+ runtimeId: "r1",
+ status: "online",
+ });
+ });
+
+ it("calls sweepStaleState", async () => {
+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([]);
+
+ await POST(postReq({ runtime_ids: ["r1"] }));
+
+ expect(mockSweepStaleState).toHaveBeenCalledWith({}, "w1");
+ });
+
+ // 403 without workspaceId is covered in routes.test.ts (cross-route validation suite)
+
+ it("respects max_tasks parameter", async () => {
+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([]);
+
+ await POST(postReq({ runtime_ids: ["r1"], max_tasks: 5 }));
+
+ expect(mockClaimTasksForRuntimes).toHaveBeenCalledWith(["r1"], 5, "w1");
+ });
+
+ it("defaults max_tasks to 1", async () => {
+ mockUpdateRuntimesLastSeen.mockResolvedValue(["r1"]);
+ mockSweepStaleState.mockResolvedValue(undefined);
+ mockBroadcastToUser.mockResolvedValue(undefined);
+ mockClaimTasksForRuntimes.mockResolvedValue([]);
+
+ await POST(postReq({ runtime_ids: ["r1"] }));
+
+ expect(mockClaimTasksForRuntimes).toHaveBeenCalledWith(["r1"], 1, "w1");
+ });
+});
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.ts
new file mode 100644
index 000000000..f564fda7c
--- /dev/null
+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts
@@ -0,0 +1,73 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { createDb, queries, PollRequestSchema } from "@alook/shared";
+import { withAuth } from "@/lib/middleware/auth";
+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
+import { taskToResponse } from "@/lib/api/responses";
+import { TaskService } from "@/lib/services/task";
+import { sweepStaleState } from "@/lib/services/sweep";
+import { broadcastToUser } from "@/lib/broadcast";
+import { log } from "@/lib/logger";
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const { env } = getCloudflareContext();
+ const db = createDb((env as Env).DB);
+
+ const [body, err] = await parseBody(req, PollRequestSchema);
+ if (err) return err;
+
+ if (!ctx.workspaceId) {
+ return writeError("Forbidden: machine token required", 403);
+ }
+
+ // 1. Liveness: bulk-update last_seen_at for all runtime IDs
+ const updatedIds = await queries.runtime.updateRuntimesLastSeen(
+ db,
+ body.runtime_ids,
+ ctx.workspaceId
+ );
+
+ if (updatedIds.length < body.runtime_ids.length) {
+ log.warn("Some runtime IDs not found in workspace", {
+ expected: body.runtime_ids.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(() => {});
+ }
+
+ // 2. Housekeeping: sweep stale state
+ await sweepStaleState(db, ctx.workspaceId);
+
+ // 3. Task claiming
+ const taskService = new TaskService(db);
+ const claimed = await taskService.claimTasksForRuntimes(
+ body.runtime_ids,
+ body.max_tasks,
+ ctx.workspaceId!
+ );
+
+ const tasks = [];
+ for (const task of claimed) {
+ const agent = await queries.agent.getAgent(db, task.agentId, task.workspaceId);
+ tasks.push({
+ ...taskToResponse(task),
+ agent: agent
+ ? {
+ instructions: agent.instructions,
+ name: agent.name,
+ runtime_config: agent.runtimeConfig || {},
+ }
+ : null,
+ });
+ }
+
+ return writeJSON({ tasks });
+});
diff --git a/src/web/src/app/api/email/[id]/body/route.test.ts b/src/web/src/app/api/email/[id]/body/route.test.ts
index 6185ec870..5c3c78525 100644
--- a/src/web/src/app/api/email/[id]/body/route.test.ts
+++ b/src/web/src/app/api/email/[id]/body/route.test.ts
@@ -10,13 +10,11 @@ vi.mock("@opennextjs/cloudflare", () => ({
}));
const mockGetEmailById = vi.fn();
-const mockGetAgent = vi.fn();
vi.mock("@alook/shared", () => ({
createDb: vi.fn(() => ({})),
queries: {
email: { getEmailById: (...args: unknown[]) => mockGetEmailById(...args) },
- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
},
}));
@@ -50,26 +48,25 @@ describe("GET /api/email/[id]/body", () => {
it("strips RFC822 headers (CRLF) and returns only body text", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
- mockGetAgent.mockResolvedValue({ id: "a1" });
mockR2Get.mockResolvedValue(
makeR2Object("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\n\r\nHello world")
);
- const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const req = new NextRequest("http://localhost/api/email/e1/body");
const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
expect(res.status).toBe(200);
expect(await res.text()).toBe("Hello world");
+ expect(mockGetEmailById).toHaveBeenCalledWith({}, "e1", "ws1");
});
it("strips RFC822 headers (LF) and returns only body text", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
- mockGetAgent.mockResolvedValue({ id: "a1" });
mockR2Get.mockResolvedValue(
makeR2Object("From: [email protected]\nTo: [email protected]\nSubject: Test\n\nHello world")
);
- const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const req = new NextRequest("http://localhost/api/email/e1/body");
const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
expect(res.status).toBe(200);
@@ -78,10 +75,9 @@ describe("GET /api/email/[id]/body", () => {
it("returns full content if no header/body separator found", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
- mockGetAgent.mockResolvedValue({ id: "a1" });
mockR2Get.mockResolvedValue(makeR2Object("Just plain text with no headers"));
- const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const req = new NextRequest("http://localhost/api/email/e1/body");
const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
expect(res.status).toBe(200);
@@ -90,10 +86,18 @@ describe("GET /api/email/[id]/body", () => {
it("returns 404 when R2 object not found", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
- mockGetAgent.mockResolvedValue({ id: "a1" });
mockR2Get.mockResolvedValue(null);
- const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const req = new NextRequest("http://localhost/api/email/e1/body");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 404 when email not found in workspace", async () => {
+ mockGetEmailById.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/email/e1/body");
const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
expect(res.status).toBe(404);
diff --git a/src/web/src/app/api/email/[id]/body/route.ts b/src/web/src/app/api/email/[id]/body/route.ts
index 44f24ae91..95d8f52ff 100644
--- a/src/web/src/app/api/email/[id]/body/route.ts
+++ b/src/web/src/app/api/email/[id]/body/route.ts
@@ -14,12 +14,9 @@ export const GET = withAuth(async (req, ctx) => {
const id = ctx.params?.id;
if (!id) return writeError("email id is required", 400);
- const email = await queries.email.getEmailById(db, id);
+ const email = await queries.email.getEmailById(db, id, ws.workspaceId);
if (!email) return writeError("email not found", 404);
- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId);
- if (!agent) return writeError("email not found", 404);
-
const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);
if (!object) {
return new Response("Email body not available", {
diff --git a/src/web/src/app/api/email/[id]/route.test.ts b/src/web/src/app/api/email/[id]/route.test.ts
index 628f712e3..2b48f19cb 100644
--- a/src/web/src/app/api/email/[id]/route.test.ts
+++ b/src/web/src/app/api/email/[id]/route.test.ts
@@ -2,7 +2,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockGetEmailById = vi.fn();
-const mockGetAgent = vi.fn();
const mockDeleteEmail = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
@@ -18,9 +17,6 @@ vi.mock("@alook/shared", () => ({
getEmailById: (...args: unknown[]) => mockGetEmailById(...args),
deleteEmail: (...args: unknown[]) => mockDeleteEmail(...args),
},
- agent: {
- getAgent: (...args: unknown[]) => mockGetAgent(...args),
- },
},
}));
@@ -43,37 +39,53 @@ vi.mock("@/lib/middleware/helpers", () => {
};
});
+vi.mock("@/lib/api/responses", () => ({
+ emailToResponse: (e: any) => ({ id: e.id }),
+}));
+
import { GET, DELETE } from "./route";
-describe("DELETE /api/email/[id]", () => {
+describe("GET /api/email/[id]", () => {
beforeEach(() => vi.clearAllMocks());
- it("deletes an email and returns 204", async () => {
+ it("returns email scoped by workspaceId", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
- mockGetAgent.mockResolvedValue({ id: "a1" });
- mockDeleteEmail.mockResolvedValue(undefined);
- const req = new NextRequest("http://localhost/api/email/e1?workspace_id=ws1", { method: "DELETE" });
- const res = await DELETE(req, { params: Promise.resolve({ id: "e1" }) } as any);
+ const req = new NextRequest("http://localhost/api/email/e1");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
- expect(res.status).toBe(204);
- expect(mockDeleteEmail).toHaveBeenCalledWith({}, "e1");
+ expect(res.status).toBe(200);
+ expect(mockGetEmailById).toHaveBeenCalledWith({}, "e1", "ws1");
});
- it("returns 404 when email not found", async () => {
+ it("returns 404 when email not found (wrong workspace)", async () => {
mockGetEmailById.mockResolvedValue(null);
- const req = new NextRequest("http://localhost/api/email/e1?workspace_id=ws1", { method: "DELETE" });
- const res = await DELETE(req, { params: Promise.resolve({ id: "e1" }) } as any);
+ const req = new NextRequest("http://localhost/api/email/e1");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
expect(res.status).toBe(404);
});
+});
+
+describe("DELETE /api/email/[id]", () => {
+ beforeEach(() => vi.clearAllMocks());
- it("returns 404 when agent not in workspace", async () => {
+ it("deletes an email scoped by workspaceId and returns 204", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
- mockGetAgent.mockResolvedValue(null);
+ mockDeleteEmail.mockResolvedValue(undefined);
+
+ const req = new NextRequest("http://localhost/api/email/e1", { method: "DELETE" });
+ const res = await DELETE(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(204);
+ expect(mockDeleteEmail).toHaveBeenCalledWith({}, "e1", "ws1");
+ });
+
+ it("returns 404 when email not found", async () => {
+ mockGetEmailById.mockResolvedValue(null);
- const req = new NextRequest("http://localhost/api/email/e1?workspace_id=ws1", { method: "DELETE" });
+ const req = new NextRequest("http://localhost/api/email/e1", { method: "DELETE" });
const res = await DELETE(req, { params: Promise.resolve({ id: "e1" }) } as any);
expect(res.status).toBe(404);
diff --git a/src/web/src/app/api/email/[id]/route.ts b/src/web/src/app/api/email/[id]/route.ts
index 07e7c5bfc..e63d33390 100644
--- a/src/web/src/app/api/email/[id]/route.ts
+++ b/src/web/src/app/api/email/[id]/route.ts
@@ -15,12 +15,9 @@ export const GET = withAuth(async (req, ctx) => {
const id = ctx.params?.id;
if (!id) return writeError("email id is required", 400);
- const email = await queries.email.getEmailById(db, id);
+ const email = await queries.email.getEmailById(db, id, ws.workspaceId);
if (!email) return writeError("email not found", 404);
- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId);
- if (!agent) return writeError("email not found", 404);
-
return writeJSON(emailToResponse(email));
});
@@ -34,13 +31,10 @@ export const DELETE = withAuth(async (req, ctx) => {
const id = ctx.params?.id;
if (!id) return writeError("email id is required", 400);
- const email = await queries.email.getEmailById(db, id);
+ const email = await queries.email.getEmailById(db, id, ws.workspaceId);
if (!email) return writeError("email not found", 404);
- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId);
- if (!agent) return writeError("email not found", 404);
-
- await queries.email.deleteEmail(db, id);
+ await queries.email.deleteEmail(db, id, ws.workspaceId);
return new Response(null, { status: 204 });
});
diff --git a/src/web/src/app/api/email/route.ts b/src/web/src/app/api/email/route.ts
index b6a1d36a4..e24152233 100644
--- a/src/web/src/app/api/email/route.ts
+++ b/src/web/src/app/api/email/route.ts
@@ -24,9 +24,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
let emailList;
if (folder === "inbox" && agentEmail) {
- emailList = await queries.email.getInboxEmails(db, agentId, agentEmail);
+ emailList = await queries.email.getInboxEmails(db, agentId, agentEmail, ws.workspaceId);
} else if (folder === "sent" && agentEmail) {
- emailList = await queries.email.getSentEmails(db, agentId, agentEmail);
+ emailList = await queries.email.getSentEmails(db, agentId, agentEmail, ws.workspaceId);
} else {
emailList = await queries.email.getEmailsByAgent(db, agentId, ws.workspaceId);
}
diff --git a/src/web/src/app/api/runtimes/route.test.ts b/src/web/src/app/api/runtimes/route.test.ts
index 8aa209807..0060b2c41 100644
--- a/src/web/src/app/api/runtimes/route.test.ts
+++ b/src/web/src/app/api/runtimes/route.test.ts
@@ -5,19 +5,22 @@ vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}));
-const mockMarkStaleRuntimesOffline = vi.fn();
const mockListAgentRuntimes = vi.fn();
+const mockSweepStaleState = vi.fn();
vi.mock("@alook/shared", () => ({
createDb: vi.fn(() => ({})),
queries: {
runtime: {
- markStaleRuntimesOffline: (...args: unknown[]) => mockMarkStaleRuntimesOffline(...args),
listAgentRuntimes: (...args: unknown[]) => mockListAgentRuntimes(...args),
},
},
}));
+vi.mock("@/lib/services/sweep", () => ({
+ sweepStaleState: (...args: unknown[]) => mockSweepStaleState(...args),
+}));
+
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
@@ -47,7 +50,7 @@ describe("GET /api/runtimes", () => {
beforeEach(() => vi.clearAllMocks());
it("lists runtimes in workspace", async () => {
- mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
+ mockSweepStaleState.mockResolvedValue(undefined);
mockListAgentRuntimes.mockResolvedValue([
{ id: "r1", name: "Runtime 1", status: "online" },
{ id: "r2", name: "Runtime 2", status: "offline" },
@@ -64,14 +67,14 @@ describe("GET /api/runtimes", () => {
expect(mockListAgentRuntimes).toHaveBeenCalledWith({}, "w1");
});
- it("marks stale runtimes offline before listing", async () => {
- mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
+ it("calls sweepStaleState before listing", async () => {
+ mockSweepStaleState.mockResolvedValue(undefined);
mockListAgentRuntimes.mockResolvedValue([]);
const req = new NextRequest("http://localhost/api/runtimes");
await GET(req, {} as any);
- expect(mockMarkStaleRuntimesOffline).toHaveBeenCalledWith({}, "w1");
- expect(mockMarkStaleRuntimesOffline).toHaveBeenCalledBefore(mockListAgentRuntimes);
+ expect(mockSweepStaleState).toHaveBeenCalledWith({}, "w1");
+ expect(mockSweepStaleState).toHaveBeenCalledBefore(mockListAgentRuntimes);
});
});
diff --git a/src/web/src/app/api/runtimes/route.ts b/src/web/src/app/api/runtimes/route.ts
index 1b07beea8..16ce785e7 100644
--- a/src/web/src/app/api/runtimes/route.ts
+++ b/src/web/src/app/api/runtimes/route.ts
@@ -4,6 +4,7 @@ import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON } from "@/lib/middleware/helpers";
import { runtimeToResponse } from "@/lib/api/responses";
+import { sweepStaleState } from "@/lib/services/sweep";
export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
@@ -12,8 +13,8 @@ export const GET = withAuth(async (req, ctx) => {
const { env } = getCloudflareContext()
const db = createDb((env as Env).DB)
- // Mark runtimes that haven't sent a heartbeat in >45s as offline
- await queries.runtime.markStaleRuntimesOffline(db, ws.workspaceId);
+ // Sweep stale state: mark offline runtimes, fail stuck tasks, reconcile agents
+ await sweepStaleState(db, ws.workspaceId);
const runtimes = await queries.runtime.listAgentRuntimes(db, ws.workspaceId);
return writeJSON(runtimes.map(runtimeToResponse));
diff --git a/src/web/src/app/api/tasks/[id]/messages/route.test.ts b/src/web/src/app/api/tasks/[id]/messages/route.test.ts
index f2ebae1b4..326bfe57d 100644
--- a/src/web/src/app/api/tasks/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/tasks/[id]/messages/route.test.ts
@@ -57,6 +57,17 @@ import { GET } from "./route";
describe("GET /api/tasks/[id]/messages", () => {
beforeEach(() => vi.clearAllMocks());
+ it("passes workspaceId to getTask", async () => {
+ const task = { id: "t1", workspaceId: "w1" };
+ mockGetTask.mockResolvedValue(task);
+ mockListTaskMessages.mockResolvedValue([]);
+ await GET(
+ new NextRequest("http://localhost/api/tasks/t1/messages"),
+ { params: Promise.resolve({ id: "t1" }) }
+ );
+ expect(mockGetTask).toHaveBeenCalledWith({}, "t1", "w1");
+ });
+
it("lists all messages", async () => {
const task = { id: "t1", workspaceId: "w1" };
const messages = [
diff --git a/src/web/src/app/api/tasks/[id]/messages/route.ts b/src/web/src/app/api/tasks/[id]/messages/route.ts
index 6c9e42a6d..c79ab1077 100644
--- a/src/web/src/app/api/tasks/[id]/messages/route.ts
+++ b/src/web/src/app/api/tasks/[id]/messages/route.ts
@@ -17,8 +17,8 @@ export const GET = withAuth(async (req, ctx) => {
return writeError("task id is required", 400);
}
- const task = await queries.task.getTask(db, id);
- if (!task || task.workspaceId !== ws.workspaceId) {
+ const task = await queries.task.getTask(db, id, ws.workspaceId);
+ if (!task) {
return writeError("task not found", 404);
}
diff --git a/src/web/src/app/api/tasks/[id]/route.test.ts b/src/web/src/app/api/tasks/[id]/route.test.ts
index 33c1e992c..b0aee33d1 100644
--- a/src/web/src/app/api/tasks/[id]/route.test.ts
+++ b/src/web/src/app/api/tasks/[id]/route.test.ts
@@ -75,10 +75,10 @@ describe("GET /api/tasks/[id]", () => {
status: "completed",
prompt: "hello",
});
- expect(mockGetTask).toHaveBeenCalledWith({}, "t1");
+ expect(mockGetTask).toHaveBeenCalledWith({}, "t1", "w1");
});
- it("returns 404 when not found", async () => {
+ it("returns 404 when not found (scoped by workspace)", async () => {
mockGetTask.mockResolvedValue(null);
const res = await GET(
@@ -90,24 +90,4 @@ describe("GET /api/tasks/[id]", () => {
expect(res.status).toBe(404);
expect(body.error).toBe("task not found");
});
-
- it("returns 404 when workspace mismatch", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "other-workspace",
- status: "completed",
- prompt: "hello",
- };
- mockGetTask.mockResolvedValue(task);
-
- const res = await GET(
- new NextRequest("http://localhost/api/tasks/t1"),
- { params: Promise.resolve({ id: "t1" }) }
- );
- const body = await res.json();
-
- expect(res.status).toBe(404);
- expect(body.error).toBe("task not found");
- });
});
diff --git a/src/web/src/app/api/tasks/[id]/route.ts b/src/web/src/app/api/tasks/[id]/route.ts
index bfeaa2c1b..028ad4dff 100644
--- a/src/web/src/app/api/tasks/[id]/route.ts
+++ b/src/web/src/app/api/tasks/[id]/route.ts
@@ -17,8 +17,8 @@ export const GET = withAuth(async (req, ctx) => {
return writeError("task id is required", 400);
}
- const task = await queries.task.getTask(db, id);
- if (!task || task.workspaceId !== ws.workspaceId) {
+ const task = await queries.task.getTask(db, id, ws.workspaceId);
+ if (!task) {
return writeError("task not found", 404);
}
diff --git a/src/web/src/lib/services/sweep.test.ts b/src/web/src/lib/services/sweep.test.ts
new file mode 100644
index 000000000..05b8e22c9
--- /dev/null
+++ b/src/web/src/lib/services/sweep.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+const mockMarkStaleRuntimesOffline = vi.fn();
+const mockFailStaleDispatchedTasks = vi.fn();
+const mockCountRunningTasks = vi.fn();
+const mockUpdateAgentStatus = vi.fn();
+
+vi.mock("@alook/shared", () => ({
+ queries: {
+ runtime: {
+ markStaleRuntimesOffline: (...args: unknown[]) => mockMarkStaleRuntimesOffline(...args),
+ },
+ task: {
+ failStaleDispatchedTasks: (...args: unknown[]) => mockFailStaleDispatchedTasks(...args),
+ countRunningTasks: (...args: unknown[]) => mockCountRunningTasks(...args),
+ },
+ agent: {
+ updateAgentStatus: (...args: unknown[]) => mockUpdateAgentStatus(...args),
+ },
+ },
+}));
+
+vi.mock("@/lib/logger", () => ({
+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },
+}));
+
+import { sweepStaleState } from "./sweep";
+
+const db = {} as any;
+
+describe("sweepStaleState", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("calls markStaleRuntimesOffline with workspace", async () => {
+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
+ mockFailStaleDispatchedTasks.mockResolvedValue([]);
+
+ await sweepStaleState(db, "w1");
+
+ expect(mockMarkStaleRuntimesOffline).toHaveBeenCalledWith(db, "w1");
+ });
+
+ it("calls failStaleDispatchedTasks with workspace", async () => {
+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
+ mockFailStaleDispatchedTasks.mockResolvedValue([]);
+
+ await sweepStaleState(db, "w1");
+
+ expect(mockFailStaleDispatchedTasks).toHaveBeenCalledWith(db, "w1");
+ });
+
+ it("reconciles agent status for each affected agent", async () => {
+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
+ mockFailStaleDispatchedTasks.mockResolvedValue([
+ { agentId: "a1", workspaceId: "w1" },
+ { agentId: "a2", workspaceId: "w1" },
+ ]);
+ mockCountRunningTasks.mockResolvedValue(0);
+ mockUpdateAgentStatus.mockResolvedValue(undefined);
+
+ await sweepStaleState(db, "w1");
+
+ expect(mockCountRunningTasks).toHaveBeenCalledTimes(2);
+ expect(mockUpdateAgentStatus).toHaveBeenCalledTimes(2);
+ });
+
+ it("deduplicates reconcile calls by agentId:workspaceId", async () => {
+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
+ mockFailStaleDispatchedTasks.mockResolvedValue([
+ { agentId: "a1", workspaceId: "w1" },
+ { agentId: "a1", workspaceId: "w1" },
+ { agentId: "a1", workspaceId: "w1" },
+ ]);
+ mockCountRunningTasks.mockResolvedValue(0);
+ mockUpdateAgentStatus.mockResolvedValue(undefined);
+
+ await sweepStaleState(db, "w1");
+
+ expect(mockCountRunningTasks).toHaveBeenCalledTimes(1);
+ expect(mockUpdateAgentStatus).toHaveBeenCalledTimes(1);
+ });
+
+ it("handles zero stale tasks gracefully", async () => {
+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);
+ mockFailStaleDispatchedTasks.mockResolvedValue([]);
+
+ await sweepStaleState(db, "w1");
+
+ expect(mockCountRunningTasks).not.toHaveBeenCalled();
+ expect(mockUpdateAgentStatus).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/web/src/lib/services/sweep.ts b/src/web/src/lib/services/sweep.ts
new file mode 100644
index 000000000..e6a404610
--- /dev/null
+++ b/src/web/src/lib/services/sweep.ts
@@ -0,0 +1,27 @@
+import type { Database } from "@alook/shared";
+import { queries } from "@alook/shared";
+import { TaskService } from "./task";
+
+/**
+ * Unified workspace housekeeping. Any code path that wants to ensure
+ * stale state is cleaned up just calls this one function.
+ */
+export async function sweepStaleState(db: Database, workspaceId: string) {
+ // 1. Mark runtimes offline if no liveness update in >45s
+ await queries.runtime.markStaleRuntimesOffline(db, workspaceId);
+
+ // 2. Fail tasks stuck in "dispatched" for >20s (daemon crashed between claim and start)
+ const stale = await queries.task.failStaleDispatchedTasks(db, workspaceId);
+
+ // 3. Reconcile agent status for any agents affected by step 2
+ if (stale.length > 0) {
+ const taskService = new TaskService(db);
+ const seen = new Set<string>();
+ for (const r of stale) {
+ const key = `${r.agentId}:${r.workspaceId}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ await taskService.reconcileAgentStatus(r.agentId, r.workspaceId);
+ }
+ }
+}
diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.ts
index 37f571161..23b11170c 100644
--- a/src/web/src/lib/services/task.test.ts
+++ b/src/web/src/lib/services/task.test.ts
@@ -10,7 +10,7 @@ vi.mock("@alook/shared", () => ({
failTask: vi.fn(),
getTask: vi.fn(),
countRunningTasks: vi.fn(),
- listPendingTasksByRuntime: vi.fn(),
+ listPendingTasksByRuntimes: vi.fn(),
},
agent: {
getAgent: vi.fn(),
@@ -135,20 +135,20 @@ describe("TaskService", () => {
});
});
- // ── claimTaskForRuntime ──────────────────────────────────────────
+ // ── claimTasksForRuntimes ─────────────────────────────────────────
- describe("claimTaskForRuntime", () => {
- it("returns null when no pending tasks", async () => {
- taskQ.listPendingTasksByRuntime.mockResolvedValue([]);
+ describe("claimTasksForRuntimes", () => {
+ it("returns empty array when no pending tasks", async () => {
+ taskQ.listPendingTasksByRuntimes.mockResolvedValue([]);
- const result = await service.claimTaskForRuntime("r1");
- expect(result).toBeNull();
+ const result = await service.claimTasksForRuntimes(["r1"], 1, "w1");
+ expect(result).toEqual([]);
});
it("deduplicates by agent ID and workspace ID", async () => {
- taskQ.listPendingTasksByRuntime.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", id: "t1" },
- { agentId: "a1", workspaceId: "w1", id: "t2" },
+ taskQ.listPendingTasksByRuntimes.mockResolvedValue([
+ { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
+ { agentId: "a1", workspaceId: "w1", id: "t2", runtimeId: "r1" },
]);
agentQ.getAgent.mockResolvedValue({
id: "a1",
@@ -161,13 +161,65 @@ describe("TaskService", () => {
runtimeId: "r1",
});
- const result = await service.claimTaskForRuntime("r1");
+ const result = await service.claimTasksForRuntimes(["r1"], 5, "w1");
- expect(result).toEqual({ id: "t1", agentId: "a1", runtimeId: "r1" });
- // claimTask on the service calls agentQ internally, but the key point
- // is taskQ.claimTask should only have been called once (dedup by agentId)
+ expect(result).toEqual([{ id: "t1", agentId: "a1", runtimeId: "r1" }]);
expect(taskQ.claimTask).toHaveBeenCalledTimes(1);
});
+
+ it("respects maxTasks limit", async () => {
+ taskQ.listPendingTasksByRuntimes.mockResolvedValue([
+ { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
+ { agentId: "a2", workspaceId: "w1", id: "t2", runtimeId: "r1" },
+ { agentId: "a3", workspaceId: "w1", id: "t3", runtimeId: "r1" },
+ ]);
+ agentQ.getAgent.mockResolvedValue({ id: "a1", maxConcurrentTasks: 5 });
+ taskQ.countRunningTasks.mockResolvedValue(0);
+
+ let callCount = 0;
+ taskQ.claimTask.mockImplementation(async () => {
+ callCount++;
+ return { id: `t${callCount}`, agentId: `a${callCount}`, runtimeId: "r1" };
+ });
+
+ const result = await service.claimTasksForRuntimes(["r1"], 2, "w1");
+ expect(result).toHaveLength(2);
+ });
+
+ it("skips claimed task whose runtimeId is not in the provided set", async () => {
+ taskQ.listPendingTasksByRuntimes.mockResolvedValue([
+ { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
+ ]);
+ agentQ.getAgent.mockResolvedValue({ id: "a1", maxConcurrentTasks: 5 });
+ taskQ.countRunningTasks.mockResolvedValue(0);
+ taskQ.claimTask.mockResolvedValue({
+ id: "t1",
+ agentId: "a1",
+ runtimeId: "r2", // different runtime than provided
+ });
+
+ const result = await service.claimTasksForRuntimes(["r1"], 5, "w1");
+ expect(result).toEqual([]);
+ });
+
+ it("returns tasks across multiple runtimes", async () => {
+ taskQ.listPendingTasksByRuntimes.mockResolvedValue([
+ { agentId: "a1", workspaceId: "w1", id: "t1", runtimeId: "r1" },
+ { agentId: "a2", workspaceId: "w1", id: "t2", runtimeId: "r2" },
+ ]);
+ agentQ.getAgent.mockResolvedValue({ id: "a1", maxConcurrentTasks: 5 });
+ taskQ.countRunningTasks.mockResolvedValue(0);
+
+ let callCount = 0;
+ taskQ.claimTask.mockImplementation(async () => {
+ callCount++;
+ const rid = callCount === 1 ? "r1" : "r2";
+ return { id: `t${callCount}`, agentId: `a${callCount}`, runtimeId: rid };
+ });
+
+ const result = await service.claimTasksForRuntimes(["r1", "r2"], 5, "w1");
+ expect(result).toHaveLength(2);
+ });
});
// ── startTask ────────────────────────────────────────────────────
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
index 37a455d72..5483cbe50 100644
--- a/src/web/src/lib/services/task.ts
+++ b/src/web/src/lib/services/task.ts
@@ -55,27 +55,30 @@ export class TaskService {
return task;
}
- async claimTaskForRuntime(runtimeId: string) {
- const tasks = await taskQueries.listPendingTasksByRuntime(
+ async claimTasksForRuntimes(runtimeIds: string[], maxTasks: number, workspaceId: string) {
+ const tasks = await taskQueries.listPendingTasksByRuntimes(
this.db,
- runtimeId
+ runtimeIds,
+ workspaceId
);
+ const runtimeIdSet = new Set(runtimeIds);
const triedAgents = new Set<string>();
+ const claimed: NonNullable<Awaited<ReturnType<typeof this.claimTask>>>[] = [];
for (const candidate of tasks) {
+ if (claimed.length >= maxTasks) break;
+
const key = `${candidate.agentId}:${candidate.workspaceId}`;
- if (triedAgents.has(key)) {
- continue;
- }
+ if (triedAgents.has(key)) continue;
triedAgents.add(key);
const task = await this.claimTask(candidate.agentId, candidate.workspaceId);
- if (task && task.runtimeId === runtimeId) {
- return task;
+ if (task && runtimeIdSet.has(task.runtimeId)) {
+ claimed.push(task);
}
}
- return null;
+ return claimed;
}
async startTask(taskId: string) {
diff --git a/src/web/src/test/e2e/daemon-lifecycle.test.ts b/src/web/src/test/e2e/daemon-lifecycle.test.ts
index 92700b868..ecb3b7422 100644
--- a/src/web/src/test/e2e/daemon-lifecycle.test.ts
+++ b/src/web/src/test/e2e/daemon-lifecycle.test.ts
@@ -68,15 +68,15 @@ describe("daemon lifecycle", () => {
expect(data.runtimes[0].id).toBe(registeredRuntimeId)
})
- it("POST /api/daemon/heartbeat updates last_seen_at", async () => {
- const res = await tokenRequest("/api/daemon/heartbeat", seed.machineToken, {
+ it("POST /api/daemon/tasks/poll updates last_seen_at", async () => {
+ const res = await tokenRequest("/api/daemon/tasks/poll", seed.machineToken, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ runtime_id: registeredRuntimeId }),
+ body: JSON.stringify({ runtime_ids: [registeredRuntimeId] }),
})
expect(res.status).toBe(200)
- const data = await res.json() as { status: string }
- expect(data.status).toBe("ok")
+ const data = await res.json() as { tasks: unknown[] }
+ expect(data.tasks).toEqual([])
// Verify last_seen_at was set in DB
const rows = sqlQuery<{ last_seen_at: string }>(
@@ -85,12 +85,12 @@ describe("daemon lifecycle", () => {
expect(rows[0]?.last_seen_at).toBeTruthy()
})
- it("POST /api/daemon/heartbeat rejects without machine token", async () => {
+ it("POST /api/daemon/tasks/poll rejects without machine token", async () => {
const APP_URL = process.env.APP_URL ?? "http://localhost:3000"
- const res = await fetch(`${APP_URL}/api/daemon/heartbeat`, {
+ const res = await fetch(`${APP_URL}/api/daemon/tasks/poll`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ runtime_id: registeredRuntimeId }),
+ body: JSON.stringify({ runtime_ids: [registeredRuntimeId] }),
})
expect(res.status).toBe(401)
})
diff --git a/src/web/src/test/e2e/task-lifecycle.test.ts b/src/web/src/test/e2e/task-lifecycle.test.ts
index e30cfb18e..d28fa4b62 100644
--- a/src/web/src/test/e2e/task-lifecycle.test.ts
+++ b/src/web/src/test/e2e/task-lifecycle.test.ts
@@ -45,21 +45,25 @@ describe("task lifecycle", () => {
expect(taskId).toBeTruthy()
})
- it("POST /api/daemon/runtimes/:id/tasks/claim claims the task", async () => {
+ it("POST /api/daemon/tasks/poll claims the task", async () => {
const res = await tokenRequest(
- `/api/daemon/runtimes/${seed.runtimeId}/tasks/claim`,
+ `/api/daemon/tasks/poll`,
seed.machineToken,
- { method: "POST" },
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ runtime_ids: [seed.runtimeId], max_tasks: 1 }),
+ },
)
expect(res.status).toBe(200)
- const data = await res.json() as { task: Record<string, unknown> | null }
- expect(data.task).not.toBeNull()
- expect(data.task!.id).toBe(taskId)
- expect(data.task!.status).toBe("dispatched")
- expect(data.task!.prompt).toBe("Run the e2e tests")
- // Claim response includes agent data
- expect(data.task!.agent).toBeTruthy()
- const agent = data.task!.agent as Record<string, unknown>
+ const data = await res.json() as { tasks: Array<Record<string, unknown>> }
+ expect(data.tasks).toHaveLength(1)
+ expect(data.tasks[0].id).toBe(taskId)
+ expect(data.tasks[0].status).toBe("dispatched")
+ expect(data.tasks[0].prompt).toBe("Run the e2e tests")
+ // Poll response includes agent data
+ expect(data.tasks[0].agent).toBeTruthy()
+ const agent = data.tasks[0].agent as Record<string, unknown>
expect(agent.name).toBe("Test Agent")
})
@@ -140,15 +144,19 @@ describe("task lifecycle", () => {
expect(data.status).toBe("completed")
})
- it("claim returns null when no tasks queued", async () => {
+ it("poll returns empty tasks when nothing queued", async () => {
const res = await tokenRequest(
- `/api/daemon/runtimes/${seed.runtimeId}/tasks/claim`,
+ `/api/daemon/tasks/poll`,
seed.machineToken,
- { method: "POST" },
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ runtime_ids: [seed.runtimeId], max_tasks: 1 }),
+ },
)
expect(res.status).toBe(200)
- const data = await res.json() as { task: unknown }
- expect(data.task).toBeNull()
+ const data = await res.json() as { tasks: unknown[] }
+ expect(data.tasks).toEqual([])
})
})
@@ -182,11 +190,15 @@ describe("task failure", () => {
failTaskId = msgData.task.id
}
- // Claim and start the task
+ // Claim and start the task via poll
await tokenRequest(
- `/api/daemon/runtimes/${seed.runtimeId}/tasks/claim`,
+ `/api/daemon/tasks/poll`,
seed.machineToken,
- { method: "POST" },
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ runtime_ids: [seed.runtimeId], max_tasks: 1 }),
+ },
)
await tokenRequest(
`/api/daemon/tasks/${failTaskId}/start`,