Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

test(web): add unit tests for flags, inbox, traces, and comments routes (#218)

Generd5d049c29262
diff --git a/src/web/src/app/api/flags/[messageId]/route.test.ts b/src/web/src/app/api/flags/[messageId]/route.test.ts
new file mode 100644
index 000000000..cfe6c91db
--- /dev/null
+++ b/src/web/src/app/api/flags/[messageId]/route.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockUnflagMessage = vi.fn();
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ messageFlag: {
+ unflagMessage: (...args: unknown[]) => mockUnflagMessage(...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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+import { DELETE } from "./route";
+
+describe("DELETE /api/flags/[messageId]", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns 400 when messageId param is missing", async () => {
+ const req = new NextRequest("http://localhost/api/flags/", { method: "DELETE" });
+ const res = await DELETE(req, { params: Promise.resolve({}) } as any);
+
+ expect(res.status).toBe(400);
+ });
+
+ it("unflag message and returns 204", async () => {
+ mockUnflagMessage.mockResolvedValue(undefined);
+
+ const req = new NextRequest("http://localhost/api/flags/m1", { method: "DELETE" });
+ const res = await DELETE(req, { params: Promise.resolve({ messageId: "m1" }) } as any);
+
+ expect(res.status).toBe(204);
+ expect(mockUnflagMessage).toHaveBeenCalledWith({}, "m1", "u1", "w1");
+ });
+});
diff --git a/src/web/src/app/api/flags/count/route.test.ts b/src/web/src/app/api/flags/count/route.test.ts
new file mode 100644
index 000000000..841c1f955
--- /dev/null
+++ b/src/web/src/app/api/flags/count/route.test.ts
@@ -0,0 +1,65 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetFlaggedCount = vi.fn();
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ messageFlag: {
+ getFlaggedCount: (...args: unknown[]) => mockGetFlaggedCount(...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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+import { GET } from "./route";
+
+describe("GET /api/flags/count", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns the flagged message count", async () => {
+ mockGetFlaggedCount.mockResolvedValue(5);
+
+ const req = new NextRequest("http://localhost/api/flags/count");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ count: 5 });
+ expect(mockGetFlaggedCount).toHaveBeenCalledWith({}, "u1", "w1");
+ });
+
+ it("returns zero when no flagged messages", async () => {
+ mockGetFlaggedCount.mockResolvedValue(0);
+
+ const req = new NextRequest("http://localhost/api/flags/count");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ count: 0 });
+ });
+});
diff --git a/src/web/src/app/api/flags/route.test.ts b/src/web/src/app/api/flags/route.test.ts
new file mode 100644
index 000000000..a45dfa4aa
--- /dev/null
+++ b/src/web/src/app/api/flags/route.test.ts
@@ -0,0 +1,211 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockListFlaggedMessageIds = vi.fn();
+const mockListFlaggedMessages = vi.fn();
+const mockGetMessageWorkspaceId = vi.fn();
+const mockFlagMessage = vi.fn();
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ messageFlag: {
+ listFlaggedMessageIds: (...args: unknown[]) => mockListFlaggedMessageIds(...args),
+ listFlaggedMessages: (...args: unknown[]) => mockListFlaggedMessages(...args),
+ getMessageWorkspaceId: (...args: unknown[]) => mockGetMessageWorkspaceId(...args),
+ flagMessage: (...args: unknown[]) => mockFlagMessage(...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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+import { GET, POST } from "./route";
+
+describe("GET /api/flags", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ describe("ids_only=true", () => {
+ it("returns 400 when conversation_id is missing", async () => {
+ const req = new NextRequest("http://localhost/api/flags?ids_only=true");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toContain("conversation_id");
+ });
+
+ it("returns message_ids when conversation_id is provided", async () => {
+ mockListFlaggedMessageIds.mockResolvedValue(["m1", "m2"]);
+
+ const req = new NextRequest("http://localhost/api/flags?ids_only=true&conversation_id=c1");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ message_ids: ["m1", "m2"] });
+ expect(mockListFlaggedMessageIds).toHaveBeenCalledWith({}, "u1", "w1", "c1");
+ });
+ });
+
+ describe("normal list", () => {
+ it("returns flagged messages with defaults (limit=30, no before)", async () => {
+ mockListFlaggedMessages.mockResolvedValue({ items: [{ id: "m1" }], hasMore: false });
+
+ const req = new NextRequest("http://localhost/api/flags");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ items: [{ id: "m1" }], has_more: false });
+ expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 30, before: undefined });
+ });
+
+ it("clamps limit to 1-100 range", async () => {
+ mockListFlaggedMessages.mockResolvedValue({ items: [], hasMore: false });
+
+ const req = new NextRequest("http://localhost/api/flags?limit=200");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 100, before: undefined });
+ });
+
+ it("clamps limit minimum to 1", async () => {
+ mockListFlaggedMessages.mockResolvedValue({ items: [], hasMore: false });
+
+ const req = new NextRequest("http://localhost/api/flags?limit=-5");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 1, before: undefined });
+ });
+
+ it("passes valid before timestamp", async () => {
+ mockListFlaggedMessages.mockResolvedValue({ items: [], hasMore: false });
+
+ const req = new NextRequest("http://localhost/api/flags?before=2024-01-01T00:00:00Z");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 30, before: "2024-01-01T00:00:00Z" });
+ });
+
+ it("returns 400 for invalid before timestamp", async () => {
+ const req = new NextRequest("http://localhost/api/flags?before=not-a-date");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toContain("invalid before timestamp");
+ });
+ });
+});
+
+describe("POST /api/flags", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns 400 when messageId is missing", async () => {
+ const req = new NextRequest("http://localhost/api/flags", {
+ method: "POST",
+ body: JSON.stringify({}),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await POST(req, {} as any);
+
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toContain("messageId");
+ });
+
+ it("returns 400 when body is not valid JSON", async () => {
+ const req = new NextRequest("http://localhost/api/flags", {
+ method: "POST",
+ body: "not json",
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await POST(req, {} as any);
+
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 404 when message workspace id is null", async () => {
+ mockGetMessageWorkspaceId.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/flags", {
+ method: "POST",
+ body: JSON.stringify({ messageId: "m1" }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await POST(req, {} as any);
+
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "message not found" });
+ });
+
+ it("returns 404 when message belongs to different workspace", async () => {
+ mockGetMessageWorkspaceId.mockResolvedValue("other-workspace");
+
+ const req = new NextRequest("http://localhost/api/flags", {
+ method: "POST",
+ body: JSON.stringify({ messageId: "m1" }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await POST(req, {} as any);
+
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "message not found" });
+ });
+
+ it("returns 201 when message is newly flagged", async () => {
+ mockGetMessageWorkspaceId.mockResolvedValue("w1");
+ mockFlagMessage.mockResolvedValue({ id: "flag1" });
+
+ const req = new NextRequest("http://localhost/api/flags", {
+ method: "POST",
+ body: JSON.stringify({ messageId: "m1" }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await POST(req, {} as any);
+
+ expect(res.status).toBe(201);
+ expect(await res.json()).toEqual({ flagged: true });
+ expect(mockFlagMessage).toHaveBeenCalledWith({}, { messageId: "m1", userId: "u1", workspaceId: "w1" });
+ });
+
+ it("returns 200 when message is already flagged", async () => {
+ mockGetMessageWorkspaceId.mockResolvedValue("w1");
+ mockFlagMessage.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/flags", {
+ method: "POST",
+ body: JSON.stringify({ messageId: "m1" }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await POST(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ flagged: true });
+ });
+});
diff --git a/src/web/src/app/api/inbox/count/route.test.ts b/src/web/src/app/api/inbox/count/route.test.ts
new file mode 100644
index 000000000..f28314a7a
--- /dev/null
+++ b/src/web/src/app/api/inbox/count/route.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetUnreadCount = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ inbox: {
+ getUnreadCount: (...args: unknown[]) => mockGetUnreadCount(...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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+vi.mock("@/lib/cache", () => ({
+ cached: vi.fn((_key: string, _ttl: number, fn: () => any) => fn()),
+ cacheKeys: { inboxCount: vi.fn(() => "test-key") },
+}));
+
+import { GET } from "./route";
+
+describe("GET /api/inbox/count", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns unread count with default types", async () => {
+ mockGetUnreadCount.mockResolvedValue(5);
+
+ const res = await GET(new NextRequest("http://localhost/api/inbox/count"));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toEqual({ count: 5 });
+ expect(mockGetUnreadCount).toHaveBeenCalledWith({}, "u1", "w1", ["user_dm_message"]);
+ });
+
+ it("filters types param by valid types", async () => {
+ mockGetUnreadCount.mockResolvedValue(2);
+
+ const res = await GET(
+ new NextRequest("http://localhost/api/inbox/count?types=calendar_event,email_notification")
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toEqual({ count: 2 });
+ expect(mockGetUnreadCount).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ ["calendar_event", "email_notification"]
+ );
+ });
+
+ it("defaults to user_dm_message when all types are invalid", async () => {
+ mockGetUnreadCount.mockResolvedValue(0);
+
+ await GET(new NextRequest("http://localhost/api/inbox/count?types=bogus"));
+
+ expect(mockGetUnreadCount).toHaveBeenCalledWith({}, "u1", "w1", ["user_dm_message"]);
+ });
+
+ it("returns count 0 when no unread items", async () => {
+ mockGetUnreadCount.mockResolvedValue(0);
+
+ const res = await GET(new NextRequest("http://localhost/api/inbox/count"));
+ const body = await res.json();
+
+ expect(body).toEqual({ count: 0 });
+ });
+
+ it("uses cached wrapper with correct key and ttl", async () => {
+ mockGetUnreadCount.mockResolvedValue(3);
+ const { cached, cacheKeys } = await import("@/lib/cache");
+
+ await GET(new NextRequest("http://localhost/api/inbox/count"));
+
+ expect(cacheKeys.inboxCount).toHaveBeenCalledWith("u1", "w1", ["user_dm_message"]);
+ expect(cached).toHaveBeenCalledWith("test-key", 60, expect.any(Function));
+ });
+});
diff --git a/src/web/src/app/api/inbox/read-all/route.test.ts b/src/web/src/app/api/inbox/read-all/route.test.ts
new file mode 100644
index 000000000..4594468fe
--- /dev/null
+++ b/src/web/src/app/api/inbox/read-all/route.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockMarkAllConversationsRead = vi.fn();
+const mockInvalidateInboxCounts = vi.fn().mockResolvedValue(undefined);
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ inbox: {
+ markAllConversationsRead: (...args: unknown[]) => mockMarkAllConversationsRead(...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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/cache", () => ({
+ invalidateInboxCounts: (...args: unknown[]) => mockInvalidateInboxCounts(...args),
+}));
+
+import { POST } from "./route";
+
+describe("POST /api/inbox/read-all", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("marks all conversations read and returns 204", async () => {
+ mockMarkAllConversationsRead.mockResolvedValue(undefined);
+
+ const res = await POST(
+ new NextRequest("http://localhost/api/inbox/read-all", { method: "POST" })
+ );
+
+ expect(res.status).toBe(204);
+ expect(mockMarkAllConversationsRead).toHaveBeenCalledWith({}, "u1", "w1");
+ expect(mockInvalidateInboxCounts).toHaveBeenCalledWith("u1", "w1");
+ });
+
+ it("does not fail if invalidateInboxCounts rejects", async () => {
+ mockMarkAllConversationsRead.mockResolvedValue(undefined);
+ mockInvalidateInboxCounts.mockRejectedValue(new Error("cache error"));
+
+ const res = await POST(
+ new NextRequest("http://localhost/api/inbox/read-all", { method: "POST" })
+ );
+
+ expect(res.status).toBe(204);
+ expect(mockMarkAllConversationsRead).toHaveBeenCalledWith({}, "u1", "w1");
+ });
+
+ it("calls markAllConversationsRead with correct workspace and user", async () => {
+ mockMarkAllConversationsRead.mockResolvedValue(undefined);
+
+ await POST(new NextRequest("http://localhost/api/inbox/read-all", { method: "POST" }));
+
+ expect(mockMarkAllConversationsRead).toHaveBeenCalledTimes(1);
+ expect(mockMarkAllConversationsRead).toHaveBeenCalledWith({}, "u1", "w1");
+ });
+});
diff --git a/src/web/src/app/api/inbox/read/route.test.ts b/src/web/src/app/api/inbox/read/route.test.ts
new file mode 100644
index 000000000..6eb7a251a
--- /dev/null
+++ b/src/web/src/app/api/inbox/read/route.test.ts
@@ -0,0 +1,119 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetConversation = vi.fn();
+const mockMarkConversationRead = vi.fn();
+const mockInvalidateInboxCounts = vi.fn().mockResolvedValue(undefined);
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ conversation: {
+ getConversation: (...args: unknown[]) => mockGetConversation(...args),
+ },
+ inbox: {
+ markConversationRead: (...args: unknown[]) => mockMarkConversationRead(...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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/cache", () => ({
+ invalidateInboxCounts: (...args: unknown[]) => mockInvalidateInboxCounts(...args),
+}));
+
+import { POST } from "./route";
+
+describe("POST /api/inbox/read", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ function makeRequest(body?: string) {
+ return new NextRequest("http://localhost/api/inbox/read", {
+ method: "POST",
+ body,
+ headers: body !== undefined ? { "Content-Type": "application/json" } : {},
+ });
+ }
+
+ it("returns 400 for invalid JSON body", async () => {
+ const res = await POST(makeRequest("not-json"));
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("invalid JSON body");
+ });
+
+ it("returns 400 when conversationId is missing", async () => {
+ const res = await POST(makeRequest(JSON.stringify({})));
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("conversationId is required");
+ });
+
+ it("returns 400 when conversationId is empty string", async () => {
+ const res = await POST(makeRequest(JSON.stringify({ conversationId: "" })));
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("conversationId is required");
+ });
+
+ it("returns 404 when conversation not found", async () => {
+ mockGetConversation.mockResolvedValue(null);
+
+ const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));
+ const body = await res.json();
+
+ expect(res.status).toBe(404);
+ expect(body.error).toBe("conversation not found");
+ expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
+ });
+
+ it("returns 404 when conversation belongs to different user", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", userId: "other-user" });
+
+ const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));
+ const body = await res.json();
+
+ expect(res.status).toBe(404);
+ expect(body.error).toBe("conversation not found");
+ });
+
+ it("marks conversation as read and returns 204", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });
+ mockMarkConversationRead.mockResolvedValue(undefined);
+
+ const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));
+
+ expect(res.status).toBe(204);
+ expect(mockMarkConversationRead).toHaveBeenCalledWith({}, "u1", "c1");
+ expect(mockInvalidateInboxCounts).toHaveBeenCalledWith("u1", "w1");
+ });
+
+ it("does not fail if invalidateInboxCounts rejects", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });
+ mockMarkConversationRead.mockResolvedValue(undefined);
+ mockInvalidateInboxCounts.mockRejectedValue(new Error("cache error"));
+
+ const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));
+
+ expect(res.status).toBe(204);
+ });
+});
diff --git a/src/web/src/app/api/inbox/route.test.ts b/src/web/src/app/api/inbox/route.test.ts
new file mode 100644
index 000000000..430f4be8d
--- /dev/null
+++ b/src/web/src/app/api/inbox/route.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockListUnreadConversations = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ inbox: {
+ listUnreadConversations: (...args: unknown[]) => mockListUnreadConversations(...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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+import { GET } from "./route";
+
+describe("GET /api/inbox", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns items and has_more with default limit", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [{ id: "c1" }], hasMore: false });
+
+ const res = await GET(new NextRequest("http://localhost/api/inbox"));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toEqual({ items: [{ id: "c1" }], has_more: false });
+ expect(mockListUnreadConversations).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ { limit: 30, before: undefined, types: ["user_dm_message"] }
+ );
+ });
+
+ it("clamps limit to minimum 1", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });
+
+ await GET(new NextRequest("http://localhost/api/inbox?limit=-5"));
+
+ expect(mockListUnreadConversations).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ expect.objectContaining({ limit: 1 })
+ );
+ });
+
+ it("clamps limit to maximum 100", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });
+
+ await GET(new NextRequest("http://localhost/api/inbox?limit=999"));
+
+ expect(mockListUnreadConversations).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ expect.objectContaining({ limit: 100 })
+ );
+ });
+
+ it("passes valid before timestamp", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });
+
+ await GET(new NextRequest("http://localhost/api/inbox?before=2026-01-01T00:00:00Z"));
+
+ expect(mockListUnreadConversations).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ expect.objectContaining({ before: "2026-01-01T00:00:00Z" })
+ );
+ });
+
+ it("returns 400 for invalid before timestamp", async () => {
+ const res = await GET(new NextRequest("http://localhost/api/inbox?before=not-a-date"));
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("invalid before timestamp");
+ expect(mockListUnreadConversations).not.toHaveBeenCalled();
+ });
+
+ it("filters types param by valid types", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });
+
+ await GET(new NextRequest("http://localhost/api/inbox?types=calendar_event,email_notification"));
+
+ expect(mockListUnreadConversations).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ expect.objectContaining({ types: ["calendar_event", "email_notification"] })
+ );
+ });
+
+ it("ignores invalid types and defaults to user_dm_message", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });
+
+ await GET(new NextRequest("http://localhost/api/inbox?types=bogus,invalid"));
+
+ expect(mockListUnreadConversations).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ expect.objectContaining({ types: ["user_dm_message"] })
+ );
+ });
+
+ it("defaults to user_dm_message when no types param", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });
+
+ await GET(new NextRequest("http://localhost/api/inbox"));
+
+ expect(mockListUnreadConversations).toHaveBeenCalledWith(
+ {},
+ "u1",
+ "w1",
+ expect.objectContaining({ types: ["user_dm_message"] })
+ );
+ });
+
+ it("returns has_more true when there are more items", async () => {
+ mockListUnreadConversations.mockResolvedValue({ items: [{ id: "c1" }], hasMore: true });
+
+ const res = await GET(new NextRequest("http://localhost/api/inbox?limit=1"));
+ const body = await res.json();
+
+ expect(body.has_more).toBe(true);
+ });
+});
diff --git a/src/web/src/app/api/issues/[id]/comments/route.test.ts b/src/web/src/app/api/issues/[id]/comments/route.test.ts
new file mode 100644
index 000000000..f29364c20
--- /dev/null
+++ b/src/web/src/app/api/issues/[id]/comments/route.test.ts
@@ -0,0 +1,251 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetIssue = vi.fn();
+const mockUpdateIssue = vi.fn();
+const mockSetLatestTask = vi.fn();
+const mockListComments = vi.fn();
+const mockCreateComment = vi.fn();
+const mockCommentToResponse = vi.fn((c: any) => ({
+ id: c.id,
+ content: c.content,
+ author_type: c.authorType,
+ author_id: c.authorId,
+ created_at: c.createdAt ?? "2026-01-01T00:00:00Z",
+}));
+const mockGetActiveTaskByConversation = vi.fn();
+const mockGetTask = vi.fn();
+const mockCreateTask = vi.fn();
+const mockGetAgent = vi.fn();
+const mockEnqueueTask = vi.fn();
+const mockBroadcastToUser = vi.fn().mockResolvedValue(undefined);
+const mockInvalidate = vi.fn().mockResolvedValue(undefined);
+const mockIsTerminalIssueStatus = vi.fn(() => false);
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", () => ({
+ CreateIssueCommentBodySchema: { parse: vi.fn((data: any) => data) },
+ TASK_TYPES: { ISSUE_EVENT: "issue_event" },
+ isTerminalIssueStatus: (...args: unknown[]) => mockIsTerminalIssueStatus(...args),
+ queries: {
+ issue: {
+ getIssue: (...a: unknown[]) => mockGetIssue(...a),
+ updateIssue: (...a: unknown[]) => mockUpdateIssue(...a),
+ setLatestTask: (...a: unknown[]) => mockSetLatestTask(...a),
+ },
+ issueComment: {
+ listComments: (...a: unknown[]) => mockListComments(...a),
+ createComment: (...a: unknown[]) => mockCreateComment(...a),
+ commentToResponse: (...a: unknown[]) => mockCommentToResponse(...a),
+ },
+ task: {
+ getActiveTaskByConversation: (...a: unknown[]) => mockGetActiveTaskByConversation(...a),
+ getTask: (...a: unknown[]) => mockGetTask(...a),
+ createTask: (...a: unknown[]) => mockCreateTask(...a),
+ },
+ agent: {
+ getAgent: (...a: unknown[]) => mockGetAgent(...a),
+ },
+ },
+}));
+
+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]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ parseBody: vi.fn(async (req: any) => {
+ const body = await req.json();
+ return [body, null];
+ }),
+ };
+});
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+}));
+
+vi.mock("@/lib/services/task", () => ({
+ TaskService: class {
+ enqueueTask(...args: any[]) {
+ return mockEnqueueTask(...args);
+ }
+ },
+}));
+
+vi.mock("@/lib/cache", () => ({
+ invalidate: (...a: unknown[]) => mockInvalidate(...a),
+ cacheKeys: { overviewTaskStats: vi.fn(() => "test-key") },
+}));
+
+import { GET, POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/issues/[id]/comments", () => {
+ it("returns 400 when id is missing", async () => {
+ const req = new NextRequest("http://localhost/api/issues//comments");
+ const res = await GET(req, { params: {} } as any);
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "issue id is required" });
+ });
+
+ it("returns 404 when issue not found", async () => {
+ mockGetIssue.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/issues/iss_1/comments");
+ const res = await GET(req, { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "issue not found" });
+ });
+
+ it("returns comments for the issue", async () => {
+ mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo" });
+ mockListComments.mockResolvedValue([
+ { id: "c1", content: "Hello", authorType: "user", authorId: "u1", createdAt: "2026-01-01T00:00:00Z" },
+ { id: "c2", content: "World", authorType: "agent", authorId: "a1", createdAt: "2026-01-01T01:00:00Z" },
+ ]);
+
+ const req = new NextRequest("http://localhost/api/issues/iss_1/comments");
+ const res = await GET(req, { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.comments).toHaveLength(2);
+ expect(body.comments[0]).toEqual({ id: "c1", content: "Hello", author_type: "user", author_id: "u1", created_at: "2026-01-01T00:00:00Z" });
+ expect(mockListComments).toHaveBeenCalledWith({}, "iss_1", "w1");
+ });
+});
+
+describe("POST /api/issues/[id]/comments", () => {
+ it("returns 400 when id is missing", async () => {
+ const req = new NextRequest("http://localhost/api/issues//comments", {
+ method: "POST",
+ body: JSON.stringify({ content: "test" }),
+ });
+ const res = await POST(req, { params: {} } as any);
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "issue id is required" });
+ });
+
+ it("returns 404 when issue not found", async () => {
+ mockGetIssue.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/issues/iss_1/comments", {
+ method: "POST",
+ body: JSON.stringify({ content: "test" }),
+ });
+ const res = await POST(req, { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "issue not found" });
+ });
+
+ it("returns 403 when agentId does not match issue", async () => {
+ mockGetIssue.mockResolvedValue({ id: "iss_1", agentId: "a1", status: "todo" });
+ const req = new NextRequest("http://localhost/api/issues/iss_1/comments?agentId=a_other", {
+ method: "POST",
+ body: JSON.stringify({ content: "test" }),
+ });
+ const res = await POST(req, { params: { id: "iss_1" } } as any);
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "issue does not belong to agent" });
+ });
+
+ it("creates a user comment without re-dispatch when status is terminal", async () => {
+ mockIsTerminalIssueStatus.mockReturnValue(true);
+ mockGetIssue.mockResolvedValue({
+ id: "iss_1", agentId: "a1", status: "done", conversationId: "conv_1", creatorUserId: "u1",
+ });
+ mockCreateComment.mockResolvedValue({
+ id: "ic_1", issueId: "iss_1", workspaceId: "w1", authorType: "user", authorId: "u1", content: "Nice", createdAt: "2026-01-01T00:00:00Z",
+ });
+ mockUpdateIssue.mockResolvedValue({ id: "iss_1" });
+
+ const req = new NextRequest("http://localhost/api/issues/iss_1/comments", {
+ method: "POST",
+ body: JSON.stringify({ content: "Nice" }),
+ });
+ const res = await POST(req, { params: { id: "iss_1" } } as any);
+
+ expect(res.status).toBe(201);
+ const body = await res.json();
+ expect(body.comment).toEqual({ id: "ic_1", content: "Nice", author_type: "user", author_id: "u1", created_at: "2026-01-01T00:00:00Z" });
+ expect(mockCreateComment).toHaveBeenCalledWith({}, expect.objectContaining({ issueId: "iss_1", authorType: "user", authorId: "u1", content: "Nice" }));
+ expect(mockUpdateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", {});
+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({ type: "issue.comment", issueId: "iss_1" }));
+ // Should NOT trigger re-dispatch because status is terminal
+ expect(mockGetActiveTaskByConversation).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).not.toHaveBeenCalled();
+ });
+
+ it("creates a user comment and triggers re-dispatch when non-terminal and no active task", async () => {
+ mockIsTerminalIssueStatus.mockReturnValue(false);
+ mockGetIssue.mockResolvedValue({
+ id: "iss_1", agentId: "a1", status: "in_progress", conversationId: "conv_1", creatorUserId: "u1", latestTaskId: "t_prev", title: "Fix bug",
+ });
+ mockCreateComment.mockResolvedValue({
+ id: "ic_2", issueId: "iss_1", workspaceId: "w1", authorType: "user", authorId: "u1", content: "Please retry", createdAt: "2026-01-02T00:00:00Z",
+ });
+ mockUpdateIssue.mockResolvedValue({ id: "iss_1" });
+ mockGetActiveTaskByConversation.mockResolvedValue(null);
+ mockGetTask.mockResolvedValue({ id: "t_prev", traceId: "trace_1" });
+ mockEnqueueTask.mockResolvedValue({ id: "t_new" });
+ mockSetLatestTask.mockResolvedValue(undefined);
+
+ const req = new NextRequest("http://localhost/api/issues/iss_1/comments", {
+ method: "POST",
+ body: JSON.stringify({ content: "Please retry" }),
+ });
+ const res = await POST(req, { params: { id: "iss_1" } } as any);
+
+ expect(res.status).toBe(201);
+ expect(mockGetActiveTaskByConversation).toHaveBeenCalledWith({}, "conv_1", "w1");
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "a1", "conv_1", "w1",
+ expect.stringContaining("Please retry"),
+ "issue_event",
+ expect.objectContaining({ contextKey: "conv_1", context: { issue_id: "iss_1" }, traceId: "trace_1" }),
+ );
+ expect(mockSetLatestTask).toHaveBeenCalledWith({}, "iss_1", "w1", "t_new");
+ expect(mockInvalidate).toHaveBeenCalled();
+ });
+
+ it("creates an agent comment without re-dispatch", async () => {
+ mockIsTerminalIssueStatus.mockReturnValue(false);
+ mockGetIssue.mockResolvedValue({
+ id: "iss_1", agentId: "a1", status: "in_progress", conversationId: "conv_1", creatorUserId: "u1",
+ });
+ mockCreateComment.mockResolvedValue({
+ id: "ic_3", issueId: "iss_1", workspaceId: "w1", authorType: "agent", authorId: "a1", content: "Working on it", createdAt: "2026-01-03T00:00:00Z",
+ });
+ mockUpdateIssue.mockResolvedValue({ id: "iss_1" });
+
+ const req = new NextRequest("http://localhost/api/issues/iss_1/comments?agentId=a1", {
+ method: "POST",
+ body: JSON.stringify({ content: "Working on it" }),
+ });
+ const res = await POST(req, { params: { id: "iss_1" } } as any);
+
+ expect(res.status).toBe(201);
+ const body = await res.json();
+ expect(body.comment.author_type).toBe("agent");
+ expect(body.comment.author_id).toBe("a1");
+ expect(mockCreateComment).toHaveBeenCalledWith({}, expect.objectContaining({ authorType: "agent", authorId: "a1" }));
+ // Agent comments should NOT trigger re-dispatch
+ expect(mockGetActiveTaskByConversation).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/web/src/app/api/traces/[traceId]/route.test.ts b/src/web/src/app/api/traces/[traceId]/route.test.ts
new file mode 100644
index 000000000..30f6277e6
--- /dev/null
+++ b/src/web/src/app/api/traces/[traceId]/route.test.ts
@@ -0,0 +1,231 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetTraceTree = vi.fn();
+const mockGetConversation = vi.fn();
+const mockGetAllAgentsForWorkspace = vi.fn();
+const mockGetAllAgentAccessForWorkspace = vi.fn();
+
+vi.mock("@/lib/middleware/helpers", () => ({
+ writeJSON: (data: any, status = 200) =>
+ new Response(JSON.stringify(data), {
+ status,
+ headers: { "content-type": "application/json" },
+ }),
+ writeError: (message: string, status: number) =>
+ new Response(JSON.stringify({ error: message }), {
+ status,
+ headers: { "content-type": "application/json" },
+ }),
+}));
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("@alook/shared", () => ({
+ queries: {
+ task: {
+ getTraceTree: (...args: any[]) => mockGetTraceTree(...args),
+ },
+ conversation: {
+ getConversation: (...args: any[]) => mockGetConversation(...args),
+ },
+ agent: {
+ getAllAgentsForWorkspace: (...args: any[]) => mockGetAllAgentsForWorkspace(...args),
+ },
+ agentAccess: {
+ getAllAgentAccessForWorkspace: (...args: any[]) => mockGetAllAgentAccessForWorkspace(...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]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ cached: vi.fn((_key: string, _ttl: number, fn: () => any) => fn()),
+ cacheKeys: {
+ allAgents: (ws: string) => `agents:${ws}`,
+ allAgentAccess: (ws: string) => `aa:${ws}`,
+ },
+}));
+vi.mock("@/lib/agent-visibility", () => ({
+ filterVisibleAgents: vi.fn((agents: any[]) => agents),
+}));
+
+import { GET } from "./route";
+
+describe("GET /api/traces/[traceId]", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns 400 for traceId without tr_ prefix", async () => {
+ const res = await GET(
+ new NextRequest("http://localhost/api/traces/invalid123"),
+ { params: Promise.resolve({ traceId: "invalid123" }) },
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("invalid traceId");
+ });
+
+ it("returns 400 for traceId that is too long", async () => {
+ const longId = "tr_" + "a".repeat(28); // length 31 > 30
+ const res = await GET(
+ new NextRequest(`http://localhost/api/traces/${longId}`),
+ { params: Promise.resolve({ traceId: longId }) },
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("invalid traceId");
+ });
+
+ it("returns 400 for missing traceId", async () => {
+ const res = await GET(
+ new NextRequest("http://localhost/api/traces/"),
+ { params: Promise.resolve({}) },
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toBe("invalid traceId");
+ });
+
+ it("returns 404 when trace not found (empty tasks)", async () => {
+ mockGetTraceTree.mockResolvedValue([]);
+
+ const res = await GET(
+ new NextRequest("http://localhost/api/traces/tr_abc123"),
+ { params: Promise.resolve({ traceId: "tr_abc123" }) },
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(404);
+ expect(body.error).toBe("trace not found");
+ });
+
+ it("returns trace with tasks and agent mapping", async () => {
+ mockGetTraceTree.mockResolvedValue([
+ {
+ id: "task_1",
+ agentId: "a1",
+ parentTaskId: null,
+ prompt: "Root task",
+ status: "completed",
+ type: "user_dm_message",
+ conversationId: "conv_1",
+ createdAt: "2026-01-01T00:00:00Z",
+ completedAt: "2026-01-01T00:01:00Z",
+ },
+ {
+ id: "task_2",
+ agentId: "a2",
+ parentTaskId: "task_1",
+ prompt: "Sub task",
+ status: "completed",
+ type: "email_notification",
+ conversationId: "conv_1",
+ createdAt: "2026-01-01T00:00:10Z",
+ completedAt: "2026-01-01T00:00:50Z",
+ },
+ ]);
+ mockGetConversation.mockResolvedValue({ channel: "slack" });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([
+ { id: "a1", name: "Agent 1", emailHandle: "agent1", avatarUrl: "https://img/a1.png" },
+ { id: "a2", name: "Agent 2", emailHandle: "agent2", avatarUrl: "https://img/a2.png" },
+ ]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ const res = await GET(
+ new NextRequest("http://localhost/api/traces/tr_abc123"),
+ { params: Promise.resolve({ traceId: "tr_abc123" }) },
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.trace_id).toBe("tr_abc123");
+ expect(body.channel).toBe("slack");
+ expect(body.tasks).toHaveLength(2);
+ expect(body.tasks[0]).toEqual({
+ id: "task_1",
+ agent_id: "a1",
+ agent: { name: "Agent 1", email_handle: "agent1", avatarUrl: "https://img/a1.png" },
+ parent_task_id: null,
+ prompt: "Root task",
+ status: "completed",
+ type: "user_dm_message",
+ conversation_id: "conv_1",
+ created_at: "2026-01-01T00:00:00Z",
+ completed_at: "2026-01-01T00:01:00Z",
+ });
+ expect(body.tasks[1].agent).toEqual({
+ name: "Agent 2",
+ email_handle: "agent2",
+ avatarUrl: "https://img/a2.png",
+ });
+ });
+
+ it("returns default channel when no conversation found", async () => {
+ mockGetTraceTree.mockResolvedValue([
+ {
+ id: "task_1",
+ agentId: "a1",
+ parentTaskId: null,
+ prompt: "Root task",
+ status: "active",
+ type: "user_dm_message",
+ conversationId: "conv_1",
+ createdAt: "2026-01-01T00:00:00Z",
+ completedAt: null,
+ },
+ ]);
+ mockGetConversation.mockResolvedValue(null);
+ mockGetAllAgentsForWorkspace.mockResolvedValue([
+ { id: "a1", name: "Agent 1", emailHandle: "agent1", avatarUrl: null },
+ ]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ const res = await GET(
+ new NextRequest("http://localhost/api/traces/tr_abc123"),
+ { params: Promise.resolve({ traceId: "tr_abc123" }) },
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.channel).toBe("default");
+ });
+
+ it("returns null agent for unknown agentId", async () => {
+ mockGetTraceTree.mockResolvedValue([
+ {
+ id: "task_1",
+ agentId: "unknown_agent",
+ parentTaskId: null,
+ prompt: "Root task",
+ status: "active",
+ type: "user_dm_message",
+ conversationId: "conv_1",
+ createdAt: "2026-01-01T00:00:00Z",
+ completedAt: null,
+ },
+ ]);
+ mockGetConversation.mockResolvedValue({ channel: "default" });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ const res = await GET(
+ new NextRequest("http://localhost/api/traces/tr_abc123"),
+ { params: Promise.resolve({ traceId: "tr_abc123" }) },
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.tasks[0].agent).toBeNull();
+ });
+});
diff --git a/src/web/src/app/api/traces/route.test.ts b/src/web/src/app/api/traces/route.test.ts
new file mode 100644
index 000000000..0f2940397
--- /dev/null
+++ b/src/web/src/app/api/traces/route.test.ts
@@ -0,0 +1,215 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockListTraces = vi.fn();
+const mockGetAllAgentsForWorkspace = vi.fn();
+const mockGetAllAgentAccessForWorkspace = vi.fn();
+
+vi.mock("@/lib/middleware/helpers", () => ({
+ writeJSON: (data: any, status = 200) =>
+ new Response(JSON.stringify(data), {
+ status,
+ headers: { "content-type": "application/json" },
+ }),
+ writeError: (message: string, status: number) =>
+ new Response(JSON.stringify({ error: message }), {
+ status,
+ headers: { "content-type": "application/json" },
+ }),
+}));
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("@alook/shared", () => ({
+ queries: {
+ task: {
+ listTraces: (...args: any[]) => mockListTraces(...args),
+ },
+ agent: {
+ getAllAgentsForWorkspace: (...args: any[]) => mockGetAllAgentsForWorkspace(...args),
+ },
+ agentAccess: {
+ getAllAgentAccessForWorkspace: (...args: any[]) => mockGetAllAgentAccessForWorkspace(...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]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ cached: vi.fn((_key: string, _ttl: number, fn: () => any) => fn()),
+ cacheKeys: {
+ allAgents: (ws: string) => `agents:${ws}`,
+ allAgentAccess: (ws: string) => `aa:${ws}`,
+ },
+}));
+vi.mock("@/lib/agent-visibility", () => ({
+ filterVisibleAgents: vi.fn((agents: any[]) => agents),
+}));
+
+import { GET } from "./route";
+
+describe("GET /api/traces", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns traces with agent info mapped", async () => {
+ mockListTraces.mockResolvedValue({
+ traces: [
+ {
+ traceId: "tr_abc",
+ rootPrompt: "Hello",
+ rootAgentId: "a1",
+ helperAgentIds: ["a2"],
+ status: "completed",
+ taskCount: 2,
+ startedAt: "2026-01-01T00:00:00Z",
+ completedAt: "2026-01-01T00:01:00Z",
+ channel: "default",
+ },
+ ],
+ hasMore: false,
+ });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([
+ { id: "a1", name: "Agent 1", avatarUrl: "https://img/a1.png" },
+ { id: "a2", name: "Agent 2", avatarUrl: "https://img/a2.png" },
+ ]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ const res = await GET(new NextRequest("http://localhost/api/traces"), {});
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.traces).toHaveLength(1);
+ expect(body.traces[0]).toEqual({
+ trace_id: "tr_abc",
+ root_prompt: "Hello",
+ root_agent_id: "a1",
+ root_agent: { name: "Agent 1", avatarUrl: "https://img/a1.png" },
+ helper_agents: [{ id: "a2", name: "Agent 2", avatarUrl: "https://img/a2.png" }],
+ status: "completed",
+ task_count: 2,
+ started_at: "2026-01-01T00:00:00Z",
+ completed_at: "2026-01-01T00:01:00Z",
+ channel: "default",
+ });
+ expect(body.has_more).toBe(false);
+ });
+
+ it("handles unknown agent (returns null for root_agent)", async () => {
+ mockListTraces.mockResolvedValue({
+ traces: [
+ {
+ traceId: "tr_xyz",
+ rootPrompt: "Test",
+ rootAgentId: "unknown_agent",
+ helperAgentIds: [],
+ status: "active",
+ taskCount: 1,
+ startedAt: "2026-01-01T00:00:00Z",
+ completedAt: null,
+ channel: "email",
+ },
+ ],
+ hasMore: false,
+ });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ const res = await GET(new NextRequest("http://localhost/api/traces"), {});
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.traces[0].root_agent).toBeNull();
+ });
+
+ it("respects status filter", async () => {
+ mockListTraces.mockResolvedValue({ traces: [], hasMore: false });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ await GET(new NextRequest("http://localhost/api/traces?status=failed"), {});
+
+ expect(mockListTraces).toHaveBeenCalledWith(
+ {},
+ "w1",
+ expect.objectContaining({ status: "failed" }),
+ );
+ });
+
+ it("ignores invalid status filter", async () => {
+ mockListTraces.mockResolvedValue({ traces: [], hasMore: false });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ await GET(new NextRequest("http://localhost/api/traces?status=invalid"), {});
+
+ expect(mockListTraces).toHaveBeenCalledWith(
+ {},
+ "w1",
+ expect.objectContaining({ status: undefined }),
+ );
+ });
+
+ it("default limit behavior", async () => {
+ mockListTraces.mockResolvedValue({ traces: [], hasMore: false });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ await GET(new NextRequest("http://localhost/api/traces"), {});
+
+ expect(mockListTraces).toHaveBeenCalledWith(
+ {},
+ "w1",
+ expect.objectContaining({ limit: undefined }),
+ );
+ });
+
+ it("clamps limit to 1-100 range", async () => {
+ mockListTraces.mockResolvedValue({ traces: [], hasMore: false });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ await GET(new NextRequest("http://localhost/api/traces?limit=200"), {});
+
+ expect(mockListTraces).toHaveBeenCalledWith(
+ {},
+ "w1",
+ expect.objectContaining({ limit: 100 }),
+ );
+ });
+
+ it("multiAgent filter", async () => {
+ mockListTraces.mockResolvedValue({ traces: [], hasMore: false });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ await GET(new NextRequest("http://localhost/api/traces?multiAgent=true"), {});
+
+ expect(mockListTraces).toHaveBeenCalledWith(
+ {},
+ "w1",
+ expect.objectContaining({ multiAgent: true }),
+ );
+ });
+
+ it("passes agentId and channel filters", async () => {
+ mockListTraces.mockResolvedValue({ traces: [], hasMore: false });
+ mockGetAllAgentsForWorkspace.mockResolvedValue([]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+
+ await GET(new NextRequest("http://localhost/api/traces?agentId=a1&channel=email"), {});
+
+ expect(mockListTraces).toHaveBeenCalledWith(
+ {},
+ "w1",
+ expect.objectContaining({ agentId: "a1", channel: "email" }),
+ );
+ });
+});