Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: multi-member data isolation across all API routes

Gus6179511f3eb4
diff --git a/src/shared/src/db/queries/agent-link.ts b/src/shared/src/db/queries/agent-link.ts
index 2e5117db2..9254eb3d5 100644
--- a/src/shared/src/db/queries/agent-link.ts
+++ b/src/shared/src/db/queries/agent-link.ts
@@ -103,6 +103,14 @@ export async function upsertByPair(
return { row: created, created: true };
}
+export async function getById(db: Database, id: string, workspaceId: string) {
+ const rows = await db
+ .select()
+ .from(agentLink)
+ .where(and(eq(agentLink.id, id), eq(agentLink.workspaceId, workspaceId)));
+ return rows[0] ?? null;
+}
+
export async function update(
db: Database,
id: string,
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index c6f3ab60a..3ef19dd8d 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -485,21 +485,24 @@ export async function countRunningTasks(db: Database, agentId: string, workspace
export async function listActiveTaskCountsByWorkspace(
db: Database,
- workspaceId: string
+ workspaceId: string,
+ agentIds?: string[]
) {
+ const conditions = [
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ inArray(agentTaskQueue.status, ["queued", "dispatched", "running"]),
+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),
+ ];
+ if (agentIds && agentIds.length > 0) {
+ conditions.push(inArray(agentTaskQueue.agentId, agentIds));
+ }
return db
.select({
agentId: agentTaskQueue.agentId,
count: count(),
})
.from(agentTaskQueue)
- .where(
- and(
- eq(agentTaskQueue.workspaceId, workspaceId),
- inArray(agentTaskQueue.status, ["queued", "dispatched", "running"]),
- ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK)
- )
- )
+ .where(and(...conditions))
.groupBy(agentTaskQueue.agentId)
.limit(200);
}
diff --git a/src/shared/test/queries/task.test.ts b/src/shared/test/queries/task.test.ts
index c4526ee13..f7dd696fd 100644
--- a/src/shared/test/queries/task.test.ts
+++ b/src/shared/test/queries/task.test.ts
@@ -42,8 +42,8 @@ describe("task query module exports", () => {
});
describe("task query function signatures", () => {
- it("listActiveTaskCountsByWorkspace accepts (db, workspaceId)", () => {
- expect(taskQueries.listActiveTaskCountsByWorkspace.length).toBe(2);
+ it("listActiveTaskCountsByWorkspace accepts (db, workspaceId, agentIds?)", () => {
+ expect(taskQueries.listActiveTaskCountsByWorkspace.length).toBe(3);
});
it("listActiveTasksByAgent accepts (db, agentId, workspaceId)", () => {
diff --git a/src/web/src/app/api/agent-links/[id]/route.test.ts b/src/web/src/app/api/agent-links/[id]/route.test.ts
index 9161bd765..bd9a23604 100644
--- a/src/web/src/app/api/agent-links/[id]/route.test.ts
+++ b/src/web/src/app/api/agent-links/[id]/route.test.ts
@@ -3,6 +3,8 @@ import { NextRequest } from "next/server";
const mockUpdate = vi.fn();
const mockRemove = vi.fn();
+const mockGetById = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -15,7 +17,11 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
+ agent: {
+ getAgent: (...a: unknown[]) => mockGetAgent(...a),
+ },
agentLink: {
+ getById: (...a: unknown[]) => mockGetById(...a),
update: (...a: unknown[]) => mockUpdate(...a),
remove: (...a: unknown[]) => mockRemove(...a),
},
@@ -34,6 +40,14 @@ vi.mock("@/lib/middleware/workspace", () => ({
withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),
}));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn(),
+ cacheKeys: {
+ allColleagues: (ws: string) => `allColleagues:${ws}`,
+ agentLinks: (ws: string) => `agentLinks:${ws}`,
+ },
+}));
+
vi.mock("@/lib/api/responses", () => ({
agentLinkToResponse: (row: any) => ({
id: row.id,
@@ -52,6 +66,16 @@ describe("PATCH /api/agent-links/[id]", () => {
beforeEach(() => vi.clearAllMocks());
it("updates instruction", async () => {
+ mockGetById.mockResolvedValue({
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "old instruction",
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ });
+ mockGetAgent.mockResolvedValue({ id: "ag_a" });
mockUpdate.mockResolvedValue({
id: "al_1",
workspaceId: "ws1",
@@ -73,7 +97,7 @@ describe("PATCH /api/agent-links/[id]", () => {
});
it("returns 404 when link not found", async () => {
- mockUpdate.mockResolvedValue(null);
+ mockGetById.mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/agent-links/al_nope", {
method: "PATCH",
body: JSON.stringify({ instruction: "test" }),
@@ -88,6 +112,16 @@ describe("DELETE /api/agent-links/[id]", () => {
beforeEach(() => vi.clearAllMocks());
it("deletes a link", async () => {
+ mockGetById.mockResolvedValue({
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "",
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ });
+ mockGetAgent.mockResolvedValue({ id: "ag_a" });
mockRemove.mockResolvedValue({
id: "al_1",
workspaceId: "ws1",
@@ -105,7 +139,7 @@ describe("DELETE /api/agent-links/[id]", () => {
});
it("returns 404 for unknown link", async () => {
- mockRemove.mockResolvedValue(null);
+ mockGetById.mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/agent-links/al_nope", {
method: "DELETE",
});
diff --git a/src/web/src/app/api/agent-links/[id]/route.ts b/src/web/src/app/api/agent-links/[id]/route.ts
index 41c6671ab..9568d509b 100644
--- a/src/web/src/app/api/agent-links/[id]/route.ts
+++ b/src/web/src/app/api/agent-links/[id]/route.ts
@@ -17,13 +17,22 @@ export const PATCH = withAuth(async (req, ctx) => {
const id = ctx.params?.id;
if (!id) return writeError("agent link id is required", 400);
+ const link = await queries.agentLink.getById(db, id, ws.workspaceId);
+ if (!link) return writeError("not found", 404);
+
+ const [sourceAgent, targetAgent] = await Promise.all([
+ queries.agent.getAgent(db, link.sourceAgentId, ws.workspaceId, ctx.userId),
+ queries.agent.getAgent(db, link.targetAgentId, ws.workspaceId, ctx.userId),
+ ]);
+ if (!sourceAgent && !targetAgent) return writeError("not found", 404);
+
const [body, err] = await parseBody(req, UpdateAgentLinkRequestSchema);
if (err) return err;
const updated = await queries.agentLink.update(db, id, ws.workspaceId, {
instruction: body.instruction,
});
- if (!updated) return writeError("agent link not found", 404);
+ if (!updated) return writeError("not found", 404);
await Promise.all([
invalidate(cacheKeys.allColleagues(ws.workspaceId)),
@@ -43,8 +52,17 @@ export const DELETE = withAuth(async (req, ctx) => {
const id = ctx.params?.id;
if (!id) return writeError("agent link id is required", 400);
+ const link = await queries.agentLink.getById(db, id, ws.workspaceId);
+ if (!link) return writeError("not found", 404);
+
+ const [sourceAgent, targetAgent] = await Promise.all([
+ queries.agent.getAgent(db, link.sourceAgentId, ws.workspaceId, ctx.userId),
+ queries.agent.getAgent(db, link.targetAgentId, ws.workspaceId, ctx.userId),
+ ]);
+ if (!sourceAgent && !targetAgent) return writeError("not found", 404);
+
const deleted = await queries.agentLink.remove(db, id, ws.workspaceId);
- if (!deleted) return writeError("agent link not found", 404);
+ if (!deleted) return writeError("not found", 404);
await Promise.all([
invalidate(cacheKeys.allColleagues(ws.workspaceId)),
diff --git a/src/web/src/app/api/agent-links/route.test.ts b/src/web/src/app/api/agent-links/route.test.ts
index 2ae63598d..1f242985b 100644
--- a/src/web/src/app/api/agent-links/route.test.ts
+++ b/src/web/src/app/api/agent-links/route.test.ts
@@ -8,6 +8,9 @@ const mockUpsertByPair = vi.fn();
const mockGetByPair = vi.fn();
const mockUpdate = vi.fn();
const mockInvalidate = vi.fn();
+const mockGetAllAgentsForWorkspace = vi.fn();
+const mockGetAllAgentAccessForWorkspace = vi.fn();
+const mockFilterVisibleAgents = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -20,7 +23,13 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ agent: {
+ getAgent: (...a: unknown[]) => mockGetAgent(...a),
+ getAllAgentsForWorkspace: (...a: unknown[]) => mockGetAllAgentsForWorkspace(...a),
+ },
+ agentAccess: {
+ getAllAgentAccessForWorkspace: (...a: unknown[]) => mockGetAllAgentAccessForWorkspace(...a),
+ },
agentLink: {
listByWorkspace: (...a: unknown[]) => mockListByWorkspace(...a),
create: (...a: unknown[]) => mockCreate(...a),
@@ -38,9 +47,15 @@ vi.mock("@/lib/cache", () => ({
cacheKeys: {
agentLinks: (ws: string) => `agentLinks:${ws}`,
allColleagues: (ws: string) => `allColleagues:${ws}`,
+ allAgents: (ws: string) => `allAgents:${ws}`,
+ allAgentAccess: (ws: string) => `allAgentAccess:${ws}`,
},
}));
+vi.mock("@/lib/agent-visibility", () => ({
+ filterVisibleAgents: (...a: unknown[]) => mockFilterVisibleAgents(...a),
+}));
+
vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
@@ -70,6 +85,9 @@ describe("GET /api/agent-links", () => {
beforeEach(() => vi.clearAllMocks());
it("lists links scoped to workspace", async () => {
+ mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "ag_a" }, { id: "ag_b" }]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
+ mockFilterVisibleAgents.mockReturnValue([{ id: "ag_a" }, { id: "ag_b" }]);
mockListByWorkspace.mockResolvedValue([
{
id: "al_1",
diff --git a/src/web/src/app/api/agent-links/route.ts b/src/web/src/app/api/agent-links/route.ts
index fe7f1a4cb..943230630 100644
--- a/src/web/src/app/api/agent-links/route.ts
+++ b/src/web/src/app/api/agent-links/route.ts
@@ -12,6 +12,7 @@ import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
import { agentLinkToResponse } from "@/lib/api/responses";
import { cached, invalidate, cacheKeys } from "@/lib/cache";
+import { filterVisibleAgents } from "@/lib/agent-visibility";
export const GET = withAuth(async (req: NextRequest, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
@@ -24,16 +25,18 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const limit = Math.min(Number(url.searchParams.get("limit")) || 200, 500);
const offset = Number(url.searchParams.get("offset")) || 0;
- if (offset === 0 && !url.searchParams.has("limit")) {
- const data = await cached(cacheKeys.agentLinks(ws.workspaceId), 120, async () => {
- const rows = await queries.agentLink.listByWorkspace(db, ws.workspaceId, { limit, offset });
- return rows.map(agentLinkToResponse);
- });
- return writeJSON(data);
- }
+ const [allAgents, allAccess] = await Promise.all([
+ cached(cacheKeys.allAgents(ws.workspaceId), 300, () => queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId)),
+ cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),
+ ]);
+ const visibleIds = new Set(filterVisibleAgents(allAgents, ctx.userId, allAccess).map((a) => a.id));
const rows = await queries.agentLink.listByWorkspace(db, ws.workspaceId, { limit, offset });
- return writeJSON(rows.map(agentLinkToResponse));
+ const filtered = rows
+ .filter((r) => visibleIds.has(r.sourceAgentId) || visibleIds.has(r.targetAgentId))
+ .map(agentLinkToResponse);
+
+ return writeJSON(filtered);
});
export const POST = withAuth(async (req: NextRequest, ctx) => {
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts
index 193eebf06..5d3068b02 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts
@@ -13,6 +13,7 @@ vi.mock("@alook/shared/crypto", () => ({ encrypt: vi.fn((v: string) => `enc(${v}
const mockGetScoped = vi.fn();
const mockUpdate = vi.fn();
const mockDelete = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual("@alook/shared");
@@ -24,6 +25,7 @@ vi.mock("@alook/shared", async () => {
updateEmailAccount: (...a: unknown[]) => mockUpdate(...a),
deleteEmailAccount: (...a: unknown[]) => mockDelete(...a),
},
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
},
};
});
@@ -54,7 +56,10 @@ const ROW = {
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
};
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
+});
const params = { id: "a1", accountId: "acc1" };
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts
index 69dc383d3..247ee1ea8 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts
@@ -51,6 +51,9 @@ export const PATCH = withAuth(async (req, ctx) => {
const accountId = ctx.params?.accountId
if (!agentId || !accountId) return writeError("missing params", 400)
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)
if (!existing) return writeError("not found", 404)
@@ -102,6 +105,9 @@ export const DELETE = withAuth(async (req, ctx) => {
const accountId = ctx.params?.accountId
if (!agentId || !accountId) return writeError("missing params", 400)
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)
if (!existing) return writeError("not found", 404)
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts
index 266172b31..2ac5757a7 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts
@@ -10,11 +10,15 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
const mockGetScoped = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual("@alook/shared");
return {
...actual,
- queries: { emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) } },
+ queries: {
+ emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) },
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ },
};
});
@@ -30,7 +34,10 @@ vi.mock("@/lib/middleware/workspace", () => ({
import { POST } from "./route";
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
+});
function post(params: Record<string, string>) {
return POST(
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts
index db2813721..80163f6fe 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts
@@ -17,6 +17,9 @@ export const POST = withAuth(async (req, ctx) => {
const accountId = ctx.params?.accountId
if (!agentId || !accountId) return writeError("missing params", 400)
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)
if (!existing) return writeError("not found", 404)
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts
index 875accda6..09729545c 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts
@@ -10,11 +10,15 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
const mockGetScoped = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual("@alook/shared");
return {
...actual,
- queries: { emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) } },
+ queries: {
+ emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) },
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ },
};
});
@@ -30,7 +34,10 @@ vi.mock("@/lib/middleware/workspace", () => ({
import { POST } from "./route";
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
+});
function post(params: Record<string, string>) {
return POST(
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts
index 6e5de5ba5..e6a629692 100644
--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts
@@ -17,6 +17,9 @@ export const POST = withAuth(async (req, ctx) => {
const accountId = ctx.params?.accountId
if (!agentId || !accountId) return writeError("missing params", 400)
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)
if (!existing) return writeError("not found", 404)
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts
index 46ccc269c..95d625aab 100644
--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts
@@ -9,6 +9,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
const mockGet = vi.fn();
const mockUpdate = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
return {
@@ -18,6 +19,7 @@ vi.mock("@alook/shared", async () => {
getMeetingSession: (...a: unknown[]) => mockGet(...a),
updateMeetingSession: (...a: unknown[]) => mockUpdate(...a),
},
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
},
};
});
@@ -34,7 +36,10 @@ vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.
import { POST } from "./route";
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
+});
const params = { id: "a1", meetingId: "m1" };
const post = () => POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts
index 84e14f08b..89c83a340 100644
--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts
@@ -14,11 +14,17 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext()
const db = getDb((env as Env).DB)
+ const agentId = ctx.params?.id
+ if (!agentId) return writeError("agent id is required", 400)
+
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const meetingId = ctx.params?.meetingId
if (!meetingId) return writeError("meeting id is required", 400)
const meeting = await queries.meetingSession.getMeetingSession(db, meetingId, ws.workspaceId)
- if (!meeting) return writeError("meeting not found", 404)
+ if (!meeting) return writeError("not found", 404)
if (meeting.status !== MeetingStatus.PENDING) {
return writeError("only pending meetings can be approved", 400)
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts
index 7b79d6224..b5ea8a0a6 100644
--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts
@@ -8,6 +8,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
const mockGet = vi.fn();
const mockDelete = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual("@alook/shared");
return {
@@ -17,6 +18,7 @@ vi.mock("@alook/shared", async () => {
getMeetingSession: (...a: unknown[]) => mockGet(...a),
deleteMeetingSession: (...a: unknown[]) => mockDelete(...a),
},
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
},
};
});
@@ -33,7 +35,10 @@ vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.
import { GET, DELETE } from "./route";
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
+});
describe("GET /api/agents/[id]/meetings/[meetingId]", () => {
it("returns a meeting scoped to workspace", async () => {
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts
index 64f9101ec..ffc40a9b9 100644
--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts
@@ -14,6 +14,12 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext()
const db = getDb((env as Env).DB)
+ const agentId = ctx.params?.id
+ if (!agentId) return writeError("agent id is required", 400)
+
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const meetingId = ctx.params?.meetingId
if (!meetingId) return writeError("meeting id is required", 400)
@@ -22,7 +28,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
meetingId,
ws.workspaceId
)
- if (!meeting) return writeError("meeting not found", 404)
+ if (!meeting) return writeError("not found", 404)
return writeJSON(meetingToResponse(meeting))
})
@@ -34,6 +40,12 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext()
const db = getDb((env as Env).DB)
+ const agentId = ctx.params?.id
+ if (!agentId) return writeError("agent id is required", 400)
+
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const meetingId = ctx.params?.meetingId
if (!meetingId) return writeError("meeting id is required", 400)
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts
index b86a81c00..1a8c99637 100644
--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts
@@ -9,6 +9,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
const mockGet = vi.fn();
const mockUpdate = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
return {
@@ -18,6 +19,7 @@ vi.mock("@alook/shared", async () => {
getMeetingSession: (...a: unknown[]) => mockGet(...a),
updateMeetingSession: (...a: unknown[]) => mockUpdate(...a),
},
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
},
};
});
@@ -34,7 +36,10 @@ vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.
import { POST } from "./route";
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
+});
const params = { id: "a1", meetingId: "m1" };
const post = () => POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts
index 81e1a3263..7c6df26aa 100644
--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts
@@ -15,11 +15,17 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const cfEnv = env as Env
const db = getDb(cfEnv.DB)
+ const agentId = ctx.params?.id
+ if (!agentId) return writeError("agent id is required", 400)
+
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const meetingId = ctx.params?.meetingId
if (!meetingId) return writeError("meeting id is required", 400)
const meeting = await queries.meetingSession.getMeetingSession(db, meetingId, ws.workspaceId)
- if (!meeting) return writeError("meeting not found", 404)
+ if (!meeting) return writeError("not found", 404)
if (meeting.status !== MeetingStatus.RECORDING && meeting.status !== MeetingStatus.JOINING) {
return writeError("meeting is not active", 400)
diff --git a/src/web/src/app/api/agents/[id]/meetings/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/route.test.ts
index 3b12dabaa..9f2dbce72 100644
--- a/src/web/src/app/api/agents/[id]/meetings/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/route.test.ts
@@ -48,6 +48,7 @@ const VALID_URL = "https://meet.google.com/abc-defg-hij";
describe("GET /api/agents/[id]/meetings", () => {
it("lists meetings scoped to agent + workspace", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
mockList.mockResolvedValue([{ id: "m1", status: "completed" }]);
const req = new NextRequest("http://localhost/api/agents/a1/meetings");
const res = await GET(req, { params: { id: "a1" } });
diff --git a/src/web/src/app/api/agents/[id]/meetings/route.ts b/src/web/src/app/api/agents/[id]/meetings/route.ts
index 390710842..b4cf42fb8 100644
--- a/src/web/src/app/api/agents/[id]/meetings/route.ts
+++ b/src/web/src/app/api/agents/[id]/meetings/route.ts
@@ -20,6 +20,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const agentId = ctx.params?.id
if (!agentId) return writeError("agent id is required", 400)
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
+
const meetings = await queries.meetingSession.listMeetingSessions(
db,
agentId,
@@ -40,8 +43,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const agentId = ctx.params?.id
if (!agentId) return writeError("agent id is required", 400)
- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId)
- if (!agent) return writeError("agent not found", 404)
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)
+ if (!agent) return writeError("not found", 404)
let body: {
meetingUrl?: string
diff --git a/src/web/src/app/api/agents/[id]/threads/route.ts b/src/web/src/app/api/agents/[id]/threads/route.ts
index 0f58ebf7c..27bbc69c0 100644
--- a/src/web/src/app/api/agents/[id]/threads/route.ts
+++ b/src/web/src/app/api/agents/[id]/threads/route.ts
@@ -17,6 +17,11 @@ export const GET = withAuth(async (req, ctx) => {
return writeError("agent id is required", 400);
}
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);
+ if (!agent) {
+ return writeError("not found", 404);
+ }
+
const url = new URL(req.url);
const before = url.searchParams.get("before") || undefined;
const limitParam = url.searchParams.get("limit");
diff --git a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts
index 1871fbb60..ecb7eeff8 100644
--- a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts
@@ -5,6 +5,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}));
const mockRemoveWhitelist = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
@@ -14,6 +15,7 @@ vi.mock("@alook/shared", () => ({
whitelist: {
removeWhitelist: (...args: unknown[]) => mockRemoveWhitelist(...args),
},
+ agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
},
}));
@@ -30,7 +32,10 @@ vi.mock("@/lib/middleware/workspace", () => ({
import { DELETE } from "./route";
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });
+});
describe("DELETE /api/agents/[id]/whitelist/[whitelistId]", () => {
it("removes entry and returns 204", async () => {
diff --git a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts
index 480b8bbe0..780dbc775 100644
--- a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts
+++ b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts
@@ -16,6 +16,9 @@ export const DELETE = withAuth(async (req, ctx) => {
const whitelistId = ctx.params?.whitelistId;
if (!agentId || !whitelistId) return writeError("missing required params", 400);
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
+
const removed = await queries.whitelist.removeWhitelist(db, whitelistId, agentId, ws.workspaceId);
if (!removed) return writeError("whitelist entry not found", 404);
diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts
index 995b1239a..eb6c8b744 100644
--- a/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts
@@ -16,6 +16,7 @@ vi.mock("@alook/shared", async () => {
...real,
queries: {
agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
+ runtime: { getAgentRuntime: vi.fn() },
workspaceFileRequest: { createRequest: (...args: unknown[]) => mockCreateRequest(...args) },
},
};
@@ -28,15 +29,27 @@ vi.mock("@/lib/middleware/auth", () => ({
}),
}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
vi.mock("@/lib/middleware/helpers", async () =>
await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
);
+vi.mock("@/lib/cache", () => ({
+ cacheKeys: { hasPendingFileRequest: (ws: string) => `pfr:${ws}` },
+}));
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToDaemon: vi.fn().mockResolvedValue(undefined),
+}));
+
import { POST } from "./route";
-function postReq(agentId: string, body: unknown, workspaceId = "w1") {
+function postReq(agentId: string, body: unknown) {
return new NextRequest(
- `http://localhost/api/agents/${agentId}/workspace/browse?workspace_id=${workspaceId}`,
+ `http://localhost/api/agents/${agentId}/workspace/browse`,
{
method: "POST",
body: JSON.stringify(body),
@@ -48,16 +61,6 @@ function postReq(agentId: string, body: unknown, workspaceId = "w1") {
describe("POST /api/agents/[id]/workspace/browse", () => {
beforeEach(() => vi.clearAllMocks());
- it("returns 400 when workspace_id is missing", async () => {
- const req = new NextRequest("http://localhost/api/agents/a1/workspace/browse", {
- method: "POST",
- body: JSON.stringify({ request_type: "tree", path: "." }),
- headers: { "Content-Type": "application/json" },
- });
- const res = await POST(req, { params: Promise.resolve({ id: "a1" }) });
- expect(res.status).toBe(400);
- });
-
it("returns 404 when agent not found", async () => {
mockGetAgent.mockResolvedValue(null);
@@ -65,6 +68,7 @@ describe("POST /api/agents/[id]/workspace/browse", () => {
params: Promise.resolve({ id: "a1" }),
});
expect(res.status).toBe(404);
+ expect(mockGetAgent).toHaveBeenCalledWith({}, "a1", "w1", "u1");
});
it("creates a file request and returns request_id for tree", async () => {
diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.ts
index 3795debe8..f120d870f 100644
--- a/src/web/src/app/api/agents/[id]/workspace/browse/route.ts
+++ b/src/web/src/app/api/agents/[id]/workspace/browse/route.ts
@@ -2,12 +2,16 @@ import { NextRequest } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare";
import { queries, WorkspaceFileBrowseRequestSchema } from "@alook/shared";
import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";
import { getDb } from "@/lib/db";
import { cacheKeys } from "@/lib/cache";
import { broadcastToDaemon } from "@/lib/broadcast";
export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
const { env } = getCloudflareContext();
const db = getDb((env as Env).DB);
@@ -17,14 +21,11 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const [body, err] = await parseBody(req, WorkspaceFileBrowseRequestSchema);
if (err) return err;
- const workspaceId = new URL(req.url).searchParams.get("workspace_id");
- if (!workspaceId) return writeError("workspace_id required", 400);
-
- const agent = await queries.agent.getAgent(db, agentId, workspaceId);
- if (!agent) return writeError("agent not found", 404);
+ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
const row = await queries.workspaceFileRequest.createRequest(db, {
- workspaceId,
+ workspaceId: ws.workspaceId,
agentId,
requestType: body.request_type,
path: body.path,
@@ -32,7 +33,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const kv = (env as Env).CACHE_KV ?? null;
if (kv) {
- kv.put(cacheKeys.hasPendingFileRequest(workspaceId), "1", { expirationTtl: 60 }).catch(() => {});
+ kv.put(cacheKeys.hasPendingFileRequest(ws.workspaceId), "1", { expirationTtl: 60 }).catch(() => {});
}
// Push file request to daemon (best-effort)
@@ -41,7 +42,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
if (runtime) {
broadcastToDaemon(runtime.daemonId, {
type: "daemon.file_requests",
- workspaceId,
+ workspaceId: ws.workspaceId,
requests: [{ id: row.id, agent_id: agentId, request_type: body.request_type, path: body.path }],
}).catch(() => {});
}
diff --git a/src/web/src/app/api/agents/active-task-counts/route.test.ts b/src/web/src/app/api/agents/active-task-counts/route.test.ts
index c48e92a11..06542f862 100644
--- a/src/web/src/app/api/agents/active-task-counts/route.test.ts
+++ b/src/web/src/app/api/agents/active-task-counts/route.test.ts
@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockListActiveTaskCountsByWorkspace = vi.fn();
+const mockGetAllAgentsForWorkspace = vi.fn();
+const mockGetAllAgentAccessForWorkspace = vi.fn();
vi.mock("@/lib/middleware/helpers", () => ({
writeJSON: (data: any, status = 200) =>
@@ -20,8 +22,12 @@ vi.mock("@opennextjs/cloudflare", () => ({
}));
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
vi.mock("@/lib/cache", () => ({
- cached: vi.fn((_key: string, _ttl: number, fn: () => any) => fn()),
- cacheKeys: { activeTaskCounts: (ws: string) => `atc:${ws}` },
+ cached: vi.fn((_key: any, _ttl: any, fn: any) => fn()),
+ cacheKeys: {
+ activeTaskCounts: (ws: string) => `atc:${ws}`,
+ allAgents: (ws: string) => `agents:${ws}`,
+ allAgentAccess: (ws: string) => `aa:${ws}`,
+ },
}));
vi.mock("@alook/shared", () => ({
queries: {
@@ -29,6 +35,14 @@ vi.mock("@alook/shared", () => ({
listActiveTaskCountsByWorkspace: (...args: any[]) =>
mockListActiveTaskCountsByWorkspace(...args),
},
+ agent: {
+ getAllAgentsForWorkspace: (...args: any[]) =>
+ mockGetAllAgentsForWorkspace(...args),
+ },
+ agentAccess: {
+ getAllAgentAccessForWorkspace: (...args: any[]) =>
+ mockGetAllAgentAccessForWorkspace(...args),
+ },
},
}));
vi.mock("@/lib/middleware/auth", () => ({
@@ -40,6 +54,9 @@ vi.mock("@/lib/middleware/auth", () => ({
vi.mock("@/lib/middleware/workspace", () => ({
withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
}));
+vi.mock("@/lib/agent-visibility", () => ({
+ filterVisibleAgents: vi.fn(() => [{ id: "ag1" }]),
+}));
import { GET } from "./route";
@@ -47,9 +64,10 @@ describe("GET /api/agents/active-task-counts", () => {
beforeEach(() => vi.clearAllMocks());
it("returns correct counts per agent", async () => {
+ mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "ag1" }]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
mockListActiveTaskCountsByWorkspace.mockResolvedValue([
- { agentId: "a1", count: 3 },
- { agentId: "a2", count: 1 },
+ { agentId: "ag1", count: 3 },
]);
const res = await GET(
@@ -59,11 +77,13 @@ describe("GET /api/agents/active-task-counts", () => {
const body = await res.json();
expect(res.status).toBe(200);
- expect(body).toEqual({ counts: { a1: 3, a2: 1 } });
- expect(mockListActiveTaskCountsByWorkspace).toHaveBeenCalledWith({}, "w1");
+ expect(body).toEqual({ counts: { ag1: 3 } });
+ expect(mockListActiveTaskCountsByWorkspace).toHaveBeenCalledWith({}, "w1", ["ag1"]);
});
it("returns empty counts when no active tasks", async () => {
+ mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "ag1" }]);
+ mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);
mockListActiveTaskCountsByWorkspace.mockResolvedValue([]);
const res = await GET(
diff --git a/src/web/src/app/api/agents/active-task-counts/route.ts b/src/web/src/app/api/agents/active-task-counts/route.ts
index fc0ac8401..22c3e9978 100644
--- a/src/web/src/app/api/agents/active-task-counts/route.ts
+++ b/src/web/src/app/api/agents/active-task-counts/route.ts
@@ -5,6 +5,7 @@ import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON } from "@/lib/middleware/helpers";
import { cached, cacheKeys } from "@/lib/cache";
+import { filterVisibleAgents } from "@/lib/agent-visibility";
export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
@@ -13,14 +14,20 @@ export const GET = withAuth(async (req, ctx) => {
const { env } = getCloudflareContext();
const db = getDb((env as Env).DB);
- const counts = await cached(cacheKeys.activeTaskCounts(ws.workspaceId), 10, async () => {
- const rows = await queries.task.listActiveTaskCountsByWorkspace(db, ws.workspaceId);
- const result: Record<string, number> = {};
- for (const row of rows) {
- result[row.agentId] = Number(row.count);
- }
- return result;
- });
+ const [allAgents, allAccess] = await Promise.all([
+ cached(cacheKeys.allAgents(ws.workspaceId), 300, () => queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId)),
+ cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),
+ ]);
+ const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);
+ const visibleAgentIds = agents.map((a) => a.id);
+
+ if (visibleAgentIds.length === 0) return writeJSON({ counts: {} });
+
+ const rows = await queries.task.listActiveTaskCountsByWorkspace(db, ws.workspaceId, visibleAgentIds);
+ const counts: Record<string, number> = {};
+ for (const row of rows) {
+ counts[row.agentId] = Number(row.count);
+ }
return writeJSON({ counts });
});
diff --git a/src/web/src/app/api/agents/recruit/route.test.ts b/src/web/src/app/api/agents/recruit/route.test.ts
index e347f44bb..a0762803e 100644
--- a/src/web/src/app/api/agents/recruit/route.test.ts
+++ b/src/web/src/app/api/agents/recruit/route.test.ts
@@ -94,7 +94,7 @@ describe("POST /api/agents/recruit", () => {
mockGetAgent.mockResolvedValue(null);
const res = await post(VALID);
expect(res.status).toBe(404);
- expect(mockGetAgent).toHaveBeenCalledWith({}, "caller", "w1");
+ expect(mockGetAgent).toHaveBeenCalledWith({}, "caller", "w1", "u1");
});
it("400 when calling agent has no runtime", async () => {
diff --git a/src/web/src/app/api/agents/recruit/route.ts b/src/web/src/app/api/agents/recruit/route.ts
index bbfe7fd94..9307f1c31 100644
--- a/src/web/src/app/api/agents/recruit/route.ts
+++ b/src/web/src/app/api/agents/recruit/route.ts
@@ -50,9 +50,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const [body, valErr] = await parseBody(req, RecruitAgentRequestSchema);
if (valErr) return valErr;
- const callingAgent = await queries.agent.getAgent(db, agentId, ws.workspaceId);
+ const callingAgent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);
if (!callingAgent) {
- return writeError("calling agent not found in workspace", 404);
+ return writeError("not found", 404);
}
const runtime = callingAgent.runtimeId
diff --git a/src/web/src/app/api/artifacts/[id]/content/route.test.ts b/src/web/src/app/api/artifacts/[id]/content/route.test.ts
index dffa25617..b87015206 100644
--- a/src/web/src/app/api/artifacts/[id]/content/route.test.ts
+++ b/src/web/src/app/api/artifacts/[id]/content/route.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockGetArtifact = vi.fn();
+const mockGetAgent = vi.fn();
const mockBucketGet = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
@@ -21,6 +22,7 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: {
artifact: { getArtifact: (...a: unknown[]) => mockGetArtifact(...a) },
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
},
};
});
@@ -44,11 +46,13 @@ describe("GET /api/artifacts/[id]/content", () => {
it("downloads artifact content for machine-token workspace access", async () => {
mockGetArtifact.mockResolvedValue({
id: "art_1",
+ agentId: "ag1",
r2Key: "artifacts/w1/ag1/c1/art_1/brief.md",
filename: "brief.md",
contentType: "text/markdown",
size: 5,
});
+ mockGetAgent.mockResolvedValue({ id: "ag1" });
mockBucketGet.mockResolvedValue({ body: new Blob(["hello"]).stream() });
const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1/content?workspace_id=w1"), { params: { id: "art_1" } } as any);
@@ -62,11 +66,13 @@ describe("GET /api/artifacts/[id]/content", () => {
it("serves non-ASCII filenames with RFC 5987 content disposition", async () => {
mockGetArtifact.mockResolvedValue({
id: "art_1",
+ agentId: "ag1",
r2Key: "artifacts/w1/ag1/c1/art_1/report.pdf",
filename: "深圳市小汽车增量指标证明文件.pdf",
contentType: "application/pdf",
size: 5,
});
+ mockGetAgent.mockResolvedValue({ id: "ag1" });
mockBucketGet.mockResolvedValue({ body: new Blob(["hello"]).stream() });
const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1/content?workspace_id=w1&download"), { params: { id: "art_1" } } as any);
diff --git a/src/web/src/app/api/artifacts/[id]/content/route.ts b/src/web/src/app/api/artifacts/[id]/content/route.ts
index 7fa1df12f..a8665bcb0 100644
--- a/src/web/src/app/api/artifacts/[id]/content/route.ts
+++ b/src/web/src/app/api/artifacts/[id]/content/route.ts
@@ -27,7 +27,12 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);
if (!row) {
- return writeError("artifact not found", 404);
+ return writeError("not found", 404);
+ }
+
+ const agent = await queries.agent.getAgent(db, row.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) {
+ return writeError("not found", 404);
}
const object = await bucket.get(row.r2Key);
diff --git a/src/web/src/app/api/artifacts/[id]/route.test.ts b/src/web/src/app/api/artifacts/[id]/route.test.ts
index 9b2e1a999..9c433eb0c 100644
--- a/src/web/src/app/api/artifacts/[id]/route.test.ts
+++ b/src/web/src/app/api/artifacts/[id]/route.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockGetArtifact = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -18,6 +19,7 @@ vi.mock("@alook/shared", async () => {
getArtifact: (...a: unknown[]) => mockGetArtifact(...a),
artifactToResponse: (row: any) => ({ id: row.id, filename: row.filename }),
},
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
},
};
});
@@ -39,7 +41,8 @@ beforeEach(() => vi.clearAllMocks());
describe("GET /api/artifacts/[id]", () => {
it("returns artifact metadata for machine-token workspace access", async () => {
- mockGetArtifact.mockResolvedValue({ id: "art_1", filename: "brief.md" });
+ mockGetArtifact.mockResolvedValue({ id: "art_1", agentId: "ag1", filename: "brief.md" });
+ mockGetAgent.mockResolvedValue({ id: "ag1" });
const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1?workspace_id=w1"), { params: { id: "art_1" } } as any);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ id: "art_1", filename: "brief.md" });
diff --git a/src/web/src/app/api/artifacts/[id]/route.ts b/src/web/src/app/api/artifacts/[id]/route.ts
index dd09b6899..8dad5c1e4 100644
--- a/src/web/src/app/api/artifacts/[id]/route.ts
+++ b/src/web/src/app/api/artifacts/[id]/route.ts
@@ -16,7 +16,12 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);
if (!row) {
- return writeError("artifact not found", 404);
+ return writeError("not found", 404);
+ }
+
+ const agent = await queries.agent.getAgent(db, row.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) {
+ return writeError("not found", 404);
}
return writeJSON(queries.artifact.artifactToResponse(row));
diff --git a/src/web/src/app/api/artifacts/route.test.ts b/src/web/src/app/api/artifacts/route.test.ts
index bbea0d463..81d14de13 100644
--- a/src/web/src/app/api/artifacts/route.test.ts
+++ b/src/web/src/app/api/artifacts/route.test.ts
@@ -7,6 +7,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
const mockList = vi.fn();
+const mockGetConversation = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual("@alook/shared");
return {
@@ -16,6 +17,7 @@ vi.mock("@alook/shared", async () => {
listArtifactsByConversation: (...a: unknown[]) => mockList(...a),
artifactToResponse: (a: any) => ({ id: a.id }),
},
+ conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },
},
};
});
@@ -35,6 +37,7 @@ beforeEach(() => vi.clearAllMocks());
describe("GET /api/artifacts", () => {
it("lists artifacts for a conversation scoped to workspace", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });
mockList.mockResolvedValue([{ id: "art_1" }, { id: "art_2" }]);
const req = new NextRequest("http://localhost/api/artifacts?conversation_id=c1");
const res = await GET(req, {});
diff --git a/src/web/src/app/api/artifacts/route.ts b/src/web/src/app/api/artifacts/route.ts
index 190658860..fdd8b5f5b 100644
--- a/src/web/src/app/api/artifacts/route.ts
+++ b/src/web/src/app/api/artifacts/route.ts
@@ -18,6 +18,11 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext();
const db = getDb((env as Env).DB);
+ const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
+ if (!conv || conv.userId !== ctx.userId) {
+ return writeError("not found", 404);
+ }
+
const rows = await queries.artifact.listArtifactsByConversation(
db,
conversationId,
diff --git a/src/web/src/app/api/artifacts/upload/route.test.ts b/src/web/src/app/api/artifacts/upload/route.test.ts
index a72c4f1f6..d946d928a 100644
--- a/src/web/src/app/api/artifacts/upload/route.test.ts
+++ b/src/web/src/app/api/artifacts/upload/route.test.ts
@@ -48,7 +48,7 @@ function formReq(fields: Record<string, string | File>) {
describe("POST /api/artifacts/upload", () => {
it("uploads a file to R2 and creates an artifact record", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1", userId: "u1" });
mockCreateArtifact.mockResolvedValue({ id: "art_xyz" });
mockGetAgent.mockResolvedValue({ ownerId: "owner1" });
diff --git a/src/web/src/app/api/artifacts/upload/route.ts b/src/web/src/app/api/artifacts/upload/route.ts
index cffc8d3f8..55a3b5a0b 100644
--- a/src/web/src/app/api/artifacts/upload/route.ts
+++ b/src/web/src/app/api/artifacts/upload/route.ts
@@ -44,8 +44,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
- if (!conv) {
- return writeError("conversation not found", 404);
+ if (!conv || conv.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
const agentId = conv.agentId;
diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts b/src/web/src/app/api/conversations/[id]/active-task/route.test.ts
index ba4fb9d3d..61a0df4f8 100644
--- a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/active-task/route.test.ts
@@ -75,7 +75,7 @@ describe("GET /api/conversations/[id]/active-task", () => {
beforeEach(() => vi.clearAllMocks());
it("returns active task when one exists", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });
mockGetActiveTaskByConversation.mockResolvedValue({ id: "t1", status: "running" });
const res = await GET(
@@ -90,7 +90,7 @@ describe("GET /api/conversations/[id]/active-task", () => {
});
it("returns 204 when no active task", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });
mockGetActiveTaskByConversation.mockResolvedValue(null);
const res = await GET(
@@ -111,7 +111,7 @@ describe("GET /api/conversations/[id]/active-task", () => {
const body = await res.json();
expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
+ expect(body.error).toBe("not found");
});
});
@@ -119,7 +119,7 @@ describe("DELETE /api/conversations/[id]/active-task", () => {
beforeEach(() => vi.clearAllMocks());
it("returns cancelled task", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });
mockCancelActiveTask.mockResolvedValue({ id: "t1", status: "cancelled" });
const res = await DELETE(
@@ -133,7 +133,7 @@ describe("DELETE /api/conversations/[id]/active-task", () => {
});
it("returns 404 when no active task", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });
mockCancelActiveTask.mockResolvedValue(null);
const res = await DELETE(
@@ -147,7 +147,7 @@ describe("DELETE /api/conversations/[id]/active-task", () => {
});
it("broadcasts task.updated on cancel", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });
mockCancelActiveTask.mockResolvedValue({ id: "t1", status: "cancelled" });
await DELETE(
@@ -172,6 +172,6 @@ describe("DELETE /api/conversations/[id]/active-task", () => {
const body = await res.json();
expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
+ expect(body.error).toBe("not found");
});
});
diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.ts b/src/web/src/app/api/conversations/[id]/active-task/route.ts
index 292859fc3..2994b08f1 100644
--- a/src/web/src/app/api/conversations/[id]/active-task/route.ts
+++ b/src/web/src/app/api/conversations/[id]/active-task/route.ts
@@ -22,8 +22,8 @@ export const GET = withAuth(async (req, ctx) => {
}
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) {
- return writeError("conversation not found", 404);
+ if (!conversation || conversation.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
const task = await queries.task.getActiveTaskByConversation(db, id, ws.workspaceId);
@@ -47,8 +47,8 @@ export const DELETE = withAuth(async (req, ctx) => {
}
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) {
- return writeError("conversation not found", 404);
+ if (!conversation || conversation.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
const taskService = new TaskService(db);
diff --git a/src/web/src/app/api/conversations/[id]/init/route.test.ts b/src/web/src/app/api/conversations/[id]/init/route.test.ts
index f35b30583..9f310e9ac 100644
--- a/src/web/src/app/api/conversations/[id]/init/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/init/route.test.ts
@@ -89,7 +89,7 @@ describe("GET /api/conversations/[id]/init", () => {
});
it("returns the init payload with messages when no cache hint", async () => {
- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });
m.listMessages.mockResolvedValue({ messages: [{ id: "m1", role: "user" }], has_more: true });
const req = new NextRequest("http://localhost/api/conversations/c1/init");
@@ -104,7 +104,7 @@ describe("GET /api/conversations/[id]/init", () => {
});
it("preloads error task messages (workspace-scoped) for a running active task", async () => {
- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });
m.getActiveTaskByConversation.mockResolvedValue({ id: "t1", status: "running" });
// The query filters to type:"error" in SQL, so the route maps whatever it returns.
m.listTaskErrorMessages.mockResolvedValue([
@@ -124,7 +124,7 @@ describe("GET /api/conversations/[id]/init", () => {
it("does not query task errors when there is no active task", async () => {
// A run that ended in error is settled to status:"failed" and re-surfaces via
// its persisted assistant error message (not through this preload).
- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });
m.getActiveTaskByConversation.mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/conversations/c1/init");
@@ -137,7 +137,7 @@ describe("GET /api/conversations/[id]/init", () => {
});
it("returns cache_valid=true and null messages when client cache matches", async () => {
- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });
m.getNewestMessageId.mockResolvedValue("m9");
m.getActiveMessageCount.mockResolvedValue(5);
m.listMessages.mockResolvedValue({ messages: [{ id: "m9", role: "user" }], has_more: false });
diff --git a/src/web/src/app/api/conversations/[id]/init/route.ts b/src/web/src/app/api/conversations/[id]/init/route.ts
index a845d010d..66d7f5655 100644
--- a/src/web/src/app/api/conversations/[id]/init/route.ts
+++ b/src/web/src/app/api/conversations/[id]/init/route.ts
@@ -31,8 +31,8 @@ export const GET = withAuth(async (req, ctx) => {
const messageCountParam = url.searchParams.get("message_count");
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) {
- return writeError("conversation not found", 404);
+ if (!conversation || conversation.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
const [serverNewest, serverMessageCount] = await Promise.all([
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 d13c371bb..a959e5467 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
@@ -73,7 +73,7 @@ describe("GET /api/conversations/[id]/messages", () => {
beforeEach(() => vi.clearAllMocks());
it("lists messages", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
const msgs = [
{ id: "m1", content: "Hello" },
{ id: "m2", content: "World" },
@@ -103,7 +103,7 @@ describe("GET /api/conversations/[id]/messages", () => {
});
it("passes limit and before params when provided", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
mockListMessages.mockResolvedValue({ messages: [], has_more: false });
@@ -123,7 +123,7 @@ describe("GET /api/conversations/[id]/messages", () => {
});
it("passes before_id param for compound cursor", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
mockListMessages.mockResolvedValue({ messages: [], has_more: false });
@@ -143,7 +143,7 @@ describe("GET /api/conversations/[id]/messages", () => {
});
it("clamps limit to max 100", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
mockListMessages.mockResolvedValue({ messages: [], has_more: false });
@@ -162,7 +162,7 @@ describe("GET /api/conversations/[id]/messages", () => {
});
it("returns has_more true when more messages exist", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
const msgs = [{ id: "m1", content: "Hello" }];
mockGetConversation.mockResolvedValue(conv);
mockListMessages.mockResolvedValue({ messages: msgs, has_more: true });
@@ -182,7 +182,7 @@ describe("POST /api/conversations/[id]/messages", () => {
beforeEach(() => vi.clearAllMocks());
it("sends message and enqueues task, returns 201", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
const msg = { id: "m1", content: "Hi there" };
const task = { id: "t1", status: "pending" };
mockGetConversation.mockResolvedValue(conv);
@@ -208,7 +208,7 @@ describe("POST /api/conversations/[id]/messages", () => {
it("auto-titles conversation with truncated first message", async () => {
const longContent = "A ".repeat(40).trim();
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
mockCreateMessage.mockResolvedValue({ id: "m1", content: longContent });
mockUpdateConversationTitle.mockResolvedValue(undefined);
@@ -229,7 +229,7 @@ describe("POST /api/conversations/[id]/messages", () => {
});
it("short messages are not truncated", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
mockCreateMessage.mockResolvedValue({ id: "m1", content: "short" });
mockUpdateConversationTitle.mockResolvedValue(undefined);
@@ -250,7 +250,7 @@ describe("POST /api/conversations/[id]/messages", () => {
});
it("returns 400 for missing content", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
const res = await POST(
@@ -282,11 +282,11 @@ describe("POST /api/conversations/[id]/messages", () => {
const body = await res.json();
expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
+ expect(body.error).toBe("not found");
});
it("passes workspaceId to getConversation", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
mockCreateMessage.mockResolvedValue({ id: "m1", content: "hello" });
mockUpdateConversationTitle.mockResolvedValue(undefined);
@@ -305,7 +305,7 @@ describe("POST /api/conversations/[id]/messages", () => {
});
it("TC2: passes metadata.quote to createMessage and adds quoted_message to task context", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
const msg = { id: "m1", content: "Can you fix this?" };
const task = { id: "t1", status: "pending" };
mockGetConversation.mockResolvedValue(conv);
@@ -345,7 +345,7 @@ describe("POST /api/conversations/[id]/messages", () => {
});
it("TC3: message without metadata has no quote in metadata or task context", async () => {
- const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
const msg = { id: "m1", content: "Hello" };
const task = { id: "t1", status: "pending" };
mockGetConversation.mockResolvedValue(conv);
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 3d6749e09..dd51ea370 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -32,8 +32,8 @@ export const GET = withAuth(async (req, ctx) => {
}
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) {
- return writeError("conversation not found", 404);
+ if (!conversation || conversation.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
const url = new URL(req.url);
@@ -112,8 +112,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) {
- return writeError("conversation not found", 404);
+ if (!conversation || conversation.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
// Upload files to R2 and create artifact rows
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 8f317f5cb..aa38e769b 100644
--- a/src/web/src/app/api/conversations/[id]/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/route.test.ts
@@ -48,7 +48,7 @@ describe("GET /api/conversations/[id]", () => {
beforeEach(() => vi.clearAllMocks());
it("returns conversation scoped by workspaceId", async () => {
- const conv = { id: "c1", title: "Test", workspaceId: "w1" };
+ const conv = { id: "c1", title: "Test", workspaceId: "w1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
const res = await GET(
@@ -72,7 +72,7 @@ describe("GET /api/conversations/[id]", () => {
const body = await res.json();
expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
+ expect(body.error).toBe("not found");
});
});
@@ -80,7 +80,7 @@ describe("DELETE /api/conversations/[id]", () => {
beforeEach(() => vi.clearAllMocks());
it("returns 204 and removes conversation + tasks with workspace scoping", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });
mockDeleteTasksByConversation.mockResolvedValue(undefined);
mockDeleteConversation.mockResolvedValue(undefined);
@@ -96,7 +96,7 @@ describe("DELETE /api/conversations/[id]", () => {
it("deletes tasks before conversation", async () => {
const callOrder: string[] = [];
- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });
mockDeleteTasksByConversation.mockImplementation(async () => {
callOrder.push("tasks");
});
@@ -125,6 +125,6 @@ describe("DELETE /api/conversations/[id]", () => {
const body = await res.json();
expect(res.status).toBe(404);
- expect(body.error).toBe("conversation not found");
+ expect(body.error).toBe("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 c22eea3f1..cc08e421a 100644
--- a/src/web/src/app/api/conversations/[id]/route.ts
+++ b/src/web/src/app/api/conversations/[id]/route.ts
@@ -19,8 +19,8 @@ export const GET = withAuth(async (req, ctx) => {
}
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) {
- return writeError("conversation not found", 404);
+ if (!conversation || conversation.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
return writeJSON(conversationToResponse(conversation));
@@ -39,8 +39,8 @@ export const DELETE = withAuth(async (req, ctx) => {
}
const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) {
- return writeError("conversation not found", 404);
+ if (!conversation || conversation.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
// Delete tasks first (no cascade on FK)
diff --git a/src/web/src/app/api/conversations/[id]/threads/route.ts b/src/web/src/app/api/conversations/[id]/threads/route.ts
index 4aeb9885a..171c90ba4 100644
--- a/src/web/src/app/api/conversations/[id]/threads/route.ts
+++ b/src/web/src/app/api/conversations/[id]/threads/route.ts
@@ -27,8 +27,8 @@ export const POST = withAuth(async (req, ctx) => {
if (valErr) return valErr;
const parentConv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
- if (!parentConv) {
- return writeError("conversation not found", 404);
+ if (!parentConv || parentConv.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
const rootMessage = await queries.message.getMessage(db, body.parent_message_id);
@@ -195,8 +195,8 @@ export const GET = withAuth(async (req, ctx) => {
}
const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
- if (!conv) {
- return writeError("conversation not found", 404);
+ if (!conv || conv.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
try {
diff --git a/src/web/src/app/api/conversations/check-fresh/route.test.ts b/src/web/src/app/api/conversations/check-fresh/route.test.ts
index 2067f1290..92a8b5f67 100644
--- a/src/web/src/app/api/conversations/check-fresh/route.test.ts
+++ b/src/web/src/app/api/conversations/check-fresh/route.test.ts
@@ -44,7 +44,7 @@ beforeEach(() => vi.clearAllMocks());
describe("GET /api/conversations/check-fresh", () => {
it("returns freshness for an existing conversation_id (scoped to workspace)", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1" });
+ mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });
mockGetNewestMessageId.mockResolvedValue("m9");
mockGetActiveMessageCount.mockResolvedValue(3);
@@ -62,7 +62,7 @@ describe("GET /api/conversations/check-fresh", () => {
const req = new NextRequest("http://localhost/api/conversations/check-fresh?conversation_id=cX");
const res = await GET(req, {});
expect(res.status).toBe(404);
- expect((await res.json()).error).toBe("conversation not found");
+ expect((await res.json()).error).toBe("not found");
});
it("resolves via agent_id when no conversation_id given", async () => {
diff --git a/src/web/src/app/api/conversations/check-fresh/route.ts b/src/web/src/app/api/conversations/check-fresh/route.ts
index 22157eb0c..b845b8d84 100644
--- a/src/web/src/app/api/conversations/check-fresh/route.ts
+++ b/src/web/src/app/api/conversations/check-fresh/route.ts
@@ -21,8 +21,8 @@ export const GET = withAuth(async (req, ctx) => {
if (conversationId) {
const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
- if (!conv) {
- return writeError("conversation not found", 404);
+ if (!conv || conv.userId !== ctx.userId) {
+ return writeError("not found", 404);
}
convId = conv.id;
} else if (agentId) {
diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
index 9dd029476..6af676d8c 100644
--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
@@ -12,12 +12,16 @@ vi.mock("postal-mime", () => ({ default: { parse: (...a: unknown[]) => mockParse
const mockGetById = vi.fn();
const mockFilter = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual("@alook/shared");
return {
...actual,
filterDownloadableAttachments: (...a: unknown[]) => mockFilter(...a),
- queries: { email: { getEmailById: (...a: unknown[]) => mockGetById(...a) } },
+ queries: {
+ email: { getEmailById: (...a: unknown[]) => mockGetById(...a) },
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ },
};
});
vi.mock("@/lib/middleware/auth", () => ({
@@ -56,7 +60,8 @@ describe("GET /api/email/[id]/attachment/[index]", () => {
});
it("404 when R2 object is missing", async () => {
- mockGetById.mockResolvedValue({ id: "e1", r2Key: "k" });
+ mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockBucketGet.mockResolvedValue(null);
const res = await get({ id: "e1", index: "0" });
expect(res.status).toBe(404);
@@ -64,7 +69,8 @@ describe("GET /api/email/[id]/attachment/[index]", () => {
});
it("404 when the index is out of range", async () => {
- mockGetById.mockResolvedValue({ id: "e1", r2Key: "k" });
+ mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });
mockParse.mockResolvedValue({ attachments: [] });
mockFilter.mockReturnValue([]);
@@ -74,7 +80,8 @@ describe("GET /api/email/[id]/attachment/[index]", () => {
});
it("streams the attachment with content headers", async () => {
- mockGetById.mockResolvedValue({ id: "e1", r2Key: "k" });
+ mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });
mockParse.mockResolvedValue({ attachments: [{}] });
mockFilter.mockReturnValue([
diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
index 296b67188..fac94b5e2 100644
--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
@@ -20,7 +20,10 @@ export const GET = withAuth(async (req, ctx) => {
if (Number.isNaN(index) || index < 0) return writeError("invalid attachment index", 400);
const email = await queries.email.getEmailById(db, id, ws.workspaceId);
- if (!email) return writeError("email not found", 404);
+ if (!email) return writeError("not found", 404);
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);
if (!object) return writeError("email content not available", 404);
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 460e34071..115d5f65e 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,6 +10,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}));
const mockGetEmailById = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
@@ -17,6 +18,7 @@ vi.mock("@alook/shared", () => ({
createDb: vi.fn(() => ({})),
queries: {
email: { getEmailById: (...args: unknown[]) => mockGetEmailById(...args) },
+ agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
},
}));
@@ -51,6 +53,7 @@ describe("GET /api/email/[id]/body", () => {
it("parses plain text email and returns text body", 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\nContent-Type: text/plain\r\n\r\nHello world")
);
@@ -66,6 +69,7 @@ describe("GET /api/email/[id]/body", () => {
it("parses HTML email and returns HTML body", 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\nContent-Type: text/html\r\n\r\n<p>Hello</p>")
);
@@ -98,6 +102,7 @@ describe("GET /api/email/[id]/body", () => {
].join("\r\n");
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockR2Get.mockResolvedValue(makeR2Object(mime));
const req = new NextRequest("http://localhost/api/email/e1/body");
@@ -111,6 +116,7 @@ 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");
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 f62659262..78146f2a8 100644
--- a/src/web/src/app/api/email/[id]/body/route.ts
+++ b/src/web/src/app/api/email/[id]/body/route.ts
@@ -17,7 +17,10 @@ export const GET = withAuth(async (req, ctx) => {
if (!id) return writeError("email id is required", 400);
const email = await queries.email.getEmailById(db, id, ws.workspaceId);
- if (!email) return writeError("email not found", 404);
+ if (!email) return writeError("not found", 404);
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);
if (!object) {
diff --git a/src/web/src/app/api/email/[id]/raw/route.test.ts b/src/web/src/app/api/email/[id]/raw/route.test.ts
index 42b754a1e..11ce2e5d8 100644
--- a/src/web/src/app/api/email/[id]/raw/route.test.ts
+++ b/src/web/src/app/api/email/[id]/raw/route.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockGetEmailById = vi.fn();
+const mockGetAgent = vi.fn();
const mockR2Get = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
@@ -23,6 +24,7 @@ vi.mock("@alook/shared", () => ({
email: {
getEmailById: (...args: unknown[]) => mockGetEmailById(...args),
},
+ agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
},
}));
@@ -52,7 +54,8 @@ describe("GET /api/email/[id]/raw", () => {
it("returns full raw MIME with content-type message/rfc822", async () => {
const rawMime = "From: [email protected]\r\nSubject: Hello\r\n\r\nBody content";
- mockGetEmailById.mockResolvedValue({ id: "e1", r2Key: "emails/e1/raw" });
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/e1/raw" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockR2Get.mockResolvedValue({
body: new ReadableStream({
start(c) { c.enqueue(new TextEncoder().encode(rawMime)); c.close(); },
@@ -69,7 +72,8 @@ describe("GET /api/email/[id]/raw", () => {
});
it("returns 404 when R2 object missing", async () => {
- mockGetEmailById.mockResolvedValue({ id: "e1", r2Key: "emails/e1/raw" });
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/e1/raw" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockR2Get.mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/email/e1/raw");
diff --git a/src/web/src/app/api/email/[id]/raw/route.ts b/src/web/src/app/api/email/[id]/raw/route.ts
index c627e101a..6a1344ad9 100644
--- a/src/web/src/app/api/email/[id]/raw/route.ts
+++ b/src/web/src/app/api/email/[id]/raw/route.ts
@@ -16,7 +16,10 @@ export const GET = withAuth(async (req, ctx) => {
if (!id) return writeError("email id is required", 400);
const email = await queries.email.getEmailById(db, id, ws.workspaceId);
- if (!email) return writeError("email not found", 404);
+ if (!email) return writeError("not found", 404);
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);
if (!object) {
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 a3d0d8a53..abe0660e6 100644
--- a/src/web/src/app/api/email/[id]/route.test.ts
+++ b/src/web/src/app/api/email/[id]/route.test.ts
@@ -4,6 +4,7 @@ import { NextRequest } from "next/server";
const mockGetEmailById = vi.fn();
const mockDeleteEmail = vi.fn();
const mockUpdateEmailStatus = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({
@@ -24,6 +25,7 @@ vi.mock("@alook/shared", async () => {
deleteEmail: (...args: unknown[]) => mockDeleteEmail(...args),
updateEmailStatus: (...args: unknown[]) => mockUpdateEmailStatus(...args),
},
+ agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
},
};
});
@@ -60,6 +62,7 @@ describe("GET /api/email/[id]", () => {
it("returns email scoped by workspaceId", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
const req = new NextRequest("http://localhost/api/email/e1");
const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
@@ -83,6 +86,7 @@ describe("DELETE /api/email/[id]", () => {
it("deletes an email scoped by workspaceId and returns 204", async () => {
mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockDeleteEmail.mockResolvedValue(undefined);
const req = new NextRequest("http://localhost/api/email/e1", { method: "DELETE" });
@@ -106,6 +110,8 @@ describe("PATCH /api/email/[id]", () => {
beforeEach(() => vi.clearAllMocks());
it("updates status for valid email in workspace", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockUpdateEmailStatus.mockResolvedValue({ id: "e1", status: "read" });
const req = new NextRequest("http://localhost/api/email/e1", {
@@ -121,6 +127,8 @@ describe("PATCH /api/email/[id]", () => {
});
it("updates status to archived", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockUpdateEmailStatus.mockResolvedValue({ id: "e1", status: "archived" });
const req = new NextRequest("http://localhost/api/email/e1", {
@@ -134,6 +142,8 @@ describe("PATCH /api/email/[id]", () => {
});
it("returns 404 when email not in workspace", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockUpdateEmailStatus.mockResolvedValue(null);
const req = new NextRequest("http://localhost/api/email/e1", {
@@ -146,6 +156,8 @@ describe("PATCH /api/email/[id]", () => {
});
it("returns 400 for invalid status value", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
const req = new NextRequest("http://localhost/api/email/e1", {
method: "PATCH",
body: JSON.stringify({ status: "deleted" }),
@@ -159,6 +171,8 @@ describe("PATCH /api/email/[id]", () => {
});
it("returns 400 for missing status", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
const req = new NextRequest("http://localhost/api/email/e1", {
method: "PATCH",
body: JSON.stringify({}),
@@ -169,6 +183,8 @@ describe("PATCH /api/email/[id]", () => {
});
it("returns 400 for invalid JSON body", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
const req = new NextRequest("http://localhost/api/email/e1", {
method: "PATCH",
body: "not json",
diff --git a/src/web/src/app/api/email/[id]/route.ts b/src/web/src/app/api/email/[id]/route.ts
index 3a0519897..5f2f0fcad 100644
--- a/src/web/src/app/api/email/[id]/route.ts
+++ b/src/web/src/app/api/email/[id]/route.ts
@@ -17,7 +17,10 @@ export const GET = withAuth(async (req, ctx) => {
if (!id) return writeError("email id is required", 400);
const email = await queries.email.getEmailById(db, id, ws.workspaceId);
- if (!email) return writeError("email not found", 404);
+ if (!email) return writeError("not found", 404);
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
return writeJSON(emailToResponse(email));
});
@@ -33,7 +36,10 @@ export const DELETE = withAuth(async (req, ctx) => {
if (!id) return writeError("email id is required", 400);
const email = await queries.email.getEmailById(db, id, ws.workspaceId);
- if (!email) return writeError("email not found", 404);
+ if (!email) return writeError("not found", 404);
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
await queries.email.deleteEmail(db, id, ws.workspaceId);
@@ -50,11 +56,17 @@ export const PATCH = 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, ws.workspaceId);
+ if (!email) return writeError("not found", 404);
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
+
const [body, valErr] = await parseBody(req, UpdateEmailStatusRequestSchema);
if (valErr) return valErr;
const updated = await queries.email.updateEmailStatus(db, id, ws.workspaceId, body.status);
- if (!updated) return writeError("email not found", 404);
+ if (!updated) return writeError("not found", 404);
return writeJSON(emailToResponse(updated));
});
diff --git a/src/web/src/app/api/email/[id]/thread/route.test.ts b/src/web/src/app/api/email/[id]/thread/route.test.ts
index c7c55d617..85c699450 100644
--- a/src/web/src/app/api/email/[id]/thread/route.test.ts
+++ b/src/web/src/app/api/email/[id]/thread/route.test.ts
@@ -8,6 +8,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
const mockGetById = vi.fn();
const mockGetByMessageId = vi.fn();
+const mockGetAgent = vi.fn();
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual("@alook/shared");
return {
@@ -17,6 +18,7 @@ vi.mock("@alook/shared", async () => {
getEmailById: (...a: unknown[]) => mockGetById(...a),
getEmailByMessageId: (...a: unknown[]) => mockGetByMessageId(...a),
},
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
},
};
});
@@ -51,14 +53,16 @@ describe("GET /api/email/[id]/thread", () => {
});
it("returns [] when the email has no parent", async () => {
- mockGetById.mockResolvedValue({ id: "e1", inReplyTo: null });
+ mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", inReplyTo: null });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
const res = await get({ id: "e1" });
expect(res.status).toBe(200);
expect(await res.json()).toEqual([]);
});
it("walks the reply chain oldest-first", async () => {
- mockGetById.mockResolvedValue({ id: "e3", inReplyTo: "msg2" });
+ mockGetById.mockResolvedValue({ id: "e3", agentId: "a1", inReplyTo: "msg2" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockGetByMessageId
.mockResolvedValueOnce({ id: "e2", inReplyTo: "msg1" })
.mockResolvedValueOnce({ id: "e1", inReplyTo: null });
@@ -67,7 +71,8 @@ describe("GET /api/email/[id]/thread", () => {
});
it("stops at a cycle without infinite looping", async () => {
- mockGetById.mockResolvedValue({ id: "e2", inReplyTo: "msgSelf" });
+ mockGetById.mockResolvedValue({ id: "e2", agentId: "a1", inReplyTo: "msgSelf" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
// parent points back to a message id already seen → loop guard breaks
mockGetByMessageId.mockResolvedValue({ id: "e1", inReplyTo: "msgSelf" });
const res = await get({ id: "e2" });
diff --git a/src/web/src/app/api/email/[id]/thread/route.ts b/src/web/src/app/api/email/[id]/thread/route.ts
index d0a41bc06..3f836a327 100644
--- a/src/web/src/app/api/email/[id]/thread/route.ts
+++ b/src/web/src/app/api/email/[id]/thread/route.ts
@@ -17,7 +17,10 @@ export const GET = withAuth(async (req, ctx) => {
if (!id) return writeError("email id is required", 400);
const email = await queries.email.getEmailById(db, id, ws.workspaceId);
- if (!email) return writeError("email not found", 404);
+ if (!email) return writeError("not found", 404);
+
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("not found", 404);
if (!email.inReplyTo) return writeJSON([]);
diff --git a/src/web/src/app/api/email/[id]/trust/route.ts b/src/web/src/app/api/email/[id]/trust/route.ts
index 258b61dbb..ee1d7008e 100644
--- a/src/web/src/app/api/email/[id]/trust/route.ts
+++ b/src/web/src/app/api/email/[id]/trust/route.ts
@@ -25,7 +25,7 @@ export const POST = withAuth(async (req, ctx) => {
if (email.isWhitelisted) return writeError("email is already trusted", 400)
if (email.direction !== "inbound") return writeError("only inbound emails can be trusted", 400)
- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId)
+ const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId)
if (!agent || !agent.runtimeId || !agent.ownerId) return writeError("agent not found or has no runtime", 404)
const updatedEmail = await queries.email.updateEmailWhitelisted(db, id, ws.workspaceId, true)
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 476b9c751..d0a9bccbc 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
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockGetTask = vi.fn();
+const mockGetAgent = vi.fn();
const mockListTaskMessages = vi.fn();
const mockListTaskMessagesSince = vi.fn();
const mockTaskMessageToResponse = vi.fn((m: any) => ({
@@ -35,6 +36,9 @@ vi.mock("@alook/shared", () => ({
task: {
getTask: (...args: any[]) => mockGetTask(...args),
},
+ agent: {
+ getAgent: (...args: any[]) => mockGetAgent(...args),
+ },
taskMessage: {
listTaskMessages: (...args: any[]) => mockListTaskMessages(...args),
listTaskMessagesSince: (...args: any[]) => mockListTaskMessagesSince(...args),
@@ -60,8 +64,9 @@ describe("GET /api/tasks/[id]/messages", () => {
beforeEach(() => vi.clearAllMocks());
it("passes workspaceId to getTask", async () => {
- const task = { id: "t1", workspaceId: "w1" };
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1" };
mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockListTaskMessages.mockResolvedValue([]);
await GET(
new NextRequest("http://localhost/api/tasks/t1/messages"),
@@ -71,12 +76,13 @@ describe("GET /api/tasks/[id]/messages", () => {
});
it("lists all messages", async () => {
- const task = { id: "t1", workspaceId: "w1" };
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1" };
const messages = [
{ id: "m1", taskId: "t1", seq: 1, type: "text", content: "hello" },
{ id: "m2", taskId: "t1", seq: 2, type: "text", content: "world" },
];
mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockListTaskMessages.mockResolvedValue(messages);
const res = await GET(
@@ -94,11 +100,12 @@ describe("GET /api/tasks/[id]/messages", () => {
});
it("filters by since parameter", async () => {
- const task = { id: "t1", workspaceId: "w1" };
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1" };
const messages = [
{ id: "m3", taskId: "t1", seq: 6, type: "text", content: "new msg" },
];
mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockListTaskMessagesSince.mockResolvedValue(messages);
const res = await GET(
@@ -116,8 +123,9 @@ describe("GET /api/tasks/[id]/messages", () => {
});
it("returns 400 for invalid since parameter", async () => {
- const task = { id: "t1", workspaceId: "w1" };
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1" };
mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
const res = await GET(
new NextRequest("http://localhost/api/tasks/t1/messages?since=abc"),
@@ -139,15 +147,16 @@ describe("GET /api/tasks/[id]/messages", () => {
const body = await res.json();
expect(res.status).toBe(404);
- expect(body.error).toBe("task not found");
+ expect(body.error).toBe("not found");
});
it("only returns text and error messages (tool-result, tool-use, thinking filtered at query level)", async () => {
- const task = { id: "t1", workspaceId: "w1" };
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1" };
const messages = [
{ id: "m1", taskId: "t1", seq: 1, type: "text", content: "hello" },
];
mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockListTaskMessages.mockResolvedValue(messages);
const res = await GET(
@@ -162,11 +171,12 @@ describe("GET /api/tasks/[id]/messages", () => {
});
it("only returns text and error messages with since parameter (filtered at query level)", async () => {
- const task = { id: "t1", workspaceId: "w1" };
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1" };
const messages = [
{ id: "m4", taskId: "t1", seq: 7, type: "text", content: "new update" },
];
mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockListTaskMessagesSince.mockResolvedValue(messages);
const res = await GET(
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 8d8df74d2..fe120f99a 100644
--- a/src/web/src/app/api/tasks/[id]/messages/route.ts
+++ b/src/web/src/app/api/tasks/[id]/messages/route.ts
@@ -20,7 +20,12 @@ export const GET = withAuth(async (req, ctx) => {
const task = await queries.task.getTask(db, id, ws.workspaceId);
if (!task) {
- return writeError("task not found", 404);
+ return writeError("not found", 404);
+ }
+
+ const agent = await queries.agent.getAgent(db, task.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) {
+ return writeError("not found", 404);
}
const sinceParam = req.nextUrl.searchParams.get("since");
diff --git a/src/web/src/app/api/tasks/[id]/retry/route.test.ts b/src/web/src/app/api/tasks/[id]/retry/route.test.ts
index fee346aa5..3f3a19df2 100644
--- a/src/web/src/app/api/tasks/[id]/retry/route.test.ts
+++ b/src/web/src/app/api/tasks/[id]/retry/route.test.ts
@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
+const mockGetTask = vi.fn();
+const mockGetAgent = vi.fn();
const mockRetryTask = vi.fn();
const mockTaskToResponse = vi.fn((t: any) => ({
id: t.id,
@@ -26,6 +28,17 @@ vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}));
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ task: {
+ getTask: (...args: any[]) => mockGetTask(...args),
+ },
+ agent: {
+ getAgent: (...args: any[]) => mockGetAgent(...args),
+ },
+ },
+}));
vi.mock("@/lib/services/task", () => {
const MockTaskService = function (this: any) {
this.retryTask = (...a: any[]) => mockRetryTask(...a);
@@ -47,6 +60,10 @@ vi.mock("@/lib/api/responses", () => ({
vi.mock("@/lib/broadcast", () => ({
broadcastToUser: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockReturnValue(Promise.resolve()),
+ cacheKeys: { overviewTaskStats: (...args: any[]) => `stats:${args.join(":")}` },
+}));
import { POST } from "./route";
@@ -54,8 +71,11 @@ describe("POST /api/tasks/[id]/retry", () => {
beforeEach(() => vi.clearAllMocks());
it("returns new task on success", async () => {
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1", status: "failed", prompt: "hello" };
const oldTask = { id: "t1", agentId: "a1", workspaceId: "w1", status: "superseded", prompt: "hello" };
const newTask = { id: "t2", agentId: "a1", workspaceId: "w1", status: "queued", prompt: "hello" };
+ mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockRetryTask.mockResolvedValue({ oldTask, newTask });
const res = await POST(
@@ -71,6 +91,9 @@ describe("POST /api/tasks/[id]/retry", () => {
});
it("returns 400 when task is not failed", async () => {
+ const task = { id: "t1", agentId: "a1", workspaceId: "w1", status: "completed", prompt: "hello" };
+ mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
mockRetryTask.mockRejectedValue(new Error("only failed tasks can be retried"));
const res = await POST(
@@ -83,8 +106,8 @@ describe("POST /api/tasks/[id]/retry", () => {
expect(body.error).toBe("only failed tasks can be retried");
});
- it("returns 400 when task not found", async () => {
- mockRetryTask.mockRejectedValue(new Error("task not found"));
+ it("returns 404 when task not found", async () => {
+ mockGetTask.mockResolvedValue(null);
const res = await POST(
new NextRequest("http://localhost/api/tasks/t1/retry", { method: "POST" }),
@@ -92,7 +115,7 @@ describe("POST /api/tasks/[id]/retry", () => {
);
const body = await res.json();
- expect(res.status).toBe(400);
- expect(body.error).toBe("task not found");
+ expect(res.status).toBe(404);
+ expect(body.error).toBe("not found");
});
});
diff --git a/src/web/src/app/api/tasks/[id]/retry/route.ts b/src/web/src/app/api/tasks/[id]/retry/route.ts
index 30be57582..b100661b9 100644
--- a/src/web/src/app/api/tasks/[id]/retry/route.ts
+++ b/src/web/src/app/api/tasks/[id]/retry/route.ts
@@ -1,4 +1,5 @@
import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries } from "@alook/shared";
import { getDb } from "@/lib/db";
import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
@@ -20,6 +21,16 @@ export const POST = withAuth(async (req, ctx) => {
return writeError("task id is required", 400);
}
+ const task = await queries.task.getTask(db, id, ws.workspaceId);
+ if (!task) {
+ return writeError("not found", 404);
+ }
+
+ const agent = await queries.agent.getAgent(db, task.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) {
+ return writeError("not found", 404);
+ }
+
const taskService = new TaskService(db);
try {
const { oldTask, newTask } = await taskService.retryTask(id, ws.workspaceId);
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 ff632afd3..27504ccbb 100644
--- a/src/web/src/app/api/tasks/[id]/route.test.ts
+++ b/src/web/src/app/api/tasks/[id]/route.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockGetTask = vi.fn();
+const mockGetAgent = vi.fn();
const mockTaskToResponse = vi.fn((t: any) => ({
id: t.id,
agent_id: t.agentId,
@@ -33,6 +34,9 @@ vi.mock("@alook/shared", () => ({
task: {
getTask: (...args: any[]) => mockGetTask(...args),
},
+ agent: {
+ getAgent: (...args: any[]) => mockGetAgent(...args),
+ },
},
}));
vi.mock("@/lib/middleware/auth", () => ({
@@ -62,6 +66,7 @@ describe("GET /api/tasks/[id]", () => {
prompt: "hello",
};
mockGetTask.mockResolvedValue(task);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
const res = await GET(
new NextRequest("http://localhost/api/tasks/t1"),
@@ -90,6 +95,6 @@ describe("GET /api/tasks/[id]", () => {
const body = await res.json();
expect(res.status).toBe(404);
- expect(body.error).toBe("task not found");
+ expect(body.error).toBe("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 7bd9517ae..9d8b9b22c 100644
--- a/src/web/src/app/api/tasks/[id]/route.ts
+++ b/src/web/src/app/api/tasks/[id]/route.ts
@@ -20,7 +20,12 @@ export const GET = withAuth(async (req, ctx) => {
const task = await queries.task.getTask(db, id, ws.workspaceId);
if (!task) {
- return writeError("task not found", 404);
+ return writeError("not found", 404);
+ }
+
+ const agent = await queries.agent.getAgent(db, task.agentId, ws.workspaceId, ctx.userId);
+ if (!agent) {
+ return writeError("not found", 404);
}
return writeJSON(taskToResponse(task));
diff --git a/src/web/src/app/api/traces/[traceId]/route.test.ts b/src/web/src/app/api/traces/[traceId]/route.test.ts
index 30f6277e6..57b875f93 100644
--- a/src/web/src/app/api/traces/[traceId]/route.test.ts
+++ b/src/web/src/app/api/traces/[traceId]/route.test.ts
@@ -201,7 +201,7 @@ describe("GET /api/traces/[traceId]", () => {
expect(body.channel).toBe("default");
});
- it("returns null agent for unknown agentId", async () => {
+ it("returns 404 when root agent is not visible", async () => {
mockGetTraceTree.mockResolvedValue([
{
id: "task_1",
@@ -225,7 +225,7 @@ describe("GET /api/traces/[traceId]", () => {
);
const body = await res.json();
- expect(res.status).toBe(200);
- expect(body.tasks[0].agent).toBeNull();
+ expect(res.status).toBe(404);
+ expect(body.error).toBe("not found");
});
});
diff --git a/src/web/src/app/api/traces/[traceId]/route.ts b/src/web/src/app/api/traces/[traceId]/route.ts
index ec77c66f9..5384e7e90 100644
--- a/src/web/src/app/api/traces/[traceId]/route.ts
+++ b/src/web/src/app/api/traces/[traceId]/route.ts
@@ -35,9 +35,14 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),
]);
const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);
+ const visibleIds = new Set(agents.map(a => a.id));
const agentMap = new Map(agents.map(a => [a.id, { name: a.name, email_handle: a.emailHandle, avatarUrl: a.avatarUrl }]));
- const traceTasks = tasks.map(t => ({
+ if (rootTask && !visibleIds.has(rootTask.agentId)) {
+ return writeError("not found", 404);
+ }
+
+ const traceTasks = tasks.filter(t => visibleIds.has(t.agentId)).map(t => ({
id: t.id,
agent_id: t.agentId,
agent: agentMap.get(t.agentId) ?? null,
diff --git a/src/web/src/app/api/traces/route.test.ts b/src/web/src/app/api/traces/route.test.ts
index 0f2940397..8943a4eeb 100644
--- a/src/web/src/app/api/traces/route.test.ts
+++ b/src/web/src/app/api/traces/route.test.ts
@@ -102,7 +102,7 @@ describe("GET /api/traces", () => {
expect(body.has_more).toBe(false);
});
- it("handles unknown agent (returns null for root_agent)", async () => {
+ it("filters out traces whose root agent is not visible", async () => {
mockListTraces.mockResolvedValue({
traces: [
{
@@ -126,7 +126,7 @@ describe("GET /api/traces", () => {
const body = await res.json();
expect(res.status).toBe(200);
- expect(body.traces[0].root_agent).toBeNull();
+ expect(body.traces).toHaveLength(0);
});
it("respects status filter", async () => {
diff --git a/src/web/src/app/api/traces/route.ts b/src/web/src/app/api/traces/route.ts
index 8177ed3ca..ba7f3fbce 100644
--- a/src/web/src/app/api/traces/route.ts
+++ b/src/web/src/app/api/traces/route.ts
@@ -31,9 +31,10 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),
]);
const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);
+ const visibleIds = new Set(agents.map(a => a.id));
const agentMap = new Map(agents.map(a => [a.id, { name: a.name, avatarUrl: a.avatarUrl }]));
- const traces = result.traces.map(t => ({
+ const traces = result.traces.filter(t => visibleIds.has(t.rootAgentId)).map(t => ({
trace_id: t.traceId,
root_prompt: t.rootPrompt,
root_agent_id: t.rootAgentId,