Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): type-aware react/pin validation (phase-2)
Gener516d0e98d321
diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.tsnew file mode 100644index 000000000..36e7269dc--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts@@ -0,0 +1,102 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockGetChannel = vi.fn();+const mockGetMember = vi.fn();+const mockUnpinMessage = vi.fn();+const mockLogAction = vi.fn();+const mockFanOut = vi.fn();++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual("@alook/shared");+ return {+ ...actual,+ queries: {+ communityChannel: { getChannel: (...a: unknown[]) => mockGetChannel(...a) },+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },+ communityPin: { unpinMessage: (...a: unknown[]) => mockUnpinMessage(...a) },+ },+ };+});++vi.mock("@/lib/community/audit", () => ({+ logAudit: (...a: unknown[]) => mockLogAction(...a),+}));++vi.mock("@/lib/community/fanout", () => ({+ fanOutToChannel: (...a: unknown[]) => mockFanOut(...a),+}));++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });+ }),+}));++vi.mock("@/lib/middleware/helpers", async () => {+ const { NextResponse } = require("next/server");+ const actual = await vi.importActual("@/lib/middleware/helpers");+ return {+ ...actual,+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ };+});++import { DELETE } from "./route";++function delReq() {+ return new NextRequest("http://localhost/api/community/channels/c1/pins/m1", { method: "DELETE" });+}+const ctx = { params: { id: "c1", messageId: "m1" } } as any;++describe("DELETE /api/community/channels/[id]/pins/[messageId]", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" });+ mockGetMember.mockResolvedValue({ userId: "u1", role: "admin" });+ mockUnpinMessage.mockResolvedValue(undefined);+ mockFanOut.mockResolvedValue(undefined);+ });++ it("unpins a message and returns 204", async () => {+ const res = await DELETE(delReq(), ctx);+ expect(res.status).toBe(204);+ expect(mockUnpinMessage).toHaveBeenCalledWith(expect.anything(), { channelId: "c1", messageId: "m1" });+ expect(mockFanOut).toHaveBeenCalled();+ });++ it("returns 404 when the channel does not exist", async () => {+ mockGetChannel.mockResolvedValue(null);+ const res = await DELETE(delReq(), ctx);+ expect(res.status).toBe(404);+ expect(mockUnpinMessage).not.toHaveBeenCalled();+ });++ it("returns 400 in a forum top-level (nothing to unpin)", async () => {+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" });+ const res = await DELETE(delReq(), ctx);+ expect(res.status).toBe(400);+ expect(mockUnpinMessage).not.toHaveBeenCalled();+ });++ it("returns 400 in a DM (governance model does not fit)", async () => {+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: null, type: "dm" });+ const res = await DELETE(delReq(), ctx);+ expect(res.status).toBe(400);+ expect(mockUnpinMessage).not.toHaveBeenCalled();+ });++ it("returns 403 when the caller is not a server admin", async () => {+ mockGetMember.mockResolvedValue({ userId: "u1", role: "member" });+ const res = await DELETE(delReq(), ctx);+ expect(res.status).toBe(403);+ expect(mockUnpinMessage).not.toHaveBeenCalled();+ });+});diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.tsindex cab8d7d5f..129055619 100644--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import { queries, WS_EVENTS } from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"import { requireServerAdmin } from "@/lib/community/permissions"+import { requirePinnableSurface } from "@/lib/community/channel-write-guard"import { logAudit } from "@/lib/community/audit"export const DELETE = withAuth(async (_req: NextRequest, ctx) => {@@ -17,6 +18,9 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const channel = await queries.communityChannel.getChannel(db, channelId)if (!channel) return writeError("channel not found", 404)+ const pinnable = requirePinnableSurface(channel.type)+ if (!pinnable.ok) return writeError(pinnable.error, pinnable.status)+// Unpinning is a moderation action — require admin / owner.const auth = await requireServerAdmin(db, channel.serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/route.test.tsindex 239507cbb..8a05b8314 100644--- a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts@@ -68,7 +68,7 @@ const ctx = { params: { id: "c1" } } as any;describe("POST /api/community/channels/[id]/pins", () => {beforeEach(() => {vi.clearAllMocks();- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" });+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" });// Pinning is admin-only — every happy path starts with an admin caller.mockGetMember.mockResolvedValue({ userId: "u1", role: "admin" });mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" });@@ -118,6 +118,20 @@ describe("POST /api/community/channels/[id]/pins", () => {expect(mockPinMessage).not.toHaveBeenCalled();});+ it("returns 400 when pinning in a forum top-level (nothing to pin)", async () => {+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" });+ const res = await POST(postReq("m1"), ctx);+ expect(res.status).toBe(400);+ expect(mockPinMessage).not.toHaveBeenCalled();+ });++ it("returns 400 when pinning in a DM (governance model does not fit)", async () => {+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: null, type: "dm" });+ const res = await POST(postReq("m1"), ctx);+ expect(res.status).toBe(400);+ expect(mockPinMessage).not.toHaveBeenCalled();+ });+it("returns 404 when the channel does not exist", async () => {mockGetChannel.mockResolvedValue(null);const res = await POST(postReq("m1"), ctx);diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.ts b/src/web/src/app/api/community/channels/[id]/pins/route.tsindex 85c59e51f..83da25b53 100644--- a/src/web/src/app/api/community/channels/[id]/pins/route.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import { queries, isUniqueConstraintError, WS_EVENTS } from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"+import { requirePinnableSurface } from "@/lib/community/channel-write-guard"import { logAudit } from "@/lib/community/audit"import { avatarInitial } from "@/lib/community/avatar"@@ -36,6 +37,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const channel = await queries.communityChannel.getChannel(db, channelId)if (!channel) return writeError("channel not found", 404)+ const pinnable = requirePinnableSurface(channel.type)+ if (!pinnable.ok) return writeError(pinnable.error, pinnable.status)+// Pinning is a moderation action — require server admin / owner.const adminCheck = await requireServerAdmin(db, channel.serverId, ctx.userId)if (!adminCheck.ok) return writeError(adminCheck.error, adminCheck.status)diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.tsnew file mode 100644index 000000000..631f5fd31--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.test.ts@@ -0,0 +1,118 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockGetMessage = vi.fn();+const mockGetChannelType = vi.fn();+const mockGetChannelForMember = vi.fn();+const mockGetDM = vi.fn();+const mockAddReaction = vi.fn();+const mockRemoveReaction = vi.fn();+const mockFanOutToChannel = vi.fn();+const mockFanOutToDM = vi.fn();++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMessage: { getMessage: (...a: unknown[]) => mockGetMessage(...a) },+ communityChannel: { getChannelType: (...a: unknown[]) => mockGetChannelType(...a) },+ communityReaction: {+ addReaction: (...a: unknown[]) => mockAddReaction(...a),+ removeReaction: (...a: unknown[]) => mockRemoveReaction(...a),+ },+ },+ };+});++vi.mock("@/lib/community/permissions", () => ({+ requireChannelMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ requireDMAccess: (...a: unknown[]) => mockGetDM(...a),+}));++vi.mock("@/lib/community/fanout", () => ({+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),+ fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),+}));++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });+ }),+}));++vi.mock("@/lib/middleware/helpers", async () => {+ const { NextResponse } = require("next/server");+ const actual = await vi.importActual("@/lib/middleware/helpers");+ return {+ ...actual,+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ };+});++import { PUT, DELETE } from "./route";++const ctx = { params: { id: "m1", emoji: encodeURIComponent("👍") } } as any;+function req(method: string) {+ return new NextRequest("http://localhost/api/community/messages/m1/reactions/%F0%9F%91%8D", { method });+}++describe("reactions [emoji] surface guard", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" });+ mockGetChannelForMember.mockResolvedValue({ ok: true, value: { id: "c1" } });+ mockGetDM.mockResolvedValue({ ok: true });+ mockAddReaction.mockResolvedValue({ messageId: "m1", userId: "u1", emoji: "👍" });+ mockRemoveReaction.mockResolvedValue(undefined);+ mockFanOutToChannel.mockResolvedValue(undefined);+ mockFanOutToDM.mockResolvedValue(undefined);+ });++ it("PUT rejects reacting on a forum top-level with 400", async () => {+ mockGetChannelType.mockResolvedValue("forum");+ const res = await PUT(req("PUT"), ctx);+ expect(res.status).toBe(400);+ expect(mockAddReaction).not.toHaveBeenCalled();+ });++ it("PUT allows reacting in a DM (bearing surface, block-checked)", async () => {+ mockGetChannelType.mockResolvedValue("dm");+ const res = await PUT(req("PUT"), ctx);+ expect(res.status).toBe(200);+ expect(mockGetDM).toHaveBeenCalled();+ expect(mockAddReaction).toHaveBeenCalled();+ expect(mockFanOutToDM).toHaveBeenCalled();+ });++ it("PUT allows reacting in a text channel", async () => {+ mockGetChannelType.mockResolvedValue("text");+ const res = await PUT(req("PUT"), ctx);+ expect(res.status).toBe(200);+ expect(mockAddReaction).toHaveBeenCalled();+ expect(mockFanOutToChannel).toHaveBeenCalled();+ });++ it("DELETE (un-react) rejects a forum top-level with 400", async () => {+ mockGetChannelType.mockResolvedValue("forum");+ const res = await DELETE(req("DELETE"), ctx);+ expect(res.status).toBe(400);+ expect(mockRemoveReaction).not.toHaveBeenCalled();+ });++ it("DELETE (un-react) works in a DM", async () => {+ mockGetChannelType.mockResolvedValue("dm");+ const res = await DELETE(req("DELETE"), ctx);+ expect(res.status).toBe(204);+ expect(mockRemoveReaction).toHaveBeenCalled();+ });+});diff --git a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.tsindex face7805a..c1ae0e67e 100644--- a/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts+++ b/src/web/src/app/api/community/messages/[id]/reactions/[emoji]/route.ts@@ -14,9 +14,10 @@ import {requireChannelMember,requireDMAccess,} from "@/lib/community/permissions"+import { requireReactableSurface } from "@/lib/community/channel-write-guard"type AccessOk = { ok: true; channelId: string; isDm: boolean }-type AccessErr = { ok: false; status: 401 | 403 | 404; error: string }+type AccessErr = { ok: false; status: 400 | 401 | 403 | 404; error: string }/*** Resolve the message and verify the caller can react.@@ -33,6 +34,8 @@ async function authorizeReaction(if (!message) return { ok: false, status: 404, error: "message not found" }const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ const reactable = requireReactableSurface(channelType)+ if (!reactable.ok) return { ok: false, status: reactable.status, error: reactable.error }if (channelType === "dm") {const check = await requireDMAccess(db, message.channelId, userId)if (!check.ok) return checkdiff --git a/src/web/src/app/api/community/reactAdd/route.test.ts b/src/web/src/app/api/community/reactAdd/route.test.tsindex 15da3e449..96c3878b4 100644--- a/src/web/src/app/api/community/reactAdd/route.test.ts+++ b/src/web/src/app/api/community/reactAdd/route.test.ts@@ -132,17 +132,26 @@ describe("POST /api/community/agent/reactAdd", () => {it("404 when the channel exists but has no message at that seq", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null })mockGetMessageByChannelAndSeq.mockResolvedValue(null)const res = await POST(req({ channel: "/studio/general", seq: 99, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(404)expect(mockAddReaction).not.toHaveBeenCalled()})+ it("400 when reacting on a forum top-level (not a message-bearing surface)", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "forum", parentChannelId: null })+ const res = await POST(req({ channel: "/studio/chore", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ expect(mockAddReaction).not.toHaveBeenCalled()+ })+it("200 happy path — channel react: inserts, fans out to channel with REACTION_ADD, excluding the bot", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null })mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 3, content: "hi" })mockAddReaction.mockResolvedValue({ messageId: "m_1", userId: "bot_1", emoji: "👍" })@@ -196,7 +205,7 @@ describe("POST /api/community/agent/reactAdd", () => {it("duplicate — addReaction throws unique-constraint → {ok:true, duplicate:true}, no fan-out", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null })mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 3, content: "hi" })// Match isUniqueConstraintError → matches SQLite UNIQUE constraint messagesmockAddReaction.mockRejectedValue(new Error("D1_ERROR: UNIQUE constraint failed: community_reaction.message_id, community_reaction.user_id, community_reaction.emoji"))diff --git a/src/web/src/app/api/community/reactAdd/route.ts b/src/web/src/app/api/community/reactAdd/route.tsindex 8b2afee51..2b32314be 100644--- a/src/web/src/app/api/community/reactAdd/route.ts+++ b/src/web/src/app/api/community/reactAdd/route.ts@@ -11,6 +11,7 @@ import { withCommunityActor, requireBot } from "@/lib/middleware/community-actorimport { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { isDmTarget } from "@/lib/community/message-handler"import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"+import { requireReactableSurface } from "@/lib/community/channel-write-guard"import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"/**@@ -57,9 +58,13 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {if (isDmTarget(resolved)) {const gate = await requireDMAccess(db, resolved.channelId, botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ const reactable = requireReactableSurface("dm")+ if (!reactable.ok) return NextResponse.json({ error: reactable.error }, { status: reactable.status })} else {const gate = await requireChannelMember(db, resolved.channelId, botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ const reactable = requireReactableSurface(gate.value.type)+ if (!reactable.ok) return NextResponse.json({ error: reactable.error }, { status: reactable.status })}const row = await queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.seq)diff --git a/src/web/src/lib/community/channel-write-guard.test.ts b/src/web/src/lib/community/channel-write-guard.test.tsindex 4a4a2db92..9f07421e3 100644--- a/src/web/src/lib/community/channel-write-guard.test.ts+++ b/src/web/src/lib/community/channel-write-guard.test.ts@@ -3,6 +3,8 @@ import {requireMessageBearingSurface,requireChildSurface,rejectDmOnGenericChannelRoute,+ requireReactableSurface,+ requirePinnableSurface,} from "./channel-write-guard"describe("requireMessageBearingSurface", () => {@@ -40,6 +42,36 @@ describe("rejectDmOnGenericChannelRoute", () => {})})+describe("requireReactableSurface", () => {+ it("accepts every message-bearing surface incl. dm (reacting in a DM is legit)", () => {+ for (const t of ["text", "forum_post", "thread", "dm"]) {+ expect(requireReactableSurface(t).ok).toBe(true)+ }+ })++ it("rejects a forum top-level (nothing to react to) with 400", () => {+ const r = requireReactableSurface("forum")+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.status).toBe(400)+ })+})++describe("requirePinnableSurface", () => {+ it("accepts text/forum_post/thread", () => {+ for (const t of ["text", "forum_post", "thread"]) {+ expect(requirePinnableSurface(t).ok).toBe(true)+ }+ })++ it("rejects dm (governance model does not fit) and forum top-level with 400", () => {+ for (const t of ["dm", "forum", null, undefined]) {+ const r = requirePinnableSurface(t)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.status).toBe(400)+ }+ })+})+describe("requireChildSurface", () => {it("accepts thread and forum_post", () => {expect(requireChildSurface("thread").ok).toBe(true)diff --git a/src/web/src/lib/community/channel-write-guard.ts b/src/web/src/lib/community/channel-write-guard.tsindex a2af520cc..7ec20ae15 100644--- a/src/web/src/lib/community/channel-write-guard.ts+++ b/src/web/src/lib/community/channel-write-guard.ts@@ -26,7 +26,26 @@ export function requireMessageBearingSurface(channelType: string | null | undefi}}+export function requireReactableSurface(channelType: string | null | undefined): WriteGuardResult {+ if (isMessageBearingSurface(channelType)) return pass+ return {+ ok: false,+ status: 400,+ error: "a forum top-level holds posts, not messages — nothing to react to here",+ }+}+export function requireChildSurface(channelType: string | null | undefined): WriteGuardResult {if (isThread(channelType) || isForumPost(channelType)) return passreturn { ok: false, status: 400, error: "not a thread or forum post" }}++export function requirePinnableSurface(channelType: string | null | undefined): WriteGuardResult {+ if (isDm(channelType)) {+ return { ok: false, status: 400, error: "direct messages don't support pinning" }+ }+ if (!isMessageBearingSurface(channelType)) {+ return { ok: false, status: 400, error: "a forum top-level holds posts, not messages — nothing to pin here" }+ }+ return pass+}