Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(app): resolve task dispatch timeout in self-hosted mode (#96)
Generd4823234196e
diff --git a/src/app/src/lib/cli-env.ts b/src/app/src/lib/cli-env.tsindex 27a0f0ca4..a7f385d69 100644--- a/src/app/src/lib/cli-env.ts+++ b/src/app/src/lib/cli-env.ts@@ -10,12 +10,15 @@ import { readPids } from "./pid.js";* 3. App mode (npx): ~/.alook/self-hosted (same as 1)*/export function buildCliEnv(webPort?: number): Record<string, string> {- const port = webPort ?? (readPids().ports?.web ?? DEFAULT_PORTS.web);+ const pids = readPids();+ const port = webPort ?? (pids.ports?.web ?? DEFAULT_PORTS.web);+ const wsDoPort = pids.ports?.wsDo ?? DEFAULT_PORTS.wsDo;return {...(process.env as Record<string, string>),ALOOK_SERVER_URL: WEB_URL(port),ALOOK_PROJECT_ROOT: SELF_HOSTED_DIR,ALOOK_CMD_PREFIX: "npx @alook/app cli",ALOOK_HEALTH_PORT: "19515",+ ALOOK_WS_DO_PORT: String(wsDoPort),};}diff --git a/src/cli/daemon/ws-client.ts b/src/cli/daemon/ws-client.tsindex 5a2340e59..390ae496d 100644--- a/src/cli/daemon/ws-client.ts+++ b/src/cli/daemon/ws-client.ts@@ -8,7 +8,7 @@ const WS_RECONNECT_INIT = 1000;const WS_RECONNECT_MAX = 30_000;const WS_PING_INTERVAL = 25_000;const WS_LIVENESS_TIMEOUT = 50_000;-const WS_DO_DEV_PORT = 8789;+const WS_DO_DEV_PORT = Number(process.env.ALOOK_WS_DO_PORT) || 8789;export interface DaemonWsClientOptions {serverURL: string;diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.tsindex 7fcb9dfaa..6a704085b 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts@@ -57,7 +57,7 @@ vi.mock("@/lib/logger", () => ({}));vi.mock("@/lib/broadcast", () => ({- broadcastToDaemon: vi.fn(() => Promise.resolve()),+ broadcastToDaemon: vi.fn(() => Promise.resolve({ sent: 1 })),}));import { POST } from "./route";diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.tsindex 3ef41a218..ef6794fe6 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts@@ -60,7 +60,7 @@ vi.mock("@/lib/logger", () => ({}));vi.mock("@/lib/broadcast", () => ({- broadcastToDaemon: vi.fn(() => Promise.resolve()),+ broadcastToDaemon: vi.fn(() => Promise.resolve({ sent: 1 })),}));// Mock global fetch for npm registrydiff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.tsindex cd9bdeb2b..014ad98bf 100644--- a/src/web/src/lib/broadcast.ts+++ b/src/web/src/lib/broadcast.ts@@ -4,7 +4,7 @@ import { DEV_WS_DO_URL, createLogger } from "@alook/shared"const log = createLogger({ service: "broadcast" })-async function doSend(url: string, body: string, label: Record<string, string>) {+async function doSend(url: string, body: string, label: Record<string, string>): Promise<{ sent: number }> {let wsDoUrl: string | undefinedtry {const { env } = getCloudflareContext()@@ -15,7 +15,14 @@ async function doSend(url: string, body: string, label: Record<string, string>)method: "POST",body,})- if (res.ok) return+ if (res.ok) {+ try {+ const json = await res.json() as { sent?: number }+ return { sent: json.sent ?? 0 }+ } catch {+ return { sent: 0 }+ }+ }log.warn("broadcast service-binding non-ok", { ...label, status: res.status })} catch {// Service binding unavailable — fall through to HTTP@@ -30,17 +37,23 @@ async function doSend(url: string, body: string, label: Record<string, string>)if (!res.ok) {throw new Error(`broadcast failed: ${res.status}`)}+ try {+ const json = await res.json() as { sent?: number }+ return { sent: json.sent ?? 0 }+ } catch {+ return { sent: 0 }+ }}function sendBroadcast(url: string, body: string, label: Record<string, string>): Promise<void> {const promise = doSend(url, body, label)try {const { ctx } = getCloudflareContext()- ctx.waitUntil(promise)+ ctx.waitUntil(promise.catch(() => {}))} catch {// Not in CF context — promise runs on its own}- return promise+ return promise.then(() => {})}export function broadcastToUser(userId: string, message: WsMessage): Promise<void> {@@ -59,10 +72,19 @@ export function broadcastToAgent(agentId: string, message: WsMessage): Promise<v)}-export function broadcastToDaemon(daemonId: string, message: DaemonPushMessage): Promise<void> {- return sendBroadcast(+export function broadcastToDaemon(daemonId: string, message: DaemonPushMessage): Promise<{ sent: number }> {+ const promise = doSend(`/broadcast/daemon/${daemonId}`,JSON.stringify(message),{ daemonId, type: message.type },)+ try {+ // CF worker may terminate before the fetch completes if the response is sent early;+ // waitUntil keeps the isolate alive until the broadcast resolves.+ const { ctx } = getCloudflareContext()+ ctx.waitUntil(promise.catch(() => {}))+ } catch {+ // Not in CF context — promise runs on its own+ }+ return promise}diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.tsindex d669c0cf0..4ab818090 100644--- a/src/web/src/lib/services/task.ts+++ b/src/web/src/lib/services/task.ts@@ -439,10 +439,13 @@ export class TaskService {}try {- await broadcastToDaemon(runtime.daemonId, {+ const { sent } = await broadcastToDaemon(runtime.daemonId, {type: "daemon.tasks",tasks: payloads,});+ if (sent === 0) {+ await taskQueries.revertDispatchedToQueued(this.db, task.id, workspaceId);+ }} catch {await taskQueries.revertDispatchedToQueued(this.db, task.id, workspaceId);}diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex f07ebd632..6b77a530d 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -152,12 +152,28 @@ describe("WebSocketDurableObject", () => {const res = await durable.fetch(req)expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ sent: 1 })expect(wsAuth.send).toHaveBeenCalledWith(JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }))expect(wsUnauth.send).not.toHaveBeenCalled()})+ it("returns sent: 0 when no connections exist", async () => {+ const { durable, ctx } = createDO()+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])++ const req = new Request("http://internal/broadcast", {+ method: "POST",+ body: '{"type":"test"}',+ })++ const res = await durable.fetch(req)++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ sent: 0 })+ })+it("skips connections that are not OPEN", async () => {const { durable, ctx } = createDO()diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 786c64ccc..8b118aefa 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -13,8 +13,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {if (url.pathname === "/broadcast" && request.method === "POST") {const body = await request.text()- this.broadcast(body)- return new Response("ok")+ const sent = this.broadcast(body)+ return new Response(JSON.stringify({ sent }), {+ headers: { "Content-Type": "application/json" },+ })}if (request.headers.get("Upgrade") !== "websocket") {@@ -91,13 +93,16 @@ export class WebSocketDurableObject extends DurableObject<Env> {try { ws.close(1011, "Internal error") } catch {}}- private broadcast(message: string): void {+ private broadcast(message: string): number {+ let sent = 0for (const ws of this.ctx.getWebSockets()) {const state = ws.deserializeAttachment() as ConnectionStateif (state.authenticated && ws.readyState === WebSocket.OPEN) {ws.send(message)+ sent++}}+ return sent}private async validateToken(token: string): Promise<string | null> {