Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(ws-do): fix production WebSocket routes, expand protocol, add tests (#6)

Gener1510bf2d9fad
diff --git a/package.json b/package.json
index e72bb7af7..60f9beae1 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"dev:web": "pnpm --filter @alook/web dev",
"dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD pnpm --filter @alook/cli dev",
"dev:email": "pnpm --filter @alook/email-worker dev",
+ "dev:ws": "pnpm --filter @alook/ws-do dev",
"dev:send": "node -e \"const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}fetch('http://localhost:8787/simulate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({from:f,to:t,subject:s,body:b})}).then(r=>r.json()).then(console.log).catch(e=>console.error('Email worker not running?',e.message))\"",
"test:shared": "pnpm --filter @alook/shared test",
"test:cli": "pnpm --filter @alook/cli test",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d4ff922a1..5d37de025 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -205,6 +205,9 @@ importers:
typescript:
specifier: latest
version: 6.0.2
+ vitest:
+ specifier: ^4.1.3
wrangler:
specifier: latest
version: 4.81.1(@cloudflare/[email protected])
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index f972885b4..fa338b522 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -135,8 +135,11 @@ export interface CreateAgentRequest {
email_handle?: string;
}
-/** Generic WebSocket message envelope used by broadcast and WS hooks. */
-export interface WsMessage {
- type: string;
- [key: string]: unknown;
-}
+/** WebSocket event types — single source of truth for the WS protocol. */
+export type WsMessage =
+ | { type: "runtime.registered"; daemonId: string; hostname: string }
+ | { type: "runtime.status"; runtimeId: string; status: string }
+ | { type: "runtime.status"; runtimeIds: string[]; status: string }
+ | { type: "runtime.deleted"; daemonId: string }
+ | { type: "task.updated"; taskId: string; status: string }
+ | { type: "email.received"; agentId: string }
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
index f52ac9720..489eb74f8 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState, useCallback } from "react";
import { useParams } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
+import { useAgentContext } from "@/contexts/agent-context";
import { listEmails, getEmailBody } from "@/lib/api";
import type { Email } from "@alook/shared";
import { Badge } from "@/components/ui/badge";
@@ -28,6 +29,7 @@ export default function AgentEmailPage() {
const params = useParams();
const agentId = params.id as string;
const { workspaceId } = useWorkspace();
+ const { subscribeWs } = useAgentContext();
const [emails, setEmails] = useState<Email[]>([]);
const [loading, setLoading] = useState(true);
@@ -52,6 +54,15 @@ export default function AgentEmailPage() {
loadEmails();
}, [loadEmails]);
+ // Re-fetch when a new email arrives for this agent
+ useEffect(() => {
+ return subscribeWs((msg) => {
+ if (msg.type === "email.received" && msg.agentId === agentId) {
+ loadEmails();
+ }
+ });
+ }, [subscribeWs, agentId, loadEmails]);
+
const handleSelect = async (emailId: string) => {
setSelectedId(emailId);
setBody(null);
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 84e5bd59a..b63553b06 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -7,6 +7,7 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers";
import { messageToResponse, taskToResponse } from "@/lib/api/responses";
import { TaskService } from "@/lib/services/task";
import { log } from "@/lib/logger";
+import { broadcastToUser } from "@/lib/broadcast";
function truncateTitle(text: string, maxLen = 50): string {
const trimmed = text.replace(/\s+/g, " ").trim();
@@ -84,6 +85,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
ws.workspaceId,
content
);
+ broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, status: "queued" }).catch(() => {});
return writeJSON(
{ message: messageToResponse(message), task: taskToResponse(task) },
201
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts
index 9adf87d0f..de68cd985 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts
@@ -6,6 +6,7 @@ import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
import { taskToResponse } from "@/lib/api/responses";
import { TaskService } from "@/lib/services/task";
import { CompleteTaskRequestSchema } from "@alook/shared";
+import { broadcastToUser } from "@/lib/broadcast";
export const POST = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext()
@@ -31,6 +32,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
sessionId,
workDir
);
+ broadcastToUser(ctx.userId, { type: "task.updated", taskId, status: "completed" }).catch(() => {});
return writeJSON(taskToResponse(task));
} catch (e: unknown) {
return writeError(e instanceof Error ? e.message : "Unknown error", 400);
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts
index 3af67081a..62ac08546 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts
@@ -6,6 +6,7 @@ import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
import { taskToResponse } from "@/lib/api/responses";
import { TaskService } from "@/lib/services/task";
import { FailTaskRequestSchema } from "@alook/shared";
+import { broadcastToUser } from "@/lib/broadcast";
export const POST = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext()
@@ -22,6 +23,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const taskService = new TaskService(db);
try {
const task = await taskService.failTask(taskId, body.error);
+ broadcastToUser(ctx.userId, { type: "task.updated", taskId, status: "failed" }).catch(() => {});
return writeJSON(taskToResponse(task));
} catch (e: unknown) {
return writeError(e instanceof Error ? e.message : "Unknown error", 400);
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index b0894e195..03c28eaa8 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -3,6 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"
import { createDb, queries } from "@alook/shared"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { TaskService } from "@/lib/services/task"
+import { broadcastToUser } from "@/lib/broadcast"
export async function POST(req: NextRequest) {
const { env } = getCloudflareContext()
@@ -21,18 +22,22 @@ export async function POST(req: NextRequest) {
forwarded: body.forwarded ?? false,
})
- if (body.isWhitelisted) {
- const agent = await queries.agent.getAgent(db, body.agentId)
- if (agent && agent.runtimeId) {
- const conv = await queries.conversation.createConversation(db, {
- workspaceId: agent.workspaceId,
- agentId: agent.id,
- userId: agent.ownerId!,
- title: `Email: ${body.subject}`.slice(0, 50),
- })
- const taskService = new TaskService(db)
- await taskService.enqueueTask(agent.id, conv.id, agent.workspaceId, `New email from ${body.from}: ${body.subject}`)
- }
+ const agent = await queries.agent.getAgent(db, body.agentId)
+
+ if (body.isWhitelisted && agent && agent.runtimeId) {
+ const conv = await queries.conversation.createConversation(db, {
+ workspaceId: agent.workspaceId,
+ agentId: agent.id,
+ userId: agent.ownerId!,
+ title: `Email: ${body.subject}`.slice(0, 50),
+ })
+ const taskService = new TaskService(db)
+ await taskService.enqueueTask(agent.id, conv.id, agent.workspaceId, `New email from ${body.from}: ${body.subject}`)
+ }
+
+ // Notify UI for all emails (whitelisted or not)
+ if (agent?.ownerId) {
+ broadcastToUser(agent.ownerId, { type: "email.received", agentId: body.agentId }).catch(() => {})
}
return writeJSON({ ok: true })
diff --git a/src/web/src/app/api/ws/route.ts b/src/web/src/app/api/ws/route.ts
new file mode 100644
index 000000000..56b72eb14
--- /dev/null
+++ b/src/web/src/app/api/ws/route.ts
@@ -0,0 +1,22 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { createAuth } from "@/lib/auth"
+
+export async function GET(request: Request) {
+ const url = new URL(request.url)
+ const agentId = url.searchParams.get("agentId")
+ if (!agentId) return new Response("agentId required", { status: 400 })
+
+ const { env } = getCloudflareContext()
+ const wsEnv = env as Env
+
+ const auth = createAuth(wsEnv)
+ const session = await auth.api.getSession({ headers: request.headers })
+ if (!session) return new Response("Unauthorized", { status: 401 })
+
+ const userId = session.user.id
+ const doUrl = new URL(request.url)
+ doUrl.searchParams.set("userId", userId)
+ const doRequest = new Request(doUrl.toString(), request)
+ doRequest.headers.set("X-Authenticated-User", userId)
+ return wsEnv.WS_DO_WORKER.fetch(doRequest)
+}
diff --git a/src/web/src/app/api/ws/user/route.ts b/src/web/src/app/api/ws/user/route.ts
new file mode 100644
index 000000000..01da981d8
--- /dev/null
+++ b/src/web/src/app/api/ws/user/route.ts
@@ -0,0 +1,18 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { createAuth } from "@/lib/auth"
+
+export async function GET(request: Request) {
+ const { env } = getCloudflareContext()
+ const wsEnv = env as Env
+
+ const auth = createAuth(wsEnv)
+ const session = await auth.api.getSession({ headers: request.headers })
+ if (!session) return new Response("Unauthorized", { status: 401 })
+
+ const userId = session.user.id
+ const doUrl = new URL(request.url)
+ doUrl.searchParams.set("userId", userId)
+ const doRequest = new Request(doUrl.toString(), request)
+ doRequest.headers.set("X-Authenticated-User", userId)
+ return wsEnv.WS_DO_WORKER.fetch(doRequest)
+}
diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsx
index 87a9cd902..752b28c0f 100644
--- a/src/web/src/contexts/agent-context.tsx
+++ b/src/web/src/contexts/agent-context.tsx
@@ -29,11 +29,14 @@ import type {
} from "@alook/shared";
import { useUserWs } from "@/lib/use-user-ws";
+type WsSubscriber = (msg: WsMessage) => void;
+
interface AgentContextValue {
agents: Agent[];
runtimes: Runtime[];
loading: boolean;
reload: () => Promise<void>;
+ subscribeWs: (fn: WsSubscriber) => () => void;
handleCreateAgent: (req: CreateAgentRequest) => Promise<Agent | null>;
handleUpdateAgent: (id: string, req: UpdateAgentRequest) => Promise<boolean>;
handleDeleteAgent: (id: string) => Promise<boolean>;
@@ -62,6 +65,12 @@ export function AgentProvider({
const [runtimes, setRuntimes] = useState<Runtime[]>([]);
const [loading, setLoading] = useState(true);
const loadedRef = useRef(false);
+ const subscribersRef = useRef(new Set<WsSubscriber>());
+
+ const subscribeWs = useCallback((fn: WsSubscriber) => {
+ subscribersRef.current.add(fn);
+ return () => { subscribersRef.current.delete(fn); };
+ }, []);
const reload = useCallback(async () => {
try {
@@ -86,6 +95,10 @@ export function AgentProvider({
// Listen for real-time WS events
const handleWsMessage = useCallback(
(msg: WsMessage) => {
+ // Dispatch to all subscribers so child components can react
+ for (const fn of subscribersRef.current) fn(msg);
+
+ // AgentProvider only reloads agents/runtimes for runtime events
switch (msg.type) {
case "runtime.registered":
case "runtime.status":
@@ -201,6 +214,7 @@ export function AgentProvider({
runtimes,
loading,
reload,
+ subscribeWs,
handleCreateAgent,
handleUpdateAgent,
handleDeleteAgent,
diff --git a/src/ws-do/package.json b/src/ws-do/package.json
index 5edcfa50f..732167d4b 100644
--- a/src/ws-do/package.json
+++ b/src/ws-do/package.json
@@ -2,7 +2,17 @@
"name": "@alook/ws-do",
"version": "0.0.1",
"private": true,
- "scripts": { "dev": "wrangler dev --persist-to ../web/.wrangler/state", "deploy": "wrangler deploy" },
+ "scripts": {
+ "dev": "wrangler dev --persist-to ../web/.wrangler/state",
+ "deploy": "wrangler deploy",
+ "test": "vitest run --passWithNoTests"
+ },
"dependencies": { "@alook/shared": "workspace:*" },
- "devDependencies": { "wrangler": "latest", "typescript": "latest", "@cloudflare/workers-types": "latest", "@types/node": "latest" }
+ "devDependencies": {
+ "wrangler": "latest",
+ "typescript": "latest",
+ "@cloudflare/workers-types": "latest",
+ "@types/node": "latest",
+ "vitest": "^4.1.3"
+ }
}
diff --git a/src/ws-do/src/__mocks__/cf.ts b/src/ws-do/src/__mocks__/cf.ts
new file mode 100644
index 000000000..caa79ff6f
--- /dev/null
+++ b/src/ws-do/src/__mocks__/cf.ts
@@ -0,0 +1,72 @@
+import { vi } from "vitest"
+
+// --- DurableObjectState context mock ---
+
+export function createMockCtx() {
+ const webSockets: MockWebSocket[] = []
+
+ const acceptWebSocket = vi.fn((ws: MockWebSocket) => {
+ webSockets.push(ws)
+ })
+ const getWebSockets = vi.fn(() => webSockets)
+ const setWebSocketAutoResponse = vi.fn()
+
+ return {
+ ctx: { acceptWebSocket, getWebSockets, setWebSocketAutoResponse } as unknown as DurableObjectState,
+ acceptWebSocket,
+ getWebSockets,
+ setWebSocketAutoResponse,
+ webSockets,
+ }
+}
+
+// --- WebSocket mock ---
+
+export interface MockWebSocket {
+ readyState: number
+ send: ReturnType<typeof vi.fn>
+ close: ReturnType<typeof vi.fn>
+ serializeAttachment: ReturnType<typeof vi.fn>
+ deserializeAttachment: ReturnType<typeof vi.fn>
+ _attachment: unknown
+}
+
+export function createMockWebSocket(readyState = WebSocket.OPEN): MockWebSocket {
+ let attachment: unknown = null
+ const ws: MockWebSocket = {
+ readyState,
+ send: vi.fn(),
+ close: vi.fn(),
+ serializeAttachment: vi.fn((val: unknown) => { attachment = val }),
+ deserializeAttachment: vi.fn(() => attachment),
+ _attachment: null,
+ }
+ // Keep _attachment as a getter for test inspection
+ Object.defineProperty(ws, "_attachment", { get: () => attachment })
+ return ws
+}
+
+// --- WebSocketPair mock ---
+
+export function createMockWebSocketPair() {
+ const client = createMockWebSocket()
+ const server = createMockWebSocket()
+ return { client, server, pair: [client, server] }
+}
+
+// --- DurableObjectNamespace / Stub mock ---
+
+export function createMockDONamespace() {
+ const stubFetch = vi.fn().mockResolvedValue(new Response("ok"))
+ const stub = { fetch: stubFetch } as unknown as DurableObjectStub
+ const get = vi.fn().mockReturnValue(stub)
+ const idFromName = vi.fn().mockReturnValue("mock-do-id")
+
+ return {
+ namespace: { idFromName, get } as unknown as DurableObjectNamespace,
+ idFromName,
+ get,
+ stub,
+ stubFetch,
+ }
+}
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
new file mode 100644
index 000000000..4bd47d8d4
--- /dev/null
+++ b/src/ws-do/src/index.test.ts
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { createMockDONamespace } from "./__mocks__/cf"
+
+// Mock ws-durable so the router import doesn't pull in cloudflare:workers
+vi.mock("./ws-durable", () => ({
+ WebSocketDurableObject: class {},
+}))
+
+import handler from "./index"
+
+describe("ws-do router", () => {
+ let doMock: ReturnType<typeof createMockDONamespace>
+ let env: { WS_DO: DurableObjectNamespace }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ doMock = createMockDONamespace()
+ env = { WS_DO: doMock.namespace } as unknown as { WS_DO: DurableObjectNamespace }
+ })
+
+ describe("broadcast route", () => {
+ it("forwards POST /broadcast/user/:userId to correct DO instance", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response("ok"))
+ const req = new Request("http://localhost/broadcast/user/user-123", {
+ method: "POST",
+ body: JSON.stringify({ type: "runtime.status", runtimeId: "r1", status: "online" }),
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-123")
+ expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
+ expect(doMock.stubFetch).toHaveBeenCalled()
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/broadcast")
+ expect(stubReq.method).toBe("POST")
+ expect(res.status).toBe(200)
+ })
+ })
+
+ describe("WebSocket route", () => {
+ it("forwards GET with userId param to DO instance", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
+ const req = new Request("http://localhost/?userId=user-456", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-456")
+ expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
+ expect(doMock.stubFetch).toHaveBeenCalledWith(req)
+ })
+
+ it("returns 400 when userId is missing", async () => {
+ const req = new Request("http://localhost/", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(400)
+ expect(await res.text()).toBe("userId required")
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index 481affca2..f0c701743 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -9,7 +9,7 @@ export default {
const userId = userBroadcast[1]
const doId = env.WS_DO.idFromName("user:" + userId)
const stub = env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body }))
+ return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body, duplex: "half" } as RequestInit))
}
const userId = url.searchParams.get("userId")
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
new file mode 100644
index 000000000..bebd45fbb
--- /dev/null
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -0,0 +1,245 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { createMockCtx, createMockWebSocket } from "./__mocks__/cf"
+
+// --- Cloudflare Workers globals that don't exist in Node ---
+
+// Replace the global Response with one that allows status 101 and a webSocket property
+class CFResponse {
+ status: number
+ webSocket: unknown
+ private _body: BodyInit | null
+ private _headers: Headers
+
+ constructor(body: BodyInit | null = null, init: ResponseInit & { webSocket?: unknown } = {}) {
+ this._body = body
+ this._headers = new Headers(init.headers)
+ this.status = init.status ?? 200
+ this.webSocket = (init as { webSocket?: unknown }).webSocket
+ }
+
+ async text(): Promise<string> {
+ if (this._body == null) return ""
+ if (typeof this._body === "string") return this._body
+ return ""
+ }
+
+ async json(): Promise<unknown> {
+ return JSON.parse(await this.text())
+ }
+
+ get headers() { return this._headers }
+}
+
+globalThis.Response = CFResponse as unknown as typeof Response
+
+// WebSocketPair — creates a paired (client, server) mock
+globalThis.WebSocketPair = class {
+ 0: ReturnType<typeof createMockWebSocket>
+ 1: ReturnType<typeof createMockWebSocket>
+ constructor() {
+ this[0] = createMockWebSocket()
+ this[1] = createMockWebSocket()
+ }
+} as unknown as typeof WebSocketPair
+
+// WebSocketRequestResponsePair — used for the ping/pong auto-response
+globalThis.WebSocketRequestResponsePair = class {
+ constructor(public request: string, public response: string) {}
+} as unknown as typeof WebSocketRequestResponsePair
+
+// --- Module mocks ---
+
+// Mock cloudflare:workers DurableObject base class
+vi.mock("cloudflare:workers", () => ({
+ DurableObject: class {
+ ctx: unknown
+ env: unknown
+ constructor(ctx: unknown, env: unknown) {
+ this.ctx = ctx
+ this.env = env
+ }
+ },
+}))
+
+// Mock @alook/shared
+const mockGetValidSession = vi.fn<(db: unknown, token: string) => Promise<string | null>>()
+const mockCreateDb = vi.fn().mockReturnValue({})
+
+vi.mock("@alook/shared", () => ({
+ createDb: (d1: unknown) => mockCreateDb(d1),
+ queries: {
+ session: { getValidSession: (db: unknown, token: string) => mockGetValidSession(db, token) },
+ },
+}))
+
+// Import after mocks
+import { WebSocketDurableObject } from "./ws-durable"
+
+function createDO() {
+ const { ctx, getWebSockets } = createMockCtx()
+ const env = { DB: {} as D1Database, WS_DO: {} as DurableObjectNamespace }
+ const durable = new WebSocketDurableObject(ctx, env)
+ return { durable, ctx, getWebSockets, env }
+}
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe("fetch — WebSocket upgrade", () => {
+ it("returns 101 for valid WebSocket upgrade", async () => {
+ const { durable } = createDO()
+ const req = new Request("http://internal/?userId=u1", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ const res = await durable.fetch(req)
+
+ expect(res.status).toBe(101)
+ expect((res as unknown as CFResponse).webSocket).toBeDefined()
+ })
+
+ it("returns 426 for non-WebSocket request", async () => {
+ const { durable } = createDO()
+ const req = new Request("http://internal/")
+
+ const res = await durable.fetch(req)
+
+ expect(res.status).toBe(426)
+ })
+
+ it("pre-authenticates when X-Authenticated-User header is present", async () => {
+ const { durable, ctx } = createDO()
+ const req = new Request("http://internal/?userId=u1", {
+ headers: { Upgrade: "websocket", "X-Authenticated-User": "user-99" },
+ })
+
+ await durable.fetch(req)
+
+ // Check that acceptWebSocket was called and the server WS has authenticated state
+ const acceptCall = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0]
+ const serverWs = acceptCall[0]
+ expect(serverWs.deserializeAttachment()).toEqual({ userId: "user-99", authenticated: true })
+ })
+ })
+
+ describe("fetch — broadcast", () => {
+ it("sends message to all authenticated connections", async () => {
+ const { durable, ctx } = createDO()
+
+ // Set up two WebSockets: one authenticated, one not
+ const wsAuth = createMockWebSocket()
+ wsAuth.serializeAttachment({ userId: "u1", authenticated: true })
+ const wsUnauth = createMockWebSocket()
+ wsUnauth.serializeAttachment({ userId: "", authenticated: false })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth, wsUnauth])
+
+ const req = new Request("http://internal/broadcast", {
+ method: "POST",
+ body: JSON.stringify({ type: "runtime.status", runtimeId: "r1", status: "online" }),
+ })
+
+ const res = await durable.fetch(req)
+
+ expect(res.status).toBe(200)
+ expect(wsAuth.send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "runtime.status", runtimeId: "r1", status: "online" })
+ )
+ expect(wsUnauth.send).not.toHaveBeenCalled()
+ })
+
+ it("skips connections that are not OPEN", async () => {
+ const { durable, ctx } = createDO()
+
+ const wsOpen = createMockWebSocket(WebSocket.OPEN)
+ wsOpen.serializeAttachment({ userId: "u1", authenticated: true })
+ const wsClosed = createMockWebSocket(WebSocket.CLOSED)
+ wsClosed.serializeAttachment({ userId: "u1", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsOpen, wsClosed])
+
+ const req = new Request("http://internal/broadcast", {
+ method: "POST",
+ body: '{"type":"test"}',
+ })
+
+ await durable.fetch(req)
+
+ expect(wsOpen.send).toHaveBeenCalled()
+ expect(wsClosed.send).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("webSocketMessage — auth flow", () => {
+ it("authenticates with valid token and sends auth.ok", async () => {
+ const { durable } = createDO()
+ mockGetValidSession.mockResolvedValue("user-42")
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+
+ expect(mockGetValidSession).toHaveBeenCalledWith({}, "valid-token")
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ expect(ws.deserializeAttachment()).toEqual({ userId: "user-42", authenticated: true })
+ })
+
+ it("closes with 1008 on invalid token", async () => {
+ const { durable } = createDO()
+ mockGetValidSession.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "bad" }))
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+
+ it("closes unauthenticated connection sending non-auth message", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "some-event" }))
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Not authenticated")
+ })
+
+ it("closes on invalid JSON", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+
+ await durable.webSocketMessage(ws as any, "not-json")
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Invalid JSON")
+ })
+
+ it("ignores binary messages", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+
+ await durable.webSocketMessage(ws as any, new ArrayBuffer(4))
+
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("webSocketError", () => {
+ it("closes with 1011", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+
+ await durable.webSocketError(ws as any, new Error("boom"))
+
+ expect(ws.close).toHaveBeenCalledWith(1011, "Internal error")
+ })
+ })
+})
diff --git a/src/ws-do/vitest.config.ts b/src/ws-do/vitest.config.ts
new file mode 100644
index 000000000..5a8caddbb
--- /dev/null
+++ b/src/ws-do/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig, mergeConfig } from "vitest/config"
+import shared from "../../vitest.shared"
+
+export default mergeConfig(shared, defineConfig({
+ test: {
+ include: ["src/**/*.test.ts"],
+ },
+}))