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
refactor(community): collapse route tree onto id-in-path + forum≡thread (#424)
Generf79e0ec2b300
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 62389c925..421e7686e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -218,9 +218,15 @@ importers:'@cloudflare/workers-types':specifier: ^4.20260702.1version: 4.20260702.1+ '@types/better-sqlite3':+ specifier: ^7.6.13+ version: 7.6.13'@types/node':specifier: ^25.9.4version: 25.9.4+ better-sqlite3:+ specifier: ^12.11.1+ version: 12.11.1knip:specifier: ^6.29.0version: 6.29.0diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex d06543d6a..36c0183be 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -31,7 +31,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {read: async () => ({ items: [], hasMore: false }),resolve: async () => null,listMembers: async () => ({ members: [], hasMore: false }),- joinServer: async () => ({ server: { id: "s", name: "s" } }),+ joinServer: async () => ({ server: { handle: "s#0042" } }),reactAdd: async () => ({ ok: true, duplicate: false }),friendRequest: async () => ({ friendshipId: "fr_1", status: "pending", hint: "Your owner needs to approve this request in DM." }),listFriends: async () => ({ accepted: [], pendingOutgoing: [], pendingIncoming: [] }),@@ -77,14 +77,14 @@ describe("envelope contract", () => {stubApi({send: async () => ({state: "sent",- message: { seq: "#7", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" },+ message: { seq: "#7", channel: "/s#0042/general", sender: "@a", content: { text: "hi" }, time: "" },}),}),);- const code = await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ const code = await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);const env = parseEnvelope(cap.lines());expect(code).toBe(0);- expect(env).toEqual({ success: { sent: "/s/general#7" } });+ expect(env).toEqual({ success: { sent: "/s#0042/general#7" } });expect("error" in env).toBe(false);expect("hint" in env).toBe(false); // null fields omitted});@@ -92,7 +92,7 @@ describe("envelope contract", () => {it("prints only `error` on failure (with hint when available)", async () => {setApiForTesting(stubApi());// Emoji ref without a seq → error carries a recovery hint- await main(["message", "emoji", "--target", "/s/general", "--emoji", "👍"]);+ await main(["message", "emoji", "--target", "/s#0042/general", "--emoji", "👍"]);const env = parseEnvelope(cap.lines());expect(typeof env.error).toBe("string");expect("success" in env).toBe(false);@@ -144,7 +144,7 @@ describe("channel alignment (message send)", () => {setApiForTesting(stubApi({ send: async () => ({ state: "blocked", reason: "unaligned", unreadCount: 3, latestSeq: 12 }) }),);- await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);const env = parseEnvelope(cap.lines());expect("success" in env).toBe(false);expect(env.error).toContain("not aligned");@@ -158,40 +158,40 @@ describe("message send --reply", () => {it("strips a leading # from --reply and forwards replyToSeq", async () => {const sendSpy = vi.fn(async () => ({state: "sent" as const,- message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "on it" }, time: "" },+ message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "on it" }, time: "" },}));setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "on it", "--reply", "#37"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "on it", "--reply", "#37"]);expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));});it("accepts a bare numeric --reply", async () => {const sendSpy = vi.fn(async () => ({state: "sent" as const,- message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "on it" }, time: "" },+ message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "on it" }, time: "" },}));setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "on it", "--reply", "37"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "on it", "--reply", "37"]);expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));});it("omits replyToSeq (undefined) when --reply is absent", async () => {const sendSpy = vi.fn(async () => ({state: "sent" as const,- message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" },+ message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "hi" }, time: "" },}));setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: undefined }));});it("rejects a non-numeric --reply with a CliError, never calling send", async () => {const sendSpy = vi.fn(async () => ({state: "sent" as const,- message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "" }, time: "" },+ message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "" }, time: "" },}));setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi", "--reply", "x"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi", "--reply", "x"]);const env = parseEnvelope(cap.lines());expect(env.error).toContain("--reply must be a message seq");expect(sendSpy).not.toHaveBeenCalled();@@ -200,10 +200,10 @@ describe("message send --reply", () => {it("rejects --reply 0 (not a real seq) with a CliError", async () => {const sendSpy = vi.fn(async () => ({state: "sent" as const,- message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "" }, time: "" },+ message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "" }, time: "" },}));setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi", "--reply", "0"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi", "--reply", "0"]);const env = parseEnvelope(cap.lines());expect(env.error).toContain("--reply must be a message seq");expect(sendSpy).not.toHaveBeenCalled();@@ -211,12 +211,35 @@ describe("message send --reply", () => {});describe("inbox pull", () => {+ it("never acks a rejected pull and only advances the returned cursor after repair", async () => {+ const ackSpy = vi.fn(async () => undefined);+ const pullSpy = vi.fn()+ .mockRejectedValueOnce(new Error("DM peer identity unavailable"))+ .mockResolvedValueOnce({+ messages: [{ seq: "#7", channel: "/.dm/Bob#0042", sender: "@Alice#1234", content: { text: "still owed" }, time: "" }],+ hasMore: false,+ });+ setApiForTesting(stubApi({ inboxPull: pullSpy, ack: ackSpy }));++ await main(["inbox", "pull"]);+ expect(parseEnvelope(cap.lines()).error).toContain("DM peer identity unavailable");+ expect(ackSpy).not.toHaveBeenCalled();++ cap.lines().length = 0;+ await main(["inbox", "pull"]);+ expect(ackSpy).toHaveBeenCalledOnce();+ expect(ackSpy).toHaveBeenCalledWith({+ agentId: expect.any(String),+ cursors: [{ channel: "/.dm/Bob#0042", seq: 7 }],+ });+ });+it("acks by default and returns messages in success", async () => {const ackSpy = vi.fn(async () => undefined);setApiForTesting(stubApi({inboxPull: async () => ({- messages: [{ seq: "#2", channel: "/s/general", sender: "@x", content: { text: "yo" }, time: "" }],+ messages: [{ seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "yo" }, time: "" }],hasMore: false,}),ack: ackSpy,@@ -237,7 +260,7 @@ describe("inbox pull", () => {setApiForTesting(stubApi({inboxPull: async () => ({- messages: [{ seq: "#2", channel: "/s/general", sender: "@x", content: { text: "yo" }, time: "" }],+ messages: [{ seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "yo" }, time: "" }],hasMore: false,}),ack: ackSpy,@@ -261,8 +284,8 @@ describe("inbox pull", () => {stubApi({inboxPull: async () => ({messages: [- { seq: "#2", channel: "/s/general", sender: "@x", content: { text: "hi" }, time: "" },- { seq: "#3", channel: "/s/general", sender: "@x", content: { text: "bye" }, time: "" },+ { seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "hi" }, time: "" },+ { seq: "#3", channel: "/s#0042/general", sender: "@x", content: { text: "bye" }, time: "" },],hasMore: false,}),@@ -283,7 +306,7 @@ describe("inbox pull", () => {setApiForTesting(stubApi({inboxPull: async () => ({- messages: [{ seq: "#2", channel: "/s/general", sender: "@x", content: { text: "yo" }, time: "" }],+ messages: [{ seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "yo" }, time: "" }],hasMore: false,}),ack: async () => undefined,@@ -301,13 +324,13 @@ describe("inbox pull", () => {describe("message send — idempotent retry (mutation-idempotency ②)", () => {const okRes = {state: "sent" as const,- message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" },+ message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "hi" }, time: "" },};it("attaches a nonce to the send request", async () => {const sendSpy = vi.fn(async () => okRes);setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);const arg = sendSpy.mock.calls[0]![0] as { nonce?: string };expect(typeof arg.nonce).toBe("string");expect((arg.nonce ?? "").length).toBeGreaterThan(0);@@ -319,13 +342,13 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {const sendSpy = vi.fn(async (req: { nonce?: string }) => {nonces.push(req.nonce);calls++;- if (calls === 1) throw new Error("upstream returned 502 with non-JSON body from /api/send");+ if (calls === 1) throw new Error("upstream returned 502 with non-JSON body during send");return okRes;});setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);const env = parseEnvelope(cap.lines());- expect(env.success.sent).toBe("/s/general#8"); // succeeded, not an error+ expect(env.success.sent).toBe("/s#0042/general#8"); // succeeded, not an errorexpect(calls).toBe(2); // retried onceexpect(nonces[0]).toBe(nonces[1]); // SAME nonce across the retry — server can dedupe});@@ -333,25 +356,25 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {it("treats a `deduped` success (same-nonce retry matched the committed message) as sent, not an error", async () => {const sendSpy = vi.fn(async () => ({ ...okRes, deduped: true }));setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);const env = parseEnvelope(cap.lines());- expect(env.success.sent).toBe("/s/general#8");+ expect(env.success.sent).toBe("/s#0042/general#8");expect(env.error).toBeUndefined();});it("does NOT retry a blocked/unaligned business outcome (it's a return, not transient)", async () => {const sendSpy = vi.fn(async () => ({ state: "blocked" as const, reason: "unaligned" as const, unreadCount: 2, latestSeq: 9 }));setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);const env = parseEnvelope(cap.lines());expect(env.error).toContain("channel not aligned");expect(sendSpy).toHaveBeenCalledTimes(1); // no retry on a business outcome});it("does NOT retry a non-transient thrown error (e.g. 4xx), surfaces it once", async () => {- const sendSpy = vi.fn(async () => { throw new Error("reply target #5 not found in /s/general"); });+ const sendSpy = vi.fn(async () => { throw new Error("reply target #5 not found in /s#0042/general"); });setApiForTesting(stubApi({ send: sendSpy }));- await main(["message", "send", "--target", "/s/general", "--text", "hi"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);const env = parseEnvelope(cap.lines());expect(env.error).toContain("reply target");expect(sendSpy).toHaveBeenCalledTimes(1); // deterministic business error — not retried@@ -414,7 +437,7 @@ describe("message post", () => {const postSpy = vi.fn(async (req: { nonce?: string }) => {nonces.push(req.nonce);calls++;- if (calls === 1) throw new Error("upstream returned 502 with non-JSON body from /api/createPost");+ if (calls === 1) throw new Error("upstream returned 502 with non-JSON body from canonical messages door");return okRes;});setApiForTesting(stubApi({ createPost: postSpy }));@@ -429,11 +452,11 @@ describe("message post", () => {describe("server list", () => {it("prints {success:{servers:[...]}} from a stubbed listServers", async () => {setApiForTesting(- stubApi({ listServers: async () => ({ servers: [{ id: "srv_1", name: "Design Studio" }] }) }),+ stubApi({ listServers: async () => ({ servers: [{ handle: "Design Studio#0042" }] }) }),);await main(["server", "list"]);const env = parseEnvelope(cap.lines());- expect(env).toEqual({ success: { servers: [{ id: "srv_1", name: "Design Studio" }] } });+ expect(env).toEqual({ success: { servers: [{ handle: "Design Studio#0042" }] } });});it("prints an empty array when the bot is in no servers", async () => {@@ -470,7 +493,7 @@ describe("server member", () => {it("rejects a non-positive-integer --limit with a clear error, listMembers never called", async () => {const listMembersSpy = vi.fn(async () => ({ members: [], hasMore: false }));setApiForTesting(stubApi({ listMembers: listMembersSpy }));- await main(["server", "member", "--server", "Design Studio", "--limit", "abc"]);+ await main(["server", "member", "--server", "Design Studio#0042", "--limit", "abc"]);const env = parseEnvelope(cap.lines());expect(env).toEqual({ error: "server member: --limit must be a positive integer" });expect(listMembersSpy).not.toHaveBeenCalled();@@ -481,12 +504,12 @@ describe("server member", () => {setApiForTesting(stubApi({ listMembers: listMembersSpy }));await main(["server", "member"]);const env = parseEnvelope(cap.lines());- expect(env).toEqual({ error: "server member: --server <name> is required" });+ expect(env).toEqual({ error: "server member: --server <name#discriminator> is required" });expect(listMembersSpy).not.toHaveBeenCalled();});- it("surfaces an ambiguous-name error verbatim as {error: <message>}", async () => {- const message = 'ambiguous server name "studio" — matches 2 servers: srv_1 ("Design Studio"), srv_2 ("Studio Ops")';+ it("surfaces an invalid-handle error verbatim as {error: <message>}", async () => {+ const message = "invalid server handle, expected name#0042";setApiForTesting(stubApi({listMembers: async () => {@@ -503,14 +526,14 @@ describe("server member", () => {describe("server join", () => {it("extracts the token from a full URL and calls joinServer with the bare token only", async () => {- const joinServerSpy = vi.fn(async () => ({ server: { id: "srv_1", name: "Design Studio" } }));+ const joinServerSpy = vi.fn(async () => ({ server: { handle: "Design Studio#0042" } }));setApiForTesting(stubApi({ joinServer: joinServerSpy }));await main(["server", "join", "--invite", "https://alook.dev/c/invite/AbC123XyZ0"]);expect(joinServerSpy).toHaveBeenCalledWith(expect.objectContaining({ invite: "AbC123XyZ0" }));});it("passes a bare token through unchanged", async () => {- const joinServerSpy = vi.fn(async () => ({ server: { id: "srv_1", name: "Design Studio" } }));+ const joinServerSpy = vi.fn(async () => ({ server: { handle: "Design Studio#0042" } }));setApiForTesting(stubApi({ joinServer: joinServerSpy }));await main(["server", "join", "--invite", "AbC123XyZ0"]);expect(joinServerSpy).toHaveBeenCalledWith(expect.objectContaining({ invite: "AbC123XyZ0" }));@@ -524,7 +547,7 @@ describe("server join", () => {});it("unparseable --invite value → descriptive error, joinServer never called", async () => {- const joinServerSpy = vi.fn(async () => ({ server: { id: "srv_1", name: "Design Studio" } }));+ const joinServerSpy = vi.fn(async () => ({ server: { handle: "Design Studio#0042" } }));setApiForTesting(stubApi({ joinServer: joinServerSpy }));await main(["server", "join", "--invite", "not an invite at all"]);const env = parseEnvelope(cap.lines());@@ -563,13 +586,13 @@ describe("server join", () => {});});- it("success prints {success:{server:{id,name}}} (no `joined` key)", async () => {+ it("success prints {success:{server:{handle}}} (no `joined` key)", async () => {setApiForTesting(- stubApi({ joinServer: async () => ({ server: { id: "srv_1", name: "Design Studio" } }) }),+ stubApi({ joinServer: async () => ({ server: { handle: "Design Studio#0042" } }) }),);await main(["server", "join", "--invite", "AbC123XyZ0"]);const env = parseEnvelope(cap.lines());- expect(env).toEqual({ success: { server: { id: "srv_1", name: "Design Studio" } } });+ expect(env).toEqual({ success: { server: { handle: "Design Studio#0042" } } });expect(env.success as object).not.toHaveProperty("joined");});});@@ -581,14 +604,14 @@ describe("channel list", () => {{category: null,channels: [- { ref: "/demo-workspace/announcements", name: "announcements", type: "text" as const, visibility: "public" as const },+ { ref: "/demo-workspace#1234/announcements", name: "announcements", type: "text" as const, visibility: "public" as const },],},{category: { name: "Ops", private: false },channels: [- { ref: "/demo-workspace/general", name: "general", type: "text" as const, visibility: "public" as const },- { ref: "/demo-workspace/help", name: "help", type: "forum" as const, visibility: "public" as const },+ { ref: "/demo-workspace#1234/general", name: "general", type: "text" as const, visibility: "public" as const },+ { ref: "/demo-workspace#1234/help", name: "help", type: "forum" as const, visibility: "public" as const },],},],@@ -602,14 +625,14 @@ describe("channel list", () => {{category: null,channels: [- { ref: "/demo-workspace/announcements", name: "announcements", type: "text", visibility: "public" },+ { ref: "/demo-workspace#1234/announcements", name: "announcements", type: "text", visibility: "public" },],},{category: { name: "Ops", private: false },channels: [- { ref: "/demo-workspace/general", name: "general", type: "text", visibility: "public" },- { ref: "/demo-workspace/help", name: "help", type: "forum", visibility: "public" },+ { ref: "/demo-workspace#1234/general", name: "general", type: "text", visibility: "public" },+ { ref: "/demo-workspace#1234/help", name: "help", type: "forum", visibility: "public" },],},],@@ -618,15 +641,15 @@ describe("channel list", () => {expect(listChannelsSpy).toHaveBeenCalledWith(expect.objectContaining({ server: "srv_8fk2" }));});- it("--server accepts a name and passes it straight through unmodified", async () => {+ it("--server accepts a handle and passes it straight through unmodified", async () => {const listChannelsSpy = vi.fn(async () => ({ groups: [] }));setApiForTesting(stubApi({ listChannels: listChannelsSpy }));- await main(["channel", "list", "--server", "Design Studio"]);- expect(listChannelsSpy).toHaveBeenCalledWith(expect.objectContaining({ server: "Design Studio" }));+ await main(["channel", "list", "--server", "Design Studio#0042"]);+ expect(listChannelsSpy).toHaveBeenCalledWith(expect.objectContaining({ server: "Design Studio#0042" }));});- it("surfaces an ambiguous-name error verbatim as {error: <message>}", async () => {- const message = 'ambiguous server name "studio" — matches 2 servers: srv_1 ("Design Studio"), srv_2 ("Studio Ops")';+ it("surfaces an invalid-handle error verbatim as {error: <message>}", async () => {+ const message = "invalid server handle, expected name#0042";setApiForTesting(stubApi({listChannels: async () => {@@ -657,7 +680,7 @@ describe("channel list", () => {setApiForTesting(stubApi({ listChannels: listChannelsSpy }));await main(["channel", "list"]);const env = parseEnvelope(cap.lines());- expect(env).toEqual({ error: "channel list: --server <id-or-name> is required" });+ expect(env).toEqual({ error: "channel list: --server <name#discriminator> is required" });expect(listChannelsSpy).not.toHaveBeenCalled();});@@ -676,7 +699,7 @@ describe("channel member", () => {hint: "This channel is public. Use `alook server member --server demo` to list who can see it.",}));setApiForTesting(stubApi({ channelMember: channelMemberSpy }));- await main(["channel", "member", "--channel", "/demo/general"]);+ await main(["channel", "member", "--channel", "/demo#0042/general"]);const env = parseEnvelope(cap.lines());expect(env).toEqual({success: {@@ -685,7 +708,7 @@ describe("channel member", () => {},});expect(channelMemberSpy).toHaveBeenCalledWith(- expect.objectContaining({ channel: "/demo/general" }),+ expect.objectContaining({ channel: "/demo#0042/general" }),);});@@ -698,7 +721,7 @@ describe("channel member", () => {],}));setApiForTesting(stubApi({ channelMember: channelMemberSpy }));- await main(["channel", "member", "--channel", "/demo/leadership"]);+ await main(["channel", "member", "--channel", "/demo#0042/leadership"]);const env = parseEnvelope(cap.lines());expect(env).toEqual({success: {@@ -714,9 +737,9 @@ describe("channel member", () => {it("thread ref passes through unchanged", async () => {const channelMemberSpy = vi.fn(async () => ({ visibility: "private" as const, members: [] }));setApiForTesting(stubApi({ channelMember: channelMemberSpy }));- await main(["channel", "member", "--channel", "/demo/general/#12"]);+ await main(["channel", "member", "--channel", "/demo#0042/general/#12"]);expect(channelMemberSpy).toHaveBeenCalledWith(- expect.objectContaining({ channel: "/demo/general/#12" }),+ expect.objectContaining({ channel: "/demo#0042/general/#12" }),);});@@ -757,11 +780,11 @@ describe("channel history", () => {const readSpy = vi.fn(async () => ({ items: [], hasMore: false }));setApiForTesting(stubApi({ read: readSpy }));await main([- "channel", "history", "--channel", "/demo-workspace/general",+ "channel", "history", "--channel", "/demo-workspace#1234/general","--before", "42", "--after", "1", "--around", "20", "--limit", "5",]);expect(readSpy).toHaveBeenCalledWith(- expect.objectContaining({ channel: "/demo-workspace/general", before: 42, after: 1, around: 20, limit: 5 }),+ expect.objectContaining({ channel: "/demo-workspace#1234/general", before: 42, after: 1, around: 20, limit: 5 }),);});@@ -769,12 +792,12 @@ describe("channel history", () => {setApiForTesting(stubApi({read: async () => ({- items: [{ seq: "#37", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" }],+ items: [{ seq: "#37", channel: "/s#0042/general", sender: "@a", content: { text: "hi" }, time: "" }],hasMore: true,}),}),);- await main(["channel", "history", "--channel", "/s/general"]);+ await main(["channel", "history", "--channel", "/s#0042/general"]);const env = parseEnvelope(cap.lines()) as { success: { items: unknown[]; hasMore: boolean } };expect(env.success.hasMore).toBe(true);expect(env.success.items).toHaveLength(1);@@ -783,7 +806,7 @@ describe("channel history", () => {it("includes latestSeq when the API returns one", async () => {setApiForTesting(stubApi({ read: async () => ({ items: [], hasMore: false, latestSeq: 41 }) }));- await main(["channel", "history", "--channel", "/s/general"]);+ await main(["channel", "history", "--channel", "/s#0042/general"]);const env = parseEnvelope(cap.lines()) as { success: { latestSeq: number } };expect(env.success.latestSeq).toBe(41);});@@ -791,8 +814,8 @@ describe("channel history", () => {it("works for a thread ref — passes it through to api.read() unmodified", async () => {const readSpy = vi.fn(async () => ({ items: [], hasMore: false }));setApiForTesting(stubApi({ read: readSpy }));- await main(["channel", "history", "--channel", "/demo-workspace/general/#12"]);- expect(readSpy).toHaveBeenCalledWith(expect.objectContaining({ channel: "/demo-workspace/general/#12" }));+ await main(["channel", "history", "--channel", "/demo-workspace#1234/general/#12"]);+ expect(readSpy).toHaveBeenCalledWith(expect.objectContaining({ channel: "/demo-workspace#1234/general/#12" }));});it("works for a DM ref — passes it through to api.read() unmodified", async () => {@@ -820,10 +843,10 @@ describe("message emoji", () => {it("channel ref — calls reactAdd with (channel, seq, emoji) and prints success envelope", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", "👍"]);- expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo/general", seq: 42, emoji: "👍" });+ await main(["message", "emoji", "--target", "/demo#0042/general#42", "--emoji", "👍"]);+ expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo#0042/general", seq: 42, emoji: "👍" });const env = parseEnvelope(cap.lines());- expect(env).toEqual({ success: { target: "/demo/general#42", emoji: "👍", duplicate: false } });+ expect(env).toEqual({ success: { target: "/demo#0042/general#42", emoji: "👍", duplicate: false } });});it("DM ref — calls reactAdd with the DM channel + seq split out", async () => {@@ -833,20 +856,12 @@ describe("message emoji", () => {expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/.dm/peer#0001", seq: 7, emoji: "🙏" });});- it("forum-post ref — reacts to a message INSIDE the post (childChannelName kept, not the parent forum)", async () => {- const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));- setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/ideas/my-post#4", "--emoji", "👍"]);- // channel is the POST scope (/demo/ideas/my-post), NOT the parent forum /demo/ideas.- expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo/ideas/my-post", seq: 4, emoji: "👍" });- });-- it("forum-post ref without a message seq → error, reactAdd never called", async () => {+ it("the old forum-post ref shape no longer parses (no-compat, phase2 forum≡thread) — errors before reactAdd", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/ideas/my-post", "--emoji", "👍"]);+ await main(["message", "emoji", "--target", "/demo#0042/ideas/my-post#4", "--emoji", "👍"]);const env = parseEnvelope(cap.lines());- expect(env.error).toMatch(/needs a ref with a seq/);+ expect(env.error).toBeDefined();expect(reactAddSpy).not.toHaveBeenCalled();});@@ -860,7 +875,7 @@ describe("message emoji", () => {},}),);- await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", "👍"]);+ await main(["message", "emoji", "--target", "/demo#0042/general#42", "--emoji", "👍"]);const env = parseEnvelope(cap.lines());expect(env).toEqual({ error: "not a member of #general", hint: "join the channel first" });});@@ -868,7 +883,7 @@ describe("message emoji", () => {it("thread scope ref without message seq → error, reactAdd never called", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/general/#5", "--emoji", "👍"]);+ await main(["message", "emoji", "--target", "/demo#0042/general/#5", "--emoji", "👍"]);const env = parseEnvelope(cap.lines());expect(env.error).toMatch(/needs a ref with a seq/);expect(env.hint).toMatch(/#N#M/);@@ -878,7 +893,7 @@ describe("message emoji", () => {it("bare channel ref (no #N) → error envelope with seq hint, reactAdd never called", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/general", "--emoji", "👍"]);+ await main(["message", "emoji", "--target", "/demo#0042/general", "--emoji", "👍"]);const env = parseEnvelope(cap.lines());expect(env.error).toMatch(/needs a ref with a seq/);expect(env.hint).toMatch(/#N/);@@ -897,7 +912,7 @@ describe("message emoji", () => {it("missing --emoji → commander error, reactAdd never called", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/general#42"]);+ await main(["message", "emoji", "--target", "/demo#0042/general#42"]);const env = parseEnvelope(cap.lines());expect("error" in env).toBe(true);expect(reactAddSpy).not.toHaveBeenCalled();@@ -907,7 +922,7 @@ describe("message emoji", () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));const big = "🎉".repeat(20);- await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", big]);+ await main(["message", "emoji", "--target", "/demo#0042/general#42", "--emoji", big]);const env = parseEnvelope(cap.lines());expect(env.error).toMatch(/too long/);expect(env.hint).toMatch(/single emoji/);@@ -916,7 +931,7 @@ describe("message emoji", () => {it("duplicate — envelope surfaces duplicate:true, exit code still 0", async () => {setApiForTesting(stubApi({ reactAdd: async () => ({ ok: true as const, duplicate: true }) }));- const code = await main(["message", "emoji", "--target", "/demo/general#42", "--emoji", "👍"]);+ const code = await main(["message", "emoji", "--target", "/demo#0042/general#42", "--emoji", "👍"]);expect(code).toBe(0);const env = parseEnvelope(cap.lines()) as { success: { duplicate: boolean } };expect(env.success.duplicate).toBe(true);@@ -925,24 +940,24 @@ describe("message emoji", () => {it("thread-reply ref — calls reactAdd with thread-scope channel + seq split out", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/general/#5#42", "--emoji", "👍"]);- expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo/general/#5", seq: 42, emoji: "👍" });+ await main(["message", "emoji", "--target", "/demo#0042/general/#5#42", "--emoji", "👍"]);+ expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo#0042/general/#5", seq: 42, emoji: "👍" });const env = parseEnvelope(cap.lines());- expect(env).toEqual({ success: { target: "/demo/general/#5#42", emoji: "👍", duplicate: false } });+ expect(env).toEqual({ success: { target: "/demo#0042/general/#5#42", emoji: "👍", duplicate: false } });});it("thread ROOT via parent channel ref (regression) unchanged", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));- await main(["message", "emoji", "--target", "/demo/general#5", "--emoji", "👀"]);- expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo/general", seq: 5, emoji: "👀" });+ await main(["message", "emoji", "--target", "/demo#0042/general#5", "--emoji", "👀"]);+ expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo#0042/general", seq: 5, emoji: "👀" });});it("thread-reply oversize emoji still hits the local check before the wire", async () => {const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));setApiForTesting(stubApi({ reactAdd: reactAddSpy }));const big = "🎉".repeat(20);- await main(["message", "emoji", "--target", "/demo/general/#5#42", "--emoji", big]);+ await main(["message", "emoji", "--target", "/demo#0042/general/#5#42", "--emoji", big]);const env = parseEnvelope(cap.lines());expect(env.error).toMatch(/too long/);expect(reactAddSpy).not.toHaveBeenCalled();@@ -950,7 +965,7 @@ describe("message emoji", () => {it("thread-reply duplicate — envelope surfaces duplicate:true", async () => {setApiForTesting(stubApi({ reactAdd: async () => ({ ok: true as const, duplicate: true }) }));- await main(["message", "emoji", "--target", "/demo/general/#5#42", "--emoji", "👍"]);+ await main(["message", "emoji", "--target", "/demo#0042/general/#5#42", "--emoji", "👍"]);const env = parseEnvelope(cap.lines()) as { success: { duplicate: boolean } };expect(env.success.duplicate).toBe(true);});@@ -984,7 +999,7 @@ describe("message attachment upload", () => {"attachment","upload","--target",- "/demo/general",+ "/demo#0042/general","--file",file,]);@@ -995,7 +1010,7 @@ describe("message attachment upload", () => {expect(uploadSpy).toHaveBeenCalledTimes(1);expect(uploadSpy).toHaveBeenCalledWith({agentId: "agent_test",- target: "/demo/general",+ target: "/demo#0042/general",file: {data: new Uint8Array(Buffer.from(body)),filename: `prototype.${extension}`,@@ -1185,7 +1200,7 @@ describe("message send — --text escape decoding wired end-to-end", () => {}),);// Two literal chars backslash-n twice, as a shell would pass them.- await main(["message", "send", "--target", "/s/general", "--text", "a\\n\\nb"]);+ await main(["message", "send", "--target", "/s#0042/general", "--text", "a\\n\\nb"]);expect(sentText).toBe("a\n\nb");expect(sentText!.split("\n")).toHaveLength(3);});@@ -1207,7 +1222,7 @@ describe("message send — --text escape decoding wired end-to-end", () => {},}),);- await main(["message", "send", "--target", "/s/general", "--file", file]);+ await main(["message", "send", "--target", "/s#0042/general", "--file", file]);fs.rmSync(dir, { recursive: true, force: true });expect(sentText).toBe("a\\nb");expect(sentText).not.toContain("\n");diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 4c11d3c07..316b6058f 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -226,7 +226,7 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const agent = agentId(opts);const channel = opts.target as string;- if (!channel) throw new CliError("message send: --target <ref> is required (e.g. /demo-workspace/general)");+ if (!channel) throw new CliError("message send: --target <ref> is required (e.g. /demo-workspace#1234/general)");let text: string | undefined;const fileFlag = opts.file as string | undefined;@@ -328,7 +328,7 @@ async function cmdMessagePost(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const agent = agentId(opts);const forum = opts.target as string;- if (!forum) throw new CliError("message post: --target <forum-ref> is required (e.g. /demo/ideas)");+ if (!forum) throw new CliError("message post: --target <forum-ref> is required (e.g. /demo#1234/ideas)");const title = opts.title as string | undefined;if (!title || title.trim().length === 0) throw new CliError("message post: --title <name> is required");@@ -365,8 +365,7 @@ async function cmdMessagePost(opts: Record<string, unknown>): Promise<unknown> {attachments: attachmentIds.length > 0 ? attachmentIds : undefined,nonce,});- // Surface the canonical /server/forum/<real-slug> ref — the bot's handle for- // the just-created post, usable directly as a `--target`.+ // Surface the canonical /server/forum/#N thread ref, usable as `--target`.return { posted: res.ref };}@@ -374,7 +373,7 @@ async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown>const api = getApi();const target = opts.target as string;const emoji = opts.emoji as string;- if (!target) throw new CliError("message emoji: --target <ref> is required (e.g. /demo/general#42)");+ if (!target) throw new CliError("message emoji: --target <ref> is required (e.g. /demo#1234/general#42)");if (!emoji) throw new CliError("message emoji: --emoji <string> is required");let parsed: ReturnType<typeof parseRef>;@@ -397,14 +396,10 @@ async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown>}// Rebuild the SCOPE ref (no pin-seq — that's passed separately as `seq`).- // A forum-post target (`/server/forum/post#N`) must keep its childChannelName- // so the reaction lands on the post, not its parent forum.const channel =- parsed.childChannelName !== undefined- ? `/${parsed.server}/${parsed.channel}/${parsed.childChannelName}`- : parsed.threadRootSeq !== undefined- ? `/${parsed.server}/${parsed.channel}/#${parsed.threadRootSeq}`- : `/${parsed.server}/${parsed.channel}`;+ parsed.threadRootSeq !== undefined+ ? `/${parsed.server}/${parsed.channel}/#${parsed.threadRootSeq}`+ : `/${parsed.server}/${parsed.channel}`;const res = await api.reactAdd({ channel, seq: parsed.seq, emoji });return { target, emoji, duplicate: res.duplicate === true };}@@ -524,7 +519,7 @@ async function cmdServerMember(opts: Record<string, unknown>): Promise<unknown>const api = getApi();const agent = agentId(opts);const server = opts.server as string;- if (!server) throw new CliError("server member: --server <name> is required");+ if (!server) throw new CliError("server member: --server <name#discriminator> is required");let limit: number | undefined;if (opts.limit !== undefined) {limit = Number(opts.limit);@@ -557,7 +552,7 @@ async function cmdChannelList(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const agent = agentId(opts);const server = opts.server as string;- if (!server) throw new CliError("channel list: --server <id-or-name> is required");+ if (!server) throw new CliError("channel list: --server <name#discriminator> is required");return await api.listChannels({ agentId: agent, server });}@@ -641,7 +636,7 @@ function buildProgram(): Command {message.command("send").description("send a message to a channel, DM, or thread")- .option("--target <ref>", "destination (path-style ref, e.g. /demo-workspace/general)")+ .option("--target <ref>", "destination (path-style ref, e.g. /demo-workspace#1234/general)").option("--text <text>", "inline message body (short messages)").option("--file <path>", "read message body from a file (long messages)").option(@@ -663,7 +658,7 @@ function buildProgram(): Command {message.command("post").description("create a new forum post in a forum")- .option("--target <forum-ref>", "the forum to post in (path-style ref, e.g. /demo/ideas)")+ .option("--target <forum-ref>", "the forum to post in (path-style ref, e.g. /demo#1234/ideas)").option("--title <name>", "the post title (its slug becomes the post's address)").option("--text <text>", "inline post body (short)").option("--file <path>", "read post body from a file (long)")@@ -685,7 +680,7 @@ function buildProgram(): Command {message.command("emoji").description("react to a message with a single emoji")- .requiredOption("--target <ref>", "message ref (path-style, e.g. /demo/general#42 or /.dm/peer#7)")+ .requiredOption("--target <ref>", "message ref (path-style, e.g. /demo#1234/general#42 or /.dm/peer#0007#42)").requiredOption("--emoji <string>", "single emoji character").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })@@ -762,7 +757,7 @@ function buildProgram(): Command {server.command("member").description("list members of a server (paginated; each member carries online + status)")- .option("--server <id-or-name>", "server id or name (from `server list`)")+ .option("--server <handle>", "server name#discriminator handle (from `server list`)").option("--limit <n>", "max members per page").option("--cursor <cursor>", "opaque cursor from a prior page's response (omit for the first page)").exitOverride()@@ -793,7 +788,7 @@ function buildProgram(): Command {channel.command("list").description("list top-level channels visible to this agent in one server")- .option("--server <id-or-name>", "server id or name (from `server list`)")+ .option("--server <handle>", "server name#discriminator handle (from `server list`)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function (this: Command) {diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.tsindex d2b6d4b4b..1e297b33a 100644--- a/src/daemon/src/cli/proxyServerApi.test.ts+++ b/src/daemon/src/cli/proxyServerApi.test.ts@@ -47,7 +47,7 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });await expect(api.listServers({ agentId: "a1" as never })).rejects.toThrow(- /upstream returned 500 with non-JSON body from \/api\/listServers/,+ /upstream returned 500 with non-JSON body during listServers/,);});@@ -69,7 +69,7 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {const fetchImpl: FetchLike = vi.fn(async () => jsonBody("<html>bad gateway", { status: 502 }));const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });await expect(api.listServers({ agentId: "a1" as never })).rejects.toThrow(- /upstream returned 502 with non-JSON body from \/api\/listServers/,+ /upstream returned 502 with non-JSON body during listServers/,);});@@ -77,7 +77,7 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {const fetchImpl: FetchLike = vi.fn(async () => textThrowingResponse(500, "terminated"));const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });await expect(api.listServers({ agentId: "a1" as never })).rejects.toThrow(- /upstream body read failed from \/api\/listServers \(500\): terminated/,+ /upstream body read failed during listServers \(500\): terminated/,);});@@ -96,7 +96,7 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {}});- it("GETs /api/community/servers and projects the SUPERSET row down to lean {id,name} (Fork C)", async () => {+ it("GETs /api/community/servers and projects the superset row down to a lean handle", async () => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {seen.push({ url, init });@@ -105,8 +105,8 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {return jsonBody(JSON.stringify({servers: [- { id: "srv_1", name: "Studio", icon: "https://cdn/x.png", ownerId: "u_owner", description: "secret" },- { id: "srv_2", name: "Lab", icon: null, ownerId: "u_owner" },+ { id: "srv_1", name: "Studio", discriminator: "0042", icon: "https://cdn/x.png", ownerId: "u_owner", description: "secret" },+ { id: "srv_2", name: "Lab", discriminator: "12345", icon: null, ownerId: "u_owner" },],}),{ status: 200 },@@ -114,54 +114,367 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {});const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });const out = await api.listServers({ agentId: "a1" as never });- // Single projection point: only {id,name} survives — no icon/ownerId/description.- expect(out).toEqual({ servers: [{ id: "srv_1", name: "Studio" }, { id: "srv_2", name: "Lab" }] });+ // Single projection point: only the handle survives — no id/name fields or metadata.+ expect(out).toEqual({ servers: [{ handle: "Studio#0042" }, { handle: "Lab#12345" }] });// Folded verb hits the real REST path (GET), not a flat POST /api/listServers.expect(seen.at(-1)!.url).toBe("http://proxy.test/api/community/servers");expect(seen.at(-1)!.init?.method).toBe("GET");});});-describe("createProxyServerApi — reactAdd", () => {- it("POSTs to /api/reactAdd with Bearer voucher and JSON body (no agentId)", async () => {+describe("createProxyServerApi — joinServer projection", () => {+ it("projects the unified join route superset to one valid handle without identity leakage", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody(JSON.stringify({+ member: { id: "mem_1", userId: "bot_1" },+ serverId: "srv_1",+ server: { id: "srv_1", name: "Design Studio", discriminator: "0042" },+ })));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const out = await api.joinServer({ agentId: "a1" as never, invite: "tok_abc" });++ expect(out).toEqual({ server: { handle: "Design Studio#0042" } });+ expect(Object.keys(out.server)).toEqual(["handle"]);+ expect(fetchImpl).toHaveBeenCalledWith(+ "http://proxy.test/api/community/invites/tok_abc/join",+ expect.objectContaining({ method: "POST" }),+ );+ });+});++describe("createProxyServerApi — reactAdd (retargeted to the canonical reaction door)", () => {+ it("PUTs the canonical reaction door with emoji-in-path + {channel,seq} body (no agentId)", async () => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {seen.push({ url, init });- return jsonBody(JSON.stringify({ ok: true, duplicate: false }), { status: 200 });+ // Canonical route returns the reaction ROW on a fresh add.+ return jsonBody(JSON.stringify({ messageId: "m1", userId: "bot_1", emoji: "👍" }), { status: 200 });});const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });- const res = await api.reactAdd({ channel: "/demo/general", seq: 42, emoji: "👍" });- expect(res).toEqual({ ok: true, duplicate: false });+ const res = await api.reactAdd({ channel: "/demo#1234/general", seq: 42, emoji: "👍" });+ // Lean contract projection at the proxy boundary: a fresh add → { ok: true }.+ expect(res).toEqual({ ok: true });expect(seen).toHaveLength(1);- expect(seen[0].url).toBe("http://proxy.test/api/reactAdd");- expect(seen[0].init?.method).toBe("POST");+ // messageId is the `resolve` placeholder (bot holds ref+seq, not an id);+ // emoji is the URL-encoded path segment.+ expect(seen[0].url).toBe(+ `http://proxy.test/api/community/messages/resolve/reactions/${encodeURIComponent("👍")}`,+ );+ expect(seen[0].init?.method).toBe("PUT");const headers = seen[0].init?.headers as Record<string, string>;expect(headers.authorization).toBe("Bearer vch_test");const body = JSON.parse(String(seen[0].init?.body ?? "{}"));- expect(body).toEqual({ channel: "/demo/general", seq: 42, emoji: "👍" });+ // Only channel+seq travel in the body; emoji is the path segment.+ expect(body).toEqual({ channel: "/demo#1234/general", seq: 42 });expect(body.agentId).toBeUndefined();});++ it("maps a duplicate reaction (route → { duplicate: true }) through to the lean contract", async () => {+ const fetchImpl: FetchLike = vi.fn(async () =>+ jsonBody(JSON.stringify({ ok: true, duplicate: true }), { status: 200 }),+ );+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const res = await api.reactAdd({ channel: "/demo#1234/general", seq: 42, emoji: "👍" });+ expect(res).toEqual({ ok: true, duplicate: true });+ });});-describe("createProxyServerApi — send forwards replyToSeq", () => {- it("POSTs replyToSeq in the body (agentId stripped, replyToSeq retained)", async () => {+describe("createProxyServerApi — send (retargeted to the canonical messages door)", () => {+ it("POSTs the canonical door with ref-in-body; replyToSeq retained, agentId stripped", async () => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {seen.push({ url, init });return jsonBody(- JSON.stringify({ state: "sent", message: { seq: "#8", channel: "/demo/general", sender: "@a", content: { text: "on it" }, time: "" } }),+ JSON.stringify({ state: "sent", message: { seq: "#8", channel: "/demo#1234/general", sender: "@a", content: { text: "on it" }, time: "" } }),{ status: 200 },);});const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });- await api.send({ agentId: "a1", channel: "/demo/general", content: { text: "on it" }, replyToSeq: 37 });- expect(seen[0].url).toBe("http://proxy.test/api/send");+ await api.send({ agentId: "a1", channel: "/demo#1234/general", content: { text: "on it" }, replyToSeq: 37 });+ // Canonical messages door; the `resolve` placeholder id (bot holds a ref).+ expect(seen[0].url).toBe("http://proxy.test/api/community/channels/resolve/messages");+ expect(seen[0].init?.method).toBe("POST");const body = JSON.parse(String(seen[0].init?.body ?? "{}"));+ // The channel REF stays in the body (resolved server-side); replyToSeq kept.+ expect(body.channel).toBe("/demo#1234/general");expect(body.replyToSeq).toBe(37);expect(body.agentId).toBeUndefined();});});+describe("createProxyServerApi — createPost (folded into the canonical messages door)", () => {+ it("maps the legacy CLI contract onto forum send and adapts the thread reply response", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return seen.length === 1+ ? jsonBody(JSON.stringify({+ state: "sent",+ message: { seq: "#12", channel: "/demo#1234/forum", content: { text: "Title" } },+ threadId: "thread_1",+ }))+ : jsonBody(JSON.stringify({+ state: "sent",+ message: { seq: "#1", channel: "/demo#1234/forum/#12", content: { text: "Body" } },+ }));+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const out = await api.createPost({+ agentId: "a1",+ forum: "/demo#1234/forum",+ title: "Title",+ content: { text: "Body" },+ attachments: ["att_1"],+ nonce: "nonce_1",+ });++ expect(seen[0].url).toBe("http://proxy.test/api/community/channels/resolve/messages");+ expect(seen[0].init?.method).toBe("POST");+ expect(JSON.parse(String(seen[0].init?.body))).toEqual({+ channel: "/demo#1234/forum",+ content: { text: "Title" },+ attachments: ["att_1"],+ nonce: "nonce_1:opener",+ });+ expect(JSON.parse(String(seen[1].init?.body))).toEqual({+ channel: "/demo#1234/forum/#12",+ content: { text: "Body" },+ attachments: ["att_1"],+ nonce: "nonce_1:reply",+ });+ expect(out).toEqual({ ref: "/demo#1234/forum/#12", name: "Title", seq: 1 });+ });+});++describe("createProxyServerApi — channelMember (retargeted to the canonical members door)", () => {+ it("GETs channels/{id}/members with ?ref= (encoded); returns the ChannelMemberResult", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ visibility: "private", members: [{ handle: "a#0001", role: "member" }] }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const res = await api.channelMember({ channel: "/demo#1234/general" });+ expect(res).toEqual({ visibility: "private", members: [{ handle: "a#0001", role: "member" }] });+ const u = new URL(seen[0].url);+ expect(u.pathname).toBe("/api/community/channels/resolve/members");+ expect(u.searchParams.get("ref")).toBe("/demo#1234/general");+ expect(seen[0].init?.method).toBe("GET");+ });+});++describe("createProxyServerApi — listMembers (retargeted to servers/{id}/members)", () => {+ it("GETs servers/{id}/members with ?server= (encoded); returns { members }", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ members: [{ handle: "a#0001", role: "owner" }] }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const res = await api.listMembers({ agentId: "a1", server: "Design Studio" });+ expect(res).toEqual({ members: [{ handle: "a#0001", role: "owner" }] });+ const u = new URL(seen[0].url);+ // servers collection door with the `resolve` placeholder id (bot holds a ref).+ expect(u.pathname).toBe("/api/community/servers/resolve/members");+ expect(u.searchParams.get("server")).toBe("Design Studio");+ expect(seen[0].init?.method).toBe("GET");+ });+});++describe("createProxyServerApi — listChannels (retargeted to servers/{id}/channels + servers/channels)", () => {+ it("single server: GETs servers/{id}/channels with ?server=", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ groups: [] }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await api.listChannels({ agentId: "a1", server: "studio" });+ const u = new URL(seen[0].url);+ expect(u.pathname).toBe("/api/community/servers/resolve/channels");+ expect(u.searchParams.get("server")).toBe("studio");+ expect(seen[0].init?.method).toBe("GET");+ });++ it("all servers (server omitted): GETs the servers/channels collection, no query", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ groups: [] }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await api.listChannels({ agentId: "a1" });+ const u = new URL(seen[0].url);+ expect(u.pathname).toBe("/api/community/servers/channels");+ expect(u.searchParams.get("server")).toBe(null);+ expect(seen[0].init?.method).toBe("GET");+ });+});++describe("createProxyServerApi — inbox trinity pull/snapshot/ack (retargeted to users/me/inbox)", () => {+ it("ack POSTs users/me/inbox/ack with cursors, agentId stripped (advance verb)", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ ok: true, applied: [], failed: [] }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await api.ack({ agentId: "a1", cursors: [{ channel: "/s/c", seq: 5 }] } as never);+ expect(seen[0].url).toBe("http://proxy.test/api/community/users/me/inbox/ack");+ expect(seen[0].init?.method).toBe("POST");+ const body = JSON.parse(String(seen[0].init?.body ?? "{}"));+ expect(body.cursors).toEqual([{ channel: "/s/c", seq: 5 }]);+ expect(body.agentId).toBeUndefined();+ });+++ it("inboxPull POSTs users/me/inbox/pull with {max} in body, agentId stripped", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ messages: [], hasMore: false }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await api.inboxPull({ agentId: "a1" as never, max: 10 });+ expect(seen[0].url).toBe("http://proxy.test/api/community/users/me/inbox/pull");+ expect(seen[0].init?.method).toBe("POST");+ const body = JSON.parse(String(seen[0].init?.body ?? "{}"));+ expect(body.max).toBe(10);+ expect(body.agentId).toBeUndefined();+ });++ it("inboxSnapshot GETs users/me/inbox/snapshot (pure peek, no body)", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ rows: [], pendingChannels: 0, pendingMessages: 0 }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await api.inboxSnapshot({ agentId: "a1" as never });+ expect(seen[0].url).toBe("http://proxy.test/api/community/users/me/inbox/snapshot");+ expect(seen[0].init?.method).toBe("GET");+ expect(seen[0].init?.body).toBeUndefined();+ });+});++describe("createProxyServerApi — nap (retargeted to bots/me/nap)", () => {+ it("nap POSTs bots/me/nap with {handoff}, agentId stripped (bot-self lifecycle)", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ napped: true }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const out = await api.nap({ agentId: "a1", handoff: "see you" } as never);+ expect(seen[0].url).toBe("http://proxy.test/api/community/bots/me/nap");+ expect(seen[0].init?.method).toBe("POST");+ const body = JSON.parse(String(seen[0].init?.body ?? "{}"));+ expect(body.handoff).toBe("see you");+ expect(body.agentId).toBeUndefined();+ expect(out).toEqual({ napped: true });+ });+});++describe("createProxyServerApi — resolve (retargeted to the canonical hydrate door)", () => {+ it("GETs messages/{id} with ref+seq on the query; returns the {message} shape", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(+ JSON.stringify({ message: { seq: "#42", channel: "/demo#1234/general", sender: "@a", content: { text: "hi" }, time: "" } }),+ { status: 200 },+ );+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const res = await api.resolve({ agentId: "a1", channel: "/demo#1234/general", seq: 42 });+ expect(res.message.seq).toBe("#42");+ const u = new URL(seen[0].url);+ // resolve is its OWN door (GET messages/{id} hydrate) — NOT the seq→id lookup.+ expect(u.pathname).toBe("/api/community/messages/resolve");+ expect(u.searchParams.get("ref")).toBe("/demo#1234/general");+ expect(u.searchParams.get("seq")).toBe("42");+ expect(seen[0].init?.method).toBe("GET");+ });+});++describe("createProxyServerApi — read (retargeted to the canonical messages door GET)", () => {+ it("GETs the canonical door with ?ref= (encoded) + seq anchors on the query", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ items: [], hasMore: false }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ await api.read({ agentId: "a1", channel: "/demo#1234/general", before: 50, limit: 20 });+ const u = new URL(seen[0].url);+ expect(u.pathname).toBe("/api/community/channels/resolve/messages");+ // ref is URL-encoded on the query (carries `/`).+ expect(u.searchParams.get("ref")).toBe("/demo#1234/general");+ expect(u.searchParams.get("before")).toBe("50");+ expect(u.searchParams.get("limit")).toBe("20");+ expect(seen[0].init?.method).toBe("GET");+ });+});++describe("caller-side ref-encode `/#` round-trip (carry — Ingaborg #267)", () => {+ // A thread ref (`/server/channel/#42`) and a DM-message ref carry `/` AND `#`;+ // the `#` MUST be percent-encoded on the query or the server sees it as a URL+ // fragment and drops it (silently reading the wrong channel). Assert every+ // ref-in-query builder (read / resolve / channelMember) round-trips a `/#` ref+ // intact: the raw URL contains `%23` (not a bare `#`), and decoding the `ref`+ // param yields the original string byte-for-byte.+ const THREAD_REF = "/demo#1234/general/#42"++ function capture() {+ const seen: Array<{ url: string }> = []+ const fetchImpl: FetchLike = vi.fn(async (url: string) => {+ seen.push({ url })+ return jsonBody(JSON.stringify({ items: [], hasMore: false, message: {}, visibility: "public", hint: "x" }), { status: 200 })+ })+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch })+ return { seen, api }+ }++ function assertRoundTrip(rawUrl: string) {+ // `#` is encoded, not a bare fragment delimiter.+ expect(rawUrl).toContain("%23")+ expect(rawUrl).not.toContain("/#42")+ // decoding the ref param recovers the exact ref.+ const u = new URL(rawUrl)+ expect(u.searchParams.get("ref")).toBe(THREAD_REF)+ }++ it("read round-trips a `/#` thread ref", async () => {+ const { seen, api } = capture()+ await api.read({ agentId: "a1", channel: THREAD_REF })+ assertRoundTrip(seen[0].url)+ })++ it("resolve round-trips a `/#` thread ref", async () => {+ const { seen, api } = capture()+ await api.resolve({ agentId: "a1", channel: THREAD_REF, seq: 42 })+ assertRoundTrip(seen[0].url)+ })++ it("channelMember round-trips a `/#` thread ref", async () => {+ const { seen, api } = capture()+ await api.channelMember({ channel: THREAD_REF })+ assertRoundTrip(seen[0].url)+ })++ it("send carries the `/#` ref in the JSON body (POST — no query encoding needed)", async () => {+ const seen: Array<{ init?: RequestInit }> = []+ const fetchImpl: FetchLike = vi.fn(async (_url: string, init?: RequestInit) => {+ seen.push({ init })+ return jsonBody(JSON.stringify({ state: "sent", message: {} }), { status: 200 })+ })+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch })+ await api.send({ agentId: "a1", channel: THREAD_REF, content: { text: "hi" } })+ const body = JSON.parse(String(seen[0].init?.body ?? "{}"))+ // In a JSON body the ref is a plain string value — no URL encoding, intact.+ expect(body.channel).toBe(THREAD_REF)+ })+})+describe("createProxyServerApi — callUpload via parseJsonResponse", () => {it("throws 'non-JSON body' on empty 500", async () => {const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));@@ -172,7 +485,26 @@ describe("createProxyServerApi — callUpload via parseJsonResponse", () => {target: "/c/s/g",file: { data: new Uint8Array([1, 2, 3]), filename: "x.png", contentType: "image/png" },} as never),- ).rejects.toThrow(/upstream returned 500 with non-JSON body from \/api\/attachmentUpload/);+ ).rejects.toThrow(/upstream returned 500 with non-JSON body during attachmentUpload/);+ });++ it("POSTs the canonical attachments door with the ref on ?target= (retargeted, `resolve` placeholder id)", async () => {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return jsonBody(JSON.stringify({ id: "att_1", filename: "x.png", contentType: "image/png", size: 3 }), { status: 200 });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ const out = await api.attachmentUpload({+ agentId: "a1",+ target: "/demo#1234/general",+ file: { data: new Uint8Array([1, 2, 3]), filename: "x.png", contentType: "image/png" },+ } as never);+ expect(out).toEqual({ id: "att_1", filename: "x.png", contentType: "image/png", size: 3 });+ const u = new URL(seen[0].url);+ expect(u.pathname).toBe("/api/community/channels/resolve/attachments");+ expect(u.searchParams.get("target")).toBe("/demo#1234/general");+ expect(seen[0].init?.method).toBe("POST");});});@@ -190,19 +522,21 @@ describe("createProxyServerApi — callDownload", () => {const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });await expect(api.attachmentDownload({ agentId: "a1", id: "att_1", destPath: path.join(tmp, "out.bin") } as never),- ).rejects.toThrow(/upstream returned 500 with non-JSON body from \/api\/attachmentDownload/);+ ).rejects.toThrow(/upstream returned 500 with non-JSON body during attachmentDownload/);});it("happy path writes the binary body to destPath", async () => {const bytes = new Uint8Array([1, 2, 3, 4]);- const fetchImpl: FetchLike = vi.fn(async () =>- bufferResponse(bytes, {+ const seen: Array<{ url: string; init?: RequestInit }> = [];+ const fetchWithCapture: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, init });+ return bufferResponse(bytes, {"content-type": "image/png","content-length": String(bytes.length),"x-alook-filename": encodeURIComponent("hi.png"),- }),- );- const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });+ });+ });+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchWithCapture as typeof fetch });const dest = path.join(tmp, "out.png");const out = await api.attachmentDownload({ agentId: "a1", id: "att_1", destPath: dest } as never);expect(out.path).toBe(dest);@@ -210,11 +544,16 @@ describe("createProxyServerApi — callDownload", () => {expect(out.contentType).toBe("image/png");expect(out.size).toBe(bytes.length);expect(fs.readFileSync(dest)).toEqual(Buffer.from(bytes));+ // Retargeted: GET the canonical attachments door with the id in the PATH+ // (`resolve` placeholder channel segment), not the old POST-body flat verb.+ const u = new URL(seen[0].url);+ expect(u.pathname).toBe("/api/community/channels/resolve/attachments/att_1");+ expect(seen[0].init?.method).toBe("GET");});});describe("createProxyServerApi — friendRequest / listFriends", () => {- it("friendRequest POSTs to /api/friendRequest, strips agentId, decodes the envelope", async () => {+ it("friendRequest POSTs to /api/community/friends/request (retargeted), strips agentId, decodes the envelope", async () => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {seen.push({ url, init });@@ -226,7 +565,7 @@ describe("createProxyServerApi — friendRequest / listFriends", () => {const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });const res = await api.friendRequest({ agentId: "a1" as never, username: "Alice#0042" });expect(res).toEqual({ friendshipId: "fr_1", status: "pending", hint: "ask your owner" });- expect(seen[0].url).toBe("http://proxy.test/api/friendRequest");+ expect(seen[0].url).toBe("http://proxy.test/api/community/friends/request");expect(seen[0].init?.method).toBe("POST");const body = JSON.parse(String(seen[0].init?.body ?? "{}"));expect(body).toEqual({ username: "Alice#0042" });@@ -248,29 +587,50 @@ describe("createProxyServerApi — friendRequest / listFriends", () => {}});- it("listFriends POSTs to /api/listFriends and decodes the three buckets verbatim", async () => {- const seen: Array<{ url: string }> = [];- const fetchImpl: FetchLike = vi.fn(async (url: string) => {- seen.push({ url });+ it("listFriends fans out to friends/accepted + friends/pending (GET, no target-user) and composes 3 buckets", async () => {+ const seen: Array<{ url: string; method?: string }> = [];+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {+ seen.push({ url, method: init?.method });+ if (url.endsWith("/friends/accepted")) {+ return jsonBody(JSON.stringify({ accepted: [{ userId: "u1", handle: "A#1" }] }), { status: 200 });+ }+ // /friends/pendingreturn jsonBody(- JSON.stringify({ accepted: [{ userId: "u1", handle: "A#1" }], pendingOutgoing: [], pendingIncoming: [] }),+ JSON.stringify({ pendingIncoming: [{ userId: "u2", handle: "B#2" }], pendingOutgoing: [] }),{ status: 200 },);});const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });const res = await api.listFriends({ agentId: "a1" as never });- expect(res).toEqual({ accepted: [{ userId: "u1", handle: "A#1" }], pendingOutgoing: [], pendingIncoming: [] });- expect(seen[0].url).toBe("http://proxy.test/api/listFriends");+ // Composed the flat 3-bucket shape `alook friend list` renders — CLI unchanged.+ expect(res).toEqual({+ accepted: [{ userId: "u1", handle: "A#1" }],+ pendingIncoming: [{ userId: "u2", handle: "B#2" }],+ pendingOutgoing: [],+ });+ const urls = seen.map((s) => s.url).sort();+ expect(urls).toEqual([+ "http://proxy.test/api/community/friends/accepted",+ "http://proxy.test/api/community/friends/pending",+ ]);+ // Bucket reads are GETs and NEVER hit friends/blocked (owner-only, bot-403).+ expect(seen.every((s) => s.method === "GET")).toBe(true);+ expect(seen.some((s) => s.url.includes("/friends/blocked"))).toBe(false);});- it("both throw the 'non-JSON body' pattern on an empty 500", async () => {+ it("friendRequest throws the 'non-JSON body' pattern on an empty 500", async () => {const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });await expect(api.friendRequest({ agentId: "a1" as never, username: "A#0001" })).rejects.toThrow(- /upstream returned 500 with non-JSON body from \/api\/friendRequest/,+ /upstream returned 500 with non-JSON body during friendRequest/,);+ });++ it("listFriends throws the 'non-JSON body' pattern when a bucket endpoint 500s", async () => {+ const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });await expect(api.listFriends({ agentId: "a1" as never })).rejects.toThrow(- /upstream returned 500 with non-JSON body from \/api\/listFriends/,+ /upstream returned 500 with non-JSON body during listFriends/,);});});diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 8bbef22ab..63c2a132b 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -6,8 +6,8 @@* - `<PREFIX>_PROXY_URL` — the local credential proxy's URL* - `<PREFIX>_PROXY_TOKEN_FILE` — a 0600 file holding the per-launch `vch_` voucher*- * This client reads those, then calls `POST <proxyUrl>/api/<method>` carrying- * `Authorization: Bearer <voucher>`. The proxy validates the voucher, swaps in+ * This client reads those, then calls canonical `/api/community/*` REST doors+ * carrying `Authorization: Bearer <voucher>`. The proxy validates the voucher, swaps in* the real key, stamps `X-Agent-Id` (derived from the voucher — NOT from anything* the agent says), and forwards to the data-plane upstream. So the agent's* identity is established by the voucher it holds, never self-asserted.@@ -49,6 +49,7 @@ import type {FriendRequestResult,FriendCard,} from "../server/contract.js";+import { formatHandle } from "@alook/shared";export interface ProxyServerApiConfig {/** The credential proxy base URL (from `<PREFIX>_PROXY_URL`). */@@ -89,20 +90,20 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {text = await res.text();} catch (err) {const cause = err instanceof Error ? err.message : String(err);- throw new Error(`upstream body read failed from /api/${method} (${res.status}): ${cause}`);+ throw new Error(`upstream body read failed during ${method} (${res.status}): ${cause}`);}if (text.length === 0) {if (res.ok) return undefined as T;- throw new Error(`upstream returned ${res.status} with non-JSON body from /api/${method}`);+ throw new Error(`upstream returned ${res.status} with non-JSON body during ${method}`);}let json: (T & { error?: string; code?: string; hint?: string }) | undefined;try {json = JSON.parse(text) as T & { error?: string; code?: string; hint?: string };} catch {- throw new Error(`upstream returned ${res.status} with non-JSON body from /api/${method}`);+ throw new Error(`upstream returned ${res.status} with non-JSON body during ${method}`);}if (!res.ok) {- const e = new Error(json?.error ?? `proxy api/${method} failed (${res.status})`);+ const e = new Error(json?.error ?? `proxy ${method} failed (${res.status})`);// Only attach when present — assigning `undefined` would leave an own// property that trips `"code" in err` / `hasOwnProperty` checks in// callers that use those as feature-tests.@@ -116,23 +117,6 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return json as T;}- async function call<T>(method: string, body: unknown): Promise<T> {- // Strip any agentId from the wire body: identity travels ONLY as the voucher,- // which the proxy turns into a trusted X-Agent-Id the bridge injects. Sending- // an agentId here would be ignored (the bridge overrides it) — we omit it so- // the wire carries no self-asserted identity at all.- const { agentId: _omit, ...wire } = (body ?? {}) as Record<string, unknown>;- const res = await fetchImpl(`${base}/api/${method}`, {- method: "POST",- headers: {- "content-type": "application/json",- authorization: `Bearer ${config.voucher}`,- },- body: JSON.stringify(wire),- });- return parseJsonResponse<T>(res, method);- }-async function callUpload(req: AttachmentUploadRequest): Promise<AgentAttachmentUploadResult> {const form = new FormData();// The Blob's `type` becomes `File.type` on the server after multipart parsing;@@ -143,7 +127,12 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {? new Blob([new Uint8Array(req.file.data)], { type: blobType }): req.file.data;form.append("file", bytes as Blob, req.file.filename);- const url = `${base}/api/attachmentUpload?target=${encodeURIComponent(req.target)}`;+ // Canonical attachments door: POST channels/{id}/attachments. The bot holds+ // a REF (not an id), so it uses the `resolve` placeholder id and carries the+ // ref on `?target=` (kept — Gener #68); the door's bot arm resolves it+ // member-scoped → 404 (①-C). Same multipart BODY + `?target=` query as the+ // old flat `attachmentUpload`; only the PATH changes.+ const url = `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/attachments?target=${encodeURIComponent(req.target)}`;const res = await fetchImpl(url, {method: "POST",headers: { authorization: `Bearer ${config.voucher}` },@@ -152,15 +141,344 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return parseJsonResponse<AgentAttachmentUploadResult>(res, "attachmentUpload");}- async function callDownload(req: AttachmentDownloadRequest): Promise<AgentAttachmentDownloadResult> {- const res = await fetchImpl(`${base}/api/attachmentDownload`, {+ // --- Canonical id-in-path message door (route/disc trunk) -----------------+ // send/read RETARGETED off the flat verbs (`/api/send`, `/api/read`) onto the+ // one canonical door `channels/{id}/messages`. The bot holds a REF, not an id,+ // and a ref carries `/` so it can't sit in a path segment — so the bot uses+ // the `resolve` placeholder id and passes the ref as body (POST) / query+ // (GET), which the door resolves server-side (resolveMessageTarget). Same wire+ // BODY as before (the door's bot arm parses the identical send/read schema);+ // only the PATH + verb-shape change. Mirrors callUpload/callListServers'+ // bespoke real-path pattern; the credential proxy preserves this canonical+ // REST path unchanged.+ const REF_PLACEHOLDER_ID = "resolve";++ async function callSend(req: SendRequest): Promise<SendResponse> {+ // agentId stripped like `call()` does — identity rides the voucher only.+ // Route through `unknown` first: SendRequest is a typed shape with no index+ // signature, so a direct `as Record<string, unknown>` is rejected (call()+ // gets this for free because its param is already `unknown`).+ const { agentId: _omit, ...wire } = (req ?? {}) as unknown as Record<string, unknown>;+ const res = await fetchImpl(`${base}/api/community/channels/${REF_PLACEHOLDER_ID}/messages`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify(wire),+ });+ return parseJsonResponse<SendResponse>(res, "send");+ }++ async function callCreatePost(req: CreatePostRequest): Promise<CreatePostResponse> {+ const endpoint = `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/messages`;+ const openerNonce = req.nonce !== undefined ? `${req.nonce}:opener` : undefined;+ const replyNonce = req.nonce !== undefined ? `${req.nonce}:reply` : undefined;+ const openerRes = await fetchImpl(endpoint, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify({+ channel: req.forum,+ content: { text: req.title },+ attachments: req.attachments ?? [],+ ...(openerNonce !== undefined ? { nonce: openerNonce } : {}),+ }),+ });+ const opener = await parseJsonResponse<{+ state: "sent";+ message: Message;+ threadId: string;+ }>(openerRes, "createPost opener");+ if (opener.state !== "sent" || !opener.message || !opener.threadId) {+ throw new Error("createPost: upstream response missing opener thread");+ }+ const threadRef = `${req.forum}/#${opener.message.seq.replace(/^#/, "")}`;+ const replyRes = await fetchImpl(endpoint, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify({+ channel: threadRef,+ content: req.content,+ attachments: req.attachments ?? [],+ ...(replyNonce !== undefined ? { nonce: replyNonce } : {}),+ }),+ });+ const reply = await parseJsonResponse<{ state: "sent"; message: Message }>(replyRes, "createPost reply");+ if (reply.state !== "sent" || !reply.message) throw new Error("createPost: upstream response missing reply");+ return {+ ref: reply.message.channel,+ name: req.title,+ seq: Number(reply.message.seq.replace(/^#/, "")),+ };+ }++ async function callRead(req: ReadRequest): Promise<Page<Message>> {+ // The ref + seq anchors go on the query string (a GET has no body). Encode+ // the ref — it carries `/` and can carry `#`/`@` in DM handles. Precedent:+ // callUpload's `?target=${encodeURIComponent(...)}`.+ const q = new URLSearchParams()+ q.set("ref", req.channel)+ if (req.before !== undefined) q.set("before", String(req.before))+ if (req.after !== undefined) q.set("after", String(req.after))+ if (req.around !== undefined) q.set("around", String(req.around))+ if (req.limit !== undefined) q.set("limit", String(req.limit))+ const res = await fetchImpl(+ `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/messages?${q.toString()}`,+ {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ },+ );+ return parseJsonResponse<Page<Message>>(res, "read");+ }++ async function callChannelMember(+ req: { agentId?: AgentId; channel: ChannelRef },+ ): Promise<ChannelMemberResult> {+ // Canonical members door: GET channels/{id}/members. The bot holds a ref+ // (not an id), so it uses the `resolve` placeholder id and carries the ref on+ // the query; the door resolves it server-side (member-scoped → 404, ①-C) and+ // returns the lean `ChannelMemberResult` (visibility + members/hint).+ const res = await fetchImpl(+ `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/members?ref=${encodeURIComponent(req.channel)}`,+ {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ },+ );+ return parseJsonResponse<ChannelMemberResult>(res, "channelMember");+ }++ async function callResolve(req: ResolveRequest): Promise<{ message: Message }> {+ // Canonical hydrate door: GET messages/{id}. The bot holds a ref+seq (not a+ // messageId), so it uses the `resolve` placeholder id and carries ref+seq on+ // the query; the door resolves ref+seq → message server-side (member-scoped+ // → 404, ①-C) and returns the `{ message }` agent shape. Encode the ref (it+ // carries `/`, and `#`/`@` in DM handles). resolve is locate∘hydrate — a+ // SEPARATE door from the seq→id lookup (which returns `{ id }`), NOT folded.+ const q = new URLSearchParams()+ q.set("ref", req.channel)+ q.set("seq", String(req.seq))+ const res = await fetchImpl(+ `${base}/api/community/messages/${REF_PLACEHOLDER_ID}?${q.toString()}`,+ {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ },+ );+ return parseJsonResponse<{ message: Message }>(res, "resolve");+ }++ async function callReactAdd(+ req: { channel: ChannelRef; seq: Seq; emoji: string },+ ): Promise<CommunityAgentReactAddResponse> {+ // Canonical reaction door: PUT messages/{id}/reactions/{emoji}. The bot+ // holds a ref+seq (not a messageId), so it uses the `resolve` placeholder id+ // and carries `{ channel, seq }` in the body; the door resolves ref+seq →+ // messageId server-side (member-scoped → 404, ①-C). The emoji is a PATH+ // segment (URL-encoded) — reactions are keyed by (message, emoji).+ const res = await fetchImpl(+ `${base}/api/community/messages/${REF_PLACEHOLDER_ID}/reactions/${encodeURIComponent(req.emoji)}`,+ {+ method: "PUT",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify({ channel: req.channel, seq: req.seq }),+ },+ );+ // Response projection (Fork C, at the single proxy boundary): the canonical+ // route returns the reaction ROW (or `{ ok, duplicate }` on a dup); the lean+ // agent contract is `{ ok: true, duplicate? }`. A 200 with a `duplicate`+ // flag maps straight through; any other 200 is a fresh add → `{ ok: true }`.+ const body = await parseJsonResponse<{ duplicate?: boolean }>(res, "reactAdd");+ return body?.duplicate ? { ok: true, duplicate: true } : { ok: true };+ }++ async function callListMembers(+ req: { agentId?: AgentId; server: string; limit?: number; cursor?: string },+ ): Promise<ServerMemberListResult> {+ // Canonical server-member door: GET servers/{id}/members. RETARGETED off the+ // flat `listMembers` verb. The bot addresses by server ref/name (not id), so+ // it uses the `resolve` placeholder id and carries the ref on `?server=`+ // (plus optional `limit`/`cursor` for the paginated roster); the door+ // resolves it member-scoped (→ 404, ①-C) and returns the lean+ // `{ members: [{handle, role, online, status}], hasMore, cursor? }` shape.+ // Encode the ref (server names can carry `#`/spaces).+ const q = new URLSearchParams()+ q.set("server", req.server)+ if (req.limit !== undefined) q.set("limit", String(req.limit))+ if (req.cursor !== undefined) q.set("cursor", req.cursor)+ const res = await fetchImpl(+ `${base}/api/community/servers/${REF_PLACEHOLDER_ID}/members?${q.toString()}`,+ {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ },+ );+ return parseJsonResponse<ServerMemberListResult>(res, "listMembers");+ }++ async function callListChannels(req: ListChannelsRequest): Promise<{ groups: ChannelGroup[] }> {+ // Canonical channel-list doors: single server → GET servers/{id}/channels+ // (ref on `?server=`, `resolve` placeholder id, member-scoped → 404 ①-C);+ // all servers (server omitted) → GET servers/channels (collection-level+ // aggregate, no id). RETARGETED off the flat `listChannels` verb. Both return+ // the same `{ groups: ChannelGroup[] }`.+ const url = req.server+ ? `${base}/api/community/servers/${REF_PLACEHOLDER_ID}/channels?server=${encodeURIComponent(req.server)}`+ : `${base}/api/community/servers/channels`;+ const res = await fetchImpl(url, {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ });+ return parseJsonResponse<{ groups: ChannelGroup[] }>(res, "listChannels");+ }++ async function callListFriends(): Promise<{+ accepted: FriendCard[];+ pendingOutgoing: FriendCard[];+ pendingIncoming: FriendCard[];+ }> {+ // RETARGETED off the flat `listFriends` verb onto the per-bucket friends+ // sub-resource endpoints (route/disc 轴3): accepted from GET friends/accepted,+ // pending from GET friends/pending. The bot NEVER calls friends/blocked+ // (owner-only, bot-403). Compose the 3-bucket shape `alook friend list`+ // renders — CLI output unchanged. Both endpoints are self-scoped to the+ // voucher's bot (no target-user param), so no addressing goes on the wire.+ const get = async (path: string) => {+ const res = await fetchImpl(`${base}/api/community/friends/${path}`, {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ });+ return res;+ };+ const [acceptedRes, pendingRes] = await Promise.all([get("accepted"), get("pending")]);+ const acceptedBody = await parseJsonResponse<{ accepted: FriendCard[] }>(acceptedRes, "listFriends");+ const pendingBody = await parseJsonResponse<{+ pendingIncoming: FriendCard[];+ pendingOutgoing: FriendCard[];+ }>(pendingRes, "listFriends");+ return {+ accepted: acceptedBody.accepted ?? [],+ pendingIncoming: pendingBody.pendingIncoming ?? [],+ pendingOutgoing: pendingBody.pendingOutgoing ?? [],+ };+ }++ async function callInboxPull(req: InboxPullRequest): Promise<InboxPullResponse> {+ // RETARGETED off the flat `inboxPull` verb onto the caller's own inbox+ // resource POST users/me/inbox/pull (route/disc 轴3). Self-scoped to the+ // voucher's bot — no target-user param on the wire (users/me/* family).+ // The legacy flat route is deleted. Same optional `{max?}` body.+ const { agentId: _omit, ...wire } = (req ?? {}) as unknown as Record<string, unknown>;+ const res = await fetchImpl(`${base}/api/community/users/me/inbox/pull`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify(wire),+ });+ return parseJsonResponse<InboxPullResponse>(res, "inboxPull");+ }++ async function callAck(req: AckRequest): Promise<void> {+ // RETARGETED off the flat `ack` verb onto POST users/me/inbox/ack (route/disc+ // 接口树统一, Gener #215 乙) — ack is the ADVANCE operation of the inbox+ // fetch↔advance trinity (snapshot=peek / pull=fetch / ack=advance, Aigneis+ // #41). Self-scoped to the voucher's bot — the wire carries only the cursors,+ // no target-user param (users/me/* family). Body byte-identical to the flat+ // verb (the endpoint is a MOVE-FLAT, same seq-native/failed[]-batch/no-create+ // shape — only the URL moved). The legacy flat route is deleted. Returns void (the daemon+ // fire-and-forgets the {ok,applied,failed} body, same as the flat verb).+ const { agentId: _omit, ...wire } = (req ?? {}) as unknown as Record<string, unknown>;+ const res = await fetchImpl(`${base}/api/community/users/me/inbox/ack`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify(wire),+ });+ return parseJsonResponse<void>(res, "ack");+ }++ async function callFriendRequest(req: { agentId: AgentId; username: string }): Promise<FriendRequestResult> {+ // RETARGETED off the flat `friendRequest` verb onto POST friends/request+ // (route/disc 接口树统一, Melly #540) — the friend-request door is dual-actor+ // (human/bot on one URL, dispatched to independent handlers). The bot arm+ // keeps its distinct semantics (sibling-auto-accept, always-owner-gated, lean+ // {friendshipId,status,hint}). Self-scoped: the wire carries only `username`,+ // never a requesterId (that's the credential's botUserId server-side). Body+ // byte-identical to the former flat verb; that legacy route is deleted.+ const { agentId: _omit, ...wire } = (req ?? {}) as unknown as Record<string, unknown>;+ const res = await fetchImpl(`${base}/api/community/friends/request`, {method: "POST",headers: {"content-type": "application/json",authorization: `Bearer ${config.voucher}`,},- body: JSON.stringify({ id: req.id }),+ body: JSON.stringify(wire),+ });+ return parseJsonResponse<FriendRequestResult>(res, "friendRequest");+ }++ async function callNap(req: { handoff: string }): Promise<{ napped: boolean }> {+ // RETARGETED off the flat `nap` verb onto POST bots/me/nap (route/disc+ // 接口树统一, Gener #215 乙; Blondie #527). nap is a bot-qua-bot self+ // lifecycle action — the agent resets its OWN session — so it lives under+ // bots/me/* (self-scope, "me" = the credential-authenticated bot, no target+ // id). Self-scoped to the voucher's bot: the wire carries only the handoff,+ // never a target-bot param (bots/me/* family invariant, same as users/me).+ // Body byte-identical to the former flat verb; that legacy route is deleted.+ const { agentId: _omit, ...wire } = (req ?? {}) as unknown as Record<string, unknown>;+ const res = await fetchImpl(`${base}/api/community/bots/me/nap`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: JSON.stringify(wire),});+ return parseJsonResponse<{ napped: boolean }>(res, "nap");+ }++ async function callInboxSnapshot(): Promise<InboxSnapshot> {+ // RETARGETED off the flat `inboxSnapshot` verb onto GET users/me/inbox/snapshot+ // (route/disc 轴3). A GET — snapshot is a pure peek (never advances the read+ // waterline, unlike pull), so the fetch↔advance decoupling is explicit in the+ // verb. Self-scoped, no target-user param; the legacy flat route is deleted.+ const res = await fetchImpl(`${base}/api/community/users/me/inbox/snapshot`, {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ });+ return parseJsonResponse<InboxSnapshot>(res, "inboxSnapshot");+ }++ async function callDownload(req: AttachmentDownloadRequest): Promise<AgentAttachmentDownloadResult> {+ // Canonical attachments door: GET channels/{id}/attachments/{attachmentId}.+ // The attachment id is authoritative (the door authorizes from the row's own+ // channel, never the path), so the id moves from the old POST body into the+ // path and the `resolve` placeholder fills the channel segment. The response+ // is still a raw binary body + `X-Alook-Filename`; success streaming ++ // error-as-JSON handling below is unchanged.+ const res = await fetchImpl(+ `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/attachments/${encodeURIComponent(req.id)}`,+ {+ method: "GET",+ headers: {+ authorization: `Bearer ${config.voucher}`,+ },+ },+ );if (!res.ok) {// Error responses ARE JSON. Streaming success responses are binary.// Route through the shared helper so empty/HTML-502/read-fail all@@ -192,13 +510,13 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {// POST /invites/<token>/join). The unified route returns a SUPERSET; the lean// contract projection (Fork C — Aigneis condition 1) happens HERE, at the// single proxy response boundary, NOT per CLI command. These hit- // `/api/community/...` directly; `rewriteAgentPath` is idempotent so the path- // passes through unprefixed. Mirrors the existing callUpload/callDownload+ // `/api/community/...` directly and the credential proxy preserves the path+ // unchanged. Mirrors the existing callUpload/callDownload// custom-path pattern.- /** Project a superset server row down to the lean `Server` ({id,name}). */- function projectServer(row: { id: string; name: string }): Server {- return { id: row.id, name: row.name };+ /** Project a server row to its sole agent-facing identity: name#discriminator. */+ function projectServer(row: { name: string; discriminator: string }): Server {+ return { handle: formatHandle(row.name, row.discriminator) };}async function callListServers(): Promise<{ servers: Server[] }> {@@ -206,11 +524,11 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {method: "GET",headers: { authorization: `Bearer ${config.voucher}` },});- const body = await parseJsonResponse<{ servers: Array<{ id: string; name: string }> }>(+ const body = await parseJsonResponse<{ servers: Array<{ name: string; discriminator: string }> }>(res,"listServers",);- // Superset in → lean out: drop icon/ownerId/etc., emit only {id,name}.+ // Superset in → lean out: emit only the canonical handle.return { servers: body.servers.map(projectServer) };}@@ -229,8 +547,8 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {body: "{}",},);- const body = await parseJsonResponse<{ server?: { id: string; name: string } }>(res, "joinServer");- // Superset {member,serverId,server} in → lean {server:{id,name}} out.+ const body = await parseJsonResponse<{ server?: { name: string; discriminator: string } }>(res, "joinServer");+ // Superset {member,serverId,server} in → canonical agent-facing handle.if (!body.server) {throw new Error("joinServer: upstream response missing server");}@@ -240,29 +558,21 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return {listServers: (_r: { agentId: AgentId }) => callListServers(),joinServer: callJoinServer,- listChannels: (r: ListChannelsRequest) => call<{ groups: ChannelGroup[] }>("listChannels", r),- channelMember: (r: { agentId?: AgentId; channel: ChannelRef }) =>- call<ChannelMemberResult>("channelMember", r),- inboxPull: (r: InboxPullRequest) => call<InboxPullResponse>("inboxPull", r),- inboxSnapshot: (r: { agentId: AgentId }) => call<InboxSnapshot>("inboxSnapshot", r),- ack: (r: AckRequest) => call<void>("ack", r),- send: (r: SendRequest) => call<SendResponse>("send", r),- createPost: (r: CreatePostRequest) => call<CreatePostResponse>("createPost", r),- read: (r: ReadRequest) => call<Page<Message>>("read", r),- resolve: (r: ResolveRequest) => call<{ message: Message }>("resolve", r),- listMembers: (r: { agentId: AgentId; server: string; limit?: number; cursor?: string }) =>- call<ServerMemberListResult>("listMembers", r),+ listChannels: callListChannels,+ channelMember: callChannelMember,+ inboxPull: callInboxPull,+ inboxSnapshot: (_r: { agentId: AgentId }) => callInboxSnapshot(),+ ack: callAck,+ send: callSend,+ createPost: callCreatePost,+ read: callRead,+ resolve: callResolve,+ listMembers: callListMembers,attachmentUpload: callUpload,attachmentDownload: callDownload,- reactAdd: (r: { channel: ChannelRef; seq: Seq; emoji: string }) =>- call<CommunityAgentReactAddResponse>("reactAdd", r),- friendRequest: (r: { agentId: AgentId; username: string }) =>- call<FriendRequestResult>("friendRequest", r),- listFriends: (r: { agentId: AgentId }) =>- call<{ accepted: FriendCard[]; pendingOutgoing: FriendCard[]; pendingIncoming: FriendCard[] }>(- "listFriends",- r,- ),- nap: (r: { handoff: string }) => call<{ napped: boolean }>("nap", r),+ reactAdd: callReactAdd,+ friendRequest: callFriendRequest,+ listFriends: (_r: { agentId: AgentId }) => callListFriends(),+ nap: callNap,};}diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex 24100e564..5d01c1922 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -47,16 +47,89 @@ async function post(url: string, voucher: string, path: string) {}describe("DEFAULT_CAPABILITY_RESOLVER", () => {- it("maps /api/reactAdd to the `send` capability (a read-only voucher must not react)", () => {- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/reactAdd")).toBe("send");- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/reactAdd")).toBe("send");- });-- it("maps friendRequest / listFriends to the `friend` capability, both pre- and post-rewrite", () => {- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/friendRequest")).toBe("friend");- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/listFriends")).toBe("friend");- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/friendRequest")).toBe("friend");- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/listFriends")).toBe("friend");+ it("maps a reaction (canonical door PUT messages/{id}/reactions) to `send` (a read-only voucher must not react)", () => {+ // Flat /api/reactAdd is DELETED (folded into the canonical reaction door).+ // The write capability now attaches to the door shape.+ expect(DEFAULT_CAPABILITY_RESOLVER("PUT", "/api/community/messages/resolve/reactions/%F0%9F%91%8D")).toBe("send");+ });++ it("maps the friends bucket sub-resource endpoints (listFriends fold) to `friend`", () => {+ // The bot's listFriends fans out to these; friends/blocked is bot-403 at the+ // route so a bot never reaches it, but the cap mapping is uniform.+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/friends/accepted")).toBe("friend");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/friends/pending")).toBe("friend");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/friends/blocked")).toBe("friend");+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/friends/request")).toBe("friend");+ });++ // ── Canonical id-in-path message door (route/disc retarget). The SHAPE is+ // matched by method, BEFORE the legacy `/channel → server` substring rule,+ // which would otherwise grab `/channels/{id}/…` first and mis-scope a bot+ // send/read to the `server` capability. ──+ it("maps the canonical messages door by METHOD: POST→send, GET→read", () => {+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/channels/resolve/messages")).toBe("send");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/resolve/messages")).toBe("read");+ // real channelId in the path (human/web shape) resolves the same way.+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/channels/abc123/messages")).toBe("send");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/abc123/messages")).toBe("read");+ // with a query string (read's ?ref=&before=…).+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/resolve/messages?ref=%2Fs%2Fg&before=5")).toBe("read");+ });++ it("does NOT let the canonical `/channels/…` path fall through to the `server` capability (the miscap this rewrite fixes)", () => {+ // Pre-rewrite this path contains `channel`, which the legacy rule maps to+ // `server`; the shape rule must intercept POST/GET first.+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/channels/resolve/messages")).not.toBe("server");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/resolve/messages")).not.toBe("server");+ });++ it("maps the canonical attachments door (attachments fold) to `attach`, NOT `server` — no new rule needed", () => {+ // The upload/download verbs folded onto channels/{id}/attachments. The+ // existing `.includes("/attachment")` rule fires FIRST (before the shape+ // rules and before the legacy `/channel → server` fallback), so the nested+ // path keeps the `attach` capability with no resolver change (Aigneis #554).+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/channels/resolve/attachments")).toBe("attach");+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/channels/c1/attachments?target=%2Fs%2Fg")).toBe("attach");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/resolve/attachments/att_1")).toBe("attach");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/c1/attachments/att_1")).toBe("attach");+ // The `/channels/` substring must NOT drag it to the `server` fallback.+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/c1/attachments/att_1")).not.toBe("server");+ // …and must NOT be mistaken for the messages door (send/read).+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/channels/resolve/attachments")).not.toBe("send");+ });++ it("maps the message-keyed write doors to `send` (reactions PUT/DELETE, threads POST, seq GET→read)", () => {+ expect(DEFAULT_CAPABILITY_RESOLVER("PUT", "/api/community/messages/resolve/reactions/%F0%9F%91%8D")).toBe("send");+ expect(DEFAULT_CAPABILITY_RESOLVER("DELETE", "/api/community/messages/m1/reactions/%F0%9F%91%8D")).toBe("send");+ // the seq→id lookup is a read.+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/channels/resolve/messages/seq/42")).toBe("read");+ });++ it("maps the single-message hydrate door GET messages/{id} to `read` (folds `resolve`)", () => {+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/messages/resolve?ref=%2Fs%2Fg&seq=42")).toBe("read");+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/messages/m1")).toBe("read");+ // must NOT shadow the more specific write sub-paths.+ expect(DEFAULT_CAPABILITY_RESOLVER("PUT", "/api/community/messages/m1/reactions/x")).toBe("send");+ });++ it("does not map deleted flat write verbs; inboxPull still matches the generic /inbox read family", () => {+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/createPost")).toBeUndefined();+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/createPost")).toBeUndefined();+ // /api/inboxPull's flat ROUTE is deleted, but the resolver's generic+ // `/inbox` substring rule (unrelated to the specific flat-verb rules)+ // still fires on this path shape — the daemon proxy only rejects the+ // capability, it never routes the request, so this mapping is harmless+ // even with the route gone.+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/inboxPull")).toBe("read");+ // The flat send/reactAdd/read/resolve/channelMember/friendRequest/listFriends+ // routes are DELETED — their bare `/api/<verb>` paths no longer carry a+ // capability rule (they only reached upstream via the flat routes, which+ // are gone). `/api/send` still matches nothing else, so it's undefined+ // now, not `send`.+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/send")).toBeUndefined();+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/reactAdd")).toBeUndefined();+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/friendRequest")).toBeUndefined();+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/listFriends")).toBeUndefined();});});@@ -181,31 +254,41 @@ describe("startCredentialProxy (zero-trust end to end)", () => {proxy = await startCredentialProxy(broker);const reg = broker.mint("a", "l", ["read"], REAL_KEY); // no "send"- const r = await post(proxy.url, reg.voucher, "/send");+ // The canonical send door (POST channels/{id}/messages) requires `send`.+ const r = await post(proxy.url, reg.voucher, "/api/community/channels/resolve/messages");expect(r.status).toBe(403);expect(upstream.seen.length).toBe(0);});- it("rewrites flat /api/* verbs to /api/community/* (plans/22 §9); is idempotent for already-namespaced paths", async () => {+ it("passes canonical REST paths through and rejects deleted flat inputs", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;+ const sightings: Array<{ agentId: string; method: string; pathname: string }> = [];const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });- proxy = await startCredentialProxy(broker);- const reg = broker.mint("agent-1", "l", ["send", "read", "server"], REAL_KEY);-- await post(proxy.url, reg.voucher, "/api/send");- expect(upstream.seen.at(-1)!.path).toBe("/api/community/send");-- await post(proxy.url, reg.voucher, "/api/inboxPull?max=10");- expect(upstream.seen.at(-1)!.path).toBe("/api/community/inboxPull?max=10");-- await post(proxy.url, reg.voucher, "/api");- expect(upstream.seen.at(-1)!.path).toBe("/api/community");+ proxy = await startCredentialProxy(broker, {+ onProxyRequest: (agentId, method, pathname) => sightings.push({ agentId, method, pathname }),+ });+ const reg = broker.mint("agent-1", "l", ["send", "read", "server", "attach"], REAL_KEY);++ for (const legacyPath of [+ "/api/send",+ "/api/attachmentUpload?target=/x/y",+ "/api/community/send",+ "/api/community/agent/send",+ "/api",+ ]) {+ expect((await post(proxy.url, reg.voucher, legacyPath)).status).toBe(404);+ }+ expect(upstream.seen).toHaveLength(0);+ expect(sightings).toEqual([]);- // Idempotent: a folded verb's real REST path (already under /api/community/)- // passes through unprefixed — NOT doubled into /api/community/community/...- await post(proxy.url, reg.voucher, "/api/community/servers");- expect(upstream.seen.at(-1)!.path).toBe("/api/community/servers");+ // A folded verb's real REST path and encoded query pass through byte-for-byte.+ await post(proxy.url, reg.voucher, "/api/community/servers?cursor=a%2Fb&limit=2");+ expect(upstream.seen).toHaveLength(1);+ expect(upstream.seen[0]!.path).toBe("/api/community/servers?cursor=a%2Fb&limit=2");+ expect(sightings).toEqual([+ { agentId: "agent-1", method: "POST", pathname: "/api/community/servers" },+ ]);});it("leaves non-/api paths untouched", async () => {@@ -241,9 +324,9 @@ describe("startCredentialProxy (zero-trust end to end)", () => {});const reg = broker.mint("agent-1", "l", ["send"], REAL_KEY);- const r = await post(proxy.url, reg.voucher, "/api/send");+ const r = await post(proxy.url, reg.voucher, "/api/community/channels/resolve/messages");expect(r.status).toBe(200);- expect(sightings).toEqual([{ agentId: "agent-1", method: "POST", pathname: "/api/send" }]);+ expect(sightings).toEqual([{ agentId: "agent-1", method: "POST", pathname: "/api/community/channels/resolve/messages" }]);});it("does NOT fire onProxyRequest on a rejected voucher (401/403)", async () => {@@ -263,9 +346,10 @@ describe("startCredentialProxy (zero-trust end to end)", () => {const bogus = await post(proxy.url, "vch_bogus", "/api/send");expect(bogus.status).toBe(401);- // Capability denied → 403 (still not fired).+ // Capability denied → 403 (still not fired). Use the canonical send door+ // (POST channels/{id}/messages → send) since the flat /api/send is deleted.const scoped = broker.mint("agent-1", "l", ["read"], REAL_KEY);- const denied = await post(proxy.url, scoped.voucher, "/api/send");+ const denied = await post(proxy.url, scoped.voucher, "/api/community/channels/resolve/messages");expect(denied.status).toBe(403);expect(sightings).toEqual([]);@@ -279,14 +363,14 @@ describe("startCredentialProxy (zero-trust end to end)", () => {const scoped = broker.mint("agent-1", "l", ["send", "read"], REAL_KEY); // no "attach"const withAttach = broker.mint("agent-2", "l2", ["attach"], REAL_KEY);- const upDenied = await post(proxy.url, scoped.voucher, "/api/attachmentUpload?target=/x/y");+ const upDenied = await post(proxy.url, scoped.voucher, "/api/community/channels/resolve/attachments?target=/x/y");expect(upDenied.status).toBe(403);- const dlDenied = await post(proxy.url, scoped.voucher, "/api/attachmentDownload");+ const dlDenied = await post(proxy.url, scoped.voucher, "/api/community/channels/resolve/attachments/att_1");expect(dlDenied.status).toBe(403);- const upOk = await post(proxy.url, withAttach.voucher, "/api/attachmentUpload?target=/x/y");+ const upOk = await post(proxy.url, withAttach.voucher, "/api/community/channels/resolve/attachments?target=/x/y");expect(upOk.status).toBe(200);- const dlOk = await post(proxy.url, withAttach.voucher, "/api/attachmentDownload");+ const dlOk = await post(proxy.url, withAttach.voucher, "/api/community/channels/resolve/attachments/att_1");expect(dlOk.status).toBe(200);});@@ -297,11 +381,12 @@ describe("startCredentialProxy (zero-trust end to end)", () => {proxy = await startCredentialProxy(broker);const reg = broker.mint("agent-1", "l", ["attach"], REAL_KEY);- const r = await post(proxy.url, reg.voucher, "/api/send");+ // Canonical send door requires `send`; an attach-only voucher is denied.+ const r = await post(proxy.url, reg.voucher, "/api/community/channels/resolve/messages");expect(r.status).toBe(403);});- it("onInboxPullResponse is NOT triggered by /attachmentDownload (tightened guard)", async () => {+ it("onInboxPullResponse is NOT triggered by canonical attachment download (tightened guard)", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;let called = 0;@@ -314,14 +399,14 @@ describe("startCredentialProxy (zero-trust end to end)", () => {const reg = broker.mint("agent-1", "l", ["attach", "read"], REAL_KEY);// Path that used to (loosely) match `.endsWith("/inboxPull")` — the- // tightened `pathname === "/api/inboxPull"` guard must not fire for- // attachment traffic, which returns raw binary.- const r = await post(proxy.url, reg.voucher, "/api/attachmentDownload");+ // exact-path guard must not fire for attachment traffic, which returns+ // raw binary.+ const r = await post(proxy.url, reg.voucher, "/api/community/channels/resolve/attachments/att_1");expect(r.status).toBe(200);expect(called).toBe(0);// The real inbox pull still triggers the callback (baseline).- const p = await post(proxy.url, reg.voucher, "/api/inboxPull");+ const p = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");expect(p.status).toBe(200);// startUpstream() returns { ok: true } (no `messages`), so the callback// still receives a call attempt — it just doesn't call the handler with@@ -330,6 +415,30 @@ describe("startCredentialProxy (zero-trust end to end)", () => {// above).});+ it("onInboxPullResponse fires for the canonical fold path users/me/inbox/pull, but NOT snapshot", async () => {+ // The inboxPull verb folds into POST users/me/inbox/pull (route/disc 轴3);+ // callInboxPull sends this full path directly (no rewrite), so the timeline+ // recorder's exact-path guard must recognize it. The snapshot door is a+ // peek (no `{ messages }`) and must NOT be treated as a pull. The flat+ // `/api/inboxPull` verb is deleted (flat-delete step) — no longer part of+ // this guard.+ const upstream = await startUpstream();+ upstreamClose = upstream.close;+ const seen: string[] = [];+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });+ proxy = await startCredentialProxy(broker, {+ onInboxPullResponse: (agentId) => seen.push(agentId),+ });+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);++ const canonical = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");+ expect(canonical.status).toBe(200);+ // startUpstream() returns { ok: true } (no messages) so the handler never+ // fires with a real list — seen stays empty, but the path isn't 500 or+ // rejected, proving it's accepted as pull traffic (the guard matched).+ expect(seen).toEqual([]);+ });+it("surfaces the buffered inboxPull response AND fires onInboxPullResponse", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;@@ -340,7 +449,7 @@ describe("startCredentialProxy (zero-trust end to end)", () => {});const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);- const r = await post(proxy.url, reg.voucher, "/api/inboxPull");+ const r = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");expect(r.status).toBe(200);// `startUpstream()` always responds `{ ok: true }` — no `messages` field —// so the callback should NOT fire for a response that isn't shaped likediff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex 10ae73888..8c5fa974d 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -232,17 +232,41 @@ function parseBearer(authHeader: string | undefined): string | null {*/export type CapabilityResolver = (method: string, pathname: string) => Capability | undefined;-export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (_method, pathname) => {+export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (method, pathname) => {// Match `/attachmentUpload` and `/attachmentDownload` (pre-rewrite pathname// — the credential proxy inspects the client's `/api/...` path here). Both// endpoints share the `"attach"` capability so a voucher can be scoped to// attach-only without granting `send`/`read`.if (pathname.includes("/attachment")) return "attach";- if (pathname.includes("/friendRequest") || pathname.includes("/listFriends")) return "friend";- // `/createPost` is a create/write (a new forum post + its first message), same- // write class as `/send`/`/reactAdd` — it needs the `send` capability so a- // read-only or attach-only voucher can't create content.- if (pathname.includes("/send") || pathname.includes("/reactAdd") || pathname.includes("/createPost")) return "send";+ // Friend surfaces: the per-bucket sub-resource endpoints (/friends,+ // /friends/accepted, /friends/pending, /friends/request). /friends/blocked is+ // bot-403 at the route (owner-only) so a bot voucher never reaches it+ // regardless of cap. The flat /friendRequest and /listFriends verbs are+ // deleted (flat-delete step) — no substring rule for them anymore.+ if (/\/friends(\/|$|\?)/.test(pathname)) return "friend";++ // ── Canonical id-in-path message door (route/disc trunk). Matched by METHOD ++ // path SHAPE, before the flat-verb substring rules below, because the+ // substring rules can't tell a canonical shape apart: `/channels/{id}/…`+ // contains the literal `channel`, which the legacy `/server|/channel →+ // "server"` rule (kept at the bottom) would grab FIRST — mis-scoping a+ // bot send/read to the `server` capability. Shape+method disambiguates:+ // the same `channels/{id}/messages` path is `read` on GET, `send` on POST.+ // - GET channels/{id}/messages → read (list, folds `read`)+ // - POST channels/{id}/messages → send (create, folds `send`)+ // - GET channels/{id}/messages/seq/{seq} → read (folds `resolve`'s seq→id)+ // - PUT/DELETE messages/{id}/reactions/… → send (write, folds `reactAdd`)+ const isMessagesDoor = /\/channels\/[^/]+\/messages(\/|$|\?)/.test(pathname)+ if (isMessagesDoor) return method === "GET" ? "read" : "send";+ if (/\/messages\/[^/]+\/reactions\//.test(pathname)) return "send";+ // Single-message hydrate door GET messages/{id} (folds the `resolve` verb — a+ // read). Matched AFTER the message-keyed write doors above so their more+ // specific `/reactions|/threads` sub-paths win first.+ if (method === "GET" && /\/messages\/[^/]+(\?|$)/.test(pathname)) return "read";++ // ── Remaining generic read/server families. ──+ // send/read/reactAdd/resolve/channelMember flat routes are DELETED (folded into+ // the canonical doors above), so their substring rules are gone.if (pathname.includes("/history") || pathname.includes("/search") || pathname.includes("/inbox"))return "read";if (pathname.includes("/server") || pathname.includes("/channel")) return "server";@@ -326,13 +350,27 @@ export async function startCredentialProxy(return;}+ // Bot traffic has one canonical REST namespace. The deleted flat+ // `/api/<verb>` surface must fail at this boundary rather than reaching an+ // upstream that might accidentally grow a matching route later.+ const canonicalCommunityDoor = /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots)(\/|$)/.test(pathname);+ if (pathname === "/api" || (pathname.startsWith("/api/") && !canonicalCommunityDoor)) {+ res.writeHead(404, { "content-type": "application/json" });+ res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));+ req.resume();+ return;+ }+const reg = verdict.reg;// Tightened from `.endsWith("/inboxPull")` — the attachment-download// endpoint returns raw binary, and a loose match here would try to JSON-- // parse it as an inbox response. Only the exact `/api/inboxPull` path- // (pre-rewrite; matches the daemon's CLI callers, see `rewriteAgentPath`)- // should trigger the timeline recorder callback.- const isInboxPull = onPull && pathname === "/api/inboxPull";+ // parse it as an inbox response. Exact-path match the canonical inbox-pull+ // door that returns the `{ messages }` shape the timeline recorder+ // consumes: `/api/community/users/me/inbox/pull` (route/disc 轴3;+ // `callInboxPull` sends this full path directly, no rewrite). The flat+ // `/api/inboxPull` verb is deleted (flat-delete step). inboxSnapshot is+ // deliberately EXCLUDED (peek, no `{ messages }` to record).+ const isInboxPull = onPull && pathname === "/api/community/users/me/inbox/pull";if (onProxyRequest) {try {@@ -371,7 +409,7 @@ export async function startCredentialProxy(hostname: upstream.hostname,port: upstream.port || (upstream.protocol === "https:" ? 443 : 80),method: req.method,- path: joinPath(upstream.pathname, rewriteAgentPath(req.url ?? "/")),+ path: joinPath(upstream.pathname, req.url ?? "/"),headers: outHeaders,},(res_) => {@@ -481,28 +519,3 @@ function joinPath(basePath: string, reqUrl: string): string {const reqPath = reqUrl.startsWith("/") ? reqUrl : `/${reqUrl}`;return (base + reqPath) || "/";}--/**- * Rewrite the CLI's bare `/api/*` ops (`/api/send`, `/api/inboxPull`, …) onto- * the real unified-actor server surface at `/api/community/*` (plans/22 §9 — the- * `/api/community/agent/*` tree was deleted; every bot verb now lives flat under- * `/api/community/`). This is a bot-only API — no back-compat to preserve — so- * the rewrite is unconditional for anything under `/api/`.- *- * IDEMPOTENT: a path already under `/api/community/` passes through untouched.- * The two FOLDED verbs (listServers → GET `/api/community/servers`, joinServer →- * POST `/api/community/invites/<token>/join`) are addressed with their real REST- * paths client-side in `proxyServerApi` (mirroring `callUpload`/`callDownload`);- * this guard lets those flow through without being double-prefixed into a- * non-existent `/api/community/community/...`.- */-function rewriteAgentPath(reqUrl: string): string {- const url = new URL(reqUrl, "http://placeholder");- if (url.pathname.startsWith("/api/community/")) {- return url.pathname + url.search;- }- if (url.pathname === "/api" || url.pathname.startsWith("/api/")) {- url.pathname = `/api/community${url.pathname.slice("/api".length)}`;- }- return url.pathname + url.search;-}diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 8d9c43501..2856a1e6b 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -165,6 +165,10 @@ describe("createDaemon", () => {describe("createDaemon — opt-in raw runtime trace (P0-1)", () => {const dirs: string[] = [];+ const expectSecureMode = (path: string) => {+ if (process.platform === "win32") return;+ expect(statSync(path).mode & 0o777).toBe(0o600);+ };afterEach(() => {for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });});@@ -199,10 +203,7 @@ describe("createDaemon — opt-in raw runtime trace (P0-1)", () => {const path = join(dir, "runtime-raw-events-%2E%2E%2Fagent_a.jsonl");expect(readFileSync(path, "utf8")).toBe('{"jsonrpc":"2.0","vendor":"kept"}\n');- // Windows cannot express POSIX 0600 via Node mode bits (see credentialProxy.test).- if (process.platform !== "win32") {- expect(statSync(path).mode & 0o777).toBe(0o600);- }+ expectSecureMode(path);expect(existsSync(join(dir, "runtime-raw-events-agent_b.jsonl"))).toBe(false);});@@ -225,9 +226,7 @@ describe("createDaemon — opt-in raw runtime trace (P0-1)", () => {expect(existsSync(`${a1}.1`)).toBe(true);expect(readFileSync(a2, "utf8")).toBe("only-a2\n");for (const path of [a1, `${a1}.1`, a2]) {- if (process.platform !== "win32") {- expect(statSync(path).mode & 0o777).toBe(0o600);- }+ expectSecureMode(path);expect(statSync(path).size).toBeLessThanOrEqual(20);}});@@ -323,7 +322,7 @@ describe("createDaemon — logging", () => {agentId: "bot_1",config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },}),);await new Promise((r) => setTimeout(r, 20));@@ -374,7 +373,7 @@ describe("createDaemon — logging", () => {agentId: "bot_1",config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },}),);await new Promise((r) => setTimeout(r, 20));@@ -435,7 +434,7 @@ describe("createDaemon — logging", () => {agentId: "bot_1",config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },}),);await new Promise((r) => setTimeout(r, 20));@@ -462,7 +461,7 @@ describe("createDaemon — logging", () => {agentId: "bot_2",config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l2",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 2 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 2 },}),);await new Promise((r) => setTimeout(r, 20));@@ -528,7 +527,7 @@ describe("createDaemon — logging", () => {agentId: "bot_1",config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },}),);await new Promise((r) => setTimeout(r, 20));@@ -539,6 +538,49 @@ describe("createDaemon — logging", () => {await daemon.stop();});+ it("preserves status and bounded text when enroll-agent returns a non-JSON error", async () => {+ global.fetch = vi.fn(async (url: string | URL) => {+ if (String(url).includes("/enroll-agent")) {+ return new Response("upstream overloaded", { status: 503 });+ }+ return new Response(JSON.stringify({ bots: [] }), { status: 200 });+ }) as unknown as typeof fetch;++ const sockets: FakeSocket[] = [];+ const logger = stubLogger();+ const daemon = await createDaemon({+ machineKey: "cmk_enroll_text_error",+ serverUrl: "http://localhost:9999",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as any,+ runtimeReport: [{ id: "codex" }],+ driverFor: () => fullFakeDriver("codex"),+ capabilities: [],+ logger,+ });+ sockets[0].emit("open");+ sockets[0].emit("message", JSON.stringify({ type: "bot:added", botId: "bot_text", name: "Bot Text" }));+ sockets[0].emit(+ "message",+ JSON.stringify({+ type: "agent:wake",+ agentId: "bot_text",+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l_text",+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },+ }),+ );+ await new Promise((r) => setTimeout(r, 20));++ expect(+ logger.calls.warn.some(([, m, d]) => {+ const err = String((d[0] as any).err);+ return m === "agent enroll failed" && err.includes("503") && err.includes("upstream overloaded");+ }),+ ).toBe(true);+ await daemon.stop();+ });+it("calls resync-wakes with the machine key bearer on open and logs the woken count", async () => {global.fetch = vi.fn(async (url: string | URL, init?: RequestInit) => {const href = String(url);@@ -657,7 +699,7 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connectiagentId: "bot_1",config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },}),);// Let enroll + spawn resolve, then land the runtime handshake so the FSM@@ -684,32 +726,11 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connecti});describe("deriveAuditLogSubcommand", () => {- it("maps the CLI's bare /api/* pathnames to their subcommand suffix", () => {- expect(deriveAuditLogSubcommand("/api/send")).toBe("send");- expect(deriveAuditLogSubcommand("/api/read")).toBe("read");- expect(deriveAuditLogSubcommand("/api/inboxPull")).toBe("inboxPull");- expect(deriveAuditLogSubcommand("/api/inboxSnapshot")).toBe("inboxSnapshot");- expect(deriveAuditLogSubcommand("/api/listChannels")).toBe("listChannels");- expect(deriveAuditLogSubcommand("/api/listServers")).toBe("listServers");- expect(deriveAuditLogSubcommand("/api/listMembers")).toBe("listMembers");- expect(deriveAuditLogSubcommand("/api/joinServer")).toBe("joinServer");- expect(deriveAuditLogSubcommand("/api/resolve")).toBe("resolve");- expect(deriveAuditLogSubcommand("/api/reactAdd")).toBe("reactAdd");- });-- it("maps the rewritten /api/community/* pathnames identically", () => {- // The proxy's rewriteAgentPath fires AFTER onProxyRequest, so the sighting- // may carry either shape depending on how the CLI called in. Both the flat- // client path and the post-rewrite /api/community/* path must derive to the- // same subcommand string. (The legacy /api/community/agent/* form is still- // normalized too, for any in-flight path.)- expect(deriveAuditLogSubcommand("/api/community/send")).toBe("send");- expect(deriveAuditLogSubcommand("/api/community/inboxPull")).toBe("inboxPull");- expect(deriveAuditLogSubcommand("/api/community/reactAdd")).toBe("reactAdd");- expect(deriveAuditLogSubcommand("/api/community/agent/send")).toBe("send");- });-- it("returns null for `ack` (dropped — paired with inboxPull, no user intent)", () => {+ it("does not normalize deleted flat or legacy-agent inputs", () => {+ expect(deriveAuditLogSubcommand("/api/send")).toBe(null);+ expect(deriveAuditLogSubcommand("/api/attachmentUpload?target=/x/y")).toBe(null);+ expect(deriveAuditLogSubcommand("/api/community/send")).toBe(null);+ expect(deriveAuditLogSubcommand("/api/community/agent/send")).toBe(null);expect(deriveAuditLogSubcommand("/api/ack")).toBe(null);expect(deriveAuditLogSubcommand("/api/community/agent/ack")).toBe(null);});@@ -718,6 +739,60 @@ describe("deriveAuditLogSubcommand", () => {expect(deriveAuditLogSubcommand("/health")).toBe(null);expect(deriveAuditLogSubcommand("/")).toBe(null);});++ it("maps the canonical id-in-path door shapes back to the logical verb (route/disc retarget)", () => {+ // Without this, slicing the first segment would log the DOOR (`channels` /+ // `messages`), losing which action the bot invoked in the cli_invocation row.+ // Messages door is dual-verb — method disambiguates read vs send.+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages", "POST")).toBe("send");+ expect(deriveAuditLogSubcommand("/api/community/channels/abc123/messages", "POST")).toBe("send");+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages", "GET")).toBe("read");+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages?ref=%2Fs%2Fg", "GET")).toBe("read");+ // message-keyed write doors.+ expect(deriveAuditLogSubcommand("/api/community/messages/resolve/reactions/%F0%9F%91%8D", "PUT")).toBe("reactAdd");+ // seq→id lookup (folded resolve).+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/messages/seq/42", "GET")).toBe("resolve");+ // single-message hydrate door GET messages/{id} = the folded `resolve` verb.+ expect(deriveAuditLogSubcommand("/api/community/messages/resolve?ref=%2Fs%2Fg&seq=42", "GET")).toBe("resolve");+ expect(deriveAuditLogSubcommand("/api/community/messages/m1", "GET")).toBe("resolve");+ // hydrate door must not shadow the write sub-paths.+ expect(deriveAuditLogSubcommand("/api/community/messages/m1/reactions/x", "PUT")).toBe("reactAdd");+ // members door (folded channelMember).+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/members?ref=%2Fs%2Fg", "GET")).toBe("channelMember");+ expect(deriveAuditLogSubcommand("/api/community/channels/c1/members", "GET")).toBe("channelMember");+ // server-scoped list doors (轴3 fold): servers/{id}/members = listMembers;+ // servers/{id}/channels + servers/channels (all-servers collection) = listChannels.+ expect(deriveAuditLogSubcommand("/api/community/servers/resolve/members?server=studio", "GET")).toBe("listMembers");+ expect(deriveAuditLogSubcommand("/api/community/servers/srv_1/members", "GET")).toBe("listMembers");+ expect(deriveAuditLogSubcommand("/api/community/servers/resolve/channels?server=studio", "GET")).toBe("listChannels");+ expect(deriveAuditLogSubcommand("/api/community/servers/srv_1/channels", "GET")).toBe("listChannels");+ expect(deriveAuditLogSubcommand("/api/community/servers/channels", "GET")).toBe("listChannels");+ // friends bucket doors (轴3 fold): accepted + pending map back to listFriends+ // (the bot's `alook friend list` fans out to both). blocked is bot-403 → not mapped.+ expect(deriveAuditLogSubcommand("/api/community/friends/accepted", "GET")).toBe("listFriends");+ expect(deriveAuditLogSubcommand("/api/community/friends/pending", "GET")).toBe("listFriends");+ // friend-request door (friendRequest fold): POST friends/request maps back to+ // `friendRequest`, not the `friends` segment (audit is daemon/proxy = bot path).+ expect(deriveAuditLogSubcommand("/api/community/friends/request", "POST")).toBe("friendRequest");+ // inbox bucket doors (轴3 fold): users/me/inbox/{pull,snapshot} map back to+ // the logical verb, not the `users` segment.+ expect(deriveAuditLogSubcommand("/api/community/users/me/inbox/pull", "POST")).toBe("inboxPull");+ expect(deriveAuditLogSubcommand("/api/community/users/me/inbox/snapshot", "GET")).toBe("inboxSnapshot");+ // ack is the advance op of the trinity but writes NO audit row here (re-homed+ // to the daemon reborn-ready signal) — null, same as flat /ack, NOT `users`.+ expect(deriveAuditLogSubcommand("/api/community/users/me/inbox/ack", "POST")).toBe(null);+ // bot-self lifecycle door (bots/me/*): nap maps back to `nap`, not `bots`.+ expect(deriveAuditLogSubcommand("/api/community/bots/me/nap", "POST")).toBe("nap");+ // attachments door (attachments fold): channels/{id}/attachments = upload,+ // channels/{id}/attachments/{attachmentId} = download. Map back to the+ // logical verb, not the `channels` door segment. Download shape (has the+ // sub-segment) must win over the bare-upload shape.+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/attachments", "POST")).toBe("attachmentUpload");+ expect(deriveAuditLogSubcommand("/api/community/channels/c1/attachments", "POST")).toBe("attachmentUpload");+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/attachments?target=%2Fs%2Fg", "POST")).toBe("attachmentUpload");+ expect(deriveAuditLogSubcommand("/api/community/channels/resolve/attachments/att_1", "GET")).toBe("attachmentDownload");+ expect(deriveAuditLogSubcommand("/api/community/channels/c1/attachments/att_1", "GET")).toBe("attachmentDownload");+ });});describe("emitImplicitTypingStopOnSend", () => {diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 3880f1cc4..f250b94cc 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -13,11 +13,8 @@* (Bearer `cmk_`) → per-agent runner key (`crk_`).* 3. credential proxy (http): validates agent vouchers, swaps in runner* keys, stamps X-Agent-Id, and forwards to the server's data plane.- * All agent traffic flows through here. The agent-facing catalog is- * `/api/{inboxPull,ack,send,read,resolve,listServers,listChannels,- * listMembers,channelMember,joinServer,reactAdd,attachmentUpload,- * attachmentDownload,friendRequest,listFriends}` (rewritten to- * `/api/community/agent/*` — see `rewriteAgentPath` in credentialProxy.ts).+ * All agent traffic flows through canonical `/api/community/*` REST+ * doors; the deleted flat `/api/<verb>` catalog is rejected by the proxy.** It is agnostic on both axes:* - whether the server is a real Alook server or a local `wrangler dev`@@ -128,28 +125,74 @@ export function createRuntimeRawLineTap(args: {/*** Derive the audit-log `cli_invocation` subcommand from a proxy request- * pathname. The credential proxy rewrites the CLI's bare `/api/*` calls onto- * `/api/community/agent/*` (see `rewriteAgentPath` in credentialProxy.ts) —- * but the sighting fires BEFORE that rewrite runs (against the inbound- * pathname), so we may see either shape here.+ * pathname. The CLI calls canonical `/api/community/*` REST doors directly;+ * the proxy preserves that pathname unchanged.*- * `/api/ack` is a paired sibling of `inboxPull` with no user intent, so it's- * dropped (returns `null`). Anything else outside the `/api/*` prefix returns- * `null` too — the proxy is generic and could carry non-audit traffic in the- * future.+ * Canonical `users/me/inbox/ack` is the advance sibling of `inboxPull` with no+ * user intent, so it is dropped (returns `null`). Anything outside recognized+ * canonical shapes returns `null` too — the proxy is generic and could carry+ * non-audit traffic in the future.*/-export function deriveAuditLogSubcommand(pathname: string): string | null {- // Normalize both the pre-rewrite client path (`/api/<verb>`) and the- // post-rewrite upstream path (`/api/community/<verb>`, plans/22 §9 — the old- // `/api/community/agent/` tree is gone) down to `/api/<verb>` before slicing.- const stripped = pathname- .replace(/^\/api\/community\/agent\//, "/api/")- .replace(/^\/api\/community\//, "/api/");- if (!stripped.startsWith("/api/")) return null;- const sub = stripped.slice("/api/".length).split("/")[0]?.split("?")[0] ?? "";- if (!sub) return null;- if (sub === "ack") return null;- return sub;+export function deriveAuditLogSubcommand(pathname: string, method?: string): string | null {+ // Route/disc retarget: several flat verbs now hit the canonical id-in-path+ // door (`channels/{id}/messages`, `messages/{id}/reactions/…`) instead of+ // `/api/<verb>`. Slicing the first segment of those would log the DOOR name+ // (`channels`/`messages`) instead of the logical verb the bot invoked, so the+ // `cli_invocation` audit row would lose which action ran. Map the canonical+ // SHAPES back to their verb FIRST, on the canonical `/api/community/…`+ // shape. The messages door is dual-verb — GET is `read`, POST is `send` — so+ // it needs the method; the others are single-verb.+ const canonical = pathname.split("?")[0] ?? pathname;+ if (/^\/api\/community\/messages\/[^/]+\/reactions\//.test(canonical)) return "reactAdd";+ if (/^\/api\/community\/channels\/[^/]+\/messages\/seq\//.test(canonical)) return "resolve";+ if (/^\/api\/community\/channels\/[^/]+\/messages(\/|$)/.test(canonical)) {+ return method === "GET" ? "read" : "send";+ }+ if (/^\/api\/community\/channels\/[^/]+\/members(\/|$)/.test(canonical)) return "channelMember";+ // Attachments door (attachments fold): the flat `attachmentUpload` /+ // `attachmentDownload` verbs fold onto channels/{id}/attachments (POST upload)+ // + channels/{id}/attachments/{attachmentId} (GET download). Map both back so+ // the audit row keeps the logical verb, not the `channels` door segment. The+ // download shape (has the `{attachmentId}` sub-segment) is tested FIRST so the+ // bare-upload shape doesn't swallow it.+ if (/^\/api\/community\/channels\/[^/]+\/attachments\/[^/]+/.test(canonical)) return "attachmentDownload";+ if (/^\/api\/community\/channels\/[^/]+\/attachments(\/|$)/.test(canonical)) return "attachmentUpload";+ // Single-message hydrate door GET messages/{id} = the folded `resolve` verb.+ // AFTER the reactions pattern so that specific sub-path wins.+ if (/^\/api\/community\/messages\/[^/]+$/.test(canonical)) return "resolve";+ // Server-scoped list doors (轴3 fold): GET servers/{id}/members = the folded+ // `listMembers` verb; GET servers/{id}/channels and GET servers/channels (the+ // all-servers collection read) = the folded `listChannels` verb. Map back so+ // the audit row keeps the logical verb, not the `servers` door segment.+ if (/^\/api\/community\/servers\/[^/]+\/members(\/|$)/.test(canonical)) return "listMembers";+ if (/^\/api\/community\/servers\/[^/]+\/channels(\/|$)/.test(canonical)) return "listChannels";+ if (/^\/api\/community\/servers\/channels(\/|$)/.test(canonical)) return "listChannels";+ // Friends bucket doors (轴3 fold): the bot's `listFriends` fans out to+ // GET friends/accepted + GET friends/pending. Map both back to the logical+ // verb so the audit row stays `listFriends`, not the `friends` segment.+ // (/friends/blocked is bot-403 → never reached by a bot, so it needs no map.)+ if (/^\/api\/community\/friends\/(accepted|pending)(\/|$|\?)/.test(canonical)) return "listFriends";+ // friend-request door (friendRequest fold): the bot verb folded onto POST+ // friends/request (dual-actor). Map back to `friendRequest` so the audit row+ // stays the logical verb, not the `friends` segment. (Audit derivation is+ // daemon/proxy-only = bot path; the human arm's own logAudit is untouched.)+ if (/^\/api\/community\/friends\/request(\/|$|\?)/.test(canonical)) return "friendRequest";+ // Inbox trinity doors (轴3 fold): the caller's own inbox pull/snapshot/ack fold+ // into users/me/inbox/{pull,snapshot,ack}. Map back to the logical verb so the+ // audit row stays inboxPull/inboxSnapshot/ack, not the `users` segment. (ack is+ // the advance operation of the fetch↔advance trinity — snapshot=peek /+ // pull=fetch / ack=advance; route/disc Gener #215 乙, relocated with the inbox+ // family, NOT to channels/{id}/read.)+ if (/^\/api\/community\/users\/me\/inbox\/pull(\/|$|\?)/.test(canonical)) return "inboxPull";+ if (/^\/api\/community\/users\/me\/inbox\/snapshot(\/|$|\?)/.test(canonical)) return "inboxSnapshot";+ if (/^\/api\/community\/users\/me\/inbox\/ack(\/|$|\?)/.test(canonical)) return null; // ack writes no audit row here (re-homed to daemon reborn-ready signal)++ // Bot-self lifecycle door (bots/me/*, Blondie #527): nap relocated from the flat+ // /nap to bots/me/nap. Map back to the logical `nap` verb so the audit stays+ // `nap`, not the `bots` segment.+ if (/^\/api\/community\/bots\/me\/nap(\/|$|\?)/.test(canonical)) return "nap";++ return null;}/**@@ -335,8 +378,8 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaonInboxPullResponse: (agentId, messages) => timeline.appendEntryForAgent(agentId, messages),// Bot audit log — Producer B (authoritative for `alook <sub>`). Fires// ONLY on `verdict.ok === true`, before the upstream request is written.- onProxyRequest: (agentId, _method, pathname) => {- const subcommand = deriveAuditLogSubcommand(pathname);+ onProxyRequest: (agentId, method, pathname) => {+ const subcommand = deriveAuditLogSubcommand(pathname, method);if (!subcommand) return;// Producer B: read the same audit context Producer A does so// cli_invocation rows carry launchId (and sessionId once the runtime@@ -531,14 +574,22 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaheaders: { "content-type": "application/json", authorization: `Bearer ${opts.machineKey}` },body: JSON.stringify({ agentId }),});- const json = (await res.json()) as { runnerKey?: string; error?: string };+ const text = await res.text();+ let json: { runnerKey?: string; error?: string } = {};+ if (text) {+ try {+ json = JSON.parse(text) as { runnerKey?: string; error?: string };+ } catch {+ json = {};+ }+ }if (!res.ok || !json.runnerKey) {if (res.status === 404) {throw new UnknownBotError(agentId);}throw new BotEnrollFailedError(agentId,- new Error(json.error ?? `enroll failed (${res.status})`),+ new Error(json.error ?? `enroll failed (${res.status})${text ? `: ${text.slice(0, 512)}` : ""}`),);}enrolledKeys.set(agentId, json.runnerKey);diff --git a/src/daemon/src/drivers/gitIdentityEnv.ts b/src/daemon/src/drivers/gitIdentityEnv.tsindex 2b32b3636..fbfb479c0 100644--- a/src/daemon/src/drivers/gitIdentityEnv.ts+++ b/src/daemon/src/drivers/gitIdentityEnv.ts@@ -39,7 +39,6 @@ const FALLBACK_LOCAL_PART = "alook-agent";* legible remains.*/function sanitizeGitName(name: string): string {- // eslint-disable-next-line no-control-regexreturn name.replace(/[\x00-\x1f\x7f]/g, "").replace(/\s+/g, " ").trim();}diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.tsindex d1ac93cb2..5dbd6f1d2 100644--- a/src/daemon/src/drivers/systemPrompt.test.ts+++ b/src/daemon/src/drivers/systemPrompt.test.ts@@ -58,4 +58,5 @@ describe("buildCliSystemPrompt", () => {const withoutRole = buildCliSystemPrompt(baseConfig);expect(withoutRole).not.toContain("You are the onboarding assistant.");});+});diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 66e669d41..4f778db28 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -119,12 +119,12 @@ function cliCommandsSection(): string {"### Servers","",`1. \`${CLI} server list\` — list your servers.`,- `2. \`${CLI} server member --server <id-or-name>\` — list a server's members.`,+ `2. \`${CLI} server member --server <name#discriminator>\` — list a server's members.`,`3. \`${CLI} server join --invite <link>\` — join via invite link or token.`,"","### Channels","",- `1. \`${CLI} channel list --server <id-or-name>\` — list top-level channels, grouped by ` ++ `1. \`${CLI} channel list --server <name#discriminator>\` — list top-level channels, grouped by ` +`category; each is marked \`public\` or \`private\`.`,`2. \`${CLI} channel history --channel <ref>\` — read a channel's or thread's past messages ` +`(the context you weren't awake for). Page with \`--before N\` / \`--after N\` (seq N as ` +@@ -191,16 +191,24 @@ function messagingSection(): string {"","| Ref | Meaning |","|---|---|",- "| `/<server>/<channel>` | Channel in a server |",- "| `/<server>/<channel>#N` | Message #N in a channel |",- "| `/<server>/<channel>/#N` | Thread rooted at message #N |",- "| `/<server>/<channel>/#N#M` | Message #M inside the thread rooted at #N (react, etc.) |",- "| `/<server>` | A server, no channel |",- "| `/.dm/<peer>` | DM with a user/agent (peer = `name#0042`) |",- "| `/.dm/<peer>#N` | Message #N in a DM |",+ "| /<server>/<channel> | Channel in a server (server = `name#1234`) |",+ "| /<server>/<channel>#N | Message #N in a channel |",+ "| /<server>/<channel>/#N | Thread rooted at message #N |",+ "| /<server>/<channel>/#N#M | Message #M inside the thread rooted at #N (react, etc.) |",+ "| /<server> | A server, no channel |",+ "| /.dm/<peer> | DM with a user/agent (peer = `name#1234`) |",+ "| /.dm/<peer>#N | Message #N in a DM |","","Use the `channel` field from a received message as `--target`. For an in-thread reply, use " +- "the thread ref (`/<server>/<channel>/#N`).",+ "the thread-ref grammar described above.",+ "",+ "Copyable refs must be standalone bare tokens. Examples:",+ "/Alook#1234/chore",+ "/Alook#1234/chore#28",+ "/Alook#1234/chore/#28",+ "/Alook#1234/chore/#28#5",+ "/Alook#1234",+ "/.dm/alice#0042","","### Reading history","",@@ -218,7 +226,7 @@ function messagingSection(): string {"The app auto-renders inline tokens in a message body — channel refs, @mentions, and message " +"refs. Two rules for all of them: a token only renders as a **standalone token** — " +"space-prefixed or at line start (glued to other text it stays literal — including when you " +- "wrap it in brackets like `(/demo/general)`, so leave refs bare, not parenthesized); and " ++ "wrap it in brackets like `(/demo#1234/general)`, so leave refs bare, not parenthesized); and " +"**never wrap it in backticks** — that kills the render. Otherwise write them as bare text.","","- **Channel refs** render as clickable links.",@@ -237,15 +245,15 @@ function messagingSection(): string {"in DMs.","","```bash",- `${CLI} message send --target \"/.dm/alice#0001\" --text \"Check the discussion in /demo/support\"`,- `${CLI} message send --target \"/demo/general\" --text \"@alice#0001 Can you review this? See /demo/general#42\"`,+ `${CLI} message send --target \"/.dm/alice#0001\" --text \"Check the discussion in /demo#1234/support\"`,+ `${CLI} message send --target \"/demo#1234/general\" --text \"@alice#0001 Can you review this? See /demo#1234/general#42\"`,"```","","### Pulled messages","","```json",- '{"seq": "#3", "channel": "/demo/general", "sender": "@gustavo#4821", "content": {"text": "hello"}, "time": "2026-06-01T12:00:00Z"}',- '{"seq": "#42", "channel": "/demo/general", "sender": "@gustavo#4821", "content": {"text": "yes, ship it", "replyTo": {"seq": "#37", "sender": "@ana#0012"}}, "time": "2026-06-01T12:01:00Z"}',+ '{"seq": "#3", "channel": "/demo#1234/general", "sender": "@gustavo#4821", "content": {"text": "hello"}, "time": "2026-06-01T12:00:00Z"}',+ '{"seq": "#42", "channel": "/demo#1234/general", "sender": "@gustavo#4821", "content": {"text": "yes, ship it", "replyTo": {"seq": "#37", "sender": "@ana#0012"}}, "time": "2026-06-01T12:01:00Z"}',"```","","`channel` is the reply ref. `seq` (`#N`) identifies the message within its channel — " +@@ -471,8 +479,8 @@ function workspaceMemorySection(): string {"the work is.","","```md",- '- [ ] {"seq": "#42", "channel": "/demo/general", "sender": "@alice#0001", "content": {"text": "can you pull the latest deploy logs and drop the tail here?"}, "time": "2026-06-01T12:00:00Z"}',- '- [ ] {"seq": "#12", "channel": "/demo/design/#12", "sender": "@alice#0001", "content": {"text": "follow-up — send a screenshot of the before/after"}, "time": "2026-06-01T12:07:00Z"}',+ '- [ ] {"seq": "#42", "channel": "/demo#1234/general", "sender": "@alice#0001", "content": {"text": "can you pull the latest deploy logs and drop the tail here?"}, "time": "2026-06-01T12:00:00Z"}',+ '- [ ] {"seq": "#12", "channel": "/demo#1234/design/#12", "sender": "@alice#0001", "content": {"text": "follow-up — send a screenshot of the before/after"}, "time": "2026-06-01T12:07:00Z"}',"```",].join("\n");}diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex 440bc80f2..fe365ab0f 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -114,11 +114,11 @@ describe("AgentRouter — agent:wake", () => {agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 7 },});expect(registers).toEqual([{ agentId: "a1", sessionId: undefined, launchId: "l1" }]);- expect(delivers).toEqual([{ agentId: "a1", text: "You have unread messages in channel /demo/general.", seq: 7 }]);+ expect(delivers).toEqual([{ agentId: "a1", text: "You have unread messages in channel /demo#1234/general.", seq: 7 }]);expect(wakeAcks).toEqual([{ agentId: "a1", launchId: "l1", status: "ok" }]);});@@ -138,10 +138,10 @@ describe("AgentRouter — agent:wake", () => {agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 7 },});- expect(delivers).toEqual([{ agentId: "a1", text: "custom: /demo/general#7", seq: 7 }]);+ expect(delivers).toEqual([{ agentId: "a1", text: "custom: /demo#1234/general#7", seq: 7 }]);});it("repeated agent:wake commands for the same agent each register + deliver again (no dedup — no deliveryId anymore)", async () => {@@ -155,7 +155,7 @@ describe("AgentRouter — agent:wake", () => {agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 7 },};await fire(wake);await fire(wake);@@ -178,7 +178,7 @@ describe("AgentRouter — agent:wake", () => {agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 7 },});// Diagnostic surfaced (batch B), but the wire ack is still ok — reachability@@ -199,7 +199,7 @@ describe("AgentRouter — agent:wake", () => {agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 7 },});expect(logger.calls.info.some(([m]) => m === NO_EFFECT_DIAG)).toBe(false);@@ -220,7 +220,7 @@ describe("AgentRouter — agent:wake", () => {agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 7 },});expect(logger.calls.info.some(([m]) => m === NO_EFFECT_DIAG)).toBe(false);@@ -528,7 +528,7 @@ describe("AgentRouter — unknown runtime → session.error", () => {agentId: "a1",config: { version: 1, runtime: "gemini", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },});expect(sessionErrors.length).toBe(1);@@ -728,12 +728,12 @@ describe("AgentRouter — logging", () => {agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 7 },});expect(logger.calls.info.some(- ([m, d]) => m === "agent:wake received" && (d[0] as any).agentId === "a1" && (d[0] as any).channel === "/demo/general",+ ([m, d]) => m === "agent:wake received" && (d[0] as any).agentId === "a1" && (d[0] as any).channel === "/demo#1234/general",),).toBe(true);expect(logger.calls.info.some(([m, d]) => m === "agent:wake ack" && (d[0] as any).status === "ok")).toBe(true);@@ -759,7 +759,7 @@ describe("AgentRouter — logging", () => {agentId: "a1",config: { version: 1, runtime: "gemini", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },});expect(logger.calls.info.some(([m, d]) => m === "agent:wake ack" && (d[0] as any).status === "error")).toBe(diff --git a/src/daemon/src/server/contract.test.ts b/src/daemon/src/server/contract.test.tsindex a518ff18f..46e324352 100644--- a/src/daemon/src/server/contract.test.ts+++ b/src/daemon/src/server/contract.test.ts@@ -24,13 +24,13 @@ describe("parseSeq / formatSeq", () => {describe("parseRef", () => {it("parses a plain channel ref", () => {- expect(parseRef("/demo/general")).toEqual({ server: "demo", channel: "general" });+ expect(parseRef("/demo#0042/general")).toEqual({ server: "demo#0042", channel: "general" });});it("parses a message-pinned ref (#N on the channel segment)", () => {- expect(parseRef("/demo/general#12")).toEqual({ server: "demo", channel: "general", seq: 12 });+ expect(parseRef("/demo#0042/general#12")).toEqual({ server: "demo#0042", channel: "general", seq: 12 });});it("parses a thread ref (/server/channel/#N)", () => {- expect(parseRef("/demo/general/#5")).toEqual({ server: "demo", channel: "general", threadRootSeq: 5 });+ expect(parseRef("/demo#0042/general/#5")).toEqual({ server: "demo#0042", channel: "general", threadRootSeq: 5 });});it("parses a DM ref", () => {// No "#" in the segment — legacy/no-discriminator id form, round-trips@@ -55,46 +55,46 @@ describe("parseRef", () => {expect(() => parseRef("demo/general")).toThrow(/must start with/);});it("rejects refs missing a channel segment", () => {- expect(() => parseRef("/demo")).toThrow(/server.*channel/);+ expect(() => parseRef("/demo#0042")).toThrow(/server.*channel/);});it("parses a thread-reply message ref (/server/channel/#N#M)", () => {- expect(parseRef("/demo/general/#5#42")).toEqual({- server: "demo",+ expect(parseRef("/demo#0042/general/#5#42")).toEqual({+ server: "demo#0042",channel: "general",threadRootSeq: 5,seq: 42,});});it("throws on empty seq tail (#5#)", () => {- expect(() => parseRef("/demo/general/#5#")).toThrow();+ expect(() => parseRef("/demo#0042/general/#5#")).toThrow();});it("throws on empty root (##5)", () => {- expect(() => parseRef("/demo/general/##5")).toThrow();+ expect(() => parseRef("/demo#0042/general/##5")).toThrow();});it("throws on non-numeric seq (#5#abc)", () => {- expect(() => parseRef("/demo/general/#5#abc")).toThrow();+ expect(() => parseRef("/demo#0042/general/#5#abc")).toThrow();});it("throws on three-token tail (#5#42#7)", () => {- expect(() => parseRef("/demo/general/#5#42#7")).toThrow();+ expect(() => parseRef("/demo#0042/general/#5#42#7")).toThrow();});it("stays permissive on #0#5 (server rejects root 0)", () => {- expect(parseRef("/demo/general/#0#5")).toEqual({- server: "demo",+ expect(parseRef("/demo#0042/general/#0#5")).toEqual({+ server: "demo#0042",channel: "general",threadRootSeq: 0,seq: 5,});});it("stays permissive on #5#0 (server rejects seq 0)", () => {- expect(parseRef("/demo/general/#5#0")).toEqual({- server: "demo",+ expect(parseRef("/demo#0042/general/#5#0")).toEqual({+ server: "demo#0042",channel: "general",threadRootSeq: 5,seq: 0,});});it("throws on slashless form with trailing #M", () => {- expect(() => parseRef("/demo/general#5#42")).toThrow();+ expect(() => parseRef("/demo#0042/general#5#42")).toThrow();});it("parses a DM thread-reply message ref (server rejects DM threads elsewhere)", () => {expect(parseRef("/.dm/gusye#1231/#5#42")).toEqual({@@ -108,26 +108,26 @@ describe("parseRef", () => {describe("formatRef", () => {it("formats a plain channel ref", () => {- expect(formatRef({ server: "demo", channel: "general" })).toBe("/demo/general");+ expect(formatRef({ server: "demo#0042", channel: "general" })).toBe("/demo#0042/general");});it("formats a thread ref", () => {- expect(formatRef({ server: "demo", channel: "general", threadRootSeq: 5 })).toBe("/demo/general/#5");+ expect(formatRef({ server: "demo#0042", channel: "general", threadRootSeq: 5 })).toBe("/demo#0042/general/#5");});it("round-trips channel refs through parse→format", () => {- const ref = "/demo/general";+ const ref = "/demo#0042/general";const p = parseRef(ref);expect(formatRef(p)).toBe(ref);});it("formats a thread-reply message ref", () => {- expect(formatRef({ server: "demo", channel: "general", threadRootSeq: 5, seq: 42 })).toBe(- "/demo/general/#5#42",+ expect(formatRef({ server: "demo#0042", channel: "general", threadRootSeq: 5, seq: 42 })).toBe(+ "/demo#0042/general/#5#42",);});it("round-trips a thread-reply message ref", () => {- const input = { server: "demo", channel: "general", threadRootSeq: 5, seq: 42 };+ const input = { server: "demo#0042", channel: "general", threadRootSeq: 5, seq: 42 };expect(parseRef(formatRef(input))).toEqual(input);});it("throws when seq is provided without threadRootSeq", () => {- expect(() => formatRef({ server: "demo", channel: "general", seq: 42 })).toThrow();+ expect(() => formatRef({ server: "demo#0042", channel: "general", seq: 42 })).toThrow();});});diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.tsindex d85b8321f..c33cc5e68 100644--- a/src/daemon/src/server/wsControlChannel.test.ts+++ b/src/daemon/src/server/wsControlChannel.test.ts@@ -426,7 +426,7 @@ describe("WsControlChannel — downlink HostCommand validation (convergence #6)"launchId: "launch_1",unreadNotice: {kind: "unread_notice",- channel: "/demo/general",+ channel: "/demo#1234/general",latestSeq: 42,channelId: "chan_xyz",},diff --git a/src/daemon/src/server/wsControlServer.test.ts b/src/daemon/src/server/wsControlServer.test.tsindex 6e0a14d81..dea229918 100644--- a/src/daemon/src/server/wsControlServer.test.ts+++ b/src/daemon/src/server/wsControlServer.test.ts@@ -38,7 +38,7 @@ const sampleWakeCommand: HostCommand = {agentId: "agent1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },launchId: "launch1",- unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },};describe("WsControlServer — machine-key auth on connect", () => {diff --git a/src/daemon/src/util/rotatingFileSink.test.ts b/src/daemon/src/util/rotatingFileSink.test.tsindex 385bf82b8..fe866849b 100644--- a/src/daemon/src/util/rotatingFileSink.test.ts+++ b/src/daemon/src/util/rotatingFileSink.test.ts@@ -73,15 +73,18 @@ describe("createRotatingFileSink (batch E1 — bounded default trace backing)",it("keeps secure mode on both active and rotated generations", () => {const path = join(dir, "runtime-raw-events-a1.jsonl");+ const rotatedPath = `${path}.1`;const sink = createRotatingFileSink(path, 20, { mode: 0o600 });sink.write("a".repeat(20));sink.write("latest");+ expect(readFileSync(path, "utf8")).toBe("latest\n");+ expect(readFileSync(rotatedPath, "utf8")).toBe(`${"a".repeat(20)}\n`);expectSecureMode(path, 0o600);// Rotated `.1` keeps the prior active's mode on POSIX; Windows mode bits// are not meaningful after rename, so only assert the active path there.if (process.platform !== "win32") {- expect(statSync(`${path}.1`).mode & 0o777).toBe(0o600);+ expectSecureMode(rotatedPath, 0o600);}});diff --git a/src/shared/package.json b/src/shared/package.jsonindex 370c8ddf6..9e7f60d1b 100644--- a/src/shared/package.json+++ b/src/shared/package.json@@ -26,7 +26,9 @@},"devDependencies": {"@cloudflare/workers-types": "^4.20260702.1",+ "@types/better-sqlite3": "^7.6.13","@types/node": "^25.9.4",+ "better-sqlite3": "^12.11.1","knip": "^6.29.0","playwright-core": "^1.61.1","typescript": "^6.0.3",diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 07af63c4f..7e944f32a 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -26,6 +26,7 @@ import { z } from "zod";import type { RuntimeConfig } from "./runtime-config";import type { ChannelType, StoredChannelType } from "./utils/community-roles";import { CHANNEL_TRAITS } from "./utils/community-roles";+import { parseNameAndTag } from "./lib/discriminator";/* ------------------------------------------------------------------ *//* Identifiers */@@ -64,8 +65,7 @@ export interface Agent {/** A server == a workspace. An agent participates in many of these. */export interface Server {- id: ServerId;- name: string;+ handle: string;}export type ChannelKind = "channel" | "dm";@@ -154,7 +154,7 @@ export type Target =* The flat, agent-facing message. This is exactly what the agent sees (one JSON* object per line, JSONL). Deliberately minimal:* - `seq` — "#N", the per-channel sequence (locate via channel + seq).- * - `channel` — the path ref, e.g. "/demo-workspace/general" or "/.dm/gustavo#4821".+ * - `channel` — the path ref, e.g. "/demo-workspace#1234/general" or "/.dm/gustavo#4821".* - `sender` — "@handle" (`name#0042`, no id, no human/agent/system type).* - `content` — `{ text }` today; an object (not a bare string) so future* content kinds (attachments, embeds, …) can be added without@@ -381,10 +381,10 @@ export interface CommunityAgentReactAddResponse {/*** Create a new forum post (`alook message post`). `forum` is a forum REF* (`/server/forum`), resolved server-side (bots hold refs, not ids — same reason- * `send` takes a ref). `title` is the raw human title; its slug becomes the- * post's addressing name. Content follows the forum-post opener contract: text- * OR at least one attachment. `attachments` are pending ids the bot uploaded- * bound to the FORUM (the post channel doesn't exist at upload time).+ * `send` takes a ref). The canonical messages door stores `title` as an opener+ * message in the forum and `content` as the first reply in its ordinary thread.+ * The reply may contain text OR at least one attachment. `attachments` are+ * pending ids the bot uploaded against the forum before the thread exists.*/export interface CreatePostRequest {agentId: AgentId;@@ -397,9 +397,8 @@ export interface CreatePostRequest {}/**- * The created post's canonical address. `ref` is the round-trippable- * `/server/forum/<real-slug>` (the slug after create-time dedupe/bump) — the bot- * hands it straight back as a target. `seq` is the body (first-message) seq.+ * The created thread's canonical address. `ref` is `/server/forum/#N`, where+ * `N` is the opener message seq; `seq` is the first reply's seq in that thread.*/export interface CreatePostResponse {ref: ChannelRef;@@ -1102,20 +1101,10 @@ export interface ServerApiError {/** A parsed channel ref: the channel location + an optional message seq (`#N`). */export interface ParsedRef {- /** Server segment (a real server id/name, or `.dm`). */+ /** Server segment (a real server id/handle, or `.dm`). */server: string;/** Channel name (or DM peer when `server === DM_SERVER`). */channel: string;- /**- * Forum-post child-channel name when the ref addresses a forum post- * (`/server/forum/post`). A forum post is a `forum_post` child channel with- * no addressable root-message seq (unlike a thread), so it is anchored by its- * OWN name under the parent forum — `channel` is the forum, `childChannelName`- * is the post. May carry a `seq` (`/server/forum/post#N`) to pin a message- * inside the post, symmetric to the top-level `/server/channel#N` form.- * Mutually exclusive with `threadRootSeq`.- */- childChannelName?: string;/** Thread root seq when the ref points into a thread (`/server/channel/#N`). */threadRootSeq?: Seq;/** Message seq when the ref pins a specific message (`/server/channel#N`). */@@ -1126,7 +1115,6 @@ export interface ParsedRef {* Parse a path ref into its parts. Grammar:* /<server>/<channel> → { server, channel }* /<server>/<channel>#N → { server, channel, seq:N }- * /<server>/<forum>/<post> → { server, channel:forum, childChannelName:post }* /<server>/<channel>/#N → { server, channel, threadRootSeq:N }* /<server>/<channel>/#N#M → { server, channel, threadRootSeq:N, seq:M }* /.dm/<peer>[...] → DM (server = ".dm", channel = peer, a@@ -1135,6 +1123,14 @@ export interface ParsedRef {* generic channel-ref `#`-split (a handle's* `#0042` suffix must NOT be mistaken for a* pinned-message seq).+ *+ * (The old `/<server>/<forum>/<post>` forum-post form is GONE, not merely+ * unsupported — a post is now addressed like any other thread, by-root-seq.+ * A 3-segment ref whose last segment doesn't start with "#" no longer+ * matches any grammar rule below and throws, same as any other malformed+ * ref; callers already render an unparseable ref as plain literal text+ * rather than a clickable pill, so an old-style link degrades cleanly+ * instead of silently resolving to the wrong target.)*/export function parseRef(ref: ChannelRef): ParsedRef {if (!ref.startsWith("/")) throw new Error(`ref must start with "/": ${ref}`);@@ -1142,6 +1138,9 @@ export function parseRef(ref: ChannelRef): ParsedRef {const parts = body.split("/");if (parts.length < 2) throw new Error(`ref needs /<server>/<channel>: ${ref}`);const server = parts[0];+ if (server !== DM_SERVER && !parseNameAndTag(server)) {+ throw new Error(`server ref must use a name#discriminator handle: ${ref}`);+ }// Trailing "#N" on the last segment pins a message seq.let seq: Seq | undefined;@@ -1153,25 +1152,11 @@ export function parseRef(ref: ChannelRef): ParsedRef {return { server, channel: parts[1], ...tail };}- // Forum-post form: /server/forum/post — exactly 3 segments, third NOT- // starting with "#" (that's the thread form above). The post is anchored by- // its own name under the parent forum. An optional trailing "#N" pins a- // message seq WITHIN the post (`/server/forum/post#N`), symmetric to the- // top-level message form `/server/channel#N` — used by `message emoji` to- // react to a specific message inside a post. A 4th path segment is not- // addressable today — reject rather than silently truncate.+ // Any other 3+ segment shape (the old forum-post form's territory) no+ // longer names a valid ref — reject rather than silently truncate to the+ // first two segments.if (parts.length >= 3 && server !== DM_SERVER) {- if (parts.length > 3) {- throw new Error(`ref has too many segments: ${ref}`);- }- const postSeg = parts[2];- const hashIdx = postSeg.indexOf("#");- if (hashIdx >= 0) {- const postName = postSeg.slice(0, hashIdx);- if (!postName) throw new Error(`forum-post ref missing post name: ${ref}`);- return { server, channel: parts[1], childChannelName: postName, seq: parseSeq(postSeg.slice(hashIdx)) };- }- return { server, channel: parts[1], childChannelName: postSeg };+ throw new Error(`ref has too many segments: ${ref}`);}const chSeg = parts[1];@@ -1189,7 +1174,7 @@ export function parseRef(ref: ChannelRef): ParsedRef {if (lastHash < 0) return { server, channel: chSeg };const firstHash = chSeg.indexOf("#");const tail = chSeg.slice(lastHash + 1);- const isBareHandle = firstHash === lastHash && /^\d{4}$/.test(tail);+ const isBareHandle = firstHash === lastHash && /^\d{4,}$/.test(tail);if (isBareHandle) return { server, channel: chSeg };// A non-numeric tail after the last `#` isn't a valid seq — rather// than throwing (which crashes every caller not wrapped in@@ -1240,35 +1225,23 @@ function parseThreadTail(segment: string): { threadRootSeq: Seq; seq?: Seq } {/*** Format a ParsedRef back to a path ref. Valid combinations:* {} → /server/channel- * { childChannelName } → /server/channel/childChannelName (forum post)- * { childChannelName, seq } → /server/channel/childChannelName#N (msg in a post)* { threadRootSeq } → /server/channel/#N* { threadRootSeq, seq } → /server/channel/#N#M- * A bare `seq` (neither `threadRootSeq` nor `childChannelName`) is NOT- * supported — the top-level message form `/server/channel#N` puts `#N` on the- * channel segment, not on a trailing path segment, and no caller needs to emit- * that shape via formatRef today. `childChannelName` (forum post) is mutually- * exclusive with `threadRootSeq`, but MAY carry a `seq` to pin a message inside- * the post (`/server/forum/post#N`), symmetric to the top-level message form.+ * A bare `seq` (without `threadRootSeq`) is NOT supported — the top-level+ * message form `/server/channel#N` puts `#N` on the channel segment, not on+ * a trailing path segment, and no caller needs to emit that shape via+ * formatRef today.*/export function formatRef(p: {server: string;channel: string;- childChannelName?: string;threadRootSeq?: Seq;seq?: Seq;}): ChannelRef {- if (p.childChannelName !== undefined && p.threadRootSeq !== undefined) {- throw new Error("formatRef: childChannelName is mutually exclusive with threadRootSeq");- }- if (p.seq !== undefined && p.threadRootSeq === undefined && p.childChannelName === undefined) {- throw new Error("formatRef: seq without threadRootSeq or childChannelName is not supported");+ if (p.seq !== undefined && p.threadRootSeq === undefined) {+ throw new Error("formatRef: seq without threadRootSeq is not supported");}const base = `/${p.server}/${p.channel}`;- if (p.childChannelName !== undefined) {- const postBase = `${base}/${p.childChannelName}`;- return p.seq === undefined ? postBase : `${postBase}#${p.seq}`;- }if (p.threadRootSeq === undefined) return base;if (p.seq === undefined) return `${base}/#${p.threadRootSeq}`;return `${base}/#${p.threadRootSeq}#${p.seq}`;@@ -1296,11 +1269,11 @@ export function formatRef(p: {*/export type CanonicalRefScope = {type: StoredChannelType;- /** Server display name (channel arm). Absent/irrelevant for a DM. */- serverName?: string;- /** The channel's own stored name — the top-level channel or the post slug. */+ /** Server handle (channel arm). Absent/irrelevant for a DM. */+ serverHandle?: string;+ /** The channel's own stored name — the top-level channel's name. */name?: string;- /** Parent forum/channel display name — for by-child-name / by-root-seq. */+ /** Parent channel display name — for by-root-seq. */parentName?: string;/** Thread root message seq — for by-root-seq. */rootSeq?: Seq;@@ -1313,19 +1286,13 @@ export function formatCanonicalRef(scope: CanonicalRefScope): ChannelRef | nullswitch (addressing) {case "by-server-name": {// Top-level channel/forum: `/server/<name>`.- if (scope.serverName === undefined || scope.name === undefined) return null;- return formatRef({ server: scope.serverName, channel: scope.name });- }- case "by-child-name": {- // Forum post: `/server/<forum>/<post-slug>` — anchored on its own name- // under the parent forum.- if (scope.serverName === undefined || scope.parentName === undefined || scope.name === undefined) return null;- return formatRef({ server: scope.serverName, channel: scope.parentName, childChannelName: scope.name });+ if (scope.serverHandle === undefined || scope.name === undefined) return null;+ return formatRef({ server: scope.serverHandle, channel: scope.name });}case "by-root-seq": {// Thread: `/server/<parent-channel>/#<rootSeq>`.- if (scope.serverName === undefined || scope.parentName === undefined || scope.rootSeq === undefined) return null;- return formatRef({ server: scope.serverName, channel: scope.parentName, threadRootSeq: scope.rootSeq });+ if (scope.serverHandle === undefined || scope.parentName === undefined || scope.rootSeq === undefined) return null;+ return formatRef({ server: scope.serverHandle, channel: scope.parentName, threadRootSeq: scope.rootSeq });}case "by-peer-identity": {// DM: `/.dm/<peer#0042>`.diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex b8df761ee..91e0bb1bb 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -74,6 +74,16 @@ export type CommunityMessageUpdated = {approval: FriendApprovalPayload}+export type CommunityMessageEdited = {+ type: "community:message.edited"+ channelId: string+ messageId: string+ content: string+ // Present only when this message is the child channel's opener. Consumers+ // use it to refresh the parent forum/thread summary; ordinary replies omit it.+ parentChannelId?: string+}+export type CommunityReactionAdd = {type: "community:reaction.add"channelId: string@@ -130,7 +140,7 @@ export type CommunityTypingStop = {discriminator?: string}-// ── Child channel events (threads + forum posts) ─────────────────────────────+// ── Child channel events (threads) ────────────────────────────────────────────export type CommunityChildChannelCreate = {type: "community:channel.child_create"@@ -138,7 +148,7 @@ export type CommunityChildChannelCreate = {channel: {id: stringname: string- type: "thread" | "forum_post"+ type: "thread"creatorId?: stringcreatedAt: string}@@ -200,7 +210,6 @@ export type CommunityChannelUpdate = {topic?: stringcategoryId?: string | nulltype?: ChannelType- forumTags?: string | null}}@@ -208,11 +217,10 @@ export type CommunityChannelDelete = {type: "community:channel.delete"serverId: stringchannelId: string- // The parent forum/thread channel, when the deleted channel is a child- // (forum_post / thread). Lets clients invalidate the parent's post/thread- // list so the deleted card disappears from the feed. Optional and additive —- // older events without it still work (the handler simply skips the parent- // invalidate).+ // The parent channel, when the deleted channel is a child (thread). Lets+ // clients invalidate the parent's post/thread list so the deleted card+ // disappears from the feed. Optional and additive — older events without+ // it still work (the handler simply skips the parent invalidate).parentChannelId?: string | null}@@ -433,7 +441,7 @@ export type CommunityUnreadBump = {serverId?: string/*** The sidebar-locatable channel row = `parentChannelId ?? channelId`, computed- * server-side. A thread/forum-post message has no independent sidebar row, so+ * server-side. A child-thread message has no independent sidebar row, so* its dot must light the PARENT channel's row; a plain channel is its own row.* Absent → client falls back to `channelId`.*/@@ -579,6 +587,7 @@ export type CommunityBotHostFrame = BotAddedFrame | BotUpdatedFrame | BotRemovedexport type CommunityWsEvent =| CommunityMessageCreate| CommunityMessageUpdated+ | CommunityMessageEdited| CommunityReactionAdd| CommunityReactionRemove| CommunityPinAdd@@ -627,6 +636,7 @@ export function isCommunityEvent(msg: { type: string }): msg is CommunityWsEventexport const WS_EVENTS = {MESSAGE_CREATE: "community:message.create",MESSAGE_UPDATED: "community:message.updated",+ MESSAGE_EDITED: "community:message.edited",REACTION_ADD: "community:reaction.add",REACTION_REMOVE: "community:reaction.remove",PIN_ADD: "community:pin.add",diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.tsindex 0d08bb9d7..6c661b54e 100644--- a/src/shared/src/constants/community.ts+++ b/src/shared/src/constants/community.ts@@ -147,8 +147,8 @@ export function normalizeNotifLevel(input: string): NotificationLevelValue {return "all"}-// Participant `source` — how a user joined a thread/forum-post's participant-// (notify) set: an `@`-mention, having spoken in it, or explicitly added.+// Participant `source` — how a user joined a child thread's notify set: an+// `@`-mention, having spoken in it, or explicitly added.// Anchors `community_channel_member.source` / thread-participant `source`.// Single value source for the literals; `ThreadParticipantSource`// (queries/community/thread.ts) derives from this via const-assert so the twodiff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex ef86d1c64..bd8d139bc 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -17,16 +17,33 @@ import { user } from "./schema";// ---------------------------------------------------------------------------// 1. community_server-export const communityServer = sqliteTable("community_server", {- id: text("id").primaryKey().$defaultFn(() => nanoid()),- name: text("name").notNull(),- description: text("description").default(""),- icon: text("icon"),- ownerId: text("owner_id")- .notNull()- .references(() => user.id, { onDelete: "restrict" }),- createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),-});+export const communityServer = sqliteTable(+ "community_server",+ {+ id: text("id").primaryKey().$defaultFn(() => nanoid()),+ name: text("name").notNull(),+ discriminator: text("discriminator").notNull().default("0000"),+ description: text("description").default(""),+ icon: text("icon"),+ ownerId: text("owner_id")+ .notNull()+ .references(() => user.id, { onDelete: "restrict" }),+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ (t) => [+ // Unique server handle `name#discriminator` — the server-segment address+ // anchor, so a ref `/name#disc/...` resolves to exactly one server. Mirrors+ // the user `(name, discriminator)` handle. Source of truth:+ // migration 0079_community_server_discriminator.sql. NOCASE on `name` there+ // so the DB ruler folds identically to resolveServerByNameForMember's+ // `COLLATE NOCASE` lookup (the index/resolver alignment migration 0075+ // established for top-level channel names). Plain `.on()` here can't express+ // COLLATE — the migration is authoritative. No `deletedAt` clause: servers+ // are not soft-deleted (community_server has no deletedAt column), unlike the+ // user index's partial `WHERE deletedAt IS NULL` (0055).+ uniqueIndex("idx_community_server_name_discriminator").on(t.name, t.discriminator),+ ]+);// 2. community_categoryexport const communityCategory = sqliteTable(@@ -45,8 +62,8 @@ export const communityCategory = sqliteTable();// 3. community_channel-// `type`: text | forum | forum_post | thread | dm. DMs have server_id + name-// NULL (no server, no name); their two participants are relation='access'+// `type`: text | forum | thread | dm. DMs have server_id + name NULL (no+// server, no name); their two participants are relation='access'// community_channel_member rows.export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable("community_channel",@@ -61,18 +78,7 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(name: text("name"),type: text("type").notNull().default("text"),topic: text("topic").default(""),- // Display-only original title of a forum post, captured verbatim BEFORE- // `slugify` lossily derives `name` (the addressing slug). `name` stays the- // single addressing identity; `display_title` only preserves the- // human-readable original ("Q3 planning / roadmap", not- // "q3-planning-roadmap") so a future "title as body-heading" render can use- // it. NEVER an addressing axis: no resolve-by-name reads it, no unique index,- // duplicates are legal, and it does NOT participate in slug dedupe/bump.- // Nullable — only forum_post CREATE writes it; threads / top-level channels /- // legacy rows leave it null.- displayTitle: text("display_title"),position: integer("position").default(0),- forumTags: text("forum_tags"), // JSONparentChannelId: text("parent_channel_id").references(() => communityChannel.id, {onDelete: "cascade",}),@@ -88,26 +94,11 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(index("idx_channel_server_last_message").on(t.serverId, t.lastMessageAt),index("idx_channel_parent").on(t.parentChannelId),// Partial unique — top-level channel names are unique per server.- // Source of truth: migration 0057_channel_unique_name.sql. Threads and- // forum posts (parent_channel_id NOT NULL) are exempt by design.+ // Source of truth: migration 0057_channel_unique_name.sql. Threads+ // (parent_channel_id NOT NULL) are exempt by design.uniqueIndex("idx_channel_server_name").on(t.serverId, t.name).where(sql`parent_channel_id IS NULL`),- // Partial unique — a forum post's slug (`name`) is its addressing anchor- // (`/server/forum/<slug>`), so it must be unique WITHIN its parent forum or- // resolve-by-name goes ambiguous and read/send/ack on the post break. Scoped- // to `type='forum_post'` ONLY (NOT all children): a thread's name is derived- // from its root message and is display-only — threads address by- // `parent_message_id` (uq_community_channel_parent_message, 0052), so- // duplicate thread names are legal. Source of truth:- // migration 0078_forum_post_unique_name.sql. Case-sensitive (plain `name`) to- // match the forum-post resolver + dedupe (getChildChannelByName /- // dedupeChildChannelSlug use plain `eq`), so the DB ruler folds identically- // to resolution (the index/resolver alignment migration 0075 established for- // top-level names). This is what makes pure-create's bump-retry race-safe.- uniqueIndex("idx_forum_post_parent_name")- .on(t.parentChannelId, t.name)- .where(sql`type = 'forum_post'`),]);@@ -116,9 +107,8 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(// - "access" — gates private units: a top-level channel in a PRIVATE// category, a forum, or a DM (a DM's two participants are access rows).// Public/uncategorized channels imply access via server membership.-// - "notify" — the thread / forum_post participant (notification) set. A-// message reaches only the unit's notify members; a thread never notifies-// its whole parent channel, a forum post never notifies the whole server.+// - "notify" — a child thread's participant (notification) set. A message+// reaches only the thread's notify members, never its whole parent channel.// A user may hold BOTH an access and a notify row for the same channel, so the// unique key is (channel_id, user_id, relation). `source` records how the row// arose: mention | spoke | added.@@ -654,3 +644,34 @@ export const communityMessageMark = sqliteTable(]);+// 24. community_message_tag+// Post tags (phase2 forum≡thread, Gener #768 — locked shape). A post is now+// just a message (its opener) that opened a thread — tags describe the+// CONTENT of that message, not the channel/thread it lives in (a thread can+// be opened by any message, so a channel/thread-level column would leak a+// tagging capability onto every thread, not just posts — this field's mere+// presence on a message row IS the "is this a tagged post" signal, no extra+// branch needed). Supersedes the old `communityChannel.forumTags` (JSON)+// column, backfilled here by migration 0082 and dropped by 0083 once that+// backfill was verified zero-loss.+export const communityMessageTag = sqliteTable(+ "community_message_tag",+ {+ id: text("id").primaryKey().$defaultFn(() => nanoid()),+ messageId: text("message_id")+ .notNull()+ .references(() => communityMessage.id, { onDelete: "cascade" }),+ tag: text("tag").notNull(),+ },+ (t) => [+ // Toggle idempotency: adding a tag already present is a no-op, not a+ // duplicate row (mirrors community_message_mark's uq_mark_user_message).+ unique("uq_message_tag").on(t.messageId, t.tag),+ // Tag-first: the read pattern is "find messages with tag X" (the forum+ // ?tag= filter, always applied on top of an already-resolved,+ // membership-gated channel's message set) — never a bare cross-channel+ // tag search (Aigneis #646/#647 red-line: that would hand a bot an+ // existence-probe, "which channels have this tag").+ index("idx_message_tag_tag").on(t.tag, t.messageId),+ ]+);diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex e1714a2dd..2135279c3 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -56,3 +56,4 @@ export * as communityMachine from "./queries/community/machine";export * as communityBot from "./queries/community/bot";export * as communityAgentInbox from "./queries/community/agent-inbox";export * as communityBotAuditLog from "./queries/community/bot-audit-log";+export * as communityMessageTag from "./queries/community/message-tag";diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex 484da6881..333ef5ffd 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -1,6 +1,6 @@/**- * Seq-based queries powering the `/api/community/agent/*` CLI bridge routes- * (plans/community-agent-cli-bridge.md §7) plus `toAgentMessages`, the+ * Seq-based queries powering the canonical community REST agent doors plus+ * `toAgentMessages`, the* DB-row → wire-`Message` projector every route that returns message bodies* uses.*@@ -37,6 +37,7 @@ import { listParticipatingThreadIds } from "./thread";import { getMessagesByIdsInScope, type MessageScope } from "./message";import { reachIsParticipantSet, type StoredChannelType } from "../../../utils/community-roles";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";+import { withD1Retry } from "../../resilience";type RawAgentMessage = {id: string;@@ -82,7 +83,7 @@ async function resolveScopeRefs(const channels = (await Promise.all(chunk(channelIds, D1_MAX_IN_PARAMS).map((ids) =>- db+ withD1Retry(() => db.select({id: communityChannel.id,name: communityChannel.name,@@ -92,7 +93,7 @@ async function resolveScopeRefs(parentMessageId: communityChannel.parentMessageId,}).from(communityChannel)- .where(inArray(communityChannel.id, ids))+ .where(inArray(communityChannel.id, ids)), { route: "community/agent-inbox:scope-channels" })))).flat();@@ -103,7 +104,7 @@ async function resolveScopeRefs(? (await Promise.all(chunk(dmChannelIds, D1_MAX_IN_PARAMS).map((ids) =>- db+ withD1Retry(() => db.select({channelId: communityChannelMember.channelId,userId: communityChannelMember.userId,@@ -115,7 +116,7 @@ async function resolveScopeRefs(eq(communityChannelMember.relation, "access"),ne(communityChannelMember.userId, viewerId))- )+ ), { route: "community/agent-inbox:dm-members" })))).flat()@@ -129,10 +130,10 @@ async function resolveScopeRefs(? (await Promise.all(chunk(dmPeerIds, D1_MAX_IN_PARAMS).map((ids) =>- db+ withD1Retry(() => db.select({ id: user.id, name: user.name, discriminator: user.discriminator }).from(user)- .where(inArray(user.id, ids))+ .where(inArray(user.id, ids)), { route: "community/agent-inbox:dm-peers" })))).flat()@@ -154,7 +155,11 @@ async function resolveScopeRefs(run: (batch: string[]) => Promise<T[]>): Promise<T[]> =>ids.length- ? Promise.all(chunk(ids, D1_MAX_IN_PARAMS).map(run)).then((r) => r.flat())+ ? Promise.all(+ chunk(ids, D1_MAX_IN_PARAMS).map((batch) =>+ withD1Retry(() => run(batch), { route: "community/agent-inbox:scope-context" })+ )+ ).then((r) => r.flat()): Promise.resolve([]);const [parentChannels, servers, parentMessages] = await Promise.all([@@ -165,7 +170,7 @@ async function resolveScopeRefs(.where(inArray(communityChannel.id, ids))),chunkedIn(serverIds, (ids) =>- db.select({ id: communityServer.id, name: communityServer.name }).from(communityServer).where(inArray(communityServer.id, ids))+ db.select({ id: communityServer.id, name: communityServer.name, discriminator: communityServer.discriminator }).from(communityServer).where(inArray(communityServer.id, ids))),chunkedIn(parentMessageIds, (ids) =>db.select({ id: communityMessage.id, seq: communityMessage.seq }).from(communityMessage).where(inArray(communityMessage.id, ids))@@ -173,7 +178,7 @@ async function resolveScopeRefs(]);const parentChannelById = new Map(parentChannels.map((c) => [c.id, c]));- const serverNameById = new Map(servers.map((s) => [s.id, s.name]));+ const serverHandleById = new Map(servers.map((s) => [s.id, formatHandle(s.name, s.discriminator)]));const parentSeqById = new Map(parentMessages.map((m) => [m.id, m.seq]));const out = new Map<string, ScopeInfo>();@@ -189,41 +194,33 @@ async function resolveScopeRefs(if (isDm) {const peerId = peerByDmChannel.get(ch.id);const peer = peerId ? dmPeerById.get(peerId) : undefined;- peerSegment = peer ? formatHandle(peer.name, peer.discriminator) : peerId || "unknown";+ if (!peer) throw new Error("DM peer identity unavailable");+ peerSegment = formatHandle(peer.name, peer.discriminator);}- const serverName = ch.serverId ? (serverNameById.get(ch.serverId) ?? ch.serverId) : "unknown";+ const serverHandle = ch.serverId ? serverHandleById.get(ch.serverId) : undefined;const parent = ch.parentChannelId ? parentChannelById.get(ch.parentChannelId) : undefined;const rootSeq = ch.parentMessageId ? parentSeqById.get(ch.parentMessageId) : undefined;- // A thread and a forum_post are both `parent`-anchored children, but only a- // thread carries a `parentMessageId` (→ root seq). Distinguish by whether a- // root seq resolved so we hand the emitter the right addressing type: a- // child WITH a root seq is a thread, WITHOUT is a forum_post.+ // A thread is a `parent`-anchored child carrying a `parentMessageId` (→+ // root seq). Only emit "thread" once that root seq actually resolved —+ // otherwise fall through to the raw stored type (degrades to the+ // "unresolvable" sentinel below via formatCanonicalRef returning null).const emitType: StoredChannelType =ch.parentChannelId && ch.parentMessageId && parent && rootSeq !== undefined? "thread"- : ch.parentChannelId && storedType === "forum_post" && parent- ? "forum_post"- : storedType;+ : storedType;const ref = formatCanonicalRef({type: emitType,- serverName,+ serverHandle,name: ch.name,parentName: parent?.name,rootSeq,peerSegment,});- // Degraded channel (emitter null — a required addressing field didn't- // hydrate, e.g. a thread missing its parent/root): skip its ENTRY in this- // channelId→ScopeInfo map. This is safe for never-drop: the map is looked- // up per message row by the two callers as `scope?.ref ?? "/unknown/<id>"`,- // which already keep the row and emit the explicit "/unknown/" sentinel when- // the scope is absent. So a missing entry funnels into that existing- // unresolvable path — the message row survives (nothing is dropped from the- // page) and its channel reads as an explicit "unresolvable" sentinel, NOT a- // hand-built top-level ref that looks addressable but 404s. This removes the- // second place the top-level ref shape was built (B1.1): the shape now lives- // ONLY in the emitter.- if (ref === null) continue;+ // Scope identity is required for delivery. A fabricated sentinel would look+ // like a route to downstream tokenizers while leaking an internal id, and a+ // skipped row would violate never-drop. Fail the whole batch so its cursor+ // is not advanced and the owed message can be retried after data repair.+ if (ref === null) throw new Error("Channel identity unavailable");out.set(ch.id, {ref,isThread: emitType === "thread",@@ -272,9 +269,10 @@ export async function toAgentMessages(return rows.map((r) => {const scope = refs.get(scopeRefKey(r));- const channel = scope?.ref ?? `/unknown/${scopeRefKey(r)}`;+ if (!scope) throw new Error("Channel identity unavailable");+ const channel = scope.ref;const author = userById.get(r.authorId);- const sender = author ? formatHandle(author.name, author.discriminator) : r.authorId;+ const sender = author ? `@${formatHandle(author.name, author.discriminator)}` : "Unknown user";// Absent (not empty array) when a message has no attachments — smaller// wire payload; documented invariant in the plan.const atts = attachmentsByMessageId?.get(r.id);@@ -285,7 +283,7 @@ export async function toAgentMessages(return {seq: formatSeq(r.seq),channel,- sender: `@${sender}`,+ sender,content,time: r.createdAt,};@@ -341,10 +339,9 @@ async function resolveReplyRefs(/*** Strict single-scope ref resolver for `UnreadNotice.channel`- * (`buildUnreadWakeCommand`, minimal-wake-queue-unread-notice plan §4). Unlike- * `resolveScopeRefs` (used for message/inbox hydration, where an `/unknown/…`- * fallback is tolerable UI degradation), a wake command's notice channel must- * NEVER be a placeholder — a missing channel, missing DM, missing parent+ * (`buildUnreadWakeCommand`, minimal-wake-queue-unread-notice plan §4).+ * A wake command's notice channel must NEVER be a placeholder — a missing+ * channel, missing DM, missing parent* channel, or missing parent message for a thread all resolve to `null` so* the caller treats it as `notice_channel_unresolvable` (ack/skip) rather* than waking an agent with a bogus ref it can't `inboxPull` against.@@ -413,41 +410,24 @@ export async function resolveUnreadNoticeChannel(const parent = parentRows[0];const root = rootRows[0];if (!parent || !root || !parent.serverId) return null;- const serverName = await getServerName(db, parent.serverId);- if (!serverName) return null;- return formatCanonicalRef({ type: "thread", serverName, parentName: parent.name, rootSeq: root.seq });- }-- // Forum post: parent forum but no parentMessageId — anchor by the post's own- // name under the forum (`/server/<forum>/<post>`). A missing/serverless parent- // resolves to null (notice_channel_unresolvable) rather than a bogus ref, per- // this function's no-placeholder contract.- if (storedType === "forum_post" && ch.parentChannelId) {- const parentRows = await db- .select({ name: communityChannel.name, serverId: communityChannel.serverId })- .from(communityChannel)- .where(eq(communityChannel.id, ch.parentChannelId))- .limit(1);- const parent = parentRows[0];- if (!parent || !parent.serverId) return null;- const serverName = await getServerName(db, parent.serverId);- if (!serverName) return null;- return formatCanonicalRef({ type: "forum_post", serverName, parentName: parent.name, name: ch.name });+ const serverHandle = await getServerHandle(db, parent.serverId);+ if (!serverHandle) return null;+ return formatCanonicalRef({ type: "thread", serverHandle, parentName: parent.name, rootSeq: root.seq });}if (!ch.serverId) return null;- const serverName = await getServerName(db, ch.serverId);- if (!serverName) return null;- return formatCanonicalRef({ type: storedType, serverName, name: ch.name ?? undefined });+ const serverHandle = await getServerHandle(db, ch.serverId);+ if (!serverHandle) return null;+ return formatCanonicalRef({ type: storedType, serverHandle, name: ch.name ?? undefined });}-async function getServerName(db: Database, serverId: string): Promise<string | null> {+async function getServerHandle(db: Database, serverId: string): Promise<string | null> {const rows = await db- .select({ name: communityServer.name })+ .select({ name: communityServer.name, discriminator: communityServer.discriminator }).from(communityServer).where(eq(communityServer.id, serverId)).limit(1);- return rows[0]?.name ?? null;+ return rows[0] ? formatHandle(rows[0].name, rows[0].discriminator) : null;}/** Single-row convenience wrapper around `toAgentMessages`. */@@ -476,14 +456,14 @@ export async function getLatestSeqForScope(db: Database, channelId: string): Pro}/**- * Effective allowed channel-id set for a bot: visible channels MINUS- * thread/forum_post channels the bot isn't a participant of. Pushes the- * thread-participation narrowing into a pre-computed set so it can join the+ * Effective allowed channel-id set for a bot: visible channels MINUS child+ * threads where it holds no `community_channel_member(relation='notify')`+ * row. Pushes the notification-set narrowing into a pre-computed set so it can join the* message SQL as a single `inArray` predicate — the old shape did the* narrowing as a JS post-filter AFTER `.limit(max)`, which silently- * collapsed a page of non-participating rows to `[]` (breaking `hasMore` in+ * collapsed a page of non-notified rows to `[]` (breaking `hasMore` in* `inboxPull`) and could return `null` from `getLatestUnreadMessageForAgent`- * when older participating unread existed outside the top-N-by-createdAt+ * when older notified unread existed outside the top-N-by-createdAt* candidate window.*/async function listAgentAllowedChannelIds(db: Database, botUserId: string): Promise<string[]> {@@ -525,12 +505,12 @@ async function listAgentAllowedChannelIds(db: Database, botUserId: string): Promconst narrowIds = typeRows.filter((r) => reachIsParticipantSet(r.type)).map((r) => r.id);- const participating =+ const notifiedChannelIds =narrowIds.length > 0? new Set(await listParticipatingThreadIds(db, narrowIds, botUserId)): new Set<string>();const narrowSet = new Set(narrowIds);- const serverAllowed = visibleChannelIds.filter((id) => !narrowSet.has(id) || participating.has(id));+ const serverAllowed = visibleChannelIds.filter((id) => !narrowSet.has(id) || notifiedChannelIds.has(id));return [...serverAllowed, ...dmChannelIds];}@@ -561,9 +541,9 @@ const channelJoinBaselineGuard = sql`${communityMessage.createdAt} > COALESCE(${** Visibility rule: same as the human unread path (`listUnreadChannels`) —* (1) channel messages restricted to `listVisibleChannelIdsForUser(botUserId)`- * (respects private-category rosters and private-forum-post narrowness), and- * (2) thread / forum_post channels additionally require a- * `community_thread_participant` row for the bot. Both dimensions are folded+ * (respects private-category rosters), and+ * (2) child threads additionally require a+ * `community_channel_member(relation='notify')` row for the bot. Both dimensions are folded* into ONE `inArray` predicate up front so `.limit(max)` operates on* already-visible rows — post-filtering after `limit` (the earlier shape)* could silently collapse a page to `[]` and break `hasMore`.@@ -658,12 +638,13 @@ export async function listUnreadMessagesForAgent(* for already-stuck bots: the gate stops counting messages the pull never hands* over.*- * Thread/forum-post participation narrowing: the pull's allowed set- * (`listAgentAllowedChannelIds`) additionally drops thread/forum_post channels+ * Child-thread notification-set narrowing: the pull's allowed set+ * (`listAgentAllowedChannelIds`) additionally drops child threads* the bot holds no `relation='notify'` row on — those are never delivered. The* gate MUST mirror that same narrowing (via the SAME `listParticipatingThreadIds`- * predicate, not a re-derived one) or it counts backlog in a non-participated- * thread that the pull will never hand over — the exact "not aligned: N unread"+ * predicate, not a re-derived one) or it counts backlog in a scope where the+ * bot holds no `community_channel_member(relation='notify')` row, which the+ * pull will never hand over — the exact "not aligned: N unread"* deadlock a bot hit trying to post into a thread it hadn't engaged. This drops* ONLY true spectators: a bot @mentioned into a thread gets a `notify` row on the* send hot path (`addThreadParticipants`, source=mention), so its owed mention@@ -675,8 +656,8 @@ export async function hasDeliverableUnreadForAgentScope(channelId: string,seen: number): Promise<boolean> {- // Participation narrowing, single-channel form of `listAgentAllowedChannelIds`'s- // set-wide step: a thread/forum_post the bot doesn't participate in is never+ // Notification-set narrowing, single-channel form of `listAgentAllowedChannelIds`'s+ // set-wide step: a child thread without a notify row for the bot is never// deliverable, so its backlog must not register as unread here. Short-circuits// before the deliverable scan — cheaper for the common spectator case too.const typeRows = await db@@ -742,12 +723,13 @@ export type InboxSnapshotRow = {** Visibility rule mirrors `listUnreadMessagesForAgent`: (1) channel scopes* restricted to `listVisibleChannelIdsForUser(botUserId)`, and (2) scopes of- * type `thread` or `forum_post` additionally require a- * `community_thread_participant` row for the bot (post-filter). Because the- * outer `WHERE` is `inArray(channelId, visibleChannelIds)` and non-participated+ * child threads additionally require a+ * `community_channel_member(relation='notify')` row for the bot (post-filter). Because the+ * outer `WHERE` is `inArray(channelId, visibleChannelIds)` and scopes lacking+ * the bot's `community_channel_member(relation='notify')` row* thread rows are dropped in the post-filter, `hasMention` (a correlated* sub-select keyed on the surviving row's `channel_id`) can never inherit a- * mention from an invisible or non-participated thread — do NOT try to+ * mention from an invisible or non-notified thread — do NOT try to* sub-select mentions independently or the leak reopens on this axis.*/export async function getInboxSnapshotForAgent(db: Database, botUserId: string): Promise<InboxSnapshotRow[]> {@@ -840,7 +822,7 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):pendingCount: r.pendingCount,firstPendingSeq: r.firstPendingSeq,latestSeq: r.latestSeq,- latestSender: `@${sender ? formatHandle(sender.name, sender.discriminator) : r.latestSenderId}`,+ latestSender: sender ? `@${formatHandle(sender.name, sender.discriminator)}` : "Unknown user",hasMention: r.mentionCount > 0,};});@@ -869,12 +851,13 @@ export async function toInboxRows(const refs = await resolveScopeRefs(db, rows, viewerId);return rows.map((r) => {const scope = refs.get(scopeRefKey(r));+ if (!scope) throw new Error("Channel identity unavailable");const flags: Array<"dm" | "thread" | "mention"> = [];if (scope?.isDm) flags.push("dm");if (scope?.isThread) flags.push("thread");if (r.hasMention) flags.push("mention");return {- channel: scope?.ref ?? `/unknown/${scopeRefKey(r)}`,+ channel: scope.ref,pendingCount: r.pendingCount,firstPendingSeq: r.firstPendingSeq,latestSeq: r.latestSeq,@@ -894,8 +877,8 @@ export async function toInboxRows(* `listUnreadMessagesForAgent`'s doc comment).** Visibility rule identical to `listUnreadMessagesForAgent`: the bot must be- * able to see the channel (`listVisibleChannelIdsForUser`) AND, for thread /- * forum_post scopes, hold a `community_thread_participant` row. Both+ * able to see the channel (`listVisibleChannelIdsForUser`) AND, for child+ * threads, hold a `community_channel_member(relation='notify')` row. Both* dimensions are folded into the SQL WHERE via `listAgentAllowedChannelIds`* so `LIMIT 1` returns the newest allowed row directly — an earlier shape* used a bounded post-filter window that could return `null` when olderdiff --git a/src/shared/src/db/queries/community/attachment.ts b/src/shared/src/db/queries/community/attachment.tsindex bd578a3aa..ef19c122f 100644--- a/src/shared/src/db/queries/community/attachment.ts+++ b/src/shared/src/db/queries/community/attachment.ts@@ -1,48 +1,10 @@-import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";+import { and, asc, count, eq, inArray, isNull, sql } from "drizzle-orm";+import { alias } from "drizzle-orm/sqlite-core";import { nanoid } from "nanoid";import { communityAttachment } from "../../community-schema";import type { Database } from "../../index";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";-/**- * Insert an attachment row already tied to a message (human-composer path).- * The agent-attachment pipeline uses `createPendingAttachment` /- * `reserveAttachmentsForMessage` instead — those two are the only writers of- * `messageId = NULL` rows.- */-export async function createAttachment(- db: Database,- data: {- messageId: string;- uploaderId: string;- targetId: string;- r2Key: string;- filename: string;- position?: number;- contentType?: string | null;- size?: number | null;- width?: number | null;- height?: number | null;- }-) {- const [row] = await db- .insert(communityAttachment)- .values({- messageId: data.messageId,- uploaderId: data.uploaderId,- targetId: data.targetId,- r2Key: data.r2Key,- filename: data.filename,- position: data.position ?? null,- contentType: data.contentType ?? null,- size: data.size ?? null,- width: data.width ?? null,- height: data.height ?? null,- })- .returning();- return row!;-}-/*** Insert a pending attachment row (`messageId = NULL`) for the agent* `attachment upload` command. The caller receives the id and later passes@@ -87,8 +49,17 @@ export async function createPendingAttachment(* the (uploader, scope) tuple. Callers compare `rows.length === ids.length`* to detect any mismatch and reject with a generic 400 that never leaks* which specific id failed (avoids id enumeration).+ *+ * Actor-agnostic: the guarantee is keyed entirely on the `uploaderId` param, so+ * BOTH the human web composer and the bot flow use it (route/disc step 2b+ * unified them onto reserve-by-id). A caller passes its own credential user id;+ * the `uploaderId` + `messageId IS NULL` filters make it confused-deputy-safe —+ * a caller can only reserve pending rows it uploaded, into the target it+ * uploaded them for (the send-side dual of the download door's+ * authorize-from-row guard). Named "…ForSender" (not "…ForBot") because the+ * sender is whichever actor's credential keys the lookup.*/-export async function findPendingAttachmentsForBot(+export async function findPendingAttachmentsForSender(db: Database,data: { ids: string[]; uploaderId: string; targetId: string }) {@@ -144,6 +115,35 @@ export async function reserveAttachmentsForMessage(return rows.map((r) => r.id);}+export async function rebindPendingAttachmentsToChild(+ db: Database,+ data: { ids: string[]; uploaderId: string; parentTargetId: string; childTargetId: string }+): Promise<boolean> {+ if (data.ids.length === 0) return true;+ const eligible = alias(communityAttachment, "eligible_attachment");+ const eligibleCount = db+ .select({ value: count() })+ .from(eligible)+ .where(and(+ inArray(eligible.id, data.ids),+ isNull(eligible.messageId),+ eq(eligible.uploaderId, data.uploaderId),+ inArray(eligible.targetId, [data.parentTargetId, data.childTargetId])+ ));+ const rebound = await db+ .update(communityAttachment)+ .set({ targetId: data.childTargetId })+ .where(and(+ inArray(communityAttachment.id, data.ids),+ isNull(communityAttachment.messageId),+ eq(communityAttachment.uploaderId, data.uploaderId),+ inArray(communityAttachment.targetId, [data.parentTargetId, data.childTargetId]),+ sql`(${eligibleCount}) = ${data.ids.length}`+ ))+ .returning({ id: communityAttachment.id });+ return rebound.length === data.ids.length;+}+/*** Compensating UPDATE for the three send-time rollback sites:* (a) reservation-mismatch (partial-overlap race),diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex 0700f8533..c7811b1cc 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -27,8 +27,6 @@ import {import {communityBotApprovalRequest,communityServerMember,- communityMessage,- communityFriendship,communityUserProfile,communityReadState,communityBotDailyActivity,diff --git a/src/shared/src/db/queries/community/category.ts b/src/shared/src/db/queries/community/category.tsindex 341631c82..a5a15bc64 100644--- a/src/shared/src/db/queries/community/category.ts+++ b/src/shared/src/db/queries/community/category.ts@@ -93,7 +93,7 @@ export async function hasChannels(db: Database, categoryId: string): Promise<booexport async function reorderCategories(db: Database,- serverId: string,+ _serverId: string,categoryIds: string[]) {const statements = categoryIds.map((id, index) =>diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex a71ff1815..5d2b85297 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -8,33 +8,10 @@ import {} from "../../community-schema";import type { Database } from "../../index";import { PARTICIPANT_SOURCE } from "../../../constants/community";-import { createLogger } from "../../../logger";-import { canManageServer, canSeePrivateChannel, visibilityIsDmParticipant } from "../../../utils/community-roles";+import { canSeePrivateChannel, visibilityIsDmParticipant } from "../../../utils/community-roles";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";-// Module-level logger — one tag per shared query module.-const log = createLogger({ service: "community-queries" });--// TEXT column at rest → string[] at the boundary. Null/empty is a clean read-// (empty tag set); a parse throw or non-array shape signals bit-rot.-function safeParseForumTags(raw: string | null, channelId: string): string[] {- if (!raw) return [];- let parsed: unknown;- try {- parsed = JSON.parse(raw);- } catch (err) {- log.warn("forum_tags_parse_failed", { channelId, err });- return [];- }- if (!Array.isArray(parsed)) {- log.warn("forum_tags_not_array", { channelId });- return [];- }- return parsed as string[];-}--// Column selection shared by every read query — keeps `forumTags` off the wire-// (renamed to `tags`) and hands each caller the same row shape.+// Column selection shared by every read query.const CHANNEL_COLUMNS = {id: communityChannel.id,serverId: communityChannel.serverId,@@ -43,7 +20,6 @@ const CHANNEL_COLUMNS = {type: communityChannel.type,topic: communityChannel.topic,position: communityChannel.position,- forumTags: communityChannel.forumTags,parentChannelId: communityChannel.parentChannelId,creatorId: communityChannel.creatorId,messageCount: communityChannel.messageCount,@@ -53,13 +29,6 @@ const CHANNEL_COLUMNS = {createdAt: communityChannel.createdAt,} as const;-function mapChannelRow<- T extends { id: string; forumTags: string | null },->(row: T): Omit<T, "forumTags"> & { tags: string[] } {- const { forumTags, ...rest } = row;- return { ...rest, tags: safeParseForumTags(forumTags, row.id) };-}-export async function createChannel(db: Database,@@ -72,9 +41,6 @@ export async function createChannel(parentChannelId?: string | null;creatorId?: string | null;parentMessageId?: string | null;- // Display-only pre-slugify original title (forum_post CREATE only). Absent- // for every other create path — leaves the column null.- displayTitle?: string | null;}) {const rows = await db@@ -88,7 +54,6 @@ export async function createChannel(parentChannelId: data.parentChannelId ?? null,creatorId: data.creatorId ?? null,parentMessageId: data.parentMessageId ?? null,- displayTitle: data.displayTitle ?? null,}).returning();return rows[0]!;@@ -100,12 +65,12 @@ export async function getChannel(db: Database, channelId: string) {.from(communityChannel).where(eq(communityChannel.id, channelId));const row = rows[0];- return row ? mapChannelRow(row) : null;+ return row ? row : null;}-// Just the `type` of a channel ("text" | "forum" | "forum_post" | "thread" |-// null). A one-column probe for hot paths that only need to branch by type-// (e.g. fan-out routing a thread to its participant set). Returns null when the+// Just the `type` of a channel ("text" | "forum" | "thread" | "dm" | null). A+// one-column probe for hot paths that only need to branch by type (e.g.+// fan-out routing a thread to its participant set). Returns null when the// channel doesn't exist.export async function getChannelType(db: Database,@@ -146,7 +111,7 @@ export async function getChannelForMember(db: Database, channelId: string, userI// DM (type=dm, server_id NULL) — readable iff the user has a// relation='access' member row.const isMember = await isChannelMember(db, channelId, userId, "access");- return isMember ? mapChannelRow(dmRow) : null;+ return isMember ? dmRow : null;}const rows = await db@@ -165,7 +130,7 @@ export async function getChannelForMember(db: Database, channelId: string, userIconst { memberRole, ...channelRow } = row;// Unified model — the anchor (`parentChannelId ?? id`) is both the privacy and- // roster anchor. A forum_post/thread climbs to its parent forum/channel for+ // roster anchor. A child thread climbs to its parent forum/channel for// BOTH the category-privacy flag and the roster (member rows + creator); a// top-level channel/forum is its own anchor. The single query below reads that// anchor and its creator.@@ -198,7 +163,7 @@ export async function getChannelForMember(db: Database, channelId: string, userI}}- return mapChannelRow(channelRow);+ return channelRow;}export async function updateChannel(@@ -208,7 +173,6 @@ export async function updateChannel(name?: string;topic?: string;categoryId?: string | null;- forumTags?: string | null;archived?: number;lastMessageAt?: string;messageCount?: number;@@ -236,7 +200,7 @@ export async function listServerChannels(db: Database, serverId: string) {.from(communityChannel).where(and(eq(communityChannel.serverId, serverId), isNull(communityChannel.parentChannelId))).orderBy(asc(communityChannel.position));- return rows.map(mapChannelRow);+ return rows;}/**@@ -246,7 +210,7 @@ export async function listServerChannels(db: Database, serverId: string) {** Ids are NOT accepted from agent surfaces. Agents address channels via* the canonical ref grammar (`/server/channel`, `/server/channel/#seq`);- * ids are a `/c` UI internal. Threads and forum posts must be reached+ * ids are a `/c` UI internal. Child threads must be reached* through their parent + `#seq`, never by direct name or id here.** The returned array is length 0 or 1: the WHERE clause narrows to a single@@ -279,7 +243,7 @@ export async function resolveChannelByNameForMember(isNull(communityChannel.parentChannelId)));- return rows.map(mapChannelRow);+ return rows;}/**@@ -328,71 +292,9 @@ export async function getThreadChannelByParentMessage());const row = rows[0];- return row ? mapChannelRow(row) : null;-}--/**- * Resolve a forum post by its name under a parent forum. A forum post is a- * `forum_post` child channel anchored by its own name (not a root-message seq- * like a thread), so `(parentChannelId, name, type='forum_post')` is its- * address. Returns ALL matches so the caller can disambiguate: post names are- * NOT unique within a forum (schema exempts child channels from the per-server- * unique index), so >1 row means an ambiguous ref the resolver must 400 on —- * never silently pick one.- */-export async function getChildChannelByName(- db: Database,- parentChannelId: string,- name: string,- type = "forum_post"-) {- const rows = await db- .select(CHANNEL_COLUMNS)- .from(communityChannel)- .where(- and(- eq(communityChannel.parentChannelId, parentChannelId),- eq(communityChannel.name, name),- eq(communityChannel.type, type)- )- );- return rows.map(mapChannelRow);+ return row ? row : null;}-/**- * Dedupe a forum-post slug within its parent forum so the name anchor- * (`/server/forum/<post>`) is a real address. Post names are not covered by the- * per-server unique index (that's top-level channels only), so uniqueness is- * enforced here at create time, mirroring the discipline top-level channel- * names already follow: `ideas` → `ideas-2` → `ideas-3`. The input is already- * a slug (the caller `slugify`s the raw name — this only appends the numeric- * suffix on collision, never re-introduces `/`/`#`/whitespace). Best-effort- * against a read snapshot; the create path is single-writer per forum in- * practice, and a rare race just yields a second same-named post the resolver's- * ambiguity floor still handles safely.- */-export async function dedupeChildChannelSlug(- db: Database,- parentChannelId: string,- baseSlug: string,- type = "forum_post"-): Promise<string> {- const rows = await db- .select({ name: communityChannel.name })- .from(communityChannel)- .where(- and(- eq(communityChannel.parentChannelId, parentChannelId),- eq(communityChannel.type, type)- )- );- const taken = new Set(rows.map((r) => r.name));- if (!taken.has(baseSlug)) return baseSlug;- for (let n = 2; ; n++) {- const candidate = `${baseSlug}-${n}`;- if (!taken.has(candidate)) return candidate;- }-}/*** Auto-create a thread channel rooted at `parentMessageId` inside@@ -432,7 +334,7 @@ export async function createThreadChannel(if (!serverId) throw new Error(`createThreadChannel: parent channel ${parentChannelId} not found`);// A thread may only root on a TOP-LEVEL channel. Rooting on a child channel- // (a forum post, or another thread) would make this a grandchild whose+ // (a forum child thread, or another thread) would make this a grandchild whose// privacy the single-level anchor climb can't resolve — it would read the// child's own `categoryId` (always NULL) as public and leak a private// forum's thread server-wide. Single chokepoint for every caller (web@@ -483,12 +385,34 @@ export async function listChildChannels(.from(communityChannel).where(and(...conditions)).orderBy(desc(communityChannel.lastMessageAt));- return rows.map(mapChannelRow);+ return rows;+}++export async function listChildChannelsByParentMessageIds(+ db: Database,+ parentChannelId: string,+ parentMessageIds: string[],+) {+ if (parentMessageIds.length === 0) return [];+ return (+ await Promise.all(+ chunk(parentMessageIds, D1_MAX_IN_PARAMS - 2).map((ids) =>+ db+ .select(CHANNEL_COLUMNS)+ .from(communityChannel)+ .where(and(+ eq(communityChannel.parentChannelId, parentChannelId),+ eq(communityChannel.type, "thread"),+ inArray(communityChannel.parentMessageId, ids),+ ))+ )+ )+ ).flat();}export async function reorderChannels(db: Database,- serverId: string,+ _serverId: string,channelIds: string[]) {const statements = channelIds.map((id, index) =>@@ -533,7 +457,30 @@ export async function getChannelsByIds(db: Database, channelIds: string[]) {))).flat();- return rows.map(mapChannelRow);+ return rows;+}++export async function getDirectChildThreadsByIds(+ db: Database,+ parentChannelId: string,+ channelIds: string[]+) {+ if (channelIds.length === 0) return [];+ const rows = (+ await Promise.all(+ chunk(channelIds, D1_MAX_IN_PARAMS - 2).map((ids) =>+ db+ .select(CHANNEL_COLUMNS)+ .from(communityChannel)+ .where(and(+ inArray(communityChannel.id, ids),+ eq(communityChannel.parentChannelId, parentChannelId),+ eq(communityChannel.type, "thread")+ ))+ )+ )+ ).flat();+ return rows;}// ---------------------------------------------------------------------------@@ -620,7 +567,7 @@ export async function deleteChannelMember(/*** ACCESS members explicitly added to a channel, joined to `user` for display.* Scoped to one channel id — cross-channel ids never resolve. Notify rows- * (thread/forum-post participants) are excluded.+ * (child-thread participants) are excluded.*/export async function listChannelMembers(db: Database, channelId: string) {return db@@ -707,7 +654,7 @@ export async function countChannelsInCategory(/*** The full recipient audience for a PRIVATE channel: explicit members ∪ the* unit's creator. Unified model — a unit's roster is always its anchor's- * (`parentChannelId ?? id`), so a forum_post/thread inherits its parent+ * (`parentChannelId ?? id`), so a child thread inherits its parent* forum/channel's roster. Only meaningful for a private anchor; callers guard on* `isChannelPrivate` first (fan-out short-circuits public channels to* `listMemberUserIds` and never calls this).@@ -736,10 +683,9 @@ export async function getPrivateChannelAudienceUserIds(// Unified access model — a unit's roster is always its anchor's roster:// - forum / text channel → its OWN explicit members ∪ its OWN creator.- // - forum_post / thread → climbs `parentChannelId` to the anchor (the- // forum / parent channel) and uses THAT roster — a post inherits the- // forum's audience exactly like a thread inherits its channel's.- // No derived union, no per-post roster: forum ≈ channel, forum_post ≈ thread.+ // - child thread → climbs `parentChannelId` to the anchor and uses that+ // forum or channel roster.+ // No derived union and no per-thread roster.const rosterAnchorId = target[0]!.parentChannelId ?? target[0]!.id;const rosterCreatorId =rosterAnchorId === target[0]!.id@@ -789,7 +735,7 @@ export async function listServerChannelsForViewer(.orderBy(asc(communityChannel.position)),resolveVisibleChannelIdSet(db, userId, { serverIds: [serverId] }),]);- return rows.filter((r) => visibleSet.has(r.id)).map(mapChannelRow);+ return rows.filter((r) => visibleSet.has(r.id));}// Shared visibility computation for the nested-membership model. Assembles the@@ -863,7 +809,7 @@ async function resolveVisibleChannelIdSet(}}- // Pass 2 — children. Both forum posts AND threads INHERIT their parent's+ // Pass 2 — child threads INHERIT their parent's// visibility (a forum member sees every post; a channel member sees every// thread). No per-post access unit.for (const r of rows) {@@ -879,10 +825,10 @@ async function resolveVisibleChannelIdSet(}/**- * The set of channel ids (top-level AND child/thread/forum-post channels) a+ * The set of channel ids (top-level AND child-thread channels) a* viewer may see — backs read-path scoping for search / inbox / mark-all-read /- * mentions. Unified model (see `resolveVisibleChannelIdSet`): forum posts AND- * threads inherit their parent's visibility; a private forum/channel is visible+ * mentions. Unified model (see `resolveVisibleChannelIdSet`): child threads+ * inherit their parent's visibility; a private forum/channel is visible* via the viewer's own member row (or creator).*/export async function listVisibleChannelIds(@@ -896,7 +842,7 @@ export async function listVisibleChannelIds(/*** Cross-server sibling of `listVisibleChannelIds` — every channel id (top-level- * AND child/thread/forum-post) a viewer may see across ALL of their servers, in+ * AND child-thread) a viewer may see across ALL of their servers, in* a handful of queries instead of an N+1 loop-per-server. Backs the inbox* consumers (unread + mentions + mark-all), which span every server the viewer* belongs to.@@ -948,7 +894,7 @@ export async function resolveChannelAccessContext(.where(eq(communityChannel.id, channelId)).limit(1);if (target.length === 0) return null;- const channel = mapChannelRow(target[0]!);+ const channel = target[0]!;const anchorId = channel.parentChannelId ?? channel.id;// DM (type=dm, server_id NULL) — access iff the user has a relation='access'@@ -990,10 +936,10 @@ export async function resolveChannelAccessContext(.where(eq(communityChannel.id, anchorId)).limit(1);if (anchorRows.length === 0) return null;- const anchor = mapChannelRow(anchorRows[0]!);+ const anchor = anchorRows[0]!;// Unified model — privacy anchor == roster anchor == `parentChannelId ?? id`.- // A forum_post/thread climbs to its parent (forum/channel) for BOTH the+ // A child thread climbs to its parent (forum/channel) for BOTH the// category-privacy flag and the roster; a forum/top-level channel is its own// anchor. So post access is pure inheritance from the forum, exactly like a// thread inherits its channel — no per-post roster, no forum-derived union.diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex beeebd2b3..6e1445038 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -1,4 +1,4 @@-import { and, eq, isNotNull, isNull, inArray, ne, sql } from "drizzle-orm";+import { aliasedTable, and, eq, gt, isNotNull, isNull, inArray, ne, or, sql } from "drizzle-orm";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";import {communityChannel,@@ -18,15 +18,26 @@ export interface UnreadChannelRow {channelName: string;serverId: string;serverName: string;- // Raw stored channel type (text | forum | thread | forum_post). Threaded- // through to the inbox so it can render the same entity icon as the sidebar.+ // Raw stored channel type (text | forum | thread). Threaded through to the+ // inbox so it can render the same entity icon as the sidebar.type: string | null;lastMessageAt: string;- // null for a top-level channel; set for a thread / forum-post child. The+ // null for a top-level channel; set for a child thread. The// inbox route uses this to nest child unreads under their parent channel.parentChannelId: string | null;}+export interface UnreadForumOpenerRow {+ forumChannelId: string;+ openerMessageId: string;+ childChannelId: string;+ title: string;+ createdAt: string;+ // Kept in the read-model row so callers can preserve the query's stable+ // createdAt → seq → id order through their own merge/cap pass.+ openerSeq: number;+}+/*** Two-branch unread predicate, shared by every reader that groups channels* by "unread since I last looked."@@ -70,7 +81,7 @@ export async function listUnreadChannels(userId: string,visibleChannelIds: string[]): Promise<UnreadChannelRow[]> {- // All channels — top-level AND child threads/forum-posts — the viewer may+ // All channels — top-level AND child threads — the viewer may// see (the `visibleChannelIds` set, resolved once per inbox fetch via// `listVisibleChannelIdsForUser`), plus read state. Visibility is the id-set// `inArray`, NOT an inlined category `or()`: a child channel's own@@ -149,7 +160,7 @@ export async function listUnreadChannels(}));- // Thread AND forum-post unreads are scoped to PARTICIPATION (notification+ // Child-thread unreads are scoped to PARTICIPATION (notification// dimension): they surface in the inbox only for their participants, NOT for// every member who can merely read them. A public post is visible to the// whole server but only notifies its participants, so an un-joined post must@@ -181,6 +192,111 @@ export async function listUnreadChannels(}));}+/**+ * Project every unread forum opener under an already-authorized parent scope.+ *+ * `forumParentIds` is intentionally supplied by the caller after visibility+ * and mute filtering. This query never discovers forums globally: it only+ * expands messages inside that bounded id set and joins each opener to the+ * child channel rooted on it.+ */+export async function listUnreadForumOpeners(+ db: Database,+ userId: string,+ forumParentIds: string[]+): Promise<UnreadForumOpenerRow[]> {+ if (forumParentIds.length === 0) return [];++ const childChannel = aliasedTable(communityChannel, "forum_inbox_child");+ const rows = (+ await Promise.all(+ chunk(forumParentIds, D1_MAX_IN_PARAMS).map((ids) =>+ db+ .select({+ forumChannelId: communityMessage.channelId,+ openerMessageId: communityMessage.id,+ openerContent: communityMessage.content,+ openerSeq: communityMessage.seq,+ childChannelId: childChannel.id,+ childName: childChannel.name,+ createdAt: communityMessage.createdAt,+ })+ .from(communityMessage)+ .innerJoin(+ communityChannel,+ eq(communityChannel.id, communityMessage.channelId)+ )+ .innerJoin(+ childChannel,+ and(+ eq(childChannel.parentChannelId, communityChannel.id),+ eq(childChannel.parentMessageId, communityMessage.id)+ )+ )+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.userId, userId)+ )+ )+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.channelId, communityChannel.id),+ eq(communityReadState.userId, userId)+ )+ )+ .where(+ and(+ inArray(communityChannel.id, ids),+ isNull(communityChannel.parentChannelId),+ eq(communityChannel.type, "forum"),+ eq(communityChannel.archived, 0),+ eq(childChannel.archived, 0),+ or(+ and(+ isNotNull(communityReadState.id),+ gt(+ communityMessage.seq,+ sql<number>`COALESCE(${communityReadState.lastReadSeq}, 0)`+ )+ ),+ and(+ isNull(communityReadState.id),+ gt(communityMessage.createdAt, communityServerMember.joinedAt)+ )+ )+ )+ )+ )+ )+ ).flat();++ // D1 chunks are independent statements. Sort only after concatenation so a+ // chunk boundary can never change the rows that survive the Inbox cap.+ rows.sort(+ (a, b) =>+ b.createdAt.localeCompare(a.createdAt) ||+ b.openerSeq - a.openerSeq ||+ b.openerMessageId.localeCompare(a.openerMessageId)+ );++ return rows.map((row) => ({+ forumChannelId: row.forumChannelId,+ openerMessageId: row.openerMessageId,+ childChannelId: row.childChannelId,+ // The opener is the forum title source of truth. Child names are derived+ // and truncated, so they are only an anomaly fallback for blank content.+ title:+ row.openerContent.trim().length > 0+ ? row.openerContent+ : row.childName?.trim() || "Thread",+ createdAt: row.createdAt,+ openerSeq: row.openerSeq,+ }));+}+// ──────────────────────────────────────────────────────────────────────────────// DM unreads// ──────────────────────────────────────────────────────────────────────────────diff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.tsindex 77715407f..820738e3e 100644--- a/src/shared/src/db/queries/community/invite.ts+++ b/src/shared/src/db/queries/community/invite.ts@@ -1,4 +1,4 @@-import { eq, and, or, gt, isNull, sql } from "drizzle-orm";+import { eq, sql } from "drizzle-orm";import {communityServerInvite,communityServerMember,diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.tsindex 8d9e52a5d..5653ddb0e 100644--- a/src/shared/src/db/queries/community/machine.ts+++ b/src/shared/src/db/queries/community/machine.ts@@ -1,5 +1,4 @@import { and, eq, gt, desc, isNull, inArray, sql } from "drizzle-orm";-import type { SQL } from "drizzle-orm";import {communityMachineToken,communityMachine,diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex adfab30b8..834632965 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -424,16 +424,19 @@ export async function removeOwnerBotsFromServer(* caller wake a bot that lost access to the scope.** The gate applies BOTH visibility AND notification-set semantics: a public- * forum_post is technically READABLE by any server member, but wakes only- * fire for its `community_thread_participant` set — same rule the human+ * child thread is technically READABLE by any server member, but wakes only+ * fire for its `community_channel_member(relation='notify')` set — same rule the human* inbox uses (`listUnreadChannels`, `inbox.ts:123-143`). Without the* participation gate a bogus source query could still leak a wake for a- * public-forum message the bot never touched (Mellicent's exact bug).+ * public-forum message whose scope has no+ * `community_channel_member(relation='notify')` row for the bot+ * (Mellicent's exact bug).** A channel in a PRIVATE category is only readable by the bot if it's the* channel creator or has a `community_channel_member` row (server admins too);- * public/uncategorized channels need only server membership. Thread/forum_post- * scopes must additionally hold a participant row on top of the access check.+ * public/uncategorized channels need only server membership. Child-thread+ * scopes must additionally hold a+ * `community_channel_member(relation='notify')` row on top of the access check.*/export async function canBotReadWakeScope(db: Database,@@ -454,8 +457,8 @@ export async function canBotReadWakeScope(});if (!accessible) return false;- // Notification-set narrowing — thread + forum_post scopes only notify- // their participants (mirrors the human inbox's post-visibility filter).+ // Notification-set narrowing — child-thread scopes only notify users with a+ // `community_channel_member(relation='notify')` row (mirrors the human inbox).// Bots are just users; notify rows are added the same way (spoke /// mention / added), so the same predicate applies verbatim.if (reachIsParticipantSet(ctx.channel.type)) {diff --git a/src/shared/src/db/queries/community/members-resolver.ts b/src/shared/src/db/queries/community/members-resolver.tsindex d2d60c46c..1aa3f9289 100644--- a/src/shared/src/db/queries/community/members-resolver.ts+++ b/src/shared/src/db/queries/community/members-resolver.ts@@ -15,7 +15,7 @@ import { listMemberUserIds } from "./member";// The ACCESS scopes — units that own (or inherit) a stored/derived access// roster. `forum` resolves like a top-level text channel (its own roster);-// `channel` is a top-level text channel. Thread / forum_post are NOT here: they+// `channel` is a top-level text channel. Child threads are NOT here: they// are the NOTIFICATION dimension (participant set), resolved at the call site// via `listThreadParticipantUserIds` — never through this resolver.export type ScopeKind = "channel" | "forum";@@ -42,8 +42,8 @@ export type ScopeMember = {* creator (delegates to `getPrivateChannelAudienceUserIds`, which climbs* `parentChannelId` so a forum resolves its own roster like a text channel).*- * Only ACCESS units (`channel`/`forum`) reach here. Notify units (thread /- * forum_post) resolve their recipient set from the participant table at the+ * Only ACCESS units (`channel`/`forum`) reach here. Child threads resolve their+ * recipient set from the participant table at the* call site.*/export async function resolveScopeMemberUserIds(diff --git a/src/shared/src/db/queries/community/message-tag.ts b/src/shared/src/db/queries/community/message-tag.tsnew file mode 100644index 000000000..a0dfe0b2c--- /dev/null+++ b/src/shared/src/db/queries/community/message-tag.ts@@ -0,0 +1,120 @@+import { eq, and, inArray, asc } from "drizzle-orm";+import { communityMessage, communityMessageTag } from "../../community-schema";+import type { Database } from "../../index";+import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";++// Idempotent add. UNIQUE(messageId, tag) makes re-adding the same tag a+// no-op, so `onConflictDoNothing` keeps this safe to call twice without a+// 409 round-trip (mirrors mark.ts's markMessage).+export async function addMessageTag(+ db: Database,+ data: { messageId: string; tag: string }+) {+ await db+ .insert(communityMessageTag)+ .values({ messageId: data.messageId, tag: data.tag })+ .onConflictDoNothing({+ target: [communityMessageTag.messageId, communityMessageTag.tag],+ });+}++export async function removeMessageTag(+ db: Database,+ data: { messageId: string; tag: string }+) {+ const [deleted] = await db+ .delete(communityMessageTag)+ .where(+ and(+ eq(communityMessageTag.messageId, data.messageId),+ eq(communityMessageTag.tag, data.tag)+ )+ )+ .returning();+ return deleted ?? null;+}++/** Atomically replace one message's complete tag set. The unconditional+ * delete and every wanted insert share one D1 batch, giving concurrent PUTs+ * last-writer-wins set semantics and preventing half-replaced rows. */+export async function replaceMessageTags(+ db: Database,+ data: { messageId: string; tags: string[] }+) {+ const statements = [+ db.delete(communityMessageTag).where(eq(communityMessageTag.messageId, data.messageId)),+ ...data.tags.map((tag) =>+ db.insert(communityMessageTag).values({ messageId: data.messageId, tag })+ ),+ ];+ await db.batch(statements as any);+}++// This message's own tag set, unordered (callers sort if they need a+// display order — no natural order on a tag set).+export async function listTagsForMessage(+ db: Database,+ messageId: string+): Promise<string[]> {+ const rows = await db+ .select({ tag: communityMessageTag.tag })+ .from(communityMessageTag)+ .where(eq(communityMessageTag.messageId, messageId));+ return rows.map((r) => r.tag);+}++// Batch variant for a post-list render (avoid N+1) — one row per+// (messageId, tag) pair; caller groups by messageId.+export async function listTagsForMessages(+ db: Database,+ messageIds: string[]+): Promise<{ messageId: string; tag: string }[]> {+ if (messageIds.length === 0) return [];+ const chunks = chunk(messageIds, D1_MAX_IN_PARAMS);+ const results = await Promise.all(+ chunks.map((ids) =>+ db+ .select({ messageId: communityMessageTag.messageId, tag: communityMessageTag.tag })+ .from(communityMessageTag)+ .where(inArray(communityMessageTag.messageId, ids))+ )+ );+ return results.flat();+}++// Filter an ALREADY-RESOLVED, membership-gated message id set down to those+// carrying `tag` (the forum `?tag=` filter). `candidateMessageIds` MUST come+// from a caller that has already scoped to one channel's message set — this+// function does NOT accept a bare tag with no candidate scope, so it can+// never become a cross-channel "which channels have this tag" existence+// probe (Aigneis #646/#647 red-line).+export async function filterMessageIdsByTag(+ db: Database,+ candidateMessageIds: string[],+ tag: string+): Promise<string[]> {+ if (candidateMessageIds.length === 0) return [];+ const chunks = chunk(candidateMessageIds, D1_MAX_IN_PARAMS);+ const results = await Promise.all(+ chunks.map((ids) =>+ db+ .select({ messageId: communityMessageTag.messageId })+ .from(communityMessageTag)+ .where(and(eq(communityMessageTag.tag, tag), inArray(communityMessageTag.messageId, ids)))+ )+ );+ return results.flat().map((r) => r.messageId);+}++export async function listDistinctTagsForChannel(+ db: Database,+ channelId: string+): Promise<string[]> {+ const rows = await db+ .selectDistinct({ tag: communityMessageTag.tag })+ .from(communityMessageTag)+ .innerJoin(communityMessage, eq(communityMessage.id, communityMessageTag.messageId))+ .where(eq(communityMessage.channelId, channelId))+ .orderBy(asc(communityMessageTag.tag));+ return rows.map((row) => row.tag);+}diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex ef5f4f4c3..84754b534 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -1,10 +1,11 @@-import { eq, and, asc, desc, gt, lt, or, sql, inArray, isNotNull } from "drizzle-orm";+import { eq, and, asc, desc, gt, lt, or, sql, inArray } from "drizzle-orm";import {communityMessage,communityChannel,communityReadState,communityMessageSeq,communityChannelMember,+ communityMessageTag,} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -118,9 +119,9 @@ export type CreateMessageData = {/*** `createMessage` overloads (plans/fix-agent-send-race-condition.md design §2):* callers that never pass `expectedSeq` keep today's non-nullable return- * type — no pointless null-checks forced onto the three direct callers- * (`channels/[id]/posts/route.ts`, `servers/[id]/bots/route.ts`,- * `friends/request/route.ts`) that never opt into the CAS guard. Only+ * type — no pointless null-checks forced onto direct callers such as message+ * send, bot provisioning, and friend request, which never opt into the CAS+ * guard. Only* callers that explicitly pass a numeric `expectedSeq` (the agent-send race* fix) see the nullable return — `null` means "lost the race, no row was* written, treat as a complete no-op".@@ -348,6 +349,7 @@ const listedMessageProjection = {createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,friendshipId: communityMessage.friendshipId,+ clientNonce: communityMessage.clientNonce,authorName: user.name,authorEmail: user.email,authorImage: user.image,@@ -365,6 +367,7 @@ export type ListedMessageRow = {createdAt: string;channelId: string;friendshipId: string | null;+ clientNonce: string | null;authorName: string;authorEmail: string;authorImage: string | null;@@ -380,6 +383,7 @@ export async function listMessages(channelId: string;cursor?: { createdAt: string; id: string };limit?: number;+ tag?: string;}) {const limit = opts.limit ?? DEFAULT_LIMIT;@@ -399,14 +403,25 @@ export async function listMessages()! as ReturnType<typeof eq>);}-- const rows = await db- .select(listedMessageProjection)- .from(communityMessage)- .innerJoin(user, eq(communityMessage.authorId, user.id))- .where(and(...conditions))- .orderBy(desc(communityMessage.createdAt), desc(communityMessage.id))- .limit(limit);+ const rows = opts.tag+ ? await db+ .select(listedMessageProjection)+ .from(communityMessage)+ .innerJoin(user, eq(communityMessage.authorId, user.id))+ .innerJoin(communityMessageTag, and(+ eq(communityMessageTag.messageId, communityMessage.id),+ eq(communityMessageTag.tag, opts.tag),+ ))+ .where(and(...conditions))+ .orderBy(desc(communityMessage.createdAt), desc(communityMessage.id))+ .limit(limit)+ : await db+ .select(listedMessageProjection)+ .from(communityMessage)+ .innerJoin(user, eq(communityMessage.authorId, user.id))+ .where(and(...conditions))+ .orderBy(desc(communityMessage.createdAt), desc(communityMessage.id))+ .limit(limit);return rows.map(parseEmbeds);}@@ -428,6 +443,7 @@ export async function listMessagesAround(channelId: string;anchor: { createdAt: string; id: string };limit?: number;+ tag?: string;}): Promise<{older: ListedMessageRow[];@@ -468,18 +484,31 @@ export async function listMessagesAround())! as ReturnType<typeof eq>;- const [olderRows, newerRows] = await Promise.all([- db+ const selectOlder = () => db.select(listedMessageProjection).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))- .where(and(...scopeConds, olderCond))- .orderBy(desc(communityMessage.createdAt), desc(communityMessage.id))- .limit(olderHalf + 1),- db+ const selectNewer = () => db.select(listedMessageProjection).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))++ const [olderRows, newerRows] = await Promise.all([+ (opts.tag+ ? selectOlder().innerJoin(communityMessageTag, and(+ eq(communityMessageTag.messageId, communityMessage.id),+ eq(communityMessageTag.tag, opts.tag),+ ))+ : selectOlder())+ .where(and(...scopeConds, olderCond))+ .orderBy(desc(communityMessage.createdAt), desc(communityMessage.id))+ .limit(olderHalf + 1),+ (opts.tag+ ? selectNewer().innerJoin(communityMessageTag, and(+ eq(communityMessageTag.messageId, communityMessage.id),+ eq(communityMessageTag.tag, opts.tag),+ ))+ : selectNewer()).where(and(...scopeConds, newerCond))// Anchor + newerHalf newer rows + 1 extra probe..orderBy(asc(communityMessage.createdAt), asc(communityMessage.id))@@ -512,6 +541,7 @@ export async function listMessagesSince(channelId: string;since: { createdAt: string; id: string };limit?: number;+ tag?: string;}): Promise<ListedMessageRow[]> {const limit = opts.limit ?? DEFAULT_LIMIT;@@ -529,10 +559,16 @@ export async function listMessagesSince()! as ReturnType<typeof eq>);- const rows = await db+ const baseQuery = db.select(listedMessageProjection).from(communityMessage)- .innerJoin(user, eq(communityMessage.authorId, user.id))+ .innerJoin(user, eq(communityMessage.authorId, user.id));+ const rows = await (opts.tag+ ? baseQuery.innerJoin(communityMessageTag, and(+ eq(communityMessageTag.messageId, communityMessage.id),+ eq(communityMessageTag.tag, opts.tag),+ ))+ : baseQuery).where(and(...conditions)).orderBy(asc(communityMessage.createdAt), asc(communityMessage.id)).limit(limit + 1);@@ -834,6 +870,20 @@ export async function getMessageByAuthorAndNonce(return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };}+/** Update only the author's own message content. The author predicate lives in+ * the write itself so a stale permission check cannot edit another row. */+export async function updateOwnMessageContent(+ db: Database,+ data: { messageId: string; authorId: string; content: string }+) {+ const [updated] = await db+ .update(communityMessage)+ .set({ content: data.content })+ .where(and(eq(communityMessage.id, data.messageId), eq(communityMessage.authorId, data.authorId)))+ .returning({ id: communityMessage.id, channelId: communityMessage.channelId, content: communityMessage.content });+ return updated ?? null;+}+// No ordering guarantee — callers build a Map<id, row> and hydrate by id.// Unknown ids silently drop out via the natural WHERE id IN (...) semantics.//@@ -842,7 +892,7 @@ export async function getMessageByAuthorAndNonce(// per-channel sequence without a separate lookup.export async function getMessagesByIds(db: Database, ids: string[]) {if (ids.length === 0) return [];- // `ids` are the thread/forum-post parents under one channel — unbounded on a+ // `ids` are child-thread openers under one channel — unbounded on a// busy forum. Chunk for D1's 100-param limit; no order/limit → concat.const rows = (await Promise.all(diff --git a/src/shared/src/db/queries/community/reaction.ts b/src/shared/src/db/queries/community/reaction.tsindex 3af37e5e8..2581af3e7 100644--- a/src/shared/src/db/queries/community/reaction.ts+++ b/src/shared/src/db/queries/community/reaction.ts@@ -44,7 +44,7 @@ export async function getMessageReactions(db: Database, messageId: string) {export async function listReactionsByMessageIds(db: Database,messageIds: string[],- currentUserId: string+ _currentUserId: string) {if (messageIds.length === 0) return [];return dbdiff --git a/src/shared/src/db/queries/community/read-state.ts b/src/shared/src/db/queries/community/read-state.tsindex 0be72796a..cfb97c6e1 100644--- a/src/shared/src/db/queries/community/read-state.ts+++ b/src/shared/src/db/queries/community/read-state.ts@@ -154,7 +154,7 @@ export async function markAllServerChannelsRead(// inbox unread + mentions consumers use (resolved once per fetch via// `listVisibleChannelIdsForUser`). Convergence on the id set replaces the// old inlined category `or()`, which climbed nothing and so evaluated child- // threads/forum-posts by their own (always-NULL) categoryId as public. The+ // child threads by their own (always-NULL) categoryId as public. The// id set parent-climbs, so a child under a private parent the viewer can't// see is now correctly EXCLUDED — mark-all no longer writes read-state rows// for channels behind an invisible private parent.diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.tsindex 1c47726df..2dac1816d 100644--- a/src/shared/src/db/queries/community/server.ts+++ b/src/shared/src/db/queries/community/server.ts@@ -9,8 +9,11 @@ import {} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";+import { nanoid } from "nanoid";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";import { MENTION_KIND } from "../../../constants/community";+import { withUniqueDiscriminator } from "../user";+import { parseNameAndTag } from "../../../lib/discriminator";export async function createServer(db: Database,@@ -26,26 +29,44 @@ export async function createServer(userDiscriminator: string;};}> {- const [server] = await db- .insert(communityServer)- .values({- name: data.name,- description: data.description ?? "",- ownerId: data.ownerId,- })- .returning();+ // Mint the id up-front so the discriminator (an FNV-1a hash of the id) is+ // written in the same INSERT — same pattern as createUser/createBot. Only the+ // server row carries the discriminator, so wrap just that insert (not the+ // whole batch): category/channel/member rows don't touch the (name,+ // discriminator) unique index, so they run after the server row wins its+ // discriminator. A collision against idx_community_server_name_discriminator+ // salt-retries the server insert; throw-at-cap on exhaustion (loud, never a+ // silent duplicate).+ const id = nanoid();+ const server = await withUniqueDiscriminator(+ db,+ { id, name: data.name },+ async (discriminator) => {+ const [row] = await db+ .insert(communityServer)+ .values({+ id,+ name: data.name,+ discriminator,+ description: data.description ?? "",+ ownerId: data.ownerId,+ })+ .returning();+ return row!;+ }+ );const [category] = await db.insert(communityCategory).values({- serverId: server!.id,+ serverId: server.id,name: "All",position: 0,}).returning();await db.insert(communityChannel).values({- serverId: server!.id,+ serverId: server.id,categoryId: category!.id,name: "general",type: "text",@@ -55,7 +76,7 @@ export async function createServer(const [memberRow] = await db.insert(communityServerMember).values({- serverId: server!.id,+ serverId: server.id,userId: data.ownerId,role: "owner",railOrder: 0,@@ -76,7 +97,7 @@ export async function createServer(.where(eq(user.id, data.ownerId));return {- server: server!,+ server,ownerMember: {id: memberRow!.id,userId: memberRow!.userId,@@ -148,6 +169,7 @@ export async function listUserServers(db: Database, userId: string) {.select({id: communityServer.id,name: communityServer.name,+ discriminator: communityServer.discriminator,description: communityServer.description,icon: communityServer.icon,ownerId: communityServer.ownerId,@@ -173,48 +195,41 @@ export async function listUserServers(db: Database, userId: string) {}/**- * Resolve a server by ID or NAME, scoped to servers `userId` is a member of.+ * Resolve a server by unique handle, scoped to servers+ * `userId` is a member of.* Returns an ARRAY — the caller decides what "ambiguous" means (0 = not- * found/not a member, 1 = resolved, 2+ = ambiguous name — ids are always- * unique so only the name-match branch can return >1). Used by- * `resolveTargetForMember` (debt #5 — ambiguity is not a hard error, the- * agent picks from a hint list).+ * found/not a member, 1 = resolved). Bare names are not an address.*/export async function resolveServerByNameForMember(db: Database,userId: string,- nameOrId: string+ handleRef: string) {- const rows = await db- .select({- id: communityServer.id,- name: communityServer.name,- })- .from(communityServer)- .innerJoin(- communityServerMember,- and(- eq(communityServerMember.serverId, communityServer.id),- eq(communityServerMember.userId, userId)+ const handle = parseNameAndTag(handleRef);+ if (handle) {+ return db+ .select({+ id: communityServer.id,+ name: communityServer.name,+ discriminator: communityServer.discriminator,+ })+ .from(communityServer)+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityServer.id),+ eq(communityServerMember.userId, userId)+ ))- )- .where(eq(communityServer.id, nameOrId));- if (rows.length > 0) return rows;+ .where(+ and(+ sql`${communityServer.name} COLLATE NOCASE = ${handle.name}`,+ eq(communityServer.discriminator, handle.discriminator)+ )+ );+ }- return db- .select({- id: communityServer.id,- name: communityServer.name,- })- .from(communityServer)- .innerJoin(- communityServerMember,- and(- eq(communityServerMember.serverId, communityServer.id),- eq(communityServerMember.userId, userId)- )- )- .where(eq(communityServer.name, nameOrId));+ return [];}export async function getServersByIds(db: Database, serverIds: string[]) {diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex 06a985f1e..c940ed572 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -1,11 +1,11 @@-import { and, eq, inArray } from "drizzle-orm";+import { and, asc, eq, inArray, lte, sql } from "drizzle-orm";import { communityChannel, communityChannelMember } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";import { chunk, maxRowsPerInsert, D1_MAX_IN_PARAMS } from "../_chunk";import { type ParticipantSource } from "../../../constants/community";-// The NOTIFICATION set for a thread OR forum_post — now relation='notify' rows+// The NOTIFICATION set for a child thread — relation='notify' rows// on `community_channel_member` (formerly the standalone// community_thread_participant table). A thread/post is not an access unit —// any parent-channel member can read it — so these rows only decide who gets@@ -117,15 +117,47 @@ export async function listThreadParticipants();}-// Batch participant hydration for many channels at once — the forum post list's+// Batch participant hydration for many channels at once — the forum list's// per-card AvatarGroup. One query for N post ids instead of N. Rows carry the// channel id so the caller can group them back per post; `addedAt` orders the// group. Soft-deleted users drop out via the inner join.export async function listParticipantsForChannels(db: Database,- channelIds: string[]+ channelIds: string[],+ limitPerChannel?: number) {if (channelIds.length === 0) return [];+ if (limitPerChannel !== undefined) {+ const ranked = db+ .select({+ channelId: communityChannelMember.channelId,+ userId: communityChannelMember.userId,+ addedAt: communityChannelMember.addedAt,+ userName: user.name,+ userImage: user.image,+ participantCount: sql<number>`count(*) over (partition by ${communityChannelMember.channelId})`.as("participant_count"),+ rank: sql<number>`row_number() over (partition by ${communityChannelMember.channelId} order by ${communityChannelMember.addedAt}, ${communityChannelMember.userId})`.as("participant_rank"),+ })+ .from(communityChannelMember)+ .innerJoin(user, eq(user.id, communityChannelMember.userId))+ .where(and(+ inArray(communityChannelMember.channelId, channelIds),+ eq(communityChannelMember.relation, "notify")+ ))+ .as("ranked_participants");+ return db+ .select({+ channelId: ranked.channelId,+ userId: ranked.userId,+ addedAt: ranked.addedAt,+ userName: ranked.userName,+ userImage: ranked.userImage,+ participantCount: ranked.participantCount,+ })+ .from(ranked)+ .where(lte(ranked.rank, limitPerChannel))+ .orderBy(asc(ranked.channelId), asc(ranked.addedAt), asc(ranked.userId));+ }return db.select({channelId: communityChannelMember.channelId,@@ -183,7 +215,7 @@ export async function removeThreadParticipant(return rows[0] ?? null;}-// Drop a user's notify rows from EVERY child channel (forum_post OR thread)+// Drop a user's notify rows from EVERY child thread// under a top-level unit. Called when a member is removed from a forum/channel's// access roster: their access is gone, so their leftover notify rows on the// unit's posts/threads must go too. A later mention/speak (which requiresdiff --git a/src/shared/src/db/queries/conversation.ts b/src/shared/src/db/queries/conversation.tsindex 8c0db9fd4..aa15d1135 100644--- a/src/shared/src/db/queries/conversation.ts+++ b/src/shared/src/db/queries/conversation.ts@@ -1,4 +1,4 @@-import { eq, and, desc, ne, lt, sql, count as drizzleCount, inArray, isNull, isNotNull } from "drizzle-orm";+import { eq, and, desc, ne, lt, sql, inArray, isNull, isNotNull } from "drizzle-orm";import { conversation, message } from "../schema";import type { Database } from "../index";import { TASK_TYPES, type TaskType } from "../../constants";diff --git a/src/shared/src/db/queries/user.ts b/src/shared/src/db/queries/user.tsindex b7ada2b14..3648a12dd 100644--- a/src/shared/src/db/queries/user.ts+++ b/src/shared/src/db/queries/user.ts@@ -6,8 +6,18 @@ import { escapeLikePattern } from "../../utils/sql-like";import { computeDiscriminator } from "../../lib/discriminator";import { isUniqueConstraintError } from "../../utils/db-errors";-/** Bounded retry ceiling for `withUniqueDiscriminator`/`probeAvailableDiscriminator` salting. */+/** Per-width salt-retry budget before widening the discriminator by one digit. */const MAX_DISCRIMINATOR_ATTEMPTS = 5;+/** Default (narrowest) discriminator width — the pre-widening `name#0042` size. */+const MIN_DISCRIMINATOR_WIDTH = 4;+/**+ * Absurd-width deadloop catcher. A width this large means 10^18 same-name+ * entities, which is physically impossible — so reaching it is a bug, not real+ * contention. We throw LOUDLY there (never a silent cap): "never-cap" means no+ * ceiling under REAL contention, and 4→5 digits alone already needs 10^4+ * same-name rows. Also keeps 10**width inside JS safe-integer range.+ */+const MAX_DISCRIMINATOR_WIDTH = 18;// ─── Column projections ──────────────────────────────────────────────────────//@@ -216,69 +226,86 @@ export async function getUserByNameAndDiscriminator(}/**- * Wrap an insert that writes `computeDiscriminator(id)` so a collision- * against the partial unique index (`idx_user_name_discriminator`, migration- * 0055) self-heals instead of failing the caller's whole request. Calls- * `insertFn(discriminator)`; on `isUniqueConstraintError` retries with- * `computeDiscriminator(id + ":" + attempt)` and a FRESH `insertFn` call- * (the caller's `insertFn` closure re-reads the salted discriminator each- * time — see `createUser`/`createBot`), bounded to- * `MAX_DISCRIMINATOR_ATTEMPTS`. Throws past the bound rather than looping- * forever — a persistent failure past a handful of attempts is almost- * certainly not actually a discriminator collision.+ * Wrap an insert that writes `computeDiscriminator(id)` so a collision against+ * the partial unique index (`idx_user_name_discriminator`, 0055 /+ * `idx_community_server_name_discriminator`, 0080) self-heals instead of+ * failing the caller's whole request. Calls `insertFn(discriminator)`; on+ * `isUniqueConstraintError` re-salts with `computeDiscriminator(id:width:attempt)`+ * and a FRESH `insertFn` call (the caller's closure re-reads the salted+ * discriminator each time — see `createUser`/`createBot`/`createServer`).+ *+ * NEVER caps: each width gets `MAX_DISCRIMINATOR_ATTEMPTS` salt tries, then the+ * discriminator WIDENS by one digit and keeps going. width=4/attempt=0 uses the+ * bare id (byte-identical to the pre-widening value, so existing rows never+ * rotate). Loud throughout — a non-unique error rethrows immediately, and the+ * final salted value is never handed back unchecked: the winning value is the+ * one whose `insertFn` actually committed. The only throw is the absurd-width+ * deadloop catcher (`MAX_DISCRIMINATOR_WIDTH`), which is loud, not a silent cap.*/export async function withUniqueDiscriminator<T>(_db: Database,input: { id: string; name: string },insertFn: (discriminator: string) => Promise<T>): Promise<T> {- let lastErr: unknown;- for (let attempt = 0; attempt < MAX_DISCRIMINATOR_ATTEMPTS; attempt++) {- const discriminator =- attempt === 0- ? computeDiscriminator(input.id)- : computeDiscriminator(`${input.id}:${attempt}`);- try {- return await insertFn(discriminator);- } catch (err) {- if (!isUniqueConstraintError(err)) throw err;- lastErr = err;+ for (let width = MIN_DISCRIMINATOR_WIDTH; width <= MAX_DISCRIMINATOR_WIDTH; width++) {+ for (let attempt = 0; attempt < MAX_DISCRIMINATOR_ATTEMPTS; attempt++) {+ const discriminator =+ width === MIN_DISCRIMINATOR_WIDTH && attempt === 0+ ? computeDiscriminator(input.id)+ : computeDiscriminator(`${input.id}:${width}:${attempt}`, width);+ try {+ return await insertFn(discriminator);+ } catch (err) {+ if (!isUniqueConstraintError(err)) throw err;+ }}}- throw lastErr;+ // Reached only at 10^MAX_DISCRIMINATOR_WIDTH same-name entities = impossible =+ // bug. Loud, never a silent cap.+ throw new Error(+ `discriminator allocation exceeded width ${MAX_DISCRIMINATOR_WIDTH} for name "${input.name}" — not a real collision`+ );}/*** Best-effort SELECT-based pre-check for callers that can't wrap their own- * insert (Better Auth's `user.create.before` hook — the adapter inserts- * AFTER the hook returns, so there's no insert call here to retry). Returns- * an available discriminator, salting past a live `(name, discriminator)`- * collision the same way `withUniqueDiscriminator` does. This is weaker than- * `withUniqueDiscriminator`: a concurrent signup of the exact same name at- * the exact same instant can still race past this check. The partial unique- * index is the actual backstop for that residual window — a double-loss- * fails Better Auth's insert, the signup surfaces a generic error, and the- * user's retry mints a fresh id/discriminator pair. Self-healing, not- * silently broken; not full parity with the insert-wrapped paths.+ * insert (Better Auth's `user.create.before` hook — the adapter inserts AFTER+ * the hook returns, so there's no insert call here to retry). Returns an+ * available discriminator, WIDENING the probe space exactly like+ * `withUniqueDiscriminator` widens its insert space: each width gets+ * `MAX_DISCRIMINATOR_ATTEMPTS` salt probes, then the discriminator widens by a+ * digit and keeps going — so email signup NEVER caps at 4 digits (the+ * insert-wrapped and probe exits both honour "never-cap"; only the mechanism+ * differs, since probe can't wrap its own insert).+ *+ * This is weaker than `withUniqueDiscriminator`: a concurrent signup of the+ * same name at the same instant can still race past the SELECT. The loud+ * backstop for probe is NOT here (this function never throws on collision) —+ * it is DOWNSTREAM at Better Auth's insert, which hits the partial unique index+ * and self-heals (the signup surfaces a generic error and the user's retry+ * mints a fresh id). Loud on collision, never a silent duplicate handle — just+ * with the loud terminal one hop downstream. The absurd-width catcher below is+ * the only throw here, matching `withUniqueDiscriminator`.*/export async function probeAvailableDiscriminator(db: Database,input: { id: string; name: string }): Promise<string> {- for (let attempt = 0; attempt < MAX_DISCRIMINATOR_ATTEMPTS; attempt++) {- const discriminator =- attempt === 0- ? computeDiscriminator(input.id)- : computeDiscriminator(`${input.id}:${attempt}`);- const existing = await getUserByNameAndDiscriminator(db, input.name, discriminator);- if (!existing) return discriminator;+ for (let width = MIN_DISCRIMINATOR_WIDTH; width <= MAX_DISCRIMINATOR_WIDTH; width++) {+ for (let attempt = 0; attempt < MAX_DISCRIMINATOR_ATTEMPTS; attempt++) {+ const discriminator =+ width === MIN_DISCRIMINATOR_WIDTH && attempt === 0+ ? computeDiscriminator(input.id)+ : computeDiscriminator(`${input.id}:${width}:${attempt}`, width);+ const existing = await getUserByNameAndDiscriminator(db, input.name, discriminator);+ if (!existing) return discriminator;+ }}- // Ceiling exhausted — hand back a salt PAST the ones the loop just- // probed, not the last-tried value. `id:${MAX-1}` would be guaranteed- // to collide (the loop just saw it taken); `id:${MAX}` has NOT been- // probed, so the caller's INSERT still has a chance. The partial unique- // index is the real backstop for a true concurrent double-collision.- return computeDiscriminator(`${input.id}:${MAX_DISCRIMINATOR_ATTEMPTS}`);+ // Reached only at 10^MAX_DISCRIMINATOR_WIDTH same-name entities = impossible =+ // bug. Loud, never a silent cap (mirrors withUniqueDiscriminator).+ throw new Error(+ `discriminator probe exceeded width ${MAX_DISCRIMINATOR_WIDTH} for name "${input.name}" — not a real collision`+ );}export async function createUser(diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex f26e1f7cc..b5740e9b6 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -588,7 +588,6 @@ export {isAssignableRole,isChannelType,isForum,- isForumPost,isThread,isDm,isMessageBearingSurface,diff --git a/src/shared/src/lib/discriminator.test.ts b/src/shared/src/lib/discriminator.test.tsindex 24e0922d5..cce1bd65c 100644--- a/src/shared/src/lib/discriminator.test.ts+++ b/src/shared/src/lib/discriminator.test.ts@@ -1,13 +1,14 @@import { describe, it, expect } from "vitest";-import { computeDiscriminator, parseNameAndTag } from "./discriminator";+import { computeDiscriminator, parseNameAndTag, formatHandle } from "./discriminator";describe("computeDiscriminator", () => {- it("is deterministic — same id returns same output across calls", () => {+ it("is deterministic — same (seed, width) returns same output across calls", () => {const id = "user_abcdef1234567890";expect(computeDiscriminator(id)).toBe(computeDiscriminator(id));+ expect(computeDiscriminator(id, 6)).toBe(computeDiscriminator(id, 6));});- it("returns exactly 4 digits, zero-padded", () => {+ it("defaults to exactly 4 digits, zero-padded (pre-widening value unchanged)", () => {for (const id of ["a", "ab", "user_1", "x".repeat(50)]) {const out = computeDiscriminator(id);expect(out).toMatch(/^\d{4}$/);@@ -15,6 +16,14 @@ describe("computeDiscriminator", () => {}});+ it("pads to its OWN width — width N returns exactly N digits (never a global max)", () => {+ for (let width = 4; width <= 9; width++) {+ const out = computeDiscriminator("some_seed", width);+ expect(out).toMatch(new RegExp(`^\\d{${width}}$`));+ expect(out.length).toBe(width);+ }+ });+it("distributes across the full 0000-9999 range", () => {// Deterministic pseudo-ids — no clock/random needed. 10k samples land in// a wide band; we just want to prove we aren't stuck near 0.@@ -33,15 +42,28 @@ describe("parseNameAndTag", () => {expect(parseNameAndTag("ada#0042")).toEqual({ name: "ada", discriminator: "0042" });});- it("preserves internal # in the name (only trailing #dddd is a tag)", () => {+ it("preserves internal # in the name (only the LAST #dddd is a tag)", () => {expect(parseNameAndTag("a#b#0042")).toEqual({ name: "a#b", discriminator: "0042" });});+ // Variable-width: a 5+-digit tail IS now a valid (widened) tag. This is the+ // intended behavior change vs the old fixed-4 `\d{4}` (which returned null).+ it("accepts a widened 5+-digit discriminator", () => {+ expect(parseNameAndTag("ada#00042")).toEqual({ name: "ada", discriminator: "00042" });+ expect(parseNameAndTag("ada#1234567")).toEqual({ name: "ada", discriminator: "1234567" });+ });++ // Single-value (Ingaborg #87 2c): a name that itself ends in digits splits to+ // exactly one (name, discriminator) at any width — the LAST #, all-digit tail.+ it("splits a digit-ending name to exactly one (name, discriminator)", () => {+ expect(parseNameAndTag("user123#4567")).toEqual({ name: "user123", discriminator: "4567" });+ expect(parseNameAndTag("user123#45678")).toEqual({ name: "user123", discriminator: "45678" });+ });+it("returns null when the tag is missing or malformed", () => {expect(parseNameAndTag("ada")).toBeNull();expect(parseNameAndTag("ada#nope")).toBeNull();- expect(parseNameAndTag("ada#42")).toBeNull();- expect(parseNameAndTag("ada#00042")).toBeNull();+ expect(parseNameAndTag("ada#42")).toBeNull(); // fewer than 4 digits is not a tagexpect(parseNameAndTag("#0042")).toBeNull();});@@ -49,3 +71,18 @@ describe("parseNameAndTag", () => {expect(parseNameAndTag(" ada #0042")).toEqual({ name: "ada", discriminator: "0042" });});});++describe("formatHandle ↔ parseNameAndTag round-trip", () => {+ // Ingaborg #87 2b: inverse at EACH width; ④ formatHandle bare-concats (no pad+ // to a uniform width), so the handle carries the disc's true width verbatim.+ it("round-trips at every width 4..8", () => {+ for (let width = 4; width <= 8; width++) {+ const disc = computeDiscriminator("round_trip_seed", width);+ const handle = formatHandle("ada", disc);+ expect(handle).toBe(`ada#${disc}`); // bare concat, no extra padding+ expect(parseNameAndTag(handle)).toEqual({ name: "ada", discriminator: disc });+ // The parsed disc width equals the true allocation width — no truncate, no pad-up.+ expect(parseNameAndTag(handle)!.discriminator.length).toBe(width);+ }+ });+});diff --git a/src/shared/src/lib/discriminator.ts b/src/shared/src/lib/discriminator.tsindex e72bbd3f7..9eb6836c5 100644--- a/src/shared/src/lib/discriminator.ts+++ b/src/shared/src/lib/discriminator.ts@@ -1,6 +1,11 @@-// 4-digit user discriminator (`name#0042`) derived from user.id via FNV-1a-// modulo 10 000. Hash on the immutable id, not the name, so renames don't-// rotate a user's tag. Stored on `user.discriminator` (see migration 0051).+// Variable-width decimal discriminator (`name#0042`) derived from a seed via+// FNV-1a modulo 10^width. The DEFAULT width is 4 (`"0000"`–`"9999"`); the+// allocator widens by one digit per exhausted collision budget so a name's tag+// pool never caps (see withUniqueDiscriminator). Derived from the immutable id,+// not the name — but rename-stability rests on the STORED value being written+// once and never recomputed (the disc is opaque; the UNIQUE index is the sole+// arbiter), not on recomputability. Stored on `user.discriminator` (0051) /+// `community_server.discriminator` (0079).const FNV_OFFSET_BASIS_32 = 0x811c9dc5;const FNV_PRIME_32 = 0x01000193;@@ -18,25 +23,30 @@ function fnv1a32(input: string): number {}/**- * Compute the 4-digit discriminator for a user id.+ * Compute a decimal discriminator for a seed at the given width.*- * - Deterministic: same id → same output, no clock / random inputs.- * - Always exactly 4 characters, zero-padded (`"0042"`, not `"42"`).- * - Range `"0000"`–`"9999"`.+ * - Deterministic: same (seed, width) → same output, no clock / random inputs.+ * - Zero-padded to EXACTLY `width` digits (`computeDiscriminator(id)` === the+ * pre-widening 4-digit value byte-for-byte, so existing rows never rotate).+ * - Padded to its OWN width — a width-5 disc is 5 digits (an honest "the 4-digit+ * pool was saturated" signal), never padded up to a uniform global width.*/-export function computeDiscriminator(userId: string): string {- return (fnv1a32(userId) % 10000).toString().padStart(4, "0");+export function computeDiscriminator(seed: string, width = 4): string {+ return (fnv1a32(seed) % 10 ** width).toString().padStart(width, "0");}/*** Parse a `name#0042` search string into its two halves.- * Returns `null` when the string doesn't match the exact format- * (name may contain `#`; only the LAST `#dddd` suffix is treated as a tag).+ * Returns `null` when the string doesn't match the format (name may contain+ * `#`; only the LAST `#dddd` suffix — 4+ decimal digits — is treated as a tag).+ * `\d{4,}` (length, not charset) so a widened 5+-digit tag still parses; the+ * LAST `#` split keeps a name that itself ends in digits (`user123#4567`)+ * splitting to exactly one (name, discriminator).*/export function parseNameAndTag(q: string): { name: string; discriminator: string } | null {- const m = /^(.+)#(\d{4})$/.exec(q);+ const m = /^(.+)#(\d{4,})$/.exec(q);if (!m) return null;const name = m[1]!.trim();const discriminator = m[2]!;diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex f28edd847..01d3850b3 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1133,8 +1133,8 @@ export type CommunityBotAddToServerRequest = z.infer<>;// ----------------------------------------------------------------------------// Community agent CLI bridge — `withAgentRunnerAuth`-mounted `/api/community/agent/*`-// request/response validators. Mirror the lifted `@alook/shared/community-cli-contract`+// Community REST agent-door request/response validators. Mirror the lifted+// `@alook/shared/community-cli-contract`// wire types verbatim (see `community-cli-contract.ts`). `agentId` is deliberately// OMITTED from every request schema below — identity comes from the `crk_` bearer// via `withAgentRunnerAuth`, never a client-supplied field (see plan §2/§7).@@ -1169,6 +1169,10 @@ export const CommunityAgentSendRequestSchema = z// retries; server dedupes on (author, nonce). Bounded length so a client// can't stuff arbitrary data. Absent = no dedup (legacy behavior).nonce: z.string().min(1).max(128).optional(),+ // When the resolved target is a forum this message becomes the opener and+ // the server synchronously creates its child thread. A first reply is a+ // separate ordinary send to the returned thread ref; there is no combined+ // title/body field on the canonical message contract.}).refine((d) => d.content.text.trim().length > 0 || d.attachments.length > 0,@@ -1176,7 +1180,7 @@ export const CommunityAgentSendRequestSchema = z);export type CommunityAgentSendRequest = z.infer<typeof CommunityAgentSendRequestSchema>;-// Response body for POST /api/community/agent/attachmentUpload. Bots see+// Response body for POST /api/community/channels/{id}/attachments. Bots see// filename+contentType+size and nothing else — no url, no r2 key, no path.export const CommunityAgentAttachmentUploadResponseSchema = z.object({id: z.string(),@@ -1232,13 +1236,10 @@ export type CommunityAgentListChannelsRequest = z.infer<typeof CommunityAgentListChannelsRequestSchema>;-// Body for POST /api/community/createPost (`alook message post`). `forum` is a-// forum REF (`/server/forum`), resolved server-side like `send`'s `channel`.-// `title` is the raw human title — its slug becomes the post's addressing name,-// the original is captured into display_title (B4b). Content follows the same-// opener contract as a forum post: text OR at least one attachment (an-// attachment-only post is legitimate). `attachments` are pending ids the bot-// uploaded bound to the FORUM (the post channel doesn't exist at upload time).+// CLI adapter input for `alook message post`. The daemon maps this shape onto+// the canonical forum send body: title → opener message, content → the ordinary+// thread's first reply. An attachment-only reply is legitimate; pending ids are+// uploaded against the forum before the thread exists.export const CommunityAgentCreatePostRequestSchema = z.object({forum: z.string().min(1),@@ -1300,7 +1301,7 @@ export type CommunityAgentReactAddRequest = z.infer<typeof CommunityAgentReactAddRequestSchema>;-// POST /api/community/agent/friendRequest — body `{ username: "name#0042" }`.+// POST /api/community/friends/request — body `{ username: "name#0042" }`.// Only the human `name#discriminator` handle is accepted (parsed + resolved// server-side); a raw userId is intentionally NOT accepted so the agent surface// mirrors the human handle format.@@ -1311,8 +1312,7 @@ export type CommunityAgentFriendRequest = z.infer<typeof CommunityAgentFriendRequestSchema>;-// POST /api/community/agent/listFriends — empty body, kept for POST uniformity-// with the rest of `/api/community/agent/*`.+// Empty body retained for the shared list-friends request contract.export const CommunityAgentListFriendsSchema = z.object({});export type CommunityAgentListFriends = z.infer<typeof CommunityAgentListFriendsSchemadiff --git a/src/shared/src/utils/community-roles.test.ts b/src/shared/src/utils/community-roles.test.tsindex 0fee77bcf..8cdf10958 100644--- a/src/shared/src/utils/community-roles.test.ts+++ b/src/shared/src/utils/community-roles.test.ts@@ -12,21 +12,18 @@ import {} from "./community-roles"describe("isMessageBearingSurface", () => {- it("is true for surfaces that bear messages: text, forum_post, thread, dm", () => {+ it("is true for all 4 stored types — text/forum/thread/dm", () => {expect(isMessageBearingSurface("text")).toBe(true)- expect(isMessageBearingSurface("forum_post")).toBe(true)+ expect(isMessageBearingSurface("forum")).toBe(true)expect(isMessageBearingSurface("thread")).toBe(true)expect(isMessageBearingSurface("dm")).toBe(true)})- it("is false for a forum top-level (a post index, not a message surface)", () => {- expect(isMessageBearingSurface("forum")).toBe(false)- })-- it("is false for null/undefined/unknown", () => {+ it("is false for null/undefined/unknown — equivalent to isStoredChannelType(t), so anything outside the closed 4-value set is denied", () => {expect(isMessageBearingSurface(null)).toBe(false)expect(isMessageBearingSurface(undefined)).toBe(false)expect(isMessageBearingSurface("bogus")).toBe(false)+ expect(isMessageBearingSurface("forum_post")).toBe(false)})})@@ -34,53 +31,39 @@ describe("isChannelType (creatable top-level types)", () => {it("accepts only text and forum", () => {expect(isChannelType("text")).toBe(true)expect(isChannelType("forum")).toBe(true)- expect(isChannelType("forum_post")).toBe(false)expect(isChannelType("thread")).toBe(false)expect(isChannelType("dm")).toBe(false)})})// B0 trait table — lock each type's trait values to today's hand-branched-// behavior (the assignments Ingaborg #41 enumerated from current code). This is-// the "scan enum assignment vs current code" gate as an executable assertion:-// a later refactor that silently flips a type's axis fails here. B0 is behavior--// inert (nothing consumes CHANNEL_TRAITS until B1), so this is the only consumer-// today and the guard that the extraction stayed behavior-invariant.+// behavior. This is the "scan enum assignment vs current code" gate as an+// executable assertion: a later refactor that silently flips a type's axis+// fails here.describe("CHANNEL_TRAITS (B0 trait model)", () => {it("maps each stored channel type to its extracted trait values", () => {expect(CHANNEL_TRAITS).toEqual({text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },- forum_post: { addressing: "by-child-name", visibility: "inherit-parent", reach: "participant-set", creation: "pure-create" },thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create" },dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create" },})})- it("each CreationTrait value names exactly one collision contract (Aigneis #45 / Blondie #49)", () => {+ it("each CreationTrait value names exactly one collision contract", () => {// reject-on-collision = top-level 409/0-rows (idx_channel_server_name);- // pure-create = forum_post bump→N distinct; get-or-create = thread/dm- // fetch-winner. A value spanning two contracts has no single oracle.+ // get-or-create = thread/dm fetch-winner.expect(CHANNEL_TRAITS.text.creation).toBe("reject-on-collision")expect(CHANNEL_TRAITS.forum.creation).toBe("reject-on-collision")- expect(CHANNEL_TRAITS.forum_post.creation).toBe("pure-create")expect(CHANNEL_TRAITS.thread.creation).toBe("get-or-create")expect(CHANNEL_TRAITS.dm.creation).toBe("get-or-create")})it("covers every stored channel type (no type left un-traited)", () => {- const types: StoredChannelType[] = ["text", "forum", "forum_post", "thread", "dm"]+ const types: StoredChannelType[] = ["text", "forum", "thread", "dm"]for (const t of types) expect(CHANNEL_TRAITS[t]).toBeDefined()expect(Object.keys(CHANNEL_TRAITS).sort()).toEqual([...types].sort())})-- it("addressing values are distinct per addressing strategy (no accidental reuse across strategies)", () => {- // forum_post addresses by its own child name, thread by root seq — the two- // must NOT share an addressing value (they resolve on different keys; a- // shared value would collapse the resolver's two branches, the exact- // do-not-fold the resolver comment warns about).- expect(CHANNEL_TRAITS.forum_post.addressing).not.toBe(CHANNEL_TRAITS.thread.addressing)- })})// B2 reach axis — the single-source classification the three reach faces (fanout@@ -89,14 +72,12 @@ describe("reach axis helpers", () => {it("channelReach reads the reach value straight from the trait table", () => {expect(channelReach("text")).toBe("server-or-roster")expect(channelReach("forum")).toBe("server-or-roster")- expect(channelReach("forum_post")).toBe("participant-set")expect(channelReach("thread")).toBe("participant-set")expect(channelReach("dm")).toBe("dm-pair")})- it("reachIsParticipantSet is true for exactly thread + forum_post (the enroll ⟷ read shared predicate)", () => {+ it("reachIsParticipantSet is true for exactly thread (the enroll ⟷ read shared predicate)", () => {expect(reachIsParticipantSet("thread")).toBe(true)- expect(reachIsParticipantSet("forum_post")).toBe(true)expect(reachIsParticipantSet("text")).toBe(false)expect(reachIsParticipantSet("forum")).toBe(false)expect(reachIsParticipantSet("dm")).toBe(false)@@ -106,12 +87,14 @@ describe("reach axis helpers", () => {expect(reachIsParticipantSet(null)).toBe(false)expect(reachIsParticipantSet(undefined)).toBe(false)expect(reachIsParticipantSet("bogus")).toBe(false)+ expect(reachIsParticipantSet("forum_post")).toBe(false)})- it("isStoredChannelType guards the five stored types", () => {- for (const t of ["text", "forum", "forum_post", "thread", "dm"]) expect(isStoredChannelType(t)).toBe(true)+ it("isStoredChannelType guards the four stored types", () => {+ for (const t of ["text", "forum", "thread", "dm"]) expect(isStoredChannelType(t)).toBe(true)expect(isStoredChannelType(null)).toBe(false)expect(isStoredChannelType("channel")).toBe(false)+ expect(isStoredChannelType("forum_post")).toBe(false)})})@@ -121,7 +104,6 @@ describe("visibility axis helpers", () => {it("channelVisibility reads the visibility value straight from the trait table", () => {expect(channelVisibility("text")).toBe("own-roster")expect(channelVisibility("forum")).toBe("own-roster")- expect(channelVisibility("forum_post")).toBe("inherit-parent")expect(channelVisibility("thread")).toBe("inherit-parent")expect(channelVisibility("dm")).toBe("dm-participant")})@@ -130,7 +112,6 @@ describe("visibility axis helpers", () => {expect(visibilityIsDmParticipant("dm")).toBe(true)expect(visibilityIsDmParticipant("text")).toBe(false)expect(visibilityIsDmParticipant("forum")).toBe(false)- expect(visibilityIsDmParticipant("forum_post")).toBe(false)expect(visibilityIsDmParticipant("thread")).toBe(false)})diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.tsindex 54e7118a7..41d2b80c6 100644--- a/src/shared/src/utils/community-roles.ts+++ b/src/shared/src/utils/community-roles.ts@@ -4,10 +4,16 @@ export type ChannelType = "text" | "forum"// with `type='dm'` in migration 0068 (`isDm` below has always checked for it),// but this union previously omitted `dm` — a real type-level gap. Widened to// the full stored set so code that switches on a channel's stored type is-// exhaustive over DM channels too. (We keep `forum_post`, NOT the `post` rename-// from the abandoned PR-408 batch1 — see-// plans/22-community-unified-actor-route-unify.md §7 ADAPT.)-export type StoredChannelType = "text" | "forum" | "forum_post" | "thread" | "dm"+// exhaustive over DM channels too.+//+// `forum_post` deleted: a post is now just an ordinary thread whose opener+// message happens to have a title-shaped `content` — no distinguishing type+// value, because a post under a forum has zero structural difference from+// any other thread. Migration 0082 type-flips every existing forum_post row+// to `thread` before this union narrows; the fold is zero-schema-difference+// by construction (see create-channels.ts's createMessageWithThread doc for+// the full shape).+export type StoredChannelType = "text" | "forum" | "thread" | "dm"export const ROLES = {OWNER: "owner",@@ -63,10 +69,6 @@ export function isForum(t: string | null | undefined): boolean {return t === "forum"}-export function isForumPost(t: string | null | undefined): boolean {- return t === "forum_post"-}-export function isThread(t: string | null | undefined): boolean {return t === "thread"}@@ -75,8 +77,14 @@ export function isDm(t: string | null | undefined): boolean {return t === "dm"}+// Every stored type is message-bearing — a channel/forum/thread/DM can all+// receive a send. This IS isStoredChannelType(t); kept as its own named+// predicate so send/react/pin call sites read as "is this surface legitimate+// to write to," not a re-derived type check (phase2 forum≡thread reversed+// this from an allowlist that excluded plain `forum` — see git history on+// this function for that transition).export function isMessageBearingSurface(t: string | null | undefined): boolean {- return t === "text" || t === "forum_post" || t === "thread" || t === "dm"+ return isStoredChannelType(t)}// ─────────────────────────────────────────────────────────────────────────────@@ -109,16 +117,19 @@ export function isMessageBearingSurface(t: string | null | undefined): boolean {// (parse → id) and the single canonical-ref emitter (id → ref), which must read// the SAME value so a type can never have two addressing paths (red-line ①).// by-server-name — `/server/<name>`; top-level, name unique per server.-// by-child-name — `/server/<forum>/<post>`; slug unique within parent forum.// by-root-seq — `/server/<channel>/#<rootSeq>`; anchored on root msg seq.// by-peer-identity— `/.dm/<peer#0042>`; the OTHER access member's handle.-export type AddressingTrait = "by-server-name" | "by-child-name" | "by-root-seq" | "by-peer-identity"+// (`by-child-name` — `/server/<forum>/<post>` — deleted with forum_post,+// phase2 forum≡thread: a post's only addressing was by its own slug under+// the forum; a post is now an ordinary thread, addressed by-root-seq like+// any other.)+export type AddressingTrait = "by-server-name" | "by-root-seq" | "by-peer-identity"// Who can SEE the channel (read axis). The miss semantics (no access → 404, the// existence-non-disclosure red-line ②) are welded to the value, not per-type.// own-roster — its own server-membership / private-category roster.// inherit-parent — climbs `parentChannelId` to the parent forum/channel's-// roster + privacy (a post/thread is not its own unit).+// roster + privacy (a thread is not its own unit).// dm-participant — the two `relation='access'` DM members; the sole surviving// 403 (block of a known participant) lives inside this value.export type VisibilityTrait = "own-roster" | "inherit-parent" | "dm-participant"@@ -133,17 +144,12 @@ export type VisibilityTrait = "own-roster" | "inherit-parent" | "dm-participant"export type ReachTrait = "server-or-roster" | "participant-set" | "dm-pair"// How a channel is CREATED (write axis) — what a name/anchor COLLISION means.-// Consumed by the create path (B4). Misusing it is a silent-success illusion-// (a pure-create wrongly merged returns 200 for a post that was never made),-// which is why it is a first-class trait, not handler-buried logic. Each value-// names EXACTLY ONE observable collision contract, so it carries exactly one-// definition-level existence-oracle (Aigneis's B0 criterion, #45) — a value that-// spanned two contracts (e.g. 409-reject AND bump) would have two end states and-// no single assertable oracle, collapsing the by-construction win back to+// Consumed by the create path (B4). Each value names EXACTLY ONE observable+// collision contract, so it carries exactly one definition-level+// existence-oracle (Aigneis's B0 criterion, #45) — a value that spanned two+// contracts (e.g. 409-reject AND bump) would have two end states and no+// single assertable oracle, collapsing the by-construction win back to// per-type hand-verification.-// pure-create — a slug collision BUMPS a new slug (`ideas`→`ideas-2`)-// and retries the insert → N distinct rows, never merged-// (forum_post). Contract: collision → bump → N distinct.// get-or-create — the anchor identifies ONE unit; a collision re-selects// and returns the existing winner (idempotent open — DM,// thread). Contract: collision → fetch winner, 1 unit.@@ -153,7 +159,12 @@ export type ReachTrait = "server-or-roster" | "participant-set" | "dm-pair"// a singleton (many channels may exist, just not same-name)// and NOT "no create" (it is a real create path with a real// 409 contract). Contract: collision → 0 rows + 409.-export type CreationTrait = "pure-create" | "get-or-create" | "reject-on-collision"+// (`pure-create` — a slug collision bumps and retries, N distinct rows,+// never merged — deleted with forum_post, phase2 forum≡thread: it was the+// sole user of this contract. A post's opener is now created via+// createMessageWithThread, which doesn't go through this dispatch at all —+// see create-channels.ts.)+export type CreationTrait = "get-or-create" | "reject-on-collision"export type ChannelTraits = {addressing: AddressingTrait@@ -168,23 +179,18 @@ export type ChannelTraits = {//// `text`/`forum` creation = `reject-on-collision`: a top-level channel create is// human-admin-only and a same-name create is REFUSED (409, 0 rows) by the-// `idx_channel_server_name` unique index — a DIFFERENT observable contract from-// forum_post's `pure-create` (collision → bump → N distinct rows). The two must-// not share a value (Aigneis #45 / Ingaborg #46 / Blondie #49 — each verified in-// code): one value = one collision contract = one oracle. `forum_post` is the-// sole `pure-create` today (the bot content-create path this round).+// `idx_channel_server_name` unique index.export const CHANNEL_TRAITS: Record<StoredChannelType, ChannelTraits> = {text: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },forum: { addressing: "by-server-name", visibility: "own-roster", reach: "server-or-roster", creation: "reject-on-collision" },- forum_post: { addressing: "by-child-name", visibility: "inherit-parent", reach: "participant-set", creation: "pure-create" },thread: { addressing: "by-root-seq", visibility: "inherit-parent", reach: "participant-set", creation: "get-or-create" },dm: { addressing: "by-peer-identity", visibility: "dm-participant", reach: "dm-pair", creation: "get-or-create" },}// ── reach axis (B2) — the SINGLE source for "who does a message here reach" ────-// The reach model of a channel type used to be re-derived as `isThread(t) ||-// isForumPost(t)` (→ participant set) vs `isDm(t)` (→ DM pair) vs else (→ server)-// in THREE places: fan-out recipients (who-receives), the agent-inbox+// The reach model of a channel type used to be re-derived as `isThread(t)`+// (→ participant set) vs `isDm(t)` (→ DM pair) vs else (→ server) in THREE+// places: fan-out recipients (who-receives), the agent-inbox// deliverable-unread narrowing (which channels need participation), and the// send-path enroll (who-enrolls into the notify set). Three copies of one// classification = drift (the agent thread-inbox deadlock was two of them@@ -204,8 +210,8 @@ export function channelReach(t: StoredChannelType): ReachTrait {// A message in a channel of this type ENROLLS participants on send (author +// @-mentioned/replied) AND its recipients/deliverable set are read from that-// same participant set. True iff the reach value is `participant-set` (thread,-// forum_post today). This is the single predicate the enroll write-side and the+// same participant set. True iff the reach value is `participant-set`+// (thread). This is the single predicate the enroll write-side and the// participation-narrowing read-side share — they are two ends of one reach// value, never separately maintained (red-line ③).export function reachIsParticipantSet(t: string | null | undefined): boolean {@@ -215,7 +221,7 @@ export function reachIsParticipantSet(t: string | null | undefined): boolean {// A narrow type guard so the reach helpers can accept the loosely-typed// `type` columns/params (string | null) that flow through the query layer.export function isStoredChannelType(t: string | null | undefined): t is StoredChannelType {- return t === "text" || t === "forum" || t === "forum_post" || t === "thread" || t === "dm"+ return t === "text" || t === "forum" || t === "thread" || t === "dm"}// ── visibility axis (B3) — how the ACCESS CHECK runs (NOT the miss status) ─────@@ -231,7 +237,7 @@ export function isStoredChannelType(t: string | null | undefined): t is StoredCh// parent inheritance (a DM is its own access unit).// own-roster / inherit-parent → the server-membership + private-category path,// with the anchor climb (`parentChannelId ?? id`) that makes a-// thread/forum_post inherit its parent's roster. That climb is+// thread inherit its parent's roster. That climb is// already a single uniform idiom, so these two values share the// same code path today; the value records the intent.export function channelVisibility(t: StoredChannelType): VisibilityTrait {@@ -253,12 +259,6 @@ export function visibilityIsDmParticipant(t: string | null | undefined): boolean// create path so "what happens when the name/anchor already exists" is chosen// from one place, not hand-branched per type. Each value = exactly one observable// contract = exactly one existence-oracle (Aigneis's B0 criterion):-// pure-create → bump a new slug and retry the insert → N distinct rows,-// never merged (forum_post). ⚠ its race-safety REQUIRES-// the partial-unique index (migration, B4b) to catch a-// concurrent collision — without it a race silent-double--// inserts. So a pure-create create path is only complete-// with that index in place.// get-or-create → the anchor is ONE unit; a collision re-selects the// existing winner (idempotent open — DM, thread).// reject-on-collision→ a same-name create is refused (409, 0 rows) by a uniquediff --git a/src/shared/src/utils/title.ts b/src/shared/src/utils/title.tsindex ca8e97128..f06433cbf 100644--- a/src/shared/src/utils/title.ts+++ b/src/shared/src/utils/title.ts@@ -50,7 +50,7 @@ export function stripInlineMarkup(raw: string): string {// in a non-whitespace char, matching the display grammar in// `chat-syntax-plugin.ts` so a spaced-name mention (`@John Doe#0042`) strips// correctly and ordinary prose (`issue #0042`) does not.- .replace(/(@[^@#\n\r]*[^@#\n\r\s])#\d{4}(?!\d)/gu, "$1")+ .replace(/(@[^@#\n\r]*[^@#\n\r\s])#\d{4,}/gu, "$1")// Line-leading block markers: heading #, blockquote >, list bullets/numbers..replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d+[.)]\s+)/gm, "");}diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex 7326a8afb..37d35ab53 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -2,17 +2,17 @@ import { describe, it, expect } from "vitest";import { parseRef, formatRef, formatCanonicalRef, formatSeq, parseSeq, DM_SERVER } from "../src/community-cli-contract";describe("parseRef", () => {- it('parses "/studio/general" as a plain channel ref', () => {- expect(parseRef("/studio/general")).toEqual({ server: "studio", channel: "general" });+ it('parses "/studio#0042/general" as a plain channel ref', () => {+ expect(parseRef("/studio#0042/general")).toEqual({ server: "studio#0042", channel: "general" });});- it('parses "/studio/general#42" as a pinned-message ref (seq)', () => {- expect(parseRef("/studio/general#42")).toEqual({ server: "studio", channel: "general", seq: 42 });+ it('parses "/studio#0042/general#42" as a pinned-message ref (seq)', () => {+ expect(parseRef("/studio#0042/general#42")).toEqual({ server: "studio#0042", channel: "general", seq: 42 });});- it('parses "/studio/general/#42" as a thread ref (threadRootSeq)', () => {- expect(parseRef("/studio/general/#42")).toEqual({- server: "studio",+ it('parses "/studio#0042/general/#42" as a thread ref (threadRootSeq)', () => {+ expect(parseRef("/studio#0042/general/#42")).toEqual({+ server: "studio#0042",channel: "general",threadRootSeq: 42,});@@ -56,7 +56,7 @@ describe("parseRef", () => {});it("throws when the ref has fewer than 2 segments", () => {- expect(() => parseRef("/studio")).toThrow();+ expect(() => parseRef("/studio#0042")).toThrow();});it('falls back to a plain-channel result for a DM ref with a non-numeric tail after "#" — does NOT throw', () => {@@ -69,62 +69,62 @@ describe("parseRef", () => {expect(parseRef("/.dm/foo#bar")).toEqual({ server: DM_SERVER, channel: "foo#bar" });});- it('parses "/demo/general/#5#42" as a thread-reply message ref', () => {- expect(parseRef("/demo/general/#5#42")).toEqual({- server: "demo",+ it('parses "/demo#0042/general/#5#42" as a thread-reply message ref', () => {+ expect(parseRef("/demo#0042/general/#5#42")).toEqual({+ server: "demo#0042",channel: "general",threadRootSeq: 5,seq: 42,});});- it('parses "/demo/general/#5" unchanged (regression)', () => {- expect(parseRef("/demo/general/#5")).toEqual({- server: "demo",+ it('parses "/demo#0042/general/#5" unchanged (regression)', () => {+ expect(parseRef("/demo#0042/general/#5")).toEqual({+ server: "demo#0042",channel: "general",threadRootSeq: 5,});});- it('throws on "/demo/general/#5#" — empty seq tail (Number("") === 0 trap)', () => {- expect(() => parseRef("/demo/general/#5#")).toThrow();+ it('throws on "/demo#0042/general/#5#" — empty seq tail (Number("") === 0 trap)', () => {+ expect(() => parseRef("/demo#0042/general/#5#")).toThrow();});- it('throws on "/demo/general/##5" — empty root', () => {- expect(() => parseRef("/demo/general/##5")).toThrow();+ it('throws on "/demo#0042/general/##5" — empty root', () => {+ expect(() => parseRef("/demo#0042/general/##5")).toThrow();});- it('throws on "/demo/general/#5#abc" — non-numeric seq', () => {- expect(() => parseRef("/demo/general/#5#abc")).toThrow();+ it('throws on "/demo#0042/general/#5#abc" — non-numeric seq', () => {+ expect(() => parseRef("/demo#0042/general/#5#abc")).toThrow();});- it('throws on "/demo/general/#5#42#7" — three tails, not two', () => {- expect(() => parseRef("/demo/general/#5#42#7")).toThrow();+ it('throws on "/demo#0042/general/#5#42#7" — three tails, not two', () => {+ expect(() => parseRef("/demo#0042/general/#5#42#7")).toThrow();});- it('parses "/demo/general/#0#5" — parser stays permissive (server rejects root 0)', () => {- expect(parseRef("/demo/general/#0#5")).toEqual({- server: "demo",+ it('parses "/demo#0042/general/#0#5" — parser stays permissive (server rejects root 0)', () => {+ expect(parseRef("/demo#0042/general/#0#5")).toEqual({+ server: "demo#0042",channel: "general",threadRootSeq: 0,seq: 5,});});- it('parses "/demo/general/#5#0" — parser stays permissive (server rejects seq 0)', () => {- expect(parseRef("/demo/general/#5#0")).toEqual({- server: "demo",+ it('parses "/demo#0042/general/#5#0" — parser stays permissive (server rejects seq 0)', () => {+ expect(parseRef("/demo#0042/general/#5#0")).toEqual({+ server: "demo#0042",channel: "general",threadRootSeq: 5,seq: 0,});});- it('throws on "/demo/general#5#42" — slashless form must NOT accept a trailing #M', () => {+ it('throws on "/demo#0042/general#5#42" — slashless form must NOT accept a trailing #M', () => {// The thread form requires the explicit `/#` separator. This shape is// ambiguous with the message form `/server/channel#N` and must be// rejected so callers can't sneak past the grammar.- expect(() => parseRef("/demo/general#5#42")).toThrow();+ expect(() => parseRef("/demo#0042/general#5#42")).toThrow();});it('parses "/.dm/gusye#1231/#5#42" — parser is DM-agnostic on thread form', () => {@@ -138,111 +138,69 @@ describe("parseRef", () => {});});- it('parses "/studio/ideas/my-post" as a forum-post ref (childChannelName)', () => {- expect(parseRef("/studio/ideas/my-post")).toEqual({- server: "studio",- channel: "ideas",- childChannelName: "my-post",- });- });-- it("does not confuse a forum-post ref with a thread ref (3rd segment has no #)", () => {- // Thread: 3rd segment starts with "#". Post: it doesn't.- expect(parseRef("/studio/ideas/#5")).toEqual({ server: "studio", channel: "ideas", threadRootSeq: 5 });- expect(parseRef("/studio/ideas/notes")).toEqual({ server: "studio", channel: "ideas", childChannelName: "notes" });+ it('the old forum-post ref shape "/studio#0042/ideas/my-post" no longer parses (no-compat, phase2 forum≡thread)', () => {+ // A post is now addressed like any other thread (by-root-seq), never by+ // its own child-name — the old 3-segment-no-hash form is GONE, not just+ // unsupported. A ref-render layer that fails to parse this degrades to+ // plain literal text (never a misresolved-to-wrong-target pill).+ expect(() => parseRef("/studio#0042/ideas/my-post")).toThrow();});- it("throws on a 4th segment (posts have no deeper addressing today)", () => {- expect(() => parseRef("/studio/ideas/post/extra")).toThrow();- });-- it('parses "/studio/ideas/post#3" — a message pinned inside a forum post', () => {- // Symmetric to the top-level message form /server/channel#N — used by- // `message emoji` to react to a specific message inside a post.- expect(parseRef("/studio/ideas/post#3")).toEqual({- server: "studio",- channel: "ideas",- childChannelName: "post",- seq: 3,- });+ it("still parses the thread form (3rd segment starts with #) unaffected by the forum-post removal", () => {+ expect(parseRef("/studio#0042/ideas/#5")).toEqual({ server: "studio#0042", channel: "ideas", threadRootSeq: 5 });});- it("throws when a forum-post pin-seq ref has an empty post name (#N with no post)", () => {- expect(() => parseRef("/studio/ideas/#3")).not.toThrow(); // this is the THREAD form, still valid- expect(parseRef("/studio/ideas/#3")).toEqual({ server: "studio", channel: "ideas", threadRootSeq: 3 });+ it("throws on any 3+ segment ref whose last segment doesn't start with # (the old forum-post ref's territory)", () => {+ expect(() => parseRef("/studio#0042/ideas/notes")).toThrow();+ expect(() => parseRef("/studio#0042/ideas/post/extra")).toThrow();+ expect(() => parseRef("/studio#0042/ideas/post#3")).toThrow();});});describe("formatRef", () => {it("formats a plain channel", () => {- expect(formatRef({ server: "studio", channel: "general" })).toBe("/studio/general");+ expect(formatRef({ server: "studio#0042", channel: "general" })).toBe("/studio#0042/general");});it("formats a thread ref with threadRootSeq", () => {- expect(formatRef({ server: "studio", channel: "general", threadRootSeq: 42 })).toBe(- "/studio/general/#42"+ expect(formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 42 })).toBe(+ "/studio#0042/general/#42");});it("round-trips through parseRef for the thread form", () => {- const ref = formatRef({ server: "studio", channel: "general", threadRootSeq: 7 });- expect(parseRef(ref)).toEqual({ server: "studio", channel: "general", threadRootSeq: 7 });+ const ref = formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 7 });+ expect(parseRef(ref)).toEqual({ server: "studio#0042", channel: "general", threadRootSeq: 7 });});it("formats a thread-reply message ref (threadRootSeq + seq)", () => {expect(- formatRef({ server: "studio", channel: "general", threadRootSeq: 5, seq: 42 }),- ).toBe("/studio/general/#5#42");+ formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 5, seq: 42 }),+ ).toBe("/studio#0042/general/#5#42");});it("round-trips through parseRef for the thread-reply form", () => {- const input = { server: "studio", channel: "general", threadRootSeq: 5, seq: 42 };+ const input = { server: "studio#0042", channel: "general", threadRootSeq: 5, seq: 42 };expect(parseRef(formatRef(input))).toEqual(input);});it("throws when seq is provided without threadRootSeq", () => {expect(() =>- formatRef({ server: "studio", channel: "general", seq: 42 }),+ formatRef({ server: "studio#0042", channel: "general", seq: 42 }),).toThrow();});it("formats a plain channel ref unchanged (regression)", () => {- expect(formatRef({ server: "studio", channel: "general" })).toBe("/studio/general");+ expect(formatRef({ server: "studio#0042", channel: "general" })).toBe("/studio#0042/general");});it("formats a plain thread ref unchanged (regression)", () => {- expect(formatRef({ server: "studio", channel: "general", threadRootSeq: 5 })).toBe(- "/studio/general/#5",- );- });-- it("formats a forum-post ref (childChannelName)", () => {- expect(formatRef({ server: "studio", channel: "ideas", childChannelName: "my-post" })).toBe(- "/studio/ideas/my-post",- );- });-- it("round-trips a forum-post ref through parseRef", () => {- const input = { server: "studio", channel: "ideas", childChannelName: "my-post" };- expect(parseRef(formatRef(input))).toEqual(input);- });-- it("formats a forum-post message ref (childChannelName + seq)", () => {- expect(formatRef({ server: "studio", channel: "ideas", childChannelName: "my-post", seq: 3 })).toBe(- "/studio/ideas/my-post#3",+ expect(formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 5 })).toBe(+ "/studio#0042/general/#5",);});- it("round-trips a forum-post message ref through parseRef", () => {- const input = { server: "studio", channel: "ideas", childChannelName: "my-post", seq: 3 };- expect(parseRef(formatRef(input))).toEqual(input);- });- it("throws when childChannelName is combined with threadRootSeq (posts have no thread root)", () => {- expect(() =>- formatRef({ server: "studio", channel: "ideas", childChannelName: "p", threadRootSeq: 5 }),- ).toThrow();- });});describe("formatSeq / parseSeq", () => {@@ -268,23 +226,17 @@ describe("formatSeq / parseSeq", () => {// inbox, wake notice, listChannels) produces one addressing identity per type.describe("formatCanonicalRef", () => {it("by-server-name (text): /server/name", () => {- expect(formatCanonicalRef({ type: "text", serverName: "studio", name: "general" })).toBe("/studio/general");+ expect(formatCanonicalRef({ type: "text", serverHandle: "studio#0042", name: "general" })).toBe("/studio#0042/general");});it("by-server-name (forum): /server/name", () => {- expect(formatCanonicalRef({ type: "forum", serverName: "studio", name: "ideas" })).toBe("/studio/ideas");- });-- it("by-child-name (forum_post): /server/forum/post", () => {- expect(- formatCanonicalRef({ type: "forum_post", serverName: "studio", parentName: "ideas", name: "my-post" }),- ).toBe("/studio/ideas/my-post");+ expect(formatCanonicalRef({ type: "forum", serverHandle: "studio#0042", name: "ideas" })).toBe("/studio#0042/ideas");});it("by-root-seq (thread): /server/channel/#rootSeq", () => {expect(- formatCanonicalRef({ type: "thread", serverName: "studio", parentName: "general", rootSeq: 42 }),- ).toBe("/studio/general/#42");+ formatCanonicalRef({ type: "thread", serverHandle: "studio#0042", parentName: "general", rootSeq: 42 }),+ ).toBe("/studio#0042/general/#42");});it("by-peer-identity (dm): /.dm/peer", () => {@@ -295,16 +247,13 @@ describe("formatCanonicalRef", () => {// resolves the same scope — the emitter and parser share the addressing model// so a ref a bot receives is one it can send/read/ack against (red-line ①).it("round-trips through parseRef for every addressing trait", () => {- expect(parseRef(formatCanonicalRef({ type: "text", serverName: "studio", name: "general" })!)).toEqual({- server: "studio",+ expect(parseRef(formatCanonicalRef({ type: "text", serverHandle: "studio#0042", name: "general" })!)).toEqual({+ server: "studio#0042",channel: "general",});expect(- parseRef(formatCanonicalRef({ type: "forum_post", serverName: "studio", parentName: "ideas", name: "notes" })!),- ).toEqual({ server: "studio", channel: "ideas", childChannelName: "notes" });- expect(- parseRef(formatCanonicalRef({ type: "thread", serverName: "studio", parentName: "general", rootSeq: 7 })!),- ).toEqual({ server: "studio", channel: "general", threadRootSeq: 7 });+ parseRef(formatCanonicalRef({ type: "thread", serverHandle: "studio#0042", parentName: "general", rootSeq: 7 })!),+ ).toEqual({ server: "studio#0042", channel: "general", threadRootSeq: 7 });expect(parseRef(formatCanonicalRef({ type: "dm", peerSegment: "gusye#1231" })!)).toEqual({server: DM_SERVER,channel: "gusye#1231",@@ -315,9 +264,8 @@ describe("formatCanonicalRef", () => {// context an addressing value needs keeps its own fallback/skip handling// rather than emitting a ref that won't round-trip.it("returns null when a required addressing field is absent", () => {- expect(formatCanonicalRef({ type: "text", serverName: "studio" })).toBeNull(); // no name- expect(formatCanonicalRef({ type: "forum_post", serverName: "studio", name: "p" })).toBeNull(); // no parentName- expect(formatCanonicalRef({ type: "thread", serverName: "studio", parentName: "g" })).toBeNull(); // no rootSeq+ expect(formatCanonicalRef({ type: "text", serverHandle: "studio#0042" })).toBeNull(); // no name+ expect(formatCanonicalRef({ type: "thread", serverHandle: "studio#0042", parentName: "g" })).toBeNull(); // no rootSeqexpect(formatCanonicalRef({ type: "dm" })).toBeNull(); // no peerSegment});});diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex bfa38a373..9801d2c57 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -74,12 +74,12 @@ describe("toAgentMessages", () => {const db = createSequentialDb([[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db, [rawMsg()], "viewer_1");expect(msg).toEqual({seq: formatSeq(1),- channel: formatRef({ server: "studio", channel: "general" }),+ channel: formatRef({ server: "studio#0042", channel: "general" }),sender: "@Alice#1234",content: { text: "hello" },time: "2026-07-01T00:00:00.000Z",@@ -94,7 +94,7 @@ describe("toAgentMessages", () => {[{ id: "thread_1", name: "thread-x", serverId: "srv_1", parentChannelId: "ch_parent", parentMessageId: "m_root" }],[{ id: "u_1", name: "Alice" }],[{ id: "ch_parent", name: "general" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],[{ id: "m_root", seq: 7 }],]);const [msg] = await agentInbox.toAgentMessages(@@ -102,29 +102,7 @@ describe("toAgentMessages", () => {[rawMsg({ channelId: "thread_1" })],"viewer_1");- expect(msg!.channel).toBe(formatRef({ server: "studio", channel: "general", threadRootSeq: 7 }));- });-- it("hydrates a forum-post message with the name-anchor ref (/server/forum/post)", async () => {- // A forum_post has a parentChannelId (the forum) but NO parentMessageId- // (unlike a thread), so it must be anchored by its own name under the- // forum — NOT fall through to the top-level fallback `/server/<post-name>`- // (which the name resolver, top-level only, could never parse back).- // Call order: 1. channels (the post itself), 2. author names,- // 3. parentChannels (the forum), 4. servers. parentMessageIds is empty- // (null) so that select is skipped.- const db = createSequentialDb([- [{ id: "post_1", name: "my-post", type: "forum_post", serverId: "srv_1", parentChannelId: "forum_1", parentMessageId: null }],- [{ id: "u_1", name: "Alice" }],- [{ id: "forum_1", name: "ideas" }],- [{ id: "srv_1", name: "studio" }],- ]);- const [msg] = await agentInbox.toAgentMessages(- db,- [rawMsg({ channelId: "post_1" })],- "viewer_1"- );- expect(msg!.channel).toBe(formatRef({ server: "studio", channel: "ideas", childChannelName: "my-post" }));+ expect(msg!.channel).toBe(formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 7 }));});it("hydrates a DM message, addressing the OTHER party (as a name#0042 handle) relative to viewerId", async () => {@@ -148,25 +126,47 @@ describe("toAgentMessages", () => {expect(msg!.channel).toBe(formatRef({ server: DM_SERVER, channel: "Bob#9999" }));});- it("falls back to /unknown/<key> when the scope can't be resolved (e.g. deleted channel)", async () => {+ it("fails the whole delivery without leaking an id when the scope can't be resolved", async () => {const db = createSequentialDb([[], // channels query returns nothing for a stale/deleted channelId[{ id: "u_1", name: "Alice" }],[], // serverIds ends up empty since no channel row was found]);- const [msg] = await agentInbox.toAgentMessages(db, [rawMsg({ channelId: "ch_gone" })], "viewer_1");- expect(msg!.channel).toBe("/unknown/ch_gone");+ await expect(agentInbox.toAgentMessages(db, [rawMsg({ channelId: "ch_gone" })], "viewer_1"))+ .rejects.toThrow("Channel identity unavailable");+ });++ it("fails the whole batch when a DM peer identity cannot hydrate", async () => {+ const db = createSequentialDb([+ [{ id: "dm_ch_1", name: null, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null }],+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],+ [{ channelId: "dm_ch_1", userId: "peer_internal_1" }],+ [], // peer user lookup misses+ ]);+ const delivery = agentInbox.toAgentMessages(db, [rawMsg({ channelId: "dm_ch_1" })], "viewer_1");+ await expect(delivery).rejects.toThrow("DM peer identity unavailable");+ await expect(delivery).rejects.not.toThrow(/peer_internal_1|dm_ch_1/);});- // B1.1 degraded-path (Ingaborg's assertion): a thread channel row EXISTS but- // its parent/root didn't hydrate (parentChannels + parentMessages come back- // empty — a dangling parent ref). The by-root-seq emitter can't build a ref- // without the root seq, so it returns null and resolveScopeRefs sets no map- // entry → the caller's `?? "/unknown/<id>"` sentinel takes over. Before B1.1- // this row got a hand-built top-level `/studio/thread-x` ref that LOOKS- // addressable but 404s on resolve; now it's an explicit unresolvable sentinel.- // The message ROW still surfaces (never-drop) — only its channel is /unknown/.- it("degraded thread (parent/root not hydrated) → /unknown/ sentinel, not a bogus top-level ref, row kept", async () => {+ it("fails a mixed valid+orphan DM batch atomically", async () => {+ const rows = [rawMsg({ id: "m_valid", channelId: "ch_valid" }), rawMsg({ id: "m_orphan", channelId: "dm_orphan", seq: 2 })];+ const db = createSequentialDb([+ [+ { id: "ch_valid", name: "general", type: "text", serverId: "srv_1", parentChannelId: null, parentMessageId: null },+ { id: "dm_orphan", name: null, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null },+ ],+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],+ [{ channelId: "dm_orphan", userId: "peer_internal_1" }],+ [], // orphan peer hydration+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],+ ]);+ await expect(agentInbox.toAgentMessages(db, rows, "viewer_1"))+ .rejects.toThrow("DM peer identity unavailable");+ });++ // A thread channel row exists but its parent/root no longer hydrates. The+ // entire delivery must fail so the cursor stays put until data repair.+ it("degraded thread fails the whole delivery instead of emitting a bogus ref", async () => {// Call order: 1. channels (the thread row itself), 2. author names,// 3. parentChannels (EMPTY — parent didn't resolve), 4. servers,// 5. parentMessages (EMPTY — root seq didn't resolve).@@ -174,25 +174,52 @@ describe("toAgentMessages", () => {[{ id: "thread_1", name: "thread-x", type: "thread", serverId: "srv_1", parentChannelId: "ch_gone_parent", parentMessageId: "m_gone_root" }],[{ id: "u_1", name: "Alice" }],[], // parentChannels: parent didn't hydrate- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],[], // parentMessages: root seq didn't hydrate]);- const [msg] = await agentInbox.toAgentMessages(db, [rawMsg({ channelId: "thread_1" })], "viewer_1");- // Row survives (never-drop) and the channel is the explicit sentinel — NOT- // a fabricated `/studio/thread-x` top-level ref.- expect(msg).toBeDefined();- expect(msg!.channel).toBe("/unknown/thread_1");- expect(msg!.channel).not.toBe(formatRef({ server: "studio", channel: "thread-x" }));+ await expect(agentInbox.toAgentMessages(db, [rawMsg({ channelId: "thread_1" })], "viewer_1"))+ .rejects.toThrow("Channel identity unavailable");});- it("falls back to the raw authorId as sender when the user row is missing", async () => {+ it("uses a non-routable sentinel when the author identity is missing", async () => {const db = createSequentialDb([[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[], // author lookup misses- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db, [rawMsg({ authorId: "u_ghost" })], "viewer_1");- expect(msg!.sender).toBe("@u_ghost");+ expect(msg!.sender).toBe("Unknown user");+ expect(JSON.stringify(msg)).not.toContain("u_ghost");+ });++ it("preserves 101 mixed-author rows across hydration chunks, changing only the missing display identity", async () => {+ const rows = Array.from({ length: 101 }, (_, i) => rawMsg({+ id: `m_${i}`,+ authorId: `u_${i}`,+ seq: i + 1,+ content: `body_${i}`,+ }));+ const users0to99 = Array.from({ length: 100 }, (_, i) => ({+ id: `u_${i}`,+ name: `User${i}`,+ discriminator: String(i).padStart(4, "0"),+ }));+ const attachments = new Map([["m_100", [{ id: "att_1", filename: "proof.txt", contentType: "text/plain", size: 5 }]]]);+ const db = createSequentialDb([+ [{ id: "ch_1", name: "general", type: "text", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],+ users0to99,+ [], // second (>100) author chunk: u_100 is deleted+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],+ ]);+ const out = await agentInbox.toAgentMessages(db, rows, "viewer_1", attachments);+ expect(out).toHaveLength(101);+ expect(out.map((m) => m.seq)).toEqual(Array.from({ length: 101 }, (_, i) => `#${i + 1}`));+ expect(out[0]).toMatchObject({ sender: "@User0#0000", content: { text: "body_0" } });+ expect(out[100]).toMatchObject({+ sender: "Unknown user",+ content: { text: "body_100", attachments: [{ id: "att_1", filename: "proof.txt" }] },+ });+ expect(JSON.stringify(out)).not.toContain("u_100");});it("read/resolvable: a channel reply gets content.replyTo = { seq, sender } from the in-scope target", async () => {@@ -202,7 +229,7 @@ describe("toAgentMessages", () => {[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],[{ id: "m_target", seq: 37, authorName: "Ana", discriminator: "0012" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db,@@ -237,7 +264,7 @@ describe("toAgentMessages", () => {[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],[], // target row deleted / not returned- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db,@@ -254,7 +281,7 @@ describe("toAgentMessages", () => {[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],[], // target is in a different channel → not returned by the scoped query- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db,@@ -269,7 +296,7 @@ describe("toAgentMessages", () => {[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],[{ id: "m_legacy", seq: 0, authorName: "Ana", discriminator: "0012" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db,@@ -285,7 +312,7 @@ describe("toAgentMessages", () => {const db = createSequentialDb([[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db, [rawMsg()], "viewer_1");expect(msg!.content).not.toHaveProperty("replyTo");@@ -301,7 +328,7 @@ describe("toAgentMessages", () => {[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],[{ id: "m_target", seq: 4, authorName: "Ana", discriminator: "0012" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const [msg] = await agentInbox.toAgentMessages(db,@@ -324,7 +351,7 @@ describe("toAgentMessages", () => {[{ id: "u_1", name: "Alice", discriminator: "1234" }],[{ id: "t_1", seq: 11, authorName: "Ana", discriminator: "0012" }],[{ id: "t_2", seq: 22, authorName: "Ben", discriminator: "3456" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const msgs = await agentInbox.toAgentMessages(db,@@ -335,9 +362,9 @@ describe("toAgentMessages", () => {"viewer_1");const byChannel = new Map(msgs.map((m) => [m.channel, m]));- expect(byChannel.get(formatRef({ server: "studio", channel: "general" }))!.content.replyTo)+ expect(byChannel.get(formatRef({ server: "studio#0042", channel: "general" }))!.content.replyTo).toEqual({ seq: formatSeq(11), sender: "@Ana#0012" });- expect(byChannel.get(formatRef({ server: "studio", channel: "random" }))!.content.replyTo)+ expect(byChannel.get(formatRef({ server: "studio#0042", channel: "random" }))!.content.replyTo).toEqual({ seq: formatSeq(22), sender: "@Ben#3456" });});});@@ -347,7 +374,7 @@ describe("toAgentMessage", () => {const db = createSequentialDb([[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],[{ id: "u_1", name: "Alice", discriminator: "1234" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],]);const msg = await agentInbox.toAgentMessage(db, rawMsg(), "viewer_1");expect(msg.sender).toBe("@Alice#1234");@@ -419,7 +446,7 @@ describe("listUnreadMessagesForAgent", () => {);});- it("excludes thread/forum_post channels the bot isn't a participant of from the allowed set", async () => {+ it("excludes thread channels the bot isn't a participant of from the allowed set", async () => {// ch_a is a plain text channel (always allowed); ch_b_thread is a thread// the bot doesn't participate in. `listAgentAllowedChannelIds` drops// ch_b_thread BEFORE the messages SQL runs, so the WHERE never lets a@@ -445,7 +472,7 @@ describe("listUnreadMessagesForAgent", () => {expect(result.map((r) => r.id)).toEqual(["m_a"]);});- it("keeps thread/forum_post channels when the bot IS a participant", async () => {+ it("keeps thread channels when the bot IS a participant", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],[@@ -617,6 +644,34 @@ describe("getInboxSnapshotForAgent", () => {expect(result).toEqual([]);});+ it("preserves 101 snapshot rows across latest-sender chunks with a missing boundary identity", async () => {+ const channels = Array.from({ length: 101 }, (_, i) => ({+ id: `ch_${i}`, type: "text", categoryId: null, categoryPrivate: null,+ creatorId: "u_owner", parentChannelId: null,+ }));+ const channelTypes = channels.map(({ id, type }) => ({ id, type }));+ const aggregated = Array.from({ length: 101 }, (_, i) => ({+ channelId: `ch_${i}`, pendingCount: i + 1, firstPendingSeq: i + 2,+ latestSeq: i + 3, latestSenderId: `sender_${i}`, mentionCount: i % 2,+ }));+ const firstSenderChunk = Array.from({ length: 100 }, (_, i) => ({+ id: `sender_${i}`, name: `Sender${i}`, discriminator: String(i).padStart(4, "0"),+ }));+ const db = createSequentialDb([+ [{ serverId: "srv_1" }], channels, [], [], channelTypes.slice(0, 100), channelTypes.slice(100),+ aggregated.slice(0, 100), aggregated.slice(100),+ firstSenderChunk, [], // sender_100 is absent in the second hydration chunk+ ]);+ const out = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");+ expect(out).toHaveLength(101);+ expect(out.map((r) => r.channelId)).toEqual(channels.map((c) => c.id));+ expect(out[0]).toMatchObject({ latestSender: "@Sender0#0000", pendingCount: 1, latestSeq: 3 });+ expect(out[100]).toMatchObject({+ latestSender: "Unknown user", pendingCount: 101, firstPendingSeq: 102, latestSeq: 103,+ });+ expect(JSON.stringify(out)).not.toContain("sender_100");+ });+it("hydrates latestSender from the user table and sets hasMention from mentionCount", async () => {const db = createSequentialDb([[{ serverId: "srv_1" }],@@ -650,7 +705,6 @@ describe("getInboxSnapshotForAgent", () => {],[{ id: "u_1", name: "Alice", discriminator: "1234" },- { id: "u_2", name: "Bob", discriminator: "5678" },],]);const result = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");@@ -668,13 +722,13 @@ describe("getInboxSnapshotForAgent", () => {pendingCount: 1,firstPendingSeq: 9,latestSeq: 9,- latestSender: "@Bob#5678",+ latestSender: "Unknown user",hasMention: false,},]);});- it("excludes thread/forum_post channels the bot isn't a participant of from the allowed set", async () => {+ it("excludes thread channels the bot isn't a participant of from the allowed set", async () => {// ch_thread is filtered out of `allowedChannelIds` up front, so the// aggregation SQL's WHERE ... inArray(channelId, allowed) never surfaces// it. No post-filter needed → no risk of an aggregation row silently@@ -761,7 +815,7 @@ describe("toInboxRows", () => {[{ channelId: "dm_ch_1", userId: "peer_1" }],[{ id: "peer_1", name: "Bob", discriminator: "9999" }],[{ id: "ch_parent", name: "general" }],- [{ id: "srv_1", name: "studio" }],+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],[{ id: "m_root", seq: 3 }],]);const result = await agentInbox.toInboxRows(db, rows, "viewer_1");@@ -770,7 +824,7 @@ describe("toInboxRows", () => {flags: ["dm", "mention"],});expect(result[1]).toMatchObject({- channel: formatRef({ server: "studio", channel: "general", threadRootSeq: 3 }),+ channel: formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 3 }),flags: ["thread"],});});@@ -864,7 +918,7 @@ describe("listMessagesBySeq", () => {describe("hasDeliverableUnreadForAgentScope", () => {// Call order (see the query's body):// 1. channel-type lookup (participation-narrowing pre-check)- // 2. `listParticipatingThreadIds` — ONLY when (1) is thread/forum_post+ // 2. `listParticipatingThreadIds` — ONLY when (1) is thread// 3. the deliverable-unread existence scan (limit 1)// For a plain (non-thread) channel, (2) is skipped: (1)=type, (2)=scan.it("returns true when a deliverable message beyond `seen` exists", async () => {diff --git a/src/shared/test/queries/community-attachment-rebind.test.ts b/src/shared/test/queries/community-attachment-rebind.test.tsnew file mode 100644index 000000000..6b3a6f0fd--- /dev/null+++ b/src/shared/test/queries/community-attachment-rebind.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it, vi } from "vitest"+import { rebindPendingAttachmentsToChild } from "../../src/db/queries/community/attachment"++function createDb(reboundIds: string[]) {+ const countChain: any = {}+ countChain.from = vi.fn(() => countChain)+ countChain.where = vi.fn(() => countChain)+ const updateChain: any = {}+ updateChain.set = vi.fn(() => updateChain)+ updateChain.where = vi.fn(() => updateChain)+ updateChain.returning = vi.fn(async () => reboundIds.map((id) => ({ id })))+ return {+ select: vi.fn(() => countChain),+ update: vi.fn(() => updateChain),+ countChain,+ updateChain,+ }+}++describe("rebindPendingAttachmentsToChild", () => {+ it("moves an eligible pending attachment to the direct child target", async () => {+ const db = createDb(["attachment_1"])++ const result = await rebindPendingAttachmentsToChild(db as any, {+ ids: ["attachment_1"],+ uploaderId: "user_1",+ parentTargetId: "forum_1",+ childTargetId: "thread_1",+ })++ expect(result).toBe(true)+ expect(db.updateChain.set).toHaveBeenCalledWith({ targetId: "thread_1" })+ })++ it("accepts an attachment already pending on the same child for replay", async () => {+ const db = createDb(["attachment_1"])++ const result = await rebindPendingAttachmentsToChild(db as any, {+ ids: ["attachment_1"],+ uploaderId: "user_1",+ parentTargetId: "forum_1",+ childTargetId: "thread_1",+ })++ expect(result).toBe(true)+ })++ it("rejects the whole set when any requested attachment is outside the scoped pending rows", async () => {+ const db = createDb([])++ const result = await rebindPendingAttachmentsToChild(db as any, {+ ids: ["attachment_1", "sibling_or_foreign_attachment"],+ uploaderId: "user_1",+ parentTargetId: "forum_1",+ childTargetId: "thread_1",+ })++ expect(result).toBe(false)+ expect(db.update).toHaveBeenCalledTimes(1)+ expect(db.select).toHaveBeenCalledTimes(1)+ })++ it("rejects a partial-overlap race from the guarded statement", async () => {+ const db = createDb(["attachment_1"])++ const result = await rebindPendingAttachmentsToChild(db as any, {+ ids: ["attachment_1", "attachment_2"],+ uploaderId: "user_1",+ parentTargetId: "forum_1",+ childTargetId: "thread_1",+ })++ expect(result).toBe(false)+ expect(db.updateChain.returning).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex e7fdf2f6f..4e67b68a1 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -132,7 +132,8 @@ describe("createBot", () => {const firstAttemptDiscriminator = userValues[0]!.discriminatorconst secondAttemptDiscriminator = userValues[3]!.discriminatorexpect(firstAttemptDiscriminator).toBe(computeDiscriminator(botId))- expect(secondAttemptDiscriminator).toBe(computeDiscriminator(`${botId}:1`))+ // Salt scheme is now `id:width:attempt`; the first retry stays at width 4.+ expect(secondAttemptDiscriminator).toBe(computeDiscriminator(`${botId}:4:1`, 4))expect(secondAttemptDiscriminator).not.toBe(firstAttemptDiscriminator)// The winning (second) attempt's discriminator is what's returned.diff --git a/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts b/src/shared/test/queries/community-can-bot-read-wake-scope.test.tsindex 22e447128..cf1144a10 100644--- a/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts+++ b/src/shared/test/queries/community-can-bot-read-wake-scope.test.ts@@ -63,21 +63,9 @@ describe("canBotReadWakeScope — visibility gate", () => {});});-describe("canBotReadWakeScope — notification-set narrowing (thread + forum_post)", () => {+describe("canBotReadWakeScope — notification-set narrowing (thread)", () => {beforeEach(() => vi.clearAllMocks());- it("public forum_post + bot IS a thread participant → true", async () => {- mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "forum_post", isPrivate: false }));- mockIsThreadParticipant.mockResolvedValue(true);- expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_1" })).toBe(true);- });-- it("public forum_post + bot NOT a participant → false (regression guard for Mellicent's exact case)", async () => {- mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "forum_post", isPrivate: false }));- mockIsThreadParticipant.mockResolvedValue(false);- expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_1" })).toBe(false);- });-it("thread under public channel + bot NOT a participant → false", async () => {mockResolveChannelAccessContext.mockResolvedValue(ctx({ type: "thread", isPrivate: false }));mockIsThreadParticipant.mockResolvedValue(false);@@ -90,20 +78,20 @@ describe("canBotReadWakeScope — notification-set narrowing (thread + forum_posexpect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "thread_1" })).toBe(true);});- it("private forum_post + bot on roster + IS a participant → true", async () => {+ it("private thread + bot on roster + IS a participant → true", async () => {mockResolveChannelAccessContext.mockResolvedValue(- ctx({ type: "forum_post", isPrivate: true, isChannelMember: true }),+ ctx({ type: "thread", isPrivate: true, isChannelMember: true }),);mockIsThreadParticipant.mockResolvedValue(true);- expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_priv" })).toBe(true);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "thread_priv" })).toBe(true);});- it("private forum_post + bot on roster but NOT a participant → false (both gates enforced)", async () => {+ it("private thread + bot on roster but NOT a participant → false (both gates enforced)", async () => {mockResolveChannelAccessContext.mockResolvedValue(- ctx({ type: "forum_post", isPrivate: true, isChannelMember: true }),+ ctx({ type: "thread", isPrivate: true, isChannelMember: true }),);mockIsThreadParticipant.mockResolvedValue(false);- expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "post_priv" })).toBe(false);+ expect(await canBotReadWakeScope(fakeDb, "bot", { channelId: "thread_priv" })).toBe(false);});});diff --git a/src/shared/test/queries/community-channel-access.test.ts b/src/shared/test/queries/community-channel-access.test.tsindex 30367985a..e603dbdbb 100644--- a/src/shared/test/queries/community-channel-access.test.ts+++ b/src/shared/test/queries/community-channel-access.test.ts@@ -16,7 +16,6 @@ function channelRow(over: Record<string, unknown> = {}) {type: "text",topic: "",position: 0,- forumTags: null,parentChannelId: null,creatorId: "creator",messageCount: 0,@@ -152,6 +151,5 @@ describe("getChannelForMember — private visibility", () => {]);const res = await channelQueries.getChannelForMember(db, "c1", "u1");expect(res).not.toHaveProperty("memberRole");- expect(res).toHaveProperty("tags");});});diff --git a/src/shared/test/queries/community-channel-resolve.test.ts b/src/shared/test/queries/community-channel-resolve.test.tsindex 045486d25..7c03c1850 100644--- a/src/shared/test/queries/community-channel-resolve.test.ts+++ b/src/shared/test/queries/community-channel-resolve.test.ts@@ -135,7 +135,6 @@ describe("resolveChannelByNameForMember — SQL invariants", () => {type: "text",topic: "",position: 0,- forumTags: null,parentChannelId: null,creatorId: "u_1",messageCount: 0,@@ -154,7 +153,5 @@ describe("resolveChannelByNameForMember — SQL invariants", () => {expect(rows).toHaveLength(1);expect(rows[0]!.id).toBe("ch_top");expect(rows[0]!.parentChannelId).toBeNull();- // forumTags is projected as `tags: string[]` (safeParseForumTags).- expect(rows[0]!.tags).toEqual([]);});});diff --git a/src/shared/test/queries/community-channel-tags.test.ts b/src/shared/test/queries/community-channel-tags.test.tsdeleted file mode 100644index 025a10fa9..000000000--- a/src/shared/test/queries/community-channel-tags.test.ts+++ /dev/null@@ -1,160 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--const { warn } = vi.hoisted(() => ({ warn: vi.fn() }));-vi.mock("../../src/logger", () => ({- createLogger: () => ({- debug: vi.fn(),- info: vi.fn(),- warn,- error: vi.fn(),- }),-}));--import * as channelQueries from "../../src/db/queries/community/channel";--function channelRow(id: string, forumTags: string | null) {- return {- id,- serverId: "s_1",- categoryId: null,- name: `ch-${id}`,- type: "forum",- topic: "",- position: 0,- forumTags,- parentChannelId: null,- creatorId: null,- messageCount: 0,- archived: 0,- parentMessageId: null,- lastMessageAt: null,- createdAt: "2025-01-01T00:00:00.000Z",- };-}--// Chain mock that resolves either at `.where()` or after `.orderBy()`.-// listServerChannels ends in orderBy → make it a Promise-and-chain hybrid.-function createSelectMock(rows: any[]) {- const chain: any = {};- const terminal = () => Object.assign(Promise.resolve(rows), chain);- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.innerJoin = vi.fn(() => chain);- chain.leftJoin = vi.fn(() => chain);- chain.where = vi.fn(() => terminal());- chain.limit = vi.fn(() => Promise.resolve(rows));- chain.orderBy = vi.fn(() => Promise.resolve(rows));- return chain;-}--describe("safeParseForumTags via getChannel", () => {- beforeEach(() => warn.mockReset());-- it("valid forumTags JSON → tags: string[]; no log", async () => {- const db = createSelectMock([channelRow("ch_1", '["bug","q&a"]')]);- const result = await channelQueries.getChannel(db, "ch_1");- expect(result?.tags).toEqual(["bug", "q&a"]);- expect(result).not.toHaveProperty("forumTags");- expect(warn).not.toHaveBeenCalled();- });-- it("malformed forumTags → tags: []; warn once with { channelId, err }", async () => {- const db = createSelectMock([channelRow("ch_bad", "{bad")]);- const result = await channelQueries.getChannel(db, "ch_bad");- expect(result?.tags).toEqual([]);- expect(warn).toHaveBeenCalledTimes(1);- expect(warn).toHaveBeenCalledWith(- "forum_tags_parse_failed",- expect.objectContaining({ channelId: "ch_bad", err: expect.any(Error) }),- );- });-- it("forumTags: null → tags: []; no log", async () => {- const db = createSelectMock([channelRow("ch_null", null)]);- const result = await channelQueries.getChannel(db, "ch_null");- expect(result?.tags).toEqual([]);- expect(warn).not.toHaveBeenCalled();- });-- it("forumTags parses to non-array → tags: []; warn forum_tags_not_array", async () => {- const db = createSelectMock([channelRow("ch_obj", '{"foo":1}')]);- const result = await channelQueries.getChannel(db, "ch_obj");- expect(result?.tags).toEqual([]);- expect(warn).toHaveBeenCalledTimes(1);- expect(warn).toHaveBeenCalledWith(- "forum_tags_not_array",- expect.objectContaining({ channelId: "ch_obj" }),- );- });-- it("no rows → null; no log", async () => {- const db = createSelectMock([]);- const result = await channelQueries.getChannel(db, "missing");- expect(result).toBeNull();- expect(warn).not.toHaveBeenCalled();- });-});--describe("safeParseForumTags via listServerChannels", () => {- beforeEach(() => warn.mockReset());-- it("maps each row's forumTags into tags: []-fallback + parsed", async () => {- const rows = [- channelRow("ch_1", '["a"]'),- channelRow("ch_2", null),- channelRow("ch_3", "{bad"),- ];- const db = createSelectMock(rows);- const result = await channelQueries.listServerChannels(db, "s_1");- expect(result[0]!.tags).toEqual(["a"]);- expect(result[1]!.tags).toEqual([]);- expect(result[2]!.tags).toEqual([]);- expect(warn).toHaveBeenCalledTimes(1);- expect(warn).toHaveBeenCalledWith(- "forum_tags_parse_failed",- expect.objectContaining({ channelId: "ch_3" }),- );- });-});--describe("safeParseForumTags via listChildChannels", () => {- beforeEach(() => warn.mockReset());-- it("returns rows with tags parsed", async () => {- const db = createSelectMock([channelRow("ch_1", '["x","y"]')]);- const result = await channelQueries.listChildChannels(db, "ch_parent");- expect(result[0]!.tags).toEqual(["x", "y"]);- });-});--describe("safeParseForumTags via getChannelsByIds", () => {- beforeEach(() => warn.mockReset());-- it("empty ids short-circuits without hitting the db", async () => {- const db = createSelectMock([channelRow("ch_1", null)]);- const result = await channelQueries.getChannelsByIds(db, []);- expect(result).toEqual([]);- expect(db.select).not.toHaveBeenCalled();- });-- it("maps forumTags → tags per row", async () => {- const db = createSelectMock([- channelRow("ch_1", '["a"]'),- channelRow("ch_2", '["b","c"]'),- ]);- const result = await channelQueries.getChannelsByIds(db, ["ch_1", "ch_2"]);- expect(result[0]!.tags).toEqual(["a"]);- expect(result[1]!.tags).toEqual(["b", "c"]);- });-});--describe("safeParseForumTags via getChannelForMember", () => {- beforeEach(() => warn.mockReset());-- it("parses forumTags into tags", async () => {- const row = channelRow("ch_1", '["bug"]');- const db = createSelectMock([row]);- const result = await channelQueries.getChannelForMember(db, "ch_1", "u_1");- expect(result?.tags).toEqual(["bug"]);- });-});diff --git a/src/shared/test/queries/community-channel-threads.test.ts b/src/shared/test/queries/community-channel-threads.test.tsindex 297a75400..c1c7e4009 100644--- a/src/shared/test/queries/community-channel-threads.test.ts+++ b/src/shared/test/queries/community-channel-threads.test.ts@@ -1,23 +1,8 @@import { describe, it, expect, vi } from "vitest";import {createThreadChannel,- getChildChannelByName,- dedupeChildChannelSlug,} from "../../src/db/queries/community/channel";-// A single-select thenable-chain db (FIFO), for the child-channel helpers-// which each issue exactly one `db.select(...)...`.-function createSelectDb(rows: unknown[]) {- const methods = ["from", "where"];- const select = vi.fn(() => {- const chain: any = {};- for (const m of methods) chain[m] = vi.fn(() => chain);- chain.then = (resolve: any, reject: any) => Promise.resolve(rows).then(resolve, reject);- return chain;- });- return { select } as any;-}-/*** `createThreadChannel` mixes two `db.select()` round trips (parent-channel* lookup, parent-message lookup, run via `Promise.all`) with one `db.insert()`@@ -57,7 +42,7 @@ describe("createThreadChannel", () => {selectResponses: [[{ serverId: "srv_1" }], // parent channel lookup[{ content: longContent }], // parent message lookup- [{ id: "thread_1", serverId: "srv_1", name: "x".repeat(40), type: "thread", forumTags: null }], // getChannel re-fetch+ [{ id: "thread_1", serverId: "srv_1", name: "x".repeat(40), type: "thread" }], // getChannel re-fetch],insertedId: "thread_1",});@@ -72,7 +57,7 @@ describe("createThreadChannel", () => {selectResponses: [[{ serverId: "srv_1" }],[{ content: " " }], // whitespace-only → trims to empty- [{ id: "thread_1", serverId: "srv_1", name: "Thread", type: "thread", forumTags: null }],+ [{ id: "thread_1", serverId: "srv_1", name: "Thread", type: "thread" }],],insertedId: "thread_1",});@@ -85,7 +70,7 @@ describe("createThreadChannel", () => {selectResponses: [[{ serverId: "srv_1" }],[{ content: "hello" }],- [{ id: "thread_1", serverId: "srv_1", name: "hello", type: "thread", forumTags: null }],+ [{ id: "thread_1", serverId: "srv_1", name: "hello", type: "thread" }],],insertedId: "thread_1",});@@ -98,7 +83,7 @@ describe("createThreadChannel", () => {selectResponses: [[{ serverId: "srv_1" }],[{ content: "hello" }],- [{ id: "thread_1", serverId: "srv_1", name: "hello", type: "thread", forumTags: null }],+ [{ id: "thread_1", serverId: "srv_1", name: "hello", type: "thread" }],],insertedId: "thread_1",});@@ -122,7 +107,7 @@ describe("createThreadChannel", () => {it("throws when the parent is itself a child channel (forum post / thread) — no grandchild threads, closes the private-forum leak", async () => {const db = createMockDb({// parent-channel lookup returns a row whose own parentChannelId is set →- // it's a forum_post/thread, not a top-level channel.+ // it's a child thread, not a top-level channel.selectResponses: [[{ serverId: "srv_1", parentChannelId: "forum_1" }], [{ content: "hi" }]],insertedId: "x",});@@ -130,37 +115,3 @@ describe("createThreadChannel", () => {expect(db.__insertValues).not.toHaveBeenCalled();});});--describe("getChildChannelByName", () => {- it("returns all matches (mapped rows) so the caller can detect ambiguity", async () => {- const db = createSelectDb([- { id: "post_1", name: "dupe", type: "forum_post", serverId: "srv_1", parentChannelId: "forum_1", forumTags: null },- { id: "post_2", name: "dupe", type: "forum_post", serverId: "srv_1", parentChannelId: "forum_1", forumTags: null },- ]);- const rows = await getChildChannelByName(db, "forum_1", "dupe");- expect(rows.map((r) => r.id)).toEqual(["post_1", "post_2"]);- });-- it("returns [] when no post with that name exists under the forum", async () => {- const db = createSelectDb([]);- const rows = await getChildChannelByName(db, "forum_1", "ghost");- expect(rows).toEqual([]);- });-});--describe("dedupeChildChannelSlug", () => {- it("returns the base slug unchanged when no post in the forum uses it", async () => {- const db = createSelectDb([{ name: "other" }]);- expect(await dedupeChildChannelSlug(db, "forum_1", "ideas")).toBe("ideas");- });-- it("appends -2 on the first collision", async () => {- const db = createSelectDb([{ name: "ideas" }]);- expect(await dedupeChildChannelSlug(db, "forum_1", "ideas")).toBe("ideas-2");- });-- it("skips already-taken numbered suffixes (ideas, ideas-2 → ideas-3)", async () => {- const db = createSelectDb([{ name: "ideas" }, { name: "ideas-2" }]);- expect(await dedupeChildChannelSlug(db, "forum_1", "ideas")).toBe("ideas-3");- });-});diff --git a/src/shared/test/queries/community-forum-message-pagination.test.ts b/src/shared/test/queries/community-forum-message-pagination.test.tsnew file mode 100644index 000000000..53f750781--- /dev/null+++ b/src/shared/test/queries/community-forum-message-pagination.test.ts@@ -0,0 +1,102 @@+import Sqlite from "better-sqlite3"+import { drizzle } from "drizzle-orm/better-sqlite3"+import { afterEach, beforeEach, describe, expect, it } from "vitest"++import * as messageQueries from "../../src/db/queries/community/message"+import * as tagQueries from "../../src/db/queries/community/message-tag"++describe("forum opener message pagination against real SQLite", () => {+ let sqlite: Sqlite.Database+ let db: ReturnType<typeof drizzle>++ beforeEach(() => {+ sqlite = new Sqlite(":memory:")+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ email TEXT NOT NULL,+ image TEXT+ );+ CREATE TABLE community_message (+ id TEXT PRIMARY KEY,+ author_id TEXT NOT NULL,+ content TEXT NOT NULL,+ type TEXT NOT NULL DEFAULT 'default',+ mention_type TEXT,+ reply_to_id TEXT,+ embeds TEXT,+ created_at TEXT NOT NULL,+ channel_id TEXT NOT NULL,+ seq INTEGER NOT NULL DEFAULT 0,+ friendship_id TEXT,+ client_nonce TEXT+ );+ CREATE TABLE community_message_tag (+ id TEXT PRIMARY KEY,+ message_id TEXT NOT NULL,+ tag TEXT NOT NULL,+ UNIQUE(message_id, tag)+ );+ `)+ sqlite.prepare("INSERT INTO user (id, name, email, image) VALUES (?, ?, ?, ?)")+ .run("u1", "Alice", "[email protected]", null)+ const insertMessage = sqlite.prepare(`+ INSERT INTO community_message+ (id, author_id, content, created_at, channel_id, seq)+ VALUES (?, 'u1', ?, ?, ?, ?)+ `)+ for (let n = 1; n <= 6; n++) {+ insertMessage.run(`m${n}`, `message ${n}`, `2026-01-01T00:00:0${n}.000Z`, "c1", n)+ }+ insertMessage.run("x1", "foreign", "2026-01-01T00:00:09.000Z", "c2", 1)+ const insertTag = sqlite.prepare("INSERT INTO community_message_tag (id, message_id, tag) VALUES (?, ?, ?)")+ for (const messageId of ["m2", "m4", "m6", "x1"]) insertTag.run(`tag-${messageId}-bug`, messageId, "bug")+ insertTag.run("tag-m1-feature", "m1", "feature")+ insertTag.run("tag-x1-secret", "x1", "secret")+ db = drizzle(sqlite)+ })++ afterEach(() => sqlite.close())++ it("filters by channel and tag before LIMIT, yielding a full page with no cross-channel leak", async () => {+ const rows = await messageQueries.listMessages(db as never, { channelId: "c1", tag: "bug", limit: 3 })+ expect(rows.map((row) => row.id)).toEqual(["m6", "m4", "m2"])+ })++ it("pages the tagged tuple cursor without overlap or omission", async () => {+ const first = await messageQueries.listMessages(db as never, { channelId: "c1", tag: "bug", limit: 2 })+ const second = await messageQueries.listMessages(db as never, {+ channelId: "c1",+ tag: "bug",+ limit: 2,+ cursor: { createdAt: first[1]!.createdAt, id: first[1]!.id },+ })+ expect(first.map((row) => row.id)).toEqual(["m6", "m4"])+ expect(second.map((row) => row.id)).toEqual(["m2"])+ expect(new Set([...first, ...second].map((row) => row.id)).size).toBe(3)+ })++ it("applies the same tagged set to anchor and since windows", async () => {+ const around = await messageQueries.listMessagesAround(db as never, {+ channelId: "c1",+ tag: "bug",+ anchor: { createdAt: "2026-01-01T00:00:04.000Z", id: "m4" },+ limit: 4,+ })+ const since = await messageQueries.listMessagesSince(db as never, {+ channelId: "c1",+ tag: "bug",+ since: { createdAt: "2026-01-01T00:00:02.000Z", id: "m2" },+ limit: 4,+ })+ expect(around.older.map((row) => row.id)).toEqual(["m2"])+ expect(around.newer.map((row) => row.id)).toEqual(["m4", "m6"])+ expect(since.map((row) => row.id)).toEqual(["m4", "m6"])+ })++ it("lists only the current channel's distinct opener-message tags", async () => {+ await expect(tagQueries.listDistinctTagsForChannel(db as never, "c1"))+ .resolves.toEqual(["bug", "feature"])+ })+})diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex dc8b0054c..5b2700e8e 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -26,6 +26,9 @@ describe("community/inbox exports", () => {it("exports isDmUnread", () => {expect(typeof inboxQueries.isDmUnread).toBe("function");});+ it("exports listUnreadForumOpeners", () => {+ expect(typeof inboxQueries.listUnreadForumOpeners).toBe("function");+ });});describe("isChannelUnread — two-branch predicate (seq)", () => {@@ -209,22 +212,90 @@ describe("listUnreadChannels — seq read-watermark behaviour", () => {expect(result).toEqual([]);});- const unreadPostRow = (channelId: string) => ({- channelId, channelName: "a post", serverId: "srv_1", serverName: "server 1",- type: "forum_post", parentChannelId: "forum_1", lastMessageAt: "2026-07-06T00:00:05.000Z",- hasReadState: 1, hasUnreadBeyondSeq: 1, archived: false, joinedAt: j,+});++describe("listUnreadForumOpeners — scoped forum projection", () => {+ function createForumOpenerMock(responseSets: any[][]) {+ let call = 0;+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve(responseSets[call++] ?? []));+ return chain;+ }++ const raw = (overrides: Partial<{+ forumChannelId: string;+ openerMessageId: string;+ openerContent: string;+ openerSeq: number;+ childChannelId: string;+ childName: string | null;+ createdAt: string;+ }> = {}) => ({+ forumChannelId: "forum_1",+ openerMessageId: "opener_1",+ openerContent: "The authoritative full opener title",+ openerSeq: 1,+ childChannelId: "post_1",+ childName: "derived truncated title",+ createdAt: "2026-07-07T10:00:00.000Z",+ ...overrides,});- it("forum post the viewer participates in surfaces as unread", async () => {- const db = createTwoQueryMock([unreadPostRow("p_in")], ["p_in"]);- const result = await inboxQueries.listUnreadChannels(db, "u_1", ["p_in"]);- expect(result.map((r) => r.channelId)).toEqual(["p_in"]);+ it("returns no rows and issues no query for an empty authorized parent scope", async () => {+ const db = createForumOpenerMock([]);+ await expect(inboxQueries.listUnreadForumOpeners(db, "u1", [])).resolves.toEqual([]);+ expect(db.select).not.toHaveBeenCalled();});- it("public forum post the viewer has NOT joined is filtered out (visible but un-notified)", async () => {- const db = createTwoQueryMock([unreadPostRow("p_out")], []);- const result = await inboxQueries.listUnreadChannels(db, "u_1", ["p_out"]);- expect(result).toEqual([]);+ it("projects opener identity, child identity, full opener content, createdAt, and seq", async () => {+ const db = createForumOpenerMock([[raw()]]);+ const result = await inboxQueries.listUnreadForumOpeners(db, "u1", ["forum_1"]);+ expect(result).toEqual([{+ forumChannelId: "forum_1",+ openerMessageId: "opener_1",+ childChannelId: "post_1",+ title: "The authoritative full opener title",+ createdAt: "2026-07-07T10:00:00.000Z",+ openerSeq: 1,+ }]);+ });++ it("falls back to the derived child name only when opener content is blank", async () => {+ const db = createForumOpenerMock([[+ raw({ openerMessageId: "blank", openerContent: " ", childName: "Fallback title" }),+ raw({ openerMessageId: "full", openerContent: " preserve me ", childName: "Wrong" }),+ ]]);+ const result = await inboxQueries.listUnreadForumOpeners(db, "u1", ["forum_1"]);+ expect(Object.fromEntries(result.map((row) => [row.openerMessageId, row.title]))).toEqual({+ blank: "Fallback title",+ full: " preserve me ",+ });+ });++ it("chunks the authorized id scope and globally sorts createdAt, seq, then id", async () => {+ const firstChunk = [+ raw({ openerMessageId: "opener_a", openerSeq: 4, createdAt: "2026-07-07T10:00:00.000Z" }),+ raw({ openerMessageId: "opener_z", openerSeq: 8, createdAt: "2026-07-07T09:00:00.000Z" }),+ ];+ const secondChunk = [+ raw({ openerMessageId: "opener_b", openerSeq: 5, createdAt: "2026-07-07T10:00:00.000Z" }),+ raw({ openerMessageId: "opener_c", openerSeq: 5, createdAt: "2026-07-07T10:00:00.000Z" }),+ ];+ const db = createForumOpenerMock([firstChunk, secondChunk]);+ const ids = Array.from({ length: 91 }, (_, i) => `forum_${i}`);+ const result = await inboxQueries.listUnreadForumOpeners(db, "u1", ids);++ expect(db.select).toHaveBeenCalledTimes(2);+ expect(result.map((row) => row.openerMessageId)).toEqual([+ "opener_c",+ "opener_b",+ "opener_a",+ "opener_z",+ ]);});});diff --git a/src/shared/test/queries/community-message-embeds.test.ts b/src/shared/test/queries/community-message-embeds.test.tsindex da6b9c7cf..fff7e7985 100644--- a/src/shared/test/queries/community-message-embeds.test.ts+++ b/src/shared/test/queries/community-message-embeds.test.ts@@ -14,6 +14,7 @@ vi.mock("../../src/logger", () => ({}));import * as messageQueries from "../../src/db/queries/community/message";+import { communityMessage } from "../../src/db/community-schema";function messageRow(id: string, embeds: string | null) {return {@@ -31,6 +32,7 @@ function messageRow(id: string, embeds: string | null) {authorName: `User ${id}`,authorEmail: `${id}@x.com`,authorImage: null,+ clientNonce: "client-1",};}@@ -60,6 +62,8 @@ describe("safeParseEmbeds via listMessages", () => {const db = createSelectMock([messageRow("m_1", raw)]);const result = await messageQueries.listMessages(db, { channelId: "ch_1" });expect(result[0]!.embeds).toEqual([{ url: "https://x/y", title: "t" }]);+ expect(result[0]!.clientNonce).toBe("client-1");+ expect(db.select.mock.calls[0]?.[0]?.clientNonce).toBe(communityMessage.clientNonce);expect(warn).not.toHaveBeenCalled();});@@ -119,6 +123,7 @@ describe("safeParseEmbeds via getMessage", () => {const db = createSelectMock([messageRow("m_1", '[{"url":"z"}]')]);const result = await messageQueries.getMessage(db, "m_1");expect(result?.embeds).toEqual([{ url: "z" }]);+ expect(db.select.mock.calls[0]?.[0]).not.toHaveProperty("clientNonce");expect(warn).not.toHaveBeenCalled();});diff --git a/src/shared/test/queries/community-message-tag.test.ts b/src/shared/test/queries/community-message-tag.test.tsnew file mode 100644index 000000000..682ec26e5--- /dev/null+++ b/src/shared/test/queries/community-message-tag.test.ts@@ -0,0 +1,141 @@+import { describe, it, expect, vi } from "vitest";+import * as tagQueries from "../../src/db/queries/community/message-tag";++describe("community/message-tag exports", () => {+ it("exports the tag CRUD + filter", () => {+ expect(typeof tagQueries.addMessageTag).toBe("function");+ expect(typeof tagQueries.removeMessageTag).toBe("function");+ expect(typeof tagQueries.replaceMessageTags).toBe("function");+ expect(typeof tagQueries.listTagsForMessage).toBe("function");+ expect(typeof tagQueries.listTagsForMessages).toBe("function");+ expect(typeof tagQueries.filterMessageIdsByTag).toBe("function");+ expect(typeof tagQueries.listDistinctTagsForChannel).toBe("function");+ });+});++describe("replaceMessageTags", () => {+ function batchMock() {+ const deleteStatement = { kind: "delete" };+ const deleteChain = { where: vi.fn(() => deleteStatement) };+ const inserts: Array<{ kind: "insert"; data: unknown }> = [];+ const db: any = {+ delete: vi.fn(() => deleteChain),+ insert: vi.fn(() => ({ values: vi.fn((data) => {+ const statement = { kind: "insert", data };+ inserts.push(statement);+ return statement;+ }) })),+ batch: vi.fn(() => Promise.resolve()),+ };+ return { db, deleteStatement, inserts };+ }++ it("batches only the unconditional delete for an empty replacement", async () => {+ const { db, deleteStatement } = batchMock();+ await tagQueries.replaceMessageTags(db, { messageId: "m1", tags: [] });+ expect(db.batch).toHaveBeenCalledWith([deleteStatement]);+ expect(db.insert).not.toHaveBeenCalled();+ });++ it("batches delete plus every wanted insert in one atomic call", async () => {+ const { db, deleteStatement, inserts } = batchMock();+ await tagQueries.replaceMessageTags(db, { messageId: "m1", tags: ["bug", "p0"] });+ expect(inserts.map((statement) => statement.data)).toEqual([+ { messageId: "m1", tag: "bug" },+ { messageId: "m1", tag: "p0" },+ ]);+ expect(db.batch).toHaveBeenCalledWith([deleteStatement, ...inserts]);+ });+});++describe("addMessageTag", () => {+ it("inserts with onConflictDoNothing (idempotent re-add)", async () => {+ const values = vi.fn(() => ({ onConflictDoNothing: vi.fn(() => Promise.resolve()) }));+ const db: any = { insert: vi.fn(() => ({ values })) };+ await tagQueries.addMessageTag(db, { messageId: "m1", tag: "bug" });+ expect(db.insert).toHaveBeenCalledTimes(1);+ expect(values).toHaveBeenCalledWith({ messageId: "m1", tag: "bug" });+ });+});++describe("removeMessageTag", () => {+ function deleteMock(returned: any[]) {+ const chain: any = {};+ chain.delete = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.returning = vi.fn(() => Promise.resolve(returned));+ return chain;+ }++ it("returns the deleted row when present", async () => {+ const db = deleteMock([{ id: "t1", messageId: "m1", tag: "bug" }]);+ const res = await tagQueries.removeMessageTag(db, { messageId: "m1", tag: "bug" });+ expect(res).toMatchObject({ tag: "bug" });+ });++ it("returns null when the (messageId, tag) pair doesn't exist", async () => {+ const db = deleteMock([]);+ const res = await tagQueries.removeMessageTag(db, { messageId: "m1", tag: "missing" });+ expect(res).toBeNull();+ });+});++describe("listTagsForMessage", () => {+ it("returns the plain tag strings, not the row shape", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve([{ tag: "bug" }, { tag: "q&a" }]));+ const res = await tagQueries.listTagsForMessage(chain, "m1");+ expect(res).toEqual(["bug", "q&a"]);+ });+});++describe("listTagsForMessages — batch (avoid N+1)", () => {+ it("skips the query entirely for an empty id list", async () => {+ const db: any = { select: vi.fn() };+ const res = await tagQueries.listTagsForMessages(db, []);+ expect(res).toEqual([]);+ expect(db.select).not.toHaveBeenCalled();+ });++ it("returns one row per (messageId, tag) pair for the caller to group", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve([+ { messageId: "m1", tag: "bug" },+ { messageId: "m2", tag: "feature" },+ ]));+ const db: any = { select: chain.select };+ const res = await tagQueries.listTagsForMessages(db, ["m1", "m2"]);+ expect(res).toEqual([+ { messageId: "m1", tag: "bug" },+ { messageId: "m2", tag: "feature" },+ ]);+ });+});++describe("filterMessageIdsByTag — the forum ?tag= filter's data access", () => {+ it("skips the query entirely for an empty candidate list (never a bare cross-channel tag scan)", async () => {+ const db: any = { select: vi.fn() };+ const res = await tagQueries.filterMessageIdsByTag(db, [], "bug");+ expect(res).toEqual([]);+ expect(db.select).not.toHaveBeenCalled();+ });++ it("narrows the CALLER-SUPPLIED candidate set to those carrying the tag — never queries by tag alone", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve([{ messageId: "m1" }]));+ const db: any = { select: chain.select };+ const res = await tagQueries.filterMessageIdsByTag(db, ["m1", "m2", "m3"], "bug");+ expect(res).toEqual(["m1"]);+ // The where() call must be reachable only via a candidate-scoped select —+ // this test can't inspect the SQL directly with this mock shape, but the+ // empty-candidate-list short-circuit above is what structurally prevents+ // a bare tag-only query from ever being issued.+ expect(chain.where).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.tsindex 0600173c1..5db9d1dd6 100644--- a/src/shared/test/queries/community-message.test.ts+++ b/src/shared/test/queries/community-message.test.ts@@ -16,6 +16,22 @@ describe("community/message exports", () => {});});+describe("updateOwnMessageContent", () => {+ it("guards the UPDATE by both message id and author id", async () => {+ const chain: any = {};+ chain.update = vi.fn(() => chain);+ chain.set = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.returning = vi.fn(() => Promise.resolve([{ id: "m1", channelId: "c1", content: "new" }]));+ const result = await messageQueries.updateOwnMessageContent(chain, {+ messageId: "m1", authorId: "u1", content: "new",+ });+ expect(chain.set).toHaveBeenCalledWith({ content: "new" });+ expect(chain.where).toHaveBeenCalledTimes(1);+ expect(result).toEqual({ id: "m1", channelId: "c1", content: "new" });+ });+});+function messageRow(id: string) {return {id,diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.tsindex 7f1149500..af467a1a2 100644--- a/src/shared/test/queries/server.test.ts+++ b/src/shared/test/queries/server.test.ts@@ -204,6 +204,24 @@ describe("createServer", () => {expect(insertCalls[0].values).toMatchObject({ description: "" });});++ it("writes a 4-digit discriminator + an up-front id on the server insert (name#disc handle)", async () => {+ const { db, insertCalls } = createDbMock({+ insertReturns: [[serverRow], [categoryRow], [], [memberRow]],+ selectReturns: [[{ name: "Alice" }]],+ });++ await serverQueries.createServer(db, { name: "My Server", ownerId });++ // The server insert now carries an id (minted up-front so the discriminator+ // can hash on it, like createUser) and a computed 4-digit decimal disc. The+ // (name, discriminator) uniqueness + salt-retry come from+ // withUniqueDiscriminator (unit-tested in user.test.ts) + the real index+ // (community-server-discriminator-unique.test.ts).+ expect(insertCalls[0].table).toBe(communityServer);+ expect(insertCalls[0].values.id).toEqual(expect.any(String));+ expect(insertCalls[0].values.discriminator).toMatch(/^\d{4}$/);+ });});// ────────────────────────────────────────────────────────────────────────────@@ -412,3 +430,56 @@ describe("listUserServers — filter predicates (source-level pin)", () => {expect(src).toMatch(/communityChannel/);});});++function createResolveServerMock(selectReturns: unknown[][]) {+ const selectCalls: Array<{ fields: Record<string, unknown>; where?: unknown }> = [];+ let index = 0;+ const db: any = {+ select(fields: Record<string, unknown>) {+ const call: { fields: Record<string, unknown>; where?: unknown } = { fields };+ selectCalls.push(call);+ const rows = selectReturns[index++] ?? [];+ const chain: any = {+ from: () => chain,+ innerJoin: () => chain,+ where(condition: unknown) {+ call.where = condition;+ return Promise.resolve(rows);+ },+ };+ return chain;+ },+ };+ return { db, selectCalls };+}++describe("resolveServerByNameForMember — handle-only entry", () => {+ it("rejects a raw server id without querying", async () => {+ const { db, selectCalls } = createResolveServerMock([]);+ await expect(serverQueries.resolveServerByNameForMember(db, "u_1", "srv_1")).resolves.toEqual([]);+ expect(selectCalls).toHaveLength(0);+ });++ it("recognizes four-digit and expanded name#discriminator handles", async () => {+ for (const handle of ["Studio#0042", "Studio#12345"]) {+ const row = { id: "srv_1", name: "Studio", discriminator: handle.split("#")[1] };+ const { db, selectCalls } = createResolveServerMock([[row]]);+ await expect(serverQueries.resolveServerByNameForMember(db, "u_1", handle)).resolves.toEqual([row]);+ expect(selectCalls).toHaveLength(1);+ }+ });++ it("rejects a bare name without probing a name fallback", async () => {+ const { db, selectCalls } = createResolveServerMock([]);+ await expect(serverQueries.resolveServerByNameForMember(db, "u_1", "Studio")).resolves.toEqual([]);+ expect(selectCalls).toHaveLength(0);+ });++ it("pins member scoping, discriminator parsing, and index-aligned NOCASE lookup in the query source", () => {+ const source = serverQueries.resolveServerByNameForMember.toString();+ expect(source).toMatch(/communityServerMember\.userId/);+ expect(source).toMatch(/parseNameAndTag/);+ expect(source).toMatch(/COLLATE NOCASE/);+ expect(source).toMatch(/communityServer\.discriminator/);+ });+});diff --git a/src/shared/test/queries/user.test.ts b/src/shared/test/queries/user.test.tsindex ee0adf2a1..5cb1baab8 100644--- a/src/shared/test/queries/user.test.ts+++ b/src/shared/test/queries/user.test.ts@@ -250,22 +250,52 @@ describe("withUniqueDiscriminator", () => {expect(insertFn).toHaveBeenCalledTimes(2);expect(insertFn).toHaveBeenNthCalledWith(1, computeDiscriminator("u_collide"));- expect(insertFn).toHaveBeenNthCalledWith(2, computeDiscriminator("u_collide:1"));- expect(result).toEqual({ discriminator: computeDiscriminator("u_collide:1") });+ // Salt scheme is now `id:width:attempt`; first retry stays at width 4, attempt 1.+ expect(insertFn).toHaveBeenNthCalledWith(2, computeDiscriminator("u_collide:4:1", 4));+ expect(result).toEqual({ discriminator: computeDiscriminator("u_collide:4:1", 4) });});- it("throws past the bounded attempt ceiling instead of looping forever", async () => {+ it("WIDENS by a digit after the per-width salt budget, never caps (A: variable-width)", async () => {+ // Every insert at width 4 collides; the allocator must exhaust the 5-try+ // width-4 budget then WIDEN to width 5 and keep going — the (A)-vs-(B)+ // behavior reversal (B threw at the cap; A never caps under real contention).const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" });+ const seen: string[] = [];+ const insertFn = vi.fn(async (discriminator: string) => {+ seen.push(discriminator);+ // Fail every width-4 (4-digit) attempt; succeed once a wider disc arrives.+ if (discriminator.length <= 4) throw uniqueErr;+ return { discriminator };+ });++ const result = await userQueries.withUniqueDiscriminator(+ {} as any,+ { id: "u_saturated", name: "Alice" },+ insertFn,+ );++ // All width-4 tries happened (bare + 4 salted), then a width-5 disc won.+ const width4 = seen.filter((d) => d.length === 4);+ const width5 = seen.filter((d) => d.length === 5);+ expect(width4.length).toBe(5); // MAX_DISCRIMINATOR_ATTEMPTS at width 4+ expect(width5.length).toBeGreaterThanOrEqual(1);+ expect(result.discriminator.length).toBe(5); // widened, not capped/thrown+ });++ it("stays loud — a widened insert failure still surfaces, never a silent dup", async () => {+ // A non-unique error mid-widen must rethrow immediately (loud), not be+ // swallowed as if it were a collision to retry past.+ const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" });+ const fatalErr = new Error("D1_ERROR: disk full");+ let n = 0;const insertFn = vi.fn(async () => {- throw uniqueErr;+ n += 1;+ throw n === 1 ? uniqueErr : fatalErr; // collide once, then a real fault});await expect(- userQueries.withUniqueDiscriminator({} as any, { id: "u_always_collides", name: "Alice" }, insertFn),- ).rejects.toBe(uniqueErr);- // Bounded — doesn't retry forever.- expect(insertFn.mock.calls.length).toBeGreaterThan(0);- expect(insertFn.mock.calls.length).toBeLessThan(20);+ userQueries.withUniqueDiscriminator({} as any, { id: "u_loud", name: "Alice" }, insertFn),+ ).rejects.toBe(fatalErr);});it("rethrows immediately on a non-unique-constraint error (no retry)", async () => {@@ -282,57 +312,51 @@ describe("withUniqueDiscriminator", () => {});describe("probeAvailableDiscriminator", () => {- it("returns a NON-collision fallback when all salted probes come back taken", async () => {- // Every SELECT resolves to a non-null row → the loop sees every salt- // (`id`, `id:1`, `id:2`, `id:3`, `id:4`) taken. The final returned- // discriminator MUST correspond to a salt the loop did NOT probe —- // otherwise Better Auth's INSERT is guaranteed to collide the very- // same instant.- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- // Every probe returns a "taken" row.- chain.limit = vi.fn(() => Promise.resolve([{ id: "u_other" }]));-- const returned = await userQueries.probeAvailableDiscriminator(chain, {+ it("WIDENS the probe space instead of capping at 4 digits when width-4 is saturated", async () => {+ // The first 5 probes (the width-4 salt budget: bare id + :4:1..:4:4) come+ // back taken → the probe must WIDEN to 5 digits and return a wider disc,+ // NOT hand back a capped 4-digit salt. This is the ★ catch: the email-signup+ // probe path must never cap at 4 either.+ let probeIdx = 0;+ const stub: any = {+ select: () => stub,+ from: () => stub,+ where: () => stub,+ limit: () => {+ const taken = probeIdx < 5; // 5 width-4 probes taken, then free+ probeIdx += 1;+ return Promise.resolve(taken ? [{ id: "u_other" }] : []);+ },+ };++ const returned = await userQueries.probeAvailableDiscriminator(stub, {id: "u_collide",name: "Alice",});- // Collect the salts the loop probed — computeDiscriminator("u_collide"),- // "u_collide:1", …, "u_collide:4". The returned value must not equal- // any of them; specifically, it should match the "one salt past the- // ceiling" (`:5`).- const probed = [- computeDiscriminator("u_collide"),- computeDiscriminator("u_collide:1"),- computeDiscriminator("u_collide:2"),- computeDiscriminator("u_collide:3"),- computeDiscriminator("u_collide:4"),- ];- expect(probed).not.toContain(returned);- expect(returned).toBe(computeDiscriminator("u_collide:5"));- });-- it("returns the first free salt on the happy path", async () => {- // First probe returns "taken", second probe returns "free" → the- // second salt's discriminator is what the caller gets.- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain);+ // 5 width-4 probes were taken, so the winner is the first width-5 disc.+ expect(returned.length).toBe(5);+ expect(returned).toBe(computeDiscriminator("u_collide:5:0", 5));+ });++ it("returns the first free salt on the happy path (still width 4)", async () => {+ // First probe (bare id) taken, second (id:4:1) free → second salt returned.+ const stub: any = {+ select: () => stub,+ from: () => stub,+ where: () => stub,+ };let calls = 0;- chain.limit = vi.fn(() => {+ stub.limit = () => {calls += 1;return Promise.resolve(calls === 1 ? [{ id: "u_other" }] : []);- });+ };- const returned = await userQueries.probeAvailableDiscriminator(chain, {+ const returned = await userQueries.probeAvailableDiscriminator(stub, {id: "u_ok",name: "Alice",});- expect(returned).toBe(computeDiscriminator("u_ok:1"));+ expect(returned).toBe(computeDiscriminator("u_ok:4:1", 4));});});diff --git a/src/shared/test/utils/predicates.test.ts b/src/shared/test/utils/predicates.test.tsindex 747ab8ca7..c14ad41ca 100644--- a/src/shared/test/utils/predicates.test.ts+++ b/src/shared/test/utils/predicates.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest"-import { isForum, isForumPost, isThread, canManageServer } from "../../src/utils/community-roles"+import { isForum, isThread, canManageServer } from "../../src/utils/community-roles"import { isPresenceOnline, isPresenceOffline } from "../../src/utils/status"import { isAccepted, isPending, isBlocked } from "../../src/utils/friendship"import { isPublic, isPrivate } from "../../src/utils/visibility"@@ -7,16 +7,10 @@ import { isPublic, isPrivate } from "../../src/utils/visibility"describe("channel-type predicates", () => {it("isForum", () => {expect(isForum("forum")).toBe(true)- expect(isForum("forum_post")).toBe(false)expect(isForum("text")).toBe(false)expect(isForum(null)).toBe(false)expect(isForum(undefined)).toBe(false)})- it("isForumPost", () => {- expect(isForumPost("forum_post")).toBe(true)- expect(isForumPost("forum")).toBe(false)- expect(isForumPost(null)).toBe(false)- })it("isThread", () => {expect(isThread("thread")).toBe(true)expect(isThread("text")).toBe(false)diff --git a/src/web/migrations/0079_community_server_discriminator.sql b/src/web/migrations/0079_community_server_discriminator.sqlnew file mode 100644index 000000000..c0f9dfc22--- /dev/null+++ b/src/web/migrations/0079_community_server_discriminator.sql@@ -0,0 +1,20 @@+-- Add a 4-digit `discriminator` to every community server for `name#0042`-style+-- disambiguation, mirroring the user discriminator (migration 0051). This is+-- the server-segment address anchor: a ref `/name#disc/channel` must resolve to+-- exactly one server, which requires `(name, discriminator)` uniqueness. The+-- unique index lands in 0080 (split from the seed so the census prerequisite+-- can run against remote between the two, same as user 0051 -> 0055).+--+-- New rows get an FNV-1a hash of community_server.id at INSERT time via+-- createServer's `withUniqueDiscriminator` wrap (see computeDiscriminator in+-- @alook/shared) — hash on the immutable id, not the name, so renames don't+-- rotate the tag.+--+-- Existing rows are seeded with a random 4-digit tag right here in SQL so we+-- don't ship a screenful of `#0000` on day one. The stored value is OPAQUE —+-- nothing recomputes it from the id and compares — so random is fine (identical+-- rationale to user 0051). Two same-name servers CAN draw the same random tag;+-- the 0080 unique index's census prerequisite catches and resolves that before+-- the index builds.+ALTER TABLE community_server ADD COLUMN discriminator TEXT NOT NULL DEFAULT '0000';+UPDATE community_server SET discriminator = printf('%04d', abs(random()) % 10000);diff --git a/src/web/migrations/0080_community_server_discriminator_unique.sql b/src/web/migrations/0080_community_server_discriminator_unique.sqlnew file mode 100644index 000000000..400d5091a--- /dev/null+++ b/src/web/migrations/0080_community_server_discriminator_unique.sql@@ -0,0 +1,24 @@+-- The `(name, discriminator)` pair is now load-bearing for server addressing:+-- a server ref `/name#0042/channel` resolves a handle to exactly one server, so+-- it must be unique. `name COLLATE NOCASE` matches the case-insensitive+-- `LIKE`-based lookups in resolveServerByNameForMember (queries/community/+-- server.ts) — the same index/resolver fold alignment migration 0075+-- established for top-level channel names. Without NOCASE, "Alook#0042" and+-- "alook#0042" could both exist as live rows and a case-insensitive handle+-- lookup would match two rows nondeterministically.+--+-- NO partial `WHERE deletedAt IS NULL` clause (unlike the user index in 0055):+-- community_server has no soft-delete column — servers are hard-deleted — so a+-- plain unique index is correct.+--+-- APPLY PREREQUISITE: zero duplicate (name COLLATE NOCASE, discriminator) among+-- servers after the 0079 random seed. The seed can draw the same tag for two+-- same-name servers, so re-scan before applying to ANY environment with+-- existing servers (local dev is empty after db:reset, so it builds directly):+-- SELECT name COLLATE NOCASE AS n, discriminator, COUNT(*) c+-- FROM community_server GROUP BY n, discriminator HAVING c > 1;+-- and resolve any collision by re-drawing the loser's discriminator (an UPDATE+-- to a free tag for that name — never delete a server, it owns channels ++-- messages) before this index will build.+CREATE UNIQUE INDEX idx_community_server_name_discriminator+ ON community_server(name COLLATE NOCASE, discriminator);diff --git a/src/web/migrations/0081_community_message_tags.sql b/src/web/migrations/0081_community_message_tags.sqlnew file mode 100644index 000000000..0d783eadb--- /dev/null+++ b/src/web/migrations/0081_community_message_tags.sql@@ -0,0 +1,31 @@+-- Post tags, migrated off the per-channel `community_channel.forum_tags` JSON+-- column onto a proper per-message table (phase2 forum≡thread, Gener #768 —+-- locked shape, not open). A post is now just a message (its opener) that+-- happens to have opened a thread; tags describe the CONTENT of that message,+-- not the channel/thread it lives in (Aigneis #696: a thread can be opened by+-- any message, so a channel/thread-level tags column would leak a tagging+-- capability onto every thread, not just posts — the field's mere presence on+-- a message row IS the "is this a tagged post" signal, no extra branch needed).+--+-- Existing `community_channel.forum_tags` JSON values get backfilled here at+-- the existing-data migration step (0082+) once the create/read paths this+-- table serves are live end-to-end; this migration is schema-only, no data+-- movement (new-door∥old-door discipline — old column stays untouched and+-- readable until the backfill + verification completes).+CREATE TABLE community_message_tag (+ id TEXT PRIMARY KEY NOT NULL,+ message_id TEXT NOT NULL REFERENCES community_message(id) ON DELETE CASCADE,+ tag TEXT NOT NULL+);++-- Toggle idempotency: adding a tag already present is a no-op, not a+-- duplicate row (mirrors community_message_mark's uq_mark_user_message).+CREATE UNIQUE INDEX uq_message_tag ON community_message_tag(message_id, tag);++-- Tag-first (per Blondie's #271 ruling): the read pattern is "find messages+-- with tag X" (the forum ?tag= filter), not "find tags for message X" — the+-- filter is always applied on top of an already-resolved, membership-gated+-- channel's message set (Aigneis #646/#647 red-line: never a bare cross-+-- channel tag search — that would hand a bot an existence-probe, "which+-- channels have this tag").+CREATE INDEX idx_message_tag_tag ON community_message_tag(tag, message_id);diff --git a/src/web/migrations/0082_forum_post_to_thread.sql b/src/web/migrations/0082_forum_post_to_thread.sqlnew file mode 100644index 000000000..a94331300--- /dev/null+++ b/src/web/migrations/0082_forum_post_to_thread.sql@@ -0,0 +1,226 @@+-- phase2 forum≡thread, step5: migrate every existing forum_post channel into+-- "a message in its forum + a thread opened on that message" — the exact+-- shape the send-into-forum path (step3) produces going forward. A+-- forum_post's `display_title` becomes the content of a brand-new opener+-- message landing in the forum itself; the forum_post channel row then+-- type-flips to `thread`, rooted on that new opener via `parent_message_id`.+--+-- TYPE-FLIP, not new-thread+move-messages: the forum_post row's `id` is kept+-- (only its `type`/`parent_message_id` change) so any existing reference to+-- that channel id stays pointed at the same row. Its existing M messages+-- (opener body + replies) are untouched — their `channel_id` already points+-- at this row's id, which now simply IS a thread, so they become the+-- thread's messages with zero rows rewritten.+--+-- The live send path's message insert hardcodes `created_at = now` with no+-- historical-timestamp override, which would forge every migrated message's+-- time as "whenever this migration ran" — real history corruption. That path+-- is NOT used here. Only ONE new row needs inventing at all (the opener), and+-- this migration mints it directly with the forum_post's OWN creation+-- time/creator as the opener's created_at/author_id: display_title was+-- itself written at that moment, so that timestamp is the correct one for+-- "when was this title given," not "whenever this backfill executed."+--+-- Deterministic id `'mig_opener_' || <forum_post channel id>` (not a random+-- id) so step 4 below can point `parent_message_id` at the exact row step 1+-- inserted for THIS forum_post, with no content/timestamp-based re-lookup+-- that could ambiguously match more than one row.+--+-- IDEMPOTENT ACROSS RE-RUNS: every step's WHERE clause keys off+-- `type = 'forum_post'`. Step 4 flips that type away, so re-running this same+-- migration a second time matches zero rows in every step — a safe no-op,+-- not a double-insert.+--+-- EXCLUDED (deliberately, pending a separate decision): forum_post rows with+-- `creator_id IS NULL` (the row's creator account was hard-deleted after+-- posting). `community_message.author_id` is NOT NULL, so no opener message+-- can be minted for one of these without inventing an author that never+-- existed — the same class of historical-data forgery the created_at fix+-- above exists to avoid. Left as `forum_post` untouched; a live scan+-- determines whether this case has any real rows before it needs an answer.+--+-- M=0 orphans (a forum_post with zero messages — a pre-existing, non-atomic+-- artifact of the old create path, unrelated to this migration) fall out of+-- these SAME statements with no special-case branch: step 1 still inserts+-- the new opener from display_title and step 4 still flips the row to+-- `type='thread'` rooted on that opener — the result is one opener message ++-- an empty thread, an entirely ordinary state (any message can open a thread+-- nobody has replied to yet).+--+-- TAGS BACKFILL (step 6 below): a post's `forum_tags` JSON array moves onto+-- the SAME new opener message (tags are an opener-message property under the+-- collapsed model, per Aigneis #696/#853 — not a channel/thread column) as+-- rows in the new `community_message_tag` table. Never-drop: a tag the user+-- actually set must survive this migration, so this backfill rides the SAME+-- commit as the type-flip rather than a separate migration file — the old+-- `forum_tags` column cannot be dropped until this has run.++-- 1. One new opener message per forum_post, landing in the forum (the parent+-- channel) — matches the live send path's model: an opener lives in the+-- addressed channel, the thread is a separate row. `seq` is assigned+-- directly against the target forum's current counter via ROW_NUMBER,+-- safe without CAS/atomicity because migrations run single-threaded+-- offline, unlike the live path's concurrent-writer claim.+INSERT INTO community_message (+ id, author_id, content, type, mention_type, reply_to_id, embeds,+ created_at, channel_id, seq, friendship_id, client_nonce+)+SELECT+ 'mig_opener_' || fp.id,+ fp.creator_id,+ COALESCE(fp.display_title, ''),+ 'default',+ NULL, NULL, NULL,+ fp.created_at,+ fp.parent_channel_id,+ COALESCE((SELECT s.next_seq FROM community_message_seq s WHERE s.channel_id = fp.parent_channel_id), 0)+ + ROW_NUMBER() OVER (PARTITION BY fp.parent_channel_id ORDER BY fp.created_at, fp.id),+ NULL, NULL+FROM community_channel AS fp+WHERE fp.type = 'forum_post' AND fp.creator_id IS NOT NULL;++-- 2. Advance each affected forum's seq counter by however many openers step 1+-- just claimed for it, so the next REAL send into that forum claims a+-- fresh seq with no collision — mirrors claimNextSeq's own upsert shape.+-- `excluded.next_seq` is the per-forum opener COUNT this SELECT computed+-- (the value that would have been inserted), not the pre-existing row's+-- value — SQLite's standard UPSERT reference for exactly this case.+INSERT INTO community_message_seq (channel_id, next_seq)+SELECT+ fp.parent_channel_id,+ COUNT(*)+FROM community_channel AS fp+WHERE fp.type = 'forum_post' AND fp.creator_id IS NOT NULL+GROUP BY fp.parent_channel_id+ON CONFLICT(channel_id) DO UPDATE SET+ next_seq = next_seq + excluded.next_seq;++-- 3. Bump each affected forum's own message_count/last_message_at for the new+-- opener(s), the same bookkeeping a live message insert does.+-- last_message_at only ADVANCES, never regresses: a historical opener's+-- created_at could predate the forum's current last_message_at if the+-- forum has had newer, unrelated activity since. SQLite's multi-arg+-- scalar max() returns NULL if EITHER argument is NULL, so a forum with+-- no prior last_message_at (NULL) must be COALESCEd to the new value+-- directly rather than compared against NULL.+UPDATE community_channel+SET+ message_count = message_count + (+ SELECT COUNT(*) FROM community_channel fp+ WHERE fp.type = 'forum_post' AND fp.parent_channel_id = community_channel.id AND fp.creator_id IS NOT NULL+ ),+ last_message_at = CASE+ WHEN last_message_at IS NULL THEN (+ SELECT MAX(fp.created_at) FROM community_channel fp+ WHERE fp.type = 'forum_post' AND fp.parent_channel_id = community_channel.id AND fp.creator_id IS NOT NULL+ )+ ELSE MAX(+ last_message_at,+ (SELECT MAX(fp.created_at) FROM community_channel fp+ WHERE fp.type = 'forum_post' AND fp.parent_channel_id = community_channel.id AND fp.creator_id IS NOT NULL)+ )+ END+WHERE id IN (+ SELECT DISTINCT parent_channel_id FROM community_channel+ WHERE type = 'forum_post' AND creator_id IS NOT NULL+);++-- 4. Type-flip: the forum_post row itself becomes the thread, rooted on the+-- opener message step 1 minted for it (deterministic id, no ambiguity).+-- `parent_channel_id` is left untouched — already points at the forum,+-- exactly where a natively-opened thread's parent_channel_id would point.+--+-- `name` MUST also be rederived here, not left as the old forum_post+-- slug: createMessageWithThread's live path (create-channels.ts) sets a+-- thread's `name` from the opener content, trimmed and truncated to+-- MAX_CHANNEL_NAME_LENGTH (100) — NOT from any slug. A migrated thread+-- that kept its old slug in `name` would be a structural difference from+-- a natively-created thread (which never has a slug-shaped name), not+-- merely an old-vs-fresh content difference — exactly what the+-- migration-equivalence requirement forbids. TRIM+CASE mirrors the live+-- path's `trim() || "thread"` fallback (an empty/whitespace-only+-- display_title falls back to the literal "thread", never an empty+-- string); SUBSTR(...,1,100) mirrors its `.slice(0, MAX_CHANNEL_NAME_LENGTH)`.+UPDATE community_channel+SET+ type = 'thread',+ parent_message_id = 'mig_opener_' || id,+ name = SUBSTR(+ CASE WHEN TRIM(COALESCE(display_title, '')) = '' THEN 'thread' ELSE TRIM(display_title) END,+ 1, 100+ )+WHERE type = 'forum_post' AND creator_id IS NOT NULL;++-- 5. Enroll participants on each newly-flipped thread — enroll is independent+-- social data; it does not appear automatically just because the row's+-- type changed. As of migration 0067, the notify/participant set lives on+-- `community_channel_member` with `relation='notify'` (the standalone+-- community_thread_participant table from 0058/0060/0061 no longer+-- exists — folded into this table). Seeded the same way 0060/0061 seeded+-- pre-existing threads/posts: distinct message authors ("spoke") + the+-- row's own creator (may not have posted, but always "spoke" the opener+-- here). INSERT OR IGNORE against uq_channel_member(channel_id, user_id,+-- relation), so re-running is a no-op (also naturally satisfied by step 4+-- already having flipped the type away on any second run).+INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, relation, source, added_by, added_at)+SELECT DISTINCT+ lower(hex(randomblob(16))),+ t.id,+ msg.author_id,+ 'notify',+ 'spoke',+ NULL,+ t.created_at+FROM community_channel AS t+JOIN community_message AS msg ON msg.channel_id = t.id+WHERE t.type = 'thread' AND t.parent_message_id = 'mig_opener_' || t.id;++INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, relation, source, added_by, added_at)+SELECT+ lower(hex(randomblob(16))),+ t.id,+ t.creator_id,+ 'notify',+ 'spoke',+ NULL,+ t.created_at+FROM community_channel AS t+WHERE t.type = 'thread' AND t.creator_id IS NOT NULL AND t.parent_message_id = 'mig_opener_' || t.id;++-- 6. Tags backfill: expand each migrated post's `forum_tags` JSON array (one+-- string per element) into `community_message_tag` rows on the new opener+-- message step 1 minted for it. `json_each` is SQLite core (no extension/+-- migration needed to enable it), reading directly off the now-flipped+-- `community_channel.type = 'thread'` rows this same commit just produced+-- — so this step must run AFTER step 4 above, keyed on the SAME+-- `parent_message_id = 'mig_opener_' || id` identity used to build the+-- enroll rows. `json_each.value` for a JSON array of strings yields the+-- unquoted string directly (SQLite decodes the JSON scalar), so no extra+-- unquoting/parsing is needed here. `id` reuses the same random-blob+-- shape as `community_message_tag.id` elsewhere (no natural key).+--+-- ⚠ The NULL/empty/malformed filter MUST live in the inner subquery, NOT+-- a WHERE on the outer join: `json_each(t.forum_tags)` is a table-valued+-- function evaluated per OUTER ROW before any outer-level WHERE narrows+-- the set, so a NULL/''/non-array argument throws "malformed JSON" for+-- that row regardless of an outer filter that would have excluded it —+-- verified against a real sqlite3 binary (a naive outer-WHERE version of+-- this statement aborted the whole INSERT on the very first tag-less+-- row). Restricting rows to json_each's input in a subquery FIRST means+-- json_each only ever sees rows already known to be a non-empty string.+-- No known malformed (non-JSON-array) `forum_tags` values exist (the live+-- read path has always parsed this same column successfully), so the+-- remaining case — a malformed value slipping through the inner filter —+-- is accepted as a hard migration-abort rather than silently swallowed+-- like the live path's `safeParseForumTags` fallback.+INSERT OR IGNORE INTO community_message_tag (id, message_id, tag)+SELECT+ lower(hex(randomblob(16))),+ 'mig_opener_' || tagged.id,+ je.value+FROM (+ SELECT id, forum_tags FROM community_channel+ WHERE type = 'thread' AND parent_message_id = 'mig_opener_' || id+ AND forum_tags IS NOT NULL AND forum_tags != '' AND forum_tags != '[]'+) AS tagged+JOIN json_each(tagged.forum_tags) AS je;diff --git a/src/web/migrations/0083_drop_forum_post_columns.sql b/src/web/migrations/0083_drop_forum_post_columns.sqlnew file mode 100644index 000000000..dd236e5f2--- /dev/null+++ b/src/web/migrations/0083_drop_forum_post_columns.sql@@ -0,0 +1,29 @@+-- phase2 forum≡thread, step 6's real remaining scope (missed when 992c9868+-- deleted forum_post from the type union — Aigneis/Ingaborg caught the gap+-- during the terminal census): drops the two migration-0078 columns ++-- their partial unique index, now that 0082 has migrated every existing+-- forum_post row (and its display_title/forum_tags) into the new+-- message/message_tags model.+--+-- ⚠ DEPLOY ORDERING (not enforced by file-number order alone — see+-- red-line 6): this migration MUST NOT ship in the same deploy window as+-- 0082. It must only run after 0082 has been confirmed applied AND+-- verified in production (e.g. migrated-message-count / migrated-tag-count+-- cross-checked against the pre-migration forum_post/forum_tags counts).+-- Once this runs, display_title/forum_tags are physically gone — there is+-- no rollback path if 0082 turns out to have had a bug that needs a rerun.++-- 1. The partial unique index scoped to `type = 'forum_post'` — a WHERE+-- clause that, after 992c9868, can never match another row again (the+-- type no longer exists in the application's StoredChannelType union).+-- Dead structure, not merely unused.+DROP INDEX IF EXISTS idx_forum_post_parent_name;++-- 2. display_title — the pre-slugify original title, captured only by the+-- now-deleted create-forum-post.ts. 0082 already copied every row's+-- value into its new opener message's content before this point.+ALTER TABLE community_channel DROP COLUMN display_title;++-- 3. forum_tags — the per-channel JSON tag list. 0082 already expanded+-- every row's value into community_message_tag rows before this point.+ALTER TABLE community_channel DROP COLUMN forum_tags;diff --git a/src/web/scripts/seed-stress.ts b/src/web/scripts/seed-stress.tsindex a05efd772..b1a680f68 100644--- a/src/web/scripts/seed-stress.ts+++ b/src/web/scripts/seed-stress.ts@@ -302,8 +302,8 @@ async function ensureChannel(const found = existing.find((c) => c.name === slug)if (found) return found.idconst data = await client.post<{ channel: { id: string } }>(- `/api/community/servers/${serverId}/channels`,- { name, type: "text" },+ "/api/community/channels",+ { serverId, name, type: "text" },)return data.channel.id}diff --git a/src/web/src/app/api/community/attachmentDownload/route.test.ts b/src/web/src/app/api/community/attachmentDownload/route.test.tsdeleted file mode 100644index 7c87f2def..000000000--- a/src/web/src/app/api/community/attachmentDownload/route.test.ts+++ /dev/null@@ -1,232 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockR2Get = vi.fn()-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({- env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mockR2Get(...a) } },- })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetBotBinding = vi.fn()-const mockGetAttachmentById = vi.fn()-const mockGetMessage = vi.fn()-const mockGetChannelForMember = vi.fn()-const mockGetChannelType = vi.fn()-const mockGetDM = vi.fn()-const mockGetDMPeer = vi.fn()--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityAttachment: {- getAttachmentById: (...a: unknown[]) => mockGetAttachmentById(...a),- },- communityMessage: {- ...actual.queries.communityMessage,- getMessage: (...a: unknown[]) => mockGetMessage(...a),- },- communityChannel: {- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- getChannelType: (...a: unknown[]) => mockGetChannelType(...a),- },- communityDm: {- getDM: (...a: unknown[]) => mockGetDM(...a),- getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),- },- communityFriendship: { isBlocked: async () => false },- },- }-})--import { POST } from "./route"--function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/attachmentDownload", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--describe("POST /api/community/agent/attachmentDownload", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- })-- it("401 without Authorization", async () => {- const res = await POST(req({ id: "x" }))- expect(res.status).toBe(401)- })-- it("404 when the id doesn't exist", async () => {- mockGetAttachmentById.mockResolvedValue(null)- const res = await POST(req({ id: "missing" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(404)- })-- it("404 (not 403) when a pending row belongs to another bot — enumeration-safe", async () => {- mockGetAttachmentById.mockResolvedValue({- id: "att_1",- messageId: null,- uploaderId: "some_other_bot",- r2Key: "channel/c1/uuid/a.png",- filename: "a.png",- contentType: "image/png",- size: 10,- })- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(404)- // Body byte-identical to "genuine 404" case.- const body = await res.json()- expect(body).toEqual({ error: "attachment not found" })- expect(mockR2Get).not.toHaveBeenCalled()- })-- it("succeeds on a pending row owned by the requesting bot (round-trip verify)", async () => {- mockGetAttachmentById.mockResolvedValue({- id: "att_1",- messageId: null,- uploaderId: "bot_1",- r2Key: "channel/c1/uuid/a.png",- filename: "a.png",- contentType: "image/png",- size: 10,- })- mockR2Get.mockResolvedValue({- body: new ReadableStream(),- size: 10,- httpMetadata: {},- arrayBuffer: async () => new ArrayBuffer(10),- })- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(res.headers.get("Content-Type")).toBe("image/png")- expect(res.headers.get("Content-Length")).toBe("10")- // RFC 5987 header. ASCII filename → percent-encoded but unchanged.- expect(res.headers.get("X-Alook-Filename")).toBe(encodeURIComponent("a.png"))- })-- it("percent-encodes non-ASCII filenames per RFC 5987", async () => {- mockGetAttachmentById.mockResolvedValue({- id: "att_1",- messageId: null,- uploaderId: "bot_1",- r2Key: "channel/c1/uuid/x.png",- filename: "图表.png",- contentType: "image/png",- size: 5,- })- mockR2Get.mockResolvedValue({- body: new ReadableStream(),- size: 5,- httpMetadata: {},- arrayBuffer: async () => new ArrayBuffer(5),- })- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- const encoded = res.headers.get("X-Alook-Filename")- expect(encoded).toBeTruthy()- expect(decodeURIComponent(encoded!)).toBe("图表.png")- })-- it("returns 502 when the row exists but R2 has no object (infra drift, not enumeration)", async () => {- mockGetAttachmentById.mockResolvedValue({- id: "att_1",- messageId: null,- uploaderId: "bot_1",- r2Key: "channel/c1/uuid/a.png",- filename: "a.png",- contentType: "image/png",- size: 10,- })- mockR2Get.mockResolvedValue(null)- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(502)- })-- it("getAttachmentById throws → 500 JSON envelope (no binary body leak)", async () => {- mockGetAttachmentById.mockRejectedValueOnce(new Error("d1_transient"))- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(500)- expect(await res.json()).toEqual({ error: "internal error", code: "internal" })- })-- it("COMMUNITY_MEDIA.get throws → 500 JSON envelope", async () => {- mockGetAttachmentById.mockResolvedValue({- id: "att_1",- messageId: null,- uploaderId: "bot_1",- r2Key: "channel/c1/uuid/a.png",- filename: "a.png",- contentType: "image/png",- size: 10,- })- mockR2Get.mockRejectedValueOnce(new Error("r2_boom"))- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(500)- expect(await res.json()).toEqual({ error: "internal error", code: "internal" })- })-- it("obj.arrayBuffer() throws (R2 stream mid-read) → 500 JSON envelope, NOT a truncated 200", async () => {- mockGetAttachmentById.mockResolvedValue({- id: "att_1",- messageId: null,- uploaderId: "bot_1",- r2Key: "channel/c1/uuid/a.png",- filename: "a.png",- contentType: "image/png",- size: 10,- })- mockR2Get.mockResolvedValue({- body: new ReadableStream(),- size: 10,- httpMetadata: {},- arrayBuffer: async () => {- throw new Error("stream_error")- },- })- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(500)- expect(await res.json()).toEqual({ error: "internal error", code: "internal" })- })-- it("404 when a persisted row's channel-member gate fails — same shape as genuine 404", async () => {- mockGetAttachmentById.mockResolvedValue({- id: "att_1",- messageId: "m_1",- uploaderId: "bot_someone",- r2Key: "channel/c1/uuid/a.png",- filename: "a.png",- contentType: "image/png",- size: 10,- })- mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c1" })- mockGetChannelType.mockResolvedValue("text")- mockGetChannelForMember.mockResolvedValue(null) // not a member- const res = await POST(req({ id: "att_1" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(404)- expect(mockR2Get).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/community/attachmentDownload/route.ts b/src/web/src/app/api/community/attachmentDownload/route.tsdeleted file mode 100644index a0be90950..000000000--- a/src/web/src/app/api/community/attachmentDownload/route.ts+++ /dev/null@@ -1,115 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, createLogger, CommunityAgentAttachmentDownloadRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"--const log = createLogger({ service: "community-agent-attachment-download" })--/**- * RFC 5987 filename encoding for `X-Alook-Filename`. Percent-encodes- * everything outside the RFC 5987 attr-char set. The daemon-side client- * decodes before writing to disk so non-ASCII filenames (`图表.png`) round- * trip safely.- */-function encodeRfc5987(value: string): string {- return encodeURIComponent(value)- .replace(/['()]/g, escape)- .replace(/\*/g, "%2A")-}--/**- * POST /api/community/attachmentDownload- *- * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor →- * 403 via requireBot.- *- * Body: `{ id }`.- * Response: raw binary body + `Content-Type`, `Content-Length`,- * `X-Alook-Filename` (RFC 5987 percent-encoded).- *- * Enumeration-safe: every "you can't have this" path returns the same 404- * with body "attachment not found" — pending-vs-persisted, wrong-owner, and- * genuine 404 are indistinguishable to a prober. A distinct 502 fires only- * when the DB row exists but R2 has drifted (infra fault, not user-facing- * gate).- *- * The body is buffered (`arrayBuffer`) inside the top-level try/catch so an- * R2 stream error becomes a structured 500 instead of a truncated 200 the- * daemon-side helper can't parse. The daemon `callDownload` already- * buffers via `res.arrayBuffer()` (attachments are capped at 25 MB), so no- * streaming behavior is lost.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId- try {- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentAttachmentDownloadRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload" }, { status: 400 })- }-- const db = getDb(ctx.env.DB)- const row = await queries.communityAttachment.getAttachmentById(db, parsed.data.id)- if (!row) {- return NextResponse.json({ error: "attachment not found" }, { status: 404 })- }-- if (row.messageId === null) {- // Pending row — only the uploading bot may see it (round-trip verify).- if (row.uploaderId !== botUserId) {- return NextResponse.json({ error: "attachment not found" }, { status: 404 })- }- } else {- // Persisted row — resolve target scope, then run the standard membership- // gate. Rewrite any non-2xx to a generic 404 so a prober can't tell- // "not a member" from "row doesn't exist".- const message = await queries.communityMessage.getMessage(db, row.messageId)- if (!message) {- return NextResponse.json({ error: "attachment not found" }, { status: 404 })- }- const channelType = await queries.communityChannel.getChannelType(db, message.channelId)- if (channelType === "dm") {- const gate = await requireDMAccess(db, message.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })- } else {- const gate = await requireChannelMember(db, message.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })- }- }-- const obj = await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)- if (!obj) {- // Row exists but R2 has no object — infra fault, distinct from the- // enumeration-safe 404 above.- return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })- }-- const contentType = row.contentType || obj.httpMetadata?.contentType || "application/octet-stream"- const size = row.size ?? obj.size- const headers: Record<string, string> = {- "Content-Type": contentType,- "X-Alook-Filename": encodeRfc5987(row.filename),- }- if (typeof size === "number") headers["Content-Length"] = String(size)-- // Buffer here (inside try/catch) so an R2 stream mid-read error surfaces- // as a structured 500 rather than a truncated 200 the client can't parse.- const buffer = await obj.arrayBuffer()- return new Response(buffer, { headers })- } catch (err) {- log.error("attachment_route_failure", {- route: "attachmentDownload",- botUserId: botUserId,- cause: err instanceof Error ? err.stack ?? err.message : String(err),- })- return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })- }-})diff --git a/src/web/src/app/api/community/nap/route.test.ts b/src/web/src/app/api/community/bots/me/nap/route.test.tssimilarity index 97%rename from src/web/src/app/api/community/nap/route.test.tsrename to src/web/src/app/api/community/bots/me/nap/route.test.tsindex 9113d3375..1699f03f3 100644--- a/src/web/src/app/api/community/nap/route.test.ts+++ b/src/web/src/app/api/community/bots/me/nap/route.test.ts@@ -53,7 +53,7 @@ vi.mock("@/lib/middleware/community-actor", () => ({import { POST } from "./route"function req(body: unknown = { handoff: "note to future self" }) {- return new NextRequest("http://localhost/api/community/nap", {+ return new NextRequest("http://localhost/api/community/bots/me/nap", {method: "POST",body: JSON.stringify(body),})@@ -70,7 +70,7 @@ const READY_CTX = {ownerUserId: "owner_1",}-describe("POST /api/community/nap", () => {+describe("POST /api/community/bots/me/nap", () => {beforeEach(() => {vi.clearAllMocks()})diff --git a/src/web/src/app/api/community/nap/route.ts b/src/web/src/app/api/community/bots/me/nap/route.tssimilarity index 54%rename from src/web/src/app/api/community/nap/route.tsrename to src/web/src/app/api/community/bots/me/nap/route.tsindex 6015729cd..19f8a2e9d 100644--- a/src/web/src/app/api/community/nap/route.ts+++ b/src/web/src/app/api/community/bots/me/nap/route.ts@@ -12,21 +12,37 @@ import { withCommunityActor, requireBot } from "@/lib/middleware/community-actorimport { pushAgentNapToMachine } from "@/lib/community/bot-push"/**- * POST /api/community/nap — `alook nap --handoff <file>|--text <s>`.+ * POST /api/community/bots/me/nap — `alook nap --handoff <file>|--text <s>`.*- * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).+ * Relocated from the flat /api/community/nap (route/disc 接口树统一, Gener #215+ * 乙; Blondie #527 placement). nap is a BOT-QUA-BOT self lifecycle action — the+ * agent resets its OWN session — so it lives under the bots/me/* family+ * (self-scope, "me" = the credential-authenticated bot, NO target id), the same+ * "me = credential actor" model users/me/* uses (a bot hits POST+ * users/me/inbox/pull for its own inbox). This is DISTINCT from:+ * - bots/{id}/* (owner MANAGES an owned bot: reset-session/approval/audit —+ * withAuth + getBotOwnedBy, owner→bot[id]); nap is bot→self, opposite auth.+ * - users/me/* (an actor's USER-scoped resources: inbox/marks — human+bot both+ * have a user row); nap is bot-qua-bot lifecycle, only a bot has a session.+ * bots/me/* family invariant (same as users/me #426): self-scope, credential =+ * identity, NO target-bot/target-user param, "me" never proxies another bot.*- * Agent-self-initiated session reset. The self-serve twin of the owner- * `reset-session` route: build the bot's RuntimeConfig → push `agent:nap`- * (carrying the mandatory handoff) to the bot's OWN machine → on delivery- * (`sent > 0`) write the `nap` audit row. If the daemon is offline- * (`sent === 0`) return 409 and write NO audit row — the audit signals a real- * nap landed at the daemon, not a request. Notifies no one: a nap is the- * agent's private self-state change.+ * Bot-only, human actor → 403 via requireBot (Gener #116). `botUserId`/+ * `machineId` come from the authenticated runner (gate.bot), NEVER a request+ * field, so an agent can only nap ITSELF — a single self-reset, not a batch and+ * not a nap of any other bot.+ *+ * The flat /api/community/nap route is deleted (flat-delete step) — this door+ * is the sole canonical entry; the deploy-orchestration verify-list gates+ * deleting it on the daemon being confirmed on this new target.*- * Auth is `withAgentRunnerAuth` (runner key), so the bot acts on ITSELF —- * `ctx.botUserId`/`ctx.machineId` come from the authenticated runner, not a- * request field, so an agent can only nap itself.+ * Agent-self-initiated session reset. The self-serve twin of the owner+ * `bots/{id}/reset-session` route: build the bot's RuntimeConfig → push+ * `agent:nap` (carrying the mandatory handoff) to the bot's OWN machine → on+ * delivery (`sent > 0`) the daemon writes the `nap` audit row at reborn-ready.+ * If the daemon is offline (`sent === 0`) return 409 and write NO audit row —+ * the audit signals a real nap landed, not a request. Notifies no one: a nap is+ * the agent's private self-state change.*/export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const gate = requireBot(ctx.actor)diff --git a/src/web/src/app/api/community/channelMember/route.test.ts b/src/web/src/app/api/community/channelMember/route.test.tsdeleted file mode 100644index c8d21cc10..000000000--- a/src/web/src/app/api/community/channelMember/route.test.ts+++ /dev/null@@ -1,250 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetUserByNameAndDiscriminator = vi.fn()-const mockGetBotBinding = vi.fn()-const mockResolveServerByNameForMember = vi.fn()-const mockGetServer = vi.fn()-const mockResolveChannelByNameForMember = vi.fn()-const mockGetChannel = vi.fn()-const mockIsChannelPrivate = vi.fn()-const mockResolveChannelAccessContext = vi.fn()-const mockListThreadParticipantUserIds = vi.fn()-const mockResolveScopeMembers = vi.fn()-const mockGetMembersByUserIds = vi.fn()-const mockGetDMBetween = vi.fn()-const mockIsBlocked = vi.fn()-const mockGetMessageByChannelAndSeq = vi.fn()-const mockGetThreadChannelByParentMessage = vi.fn()--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: {- ...actual.queries.user,- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),- },- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityServer: {- ...actual.queries.communityServer,- resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),- getServer: (...a: unknown[]) => mockGetServer(...a),- },- communityChannel: {- ...actual.queries.communityChannel,- resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),- getChannel: (...a: unknown[]) => mockGetChannel(...a),- isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),- resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),- getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),- },- communityThread: {- ...actual.queries.communityThread,- listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),- },- communityMembersResolver: {- ...actual.queries.communityMembersResolver,- resolveScopeMembers: (...a: unknown[]) => mockResolveScopeMembers(...a),- },- communityMember: {- ...actual.queries.communityMember,- getMembersByUserIds: (...a: unknown[]) => mockGetMembersByUserIds(...a),- },- communityMessage: {- ...actual.queries.communityMessage,- getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),- },- communityDm: {- ...actual.queries.communityDm,- getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),- },- communityFriendship: {- ...actual.queries.communityFriendship,- isBlocked: (...a: unknown[]) => mockIsBlocked(...a),- },- },- }-})--const mockFetchOnlineUserIds = vi.fn()-// Presence is a bulk ws-do fan-out — mock the helper so the route test stays-// unit-scoped; the set it returns drives each member's `online` boolean.-vi.mock("@/lib/community/member-presence", async () => {- const actual = await vi.importActual<typeof import("@/lib/community/member-presence")>(- "@/lib/community/member-presence",- )- return {- ...actual,- fetchOnlineUserIds: (...a: unknown[]) => mockFetchOnlineUserIds(...a),- }-})--import { POST } from "./route"--function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/channelMember", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--describe("POST /api/community/agent/channelMember", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- mockFetchOnlineUserIds.mockResolvedValue(new Set<string>())- // Default: bot has channel access (server member, public channel).- mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null, creatorId: "owner_1", categoryId: null },- anchor: { id: "ch_1", type: "text", creatorId: "owner_1", categoryId: null },- role: "member",- isChannelMember: false,- isCreator: false,- isPrivate: false,- })- })-- it("401 without Authorization", async () => {- const res = await POST(req({ channel: "/demo/general" }))- expect(res.status).toBe(401)- })-- it("400 on payload validation failure (missing channel)", async () => {- const res = await POST(req({}, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- })-- it("400 on a DM ref — channel-scoped only", async () => {- // No DB mocks needed: DM refs are rejected up front, so an un-opened DM- // (no peer, no DM row) still gets the specific channel-scoped 400 instead- // of a misleading "dm not found" 404.- const res = await POST(req({ channel: "/.dm/peer#0042" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- const body = await res.json()- expect(body.error).toContain("channel-scoped")- expect(mockGetUserByNameAndDiscriminator).not.toHaveBeenCalled()- expect(mockGetDMBetween).not.toHaveBeenCalled()- })-- it("400 on a malformed ref", async () => {- const res = await POST(req({ channel: "not-a-ref" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- })-- it("public top-level channel → { visibility:'public', hint } with the server's actual name substituted", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1", name: "general", type: "text", parentChannelId: null }])- mockGetChannel.mockResolvedValue({ id: "ch_1", serverId: "srv_1", name: "general", type: "text" })- mockGetServer.mockResolvedValue({ id: "srv_1", name: "demo" })- mockIsChannelPrivate.mockResolvedValue(false)- const res = await POST(req({ channel: "/demo/general" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({- visibility: "public",- hint: "This channel is public. Use `alook server member --server demo` to list who can see it.",- })- expect("members" in body).toBe(false)- })-- it("private top-level channel → { visibility:'private', members } from resolveScopeMembers", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1", name: "leadership", type: "text", parentChannelId: null }])- mockGetChannel.mockResolvedValue({ id: "ch_1", serverId: "srv_1", name: "leadership", type: "text" })- // Access context: bot is the creator (so it can see the private channel).- mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null, creatorId: "bot_1", categoryId: "cat_1" },- anchor: { id: "ch_1", type: "text", creatorId: "bot_1", categoryId: "cat_1" },- role: "member",- isChannelMember: false,- isCreator: true,- isPrivate: true,- })- mockIsChannelPrivate.mockResolvedValue(true)- mockResolveScopeMembers.mockResolvedValue([- { userId: "u_owner", role: "owner", source: "explicit" },- { userId: "u_alice", role: "member", source: "explicit" },- ])- mockGetMembersByUserIds.mockResolvedValue([- { userId: "u_owner", userName: "gustavo", discriminator: "4821", role: "owner", statusEmoji: "🎧", statusText: "vibing" },- { userId: "u_alice", userName: "alice", discriminator: "0193", role: "member", statusEmoji: null, statusText: null },- ])- mockFetchOnlineUserIds.mockResolvedValue(new Set(["u_owner"]))- const res = await POST(req({ channel: "/demo/leadership" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({- visibility: "private",- hasMore: false,- members: [- { handle: "gustavo#4821", role: "owner", online: true, status: { emoji: "🎧", text: "vibing" } },- { handle: "alice#0193", role: "member", online: false, status: { emoji: null, text: "" } },- ],- })- // presence batched over the resolved (bounded) roster — never per-member.- expect(mockFetchOnlineUserIds).toHaveBeenCalledWith(expect.anything(), ["u_owner", "u_alice"], "srv_1")- })-- it("thread ref → always private on the wire; roster is the thread-participant set", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_parent", name: "general", type: "text", parentChannelId: null }])- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_12" })- mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "th_1" })- mockGetChannel.mockResolvedValue({ id: "th_1", serverId: "srv_1", name: "Thread", type: "thread", parentChannelId: "ch_parent" })- mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "th_1", serverId: "srv_1", type: "thread", parentChannelId: "ch_parent", creatorId: "bot_1", categoryId: null },- anchor: { id: "ch_parent", type: "text", creatorId: "owner_1", categoryId: null },- role: "member",- isChannelMember: false,- isCreator: false,- isPrivate: false,- })- mockListThreadParticipantUserIds.mockResolvedValue(["u_owner", "u_bot"])- mockGetMembersByUserIds.mockResolvedValue([- { userId: "u_owner", userName: "gustavo", discriminator: "4821", role: "owner", nickname: null, statusEmoji: null, statusText: null },- { userId: "u_bot", userName: "otter", discriminator: "5522", role: "member", nickname: null, statusEmoji: "🌀", statusText: "running" },- ])- mockFetchOnlineUserIds.mockResolvedValue(new Set(["u_bot"]))-- const res = await POST(req({ channel: "/demo/general/#12" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body.visibility).toBe("private")- expect(body.hasMore).toBe(false)- expect(body.members).toEqual([- { handle: "gustavo#4821", role: "owner", online: false, status: { emoji: null, text: "" } },- { handle: "otter#5522", role: "member", online: true, status: { emoji: "🌀", text: "running" } },- ])- expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "th_1")- })-- // Forum posts are not agent-addressable via any current ref grammar- // (`resolveChannelByNameForMember` filters `parent_channel_id IS NULL`- // and `#N` refs materialize as `type: "thread"`), so there is no code- // path that reaches this handler with a `forum_post` row. If forum-post- // refs are ever reintroduced, add a test back here.-})diff --git a/src/web/src/app/api/community/channelMember/route.ts b/src/web/src/app/api/community/channelMember/route.tsdeleted file mode 100644index 14dfe0b71..000000000--- a/src/web/src/app/api/community/channelMember/route.ts+++ /dev/null@@ -1,147 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import {- queries,- CommunityAgentChannelMemberRequestSchema,- DM_SERVER,- formatHandle,- isThread,- parseRef,-} from "@alook/shared"-import type {- CommunityCliChannelMemberResult as ChannelMemberResult,- CommunityCliServerMember as ServerMember,-} from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { requireChannelAccess } from "@/lib/community/permissions"-import { fetchOnlineUserIds, toMemberStatus } from "@/lib/community/member-presence"--/**- * POST /api/community/channelMember — `alook channel member --channel <ref>`.- * Returns the followed members of a channel/thread.- *- * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor →- * 403 via requireBot.- *- * Branches by resolved target:- * - DM ref → 400 (channel-scoped). Rejected UP FRONT (before- * `resolveTargetForMember`) so an un-opened DM surfaces the correct- * channel-scoped 400 instead of a misleading 404 "dm not found".- * - thread (`type = "thread"`) → always private on the wire; returns the- * participant roster (`community_thread_participant`). Threads are the- * NOTIFY dimension: they carry their own notify set irrespective of the- * parent channel's public/private state. Forum posts share this shape but- * are not agent-addressable via any current ref grammar, so this branch- * only fires for threads reached via `<server>/<channel>/#N`.- * - public top-level channel/forum → `{ visibility: "public", hint }` (no- * roster enumeration — every server member can see it, so the agent should- * use `alook server member --server <name>` instead).- * - private channel / private forum → `{ visibility: "private", members }`- * sourced from `resolveScopeMembers` (the same audience the fan-out and- * human UI use).- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentChannelMemberRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }-- // Reject DM refs up front: an un-opened DM would otherwise trip- // `resolveTargetForMember`'s 404 "dm not found" before the DM-branch guard- // below could emit the specific channel-scoped 400.- try {- const p = parseRef(parsed.data.channel)- if (p.server === DM_SERVER) {- return NextResponse.json(- { error: "channel member is channel-scoped — DM refs are not supported" },- { status: 400 },- )- }- } catch {- // Fall through — resolveTargetForMember returns the canonical 400.- }-- const resolved = await resolveTargetForMember(db, botUserId, parsed.data.channel, {- createDmIfMissing: false,- createThreadIfMissing: false,- callerKind: "bot",- })- if ("error" in resolved) return resolveErrorResponse(resolved)- if (resolved.kind === "dm") {- return NextResponse.json(- { error: "channel member is channel-scoped — DM refs are not supported" },- { status: 400 },- )- }-- const channelId = resolved.channelId- const access = await requireChannelAccess(db, channelId, botUserId)- if (!access.ok) return NextResponse.json({ error: access.error }, { status: access.status })-- const { channel, isPrivate } = access.value-- // Thread branch: the NOTIFY dimension — the roster is the participant set- // (`community_thread_participant`), always private on the wire regardless of- // the parent's public/private state. Forum posts are not agent-addressable,- // so this handler only sees `thread` or top-level channel rows here.- if (isThread(channel.type)) {- const userIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)- const members = await hydrateMembers(db, ctx.env, channel.serverId, userIds)- // hasMore: false — a thread participant roster is membership-bounded and- // returned whole; the field keeps the wire shape uniform with `server- // member` (pagination is a pure back-end add later if ever needed).- return NextResponse.json<ChannelMemberResult>({ visibility: "private", members, hasMore: false })- }-- if (!isPrivate) {- const server = await queries.communityServer.getServer(db, channel.serverId)- const serverName = server?.name ?? channel.serverId- const hint = `This channel is public. Use \`alook server member --server ${serverName}\` to list who can see it.`- return NextResponse.json<ChannelMemberResult>({ visibility: "public", hint })- }-- const scoped = await queries.communityMembersResolver.resolveScopeMembers(db, { scope: "channel", scopeId: channelId })- const userIds = scoped.map((s) => s.userId)- const members = await hydrateMembers(db, ctx.env, channel.serverId, userIds)- // hasMore: false — a private channel roster is membership-bounded (see thread- // branch note); returned whole, wire shape kept uniform with `server member`.- return NextResponse.json<ChannelMemberResult>({ visibility: "private", members, hasMore: false })-})--/**- * Hydrate a user id list into `ServerMember[]` — mirrors `listMembers`'s- * mapping (formatHandle, default role "member", online snapshot, status). Users- * whose account is soft-deleted drop out via `getMembersByUserIds`'s inner- * join on `user`. Users missing a `community_server_member` row (shouldn't- * happen in normal flow) also drop out; they never surface as a stub row.- * Presence is one bulk read over the resolved (bounded) roster — never- * per-member.- */-async function hydrateMembers(- db: ReturnType<typeof getDb>,- env: Env,- serverId: string,- userIds: string[],-): Promise<ServerMember[]> {- if (userIds.length === 0) return []- const rows = await queries.communityMember.getMembersByUserIds(db, serverId, userIds)- const onlineSet = await fetchOnlineUserIds(env, rows.map((r) => r.userId), serverId)- return rows.map((r) => ({- handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),- role: r.role ?? "member",- online: onlineSet.has(r.userId),- status: toMemberStatus(r),- }))-}diff --git a/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts b/src/web/src/app/api/community/channels/[id]/addable-members/route.test.tsdeleted file mode 100644index b6f5090f5..000000000--- a/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--const mockResolveChannelAccessContext = vi.fn()-const mockListMembers = vi.fn()-const mockListChannelMemberUserIds = 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: {- communityChannel: {- resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),- listChannelMemberUserIds: (...a: unknown[]) => mockListChannelMemberUserIds(...a),- },- communityMember: { listMembers: (...a: unknown[]) => mockListMembers(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--const ctx = { params: { id: "c1" } } as any-function req() {- return new NextRequest("http://localhost/api/community/channels/c1/addable-members")-}--function managerCtx() {- return {- channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "u1" },- anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },- role: "member",- isPrivate: true,- isChannelMember: true,- isCreator: true,- }-}--describe("GET /channels/[id]/addable-members", () => {- beforeEach(() => {- vi.clearAllMocks()- mockResolveChannelAccessContext.mockResolvedValue(managerCtx())- mockListMembers.mockResolvedValue([- { userId: "u1", userName: "Creator", userImage: null, discriminator: "0001" },- { userId: "u2", userName: "Bob", userImage: null, discriminator: "0002" },- { userId: "u3", userName: "Cara", userImage: null, discriminator: "0003" },- ])- mockListChannelMemberUserIds.mockResolvedValue(["u2"])- })-- it("excludes existing channel members and the creator", async () => {- const res = await GET(req(), ctx)- expect(res.status).toBe(200)- const body = await res.json()- const ids = body.members.map((m: { userId: string }) => m.userId)- expect(ids).toEqual(["u3"]) // u1 = creator, u2 = already member- })-- it("allows a plain member (not just creator) to load the picker", async () => {- mockResolveChannelAccessContext.mockResolvedValue({- ...managerCtx(),- channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "other" },- anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" },- role: "member",- isChannelMember: true,- isCreator: false,- })- const res = await GET(req(), ctx)- expect(res.status).toBe(200)- })-- it("rejects a non-member outsider (403 from the access gate)", async () => {- mockResolveChannelAccessContext.mockResolvedValue(null)- const res = await GET(req(), ctx)- expect(res.status).toBe(403)- })-})diff --git a/src/web/src/app/api/community/channels/[id]/addable-members/route.ts b/src/web/src/app/api/community/channels/[id]/addable-members/route.tsdeleted file mode 100644index 054e11c02..000000000--- a/src/web/src/app/api/community/channels/[id]/addable-members/route.ts+++ /dev/null@@ -1,43 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { requireChannelAccess } from "@/lib/community/permissions"-import { avatarInitial } from "@/lib/community/avatar"--/**- * Server members who are NOT yet in this private-category channel — backs the- * "add members" picker. Only creator/admins (canManage) may see it. Scoped by- * subtracting the channel roster from the server member list server-side (a- * stale client cache can't leak the wrong set).- */-export const GET = withAuth(async (_req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)-- const db = getDb(ctx.env.DB)- // Any current member may add, so the add-picker is available to anyone who- // passes the access gate (creator or member; admins have no implicit access).- const access = await requireChannelAccess(db, channelId, ctx.userId)- if (!access.ok) return writeError(access.error, access.status)-- const channel = access.value.channel- const [members, channelMemberIds] = await Promise.all([- queries.communityMember.listMembers(db, channel.serverId),- queries.communityChannel.listChannelMemberUserIds(db, channelId),- ])- const inChannel = new Set(channelMemberIds)- if (channel.creatorId) inChannel.add(channel.creatorId)-- const addable = members- .filter((m) => !inChannel.has(m.userId))- .map((m) => ({- userId: m.userId,- name: m.userName,- discriminator: m.discriminator,- avatar: m.userImage ?? avatarInitial(m.userName ?? ""),- }))-- return writeJSON({ members: addable })-})diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.tsnew file mode 100644index 000000000..06cd96b36--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts@@ -0,0 +1,228 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const mockR2Get = vi.fn()+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockGetAttachmentById = vi.fn()+const mockGetMessage = vi.fn()+const mockGetChannelType = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityAttachment: {+ getAttachmentById: (...a: unknown[]) => mockGetAttachmentById(...a),+ },+ communityMessage: {+ ...actual.queries.communityMessage,+ getMessage: (...a: unknown[]) => mockGetMessage(...a),+ },+ communityChannel: {+ ...actual.queries.communityChannel,+ getChannelType: (...a: unknown[]) => mockGetChannelType(...a),+ },+ },+ }+})++const mockRequireChannelMember = vi.fn()+const mockRequireDMAccess = vi.fn()+vi.mock("@/lib/community/permissions", () => ({+ requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...a),+ requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...a),+}))++// Dual-actor: crk_ bearer → bot arm, else human. The route dispatches by+// actor.kind for the RESPONSE shape; the authz core is identical. A test may+// inject a specific actor via ctx.actor.+vi.mock("@/lib/middleware/community-actor", async () => {+ const actual = await vi.importActual<typeof import("@/lib/middleware/community-actor")>(+ "@/lib/middleware/community-actor",+ )+ return {+ ...actual,+ withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ const authz = req?.headers?.get?.("Authorization") ?? ""+ const actor =+ ctx?.actor ??+ (authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]", isBot: false })+ return handler(req, { env: { COMMUNITY_MEDIA: { get: (...a: unknown[]) => mockR2Get(...a) } }, actor, params })+ },+ }+})++import { GET } from "./route"++function req(headers: Record<string, string> = {}): NextRequest {+ return new NextRequest("http://localhost/api/community/channels/c1/attachments/att_1", {+ method: "GET",+ headers,+ })+}++// params.id = the PATH channel id (routing anchor only, NEVER trusted for+// authz). params.attachmentId = the authoritative id.+const ctx = (attachmentId: string | undefined = "att_1", id = "c1") =>+ ({ params: { id, attachmentId } }) as any++const persistedRow = (over: Record<string, unknown> = {}) => ({+ id: "att_1",+ messageId: "m_1",+ targetId: "c_row", // the row's OWN target — deliberately != path id "c1"+ uploaderId: "someone",+ r2Key: "channel/c_row/uuid/a.png",+ filename: "a.png",+ contentType: "image/png",+ size: 10,+ width: null,+ height: null,+ ...over,+})++const r2Object = (over: Record<string, unknown> = {}) => ({+ body: new ReadableStream(),+ size: 10,+ httpMetadata: {},+ arrayBuffer: async () => new ArrayBuffer(10),+ ...over,+})++describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockRequireChannelMember.mockResolvedValue({ ok: true, value: {} })+ mockRequireDMAccess.mockResolvedValue({ ok: true, value: {} })+ })++ it("404 when attachmentId is missing", async () => {+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx(undefined))+ expect(res.status).toBe(404)+ })++ it("404 when the id doesn't exist (bot)", async () => {+ mockGetAttachmentById.mockResolvedValue(null)+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "attachment not found" })+ })++ // ⚠ CONFUSED-DEPUTY — the top red line. The gate resolves the row's OWN+ // channel (row.targetId → row.messageId → message.channelId), NOT the path+ // `[id]`. A caller who IS a member of the path channel "c1" but NOT of the+ // row's real channel must still 404. We prove it by making the membership+ // gate observe the ROW's channel id, and by returning not-a-member there.+ it("authorizes from the ROW's channel, not the path id — member of path-c1 but not row-channel → 404", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow())+ mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })+ mockGetChannelType.mockResolvedValue("text")+ mockRequireChannelMember.mockResolvedValue({ ok: false, status: 403, error: "not a member" })++ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx("att_1", "c1"))+ expect(res.status).toBe(404)+ // The membership gate was called with the ROW's message channel, not "c1".+ expect(mockRequireChannelMember).toHaveBeenCalledWith({}, "c_real", "bot_1")+ // No path-id was consulted for authz.+ expect(mockRequireChannelMember).not.toHaveBeenCalledWith({}, "c1", expect.anything())+ expect(mockR2Get).not.toHaveBeenCalled()+ })++ it("404 (not 403) when a pending row belongs to another actor — enumeration-safe", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "other" }))+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "attachment not found" })+ expect(mockR2Get).not.toHaveBeenCalled()+ })++ it("bot: pending row owned by the requesting bot round-trips (200 + X-Alook-Filename)", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))+ mockR2Get.mockResolvedValue(r2Object())+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(200)+ expect(res.headers.get("Content-Type")).toBe("image/png")+ expect(res.headers.get("Content-Length")).toBe("10")+ expect(res.headers.get("X-Alook-Filename")).toBe(encodeURIComponent("a.png"))+ })++ it("bot: percent-encodes non-ASCII filenames per RFC 5987", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1", filename: "图表.png" }))+ mockR2Get.mockResolvedValue(r2Object())+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(200)+ const encoded = res.headers.get("X-Alook-Filename")+ expect(encoded).toBeTruthy()+ expect(decodeURIComponent(encoded!)).toBe("图表.png")+ })++ it("human: persisted image on a channel the user is a member of → 200 inline + immutable cache, no X-Alook-Filename", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow())+ mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })+ mockGetChannelType.mockResolvedValue("text")+ mockRequireChannelMember.mockResolvedValue({ ok: true, value: {} })+ mockR2Get.mockResolvedValue(r2Object())+ const res = await GET(req(), ctx()) // no crk_ → human arm+ expect(res.status).toBe(200)+ expect(res.headers.get("Content-Type")).toBe("image/png")+ expect(res.headers.get("Content-Disposition")).toBe("inline")+ expect(res.headers.get("Cache-Control")).toBeTruthy()+ // Human arm never emits the bot download header.+ expect(res.headers.get("X-Alook-Filename")).toBeNull()+ })++ it("human: non-image → attachment; Content-Disposition carries the filename", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow({ contentType: "application/pdf", filename: "doc.pdf" }))+ mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })+ mockGetChannelType.mockResolvedValue("text")+ mockR2Get.mockResolvedValue(r2Object({ httpMetadata: { contentType: "application/pdf" } }))+ const res = await GET(req(), ctx())+ expect(res.status).toBe(200)+ expect(res.headers.get("Content-Disposition")).toBe('attachment; filename="doc.pdf"')+ })++ it("routes a DM-scoped row through requireDMAccess (block gate), not requireChannelMember", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow())+ mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "dm_1" })+ mockGetChannelType.mockResolvedValue("dm")+ mockRequireDMAccess.mockResolvedValue({ ok: true, value: {} })+ mockR2Get.mockResolvedValue(r2Object())+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(200)+ expect(mockRequireDMAccess).toHaveBeenCalledWith({}, "dm_1", "bot_1")+ expect(mockRequireChannelMember).not.toHaveBeenCalled()+ })++ it("502 when the row exists but R2 has no object (infra drift, not enumeration)", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))+ mockR2Get.mockResolvedValue(null)+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(502)+ })++ it("getAttachmentById throws → 500 JSON envelope (no binary body leak)", async () => {+ mockGetAttachmentById.mockRejectedValueOnce(new Error("d1_transient"))+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ })++ it("bot: obj.arrayBuffer() throws mid-read → 500 JSON envelope, NOT a truncated 200", async () => {+ mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))+ mockR2Get.mockResolvedValue(+ r2Object({+ arrayBuffer: async () => {+ throw new Error("stream_error")+ },+ }),+ )+ const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())+ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.tsnew file mode 100644index 000000000..73525dc3d--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts@@ -0,0 +1,153 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, createLogger, CACHE_IMMUTABLE } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, type CommunityActor } from "@/lib/middleware/community-actor"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"++const log = createLogger({ service: "community-attachments-download" })++/**+ * RFC 5987 filename encoding for `X-Alook-Filename`. Percent-encodes+ * everything outside the RFC 5987 attr-char set. The daemon-side client+ * decodes before writing to disk so non-ASCII filenames (`图表.png`) round+ * trip safely.+ */+function encodeRfc5987(value: string): string {+ return encodeURIComponent(value)+ .replace(/['()]/g, escape)+ .replace(/\*/g, "%2A")+}++/**+ * GET /api/community/channels/[id]/attachments/[attachmentId] — the canonical+ * attachment-download door. Dual-actor (route/disc trunk — folds the bot+ * `attachmentDownload` verb + the human `media/[...key]` GET's attachment+ * part):+ * - human/web (`<img src>` / link) → cookie session → bytes + inline/attach+ * `Content-Disposition` + immutable cache (the media route's serve shape).+ * - bot/CLI (crk_ bearer) → raw body + `X-Alook-Filename` (RFC 5987), the+ * shape the daemon `callDownload` buffers and writes to disk.+ *+ * ⚠ CONFUSED-DEPUTY (top red line, Aigneis ② / Blondie): authorization is+ * derived from the ATTACHMENT ROW's OWN channel (attachmentId → row →+ * row.messageId → message.channelId → membership), NEVER from the path `[id]`.+ * The `[id]` segment is a routing anchor only; a member of channel A must not+ * reach an attachment of channel B by putting A's id in the path. The old flat+ * `attachmentDownload` did this correctly — the fold does not regress it.+ *+ * Enumeration-safe: every "you can't have this" path (pending non-owner,+ * not-a-member, genuine miss) returns the SAME 404. A distinct 502 fires only+ * when the DB row exists but R2 has drifted (infra fault, not a user-facing+ * gate). Response FORM forks by actor; the authz core is identical.+ */+export const GET = withCommunityActor(async (req: NextRequest, ctx) => {+ const attachmentId = ctx.params?.attachmentId+ if (!attachmentId) {+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }++ const userId = ctx.actor.userId+ try {+ const db = getDb(ctx.env.DB)++ // Authorize from the ROW's own channel — never trust the path `[id]`.+ const authz = await authorizeAttachment(ctx.actor, db, attachmentId)+ if (!authz.ok) {+ // Enumeration-safe: every deny is an indistinguishable 404.+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }+ const row = authz.row++ const obj = await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)+ if (!obj) {+ // Row exists but R2 has no object — infra fault, distinct from the+ // enumeration-safe 404 above.+ return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })+ }++ const contentType =+ row.contentType || obj.httpMetadata?.contentType || "application/octet-stream"++ if (ctx.actor.kind === "bot") {+ // Bot arm — raw body + X-Alook-Filename. Buffer inside the try/catch so an+ // R2 stream mid-read error surfaces as a structured 500 rather than a+ // truncated 200 the daemon-side helper can't parse. The daemon+ // `callDownload` buffers via arrayBuffer (attachments cap at 25 MB), so+ // no streaming behavior is lost.+ const size = row.size ?? obj.size+ const headers: Record<string, string> = {+ "Content-Type": contentType,+ "X-Alook-Filename": encodeRfc5987(row.filename),+ }+ if (typeof size === "number") headers["Content-Length"] = String(size)+ const buffer = await obj.arrayBuffer()+ return new Response(buffer, { headers })+ }++ // Human arm — inline for images, attachment download otherwise, immutable+ // cache (the media route's serve shape). Stream the body directly.+ const isImage = contentType.startsWith("image/")+ return new Response(obj.body, {+ headers: {+ "Content-Type": contentType,+ "Content-Disposition": isImage+ ? "inline"+ : `attachment; filename="${row.filename}"`,+ "Cache-Control": CACHE_IMMUTABLE,+ },+ })+ } catch (err) {+ log.error("attachment_route_failure", {+ route: "channels/[id]/attachments/[attachmentId]",+ actorKind: ctx.actor.kind,+ userId,+ cause: err instanceof Error ? err.stack ?? err.message : String(err),+ })+ return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })+ }+})++type AuthzOk = {+ ok: true+ row: NonNullable<Awaited<ReturnType<typeof queries.communityAttachment.getAttachmentById>>>+}++/**+ * Confused-deputy-safe attachment authorization. Returns the row ONLY when the+ * caller may read it, deriving scope from the row's own channel — the path+ * `[id]` is never consulted. Both actor arms run the identical gate:+ * - pending row (messageId = NULL) → only the uploading actor (round-trip).+ * - persisted row → resolve the row's message → its channel → membership /+ * DM access.+ * Any deny collapses to `{ ok: false }` so the caller can render a uniform 404.+ */+async function authorizeAttachment(+ actor: CommunityActor,+ db: ReturnType<typeof getDb>,+ attachmentId: string,+): Promise<AuthzOk | { ok: false }> {+ const userId = actor.userId+ const row = await queries.communityAttachment.getAttachmentById(db, attachmentId)+ if (!row) return { ok: false }++ if (row.messageId === null) {+ // Pending row — only the uploading actor may see it (round-trip verify).+ if (row.uploaderId !== userId) return { ok: false }+ return { ok: true, row }+ }++ // Persisted row — resolve target scope FROM THE ROW, then run the standard+ // membership gate. Any non-ok collapses to a generic deny so a prober can't+ // tell "not a member" from "row doesn't exist".+ const message = await queries.communityMessage.getMessage(db, row.messageId)+ if (!message) return { ok: false }+ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ if (channelType === "dm") {+ const gate = await requireDMAccess(db, message.channelId, userId)+ if (!gate.ok) return { ok: false }+ } else {+ const gate = await requireChannelMember(db, message.channelId, userId)+ if (!gate.ok) return { ok: false }+ }+ return { ok: true, row }+}diff --git a/src/web/src/app/api/community/attachmentUpload/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.tssimilarity index 68%rename from src/web/src/app/api/community/attachmentUpload/route.test.tsrename to src/web/src/app/api/community/channels/[id]/attachments/route.test.tsindex 325b12a25..66af38edd 100644--- a/src/web/src/app/api/community/attachmentUpload/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts@@ -10,8 +10,7 @@ vi.mock("@opennextjs/cloudflare", () => ({vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))// Unified actor: a request with no `crk_` bearer falls through to the human// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.+// yields the human-path 401 — the real unified-actor contract.vi.mock("@/lib/auth", () => ({createAuth: vi.fn(() => ({api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },@@ -55,21 +54,26 @@ vi.mock("@alook/shared", async () => {})const mockHandleAttachmentUpload = vi.fn()+const mockRunAttachmentUpload = vi.fn()vi.mock("@/lib/community/upload", () => ({handleAttachmentUpload: (...a: unknown[]) => mockHandleAttachmentUpload(...a),+ runAttachmentUpload: (...a: unknown[]) => mockRunAttachmentUpload(...a),}))import { POST } from "./route"-function req(target: string | null, headers: Record<string, string> = {}): NextRequest {+// The path `[id]` carries the `resolve` placeholder for a bot (it addresses by+// `?target=`); a human puts the real channelId there.+function botReq(target: string | null, headers: Record<string, string> = {}): NextRequest {const q = target !== null ? `?target=${encodeURIComponent(target)}` : ""- return new NextRequest(`http://localhost/api/community/agent/attachmentUpload${q}`, {+ return new NextRequest(`http://localhost/api/community/channels/resolve/attachments${q}`, {method: "POST",headers,})}+const botCtx = { params: { id: "resolve" } } as any-describe("POST /api/community/agent/attachmentUpload", () => {+describe("POST /api/community/channels/[id]/attachments — bot arm (folds attachmentUpload)", () => {beforeEach(() => {vi.clearAllMocks()mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })@@ -91,12 +95,12 @@ describe("POST /api/community/agent/attachmentUpload", () => {})it("401 without Authorization", async () => {- const res = await POST(req("/studio/general"))+ const res = await POST(botReq("/studio#0042/general"), botCtx)expect(res.status).toBe(401)})it("400 when target query param is missing", async () => {- const res = await POST(req(null, { Authorization: "Bearer crk_abc" }))+ const res = await POST(botReq(null, { Authorization: "Bearer crk_abc" }), botCtx)expect(res.status).toBe(400)})@@ -107,7 +111,7 @@ describe("POST /api/community/agent/attachmentUpload", () => {])mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })- const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ const res = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)expect(res.status).toBe(200)const body = await res.json()expect(body).toEqual({@@ -119,7 +123,8 @@ describe("POST /api/community/agent/attachmentUpload", () => {// No leaked internals.expect(body.url).toBeUndefined()expect(body.r2Key).toBeUndefined()- // Uploader tag is threaded to the R2 primitive.+ // Uploader tag threaded to the R2 primitive; the resolved id is used (not+ // the placeholder path id).expect(mockHandleAttachmentUpload).toHaveBeenCalledWith(expect.anything(),expect.anything(),@@ -142,31 +147,15 @@ describe("POST /api/community/agent/attachmentUpload", () => {mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1_transient"))- const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(500)- const body = await res.json()- expect(body).toEqual({ error: "internal error", code: "internal" })- expect(mockR2Delete).toHaveBeenCalledWith("channel/c1/uuid/hi.png")- })-- it("createPendingAttachment throws AND R2 delete also throws → still 500 JSON, no rethrow", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([- { id: "c1", serverId: "srv_1", parentChannelId: null },- ])- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })- mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1_transient"))- mockR2Delete.mockRejectedValueOnce(new Error("r2_boom"))-- const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ const res = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)expect(res.status).toBe(500)expect(await res.json()).toEqual({ error: "internal error", code: "internal" })+ expect(mockR2Delete).toHaveBeenCalledWith("channel/c1/uuid/hi.png")})it("pre-R2 throw (resolveTargetForMember errors) → 500 JSON, R2 delete NOT called", async () => {mockResolveServerByNameForMember.mockRejectedValueOnce(new Error("d1_outage"))-- const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ const res = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)expect(res.status).toBe(500)expect(await res.json()).toEqual({ error: "internal error", code: "internal" })expect(mockR2Delete).not.toHaveBeenCalled()@@ -183,8 +172,41 @@ describe("POST /api/community/agent/attachmentUpload", () => {response: new Response(JSON.stringify({ error: "file too large" }), { status: 413 }),})- const res = await POST(req("/studio/general", { Authorization: "Bearer crk_abc" }))+ const res = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)expect(res.status).toBe(413)expect(mockCreatePendingAttachment).not.toHaveBeenCalled()})})++describe("POST /api/community/channels/[id]/attachments — human arm (re-homes channels/[id]/upload)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it("delegates to runAttachmentUpload with the id-in-path ctx, returns its response unchanged", async () => {+ const helperResponse = new Response(JSON.stringify({ url: "/api/community/media/x", filename: "a.png" }), { status: 200 })+ mockRunAttachmentUpload.mockResolvedValueOnce(helperResponse)++ // Human session resolves — withAuth adopts { userId }.+ const { createAuth } = await import("@/lib/auth")+ ;(createAuth as unknown as ReturnType<typeof vi.fn>).mockReturnValueOnce({+ api: {+ getSession: vi.fn(async () => ({+ headers: new Headers(),+ response: { user: { id: "u1", email: "[email protected]", isBot: false, deletedAt: null } },+ })),+ },+ })++ const req = new NextRequest("http://localhost/api/community/channels/c1/attachments", { method: "POST" })+ const res = await POST(req, { params: { id: "c1" } } as any)+ expect(res).toBe(helperResponse)+ expect(mockRunAttachmentUpload).toHaveBeenCalledOnce()+ const args = mockRunAttachmentUpload.mock.calls[0]+ expect(args[0]).toBe(req)+ // The human arm forwards the id-in-path so the shared trunk resolves surface.+ expect(args[1]).toMatchObject({ userId: "u1", params: { id: "c1" } })+ // Bot-only pending-row insert never runs on the human arm.+ expect(mockCreatePendingAttachment).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/attachmentUpload/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.tssimilarity index 51%rename from src/web/src/app/api/community/attachmentUpload/route.tsrename to src/web/src/app/api/community/channels/[id]/attachments/route.tsindex 03cfba1be..5c6533fec 100644--- a/src/web/src/app/api/community/attachmentUpload/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.ts@@ -1,29 +1,65 @@import { NextResponse, type NextRequest } from "next/server"import { queries, createLogger } from "@alook/shared"import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { withCommunityActor, requireBot, type CommunityActor } from "@/lib/middleware/community-actor"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"-import { handleAttachmentUpload } from "@/lib/community/upload"+import { handleAttachmentUpload, runAttachmentUpload } from "@/lib/community/upload"-const log = createLogger({ service: "community-agent-attachment-upload" })+const log = createLogger({ service: "community-attachments-upload" })+// A bot addresses by ref-in-query (`?target=`, the folded `attachmentUpload`+// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`),+// which the bot arm ignores — it resolves the ref itself. A human/web caller+// puts the real channelId in the path. Mirrors the channels/[id]/members+// dual-actor door./**- * POST /api/community/attachmentUpload?target=<ref> — moved from- * /api/community/agent/attachmentUpload (plan §4 MOVE-FLAT, §9 phase 3).+ * POST /api/community/channels/[id]/attachments — the canonical+ * attachment-upload door. Dual-actor (route/disc trunk — folds the bot+ * `attachmentUpload` verb + re-homes the human `channels/[id]/upload` route):+ * - human/web (id-in-path) → `runAttachmentUpload`: multipart file →+ * surface-derived kind → R2 put; returns the pre-refactor carrier shape+ * `{ url, filename, contentType, size }` (the `/media/<key>` URL the+ * composer echoes back on send). The composer switches to reserve-by-id in+ * step (b); until then the human upload→send round-trip stays key-carried.+ * - bot/CLI (ref-in-query) → resolve `?target=<ref>` member-scoped, gate+ * write access identical to `send`, upload, then reserve a PENDING row+ * (messageId = NULL) and return `{ id, filename, contentType, size }` —+ * the bot holds the id and passes it to `send` later.*- * Body: multipart/form-data with a single `file` field.- * Response: `{ id, filename, contentType, size }` — no url, no r2 key (the- * bot-shaped result: returns a stable pending id, unlike the human upload route- * which returns a url). Ref-addressed via `?target=<ref>` (kept, not id —- * Gener #68), so it stays flat and can't fold onto an `[id]` route (Fork B).- * Bot-only → human actor rejected 403 (`requireBot`, Gener #116). `target` is- * resolved through `resolveTargetForMember` so the bot's membership +- * write-permission gate is identical to `send`. Handler body unchanged from the- * /agent original except the wrapper + identity source (ctx.botUserId →- * botUserId).+ * Response FORM forks by the credential actor (never a field). The bot arm is+ * byte-identical to the old flat `attachmentUpload` route; the human arm+ * delegates to the same shared trunk the old `channels/[id]/upload` route did.*/export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ if (ctx.actor.kind === "bot") {+ return handleBotAttachmentUpload(req, ctx)+ }+ // Human arm — id-in-path, shared upload trunk (surface dispatch ++ // per-surface guard + DM block gate live inside runAttachmentUpload).+ return runAttachmentUpload(req, {+ env: ctx.env,+ userId: ctx.actor.userId,+ email: ctx.actor.email,+ workspaceId: ctx.actor.workspaceId,+ params: ctx.params,+ })+})++/**+ * Bot upload arm. Body unchanged from the old flat `attachmentUpload` route+ * except that the ref arrives via `?target=` while the path carries the+ * `resolve` placeholder (the door is now id-in-path for humans). Best-effort R2+ * cleanup on a D1-throw so no orphan blob is left when the pending-row insert+ * fails.+ */+async function handleBotAttachmentUpload(+ req: NextRequest,+ ctx: { env: Env; actor: CommunityActor },+): Promise<NextResponse | Response> {+ // requireBot backstop — the dispatch already routed only bots here, but the+ // guard keeps the bot-only authz on the arm itself (not on "no one else+ // calls it"), matching the dual-actor discipline the other folded verbs use.const gate0 = requireBot(ctx.actor)if (!gate0.ok) return gate0.responseconst botUserId = gate0.bot.userId@@ -90,7 +126,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {r2KeyCleaned = true} catch (cleanupErr) {log.error("attachment_route_r2_cleanup_failed", {- route: "attachmentUpload",+ route: "channels/[id]/attachments",botUserId,r2Key: r2KeyToCleanUp,cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),@@ -98,11 +134,11 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {}}log.error("attachment_route_failure", {- route: "attachmentUpload",+ route: "channels/[id]/attachments",botUserId,r2KeyCleaned,cause: err instanceof Error ? err.stack ?? err.message : String(err),})return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })}-})+}diff --git a/src/web/src/app/api/community/channels/[id]/bootstrap/route.test.ts b/src/web/src/app/api/community/channels/[id]/bootstrap/route.test.tsdeleted file mode 100644index 99f118508..000000000--- a/src/web/src/app/api/community/channels/[id]/bootstrap/route.test.ts+++ /dev/null@@ -1,102 +0,0 @@-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 mockGetReadState = vi.fn()-const mockListMessages = vi.fn()-const mockRequireChannelMember = vi.fn()-const mockEnrichMessages = 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,- withD1Retry: (fn: () => unknown) => fn(),- queries: {- communityChannel: {- getChannel: (...a: unknown[]) => mockGetChannel(...a),- },- communityReadState: {- getReadState: (...a: unknown[]) => mockGetReadState(...a),- },- communityMessage: {- listMessages: (...a: unknown[]) => mockListMessages(...a),- },- },- }-})--vi.mock("@/lib/community/permissions", () => ({- requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...a),-}))--vi.mock("@/lib/community/enrich-messages", () => ({- enrichMessages: (...a: unknown[]) => mockEnrichMessages(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--function call(channelId: string | undefined = "c1") {- const req = new NextRequest("http://localhost/api/community/channels/c1/bootstrap", { method: "GET" })- return GET(req, { params: { id: channelId } } as any)-}--describe("GET /api/community/channels/[id]/bootstrap — access gate (BE1)", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetReadState.mockResolvedValue(null)- mockListMessages.mockResolvedValue([])- mockEnrichMessages.mockResolvedValue({ messages: [], latestSeq: 0 })- })-- it("happy path: a member with access resolves in ONE query and never probes getChannel", async () => {- mockRequireChannelMember.mockResolvedValue({ ok: true, value: { id: "c1", serverId: "s1" } })-- const res = await call()-- expect(res.status).toBe(200)- // The round-trip BE1 saves: the existence probe must NOT run on the hot path.- expect(mockGetChannel).not.toHaveBeenCalled()- })-- it("403 when the channel exists but the caller is not a member", async () => {- mockRequireChannelMember.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })-- const res = await call()-- expect(res.status).toBe(403)- expect(await res.json()).toEqual({ error: "forbidden" })- })-- it("404 when the channel does not exist (ordering preserved over the 403)", async () => {- mockRequireChannelMember.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })- mockGetChannel.mockResolvedValue(null)-- const res = await call()-- expect(res.status).toBe(404)- expect(await res.json()).toEqual({ error: "channel not found" })- })-})diff --git a/src/web/src/app/api/community/channels/[id]/bootstrap/route.ts b/src/web/src/app/api/community/channels/[id]/bootstrap/route.tsdeleted file mode 100644index 48227b66c..000000000--- a/src/web/src/app/api/community/channels/[id]/bootstrap/route.ts+++ /dev/null@@ -1,119 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries, withD1Retry } from "@alook/shared"-import {- parsePageSize,- buildPaginatedResponse,- buildAnchorResponse,-} from "@/lib/community/messages"-import { enrichMessages } from "@/lib/community/enrich-messages"-import { requireChannelMember } from "@/lib/community/permissions"--/**- * GET /api/community/channels/:id/bootstrap- *- * The de-serialized channel-open payload. See- * plans/community-switch-perf-optimization.md (WS2). Instead of the client- * firing `read-state`, waiting for it, then firing `messages?anchor=` (two- * serial network round-trips gated client-side), this route does BOTH server- * side behind ONE `requireChannelMember` preflight and returns them together:- *- * { readState, messages, hasMoreOlder, hasMoreNewer, olderCursor,- * newerCursor, latestSeq }- *- * The `messages` payload is byte-identical to what the `messages` route's- * anchor/legacy branch returns (same `enrichMessages`, same anchor-mode- * envelope with `hasMoreOlder`/`hasMoreNewer`), so the client can seed its- * existing message cache and let `useMessages` paginate + WS-patch unchanged.- *- * Only the INITIAL window lives here; pagination stays on the `messages` route.- */-export const GET = withAuth(async (_req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)-- const db = getDb(ctx.env.DB)-- // Access gate first: the happy path (a member with access — the hot- // channel-open case) resolves the channel in one query and skips the- // existence probe entirely. Only on failure do we run getChannel to split- // 404 (unknown channel) from 403 (known but not a member), preserving the- // read-state route's 404-vs-403 ordering without paying for it every open.- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) {- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return writeError("channel not found", 404)- return writeError(auth.error, auth.status)- }-- const pageSize = parsePageSize(null)-- const readRow = await withD1Retry(- () => queries.communityReadState.getReadState(db, { userId: ctx.userId, channelId }),- { route: "community/channels/bootstrap:read-state" },- )- const readState = {- lastReadMessageId: readRow?.lastReadMessageId ?? null,- lastReadAt: readRow?.lastReadAt ?? null,- lastReadSeq: readRow?.lastReadSeq ?? 0,- }-- // Anchor on the read pointer when present AND still resolvable in scope.- // A stored pointer at a since-deleted / purged message must fall back to the- // newest page — NOT 404 (that would break channel-open entirely). This is the- // one behavior the standalone messages route can't safely centralize.- const anchorId = readState.lastReadMessageId- const anchor = anchorId- ? await queries.communityMessage.getMessageInScope(db, anchorId, { channelId })- : null-- if (anchor) {- const around = await queries.communityMessage.listMessagesAround(db, {- channelId,- anchor: { createdAt: anchor.createdAt, id: anchor.id },- limit: pageSize,- })- const { items, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor } = buildAnchorResponse(- around.older,- around.newer,- { hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },- )- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items)- return writeJSON({- readState,- anchorMode: "anchor" as const,- anchorMessageId: anchorId,- messages,- hasMoreOlder,- hasMoreNewer,- olderCursor,- newerCursor,- latestSeq,- })- }-- // Newest-page fallback: no read pointer, or the pointer's message is gone.- // Mirrors the messages route's legacy branch (DESC + one-extra-row probe,- // reversed to ASC) so the seeded page is a trusted newest-tail window.- const rows = await queries.communityMessage.listMessages(db, {- channelId,- limit: pageSize + 1,- })- const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items.slice().reverse())- return writeJSON({- readState,- anchorMode: "newest" as const,- anchorMessageId: null,- messages,- // Normalize to the anchor-mode envelope so the client seed is uniform:- // a newest page has no newer side, and `hasMore` is the older side.- hasMoreOlder: hasMore,- hasMoreNewer: false,- olderCursor: nextCursor,- newerCursor: null,- latestSeq,- })-})diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.tsindex 15d1986ad..00bb44214 100644--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts@@ -2,13 +2,13 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries, WS_EVENTS, isThread, isForumPost } from "@alook/shared"+import { queries, WS_EVENTS, isThread } from "@alook/shared"import { broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"import { requireChannelAccess } from "@/lib/community/permissions"/**- * Remove a member from a private access unit (channel or forum post).+ * Remove a member from a private access unit (channel).* - Self-leave: any member may remove THEMSELVES (drop their own access).* - Remove others: CREATOR only (add is open to members, but evicting someone* else is the creator's call; admins have no content privilege here).@@ -26,8 +26,8 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channel- if (isThread(channel.type) || isForumPost(channel.type) || channel.parentMessageId) {- return writeError("threads and forum posts inherit their parent's members — remove participants instead", 400)+ if (isThread(channel.type) || channel.parentMessageId) {+ return writeError("threads inherit their parent's members — remove participants instead", 400)}if (channel.creatorId === targetUserId) {// Covers both "creator can't be removed" and "creator can't leave".@@ -40,8 +40,8 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const removed = await queries.communityChannel.deleteChannelMember(db, channelId, targetUserId)if (!removed) return writeError("member not found", 404)- // A removed member loses access to every child unit (a forum's posts, a- // channel's threads); drop their leftover participant (notify) rows across+ // A removed member loses access to every child unit (a channel's/forum's+ // threads); drop their leftover participant (notify) rows across// those children so fan-out stops pushing new post/thread messages they can no// longer read. A later mention/speak (which requires access) re-adds them.await queries.communityThread.removeParticipantFromChildChannels(db, channelId, targetUserId)diff --git a/src/web/src/app/api/community/channels/[id]/members/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/route.test.tsindex 18f9baae3..5d98cd32d 100644--- a/src/web/src/app/api/community/channels/[id]/members/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/members/route.test.ts@@ -17,6 +17,26 @@ const mockBroadcastToUserSafe = vi.fn()const mockLogAudit = vi.fn()const mockAddThreadParticipants = vi.fn()const mockListThreadParticipants = vi.fn()+const mockListThreadParticipantUserIds = vi.fn()+const mockResolveTargetForMember = vi.fn()+const mockGetServer = vi.fn()+const mockFetchOnlineUserIds = vi.fn()++vi.mock("@/lib/community/resolve-ref", () => ({+ resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),+}))++// Presence is a bulk ws-do fan-out — mock the helper so the route test stays+// unit-scoped; the set it returns drives each member's `online` boolean.+vi.mock("@/lib/community/member-presence", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/member-presence")>(+ "@/lib/community/member-presence",+ )+ return {+ ...actual,+ fetchOnlineUserIds: (...a: unknown[]) => mockFetchOnlineUserIds(...a),+ }+})vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -41,7 +61,9 @@ vi.mock("@alook/shared", async () => {communityThread: {addThreadParticipants: (...a: unknown[]) => mockAddThreadParticipants(...a),listThreadParticipants: (...a: unknown[]) => mockListThreadParticipants(...a),+ listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),},+ communityServer: { getServer: (...a: unknown[]) => mockGetServer(...a) },user: { getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a) },},}@@ -55,11 +77,22 @@ vi.mock("@/lib/community/audit", async () => {return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }})-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+// Dual-actor: crk_ bearer → bot (folded channelMember), else human.+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),+ const authz = req?.headers?.get?.("Authorization") ?? ""+ const actor = authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]" }+ return handler(req, { env: { DB: {} }, actor, params })+ },+ rejectBot: (actor: { kind: string }) => {+ const { NextResponse } = require("next/server")+ return actor.kind === "bot"+ ? NextResponse.json({ error: "forbidden: not available to bots" }, { status: 403 })+ : null+ },}))vi.mock("@/lib/middleware/helpers", () => {@@ -125,6 +158,25 @@ describe("GET /channels/[id]/members", () => {expect(admin.role).toBe("admin")})+ it("retries a BUSY scope resolution and preserves the resolved member result", async () => {+ vi.spyOn(Math, "random").mockReturnValue(0)+ mockResolveScopeMembers+ .mockRejectedValueOnce(new Error("D1_ERROR: database is locked"))+ .mockResolvedValueOnce([{ userId: "u1", role: "member", source: "explicit" }])+ const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)+ expect(res.status).toBe(200)+ expect((await res.json()).members.map((member: { userId: string }) => member.userId)).toEqual(["u1"])+ expect(mockResolveScopeMembers).toHaveBeenCalledTimes(2)+ expect(mockResolveChannelAccessContext).toHaveBeenCalledTimes(1)+ })++ it("rethrows a non-BUSY scope-resolution failure without retrying", async () => {+ const error = new Error("programmer bug")+ mockResolveScopeMembers.mockRejectedValueOnce(error)+ await expect(GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)).rejects.toBe(error)+ expect(mockResolveScopeMembers).toHaveBeenCalledTimes(1)+ })+it("drops audience members with no hydrated (non-deleted) server row", async () => {mockGetMembersByUserIds.mockResolvedValue([{ id: "m1", serverId: "s1", userId: "u1", role: "member", nickname: null, userName: "Ann", userImage: null, discriminator: "0001", statusEmoji: null, statusText: null, userIsBot: false, userOwnerUserId: null },@@ -152,11 +204,11 @@ describe("GET /channels/[id]/members", () => {expect(mockGetMembersByUserIds).toHaveBeenCalledWith(expect.anything(), "s1", ["u1"])})- it("forum post reads PARTICIPANTS and badges the post's OWN creator", async () => {+ it("post (a thread rooted under a forum) reads PARTICIPANTS and badges the post's OWN creator", async () => {// Post p1 authored by u2; the forum (anchor) is owned by u1. A public post's// panel is its participant set — NOT the whole server / access audience.mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "p1", serverId: "s1", type: "forum_post", parentChannelId: "f1", parentMessageId: null, creatorId: "u2" },+ channel: { id: "p1", serverId: "s1", type: "thread", parentChannelId: "f1", parentMessageId: "m1", creatorId: "u2" },anchor: { id: "f1", serverId: "s1", parentChannelId: null, creatorId: "u1" },role: "member", isPrivate: false, isChannelMember: false, isCreator: false,})@@ -186,6 +238,7 @@ describe("POST /channels/[id]/members", () => {mockResolveChannelAccessContext.mockResolvedValue(managerCtx())mockGetMember.mockResolvedValue({ id: "m2", userId: "u2", role: "member" })mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"])+ mockFetchOnlineUserIds.mockResolvedValue(new Set<string>())})it("adds an existing server member", async () => {@@ -253,7 +306,7 @@ describe("POST /channels/[id]/members", () => {it("rejects adding to a forum POST (400): posts take participants, not members", async () => {mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "p1", serverId: "s1", type: "forum_post", parentChannelId: "f1", parentMessageId: null, creatorId: "u1" },+ channel: { id: "p1", serverId: "s1", type: "thread", parentChannelId: "f1", parentMessageId: "m1", creatorId: "u1" },anchor: { id: "f1", serverId: "s1", parentChannelId: null, creatorId: "u1" },role: "member", isPrivate: true, isChannelMember: true, isCreator: true,})@@ -263,4 +316,112 @@ describe("POST /channels/[id]/members", () => {// the participants route instead.expect(mockCreateChannelMember).not.toHaveBeenCalled()})++ // ── bot arm (folded `channelMember` verb): ref-in-query → member-scoped 404,+ // lean ChannelMemberResult. ──++ function botGetReq(ref?: string) {+ const q = ref !== undefined ? `?ref=${encodeURIComponent(ref)}` : ""+ return new NextRequest(`http://localhost/api/community/channels/resolve/members${q}`, {+ method: "GET",+ headers: { Authorization: "Bearer crk_abc" },+ })+ }+ const ctxResolve = { params: { id: "resolve" } } as any++ it("bot: private channel → { visibility: private, members, hasMore:false } (lean handle+role+online+status)", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })+ mockResolveChannelAccessContext.mockResolvedValue(managerCtx())+ mockResolveScopeMembers.mockResolvedValue([{ userId: "u1", source: "explicit" }])+ mockGetMembersByUserIds.mockResolvedValue([+ { userId: "u1", userName: "alice", discriminator: "0001", role: "member", statusEmoji: "🎧", statusText: "vibing" },+ ])+ mockFetchOnlineUserIds.mockResolvedValue(new Set(["u1"]))+ const res = await GET(botGetReq("/s/general"), ctxResolve)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({+ visibility: "private",+ hasMore: false,+ members: [{ handle: "alice#0001", role: "member", online: true, status: { emoji: "🎧", text: "vibing" } }],+ })+ expect(mockResolveTargetForMember).toHaveBeenCalledWith({}, "bot_1", "/s/general", {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ // presence batched over the resolved (bounded) roster — never per-member.+ expect(mockFetchOnlineUserIds).toHaveBeenCalledWith(expect.anything(), ["u1"], "s1")+ })++ it("bot: thread ref → always private on the wire; roster is the thread-participant set", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "t1" })+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "t1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", creatorId: "u1" },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ role: "member", isPrivate: false, isChannelMember: false, isCreator: false,+ })+ mockListThreadParticipantUserIds.mockResolvedValue(["u1", "u2"])+ mockGetMembersByUserIds.mockResolvedValue([+ { userId: "u1", userName: "alice", discriminator: "0001", role: "owner", statusEmoji: null, statusText: null },+ { userId: "u2", userName: "bob", discriminator: "0002", role: "member", statusEmoji: "🌀", statusText: "running" },+ ])+ mockFetchOnlineUserIds.mockResolvedValue(new Set(["u2"]))+ const res = await GET(botGetReq("/s/general/#12"), ctxResolve)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.visibility).toBe("private")+ expect(body.hasMore).toBe(false)+ expect(body.members).toEqual([+ { handle: "alice#0001", role: "owner", online: false, status: { emoji: null, text: "" } },+ { handle: "bob#0002", role: "member", online: true, status: { emoji: "🌀", text: "running" } },+ ])+ expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith({}, "t1")+ })++ it("bot: public channel → { visibility: public, hint } (no enumeration)", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "u9" },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u9" },+ role: "member", isPrivate: false, isChannelMember: false, isCreator: false,+ })+ mockGetServer.mockResolvedValue({ id: "s1", name: "demo" })+ const res = await GET(botGetReq("/demo/general"), ctxResolve)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.visibility).toBe("public")+ expect(body.hint).toContain("alook server member --server demo")+ expect(mockResolveScopeMembers).not.toHaveBeenCalled()+ })++ it("①-C: bot ref to an UNREACHABLE channel → 404, never enumerates", async () => {+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "channel not found: general" })+ const res = await GET(botGetReq("/s/general"), ctxResolve)+ expect(res.status).toBe(404)+ expect(mockResolveChannelAccessContext).not.toHaveBeenCalled()+ expect(mockResolveScopeMembers).not.toHaveBeenCalled()+ })++ it("bot: DM ref → 400 (channel-scoped, rejected up front before resolve)", async () => {+ const res = await GET(botGetReq("/.dm/alice#0001"), ctxResolve)+ expect(res.status).toBe(400)+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()+ })++ it("bot: missing ref → 400", async () => {+ const res = await GET(botGetReq(), ctxResolve)+ expect(res.status).toBe(400)+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()+ })++ it("bot POST (add-member) → 403 (no bot verb, capability boundary not 404)", async () => {+ const botPost = new NextRequest("http://localhost/api/community/channels/resolve/members", {+ method: "POST",+ headers: { Authorization: "Bearer crk_abc", "content-type": "application/json" },+ body: JSON.stringify({ userId: "u2" }),+ })+ const res = await POST(botPost, ctxResolve)+ expect(res.status).toBe(403)+ expect(mockCreateChannelMember).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.tsindex 7f7c6a02f..a73446fc0 100644--- a/src/web/src/app/api/community/channels/[id]/members/route.ts+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts@@ -1,38 +1,67 @@import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"+import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries, WS_EVENTS, isForum, isForumPost, isThread } from "@alook/shared"+import {+ queries,+ WS_EVENTS,+ isForum,+ isThread,+ DM_SERVER,+ formatHandle,+ parseRef,+ withD1Retry,+} from "@alook/shared"+import type { CommunityCliServerMember as ServerMember } from "@alook/shared"import { broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"import { requireChannelAccess } from "@/lib/community/permissions"+import { resolveTargetForMember } from "@/lib/community/resolve-ref"import { mapMemberForApi } from "@/lib/community/member-payload"+import { fetchOnlineUserIds, toMemberStatus } from "@/lib/community/member-presence"++// A bot addresses by ref-in-query (`?ref=`, the folded `channelMember` verb);+// the path `[id]` is then the `resolve` placeholder (a ref carries `/`). A+// human/web caller puts the real channelId in the path.+const REF_PLACEHOLDER_ID = "resolve"/**- * List the full resolved audience of a channel — the canonical "who is in this- * channel" endpoint. For a private-category channel that's admins ∪ creator ∪- * explicit members; for a public/uncategorized channel it's every server- * member. Each row carries `role`, `source` ("explicit" | "inherited" |- * "admin"), and `isCreator` so the drawer can group and the manage-members- * dialog can decide which rows are removable. Any caller with access may read.+ * GET /api/community/channels/[id]/members — the canonical "who is in this+ * channel" door. Dual-actor (route/disc trunk — folds the `channelMember` verb):+ * - human/web (id-in-path) → the FULL resolved audience via mapMemberForApi:+ * each row carries role / source / isCreator for the drawer + manage dialog.+ * - bot/CLI (ref-in-query) → the lean `ChannelMemberResult` the folded+ * `channelMember` verb returns: `{ visibility, members? , hint? }` — a public+ * channel yields a hint (use `server member`), a private one / thread yields+ * the roster as `{ handle, role }`. DM refs are channel-scoped → 400.+ * Response FORM forks by the credential actor (Aigneis ②, never a field); the+ * ①-C existence mask is uniform (bot ref → member-scoped resolve → 404 before+ * any enumeration; human id → requireChannelAccess 403/404). Any caller with+ * access may read.*/-export const GET = withAuth(async (_req: NextRequest, ctx) => {+export const GET = withCommunityActor(async (req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)++ if (ctx.actor.kind === "bot") {+ return handleBotChannelMember(db, ctx.env, ctx.actor.userId, req)+ }+const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)+ if (!channelId || channelId === REF_PLACEHOLDER_ID) return writeError("missing channel id", 400)- const db = getDb(ctx.env.DB)- const access = await requireChannelAccess(db, channelId, ctx.userId)+ const access = await requireChannelAccess(db, channelId, ctx.actor.userId)if (!access.ok) return writeError(access.error, access.status)+ const userId = ctx.actor.userIdconst { anchor, channel } = access.value- // Thread / forum-post: the NOTIFY dimension. The panel == the participant set- // (not the access audience), so a public forum post lists only its- // participants, never the whole server. The row's `isCreator` locks the- // UNIT's own author (`channel.creatorId`), NOT the access anchor. NOTE: the- // live /c UI reads `/participants` for these units; this branch is API/agent- // parity so a direct GET of a post's `/members` agrees.- if (isThread(channel.type) || isForumPost(channel.type)) {+ // Thread: the NOTIFY dimension. The panel == the participant set (not the+ // access audience), so a public thread lists only its participants, never+ // the whole server. The row's `isCreator` locks the UNIT's own author+ // (`channel.creatorId`), NOT the access anchor. NOTE: the live /c UI reads+ // `/participants` for these units; this branch is API/agent parity so a+ // direct GET of a thread's `/members` agrees.+ if (isThread(channel.type)) {const participants = await queries.communityThread.listThreadParticipants(db, channelId)const userIds = participants.map((p) => p.userId)const rows = await queries.communityMember.getMembersByUserIds(db, channel.serverId, userIds)@@ -41,7 +70,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {.map((p) => {const row = rowByUser.get(p.userId)if (!row) return null- return mapMemberForApi(row, ctx.userId, {+ return mapMemberForApi(row, userId, {isCreator: p.userId === channel.creatorId,source: p.source,})@@ -53,10 +82,13 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {// Channel / forum: the ACCESS dimension. Resolve the audience (public → all// server members; private → own roster ∪ creator). The anchor IS the roster// for these top-level units, so the roster creator is `anchor.creatorId`.- const scopeMembers = await queries.communityMembersResolver.resolveScopeMembers(db, {- scope: isForum(channel.type) ? "forum" : "channel",- scopeId: channelId,- })+ const scopeMembers = await withD1Retry(+ () => queries.communityMembersResolver.resolveScopeMembers(db, {+ scope: isForum(channel.type) ? "forum" : "channel",+ scopeId: channelId,+ }),+ { route: "community/channel-members:resolve-scope" },+ )const rows = await queries.communityMember.getMembersByUserIds(db,anchor.serverId,@@ -70,7 +102,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {.map((sm) => {const row = rowByUser.get(sm.userId)if (!row) return null- return mapMemberForApi(row, ctx.userId, {+ return mapMemberForApi(row, userId, {isCreator: sm.userId === anchor.creatorId,source: sm.source,})@@ -85,26 +117,32 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {* (both own their roster; a forum resolves access like a channel). ANY current* member (or the creator) may add — passing `requireChannelAccess` for a private* unit already means the caller is the creator or an added member (admins have- * no implicit access). The target must be an existing server member. Threads AND- * forum posts are rejected — they're the NOTIFY dimension, inherit the parent's- * roster, and take PARTICIPANTS (via the participants route), not access members.+ * no implicit access). The target must be an existing server member. Threads+ * are rejected — they're the NOTIFY dimension, inherit the parent's roster,+ * and take PARTICIPANTS (via the participants route), not access members.*/-export const POST = withAuth(async (req: NextRequest, ctx) => {+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ // Human-only management op (add a member to a private access unit). There is+ // NO bot add-member verb, and this is a capability boundary (not an+ // existence-mask concern), so a bot is a plain 403, not an opaque 404.+ const rejected = rejectBot(ctx.actor)+ if (rejected) return rejected+const channelId = ctx.params?.idif (!channelId) return writeError("missing channel id", 400)+ const userId = ctx.actor.userIdconst db = getDb(ctx.env.DB)- const access = await requireChannelAccess(db, channelId, ctx.userId)+ const access = await requireChannelAccess(db, channelId, userId)if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channel- // Threads AND forum posts are the NOTIFY dimension — they inherit their parent- // channel/forum's access roster and store their own set in the participant- // table. You add PARTICIPANTS to them (via the participants route), not access- // members. A thread has a `parentMessageId`; a forum post has a- // `parentChannelId` but no `parentMessageId`.- if (isThread(channel.type) || isForumPost(channel.type) || channel.parentMessageId) {- return writeError("threads and forum posts inherit their parent's members — add participants instead", 400)+ // Threads are the NOTIFY dimension — they inherit their parent channel/+ // forum's access roster and store their own set in the participant table.+ // You add PARTICIPANTS to them (via the participants route), not access+ // members. A thread carries a `parentMessageId`.+ if (isThread(channel.type) || channel.parentMessageId) {+ return writeError("threads inherit their parent's members — add participants instead", 400)}// `isPrivate` from requireChannelAccess reflects the category. A public// channel/forum has no explicit roster (everyone can access it).@@ -129,7 +167,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {await queries.communityChannel.createChannelMember(db, {channelId,userId: targetUserId,- addedBy: ctx.userId,+ addedBy: userId,})const event = {@@ -143,7 +181,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {logAudit(db, {serverId: channel.serverId,- actorId: ctx.userId,+ actorId: userId,action: "channel_member_add",targetType: "channel",targetId: channelId,@@ -152,3 +190,101 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ ok: true }, 201)})++/**+ * Bot arm — the folded `channelMember` verb (`alook channel member --channel+ * <ref>`). ref-in-query → member-scoped resolve (404-before-enumeration, ①-C) →+ * the lean `ChannelMemberResult`. Behavior byte-identical to the old flat+ * `channelMember` route: DM refs are channel-scoped → 400; a thread returns its+ * participant roster (always private on the wire); a public top-level channel/+ * forum returns a `{ visibility: "public", hint }` (no enumeration — point the+ * agent at `server member`); a private one returns `{ visibility: "private",+ * members }` from the same audience the fan-out uses. Members carry `online` ++ * `status` (bulk presence read, never per-member); `hasMore: false` — a+ * channel/thread roster is membership-bounded and returned whole, wire shape+ * kept uniform with `server member`'s pagination.+ */+async function handleBotChannelMember(+ db: ReturnType<typeof getDb>,+ env: Env,+ botUserId: string,+ req: NextRequest,+) {+ const ref = req.nextUrl.searchParams.get("ref")+ if (!ref) return writeError("channel ref required", 400)++ // Reject DM refs up front: an un-opened DM would otherwise trip+ // resolveTargetForMember's 404 "dm not found" before this channel-scoped 400.+ try {+ const p = parseRef(ref)+ if (p.server === DM_SERVER) {+ return writeError("channel member is channel-scoped — DM refs are not supported", 400)+ }+ } catch {+ // Fall through — resolveTargetForMember returns the canonical 400.+ }++ // Member-scoped resolve (unreachable → 404 before enumeration, ①-C). No+ // create-if-missing — a roster read is pure addressing.+ const resolved = await resolveTargetForMember(db, botUserId, ref, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return writeError(resolved.message, resolved.error)+ if (resolved.kind === "dm") {+ return writeError("channel member is channel-scoped — DM refs are not supported", 400)+ }++ const channelId = resolved.channelId+ const access = await requireChannelAccess(db, channelId, botUserId)+ if (!access.ok) return writeError(access.error, access.status)++ const { channel, isPrivate } = access.value++ // Thread: the NOTIFY dimension — roster is the participant set, always private+ // on the wire regardless of the parent's public/private state.+ if (isThread(channel.type)) {+ const userIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ const members = await hydrateBotMembers(db, env, channel.serverId, userIds)+ return writeJSON({ visibility: "private", members, hasMore: false })+ }++ if (!isPrivate) {+ const server = await queries.communityServer.getServer(db, channel.serverId)+ const serverName = server?.name ?? channel.serverId+ const hint = `This channel is public. Use \`alook server member --server ${serverName}\` to list who can see it.`+ return writeJSON({ visibility: "public", hint })+ }++ const scoped = await withD1Retry(+ () => queries.communityMembersResolver.resolveScopeMembers(db, { scope: "channel", scopeId: channelId }),+ { route: "community/channel-members:resolve-scope" },+ )+ const members = await hydrateBotMembers(db, env, channel.serverId, scoped.map((s) => s.userId))+ return writeJSON({ visibility: "private", members, hasMore: false })+}++/**+ * Hydrate a user id list into the lean `ServerMember[]` the bot contract uses+ * (handle + role + online + status) — mirrors the flat channelMember route's+ * `hydrateMembers`. Soft-deleted / missing-member-row users drop out via the+ * inner join. Presence is one bulk read over the resolved (bounded) roster —+ * never per-member.+ */+async function hydrateBotMembers(+ db: ReturnType<typeof getDb>,+ env: Env,+ serverId: string,+ userIds: string[],+): Promise<ServerMember[]> {+ if (userIds.length === 0) return []+ const rows = await queries.communityMember.getMembersByUserIds(db, serverId, userIds)+ const onlineSet = await fetchOnlineUserIds(env, rows.map((r) => r.userId), serverId)+ return rows.map((r) => ({+ handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),+ role: r.role ?? "member",+ online: onlineSet.has(r.userId),+ status: toMemberStatus(r),+ }))+}diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.tsnew file mode 100644index 000000000..7758e5e04--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts@@ -0,0 +1,125 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })) }))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockCreateMessageWithThread = vi.fn()+const mockResolveTargetForMember = vi.fn()+const mockRequireMessageSurfaceAccess = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityAgentInbox: {+ ...actual.queries.communityAgentInbox,+ toAgentMessage: vi.fn(async (_db, row) => ({ id: row.id, content: row.content, seq: row.seq ?? 1 })),+ },+ },+ }+})+vi.mock("@/lib/community/resolve-ref", () => ({ resolveTargetForMember: (...args: unknown[]) => mockResolveTargetForMember(...args) }))+vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))+vi.mock("@/lib/community/create-channels", () => ({ createMessageWithThread: (...args: unknown[]) => mockCreateMessageWithThread(...args) }))+vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn(async () => ({ allowed: true })) }))+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: any, ctx?: any) => handler(req, {+ env: { DB: {} },+ actor: { kind: "bot", userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" },+ params: ctx?.params instanceof Promise ? await ctx.params : ctx?.params,+ }),+}))+vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { POST } from "./route"++const ctx = { params: { id: "resolve" } } as any+const request = (body: unknown) => new NextRequest("http://localhost/api/community/channels/resolve/messages", {+ method: "POST",+ headers: { Authorization: "Bearer crk_abc", "content-type": "application/json" },+ body: JSON.stringify(body),+})++describe("forum sends open a thread through the canonical message route", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockResolveTargetForMember.mockResolvedValue({ channelId: "forum_1" })+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "forum_1", serverId: "server_1", type: "forum", parentChannelId: null } },+ })+ mockCreateMessageWithThread.mockResolvedValue({+ ok: true,+ message: { id: "message_1", content: "Title", seq: 5 },+ attachments: [],+ thread: { id: "thread_1" },+ })+ })++ it("creates only the opener and structural child thread", async () => {+ const response = await POST(request({ channel: "/demo/forum", content: { text: "Title" }, nonce: "command:opener" }), ctx)++ expect(response.status).toBe(200)+ expect(mockCreateMessageWithThread).toHaveBeenCalledWith(expect.objectContaining({+ authorId: "bot_1",+ parentChannelId: "forum_1",+ serverId: "server_1",+ body: { content: "Title" },+ pendingAttachmentIdsToRebind: [],+ clientNonce: "command:opener",+ }))+ expect(await response.json()).toEqual(expect.objectContaining({ state: "sent", threadId: "thread_1" }))+ })++ it("passes pending attachment ids to the structural primitive for scope-safe rebind", async () => {+ await POST(request({ channel: "/demo/forum", content: { text: "Title" }, attachments: ["attachment_1"] }), ctx)++ expect(mockCreateMessageWithThread).toHaveBeenCalledWith(expect.objectContaining({+ pendingAttachmentIdsToRebind: ["attachment_1"],+ attachmentIds: undefined,+ }))+ })++ it("accepts a deduped opener replay without a pending-attachment precheck", async () => {+ mockCreateMessageWithThread.mockResolvedValueOnce({+ ok: true,+ deduped: true,+ message: { id: "message_1", content: "Title", seq: 5 },+ attachments: [],+ thread: { id: "thread_1" },+ })++ const response = await POST(request({ channel: "/demo/forum", content: { text: "Title" }, attachments: ["attachment_1"], nonce: "command:opener" }), ctx)++ expect(response.status).toBe(200)+ expect(await response.json()).toEqual(expect.objectContaining({ deduped: true, threadId: "thread_1" }))+ })++ it("does not open a nested thread for an ordinary thread target", async () => {+ mockRequireMessageSurfaceAccess.mockResolvedValueOnce({+ ok: true,+ value: { surface: "channel", channel: { id: "thread_1", serverId: "server_1", type: "thread", parentChannelId: "forum_1" } },+ })++ await expect(POST(request({ channel: "/demo/forum/#5", content: { text: "Body" } }), ctx)).rejects.toThrow()+ expect(mockCreateMessageWithThread).not.toHaveBeenCalled()+ })++ it("propagates structural primitive failures", async () => {+ mockCreateMessageWithThread.mockResolvedValueOnce({ ok: false, status: 400, error: "attachment not found or not attachable to this thread" })++ const response = await POST(request({ channel: "/demo/forum", content: { text: "Title" }, attachments: ["stolen"] }), ctx)++ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: "attachment not found or not attachable to this thread" })+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex 194ab7eda..5303ab9c0 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -15,7 +15,6 @@ const mockGetMessagesByIdsInScope = vi.fn()const mockListMembers = vi.fn()const mockListMemberUserIds = vi.fn()const mockCreateMentions = vi.fn()-const mockCreateAttachment = vi.fn()const mockListChildChannels = vi.fn()const mockIsChannelPrivate = vi.fn(() => false)const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])@@ -24,8 +23,29 @@ const mockListMessagesAround = vi.fn()const mockListMessagesSince = vi.fn()const mockGetLatestMessageSeq = vi.fn()const mockListByMessageIds = vi.fn()+const mockFindPendingAttachmentsForSender = vi.fn()+const mockReserveAttachmentsForMessage = vi.fn()const mockListReactionsByMessageIds = vi.fn()const mockGetUserInternal = vi.fn()+const mockGetDM = vi.fn()+const mockGetDMPeer = vi.fn()+const mockIsBlocked = vi.fn()+const mockListMessagesBySeq = vi.fn()+const mockToAgentMessages = vi.fn()+const mockToAgentMessage = vi.fn()+const mockGetLatestSeqForScope = vi.fn()+const mockGetReadState = vi.fn()+const mockHasDeliverableUnreadForAgentScope = vi.fn()+const mockBumpBotDailyActivityStatement = vi.fn()+const mockResolveServerByNameForMember = vi.fn()+const mockResolveChannelByNameForMember = vi.fn()+const mockGetUserByNameAndDiscriminator = vi.fn()+const mockGetDMBetween = vi.fn()+const mockCreateChannel = vi.fn()+const mockGetThreadChannelByParentMessage = vi.fn()+const mockDeleteChannel = vi.fn()+const mockHardDeleteMessage = vi.fn()+const mockRebindPendingAttachmentsToChild = vi.fn()const mockFanOutToChannel = vi.fn()const mockResolveChannelRecipients = vi.fn(async () => [] as string[])@@ -47,9 +67,13 @@ vi.mock("@alook/shared", async () => {communityChannel: {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),getChannel: (...a: unknown[]) => mockGetChannel(...a),+ resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),+ createChannel: (...a: unknown[]) => mockCreateChannel(...a),+ getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),+ deleteChannel: (...a: unknown[]) => mockDeleteChannel(...a),},communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),@@ -61,6 +85,8 @@ vi.mock("@alook/shared", async () => {listMessagesAround: (...a: unknown[]) => mockListMessagesAround(...a),listMessagesSince: (...a: unknown[]) => mockListMessagesSince(...a),getLatestMessageSeq: (...a: unknown[]) => mockGetLatestMessageSeq(...a),+ hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),+ getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),},communityMember: {listMembers: (...a: unknown[]) => mockListMembers(...a),@@ -73,14 +99,45 @@ vi.mock("@alook/shared", async () => {addThreadParticipants: vi.fn(async () => undefined),},communityAttachment: {- createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),+ findPendingAttachmentsForSender: (...a: unknown[]) => mockFindPendingAttachmentsForSender(...a),+ reserveAttachmentsForMessage: (...a: unknown[]) => mockReserveAttachmentsForMessage(...a),+ rebindPendingAttachmentsToChild: (...a: unknown[]) => mockRebindPendingAttachmentsToChild(...a),},communityReaction: {listReactionsByMessageIds: (...a: unknown[]) => mockListReactionsByMessageIds(...a),},user: {getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),+ },+ // The door's DM arm (requireDMAccess) uses these when a DM id is dispatched.+ communityDm: {+ getDM: (...a: unknown[]) => mockGetDM(...a),+ getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),+ getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ },+ communityFriendship: {+ isBlocked: (...a: unknown[]) => mockIsBlocked(...a),+ },+ // Bot read arm (GET dual-actor): seq-window + agent-message projection.+ communityAgentInbox: {+ listMessagesBySeq: (...a: unknown[]) => mockListMessagesBySeq(...a),+ toAgentMessages: (...a: unknown[]) => mockToAgentMessages(...a),+ toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a),+ getLatestSeqForScope: (...a: unknown[]) => mockGetLatestSeqForScope(...a),+ hasDeliverableUnreadForAgentScope: (...a: unknown[]) => mockHasDeliverableUnreadForAgentScope(...a),+ },+ communityReadState: {+ getReadState: (...a: unknown[]) => mockGetReadState(...a),+ },+ communityBot: {+ bumpBotDailyActivityStatement: (...a: unknown[]) => mockBumpBotDailyActivityStatement(...a),+ },+ // resolveTargetForMember (real, for the bot ref-via-query arm) resolves+ // the server then channel by name, both member-scoped.+ communityServer: {+ resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),},},}@@ -106,6 +163,22 @@ vi.mock("@/lib/middleware/auth", () => ({}),}))+// POST is now the dual-actor door (withCommunityActor). These POST tests+// exercise the HUMAN arm — mock the wrapper to yield a human actor + the real+// channelId from the path. The bot arm is covered in the send-fold tests.+vi.mock("@/lib/middleware/community-actor", () => ({+ // Credential-based actor dispatch (mirrors the real wrapper): a crk_ bearer →+ // bot actor, else → human. Lets the bot-read arm be exercised via header.+ withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ const authz = req?.headers?.get?.("Authorization") ?? ""+ const actor = authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]" }+ return handler(req, { env: { DB: {} }, actor, params })+ }),+}))+vi.mock("@/lib/middleware/helpers", () => {const { NextResponse } = require("next/server")return {@@ -116,7 +189,7 @@ vi.mock("@/lib/middleware/helpers", () => {})import { POST, GET } from "./route"-import { MAX_MESSAGE_CONTENT_LENGTH, MAX_ATTACHMENTS_PER_MESSAGE, WS_EVENTS } from "@alook/shared"+import { MAX_MESSAGE_CONTENT_LENGTH, MAX_ATTACHMENTS_PER_MESSAGE, MAX_FORUM_TAG_LENGTH, WS_EVENTS } from "@alook/shared"function postReq(body: unknown) {return new NextRequest("http://localhost/api/community/channels/c1/messages", {@@ -126,6 +199,14 @@ function postReq(body: unknown) {})}+function botPostReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/channels/send/messages", {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json", Authorization: "Bearer crk_test" },+ })+}+function getReq() {return new NextRequest("http://localhost/api/community/channels/c1/messages", { method: "GET" })}@@ -135,7 +216,10 @@ const ctx = { params: { id: "c1" } } as anydescribe("POST /api/community/channels/[id]/messages", () => {beforeEach(() => {vi.clearAllMocks()- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })+ // The door's single mask (requireMessageSurfaceAccess) probes getChannel+ // first to dispatch by surface; default = the same text channel.+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })mockCreateMessage.mockResolvedValue({ id: "m1" })// Human author by default — `createCommunityMessage`'s bot-authored audit// (plan §10) only fires when `isBot === true`, which none of these tests exercise.@@ -151,34 +235,48 @@ describe("POST /api/community/channels/[id]/messages", () => {type: "default",mentionType: null,replyToId: null,+ channelId: "c1",embeds: null,createdAt: "2026-06-30T00:00:00.000Z",})mockGetMessageByAuthorAndNonce.mockResolvedValue(null)mockListMembers.mockResolvedValue([])+ mockListByMessageIds.mockResolvedValue([])mockListMemberUserIds.mockResolvedValue([])mockGetMessagesByIdsInScope.mockResolvedValue([])mockCreateMentions.mockResolvedValue(undefined)- mockCreateAttachment.mockImplementation(async (_db: unknown, input: any) => ({- id: "a1",- ...input,- }))mockFanOutToChannel.mockResolvedValue(undefined)mockBroadcastToUser.mockResolvedValue(undefined)+ mockGetLatestSeqForScope.mockResolvedValue(0)+ mockGetReadState.mockResolvedValue(null)+ mockHasDeliverableUnreadForAgentScope.mockResolvedValue(false)+ mockBumpBotDailyActivityStatement.mockReturnValue({})+ mockToAgentMessage.mockImplementation(async (_db, row, _user, attachments) => ({ ...row, attachments }))mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })+ mockCreateChannel.mockResolvedValue({ id: "thread_1", creatorId: "u1", createdAt: "t0", name: "thread" })+ mockRebindPendingAttachmentsToChild.mockResolvedValue(true)})- it("rejects a bare message to a forum top-level with 400 (not a message-bearing surface)", async () => {- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" })- const res = await POST(postReq({ content: "bare into forum index" }), ctx)- expect(res.status).toBe(400)- expect(mockCreateMessage).not.toHaveBeenCalled()+ it("accepts a bare message to a forum top-level (phase2 forum≡thread write-guard reversal — forum is now directly sendable)", async () => {+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })+ const res = await POST(postReq({ content: "a post's opener message" }), ctx)+ expect(res.status).toBe(201)+ expect(mockCreateMessage).toHaveBeenCalled()})- it("rejects a message to a DM channel id via the generic channel route with 400 (block-bypass guard)", async () => {- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: null, type: "dm" })+ it("a DM id via the door routes to the DM arm — the block gate runs (blocked peer → 403, not a silent channel-route bypass)", async () => {+ // Corrected direction (one door): a DM id is a valid target here, dispatched+ // to requireDMAccess (which runs the block check) — NOT the old two-door+ // "reject DM on channel route with 400". The P0 the old test guarded (block+ // bypass) is now closed by the dm arm running requireDMAccess, proven here:+ // a blocked peer is refused 403, and createCommunityMessage never fires.+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: null, type: "dm", parentChannelId: null })+ mockGetDM.mockResolvedValue({ id: "c1", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })+ mockIsBlocked.mockResolvedValue(true)const res = await POST(postReq({ content: "sneaking past block" }), ctx)- expect(res.status).toBe(400)+ expect(res.status).toBe(403)expect(mockCreateMessage).not.toHaveBeenCalled()})@@ -228,12 +326,27 @@ describe("POST /api/community/channels/[id]/messages", () => {})it("returns the original canonical contract for a same-nonce replay", async () => {- mockGetMessageByAuthorAndNonce.mockResolvedValue({ id: "m-existing", seq: 8, clientNonce: "n1" })+ mockGetMessageByAuthorAndNonce.mockResolvedValue({+ id: "m-existing",+ seq: 8,+ clientNonce: "n1",+ channelId: "c1",+ authorId: "u1",+ authorName: "Alice",+ authorImage: null,+ authorEmail: "[email protected]",+ content: "hello",+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ createdAt: "2026-06-30T00:00:00.000Z",+ })const res = await POST(postReq({ content: "hello", nonce: "n1" }), ctx)const body = await res.json() as { message: { id: string; seq: number; clientNonce?: string }; deduped: boolean }- expect(res.status).toBe(201)+ expect(res.status).toBe(200)expect(body).toEqual({message: expect.objectContaining({ id: "m-existing", seq: 8, clientNonce: "n1" }),deduped: true,@@ -241,6 +354,30 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(mockCreateMessage).not.toHaveBeenCalled()})+ it("returns the full raw message row for human POST convergence", async () => {+ const row = {+ id: "m_full",+ authorId: "u1",+ authorName: "Canonical Author",+ authorImage: "https://avatar.test/u1.png",+ authorEmail: "[email protected]",+ content: "canonical content",+ type: "default",+ mentionType: null,+ replyToId: null,+ channelId: "c1",+ embeds: [{ title: "Canonical embed" }],+ seq: 42,+ createdAt: "2026-08-07T10:00:00.000Z",+ }+ mockGetMessage.mockResolvedValue(row)++ const response = await POST(postReq({ content: "canonical content", nonce: "client-1" }), ctx)++ expect(response.status).toBe(201)+ expect(await response.json()).toEqual({ message: row })+ })+it("rejects content longer than MAX_MESSAGE_CONTENT_LENGTH with 400", async () => {const tooLong = "a".repeat(MAX_MESSAGE_CONTENT_LENGTH + 1)const res = await POST(postReq({ content: tooLong }), ctx)@@ -249,13 +386,40 @@ describe("POST /api/community/channels/[id]/messages", () => {})it("rejects more than MAX_ATTACHMENTS_PER_MESSAGE attachments with 400", async () => {- const attachments = Array.from({ length: MAX_ATTACHMENTS_PER_MESSAGE + 1 }, (_, i) => ({- url: `r2://x/${i}`,- filename: `f${i}.png`,- contentType: "image/png",- size: 1,- }))- const res = await POST(postReq({ content: "ok", attachments }), ctx)+ // Reserve-by-id: the human arm sends pending-row IDS. All ids validate as+ // owned/attachable (findPending echoes them), so the over-cap rejection is+ // the message handler's own MAX_ATTACHMENTS_PER_MESSAGE guard, not a+ // validation miss.+ const attachmentIds = Array.from({ length: MAX_ATTACHMENTS_PER_MESSAGE + 1 }, (_, i) => `att_${i}`)+ mockFindPendingAttachmentsForSender.mockResolvedValue(attachmentIds.map((id) => ({ id })))+ const res = await POST(postReq({ content: "ok", attachments: attachmentIds }), ctx)+ expect(res.status).toBe(400)+ expect(mockCreateMessage).not.toHaveBeenCalled()+ })++ it("reserve-by-id: validates the pending ids (uploader+target) then passes attachmentIds to the handler", async () => {+ mockFindPendingAttachmentsForSender.mockResolvedValue([{ id: "att_1" }, { id: "att_2" }])+ mockCreateMessage.mockResolvedValue({ id: "m_new" })+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1", "att_2"])+ mockListByMessageIds.mockResolvedValue([])+ const res = await POST(postReq({ content: "pics", attachments: ["att_1", "att_2"] }), ctx)+ expect(res.status).toBe(201)+ // The validation query is scoped to THIS user + THIS channel (self-scope /+ // confused-deputy-safe — the human dual of the download authorize-from-row).+ expect(mockFindPendingAttachmentsForSender).toHaveBeenCalledWith(+ {},+ expect.objectContaining({ ids: ["att_1", "att_2"], uploaderId: "u1" }),+ )+ })++ it("reserve-by-id confused-deputy guard: a foreign/stolen pending id (count mismatch) → 400, no message", async () => {+ // The composer sends 2 ids but only 1 is owned by this user in this target+ // (the other belongs to someone else / a different channel). The+ // uploader+target-scoped query returns fewer rows than requested → reject+ // with a generic 400 that never says which id failed, and NO message row is+ // created. This is the send-side confused-deputy guard.+ mockFindPendingAttachmentsForSender.mockResolvedValue([{ id: "att_mine" }])+ const res = await POST(postReq({ content: "steal", attachments: ["att_mine", "att_theirs"] }), ctx)expect(res.status).toBe(400)expect(mockCreateMessage).not.toHaveBeenCalled()})@@ -380,27 +544,65 @@ describe("POST /api/community/channels/[id]/messages", () => {(c) => c[1]?.type === WS_EVENTS.CHILD_CHANNEL_UPDATE,)expect(childUpdateCall).toBeUndefined()- // getChannel is only invoked in the thread branch to read messageCount /- // lastMessageAt for the CHILD_CHANNEL_UPDATE payload — must not fire here.- expect(mockGetChannel).not.toHaveBeenCalled()- })-- // ── Idempotency nonce (mutation-idempotency plan, ③) ──────────────────────- // The human web send path threads `nonce` symmetrically to the agent send- // route (bot=user, Gus #204): body `nonce` → `createCommunityMessage`'s- // `clientNonce` param → surfaced `deduped` on the response. The route change- // is a thin pass-through; the handler-internal dedup (nonce pre-check,- // partial-unique backstop) is covered by the handler/① tests, and the- // end-to-end retry-dedup by Blair/Olivia's integration pass. Asserting the- // nonce plumbing here would require reaching into the handler's own query- // mocks (getMessageByAuthorAndNonce), which this route-level suite doesn't- // wire — kept out to avoid a wrong-layer assertion.+ // (Under the door, getChannel IS called by the dispatch mask+ // (requireMessageSurfaceAccess) for every send — the old "getChannel only in+ // the thread branch" check no longer holds; the real regression guard is the+ // no-CHILD_CHANNEL_UPDATE assertion above.)+ })++ it("human full-command replay hydrates bound attachments before pending validation", async () => {+ const stored = { id: "a1", targetId: "c1", filename: "x.png", contentType: "image/png", size: 10, width: 1, height: 1 }+ mockFindPendingAttachmentsForSender.mockResolvedValueOnce([stored])+ mockReserveAttachmentsForMessage.mockResolvedValueOnce(["a1"])+ mockListByMessageIds.mockResolvedValue([stored])+ mockGetMessageByAuthorAndNonce+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ ...await mockGetMessage(), clientNonce: "cmd:reply" })++ const first = await POST(postReq({ content: "reply", attachments: ["a1"], nonce: "cmd:reply" }), ctx)+ const replay = await POST(postReq({ content: "reply", attachments: ["a1"], nonce: "cmd:reply" }), ctx)++ expect(first.status).toBe(201)+ expect(replay.status).toBe(200)+ expect(await replay.json()).toEqual(expect.objectContaining({ deduped: true }))+ expect(mockFindPendingAttachmentsForSender).toHaveBeenCalledTimes(1)+ expect(mockCreateMessage).toHaveBeenCalledTimes(1)+ expect(mockReserveAttachmentsForMessage).toHaveBeenCalledTimes(1)+ })++ it("bot full-command replay bypasses alignment and pending checks after the first committed send", async () => {+ const stored = { id: "a1", targetId: "c1", filename: "x.png", contentType: "image/png", size: 10, width: 1, height: 1 }+ const row = { ...await mockGetMessage(), authorId: "bot_1", clientNonce: "cmd:reply" }+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "s1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "c1", serverId: "s1", type: "text", parentChannelId: null }])+ mockFindPendingAttachmentsForSender.mockResolvedValueOnce([stored])+ mockReserveAttachmentsForMessage.mockResolvedValueOnce(["a1"])+ mockListByMessageIds.mockResolvedValue([stored])+ mockGetMessageByAuthorAndNonce+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(row)++ const body = { channel: "/demo#0042/text", content: { text: "reply" }, attachments: ["a1"], nonce: "cmd:reply" }+ const first = await POST(botPostReq(body), ctx)+ const replay = await POST(botPostReq(body), ctx)++ expect(first.status).toBe(200)+ expect(replay.status).toBe(200)+ expect(await replay.json()).toEqual(expect.objectContaining({ state: "sent", deduped: true }))+ expect(mockFindPendingAttachmentsForSender).toHaveBeenCalledTimes(1)+ expect(mockCreateMessage).toHaveBeenCalledTimes(1)+ expect(mockHasDeliverableUnreadForAgentScope).toHaveBeenCalledTimes(1)+ })})describe("GET /api/community/channels/[id]/messages", () => {beforeEach(() => {vi.clearAllMocks()- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })+ // The door's single mask probes getChannel first (dual-actor GET dispatch).+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })mockListChildChannels.mockResolvedValue([])mockListByMessageIds.mockResolvedValue([])mockListReactionsByMessageIds.mockResolvedValue([])@@ -447,6 +649,33 @@ describe("GET /api/community/channels/[id]/messages", () => {expect(scope).toEqual({ channelId: "c1" })})+ it("retries BUSY reply enrichment and preserves the paginated response", async () => {+ vi.spyOn(Math, "random").mockReturnValue(0)+ mockListMessages.mockResolvedValue([+ { id: "m1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "reply", type: "default", mentionType: null, replyToId: "r1", channelId: "c1", embeds: null, createdAt: "t1" },+ ])+ mockGetMessagesByIdsInScope+ .mockRejectedValueOnce(new Error("D1_ERROR: database is locked"))+ .mockResolvedValueOnce([{ id: "r1", authorName: "B", content: "root", channelId: "c1", dmConversationId: null }])+ const res = await GET(getReq(), ctx)+ const body = await res.json()+ expect(body.messages).toHaveLength(1)+ expect(body.messages[0].replyTo).toEqual({ id: "r1", authorName: "B", text: "root" })+ expect(body.hasMore).toBe(false)+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(2)+ expect(mockListMessages).toHaveBeenCalledTimes(1)+ })++ it("rethrows a non-BUSY reply-enrichment failure without retrying", async () => {+ const error = new Error("bad projection")+ mockListMessages.mockResolvedValue([+ { id: "m1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "reply", type: "default", mentionType: null, replyToId: "r1", channelId: "c1", embeds: null, createdAt: "t1" },+ ])+ mockGetMessagesByIdsInScope.mockRejectedValueOnce(error)+ await expect(GET(getReq(), ctx)).rejects.toBe(error)+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)+ })+it("returns author.name verbatim — no 'Unknown' sentinel, no email leak", async () => {// Post-migration 0050 the shared query returns user.name as a non-empty// string. The route must drop the pre-migration cascade@@ -542,6 +771,33 @@ describe("GET /api/community/channels/[id]/messages", () => {expect(mockGetLatestMessageSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "c1" })})+ it("passes a normalized tag into the channel-scoped message query before pagination", async () => {+ mockListMessages.mockResolvedValue([])+ const req = new NextRequest("http://localhost/api/community/channels/c1/messages?tag=%20Bug%20&cursor=2026-01-01T00%3A00%3A00.000Z%7Cm1", { method: "GET" })+ const res = await GET(req, ctx)+ expect(res.status).toBe(200)+ expect(mockListMessages).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({+ channelId: "c1",+ tag: "bug",+ cursor: { createdAt: "2026-01-01T00:00:00.000Z", id: "m1" },+ }))+ })++ it.each(["", " "])("rejects an explicitly empty tag %j instead of widening to all messages", async (tag) => {+ const req = new NextRequest(`http://localhost/api/community/channels/c1/messages?tag=${encodeURIComponent(tag)}`, { method: "GET" })+ const res = await GET(req, ctx)+ expect(res.status).toBe(400)+ expect(mockListMessages).not.toHaveBeenCalled()+ })++ it("rejects a tag longer than the public message-tag limit", async () => {+ const tag = "x".repeat(MAX_FORUM_TAG_LENGTH + 1)+ const req = new NextRequest(`http://localhost/api/community/channels/c1/messages?tag=${tag}`, { method: "GET" })+ const res = await GET(req, ctx)+ expect(res.status).toBe(400)+ expect(mockListMessages).not.toHaveBeenCalled()+ })+describe("?anchor mode", () => {it("returns a centered window with the anchor row present, plus latestSeq + cursors", async () => {mockGetMessageInScope.mockResolvedValue({@@ -594,6 +850,19 @@ describe("GET /api/community/channels/[id]/messages", () => {expect(res.status).toBe(404)expect(mockListMessagesAround).not.toHaveBeenCalled()})++ it("applies tag to the same channel-scoped anchor window", async () => {+ mockGetMessageInScope.mockResolvedValue({ id: "m_anchor", createdAt: "2026-06-30T00:00:03.000Z" })+ mockListMessagesAround.mockResolvedValue({ older: [], newer: [], hasMoreOlder: false, hasMoreNewer: false })+ const req = new NextRequest("http://localhost/api/community/channels/c1/messages?anchor=m_anchor&tag=%20Bug%20", { method: "GET" })+ const res = await GET(req, ctx)+ expect(res.status).toBe(200)+ expect(mockListMessagesAround).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({+ channelId: "c1",+ anchor: { createdAt: "2026-06-30T00:00:03.000Z", id: "m_anchor" },+ tag: "bug",+ }))+ })})describe("?since mode", () => {@@ -629,5 +898,102 @@ describe("GET /api/community/channels/[id]/messages", () => {expect(mockGetMessageInScope).not.toHaveBeenCalled()expect(mockListMessagesAround).not.toHaveBeenCalled()})++ it("applies tag to the same channel-scoped since delta", async () => {+ mockListMessagesSince.mockResolvedValue([])+ const req = new NextRequest(+ "http://localhost/api/community/channels/c1/messages?since=2026-06-30T00:00:00.000Z%7Cm_0&tag=%20Bug%20",+ { method: "GET" },+ )+ const res = await GET(req, ctx)+ expect(res.status).toBe(200)+ expect(mockListMessagesSince).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({+ channelId: "c1",+ since: { createdAt: "2026-06-30T00:00:00.000Z", id: "m_0" },+ tag: "bug",+ }))+ })+ })++ describe("bot arm (GET/read convergence — seq window + {items}, ref-via-query, no create)", () => {+ function botGetReq(query = "") {+ return new NextRequest(`http://localhost/api/community/channels/resolve/messages${query}`, {+ method: "GET",+ headers: { Authorization: "Bearer crk_abc" },+ })+ }+ const botCtx = { params: { id: "resolve" } } as any++ it("bot reads via ?ref= → seq window → {items} (agent-message projection), NOT {messages}", async () => {+ // ref resolves to a channel; the door's single mask passes it (bot scope),+ // then the bot arm pages by seq and projects to agent-message {items}.+ // ref /studio#0042/general resolves server→channel (both member-scoped), then+ // the door's mask probes getChannel.+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "s1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "c1" }])+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })+ mockListMessagesBySeq.mockResolvedValue({ items: [{ id: "m1", seq: 1 }], hasMore: false, latestSeq: 1 })+ mockToAgentMessages.mockResolvedValue([{ seq: 1, text: "hi" }])++ const res = await GET(botGetReq("?ref=%2Fstudio%230042%2Fgeneral&after=0"), botCtx)+ expect(res.status).toBe(200)+ const body = await res.json() as { items?: unknown[]; messages?: unknown[] }+ expect(body.items).toEqual([{ seq: 1, text: "hi" }])+ expect(body.messages).toBeUndefined() // bot arm = {items}, never {messages}+ // Read went through the shared seq query, scoped to the resolved channel.+ expect(mockListMessagesBySeq).toHaveBeenCalledWith({}, { channelId: "c1" }, expect.objectContaining({ after: 0 }))+ })++ it("decodes an encoded ref carrying / and # (DM handle round-trip: %2F.dm%2Fgusye%231231 → /.dm/gusye#1231)", async () => {+ // Gener #263 / Melly #264: a DM ref has `/` AND `#` (fragment char) — the+ // CLI encodeURIComponent's it into the query; NextRequest.searchParams.get+ // auto-decodes, so resolveTargetForMember sees the real ref. This asserts+ // the door gets the DECODED ref (not truncated at #, not left percent-escaped).+ const peer = { id: "peer_1", discriminator: "1231" }+ mockGetUserByNameAndDiscriminator.mockResolvedValue(peer)+ mockGetDMBetween.mockResolvedValue({ id: "dm1" })+ mockGetChannel.mockResolvedValue({ id: "dm1", serverId: null, type: "dm", parentChannelId: null })+ mockGetDM.mockResolvedValue({ id: "dm1", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })+ mockIsBlocked.mockResolvedValue(false)+ mockListMessagesBySeq.mockResolvedValue({ items: [{ id: "m1", seq: 1 }], hasMore: false, latestSeq: 1 })+ mockToAgentMessages.mockResolvedValue([{ seq: 1, text: "dm hi" }])++ const encoded = encodeURIComponent("/.dm/gusye#1231")+ const res = await GET(botGetReq(`?ref=${encoded}`), botCtx)+ expect(res.status).toBe(200)+ // The DM handle's #1231 was NOT lost as a URL fragment — the peer lookup+ // received the decoded name#disc, proving the round-trip.+ expect(mockGetUserByNameAndDiscriminator).toHaveBeenCalledWith({}, "gusye", "1231")+ const body = await res.json() as { items?: unknown[] }+ expect(body.items).toEqual([{ seq: 1, text: "dm hi" }])+ })++ it("loudly rejects read hydration for an orphan DM without leaking raw ids", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_internal", discriminator: "1231" })+ mockGetDMBetween.mockResolvedValue({ id: "dm_internal" })+ mockGetChannel.mockResolvedValue({ id: "dm_internal", serverId: null, type: "dm", parentChannelId: null })+ mockGetDM.mockResolvedValue({ id: "dm_internal", lastMessageAt: null, createdAt: "t" })+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_internal" })+ mockIsBlocked.mockResolvedValue(false)+ mockListMessagesBySeq.mockResolvedValue({ items: [{ id: "message_internal", seq: 1 }], hasMore: false, latestSeq: 1 })+ mockToAgentMessages.mockRejectedValue(new Error("DM peer identity unavailable"))++ const read = GET(botGetReq(`?ref=${encodeURIComponent("/.dm/gusye#1231")}`), botCtx)+ await expect(read).rejects.toThrow("DM peer identity unavailable")+ await expect(read).rejects.not.toThrow(/peer_internal|dm_internal|message_internal/)+ })++ it("bot read of a ref to a nonexistent target → 404, NO create (read-create=false ⑤)", async () => {+ // resolveTargetForMember (real, through the mocked queries) returns+ // not-found for an unknown ref; the door surfaces 404 and never creates.+ mockResolveServerByNameForMember.mockResolvedValue([]) // server not found → resolve 404+ const res = await GET(botGetReq("?ref=%2Fnope%230042%2Fmissing"), botCtx)+ expect(res.status).toBe(404)+ // No create query fired — read is pure addressing (structurally the GET+ // descriptor carries no create-if-missing).+ expect(mockCreateMessage).not.toHaveBeenCalled()+ })})})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.tsindex 1a49c000a..e82a7ff57 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts@@ -1,8 +1,8 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"+import { NextRequest, NextResponse } from "next/server"+import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"+import { queries, withD1Retry, CommunityAgentSendRequestSchema, MAX_FORUM_TAG_LENGTH, utcDayKey } from "@alook/shared"import {parseCursor,parseAnchor,@@ -12,29 +12,113 @@ import {buildSinceResponse,} from "@/lib/community/messages"import { enrichMessages } from "@/lib/community/enrich-messages"-import { requireChannelMember } from "@/lib/community/permissions"-import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"import { checkRateLimit } from "@/lib/rate-limit"-import { createCommunityMessage } from "@/lib/community/message-handler"+import { createCommunityMessage, getCommunityMessageReplay } from "@/lib/community/message-handler"+import { createMessageWithThread } from "@/lib/community/create-channels"+import {+ resolveMessageTarget,+ type MessageTargetDescriptor,+} from "@/lib/community/message-door"++// A bot addresses by ref-in-body; the path `[id]` is then a placeholder+// (`channels/resolve/messages`) since a ref carries `/` and can't sit in a path+// segment. A human/web caller puts the real channelId in the path. This is the+// one door's single addressing input — id (path) xor ref (body), Gener #752.+const REF_PLACEHOLDER_ID = "resolve"-export const GET = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)+// Parse a non-negative integer query param (bot read's seq anchors/limit).+// Returns undefined for absent/invalid so downstream defaults apply.+function parseIntParam(raw: string | null): number | undefined {+ if (raw === null) return undefined+ const n = Number(raw)+ return Number.isInteger(n) && n >= 0 ? n : undefined+}+/**+ * GET /api/community/channels/{id}/messages — the canonical read door (GET/read+ * convergence, (A) ruled Melly #237). Dual-actor: human/web pages by createdAt+ * → enrich → {messages}; bot/CLI pages by seq → agent-message → {items} (the+ * former flat `read` verb, daemon contract). Both arms:+ * - go through the SINGLE authorization entry (resolveMessageTarget →+ * requireMessageSurfaceAccess) — no standalone requireChannelMember (§3);+ * a bot passes the SAME mask (①-C read side, never skipped);+ * - query the SAME channel-scoped set (same channelId + actor scope) — the+ * response-form branch is a projection/pagination difference ONLY, never a+ * visibility/set difference (Ingaborg ★ / Aigneis ④);+ * The branch key is the CREDENTIAL actor.kind, never a field (Aigneis ②); auth+ * failures (404/403) happen at the mask BEFORE the branch, opaque for both arms+ * (Aigneis ③). Read NEVER creates: the descriptor built here carries no+ * create-if-missing (structurally, not just create=false — Aigneis #246 ⑤); a+ * ref to a nonexistent target is a 404, not a read-then-create.+ */+export const GET = withCommunityActor(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)+ const params = req.nextUrl.searchParams- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)+ // Single authorization entry, shared by both arms. Human: id from the path.+ // Bot: ref from the query (?ref=), a ref carrying `/` can't sit in the path+ // segment. NO create-if-missing on either — read is pure addressing.+ const refParam = params.get("ref")+ const descriptor = ctx.actor.kind === "bot" && refParam+ ? { ref: refParam }+ : { id: ctx.params?.id === REF_PLACEHOLDER_ID ? "" : (ctx.params?.id ?? "") }+ if (descriptor.id !== undefined && !descriptor.id) {+ return NextResponse.json({ error: "missing channel id" }, { status: 400 })+ }- const params = req.nextUrl.searchParams+ const resolved = await resolveMessageTarget(db, ctx.actor.userId, descriptor, ctx.actor.kind)+ if (!resolved.ok) {+ return NextResponse.json(+ { error: resolved.error, ...(resolved.hint ? { hint: resolved.hint } : {}) },+ { status: resolved.status },+ )+ }+ const channelId = resolved.value.target.channelId+ // The surface trait drives enrichment: a DM (type=dm) skips thread indicators+ // and hydrates friend-approval cards; a channel does the opposite. Derived+ // from the resolved surface (not re-tested) so the human read is byte-+ // identical whether the caller addressed a DM by its channelId here or via the+ // old dm/[id]/messages route (which passed isDm:true explicitly).+ const isDm = resolved.value.isDm+ const isForum = resolved.value.target.kind === "forum"++ // TODO(route-disc): unify the two response projections.+ // Auth/pagination-scope already single-source (one mask, one channel-scoped set);+ // the remaining fork is PROJECTION ONLY — human: enrichMessages→{messages},+ // bot: toAgentMessages→{items}. Kept split today because {items}+agent-message+ // is the daemon/CLI contract (inboxPull-shape reserved). Converge when the+ // agent-message form and enrich can share one projection (or CLI contract lifts).+ // Invariant to preserve on merge: both arms hit the SAME channel-scoped row-set+ // (set-equality) — only pagination-window + projection differ, no arm adds a where.++ // ── bot arm: seq-anchored window → agent-message projection → {items} ──+ if (ctx.actor.kind === "bot") {+ const readParams = {+ before: parseIntParam(params.get("before")),+ after: parseIntParam(params.get("after")),+ around: parseIntParam(params.get("around")),+ limit: parseIntParam(params.get("limit")),+ }+ const { items, hasMore, latestSeq } = await queries.communityAgentInbox.listMessagesBySeq(+ db,+ { channelId },+ readParams,+ )+ const messages = await queries.communityAgentInbox.toAgentMessages(db, items, ctx.actor.userId)+ return NextResponse.json({ items: messages, hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) })+ }++ // ── human arm: createdAt-anchored window → enrich → {messages} ──+ const userId = ctx.actor.userIdconst anchorId = parseAnchor(params.get("anchor"))const since = parseCursor(params.get("since"))const cursor = parseCursor(params.get("cursor"))+ const rawTag = params.get("tag")+ const tag = rawTag?.trim().toLowerCase()+ if (rawTag !== null && !tag) return writeError("tag must not be empty", 400)+ if (tag && tag.length > MAX_FORUM_TAG_LENGTH) return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)const pageSize = parsePageSize(params.get("limit"))- // Anchor branch: resolve the target message inside the channel scope first- // (a scope-first lookup — see AGENTS.md "scope the queries before"), then- // fetch the centered window and enrich.if (anchorId) {const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { channelId })if (!anchor) return writeError("anchor not found", 404)@@ -43,6 +127,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {channelId,anchor: { createdAt: anchor.createdAt, id: anchor.id },limit: pageSize,+ tag,})const { items, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor } = buildAnchorResponse(@@ -51,104 +136,315 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {{ hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items)+ const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })}- // Since branch: strictly-newer diff for cache hydration & WS-reconnect- // catch-up. Rows arrive ASC directly from the query; no reverse pass here.if (since) {const rows = await queries.communityMessage.listMessagesSince(db, {channelId,since,limit: pageSize,+ tag,})const { items, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor } = buildSinceResponse(rows, pageSize)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items)+ const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)return writeJSON({ messages, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor, latestSeq })}- // Legacy branch (unchanged behavior beyond `latestSeq` addition): newest page- // via DESC + one-extra-row probe, response items reversed to ASC.const rows = await queries.communityMessage.listMessages(db, {channelId,cursor,limit: pageSize + 1,+ tag,})const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items.slice().reverse())+ const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items.slice().reverse())return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })})-export const POST = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)-+/**+ * POST /api/community/channels/{id}/messages — the CANONICAL message door+ * (route/disc corrected direction, Melly #210): one id-in-path route serving+ * BOTH callers, the flat `send` verb folds in here (§3 replacement, Ingaborg+ * #219). Addressing is id-xor-ref, one door:+ * - human/web: real channelId in the path.+ * - bot/CLI: ref-in-body; the path `[id]` is the `resolve` placeholder (a ref+ * carries `/`, can't sit in a path segment).+ *+ * Authorization is credential-defined, addressing is body/path only. First+ * segment = `withCommunityActor` credential dispatch (crk_ → bot arm; session →+ * human arm) BEFORE any field is read, so a body field can't flip the actor arm.+ *+ * §3 (Ingaborg #219): the former standalone `requireChannelMember` is REPLACED+ * by `requireMessageSurfaceAccess` (via resolveMessageTarget) — the dispatch+ * subsumes the member check AND returns the channel, so there is EXACTLY ONE+ * authorization entry (no standalone member/DM gate remains — a second gate+ * would be a bypass of the single mask). A bot hitting this id route passes the+ * SAME mask (never skipped because machine-token — ASSERT 1 ①-C).+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- const channel = auth.value+ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid request body" }, { status: 400 })+ }- const bearing = requireMessageBearingSurface(channel.type)- if (!bearing.ok) return writeError(bearing.error, bearing.status)+ if (ctx.actor.kind === "bot") {+ return handleBotSend(db, ctx.actor.userId, raw)+ }+ return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw)+})++/**+ * Human/web arm — real channelId in the path (id descriptor). Rate-limit ++ * nonce + 201 shape preserved from the pre-fold channels POST; the raw body is+ * now schema-tightened via the door-core descriptor + createCommunityMessage's+ * own validation (the direction Ingaborg #196 flagged).+ */+async function handleHumanSend(+ db: ReturnType<typeof getDb>,+ userId: string,+ env: Env,+ pathId: string | undefined,+ raw: unknown,+): Promise<NextResponse> {+ if (!pathId || pathId === REF_PLACEHOLDER_ID) {+ return NextResponse.json({ error: "missing channel id" }, { status: 400 })+ }++ const descriptor: MessageTargetDescriptor = { id: pathId }- const rateLimit = await checkRateLimit(ctx.env, "community:msgSend", ctx.userId)+ const rateLimit = await checkRateLimit(env, "community:msgSend", userId)if (!rateLimit.allowed) {- return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })+ return NextResponse.json({ error: "rate limited" }, { status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSec) } })}- let body: unknown- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- // Child channels (those with a parentChannelId — threads AND forum posts)- // fire CHILD_CHANNEL_UPDATE on the parent so its indicator ticks, and both- // scope their notify set to participants. They're distinguished by- // `channel.type`: a forum_post uses the `forum_post` target kind so it can't- // silently ride the thread branch. Detected server-side from the channel row- // — clients always POST here, never to a separate endpoint, which avoided a- // UI race where a fast user could type before a client-side meta fetch- // resolved.- const target = channel.parentChannelId- ? {- kind: channel.type === "forum_post" ? ("forum_post" as const) : ("thread" as const),- channelId,- parentChannelId: channel.parentChannelId,- serverId: channel.serverId,- }- : {- kind: "channel" as const,- channelId,- serverId: channel.serverId,- }-- // Idempotency nonce (mutation-idempotency plan): the human web client mirrors- // the agent send route — it generates a random nonce per logical send and- // reuses it across retry-pill clicks, so a 500-after-commit resend dedupes- // server-side instead of double-posting. Extracted defensively (this route- // hands the raw body to the handler, no zod pass); the handler ignores an- // absent nonce and falls back to today's behavior.- const clientNonce =- typeof (body as { nonce?: unknown })?.nonce === "string"- ? (body as { nonce: string }).nonce- : undefined+ // SINGLE authorization entry — resolveMessageTarget → requireMessageSurfaceAccess+ // subsumes member/DM + returns the target (no standalone requireChannelMember).+ const resolved = await resolveMessageTarget(db, userId, descriptor, "human")+ if (!resolved.ok) return NextResponse.json({ error: resolved.error }, { status: resolved.status })++ const body = raw as { nonce?: unknown; attachments?: unknown }+ const clientNonce = typeof body?.nonce === "string" ? body.nonce : undefined+ const target = resolved.value.target++ // Reserve-by-id (route/disc step 2b): the composer uploads first (creating a+ // pending row) and sends the attachment IDS, mirroring the bot flow. Validate+ // each id against (uploader = this user, target = this channel) BEFORE the+ // message insert — the SAME `findPendingAttachmentsForSender` scope the bot arm+ // uses (the query is keyed on the `uploaderId` param, so it is actor-agnostic:+ // a stolen id owned by another user, or one pending against a different+ // target, fails the count check and rejects with a generic 400 that never+ // leaks which id). This is the human-side dual of the download door's+ // authorize-from-row confused-deputy guard.+ const attachmentIds = Array.isArray(body.attachments)+ ? (body.attachments as unknown[]).filter((x): x is string => typeof x === "string")+ : []+ // A human send into a forum uses the same canonical message door and the+ // same opener+thread primitive as the bot arm. The body is sent separately+ // through this ordinary message door after the caller receives threadId.+ if (target.kind === "forum") {+ const forumBody = raw as { content?: unknown; mentionType?: unknown }+ const content = typeof forumBody.content === "string" ? forumBody.content : ""+ if (!content.trim()) return NextResponse.json({ error: "content is required" }, { status: 400 })+ const created = await createMessageWithThread({+ db,+ authorId: userId,+ parentChannelId: target.channelId,+ serverId: target.serverId,+ body: { content, mentionType: forumBody.mentionType },+ pendingAttachmentIdsToRebind: attachmentIds,+ clientNonce,+ source: "web",+ })+ if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })+ return NextResponse.json({+ message: created.message,+ threadId: created.thread.id,+ deduped: created.deduped,+ }, { status: created.deduped ? 200 : 201 })+ }++ const replay = await getCommunityMessageReplay({+ db,+ authorId: userId,+ channelId: target.channelId,+ clientNonce,+ })+ if (replay) {+ return NextResponse.json({ message: replay.row, deduped: true }, { status: 200 })+ }++ if (attachmentIds.length > 0) {+ const channelId = target.channelId+ const rows = await withD1Retry(+ () => queries.communityAttachment.findPendingAttachmentsForSender(db, { ids: attachmentIds, uploaderId: userId, targetId: channelId }),+ { route: "community/messages:human-attachments" },+ )+ if (rows.length !== attachmentIds.length) {+ return NextResponse.json({ error: "attachment not found or not attachable to this target" }, { status: 400 })+ }+ }const result = await createCommunityMessage({db,- authorId: ctx.userId,+ authorId: userId,target,- body: body as Record<string, unknown>,+ body: raw as Record<string, unknown>,+ source: "web",clientNonce,+ attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,})- if (!result.ok) return writeError(result.error, result.status)+ if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })+ return NextResponse.json({ message: result.row, deduped: result.deduped }, { status: 201 })+}- // Surface `deduped` so the client reconciles a retry-pill resend that matched- // an already-committed message (align the optimistic row to the canonical- // seq/id, clear the failed pill) instead of treating it as a fresh insert.- return writeJSON({ message: result.row, deduped: result.deduped }, 201)-})+/**+ * Bot arm — ref-in-body (`channel`), the former `send` verb's behavior verbatim:+ * single resolve WITH create-if-missing, channel-alignment gate, CAS via+ * `expectedSeq`, SENT-heatmap bump, agent-message response. Target resolution ++ * per-surface auth flow through the shared door-core (single mask entry).+ */+async function handleBotSend(+ db: ReturnType<typeof getDb>,+ botUserId: string,+ raw: unknown,+): Promise<NextResponse> {+ const parsed = CommunityAgentSendRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const body = parsed.data++ const descriptor: MessageTargetDescriptor = {+ ref: body.channel,+ createDmIfMissing: true,+ createThreadIfMissing: true,+ }+ const resolved = await resolveMessageTarget(db, botUserId, descriptor, "bot")+ if (!resolved.ok) {+ return NextResponse.json(+ { error: resolved.error, ...(resolved.hint ? { hint: resolved.hint } : {}) },+ { status: resolved.status },+ )+ }+ const target = resolved.value.target+ const channelId = target.channelId++ // Sending into a forum's top level always opens a thread on the opener+ // message — a forum is a browsable topic list, so every message landing+ // there needs its own thread the same way a post always did. This branches+ // on the TARGET's resolved kind (set by resolveMessageTarget from the+ // channel's own stored type), never on a body field's presence — a forum+ // message always gets this treatment regardless of what fields the client+ // happened to send, and a plain channel/thread/DM never does regardless of+ // what fields it sends either. A thread can't nest another thread and a DM+ // has no thread axis, which is+ // exactly why this path is only reachable when the target's kind is+ // "forum". No alignment/hasUnread gate on this branch — opening a+ // brand-new thread is a fresh scope with no seq contention to align+ // against.+ if (target.kind === "forum") {+ const created = await createMessageWithThread({+ db,+ authorId: botUserId,+ parentChannelId: channelId,+ serverId: target.serverId,+ body: { content: body.content.text },+ attachmentIds: undefined,+ pendingAttachmentIdsToRebind: body.attachments,+ clientNonce: body.nonce,+ source: "cli",+ })+ if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })+ const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)+ return NextResponse.json({+ state: "sent",+ message,+ threadId: created.thread.id,+ deduped: created.deduped,+ })+ }+++ const replay = await getCommunityMessageReplay({+ db,+ authorId: botUserId,+ channelId,+ clientNonce: body.nonce,+ })+ if (replay) {+ const orderedAttachments = replay.attachments.map((a) => ({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size }))+ const message = await queries.communityAgentInbox.toAgentMessage(db, replay.row, botUserId, orderedAttachments)+ return NextResponse.json({ state: "sent", message, deduped: true })+ }++ const scopeTarget = { channelId }+ const [latestSeq, readState] = await Promise.all([+ withD1Retry(() => queries.communityAgentInbox.getLatestSeqForScope(db, channelId), { route: "community/messages:latest-seq" }),+ withD1Retry(() => queries.communityReadState.getReadState(db, { userId: botUserId, ...scopeTarget }), { route: "community/messages:read-state" }),+ ])+ const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0+ const hasUnread = await withD1Retry(+ () => queries.communityAgentInbox.hasDeliverableUnreadForAgentScope(db, botUserId, channelId, seen),+ { route: "community/messages:has-unread" },+ )+ if (hasUnread) {+ return NextResponse.json({ state: "blocked", reason: "unaligned", unreadCount: Math.max(0, latestSeq - seen), latestSeq })+ }++ if (body.attachments.length > 0) {+ const rows = await withD1Retry(+ () => queries.communityAttachment.findPendingAttachmentsForSender(db, { ids: body.attachments, uploaderId: botUserId, targetId: channelId }),+ { route: "community/messages:attachments" },+ )+ if (rows.length !== body.attachments.length) {+ return NextResponse.json({ error: "attachment not found or not attachable to this target" }, { status: 400 })+ }+ }++ let replyToId: string | undefined+ if (body.replyToSeq !== undefined) {+ const replyTarget = await withD1Retry(+ () => queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.replyToSeq!),+ { route: "community/messages:reply-lookup" },+ )+ if (!replyTarget) {+ return NextResponse.json({ error: `reply target #${body.replyToSeq} not found in ${body.channel}` }, { status: 400 })+ }+ replyToId = replyTarget.id+ }++ const result = await createCommunityMessage({+ db,+ authorId: botUserId,+ target,+ body: { content: body.content.text, replyToId },+ source: "cli",+ expectedSeq: latestSeq,+ attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,+ clientNonce: body.nonce,+ extraStatements: [+ queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),+ ],+ })+ if (!result.ok) {+ if (result.status === 409) {+ const freshLatestSeq = await withD1Retry(+ () => queries.communityAgentInbox.getLatestSeqForScope(db, channelId),+ { route: "community/messages:fresh-latest-seq" },+ )+ return NextResponse.json({ state: "blocked", reason: "unaligned", unreadCount: Math.max(0, freshLatestSeq - seen), latestSeq: freshLatestSeq })+ }+ return NextResponse.json({ error: result.error }, { status: result.status })+ }++ const orderedAttachments = (result.attachments ?? []).map((a) => ({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size }))+ const message = await queries.communityAgentInbox.toAgentMessage(db, result.row, botUserId, orderedAttachments)+ return NextResponse.json({ state: "sent", message, deduped: result.deduped })+}diff --git a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.test.tsnew file mode 100644index 000000000..5d94cbffc--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.test.ts@@ -0,0 +1,153 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const mockGetChannel = vi.fn()+const mockGetChannelForMember = vi.fn()+const mockGetMessageByChannelAndSeq = vi.fn()+const mockResolveTargetForMember = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@/lib/community/resolve-ref", () => ({+ resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),+}))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityChannel: {+ getChannel: (...a: unknown[]) => mockGetChannel(...a),+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ },+ communityMessage: {+ getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),+ },+ },+ }+})++// Dual-actor: crk_ bearer → bot, else human (mirrors the real wrapper).+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ const authz = req?.headers?.get?.("Authorization") ?? ""+ const actor = authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]" }+ return handler(req, { env: { DB: {} }, actor, params })+ },+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { GET } from "./route"++function getReq(headers: Record<string, string> = {}) {+ return new NextRequest("http://localhost/api/community/channels/c1/messages/seq/42", { method: "GET", headers })+}+const ctx = (id = "c1", seq = "42") => ({ params: { id, seq } }) as any++// Bot request: crk_ bearer + optional `?ref=` (the `resolve` placeholder sits+// in the path, the real target is the encoded ref in the query).+function botReq(ref?: string, seq = "42") {+ const q = ref ? `?ref=${encodeURIComponent(ref)}` : ""+ return new NextRequest(`http://localhost/api/community/channels/resolve/messages/seq/${seq}${q}`, {+ method: "GET",+ headers: { Authorization: "Bearer crk_abc" },+ })+}+const ctxResolve = (seq = "42") => ({ params: { id: "resolve", seq } }) as any++describe("GET /api/community/channels/[id]/messages/seq/[seq] — dual-actor seq→id lookup", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text", parentChannelId: null })+ })++ it("resolves a seq to its message id for a member (single-auth-entry via requireMessageSurfaceAccess)", async () => {+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m42" })+ const res = await GET(getReq(), ctx())+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ id: "m42" })+ expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42)+ })++ it("404 not_found when the seq has no message in this channel", async () => {+ mockGetMessageByChannelAndSeq.mockResolvedValue(null)+ const res = await GET(getReq(), ctx())+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "not_found" })+ })++ it("unknown channel → 404 at the mask (before the seq lookup, opaque)", async () => {+ mockGetChannel.mockResolvedValue(null) // getChannel probe → not found+ const res = await GET(getReq(), ctx())+ expect(res.status).toBe(404)+ expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled()+ })++ it("known channel + non-member → 403 (human split preserved)", async () => {+ mockGetChannelForMember.mockResolvedValue(null) // known (getChannel found) but not a member+ const res = await GET(getReq(), ctx())+ expect(res.status).toBe(403)+ expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled()+ })++ it("invalid seq → 400 before any query", async () => {+ const res = await GET(getReq(), ctx("c1", "0"))+ expect(res.status).toBe(400)+ expect(mockGetChannel).not.toHaveBeenCalled()+ })++ // ── bot arm: ref-in-query (`?ref=`), member-scoped resolve → 404, never 403 ──++ it("bot resolves ref+seq via resolveTargetForMember, then the shared mask", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m42" })+ const res = await GET(botReq("/s/general"), ctxResolve())+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ id: "m42" })+ // ref went through the member-scoped resolver, keyed on the BOT userId.+ expect(mockResolveTargetForMember).toHaveBeenCalledWith({}, "bot_1", "/s/general", {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ // then the same channel-scoped seq lookup + shared mask.+ expect(mockGetChannelForMember).toHaveBeenCalledWith({}, "c1", "bot_1")+ })++ it("①-C: bot ref to an UNREACHABLE channel → 404 (member-scoped resolve, NOT a 403 leak)", async () => {+ // resolveTargetForMember's inner-join yields zero rows for a non-member →+ // it returns 404 BEFORE the mask, so the bot never sees the known-but-non-+ // member 403 that would disclose the channel/message exists.+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "channel not found: general" })+ const res = await GET(botReq("/s/general"), ctxResolve())+ expect(res.status).toBe(404)+ expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled()+ // the mask is never reached — the 404 is upstream at resolve.+ expect(mockGetChannel).not.toHaveBeenCalled()+ })++ it("bot ref resolves but seq absent in that channel → 404 (channel-scoped, opaque)", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })+ mockGetMessageByChannelAndSeq.mockResolvedValue(null)+ const res = await GET(botReq("/s/general"), ctxResolve())+ expect(res.status).toBe(404)+ })++ it("bot with no ref falls to the (empty) path id → 400 missing channel id", async () => {+ const res = await GET(botReq(), ctxResolve())+ expect(res.status).toBe(400)+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.tsindex f874acc40..bea69ac02 100644--- a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts@@ -1,23 +1,47 @@import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"+import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"-import { requireChannelMember } from "@/lib/community/permissions"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"+import { resolveTargetForMember } from "@/lib/community/resolve-ref"++// A bot addresses by ref-in-query (`?ref=`); the path `[id]` is then the+// `resolve` placeholder (a ref carries `/` and can't sit in a path segment).+// A human/web caller puts the real channelId in the path. Same one-door input+// as the messages door — id (path) xor ref (query).+const REF_PLACEHOLDER_ID = "resolve"/*** GET /api/community/channels/:id/messages/seq/:seq** Resolve a seq number to its message ID within a channel. Used for message* ref jumping: when the user clicks #123 and that message isn't loaded, we- * need its ID to trigger an anchor fetch.+ * need its ID to trigger an anchor fetch. Also the folded `resolve` bot verb's+ * seq→id lookup.+ *+ * Dual-actor door (route/disc trunk — message-keyed faces). withCommunityActor+ * serves human (session, id-in-path) + bot (crk_, ref-in-query). Two steps,+ * both arms:+ * 1. arrive at a channelId — human: path id; bot: `resolveTargetForMember`+ * (member-scoped inner-join, so an unreachable channel yields ZERO rows →+ * 404 BEFORE the mask). This is why a bot never sees the mask's 403 for a+ * known-but-non-member channel — it 404s here first (①-C uniform+ * existence-mask; the 403 leak 5c newly exposed by opening this route to+ * bot credentials, Blondie/Aigneis #294/#295). The human arm skips this+ * step (it already holds an id), keeping its 403/404 split untouched.+ * 2. `requireMessageSurfaceAccess` — the SINGLE mask both arms share (§3, no+ * standalone requireChannelMember): DM→requireDMAccess (incl block), else+ * requireChannelMember; unknown id → opaque 404. Byte-identical to the+ * pre-5c human path.+ * The seq lookup is channel-scoped (getMessageByChannelAndSeq), so a seq in a+ * channel the caller can't reach never returns another channel's message.** Returns: { id: string } | { error: "not_found" }*/-export const GET = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id+export const GET = withCommunityActor(async (req: NextRequest, ctx) => {const seqStr = ctx.params?.seq- if (typeof channelId !== "string" || typeof seqStr !== "string") {+ if (typeof seqStr !== "string") {return writeJSON({ error: "invalid_params" }, 400)}@@ -27,10 +51,33 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {}const db = getDb(ctx.env.DB)+ const userId = ctx.actor.userId++ // Step 1 — channelId. Bot: ref-in-query, member-scoped resolve (unreachable →+ // 404, never a leaking 403). Human: id-in-path, unchanged. NO create-if-+ // missing — a seq lookup is pure addressing (resolve≠create).+ let channelId: string+ const refParam = req.nextUrl.searchParams.get("ref")+ if (ctx.actor.kind === "bot" && refParam) {+ const resolved = await resolveTargetForMember(db, userId, refParam, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return writeError(resolved.message, resolved.error)+ channelId = resolved.channelId+ } else {+ const pathId = ctx.params?.id+ if (typeof pathId !== "string" || !pathId || pathId === REF_PLACEHOLDER_ID) {+ return writeError("missing channel id", 400)+ }+ channelId = pathId+ }- // Permission check: user must have access to this channel- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)+ // Step 2 — the single mask (§3). DM block + opaque-404 folded in; the human+ // arm's known-but-non-member 403 is preserved.+ const access = await requireMessageSurfaceAccess(db, channelId, userId)+ if (!access.ok) return writeError(access.error, access.status)const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { channelId }, seq)if (!message) {diff --git a/src/web/src/app/api/community/channels/[id]/messages/tags/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/tags/route.test.tsnew file mode 100644index 000000000..780d68e24--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/messages/tags/route.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })) }))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockRequireChannelAccess = vi.fn()+const mockListDistinctTagsForChannel = vi.fn()++vi.mock("@/lib/community/permissions", () => ({+ requireChannelAccess: (...args: unknown[]) => mockRequireChannelAccess(...args),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMessageTag: {+ ...actual.queries.communityMessageTag,+ listDistinctTagsForChannel: (...args: unknown[]) => mockListDistinctTagsForChannel(...args),+ },+ },+ }+})+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any, ctx: any) => handler(req, {+ env: { DB: {} },+ userId: "user_1",+ params: await ctx.params,+ }),+}))++import { GET } from "./route"++const ctx = { params: Promise.resolve({ id: "forum_1" }) } as any++describe("GET /api/community/channels/[id]/messages/tags", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockRequireChannelAccess.mockResolvedValue({ ok: true })+ mockListDistinctTagsForChannel.mockResolvedValue([])+ })++ it("returns an empty message-tag vocabulary for an accessible empty channel", async () => {+ const response = await GET(new Request("http://localhost/api/community/channels/forum_1/messages/tags"), ctx)+ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ tags: [] })+ expect(mockRequireChannelAccess).toHaveBeenCalledWith(expect.anything(), "forum_1", "user_1")+ expect(mockListDistinctTagsForChannel).toHaveBeenCalledWith(expect.anything(), "forum_1")+ })++ it("returns sorted distinct tags from the scoped message resource", async () => {+ mockListDistinctTagsForChannel.mockResolvedValue(["bug", "feature"])+ const response = await GET(new Request("http://localhost/api/community/channels/forum_1/messages/tags"), ctx)+ expect(await response.json()).toEqual({ tags: ["bug", "feature"] })+ })++ it("preserves private-channel access denial without querying tag rows", async () => {+ mockRequireChannelAccess.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })+ const response = await GET(new Request("http://localhost/api/community/channels/forum_1/messages/tags"), ctx)+ expect(response.status).toBe(403)+ expect(mockListDistinctTagsForChannel).not.toHaveBeenCalled()+ })++ it("preserves a missing-channel 404 without querying tag rows", async () => {+ mockRequireChannelAccess.mockResolvedValue({ ok: false, error: "channel not found", status: 404 })+ const response = await GET(new Request("http://localhost/api/community/channels/missing/messages/tags"), ctx)+ expect(response.status).toBe(404)+ expect(mockListDistinctTagsForChannel).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/messages/tags/route.ts b/src/web/src/app/api/community/channels/[id]/messages/tags/route.tsnew file mode 100644index 000000000..8a30e4ef9--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/messages/tags/route.ts@@ -0,0 +1,16 @@+import { queries } from "@alook/shared"++import { getDb } from "@/lib/db"+import { requireChannelAccess } from "@/lib/community/permissions"+import { withAuth } from "@/lib/middleware/auth"+import { writeError, writeJSON } from "@/lib/middleware/helpers"++export const GET = withAuth(async (_req, ctx) => {+ const channelId = ctx.params?.id+ if (!channelId) return writeError("missing channel id", 400)+ const db = getDb(ctx.env.DB)+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ const tags = await queries.communityMessageTag.listDistinctTagsForChannel(db, channelId)+ return writeJSON({ tags })+})diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.tsindex 4217a7f6d..c096372b5 100644--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts@@ -2,13 +2,13 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries, isThread, isForumPost } from "@alook/shared"+import { queries, isThread } from "@alook/shared"import { requireChannelAccess } from "@/lib/community/permissions"/**- * Leave a thread/forum-post (remove a participant row). The viewer may remove- * THEMSELVES; the unit creator may remove anyone. Thread/forum-post only. A- * later mention/speak re-adds a user who left.+ * Leave a thread (remove a participant row). The viewer may remove+ * THEMSELVES; the unit creator may remove anyone. Thread only. A later+ * mention/speak re-adds a user who left.** (Muting is NOT here — that's the outer channel-header notification level,* per-layer, same control a channel uses. Participation is add/leave only.)@@ -22,12 +22,12 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const access = await requireChannelAccess(db, channelId, ctx.userId)if (!access.ok) return writeError(access.error, access.status)const type = access.value.channel.type- if (!isThread(type) && !isForumPost(type)) {- return writeError("not a thread or forum post", 400)+ if (!isThread(type)) {+ return writeError("not a thread", 400)}// Removing another participant is the UNIT creator's call — the person who- // started the thread/post (`channel.creatorId`), NOT `access.value.isCreator`,+ // started the thread (`channel.creatorId`), NOT `access.value.isCreator`,// which resolves to the parent channel/forum's creator (the access anchor).// Any participant may always remove themselves.const isSelf = targetUserId === ctx.userIddiff --git a/src/web/src/app/api/community/channels/[id]/participants/route.ts b/src/web/src/app/api/community/channels/[id]/participants/route.tsindex d943144b2..c5510e077 100644--- a/src/web/src/app/api/community/channels/[id]/participants/route.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/route.ts@@ -2,18 +2,18 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries, WS_EVENTS, isThread, isForumPost, PARTICIPANT_SOURCE } from "@alook/shared"+import { queries, WS_EVENTS, isThread, PARTICIPANT_SOURCE } from "@alook/shared"import { broadcastToUserSafe } from "@/lib/community/fanout"import { requireChannelAccess } from "@/lib/community/permissions"// GET (the participant-list READ) was retired: the unified `/members` endpoint// now serves the notify set in the canonical `MappedMember` shape, and the-// post/thread panel reads that. Only the participant WRITE endpoints remain-// here (POST add + DELETE in `[userId]/route.ts`).+// thread panel reads that. Only the participant WRITE endpoints remain here+// (POST add + DELETE in `[userId]/route.ts`)./**- * Add a participant to a thread/forum-post — the "add from channel" flow. ANY- * current viewer with access may add (passing `requireChannelAccess` means the+ * Add a participant to a thread — the "add from channel" flow. ANY current+ * viewer with access may add (passing `requireChannelAccess` means the* caller can see the unit — i.e. is a member of the parent channel/forum).* Other joins happen automatically via mention/speak. The target must be a* member of the PARENT's access audience (you can only pull in people who can@@ -27,8 +27,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const access = await requireChannelAccess(db, channelId, ctx.userId)if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channel- if (!isThread(channel.type) && !isForumPost(channel.type)) {- return writeError("not a thread or forum post", 400)+ if (!isThread(channel.type)) {+ return writeError("not a thread", 400)}let body: { userId?: string }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.tsindex 36e7269dc..23fea9678 100644--- 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.ts@@ -79,11 +79,11 @@ describe("DELETE /api/community/channels/[id]/pins/[messageId]", () => {expect(mockUnpinMessage).not.toHaveBeenCalled();});- it("returns 400 in a forum top-level (nothing to unpin)", async () => {+ it("unpins a message in a forum top-level (phase2 forum≡thread write-guard reversal — forum is now a message-bearing surface)", async () => {mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" });const res = await DELETE(delReq(), ctx);- expect(res.status).toBe(400);- expect(mockUnpinMessage).not.toHaveBeenCalled();+ expect(res.status).toBe(204);+ expect(mockUnpinMessage).toHaveBeenCalledWith(expect.anything(), { channelId: "c1", messageId: "m1" });});it("returns 400 in a DM (governance model does not fit)", async () => {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 e9351912d..5c7e582ca 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@@ -130,11 +130,12 @@ 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 () => {+ it("pins a message in a forum top-level (phase2 forum≡thread write-guard reversal — forum is now a message-bearing surface)", async () => {mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" });+ mockPinMessage.mockResolvedValue({ channelId: "c1", messageId: "m1", pinnedBy: "u1" });const res = await POST(postReq("m1"), ctx);- expect(res.status).toBe(400);- expect(mockPinMessage).not.toHaveBeenCalled();+ expect(res.status).toBe(201);+ expect(mockPinMessage).toHaveBeenCalled();});it("returns 400 when pinning in a DM (governance model does not fit)", async () => {diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.tsdeleted file mode 100644index 214e97311..000000000--- a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts+++ /dev/null@@ -1,403 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockGetChannelForMember = vi.fn()-const mockResolveChannelAccessContext = vi.fn()-const mockCreateChannel = vi.fn()-const mockDedupeChildChannelSlug = vi.fn(async (_db: unknown, _parent: unknown, slug: string) => slug)-const mockCreateMessage = vi.fn()-const mockGetMessage = vi.fn()-const mockGetUserSelf = vi.fn()-const mockGetUserInternal = vi.fn()-const mockFanOutToChannel = vi.fn()-const mockListChildChannels = vi.fn()-const mockGetUsersByIds = vi.fn()-const mockGetFirstMessageByChannelIds = vi.fn()-const mockListParticipantsForChannels = vi.fn(async () => [] as unknown[])--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--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: {- communityChannel: {- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),- createChannel: (...a: unknown[]) => mockCreateChannel(...a),- dedupeChildChannelSlug: (...a: unknown[]) => mockDedupeChildChannelSlug(...a),- listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),- // createCommunityMessage's private-channel scoping guard is only hit- // when there are mentions; the happy-path posts have none, so these- // return public/empty.- isChannelPrivate: vi.fn(async () => false),- },- communityMessage: {- createMessage: (...a: unknown[]) => mockCreateMessage(...a),- getMessage: (...a: unknown[]) => mockGetMessage(...a),- getFirstMessageByChannelIds: (...a: unknown[]) => mockGetFirstMessageByChannelIds(...a),- },- communityMember: {- listMembers: vi.fn(async () => []),- listMemberUserIds: vi.fn(async () => []),- },- communityMention: {- createMentions: vi.fn(async () => []),- },- communityAttachment: {- createAttachment: vi.fn(async (_db: unknown, args: Record<string, unknown>) => ({- id: "att_1",- filename: args.filename,- r2Key: args.r2Key,- contentType: args.contentType,- size: args.size,- width: args.width,- height: args.height,- })),- listByMessageIds: vi.fn(async () => []),- unreserveAttachments: vi.fn(async () => {}),- },- communityThread: {- addThreadParticipants: vi.fn(async () => {}),- listParticipantsForChannels: (...a: unknown[]) => mockListParticipantsForChannels(...a),- },- user: {- getUserSelf: (...a: unknown[]) => mockGetUserSelf(...a),- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a),- },- },- }-})--vi.mock("@/lib/community/fanout", () => ({- fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),- fanOutToDM: vi.fn(async () => {}),- resolveChannelRecipients: vi.fn(async () => [] as string[]),-}))--vi.mock("@/lib/community/notify", () => ({- dispatchMessageNotify: vi.fn(async () => {}),-}))--// createCommunityMessage's non-fanout side effects — stub so the pipeline runs.-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn(async () => {}),-}))-vi.mock("@/lib/community/audit", () => ({- logAudit: vi.fn(),- COMMUNITY_AUDIT_ACTIONS: { MESSAGE_AUTHORED_AS_BOT: "message_authored_as_bot" },-}))--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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { GET, POST } from "./route"--const ctx = { params: { id: "ch1" } } as any--function postReq(body: unknown) {- return new NextRequest("http://localhost/api/community/channels/ch1/posts", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- })-}--describe("POST /api/community/channels/[id]/posts — name normalization", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetChannelForMember.mockResolvedValue({ id: "ch1", serverId: "s1", type: "forum", tags: [] })- mockCreateMessage.mockResolvedValue({ id: "m1", createdAt: "2026-07-02T00:00:00.000Z" })- // createCommunityMessage re-fetches the row via getMessage after insert.- mockGetMessage.mockResolvedValue({- id: "m1",- authorId: "u1",- authorName: "Alice",- authorImage: null,- content: "hello",- type: "default",- mentionType: null,- replyToId: null,- embeds: null,- channelId: "post1",- dmConversationId: null,- seq: 1,- createdAt: "2026-07-02T00:00:00.000Z",- })- mockGetUserSelf.mockResolvedValue({ id: "u1", name: "Alice", image: null })- mockGetUserInternal.mockResolvedValue({ id: "u1", name: "Alice", isBot: false })- mockFanOutToChannel.mockResolvedValue(undefined)- })-- it("normalizes a spaced post title via slugify before creating the post channel", async () => {- mockCreateChannel.mockResolvedValue({- id: "post1",- name: "My-thoughts-on-this!",- createdAt: "2026-07-02T00:00:00.000Z",- })-- const res = await POST(postReq({ name: "My thoughts on this!", content: "hello" }), ctx)- expect(res.status).toBe(201)- // The addressing name is the slug; display_title captures the PRE-slugify- // original verbatim (B4b) — the two MUST differ here, proving capture happens- // before slugify (a slugified display_title would be worthless).- expect(mockCreateChannel).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ name: "My-thoughts-on-this!", displayTitle: "My thoughts on this!" }),- )- })-- it("returns 400 (and never calls createChannel) when the post title is all disallowed characters", async () => {- const res = await POST(postReq({ name: "///", content: "hello" }), ctx)- expect(res.status).toBe(400)- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("dedupes the slug within the forum before creating (so the name anchor is unique)", async () => {- // The forum already has an "ideas" post → dedupe yields "ideas-2".- mockDedupeChildChannelSlug.mockResolvedValueOnce("ideas-2")- mockCreateChannel.mockResolvedValue({- id: "post1",- name: "ideas-2",- createdAt: "2026-07-02T00:00:00.000Z",- })- const res = await POST(postReq({ name: "ideas", content: "hello" }), ctx)- expect(res.status).toBe(201)- // dedupe is called with the slugified base name under this forum...- expect(mockDedupeChildChannelSlug).toHaveBeenCalledWith(expect.anything(), "ch1", "ideas")- // ...and the DEDUPED name is what gets persisted.- expect(mockCreateChannel).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ name: "ideas-2" }),- )- const body = await res.json()- expect(body.post.name).toBe("ideas-2")- })-- it("returns messageCount 0 in the response (body IS the first message, not a reply)", async () => {- mockCreateChannel.mockResolvedValue({- id: "post1",- name: "solo",- createdAt: "2026-07-02T00:00:00.000Z",- })- const res = await POST(postReq({ name: "solo", content: "hi" }), ctx)- expect(res.status).toBe(201)- const body = await res.json()- expect(body.post.messageCount).toBe(0)- })-})--describe("POST /api/community/channels/[id]/posts — content + attachments contract", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetChannelForMember.mockResolvedValue({ id: "ch1", serverId: "s1", type: "forum", tags: [] })- mockCreateMessage.mockResolvedValue({ id: "m1", createdAt: "2026-07-02T00:00:00.000Z" })- mockGetMessage.mockResolvedValue({- id: "m1",- authorId: "u1",- authorName: "Alice",- authorImage: null,- content: "",- type: "default",- mentionType: null,- replyToId: null,- embeds: null,- channelId: "post1",- dmConversationId: null,- seq: 1,- createdAt: "2026-07-02T00:00:00.000Z",- })- mockGetUserSelf.mockResolvedValue({ id: "u1", name: "Alice", image: null })- mockGetUserInternal.mockResolvedValue({ id: "u1", name: "Alice", isBot: false })- mockFanOutToChannel.mockResolvedValue(undefined)- mockCreateChannel.mockResolvedValue({- id: "post1",- name: "my-post",- createdAt: "2026-07-02T00:00:00.000Z",- })- })-- it("empty content + zero attachments returns 400", async () => {- const res = await POST(postReq({ name: "my post", content: "" }), ctx)- expect(res.status).toBe(400)- const body = await res.json()- expect(body.error).toBe("post is empty")- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("empty content + one valid attachment creates the post (attachments-only path)", async () => {- const attachments = [- { url: "/api/community/media/abc.png", filename: "abc.png", contentType: "image/png", size: 100, width: 10, height: 10 },- ]- const res = await POST(postReq({ name: "img", content: "", attachments }), ctx)- expect(res.status).toBe(201)- // Route passes attachments through to createCommunityMessage.- expect(mockCreateChannel).toHaveBeenCalled()- })-- it("threads mentionType through to createCommunityMessage / first message", async () => {- const res = await POST(- postReq({ name: "heads up", content: "Heads up @everyone", mentionType: "everyone" }),- ctx,- )- expect(res.status).toBe(201)- // The mock records the createMessage call — the pipeline lifts mentionType- // out of `body` and lands it on the row.- const call = mockCreateMessage.mock.calls[0]?.[1]- expect(call?.mentionType).toBe("everyone")- })-})--describe("GET /api/community/channels/[id]/posts — authorId", () => {- beforeEach(() => {- vi.clearAllMocks()- // GET now uses requireChannelAccess. Public forum → isPrivate:false so the- // per-post visibility filter is skipped.- mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "ch1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "u1", tags: [] },- anchor: { id: "ch1", serverId: "s1", parentChannelId: null, creatorId: "u1" },- role: "member", isPrivate: false, isChannelMember: false, isCreator: true,- })- mockGetFirstMessageByChannelIds.mockResolvedValue([])- })-- function getReq() {- return new NextRequest("http://localhost/api/community/channels/ch1/posts")- }-- it("carries each post's creatorId through as authorId", async () => {- mockListChildChannels.mockResolvedValue([- { id: "post1", name: "First", messageCount: 2, lastMessageAt: "2026-07-02T00:00:00.000Z", createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_alice", tags: [] },- ])- mockGetUsersByIds.mockResolvedValue([{ id: "u_alice", name: "Alice", image: null }])-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)- const body = await res.json()- expect(body.posts).toHaveLength(1)- expect(body.posts[0].authorId).toBe("u_alice")- })-- it("falls back to an empty authorId when the creator was deleted (creatorId null)", async () => {- mockListChildChannels.mockResolvedValue([- { id: "post1", name: "Orphan", messageCount: 0, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: null, tags: [] },- ])- mockGetUsersByIds.mockResolvedValue([])-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)- const body = await res.json()- expect(body.posts[0].authorId).toBe("")- })-- it("groups each post's participants onto its card, ordered by addedAt (creator first)", async () => {- mockListChildChannels.mockResolvedValue([- { id: "post1", name: "Multi", messageCount: 3, lastMessageAt: "2026-07-02T00:00:00.000Z", createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_alice", tags: [] },- { id: "post2", name: "Solo", messageCount: 1, lastMessageAt: "2026-07-02T00:00:00.000Z", createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_bob", tags: [] },- ])- mockGetUsersByIds.mockResolvedValue([- { id: "u_alice", name: "Alice", image: null },- { id: "u_bob", name: "Bob", image: null },- ])- // Rows arrive unordered; the route sorts by addedAt so the creator (earliest- // "spoke") leads.- mockListParticipantsForChannels.mockResolvedValue([- { channelId: "post1", userId: "u_carol", addedAt: "2026-07-01T00:01:00.000Z", userName: "Carol", userImage: null },- { channelId: "post1", userId: "u_alice", addedAt: "2026-07-01T00:00:00.000Z", userName: "Alice", userImage: null },- { channelId: "post2", userId: "u_bob", addedAt: "2026-07-01T00:00:00.000Z", userName: "Bob", userImage: null },- ])-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)- const body = await res.json()- const multi = body.posts.find((p: { id: string }) => p.id === "post1")- const solo = body.posts.find((p: { id: string }) => p.id === "post2")- expect(multi.participants.map((m: { id: string }) => m.id)).toEqual(["u_alice", "u_carol"])- expect(solo.participants.map((m: { id: string }) => m.id)).toEqual(["u_bob"])- })-})--describe("GET /api/community/channels/[id]/posts — private-forum post visibility", () => {- const posts = [- { id: "p_mine", name: "Mine", messageCount: 1, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_other", tags: [] },- { id: "p_hidden", name: "Secret", messageCount: 1, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_other", tags: [] },- { id: "p_created", name: "By me", messageCount: 1, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u1", tags: [] },- ]-- beforeEach(() => {- vi.clearAllMocks()- mockGetFirstMessageByChannelIds.mockResolvedValue([])- mockGetUsersByIds.mockResolvedValue([])- mockListChildChannels.mockResolvedValue(posts)- })-- function getReq() {- return new NextRequest("http://localhost/api/community/channels/ch1/posts")- }-- it("a forum member sees ALL posts (unified model: posts inherit forum access)", async () => {- // Reaching here means requireChannelAccess already granted forum access; a- // forum member sees every post under it (no per-post filter). A non-member- // 403s up front (next test).- mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "ch1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "owner", tags: [] },- anchor: { id: "ch1", serverId: "s1", parentChannelId: null, creatorId: "owner" },- role: "member", isPrivate: true, isChannelMember: true, isCreator: false,- })-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)- const body = await res.json()- const ids = body.posts.map((p: { id: string }) => p.id).sort()- expect(ids).toEqual(["p_created", "p_hidden", "p_mine"]) // all posts visible- })-- it("server admin WITH forum access sees every post", async () => {- mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "ch1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "owner", tags: [] },- anchor: { id: "ch1", serverId: "s1", parentChannelId: null, creatorId: "owner" },- role: "admin", isPrivate: true, isChannelMember: true, isCreator: false,- })-- const res = await GET(getReq(), ctx)- const body = await res.json()- expect(body.posts).toHaveLength(3)- })-- it("non-member is forbidden up front (no post leak)", async () => {- mockResolveChannelAccessContext.mockResolvedValue(null)- const res = await GET(getReq(), ctx)- expect(res.status).toBe(403)- })-- it("forum creator sees every post (like any forum member)", async () => {- mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "ch1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "u1", tags: [] },- anchor: { id: "ch1", serverId: "s1", parentChannelId: null, creatorId: "u1" },- role: "member", isPrivate: true, isChannelMember: true, isCreator: true,- })- const res = await GET(getReq(), ctx)- const body = await res.json()- const ids = body.posts.map((p: { id: string }) => p.id).sort()- expect(ids).toEqual(["p_created", "p_hidden", "p_mine"]) // all posts, not just their own- })-})diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.tsdeleted file mode 100644index 57c24d892..000000000--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts+++ /dev/null@@ -1,179 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import {- queries,- MESSAGE_PREVIEW_LENGTH,- WS_EVENTS,-} from "@alook/shared"-import { fanOutToChannel } from "@/lib/community/fanout"-import { requireChannelMember, requireChannelAccess } from "@/lib/community/permissions"-import { avatarInitial } from "@/lib/community/avatar"-import { createForumPost } from "@/lib/community/create-forum-post"--export const GET = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)-- const db = getDb(ctx.env.DB)-- const auth = await requireChannelAccess(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- const channel = auth.value.channel-- if (channel.type !== "forum") {- return writeError("channel is not a forum", 400)- }-- const tag = req.nextUrl.searchParams.get("tag")-- let childChannels = await queries.communityChannel.listChildChannels(db, channelId, {- archived: false,- type: "forum_post",- })-- if (tag) {- childChannels = childChannels.filter((ch) => ch.tags.includes(tag))- }-- // Unified model: a forum's posts INHERIT the forum's access (a post is not its- // own access unit — like a thread inherits its channel). Reaching here means- // `requireChannelAccess` already granted the viewer access to the forum (a- // private forum 403s a non-member up front), so they see ALL of its posts. No- // per-post membership filter.-- // Batch-fetch all creators in one query- const creatorIds = [...new Set(childChannels.map((t) => t.creatorId).filter(Boolean) as string[])]- const creators = creatorIds.length > 0 ? await queries.user.getUsersByIds(db, creatorIds) : []- const creatorMap = new Map(creators.map((u) => [u.id, u]))-- // Batch-fetch first message for each post channel- const postChannelIds = childChannels.map((t) => t.id)- const firstMessages = postChannelIds.length > 0- ? await queries.communityMessage.getFirstMessageByChannelIds(db, postChannelIds)- : []- const previewMap = new Map(firstMessages.map((m) => [m.channelId, m.content]))-- // Batch-fetch each post's participant (notify) set for the card AvatarGroup.- // A post's participants are the people actually involved (creator + whoever- // spoke / was mentioned / was added), the same set fan-out notifies. Grouped- // by channel id and ordered by `addedAt` so the creator (earliest "spoke"- // row) leads.- const participantRows = postChannelIds.length > 0- ? await queries.communityThread.listParticipantsForChannels(db, postChannelIds)- : []- const participantsByPost = new Map<string, { id: string; name: string; avatar: string }[]>()- for (const r of [...participantRows].sort((a, b) => a.addedAt.localeCompare(b.addedAt))) {- const list = participantsByPost.get(r.channelId) ?? []- list.push({ id: r.userId, name: r.userName ?? "", avatar: r.userImage ?? avatarInitial(r.userName ?? "") })- participantsByPost.set(r.channelId, list)- }-- const posts = childChannels.map((t) => {- const creator = t.creatorId ? creatorMap.get(t.creatorId) : null- // creator can be null if the user was deleted (channel.creatorId has ON DELETE SET NULL).- const authorName = creator ? creator.name : ""- const authorAvatar = creator?.image ?? avatarInitial(authorName)- const preview = (previewMap.get(t.id) ?? "").slice(0, MESSAGE_PREVIEW_LENGTH)- return {- id: t.id,- name: t.name,- // Excludes the body message — the body IS the first message; the badge- // shows reply count, not total message count.- messageCount: Math.max(0, (t.messageCount ?? 0) - 1),- lastMessageAt: t.lastMessageAt ?? t.createdAt,- parent: { authorName, text: preview },- authorId: t.creatorId ?? "",- authorAvatar,- tags: t.tags ?? [],- preview,- participants: participantsByPost.get(t.id) ?? [],- }- })-- return writeJSON({ posts })-})--export const POST = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)-- const db = getDb(ctx.env.DB)-- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- const channel = auth.value-- if (channel.type !== "forum") {- return writeError("channel is not a forum", 400)- }-- let body: { name?: string; content?: string; attachments?: unknown; mentionType?: unknown }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- if (!body.name || typeof body.name !== "string") {- return writeError("name is required", 400)- }- const content = typeof body.content === "string" ? body.content : ""-- // Create via the shared core (B4 creation-axis convergence): slug dedupe +- // forum_post child create + first-message-as-body, with the collision- // contract dispatched on the forum_post `creation` trait (pure-create:- // bump-and-retry, never merge). The bot verb (`createPost` / `alook message- // post`) calls the SAME `createForumPost`, so the two can't drift on how a- // post is created. This route keeps its own response projection + the human- // CHILD_CHANNEL_CREATE fan-out below.- const result = await createForumPost({- db,- forumChannelId: channelId,- serverId: channel.serverId!,- authorId: ctx.userId,- rawTitle: body.name,- content,- attachments: body.attachments,- mentionType: body.mentionType,- })- if (!result.ok) return writeError(result.error, result.status)- const postChannel = result.postChannel- const message = result.messageRow-- // Resolve author info for response- const creator = await queries.user.getUserSelf(db, ctx.userId)- const authorName = creator ? creator.name : ""- const authorAvatar = creator?.image ?? avatarInitial(authorName)-- fanOutToChannel(channelId, {- type: WS_EVENTS.CHILD_CHANNEL_CREATE,- parentChannelId: channelId,- channel: {- id: postChannel.id,- name: postChannel.name,- type: "forum_post" as const,- creatorId: ctx.userId,- createdAt: postChannel.createdAt,- },- })-- return writeJSON({- post: {- id: postChannel.id,- name: postChannel.name,- // Excludes the body message — the body IS the first message; the badge- // shows reply count, so a freshly created post reads 0.- messageCount: 0,- lastMessageAt: message.createdAt,- parent: { authorName, text: content.slice(0, MESSAGE_PREVIEW_LENGTH) },- authorId: ctx.userId,- authorAvatar,- tags: [],- preview: content.slice(0, MESSAGE_PREVIEW_LENGTH),- // A fresh post's only participant is its creator (just enrolled above).- participants: [{ id: ctx.userId, name: authorName, avatar: authorAvatar }],- },- }, 201)-})diff --git a/src/web/src/app/api/community/channels/[id]/read-state/route.ts b/src/web/src/app/api/community/channels/[id]/read-state/route.tsindex 3a0a710ae..c19662577 100644--- a/src/web/src/app/api/community/channels/[id]/read-state/route.ts+++ b/src/web/src/app/api/community/channels/[id]/read-state/route.ts@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries, withD1Retry } from "@alook/shared"-import { requireChannelMember } from "@/lib/community/permissions"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"/*** GET /api/community/channels/:id/read-state@@ -14,10 +14,12 @@ import { requireChannelMember } from "@/lib/community/permissions"* channel — the caller treats that as "everything is new, but no divider* (start at the bottom)", matching common chat-app first-visit UX.*- * Contract mirrors the sibling `read` route: 404 for unknown channels, 403- * for non-members. The two-step check preserves that ordering (unknown →- * 404, known-but-not-a-member → 403); `requireChannelMember` alone collapses- * both into 403.+ * Access via the unified id-in-path gate: 404 for unknown, 403 for non-members+ * (the human split, preserved) — and, when the id is a DM, the DM block gate+ * runs too. That block check is why this route moved off the bare+ * `requireChannelMember`: a blocked-but-still-DM-member could otherwise read a+ * DM's read-state through this channel route (the incidental P0 the trunk+ * closes; the old path only ran the access-member check, never the block).*/export const GET = withAuth(async (_req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -25,9 +27,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return writeError("channel not found", 404)- const auth = await requireChannelMember(db, channelId, ctx.userId)+ const auth = await requireMessageSurfaceAccess(db, channelId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)// Wrap in `withD1Retry` on the server so the client can keep `retry: 1`diff --git a/src/web/src/app/api/community/channels/[id]/read/route.test.ts b/src/web/src/app/api/community/channels/[id]/read/route.test.tsindex 01d1a7354..562dcf7a4 100644--- a/src/web/src/app/api/community/channels/[id]/read/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/read/route.test.ts@@ -140,6 +140,34 @@ describe("PUT /api/community/channels/[id]/read", () => {expect(mockBatch).toHaveBeenCalledTimes(1)})+ it("retries a transient BUSY from the atomic batch with the same monotonic target", async () => {+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })+ mockGetLatestMessage.mockResolvedValue({+ id: "m_latest",+ createdAt: "2026-07-05T10:00:00.000Z",+ seq: 42,+ })+ mockBatch+ .mockRejectedValueOnce(new Error("SQLITE_BUSY: database is locked"))+ .mockResolvedValueOnce(undefined)++ const res = await PUT(putReq(), { params: { id: "c1" } } as any)++ expect(res.status).toBe(200)+ expect(mockBatch).toHaveBeenCalledTimes(2)+ expect(mockMarkReadToMessageBuilder).toHaveBeenNthCalledWith(1, expect.anything(), {+ userId: "u1",+ channelId: "c1",+ message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z", seq: 42 },+ })+ expect(mockMarkReadToMessageBuilder).toHaveBeenNthCalledWith(2, expect.anything(), {+ userId: "u1",+ channelId: "c1",+ message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z", seq: 42 },+ })+ })+it("returns 400 when the channel id is missing", async () => {const res = await PUT(putReq(), { params: {} } as any)expect(res.status).toBe(400)diff --git a/src/web/src/app/api/community/channels/[id]/read/route.ts b/src/web/src/app/api/community/channels/[id]/read/route.tsindex f0d7ad3cd..f1c77fc59 100644--- a/src/web/src/app/api/community/channels/[id]/read/route.ts+++ b/src/web/src/app/api/community/channels/[id]/read/route.ts@@ -2,8 +2,8 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { requireChannelMember } from "@/lib/community/permissions"+import { queries, withD1Retry } from "@alook/shared"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"/*** PUT /api/community/channels/:id/read@@ -33,13 +33,15 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- // Two-step check preserves the 404-vs-403 contract that sibling channel- // routes (pins, threads, PATCH/DELETE) also honor: unknown channel → 404,- // known channel + non-member → 403. `requireChannelMember` alone collapses- // both into 403 because the JOIN can't tell the difference.- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return writeError("channel not found", 404)- const auth = await requireChannelMember(db, channelId, ctx.userId)+ // Unified id-in-path access gate: preserves the 404-vs-403 human split+ // (unknown → 404, known non-member → 403) AND, for a DM id, runs the DM block+ // gate — closing the incidental P0 where a blocked-but-still-DM-member could+ // mark a DM read through this bare-channel route (the old path ran only the+ // access-member check, never the block).+ const auth = await withD1Retry(+ () => requireMessageSurfaceAccess(db, channelId, ctx.userId),+ { route: "community/channel-read:access" }+ )if (!auth.ok) return writeError(auth.error, auth.status)// Parse the body — best-effort. An empty body is legal (mass mark-read).@@ -62,7 +64,10 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {// to a real message — that's the read-state invariant.let target: { id: string; createdAt: string; seq: number } | nullif (lastReadMessageId) {- const msg = await queries.communityMessage.getMessage(db, lastReadMessageId)+ const msg = await withD1Retry(+ () => queries.communityMessage.getMessage(db, lastReadMessageId),+ { route: "community/channel-read:message" }+ )if (!msg) return writeError("message not found", 404)// Scope check — a message from another channel MUST NOT advance THIS// channel's watermark.@@ -71,7 +76,10 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {}target = { id: msg.id, createdAt: msg.createdAt, seq: msg.seq }} else {- target = await queries.communityMessage.getLatestMessage(db, { channelId })+ target = await withD1Retry(+ () => queries.communityMessage.getLatestMessage(db, { channelId }),+ { route: "community/channel-read:latest" }+ )// Empty channel: no row can be written under the invariant. Nothing to// clear either (mentions/for-you require messages to exist first), so// short-circuit with a successful no-op.@@ -81,14 +89,17 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {// Fire both writes in one D1 batch so partial failure can't leave the// inbox inconsistent (mark-read succeeded but the mention clear didn't, or// vice versa). D1 batches are atomic per SQLite guarantees.- await db.batch([- queries.communityReadState.markReadToMessageBuilder(db, {- userId: ctx.userId,- channelId,- message: target,- }),- queries.communityMention.markChannelMentionsReadBuilder(db, ctx.userId, channelId),- ])+ await withD1Retry(+ () => db.batch([+ queries.communityReadState.markReadToMessageBuilder(db, {+ userId: ctx.userId,+ channelId,+ message: target,+ }),+ queries.communityMention.markChannelMentionsReadBuilder(db, ctx.userId, channelId),+ ]),+ { route: "community/channel-read:commit" }+ )return writeJSON({ ok: true })})diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.tsindex 5325e276e..9d44830ad 100644--- a/src/web/src/app/api/community/channels/[id]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts@@ -6,6 +6,9 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockResolveChannelAccessContext = vi.fn()+const mockGetChannel = vi.fn()+const mockGetChannelForMember = vi.fn()+const mockGetChannelType = vi.fn()const mockIsChannelPrivate = vi.fn(() => false)const mockGetCategory = vi.fn()const mockUpdateChannel = vi.fn()@@ -25,6 +28,9 @@ vi.mock("@alook/shared", async () => {queries: {communityChannel: {resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),+ getChannel: (...a: unknown[]) => mockGetChannel(...a),+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ getChannelType: (...a: unknown[]) => mockGetChannelType(...a),isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),updateChannel: (...a: unknown[]) => mockUpdateChannel(...a),deleteChannel: (...a: unknown[]) => mockDeleteChannel(...a),@@ -60,7 +66,7 @@ vi.mock("@/lib/middleware/helpers", () => {}})-import { PATCH, DELETE } from "./route"+import { GET, PATCH, DELETE } from "./route"const ctx = { params: { id: "c1" } } as anyfunction patchReq(body: unknown) {@@ -118,6 +124,49 @@ function accessCtx(over: Partial<{}}+function getReq() {+ return new NextRequest("http://localhost/api/community/channels/c1", { method: "GET" })+}++// GET is the canonical channel-meta reader (folds the old threads/[id] GET —+// the thread-view opener + child-channel bootstrap that page.tsx:473 read).+// Two-step probe: unknown channel → 404, known channel + non-member → 403.+describe("GET /channels/[id] — channel meta", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it("returns the channel row when the caller is a member", async () => {+ const channel = { id: "c1", serverId: "s1", type: "thread", parentChannelId: "p1", parentMessageId: "m1", creatorId: "u1" }+ mockGetChannel.mockResolvedValue(channel)+ mockGetChannelForMember.mockResolvedValue(channel)+ const res = await GET(getReq(), { params: { id: "c1" } } as any)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual(channel)+ })++ it("returns 400 when the id is missing", async () => {+ const res = await GET(getReq(), { params: {} } as any)+ expect(res.status).toBe(400)+ expect(mockGetChannel).not.toHaveBeenCalled()+ expect(mockGetChannelForMember).not.toHaveBeenCalled()+ })++ it("returns 404 when the channel does not exist (existence-mask 404 before the membership check)", async () => {+ mockGetChannel.mockResolvedValue(null)+ const res = await GET(getReq(), { params: { id: "c1" } } as any)+ expect(res.status).toBe(404)+ expect(mockGetChannelForMember).not.toHaveBeenCalled()+ })++ it("returns 403 when the channel exists but the caller is not a member", async () => {+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })+ mockGetChannelForMember.mockResolvedValue(null)+ const res = await GET(getReq(), { params: { id: "c1" } } as any)+ expect(res.status).toBe(403)+ })+})+describe("PATCH /channels/[id] — permission gate", () => {beforeEach(() => {vi.clearAllMocks()@@ -179,14 +228,19 @@ describe("PATCH /channels/[id] — permission gate", () => {})})-// The forum-post tag carve-out: a PUBLIC forum post's creator has-// canManage=false (canManage = isAdmin || (isPrivate && isCreator)), but may-// still edit THAT post's `forumTags` — and nothing else.+// The post self-delete carve-out: a PUBLIC post (= a thread rooted directly+// under a forum) creator has canManage=false (canManage = isAdmin ||+// (isPrivate && isCreator)), but may still delete THAT post. The carve-out+// keys off (isThread && creatorId===caller && parent is a forum) — NOT+// "any thread's creator" (Aigneis's authz catch: a thread opened incidentally+// by replying in an ordinary channel must NOT grant its opener delete power+// over the whole conversation). Tests here mock `getChannelType` for the+// parent-is-forum lookup.function forumPostCtx(over: { isCreator?: boolean; type?: string } = {}) {- const { isCreator = true, type = "forum_post" } = over+ const { isCreator = true, type = "thread" } = overconst channel = {id: "c1", serverId: "s1", type, parentChannelId: "forum_1",- parentMessageId: null, creatorId: isCreator ? "u1" : "someone_else", categoryId: null,+ parentMessageId: "m1", creatorId: isCreator ? "u1" : "someone_else", categoryId: null,}return {channel,@@ -198,68 +252,6 @@ function forumPostCtx(over: { isCreator?: boolean; type?: string } = {}) {}}-describe("PATCH /channels/[id] — forum-post tag carve-out", () => {- beforeEach(() => {- vi.clearAllMocks()- mockIsChannelPrivate.mockResolvedValue(false)- mockUpdateChannel.mockResolvedValue({ id: "c1", tags: ["alpha"] })- })-- it("a public post's creator (no canManage) can edit that post's tags", async () => {- mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))- const res = await PATCH(patchReq({ forumTags: JSON.stringify(["Alpha", "alpha", " beta "]) }), ctx)- expect(res.status).toBe(200)- // Normalized: lowercased, trimmed, deduped.- expect(mockUpdateChannel).toHaveBeenCalledWith(expect.anything(), "c1", {- forumTags: JSON.stringify(["alpha", "beta"]),- })- })-- it("a public post's creator cannot rename the post via the same route (403)", async () => {- mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))- const res = await PATCH(patchReq({ name: "sneaky" }), ctx)- expect(res.status).toBe(403)- expect(mockUpdateChannel).not.toHaveBeenCalled()- })-- it("a non-creator non-manager cannot edit the post's tags (403)", async () => {- mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: false }))- const res = await PATCH(patchReq({ forumTags: JSON.stringify(["x"]) }), ctx)- expect(res.status).toBe(403)- expect(mockUpdateChannel).not.toHaveBeenCalled()- })-- it("the FORUM creator cannot edit a post they didn't author (isCreator is access-only)", async () => {- // Unified model: access `isCreator` collapses to the forum (anchor) creator.- // The post-tag carve-out must key off the POST's own creator, so a forum- // creator who isn't the post author is NOT granted edit (would be a- // regression if it keyed off `access.value.isCreator`).- mockResolveChannelAccessContext.mockResolvedValue({- ...forumPostCtx({ isCreator: false }), // post authored by "someone_else"- isCreator: true, // but caller u1 IS the forum/anchor creator (access flag)- })- const res = await PATCH(patchReq({ forumTags: JSON.stringify(["x"]) }), ctx)- expect(res.status).toBe(403)- expect(mockUpdateChannel).not.toHaveBeenCalled()- })-- it("rejects forumTags on a non-forum_post channel (400)", async () => {- // A manager editing a plain text channel: canManage true, but tags are a- // per-post concept only.- mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))- const res = await PATCH(patchReq({ forumTags: JSON.stringify(["x"]) }), ctx)- expect(res.status).toBe(400)- expect(mockUpdateChannel).not.toHaveBeenCalled()- })-- it("rejects a malformed forumTags payload (not a JSON string array) with 400", async () => {- mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))- const res = await PATCH(patchReq({ forumTags: JSON.stringify([1, 2]) }), ctx)- expect(res.status).toBe(400)- expect(mockUpdateChannel).not.toHaveBeenCalled()- })-})-describe("PATCH /channels/[id] — categoryId move", () => {beforeEach(() => {vi.clearAllMocks()@@ -326,6 +318,7 @@ describe("DELETE /channels/[id]", () => {vi.clearAllMocks()mockDeleteChannel.mockResolvedValue({ id: "c1" })mockIsChannelPrivate.mockResolvedValue(false)+ mockGetChannelType.mockResolvedValue("forum")})it("403 when not canManage", async () => {@@ -355,7 +348,7 @@ describe("DELETE /channels/[id]", () => {expect(mockFanOutToServerMembers).not.toHaveBeenCalled()})- it("admin deletes any forum_post → 204 and broadcasts", async () => {+ it("admin deletes any post (thread under a forum) → 204 and broadcasts", async () => {mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true, creatorId: "someone_else" }),)@@ -365,14 +358,15 @@ describe("DELETE /channels/[id]", () => {expect(mockFanOutToServerMembers).toHaveBeenCalled()})- it("a PUBLIC forum_post's creator (no canManage) can delete it via the carve-out", async () => {+ it("a PUBLIC post's creator (no canManage) can delete it via the carve-out", async () => {mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))const res = await DELETE(delReq(), ctx)expect(res.status).toBe(204)expect(mockDeleteChannel).toHaveBeenCalledWith(expect.anything(), "c1")+ expect(mockGetChannelType).toHaveBeenCalledWith(expect.anything(), "forum_1")})- it("a private forum_post's creator can delete it (canManage already true)", async () => {+ it("a private post's creator can delete it (canManage already true)", async () => {// Private post creator: canManage = isPrivate && isCreator → true anyway.mockResolveChannelAccessContext.mockResolvedValue({...forumPostCtx({ isCreator: true }),@@ -385,7 +379,7 @@ describe("DELETE /channels/[id]", () => {expect(mockDeleteChannel).toHaveBeenCalled()})- it("a non-creator non-admin cannot delete a forum_post → 403", async () => {+ it("a non-creator non-admin cannot delete a post → 403", async () => {mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: false }))const res = await DELETE(delReq(), ctx)expect(res.status).toBe(403)@@ -404,6 +398,21 @@ describe("DELETE /channels/[id]", () => {expect(mockDeleteChannel).not.toHaveBeenCalled()})+ // SECURITY REGRESSION GUARD (Aigneis's catch): the carve-out must NOT widen+ // to "any thread's creator". A thread opened incidentally by replying in an+ // ordinary text channel is a conversation side-effect, not an intentional+ // "post" — its creator must NOT gain delete power over the whole thread+ // (which would cascade-delete every reply in it) just because they+ // triggered it. Only a thread whose PARENT is a forum carries the+ // deliberate creation semantics the old forum_post carve-out covered.+ it("a thread's creator under a PLAIN CHANNEL (not a forum) cannot delete it via the carve-out → 403", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))+ mockGetChannelType.mockResolvedValue("text") // parent is a plain channel, not a forum+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(403)+ expect(mockDeleteChannel).not.toHaveBeenCalled()+ })+it("the broadcast CHANNEL_DELETE payload carries parentChannelId", async () => {mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))const res = await DELETE(delReq(), ctx)@@ -416,9 +425,9 @@ describe("DELETE /channels/[id]", () => {})})- it("the carve-out does NOT let a non-creator delete a normal (non-forum_post) channel", async () => {+ it("the carve-out does NOT let a non-creator delete a normal (non-thread) channel", async () => {// canManage=false + type="text" + not creator → still 403 (carve-out is- // scoped to forum_post only).+ // scoped to threads-under-a-forum only).mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: false }))const res = await DELETE(delReq(), ctx)expect(res.status).toBe(403)diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.tsindex 589143dd4..e8e814c61 100644--- a/src/web/src/app/api/community/channels/[id]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/route.ts@@ -5,6 +5,8 @@ import { getDb } from "@/lib/db"import {queries,canManageServer,+ isForum,+ isThread,isUniqueConstraintError,MAX_CHANNEL_NAME_LENGTH,MAX_CHANNEL_TOPIC_LENGTH,@@ -13,7 +15,34 @@ import {} from "@alook/shared"import { fanOutToServerMembers, fanOutToChannel, broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"-import { requireChannelAccess } from "@/lib/community/permissions"+import { requireChannelAccess, requireChannelMember } from "@/lib/community/permissions"++/**+ * GET /api/community/channels/[id] — single channel metadata (the+ * `getChannelForMember` row: id, name, type, parentChannelId, parentMessageId,+ * creatorId, …). The canonical home for reading ANY channel's meta — a+ * top-level channel, a thread, or a forum post (a DM's meta is not read this+ * way; DMs surface through the DM list). Folds the old `threads/[id]` GET, which+ * only ever served child-thread metadata but was channel metadata by another+ * name (a thread IS a channel row). The thread-view opener + child-channel+ * bootstrap read it.+ *+ * Two-step check preserves the 404-vs-403 contract sibling channel routes honor:+ * unknown channel → 404, known channel + non-member → 403 (`requireChannelMember`+ * alone collapses both to 403 because the membership JOIN can't tell them apart).+ */+export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const channelId = ctx.params?.id+ if (!channelId) return writeError("missing channel id", 400)++ const db = getDb(ctx.env.DB)+ const channel = await queries.communityChannel.getChannel(db, channelId)+ if (!channel) return writeError("channel not found", 404)+ const auth = await requireChannelMember(db, channelId, ctx.userId)+ if (!auth.ok) return writeError(auth.error, auth.status)++ return writeJSON(auth.value)+})export const PATCH = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -24,33 +53,16 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channelconst isAdmin = canManageServer(access.value.member.role)- // A forum post's OWN creator may edit that post's tags even without full- // `canManage`. `access.value.isCreator` is the ACCESS creator (the forum- // creator for a post), so we derive the post-own-creator directly from- // `channel.creatorId` — the same pattern the participants route uses for the- // unit-creator lock. Scoped to the `forumTags` field only below; every other- // field still requires `canManage`.- const canEditPostTags =- channel.type === "forum_post" && channel.creatorId === ctx.userId- if (!access.value.canManage && !canEditPostTags) return writeError("forbidden", 403)-- let body: { name?: string; topic?: string; categoryId?: string | null; forumTags?: string | null }+ if (!access.value.canManage) return writeError("forbidden", 403)++ let body: { name?: string; topic?: string; categoryId?: string | null }try {body = await req.json()} catch {return writeError("invalid request body", 400)}- // A creator-without-canManage reached here only for the tag carve-out — they- // may edit forumTags and nothing else. Reject any other field explicitly- // rather than silently ignoring it.- if (!access.value.canManage) {- const nonTagField =- body.name !== undefined || body.topic !== undefined || body.categoryId !== undefined- if (nonTagField) return writeError("forbidden", 403)- }-- const changes: { name?: string; topic?: string; categoryId?: string | null; forumTags?: string | null } = {}+ const changes: { name?: string; topic?: string; categoryId?: string | null } = {}if (body.name !== undefined) {if (typeof body.name !== "string") return writeError("name must be a string", 400)const trimmed = body.name.trim()@@ -91,31 +103,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {}changes.categoryId = body.categoryId}- if (body.forumTags !== undefined) {- // Tags are a per-post concept: only a forum_post carries a selected-tag- // list (a forum's tag vocabulary is now derived as the union of its posts).- if (channel.type !== "forum_post") {- return writeError("only forum posts can have tags", 400)- }- // Validate the shape the read side (`safeParseForumTags`) expects: a JSON- // array of strings, stored as its stringified form. Reject anything else so- // a malformed value can't poison the parse.- if (body.forumTags !== null) {- let parsed: unknown- try {- parsed = JSON.parse(body.forumTags)- } catch {- return writeError("forumTags must be a JSON array of strings", 400)- }- if (!Array.isArray(parsed) || parsed.some((t) => typeof t !== "string")) {- return writeError("forumTags must be a JSON array of strings", 400)- }- const normalized = [...new Set(parsed.map((t) => t.trim().toLowerCase()).filter(Boolean))]- changes.forumTags = JSON.stringify(normalized)- } else {- changes.forumTags = null- }- }if (Object.keys(changes).length === 0) {return writeError("no changes provided", 400)@@ -169,13 +156,23 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const access = await requireChannelAccess(db, channelId, ctx.userId)if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channel- // A forum post's OWN creator may delete their own post even without full- // `canManage`. Mirrors the PATCH tag carve-out. `access.value.isCreator` is the- // ACCESS creator (the forum creator for a post), so derive the post-own-creator- // directly from `channel.creatorId`. Scoped to `forum_post` so normal-channel- // and thread creators are not granted delete.- const canDeletePost =- channel.type === "forum_post" && channel.creatorId === ctx.userId+ // A post's OWN creator may delete their own post — this carve-out predates+ // forum_post's collapse into thread; a post is now a thread rooted under a+ // forum, so its shape is `isThread(channel.type) && parent is a forum`.+ // ⚠ MUST NOT widen to "any thread's creator" (Aigneis's catch): the+ // carve-out is a session-authed HTTP DELETE, not a UI-gated action — anyone+ // who replies to a message in an ordinary channel incidentally becomes a+ // thread's creator, and that person must NOT gain the power to delete the+ // whole thread (cascading every reply in it) just because they happened to+ // trigger it. Only a thread whose PARENT is a forum carries the deliberate,+ // intentional-creation semantics the old forum_post carve-out was actually+ // scoped to. `access.value.isCreator` is the ACCESS creator (the parent's+ // creator), so derive the unit-own-creator directly from `channel.creatorId`.+ let canDeletePost = false+ if (isThread(channel.type) && channel.creatorId === ctx.userId && channel.parentChannelId) {+ const parentType = await queries.communityChannel.getChannelType(db, channel.parentChannelId)+ canDeletePost = isForum(parentType)+ }if (!access.value.canManage && !canDeletePost) return writeError("forbidden", 403)// Resolve the private-channel audience BEFORE deleting (the member rowsdiff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.tsindex 5ded82538..92e940997 100644--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts@@ -15,6 +15,7 @@ const mockGetFirstMessageByChannelIds = vi.fn()const mockGetMessage = vi.fn()const mockGetUser = vi.fn()const mockListMessages = vi.fn()+const mockFilterMessageIdsByTag = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -37,6 +38,9 @@ vi.mock("@alook/shared", async () => {getFirstMessageByChannelIds: (...a: unknown[]) => mockGetFirstMessageByChannelIds(...a),listMessages: (...a: unknown[]) => mockListMessages(...a),},+ communityMessageTag: {+ filterMessageIdsByTag: (...a: unknown[]) => mockFilterMessageIdsByTag(...a),+ },user: {getUser: (...a: unknown[]) => mockGetUser(...a),getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a),@@ -84,7 +88,7 @@ describe("GET /api/community/channels/[id]/threads", () => {})})- it("resolves parent/creator/first-message via three batched calls (never per-item)", async () => {+ it("returns plain child-thread rows without a view-specific hydration facade", async () => {// Fixture: 3 threads.// thread-A: parent message (parentMessageId set)// thread-B: creator only, has a first message@@ -121,45 +125,43 @@ describe("GET /api/community/channels/[id]/threads", () => {creatorId: "u-c",},])- mockGetMessagesByIds.mockResolvedValue([- {- id: "msg-p",- content: "parent-content",- authorName: "Alice",- authorEmail: "[email protected]",- seq: 7,- },- ])- mockGetUsersByIds.mockResolvedValue([- { id: "u-b", name: "Bob" },- { id: "u-c", name: "Carol" },- ])- mockGetFirstMessageByChannelIds.mockResolvedValue([- { channelId: "t-B", content: "first-in-B" },- ])-const res = await GET(req(), ctx)expect(res.status).toBe(200)- const body = await res.json() as { threads: Array<{ id: string; parent: { authorName: string; text: string }; parentSeq?: number }> }+ const body = await res.json() as { threads: Array<{ id: string; parentMessageId: string | null }> }expect(body.threads).toEqual([- { id: "t-A", name: "A", kind: "thread", messageCount: 3, lastMessageAt: "2026-06-30T01:00:00.000Z", parent: { authorName: "Alice", text: "parent-content" }, parentSeq: 7 },- { id: "t-B", name: "B", kind: "thread", messageCount: 2, lastMessageAt: "2026-06-30T00:00:00.000Z", parent: { authorName: "Bob", text: "first-in-B" } },- { id: "t-C", name: "C", kind: "thread", messageCount: 1, lastMessageAt: "2026-06-30T00:00:00.000Z", parent: { authorName: "Carol", text: "" } },+ { id: "t-A", name: "A", type: "thread", messageCount: 3, lastMessageAt: "2026-06-30T01:00:00.000Z", createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: "msg-p", creatorId: null },+ { id: "t-B", name: "B", type: "thread", messageCount: 2, lastMessageAt: null, createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: null, creatorId: "u-b" },+ { id: "t-C", name: "C", type: "thread", messageCount: 1, lastMessageAt: null, createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: null, creatorId: "u-c" },])- // t-B/t-C were created from a creator (no parent message) — parentSeq- // must be omitted, not `undefined`-valued, so a naive `"parentSeq" in- // thread` check on the client can't be fooled by an explicit undefined.- expect(Object.keys(body.threads[1])).not.toContain("parentSeq")- expect(Object.keys(body.threads[2])).not.toContain("parentSeq")-- expect(mockGetMessagesByIds).toHaveBeenCalledTimes(1)- expect(mockGetUsersByIds).toHaveBeenCalledTimes(1)- expect(mockGetFirstMessageByChannelIds).toHaveBeenCalledTimes(1)+ expect(mockGetMessagesByIds).not.toHaveBeenCalled()+ expect(mockGetUsersByIds).not.toHaveBeenCalled()+ expect(mockGetFirstMessageByChannelIds).not.toHaveBeenCalled()// Ensure the deprecated per-item fetches never fire.expect(mockGetMessage).not.toHaveBeenCalled()expect(mockGetUser).not.toHaveBeenCalled()expect(mockListMessages).not.toHaveBeenCalled()})++ it("filters only the scoped child opener candidates for a normalized tag", async () => {+ mockListChildChannels.mockResolvedValue([+ { id: "post_1", parentMessageId: "opener_1" },+ { id: "post_2", parentMessageId: "opener_2" },+ { id: "plain_thread", parentMessageId: null },+ ])+ mockFilterMessageIdsByTag.mockResolvedValue(["opener_2"])++ const res = await GET(req("http://localhost/api/community/channels/c1/threads?tag=%20BUG%20"), ctx)+ expect(res.status).toBe(200)+ expect(mockFilterMessageIdsByTag).toHaveBeenCalledWith(expect.anything(), ["opener_1", "opener_2"], "bug")+ expect((await res.json()).threads).toEqual([{ id: "post_2", parentMessageId: "opener_2" }])+ })++ it("rejects an empty tag before querying message_tags", async () => {+ mockListChildChannels.mockResolvedValue([])+ const res = await GET(req("http://localhost/api/community/channels/c1/threads?tag=%20%20"), ctx)+ expect(res.status).toBe(400)+ expect(mockFilterMessageIdsByTag).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.tsindex 2a97360a4..6ac1b46a3 100644--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"+import { queries, MAX_FORUM_TAG_LENGTH } from "@alook/shared"import { requireChannelAccess } from "@/lib/community/permissions"export const GET = withAuth(async (req: NextRequest, ctx) => {@@ -20,69 +20,23 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const archivedParam = req.nextUrl.searchParams.get("archived")const archived = archivedParam === "true" ? true : archivedParam === "false" ? false : undefined- const childChannels = await queries.communityChannel.listChildChannels(db, channelId, {+ let childChannels = await queries.communityChannel.listChildChannels(db, channelId, {archived,type: "thread",})- // Collect id sets up front so we can resolve parent-message / creator /- // first-message previews in three parallel batches instead of 1+2N calls.- const parentIds = [- ...new Set(childChannels.filter((r) => r.parentMessageId).map((r) => r.parentMessageId!)),- ]- const creatorIds = [- ...new Set(- childChannels- .filter((r) => !r.parentMessageId && r.creatorId)- .map((r) => r.creatorId!),- ),- ]- const firstMessageChannelIds = [- ...new Set(childChannels.filter((r) => !r.parentMessageId).map((r) => r.id)),- ]-- const [parentMessages, creators, firstMessages] = await Promise.all([- queries.communityMessage.getMessagesByIds(db, parentIds),- queries.user.getUsersByIds(db, creatorIds),- queries.communityMessage.getFirstMessageByChannelIds(db, firstMessageChannelIds),- ])-- const parentMessageMap = new Map(parentMessages.map((m) => [m.id, m]))- const creatorMap = new Map(creators.map((u) => [u.id, u]))- const firstMessageMap = new Map(- firstMessages.map((m) => [m.channelId as string, m.content]),- )-- const threads = childChannels.map((t) => {- let parent = { authorName: "", text: "" }- let parentSeq: number | undefined- if (t.parentMessageId) {- const msg = parentMessageMap.get(t.parentMessageId)- if (msg) {- parent = {- authorName: msg.authorName,- text: (msg.content ?? "").slice(0, 100),- }- parentSeq = msg.seq- }- } else if (t.creatorId) {- const creator = creatorMap.get(t.creatorId)- if (creator) parent = { authorName: creator.name, text: "" }- const firstText = firstMessageMap.get(t.id)- if (firstText !== undefined) {- parent = { ...parent, text: (firstText ?? "").slice(0, 100) }- }- }- return {- id: t.id,- name: t.name,- kind: t.type,- messageCount: t.messageCount ?? 0,- lastMessageAt: t.lastMessageAt ?? t.createdAt,- parent,- ...(parentSeq !== undefined ? { parentSeq } : {}),- }- })-- return writeJSON({ threads })+ const rawTag = req.nextUrl.searchParams.get("tag")+ if (rawTag !== null) {+ const tag = rawTag.trim().toLowerCase()+ if (!tag) return writeError("tag is required", 400)+ if (tag.length > MAX_FORUM_TAG_LENGTH) return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)+ const openerIds = childChannels.map((child) => child.parentMessageId).filter((id): id is string => !!id)+ const matching = new Set(await queries.communityMessageTag.filterMessageIdsByTag(db, openerIds, tag))+ childChannels = childChannels.filter((child) => !!child.parentMessageId && matching.has(child.parentMessageId))+ }++ // Plain nested collection representation. View-specific parent previews,+ // first messages, tags, participants, and creator presentation are composed+ // by consumers through the generic batch resource reads.+ return writeJSON({ threads: childChannels })})diff --git a/src/web/src/app/api/community/channels/[id]/upload/route.test.ts b/src/web/src/app/api/community/channels/[id]/upload/route.test.tsindex 0e2bab5ac..2d2a641b1 100644--- a/src/web/src/app/api/community/channels/[id]/upload/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/upload/route.test.ts@@ -2,16 +2,11 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mockRunAttachmentUpload = vi.fn()-const mockRequireChannelMember = vi.fn()vi.mock("@/lib/community/upload", () => ({runAttachmentUpload: (...a: unknown[]) => mockRunAttachmentUpload(...a),}))-vi.mock("@/lib/community/permissions", () => ({- requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...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@@ -29,39 +24,30 @@ function postReq() {const ctx = { params: { id: "c1" } } as any-describe("POST /api/community/channels/[id]/upload", () => {+describe("POST /api/community/channels/[id]/upload — unified upload trunk entry", () => {beforeEach(() => {vi.clearAllMocks()- mockRunAttachmentUpload.mockResolvedValue(- new Response(null, { status: 200 }),- )+ mockRunAttachmentUpload.mockResolvedValue(new Response(null, { status: 200 }))})- it("delegates to runAttachmentUpload with kind='channel' + requireChannelMember", async () => {- // The route file is intentionally a one-liner over the shared helper.- // Its only job is to bind the right (kind, permissionCheck) pair — lock- // that binding in so accidental swaps between the three upload routes- // (channel / dm / thread) are caught.+ it("delegates to runAttachmentUpload with just (req, ctx) — surface + kind are derived inside", async () => {+ // The route is a one-liner over the shared trunk. Since (A) collapsed the+ // three upload routes to one surface-dispatching entry, the route no longer+ // binds a (kind, permissionCheck) pair — it just forwards; runAttachmentUpload+ // resolves access + derives kind from the dispatch. Lock that it forwards+ // (req, ctx) and passes NO fixed kind/permission (a regression to the old+ // 4-arg binding would show extra args here).const req = postReq()await POST(req, ctx)expect(mockRunAttachmentUpload).toHaveBeenCalledOnce()- const [passedReq, passedCtx, kind, permCheck] =- mockRunAttachmentUpload.mock.calls[0]- expect(passedReq).toBe(req)- expect(passedCtx).toMatchObject({ userId: "u1", params: { id: "c1" } })- expect(kind).toBe("channel")- // The permissionCheck reference is the module export — invoke it and- // observe that the underlying mock fires, which pins the binding to- // `requireChannelMember` (a swap to a different permission helper- // would hit a different mock).- await (permCheck as (...a: unknown[]) => unknown)("db", "c1", "u1")- expect(mockRequireChannelMember).toHaveBeenCalledWith("db", "c1", "u1")+ const args = mockRunAttachmentUpload.mock.calls[0]+ expect(args[0]).toBe(req)+ expect(args[1]).toMatchObject({ userId: "u1", params: { id: "c1" } })+ expect(args).toHaveLength(2) // no fixed kind / permissionCheck})it("returns whatever runAttachmentUpload returns unchanged", async () => {- const helperResponse = new Response(JSON.stringify({ ok: 1 }), {- status: 201,- })+ const helperResponse = new Response(JSON.stringify({ ok: 1 }), { status: 201 })mockRunAttachmentUpload.mockResolvedValueOnce(helperResponse)const res = await POST(postReq(), ctx)expect(res).toBe(helperResponse)diff --git a/src/web/src/app/api/community/channels/[id]/upload/route.ts b/src/web/src/app/api/community/channels/[id]/upload/route.tsindex 2c1d490bb..0b009c924 100644--- a/src/web/src/app/api/community/channels/[id]/upload/route.ts+++ b/src/web/src/app/api/community/channels/[id]/upload/route.ts@@ -1,8 +1,9 @@import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"-import { requireChannelMember } from "@/lib/community/permissions"import { runAttachmentUpload } from "@/lib/community/upload"-export const POST = withAuth((req: NextRequest, ctx) =>- runAttachmentUpload(req, ctx, "channel", requireChannelMember),-)+// The unified attachment-upload trunk: one route, dispatched by surface inside+// runAttachmentUpload (requireMessageSurfaceAccess → kind derived from surface ++// channel.type). A DM id runs the DM block gate; a child-thread id runs+// the child-surface gate — all surfaces upload through this one door.+export const POST = withAuth((req: NextRequest, ctx) => runAttachmentUpload(req, ctx))diff --git a/src/web/src/app/api/community/channels/participants/batch/route.test.ts b/src/web/src/app/api/community/channels/participants/batch/route.test.tsnew file mode 100644index 000000000..0f55521aa--- /dev/null+++ b/src/web/src/app/api/community/channels/participants/batch/route.test.ts@@ -0,0 +1,89 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })) }))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockRequireMessageSurfaceAccess = vi.fn()+const mockGetDirectChildThreadsByIds = vi.fn()+const mockListParticipantsForChannels = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityChannel: {+ ...actual.queries.communityChannel,+ getDirectChildThreadsByIds: (...args: unknown[]) => mockGetDirectChildThreadsByIds(...args),+ },+ communityThread: {+ ...actual.queries.communityThread,+ listParticipantsForChannels: (...args: unknown[]) => mockListParticipantsForChannels(...args),+ },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any) => handler(req, { env: { DB: {} }, userId: "user_1" }),+}))++import { POST } from "./route"++function request(body: unknown) {+ return new NextRequest("http://localhost/api/community/channels/participants/batch", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ })+}++describe("POST /api/community/channels/participants/batch", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: true })+ mockGetDirectChildThreadsByIds.mockResolvedValue([{ id: "thread_1" }, { id: "thread_2" }])+ mockListParticipantsForChannels.mockResolvedValue([])+ })++ it("gates one parent and validates the whole direct-child set in one query", async () => {+ const response = await POST(request({ parentChannelId: "forum_1", channelIds: ["thread_1", "thread_2"] }))+ expect(response.status).toBe(200)+ expect(mockRequireMessageSurfaceAccess).toHaveBeenCalledTimes(1)+ expect(mockGetDirectChildThreadsByIds).toHaveBeenCalledWith(expect.anything(), "forum_1", ["thread_1", "thread_2"])+ expect(mockListParticipantsForChannels).toHaveBeenCalledWith(expect.anything(), ["thread_1", "thread_2"])+ })++ it("rejects all results when one requested id belongs elsewhere", async () => {+ mockGetDirectChildThreadsByIds.mockResolvedValue([{ id: "thread_1" }])+ const response = await POST(request({ parentChannelId: "forum_1", channelIds: ["thread_1", "foreign"] }))+ expect(response.status).toBe(404)+ expect(mockListParticipantsForChannels).not.toHaveBeenCalled()+ })++ it("passes an explicit capped preview limit without changing the legacy absent-limit call", async () => {+ const response = await POST(request({+ parentChannelId: "forum_1",+ channelIds: ["thread_1", "thread_2"],+ limitPerChannel: 5,+ }))+ expect(response.status).toBe(200)+ expect(mockListParticipantsForChannels).toHaveBeenCalledWith(+ expect.anything(),+ ["thread_1", "thread_2"],+ 5,+ )+ })++ it.each([0, -1, 11, 1.5, "5"])("rejects invalid present limitPerChannel %s", async (limitPerChannel) => {+ const response = await POST(request({+ parentChannelId: "forum_1",+ channelIds: ["thread_1", "thread_2"],+ limitPerChannel,+ }))+ expect(response.status).toBe(400)+ expect(mockListParticipantsForChannels).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/channels/participants/batch/route.ts b/src/web/src/app/api/community/channels/participants/batch/route.tsnew file mode 100644index 000000000..ae374a7cd--- /dev/null+++ b/src/web/src/app/api/community/channels/participants/batch/route.ts@@ -0,0 +1,30 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"++export const POST = withAuth(async (req: NextRequest, ctx) => {+ let body: { parentChannelId?: unknown; channelIds?: unknown; limitPerChannel?: unknown }+ try { body = await req.json() } catch { return writeError("invalid request body", 400) }+ const ids = Array.isArray(body.channelIds) ? [...new Set(body.channelIds.filter((id): id is string => typeof id === "string"))] : []+ if (ids.length > 100) return writeError("too many ids", 400)+ if (typeof body.parentChannelId !== "string") return writeError("parentChannelId is required", 400)+ const db = getDb(ctx.env.DB)+ const parentAccess = await requireMessageSurfaceAccess(db, body.parentChannelId, ctx.userId)+ if (!parentAccess.ok) return writeError(parentAccess.error, parentAccess.status)+ const childThreads = await queries.communityChannel.getDirectChildThreadsByIds(db, body.parentChannelId, ids)+ if (childThreads.length !== ids.length) return writeError("thread not found", 404)+ const limitPerChannel = body.limitPerChannel+ if (limitPerChannel !== undefined && (+ typeof limitPerChannel !== "number"+ || !Number.isInteger(limitPerChannel)+ || limitPerChannel < 1+ || limitPerChannel > 10+ )) return writeError("limitPerChannel must be an integer between 1 and 10", 400)+ const participants = limitPerChannel === undefined+ ? await queries.communityThread.listParticipantsForChannels(db, ids)+ : await queries.communityThread.listParticipantsForChannels(db, ids, limitPerChannel)+ return writeJSON({ participants })+})diff --git a/src/web/src/app/api/community/channels/route.test.ts b/src/web/src/app/api/community/channels/route.test.tsnew file mode 100644index 000000000..2b3adfcb7--- /dev/null+++ b/src/web/src/app/api/community/channels/route.test.ts@@ -0,0 +1,191 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++const mockCreateServerChannel = vi.fn()+const mockCreateDm = vi.fn()+const mockCreateThread = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++// Dual-actor: crk_ bearer → bot, else human. The bot arm is a capability+// boundary — creating channels is not a bot capability (channel-create permanent+// reject; dm/thread defensive, no bot verb today) → bot → 403 before any target+// touch. The human arm dispatches to the creation cores.+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: any) => {+ const authz = req?.headers?.get?.("Authorization") ?? ""+ const actor = authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]" }+ return handler(req, { env: { DB: {} }, actor })+ },+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++vi.mock("@/lib/community/create-channels", () => ({+ createServerChannelForUser: (...a: unknown[]) => mockCreateServerChannel(...a),+ createDmForUser: (...a: unknown[]) => mockCreateDm(...a),+ createThreadForUser: (...a: unknown[]) => mockCreateThread(...a),+}))++import { POST } from "./route"++function req(body: unknown) {+ return new NextRequest("http://localhost/api/community/channels", {+ method: "POST",+ body: JSON.stringify(body),+ })+}++function botReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/channels", {+ method: "POST",+ headers: { Authorization: "Bearer crk_test" },+ body: JSON.stringify(body),+ })+}++describe("POST /api/community/channels (create door — human arm)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockCreateServerChannel.mockResolvedValue({ ok: true, value: { id: "c-new", name: "general", type: "text" } })+ mockCreateDm.mockResolvedValue({ ok: true, value: { id: "dm-1" } })+ mockCreateThread.mockResolvedValue({ ok: true, value: { id: "t-1", parentMessageId: "msg-p" } })+ })++ it("dispatches type=text to the server-channel core, 201 {channel}", async () => {+ const res = await POST(req({ type: "text", serverId: "s1", name: "general" }))+ expect(res.status).toBe(201)+ expect(mockCreateServerChannel).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ serverId: "s1", actorUserId: "u1", name: "general", type: "text" }),+ )+ const body = await res.json()+ expect(body.channel.id).toBe("c-new")+ expect(mockCreateDm).not.toHaveBeenCalled()+ expect(mockCreateThread).not.toHaveBeenCalled()+ })++ it("dispatches type=forum to the server-channel core", async () => {+ const res = await POST(req({ type: "forum", serverId: "s1", name: "ideas" }))+ expect(res.status).toBe(201)+ expect(mockCreateServerChannel).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ type: "forum" }),+ )+ })++ it("dispatches undefined type to the server-channel core (defaults to text)", async () => {+ const res = await POST(req({ serverId: "s1", name: "general" }))+ expect(res.status).toBe(201)+ expect(mockCreateServerChannel).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ serverId: "s1", type: undefined }),+ )+ })++ it("400s a text/forum create with no serverId (before touching the core)", async () => {+ const res = await POST(req({ type: "text", name: "general" }))+ expect(res.status).toBe(400)+ expect(mockCreateServerChannel).not.toHaveBeenCalled()+ })++ it("dispatches type=dm to the DM core, 201 {conversation}", async () => {+ const res = await POST(req({ type: "dm", userId: "u2" }))+ expect(res.status).toBe(201)+ expect(mockCreateDm).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ actorUserId: "u1", peerUserId: "u2" }),+ )+ const body = await res.json()+ expect(body.conversation.id).toBe("dm-1")+ })++ it("dispatches type=thread to the thread core, 201 with the child channel", async () => {+ const res = await POST(req({ type: "thread", messageId: "msg-p", name: "side chat" }))+ expect(res.status).toBe(201)+ expect(mockCreateThread).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ messageId: "msg-p", actorUserId: "u1", name: "side chat" }),+ )+ const body = await res.json()+ expect(body.id).toBe("t-1")+ })++ it("400s a thread create with no messageId (before touching the core)", async () => {+ const res = await POST(req({ type: "thread", name: "x" }))+ expect(res.status).toBe(400)+ expect(mockCreateThread).not.toHaveBeenCalled()+ })++ it("400s an unknown type", async () => {+ const res = await POST(req({ type: "forum_post", serverId: "s1", name: "x" }))+ expect(res.status).toBe(400)+ expect(mockCreateServerChannel).not.toHaveBeenCalled()+ expect(mockCreateDm).not.toHaveBeenCalled()+ expect(mockCreateThread).not.toHaveBeenCalled()+ })++ it("400s an invalid JSON body", async () => {+ const bad = new NextRequest("http://localhost/api/community/channels", { method: "POST", body: "{not json" })+ const res = await POST(bad)+ expect(res.status).toBe(400)+ })++ it("propagates a core's structured failure (status + error) verbatim", async () => {+ mockCreateServerChannel.mockResolvedValue({ ok: false, status: 409, error: "a channel with this name already exists" })+ const res = await POST(req({ type: "text", serverId: "s1", name: "dup" }))+ expect(res.status).toBe(409)+ const body = await res.json()+ expect(body.error).toBe("a channel with this name already exists")+ })++ describe("bot capability boundary (403 before any target touch)", () => {+ // (1) channel-create is a PERMANENT capability reject for bots — reject fires+ // before resolving any target, so the 403 is channel-independent (zero+ // existence leak). It does NOT open with any future verb.+ it("403s a bot creating a text channel, before touching the core (permanent capability boundary)", async () => {+ const res = await POST(botReq({ type: "text", serverId: "s1", name: "general" }))+ expect(res.status).toBe(403)+ expect(mockCreateServerChannel).not.toHaveBeenCalled()+ })++ it("403s a bot creating a forum channel", async () => {+ const res = await POST(botReq({ type: "forum", serverId: "s1", name: "ideas" }))+ expect(res.status).toBe(403)+ expect(mockCreateServerChannel).not.toHaveBeenCalled()+ })++ // (2) dm / thread → defensive reject (no bot create-DM/thread verb today; the+ // real ①-C ref arm lands with a future verb + MUST be verified then). The+ // reject is target-independent: it fires before any resolve/probe, so a bot+ // can't use it to probe DM/message existence.+ it("403s a bot creating a DM, before touching the core (defensive — no bot verb today)", async () => {+ const res = await POST(botReq({ type: "dm", userId: "u2" }))+ expect(res.status).toBe(403)+ expect(mockCreateDm).not.toHaveBeenCalled()+ })++ it("403s a bot creating a thread, before touching the core (defensive)", async () => {+ const res = await POST(botReq({ type: "thread", messageId: "msg-p", name: "x" }))+ expect(res.status).toBe(403)+ expect(mockCreateThread).not.toHaveBeenCalled()+ })++ it("403s a bot with an unknown type too (reject precedes type dispatch — no info leak)", async () => {+ const res = await POST(botReq({ type: "forum_post", serverId: "s1", name: "x" }))+ expect(res.status).toBe(403)+ })+ })+})diff --git a/src/web/src/app/api/community/channels/route.ts b/src/web/src/app/api/community/channels/route.tsnew file mode 100644index 000000000..5bab57bd2--- /dev/null+++ b/src/web/src/app/api/community/channels/route.ts@@ -0,0 +1,119 @@+import { NextRequest } from "next/server"+import { withCommunityActor } from "@/lib/middleware/community-actor"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import {+ createServerChannelForUser,+ createDmForUser,+ createThreadForUser,+} from "@/lib/community/create-channels"++/**+ * POST /api/community/channels — the create door (route/disc trunk 接口树统一,+ * create-door step). ONE collection-level route that creates any channel kind,+ * dispatching on the requested `type`'s creation trait:+ * - text / forum → reject-on-collision (by server-scoped name)+ * - dm → get-or-create by peer identity (createOrGetDM)+ * - thread → get-or-create by root-message anchor+ * It folds the three legacy create entries (servers/[id]/channels POST, dm POST,+ * messages/[id]/threads POST), which now call the SAME single-source cores in+ * create-channels.ts and stay alive transitionally (deleted at the flat-delete+ * step after the deploy window closes).+ *+ * Dual-actor (`withCommunityActor`), but bot CAPABILITY is minimal and ORTHOGONAL+ * to the 4-type dispatch — supporting a type ≠ opening it to bots. The bot arm is+ * two DIFFERENT rejections, kept distinct on purpose (Melly #486 / Aigneis #475):+ *+ * (1) text/forum channel-create → 403 capability-reject, PERMANENT. This is a+ * fixed capability boundary, NOT a deferred half: a bot creating a+ * top-level channel changes server structure, a sensitive capability bots+ * have never had. Granting it is an explicit capability EXPANSION (its own+ * review), and it will NEVER open as a side effect of any future verb. The+ * reject fires BEFORE resolving/touching any target → the 403 is+ * channel-independent (zero existence leak, capability axis not existence+ * axis, same form as members-POST #347).+ *+ * (2) dm / thread → defensive reject, DEFERRED half. There is no bot+ * create-DM/thread verb today (bots get DM/thread only as a get-or-create+ * side effect of `send`, via resolve-ref — not this door), and no bot-ref+ * descriptor shape is defined. So the bot arm here is defensive (reject+ * BEFORE any target probe, never a bare requireChannelMember fallback whose+ * known-non-member 403 would leak existence). When a real bot+ * create-DM/thread verb lands, THAT commit builds the ①-C ref arm here —+ * switch to resolveTargetForMember (ref → member-scoped → 404-before-mask,+ * resolve≠create) with the descriptor's ref shape defined alongside the+ * verb — and MUST verify it then (Ingaborg #485 tripwire: openable anytime,+ * opening MUST test; never inherit "defensive passed" as verified).+ *+ * Human path is unchanged from the human-arm commit. Descriptor is discriminated+ * on `type`; the parent is addressed by the id each kind needs (serverId / peer+ * userId / root messageId).+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)++ let body: {+ type?: unknown+ serverId?: unknown+ name?: unknown+ categoryId?: unknown+ topic?: unknown+ userId?: unknown+ messageId?: unknown+ }+ try {+ body = await req.json()+ } catch {+ return writeError("invalid request body", 400)+ }++ // Bot capability boundary — rejected BEFORE resolving/probing any target, so+ // every bot rejection is target-independent (zero existence leak). See the two+ // segments in the route doc: (1) channel-create is a permanent capability+ // reject; (2) dm/thread is a defensive reject (no bot verb today).+ if (ctx.actor.kind === "bot") {+ return writeError("forbidden: creating channels is not available to bots", 403)+ }+ const actorUserId = ctx.actor.userId++ switch (body.type) {+ case "text":+ case "forum":+ case undefined: {+ // text/forum channel under a server (undefined type defaults to text, same+ // as the legacy route + createChannel default).+ if (typeof body.serverId !== "string" || !body.serverId) {+ return writeError("serverId is required", 400)+ }+ const result = await createServerChannelForUser(db, {+ serverId: body.serverId,+ actorUserId,+ name: body.name,+ type: body.type,+ categoryId: body.categoryId,+ topic: body.topic,+ })+ if (!result.ok) return writeError(result.error, result.status)+ return writeJSON({ channel: result.value }, 201)+ }+ case "dm": {+ const result = await createDmForUser(db, { actorUserId, peerUserId: body.userId })+ if (!result.ok) return writeError(result.error, result.status)+ return writeJSON({ conversation: result.value }, 201)+ }+ case "thread": {+ if (typeof body.messageId !== "string" || !body.messageId) {+ return writeError("messageId is required", 400)+ }+ const result = await createThreadForUser(db, {+ messageId: body.messageId,+ actorUserId,+ name: body.name,+ })+ if (!result.ok) return writeError(result.error, result.status)+ return writeJSON(result.value, 201)+ }+ default:+ return writeError("type must be one of 'text', 'forum', 'dm', 'thread'", 400)+ }+})diff --git a/src/web/src/app/api/community/createPost/route.test.ts b/src/web/src/app/api/community/createPost/route.test.tsdeleted file mode 100644index 979515a5e..000000000--- a/src/web/src/app/api/community/createPost/route.test.ts+++ /dev/null@@ -1,155 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetBotBinding = vi.fn()-const mockResolveServerByNameForMember = vi.fn()-const mockResolveChannelByNameForMember = vi.fn()-const mockGetChannelForMember = vi.fn()-const mockGetServer = vi.fn()-const mockFindPendingAttachmentsForBot = vi.fn()--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityServer: {- resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),- getServer: (...a: unknown[]) => mockGetServer(...a),- },- communityChannel: {- resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityAttachment: {- findPendingAttachmentsForBot: (...a: unknown[]) => mockFindPendingAttachmentsForBot(...a),- },- },- }-})--const mockCreateForumPost = vi.fn()-vi.mock("@/lib/community/create-forum-post", () => ({- createForumPost: (...a: unknown[]) => mockCreateForumPost(...a),-}))--import { POST } from "./route"--function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/createPost", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--const AUTH = { Authorization: "Bearer crk_abc" }--describe("POST /api/community/createPost", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- // Forum ref resolves to a forum channel the bot can access.- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "forum_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "forum_1", serverId: "srv_1", type: "forum", name: "ideas", parentChannelId: null })- mockGetServer.mockResolvedValue({ id: "srv_1", name: "studio" })- mockFindPendingAttachmentsForBot.mockResolvedValue([])- mockCreateForumPost.mockResolvedValue({- ok: true,- postChannel: { id: "post_1", name: "my-post", createdAt: "2026-08-04T00:00:00.000Z" },- messageRow: { id: "m_1", seq: 1 },- attachments: [],- })- })-- it("401 without Authorization (human path, no session)", async () => {- const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hi" } }))- expect(res.status).toBe(401)- })-- it("400 on schema failure — empty title", async () => {- const res = await POST(req({ forum: "/studio/ideas", title: "", content: { text: "hi" } }, AUTH))- expect(res.status).toBe(400)- })-- it("400 on opener empty — no text and no attachments (attachment-only IS allowed, empty is not)", async () => {- const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "" } }, AUTH))- expect(res.status).toBe(400)- })-- it("201 + canonical /server/forum/<slug> ref on success (round-trippable as next --target)", async () => {- const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hello" } }, AUTH))- expect(res.status).toBe(201)- const body = await res.json()- expect(body.post.ref).toBe("/studio/ideas/my-post")- expect(body.post.name).toBe("my-post")- })-- it("authz symmetry: a bot that is NOT a member of the (private) forum → 403, same as a human", async () => {- // requireChannelMember → getChannelForMember returns null when the bot can't- // see the forum (private, not a member) → 403 "forbidden". This proves the- // create gate runs requireChannelMember, not a requireBot shortcut.- mockGetChannelForMember.mockResolvedValue(null)- const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hi" } }, AUTH))- expect(res.status).toBe(403)- expect(mockCreateForumPost).not.toHaveBeenCalled()- })-- it("400 when the resolved target is not a forum (e.g. a text channel)", async () => {- mockGetChannelForMember.mockResolvedValue({ id: "forum_1", serverId: "srv_1", type: "text", name: "general", parentChannelId: null })- const res = await POST(req({ forum: "/studio/general", title: "My Post", content: { text: "hi" } }, AUTH))- expect(res.status).toBe(400)- expect(mockCreateForumPost).not.toHaveBeenCalled()- })-- it("(5b) attachment widen: a pending id NOT bound to this forum → 400, no cross-forum reuse", async () => {- // Bound to forum A but this create targets forum_1 → findPendingAttachmentsForBot- // (queried with targetId=forum_1) returns fewer rows than requested → 400.- mockFindPendingAttachmentsForBot.mockResolvedValue([]) // 0 found for 1 requested- const res = await POST(- req({ forum: "/studio/ideas", title: "My Post", content: { text: "" }, attachments: ["att_from_other_forum"] }, AUTH),- )- expect(res.status).toBe(400)- expect(mockCreateForumPost).not.toHaveBeenCalled()- // Validated against THIS forum's id (the widen: bind-to-forum).- expect(mockFindPendingAttachmentsForBot).toHaveBeenCalledWith(expect.anything(), {- ids: ["att_from_other_forum"],- uploaderId: "bot_1",- targetId: "forum_1",- })- })-- it("attachment-only post (no text, valid forum-bound attachment) → succeeds", async () => {- mockFindPendingAttachmentsForBot.mockResolvedValue([{ id: "att_1" }])- const res = await POST(- req({ forum: "/studio/ideas", title: "My Post", content: { text: "" }, attachments: ["att_1"] }, AUTH),- )- expect(res.status).toBe(201)- expect(mockCreateForumPost).toHaveBeenCalled()- })-- it("surfaces createForumPost's structured error (e.g. slug allocation 409)", async () => {- mockCreateForumPost.mockResolvedValue({ ok: false, status: 409, error: "could not allocate a unique name after repeated collisions" })- const res = await POST(req({ forum: "/studio/ideas", title: "My Post", content: { text: "hi" } }, AUTH))- expect(res.status).toBe(409)- })-})diff --git a/src/web/src/app/api/community/createPost/route.ts b/src/web/src/app/api/community/createPost/route.tsdeleted file mode 100644index d48248506..000000000--- a/src/web/src/app/api/community/createPost/route.ts+++ /dev/null@@ -1,125 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry, CommunityAgentCreatePostRequestSchema, formatCanonicalRef } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { requireChannelMember } from "@/lib/community/permissions"-import { createForumPost } from "@/lib/community/create-forum-post"--/**- * POST /api/community/createPost — bot verb behind `alook message post`. Creates- * a NEW forum post: body `{ forum, title, content, attachments?, nonce? }` where- * `forum` is a forum REF (`/server/forum`, resolved server-side like `send`'s- * `channel`). Bot-only (`requireBot`); a human posts via the web New-Post button- * (the human `channels/[id]/posts` route). Both call the SAME `createForumPost`- * core, so the two creation paths can't drift.- *- * Gate order (thread /Alook/discuss/#462, Aigneis's authz red-line): resolve the- * forum ref (NO create flags — we don't auto-create a forum) → assert it IS a- * forum → really run `requireChannelMember(forum, botUserId)` (the CREATE authz- * gate — a bot may create a post only in a forum it can access, same as a human;- * a non-member 403s, NOT a requireBot shortcut) → createForumPost. NO alignment- * gate: a fresh post is a new scope with no seq contention.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate0 = requireBot(ctx.actor)- if (!gate0.ok) return gate0.response- const botUserId = gate0.bot.userId-- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentCreatePostRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }- const body = parsed.data-- // Resolve the forum ref WITHOUT create flags — a stale/typo ref must 404, never- // materialize a channel. `/server/forum` resolves to the forum's own channel.- const resolved = await resolveTargetForMember(db, botUserId, body.forum)- if ("error" in resolved) return resolveErrorResponse(resolved)- if (resolved.kind !== "channel") {- return NextResponse.json({ error: "target is not a forum" }, { status: 400 })- }-- // Authz gate = the SAME requireChannelMember(forum) a human create passes — a- // bot creates a post only in a forum it can access (non-member → 403). This is- // the create authorization gate, distinct from requireBot (which only answers- // "is a bot") and from resolveTargetForMember's membership-scoped addressing.- const gate = await requireChannelMember(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- const forum = gate.value- if (forum.type !== "forum") {- return NextResponse.json({ error: "target is not a forum" }, { status: 400 })- }-- // Attachment ownership (坑1): a bot uploads a pending attachment BEFORE the post- // channel exists, so it binds the pending row's `target_id` to the FORUM id.- // Validate ownership against that forum id here (the widen: bind-to-forum for a- // post, vs `send`'s bind-to-channel — the post channel doesn't exist yet at- // upload time). This is the authorization check; the actual reservation- // (`reserveAttachmentsForMessage`, inside createForumPost's first-message send)- // then binds each pending row to the new message BY ID, so no target re-point- // is needed — the forum-ownership gate is enforced right here, up front. A- // mismatch → generic 400, no leak of which id failed.- if (body.attachments.length > 0) {- const rows = await withD1Retry(- () => queries.communityAttachment.findPendingAttachmentsForBot(db, {- ids: body.attachments,- uploaderId: botUserId,- targetId: resolved.channelId,- }),- { route: "community/createPost:attachments" },- )- if (rows.length !== body.attachments.length) {- return NextResponse.json(- { error: "attachment not found or not attachable to this forum" },- { status: 400 },- )- }- }-- const result = await createForumPost({- db,- forumChannelId: forum.id,- serverId: forum.serverId!,- authorId: botUserId,- rawTitle: body.title,- content: body.content.text,- attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,- clientNonce: body.nonce,- })- if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })-- // Return the canonical, addressable ref of the created post — `/server/forum/- // <real-slug>` (the slug after dedupe/bump), which the bot can hand straight- // back as a `--target`. Built by the single canonical-ref emitter (B1), the- // same one inbox/send resolve against, so it round-trips by construction.- const server = await withD1Retry(- () => queries.communityServer.getServer(db, forum.serverId!),- { route: "community/createPost:server" },- )- const serverName = server?.name ?? null- const ref = serverName- ? formatCanonicalRef({- type: "forum_post",- serverName,- parentName: forum.name ?? undefined,- name: result.postChannel.name,- })- : null-- return NextResponse.json({- post: {- ref,- name: result.postChannel.name,- seq: result.messageRow.seq,- },- }, { status: 201 })-})diff --git a/src/web/src/app/api/community/daemon/enroll-agent/route.ts b/src/web/src/app/api/community/daemon/enroll-agent/route.tsindex 8545eb450..68b5145f1 100644--- a/src/web/src/app/api/community/daemon/enroll-agent/route.ts+++ b/src/web/src/app/api/community/daemon/enroll-agent/route.ts@@ -3,6 +3,7 @@ import {queries,CommunityDaemonEnrollAgentRequestSchema,type CommunityDaemonEnrollAgentResponse,+ withD1Retry,} from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"@@ -14,7 +15,8 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"* runner key (`crk_...`) scoped to (userId, machineId, agentId). The daemon's* `CredentialBroker` swaps this runner key in for the agent's per-launch* voucher at its local credential proxy, so subprocess CLIs never see it- * directly — they only reach `/api/community/agent/*` through that proxy.+ * directly — they only reach canonical `/api/community/*` REST doors through+ * that proxy.*/export const POST = withCommunityDaemonAuth(async (req, ctx) => {let raw: unknown@@ -38,7 +40,10 @@ export const POST = withCommunityDaemonAuth(async (req, ctx) => {// AND its binding must point to this machine. Prevents a compromised daemon// on machine A from minting a `crk_` for a bot bound to machine B (which// would otherwise slip through the old blind-mint path).- const target = await queries.user.getUserInternal(db, parsed.data.agentId)+ const target = await withD1Retry(+ () => queries.user.getUserInternal(db, parsed.data.agentId),+ { route: "community/daemon/enroll-agent:target" }+ )if (!target ||target.isBot !== true ||@@ -47,7 +52,10 @@ export const POST = withCommunityDaemonAuth(async (req, ctx) => {) {return NextResponse.json({ error: "bot not found" }, { status: 404 })}- const binding = await queries.communityBot.getBotBinding(db, parsed.data.agentId)+ const binding = await withD1Retry(+ () => queries.communityBot.getBotBinding(db, parsed.data.agentId),+ { route: "community/daemon/enroll-agent:binding" }+ )if (!binding || binding.machineId !== ctx.machineId) {return NextResponse.json({ error: "bot not on this machine" }, { status: 404 })}diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts b/src/web/src/app/api/community/dm/[id]/messages/route.test.tsdeleted file mode 100644index 0ed180eee..000000000--- a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts+++ /dev/null@@ -1,441 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--const mockGetDM = vi.fn()-const mockGetDMPeer = vi.fn()-const mockIsBlocked = vi.fn()-const mockCreateMessage = vi.fn()-const mockGetMessage = vi.fn()-const mockGetMessageByAuthorAndNonce = vi.fn()-const mockGetMessageInScope = vi.fn()-const mockGetMessagesByIdsInScope = vi.fn()-const mockListMessages = vi.fn()-const mockListMessagesAround = vi.fn()-const mockListMessagesSince = vi.fn()-const mockGetLatestMessageSeq = vi.fn()-const mockListByMessageIds = vi.fn()-const mockListReactionsByMessageIds = vi.fn()-const mockListMembers = vi.fn()-const mockListMemberUserIds = vi.fn()-const mockCreateAttachment = vi.fn()-const mockGetUserInternal = vi.fn()--const mockFanOutToChannel = vi.fn()-const mockFanOutToDM = vi.fn()-const mockResolveChannelRecipients = vi.fn(async () => [] as string[])-const mockDispatchMessageNotify = vi.fn(async () => {})-const mockBroadcastToUser = vi.fn()-const mockCheckMessageRateLimit = vi.fn()--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--vi.mock("@/lib/rate-limit", () => ({- checkRateLimit: (...a: unknown[]) => mockCheckMessageRateLimit(...a),-}))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityDm: {- getDM: (...a: unknown[]) => mockGetDM(...a),- getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),- },- communityFriendship: {- isBlocked: (...a: unknown[]) => mockIsBlocked(...a),- hydrateApprovalsForDmMessages: vi.fn(async () => new Map()),- },- communityMessage: {- createMessage: (...a: unknown[]) => mockCreateMessage(...a),- getMessage: (...a: unknown[]) => mockGetMessage(...a),- getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),- getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),- getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),- listMessages: (...a: unknown[]) => mockListMessages(...a),- listMessagesAround: (...a: unknown[]) => mockListMessagesAround(...a),- listMessagesSince: (...a: unknown[]) => mockListMessagesSince(...a),- getLatestMessageSeq: (...a: unknown[]) => mockGetLatestMessageSeq(...a),- },- communityMember: {- listMembers: (...a: unknown[]) => mockListMembers(...a),- listMemberUserIds: (...a: unknown[]) => mockListMemberUserIds(...a),- },- communityMention: {- createMentions: vi.fn(),- },- communityAttachment: {- createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),- listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),- },- communityReaction: {- listReactionsByMessageIds: (...a: unknown[]) =>- mockListReactionsByMessageIds(...a),- },- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- },- },- }-})--vi.mock("@/lib/community/fanout", () => ({- fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),- fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),- resolveChannelRecipients: (...a: unknown[]) => mockResolveChannelRecipients(...a),-}))--vi.mock("@/lib/community/notify", () => ({- dispatchMessageNotify: (...a: unknown[]) => mockDispatchMessageNotify(...a),-}))--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number, headers?: Record<string, string>) =>- NextResponse.json({ error: message }, { status, ...(headers ? { headers } : {}) }),- }-})--import { GET, POST } from "./route"--function postReq(body: unknown) {- return new NextRequest("http://localhost/api/community/dm/d1/messages", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- })-}--function getReq() {- return new NextRequest("http://localhost/api/community/dm/d1/messages", {- method: "GET",- })-}--const ctx = { params: { id: "d1" } } as any--describe("POST /api/community/dm/[id]/messages", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetDM.mockResolvedValue({- id: "d1",- lastMessageAt: null,- createdAt: "2026-06-30T00:00:00.000Z",- })- mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })- // Human author by default — `createCommunityMessage`'s bot-authored audit- // (plan §10) only fires when `isBot === true`, which none of these tests exercise.- mockGetUserInternal.mockResolvedValue({ isBot: false, deletedAt: null })- mockFanOutToChannel.mockResolvedValue(undefined)- mockFanOutToDM.mockResolvedValue(undefined)- mockBroadcastToUser.mockResolvedValue(undefined)- mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })- mockGetMessageByAuthorAndNonce.mockResolvedValue(null)- })-- it("returns 429 with Retry-After when the sender is rate limited", async () => {- mockIsBlocked.mockResolvedValue(false)- mockCheckMessageRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 4 })-- const res = await POST(postReq({ content: "hi" }), ctx)-- expect(res.status).toBe(429)- expect(res.headers.get("Retry-After")).toBe("4")- expect(mockCreateMessage).not.toHaveBeenCalled()- expect(mockFanOutToChannel).not.toHaveBeenCalled()- })-- it("returns 403 when the DM counterpart is blocked", async () => {- mockIsBlocked.mockResolvedValue(true)-- const res = await POST(postReq({ content: "hi" }), ctx)-- expect(res.status).toBe(403)- expect(mockCreateMessage).not.toHaveBeenCalled()- expect(mockFanOutToChannel).not.toHaveBeenCalled()- })-- it("does not query members for a DM post (target.kind === 'dm')", async () => {- // DMs have no member roster and no @-anyone semantics — neither- // listMembers nor listMemberUserIds should ever fire.- mockIsBlocked.mockResolvedValue(false)- mockCreateMessage.mockResolvedValue({ id: "m1" })- mockGetMessage.mockResolvedValue({- id: "m1",- authorId: "u1",- authorName: "Alice",- authorImage: null,- authorEmail: "[email protected]",- content: "hi @Bob",- type: "default",- mentionType: null,- replyToId: null,- embeds: null,- createdAt: "2026-06-30T00:00:00.000Z",- })-- const res = await POST(postReq({ content: "hi @Bob" }), ctx)- expect(res.status).toBe(201)- expect(mockListMembers).not.toHaveBeenCalled()- expect(mockListMemberUserIds).not.toHaveBeenCalled()- })-- it("returns canonical id, seq, and clientNonce for fresh and replayed sends", async () => {- mockIsBlocked.mockResolvedValue(false)- mockCreateMessage.mockResolvedValue({ id: "m1" })- mockGetMessage.mockResolvedValue({- id: "m1",- seq: 12,- clientNonce: "n1",- authorId: "u1",- authorName: "Alice",- authorImage: null,- authorEmail: "[email protected]",- content: "hi",- type: "default",- mentionType: null,- replyToId: null,- embeds: null,- createdAt: "2026-06-30T00:00:00.000Z",- })-- const fresh = await POST(postReq({ content: "hi", nonce: "n1" }), ctx)- expect(await fresh.json()).toEqual({- message: expect.objectContaining({ id: "m1", seq: 12, clientNonce: "n1" }),- })-- mockGetMessageByAuthorAndNonce.mockResolvedValue({ id: "m1", seq: 12, clientNonce: "n1" })- const replay = await POST(postReq({ content: "hi", nonce: "n1" }), ctx)- expect(await replay.json()).toEqual({- message: expect.objectContaining({ id: "m1", seq: 12, clientNonce: "n1" }),- deduped: true,- })- })-})--describe("GET /api/community/dm/[id]/messages", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetDM.mockResolvedValue({- id: "d1",- lastMessageAt: null,- createdAt: "2026-06-30T00:00:00.000Z",- })- mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })- // Every route branch calls `getLatestMessageSeq` — default to 0 so tests- // don't have to wire it individually.- mockGetLatestMessageSeq.mockResolvedValue(0)- })-- it("returns 403 and never reads messages when the counterpart is blocked", async () => {- // A blocked relationship must hide historical DM messages — the listMessages- // query should never run for the blocked party. This is a security contract,- // not just a UX nicety; lock it in.- mockIsBlocked.mockResolvedValue(true)-- const res = await GET(getReq(), ctx)-- expect(res.status).toBe(403)- expect(mockListMessages).not.toHaveBeenCalled()- })-- it("resolves reply previews via one scoped getMessagesByIdsInScope call (never per-item getMessage)", async () => {- // 5-message page. 3 have replyToId set:- // m-a → target r-in-scope (same DM) → resolves.- // m-b → target r-out-of-scope (a different DM) → the scoped query never- // returns it (it's filtered in SQL, not in application code) → deleted: true.- // m-c → target r-missing → deleted: true.- // m-d → replies to r-in-scope again → resolves.- // m-e → no reply.- mockIsBlocked.mockResolvedValue(false)- mockListMessages.mockResolvedValue([- { id: "m-a", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hey", type: "default", mentionType: null, replyToId: "r-in-scope", dmConversationId: "d1", embeds: null, createdAt: "t1" },- { id: "m-b", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "leak?", type: "default", mentionType: null, replyToId: "r-out-of-scope", dmConversationId: "d1", embeds: null, createdAt: "t2" },- { id: "m-c", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "gone", type: "default", mentionType: null, replyToId: "r-missing", dmConversationId: "d1", embeds: null, createdAt: "t3" },- { id: "m-d", authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, content: "again", type: "default", mentionType: null, replyToId: "r-in-scope", dmConversationId: "d1", embeds: null, createdAt: "t4" },- { id: "m-e", authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, content: "no reply", type: "default", mentionType: null, replyToId: null, dmConversationId: "d1", embeds: null, createdAt: "t5" },- ])- mockListByMessageIds.mockResolvedValue([])- mockListReactionsByMessageIds.mockResolvedValue([])- // The (mocked) scoped query only ever returns in-scope rows — "r-out-of-scope"- // and "r-missing" are absent, simulating the real WHERE-clause scoping.- mockGetMessagesByIdsInScope.mockResolvedValue([- { id: "r-in-scope", authorName: "Zed", content: "original", dmConversationId: "d1", channelId: null },- ])-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)- const body = await res.json() as { messages: Array<{ id: string; replyTo?: { id: string; authorName: string; text: string; deleted?: boolean } }> }- // route reverses the messages array before returning.- const byId = new Map(body.messages.map((m) => [m.id, m]))-- expect(byId.get("m-a")?.replyTo).toEqual({ id: "r-in-scope", authorName: "Zed", text: "original" })- expect(byId.get("m-b")?.replyTo).toEqual({ id: "r-out-of-scope", authorName: "Unknown", text: "", deleted: true })- expect(byId.get("m-c")?.replyTo).toEqual({ id: "r-missing", authorName: "Unknown", text: "", deleted: true })- expect(byId.get("m-d")?.replyTo).toEqual({ id: "r-in-scope", authorName: "Zed", text: "original" })- expect(byId.get("m-e")?.replyTo).toBeUndefined()-- // Single batched, scoped fetch — no per-item getMessage.- expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)- expect(mockGetMessage).not.toHaveBeenCalled()- const [, ids, scope] = mockGetMessagesByIdsInScope.mock.calls[0]- expect(ids.sort()).toEqual(["r-in-scope", "r-in-scope", "r-missing", "r-out-of-scope"].sort())- expect(scope).toEqual({ channelId: "d1" })- })-- it("runs attachment, reaction, reply-target, and latest-seq fetches in parallel", async () => {- // The 4 follow-up fetches have no cross-dependency; they must run- // concurrently (Promise.all), not sequentially. Prove it by observing- // in-flight count — all 4 must be dispatched before any resolves.- mockIsBlocked.mockResolvedValue(false)- mockListMessages.mockResolvedValue([- { id: "m-1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hi", type: "default", mentionType: null, replyToId: "r-1", dmConversationId: "d1", embeds: null, createdAt: "t1" },- ])-- let inFlight = 0- let maxInFlight = 0- async function tracked<T>(value: T): Promise<T> {- inFlight++- maxInFlight = Math.max(maxInFlight, inFlight)- await new Promise((r) => setTimeout(r, 15))- inFlight--- return value- }- mockListByMessageIds.mockImplementation(() => tracked([]))- mockListReactionsByMessageIds.mockImplementation(() => tracked([]))- mockGetMessagesByIdsInScope.mockImplementation(() => tracked([]))- mockGetLatestMessageSeq.mockImplementation(() => tracked(0))-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)-- expect(maxInFlight).toBe(4)- expect(mockListByMessageIds).toHaveBeenCalledTimes(1)- expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)- expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)- expect(mockGetLatestMessageSeq).toHaveBeenCalledTimes(1)- })-- it("always includes latestSeq in the legacy-mode envelope", async () => {- mockIsBlocked.mockResolvedValue(false)- mockListMessages.mockResolvedValue([])- mockListByMessageIds.mockResolvedValue([])- mockListReactionsByMessageIds.mockResolvedValue([])- mockGetLatestMessageSeq.mockResolvedValue(23)- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)- const body = (await res.json()) as { latestSeq: number }- expect(body.latestSeq).toBe(23)- expect(mockGetLatestMessageSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "d1" })- })-- describe("?anchor mode", () => {- it("returns a centered window with the anchor row present, plus latestSeq + cursors", async () => {- mockIsBlocked.mockResolvedValue(false)- mockGetMessageInScope.mockResolvedValue({- id: "m_anchor",- createdAt: "2026-06-30T00:00:03.000Z",- })- mockListMessagesAround.mockResolvedValue({- older: [- { id: "m_o1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "o1", type: "default", mentionType: null, replyToId: null, dmConversationId: "d1", embeds: null, createdAt: "2026-06-30T00:00:02.000Z" },- ],- newer: [- { id: "m_anchor", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "anchor", type: "default", mentionType: null, replyToId: null, dmConversationId: "d1", embeds: null, createdAt: "2026-06-30T00:00:03.000Z" },- { id: "m_n1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "n1", type: "default", mentionType: null, replyToId: null, dmConversationId: "d1", embeds: null, createdAt: "2026-06-30T00:00:04.000Z" },- ],- hasMoreOlder: false,- hasMoreNewer: true,- })- mockListByMessageIds.mockResolvedValue([])- mockListReactionsByMessageIds.mockResolvedValue([])- mockGetLatestMessageSeq.mockResolvedValue(11)-- const req = new NextRequest("http://localhost/api/community/dm/d1/messages?anchor=m_anchor", {- method: "GET",- })- const res = await GET(req, ctx)- expect(res.status).toBe(200)- const body = (await res.json()) as {- messages: Array<{ id: string }>- hasMoreOlder: boolean- hasMoreNewer: boolean- olderCursor?: string- newerCursor?: string- latestSeq: number- }- expect(body.messages.map((m) => m.id)).toEqual(["m_o1", "m_anchor", "m_n1"])- expect(body.hasMoreOlder).toBe(false)- expect(body.hasMoreNewer).toBe(true)- expect(body.olderCursor).toBeUndefined()- expect(body.newerCursor).toBe(`2026-06-30T00:00:04.000Z|m_n1`)- expect(body.latestSeq).toBe(11)- // Scope-first resolve: anchor lookup passes the DM channel scope.- expect(mockGetMessageInScope).toHaveBeenCalledWith(expect.anything(), "m_anchor", { channelId: "d1" })- })-- it("returns 404 when the anchor is not visible in this DM", async () => {- mockIsBlocked.mockResolvedValue(false)- mockGetMessageInScope.mockResolvedValue(null)- const req = new NextRequest("http://localhost/api/community/dm/d1/messages?anchor=m_missing", {- method: "GET",- })- const res = await GET(req, ctx)- expect(res.status).toBe(404)- expect(mockListMessagesAround).not.toHaveBeenCalled()- })- })-- describe("?since mode", () => {- it("returns rows strictly newer than the cursor with hasMoreNewer + newerCursor + latestSeq", async () => {- mockIsBlocked.mockResolvedValue(false)- mockListMessagesSince.mockResolvedValue([- { id: "m_1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "1", type: "default", mentionType: null, replyToId: null, dmConversationId: "d1", embeds: null, createdAt: "2026-06-30T00:00:01.000Z" },- ])- mockListByMessageIds.mockResolvedValue([])- mockListReactionsByMessageIds.mockResolvedValue([])- mockGetLatestMessageSeq.mockResolvedValue(1)-- const req = new NextRequest(- "http://localhost/api/community/dm/d1/messages?since=2026-06-30T00:00:00.000Z%7Cm_0",- { method: "GET" },- )- const res = await GET(req, ctx)- expect(res.status).toBe(200)- const body = (await res.json()) as {- messages: Array<{ id: string }>- hasMoreNewer: boolean- newerCursor?: string- hasMoreOlder: boolean- olderCursor?: string- latestSeq: number- }- expect(body.messages.map((m) => m.id)).toEqual(["m_1"])- expect(body.hasMoreNewer).toBe(false)- expect(body.latestSeq).toBe(1)- // A since delta must carry an older-side signal so it can be paged back- // through if it lands as the sole/oldest cache page (the DM-history bug).- expect(body.hasMoreOlder).toBe(true)- expect(body.olderCursor).toBe("2026-06-30T00:00:01.000Z|m_1")- expect(mockGetMessageInScope).not.toHaveBeenCalled()- expect(mockListMessagesAround).not.toHaveBeenCalled()- })- })-})diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.ts b/src/web/src/app/api/community/dm/[id]/messages/route.tsdeleted file mode 100644index 77b056f1c..000000000--- a/src/web/src/app/api/community/dm/[id]/messages/route.ts+++ /dev/null@@ -1,113 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import {- parseCursor,- parseAnchor,- parsePageSize,- buildPaginatedResponse,- buildAnchorResponse,- buildSinceResponse,-} from "@/lib/community/messages"-import { enrichMessages } from "@/lib/community/enrich-messages"-import { requireDMAccess } from "@/lib/community/permissions"-import { checkRateLimit } from "@/lib/rate-limit"-import { createCommunityMessage } from "@/lib/community/message-handler"--export const GET = withAuth(async (req: NextRequest, ctx) => {- const dmId = ctx.params?.id- if (!dmId) return writeError("missing dm id", 400)-- const db = getDb(ctx.env.DB)- const auth = await requireDMAccess(db, dmId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- const params = req.nextUrl.searchParams- const anchorId = parseAnchor(params.get("anchor"))- const since = parseCursor(params.get("since"))- const cursor = parseCursor(params.get("cursor"))- const pageSize = parsePageSize(params.get("limit"))-- if (anchorId) {- const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { channelId: dmId })- if (!anchor) return writeError("anchor not found", 404)-- const around = await queries.communityMessage.listMessagesAround(db, {- channelId: dmId,- anchor: { createdAt: anchor.createdAt, id: anchor.id },- limit: pageSize,- })-- const { items, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor } = buildAnchorResponse(- around.older,- around.newer,- { hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },- )-- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId: dmId, isDm: true }, items)- return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })- }-- if (since) {- const rows = await queries.communityMessage.listMessagesSince(db, {- channelId: dmId,- since,- limit: pageSize,- })- const { items, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor } = buildSinceResponse(rows, pageSize)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId: dmId, isDm: true }, items)- return writeJSON({ messages, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor, latestSeq })- }-- const rows = await queries.communityMessage.listMessages(db, {- channelId: dmId,- cursor,- limit: pageSize + 1,- })-- const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)- const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId: dmId, isDm: true }, items.slice().reverse())- return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })-})--export const POST = withAuth(async (req: NextRequest, ctx) => {- const dmId = ctx.params?.id- if (!dmId) return writeError("missing dm id", 400)-- const db = getDb(ctx.env.DB)- const auth = await requireDMAccess(db, dmId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- const rateLimit = await checkRateLimit(ctx.env, "community:msgSend", ctx.userId)- if (!rateLimit.allowed) {- return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })- }-- let body: unknown- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- // Idempotency nonce — mirror the channel send path (mutation-idempotency- // plan): reuse the same nonce across retry-pill clicks so a 500-after-commit- // resend dedupes server-side. Absent nonce = today's behavior.- const clientNonce =- typeof (body as { nonce?: unknown })?.nonce === "string"- ? (body as { nonce: string }).nonce- : undefined-- const result = await createCommunityMessage({- db,- authorId: ctx.userId,- target: { kind: "dm", channelId: dmId, otherUserId: auth.value.otherUserId },- body: body as Record<string, unknown>,- clientNonce,- })- if (!result.ok) return writeError(result.error, result.status)-- return writeJSON({ message: result.row, deduped: result.deduped }, 201)-})diff --git a/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts b/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.tsdeleted file mode 100644index 73244e3e0..000000000--- a/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts+++ /dev/null@@ -1,41 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { requireDMAccess } from "@/lib/community/permissions"--/**- * GET /api/community/dm/:id/messages/seq/:seq- *- * Resolve a seq number to its message ID within a DM. Used for message- * ref jumping: when the user clicks #123 and that message isn't loaded, we- * need its ID to trigger an anchor fetch.- *- * Returns: { id: string } | { error: "not_found" }- */-export const GET = withAuth(async (req: NextRequest, ctx) => {- const dmId = ctx.params?.id- const seqStr = ctx.params?.seq- if (typeof dmId !== "string" || typeof seqStr !== "string") {- return writeJSON({ error: "invalid_params" }, 400)- }-- const seq = parseInt(seqStr, 10)- if (isNaN(seq) || seq <= 0) {- return writeJSON({ error: "invalid_seq" }, 400)- }-- const db = getDb(ctx.env.DB)-- // Permission check: user must be a participant in this DM- const auth = await requireDMAccess(db, dmId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { channelId: dmId }, seq)- if (!message) {- return writeJSON({ error: "not_found" }, 404)- }-- return writeJSON({ id: message.id })-})diff --git a/src/web/src/app/api/community/dm/[id]/read-state/route.test.ts b/src/web/src/app/api/community/dm/[id]/read-state/route.test.tsdeleted file mode 100644index d1f920cba..000000000--- a/src/web/src/app/api/community/dm/[id]/read-state/route.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--const mockGetReadState = vi.fn()-const mockRequireDMAccess = 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: {- communityReadState: {- getReadState: (...a: unknown[]) => mockGetReadState(...a),- },- },- }-})--vi.mock("@/lib/community/permissions", () => ({- requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--function getReq() {- return new NextRequest(- "http://localhost/api/community/dm/dm1/read-state",- { method: "GET" },- )-}--describe("GET /api/community/dm/[id]/read-state", () => {- beforeEach(() => {- vi.clearAllMocks()- mockRequireDMAccess.mockResolvedValue({ ok: true })- })-- it("returns { null, null, 0 } when no read-state row exists (never-opened dm)", async () => {- mockGetReadState.mockResolvedValue(null)-- const res = await GET(getReq(), { params: { id: "dm1" } } as any)- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({ lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 })- // Args to getReadState should scope by (userId, dmConversationId).- expect(mockGetReadState).toHaveBeenCalledWith(expect.anything(), {- userId: "u1",- channelId: "dm1",- })- })-- it("returns the actual (lastReadMessageId, lastReadAt, lastReadSeq) tuple when a row exists", async () => {- mockGetReadState.mockResolvedValue({- lastReadMessageId: "m_42",- lastReadAt: "2026-07-01T00:00:00.000Z",- lastReadSeq: 42,- })-- const res = await GET(getReq(), { params: { id: "dm1" } } as any)- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({- lastReadMessageId: "m_42",- lastReadAt: "2026-07-01T00:00:00.000Z",- lastReadSeq: 42,- })- })-- it("returns 400 when the dm id is missing", async () => {- const res = await GET(getReq(), { params: {} } as any)- expect(res.status).toBe(400)- expect(mockRequireDMAccess).not.toHaveBeenCalled()- expect(mockGetReadState).not.toHaveBeenCalled()- })-- it("returns 403 when the caller is not a participant", async () => {- mockRequireDMAccess.mockResolvedValue({- ok: false,- error: "not a participant",- status: 403,- })-- const res = await GET(getReq(), { params: { id: "dm1" } } as any)- expect(res.status).toBe(403)- expect(mockGetReadState).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/community/dm/[id]/read-state/route.ts b/src/web/src/app/api/community/dm/[id]/read-state/route.tsdeleted file mode 100644index a8981f85b..000000000--- a/src/web/src/app/api/community/dm/[id]/read-state/route.ts+++ /dev/null@@ -1,49 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries, withD1Retry } from "@alook/shared"-import { requireDMAccess } from "@/lib/community/permissions"--/**- * GET /api/community/dm/:id/read-state- *- * DM twin of `GET /channels/:id/read-state`. Snapshot of the viewer's read- * pointer for a single DM. Consumed once per DM mount to compute the "New"- * divider anchor and initial scroll position. Returns `{ null, null, 0 }`- * when the viewer has never opened the DM — the caller treats that as- * "everything is new, but no divider (start at the bottom)", matching common- * chat-app first-visit UX.- *- * `requireDMAccess` handles both unknown-DM and non-participant cases (the DM- * permission helper collapses them, unlike the channel route which surfaces a- * 404 for unknown ids).- */-export const GET = withAuth(async (_req: NextRequest, ctx) => {- const dmId = ctx.params?.id- if (!dmId) return writeError("missing dm id", 400)-- const db = getDb(ctx.env.DB)- const auth = await requireDMAccess(db, dmId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- // Server-side retry stack. See channel twin for the invariant.- const row = await withD1Retry(- () => queries.communityReadState.getReadState(db, {- userId: ctx.userId,- channelId: dmId,- }),- { route: "community/dm/read-state" },- )-- return writeJSON({- lastReadMessageId: row?.lastReadMessageId ?? null,- lastReadAt: row?.lastReadAt ?? null,- // Seq is the numeric equivalent of the (createdAt, id) pointer — used- // client-side to compute the `↓ N` unread count without walking the- // loaded rows (`latestSeq - lastReadSeq`). Falls back to 0 when the- // viewer has never visited: `latestSeq - 0` = all-messages-are-new,- // matching what the divider anchor implies.- lastReadSeq: row?.lastReadSeq ?? 0,- })-})diff --git a/src/web/src/app/api/community/dm/[id]/read/route.test.ts b/src/web/src/app/api/community/dm/[id]/read/route.test.tsdeleted file mode 100644index 68a80de2d..000000000--- a/src/web/src/app/api/community/dm/[id]/read/route.test.ts+++ /dev/null@@ -1,147 +0,0 @@-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 mockGetLatestMessage = vi.fn()-const mockMarkReadToMessage = vi.fn()-const mockRequireDMAccess = 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: {- communityMessage: {- getMessage: (...a: unknown[]) => mockGetMessage(...a),- getLatestMessage: (...a: unknown[]) => mockGetLatestMessage(...a),- },- communityReadState: {- markReadToMessage: (...a: unknown[]) => mockMarkReadToMessage(...a),- },- },- }-})--vi.mock("@/lib/community/permissions", () => ({- requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { PUT } from "./route"--function putReq(body?: unknown) {- return new NextRequest("http://localhost/api/community/dm/dm1/read", {- method: "PUT",- body: body === undefined ? undefined : JSON.stringify(body),- headers: body === undefined ? undefined : { "Content-Type": "application/json" },- })-}--describe("PUT /api/community/dm/[id]/read", () => {- beforeEach(() => {- vi.clearAllMocks()- mockMarkReadToMessage.mockResolvedValue(undefined)- mockRequireDMAccess.mockResolvedValue({ ok: true })- })-- it("body id present: aligns write to the message when it belongs to this dm", async () => {- mockGetMessage.mockResolvedValue({- id: "m9",- channelId: "dm1",- createdAt: "2026-07-04T09:00:00.000Z",- })-- const res = await PUT(putReq({ lastReadMessageId: "m9" }), { params: { id: "dm1" } } as any)- expect(res.status).toBe(200)-- expect(mockGetMessage).toHaveBeenCalledWith(expect.anything(), "m9")- expect(mockMarkReadToMessage).toHaveBeenCalledWith(expect.anything(), {- userId: "u1",- channelId: "dm1",- message: { id: "m9", createdAt: "2026-07-04T09:00:00.000Z" },- })- expect(mockGetLatestMessage).not.toHaveBeenCalled()- })-- it("body id present but message belongs to another dm → 400, no write", async () => {- mockGetMessage.mockResolvedValue({- id: "m9",- channelId: "dm_other",- createdAt: "2026-07-04T09:00:00.000Z",- })-- const res = await PUT(putReq({ lastReadMessageId: "m9" }), { params: { id: "dm1" } } as any)- expect(res.status).toBe(400)- expect(mockMarkReadToMessage).not.toHaveBeenCalled()- })-- it("body id present but message does not exist → 400, no write", async () => {- mockGetMessage.mockResolvedValue(null)-- const res = await PUT(putReq({ lastReadMessageId: "m_ghost" }), { params: { id: "dm1" } } as any)- expect(res.status).toBe(400)- expect(mockMarkReadToMessage).not.toHaveBeenCalled()- })-- it("no body: uses latest DM message and aligns write to it", async () => {- mockGetLatestMessage.mockResolvedValue({- id: "m_latest",- createdAt: "2026-07-05T10:00:00.000Z",- })-- const res = await PUT(putReq(), { params: { id: "dm1" } } as any)- expect(res.status).toBe(200)- expect(mockGetLatestMessage).toHaveBeenCalledWith(expect.anything(), { channelId: "dm1" })- expect(mockMarkReadToMessage).toHaveBeenCalledWith(expect.anything(), {- userId: "u1",- channelId: "dm1",- message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z" },- })- expect(mockGetMessage).not.toHaveBeenCalled()- })-- it("no body on EMPTY dm: no write at all, returns 200 { ok: true }", async () => {- mockGetLatestMessage.mockResolvedValue(null)-- const res = await PUT(putReq(), { params: { id: "dm1" } } as any)- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ ok: true })- expect(mockMarkReadToMessage).not.toHaveBeenCalled()- })-- it("returns 400 when the dm id is missing", async () => {- const res = await PUT(putReq(), { params: {} } as any)- expect(res.status).toBe(400)- expect(mockRequireDMAccess).not.toHaveBeenCalled()- })-- it("returns permission error when caller is not a participant", async () => {- mockRequireDMAccess.mockResolvedValue({ ok: false, error: "not a participant", status: 403 })-- const res = await PUT(putReq(), { params: { id: "dm1" } } as any)- expect(res.status).toBe(403)- expect(mockMarkReadToMessage).not.toHaveBeenCalled()- expect(mockGetLatestMessage).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/community/dm/[id]/read/route.ts b/src/web/src/app/api/community/dm/[id]/read/route.tsdeleted file mode 100644index 22824670d..000000000--- a/src/web/src/app/api/community/dm/[id]/read/route.ts+++ /dev/null@@ -1,51 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { requireDMAccess } from "@/lib/community/permissions"--/**- * PUT /api/community/dm/:id/read- *- * DM twin of `PUT /channels/:id/read`.- * - Body `{ lastReadMessageId }` present → verify the message lives in this- * DM, then align to it.- * - Body absent / empty → align to the DM's latest message. Empty DM →- * no-op (invariant forbids `lastReadMessageId = null` rows).- */-export const PUT = withAuth(async (req: NextRequest, ctx) => {- const dmId = ctx.params?.id- if (!dmId) return writeError("missing dm id", 400)-- const db = getDb(ctx.env.DB)- const auth = await requireDMAccess(db, dmId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- let body: { lastReadMessageId?: string } = {}- try {- body = await req.json()- } catch {- // Body is optional- }-- let target: { id: string; createdAt: string; seq: number } | null- if (body.lastReadMessageId) {- const msg = await queries.communityMessage.getMessage(db, body.lastReadMessageId)- if (!msg || msg.channelId !== dmId) {- return writeError("lastReadMessageId does not belong to this dm", 400)- }- target = { id: msg.id, createdAt: msg.createdAt, seq: msg.seq }- } else {- target = await queries.communityMessage.getLatestMessage(db, { channelId: dmId })- if (!target) return writeJSON({ ok: true })- }-- await queries.communityReadState.markReadToMessage(db, {- userId: ctx.userId,- channelId: dmId,- message: target,- })-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/community/dm/[id]/upload/route.test.ts b/src/web/src/app/api/community/dm/[id]/upload/route.test.tsdeleted file mode 100644index 47ac21012..000000000--- a/src/web/src/app/api/community/dm/[id]/upload/route.test.ts+++ /dev/null@@ -1,67 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockRunAttachmentUpload = vi.fn()-const mockRequireDMAccess = vi.fn()--vi.mock("@/lib/community/upload", () => ({- runAttachmentUpload: (...a: unknown[]) => mockRunAttachmentUpload(...a),-}))--vi.mock("@/lib/community/permissions", () => ({- requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...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- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- },-}))--import { POST } from "./route"--function postReq() {- return new NextRequest("http://localhost/api/community/dm/d1/upload", {- method: "POST",- })-}--const ctx = { params: { id: "d1" } } as any--describe("POST /api/community/dm/[id]/upload", () => {- beforeEach(() => {- vi.clearAllMocks()- mockRunAttachmentUpload.mockResolvedValue(- new Response(null, { status: 200 }),- )- })-- it("delegates to runAttachmentUpload with kind='dm' + requireDMAccess", async () => {- // DM uploads must go through the DM-scoped permission check, which also- // enforces the block relationship. Any drift away from requireDMAccess- // would silently open uploads to a blocked counterpart — pin the binding.- const req = postReq()- await POST(req, ctx)- expect(mockRunAttachmentUpload).toHaveBeenCalledOnce()- const [passedReq, passedCtx, kind, permCheck] =- mockRunAttachmentUpload.mock.calls[0]- expect(passedReq).toBe(req)- expect(passedCtx).toMatchObject({ userId: "u1", params: { id: "d1" } })- expect(kind).toBe("dm")- // Invoke the passed permission-check reference and observe the underlying- // mock — pins the route to `requireDMAccess` (a swap to another- // helper would hit a different mock).- await (permCheck as (...a: unknown[]) => unknown)("db", "d1", "u1")- expect(mockRequireDMAccess).toHaveBeenCalledWith("db", "d1", "u1")- })-- it("returns whatever runAttachmentUpload returns unchanged", async () => {- const helperResponse = new Response(JSON.stringify({ ok: 1 }), {- status: 201,- })- mockRunAttachmentUpload.mockResolvedValueOnce(helperResponse)- const res = await POST(postReq(), ctx)- expect(res).toBe(helperResponse)- })-})diff --git a/src/web/src/app/api/community/dm/[id]/upload/route.ts b/src/web/src/app/api/community/dm/[id]/upload/route.tsdeleted file mode 100644index bcd5a2f34..000000000--- a/src/web/src/app/api/community/dm/[id]/upload/route.ts+++ /dev/null@@ -1,8 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { requireDMAccess } from "@/lib/community/permissions"-import { runAttachmentUpload } from "@/lib/community/upload"--export const POST = withAuth((req: NextRequest, ctx) =>- runAttachmentUpload(req, ctx, "dm", requireDMAccess),-)diff --git a/src/web/src/app/api/community/dm/route.ts b/src/web/src/app/api/community/dm/route.tsdeleted file mode 100644index 42f515f8c..000000000--- a/src/web/src/app/api/community/dm/route.ts+++ /dev/null@@ -1,47 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { guardDmOpen } from "@/lib/community/dm-guard"-import { avatarInitial } from "@/lib/community/avatar"--export const GET = withAuth(async (_req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)- const rows = await queries.communityDm.listDMs(db, ctx.userId)- const conversations = rows.map((r) => ({- id: r.id,- userId: r.otherUserId,- name: r.otherUserName,- discriminator: r.otherUserDiscriminator,- avatar: r.otherUserImage ?? avatarInitial(r.otherUserName),- status: "offline" as const,- preview: "",- }))- return writeJSON({ conversations })-})--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- let body: { userId: string }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- if (!body.userId) return writeError("userId is required", 400)-- // Default callerKind ("human") — 404-on-friend-failure / pass-as-human- // preserved exactly as this route's pre-extraction behavior.- const guard = await guardDmOpen(db, ctx.userId, body.userId)- if (!guard.ok) return writeError(guard.error, guard.status)-- const dm = await queries.communityDm.createOrGetDM(db, {- userId1: ctx.userId,- userId2: body.userId,- })-- return writeJSON({ conversation: dm })-})diff --git a/src/web/src/app/api/community/friendRequest/route.test.ts b/src/web/src/app/api/community/friendRequest/route.test.tsdeleted file mode 100644index 6660b66e2..000000000--- a/src/web/src/app/api/community/friendRequest/route.test.ts+++ /dev/null@@ -1,208 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a no-`crk_` request falls through to the human withAuth path.-// Mock Better-Auth to "no session" so a no-auth request yields the human-path-// 401 instead of a 503 from unmocked session validation.-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetUserPublic = vi.fn()-const mockGetUserByNameAndDiscriminator = vi.fn()-const mockGetBotBinding = vi.fn()-const mockIsBlocked = vi.fn()-const mockSendRequest = vi.fn()-const mockEnsureSibling = vi.fn()-const mockBroadcastToUser = vi.fn(async () => undefined)-const mockLogAudit = vi.fn()--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),-}))-vi.mock("@/lib/community/audit", async () => {- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }-})--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),- getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),- },- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityFriendship: {- isBlocked: (...a: unknown[]) => mockIsBlocked(...a),- sendRequest: (...a: unknown[]) => mockSendRequest(...a),- ensureSiblingBotFriendship: (...a: unknown[]) => mockEnsureSibling(...a),- },- },- }-})--import { POST } from "./route"--const BOT = "bot_zoe"-const OWNER = "owner_bob"--function req(body: unknown, headers: Record<string, string> = { Authorization: "Bearer crk_abc" }): NextRequest {- return new NextRequest("http://localhost/api/community/agent/friendRequest", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--describe("POST /api/community/agent/friendRequest", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: OWNER, machineId: "m_1", agentId: BOT })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- // getUserInternal is called by the auth middleware (bot) AND the route- // (target). Route by id.- mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {- if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }- return null- })- mockGetUserPublic.mockResolvedValue({ id: OWNER, name: "Bob", discriminator: "0001" })- mockIsBlocked.mockResolvedValue(false)- })-- it("401 without Authorization", async () => {- const res = await POST(req({ username: "Alice#0042" }, {}))- expect(res.status).toBe(401)- })-- it("bot→human happy path: 200 pending with a hint naming the owner", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "u_alice" })- mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {- if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }- if (id === "u_alice") return { id: "u_alice", isBot: false, deletedAt: null, ownerUserId: null }- return null- })- mockSendRequest.mockResolvedValue({- kind: "created",- friendship: { id: "fr_1" },- supersededIds: [],- broadcasts: [{ userId: OWNER, event: { type: "community:dm.new_message" } }],- })- const res = await POST(req({ username: "Alice#0042" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body.status).toBe("pending")- expect(body.friendshipId).toBe("fr_1")- expect(body.hint).toContain("Bob")- expect(mockBroadcastToUser).toHaveBeenCalled()- })-- it("owner target: 409 already_friends, sendRequest never called", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: OWNER })- const res = await POST(req({ username: "Bob#0001" }))- expect(res.status).toBe(409)- const body = await res.json()- expect(body.code).toBe("already_friends")- expect(mockSendRequest).not.toHaveBeenCalled()- })-- it("sibling bot target: auto-accepts, 200 accepted with hint null", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "bot_yara" })- mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {- if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }- if (id === "bot_yara") return { id: "bot_yara", isBot: true, deletedAt: null, ownerUserId: OWNER }- return null- })- mockEnsureSibling.mockResolvedValue({ blocked: false, friendshipId: "fr_sib", wasCreated: true })- const res = await POST(req({ username: "Yara#0042" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({ friendshipId: "fr_sib", status: "accepted", hint: null })- expect(mockSendRequest).not.toHaveBeenCalled()- })-- it("sibling bot target with a blocked row: 403 blocked", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "bot_yara" })- mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {- if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }- if (id === "bot_yara") return { id: "bot_yara", isBot: true, deletedAt: null, ownerUserId: OWNER }- return null- })- mockEnsureSibling.mockResolvedValue({ blocked: true })- const res = await POST(req({ username: "Yara#0042" }))- expect(res.status).toBe(403)- const body = await res.json()- expect(body.code).toBe("blocked")- })-- it("self target: 400", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: BOT })- const res = await POST(req({ username: "Zoe#0042" }))- expect(res.status).toBe(400)- })-- it("unknown user: 404", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue(null)- const res = await POST(req({ username: "Nobody#0000" }))- expect(res.status).toBe(404)- })-- it("malformed handle (no #tag): 400", async () => {- const res = await POST(req({ username: "not-a-tag" }))- expect(res.status).toBe(400)- expect(mockGetUserByNameAndDiscriminator).not.toHaveBeenCalled()- })-- it("missing username: 400", async () => {- const res = await POST(req({}))- expect(res.status).toBe(400)- })-- it("logs BOT_FRIEND_REQUEST_SUPERSEDED for each row the request superseded", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "u_alice" })- mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {- if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }- if (id === "u_alice") return { id: "u_alice", isBot: false, deletedAt: null, ownerUserId: null }- return null- })- mockSendRequest.mockResolvedValue({- kind: "created",- friendship: { id: "fr_new" },- supersededIds: ["fr_old"],- broadcasts: [],- })- await POST(req({ username: "Alice#0042" }))- const superseded = mockLogAudit.mock.calls.find(- (c) => (c[1] as { action: string }).action === "community.bot.friend_request_superseded",- )- expect(superseded).toBeDefined()- expect((superseded![1] as { targetId: string }).targetId).toBe("fr_old")- })-- it("propagates a sendRequest 'already friends' as 409 already_friends", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "u_alice" })- mockGetUserInternal.mockImplementation(async (_db: unknown, id: string) => {- if (id === BOT) return { id: BOT, isBot: true, deletedAt: null, ownerUserId: OWNER }- if (id === "u_alice") return { id: "u_alice", isBot: false, deletedAt: null, ownerUserId: null }- return null- })- mockSendRequest.mockRejectedValue(new Error("already friends"))- const res = await POST(req({ username: "Alice#0042" }))- expect(res.status).toBe(409)- const body = await res.json()- expect(body.code).toBe("already_friends")- })-})diff --git a/src/web/src/app/api/community/friendRequest/route.ts b/src/web/src/app/api/community/friendRequest/route.tsdeleted file mode 100644index 70dce804f..000000000--- a/src/web/src/app/api/community/friendRequest/route.ts+++ /dev/null@@ -1,143 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import {- queries,- CommunityAgentFriendRequestSchema,- parseNameAndTag,- isBlocked,-} from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { requireNotBlocked } from "@/lib/community/permissions"-import { broadcastToUserSafe } from "@/lib/community/fanout"-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"--/**- * POST /api/community/friendRequest — moved from- * /api/community/agent/friendRequest (plan §4, §9 phase 4). MOVE-FLAT, not FOLD- * onto POST /friends/request: the bot flow has DIFFERENT semantics — sibling-bot- * auto-accept, always-owner-gated (needsOwnerApproval), and a lean- * `{friendshipId, status, hint}` response — vs the human route's direct- * send + full-friendship response. Per the plan's judgment rule (Melly #113:- * different semantics → keep distinct under the unified actor), and matching- * batch1 which kept friendRequest as a distinct RPC. Bot-only → human actor- * rejected 403 (the human uses /friends/request, which itself already rejects- * bots). Audit BOT_FRIEND_REQUESTED / BOT_FRIEND_REQUEST_SUPERSEDED preserved- * (§6). Body unchanged from the /agent original except wrapper + identity.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const { userId: botUserId, ownerUserId } = gate.bot-- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentFriendRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload" }, { status: 400 })- }-- // Only the human `name#0042` handle is accepted.- const handle = parseNameAndTag(parsed.data.username)- if (!handle) {- return NextResponse.json({ error: "username must be in name#0042 form" }, { status: 400 })- }- const target = await queries.user.getUserByNameAndDiscriminator(db, handle.name, handle.discriminator)- if (!target) return NextResponse.json({ error: "user not found" }, { status: 404 })-- // Guards in order (design steps 3–4).- if (target.id === botUserId) {- return NextResponse.json({ error: "cannot friend yourself" }, { status: 400 })- }- if (target.id === ownerUserId) {- // Owner ↔ bot is synthetic; no row can exist.- return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })- }-- // Resolve internal flags to detect the sibling-bot case.- const targetInternal = await queries.user.getUserInternal(db, target.id)- if (!targetInternal || targetInternal.deletedAt !== null) {- return NextResponse.json({ error: "user not found" }, { status: 404 })- }-- // Sibling auto-accept branch (design step 5).- if (targetInternal.isBot === true && targetInternal.ownerUserId === ownerUserId) {- const block = await requireNotBlocked(db, botUserId, target.id)- if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })-- const result = await queries.communityFriendship.ensureSiblingBotFriendship(db, {- botA: botUserId,- botB: target.id,- })- if (result.blocked) {- return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })- }- return NextResponse.json({ friendshipId: result.friendshipId, status: "accepted", hint: null })- }-- // Belt-and-suspenders (sendRequest also checks).- const block = await requireNotBlocked(db, botUserId, target.id)- if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })-- let result- try {- result = await queries.communityFriendship.sendRequest(db, {- requesterId: botUserId,- addresseeId: target.id,- })- } catch (err: unknown) {- if (err instanceof Error) {- if (isBlocked(err.message)) {- return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })- }- if (err.message === "already friends") {- return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })- }- if (err.message === "friend request already sent") {- return NextResponse.json(- { error: "friend request already sent", code: "friend_request_already_sent" },- { status: 409 },- )- }- }- throw err- }-- for (const b of result.broadcasts) {- await broadcastToUserSafe(b.userId, b.event)- }-- logAudit(db, {- serverId: null,- actorId: botUserId,- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUESTED,- targetType: "user",- targetId: target.id,- changes: JSON.stringify({ requesterBotId: botUserId, addresseeId: target.id }),- })- for (const supersededId of result.supersededIds) {- logAudit(db, {- serverId: null,- actorId: botUserId,- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,- targetType: "friendship",- targetId: supersededId,- changes: JSON.stringify({ supersededBy: result.friendship.id }),- })- }-- // Bot-origin sendRequest always sets needsOwnerApproval, so this is always- // the pending variant. Resolve the owner's display name for the hint copy.- const owner = await queries.user.getUserPublic(db, ownerUserId)- const ownerDisplayName = owner?.name ?? "your owner"- return NextResponse.json({- friendshipId: result.friendship.id,- status: "pending",- hint: `Your owner ${ownerDisplayName} needs to approve this request in DM.`,- })-})diff --git a/src/web/src/app/api/community/listFriends/route.test.ts b/src/web/src/app/api/community/friends/accepted/route.bot.test.tssimilarity index 82%rename from src/web/src/app/api/community/listFriends/route.test.tsrename to src/web/src/app/api/community/friends/accepted/route.bot.test.tsindex 32cdaeff3..385f41e57 100644--- a/src/web/src/app/api/community/listFriends/route.test.ts+++ b/src/web/src/app/api/community/friends/accepted/route.bot.test.ts@@ -38,19 +38,22 @@ vi.mock("@alook/shared", async () => {}})-import { POST } from "./route"+import { GET } from "./route"const BOT = "bot_zoe"+// Bot arm of GET /api/community/friends/accepted (folds the flat listFriends+// verb's accepted bucket). Bot addresses with no target-user param (self-scope,+// users/me/* family invariant); a no-crk_ request falls to the human withAuth+// arm → 401 via the mocked no-session auth.function req(headers: Record<string, string> = { Authorization: "Bearer crk_abc" }): NextRequest {- return new NextRequest("http://localhost/api/community/agent/listFriends", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: "{}",+ return new NextRequest("http://localhost/api/community/friends/accepted", {+ method: "GET",+ headers: { ...headers },})}-describe("POST /api/community/agent/listFriends", () => {+describe("GET /api/community/friends/accepted — bot arm (folds listFriends accepted bucket)", () => {beforeEach(() => {vi.clearAllMocks()mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: BOT })@@ -60,7 +63,7 @@ describe("POST /api/community/agent/listFriends", () => {})it("401 without Authorization", async () => {- const res = await POST(req({}))+ const res = await GET(req({}))expect(res.status).toBe(401)})@@ -81,7 +84,7 @@ describe("POST /api/community/agent/listFriends", () => {pendingOutgoing: [],pendingIncoming: [],})- const res = await POST(req())+ const res = await GET(req())expect(res.status).toBe(200)const raw = await res.text()expect(raw).not.toContain("\"isBot\"")@@ -106,16 +109,16 @@ describe("POST /api/community/agent/listFriends", () => {pendingOutgoing: [],pendingIncoming: [],})- const res = await POST(req())+ const res = await GET(req())const body = await res.json()expect(body.accepted[0].presence).toBe("offline")})- it("returns empty arrays (not null) for a bot with no friends; presence is not queried", async () => {+ it("returns { accepted: [] } (not null) for a bot with no accepted friends; presence not queried", async () => {mockListAgentFriends.mockResolvedValue({ accepted: [], pendingOutgoing: [], pendingIncoming: [] })- const res = await POST(req())+ const res = await GET(req())const body = await res.json()- expect(body).toEqual({ accepted: [], pendingOutgoing: [], pendingIncoming: [] })+ expect(body).toEqual({ accepted: [] })expect(mockWsDoFetch).not.toHaveBeenCalled()})})diff --git a/src/web/src/app/api/community/friends/route.test.ts b/src/web/src/app/api/community/friends/accepted/route.test.tssimilarity index 84%rename from src/web/src/app/api/community/friends/route.test.tsrename to src/web/src/app/api/community/friends/accepted/route.test.tsindex dd1d31427..ef626bfaf 100644--- a/src/web/src/app/api/community/friends/route.test.ts+++ b/src/web/src/app/api/community/friends/accepted/route.test.ts@@ -2,7 +2,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const listFriends = vi.fn()-const listBlocked = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -13,12 +12,14 @@ vi.mock("@alook/shared", async () => {queries: {communityFriendship: {listFriends: (...a: unknown[]) => listFriends(...a),- listBlocked: (...a: unknown[]) => listBlocked(...a),},},}})+// Human arm delegates through the real withCommunityActor → withAuth; mock+// withAuth to inject a human ctx (this route's accepted human arm is the+// inheritor of the retired aggregate GET /friends' friends[] projection).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@@ -26,21 +27,13 @@ vi.mock("@/lib/middleware/auth", () => ({}),}))-vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- }-})-import { GET } from "./route"-const req = new NextRequest("http://localhost/api/community/friends")+const req = new NextRequest("http://localhost/api/community/friends/accepted")-describe("GET /api/community/friends", () => {+describe("GET /api/community/friends/accepted — human arm (inherits legacy GET /friends friends[])", () => {beforeEach(() => {vi.clearAllMocks()- listBlocked.mockResolvedValue([])})it("includes statusEmoji/statusText sourced from the joined profile row", async () => {diff --git a/src/web/src/app/api/community/friends/accepted/route.ts b/src/web/src/app/api/community/friends/accepted/route.tsnew file mode 100644index 000000000..37ce586db--- /dev/null+++ b/src/web/src/app/api/community/friends/accepted/route.ts@@ -0,0 +1,56 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, readOrStale } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor } from "@/lib/middleware/community-actor"+import { avatarInitial } from "@/lib/community/avatar"+import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"++/**+ * GET /api/community/friends/accepted — the accepted-friends bucket (route/disc+ * trunk, 接口树统一 轴3, folds the flat `listFriends` verb's accepted bucket).+ *+ * Dual-actor, reading the SAME `communityFriendship` status='accepted' data,+ * projected by actor.kind (Blondie #436: one source of truth so the human+ * migration off the legacy aggregate GET /friends is later byte-consistent):+ * - human → UI DTO (same shape GET /friends' `friends[]` emits today)+ * - bot → lean `FriendCard` + presence+ *+ * ①-C / users/me/* family invariant (Aigneis #426): scope is ALWAYS the caller's+ * own userId (ctx.actor.userId) — this endpoint takes NO target-user param, so a+ * bot can only ever read ITS OWN accepted friends, never probe another user's.+ */+export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)+ const userId = ctx.actor.userId++ if (ctx.actor.kind === "bot") {+ const buckets = await queries.communityFriendship.listAgentFriends(db, userId)+ const onlineSet = await resolvePresence(+ ctx.env,+ buckets.accepted.map((r) => r.peerUserId),+ userId,+ )+ return NextResponse.json({ accepted: buckets.accepted.map((r) => toFriendCard(r, onlineSet)) })+ }++ // Human arm — same accepted projection GET /friends emits today (the legacy+ // aggregate stays live this step; this endpoint is the migration target).+ type FriendRow = Awaited<ReturnType<typeof queries.communityFriendship.listFriends>>[number]+ const { value, stale } = await readOrStale<{ rows: FriendRow[] }>(+ async () => ({ rows: await queries.communityFriendship.listFriends(db, userId) }),+ { rows: [] },+ { route: "community/friends/accepted" },+ )+ const friends = value.rows.map((f) => ({+ id: f.id,+ userId: f.friendUserId,+ name: f.friendName,+ discriminator: f.friendDiscriminator,+ avatar: f.friendImage ?? avatarInitial(f.friendName),+ status: "offline" as const,+ sub: "",+ statusEmoji: f.statusEmoji ?? null,+ statusText: f.statusText ?? "",+ }))+ return NextResponse.json(stale ? { friends, stale: true } : { friends })+})diff --git a/src/web/src/app/api/community/friends/blocked/route.test.ts b/src/web/src/app/api/community/friends/blocked/route.test.tsnew file mode 100644index 000000000..7f6baafd8--- /dev/null+++ b/src/web/src/app/api/community/friends/blocked/route.test.ts@@ -0,0 +1,77 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/auth", () => ({+ createAuth: vi.fn(() => ({+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },+ })),+}))++const mockFindActiveAgentRunnerKeyByBearer = vi.fn()+const mockGetUserInternal = vi.fn()+const mockGetBotBinding = vi.fn()+const mockListBlocked = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },+ user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityFriendship: { listBlocked: (...a: unknown[]) => mockListBlocked(...a) },+ },+ }+})++// The human arm delegates through the real withAuth; mock it so a human ctx is+// injected without exercising Better-Auth.+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: { DB: {} }, userId: "u_owner", email: "[email protected]", params })+ }),+}))++import { GET } from "./route"++function req(headers: Record<string, string> = {}): NextRequest {+ return new NextRequest("http://localhost/api/community/friends/blocked", {+ method: "GET",+ headers: { ...headers },+ })+}++describe("GET /api/community/friends/blocked", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_zoe" })+ mockGetUserInternal.mockResolvedValue({ id: "bot_zoe", isBot: true, deletedAt: null, ownerUserId: "owner_1" })+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ })++ it("bot → 403 BEFORE any blocked query (owner-only, zero existence leak)", async () => {+ const res = await GET(req({ Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(403)+ // reject-before-query: the blocked list is never read for a bot caller.+ expect(mockListBlocked).not.toHaveBeenCalled()+ })++ it("human → the blocked list", async () => {+ mockListBlocked.mockResolvedValue([+ { id: "bk_1", blockedUserId: "u_x", blockedName: "X", blockedImage: null },+ ])+ const res = await GET(req())+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.blocked).toEqual([+ { id: "bk_1", userId: "u_x", name: "X", avatar: expect.any(String) },+ ])+ })+})diff --git a/src/web/src/app/api/community/friends/blocked/route.ts b/src/web/src/app/api/community/friends/blocked/route.tsnew file mode 100644index 000000000..226ec5c46--- /dev/null+++ b/src/web/src/app/api/community/friends/blocked/route.ts@@ -0,0 +1,36 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, readOrStale } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"+import { avatarInitial } from "@/lib/community/avatar"++/**+ * GET /api/community/friends/blocked — the blocked bucket (route/disc trunk,+ * 接口树统一 轴3). Owner-only: a bot NEVER sees who its owner blocked.+ *+ * The bot exclusion is an ENDPOINT-level capability gate (Aigneis #408/#421,+ * Blondie #436): `rejectBot` returns 403 BEFORE any blocked-data query runs, so+ * the 403 is independent of whether/whom the caller blocked — zero existence+ * leak, a pure capability boundary (not a row-projection filter). The flat+ * `listFriends` verb never exposed blocked to bots; this keeps that invariant+ * while giving human a clean per-bucket read.+ */+export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {+ const denied = rejectBot(ctx.actor)+ if (denied) return denied++ const db = getDb(ctx.env.DB)+ type BlockedRow = Awaited<ReturnType<typeof queries.communityFriendship.listBlocked>>[number]+ const { value, stale } = await readOrStale<{ rows: BlockedRow[] }>(+ async () => ({ rows: await queries.communityFriendship.listBlocked(db, ctx.actor.userId) }),+ { rows: [] },+ { route: "community/friends/blocked" },+ )+ const blocked = value.rows.map((b) => ({+ id: b.id,+ userId: b.blockedUserId,+ name: b.blockedName,+ avatar: b.blockedImage ?? avatarInitial(b.blockedName),+ }))+ return NextResponse.json(stale ? { blocked, stale: true } : { blocked })+})diff --git a/src/web/src/app/api/community/friends/pending/route.bot.test.ts b/src/web/src/app/api/community/friends/pending/route.bot.test.tsnew file mode 100644index 000000000..e64c233bd--- /dev/null+++ b/src/web/src/app/api/community/friends/pending/route.bot.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/auth", () => ({+ createAuth: vi.fn(() => ({+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },+ })),+}))++const mockFindActiveAgentRunnerKeyByBearer = vi.fn()+const mockGetUserInternal = vi.fn()+const mockGetBotBinding = vi.fn()+const mockListAgentFriends = vi.fn()+const mockWsDoFetch = vi.fn()++vi.mock("@/lib/broadcast", () => ({+ wsDoFetch: (...a: unknown[]) => mockWsDoFetch(...a),+}))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },+ user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityFriendship: { listAgentFriends: (...a: unknown[]) => mockListAgentFriends(...a) },+ },+ }+})++import { GET } from "./route"++const BOT = "bot_zoe"++function req(headers: Record<string, string> = { Authorization: "Bearer crk_abc" }): NextRequest {+ return new NextRequest("http://localhost/api/community/friends/pending", {+ method: "GET",+ headers: { ...headers },+ })+}++describe("GET /api/community/friends/pending — bot arm (folds listFriends pending buckets)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: BOT })+ mockGetUserInternal.mockResolvedValue({ id: BOT, isBot: true, deletedAt: null, ownerUserId: "owner_1" })+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ mockWsDoFetch.mockResolvedValue({ ok: true, json: async () => ({ online: ["u_bob"] }) })+ })++ it("returns the two directional buckets as FriendCards with presence", async () => {+ mockListAgentFriends.mockResolvedValue({+ accepted: [],+ pendingIncoming: [+ { friendshipId: "fr_in", peerUserId: "u_bob", name: "Bob", discriminator: "0007", image: null, aboutMe: null, statusEmoji: null, statusText: null },+ ],+ pendingOutgoing: [+ { friendshipId: "fr_out", peerUserId: "u_cara", name: "Cara", discriminator: "0009", image: null, aboutMe: null, statusEmoji: null, statusText: null },+ ],+ })+ const res = await GET(req())+ expect(res.status).toBe(200)+ const raw = await res.text()+ expect(raw).not.toContain("\"isBot\"")+ const body = JSON.parse(raw)+ expect(body.pendingIncoming[0]).toMatchObject({ userId: "u_bob", handle: "Bob#0007", presence: "online" })+ expect(body.pendingOutgoing[0]).toMatchObject({ userId: "u_cara", handle: "Cara#0009", presence: "offline" })+ // Bot arm does NOT emit the accepted bucket (that's friends/accepted).+ expect("accepted" in body).toBe(false)+ })++ it("empty pending → both buckets [], presence not queried", async () => {+ mockListAgentFriends.mockResolvedValue({ accepted: [], pendingIncoming: [], pendingOutgoing: [] })+ const res = await GET(req())+ expect(await res.json()).toEqual({ pendingIncoming: [], pendingOutgoing: [] })+ expect(mockWsDoFetch).not.toHaveBeenCalled()+ })++ it("401 without Authorization", async () => {+ const res = await GET(req({}))+ expect(res.status).toBe(401)+ })+})diff --git a/src/web/src/app/api/community/friends/pending/route.ts b/src/web/src/app/api/community/friends/pending/route.tsindex 02d29622f..004dd945f 100644--- a/src/web/src/app/api/community/friends/pending/route.ts+++ b/src/web/src/app/api/community/friends/pending/route.ts@@ -1,14 +1,45 @@+import { NextResponse, type NextRequest } from "next/server"import { queries, readOrStale } from "@alook/shared"import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON } from "@/lib/middleware/helpers"+import { withCommunityActor } from "@/lib/middleware/community-actor"import { avatarInitial } from "@/lib/community/avatar"+import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"-export const GET = withAuth(async (_req, ctx) => {+/**+ * GET /api/community/friends/pending — the pending-requests bucket (route/disc+ * trunk, 接口树统一 轴3). Was human-only (withAuth); now dual-actor, folding the+ * flat `listFriends` verb's pendingIncoming/pendingOutgoing buckets for the bot.+ * Both arms read the SAME `communityFriendship` status='pending' data, projected+ * by actor.kind (Blondie #436 single-source-of-truth):+ * - human → the pending-page DTO (one `pending[]` with a `kind` in|out tag),+ * UNCHANGED from before this fold (byte-identical for the web client).+ * - bot → the two directional buckets `{ pendingIncoming, pendingOutgoing }`+ * as lean FriendCards + presence (the shape `alook friend list` composes).+ *+ * ①-C / users/me/* family invariant (Aigneis #426): NO target-user param — a+ * bot only ever reads its own pending set (scope = ctx.actor.userId).+ */+export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)+ const userId = ctx.actor.userId++ if (ctx.actor.kind === "bot") {+ const buckets = await queries.communityFriendship.listAgentFriends(db, userId)+ const onlineSet = await resolvePresence(+ ctx.env,+ [...buckets.pendingIncoming, ...buckets.pendingOutgoing].map((r) => r.peerUserId),+ userId,+ )+ return NextResponse.json({+ pendingIncoming: buckets.pendingIncoming.map((r) => toFriendCard(r, onlineSet)),+ pendingOutgoing: buckets.pendingOutgoing.map((r) => toFriendCard(r, onlineSet)),+ })+ }++ // Human arm — byte-identical to the pre-fold human pending route.type PendingRow = Awaited<ReturnType<typeof queries.communityFriendship.listPending>>[number]const { value, stale } = await readOrStale<{ rows: PendingRow[] }>(- async () => ({ rows: await queries.communityFriendship.listPending(db, ctx.userId) }),+ async () => ({ rows: await queries.communityFriendship.listPending(db, userId) }),{ rows: [] },{ route: "community/friends/pending" },)@@ -23,5 +54,5 @@ export const GET = withAuth(async (_req, ctx) => {kind: r.kind,needsOwnerApproval: r.needsOwnerApproval,}))- return writeJSON(stale ? { pending, stale: true } : { pending })+ return NextResponse.json(stale ? { pending, stale: true } : { pending })})diff --git a/src/web/src/app/api/community/friends/request/route.test.ts b/src/web/src/app/api/community/friends/request/route.test.tsindex 429a0f4f6..ce4ea2548 100644--- a/src/web/src/app/api/community/friends/request/route.test.ts+++ b/src/web/src/app/api/community/friends/request/route.test.ts@@ -4,9 +4,12 @@ import { NextRequest } from "next/server"const getUserInternal = vi.fn()const getUserByNameAndDiscriminator = vi.fn()const getUserByNameCaseInsensitive = vi.fn()+const getUserPublic = vi.fn()const isBlocked = vi.fn()const sendRequest = vi.fn()+const ensureSiblingBotFriendship = vi.fn()const broadcastToUser = vi.fn()+const mockLogAudit = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -19,20 +22,33 @@ vi.mock("@alook/shared", async () => {getUserInternal: (...a: unknown[]) => getUserInternal(...a),getUserByNameAndDiscriminator: (...a: unknown[]) => getUserByNameAndDiscriminator(...a),getUserByNameCaseInsensitive: (...a: unknown[]) => getUserByNameCaseInsensitive(...a),+ getUserPublic: (...a: unknown[]) => getUserPublic(...a),},communityFriendship: {sendRequest: (...a: unknown[]) => sendRequest(...a),isBlocked: (...a: unknown[]) => isBlocked(...a),+ ensureSiblingBotFriendship: (...a: unknown[]) => ensureSiblingBotFriendship(...a),},},}})-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+// Dual-actor: crk_ bearer → bot arm, else human. The route dispatches by+// actor.kind to two independent handlers.+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (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]", user: { isBot: false }, params })- }),+ // A test may inject a specific actor via ctx.actor (used to drive the+ // isBot→403 backstop); otherwise derive it from the Authorization header+ // (crk_ → bot arm, else human).+ const authz = req?.headers?.get?.("Authorization") ?? ""+ const actor =+ ctx?.actor ??+ (authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]", isBot: false })+ return handler(req, { env: {}, actor, params })+ },}))vi.mock("@/lib/middleware/helpers", async () => {@@ -47,6 +63,11 @@ vi.mock("@/lib/broadcast", () => ({broadcastToUser: (...a: unknown[]) => broadcastToUser(...a),}))+vi.mock("@/lib/community/audit", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }+})+import { POST } from "./route"function postReq(body: unknown) {@@ -208,4 +229,65 @@ describe("POST /api/community/friends/request", () => {expect(sendRequest).not.toHaveBeenCalled()})})++ // The dual-actor fold added a bot arm — dispatched by a crk_ bearer. The flat+ // /friendRequest test covers the bot flow's full detail; here we lock the+ // DISPATCH (crk_ → the bot handler, its distinct owner-gated/lean semantics)+ // and the isBot→403 backstop on the human arm (Aigneis #541).+ describe("dual-actor dispatch (crk_ bearer → bot arm)", () => {+ function botReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/friends/request", {+ method: "POST",+ headers: { "Content-Type": "application/json", Authorization: "Bearer crk_test" },+ body: JSON.stringify(body),+ })+ }++ it("routes a bot to the owner-gated pending flow with the lean {friendshipId,status,hint} shape", async () => {+ // Non-sibling target → the always-owner-gated pending branch.+ getUserByNameAndDiscriminator.mockResolvedValue({ id: "u2", name: "Alex", discriminator: "0002" })+ getUserInternal.mockResolvedValue({ id: "u2", isBot: false, ownerUserId: null, deletedAt: null })+ isBlocked.mockResolvedValue(false)+ sendRequest.mockResolvedValue({ friendship: { id: "fr_1" }, supersededIds: [], broadcasts: [] })+ getUserPublic.mockResolvedValue({ name: "Owner Ann" })++ const res = await POST(botReq({ username: "Alex#0002" }), {} as never)+ expect(res.status).toBe(200)+ const body = (await res.json()) as { friendshipId: string; status: string; hint: string }+ // Lean bot shape — NOT the human full-friendship shape.+ expect(body.friendshipId).toBe("fr_1")+ expect(body.status).toBe("pending")+ expect(body.hint).toContain("Owner Ann")+ // Self-scope: the bot's own credential id is the requester, never a body field.+ expect(sendRequest).toHaveBeenCalledWith({}, { requesterId: "bot_1", addresseeId: "u2" })+ })++ it("auto-accepts a sibling bot (same owner) with status accepted, no owner gate", async () => {+ getUserByNameAndDiscriminator.mockResolvedValue({ id: "sib", name: "Sib", discriminator: "0003" })+ getUserInternal.mockResolvedValue({ id: "sib", isBot: true, ownerUserId: "o_1", deletedAt: null })+ isBlocked.mockResolvedValue(false)+ ensureSiblingBotFriendship.mockResolvedValue({ friendshipId: "fr_sib", blocked: false })++ const res = await POST(botReq({ username: "Sib#0003" }), {} as never)+ expect(res.status).toBe(200)+ const body = (await res.json()) as { status: string }+ expect(body.status).toBe("accepted")+ expect(ensureSiblingBotFriendship).toHaveBeenCalledWith({}, { botA: "bot_1", botB: "sib" })+ // The sibling branch never touches the pending sendRequest path.+ expect(sendRequest).not.toHaveBeenCalled()+ })+ })++ // Backstop (Aigneis #541): the human arm auto-accepts with no owner gate, so a+ // bot must NEVER reach it. Dispatch is the main door; isBot→403 is the last+ // line if a future auth regression puts isBot=true on a human actor. The mock+ // honors ctx.actor so we can inject the crafted (production-impossible) case.+ it("human arm rejects an isBot=true human actor with 403 (backstop survives the fold)", async () => {+ const res = await POST(postReq({ username: "alex" }), {+ actor: { kind: "human", userId: "u1", email: "[email protected]", isBot: true },+ } as never)+ expect(res.status).toBe(403)+ // Never reaches the friend-graph write.+ expect(sendRequest).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.tsindex 4b02de38a..1667aa86f 100644--- a/src/web/src/app/api/community/friends/request/route.ts+++ b/src/web/src/app/api/community/friends/request/route.ts@@ -1,19 +1,62 @@-import { NextRequest } from "next/server"-import { queries, parseNameAndTag, isBlocked } from "@alook/shared"+import { NextRequest, NextResponse } from "next/server"+import {+ queries,+ parseNameAndTag,+ isBlocked,+ CommunityAgentFriendRequestSchema,+} from "@alook/shared"import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"+import { withCommunityActor } from "@/lib/middleware/community-actor"+import type { BotActor, CommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { broadcastToUserSafe } from "@/lib/community/fanout"import { requireNotBlocked } from "@/lib/community/permissions"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"-export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)+/**+ * POST /api/community/friends/request — the friend-request door (route/disc+ * 接口树统一, friendRequest fold; Melly #540). Dual-actor via withCommunityActor,+ * dispatched by actor.kind to TWO INDEPENDENT handlers that share ONLY the URL ++ * the gate — NOT one handler with shared-middle if-branches (that would flatten+ * the two distinct semantics; Ingaborg #539/#542 reds cross-contamination):+ * - human → handleHumanFriendRequest: {userId|username}, direct send, returns+ * the FULL friendship (201, or 200 on auto-accept). Byte-identical to the+ * former withAuth route — NO owner-gate. KEEPS its isBot→403 backstop+ * (Aigneis #541): the human arm auto-accepts (no owner gate), so if the+ * dispatch ever had a seam that let a bot reach here, the bot would bypass+ * owner-approval and directly auto-friend = capability escalation. Dispatch+ * is the main gate; isBot→403 is the last-line backstop. BOTH stay.+ * - bot → handleBotFriendRequest: {username} (name#tag only), sibling-bot+ * auto-accept, ALWAYS owner-gated (needsOwnerApproval, never dropped), lean+ * {friendshipId,status,hint} response, audit BOT_FRIEND_REQUESTED/+ * SUPERSEDED. Folds the flat /friendRequest bot verb (flat verb deleted at+ * the flat-delete step). Self-scoped: requesterId = the credential's+ * botUserId, never a body field.+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ if (ctx.actor.kind === "bot") {+ return handleBotFriendRequest(req, ctx.env, ctx.actor)+ }+ return handleHumanFriendRequest(req, ctx.env, ctx.actor)+})++async function handleHumanFriendRequest(+ req: NextRequest,+ env: Env,+ actor: Extract<CommunityActor, { kind: "human" }>,+): Promise<NextResponse> {+ const db = getDb(env.DB)- // Belt-and-suspenders: bot sessions never reach here (auth.ts:204 rejects- // them), but a future auth regression must not let a bot author friend-graph- // state. See plans/agent-friendship-approval-gate.md §Hardening.- if (ctx.user?.isBot) return writeError("forbidden", 403)+ // Belt-and-suspenders backstop (Aigneis #541 — MUST survive the dual-actor+ // fold, NOT redundant): the actor-gate dispatch is the main door (a bot routes+ // to handleBotFriendRequest, never here), but this human arm AUTO-ACCEPTS (200,+ // no owner gate) — if the dispatch ever had a seam that let a bot reach here,+ // the bot would bypass owner-approval and directly auto-friend = capability+ // escalation. So keep the last-line isBot→403 even with the gate above.+ // (Always false in production — a bot session is rejected at 401 before any+ // handler runs; this is the future-auth-regression backstop.) See+ // plans/agent-friendship-approval-gate.md §Hardening.+ if (actor.isBot) return writeError("forbidden", 403)let body: { userId?: string; username?: string }try {@@ -36,7 +79,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("userId or username is required", 400)}- if (targetUserId === ctx.userId) {+ if (targetUserId === actor.userId) {return writeError("cannot send friend request to yourself", 400)}@@ -45,16 +88,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// Owner ↔ own-bot is a synthetic friendship — no row can exist. 409 so the UI// treats it as a no-op.- if (target.isBot === true && target.ownerUserId === ctx.userId) {+ if (target.isBot === true && target.ownerUserId === actor.userId) {return writeError("already friends", 409)}- const block = await requireNotBlocked(db, ctx.userId, targetUserId)+ const block = await requireNotBlocked(db, actor.userId, targetUserId)if (!block.ok) return writeError(block.error, block.status)try {const result = await queries.communityFriendship.sendRequest(db, {- requesterId: ctx.userId,+ requesterId: actor.userId,addresseeId: targetUserId,})// The query owns supersede + card writes + broadcast payloads; the route@@ -65,7 +108,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {for (const supersededId of result.supersededIds) {logAudit(db, {serverId: null,- actorId: ctx.userId,+ actorId: actor.userId,action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,targetType: "friendship",targetId: supersededId,@@ -86,4 +129,123 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}throw err}-})+}++async function handleBotFriendRequest(+ req: NextRequest,+ env: Env,+ bot: BotActor,+): Promise<NextResponse> {+ const { userId: botUserId, ownerUserId } = bot+ const db = getDb(env.DB)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentFriendRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload" }, { status: 400 })+ }++ // Only the human `name#0042` handle is accepted.+ const handle = parseNameAndTag(parsed.data.username)+ if (!handle) {+ return NextResponse.json({ error: "username must be in name#0042 form" }, { status: 400 })+ }+ const target = await queries.user.getUserByNameAndDiscriminator(db, handle.name, handle.discriminator)+ if (!target) return NextResponse.json({ error: "user not found" }, { status: 404 })++ // Guards in order (design steps 3–4).+ if (target.id === botUserId) {+ return NextResponse.json({ error: "cannot friend yourself" }, { status: 400 })+ }+ if (target.id === ownerUserId) {+ // Owner ↔ bot is synthetic; no row can exist.+ return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })+ }++ // Resolve internal flags to detect the sibling-bot case.+ const targetInternal = await queries.user.getUserInternal(db, target.id)+ if (!targetInternal || targetInternal.deletedAt !== null) {+ return NextResponse.json({ error: "user not found" }, { status: 404 })+ }++ // Sibling auto-accept branch (design step 5).+ if (targetInternal.isBot === true && targetInternal.ownerUserId === ownerUserId) {+ const block = await requireNotBlocked(db, botUserId, target.id)+ if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })++ const result = await queries.communityFriendship.ensureSiblingBotFriendship(db, {+ botA: botUserId,+ botB: target.id,+ })+ if (result.blocked) {+ return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })+ }+ return NextResponse.json({ friendshipId: result.friendshipId, status: "accepted", hint: null })+ }++ // Belt-and-suspenders (sendRequest also checks).+ const block = await requireNotBlocked(db, botUserId, target.id)+ if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })++ let result+ try {+ result = await queries.communityFriendship.sendRequest(db, {+ requesterId: botUserId,+ addresseeId: target.id,+ })+ } catch (err: unknown) {+ if (err instanceof Error) {+ if (isBlocked(err.message)) {+ return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })+ }+ if (err.message === "already friends") {+ return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })+ }+ if (err.message === "friend request already sent") {+ return NextResponse.json(+ { error: "friend request already sent", code: "friend_request_already_sent" },+ { status: 409 },+ )+ }+ }+ throw err+ }++ for (const b of result.broadcasts) {+ await broadcastToUserSafe(b.userId, b.event)+ }++ logAudit(db, {+ serverId: null,+ actorId: botUserId,+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUESTED,+ targetType: "user",+ targetId: target.id,+ changes: JSON.stringify({ requesterBotId: botUserId, addresseeId: target.id }),+ })+ for (const supersededId of result.supersededIds) {+ logAudit(db, {+ serverId: null,+ actorId: botUserId,+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,+ targetType: "friendship",+ targetId: supersededId,+ changes: JSON.stringify({ supersededBy: result.friendship.id }),+ })+ }++ // Bot-origin sendRequest always sets needsOwnerApproval, so this is always+ // the pending variant. Resolve the owner's display name for the hint copy.+ const owner = await queries.user.getUserPublic(db, ownerUserId)+ const ownerDisplayName = owner?.name ?? "your owner"+ return NextResponse.json({+ friendshipId: result.friendship.id,+ status: "pending",+ hint: `Your owner ${ownerDisplayName} needs to approve this request in DM.`,+ })+}diff --git a/src/web/src/app/api/community/friends/route.ts b/src/web/src/app/api/community/friends/route.tsdeleted file mode 100644index de521f3f8..000000000--- a/src/web/src/app/api/community/friends/route.ts+++ /dev/null@@ -1,40 +0,0 @@-import { queries, readOrStale } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON } from "@/lib/middleware/helpers"-import { avatarInitial } from "@/lib/community/avatar"--export const GET = withAuth(async (_req, ctx) => {- const db = getDb(ctx.env.DB)- type FriendRow = Awaited<ReturnType<typeof queries.communityFriendship.listFriends>>[number]- type BlockedRow = Awaited<ReturnType<typeof queries.communityFriendship.listBlocked>>[number]- const { value, stale } = await readOrStale<{ rawFriends: FriendRow[]; rawBlocked: BlockedRow[] }>(- async () => {- const [rawFriends, rawBlocked] = await Promise.all([- queries.communityFriendship.listFriends(db, ctx.userId),- queries.communityFriendship.listBlocked(db, ctx.userId),- ])- return { rawFriends, rawBlocked }- },- { rawFriends: [], rawBlocked: [] },- { route: "community/friends" },- )- const friends = value.rawFriends.map((f) => ({- id: f.id,- userId: f.friendUserId,- name: f.friendName,- discriminator: f.friendDiscriminator,- avatar: f.friendImage ?? avatarInitial(f.friendName),- status: "offline" as const,- sub: "",- statusEmoji: f.statusEmoji ?? null,- statusText: f.statusText ?? "",- }))- const blocked = value.rawBlocked.map((b) => ({- id: b.id,- userId: b.blockedUserId,- name: b.blockedName,- avatar: b.blockedImage ?? avatarInitial(b.blockedName),- }))- return writeJSON(stale ? { friends, blocked, stale: true } : { friends, blocked })-})diff --git a/src/web/src/app/api/community/inboxSnapshot/route.ts b/src/web/src/app/api/community/inboxSnapshot/route.tsdeleted file mode 100644index fd238f231..000000000--- a/src/web/src/app/api/community/inboxSnapshot/route.ts+++ /dev/null@@ -1,33 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"--/**- * POST /api/community/inboxSnapshot — plan §7. Body `{}`.- * Non-consuming bodiless summary of pending unread, bucketed per channel/DM.- *- * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).- */-export const POST = withCommunityActor(async (_req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const { userId: botUserId } = gate.bot-- const db = getDb(ctx.env.DB)-- const snapshot = await withD1Retry(- () => queries.communityAgentInbox.getInboxSnapshotForAgent(db, botUserId),- { route: "community/inboxSnapshot:snapshot" },- )- const rows = await withD1Retry(- () => queries.communityAgentInbox.toInboxRows(db, snapshot, botUserId),- { route: "community/inboxSnapshot:rows" },- )-- return NextResponse.json({- rows,- pendingChannels: rows.length,- pendingMessages: rows.reduce((n, r) => n + r.pendingCount, 0),- })-})diff --git a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.tsindex d9a4cbd59..44a38d318 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts@@ -130,14 +130,14 @@ describe("POST /api/community/invites/[token]/join — bot path", () => {invite: { id: "inv_1", serverId: "srv_1" },member: { id: "mem_1", userId: "bot_1", role: "member", nickname: null, userName: "bot", userImage: null, discriminator: "1234", joinedAt: "2026-01-01" },})- mockGetServer.mockResolvedValue({ id: "srv_1", name: "Design Studio" })+ mockGetServer.mockResolvedValue({ id: "srv_1", name: "Design Studio", discriminator: "0042" })const res = await POST(req(TOKEN, { Authorization: "Bearer crk_abc" }), params(TOKEN))expect(res.status).toBe(200)- // Superset response (Fork C): the bot's daemon projects `server` down to- // the old lean {server:{id,name}} shape; serverId/member ride along.+ // The route superset includes the discriminator; the daemon projects+ // `server` to the canonical handle while serverId/member stay route-local.const body = await res.json()- expect(body.server).toEqual({ id: "srv_1", name: "Design Studio" })+ expect(body.server).toEqual({ id: "srv_1", name: "Design Studio", discriminator: "0042" })expect(body.serverId).toBe("srv_1")expect(mockFanOutToServerMembers).toHaveBeenCalledWith(diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.tsindex e3920e893..001f0269b 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts@@ -101,14 +101,14 @@ export const POST = withCommunityActor(async (_req, ctx) => {}// Superset response: the human web client reads member/serverId; the bot's- // daemon reads `server` ({id,name}) and projects it to the CLI. `server` is+ // daemon reads `server` and projects it to the canonical handle. `server` is// populated only for a bot — the human path already has serverId and would// otherwise pay an extra getServer round-trip for a field it ignores (the// superset is about a unified SHAPE, not forcing identical queries).- let server: { id: string; name: string } | undefined+ let server: { id: string; name: string; discriminator: string } | undefinedif (actor.kind === "bot") {const row = await queries.communityServer.getServer(db, result.invite.serverId)- server = row ? { id: row.id, name: row.name } : undefined+ server = row ? { id: row.id, name: row.name, discriminator: row.discriminator } : undefined}return writeJSON({member: result.member,diff --git a/src/web/src/app/api/community/listChannels/route.ts b/src/web/src/app/api/community/listChannels/route.tsdeleted file mode 100644index 619234b6c..000000000--- a/src/web/src/app/api/community/listChannels/route.ts+++ /dev/null@@ -1,132 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentListChannelsRequestSchema, formatCanonicalRef, type StoredChannelType } from "@alook/shared"-import type {- CommunityCliChannelGroup as ChannelGroup,- ChannelListItem,-} from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"--/**- * POST /api/community/listChannels — moved from /api/community/agent/listChannels- * (plan §4 MOVE-FLAT, §9 phase 4). `alook channel list`. Body `{ server? }` —- * `server` accepts the server's id OR display name (resolved via- * `resolveServerByNameForMember`), or omit to list across every server the bot- * is in. Ref/name-addressed → can't fold onto an `[id]` route (Fork B); the- * server channel-list also has no human GET twin (the web reads it via the- * server bootstrap tree), so this is a clean MOVE. Bot-only → human actor 403.- * Body unchanged from the /agent original except wrapper + identity source.- *- * Top-level channels only (`listChannelsForMember` filters- * `parentChannelId IS NULL`) — same visibility rule a human sees. Response is- * `{ groups: [{ category, channels: [{ref, name, type, visibility}] }] }`;- * channels bucketed by `categoryId` (uncategorized first, then categories by- * position). Empty groups dropped so a private-category name never leaks.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId-- const db = getDb(ctx.env.DB)-- let raw: unknown = {}- try {- const text = await req.text()- if (text) raw = JSON.parse(text)- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentListChannelsRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }-- let servers: Array<{ id: string; name: string }>- if (parsed.data.server) {- servers = await queries.communityServer.resolveServerByNameForMember(db, botUserId, parsed.data.server)- if (servers.length === 0) {- return NextResponse.json({ error: `server not found: ${parsed.data.server}` }, { status: 404 })- }- if (servers.length > 1) {- const candidates = servers.map((s) => `${s.id} ("${s.name}")`).join(", ")- return NextResponse.json(- { error: `ambiguous server name "${parsed.data.server}" — matches ${servers.length} servers: ${candidates}` },- { status: 400 },- )- }- } else {- servers = await queries.communityServer.listUserServers(db, botUserId)- }-- // Fan out per-server DB work in parallel — for a bot in N servers this- // stays flat instead of paying N× the RTT that a sequential per-server- // loop would.- const perServer = await Promise.all(- servers.map(async (server) => {- const [rows, categories] = await Promise.all([- queries.communityChannel.listChannelsForMember(db, server.id, botUserId),- queries.communityCategory.listCategoriesByServer(db, server.id),- ])-- const categoryById = new Map<string, { id: string; name: string; position: number | null; private: number | null }>()- for (const c of categories) categoryById.set(c.id, c)-- const uncategorized: ChannelListItem[] = []- const byCategory = new Map<string, ChannelListItem[]>()-- // rows come from `listChannelsForMember` already ordered by- // `communityChannel.position asc`; bucket into groups preserving that- // per-bucket order.- for (const c of rows) {- const cat = c.categoryId ? categoryById.get(c.categoryId) : null- const isPrivate = !!(cat && (cat.private ?? 0) === 1)- // Single canonical-ref emitter (B1): dispatch the ref shape off the- // channel type's addressing trait, same emitter the agent inbox uses,- // so listChannels can't drift from how send/read/ack resolve the ref.- // These are top-level channels (`listChannelsForMember` filters- // parent_channel_id IS NULL) → the `by-server-name` arm, which given- // server+name never returns null; the non-null assertion documents that- // (B1.1: the old `?? formatRef(...)` fallback was dead code — a second- // hand-built top-level shape outside the emitter — and is removed so the- // ref shape lives ONLY in formatCanonicalRef).- const ref = formatCanonicalRef({- type: (c.type ?? "text") as StoredChannelType,- serverName: server.name,- name: c.name,- })- const item: ChannelListItem = {- ref: ref!,- name: c.name,- type: c.type,- visibility: isPrivate ? "private" : "public",- }- if (!c.categoryId || !cat) {- uncategorized.push(item)- } else {- const bucket = byCategory.get(c.categoryId) ?? []- bucket.push(item)- byCategory.set(c.categoryId, bucket)- }- }-- const serverGroups: ChannelGroup[] = []- if (uncategorized.length > 0) {- serverGroups.push({ category: null, channels: uncategorized })- }- for (const cat of categories) {- const items = byCategory.get(cat.id)- if (!items || items.length === 0) continue- serverGroups.push({- category: { name: cat.name, private: (cat.private ?? 0) === 1 },- channels: items,- })- }- return serverGroups- }),- )-- const groups: ChannelGroup[] = perServer.flat()-- return NextResponse.json({ groups })-})diff --git a/src/web/src/app/api/community/listFriends/route.ts b/src/web/src/app/api/community/listFriends/route.tsdeleted file mode 100644index 5b11d650c..000000000--- a/src/web/src/app/api/community/listFriends/route.ts+++ /dev/null@@ -1,74 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries } from "@alook/shared"-import type { FriendCard } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { wsDoFetch } from "@/lib/broadcast"--/**- * POST /api/community/listFriends — moved from /api/community/agent/listFriends- * (plan §4, §9 phase 4). MOVE-FLAT, not FOLD onto GET /friends: the bot's- * friend list has DIFFERENT semantics from the human's — it aggregates three- * buckets (accepted + pendingOutgoing + pendingIncoming) with presence via- * `listAgentFriends`, whereas the human GET /friends returns accepted + blocked- * (pending is a separate /friends/pending route). Per the plan's judgment rule- * (Melly #113: different semantics → keep distinct under the unified actor,- * bot-gated), and matching batch1 which also kept listFriends as a distinct RPC.- * Bot-only → human actor rejected 403. Never emits `isBot`. Body unchanged from- * the /agent original except wrapper + identity source.- */-export const POST = withCommunityActor(async (_req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId-- const db = getDb(ctx.env.DB)-- const buckets = await queries.communityFriendship.listAgentFriends(db, botUserId)-- // Presence is WS-connection-based (see friends/presence route) — one bulk- // check across every peer id in every bucket.- const allPeerIds = [- ...buckets.accepted,- ...buckets.pendingOutgoing,- ...buckets.pendingIncoming,- ].map((r) => r.peerUserId)- const uniquePeerIds = [...new Set(allPeerIds)]- let onlineSet = new Set<string>()- if (uniquePeerIds.length > 0) {- try {- const resp = await wsDoFetch(- ctx.env,- "/presence/users",- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ids: uniquePeerIds }),- },- { label: botUserId },- )- if (resp.ok) {- const data = (await resp.json()) as { online: string[] }- if (Array.isArray(data.online)) onlineSet = new Set(data.online)- }- } catch {- /* presence best-effort — default everyone offline */- }- }-- const toCard = (r: (typeof buckets.accepted)[number]): FriendCard => ({- userId: r.peerUserId,- handle: `${r.name}#${r.discriminator}`,- name: r.name,- bio: r.aboutMe ?? null,- statusText: r.statusText ?? null,- statusEmoji: r.statusEmoji ?? null,- presence: onlineSet.has(r.peerUserId) ? "online" : "offline",- })-- return NextResponse.json({- accepted: buckets.accepted.map(toCard),- pendingOutgoing: buckets.pendingOutgoing.map(toCard),- pendingIncoming: buckets.pendingIncoming.map(toCard),- })-})diff --git a/src/web/src/app/api/community/listMembers/route.ts b/src/web/src/app/api/community/listMembers/route.tsdeleted file mode 100644index c178f6084..000000000--- a/src/web/src/app/api/community/listMembers/route.ts+++ /dev/null@@ -1,92 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import {- queries,- CommunityAgentListMembersRequestSchema,- formatHandle,- DEFAULT_MEMBERS_PAGE_SIZE,- MAX_MEMBERS_PAGE_SIZE,-} from "@alook/shared"-import type { CommunityCliServerMemberListResult as ServerMemberListResult } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { parseMemberCursor } from "@/lib/community/messages"-import { fetchOnlineUserIds, toMemberStatus } from "@/lib/community/member-presence"--/**- * POST /api/community/listMembers — moved from /api/community/agent/listMembers- * (plan §4 MOVE-FLAT, §9 phase 4). `alook server member --server <id-or-name>`.- * Body `{ server }` — id OR name, resolved via `resolveServerByNameForMember`.- * Ref/name-addressed → can't fold onto the `[id]`-param human- * servers/[id]/members route (Fork B): the bot addresses by name, the CLI- * can't form the `[id]` URL. Lean handle shape `{handle, role}` (distinct from- * the human members route's full UI DTO). Bot-only → human actor 403. Body- * unchanged from the /agent original except wrapper + identity source.- *- * Ambiguous name matches (2+ servers) bake the candidate ids/names into the- * `error` string (no structured-hint consumer on the CLI side).- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId-- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentListMembersRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }-- const servers = await queries.communityServer.resolveServerByNameForMember(db, botUserId, parsed.data.server)- if (servers.length === 0) {- return NextResponse.json({ error: `server not found: ${parsed.data.server}` }, { status: 404 })- }- if (servers.length > 1) {- const candidates = servers.map((s) => `${s.id} ("${s.name}")`).join(", ")- return NextResponse.json(- { error: `ambiguous server name "${parsed.data.server}" — matches ${servers.length} servers: ${candidates}` },- { status: 400 },- )- }- const serverId = servers[0]!.id-- // Forward-paginated roster (opaque `joinedAt|id` cursor). The server roster is- // the whole-server audience — potentially unbounded — so unlike private- // channel/thread rosters it must page. limit is clamped to DEFAULT/MAX.- const limit = Math.min(- Math.max(parsed.data.limit ?? DEFAULT_MEMBERS_PAGE_SIZE, 1),- MAX_MEMBERS_PAGE_SIZE,- )- const cursor = parseMemberCursor(parsed.data.cursor ?? null)- const page = await queries.communityMember.listMembersPaginated(db, serverId, { cursor, limit })-- // Bulk presence for THIS page's user ids only (bounded) — never per-member.- const onlineSet = await fetchOnlineUserIds(- ctx.env,- page.members.map((r) => r.userId),- serverId,- )-- const members = page.members.map((r) => ({- handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),- role: r.role ?? "member",- online: onlineSet.has(r.userId),- status: toMemberStatus(r),- }))-- // listMembersPaginated already computed the next-page keyset (present iff- // hasMore); serialize it to the opaque `joinedAt|id` wire cursor.- const cursorOut = page.cursor ? `${page.cursor.joinedAt}|${page.cursor.id}` : undefined-- return NextResponse.json<ServerMemberListResult>({- members,- hasMore: page.hasMore,- cursor: cursorOut,- })-})diff --git a/src/web/src/app/api/community/marks/[messageId]/route.test.ts b/src/web/src/app/api/community/marks/[messageId]/route.test.tsdeleted file mode 100644index 374fe4ffe..000000000--- a/src/web/src/app/api/community/marks/[messageId]/route.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockUnmarkMessage = vi.fn()-const mockIsMessageMarked = vi.fn()--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--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: {- communityMessageMark: {- unmarkMessage: (...args: unknown[]) => mockUnmarkMessage(...args),- isMessageMarked: (...args: unknown[]) => mockIsMessageMarked(...args),- },- },- }-})--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { DELETE, GET } from "./route"--const ctx = { params: { messageId: "m1" } }--describe("DELETE /api/community/marks/[messageId]", () => {- beforeEach(() => vi.clearAllMocks())-- it("unmarks self-scoped to ctx.userId and returns ok", async () => {- mockUnmarkMessage.mockResolvedValue({ id: "mk1" })- const res = await DELETE(new NextRequest("http://localhost/api/community/marks/m1", { method: "DELETE" }), ctx)- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ ok: true })- expect(mockUnmarkMessage).toHaveBeenCalledWith({}, { userId: "u1", messageId: "m1" })- })-- it("returns ok even when nothing was deleted (another user's mark = 0-row no-op)", async () => {- // unmarkMessage's WHERE is userId=ctx.userId AND messageId, so deleting a- // mark owned by someone else matches 0 rows — the route still returns ok- // (idempotent), never touching the other user's private mark.- mockUnmarkMessage.mockResolvedValue(null)- const res = await DELETE(new NextRequest("http://localhost/api/community/marks/m1", { method: "DELETE" }), ctx)- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ ok: true })- })-})--describe("GET /api/community/marks/[messageId]", () => {- beforeEach(() => vi.clearAllMocks())-- it("returns {marked:true} when the current user marked the message", async () => {- mockIsMessageMarked.mockResolvedValue(true)- const res = await GET(new NextRequest("http://localhost/api/community/marks/m1"), ctx)- expect(await res.json()).toEqual({ marked: true })- // self-scoped: the query is asked "did u1 mark m1", never "did anyone".- expect(mockIsMessageMarked).toHaveBeenCalledWith({}, "u1", "m1")- })-- it("returns {marked:false} when the current user has not marked it", async () => {- mockIsMessageMarked.mockResolvedValue(false)- const res = await GET(new NextRequest("http://localhost/api/community/marks/m1"), ctx)- expect(await res.json()).toEqual({ marked: false })- })-})diff --git a/src/web/src/app/api/community/marks/[messageId]/route.ts b/src/web/src/app/api/community/marks/[messageId]/route.tsdeleted file mode 100644index 18968a0e7..000000000--- a/src/web/src/app/api/community/marks/[messageId]/route.ts+++ /dev/null@@ -1,38 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"--// Toggle-off: unmark a message for the current user. Self-scoped — deletes only-// ctx.userId's own row; another user's mark on the same message is untouched-// (0-row no-op). Returns ok whether or not a row existed (idempotent).-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {- const messageId = ctx.params?.messageId- if (!messageId) return writeError("missing message id", 400)-- const db = getDb(ctx.env.DB)- await queries.communityMessageMark.unmarkMessage(db, {- userId: ctx.userId,- messageId,- })-- return writeJSON({ ok: true })-})--// Menu-open check: is THIS message marked by the current user? Self-scoped-// (WHERE userId=ctx.userId) — answers "did *I* mark it", never "did anyone",-// so it can't leak another user's private mark state. One-row index lookup.-export const GET = withAuth(async (_req: NextRequest, ctx) => {- const messageId = ctx.params?.messageId- if (!messageId) return writeError("missing message id", 400)-- const db = getDb(ctx.env.DB)- const marked = await queries.communityMessageMark.isMessageMarked(- db,- ctx.userId,- messageId,- )-- return writeJSON({ marked })-})diff --git a/src/web/src/app/api/community/marks/route.ts b/src/web/src/app/api/community/marks/route.tsdeleted file mode 100644index 9a07f0fc6..000000000--- a/src/web/src/app/api/community/marks/route.ts+++ /dev/null@@ -1,42 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { requireChannelMember } from "@/lib/community/permissions"--// Toggle-on: mark a message for the current user. Self-scoped — the mark row is-// always keyed to ctx.userId, never a body-supplied id. Idempotent: a re-mark-// hits UNIQUE(userId, messageId) and no-ops (markMessage uses-// onConflictDoNothing), so the client can call it without a 409 dance.-export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- let body: { channelId?: string; messageId?: string }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }- if (!body.messageId) return writeError("missing messageId", 400)- if (!body.channelId) return writeError("missing channelId", 400)-- // You can only mark a message you can see — gate on channel membership.- const auth = await requireChannelMember(db, body.channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- // The target message must belong to the channel the caller claims — prevents- // marking a message via a channel the caller can see but the message isn't in.- const target = await queries.communityMessage.getMessage(db, body.messageId)- if (!target || target.channelId !== body.channelId) {- return writeError("message not found", 404)- }-- await queries.communityMessageMark.markMessage(db, {- userId: ctx.userId,- channelId: body.channelId,- messageId: body.messageId,- })-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/community/media/[...key]/route.test.ts b/src/web/src/app/api/community/media/[...key]/route.test.tsdeleted file mode 100644index b73be3dfe..000000000--- a/src/web/src/app/api/community/media/[...key]/route.test.ts+++ /dev/null@@ -1,188 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const r2Get = vi.fn()-const getSession = vi.fn()-const getChannelForMember = vi.fn()-const getDM = vi.fn()-const getDMPeer = vi.fn()-const isBlocked = vi.fn()--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({- env: {- DB: {},- CACHE_KV: null,- COMMUNITY_MEDIA: { get: (...a: unknown[]) => r2Get(...a) },- },- })),-}))--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-vi.mock("@/lib/cache", () => ({ bindCacheKV: vi.fn() }))--vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: (...a: unknown[]) => getSession(...a) },- })),-}))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityChannel: { getChannelForMember: (...a: unknown[]) => getChannelForMember(...a) },- communityDm: {- getDM: (...a: unknown[]) => getDM(...a),- getDMPeer: (...a: unknown[]) => getDMPeer(...a),- },- communityFriendship: { isBlocked: (...a: unknown[]) => isBlocked(...a) },- },- }-})--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--function call(segments: string[]) {- return GET(- new NextRequest("http://localhost/api/community/media/" + segments.join("/"), {- method: "GET",- }),- { params: Promise.resolve({ key: segments }) },- )-}--describe("GET /api/community/media/[...key]", () => {- beforeEach(() => {- vi.clearAllMocks()- getSession.mockResolvedValue({ user: { id: "u1" } })- isBlocked.mockResolvedValue(false)- r2Get.mockResolvedValue({- body: new ReadableStream(),- httpMetadata: { contentType: "image/png" },- })- })-- it("returns 401 when there is no authenticated session", async () => {- getSession.mockResolvedValue(null)- const res = await call(["channel", "c1", "f1", "x.png"])- expect(res.status).toBe(401)- expect(r2Get).not.toHaveBeenCalled()- })-- it("returns 400 when any segment is `..` (path traversal)", async () => {- const res = await call(["channel", "..", "f1", "x.png"])- expect(res.status).toBe(400)- expect(r2Get).not.toHaveBeenCalled()- })-- it("returns 400 when any segment contains a slash", async () => {- const res = await call(["channel", "c1/extra", "f1", "x.png"])- // NextRequest may collapse multi-slash routes; just guard the unit- // contract by passing segments directly.- expect(res.status).toBe(400)- expect(r2Get).not.toHaveBeenCalled()- })-- it("returns 403 when the caller is not a member of the channel", async () => {- getChannelForMember.mockResolvedValue(null)- const res = await call(["channel", "c1", "f1", "x.png"])- expect(res.status).toBe(403)- expect(r2Get).not.toHaveBeenCalled()- })-- it("serves a channel attachment when the caller is a member", async () => {- getChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })- const res = await call(["channel", "c1", "f1", "x.png"])- expect(res.status).toBe(200)- expect(res.headers.get("Content-Type")).toBe("image/png")- expect(res.headers.get("Content-Disposition")).toBe("inline")- expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff")- expect(r2Get).toHaveBeenCalledWith("channel/c1/f1/x.png")- })-- it("returns 404 when the caller is not a DM participant (no access-member row)", async () => {- // DMs are channels: a non-participant has no relation='access' member row,- // so `getDMPeer` returns null and `requireDMAccess` collapses to 404.- getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "" })- getDMPeer.mockResolvedValue(null)- const res = await call(["dm", "d1", "f1", "x.png"])- expect(res.status).toBe(404)- expect(r2Get).not.toHaveBeenCalled()- })-- it("returns 404 when the DM does not exist", async () => {- getDM.mockResolvedValue(null)- const res = await call(["dm", "d1", "f1", "x.png"])- expect(res.status).toBe(404)- })-- it("returns 403 when the caller is blocked by the DM counterpart", async () => {- // Behaviour change: previously the DM branch skipped the block check and- // would happily serve the bytes. Folding the block into- // `requireDMAccess` closes that gap.- getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "" })- getDMPeer.mockResolvedValue({ otherUserId: "u2" })- isBlocked.mockResolvedValue(true)- const res = await call(["dm", "d1", "f1", "x.png"])- expect(res.status).toBe(403)- expect(r2Get).not.toHaveBeenCalled()- })-- it("serves a DM attachment when the caller participates and isn't blocked", async () => {- getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "" })- getDMPeer.mockResolvedValue({ otherUserId: "u2" })- isBlocked.mockResolvedValue(false)- const res = await call(["dm", "d1", "f1", "x.png"])- expect(res.status).toBe(200)- expect(r2Get).toHaveBeenCalledWith("dm/d1/f1/x.png")- })-- it("serves a server-icon to any authenticated user (no membership check)", async () => {- const res = await call(["server-icon", "s1", "f1"])- expect(res.status).toBe(200)- expect(getChannelForMember).not.toHaveBeenCalled()- expect(getDM).not.toHaveBeenCalled()- })-- it("returns 404 for unknown resource kinds", async () => {- const res = await call(["secret", "s1", "x"])- expect(res.status).toBe(404)- expect(r2Get).not.toHaveBeenCalled()- })-- it.each(["image/png", "image/jpeg", "image/webp", "image/gif"])(- "serves the safe raster type %s inline",- async (contentType) => {- getChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })- r2Get.mockResolvedValue({ body: new ReadableStream(), httpMetadata: { contentType } })- const res = await call(["channel", "c1", "f1", "safe-image"])- expect(res.headers.get("Content-Disposition")).toBe("inline")- expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff")- },- )-- it.each([- ["image/svg+xml", "vector.svg"],- ["image/x-custom", "forged.img"],- ["text/html", "prototype.html"],- ["application/octet-stream", "unknown.blend"],- ])("forces %s downloads and disables sniffing", async (contentType, filename) => {- getChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })- r2Get.mockResolvedValue({- body: new ReadableStream(),- httpMetadata: { contentType },- })- const res = await call(["channel", "c1", "f1", filename])- expect(res.headers.get("Content-Disposition")).toBe(`attachment; filename="${filename}"`)- expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff")- })-})diff --git a/src/web/src/app/api/community/media/[...key]/route.ts b/src/web/src/app/api/community/media/[...key]/route.tsdeleted file mode 100644index 8635d0076..000000000--- a/src/web/src/app/api/community/media/[...key]/route.ts+++ /dev/null@@ -1,82 +0,0 @@-import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { CACHE_IMMUTABLE } from "@alook/shared"-import { writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { createAuth } from "@/lib/auth"-import { bindCacheKV } from "@/lib/cache"-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"-import { isChannelTarget, isThreadTarget, isDmTarget } from "@/lib/community/message-handler"-import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"--// Reject any segment that could smuggle traversal or escape the bucket.-function isSafeSegment(s: string): boolean {- return s.length > 0 && s !== "." && s !== ".." && !s.includes("/") && !s.includes("\\")-}--/**- * Authenticated media proxy for community attachments.- *- * Catch-all `[...key]` requires a custom params shape (`string[]`) that- * `withAuth`'s `Record<string, string>` typing rejects, so we inline the- * Better-Auth session lookup here instead of going through `withAuth`.- */-export const GET = async (- req: NextRequest,- { params }: { params: Promise<{ key: string[] }> },-) => {- const { key } = await params- if (!key?.length) return writeError("not found", 404)- if (!key.every(isSafeSegment)) return writeError("invalid path", 400)-- const { env } = await getCloudflareContext({ async: true })- const cloudflareEnv = env as Env- bindCacheKV(cloudflareEnv.CACHE_KV ?? null)-- const auth = createAuth(cloudflareEnv)- let session: Awaited<ReturnType<typeof auth.api.getSession>>- try {- session = await auth.api.getSession({ headers: req.headers })- } catch {- return writeError("session validation failed", 503)- }- if (!session) return writeError("unauthorized", 401)- const userId = session.user.id-- const [kind, id] = key- const db = getDb(cloudflareEnv.DB)-- // Authorize by resource kind. Each branch loads the parent resource and- // verifies membership/participation BEFORE serving any bytes.- if (isChannelTarget(kind) || isThreadTarget(kind)) {- if (!id) return writeError("not found", 404)- const check = await requireChannelMember(db, id, userId)- if (!check.ok) return writeError(check.error, check.status)- } else if (isDmTarget(kind)) {- if (!id) return writeError("not found", 404)- // Block check is inherited from `requireDMAccess` — do not re-inline.- const check = await requireDMAccess(db, id, userId)- if (!check.ok) return writeError(check.error, check.status)- } else if (kind === "server-icon") {- // Icons are readable by any authenticated user — auth-only gate.- } else {- return writeError("not found", 404)- }-- const r2Key = key.join("/")- const obj = await cloudflareEnv.COMMUNITY_MEDIA.get(r2Key)- if (!obj) return writeError("not found", 404)-- const contentType = obj.httpMetadata?.contentType ?? "application/octet-stream"- const isInline = isInlineAttachmentContentType(contentType)- const lastSegment = key[key.length - 1] ?? "file"-- return new Response(obj.body, {- headers: {- "Content-Type": contentType,- "Content-Disposition": isInline ? "inline" : `attachment; filename="${lastSegment}"`,- "X-Content-Type-Options": "nosniff",- "Cache-Control": CACHE_IMMUTABLE,- },- })-}diff --git a/src/web/src/app/api/community/marks/route.test.ts b/src/web/src/app/api/community/messages/[id]/marks/route.test.tssimilarity index 51%rename from src/web/src/app/api/community/marks/route.test.tsrename to src/web/src/app/api/community/messages/[id]/marks/route.test.tsindex 44fb92b70..b8f390887 100644--- a/src/web/src/app/api/community/marks/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/marks/route.test.ts@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mockMarkMessage = vi.fn()+const mockUnmarkMessage = vi.fn()+const mockIsMessageMarked = vi.fn()const mockGetMessage = vi.fn()const mockRequireChannelMember = vi.fn()@@ -18,6 +20,8 @@ vi.mock("@alook/shared", async () => {queries: {communityMessageMark: {markMessage: (...args: unknown[]) => mockMarkMessage(...args),+ unmarkMessage: (...args: unknown[]) => mockUnmarkMessage(...args),+ isMessageMarked: (...args: unknown[]) => mockIsMessageMarked(...args),},communityMessage: {getMessage: (...args: unknown[]) => mockGetMessage(...args),@@ -45,16 +49,21 @@ vi.mock("@/lib/middleware/helpers", () => {}})-import { POST } from "./route"+import { PUT, DELETE, GET } from "./route"-function postReq(body: unknown) {- return new NextRequest("http://localhost/api/community/marks", {- method: "POST",+const ctx = { params: { id: "m1" } }++function putReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/messages/m1/marks", {+ method: "PUT",body: JSON.stringify(body),})}-describe("POST /api/community/marks", () => {+// PUT = toggle-on. messageId in the path, channelId in the body (the+// membership + belongs-to-channel gate). Byte-identical to the former flat+// POST /marks except the message id moved flat→path.+describe("PUT /api/community/messages/[id]/marks", () => {beforeEach(() => {vi.clearAllMocks()mockRequireChannelMember.mockResolvedValue({ ok: true, value: { id: "c1" } })@@ -63,7 +72,7 @@ describe("POST /api/community/marks", () => {})it("marks a visible message for the current user, self-scoped to ctx.userId", async () => {- const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))+ const res = await PUT(putReq({ channelId: "c1" }), ctx)expect(res.status).toBe(200)expect(await res.json()).toEqual({ ok: true })expect(mockMarkMessage).toHaveBeenCalledWith({}, {@@ -74,38 +83,72 @@ describe("POST /api/community/marks", () => {})it("is idempotent — a re-mark still returns ok (markMessage no-ops on conflict)", async () => {- // markMessage uses onConflictDoNothing, so the route does not 409; the- // second call is a plain ok, unlike pins which 409 on duplicate.- await POST(postReq({ channelId: "c1", messageId: "m1" }))- const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))+ await PUT(putReq({ channelId: "c1" }), ctx)+ const res = await PUT(putReq({ channelId: "c1" }), ctx)expect(res.status).toBe(200)expect(await res.json()).toEqual({ ok: true })})it("404s when the message does not belong to the claimed channel", async () => {mockGetMessage.mockResolvedValue({ id: "m1", channelId: "other" })- const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))+ const res = await PUT(putReq({ channelId: "c1" }), ctx)expect(res.status).toBe(404)expect(mockMarkMessage).not.toHaveBeenCalled()})it("404s when the message does not exist", async () => {mockGetMessage.mockResolvedValue(null)- const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))+ const res = await PUT(putReq({ channelId: "c1" }), ctx)expect(res.status).toBe(404)expect(mockMarkMessage).not.toHaveBeenCalled()})it("forwards the channel-membership gate — a non-member cannot mark", async () => {mockRequireChannelMember.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })- const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))+ const res = await PUT(putReq({ channelId: "c1" }), ctx)expect(res.status).toBe(403)expect(mockGetMessage).not.toHaveBeenCalled()expect(mockMarkMessage).not.toHaveBeenCalled()})- it("400s on missing messageId or channelId", async () => {- expect((await POST(postReq({ channelId: "c1" }))).status).toBe(400)- expect((await POST(postReq({ messageId: "m1" }))).status).toBe(400)+ it("400s on missing channelId", async () => {+ expect((await PUT(putReq({}), ctx)).status).toBe(400)+ })+})++describe("DELETE /api/community/messages/[id]/marks", () => {+ beforeEach(() => vi.clearAllMocks())++ it("unmarks self-scoped to ctx.userId and returns ok", async () => {+ mockUnmarkMessage.mockResolvedValue({ id: "mk1" })+ const res = await DELETE(new NextRequest("http://localhost/api/community/messages/m1/marks", { method: "DELETE" }), ctx)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ ok: true })+ expect(mockUnmarkMessage).toHaveBeenCalledWith({}, { userId: "u1", messageId: "m1" })+ })++ it("returns ok even when nothing was deleted (another user's mark = 0-row no-op)", async () => {+ mockUnmarkMessage.mockResolvedValue(null)+ const res = await DELETE(new NextRequest("http://localhost/api/community/messages/m1/marks", { method: "DELETE" }), ctx)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ ok: true })+ })+})++describe("GET /api/community/messages/[id]/marks", () => {+ beforeEach(() => vi.clearAllMocks())++ it("returns {marked:true} when the current user marked the message", async () => {+ mockIsMessageMarked.mockResolvedValue(true)+ const res = await GET(new NextRequest("http://localhost/api/community/messages/m1/marks"), ctx)+ expect(await res.json()).toEqual({ marked: true })+ // self-scoped: the query is asked "did u1 mark m1", never "did anyone".+ expect(mockIsMessageMarked).toHaveBeenCalledWith({}, "u1", "m1")+ })++ it("returns {marked:false} when the current user has not marked it", async () => {+ mockIsMessageMarked.mockResolvedValue(false)+ const res = await GET(new NextRequest("http://localhost/api/community/messages/m1/marks"), ctx)+ expect(await res.json()).toEqual({ marked: false })})})diff --git a/src/web/src/app/api/community/messages/[id]/marks/route.ts b/src/web/src/app/api/community/messages/[id]/marks/route.tsnew file mode 100644index 000000000..1d0510dbb--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/marks/route.ts@@ -0,0 +1,89 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { requireChannelMember } from "@/lib/community/permissions"++/**+ * Message-keyed mark door (route/disc trunk 接口树统一, marks relocation, Melly+ * #420): a mark is a mutation ON a message → message-keyed, self-scoped (the row+ * is always keyed to ctx.userId, never a body-supplied id). Folds the former+ * flat `marks` verbs:+ * - PUT → toggle-on (was POST /marks)+ * - DELETE → toggle-off (was DELETE /marks/{messageId})+ * - GET → is-this-marked-by-me (was GET /marks/{messageId})+ * The cross-channel "my marks list" aggregate is a user-scoped read and lives at+ * GET users/me/marks (relocated separately). Bodies are byte-identical to the+ * former routes; only the addressing moved (messageId flat→path).+ */++// Toggle-on: mark a message for the current user. Idempotent — a re-mark hits+// UNIQUE(userId, messageId) and no-ops (markMessage uses onConflictDoNothing),+// so the client can call it without a 409 dance.+export const PUT = withAuth(async (req: NextRequest, ctx) => {+ const messageId = ctx.params?.id+ if (!messageId) return writeError("missing message id", 400)++ const db = getDb(ctx.env.DB)++ let body: { channelId?: string }+ try {+ body = await req.json()+ } catch {+ return writeError("invalid request body", 400)+ }+ if (!body.channelId) return writeError("missing channelId", 400)++ // You can only mark a message you can see — gate on channel membership.+ const auth = await requireChannelMember(db, body.channelId, ctx.userId)+ if (!auth.ok) return writeError(auth.error, auth.status)++ // The target message must belong to the channel the caller claims — prevents+ // marking a message via a channel the caller can see but the message isn't in.+ const target = await queries.communityMessage.getMessage(db, messageId)+ if (!target || target.channelId !== body.channelId) {+ return writeError("message not found", 404)+ }++ await queries.communityMessageMark.markMessage(db, {+ userId: ctx.userId,+ channelId: body.channelId,+ messageId,+ })++ return writeJSON({ ok: true })+})++// Toggle-off: unmark a message for the current user. Self-scoped — deletes only+// ctx.userId's own row; another user's mark on the same message is untouched+// (0-row no-op). Returns ok whether or not a row existed (idempotent).+export const DELETE = withAuth(async (_req: NextRequest, ctx) => {+ const messageId = ctx.params?.id+ if (!messageId) return writeError("missing message id", 400)++ const db = getDb(ctx.env.DB)+ await queries.communityMessageMark.unmarkMessage(db, {+ userId: ctx.userId,+ messageId,+ })++ return writeJSON({ ok: true })+})++// Menu-open check: is THIS message marked by the current user? Self-scoped+// (WHERE userId=ctx.userId) — answers "did *I* mark it", never "did anyone",+// so it can't leak another user's private mark state. One-row index lookup.+export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const messageId = ctx.params?.id+ if (!messageId) return writeError("missing message id", 400)++ const db = getDb(ctx.env.DB)+ const marked = await queries.communityMessageMark.isMessageMarked(+ db,+ ctx.userId,+ messageId,+ )++ return writeJSON({ marked })+})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.tsindex 631f5fd31..6b242f2e3 100644--- 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.ts@@ -22,7 +22,10 @@ vi.mock("@alook/shared", async () => {...actual,queries: {...actual.queries,- communityMessage: { getMessage: (...a: unknown[]) => mockGetMessage(...a) },+ communityMessage: {+ getMessage: (...a: unknown[]) => mockGetMessage(...a),+ getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),+ },communityChannel: { getChannelType: (...a: unknown[]) => mockGetChannelType(...a) },communityReaction: {addReaction: (...a: unknown[]) => mockAddReaction(...a),@@ -42,11 +45,25 @@ vi.mock("@/lib/community/fanout", () => ({fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+const mockGetMessageByChannelAndSeq = vi.fn();+const mockResolveTargetForMember = vi.fn();++vi.mock("@/lib/community/resolve-ref", () => ({+ resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),+}));++// Dual-actor: crk_ bearer → bot, else human (mirrors the real wrapper). The bot+// arm reaches resolveTargetForMember + getMessageByChannelAndSeq; the human arm+// carries the messageId in the path.+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (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 });- }),+ const authz = req?.headers?.get?.("Authorization") ?? "";+ const actor = authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]" };+ return handler(req, { env: { DB: {} }, actor, params });+ },}));vi.mock("@/lib/middleware/helpers", async () => {@@ -66,6 +83,17 @@ function req(method: string) {return new NextRequest("http://localhost/api/community/messages/m1/reactions/%F0%9F%91%8D", { method });}+// Bot PUT: crk_ bearer + `{ channel, seq }` body (folded reactAdd); the path id+// is the `resolve` placeholder.+const ctxResolve = { params: { id: "resolve", emoji: encodeURIComponent("👍") } } as any;+function botReq(method: string, body?: unknown) {+ return new NextRequest("http://localhost/api/community/messages/resolve/reactions/%F0%9F%91%8D", {+ method,+ headers: { Authorization: "Bearer crk_abc", "content-type": "application/json" },+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),+ });+}+describe("reactions [emoji] surface guard", () => {beforeEach(() => {vi.clearAllMocks();@@ -78,11 +106,11 @@ describe("reactions [emoji] surface guard", () => {mockFanOutToDM.mockResolvedValue(undefined);});- it("PUT rejects reacting on a forum top-level with 400", async () => {+ it("PUT allows reacting on a forum top-level (phase2 forum≡thread write-guard reversal — forum is now a message-bearing surface)", async () => {mockGetChannelType.mockResolvedValue("forum");const res = await PUT(req("PUT"), ctx);- expect(res.status).toBe(400);- expect(mockAddReaction).not.toHaveBeenCalled();+ expect(res.status).toBe(200);+ expect(mockAddReaction).toHaveBeenCalled();});it("PUT allows reacting in a DM (bearing surface, block-checked)", async () => {@@ -102,11 +130,11 @@ describe("reactions [emoji] surface guard", () => {expect(mockFanOutToChannel).toHaveBeenCalled();});- it("DELETE (un-react) rejects a forum top-level with 400", async () => {+ it("DELETE (un-react) allows a forum top-level (phase2 forum≡thread write-guard reversal — forum is now a message-bearing surface)", async () => {mockGetChannelType.mockResolvedValue("forum");const res = await DELETE(req("DELETE"), ctx);- expect(res.status).toBe(400);- expect(mockRemoveReaction).not.toHaveBeenCalled();+ expect(res.status).toBe(204);+ expect(mockRemoveReaction).toHaveBeenCalled();});it("DELETE (un-react) works in a DM", async () => {@@ -115,4 +143,54 @@ describe("reactions [emoji] surface guard", () => {expect(res.status).toBe(204);expect(mockRemoveReaction).toHaveBeenCalled();});++ // ── bot arm (folded reactAdd `{channel,seq,emoji}`): ref+seq → member-scoped+ // 404, never a 403 leak (①-C). ──++ it("bot PUT resolves ref+seq via resolveTargetForMember, then reacts", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" });+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m1" });+ mockGetChannelType.mockResolvedValue("text");+ const res = await PUT(botReq("PUT", { channel: "/s/general", seq: 42 }), ctxResolve);+ expect(res.status).toBe(200);+ expect(mockResolveTargetForMember).toHaveBeenCalledWith({}, "bot_1", "/s/general", {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ });+ expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42);+ expect(mockAddReaction).toHaveBeenCalled();+ });++ it("①-C: bot PUT ref to an UNREACHABLE channel → 404 (resolve member-scoped, not 403)", async () => {+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "channel not found: general" });+ const res = await PUT(botReq("PUT", { channel: "/s/general", seq: 42 }), ctxResolve);+ expect(res.status).toBe(404);+ // never reaches the messageId-keyed authorizeReaction / addReaction.+ expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled();+ expect(mockGetMessage).not.toHaveBeenCalled();+ expect(mockAddReaction).not.toHaveBeenCalled();+ });++ it("bot PUT ref resolves but seq absent → 404", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" });+ mockGetMessageByChannelAndSeq.mockResolvedValue(null);+ const res = await PUT(botReq("PUT", { channel: "/s/general", seq: 999 }), ctxResolve);+ expect(res.status).toBe(404);+ expect(mockAddReaction).not.toHaveBeenCalled();+ });++ it("bot PUT rejects a body missing channel/seq with 400", async () => {+ const res = await PUT(botReq("PUT", { seq: 42 }), ctxResolve);+ expect(res.status).toBe(400);+ expect(mockResolveTargetForMember).not.toHaveBeenCalled();+ });++ it("bot DELETE (no react-remove verb) → defensive 404, never the 403 leak", async () => {+ const res = await DELETE(botReq("DELETE"), ctxResolve);+ expect(res.status).toBe(404);+ // opaque — no message/channel lookup runs for the bot arm.+ expect(mockGetMessage).not.toHaveBeenCalled();+ expect(mockRemoveReaction).not.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 c1ae0e67e..914b8387a 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@@ -1,5 +1,5 @@import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"+import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import {@@ -9,16 +9,74 @@ import {WS_EVENTS,} from "@alook/shared"import type { Database } from "@alook/shared"+import type { CommunityActor } from "@/lib/middleware/community-actor"import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"import {requireChannelMember,requireDMAccess,} from "@/lib/community/permissions"import { requireReactableSurface } from "@/lib/community/channel-write-guard"+import { resolveTargetForMember } from "@/lib/community/resolve-ref"++// A bot addresses by ref-in-body (`{ channel, seq }`, the folded `reactAdd`+// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`+// and can't sit in a path segment). A human/web caller puts the real messageId+// in the path.+const REF_PLACEHOLDER_ID = "resolve"type AccessOk = { ok: true; channelId: string; isDm: boolean }type AccessErr = { ok: false; status: 400 | 401 | 403 | 404; error: string }+type MsgIdOk = { ok: true; messageId: string }+type MsgIdErr = { ok: false; status: number; error: string }++/**+ * Resolve the target messageId for a reaction, one addressing input per actor:+ * - human/web: real messageId in the path (unchanged — byte-identical to pre-+ * 5c; `authorizeReaction` below then re-resolves the message → channel and+ * keeps the 403/404 split web needs).+ * - bot/CLI: ref-in-body `{ channel, seq }` (the folded `reactAdd`). The ref+ * goes through `resolveTargetForMember` FIRST (member-scoped inner-join, so+ * an unreachable channel yields ZERO rows → 404 BEFORE any message lookup),+ * then the channel-scoped `getMessageByChannelAndSeq` (a seq absent in that+ * channel → 404). So a bot NEVER sees the mask's 403 for a known-but-non-+ * member channel — it 404s at resolve first (①-C uniform existence-mask; the+ * 403 leak 5c newly exposed by opening this route to bot credentials,+ * Blondie/Aigneis #294/#295). Reaction is add-only for bots (no+ * create-if-missing — a ref to a nonexistent DM/thread 404s, never creates).+ */+async function resolveReactionMessageId(+ db: Database,+ actor: CommunityActor,+ ctx: { params?: { id?: string } },+ raw: unknown,+): Promise<MsgIdOk | MsgIdErr> {+ if (actor.kind === "bot") {+ const body = (raw ?? {}) as { channel?: unknown; seq?: unknown }+ const ref = typeof body.channel === "string" ? body.channel : ""+ const seq = typeof body.seq === "number" ? body.seq : NaN+ if (!ref) return { ok: false, status: 400, error: "channel ref required" }+ if (!Number.isInteger(seq) || seq <= 0) return { ok: false, status: 400, error: "valid seq required" }++ const resolved = await resolveTargetForMember(db, actor.userId, ref, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return { ok: false, status: resolved.error, error: resolved.message }++ const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { channelId: resolved.channelId }, seq)+ if (!message) return { ok: false, status: 404, error: "message not found" }+ return { ok: true, messageId: message.id }+ }++ const pathId = ctx.params?.id+ if (typeof pathId !== "string" || !pathId || pathId === REF_PLACEHOLDER_ID) {+ return { ok: false, status: 400, error: "missing message id" }+ }+ return { ok: true, messageId: pathId }+}+/*** Resolve the message and verify the caller can react.* Reactions follow the same access rules as reading the message itself —@@ -46,25 +104,51 @@ async function authorizeReaction(return { ok: true, channelId: message.channelId, isDm: false }}-export const PUT = withAuth(async (_req: NextRequest, ctx) => {- const messageId = ctx.params?.id+/**+ * Message-keyed reaction door (route/disc trunk — message-keyed faces dual-actor).+ * withCommunityActor: both human (session) and bot (crk_, the folded `reactAdd`+ * verb) hit this one route. Authorization is credential-scoped — `authorizeReaction`+ * resolves the message → its channel → the per-surface gate (requireDMAccess for a+ * DM incl block, requireChannelMember otherwise) keyed on `ctx.actor.userId`, so a+ * bot reaction runs the SAME mask a human does (no bot bypass). The bot's ref+seq→+ * messageId resolution happens upstream at the flat-verb→door retarget (proxy); this+ * route is message-keyed (messageId in path) for both actors.+ */+export const PUT = withCommunityActor(async (req: NextRequest, ctx) => {const rawEmoji = ctx.params?.emoji- if (!messageId || !rawEmoji) return writeError("missing params", 400)+ if (!rawEmoji) return writeError("missing params", 400)const emoji = decodeURIComponent(rawEmoji)if (Buffer.byteLength(emoji, "utf8") > MAX_EMOJI_BYTES) {return writeError("emoji too long", 400)}+ const userId = ctx.actor.userIdconst db = getDb(ctx.env.DB)- const access = await authorizeReaction(db, messageId, ctx.userId)++ // Target messageId: bot ref+seq (member-scoped → 404), human path id. A bot+ // body is `{ channel, seq, emoji }` — emoji is already the path segment, so+ // only channel+seq are read from the body here.+ let raw: unknown = undefined+ if (ctx.actor.kind === "bot") {+ try {+ raw = await req.json()+ } catch {+ return writeError("invalid JSON body", 400)+ }+ }+ const msgId = await resolveReactionMessageId(db, ctx.actor, ctx, raw)+ if (!msgId.ok) return writeError(msgId.error, msgId.status)+ const messageId = msgId.messageId++ const access = await authorizeReaction(db, messageId, userId)if (!access.ok) return writeError(access.error, access.status)let reactiontry {reaction = await queries.communityReaction.addReaction(db, {messageId,- userId: ctx.userId,+ userId,emoji,})} catch (e) {@@ -75,49 +159,58 @@ export const PUT = withAuth(async (_req: NextRequest, ctx) => {const event = {type: WS_EVENTS.REACTION_ADD as typeof WS_EVENTS.REACTION_ADD,messageId,- userId: ctx.userId,+ userId,emoji,channelId: access.channelId,}if (access.isDm) {- fanOutToDM(access.channelId, event, { excludeUserId: ctx.userId })+ fanOutToDM(access.channelId, event, { excludeUserId: userId })} else {- fanOutToChannel(access.channelId, event, { excludeUserId: ctx.userId })+ fanOutToChannel(access.channelId, event, { excludeUserId: userId })}return writeJSON(reaction)})-export const DELETE = withAuth(async (_req: NextRequest, ctx) => {+export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {+ // Defensive bot→404 (①-C): there is NO bot react-REMOVE verb in the ServerApi+ // contract (only `reactAdd`), so no bot caller reaches this arm today and the+ // retarget wires none. 5c opened bot credentials on the route; collapse the+ // bot arm to an opaque 404 rather than let a future react-remove verb slip+ // through to the messageId-in-path `authorizeReaction` (whose 403 would leak+ // message existence to a bot). Human path unchanged.+ if (ctx.actor.kind === "bot") return writeError("not found", 404)+const messageId = ctx.params?.idconst rawEmoji = ctx.params?.emojiif (!messageId || !rawEmoji) return writeError("missing params", 400)const emoji = decodeURIComponent(rawEmoji)+ const userId = ctx.actor.userIdconst db = getDb(ctx.env.DB)- const access = await authorizeReaction(db, messageId, ctx.userId)+ const access = await authorizeReaction(db, messageId, userId)if (!access.ok) return writeError(access.error, access.status)await queries.communityReaction.removeReaction(db, {messageId,- userId: ctx.userId,+ userId,emoji,})const event = {type: WS_EVENTS.REACTION_REMOVE as typeof WS_EVENTS.REACTION_REMOVE,messageId,- userId: ctx.userId,+ userId,emoji,channelId: access.channelId,}if (access.isDm) {- fanOutToDM(access.channelId, event, { excludeUserId: ctx.userId })+ fanOutToDM(access.channelId, event, { excludeUserId: userId })} else {- fanOutToChannel(access.channelId, event, { excludeUserId: ctx.userId })+ fanOutToChannel(access.channelId, event, { excludeUserId: userId })}return new Response(null, { status: 204 })diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.tsindex bbd86f670..409cd2144 100644--- a/src/web/src/app/api/community/messages/[id]/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts@@ -6,17 +6,30 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockGetMessage = vi.fn()+const mockUpdateOwnMessageContent = vi.fn()const mockGetMessagesByIdsInScope = vi.fn()const mockGetChannelForMember = vi.fn()const mockGetChannelType = vi.fn()+const mockGetThreadChannelByParentMessage = vi.fn()const mockGetDM = vi.fn()const mockGetDMPeer = vi.fn()const mockIsBlocked = vi.fn()const mockListByMessageIds = vi.fn()const mockListReactionsByMessageIds = vi.fn()+const mockGetMessageByChannelAndSeq = vi.fn()+const mockToAgentMessage = vi.fn()+const mockResolveTargetForMember = vi.fn()+const mockFanOutToChannel = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/community/resolve-ref", () => ({+ resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),+}))+vi.mock("@/lib/community/fanout", () => ({+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),+}))+vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {@@ -25,10 +38,16 @@ vi.mock("@alook/shared", async () => {communityChannel: {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),getChannelType: (...a: unknown[]) => mockGetChannelType(...a),+ getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),},communityMessage: {getMessage: (...a: unknown[]) => mockGetMessage(...a),getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),+ getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),+ updateOwnMessageContent: (...a: unknown[]) => mockUpdateOwnMessageContent(...a),+ },+ communityAgentInbox: {+ toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a),},communityAttachment: {listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),@@ -47,11 +66,17 @@ vi.mock("@alook/shared", async () => {}})-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+// Dual-actor: crk_ bearer → bot (folded resolve), else human. Human arm carries+// messageId in the path; bot arm carries ref+seq on the query.+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),+ const authz = req?.headers?.get?.("Authorization") ?? ""+ const actor = authz.startsWith("Bearer crk_")+ ? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }+ : { kind: "human", userId: "u1", email: "[email protected]" }+ return handler(req, { env: { DB: {} }, actor, params })+ },}))vi.mock("@/lib/middleware/helpers", () => {@@ -62,7 +87,7 @@ vi.mock("@/lib/middleware/helpers", () => {}})-import { GET } from "./route"+import { GET, PATCH } from "./route"function req() {return new NextRequest("http://localhost/api/community/messages/m1", { method: "GET" })@@ -94,8 +119,9 @@ describe("GET /api/community/messages/[id]", () => {dmConversationId: null,})mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })+ mockGetThreadChannelByParentMessage.mockResolvedValue(null)mockListByMessageIds.mockResolvedValue([- { messageId: "m1", filename: "photo.png", r2Key: "channel/c1/uuid/photo.png", contentType: "image/png", size: 12345 },+ { id: "att_1", messageId: "m1", targetId: "c1", filename: "photo.png", r2Key: "channel/c1/uuid/photo.png", contentType: "image/png", size: 12345 },])mockListReactionsByMessageIds.mockResolvedValue([{ messageId: "m1", emoji: "👍", userId: "u1" },@@ -107,10 +133,11 @@ describe("GET /api/community/messages/[id]", () => {expect(body.id).toBe("m1")expect(body.content).toBe("hello")expect(body.authorName).toBe("Alice")- // Attachments came through the mapper (grouped shape) — url is now- // derived from r2Key via the shared helper.+ // Attachments came through the mapper (grouped shape) — url is now the+ // id-addressed render URL (attachments fold), served by the canonical+ // channels/{targetId}/attachments/{attachmentId} door.expect(body.attachments).toEqual([- { kind: "image", name: "photo.png", url: "/api/community/media/channel/c1/uuid/photo.png" },+ { kind: "image", name: "photo.png", url: "/api/community/channels/c1/attachments/att_1" },])// Reactions came through with `me: true` since userId matches.expect(body.reactions).toEqual([@@ -264,4 +291,137 @@ describe("GET /api/community/messages/[id]", () => {expect(res.status).toBe(400)expect(mockGetMessage).not.toHaveBeenCalled()})++ // ── bot arm (folded `resolve` verb): ref+seq → member-scoped 404, {message}+ // agent-shape projection. ──++ function botReq(ref?: string, seq?: string) {+ const q = new URLSearchParams()+ if (ref !== undefined) q.set("ref", ref)+ if (seq !== undefined) q.set("seq", seq)+ return new NextRequest(`http://localhost/api/community/messages/resolve?${q.toString()}`, {+ method: "GET",+ headers: { Authorization: "Bearer crk_abc" },+ })+ }+ const ctxResolve = { params: { id: "resolve" } } as any++ it("bot resolves ref+seq via resolveTargetForMember → {message} agent shape", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m42", channelId: "c1" })+ mockListByMessageIds.mockResolvedValue([])+ mockToAgentMessage.mockResolvedValue({ seq: "#42", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" })+ const res = await GET(botReq("/s/general", "42"), ctxResolve)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ message: expect.objectContaining({ seq: "#42" }) })+ expect(mockResolveTargetForMember).toHaveBeenCalledWith({}, "bot_1", "/s/general", {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 42)+ })++ it("①-C: bot ref to an UNREACHABLE channel → 404 (member-scoped resolve, not a 403 leak)", async () => {+ mockResolveTargetForMember.mockResolvedValue({ error: 404, message: "channel not found: general" })+ const res = await GET(botReq("/s/general", "42"), ctxResolve)+ expect(res.status).toBe(404)+ // never reaches the seq lookup or the message hydrate.+ expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled()+ expect(mockGetMessage).not.toHaveBeenCalled()+ })++ it("bot ref resolves but seq absent in the channel → 404", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })+ mockGetMessageByChannelAndSeq.mockResolvedValue(null)+ const res = await GET(botReq("/s/general", "999"), ctxResolve)+ expect(res.status).toBe(404)+ })++ it("bot seq 0 → 404 (legacy pre-migration sentinel, never a real message)", async () => {+ const res = await GET(botReq("/s/general", "0"), ctxResolve)+ expect(res.status).toBe(404)+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()+ })++ it("bot missing ref → 400", async () => {+ const res = await GET(botReq(undefined, "42"), ctxResolve)+ expect(res.status).toBe(400)+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()+ })++ it("bot non-integer seq → 400", async () => {+ const res = await GET(botReq("/s/general", "abc"), ctxResolve)+ expect(res.status).toBe(400)+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()+ })+})++describe("PATCH /api/community/messages/[id]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetChannelType.mockResolvedValue("text")+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1", authorId: "u1", content: "old" })+ mockUpdateOwnMessageContent.mockResolvedValue({ id: "m1", channelId: "c1", content: "new" })+ mockFanOutToChannel.mockResolvedValue(undefined)+ })++ function editReq(content: unknown, bot = false) {+ return new NextRequest("http://localhost/api/community/messages/m1", {+ method: "PATCH",+ headers: { "content-type": "application/json", ...(bot ? { Authorization: "Bearer crk_x" } : {}) },+ body: JSON.stringify({ content }),+ })+ }++ it("updates the author's own content", async () => {+ const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)+ expect(res.status).toBe(200)+ expect(mockUpdateOwnMessageContent).toHaveBeenCalledWith(expect.anything(), {+ messageId: "m1", authorId: "u1", content: "new",+ })+ expect(mockFanOutToChannel).toHaveBeenCalledWith("c1", {+ type: "community:message.edited", channelId: "c1", messageId: "m1", content: "new",+ })+ })++ it("does not let an admin or other member edit someone else's message", async () => {+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1", authorId: "u2", content: "old" })+ const res = await PATCH(editReq("hijack"), { params: { id: "m1" } } as any)+ expect(res.status).toBe(403)+ expect(mockUpdateOwnMessageContent).not.toHaveBeenCalled()+ })++ it("resolves a real parent-forum opener to its child and omits parent data for replies", async () => {+ // Production shape: opener m1 belongs to the parent forum c1; the child+ // post row points back to it through parentMessageId.+ mockGetChannelType.mockResolvedValue("forum")+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })+ mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "post_1", type: "thread", parentChannelId: "c1", parentMessageId: "m1" })+ const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)+ expect(res.status).toBe(200)+ expect(mockGetThreadChannelByParentMessage).toHaveBeenCalledWith(expect.anything(), "c1", "m1")+ expect(mockFanOutToChannel).toHaveBeenCalledWith("c1", expect.objectContaining({ parentChannelId: "c1" }))++ mockFanOutToChannel.mockClear()+ mockGetChannelType.mockResolvedValue("thread")+ mockGetMessage.mockResolvedValue({ id: "reply_1", channelId: "post_1", authorId: "u1", content: "old" })+ mockGetChannelForMember.mockResolvedValue({ id: "post_1", serverId: "s1", type: "thread", parentChannelId: "c1" })+ mockUpdateOwnMessageContent.mockResolvedValue({ id: "reply_1", channelId: "post_1", content: "new" })+ await PATCH(+ new NextRequest("http://localhost/api/community/messages/reply_1", {+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ content: "new" }),+ }),+ { params: { id: "reply_1" } } as any,+ )+ expect(mockFanOutToChannel.mock.calls[0]?.[1]).not.toHaveProperty("parentChannelId")+ })++ it("rejects bot credentials and empty content", async () => {+ expect((await PATCH(editReq("new", true), { params: { id: "m1" } } as any)).status).toBe(401)+ expect((await PATCH(editReq(" "), { params: { id: "m1" } } as any)).status).toBe(400)+ })})diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.tsindex ee5fd1c4f..36a2c9ef8 100644--- a/src/web/src/app/api/community/messages/[id]/route.ts+++ b/src/web/src/app/api/community/messages/[id]/route.ts@@ -1,34 +1,119 @@import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"+import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"+import { queries, MAX_MESSAGE_CONTENT_LENGTH, WS_EVENTS } from "@alook/shared"import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"+import { resolveTargetForMember } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"+import { fanOutToChannel } from "@/lib/community/fanout"import { groupAttachments, groupReactions } from "@/lib/community/messages"import { mapMessageForApi } from "@/lib/community/message-payload"+// A bot addresses by ref-in-query (`?ref=` + `?seq=`, the folded `resolve`+// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`+// and can't sit in a path segment). A human/web caller puts the real messageId+// in the path.+const REF_PLACEHOLDER_ID = "resolve"+/**- * GET /api/community/messages/[id]+ * GET /api/community/messages/[id] — single fully-hydrated message.*- * Returns a single fully-hydrated message (attachments + reactions + reply- * preview) shaped by `mapMessageForApi`. Currently the only client of this is- * the thread-view "opener" block — when the user opens a thread channel, the- * client fetches the parent message via its `parentMessageId` pointer and- * renders it pinned at the top of the message list.+ * Dual-actor hydrate door (route/disc trunk — folds the `resolve` bot verb).+ * withCommunityActor serves human (session, id-in-path) + bot (crk_, ref+seq).+ * The response FORM forks by the credential actor (Aigneis ②, never a field):+ * - human/web → `mapMessageForApi` (attachments + reactions + reply preview),+ * the thread-opener block shape. Addressing: messageId in the path.+ * - bot/CLI → `toAgentMessage` (the folded `resolve` verb's `{ message }`+ * agent shape). Addressing: ref+seq — the bot holds a ref+seq, not an id,+ * so `resolve` was never id-addressable (Gener #68).*- * Access model: the caller must have access to the surface the message lives- * in — a server member for channel messages, a DM participant for DM messages.- * This is deliberately the SAME check as GET /channels/[id]/messages: since- * server membership grants access to every channel in the server, a thread- * viewer who can read the thread's messages can also read the outer channel's- * parent-message opener. No separate "is this a parentMessageId of a thread I- * can see" branch is needed — the server-scoped check subsumes it.+ * Authorization is credential-scoped and ①-C uniform:+ * - human/id: getMessage → its channel → per-surface gate (requireDMAccess /+ * requireChannelMember). known-but-non-member → 403, the 403/404 split web+ * needs — byte-identical to the pre-fold route.+ * - bot/ref: `resolveTargetForMember` FIRST (member-scoped inner-join → an+ * unreachable channel is 0 rows → 404 BEFORE any message lookup), then the+ * channel-scoped seq lookup. So a bot never sees a 403 disclosing a+ * message/channel it can't reach (same ①-C mask as reactions/seq).+ * Both arms hydrate the SAME row (attachments + reply scoped to the message's+ * own surface); only the projection differs.*/-export const GET = withAuth(async (_req: NextRequest, ctx) => {+export const GET = withCommunityActor(async (req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)++ if (ctx.actor.kind === "bot") {+ return handleBotResolve(db, ctx.actor.userId, req)+ }+ return handleHumanGet(db, ctx.actor.userId, ctx.params?.id)+})++/** PATCH /api/community/messages/[id] — edit only the caller's own text.+ * Admin status never grants edit-as-author; attachments are intentionally not+ * part of this contract. */+export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {+ if (ctx.actor.kind !== "human") return writeError("human session required", 401)const messageId = ctx.params?.id- if (!messageId) return writeError("missing message id", 400)+ if (!messageId || messageId === REF_PLACEHOLDER_ID) return writeError("missing message id", 400)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return writeError("invalid request body", 400)+ }+ const content = raw && typeof raw === "object" ? (raw as { content?: unknown }).content : undefined+ if (typeof content !== "string" || content.trim().length === 0) {+ return writeError("content is required", 400)+ }+ if (content.length > MAX_MESSAGE_CONTENT_LENGTH) {+ return writeError(`content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters`, 400)+ }const db = getDb(ctx.env.DB)+ const message = await queries.communityMessage.getMessage(db, messageId)+ if (!message) return writeError("message not found", 404)++ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ const access = channelType === "dm"+ ? await requireDMAccess(db, message.channelId, ctx.actor.userId)+ : await requireChannelMember(db, message.channelId, ctx.actor.userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (message.authorId !== ctx.actor.userId) return writeError("only the message author may edit it", 403)++ const updated = await queries.communityMessage.updateOwnMessageContent(db, {+ messageId,+ authorId: ctx.actor.userId,+ content,+ })+ if (!updated) return writeError("message not found", 404)+ // Forum openers live in the PARENT forum channel; the child post points back+ // to them via parentMessageId. Resolve through the same indexed relation as+ // the tags route instead of inspecting the parent row's own parentMessageId.+ const openerThread = channelType === "forum"+ ? await queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId, messageId)+ : null+ const parentChannelId = openerThread?.type === "thread" ? message.channelId : undefined+ await fanOutToChannel(message.channelId, {+ type: WS_EVENTS.MESSAGE_EDITED,+ channelId: message.channelId,+ messageId,+ content,+ ...(parentChannelId ? { parentChannelId } : {}),+ })+ return writeJSON({ message: updated })+})++/**+ * Human arm — messageId in the path, `mapMessageForApi` shape. Unchanged from+ * the pre-fold route (the 403/404 split is a correct pre-existing contract).+ */+async function handleHumanGet(+ db: ReturnType<typeof getDb>,+ userId: string,+ messageId: string | undefined,+) {+ if (!messageId || messageId === REF_PLACEHOLDER_ID) return writeError("missing message id", 400)const message = await queries.communityMessage.getMessage(db, messageId)if (!message) return writeError("message not found", 404)@@ -37,40 +122,84 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {// (including threads/forum posts) uses the server-scoped member gate.const channelType = await queries.communityChannel.getChannelType(db, message.channelId)if (channelType === "dm") {- const auth = await requireDMAccess(db, message.channelId, ctx.userId)+ const auth = await requireDMAccess(db, message.channelId, userId)if (!auth.ok) return writeError(auth.error, auth.status)} else {- const auth = await requireChannelMember(db, message.channelId, ctx.userId)+ const auth = await requireChannelMember(db, message.channelId, userId)if (!auth.ok) return writeError(auth.error, auth.status)}- // Hydrate attachments, reactions, and reply target — same shape as the- // list endpoint. Run in parallel; all three depend only on `messageId`.const [allAttachments, allReactions, replyMessages] = await Promise.all([queries.communityAttachment.listByMessageIds(db, [messageId]),- queries.communityReaction.listReactionsByMessageIds(db, [messageId], ctx.userId),+ queries.communityReaction.listReactionsByMessageIds(db, [messageId], userId),message.replyToId- ? queries.communityMessage.getMessagesByIdsInScope(- db,- [message.replyToId],- { channelId: message.channelId },- )+ ? queries.communityMessage.getMessagesByIdsInScope(db, [message.replyToId], { channelId: message.channelId }): Promise.resolve([]),])const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, ctx.userId)-- // Reply target is already scoped to the SAME surface as the parent by the- // query above — a reply preview must not leak content from a different- // channel/DM.+ const reactionsByMessage = groupReactions(allReactions, userId)+ // Reply target already scoped to the SAME surface as the parent — a reply+ // preview must not leak content from a different channel/DM.const replyMap = new Map(replyMessages.map((m) => [m.id, m]))- const payload = mapMessageForApi(message, {- replyMap,- attachmentsByMessage,- reactionsByMessage,+ const payload = mapMessageForApi(message, { replyMap, attachmentsByMessage, reactionsByMessage })+ return writeJSON(payload)+}++/**+ * Bot arm — the folded `resolve` verb. ref+seq (query) → member-scoped resolve+ * (404-before-mask) → channel-scoped seq lookup → `toAgentMessage` shape.+ * Behavior byte-identical to the old flat `resolve` route (same gates, same+ * `{ message }` agent shape, same seq===0 legacy-sentinel 404).+ */+async function handleBotResolve(+ db: ReturnType<typeof getDb>,+ botUserId: string,+ req: NextRequest,+) {+ const params = req.nextUrl.searchParams+ const ref = params.get("ref")+ const seqRaw = params.get("seq")+ if (!ref) return writeError("channel ref required", 400)+ const seq = seqRaw === null ? NaN : Number(seqRaw)+ if (!Number.isInteger(seq)) return writeError("valid seq required", 400)+ // seq 0 is the legacy pre-migration sentinel — never a real message.+ if (seq === 0) return writeError("seq 0 is not a real message", 404)+ if (seq < 0) return writeError("valid seq required", 400)++ // Member-scoped resolve FIRST (unreachable → 404 before any lookup, ①-C). No+ // create-if-missing — resolve is pure addressing (resolve≠create).+ const resolved = await resolveTargetForMember(db, botUserId, ref, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",})+ if ("error" in resolved) return writeError(resolved.message, resolved.error)- return writeJSON(payload)-})+ const scopeTarget = { channelId: resolved.channelId }+ // Per-surface gate on the resolved channel (dispatch by surface; DM incl+ // block). resolveTargetForMember already member-scoped the resolve, so this+ // re-affirms access on the concrete channel — matching the old resolve route.+ if (isDmTarget(resolved)) {+ const gate = await requireDMAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) return writeError(gate.error, gate.status)+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return writeError(gate.error, gate.status)+ }++ const row = await queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, seq)+ if (!row) return writeError(`no message with seq #${seq} in ${ref}`, 404)++ const attachmentRows = await queries.communityAttachment.listByMessageIds(db, [row.id])+ const attachments = attachmentRows.map((a) => ({+ id: a.id,+ filename: a.filename,+ contentType: a.contentType,+ size: a.size,+ }))++ const message = await queries.communityAgentInbox.toAgentMessage(db, row, botUserId, attachments)+ return writeJSON({ message })+}diff --git a/src/web/src/app/api/community/messages/[id]/tags/route.test.ts b/src/web/src/app/api/community/messages/[id]/tags/route.test.tsnew file mode 100644index 000000000..16ee3d766--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/tags/route.test.ts@@ -0,0 +1,107 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const mockGetMessage = vi.fn()+const mockGetThread = vi.fn()+const mockReplaceTags = vi.fn()+const mockRequireChannelAccess = 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: { ...actual.queries.communityMessage, getMessage: (...args: unknown[]) => mockGetMessage(...args) },+ communityChannel: { ...actual.queries.communityChannel, getThreadChannelByParentMessage: (...args: unknown[]) => mockGetThread(...args) },+ communityMessageTag: {+ ...actual.queries.communityMessageTag,+ replaceMessageTags: (...args: unknown[]) => mockReplaceTags(...args),+ },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({+ requireChannelAccess: (...args: unknown[]) => mockRequireChannelAccess(...args),+}))+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => (req: any, routeCtx: any) => handler(req, {+ env: { DB: {} },+ userId: "u1",+ params: routeCtx.params,+ }),+}))+vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (error: string, status: number) => NextResponse.json({ error }, { status }),+ }+})++import { PUT } from "./route"++function request(tags: unknown) {+ return new NextRequest("http://localhost/api/community/messages/m1/tags", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ tags }),+ })+}++const ctx = { params: { id: "m1" } } as any++describe("PUT /api/community/messages/[id]/tags", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "forum1", authorId: "u1" })+ mockRequireChannelAccess.mockResolvedValue({+ ok: true,+ value: { channel: { id: "forum1", type: "forum" }, member: { role: "member" } },+ })+ mockGetThread.mockResolvedValue({ id: "thread1", type: "thread", parentMessageId: "m1" })+ })++ it("lets the opener author replace the normalized tag set", async () => {+ const res = await PUT(request([" Keep ", "NEW", "new"]), ctx)++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ tags: ["keep", "new"] })+ expect(mockReplaceTags).toHaveBeenCalledWith(expect.anything(), { messageId: "m1", tags: ["keep", "new"] })+ })++ it("lets a server admin edit another author's opener tags", async () => {+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "forum1", authorId: "u2" })+ mockRequireChannelAccess.mockResolvedValue({+ ok: true,+ value: { channel: { id: "forum1", type: "forum" }, member: { role: "admin" } },+ })++ const res = await PUT(request(["triage"]), ctx)+ expect(res.status).toBe(200)+ expect(mockReplaceTags).toHaveBeenCalledWith(expect.anything(), { messageId: "m1", tags: ["triage"] })+ })++ it("rejects a non-author member", async () => {+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "forum1", authorId: "u2" })++ const res = await PUT(request(["nope"]), ctx)+ expect(res.status).toBe(403)+ expect(mockReplaceTags).not.toHaveBeenCalled()+ })++ it("rejects a normal forum message that did not open a thread", async () => {+ mockGetThread.mockResolvedValue(null)++ const res = await PUT(request(["nope"]), ctx)+ expect(res.status).toBe(400)+ expect(await res.json()).toEqual({ error: "message is not a forum opener" })+ })++ it("enforces the server-side tag count limit", async () => {+ const res = await PUT(request(["a", "b", "c", "d", "e", "f"]), ctx)+ expect(res.status).toBe(400)+ expect(mockGetMessage).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/messages/[id]/tags/route.ts b/src/web/src/app/api/community/messages/[id]/tags/route.tsnew file mode 100644index 000000000..d20c2fb44--- /dev/null+++ b/src/web/src/app/api/community/messages/[id]/tags/route.ts@@ -0,0 +1,63 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import {+ queries,+ canManageServer,+ MAX_FORUM_TAG_LENGTH,+ MAX_FORUM_TAGS_PER_POST,+} from "@alook/shared"+import { requireChannelAccess } from "@/lib/community/permissions"++/** Replace the tag set on a forum opener message. */+export const PUT = withAuth(async (req: NextRequest, ctx) => {+ const messageId = ctx.params?.id+ if (!messageId) return writeError("missing message id", 400)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return writeError("invalid request body", 400)+ }+ if (!raw || typeof raw !== "object" || !Array.isArray((raw as { tags?: unknown }).tags)) {+ return writeError("tags must be an array", 400)+ }+ const input = (raw as { tags: unknown[] }).tags+ if (input.some((tag) => typeof tag !== "string")) {+ return writeError("tags must contain only strings", 400)+ }+ const tags = [...new Set((input as string[]).map((tag) => tag.trim().toLowerCase()).filter(Boolean))]+ if (tags.length > MAX_FORUM_TAGS_PER_POST) {+ return writeError(`too many tags (max ${MAX_FORUM_TAGS_PER_POST})`, 400)+ }+ if (tags.some((tag) => tag.length > MAX_FORUM_TAG_LENGTH)) {+ return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)+ }++ const db = getDb(ctx.env.DB)+ const message = await queries.communityMessage.getMessage(db, messageId)+ if (!message) return writeError("message not found", 404)++ const access = await requireChannelAccess(db, message.channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (access.value.channel.type !== "forum") {+ return writeError("tags are only supported on forum opener messages", 400)+ }+ const thread = await queries.communityChannel.getThreadChannelByParentMessage(+ db,+ message.channelId,+ message.id,+ )+ if (!thread || thread.type !== "thread") {+ return writeError("message is not a forum opener", 400)+ }++ const mayEdit = message.authorId === ctx.userId || canManageServer(access.value.member.role)+ if (!mayEdit) return writeError("forbidden", 403)++ await queries.communityMessageTag.replaceMessageTags(db, { messageId, tags })++ return writeJSON({ tags })+})diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts b/src/web/src/app/api/community/messages/[id]/threads/route.test.tsdeleted file mode 100644index 7b778bf37..000000000--- a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts+++ /dev/null@@ -1,267 +0,0 @@-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 mockGetChannelForMember = vi.fn()-const mockListChildChannels = vi.fn()-const mockCreateChannel = vi.fn()-const mockCreateMessage = vi.fn()-const mockListMessages = vi.fn()-const mockAddThreadParticipants = vi.fn()--const mockFanOutToChannel = 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: {- communityChannel: {- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),- createChannel: (...a: unknown[]) => mockCreateChannel(...a),- },- communityMessage: {- getMessage: (...a: unknown[]) => mockGetMessage(...a),- createMessage: (...a: unknown[]) => mockCreateMessage(...a),- listMessages: (...a: unknown[]) => mockListMessages(...a),- },- communityThread: {- addThreadParticipants: (...a: unknown[]) => mockAddThreadParticipants(...a),- },- },- }-})--vi.mock("@/lib/community/fanout", () => ({- fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { POST } from "./route"-import { queries } from "@alook/shared"--function req(body: unknown) {- return new NextRequest("http://localhost/api/community/messages/msg-p/threads", {- method: "POST",- body: JSON.stringify(body),- })-}--const ctx = { params: { id: "msg-p" } } as any--describe("POST /api/community/messages/[id]/threads", () => {- beforeEach(() => {- vi.clearAllMocks()- // The unified pipeline fires `fanOutToChannel(...).catch(...)` — the mock- // must return a promise so the `.catch` chain resolves.- mockFanOutToChannel.mockResolvedValue(undefined)- mockAddThreadParticipants.mockResolvedValue(undefined)- // Both the caller (u1) and the parent-message author (u-author) resolve as- // members by default — the seeding path checks membership per userId.- mockGetChannelForMember.mockResolvedValue({- id: "c-parent",- serverId: "s1",- type: "text",- })- mockListChildChannels.mockResolvedValue([])- mockCreateChannel.mockResolvedValue({- id: "t-new",- name: "my thread",- serverId: "s1",- parentChannelId: "c-parent",- parentMessageId: "msg-p",- type: "thread",- creatorId: "u1",- messageCount: 0,- createdAt: "2026-07-03T00:00:00.000Z",- })- mockGetMessage.mockResolvedValue({- id: "msg-p",- authorId: "u-author",- content: "the parent content",- channelId: "c-parent",- })- })-- it("creates the child channel WITHOUT inserting any message into either channel", async () => {- const res = await POST(req({ name: "my thread" }), ctx)- expect(res.status).toBe(201)-- // No message row is created anywhere: no clone into the new thread- // channel, and no "XXX started a thread: NAME" notice into the parent.- expect(mockCreateMessage).not.toHaveBeenCalled()-- // Structural check: listMessages on the new thread channel is empty —- // no opener clone row exists.- mockListMessages.mockResolvedValue([])- const listed = await queries.communityMessage.listMessages({} as never, {- channelId: "t-new",- })- expect(listed).toEqual([])-- // The child channel keeps the parentMessageId pointer (single source of- // truth for the opener).- expect(mockCreateChannel).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- parentChannelId: "c-parent",- parentMessageId: "msg-p",- type: "thread",- }),- )-- // Response is the child channel itself — not a message.- const body = await res.json()- expect(body.id).toBe("t-new")- expect(body.parentMessageId).toBe("msg-p")-- // Only the CHILD_CHANNEL_CREATE fan-out fires to the parent channel — no- // system-message MESSAGE_CREATE broadcast.- expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)- expect(mockFanOutToChannel).toHaveBeenCalledWith(- "c-parent",- expect.objectContaining({ parentMessageId: "msg-p" }),- expect.anything(),- )- const messageCreateCall = mockFanOutToChannel.mock.calls.find(- (call) => (call[1] as { type?: string }).type === "community:message.create",- )- expect(messageCreateCall).toBeUndefined()- })-- it("rejects a second thread on the same parent message", async () => {- mockListChildChannels.mockResolvedValue([- { id: "t-existing", parentMessageId: "msg-p", type: "thread" },- ])- const res = await POST(req({ name: "second thread" }), ctx)- expect(res.status).toBe(409)- expect(mockCreateChannel).not.toHaveBeenCalled()- expect(mockCreateMessage).not.toHaveBeenCalled()- })-- it("400s when the parent message has no channelId (DM parent isn't threadable)", async () => {- mockGetMessage.mockResolvedValue({- id: "msg-p",- authorId: "u-author",- content: "dm content",- channelId: null,- dmConversationId: "dm-1",- })- const res = await POST(req({ name: "x" }), ctx)- expect(res.status).toBe(400)- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("404s when the parent message doesn't exist", async () => {- mockGetMessage.mockResolvedValue(null)- const res = await POST(req({ name: "x" }), ctx)- expect(res.status).toBe(404)- })-- it("400s when the parent message lives in a child channel (forum post / thread) — no grandchild threads", async () => {- // A message inside a forum_post/thread: its channel has parentChannelId set.- // Rooting a thread here would create a grandchild the single-level privacy- // anchor climb can't resolve, leaking a private forum's thread server-wide.- mockGetChannelForMember.mockResolvedValue({- id: "forum-post-1",- serverId: "s1",- parentChannelId: "forum-1",- })- const res = await POST(req({ name: "x" }), ctx)- expect(res.status).toBe(400)- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("403s when the caller isn't a member of the parent channel's server", async () => {- mockGetChannelForMember.mockResolvedValue(null)- const res = await POST(req({ name: "x" }), ctx)- expect(res.status).toBe(403)- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("400s when rooting a thread on a forum top-level message (not a message-bearing surface)", async () => {- mockGetChannelForMember.mockResolvedValue({- id: "forum-1",- serverId: "s1",- type: "forum",- parentChannelId: null,- })- const res = await POST(req({ name: "x" }), ctx)- expect(res.status).toBe(400)- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("seeds the creator (spoke) AND the parent-message author (added) as default participants", async () => {- const res = await POST(req({ name: "my thread" }), ctx)- expect(res.status).toBe(201)- expect(mockAddThreadParticipants).toHaveBeenCalledTimes(1)- const [, threadId, rows] = mockAddThreadParticipants.mock.calls[0] as [- unknown,- string,- { userId: string; source: string }[],- ]- expect(threadId).toBe("t-new")- // Creator uses "spoke" (matches the forum-post creation flow); the author- // was pulled in by someone else, so "added".- expect(rows).toEqual([- { userId: "u1", source: "spoke" },- { userId: "u-author", source: "added" },- ])- })-- it("de-dupes when the creator threads their own message (one 'spoke' row, no duplicate)", async () => {- mockGetMessage.mockResolvedValue({- id: "msg-p",- authorId: "u1",- content: "my own message",- channelId: "c-parent",- })- const res = await POST(req({ name: "my thread" }), ctx)- expect(res.status).toBe(201)- const [, , rows] = mockAddThreadParticipants.mock.calls[0] as [- unknown,- string,- { userId: string; source: string }[],- ]- expect(rows).toEqual([{ userId: "u1", source: "spoke" }])- })-- it("does NOT seed the author when they've lost access to the parent channel", async () => {- // Caller (u1) resolves as a member; the author (u-author) does not — the- // per-userId getChannelForMember returns null for them, so seeding skips- // the author to avoid pushing a private thread to a non-member.- mockGetChannelForMember.mockImplementation(async (_db: unknown, _channelId: string, userId: string) => {- if (userId === "u1") return { id: "c-parent", serverId: "s1", type: "text" }- return null- })- const res = await POST(req({ name: "my thread" }), ctx)- expect(res.status).toBe(201)- const [, , rows] = mockAddThreadParticipants.mock.calls[0] as [- unknown,- string,- { userId: string; source: string }[],- ]- expect(rows).toEqual([{ userId: "u1", source: "spoke" }])- })-})diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.ts b/src/web/src/app/api/community/messages/[id]/threads/route.tsdeleted file mode 100644index 2168ca58a..000000000--- a/src/web/src/app/api/community/messages/[id]/threads/route.ts+++ /dev/null@@ -1,111 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries, MAX_CHANNEL_NAME_LENGTH, WS_EVENTS, PARTICIPANT_SOURCE } from "@alook/shared"-import { fanOutToChannel } from "@/lib/community/fanout"-import { requireChannelMember } from "@/lib/community/permissions"-import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"--export const POST = withAuth(async (req: NextRequest, ctx) => {- const messageId = ctx.params?.id- if (!messageId) return writeError("missing message id", 400)-- const db = getDb(ctx.env.DB)-- const message = await queries.communityMessage.getMessage(db, messageId)- if (!message) return writeError("message not found", 404)- if (!message.channelId) return writeError("message is not in a channel", 400)-- const auth = await requireChannelMember(db, message.channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- const channel = auth.value-- // Threads may only root on a TOP-LEVEL channel's message. Rooting on a child- // channel (a forum post, or another thread) would make the new thread a- // grandchild whose privacy the single-level anchor climb can't resolve — it- // would read the child's own `categoryId` (always NULL) as public and leak a- // private forum's thread server-wide. The UI already forbids this (child- // views pass no create-thread action); enforce it on the API too.- if (channel.parentChannelId) {- return writeError("can't start a thread on a message in a thread or forum post", 400)- }-- // A thread roots on a real message, so the anchor's channel must be a- // message-bearing surface. A `forum` top-level is a post index, not a- // message surface — any bare message there is illegitimate (see the- // channel-type write guard), so no thread may root on it.- const bearing = requireMessageBearingSurface(channel.type)- if (!bearing.ok) return writeError(bearing.error, bearing.status)-- let body: { name?: string }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }- if (!body.name || typeof body.name !== "string") return writeError("name is required", 400)- const name = body.name.trim()- if (!name || name.length > MAX_CHANNEL_NAME_LENGTH) {- return writeError(`name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters`, 400)- }-- // One thread per message.- const existing = await queries.communityChannel.listChildChannels(db, message.channelId, {- type: "thread",- })- if (existing.some((c) => c.parentMessageId === messageId)) {- return writeError("message already has a thread", 409)- }-- const childChannel = await queries.communityChannel.createChannel(db, {- serverId: channel.serverId,- parentChannelId: message.channelId,- parentMessageId: messageId,- name,- type: "thread",- creatorId: ctx.userId,- })-- // Seed the default NOTIFY set: the thread creator (source "spoke", matching- // the forum-post creation flow and what the message-handler would write once- // they post), plus the original message's author (source "added" — they were- // pulled in by someone else, like the manual add-participant flow). The- // author is only enrolled if they are STILL a member of the parent channel —- // `requireChannelMember` above only gated the creator, so seeding the author- // unconditionally could push a private channel's thread to someone who lost- // access (the leak `removeParticipantFromChildChannels` exists to prevent).- const seedRows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.ADDED }[] = [- { userId: ctx.userId, source: PARTICIPANT_SOURCE.SPOKE },- ]- // De-dupe: when the creator threads their own message the author is the same- // user, and the creator's "spoke" row already covers them.- if (message.authorId !== ctx.userId) {- const authorStillMember = await requireChannelMember(db, message.channelId, message.authorId)- if (authorStillMember.ok) seedRows.push({ userId: message.authorId, source: PARTICIPANT_SOURCE.ADDED })- }- await queries.communityThread.addThreadParticipants(db, childChannel.id, seedRows)-- // Note: we intentionally do NOT clone the parent message into the new thread- // channel. The `parentMessageId` pointer above is the single source of truth- // for the opener — the thread page fetches the parent live via- // GET /api/community/messages/[id] and renders it as a pinned block at the- // top of the message list. Cloning would drift the moment the original is- // edited, and it never carried attachments / reactions / mentions in the- // first place.-- fanOutToChannel(message.channelId, {- type: WS_EVENTS.CHILD_CHANNEL_CREATE,- parentChannelId: message.channelId,- channel: {- id: childChannel.id,- name: childChannel.name,- type: "thread" as const,- creatorId: ctx.userId,- createdAt: childChannel.createdAt,- },- parentMessageId: messageId,- }, { excludeUserId: ctx.userId })-- return writeJSON(childChannel, 201)-})diff --git a/src/web/src/app/api/community/messages/batch/route.test.ts b/src/web/src/app/api/community/messages/batch/route.test.tsnew file mode 100644index 000000000..cedbe8667--- /dev/null+++ b/src/web/src/app/api/community/messages/batch/route.test.ts@@ -0,0 +1,86 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })) }))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockRequireMessageSurfaceAccess = vi.fn()+const mockGetMessagesByIdsInScope = vi.fn()+const mockGetFirstMessageByChannelIds = vi.fn()+const mockGetDirectChildThreadsByIds = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMessage: {+ ...actual.queries.communityMessage,+ getMessagesByIdsInScope: (...args: unknown[]) => mockGetMessagesByIdsInScope(...args),+ getFirstMessageByChannelIds: (...args: unknown[]) => mockGetFirstMessageByChannelIds(...args),+ },+ communityChannel: {+ ...actual.queries.communityChannel,+ getDirectChildThreadsByIds: (...args: unknown[]) => mockGetDirectChildThreadsByIds(...args),+ },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any) => handler(req, { env: { DB: {} }, userId: "user_1" }),+}))+vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { POST } from "./route"++function request(body: unknown) {+ return new NextRequest("http://localhost/api/community/messages/batch", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ })+}++describe("POST /api/community/messages/batch", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: true })+ mockGetMessagesByIdsInScope.mockResolvedValue([{ id: "message_1", channelId: "forum_1" }])+ mockGetFirstMessageByChannelIds.mockResolvedValue([{ id: "reply_1", channelId: "thread_1" }])+ mockGetDirectChildThreadsByIds.mockResolvedValue([{ id: "thread_1" }])+ })++ it("gates the parent once and validates all requested direct children in one query", async () => {+ const response = await POST(request({ channelId: "forum_1", ids: ["message_1"], firstInChannelIds: ["thread_1"] }))++ expect(response.status).toBe(200)+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledWith(expect.anything(), ["message_1"], { channelId: "forum_1" })+ expect(mockRequireMessageSurfaceAccess).toHaveBeenCalledWith(expect.anything(), "forum_1", "user_1")+ expect(mockRequireMessageSurfaceAccess).toHaveBeenCalledTimes(1)+ expect(mockGetDirectChildThreadsByIds).toHaveBeenCalledWith(expect.anything(), "forum_1", ["thread_1"])+ })++ it("does not query messages when the parent scope is inaccessible", async () => {+ mockRequireMessageSurfaceAccess.mockResolvedValueOnce({ ok: false, status: 404, error: "channel not found" })++ const response = await POST(request({ channelId: "private_forum", ids: ["message_1"] }))++ expect(response.status).toBe(404)+ expect(mockGetMessagesByIdsInScope).not.toHaveBeenCalled()+ })++ it("rejects the entire batch when any id is not a direct child", async () => {+ mockGetDirectChildThreadsByIds.mockResolvedValue([])+ const response = await POST(request({ channelId: "forum_1", firstInChannelIds: ["foreign_thread"] }))+ expect(response.status).toBe(404)+ expect(mockGetFirstMessageByChannelIds).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/messages/batch/route.ts b/src/web/src/app/api/community/messages/batch/route.tsnew file mode 100644index 000000000..d1960c364--- /dev/null+++ b/src/web/src/app/api/community/messages/batch/route.ts@@ -0,0 +1,26 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"++export const POST = withAuth(async (req: NextRequest, ctx) => {+ let body: { channelId?: unknown; ids?: unknown; firstInChannelIds?: unknown }+ try { body = await req.json() } catch { return writeError("invalid request body", 400) }+ const ids = Array.isArray(body.ids) ? body.ids.filter((id): id is string => typeof id === "string") : []+ const firstInChannelIds = Array.isArray(body.firstInChannelIds)+ ? [...new Set(body.firstInChannelIds.filter((id): id is string => typeof id === "string"))]+ : []+ if (ids.length > 100 || firstInChannelIds.length > 100) return writeError("too many ids", 400)+ if (typeof body.channelId !== "string") return writeError("channelId is required", 400)++ const db = getDb(ctx.env.DB)+ const parentAccess = await requireMessageSurfaceAccess(db, body.channelId, ctx.userId)+ if (!parentAccess.ok) return writeError(parentAccess.error, parentAccess.status)+ const messages = await queries.communityMessage.getMessagesByIdsInScope(db, ids, { channelId: body.channelId })+ const childThreads = await queries.communityChannel.getDirectChildThreadsByIds(db, body.channelId, firstInChannelIds)+ if (childThreads.length !== firstInChannelIds.length) return writeError("thread not found", 404)+ const firstMessages = await queries.communityMessage.getFirstMessageByChannelIds(db, firstInChannelIds)+ return writeJSON({ messages, firstMessages })+})diff --git a/src/web/src/app/api/community/search/route.test.ts b/src/web/src/app/api/community/messages/search/route.test.tssimilarity index 91%rename from src/web/src/app/api/community/search/route.test.tsrename to src/web/src/app/api/community/messages/search/route.test.tsindex 765de1d10..dc0d88c92 100644--- a/src/web/src/app/api/community/search/route.test.ts+++ b/src/web/src/app/api/community/messages/search/route.test.ts@@ -40,7 +40,7 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"-describe("GET /api/community/search — server scope", () => {+describe("GET /api/community/messages/search — server scope", () => {beforeEach(() => {vi.clearAllMocks()mockGetMember.mockResolvedValue({ id: "m1", role: "member" })@@ -50,7 +50,7 @@ describe("GET /api/community/search — server scope", () => {it("scopes the server search to the viewer's visible channel ids", async () => {const res = await GET(- new NextRequest("http://localhost/api/community/search?q=hello&serverId=s1"),+ new NextRequest("http://localhost/api/community/messages/search?q=hello&serverId=s1"),{ params: {} } as any,)expect(res.status).toBe(200)@@ -70,7 +70,7 @@ describe("GET /api/community/search — server scope", () => {it("admin gets the same member-scoped visibility (no isAdmin flag)", async () => {mockGetMember.mockResolvedValue({ id: "m1", role: "owner" })await GET(- new NextRequest("http://localhost/api/community/search?q=hello&serverId=s1"),+ new NextRequest("http://localhost/api/community/messages/search?q=hello&serverId=s1"),{ params: {} } as any,)expect(mockListVisibleChannelIds).toHaveBeenCalledWith(diff --git a/src/web/src/app/api/community/search/route.ts b/src/web/src/app/api/community/messages/search/route.tssimilarity index 100%rename from src/web/src/app/api/community/search/route.tsrename to src/web/src/app/api/community/messages/search/route.tsdiff --git a/src/web/src/app/api/community/messages/tags/batch/route.test.ts b/src/web/src/app/api/community/messages/tags/batch/route.test.tsnew file mode 100644index 000000000..1863c14b9--- /dev/null+++ b/src/web/src/app/api/community/messages/tags/batch/route.test.ts@@ -0,0 +1,53 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })) }))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockRequireMessageSurfaceAccess = vi.fn()+const mockGetMessagesByIdsInScope = vi.fn()+const mockListTagsForMessages = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMessage: { ...actual.queries.communityMessage, getMessagesByIdsInScope: (...args: unknown[]) => mockGetMessagesByIdsInScope(...args) },+ communityMessageTag: { ...actual.queries.communityMessageTag, listTagsForMessages: (...args: unknown[]) => mockListTagsForMessages(...args) },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: (...args: unknown[]) => mockRequireMessageSurfaceAccess(...args) }))+vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: any) => async (req: any) => handler(req, { env: { DB: {} }, userId: "user_1" }) }))+vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { POST } from "./route"++describe("POST /api/community/messages/tags/batch", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: true })+ mockGetMessagesByIdsInScope.mockResolvedValue([{ id: "message_1" }])+ mockListTagsForMessages.mockResolvedValue([{ messageId: "message_1", tag: "bug" }])+ })++ it("reads tags only for message ids selected inside the authorized channel scope", async () => {+ const response = await POST(new NextRequest("http://localhost/api/community/messages/tags/batch", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ channelId: "forum_1", messageIds: ["message_1", "foreign_message"] }),+ }))++ expect(response.status).toBe(200)+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledWith(expect.anything(), ["message_1", "foreign_message"], { channelId: "forum_1" })+ expect(mockListTagsForMessages).toHaveBeenCalledWith(expect.anything(), ["message_1"])+ })+})diff --git a/src/web/src/app/api/community/messages/tags/batch/route.ts b/src/web/src/app/api/community/messages/tags/batch/route.tsnew file mode 100644index 000000000..fcf4bc707--- /dev/null+++ b/src/web/src/app/api/community/messages/tags/batch/route.ts@@ -0,0 +1,20 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"++export const POST = withAuth(async (req: NextRequest, ctx) => {+ let body: { channelId?: unknown; messageIds?: unknown }+ try { body = await req.json() } catch { return writeError("invalid request body", 400) }+ const ids = Array.isArray(body.messageIds) ? body.messageIds.filter((id): id is string => typeof id === "string") : []+ if (ids.length > 100) return writeError("too many ids", 400)+ if (typeof body.channelId !== "string") return writeError("channelId is required", 400)+ const db = getDb(ctx.env.DB)+ const access = await requireMessageSurfaceAccess(db, body.channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ const messages = await queries.communityMessage.getMessagesByIdsInScope(db, ids, { channelId: body.channelId })+ const tags = await queries.communityMessageTag.listTagsForMessages(db, messages.map((message) => message.id))+ return writeJSON({ tags })+})diff --git a/src/web/src/app/api/community/reactAdd/route.test.ts b/src/web/src/app/api/community/reactAdd/route.test.tsdeleted file mode 100644index 96c3878b4..000000000--- a/src/web/src/app/api/community/reactAdd/route.test.ts+++ /dev/null@@ -1,220 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetUserByNameAndDiscriminator = vi.fn()-const mockGetBotBinding = vi.fn()-const mockResolveServerByNameForMember = vi.fn()-const mockResolveChannelByNameForMember = vi.fn()-const mockGetChannelForMember = vi.fn()-const mockGetDM = vi.fn()-const mockGetDMBetween = vi.fn()-const mockGetDMPeer = vi.fn()-const mockIsBlocked = vi.fn()-const mockGetMessageByChannelAndSeq = vi.fn()-const mockAddReaction = vi.fn()-const mockFanOutToChannel = vi.fn(async () => undefined)-const mockFanOutToDM = vi.fn(async () => undefined)--vi.mock("@/lib/community/fanout", () => ({- fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),- fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),-}))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),- },- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityFriendship: { isBlocked: (...a: unknown[]) => mockIsBlocked(...a) },- communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },- communityChannel: {- resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityDm: {- getDM: (...a: unknown[]) => mockGetDM(...a),- getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),- getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),- },- communityMessage: {- ...actual.queries.communityMessage,- getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),- },- communityReaction: {- ...actual.queries.communityReaction,- addReaction: (...a: unknown[]) => mockAddReaction(...a),- },- },- }-})--import { POST } from "./route"--function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/reactAdd", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--describe("POST /api/community/agent/reactAdd", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- })-- it("401 without Authorization", async () => {- const res = await POST(req({ channel: "/studio/general", seq: 1, emoji: "👍" }))- expect(res.status).toBe(401)- })-- it("400 on invalid payload (missing emoji)", async () => {- const res = await POST(req({ channel: "/studio/general", seq: 1 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- })-- it("400 rejects seq 0 (positive-seq schema)", async () => {- const res = await POST(req({ channel: "/studio/general", seq: 0, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- })-- it("400 rejects oversize emoji", async () => {- const bigEmoji = "🎉".repeat(20)- const res = await POST(req({ channel: "/studio/general", seq: 1, emoji: bigEmoji }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- expect(mockAddReaction).not.toHaveBeenCalled()- })-- it("404 propagates unresolvable ref", async () => {- mockResolveServerByNameForMember.mockResolvedValue([])- const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(404)- expect(mockAddReaction).not.toHaveBeenCalled()- expect(mockFanOutToChannel).not.toHaveBeenCalled()- })-- it("403 when the bot is not a channel member", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue(null)- const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(403)- expect(mockAddReaction).not.toHaveBeenCalled()- expect(mockFanOutToChannel).not.toHaveBeenCalled()- })-- 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", 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", type: "text", parentChannelId: null })- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 3, content: "hi" })- mockAddReaction.mockResolvedValue({ messageId: "m_1", userId: "bot_1", emoji: "👍" })-- const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({ ok: true })- expect(mockAddReaction).toHaveBeenCalledWith(expect.anything(), { messageId: "m_1", userId: "bot_1", emoji: "👍" })- expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)- const [channelId, event, opts] = mockFanOutToChannel.mock.calls[0]- expect(channelId).toBe("ch_1")- expect(event).toMatchObject({- type: "community:reaction.add",- messageId: "m_1",- userId: "bot_1",- emoji: "👍",- channelId: "ch_1",- })- expect(opts).toEqual({ excludeUserId: "bot_1" })- expect(mockFanOutToDM).not.toHaveBeenCalled()- })-- it("200 happy path — DM react: fans out via fanOutToDM with channelId", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })- mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>- Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }),- )- mockGetDMBetween.mockResolvedValue({ id: "dm_1" })- mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "t" })- mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })- mockIsBlocked.mockResolvedValue(false)- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_dm_1", seq: 2, content: "hey" })- mockAddReaction.mockResolvedValue({ messageId: "m_dm_1", userId: "bot_1", emoji: "🙏" })-- const res = await POST(req({ channel: "/.dm/peer#0001", seq: 2, emoji: "🙏" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(mockFanOutToDM).toHaveBeenCalledTimes(1)- const [dmId, event, opts] = mockFanOutToDM.mock.calls[0]- expect(dmId).toBe("dm_1")- expect(event).toMatchObject({- type: "community:reaction.add",- messageId: "m_dm_1",- userId: "bot_1",- emoji: "🙏",- channelId: "dm_1",- })- expect(opts).toEqual({ excludeUserId: "bot_1" })- expect(mockFanOutToChannel).not.toHaveBeenCalled()- })-- 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", type: "text", parentChannelId: null })- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 3, content: "hi" })- // Match isUniqueConstraintError → matches SQLite UNIQUE constraint messages- mockAddReaction.mockRejectedValue(new Error("D1_ERROR: UNIQUE constraint failed: community_reaction.message_id, community_reaction.user_id, community_reaction.emoji"))-- const res = await POST(req({ channel: "/studio/general", seq: 3, emoji: "👍" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({ ok: true, duplicate: true })- expect(mockFanOutToChannel).not.toHaveBeenCalled()- expect(mockFanOutToDM).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/community/reactAdd/route.ts b/src/web/src/app/api/community/reactAdd/route.tsdeleted file mode 100644index 2b32314be..000000000--- a/src/web/src/app/api/community/reactAdd/route.ts+++ /dev/null@@ -1,103 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import {- queries,- CommunityAgentReactAddRequestSchema,- MAX_EMOJI_BYTES,- WS_EVENTS,- isUniqueConstraintError,-} from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { 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"--/**- * POST /api/community/reactAdd — agent-facing counterpart of the user- * route's PUT /api/community/messages/[id]/reactions/[emoji]. Body- * `{ channel, seq, emoji }`; identity is the bearer voucher (never a- * client-supplied agentId). Duplicates are idempotent: the DB unique- * constraint on `(messageId, userId, emoji)` throws, `isUniqueConstraintError`- * catches it, and the endpoint returns `{ ok:true, duplicate:true }` without- * a fan-out.- * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor → 403 via requireBot.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentReactAddRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }- const body = parsed.data-- if (Buffer.byteLength(body.emoji, "utf8") > MAX_EMOJI_BYTES) {- return NextResponse.json({ error: "emoji too long" }, { status: 400 })- }-- const resolved = await resolveTargetForMember(db, botUserId, body.channel, {- createDmIfMissing: false,- createThreadIfMissing: false,- callerKind: "bot",- })- if ("error" in resolved) return resolveErrorResponse(resolved)-- const scopeTarget = { channelId: resolved.channelId }-- 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)- if (!row) {- return NextResponse.json({ error: `no message with seq #${body.seq} in ${body.channel}` }, { status: 404 })- }-- try {- await queries.communityReaction.addReaction(db, {- messageId: row.id,- userId: botUserId,- emoji: body.emoji,- })- } catch (e) {- if (isUniqueConstraintError(e)) {- return NextResponse.json({ ok: true, duplicate: true })- }- throw e- }-- const event = {- type: WS_EVENTS.REACTION_ADD as typeof WS_EVENTS.REACTION_ADD,- messageId: row.id,- userId: botUserId,- emoji: body.emoji,- channelId: resolved.channelId,- }-- if (isDmTarget(resolved)) {- await fanOutToDM(resolved.channelId, event, { excludeUserId: botUserId })- } else {- await fanOutToChannel(resolved.channelId, event, { excludeUserId: botUserId })- }-- return NextResponse.json({ ok: true })-})diff --git a/src/web/src/app/api/community/read/route.test.ts b/src/web/src/app/api/community/read/route.test.tsdeleted file mode 100644index 6a8174a0e..000000000--- a/src/web/src/app/api/community/read/route.test.ts+++ /dev/null@@ -1,116 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetBotBinding = vi.fn()-const mockResolveServerByNameForMember = vi.fn()-const mockResolveChannelByNameForMember = vi.fn()-const mockGetChannelForMember = vi.fn()-const mockListMessagesBySeq = vi.fn()-const mockToAgentMessages = vi.fn()--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },- communityChannel: {- resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityAgentInbox: {- listMessagesBySeq: (...a: unknown[]) => mockListMessagesBySeq(...a),- toAgentMessages: (...a: unknown[]) => mockToAgentMessages(...a),- },- },- }-})--import { POST } from "./route"--function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/read", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--describe("POST /api/community/agent/read", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })- mockToAgentMessages.mockImplementation((_db: unknown, rows: unknown[]) => Promise.resolve(rows))- })-- it("401 without Authorization", async () => {- const res = await POST(req({ channel: "/studio/general" }))- expect(res.status).toBe(401)- })-- it("400 when more than one of before/after/around is supplied", async () => {- const res = await POST(- req({ channel: "/studio/general", before: 5, after: 1 }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(400)- })-- it("403 forbidden when the bot isn't a member of the resolved channel", async () => {- mockGetChannelForMember.mockResolvedValue(null)- const res = await POST(req({ channel: "/studio/general" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(403)- })-- it("200 happy path: returns { items, hasMore, latestSeq } from listMessagesBySeq", async () => {- mockListMessagesBySeq.mockResolvedValue({- items: [{ id: "m_1", seq: 1 }, { id: "m_2", seq: 2 }],- hasMore: true,- latestSeq: 2,- })- const res = await POST(req({ channel: "/studio/general", after: 0, limit: 2 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(await res.json()).toEqual({- items: [{ id: "m_1", seq: 1 }, { id: "m_2", seq: 2 }],- hasMore: true,- latestSeq: 2,- })- expect(mockListMessagesBySeq).toHaveBeenCalledWith(- expect.anything(),- { channelId: "ch_1" },- { before: undefined, after: 0, around: undefined, limit: 2 }- )- })-- it("omits latestSeq from the response when the page is empty (undefined, not null/0)", async () => {- mockListMessagesBySeq.mockResolvedValue({ items: [], hasMore: false, latestSeq: undefined })- const res = await POST(req({ channel: "/studio/general" }, { Authorization: "Bearer crk_abc" }))- const body = await res.json()- expect(body).toEqual({ items: [], hasMore: false })- expect("latestSeq" in body).toBe(false)- })-})diff --git a/src/web/src/app/api/community/read/route.ts b/src/web/src/app/api/community/read/route.tsdeleted file mode 100644index b8460cdb2..000000000--- a/src/web/src/app/api/community/read/route.ts+++ /dev/null@@ -1,60 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentReadRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { isDmTarget } from "@/lib/community/message-handler"-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"--/**- * POST /api/community/read — plan §7. Seq-anchored pagination (NOT- * `createdAt`-based) — pick at most one of `before`/`after`/`around`- * (enforced at the Zod layer). Response is `{ items, hasMore, latestSeq? }`- * — `items`, not `messages` (that name is reserved for `inboxPull`'s shape).- * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor → 403 via requireBot.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentReadRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }- const body = parsed.data-- const resolved = await resolveTargetForMember(db, botUserId, body.channel, {- createDmIfMissing: false,- createThreadIfMissing: false,- callerKind: "bot",- })- if ("error" in resolved) return resolveErrorResponse(resolved)-- const scopeTarget = { channelId: resolved.channelId }-- if (isDmTarget(resolved)) {- const gate = await requireDMAccess(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- } else {- const gate = await requireChannelMember(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- }-- const { items, hasMore, latestSeq } = await queries.communityAgentInbox.listMessagesBySeq(db, scopeTarget, {- before: body.before,- after: body.after,- around: body.around,- limit: body.limit,- })- const messages = await queries.communityAgentInbox.toAgentMessages(db, items, botUserId)-- return NextResponse.json({ items: messages, hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) })-})diff --git a/src/web/src/app/api/community/resolve/route.test.ts b/src/web/src/app/api/community/resolve/route.test.tsdeleted file mode 100644index 2791b2b6c..000000000--- a/src/web/src/app/api/community/resolve/route.test.ts+++ /dev/null@@ -1,176 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetUserByNameAndDiscriminator = vi.fn()-const mockGetBotBinding = vi.fn()-const mockResolveServerByNameForMember = vi.fn()-const mockResolveChannelByNameForMember = vi.fn()-const mockGetChannelForMember = vi.fn()-const mockGetDM = vi.fn()-const mockGetDMBetween = vi.fn()-const mockGetDMPeer = vi.fn()-const mockIsBlocked = vi.fn()-const mockGetMessageByChannelAndSeq = vi.fn()-const mockToAgentMessage = vi.fn()--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),- },- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },- communityFriendship: { isBlocked: (...a: unknown[]) => mockIsBlocked(...a) },- communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },- communityChannel: {- resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityDm: {- getDM: (...a: unknown[]) => mockGetDM(...a),- getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),- getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),- },- communityMessage: {- ...actual.queries.communityMessage,- getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),- },- communityAgentInbox: { toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a) },- communityAttachment: { listByMessageIds: async () => [] },- },- }-})--import { POST } from "./route"--function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/resolve", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--describe("POST /api/community/agent/resolve", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- mockToAgentMessage.mockImplementation((_db: unknown, row: unknown) => Promise.resolve({ ...row as object, wireShaped: true }))- })-- it("401 without Authorization", async () => {- const res = await POST(req({ channel: "/studio/general", seq: 1 }))- expect(res.status).toBe(401)- })-- it("400 on a payload that fails schema validation", async () => {- const res = await POST(req({ channel: "", seq: 1 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- })-- it("404 rejects seq 0 (legacy sentinel) before even resolving the channel", async () => {- const res = await POST(req({ channel: "/studio/general", seq: 0 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(404)- expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()- })-- it("404 propagates the ref-resolution error (channel not found)", async () => {- mockResolveServerByNameForMember.mockResolvedValue([])- const res = await POST(req({ channel: "/studio/general", seq: 3 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(404)- expect(await res.json()).toEqual({ error: "server not found: studio" })- })-- it("403 forbidden when the bot resolves the channel but isn't actually a member", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue(null)- const res = await POST(req({ channel: "/studio/general", seq: 3 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(403)- })-- 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 })- mockGetMessageByChannelAndSeq.mockResolvedValue(null)- const res = await POST(req({ channel: "/studio/general", seq: 99 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(404)- expect((await res.json()).error).toMatch(/no message with seq #99/)- })-- it("200 happy path: resolves the channel ref, fetches by seq, and wire-shapes via toAgentMessage", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 3, content: "hi" })- const res = await POST(req({ channel: "/studio/general", seq: 3 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- const body = await res.json()- expect(body.message).toMatchObject({ id: "m_1", seq: 3, wireShaped: true })- expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "ch_1" }, 3)- })-- it("200 happy path over a DM ref, gated by requireDMAccess", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })- mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>- Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null })- )- // resolveTargetForMember (no createDmIfMissing) needs an existing DM row.- mockGetDMBetween.mockResolvedValue({ id: "dm_1" })- mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "t" })- mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })- mockIsBlocked.mockResolvedValue(false)- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_dm_1", seq: 2, content: "hey" })- const res = await POST(req({ channel: "/.dm/peer#0001", seq: 2 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "dm_1" }, 2)- })-- it("400 invalid DM handle when the channel segment has no #0042 tag", async () => {- const res = await POST(req({ channel: "/.dm/peer_1", seq: 2 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- })-- it("read/resolve-route parity: the reply row's replyToId is threaded into toAgentMessage (guards the getMessageByChannelAndSeq projection)", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })- // getMessageByChannelAndSeq now projects replyToId (see message.ts) — the- // route feeds this row straight into toAgentMessage, which surfaces- // content.replyTo. If replyToId were dropped from the projection this row- // wouldn't carry it (and TS would fail to compile RawAgentMessage).- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 42, content: "yes", replyToId: "m_target" })- const res = await POST(req({ channel: "/studio/general", seq: 42 }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(mockToAgentMessage).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ replyToId: "m_target" }),- "bot_1",- expect.anything()- )- })-})diff --git a/src/web/src/app/api/community/resolve/route.ts b/src/web/src/app/api/community/resolve/route.tsdeleted file mode 100644index a83f55ca7..000000000--- a/src/web/src/app/api/community/resolve/route.ts+++ /dev/null@@ -1,83 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentResolveRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { isDmTarget } from "@/lib/community/message-handler"-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"--/**- * POST /api/community/resolve — moved from /api/community/agent/resolve- * (plan §4 MOVE-FLAT, §9 phase 3). Body `{ channel, seq }` — a REF + seq (kept,- * not id-addressed: Gener #68). Ref-in-body is why this can't fold onto the- * `[id]`-parameterized human message routes (Fork B): the bot holds a ref, the- * CLI has no DB to resolve it into a channelId, so `resolveTargetForMember`- * must run server-side.- *- * Bot-only verb: a human actor is rejected 403 (`requireBot`, Gener #116). The- * handler body is unchanged from the /agent original — only the wrapper- * (withAgentRunnerAuth → withCommunityActor) and the identity source- * (ctx.botUserId → ctx.actor.userId) differ. `seq === 0` is the legacy- * pre-migration sentinel, rejected 404.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate = requireBot(ctx.actor)- if (!gate.ok) return gate.response- const botUserId = gate.bot.userId-- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentResolveRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }- const body = parsed.data-- if (body.seq === 0) {- return NextResponse.json({ error: "seq 0 is not a real message" }, { status: 404 })- }-- const resolved = await resolveTargetForMember(db, botUserId, body.channel, {- createDmIfMissing: false,- createThreadIfMissing: false,- callerKind: "bot",- })- if ("error" in resolved) return resolveErrorResponse(resolved)-- const scopeTarget = { channelId: resolved.channelId }-- if (isDmTarget(resolved)) {- const gate = await requireDMAccess(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- } else {- const gate = await requireChannelMember(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- }-- const row = await queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.seq)- if (!row) {- return NextResponse.json({ error: `no message with seq #${body.seq} in ${body.channel}` }, { status: 404 })- }-- const attachmentRows = await queries.communityAttachment.listByMessageIds(db, [row.id])- const attachments = attachmentRows.map((a) => ({- id: a.id,- filename: a.filename,- contentType: a.contentType,- size: a.size,- }))-- const message = await queries.communityAgentInbox.toAgentMessage(- db,- row,- botUserId,- attachments,- )- return NextResponse.json({ message })-})diff --git a/src/web/src/app/api/community/send/route.test.ts b/src/web/src/app/api/community/send/route.test.tsdeleted file mode 100644index 2fbd0f925..000000000--- a/src/web/src/app/api/community/send/route.test.ts+++ /dev/null@@ -1,466 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.-vi.mock("@/lib/auth", () => ({- createAuth: vi.fn(() => ({- api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },- })),-}))--const mockFindPendingAttachmentsForBot = vi.fn(async () => [] as unknown[])-const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetUserByNameAndDiscriminator = vi.fn()-const mockGetBotBinding = vi.fn()-const mockBumpBotDailyActivityStatement = vi.fn(() => ({ __stmt: "sent-bump" }))-const mockResolveServerByNameForMember = vi.fn()-const mockResolveChannelByNameForMember = vi.fn()-const mockGetChannelForMember = vi.fn()-const mockGetDM = vi.fn()-const mockGetDMBetween = vi.fn()-const mockGetDMPeer = vi.fn()-const mockCreateOrGetDM = vi.fn()-const mockIsBlocked = vi.fn()-const mockAreFriends = vi.fn()-const mockGetLatestSeqForScope = vi.fn()-const mockHasDeliverableUnread = vi.fn()-const mockGetReadState = vi.fn()-const mockToAgentMessage = vi.fn()-const mockGetMessageByChannelAndSeq = vi.fn()--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),- },- communityBot: {- getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a),- // Sentinel — the route builds this into `extraStatements`; the upsert- // SQL itself is verified in the shared community-bot test.- bumpBotDailyActivityStatement: (...a: unknown[]) => mockBumpBotDailyActivityStatement(...a),- },- communityFriendship: {- isBlocked: (...a: unknown[]) => mockIsBlocked(...a),- areFriends: (...a: unknown[]) => mockAreFriends(...a),- },- communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },- communityChannel: {- resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityDm: {- getDM: (...a: unknown[]) => mockGetDM(...a),- getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),- getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),- createOrGetDM: (...a: unknown[]) => mockCreateOrGetDM(...a),- },- communityMessage: {- ...actual.queries.communityMessage, // keep the real scopeKeyForTarget- getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),- },- communityAgentInbox: {- getLatestSeqForScope: (...a: unknown[]) => mockGetLatestSeqForScope(...a),- hasDeliverableUnreadForAgentScope: (...a: unknown[]) => mockHasDeliverableUnread(...a),- toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a),- },- communityReadState: { getReadState: (...a: unknown[]) => mockGetReadState(...a) },- communityAttachment: {- findPendingAttachmentsForBot: (...a: unknown[]) => mockFindPendingAttachmentsForBot(...a),- listByMessageIds: async () => [],- },- },- }-})--const mockCreateCommunityMessage = vi.fn()-vi.mock("@/lib/community/message-handler", async (importOriginal) => ({- ...(await importOriginal<typeof import("@/lib/community/message-handler")>()),- createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),-}))--import { POST } from "./route"--function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/send", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),- })-}--describe("POST /api/community/agent/send", () => {- beforeEach(() => {- vi.clearAllMocks()- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null })- mockGetLatestSeqForScope.mockResolvedValue(0)- // Default aligned (no deliverable unread) — matches the beforeEach- // latest=0. Tests asserting `blocked/unaligned` set this true explicitly;- // the wedge test sets it false while latest>seen to prove the gate no- // longer blocks on undeliverable backlog.- mockHasDeliverableUnread.mockResolvedValue(false)- mockGetReadState.mockResolvedValue(null)- mockToAgentMessage.mockImplementation((_db: unknown, row: unknown) => Promise.resolve({ ...row as object, wireShaped: true }))- mockGetMessageByChannelAndSeq.mockResolvedValue(null)- })-- it("401 without Authorization", async () => {- const res = await POST(req({ channel: "/studio/general", content: { text: "hi" } }))- expect(res.status).toBe(401)- })-- it("400 on a payload that fails schema validation (empty content text)", async () => {- const res = await POST(- req({ channel: "/studio/general", content: { text: "" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(400)- })-- it("404 propagates ref-resolution errors (e.g. channel not found)", async () => {- mockResolveChannelByNameForMember.mockResolvedValue([])- const res = await POST(- req({ channel: "/studio/missing", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(404)- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()- })-- it("returns { state: blocked, reason: unaligned } when the bot is behind the channel's latest seq and hasn't caught up", async () => {- mockGetLatestSeqForScope.mockResolvedValue(10)- mockGetReadState.mockResolvedValue({ lastReadSeq: 4 })- mockHasDeliverableUnread.mockResolvedValue(true)- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ state: "blocked", reason: "unaligned", unreadCount: 6, latestSeq: 10 })- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()- })-- it("late-joiner wedge: latestSeq is ahead of `seen` (pre-join backlog) but NO deliverable unread → send is NOT blocked", async () => {- // The @-mentioned-into-a-thread-with-backlog case. Raw seq gate would- // block forever (latestSeq 20 > seen 0) while inboxPull delivers nothing- // to advance the waterline. Gating on deliverable-unread lets the send- // through — the backlog is behind the join baseline, so it doesn't count.- mockGetLatestSeqForScope.mockResolvedValue(20)- mockGetReadState.mockResolvedValue(null) // fresh member, lastReadSeq → 0- mockHasDeliverableUnread.mockResolvedValue(false)- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 21, content: "hi" } })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- expect((await res.json()).state).toBe("sent")- expect(mockCreateCommunityMessage).toHaveBeenCalled()- })-- it("propagates a CAS 409 conflict from createCommunityMessage as blocked/unaligned with a freshly re-fetched latestSeq", async () => {- // Alignment gate passes (latestSeq=9, seen=9), but another agent's send- // wins the race between the gate and the CAS claim — by the time this- // request's claim runs, the counter has already moved to 10.- mockGetLatestSeqForScope.mockResolvedValueOnce(9).mockResolvedValueOnce(10)- mockGetReadState.mockResolvedValue({ lastReadSeq: 9 })- mockCreateCommunityMessage.mockResolvedValue({ ok: false, status: 409, error: "seq_conflict" })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ state: "blocked", reason: "unaligned", unreadCount: 1, latestSeq: 10 })- expect(mockGetLatestSeqForScope).toHaveBeenCalledTimes(2)- })-- it("happy path: createCommunityMessage is called with expectedSeq equal to the alignment-check's latestSeq (regression guard against drift)", async () => {- mockGetLatestSeqForScope.mockResolvedValue(5)- mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "hi" } })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({ expectedSeq: 5 })- )- })-- it("an explicit seenUpToSeq overrides the bot's own tracked lastReadSeq for the alignment check", async () => {- mockGetLatestSeqForScope.mockResolvedValue(10)- mockGetReadState.mockResolvedValue({ lastReadSeq: 2 }) // would block if used- mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null })- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 10 } })- const res = await POST(- req(- { channel: "/studio/general", content: { text: "hi" }, seenUpToSeq: 10 },- { Authorization: "Bearer crk_abc" }- )- )- expect(res.status).toBe(200)- expect((await res.json()).state).toBe("sent")- })-- it("403 forbidden when resolution succeeds but channel membership gate fails", async () => {- mockGetChannelForMember.mockResolvedValue(null)- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(403)- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()- })-- it("200 { state: sent } happy path for a plain channel send", async () => {- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 1, content: "hi" } })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- const body = await res.json()- expect(body.state).toBe("sent")- expect(body.message).toMatchObject({ id: "m_1", wireShaped: true })- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({- authorId: "bot_1",- target: { kind: "channel", channelId: "ch_1", serverId: "srv_1" },- body: { content: "hi" },- source: "cli",- })- )- })-- it("reconstructs a thread MessageTarget (kind: thread) when the resolved channel has a parentChannelId", async () => {- // A plain channel ref that happens to resolve to a thread's own channel- // row exercises the SAME reconstruction branch as an actual `/#N`- // thread ref, without needing to also mock the root-message/thread-row- // lookups `resolveTargetForMember`'s thread-form parsing would trigger.- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "thread_1" }])- mockGetChannelForMember.mockResolvedValue({ id: "thread_1", serverId: "srv_1", type: "thread", parentChannelId: "ch_parent" })- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 1, content: "hi" } })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({- target: { kind: "thread", channelId: "thread_1", parentChannelId: "ch_parent", serverId: "srv_1" },- })- )- })-- it("propagates createCommunityMessage's own validation error (e.g. content too long) with its status", async () => {- mockCreateCommunityMessage.mockResolvedValue({ ok: false, status: 400, error: "content is required" })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(400)- expect(await res.json()).toEqual({ error: "content is required" })- })-- it("200 happy path for a DM send, auto-creating the DM row via createDmIfMissing", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })- mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>- Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null })- )- mockIsBlocked.mockResolvedValue(false)- mockCreateOrGetDM.mockResolvedValue({ id: "dm_new" })- mockGetDM.mockResolvedValue({ id: "dm_new", lastMessageAt: null, createdAt: "t" })- mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_dm", seq: 1, content: "hey" } })- const res = await POST(- req({ channel: "/.dm/peer#0001", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({ target: { kind: "dm", channelId: "dm_new", otherUserId: "peer_1" } })- )- })-- it("403 blocked propagates from guardDmOpen when trying to auto-create a DM with a blocking peer", async () => {- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })- mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>- Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null })- )- mockIsBlocked.mockResolvedValue(true)- const res = await POST(- req({ channel: "/.dm/peer#0001", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(403)- expect(mockCreateOrGetDM).not.toHaveBeenCalled()- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()- })-- it("400 invalid DM handle when the channel segment has no #0042 tag", async () => {- const res = await POST(- req({ channel: "/.dm/peer_1", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(400)- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()- })-- it("attachment-only DM send: passes attachmentIds through to createCommunityMessage", async () => {- // Regression: user reported {"error":"Unexpected end of JSON input"} when- // running `alook message send --attachment I-... --target /.dm/peer#0001`- // with no `--text`. The CLI sends `content: {text: ""}` + `attachments`.- mockFindPendingAttachmentsForBot.mockResolvedValueOnce([- { id: "I-abc", uploaderId: "bot_1", kind: "dm", targetId: "dm_new" },- ])- mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })- mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>- Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null })- )- mockIsBlocked.mockResolvedValue(false)- mockCreateOrGetDM.mockResolvedValue({ id: "dm_new" })- mockGetDM.mockResolvedValue({ id: "dm_new", lastMessageAt: null, createdAt: "t" })- mockGetDMPeer.mockResolvedValue({ otherUserId: "peer_1" })- mockCreateCommunityMessage.mockResolvedValue({- ok: true,- row: { id: "m_dm", seq: 1, content: "" },- attachments: [{ id: "I-abc", filename: "AGENTS.md", contentType: "text/plain", size: 7990 }],- })- const res = await POST(- req(- { channel: "/.dm/peer#0001", content: { text: "" }, attachments: ["I-abc"] },- { Authorization: "Bearer crk_abc" },- ),- )- expect(res.status).toBe(200)- const body = await res.json()- expect(body.state).toBe("sent")- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({ attachmentIds: ["I-abc"] }),- )- })-- it("sequential scenario: blocked/unaligned → pull+ack (simulated by an advancing lastReadSeq) → send succeeds → a new message arrives → send blocks again", async () => {- // 1. Bot is behind: latestSeq=10, bot's own tracked lastReadSeq=4 → blocked- // (deliverable unread exists).- mockGetLatestSeqForScope.mockResolvedValueOnce(10)- mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 4 })- mockHasDeliverableUnread.mockResolvedValueOnce(true)- const blocked1 = await POST(- req({ channel: "/studio/general", content: { text: "catching up" } }, { Authorization: "Bearer crk_abc" })- )- expect(blocked1.status).toBe(200)- expect(await blocked1.json()).toEqual({ state: "blocked", reason: "unaligned", unreadCount: 6, latestSeq: 10 })- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()-- // 2. The agent pulls the backlog and acks up to seq 10 — modeled here as- // the bot's tracked read state catching up to the channel's latest seq- // (what a real inboxPull+ack round trip against- // /api/community/agent/{inboxPull,ack} would produce).- mockGetLatestSeqForScope.mockResolvedValueOnce(10)- mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 10 })- mockCreateCommunityMessage.mockResolvedValueOnce({ ok: true, row: { id: "m_1", seq: 11, content: "caught up" } })- const sent = await POST(- req({ channel: "/studio/general", content: { text: "caught up" } }, { Authorization: "Bearer crk_abc" })- )- expect(sent.status).toBe(200)- expect((await sent.json()).state).toBe("sent")- expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)-- // 3. A new message (from someone else) lands in the channel, advancing- // latestSeq past the bot's now-stale read state — the next send blocks- // again without a fresh pull+ack.- mockGetLatestSeqForScope.mockResolvedValueOnce(12)- mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 10 })- mockHasDeliverableUnread.mockResolvedValueOnce(true)- const blocked2 = await POST(- req({ channel: "/studio/general", content: { text: "still going" } }, { Authorization: "Bearer crk_abc" })- )- expect(blocked2.status).toBe(200)- expect(await blocked2.json()).toEqual({ state: "blocked", reason: "unaligned", unreadCount: 2, latestSeq: 12 })- // Still only the one successful send from step 2 — this blocked call- // must not have reached createCommunityMessage.- expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)- })-- it("reply/happy path: replyToSeq resolves to an in-scope message id, passed as body.replyToId", async () => {- mockGetLatestSeqForScope.mockResolvedValue(5)- mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })- mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_target", seq: 3 })- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "on it" } })- const res = await POST(- req(- { channel: "/studio/general", content: { text: "on it" }, replyToSeq: 3 },- { Authorization: "Bearer crk_abc" }- )- )- expect(res.status).toBe(200)- expect((await res.json()).state).toBe("sent")- // Resolution is scope-first: the same scopeTarget the send targets.- expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(- expect.anything(),- { channelId: "ch_1" },- 3- )- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({ body: { content: "on it", replyToId: "m_target" } })- )- })-- it("reply/bad seq: replyToSeq with no matching in-scope message → 400, no row inserted", async () => {- mockGetLatestSeqForScope.mockResolvedValue(5)- mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })- mockGetMessageByChannelAndSeq.mockResolvedValue(null)- const res = await POST(- req(- { channel: "/studio/general", content: { text: "on it" }, replyToSeq: 99999 },- { Authorization: "Bearer crk_abc" }- )- )- expect(res.status).toBe(400)- expect(await res.json()).toEqual({ error: "reply target #99999 not found in /studio/general" })- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()- })-- it("reply/no reply: send without replyToSeq → body carries no replyToId (undefined)", async () => {- mockGetLatestSeqForScope.mockResolvedValue(5)- mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "hi" } })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled()- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({ body: { content: "hi", replyToId: undefined } })- )- })-- it("heatmap: a bot send bumps its per-day SENT rollup, folded into the message batch", async () => {- mockGetLatestSeqForScope.mockResolvedValue(5)- mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "hi" } })- const res = await POST(- req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })- )- expect(res.status).toBe(200)- // The "sent" upsert is built for THIS bot + today's UTC day key and handed- // to createCommunityMessage as an extra batch statement — it rides the- // message insert batch (zero new round-trip), not a separate write.- expect(mockBumpBotDailyActivityStatement).toHaveBeenCalledWith(- expect.anything(),- "bot_1",- expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),- "sent",- )- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(- expect.objectContaining({ extraStatements: [{ __stmt: "sent-bump" }] })- )- })-})diff --git a/src/web/src/app/api/community/send/route.ts b/src/web/src/app/api/community/send/route.tsdeleted file mode 100644index 03af6829c..000000000--- a/src/web/src/app/api/community/send/route.ts+++ /dev/null@@ -1,244 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry, CommunityAgentSendRequestSchema, utcDayKey } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"-import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"-import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"-import { createCommunityMessage, isDmTarget, type MessageTarget } from "@/lib/community/message-handler"--/**- * POST /api/community/send — moved from /api/community/agent/send (plan §4- * MOVE-FLAT, §9 phase 3). Ref-addressed bot send: body `{ channel, content,- * attachments, replyToSeq?, seenUpToSeq?, nonce? }` where `channel` is a REF- * (kept, not id — Gener #68). This is why it CANNOT fold onto the human- * `channels/[id]/messages` POST (Fork B): a bot holds a ref, the CLI can't- * resolve it to a channelId, so `resolveTargetForMember` runs server-side (and- * that resolve is also where create-DM/thread-if-missing happens). Humans send- * via the `[id]` route; this flat verb is bot-only → human actor rejected 403- * (`requireBot`, Gener #116). Handler body is unchanged from the /agent- * original except the wrapper + identity source (ctx.botUserId → botUserId).- *- * Single resolve, WITH create flags (`createDmIfMissing`/`createThreadIfMissing:- * true`), rather than a read-only-then-mutating double resolve. Behaviorally- * identical: a DM/thread row can only be auto-created when it has NEVER had a- * message sent to it, so that scope's `community_message_seq` counter is absent- * (`latestSeq === 0`) — it is IMPOSSIBLE for the alignment gate to block a send- * into a target that doesn't exist yet (blocking requires `latestSeq > seen`,- * `seen >= 0` always). So auto-create never fires on a request this gate would- * have blocked — a single resolve is safe and avoids a redundant round trip.- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {- const gate0 = requireBot(ctx.actor)- if (!gate0.ok) return gate0.response- const botUserId = gate0.bot.userId-- const db = getDb(ctx.env.DB)-- let raw: unknown- try {- raw = await req.json()- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })- }- const parsed = CommunityAgentSendRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }- const body = parsed.data-- const resolved = await resolveTargetForMember(db, botUserId, body.channel, {- createDmIfMissing: true,- createThreadIfMissing: true,- callerKind: "bot",- })- if ("error" in resolved) return resolveErrorResponse(resolved)-- const scopeTarget = { channelId: resolved.channelId }-- // Channel-alignment gate (plan §7, debt #2 corrected) — no bypass. The- // server is the source of truth for the "seen" waterline: a client that- // omits `seenUpToSeq` is checked against its OWN tracked `lastReadSeq`,- // never allowed to skip the gate by simply not sending the field.- //- // "Unaligned" means the bot has an unread message it could actually PULL —- // so the gate shares `inboxPull`'s deliverability predicate (join baseline +- // not-own) via `hasDeliverableUnreadForAgentScope`, NOT the raw channel- // `nextSeq`. A late joiner (@mentioned into a channel/thread with backlog)- // has pre-join messages the pull will never deliver; gating on `nextSeq`- // would block it forever while the pull hands over nothing to advance its- // `lastReadSeq` — a permanent wedge. `latestSeq` is still fetched: it feeds- // the optimistic `expectedSeq` claim below and the `blocked` response shape.- // Each D1 call is wrapped in withD1Retry so a transient miniflare/D1 blip- // retries instead of hard-500ing the bot (same armor as bootstrap). The- // alignment DECISION (blocked/unaligned) and the CAS 409 below are- // structured returns, not thrown errors, so they never enter the retry —- // only genuine D1 exceptions do (Cecilia red line: never retry business- // failures).- const [latestSeq, readState] = await Promise.all([- withD1Retry(- () => queries.communityAgentInbox.getLatestSeqForScope(db, resolved.channelId),- { route: "community/send:latest-seq" },- ),- withD1Retry(- () => queries.communityReadState.getReadState(db, { userId: botUserId, ...scopeTarget }),- { route: "community/send:read-state" },- ),- ])- const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0- const hasUnread = await withD1Retry(- () => queries.communityAgentInbox.hasDeliverableUnreadForAgentScope(- db,- botUserId,- resolved.channelId,- seen,- ),- { route: "community/send:has-unread" },- )- if (hasUnread) {- return NextResponse.json({- state: "blocked",- reason: "unaligned",- unreadCount: Math.max(0, latestSeq - seen),- latestSeq,- })- }-- // Permission gate + MessageTarget reconstruction (plan §5 — threads are- // channels for routing, but `createCommunityMessage` needs the full- // 3-variant union to fire `CHILD_CHANNEL_UPDATE` for thread replies).- let target: MessageTarget- if (isDmTarget(resolved)) {- const gate = await requireDMAccess(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- target = { kind: "dm", channelId: resolved.channelId, otherUserId: resolved.otherUserId }- } else {- const gate = await requireChannelMember(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- const channel = gate.value- const bearing = requireMessageBearingSurface(channel.type)- if (!bearing.ok) return NextResponse.json({ error: bearing.error }, { status: bearing.status })- // Only threads have a non-null parentChannelId in this path — the ref- // resolver filters name lookups to top-level (parent_channel_id IS NULL)- // and thread refs (`#N`) create/reuse rows with type="thread". Forum- // posts are not addressable by any agent ref today, so no `forum_post`- // arm is needed here.- target = channel.parentChannelId- ? {- kind: "thread",- channelId: channel.id,- parentChannelId: channel.parentChannelId,- serverId: channel.serverId,- }- : { kind: "channel", channelId: channel.id, serverId: channel.serverId }- }-- // Attachments (plan agent-attachment-pipeline.md §Send). Validate every- // pending id belongs to this bot, kind, and target BEFORE reservation —- // the (uploader_id, kind, target_id) tuple is a single indexed lookup.- // Any mismatch returns the same generic 400, no leakage of which id failed.- const attachmentTargetId = target.channelId- if (body.attachments.length > 0) {- const rows = await withD1Retry(- () => queries.communityAttachment.findPendingAttachmentsForBot(db, {- ids: body.attachments,- uploaderId: botUserId,- targetId: attachmentTargetId,- }),- { route: "community/send:attachments" },- )- if (rows.length !== body.attachments.length) {- return NextResponse.json(- { error: "attachment not found or not attachable to this target" },- { status: 400 },- )- }- }-- // Reply/cite (plan agent-reply-cite.md §Write) — resolve the cited seq to a- // message id WITHIN `scopeTarget` (the same channel/DM this send targets).- // Scope-first: a `replyToSeq` can never cross-cite into another scope. A seq- // with no matching message here (typo, wrong scope, deleted) is a hard 400 —- // nothing is posted.- let replyToId: string | undefined- if (body.replyToSeq !== undefined) {- const replyTarget = await withD1Retry(- () => queries.communityMessage.getMessageByChannelAndSeq(- db,- scopeTarget,- body.replyToSeq!,- ),- { route: "community/send:reply-lookup" },- )- if (!replyTarget) {- return NextResponse.json(- { error: `reply target #${body.replyToSeq} not found in ${body.channel}` },- { status: 400 },- )- }- replyToId = replyTarget.id- }-- // `expectedSeq: latestSeq` reuses the exact snapshot the alignment gate- // above already fetched — no new query. If another agent's `send` wins- // the race between that snapshot and this claim, `createCommunityMessage`- // returns a 409 and we translate it into the SAME `blocked`/`unaligned`- // shape the gate above returns, with a freshly re-fetched `latestSeq` (the- // stale one is now off-by-at-least-one). The daemon's existing "blocked →- // inbox pull → retry" handling needs no changes for this (plan §4).- // NOT wrapped in withD1Retry: createCommunityMessage is a CAS-guarded write- // (`expectedSeq`). Blindly retrying it on a transient could re-attempt a- // partially-applied claim; its own conflict handling returns a structured- // 409 (below) which the daemon already realigns on. Its internal transient- // resilience, if any, belongs inside the handler, not a blanket outer retry.- const result = await createCommunityMessage({- db,- authorId: botUserId,- target,- body: { content: body.content.text, replyToId },- source: "cli",- expectedSeq: latestSeq,- attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,- clientNonce: body.nonce,- // Heatmap: bump this bot's per-day SENT rollup in the SAME batch as the- // message insert (zero new round-trip). Only the bot-send routes pass this,- // so human sends never bump; `createMessage` stays identity-agnostic.- extraStatements: [- queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),- ],- })- if (!result.ok) {- if (result.status === 409) {- const freshLatestSeq = await withD1Retry(- () => queries.communityAgentInbox.getLatestSeqForScope(db, resolved.channelId),- { route: "community/send:fresh-latest-seq" },- )- return NextResponse.json({- state: "blocked",- reason: "unaligned",- unreadCount: Math.max(0, freshLatestSeq - seen),- latestSeq: freshLatestSeq,- })- }- return NextResponse.json({ error: result.error }, { status: result.status })- }-- // `createCommunityMessage` already fetched the reserved attachments via- // listByMessageIds (ordered by `position`, which we stamped 0..N-1 in- // caller order at reservation time). Project directly off `result.attachments`- // instead of re-issuing the same query.- const orderedAttachments = (result.attachments ?? []).map((a) => ({- id: a.id,- filename: a.filename,- contentType: a.contentType,- size: a.size,- }))-- const message = await queries.communityAgentInbox.toAgentMessage(- db,- result.row,- botUserId,- orderedAttachments,- )- return NextResponse.json({ state: "sent", message, deduped: result.deduped })-})diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/route.test.tsindex 2ec16732e..815280e33 100644--- a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts@@ -5,12 +5,13 @@ const mockGetMember = vi.fn()const mockCreateCategory = vi.fn()const mockLogAction = vi.fn()const mockFanOut = vi.fn()+const mockFindMany = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ query: { communityCategory: { findMany: (...a: unknown[]) => mockFindMany(...a) } } })) }))vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -48,10 +49,18 @@ vi.mock("@/lib/middleware/helpers", () => {}})-import { POST } from "./route"+import { GET, POST } from "./route"const ctx = { params: { id: "s1" } } as any+it("GET returns the canonical category rows for a server member", async () => {+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })+ mockFindMany.mockResolvedValue([{ id: "cat1", serverId: "s1", name: "General", position: 0, private: 0 }])+ const res = await GET(new NextRequest("http://localhost/api/community/servers/s1/categories"), ctx)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ categories: [{ id: "cat1", serverId: "s1", name: "General", position: 0, private: 0 }] })+})+function postReq(body: unknown) {return new NextRequest("http://localhost/api/community/servers/s1/categories", {method: "POST",diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.ts b/src/web/src/app/api/community/servers/[id]/categories/route.tsindex 9435821f1..4bfb268d9 100644--- a/src/web/src/app/api/community/servers/[id]/categories/route.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/route.ts@@ -10,7 +10,20 @@ import {} from "@alook/shared"import { fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"-import { requireServerAdmin } from "@/lib/community/permissions"+import { requireServerAdmin, requireServerMember } from "@/lib/community/permissions"++export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const serverId = ctx.params?.id+ if (!serverId) return writeError("missing server id", 400)+ const db = getDb(ctx.env.DB)+ const auth = await requireServerMember(db, serverId, ctx.userId)+ if (!auth.ok) return writeError(auth.error, auth.status)+ const categories = await db.query.communityCategory.findMany({+ where: (t, { eq }) => eq(t.serverId, serverId),+ orderBy: (t, { asc }) => [asc(t.position)],+ })+ return writeJSON({ categories })+})export const POST = withAuth(async (req: NextRequest, ctx) => {const serverId = ctx.params?.iddiff --git a/src/web/src/app/api/community/listChannels/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.tssimilarity index 59%rename from src/web/src/app/api/community/listChannels/route.test.tsrename to src/web/src/app/api/community/servers/[id]/channels/route.bot.test.tsindex 9817adaa0..2395e1476 100644--- a/src/web/src/app/api/community/listChannels/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts@@ -42,17 +42,22 @@ vi.mock("@alook/shared", async () => {}})-import { POST } from "./route"+import { GET } from "./route"-function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/listChannels", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: JSON.stringify(body),- })+// Bot arm of the dual-actor GET servers/[id]/channels (single-server, folds the+// flat `listChannels` verb's `--server` mode). The bot addresses by+// `?server=<ref>`; the `[id]` path segment is the `resolve` placeholder the+// daemon sends. The all-servers mode (bot omits `server`) lives at the+// collection route `servers/channels` (separate test). `listUserServers` is+// mocked here only to assert this single-server route never calls it.+function req(server: string | undefined, headers: Record<string, string> = {}): NextRequest {+ const url = new URL("http://localhost/api/community/servers/resolve/channels")+ if (server !== undefined) url.searchParams.set("server", server)+ return new NextRequest(url, { method: "GET", headers: { ...headers } })}+const ctx = { params: { id: "resolve" } } as unknown as { params: { id: string } }-describe("POST /api/community/agent/listChannels", () => {+describe("GET /api/community/servers/[id]/channels — bot arm (folds listChannels --server)", () => {beforeEach(() => {vi.clearAllMocks()mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })@@ -62,69 +67,36 @@ describe("POST /api/community/agent/listChannels", () => {})it("401 without Authorization", async () => {- const res = await POST(- new NextRequest("http://localhost/api/community/agent/listChannels", { method: "POST", body: "{}" })- )+ const res = await GET(req("studio"), ctx as never)expect(res.status).toBe(401)})- it("400 on a payload that fails schema validation", async () => {- const res = await POST(req({ server: "" }, { Authorization: "Bearer crk_abc" }))+ it("400 when the server query param is missing", async () => {+ const res = await GET(req(undefined, { Authorization: "Bearer crk_abc" }), ctx as never)expect(res.status).toBe(400)- })-- it("empty body defaults to {} — concatenates groups across every server the bot is in", async () => {- mockListUserServers.mockResolvedValue([{ id: "srv_1", name: "studio" }, { id: "srv_2", name: "lounge" }])- mockListChannelsForMember.mockImplementation((_db: unknown, serverId: string) =>- Promise.resolve(- serverId === "srv_1"- ? [{ id: "ch_1", serverId: "srv_1", name: "general", type: "text", categoryId: null }]- : [{ id: "ch_2", serverId: "srv_2", name: "random", type: "text", categoryId: null }]- )- )- const res = await POST(- new NextRequest("http://localhost/api/community/agent/listChannels", {- method: "POST",- headers: { Authorization: "Bearer crk_abc" },- })- )- expect(res.status).toBe(200)- expect(await res.json()).toEqual({- groups: [- {- category: null,- channels: [{ ref: "/studio/general", name: "general", type: "text", visibility: "public" }],- },- {- category: null,- channels: [{ ref: "/lounge/random", name: "random", type: "text", visibility: "public" }],- },- ],- })- expect(mockListUserServers).toHaveBeenCalledTimes(1)expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()})it("--server <id>: resolves server-side and scopes to that one server", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio", discriminator: "0042" }])mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "general", type: "text", categoryId: null }])- const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))+ const res = await GET(req("studio#0042", { Authorization: "Bearer crk_abc" }), ctx as never)expect(res.status).toBe(200)expect(mockListUserServers).not.toHaveBeenCalled()- expect(mockResolveServerByNameForMember).toHaveBeenCalledWith(expect.anything(), "bot_1", "srv_1")+ expect(mockResolveServerByNameForMember).toHaveBeenCalledWith(expect.anything(), "bot_1", "studio#0042")expect(mockListChannelsForMember).toHaveBeenCalledWith(expect.anything(), "srv_1", "bot_1")expect(await res.json()).toEqual({groups: [{category: null,- channels: [{ ref: "/studio/general", name: "general", type: "text", visibility: "public" }],+ channels: [{ ref: "/studio#0042/general", name: "general", type: "text", visibility: "public" }],},],})})it("channels bucketed into their category groups; null-category emitted first; empty groups dropped", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo", discriminator: "0042" }])mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "announcements", type: "text", categoryId: null, position: 0 },{ id: "ch_2", serverId: "srv_1", name: "general", type: "text", categoryId: "cat_ops", position: 1 },@@ -135,40 +107,40 @@ describe("POST /api/community/agent/listChannels", () => {{ id: "cat_founders", name: "Founders", position: 1, private: 1 },{ id: "cat_empty", name: "Empty", position: 2, private: 0 },])- const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))+ const res = await GET(req("studio#0042", { Authorization: "Bearer crk_abc" }), ctx as never)expect(res.status).toBe(200)expect(await res.json()).toEqual({groups: [{category: null,- channels: [{ ref: "/demo/announcements", name: "announcements", type: "text", visibility: "public" }],+ channels: [{ ref: "/demo#0042/announcements", name: "announcements", type: "text", visibility: "public" }],},{category: { name: "Ops", private: false },- channels: [{ ref: "/demo/general", name: "general", type: "text", visibility: "public" }],+ channels: [{ ref: "/demo#0042/general", name: "general", type: "text", visibility: "public" }],},{category: { name: "Founders", private: true },- channels: [{ ref: "/demo/leadership", name: "leadership", type: "text", visibility: "private" }],+ channels: [{ ref: "/demo#0042/leadership", name: "leadership", type: "text", visibility: "private" }],},],})})it("a forum-type channel is reported with type:'forum'; a plain channel with type:'text'", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio", discriminator: "0042" }])mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "general", type: "text", categoryId: null },{ id: "ch_2", serverId: "srv_1", name: "help", type: "forum", categoryId: null },])- const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))+ const res = await GET(req("studio#0042", { Authorization: "Bearer crk_abc" }), ctx as never)expect(await res.json()).toEqual({groups: [{category: null,channels: [- { ref: "/studio/general", name: "general", type: "text", visibility: "public" },- { ref: "/studio/help", name: "help", type: "forum", visibility: "public" },+ { ref: "/studio#0042/general", name: "general", type: "text", visibility: "public" },+ { ref: "/studio#0042/help", name: "help", type: "forum", visibility: "public" },],},],@@ -177,28 +149,15 @@ describe("POST /api/community/agent/listChannels", () => {it("--server matching no server → 404, listChannelsForMember never called", async () => {mockResolveServerByNameForMember.mockResolvedValue([])- const res = await POST(req({ server: "Nope" }, { Authorization: "Bearer crk_abc" }))+ const res = await GET(req("Nope#0042", { Authorization: "Bearer crk_abc" }), ctx as never)expect(res.status).toBe(404)expect(mockListChannelsForMember).not.toHaveBeenCalled()})- it("--server matching 2+ servers → 400 ambiguous, listing candidate ids/names", async () => {- mockResolveServerByNameForMember.mockResolvedValue([- { id: "srv_1", name: "Design Studio" },- { id: "srv_2", name: "Design Studio" },- ])- const res = await POST(req({ server: "Design Studio" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- const body = await res.json()- expect(body.error).toContain("srv_1")- expect(body.error).toContain("srv_2")- expect(mockListChannelsForMember).not.toHaveBeenCalled()- })-it("empty channel list → { groups: [] }, not an error", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio", discriminator: "0042" }])mockListChannelsForMember.mockResolvedValue([])- const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))+ const res = await GET(req("studio#0042", { Authorization: "Bearer crk_abc" }), ctx as never)expect(res.status).toBe(200)expect(await res.json()).toEqual({ groups: [] })})diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.tsnew file mode 100644index 000000000..166011d6e--- /dev/null+++ b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const mockGetMember = vi.fn()+const mockListServerChannelsForViewer = 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,+ communityMember: { getMember: (...args: unknown[]) => mockGetMember(...args) },+ communityChannel: {+ ...actual.queries.communityChannel,+ listServerChannelsForViewer: (...args: unknown[]) => mockListServerChannelsForViewer(...args),+ },+ },+ }+})+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: any, ctx: any) => handler(req, {+ env: { DB: {} },+ actor: { kind: "human", userId: "user_1", email: "[email protected]" },+ params: ctx.params,+ }),+}))++import { GET } from "./route"++describe("GET /api/community/servers/[id]/channels — human resource", () => {+ it("returns only viewer-visible channel rows after one server membership gate", async () => {+ mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })+ mockListServerChannelsForViewer.mockResolvedValue([{ id: "channel_1", serverId: "server_1", name: "general" }])+ const response = await GET(+ new NextRequest("http://localhost/api/community/servers/server_1/channels"),+ { params: { id: "server_1" } } as never,+ )+ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ channels: [{ id: "channel_1", serverId: "server_1", name: "general" }] })+ expect(mockListServerChannelsForViewer).toHaveBeenCalledWith(expect.anything(), "server_1", "user_1")+ })+})diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.test.tsdeleted file mode 100644index 55f743438..000000000--- a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts+++ /dev/null@@ -1,160 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--const mockGetMember = vi.fn()-const mockGetCategory = vi.fn()-const mockCreateChannel = vi.fn()-const mockCreateChannelMember = vi.fn()-const mockFanOutToServerMembers = vi.fn()-const mockFanOutToChannel = vi.fn()-const mockLogAudit = 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: {- communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },- communityCategory: { getCategory: (...a: unknown[]) => mockGetCategory(...a) },- communityChannel: {- createChannel: (...a: unknown[]) => mockCreateChannel(...a),- createChannelMember: (...a: unknown[]) => mockCreateChannelMember(...a),- },- },- }-})--vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),- fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),-}))-vi.mock("@/lib/community/audit", async () => {- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { POST } from "./route"--const ctx = { params: { id: "s1" } } as any-function req(body: unknown) {- return new NextRequest("http://localhost/api/community/servers/s1/channels", {- method: "POST",- body: JSON.stringify(body),- })-}--describe("POST /servers/[id]/channels", () => {- beforeEach(() => {- vi.clearAllMocks()- mockCreateChannel.mockResolvedValue({- id: "c_new", name: "chan", type: "text", categoryId: null, topic: "", position: 0,- createdAt: "2026-07-12T00:00:00Z",- })- })-- it("rejects a plain member creating an uncategorized channel (403, admin-only)", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "member" })- const res = await POST(req({ name: "chan" }), ctx)- expect(res.status).toBe(403)- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("admin can create an uncategorized channel; fans out server-wide", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })- const res = await POST(req({ name: "chan" }), ctx)- expect(res.status).toBe(201)- expect(mockFanOutToServerMembers).toHaveBeenCalled()- expect(mockFanOutToChannel).not.toHaveBeenCalled()- })-- it("coerces an empty-string categoryId to null on a top-level create", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })- const res = await POST(req({ name: "chan", categoryId: "" }), ctx)- expect(res.status).toBe(201)- expect(mockCreateChannel).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ categoryId: null }),- )- })-- it("rejects a plain member creating in a public category (403)", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "member" })- mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", private: 0 })- const res = await POST(req({ name: "chan", categoryId: "cat1" }), ctx)- expect(res.status).toBe(403)- })-- it("member CAN create in a private category; seeds a creator member row + channel-scoped fanout", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "member" })- mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", private: 1 })- const res = await POST(req({ name: "chan", categoryId: "cat1" }), ctx)- expect(res.status).toBe(201)- expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), {- channelId: "c_new",- userId: "u1",- addedBy: "u1",- })- expect(mockFanOutToChannel).toHaveBeenCalled()- expect(mockFanOutToServerMembers).not.toHaveBeenCalled()- })-- it("normalizes a spaced name via slugify before creating the channel", async () => {- // Admin, since an uncategorized channel is admin-only to create.- mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })- const res = await POST(req({ name: "General Chat" }), ctx)- expect(res.status).toBe(201)- expect(mockCreateChannel).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ name: "General-Chat" }),- )- })-- it("returns 400 (and never calls createChannel) when the name is all disallowed characters", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })- const res = await POST(req({ name: "###" }), ctx)- expect(res.status).toBe(400)- expect(mockCreateChannel).not.toHaveBeenCalled()- })-- it("returns 409 when a channel with this name already exists in the server", async () => {- // Uncategorized create is admin-only.- mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })- mockCreateChannel.mockRejectedValue(- Object.assign(new Error("UNIQUE constraint failed: community_channel.server_id, community_channel.name"), {- code: "SQLITE_CONSTRAINT_UNIQUE",- }),- )-- const res = await POST(req({ name: "general" }), ctx)- expect(res.status).toBe(409)- expect(await res.json()).toEqual({ error: "a channel with this name already exists" })- expect(mockFanOutToServerMembers).not.toHaveBeenCalled()- })-- it("rethrows non-uniqueness errors from createChannel", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })- mockCreateChannel.mockRejectedValue(new Error("boom"))- await expect(POST(req({ name: "general" }), ctx)).rejects.toThrow("boom")- })-})diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.tsindex 263848d49..27b29d54e 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts@@ -1,147 +1,51 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { NextResponse, NextRequest } from "next/server"import { getDb } from "@/lib/db"-import {- queries,- canManageServer,- isChannelType,- channelCreation,- MAX_CHANNEL_NAME_LENGTH,- MAX_CHANNEL_TOPIC_LENGTH,- WS_EVENTS,- slugify,- type ChannelType,- type StoredChannelType,-} from "@alook/shared"-import { fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"-import { createWithCollisionPolicy } from "@/lib/community/create-collision"-import { logAudit } from "@/lib/community/audit"+import { parseNameAndTag, queries } from "@alook/shared"+import { withCommunityActor } from "@/lib/middleware/community-actor"+import { buildServerChannelGroups } from "@/lib/community/list-channels"import { requireServerMember } from "@/lib/community/permissions"-export const POST = withAuth(async (req: NextRequest, ctx) => {- const serverId = ctx.params?.id- if (!serverId) return writeError("missing server id", 400)-+/**+ * GET /api/community/servers/[id]/channels — single-server channel list, bot+ * arm of the folded `listChannels` verb (route/disc trunk, 接口树统一 轴3). The+ * bot addresses by `?server=<name#discriminator>`; the all-servers mode+ * (bot omitting `server`) lives at the servers-collection route `GET+ * servers/channels` instead — a cross-server aggregate has no single-`[id]`+ * home. Human web reads the channel tree via the server bootstrap, so this GET+ * is bot-only today; a human actor gets a lean 404 (no human channel-list DTO+ * to project — the human read simply isn't this door).+ *+ * ①-C existence mask: `resolveServerByNameForMember` is member-scoped, so a+ * server the bot isn't in returns zero matches → 404 (indistinguishable from a+ * nonexistent server). `buildServerChannelGroups` runs `listChannelsForMember`+ * so private-category channels the bot can't see never appear.+ */+export const GET = withCommunityActor(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- const member = auth.value!- let body: { name?: string; type?: string; categoryId?: string; topic?: string }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)+ if (ctx.actor.kind === "human") {+ const serverId = ctx.params?.id+ if (!serverId) return NextResponse.json({ error: "missing server id" }, { status: 400 })+ const auth = await requireServerMember(db, serverId, ctx.actor.userId)+ if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status })+ const channels = await queries.communityChannel.listServerChannelsForViewer(db, serverId, ctx.actor.userId)+ return NextResponse.json({ channels })}- if (!body.name || typeof body.name !== "string") {- return writeError("name is required", 400)- }- const trimmed = body.name.trim()- if (!trimmed || trimmed.length > MAX_CHANNEL_NAME_LENGTH) {- return writeError(`name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters`, 400)- }- const name = slugify(trimmed)- if (!name) {- return writeError("name is required", 400)- }- if (body.type !== undefined && !isChannelType(body.type)) {- return writeError("type must be 'text' or 'forum'", 400)- }- if (body.topic !== undefined) {- if (typeof body.topic !== "string") return writeError("topic must be a string", 400)- if (body.topic.length > MAX_CHANNEL_TOPIC_LENGTH) {- return writeError(`topic must be ≤ ${MAX_CHANNEL_TOPIC_LENGTH} characters`, 400)- }- }+ const botUserId = ctx.actor.userId- // Who may create depends on the target location:- // - uncategorized OR public category → admin/owner only- // - private category → any server member (they own the channel + its roster)- const isAdmin = canManageServer(member.role)- let isPrivateCategory = false- if (body.categoryId) {- const category = await queries.communityCategory.getCategory(db, body.categoryId)- if (!category || category.serverId !== serverId) {- return writeError("category not found", 404)- }- isPrivateCategory = !!category.private+ const serverRef = new URL(req.url).searchParams.get("server")+ if (!serverRef) {+ return NextResponse.json({ error: "missing server query param" }, { status: 400 })}- if (!isPrivateCategory && !isAdmin) {- return writeError("admin permission required", 403)+ if (!parseNameAndTag(serverRef)) {+ return NextResponse.json({ error: "invalid server handle, expected name#0042" }, { status: 400 })}- // Collision handling via the shared trait-keyed policy (B4 convergence): a- // top-level channel's creation trait is reject-on-collision — a duplicate name- // (idx_channel_server_name) is REFUSED with 409, never bumped or merged. Same- // createWithCollisionPolicy dispatch that runs forum_post's pure-create- // (bump-retry) and thread's get-or-create (fetch-winner); only the attempt- // callback + the reject message are top-level-specific. Behavior is unchanged- // — still 409 "already exists", still the admin/private gate above; only the- // dispatch mechanism is shared now.- // Effective stored type — validated to text/forum above; undefined defaults to- // "text" (same default createChannel applies). Both top-level types are- // reject-on-collision, so channelCreation resolves the same policy either way.- const effectiveType: StoredChannelType = body.type === "forum" ? "forum" : "text"- const createResult = await createWithCollisionPolicy(channelCreation(effectiveType), {- attempt: () => queries.communityChannel.createChannel(db, {- serverId,- categoryId: body.categoryId || null,- name,- type: body.type,- topic: body.topic,- creatorId: ctx.userId,- }),- onReject: () => ({ status: 409, error: "a channel with this name already exists" }),- })- if (!createResult.ok) return writeError(createResult.error, createResult.status)- const row = createResult.value-- // Private-category channels track an explicit roster; seed the creator so- // audience resolution + the manage-members list are single queries.- if (isPrivateCategory) {- await queries.communityChannel.createChannelMember(db, {- channelId: row.id,- userId: ctx.userId,- addedBy: ctx.userId,- })+ const servers = await queries.communityServer.resolveServerByNameForMember(db, botUserId, serverRef)+ if (servers.length === 0) {+ return NextResponse.json({ error: `server not found: ${serverRef}` }, { status: 404 })}-- const channel = {- id: row.id,- name: row.name,- type: row.type as ChannelType,- categoryId: row.categoryId,- topic: row.topic ?? undefined,- position: row.position ?? 0,- createdAt: row.createdAt,- }-- // A private channel's creation must NOT fan out to the whole server (that- // would leak its existence). Route it through the channel audience (creator- // + admins); public/uncategorized channels stay server-wide.- if (isPrivateCategory) {- await fanOutToChannel(row.id, {- type: WS_EVENTS.CHANNEL_CREATE,- serverId,- channel,- })- } else {- await fanOutToServerMembers(serverId, {- type: WS_EVENTS.CHANNEL_CREATE,- serverId,- channel,- })- }-- logAudit(db, {- serverId,- actorId: ctx.userId,- action: "channel_create",- targetType: "channel",- targetId: channel.id,- })-- return writeJSON({ channel }, 201)+ const groups = await buildServerChannelGroups(db, servers[0]!, botUserId)+ return NextResponse.json({ groups })})diff --git a/src/web/src/app/api/community/servers/[id]/invitable-friends/route.test.ts b/src/web/src/app/api/community/servers/[id]/invitable-friends/route.test.tsdeleted file mode 100644index 11197deb7..000000000--- a/src/web/src/app/api/community/servers/[id]/invitable-friends/route.test.ts+++ /dev/null@@ -1,80 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const listFriends = vi.fn()-const listMemberUserIds = vi.fn()-const getMember = 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: {- communityFriendship: { listFriends: (...a: unknown[]) => listFriends(...a) },- communityMember: {- listMemberUserIds: (...a: unknown[]) => listMemberUserIds(...a),- getMember: (...a: unknown[]) => getMember(...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", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--const ctx = { params: { id: "s1" } } as any-const req = new NextRequest("http://localhost/api/community/servers/s1/invitable-friends")--describe("GET /api/community/servers/[id]/invitable-friends", () => {- beforeEach(() => {- vi.clearAllMocks()- getMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })- listMemberUserIds.mockResolvedValue([])- })-- it("includes statusEmoji/statusText sourced from the joined profile row, same as friends-page.tsx", async () => {- listFriends.mockResolvedValue([- { id: "f1", friendUserId: "u2", friendName: "Gus", friendDiscriminator: "1337", friendImage: null, statusEmoji: "🎮", statusText: "Gaming" },- ])- const res = await GET(req, ctx)- expect(res.status).toBe(200)- const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }- expect(body.friends[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" })- })-- it("defaults statusEmoji/statusText for a friend with no profile row", async () => {- listFriends.mockResolvedValue([- { id: "f2", friendUserId: "u3", friendName: "Lindsay", friendDiscriminator: "0007", friendImage: null, statusEmoji: null, statusText: null },- ])- const res = await GET(req, ctx)- expect(res.status).toBe(200)- const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }- expect(body.friends[0]).toMatchObject({ statusEmoji: null, statusText: "" })- })-- it("still excludes friends who are already members of the server", async () => {- listFriends.mockResolvedValue([- { id: "f1", friendUserId: "u2", friendName: "Gus", friendDiscriminator: "1337", friendImage: null, statusEmoji: null, statusText: null },- ])- listMemberUserIds.mockResolvedValue(["u2"])- const res = await GET(req, ctx)- const body = await res.json() as { friends: unknown[] }- expect(body.friends).toHaveLength(0)- })-})diff --git a/src/web/src/app/api/community/servers/[id]/invitable-friends/route.ts b/src/web/src/app/api/community/servers/[id]/invitable-friends/route.tsdeleted file mode 100644index 3b9374eae..000000000--- a/src/web/src/app/api/community/servers/[id]/invitable-friends/route.ts+++ /dev/null@@ -1,47 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { requireServerMember } from "@/lib/community/permissions"-import { avatarInitial } from "@/lib/community/avatar"--/**- * List the viewer's friends who are NOT already members of this server —- * the invite dialog consumes this so already-joined friends don't clutter- * the picker (or leave the inviter thinking they're "sending" a fresh invite).- *- * Membership must be checked server-side, not on the client: a stale friends- * cache + a stale members cache would race and mis-classify. Here we scope- * one query per side, subtract, and return the survivor set — the caller- * gets the same `Friend`-row shape as /api/community/friends.- */-export const GET = withAuth(async (_req, ctx) => {- const serverId = ctx.params?.id- if (!serverId) return writeError("missing server id", 400)-- const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- const [rawFriends, memberIds] = await Promise.all([- queries.communityFriendship.listFriends(db, ctx.userId),- queries.communityMember.listMemberUserIds(db, serverId),- ])- const memberSet = new Set(memberIds)-- const friends = rawFriends- .filter((f) => !memberSet.has(f.friendUserId))- .map((f) => ({- id: f.id,- userId: f.friendUserId,- name: f.friendName,- discriminator: f.friendDiscriminator,- avatar: f.friendImage ?? avatarInitial(f.friendName),- status: "offline" as const,- sub: "",- statusEmoji: f.statusEmoji ?? null,- statusText: f.statusText ?? "",- }))-- return writeJSON({ friends })-})diff --git a/src/web/src/app/api/community/listMembers/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.bot.test.tssimilarity index 77%rename from src/web/src/app/api/community/listMembers/route.test.tsrename to src/web/src/app/api/community/servers/[id]/members/route.bot.test.tsindex c3dff8599..657a20a08 100644--- a/src/web/src/app/api/community/listMembers/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts@@ -49,17 +49,28 @@ vi.mock("@/lib/community/member-presence", async () => {}})-import { POST } from "./route"+import { GET } from "./route"-function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/listMembers", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: typeof body === "string" ? body : JSON.stringify(body),+// Bot arm of the dual-actor GET servers/[id]/members (folds the flat+// `listMembers` verb). The bot addresses by `?server=<ref>` (+ optional+// `limit`/`cursor`); the `[id]` path segment is the `resolve` placeholder the+// daemon sends. A no-crk_ request falls through to the human withAuth arm+// (401 here via the mocked no-session auth).+function req(+ params: { server?: string; limit?: number; cursor?: string },+ headers: Record<string, string> = {},+): NextRequest {+ const url = new URL("http://localhost/api/community/servers/resolve/members")+ if (params.server !== undefined) url.searchParams.set("server", params.server)+ if (params.limit !== undefined) url.searchParams.set("limit", String(params.limit))+ if (params.cursor !== undefined) url.searchParams.set("cursor", params.cursor)+ return new NextRequest(url, {+ method: "GET",+ headers: { ...headers },})}-describe("POST /api/community/agent/listMembers", () => {+describe("GET /api/community/servers/[id]/members — bot arm (folds listMembers)", () => {beforeEach(() => {vi.clearAllMocks()mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })@@ -69,32 +80,18 @@ describe("POST /api/community/agent/listMembers", () => {})it("401 without Authorization", async () => {- const res = await POST(req({ server: "Design Studio" }))+ const res = await GET(req({ server: "Design Studio#0042" }), { params: { id: "resolve" } } as any)expect(res.status).toBe(401)expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()})it("404 when the server name/id doesn't resolve for this bot", async () => {mockResolveServerByNameForMember.mockResolvedValue([])- const res = await POST(req({ server: "Nope" }, { Authorization: "Bearer crk_abc" }))+ const res = await GET(req({ server: "Nope#0042" }, { Authorization: "Bearer crk_abc" }), { params: { id: "resolve" } } as any)expect(res.status).toBe(404)expect(mockListMembersPaginated).not.toHaveBeenCalled()})- it("400 with candidate server ids/names baked into the error STRING (not a hint field) when ambiguous", async () => {- mockResolveServerByNameForMember.mockResolvedValue([- { id: "srv_1", name: "Design Studio" },- { id: "srv_2", name: "Design Studio" },- ])- const res = await POST(req({ server: "Design Studio" }, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- const body = await res.json()- expect(body.error).toContain("srv_1")- expect(body.error).toContain("srv_2")- expect("hint" in body).toBe(false)- expect(mockListMembersPaginated).not.toHaveBeenCalled()- })-it("200 maps rows to {handle, role, online, status}, defaulting null role to member", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "Design Studio" }])mockListMembersPaginated.mockResolvedValue({@@ -107,7 +104,7 @@ describe("POST /api/community/agent/listMembers", () => {})// u_gus online, u_ally offline — proves the per-page bulk presence stamps each row.mockFetchOnlineUserIds.mockResolvedValue(new Set(["u_gus"]))- const res = await POST(req({ server: "Design Studio" }, { Authorization: "Bearer crk_abc" }))+ const res = await GET(req({ server: "Design Studio#0042" }, { Authorization: "Bearer crk_abc" }), { params: { id: "resolve" } } as any)expect(res.status).toBe(200)expect(await res.json()).toEqual({members: [@@ -127,8 +124,9 @@ describe("POST /api/community/agent/listMembers", () => {hasMore: true,cursor: { joinedAt: "2026-03-01T00:00:00Z", id: "sm_9" },})- const res = await POST(- req({ server: "srv_1", limit: 1, cursor: "2026-02-01T00:00:00Z|sm_5" }, { Authorization: "Bearer crk_abc" }),+ const res = await GET(+ req({ server: "Design Studio#0042", limit: 1, cursor: "2026-02-01T00:00:00Z|sm_5" }, { Authorization: "Bearer crk_abc" }),+ { params: { id: "resolve" } } as any,)expect(res.status).toBe(200)// limit passed through; cursor string parsed into {joinedAt, id}.diff --git a/src/web/src/app/api/community/servers/[id]/members/route.ts b/src/web/src/app/api/community/servers/[id]/members/route.tsindex 5f7847059..2258cbfc5 100644--- a/src/web/src/app/api/community/servers/[id]/members/route.ts+++ b/src/web/src/app/api/community/servers/[id]/members/route.ts@@ -1,21 +1,102 @@-import { withAuth } from "@/lib/middleware/auth"+import { NextResponse, type NextRequest } from "next/server"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import {queries,+ formatHandle,+ parseNameAndTag,DEFAULT_MEMBERS_PAGE_SIZE,MAX_MEMBERS_PAGE_SIZE,} from "@alook/shared"+import { withCommunityActor } from "@/lib/middleware/community-actor"import { requireServerMember } from "@/lib/community/permissions"import { parseBoundedInt, parseMemberCursor, buildMemberPaginatedResponse } from "@/lib/community/messages"import { mapMemberForApi } from "@/lib/community/member-payload"+import { fetchOnlineUserIds, toMemberStatus } from "@/lib/community/member-presence"-export const GET = withAuth(async (req, ctx) => {- const serverId = ctx.params?.id+/**+ * GET /api/community/servers/[id]/members — dual-actor server-member list+ * (route/disc trunk, 接口树统一 轴3). Folds the flat bot `listMembers` verb into+ * this canonical server-scoped collection: human addresses by `[id]` path, bot+ * addresses by `?server=<ref>` (id OR display name), both converge on one+ * serverId and one member read. Type/caller is data, not a separate route.+ *+ * Two projections off actor.kind (Fork-C): human = full UI DTO (paginated,+ * owner-scoped isBot/ownerUserId via `mapMemberForApi` botGating) ; bot = lean+ * `{handle, role, online, status}` (no internal ids), also PAGINATED (stable+ * keyset cursor, `hasMore`/`cursor` on the wire) — the roster is a whole-server+ * audience and potentially unbounded, unlike a channel/thread roster.+ *+ * ①-C existence mask: the bot's `resolveServerByNameForMember` is member-scoped,+ * so a server the bot isn't in returns zero matches → 404 "server not found"+ * (indistinguishable from a truly nonexistent server — no existence leak). The+ * human arm keeps `requireServerMember`'s own 403/404.+ */+export const GET = withCommunityActor(async (req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)++ if (ctx.actor.kind === "bot") {+ return handleBotList(req, ctx.env, db, ctx.actor.userId)+ }+ return handleHumanList(req, db, ctx.actor.userId, ctx.params?.id)+})++async function handleBotList(+ req: NextRequest,+ env: Env,+ db: ReturnType<typeof getDb>,+ botUserId: string,+): Promise<NextResponse> {+ const url = new URL(req.url)+ const serverRef = url.searchParams.get("server")+ if (!serverRef) {+ return NextResponse.json({ error: "missing server query param" }, { status: 400 })+ }+ if (!parseNameAndTag(serverRef)) {+ return NextResponse.json({ error: "invalid server handle, expected name#0042" }, { status: 400 })+ }++ const servers = await queries.communityServer.resolveServerByNameForMember(db, botUserId, serverRef)+ if (servers.length === 0) {+ return NextResponse.json({ error: `server not found: ${serverRef}` }, { status: 404 })+ }+ const serverId = servers[0]!.id++ // Forward-paginated roster (opaque `joinedAt|id` cursor) — same as the human+ // arm; the server roster is potentially unbounded so unlike a channel/thread+ // roster it must page.+ const limit = parseBoundedInt(+ url.searchParams.get("limit"),+ DEFAULT_MEMBERS_PAGE_SIZE,+ MAX_MEMBERS_PAGE_SIZE,+ )+ const cursor = parseMemberCursor(url.searchParams.get("cursor"))+ const page = await queries.communityMember.listMembersPaginated(db, serverId, { cursor, limit })++ // Bulk presence for THIS page's user ids only (bounded) — never per-member.+ const onlineSet = await fetchOnlineUserIds(env, page.members.map((r) => r.userId), serverId)++ const members = page.members.map((r) => ({+ handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),+ role: r.role ?? "member",+ online: onlineSet.has(r.userId),+ status: toMemberStatus(r),+ }))++ const cursorOut = page.cursor ? `${page.cursor.joinedAt}|${page.cursor.id}` : undefined++ return NextResponse.json({ members, hasMore: page.hasMore, cursor: cursorOut })+}++async function handleHumanList(+ req: NextRequest,+ db: ReturnType<typeof getDb>,+ userId: string,+ serverId: string | undefined,+): Promise<NextResponse> {if (!serverId) return writeError("missing server id", 400)- const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)+ const auth = await requireServerMember(db, serverId, userId)if (!auth.ok) return writeError(auth.error, auth.status)const url = new URL(req.url)@@ -44,8 +125,8 @@ export const GET = withAuth(async (req, ctx) => {// own; other bots appear as normal humans. This is the load-bearing// pass-as-human projection at the member-list layer.const members = envelope.members.map((r) =>- mapMemberForApi(r, ctx.userId, { botGating: true }),+ mapMemberForApi(r, userId, { botGating: true }),)return writeJSON({ members, hasMore: envelope.hasMore, cursor: envelope.cursor, limit, total })-})+}diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.tsindex 66ff0995e..adacb9d01 100644--- a/src/web/src/app/api/community/servers/[id]/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts@@ -5,20 +5,13 @@ const mockGetMember = vi.fn()const mockUpdateServer = vi.fn()const mockLogAction = vi.fn()const mockFanOut = vi.fn()-const mockGetServer = vi.fn()-const mockListServerChannels = vi.fn()-const mockListUnreadChannels = vi.fn()-const mockListVisibleChannelIds = vi.fn()-const mockFindManyCategories = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),}))vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({- query: { communityCategory: { findMany: (...a: unknown[]) => mockFindManyCategories(...a) } },- })),+ getDb: vi.fn(() => ({})),}))vi.mock("@alook/shared", async () => {@@ -28,16 +21,8 @@ vi.mock("@alook/shared", async () => {queries: {communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },communityServer: {- getServer: (...a: unknown[]) => mockGetServer(...a),updateServer: (...a: unknown[]) => mockUpdateServer(...a),},- communityChannel: {- listServerChannelsForViewer: (...a: unknown[]) => mockListServerChannels(...a),- listVisibleChannelIdsForUser: (...a: unknown[]) => mockListVisibleChannelIds(...a),- },- communityInbox: {- listUnreadChannels: (...a: unknown[]) => mockListUnreadChannels(...a),- },communityAuditLog: {logAction: (...a: unknown[]) => mockLogAction(...a),},@@ -65,7 +50,7 @@ vi.mock("@/lib/middleware/helpers", () => {}})-import { GET, PATCH } from "./route"+import { PATCH } from "./route"const ctx = { params: { id: "s1" } } as any@@ -107,116 +92,3 @@ describe("PATCH /api/community/servers/[id]", () => {expect(mockUpdateServer).not.toHaveBeenCalled()})})--// ── GET — channel unread projection ──────────────────────────────────────-describe("GET /api/community/servers/[id]", () => {- const getReq = () => new NextRequest("http://localhost/api/community/servers/s1")-- beforeEach(() => {- vi.clearAllMocks()- mockListVisibleChannelIds.mockResolvedValue([])- mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })- mockGetServer.mockResolvedValue({- id: "s1",- name: "Server",- description: "",- icon: null,- ownerId: "u_owner",- })- mockFindManyCategories.mockResolvedValue([- { id: "cat_A", serverId: "s1", name: "Category A", position: 0, private: 0 },- ])- })-- it("a channel with lastMessageAt > lastReadAt (has read-state row) is returned with unread: true", async () => {- mockListServerChannels.mockResolvedValue([- { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },- ])- mockListUnreadChannels.mockResolvedValue([- { channelId: "ch_1", channelName: "general", serverId: "s1", serverName: "Server", lastMessageAt: "t2", lastReadAt: "t1" },- ])-- const res = await GET(getReq(), ctx)- const body = await res.json()- expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: true })- })-- it("a channel the viewer has already read is returned with unread: false", async () => {- mockListServerChannels.mockResolvedValue([- { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },- ])- mockListUnreadChannels.mockResolvedValue([])-- const res = await GET(getReq(), ctx)- const body = await res.json()- expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })- })-- it("a channel unread since before the viewer's read-state existed (no read-state row, lastMessageAt > joinedAt) is returned with unread: true", async () => {- // listUnreadChannels already applies isChannelUnread — the route just- // trusts its output, so a row present in the unread list (regardless of- // lastReadAt being null) must project unread: true.- mockListServerChannels.mockResolvedValue([- { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },- ])- mockListUnreadChannels.mockResolvedValue([- { channelId: "ch_1", channelName: "general", serverId: "s1", serverName: "Server", lastMessageAt: "t2", lastReadAt: null },- ])-- const res = await GET(getReq(), ctx)- const body = await res.json()- expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: true })- })-- it("a channel with historical messages predating membership is returned with unread: false (no false-positive on first join)", async () => {- mockListServerChannels.mockResolvedValue([- { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },- ])- // isChannelUnread already excluded this row upstream — listUnreadChannels- // never returns it.- mockListUnreadChannels.mockResolvedValue([])-- const res = await GET(getReq(), ctx)- const body = await res.json()- expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })- })-- it("an unread channel belonging to a different server is not counted — scoped correctly by serverId", async () => {- mockListServerChannels.mockResolvedValue([- { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },- ])- mockListUnreadChannels.mockResolvedValue([- { channelId: "ch_other", channelName: "other", serverId: "s2", serverName: "Other", lastMessageAt: "t2", lastReadAt: null },- ])-- const res = await GET(getReq(), ctx)- const body = await res.json()- expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })- })-- it("projects unread onto both categorized channels and the synthetic __uncategorized__ bucket", async () => {- mockListServerChannels.mockResolvedValue([- { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },- { id: "ch_2", serverId: "s1", categoryId: null, name: "loose", tags: [] },- ])- mockListUnreadChannels.mockResolvedValue([- { channelId: "ch_2", channelName: "loose", serverId: "s1", serverName: "Server", lastMessageAt: "t2", lastReadAt: null },- ])-- const res = await GET(getReq(), ctx)- const body = await res.json()- const uncategorized = body.categories.find((c: { id: string }) => c.id === "__uncategorized__")- expect(uncategorized.channels[0]).toMatchObject({ id: "ch_2", unread: true })- expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })- })-- it("returns 403 when the caller is not a member", async () => {- mockGetMember.mockResolvedValue(null)- mockListServerChannels.mockResolvedValue([])- mockListUnreadChannels.mockResolvedValue([])-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(403)- expect(mockGetServer).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.tsindex aecea3a03..11b7d9679 100644--- a/src/web/src/app/api/community/servers/[id]/route.ts+++ b/src/web/src/app/api/community/servers/[id]/route.ts@@ -7,80 +7,12 @@ import {isServerOwner,MAX_SERVER_NAME_LENGTH,MAX_SERVER_DESCRIPTION_LENGTH,- UNCATEGORIZED_CATEGORY_ID,WS_EVENTS,slugify,- withD1Retry,} from "@alook/shared"import { fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"-import { requireServerAdmin, requireServerMember } from "@/lib/community/permissions"-import { serverIconUrl } from "@/lib/community/storage"--export const GET = withAuth(async (_req, ctx) => {- const serverId = ctx.params?.id- if (!serverId) return writeError("missing server id", 400)-- const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- const [server, rawChannels, categories, unreadRows] = await withD1Retry(async () => {- const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)- return Promise.all([- queries.communityServer.getServer(db, serverId),- // Viewer-scoped: private-category channels are only returned if the viewer- // is the channel creator or an added member (admins get NO special- // visibility). Private category HEADERS still appear (below) so members can- // create channels in them.- queries.communityChannel.listServerChannelsForViewer(db, serverId, ctx.userId),- db.query.communityCategory.findMany({- where: (t, { eq }) => eq(t.serverId, serverId),- orderBy: (t, { asc }) => [asc(t.position)],- }),- queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds),- ])- }, { route: "community/servers/detail" })-- if (!server) return writeError("server not found", 404)-- // Project the viewer's per-channel unread state onto the shared `channels`- // array once, before splitting into categorized/uncategorized — so both- // branches inherit `unread` from the same source instead of two separate- // maps. `listUnreadChannels` scans all of the viewer's servers; scope it- // down to this one via the Set.- const unreadIds = new Set(- unreadRows.filter((r) => r.serverId === serverId).map((r) => r.channelId),- )- const channels = rawChannels.map((ch) => ({ ...ch, unread: unreadIds.has(ch.id) }))-- const categoriesWithChannels = categories.map((c) => ({- ...c,- channels: channels.filter((ch) => ch.categoryId === c.id),- }))- const uncategorized = channels.filter((ch) => !ch.categoryId)- if (uncategorized.length > 0) {- categoriesWithChannels.push({- id: UNCATEGORIZED_CATEGORY_ID,- serverId: server.id,- // Empty name is load-bearing: the sidebar detects the uncategorized- // bucket by `name === ""` (renders its channels as the bare top list, and- // maps a drag INTO it back to `categoryId: null`).- name: "",- position: -1,- private: 0,- channels: uncategorized,- } as (typeof categoriesWithChannels)[number])- }- return writeJSON({- id: server.id,- name: server.name,- description: server.description ?? "",- icon: serverIconUrl(server),- ownerId: server.ownerId,- categories: categoriesWithChannels,- })-})+import { requireServerAdmin } from "@/lib/community/permissions"export const PATCH = withAuth(async (req: NextRequest, ctx) => {const serverId = ctx.params?.iddiff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.test.tsnew file mode 100644index 000000000..7b93ed8af--- /dev/null+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts@@ -0,0 +1,92 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const mockGetMember = vi.fn()+const mockListVisibleChannelIds = vi.fn()+const mockListUnreadChannels = 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,+ communityMember: { getMember: (...args: unknown[]) => mockGetMember(...args) },+ communityChannel: {+ ...actual.queries.communityChannel,+ listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),+ },+ communityInbox: {+ ...actual.queries.communityInbox,+ listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),+ },+ },+ }+})+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any, ctx: any) => handler(req, {+ env: { DB: {} },+ userId: "user_1",+ params: ctx.params,+ }),+}))++import { GET } from "./route"++describe("GET /api/community/servers/[id]/unreads", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })+ mockListVisibleChannelIds.mockResolvedValue(["channel_1", "channel_2", "other_1"])+ mockListUnreadChannels.mockResolvedValue([+ { serverId: "server_1", channelId: "channel_1" },+ { serverId: "server_1", channelId: "channel_2" },+ { serverId: "server_2", channelId: "other_1" },+ ])+ })++ it("returns the complete viewer-visible unread id set scoped to the server", async () => {+ const response = await GET(+ new NextRequest("http://localhost/api/community/servers/server_1/unreads"),+ { params: { id: "server_1" } } as never,+ )++ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ channelIds: ["channel_1", "channel_2"], stale: false })+ expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["channel_1", "channel_2", "other_1"])+ })++ it("does not consult notification settings, so server/channel mute cannot hide read-state", async () => {+ const response = await GET(+ new NextRequest("http://localhost/api/community/servers/server_1/unreads"),+ { params: { id: "server_1" } } as never,+ )++ expect(await response.json()).toMatchObject({ channelIds: ["channel_1", "channel_2"] })+ expect(mockListUnreadChannels).toHaveBeenCalledOnce()+ })++ it("fails closed when the viewer is not a server member", async () => {+ mockGetMember.mockResolvedValue(null)+ const response = await GET(+ new NextRequest("http://localhost/api/community/servers/server_1/unreads"),+ { params: { id: "server_1" } } as never,+ )++ expect(response.status).toBe(403)+ expect(mockListVisibleChannelIds).not.toHaveBeenCalled()+ expect(mockListUnreadChannels).not.toHaveBeenCalled()+ })++ it("marks retry-exhausted reads stale instead of caching an empty read set", async () => {+ mockListVisibleChannelIds.mockRejectedValue(new Error("D1_ERROR: database is locked"))+ const response = await GET(+ new NextRequest("http://localhost/api/community/servers/server_1/unreads"),+ { params: { id: "server_1" } } as never,+ )++ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ channelIds: [], stale: true })+ })+})diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.tsnew file mode 100644index 000000000..9fbcd8b41--- /dev/null+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.ts@@ -0,0 +1,31 @@+import { NextResponse } from "next/server"+import { queries, readOrStale } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withAuth } from "@/lib/middleware/auth"+import { requireServerMember } from "@/lib/community/permissions"++/**+ * Raw read-state projection for one server. Unlike the inbox notification+ * feed, this resource deliberately does not apply notification preferences:+ * muting a server/channel must not turn its sidebar read-state badge off.+ */+export const GET = withAuth(async (_req, ctx) => {+ const serverId = ctx.params?.id+ if (!serverId) return NextResponse.json({ error: "missing server id" }, { status: 400 })++ const db = getDb(ctx.env.DB)+ const auth = await requireServerMember(db, serverId, ctx.userId)+ if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status })++ const { value, stale } = await readOrStale(+ async () => {+ const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)+ const unread = await queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds)+ return { channelIds: unread.filter((row) => row.serverId === serverId).map((row) => row.channelId) }+ },+ { channelIds: [] as string[] },+ { route: "community/servers/:id/unreads" },+ )++ return NextResponse.json({ channelIds: value.channelIds, stale })+})diff --git a/src/web/src/app/api/community/servers/channels/route.bot.test.ts b/src/web/src/app/api/community/servers/channels/route.bot.test.tsnew file mode 100644index 000000000..8dcccc7e0--- /dev/null+++ b/src/web/src/app/api/community/servers/channels/route.bot.test.ts@@ -0,0 +1,101 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+// Unified actor: a request with no `crk_` bearer falls through to the human+// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request+// yields the human-path 401 — but this route's human arm returns a lean 404+// (no all-servers human DTO), so the no-crk_ case here lands on that.+vi.mock("@/lib/auth", () => ({+ createAuth: vi.fn(() => ({+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },+ })),+}))++const mockFindActiveAgentRunnerKeyByBearer = vi.fn()+const mockGetUserInternal = vi.fn()+const mockGetBotBinding = vi.fn()+const mockListUserServers = vi.fn()+const mockListChannelsForMember = vi.fn()+const mockListCategoriesByServer = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },+ user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityServer: { listUserServers: (...a: unknown[]) => mockListUserServers(...a) },+ communityChannel: { listChannelsForMember: (...a: unknown[]) => mockListChannelsForMember(...a) },+ communityCategory: { listCategoriesByServer: (...a: unknown[]) => mockListCategoriesByServer(...a) },+ },+ }+})++import { GET } from "./route"++function req(headers: Record<string, string> = {}): NextRequest {+ return new NextRequest("http://localhost/api/community/servers/channels", {+ method: "GET",+ headers: { ...headers },+ })+}++// The all-servers channel list: GET servers/channels (collection level). Folds+// the flat `listChannels` verb's no-`--server` mode — fan out across every+// server the bot is in, concatenate groups in listUserServers order.+describe("GET /api/community/servers/channels — bot arm (folds listChannels all-servers)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })+ mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ mockListCategoriesByServer.mockResolvedValue([])+ })++ it("401 without Authorization (falls to human arm, no session)", async () => {+ const res = await GET(req())+ expect(res.status).toBe(401)+ expect(mockListUserServers).not.toHaveBeenCalled()+ })++ it("concatenates groups across every server the bot is in", async () => {+ mockListUserServers.mockResolvedValue([{ id: "srv_1", name: "studio", discriminator: "0042" }, { id: "srv_2", name: "lounge", discriminator: "0042" }])+ mockListChannelsForMember.mockImplementation((_db: unknown, serverId: string) =>+ Promise.resolve(+ serverId === "srv_1"+ ? [{ id: "ch_1", serverId: "srv_1", name: "general", type: "text", categoryId: null }]+ : [{ id: "ch_2", serverId: "srv_2", name: "random", type: "text", categoryId: null }]+ )+ )+ const res = await GET(req({ Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({+ groups: [+ {+ category: null,+ channels: [{ ref: "/studio#0042/general", name: "general", type: "text", visibility: "public" }],+ },+ {+ category: null,+ channels: [{ ref: "/lounge#0042/random", name: "random", type: "text", visibility: "public" }],+ },+ ],+ })+ expect(mockListUserServers).toHaveBeenCalledTimes(1)+ })++ it("bot in zero servers → { groups: [] }", async () => {+ mockListUserServers.mockResolvedValue([])+ const res = await GET(req({ Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ groups: [] })+ expect(mockListChannelsForMember).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/servers/channels/route.ts b/src/web/src/app/api/community/servers/channels/route.tsnew file mode 100644index 000000000..bff2c6072--- /dev/null+++ b/src/web/src/app/api/community/servers/channels/route.ts@@ -0,0 +1,41 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries } from "@alook/shared"+import type { CommunityCliChannelGroup as ChannelGroup } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor } from "@/lib/middleware/community-actor"+import { buildServerChannelGroups } from "@/lib/community/list-channels"++/**+ * GET /api/community/servers/channels — all-servers channel list, the+ * servers-COLLECTION-level read (Gener #392). This is the bot's `channel list`+ * with no `--server`: fan out across every server the bot is in and return one+ * flat `ChannelGroup[]` (grouped-by-category per server, in `listUserServers`+ * order). A cross-server aggregate has no single-`[id]` home, so it lives at the+ * collection level — NOT a floating top-level operation-named route (Melly+ * #393: 能嵌就嵌到底). The single-server read is the sibling `servers/[id]/channels`+ * GET.+ *+ * Bot-only (no human all-servers channel DTO — the web reads per-server via the+ * bootstrap tree). Human actor → lean 404. Per-server visibility comes from+ * `listChannelsForMember` inside `buildServerChannelGroups`, so private channels+ * the bot can't see never appear; there is no server the bot isn't a member of+ * in `listUserServers`, so no existence mask is needed here.+ */+export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {+ if (ctx.actor.kind !== "bot") {+ return NextResponse.json({ error: "not found" }, { status: 404 })+ }+ const botUserId = ctx.actor.userId+ const db = getDb(ctx.env.DB)++ const servers = await queries.communityServer.listUserServers(db, botUserId)++ // Fan out per-server DB work in parallel — for a bot in N servers this stays+ // flat instead of paying N× the RTT a sequential per-server loop would.+ const perServer = await Promise.all(+ servers.map((server) => buildServerChannelGroups(db, server, botUserId)),+ )++ const groups: ChannelGroup[] = perServer.flat()+ return NextResponse.json({ groups })+})diff --git a/src/web/src/app/api/community/servers/route.bot.test.ts b/src/web/src/app/api/community/servers/route.bot.test.tsindex 331748a92..521d0e002 100644--- a/src/web/src/app/api/community/servers/route.bot.test.ts+++ b/src/web/src/app/api/community/servers/route.bot.test.ts@@ -5,7 +5,7 @@ import { NextRequest } from "next/server"// GET /servers, plan §4/§9 phase 4-5). A `crk_` bearer drives// withCommunityActor's bot path; GET lists via listUserServers(actor.userId).// The route returns the SUPERSET (full rows + icon) — the daemon/CLI projects-// each row down to the lean {id,name} shape (Fork C). That daemon-side lean+// each row down to the lean {handle} shape. That daemon-side lean// projection is asserted by the daemon projection test, NOT here; here we lock// the ROUTE contract: bot auth works, scoping is by the bot's own membership,// and the full rows (incl. id+name) are returned.diff --git a/src/web/src/app/api/community/threads/[id]/messages/route.test.ts b/src/web/src/app/api/community/threads/[id]/messages/route.test.tsdeleted file mode 100644index 9144b8793..000000000--- a/src/web/src/app/api/community/threads/[id]/messages/route.test.ts+++ /dev/null@@ -1,125 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--const mockGetChannelForMember = vi.fn()-const mockGetMessagesByIdsInScope = vi.fn()-const mockListMessages = vi.fn()-const mockListByMessageIds = vi.fn()-const mockListReactionsByMessageIds = 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: {- communityChannel: {- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityMessage: {- getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),- listMessages: (...a: unknown[]) => mockListMessages(...a),- },- communityAttachment: {- listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),- },- communityReaction: {- listReactionsByMessageIds: (...a: unknown[]) => mockListReactionsByMessageIds(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--function getReq() {- return new NextRequest("http://localhost/api/community/threads/t1/messages", {- method: "GET",- })-}--const ctx = { params: { id: "t1" } } as any--describe("GET /api/community/threads/[id]/messages", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetChannelForMember.mockResolvedValue({- id: "t1",- serverId: "s1",- parentChannelId: "c-parent",- })- mockListByMessageIds.mockResolvedValue([])- mockListReactionsByMessageIds.mockResolvedValue([])- mockGetMessagesByIdsInScope.mockResolvedValue([])- })-- it("runs attachment, reaction, and reply-target fetches in parallel", async () => {- // The 3 follow-up fetches have no cross-dependency; they must run- // concurrently (Promise.all), not sequentially. Prove it by observing- // in-flight count — all 3 must be dispatched before any resolves.- mockListMessages.mockResolvedValue([- { id: "m-1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hi", type: "default", mentionType: null, replyToId: "r-1", channelId: "t1", embeds: null, createdAt: "t1" },- ])-- let inFlight = 0- let maxInFlight = 0- async function tracked<T>(value: T): Promise<T> {- inFlight++- maxInFlight = Math.max(maxInFlight, inFlight)- await new Promise((r) => setTimeout(r, 15))- inFlight--- return value- }- mockListByMessageIds.mockImplementation(() => tracked([]))- mockListReactionsByMessageIds.mockImplementation(() => tracked([]))- mockGetMessagesByIdsInScope.mockImplementation(() => tracked([]))-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)-- expect(maxInFlight).toBe(3)- expect(mockListByMessageIds).toHaveBeenCalledTimes(1)- expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)- expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)- })-- it("preserves response shape: reply preview scoped to this channel", async () => {- // Response shape sanity: reply target in-scope resolves; out-of-scope is- // filtered and marked deleted. Same contract as the pre-Promise.all code.- mockListMessages.mockResolvedValue([- { id: "m-a", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hi", type: "default", mentionType: null, replyToId: "r-in-scope", channelId: "t1", embeds: null, createdAt: "t1" },- { id: "m-b", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "leak?", type: "default", mentionType: null, replyToId: "r-out-of-scope", channelId: "t1", embeds: null, createdAt: "t2" },- ])- mockGetMessagesByIdsInScope.mockResolvedValue([- { id: "r-in-scope", authorName: "Zed", content: "original", channelId: "t1", dmConversationId: null },- ])-- const res = await GET(getReq(), ctx)- expect(res.status).toBe(200)- const body = await res.json() as { messages: Array<{ id: string; replyTo?: { id: string; authorName: string; text: string; deleted?: boolean } }> }- const byId = new Map(body.messages.map((m) => [m.id, m]))-- expect(byId.get("m-a")?.replyTo).toEqual({ id: "r-in-scope", authorName: "Zed", text: "original" })- expect(byId.get("m-b")?.replyTo).toEqual({ id: "r-out-of-scope", authorName: "Unknown", text: "", deleted: true })- })-})diff --git a/src/web/src/app/api/community/threads/[id]/messages/route.ts b/src/web/src/app/api/community/threads/[id]/messages/route.tsdeleted file mode 100644index dff4834c1..000000000--- a/src/web/src/app/api/community/threads/[id]/messages/route.ts+++ /dev/null@@ -1,61 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { parseCursor, parsePageSize, buildPaginatedResponse, groupAttachments, groupReactions } from "@/lib/community/messages"-import { requireChannelMember } from "@/lib/community/permissions"-import { mapMessageForApi } from "@/lib/community/message-payload"--export const GET = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)-- const db = getDb(ctx.env.DB)-- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- const cursor = parseCursor(req.nextUrl.searchParams.get("cursor"))- const pageSize = parsePageSize(req.nextUrl.searchParams.get("limit"))-- const rows = await queries.communityMessage.listMessages(db, {- channelId,- cursor,- limit: pageSize + 1,- })-- const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)-- // All three follow-up fetches depend only on `items` — no cross-dependency —- // so run them concurrently to collapse 3 sequential D1 round-trips into one- // wall-clock hop.- const messageIds = items.map((m) => m.id)- const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]-- const [allAttachments, allReactions, replyMessages] = await Promise.all([- messageIds.length > 0- ? queries.communityAttachment.listByMessageIds(db, messageIds)- : Promise.resolve([]),- messageIds.length > 0- ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, ctx.userId)- : Promise.resolve([]),- replyToIds.length > 0- ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId })- : Promise.resolve([]),- ])-- const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, ctx.userId)-- // Reply targets are already scoped to this channel by the query above — a- // caller can't leak previews of messages from other channels/DMs just by- // referencing their id.- const replyMap = new Map(replyMessages.map((m) => [m.id, m]))-- const messages = items.map((r) =>- mapMessageForApi(r, { replyMap, attachmentsByMessage, reactionsByMessage }),- )-- return writeJSON({ messages: messages.reverse(), hasMore, cursor: nextCursor })-})diff --git a/src/web/src/app/api/community/threads/[id]/read/route.test.ts b/src/web/src/app/api/community/threads/[id]/read/route.test.tsdeleted file mode 100644index 3599bc41c..000000000--- a/src/web/src/app/api/community/threads/[id]/read/route.test.ts+++ /dev/null@@ -1,193 +0,0 @@-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 mockGetChannelForMember = vi.fn()-const mockGetMessage = vi.fn()-const mockGetLatestMessage = vi.fn()-const mockMarkReadToMessageBuilder = vi.fn()-const mockMarkChannelMentionsReadBuilder = vi.fn()-const mockBatch = vi.fn()--// The route now fires read-watermark + mention-clear in one `db.batch([...])`-// (mirrors the channel read route). The builders return opaque statement-// markers the batch collects; assert on the builder args, not the statements.-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ batch: (...a: unknown[]) => mockBatch(...a) })) }))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityChannel: {- getChannel: (...a: unknown[]) => mockGetChannel(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityMessage: {- getMessage: (...a: unknown[]) => mockGetMessage(...a),- getLatestMessage: (...a: unknown[]) => mockGetLatestMessage(...a),- },- communityReadState: {- markReadToMessageBuilder: (...a: unknown[]) => mockMarkReadToMessageBuilder(...a),- },- communityMention: {- markChannelMentionsReadBuilder: (...a: unknown[]) => mockMarkChannelMentionsReadBuilder(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { PUT } from "./route"--function putReq(body?: unknown) {- return new NextRequest("http://localhost/api/community/threads/t1/read", {- method: "PUT",- body: body === undefined ? undefined : JSON.stringify(body),- headers: body === undefined ? undefined : { "Content-Type": "application/json" },- })-}--describe("PUT /api/community/threads/[id]/read", () => {- beforeEach(() => {- vi.clearAllMocks()- mockMarkReadToMessageBuilder.mockReturnValue({ __stmt: "read" })- mockMarkChannelMentionsReadBuilder.mockReturnValue({ __stmt: "mentions" })- mockBatch.mockResolvedValue(undefined)- })-- it("body id present: fetches message, scope-checks, batches read + mention-clear to (msg.id, msg.createdAt)", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })- mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })- mockGetMessage.mockResolvedValue({- id: "m9",- channelId: "t1",- createdAt: "2026-07-04T09:00:00.000Z",- })-- const res = await PUT(putReq({ lastReadMessageId: "m9" }), { params: { id: "t1" } } as any)- expect(res.status).toBe(200)-- expect(mockGetMessage).toHaveBeenCalledWith(expect.anything(), "m9")- expect(mockMarkReadToMessageBuilder).toHaveBeenCalledTimes(1)- expect(mockMarkReadToMessageBuilder.mock.calls[0][1]).toEqual({- userId: "u1",- channelId: "t1",- message: { id: "m9", createdAt: "2026-07-04T09:00:00.000Z" },- })- // The thread's own mentions are cleared in the same batch (plan gap #4).- expect(mockMarkChannelMentionsReadBuilder).toHaveBeenCalledWith(expect.anything(), "u1", "t1")- expect(mockBatch).toHaveBeenCalledTimes(1)- expect(mockBatch.mock.calls[0][0]).toEqual([{ __stmt: "read" }, { __stmt: "mentions" }])- expect(mockGetLatestMessage).not.toHaveBeenCalled()- })-- it("body id present but message belongs to another channel → 400, no write", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })- mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })- mockGetMessage.mockResolvedValue({- id: "m9",- channelId: "t_other",- createdAt: "2026-07-04T09:00:00.000Z",- })-- const res = await PUT(putReq({ lastReadMessageId: "m9" }), { params: { id: "t1" } } as any)- expect(res.status).toBe(400)- expect(mockBatch).not.toHaveBeenCalled()- })-- it("body id present but message does not exist → 404, no write", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })- mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })- mockGetMessage.mockResolvedValue(null)-- const res = await PUT(putReq({ lastReadMessageId: "m_ghost" }), { params: { id: "t1" } } as any)- expect(res.status).toBe(404)- expect(mockBatch).not.toHaveBeenCalled()- })-- it("no body: uses latest message and aligns write to it", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })- mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })- mockGetLatestMessage.mockResolvedValue({- id: "m_latest",- createdAt: "2026-07-05T10:00:00.000Z",- })-- const res = await PUT(putReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(200)- expect(mockGetLatestMessage).toHaveBeenCalledWith(expect.anything(), { channelId: "t1" })- expect(mockMarkReadToMessageBuilder).toHaveBeenCalledWith(expect.anything(), {- userId: "u1",- channelId: "t1",- message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z" },- })- expect(mockBatch).toHaveBeenCalledTimes(1)- // Body path never consults getMessage.- expect(mockGetMessage).not.toHaveBeenCalled()- })-- it("no body on EMPTY thread: no write at all, returns 200 { ok: true }", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })- mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })- mockGetLatestMessage.mockResolvedValue(null)-- const res = await PUT(putReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ ok: true })- expect(mockBatch).not.toHaveBeenCalled()- })-- it("returns 400 when the id is missing", async () => {- const res = await PUT(putReq(), { params: {} } as any)- expect(res.status).toBe(400)- expect(mockGetChannel).not.toHaveBeenCalled()- expect(mockGetChannelForMember).not.toHaveBeenCalled()- })-- it("returns 404 when the thread channel does not exist", async () => {- mockGetChannel.mockResolvedValue(null)-- const res = await PUT(putReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(404)- expect(mockGetChannelForMember).not.toHaveBeenCalled()- expect(mockBatch).not.toHaveBeenCalled()- })-- it("returns 403 when the channel exists but the caller is not a member", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "thread" })- mockGetChannelForMember.mockResolvedValue(null)-- const res = await PUT(putReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(403)- expect(mockBatch).not.toHaveBeenCalled()- })-- it("returns 400 when the channel id is a top-level channel, not a thread/forum_post", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1", type: "text" })-- const res = await PUT(putReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(400)- expect(mockGetChannelForMember).not.toHaveBeenCalled()- expect(mockBatch).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/community/threads/[id]/read/route.ts b/src/web/src/app/api/community/threads/[id]/read/route.tsdeleted file mode 100644index d25e0b500..000000000--- a/src/web/src/app/api/community/threads/[id]/read/route.ts+++ /dev/null@@ -1,69 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { requireChannelMember } from "@/lib/community/permissions"-import { requireChildSurface } from "@/lib/community/channel-write-guard"--/**- * PUT /api/community/threads/:id/read- *- * Same two-shape contract as `PUT /channels/:id/read` (a thread is a channel):- * - Body `{ lastReadMessageId }` present → scope-check + align to that- * message.- * - Body absent / empty → align to the thread's latest message. Empty thread- * → no-op (invariant forbids `lastReadMessageId = null` rows).- */-export const PUT = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing id", 400)-- const db = getDb(ctx.env.DB)-- // Two-step check preserves the 404-vs-403 contract that sibling channel- // routes (pins, threads, PATCH/DELETE) also honor: unknown channel → 404,- // known channel + non-member → 403. `requireChannelMember` alone collapses- // both into 403 because the JOIN can't tell the difference.- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return writeError("channel not found", 404)- const child = requireChildSurface(channel.type)- if (!child.ok) return writeError(child.error, child.status)- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- let body: { lastReadMessageId?: string } = {}- try {- body = await req.json()- } catch {- // Body is optional- }-- let target: { id: string; createdAt: string; seq: number } | null- if (body.lastReadMessageId) {- const msg = await queries.communityMessage.getMessage(db, body.lastReadMessageId)- if (!msg) return writeError("message not found", 404)- if (msg.channelId !== channelId) {- return writeError("message not in channel", 400)- }- target = { id: msg.id, createdAt: msg.createdAt, seq: msg.seq }- } else {- target = await queries.communityMessage.getLatestMessage(db, { channelId })- if (!target) return writeJSON({ ok: true })- }-- // A thread IS a channel — mirror the channel read route: advance the read- // watermark AND clear the thread's own mentions in one D1 batch (keyed on the- // thread's channelId). Without the mention clear, opening a thread wouldn't- // dismiss its mentions (plan gap #4).- await db.batch([- queries.communityReadState.markReadToMessageBuilder(db, {- userId: ctx.userId,- channelId,- message: target,- }),- queries.communityMention.markChannelMentionsReadBuilder(db, ctx.userId, channelId),- ])-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/community/threads/[id]/route.test.ts b/src/web/src/app/api/community/threads/[id]/route.test.tsdeleted file mode 100644index a48a445a9..000000000--- a/src/web/src/app/api/community/threads/[id]/route.test.ts+++ /dev/null@@ -1,86 +0,0 @@-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 mockGetChannelForMember = 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: {- communityChannel: {- getChannel: (...a: unknown[]) => mockGetChannel(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...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: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--function getReq() {- return new NextRequest("http://localhost/api/community/threads/t1", { method: "GET" })-}--describe("GET /api/community/threads/[id]", () => {- beforeEach(() => {- vi.clearAllMocks()- })-- it("returns the channel row when the caller is a member", async () => {- const channel = { id: "t1", serverId: "s1", parentChannelId: "c-parent" }- mockGetChannel.mockResolvedValue(channel)- mockGetChannelForMember.mockResolvedValue(channel)-- const res = await GET(getReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual(channel)- })-- it("returns 400 when the id is missing", async () => {- const res = await GET(getReq(), { params: {} } as any)- expect(res.status).toBe(400)- expect(mockGetChannel).not.toHaveBeenCalled()- expect(mockGetChannelForMember).not.toHaveBeenCalled()- })-- it("returns 404 when the thread channel does not exist", async () => {- mockGetChannel.mockResolvedValue(null)-- const res = await GET(getReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(404)- expect(mockGetChannelForMember).not.toHaveBeenCalled()- })-- it("returns 403 when the channel exists but the caller is not a member", async () => {- mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })- mockGetChannelForMember.mockResolvedValue(null)-- const res = await GET(getReq(), { params: { id: "t1" } } as any)- expect(res.status).toBe(403)- })-})diff --git a/src/web/src/app/api/community/threads/[id]/route.ts b/src/web/src/app/api/community/threads/[id]/route.tsdeleted file mode 100644index b5b3f40e4..000000000--- a/src/web/src/app/api/community/threads/[id]/route.ts+++ /dev/null@@ -1,26 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"-import { requireChannelMember } from "@/lib/community/permissions"--// Thread/forum-post metadata is edited through the shared channel PATCH at-// /api/community/channels/[id]. This file is GET-only.-export const GET = withAuth(async (_req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing id", 400)-- const db = getDb(ctx.env.DB)-- // Two-step check preserves the 404-vs-403 contract that sibling channel- // routes (pins, threads, PATCH/DELETE) also honor: unknown channel → 404,- // known channel + non-member → 403. `requireChannelMember` alone collapses- // both into 403 because the JOIN can't tell the difference.- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return writeError("channel not found", 404)- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- return writeJSON(auth.value)-})diff --git a/src/web/src/app/api/community/threads/[id]/upload/route.test.ts b/src/web/src/app/api/community/threads/[id]/upload/route.test.tsdeleted file mode 100644index 9b84ce473..000000000--- a/src/web/src/app/api/community/threads/[id]/upload/route.test.ts+++ /dev/null@@ -1,67 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockRunAttachmentUpload = vi.fn()-const mockRequireChannelMember = vi.fn()--vi.mock("@/lib/community/upload", () => ({- runAttachmentUpload: (...a: unknown[]) => mockRunAttachmentUpload(...a),-}))--vi.mock("@/lib/community/permissions", () => ({- requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...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- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- },-}))--import { POST } from "./route"--function postReq() {- return new NextRequest("http://localhost/api/community/threads/t1/upload", {- method: "POST",- })-}--const ctx = { params: { id: "t1" } } as any--describe("POST /api/community/threads/[id]/upload", () => {- beforeEach(() => {- vi.clearAllMocks()- mockRunAttachmentUpload.mockResolvedValue(- new Response(null, { status: 200 }),- )- })-- it("delegates to runAttachmentUpload with kind='thread' + requireChannelMember", async () => {- // Thread channels are still community channels — reuse requireChannelMember- // rather than a thread-specific check. The distinguishing bit is the- // `kind: "thread"` argument, which selects the R2 key prefix.- const req = postReq()- await POST(req, ctx)- expect(mockRunAttachmentUpload).toHaveBeenCalledOnce()- const [passedReq, passedCtx, kind, permCheck] =- mockRunAttachmentUpload.mock.calls[0]- expect(passedReq).toBe(req)- expect(passedCtx).toMatchObject({ userId: "u1", params: { id: "t1" } })- expect(kind).toBe("thread")- // Invoke the passed permission-check reference and observe the underlying- // mock — pins the route to `requireChannelMember` (a swap to another- // helper would hit a different mock).- await (permCheck as (...a: unknown[]) => unknown)("db", "t1", "u1")- expect(mockRequireChannelMember).toHaveBeenCalledWith("db", "t1", "u1")- })-- it("returns whatever runAttachmentUpload returns unchanged", async () => {- const helperResponse = new Response(JSON.stringify({ ok: 1 }), {- status: 201,- })- mockRunAttachmentUpload.mockResolvedValueOnce(helperResponse)- const res = await POST(postReq(), ctx)- expect(res).toBe(helperResponse)- })-})diff --git a/src/web/src/app/api/community/threads/[id]/upload/route.ts b/src/web/src/app/api/community/threads/[id]/upload/route.tsdeleted file mode 100644index 017fe3598..000000000--- a/src/web/src/app/api/community/threads/[id]/upload/route.ts+++ /dev/null@@ -1,8 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { requireChannelMember } from "@/lib/community/permissions"-import { runAttachmentUpload } from "@/lib/community/upload"--export const POST = withAuth((req: NextRequest, ctx) =>- runAttachmentUpload(req, ctx, "thread", requireChannelMember),-)diff --git a/src/web/src/app/api/community/dm/route.test.ts b/src/web/src/app/api/community/users/me/dms/route.test.tssimilarity index 93%rename from src/web/src/app/api/community/dm/route.test.tsrename to src/web/src/app/api/community/users/me/dms/route.test.tsindex 110804879..57e8aec9b 100644--- a/src/web/src/app/api/community/dm/route.test.ts+++ b/src/web/src/app/api/community/users/me/dms/route.test.ts@@ -49,10 +49,10 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"function getReq() {- return new NextRequest("http://localhost/api/community/dm", { method: "GET" })+ return new NextRequest("http://localhost/api/community/users/me/dms", { method: "GET" })}-describe("GET /api/community/dm — name projection", () => {+describe("GET /api/community/users/me/dms — name projection", () => {beforeEach(() => vi.clearAllMocks())it("returns the counterpart's user.name verbatim (no email fallback)", async () => {diff --git a/src/web/src/app/api/community/users/me/dms/route.ts b/src/web/src/app/api/community/users/me/dms/route.tsnew file mode 100644index 000000000..d85126dfa--- /dev/null+++ b/src/web/src/app/api/community/users/me/dms/route.ts@@ -0,0 +1,34 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { avatarInitial } from "@/lib/community/avatar"++/**+ * GET /api/community/users/me/dms — the DM sidebar list, relocated from the+ * flat `GET /api/community/dm` (route/disc 接口树统一, Blondie #615/#432 terminal+ * table: RELOCATE into the users/me/* family, same class as inbox/marks/+ * server-folders — "my own" aggregate read, self-scope, no target-user param).+ * Byte-identical body to the former GET /dm handler; only the URL moved.+ *+ * DM channels carry server_id = NULL (no server to hang a `servers/{id}/…`+ * listing off), so this doesn't fit the channels/servers resource tree — it's+ * "the DM channels I'm a participant in", which is exactly the users/me/*+ * shape. POST (DM creation) already lives in the create-door (POST /channels+ * type: dm via createDmForUser) and needs no change here.+ */+export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)+ const rows = await queries.communityDm.listDMs(db, ctx.userId)+ const conversations = rows.map((r) => ({+ id: r.id,+ userId: r.otherUserId,+ name: r.otherUserName,+ discriminator: r.otherUserDiscriminator,+ avatar: r.otherUserImage ?? avatarInitial(r.otherUserName),+ status: "offline" as const,+ preview: "",+ }))+ return writeJSON({ conversations })+})diff --git a/src/web/src/app/api/community/ack/route.test.ts b/src/web/src/app/api/community/users/me/inbox/ack/route.test.tssimilarity index 85%rename from src/web/src/app/api/community/ack/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/ack/route.test.tsindex c5737f30f..3ae90d806 100644--- a/src/web/src/app/api/community/ack/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts@@ -59,14 +59,14 @@ vi.mock("@alook/shared", async () => {import { POST } from "./route"function req(body: unknown, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/ack", {+ return new NextRequest("http://localhost/api/community/users/me/inbox/ack", {method: "POST",headers: { "content-type": "application/json", ...headers },body: typeof body === "string" ? body : JSON.stringify(body),})}-describe("POST /api/community/agent/ack", () => {+describe("POST /api/community/users/me/inbox/ack", () => {beforeEach(() => {vi.clearAllMocks()mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })@@ -78,7 +78,7 @@ describe("POST /api/community/agent/ack", () => {})it("401 without Authorization", async () => {- const res = await POST(req({ cursors: [{ channel: "/studio/general", seq: 3 }] }))+ const res = await POST(req({ cursors: [{ channel: "/studio#0042/general", seq: 3 }] }))expect(res.status).toBe(401)})@@ -89,7 +89,7 @@ describe("POST /api/community/agent/ack", () => {it("400 when a cursor uses seq 0 sentinel", async () => {const res = await POST(- req({ cursors: [{ channel: "/studio/general", seq: 0 }] }, { Authorization: "Bearer crk_abc" })+ req({ cursors: [{ channel: "/studio#0042/general", seq: 0 }] }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(400)expect(mockBumpReadCursor).not.toHaveBeenCalled()@@ -98,7 +98,7 @@ describe("POST /api/community/agent/ack", () => {it("never auto-creates a DM/thread as a side effect — resolves with createDmIfMissing/createThreadIfMissing false", async () => {mockResolveServerByNameForMember.mockResolvedValue([])const res = await POST(- req({ cursors: [{ channel: "/studio/general", seq: 3 }] }, { Authorization: "Bearer crk_abc" })+ req({ cursors: [{ channel: "/studio#0042/general", seq: 3 }] }, { Authorization: "Bearer crk_abc" }))// Best-effort: an unresolvable cursor is reported in `failed`, not a// request-level error. Still never bumps (nothing resolved).@@ -107,7 +107,7 @@ describe("POST /api/community/agent/ack", () => {expect(body.ok).toBe(false)expect(body.applied).toEqual([])expect(body.failed).toEqual([- { channel: "/studio/general", seq: 3, code: "unresolvable", error: expect.any(String) },+ { channel: "/studio#0042/general", seq: 3, code: "unresolvable", error: expect.any(String) },])expect(mockBumpReadCursor).not.toHaveBeenCalled()})@@ -115,13 +115,13 @@ describe("POST /api/community/agent/ack", () => {it("reports no_such_seq in failed[] (not a request error) when bumpReadCursor can't find that seq", async () => {mockBumpReadCursor.mockResolvedValue(null)const res = await POST(- req({ cursors: [{ channel: "/studio/general", seq: 99 }] }, { Authorization: "Bearer crk_abc" })+ req({ cursors: [{ channel: "/studio#0042/general", seq: 99 }] }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)const body = await res.json()expect(body.ok).toBe(false)expect(body.applied).toEqual([])- expect(body.failed[0]).toMatchObject({ channel: "/studio/general", seq: 99, code: "no_such_seq" })+ expect(body.failed[0]).toMatchObject({ channel: "/studio#0042/general", seq: 99, code: "no_such_seq" })expect(body.failed[0].error).toMatch(/no message with seq #99/)})@@ -131,8 +131,8 @@ describe("POST /api/community/agent/ack", () => {// good DM. Under the old fail-fast this returned 404 and the DM after the// poison cursor never bumped — the exact mechanism that muted the bot.mockResolveChannelByNameForMember- .mockResolvedValueOnce([{ id: "ch_1" }]) // /studio/general → ok- .mockResolvedValueOnce([]) // /studio/badpost → unresolvable+ .mockResolvedValueOnce([{ id: "ch_1" }]) // /studio#0042/general → ok+ .mockResolvedValueOnce([]) // /studio#0042/badpost → unresolvablemockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null })@@ -146,8 +146,8 @@ describe("POST /api/community/agent/ack", () => {req({cursors: [- { channel: "/studio/general", seq: 3 },- { channel: "/studio/badpost", seq: 5 },+ { channel: "/studio#0042/general", seq: 3 },+ { channel: "/studio#0042/badpost", seq: 5 },{ channel: "/.dm/peer#0001", seq: 1 },],},@@ -159,11 +159,11 @@ describe("POST /api/community/agent/ack", () => {expect(body.ok).toBe(false)// Both good cursors applied AND bumped — despite the poison cursor between them.expect(body.applied).toEqual([- { channel: "/studio/general", seq: 3 },+ { channel: "/studio#0042/general", seq: 3 },{ channel: "/.dm/peer#0001", seq: 1 },])expect(body.failed).toEqual([- { channel: "/studio/badpost", seq: 5, code: "unresolvable", error: expect.any(String) },+ { channel: "/studio#0042/badpost", seq: 5, code: "unresolvable", error: expect.any(String) },])expect(mockBumpReadCursor).toHaveBeenCalledTimes(2)expect(mockBumpReadCursor).toHaveBeenNthCalledWith(1, expect.anything(), "bot_1", { channelId: "ch_1" }, 3)@@ -183,8 +183,8 @@ describe("POST /api/community/agent/ack", () => {req({cursors: [- { channel: "/studio/secret", seq: 7 },- { channel: "/studio/general", seq: 2 },+ { channel: "/studio#0042/secret", seq: 7 },+ { channel: "/studio#0042/general", seq: 2 },],},{ Authorization: "Bearer crk_abc" }@@ -193,15 +193,15 @@ describe("POST /api/community/agent/ack", () => {expect(res.status).toBe(200)const body = await res.json()expect(body.ok).toBe(false)- expect(body.applied).toEqual([{ channel: "/studio/general", seq: 2 }])- expect(body.failed[0]).toMatchObject({ channel: "/studio/secret", seq: 7, code: "forbidden" })+ expect(body.applied).toEqual([{ channel: "/studio#0042/general", seq: 2 }])+ expect(body.failed[0]).toMatchObject({ channel: "/studio#0042/secret", seq: 7, code: "forbidden" })expect(mockBumpReadCursor).toHaveBeenCalledTimes(1)})it("propagates a genuine D1 exception as a 500 (never swallowed into failed[])", async () => {mockBumpReadCursor.mockRejectedValue(new Error("D1_ERROR: something non-retryable"))await expect(- POST(req({ cursors: [{ channel: "/studio/general", seq: 3 }] }, { Authorization: "Bearer crk_abc" }))+ POST(req({ cursors: [{ channel: "/studio#0042/general", seq: 3 }] }, { Authorization: "Bearer crk_abc" }))).rejects.toThrow()})@@ -219,7 +219,7 @@ describe("POST /api/community/agent/ack", () => {req({cursors: [- { channel: "/studio/general", seq: 3 },+ { channel: "/studio#0042/general", seq: 3 },{ channel: "/.dm/peer#0001", seq: 1 },],},@@ -230,7 +230,7 @@ describe("POST /api/community/agent/ack", () => {expect(await res.json()).toEqual({ok: true,applied: [- { channel: "/studio/general", seq: 3 },+ { channel: "/studio#0042/general", seq: 3 },{ channel: "/.dm/peer#0001", seq: 1 },],failed: [],diff --git a/src/web/src/app/api/community/ack/route.ts b/src/web/src/app/api/community/users/me/inbox/ack/route.tssimilarity index 70%rename from src/web/src/app/api/community/ack/route.tsrename to src/web/src/app/api/community/users/me/inbox/ack/route.tsindex 46fa4412f..c635fc90d 100644--- a/src/web/src/app/api/community/ack/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/ack/route.ts@@ -7,17 +7,31 @@ import { isDmTarget } from "@/lib/community/message-handler"import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"/**- * POST /api/community/ack — plan §7. The ONLY endpoint that advances- * `lastReadSeq` (`inboxPull` never mutates read state — debt #2 correction).- * Each cursor's `channel` ref is resolved read-only (no DM/thread- * auto-create — a stale ref must never materialize a row as a side effect- * of an ack) and membership-gated before `bumpReadCursor`.+ * POST /api/community/users/me/inbox/ack — the canonical bot batch-ack+ * (route/disc 接口树统一, ack relocation, Gener #215 乙). ack ADVANCES the bot's+ * cross-channel read waterline (`lastReadSeq`); it is the third operation on the+ * one inbox resource, completing the fetch↔advance separation (Aigneis #41):+ * - GET users/me/inbox/snapshot → peek (never advances)+ * - POST users/me/inbox/pull → fetch+ * - POST users/me/inbox/ack → advance+ * The waterline WRITE (bumpReadCursor) converges with the human read route's+ * markReadToMessageBuilder on the SAME communityReadState row + same 3 columns+ * (lastReadAt/lastReadMessageId/lastReadSeq) — one waterline, two input anchors+ * (bot=seq / human=messageId). That single-source is at the write layer, NOT the+ * URL: this endpoint stays a bot-native MOVE-FLAT (乙: 寻址/水位归一 ≠ URL归一),+ * kept distinct from the human PUT channels/{id}/read for three orthogonal+ * reasons — (1) batch-of-cursors best-effort + failed[] never-drop, (2) it does+ * NOT clear mentions (the human PUT does), (3) ref-resolve with create DISABLED+ * (resolve≠create). Bot-only; a human actor → 403 via requireBot (Gener #116).*- * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).+ * The flat /api/community/ack route is deleted (flat-delete step) — this door+ * is the sole canonical entry; the deploy-orchestration verify-list gates+ * deleting it (and inboxPull's flat verb) on the daemon being confirmed on+ * this new target.** Best-effort per cursor, NOT fail-fast: every good cursor is applied and its* waterline advanced regardless of any sibling cursor failing. A single- * unresolvable cursor (e.g. a forum_post whose ref can't parse back) must+ * unresolvable child-thread cursor must* never stall the healthy cursors behind it — that regressed their waterlines* and muted the bot in every channel with unread. Bad cursors are collected* into `failed[]` with a coarse `code`; the response is ALWAYS 200 (partial@@ -81,7 +95,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {// into `failed`).const bumped = await withD1Retry(() => queries.communityReadState.bumpReadCursor(db, botUserId, scopeTarget, cursor.seq),- { route: "community/agent/ack:bump" },+ { route: "community/users/me/inbox/ack:bump" },)if (!bumped) {failed.push({diff --git a/src/web/src/app/api/community/inbox/dms/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.tssimilarity index 93%rename from src/web/src/app/api/community/inbox/dms/read-all/route.tsrename to src/web/src/app/api/community/users/me/inbox/dms/read-all/route.tsindex f25dc4243..f0707c3c4 100644--- a/src/web/src/app/api/community/inbox/dms/read-all/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts@@ -4,7 +4,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON } from "@/lib/middleware/helpers"/**- * POST /api/community/inbox/dms/read-all+ * POST /api/community/users/me/inbox/dms/read-all** Mark every DM the viewer participates in read at its latest message. Kept a* DISTINCT route from `/inbox/unreads/read-all` (channels) so the inboxdiff --git a/src/web/src/app/api/community/inbox/mentions/[id]/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.tssimilarity index 88%rename from src/web/src/app/api/community/inbox/mentions/[id]/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.tsindex 6cae2b200..ce52fcf3f 100644--- a/src/web/src/app/api/community/inbox/mentions/[id]/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts@@ -35,13 +35,13 @@ vi.mock("@/lib/middleware/helpers", () => {import { DELETE } from "./route"-describe("DELETE /api/community/inbox/mentions/{id}", () => {+describe("DELETE /api/community/users/me/inbox/mentions/{id}", () => {beforeEach(() => vi.clearAllMocks())it("deletes the mention scoped to the current user", async () => {// The query returns the number of rows affected; a real hit returns 1.mockDeleteMention.mockResolvedValue(1)- const res = await DELETE(new NextRequest("http://localhost/api/community/inbox/mentions/mn1", { method: "DELETE" }), {+ const res = await DELETE(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/mn1", { method: "DELETE" }), {params: { id: "mn1" },} as never)expect(res.status).toBe(200)@@ -50,14 +50,14 @@ describe("DELETE /api/community/inbox/mentions/{id}", () => {it("404 when the mention does not exist or belongs to another user", async () => {mockDeleteMention.mockResolvedValue(0)- const res = await DELETE(new NextRequest("http://localhost/api/community/inbox/mentions/mn1", { method: "DELETE" }), {+ const res = await DELETE(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/mn1", { method: "DELETE" }), {params: { id: "mn1" },} as never)expect(res.status).toBe(404)})it("400 when mention id is missing from route params", async () => {- const res = await DELETE(new NextRequest("http://localhost/api/community/inbox/mentions/", { method: "DELETE" }), {+ const res = await DELETE(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/", { method: "DELETE" }), {params: {},} as never)expect(res.status).toBe(400)diff --git a/src/web/src/app/api/community/inbox/mentions/[id]/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.tssimilarity index 100%rename from src/web/src/app/api/community/inbox/mentions/[id]/route.tsrename to src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.tsdiff --git a/src/web/src/app/api/community/inbox/mentions/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.tssimilarity index 91%rename from src/web/src/app/api/community/inbox/mentions/read-all/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.tsindex ea72f7201..b370c92ba 100644--- a/src/web/src/app/api/community/inbox/mentions/read-all/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts@@ -35,12 +35,12 @@ vi.mock("@/lib/middleware/helpers", () => {import { POST } from "./route"-describe("POST /api/community/inbox/mentions/read-all", () => {+describe("POST /api/community/users/me/inbox/mentions/read-all", () => {beforeEach(() => vi.clearAllMocks())it("marks all mentions read for the current user", async () => {mockMarkAllMentionsRead.mockResolvedValue(undefined)- const res = await POST(new NextRequest("http://localhost/api/community/inbox/mentions/read-all", { method: "POST" }))+ const res = await POST(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/read-all", { method: "POST" }))expect(res.status).toBe(200)expect(mockMarkAllMentionsRead).toHaveBeenCalledWith({}, "u1")})diff --git a/src/web/src/app/api/community/inbox/mentions/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.tssimilarity index 100%rename from src/web/src/app/api/community/inbox/mentions/read-all/route.tsrename to src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.tsdiff --git a/src/web/src/app/api/community/inbox/mentions/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.tssimilarity index 93%rename from src/web/src/app/api/community/inbox/mentions/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/mentions/route.test.tsindex c205ce8d5..37deeb2eb 100644--- a/src/web/src/app/api/community/inbox/mentions/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts@@ -48,7 +48,7 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"-describe("GET /api/community/inbox/mentions", () => {+describe("GET /api/community/users/me/inbox/mentions", () => {beforeEach(() => {vi.clearAllMocks()mockGetChannelsByIds.mockResolvedValue([])@@ -58,7 +58,7 @@ describe("GET /api/community/inbox/mentions", () => {it("queries BOTH mention + reply kinds (no kind filter) scoped to visible channels", async () => {mockListUnreadMentions.mockResolvedValue([])- await GET(new NextRequest("http://localhost/api/community/inbox/mentions"))+ await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))// No `kind` narrowing — both @-mentions and reply notifications surface.const opts = mockListUnreadMentions.mock.calls[0][2]expect(opts.kind).toBeUndefined()@@ -76,7 +76,7 @@ describe("GET /api/community/inbox/mentions", () => {mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/mentions"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))const body = await res.json()expect(body.mentions).toHaveLength(1)expect(body.mentions[0]).toMatchObject({@@ -103,21 +103,21 @@ describe("GET /api/community/inbox/mentions", () => {])mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/mentions"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))const body = await res.json()expect(body.mentions[0].kind).toBe("reply")})it("returns empty mentions array when none", async () => {mockListUnreadMentions.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/mentions"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))const body = await res.json()expect(body.mentions).toEqual([])})it("clamps over-cap limit and forwards it to the query", async () => {mockListUnreadMentions.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/mentions?limit=99999"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions?limit=99999"))const body = await res.json()expect(body.limit).toBe(200) // MAX_INBOX_PAGE_SIZEexpect(mockListUnreadMentions).toHaveBeenCalledWith({}, "u1", { limit: 200, visibleChannelIds: ["c1"] })diff --git a/src/web/src/app/api/community/inbox/mentions/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.tssimilarity index 100%rename from src/web/src/app/api/community/inbox/mentions/route.tsrename to src/web/src/app/api/community/users/me/inbox/mentions/route.tsdiff --git a/src/web/src/app/api/community/inboxPull/route.test.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.test.tssimilarity index 55%rename from src/web/src/app/api/community/inboxPull/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/pull/route.test.tsindex c6897d0d5..c6ee442ab 100644--- a/src/web/src/app/api/community/inboxPull/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts@@ -5,10 +5,6 @@ vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),}))vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.vi.mock("@/lib/auth", () => ({createAuth: vi.fn(() => ({api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },@@ -44,15 +40,19 @@ vi.mock("@alook/shared", async () => {import { POST } from "./route"+// Bot arm of POST users/me/inbox/pull (folds the flat inboxPull verb). The pull+// is self-scoped to the voucher's bot (users/me/* family invariant): the body+// schema is `{ max? }` only — NO target-user param — so a bot can only pull its+// own inbox. A no-crk_ request falls to the human arm → 401.function req(body?: string, headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/inboxPull", {+ return new NextRequest("http://localhost/api/community/users/me/inbox/pull", {method: "POST",headers: { "content-type": "application/json", ...headers },...(body !== undefined ? { body } : {}),})}-describe("POST /api/community/agent/inboxPull", () => {+describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)", () => {beforeEach(() => {vi.clearAllMocks()mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })@@ -62,7 +62,7 @@ describe("POST /api/community/agent/inboxPull", () => {mockListByMessageIds.mockResolvedValue([])})- it("401 without Authorization", async () => {+ it("401 without Authorization (human arm, no session)", async () => {const res = await POST(req(undefined))expect(res.status).toBe(401)})@@ -72,29 +72,16 @@ describe("POST /api/community/agent/inboxPull", () => {expect(res.status).toBe(400)})- it("400 when max is out of the schema's allowed range", async () => {- const res = await POST(req(JSON.stringify({ max: 0 }), { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(400)- })-- it("a missing/empty body defaults to {} and uses the default max", async () => {- mockListUnreadMessagesForAgent.mockResolvedValue([])- const res = await POST(req(undefined, { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(mockListUnreadMessagesForAgent).toHaveBeenCalledWith(expect.anything(), "bot_1", { max: 201 })- })-- it("hasMore is false and no probe row leaks through when unread count <= max", async () => {- mockListUnreadMessagesForAgent.mockResolvedValue([{ id: "m_1" }, { id: "m_2" }])- const res = await POST(req(JSON.stringify({ max: 5 }), { Authorization: "Bearer crk_abc" }))+ it("self-scoped: pull always queries the caller's OWN userId (bot_1), never a body-supplied target", async () => {+ mockListUnreadMessagesForAgent.mockResolvedValue([{ id: "m_1" }])+ // A body carrying a rogue `userId` must be ignored — the scope comes from the+ // credential, not the payload (users/me/* family invariant).+ const res = await POST(req(JSON.stringify({ max: 5, userId: "someone_else" }), { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)- const body = await res.json()- expect(body.hasMore).toBe(false)- expect(body.messages).toHaveLength(2)expect(mockListUnreadMessagesForAgent).toHaveBeenCalledWith(expect.anything(), "bot_1", { max: 6 })})- it("hasMore is true and the probe row is trimmed off when unread count > max", async () => {+ it("hasMore + probe-row trim behave (unread > max)", async () => {mockListUnreadMessagesForAgent.mockResolvedValue([{ id: "m_1" }, { id: "m_2" }, { id: "m_3" }])const res = await POST(req(JSON.stringify({ max: 2 }), { Authorization: "Bearer crk_abc" }))const body = await res.json()@@ -102,34 +89,32 @@ describe("POST /api/community/agent/inboxPull", () => {expect(body.messages).toHaveLength(2)})- it("caps an oversized max at MAX_PULL (200) before querying", async () => {- mockListUnreadMessagesForAgent.mockResolvedValue([])- // Schema itself caps at 200, so this exercises the route's own `Math.min` no-op path at the ceiling.- const res = await POST(req(JSON.stringify({ max: 200 }), { Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(mockListUnreadMessagesForAgent).toHaveBeenCalledWith(expect.anything(), "bot_1", { max: 201 })- })-- it("retries a transient D1 error and succeeds (withD1Retry wraps the pull reads)", async () => {- // First call throws a retryable transient (`internal error; reference` is- // on isRetryableD1Error's list), second succeeds — the route should NOT- // 500, it should retry and return the messages.+ it("retries a transient D1 error (withD1Retry armor carried over)", async () => {mockListUnreadMessagesForAgent.mockRejectedValueOnce(new Error("D1_ERROR: internal error; reference = abc123")).mockResolvedValueOnce([{ id: "m_1" }])const res = await POST(req(JSON.stringify({ max: 5 }), { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)- expect((await res.json()).messages).toHaveLength(1)expect(mockListUnreadMessagesForAgent).toHaveBeenCalledTimes(2)})- it("a NON-retryable error is not retried and surfaces (no silent swallow)", async () => {- // A logic error (not a transient) must propagate, not be retried into a- // false success. withD1Retry rethrows non-retryable errors immediately.- mockListUnreadMessagesForAgent.mockRejectedValue(new Error("SQLITE_CONSTRAINT: bad column"))- await expect(POST(req(JSON.stringify({ max: 5 }), { Authorization: "Bearer crk_abc" }))).rejects.toThrow(- /SQLITE_CONSTRAINT/,- )- expect(mockListUnreadMessagesForAgent).toHaveBeenCalledTimes(1)+ it("keeps an orphan-DM message owed after a loud hydration failure and redelivers it after repair", async () => {+ const owed = { id: "owed_message_internal", channelId: "dm_channel_internal", seq: 7 }+ mockListUnreadMessagesForAgent.mockResolvedValue([owed])+ mockToAgentMessages+ .mockRejectedValueOnce(new Error("DM peer identity unavailable"))+ .mockResolvedValueOnce([{ seq: "#7", channel: "/.dm/Bob#0042", sender: "@Alice#1234", content: { text: "still owed" } }])++ const first = POST(req(JSON.stringify({ max: 5 }), { Authorization: "Bearer crk_abc" }))+ await expect(first).rejects.toThrow("DM peer identity unavailable")+ await expect(first).rejects.not.toThrow(/owed_message_internal|dm_channel_internal/)++ const repaired = await POST(req(JSON.stringify({ max: 5 }), { Authorization: "Bearer crk_abc" }))+ expect(repaired.status).toBe(200)+ expect(await repaired.json()).toMatchObject({+ messages: [{ seq: "#7", channel: "/.dm/Bob#0042", content: { text: "still owed" } }],+ })+ expect(mockListUnreadMessagesForAgent).toHaveBeenCalledTimes(2)+ expect(mockListUnreadMessagesForAgent.mock.results.map((r) => r.value)).toHaveLength(2)})})diff --git a/src/web/src/app/api/community/inboxPull/route.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.tssimilarity index 57%rename from src/web/src/app/api/community/inboxPull/route.tsrename to src/web/src/app/api/community/users/me/inbox/pull/route.tsindex 16a2cced3..cd66b446d 100644--- a/src/web/src/app/api/community/inboxPull/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.ts@@ -6,16 +6,20 @@ import { withCommunityActor, requireBot } from "@/lib/middleware/community-actorconst MAX_PULL = 200/**- * POST /api/community/inboxPull — plan §7.+ * POST /api/community/users/me/inbox/pull — the caller's own inbox pull+ * (route/disc trunk, 接口树统一 轴3; folds the flat `inboxPull` verb into the+ * users/me resource). Bot-only (human actor → 403 via requireBot); a human+ * reads unread through the inbox aggregate sub-routes, not this consuming pull.*- * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).+ * ⭐ users/me/* family invariant (Aigneis #426/Melly #427/#447): scope is ALWAYS+ * the caller's own userId (`gate.bot.userId` from the voucher) — this endpoint+ * takes NO target-user param, so a bot can only ever pull ITS OWN inbox, never+ * another user's unread. inbox = "my unread", so a leaked target param would be+ * a cross-user data leak; the self-scope is load-bearing here.*- * Grouped-by-channel fill (v4 decision): `ORDER BY channel_id, seq ASC`, one- * channel's unread always drained fully before the next starts — `seq` is a- * per-scope counter, so raw cross-channel seq comparison is meaningless (see- * `listUnreadMessagesForAgent`'s doc comment). Excludes the bot's own- * authored messages. Never mutates read state — `ack` is the only mutator- * (debt #2 correction).+ * Grouped-by-channel fill (v4): `ORDER BY channel_id, seq ASC`, one channel's+ * unread drained fully before the next (`seq` is per-scope). Excludes the bot's+ * own authored messages. Never mutates read state — `ack` is the only mutator.*/export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const gate = requireBot(ctx.actor)@@ -24,9 +28,9 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- // Body is optional (`InboxPullRequest = { max? }`) — an empty/missing body- // is equivalent to `{}`, not a 400. Only a body that parses to JSON but- // fails schema validation (e.g. `max` out of range) is rejected.+ // Body is optional (`InboxPullRequest = { max? }`) — an empty/missing body is+ // equivalent to `{}`, not a 400. Only a body that parses to JSON but fails+ // schema validation (e.g. `max` out of range) is rejected.let raw: unknown = {}try {const text = await req.text()@@ -40,27 +44,22 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {}const max = Math.min(parsed.data.max ?? MAX_PULL, MAX_PULL)- // Fetch one extra row to detect whether more unread remain beyond `max`.- // Each D1 call is wrapped in withD1Retry so a transient miniflare/D1 blip- // (`internal error; reference`, on isRetryableD1Error's list) is retried- // instead of surfacing as a hard 500 to the bot — the same armor the- // human-facing bootstrap route already has. A non-transient throw still- // propagates (withD1Retry rethrows once retries are exhausted / on a- // non-retryable error).+ // Fetch one extra row to detect whether more unread remain beyond `max`. Each+ // D1 call is wrapped in withD1Retry so a transient blip is retried, not a hard+ // 500 to the bot.const rows = await withD1Retry(() => queries.communityAgentInbox.listUnreadMessagesForAgent(db, botUserId, { max: max + 1 }),- { route: "community/agent/inboxPull:list-unread" },+ { route: "community/users/me/inbox/pull:list-unread" },)const hasMore = rows.length > maxconst page = hasMore ? rows.slice(0, max) : rows- // Batch-fetch attachments in one query (plan §Inbox projection). Pending- // rows (message_id = NULL) never match this inArray, so agent-uploaded- // pending rows are naturally excluded from the inbox.+ // Batch-fetch attachments in one query. Pending rows (message_id = NULL) never+ // match this inArray, so agent-uploaded pending rows are naturally excluded.const messageIds = page.map((r) => r.id)const attachmentRows = await withD1Retry(() => queries.communityAttachment.listByMessageIds(db, messageIds),- { route: "community/agent/inboxPull:attachments" },+ { route: "community/users/me/inbox/pull:attachments" },)const attachmentsByMessageId = new Map<string, Array<{ id: string; filename: string; contentType: string | null; size: number | null }>>()for (const a of attachmentRows) {@@ -77,7 +76,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {botUserId,attachmentsByMessageId,),- { route: "community/agent/inboxPull:hydrate" },+ { route: "community/users/me/inbox/pull:hydrate" },)return NextResponse.json({ messages, hasMore })})diff --git a/src/web/src/app/api/community/inboxSnapshot/route.test.ts b/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.tssimilarity index 52%rename from src/web/src/app/api/community/inboxSnapshot/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/snapshot/route.test.tsindex 35bfa5d06..6c4d2b676 100644--- a/src/web/src/app/api/community/inboxSnapshot/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts@@ -5,10 +5,6 @@ vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),}))vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-// Unified actor: a request with no `crk_` bearer falls through to the human-// withAuth path. Mock Better-Auth to resolve "no session" so a no-auth request-// yields the human-path 401 ("unauthorized") — the real unified-actor contract —-// instead of a 503 from unmocked session validation.vi.mock("@/lib/auth", () => ({createAuth: vi.fn(() => ({api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },@@ -38,17 +34,20 @@ vi.mock("@alook/shared", async () => {}})-import { POST } from "./route"+import { GET } from "./route"+// Bot arm of GET users/me/inbox/snapshot (folds the flat inboxSnapshot verb). A+// GET — pure peek, never advances the read waterline. Self-scoped to the+// voucher's bot (no target-user param). A no-crk_ request falls to the human+// arm → 401.function req(headers: Record<string, string> = {}): NextRequest {- return new NextRequest("http://localhost/api/community/agent/inboxSnapshot", {- method: "POST",- headers: { "content-type": "application/json", ...headers },- body: "{}",+ return new NextRequest("http://localhost/api/community/users/me/inbox/snapshot", {+ method: "GET",+ headers: { ...headers },})}-describe("POST /api/community/agent/inboxSnapshot", () => {+describe("GET /api/community/users/me/inbox/snapshot — bot arm (folds inboxSnapshot)", () => {beforeEach(() => {vi.clearAllMocks()mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })@@ -56,32 +55,39 @@ describe("POST /api/community/agent/inboxSnapshot", () => {mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })})- it("401 without Authorization", async () => {- const res = await POST(new NextRequest("http://localhost/api/community/agent/inboxSnapshot", { method: "POST" }))+ it("401 without Authorization (human arm, no session)", async () => {+ const res = await GET(req())expect(res.status).toBe(401)- expect(mockGetInboxSnapshotForAgent).not.toHaveBeenCalled()})- it("200 with rows plus derived pendingChannels/pendingMessages totals", async () => {- mockGetInboxSnapshotForAgent.mockResolvedValue([{ channelId: "ch_1" }, { channelId: "ch_2" }])+ it("returns the per-channel snapshot with pending totals, scoped to the caller's own bot", async () => {+ mockGetInboxSnapshotForAgent.mockResolvedValue({ any: "shape" })mockToInboxRows.mockResolvedValue([- { channel: "/studio/general", pendingCount: 3, firstPendingSeq: 1, latestSeq: 3, latestSender: "@Alice", flags: [] },- { channel: "/.dm/Bob", pendingCount: 2, firstPendingSeq: 5, latestSeq: 6, latestSender: "@Bob", flags: ["dm"] },+ { channelId: "c1", pendingCount: 2 },+ { channelId: "c2", pendingCount: 3 },])- const res = await POST(req({ Authorization: "Bearer crk_abc" }))+ const res = await GET(req({ Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)const body = await res.json()- expect(body.pendingChannels).toBe(2)- expect(body.pendingMessages).toBe(5)- expect(body.rows).toHaveLength(2)+ expect(body).toEqual({+ rows: [+ { channelId: "c1", pendingCount: 2 },+ { channelId: "c2", pendingCount: 3 },+ ],+ pendingChannels: 2,+ pendingMessages: 5,+ })+ // self-scope: the snapshot query is called with the caller's own bot userId.expect(mockGetInboxSnapshotForAgent).toHaveBeenCalledWith(expect.anything(), "bot_1")})- it("200 with empty rows → zeroed totals, no pending unread", async () => {- mockGetInboxSnapshotForAgent.mockResolvedValue([])- mockToInboxRows.mockResolvedValue([])- const res = await POST(req({ Authorization: "Bearer crk_abc" }))- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ rows: [], pendingChannels: 0, pendingMessages: 0 })+ it("loudly rejects an orphan scope without leaking internal ids", async () => {+ mockGetInboxSnapshotForAgent.mockResolvedValue([+ { channelId: "dm_channel_internal", latestSenderId: "peer_internal" },+ ])+ mockToInboxRows.mockRejectedValue(new Error("DM peer identity unavailable"))+ const request = GET(req({ Authorization: "Bearer crk_abc" }))+ await expect(request).rejects.toThrow("DM peer identity unavailable")+ await expect(request).rejects.not.toThrow(/dm_channel_internal|peer_internal/)})})diff --git a/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts b/src/web/src/app/api/community/users/me/inbox/snapshot/route.tsnew file mode 100644index 000000000..40dce9510--- /dev/null+++ b/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts@@ -0,0 +1,39 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, withD1Retry } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"++/**+ * GET /api/community/users/me/inbox/snapshot — a non-consuming, bodiless summary+ * of the caller's pending unread, bucketed per channel/DM (route/disc trunk,+ * 接口树统一 轴3; folds the flat `inboxSnapshot` verb into the users/me resource).+ * A GET (pure peek — it NEVER advances the read waterline, unlike pull), so the+ * fetch↔advance decoupling is preserved (Aigneis #41: snapshot=peek, pull=fetch,+ * ack=advance).+ *+ * Bot-only (human actor → 403). ⭐ users/me/* family invariant (Aigneis #426):+ * scope is the caller's own userId (`gate.bot.userId`), NO target-user param —+ * a bot only ever sees its own inbox summary.+ */+export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ const { userId: botUserId } = gate.bot++ const db = getDb(ctx.env.DB)++ const snapshot = await withD1Retry(+ () => queries.communityAgentInbox.getInboxSnapshotForAgent(db, botUserId),+ { route: "community/users/me/inbox/snapshot:snapshot" },+ )+ const rows = await withD1Retry(+ () => queries.communityAgentInbox.toInboxRows(db, snapshot, botUserId),+ { route: "community/users/me/inbox/snapshot:rows" },+ )++ return NextResponse.json({+ rows,+ pendingChannels: rows.length,+ pendingMessages: rows.reduce((n, r) => n + r.pendingCount, 0),+ })+})diff --git a/src/web/src/app/api/community/inbox/unreads/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.tssimilarity index 92%rename from src/web/src/app/api/community/inbox/unreads/read-all/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.tsindex 57a3c8ecf..07a0cd099 100644--- a/src/web/src/app/api/community/inbox/unreads/read-all/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts@@ -39,7 +39,7 @@ vi.mock("@/lib/middleware/helpers", () => {import { POST } from "./route"-describe("POST /api/community/inbox/unreads/read-all", () => {+describe("POST /api/community/users/me/inbox/unreads/read-all", () => {beforeEach(() => {vi.clearAllMocks()mockListVisibleChannelIds.mockResolvedValue(["c1", "c2"])@@ -49,7 +49,7 @@ describe("POST /api/community/inbox/unreads/read-all", () => {// Post-invariant: count == channels that actually received an aligned// write. Empty channels are skipped, so this is <= reachable-channel count.mockMarkAllServerChannelsRead.mockResolvedValue(7)- const res = await POST(new NextRequest("http://localhost/api/community/inbox/unreads/read-all", { method: "POST" }))+ const res = await POST(new NextRequest("http://localhost/api/community/users/me/inbox/unreads/read-all", { method: "POST" }))const body = await res.json()expect(res.status).toBe(200)expect(body).toEqual({ ok: true, count: 7 })@@ -59,7 +59,7 @@ describe("POST /api/community/inbox/unreads/read-all", () => {it("returns count 0 when every channel is empty (nothing to write)", async () => {mockMarkAllServerChannelsRead.mockResolvedValue(0)- const res = await POST(new NextRequest("http://localhost/api/community/inbox/unreads/read-all", { method: "POST" }))+ const res = await POST(new NextRequest("http://localhost/api/community/users/me/inbox/unreads/read-all", { method: "POST" }))const body = await res.json()expect(res.status).toBe(200)expect(body).toEqual({ ok: true, count: 0 })diff --git a/src/web/src/app/api/community/inbox/unreads/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.tssimilarity index 88%rename from src/web/src/app/api/community/inbox/unreads/read-all/route.tsrename to src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.tsindex a0645f97c..c9b2749cc 100644--- a/src/web/src/app/api/community/inbox/unreads/read-all/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts@@ -5,7 +5,7 @@ import { writeJSON } from "@/lib/middleware/helpers"export const POST = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)- // Resolve the viewer's visible channels once (top-level + threads/forum-posts,+ // Resolve the viewer's visible channels once (top-level + child threads,// parent-climbed) and scope the mark-all to them — a private thread under an// invisible parent is excluded.const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)diff --git a/src/web/src/app/api/community/inbox/unreads/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.tssimilarity index 69%rename from src/web/src/app/api/community/inbox/unreads/route.test.tsrename to src/web/src/app/api/community/users/me/inbox/unreads/route.test.tsindex a0696721c..fface1bb4 100644--- a/src/web/src/app/api/community/inbox/unreads/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mockListUnreadChannels = vi.fn()+const mockListUnreadForumOpeners = vi.fn()const mockGetSettings = vi.fn()const mockListUnreadMentions = vi.fn()const mockListUnreadDms = vi.fn()@@ -21,6 +22,7 @@ vi.mock("@alook/shared", async () => {queries: {communityInbox: {listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),+ listUnreadForumOpeners: (...args: unknown[]) => mockListUnreadForumOpeners(...args),listUnreadDms: (...args: unknown[]) => mockListUnreadDms(...args),},communityNotificationSetting: {@@ -68,12 +70,32 @@ function row(overrides: Partial<{ channelId: string; channelName: string; server}}-describe("GET /api/community/inbox/unreads", () => {+function opener(overrides: Partial<{+ forumChannelId: string+ openerMessageId: string+ childChannelId: string+ title: string+ createdAt: string+ openerSeq: number+}> = {}) {+ return {+ forumChannelId: "f1",+ openerMessageId: "m1",+ childChannelId: "p1",+ title: "Full opener content",+ createdAt: "2026-06-25T10:00:00Z",+ openerSeq: 1,+ ...overrides,+ }+}++describe("GET /api/community/users/me/inbox/unreads", () => {beforeEach(() => {vi.clearAllMocks()mockGetSettings.mockResolvedValue([])mockListUnreadMentions.mockResolvedValue([])mockListUnreadDms.mockResolvedValue([])+ mockListUnreadForumOpeners.mockResolvedValue([])mockListVisibleChannelIds.mockResolvedValue([])mockGetChannelsByIds.mockResolvedValue([])})@@ -85,7 +107,7 @@ describe("GET /api/community/inbox/unreads", () => {row({ serverId: "s2", serverName: "Other", channelId: "c3", channelName: "lounge", lastMessageAt: "2026-06-25T11:00:00Z" }),])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(res.status).toBe(200)@@ -104,7 +126,7 @@ describe("GET /api/community/inbox/unreads", () => {])mockGetSettings.mockResolvedValue([{ serverId: "s1", channelId: null, level: "nothing" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers.map((s: { serverId: string }) => s.serverId)).toEqual(["s2"])@@ -117,7 +139,7 @@ describe("GET /api/community/inbox/unreads", () => {])mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "c2", level: "nothing" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels.map((c: { channelId: string }) => c.channelId)).toEqual(["c1"])@@ -130,7 +152,7 @@ describe("GET /api/community/inbox/unreads", () => {{ message: { channelId: "c1" } },{ message: { channelId: "c-other" } },])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].mentionCount).toBe(2)})@@ -143,7 +165,7 @@ describe("GET /api/community/inbox/unreads", () => {row({ serverId: "s1", channelId: "c3", lastMessageAt: "2026-06-25T10:00:00Z" }),])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads?limit=2"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=2"))const body = await res.json()expect(body.limit).toBe(2)@@ -153,7 +175,7 @@ describe("GET /api/community/inbox/unreads", () => {it("reports truncated=false when total channel count fits the limit", async () => {mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads?limit=10"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=10"))const body = await res.json()expect(body.truncated).toBe(false)})@@ -165,7 +187,7 @@ describe("GET /api/community/inbox/unreads", () => {{ channelId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(res.status).toBe(200)@@ -180,7 +202,7 @@ describe("GET /api/community/inbox/unreads", () => {it("returns empty dms array when only channels are unread", async () => {mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])mockListUnreadDms.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.dms).toEqual([])expect(body.servers).toHaveLength(1)@@ -191,7 +213,7 @@ describe("GET /api/community/inbox/unreads", () => {mockListUnreadDms.mockResolvedValue([{ channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers).toHaveLength(1)expect(body.dms).toHaveLength(1)@@ -207,7 +229,7 @@ describe("GET /api/community/inbox/unreads", () => {])mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(res.status).toBe(200)@@ -225,7 +247,7 @@ describe("GET /api/community/inbox/unreads", () => {row({ channelId: "c1", channelName: "general", lastMessageAt: "2026-06-25T10:00:00Z" }),row({ channelId: "t1", channelName: "budget-2026", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()// Parent was already present → no getChannelsByIds resolve needed.expect(mockGetChannelsByIds).not.toHaveBeenCalled()@@ -243,7 +265,7 @@ describe("GET /api/community/inbox/unreads", () => {{ message: { channelId: "t1" } },{ message: { channelId: "t1" } },])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].children[0].mentionCount).toBe(2)})@@ -255,7 +277,7 @@ describe("GET /api/community/inbox/unreads", () => {mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])// Parent c1 muted → the whole subtree is suppressed.mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "c1", level: "nothing" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers).toHaveLength(0)})@@ -268,7 +290,7 @@ describe("GET /api/community/inbox/unreads", () => {row({ channelId: "t1", channelName: "thread-1", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),row({ channelId: "t2", channelName: "thread-2", parentChannelId: "c1", lastMessageAt: "2026-06-25T10:00:00Z" }),])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads?limit=2"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=2"))const body = await res.json()expect(body.truncated).toBe(true)const parent = body.servers[0].channels[0]@@ -279,7 +301,7 @@ describe("GET /api/community/inbox/unreads", () => {it("top-level channels carry an empty children array", async () => {mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].children).toEqual([])})@@ -291,7 +313,7 @@ describe("GET /api/community/inbox/unreads", () => {row({ channelId: "c1", channelName: "general", type: "text" }),row({ channelId: "c2", channelName: "help-forum", type: "forum", lastMessageAt: "2026-06-25T09:00:00Z" }),])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()const byId = Object.fromEntries(body.servers[0].channels.map((c: { channelId: string; type?: string }) => [c.channelId, c.type]),@@ -304,7 +326,7 @@ describe("GET /api/community/inbox/unreads", () => {row({ channelId: "c1", channelName: "general", type: "text" }),row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()const parent = body.servers[0].channels[0]expect(parent.type).toBe("text")@@ -316,8 +338,100 @@ describe("GET /api/community/inbox/unreads", () => {row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1" }),])mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "help-forum", serverId: "s1", type: "forum" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].type).toBe("forum")})++ // ── Per-post forum opener projection ──────────────────────────────────────++ it("queries only visible, direct-unread, unmuted top-level forum parents", async () => {+ mockListVisibleChannelIds.mockResolvedValue(["f1", "f2", "text1", "post1"])+ mockListUnreadChannels.mockResolvedValue([+ row({ channelId: "f1", channelName: "Forum 1", type: "forum" }),+ row({ channelId: "f2", channelName: "Muted forum", type: "forum" }),+ row({ channelId: "text1", channelName: "Text", type: "text" }),+ row({ channelId: "post1", channelName: "Post", type: "thread", parentChannelId: "f1" }),+ ])+ mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "f2", level: "nothing" }])++ await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))++ expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "u1", ["f1", "f2", "text1", "post1"])+ expect(mockListUnreadForumOpeners).toHaveBeenCalledWith(expect.anything(), "u1", ["f1"])+ })++ it("renders every unread opener as a separately titled child row, newest first", async () => {+ mockListUnreadChannels.mockResolvedValue([+ row({ channelId: "f1", channelName: "Forum", type: "forum", lastMessageAt: "2026-06-25T11:00:00Z" }),+ ])+ mockListUnreadForumOpeners.mockResolvedValue([+ opener({ openerMessageId: "m2", childChannelId: "p2", title: "Second full opener", createdAt: "2026-06-25T11:00:00Z", openerSeq: 2 }),+ opener({ openerMessageId: "m1", childChannelId: "p1", title: "First full opener", createdAt: "2026-06-25T10:00:00Z", openerSeq: 1 }),+ ])++ const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()+ const children = body.servers[0].channels[0].children+ expect(children.map((child: { channelId: string; channelName: string; openerMessageId: string }) => ({+ channelId: child.channelId,+ title: child.channelName,+ openerMessageId: child.openerMessageId,+ }))).toEqual([+ { channelId: "p2", title: "Second full opener", openerMessageId: "m2" },+ { channelId: "p1", title: "First full opener", openerMessageId: "m1" },+ ])+ })++ it("dedupes an unread opener and child replies by childChannelId while retaining the parent target", async () => {+ mockListUnreadChannels.mockResolvedValue([+ row({ channelId: "f1", channelName: "Forum", type: "forum", lastMessageAt: "2026-06-25T10:00:00Z" }),+ row({ channelId: "p1", channelName: "Derived title", type: "thread", parentChannelId: "f1", lastMessageAt: "2026-06-25T12:00:00Z" }),+ ])+ mockListUnreadForumOpeners.mockResolvedValue([+ opener({ title: "Canonical opener title", createdAt: "2026-06-25T10:00:00Z", openerSeq: 7 }),+ ])+ mockListUnreadMentions.mockResolvedValue([+ { message: { channelId: "p1" } },+ { message: { channelId: "p1" } },+ ])++ const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()+ const children = body.servers[0].channels[0].children+ expect(children).toHaveLength(1)+ expect(children[0]).toMatchObject({+ channelId: "p1",+ channelName: "Canonical opener title",+ openerMessageId: "m1",+ lastMessageAt: "2026-06-25T12:00:00Z",+ mentionCount: 2,+ })+ })++ it("drops opener rows whose child channel is individually muted", async () => {+ mockListUnreadChannels.mockResolvedValue([+ row({ channelId: "f1", channelName: "Forum", type: "forum" }),+ ])+ mockListUnreadForumOpeners.mockResolvedValue([opener()])+ mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "p1", level: "nothing" }])++ const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()+ expect(body.servers[0].channels[0].children).toEqual([])+ })++ it("uses opener seq/id as deterministic tie-breaks before child cap truncation", async () => {+ mockListUnreadChannels.mockResolvedValue([+ row({ channelId: "f1", channelName: "Forum", type: "forum" }),+ ])+ mockListUnreadForumOpeners.mockResolvedValue([+ opener({ openerMessageId: "m1", childChannelId: "p1", openerSeq: 1 }),+ opener({ openerMessageId: "m3", childChannelId: "p3", openerSeq: 3 }),+ opener({ openerMessageId: "m2", childChannelId: "p2", openerSeq: 2 }),+ ])++ const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=3"))).json()+ expect(body.truncated).toBe(true)+ // Parent consumes one row; the two newest equal-time openers consume the+ // remaining rows in stable seq order.+ expect(body.servers[0].channels[0].children.map((child: { channelId: string }) => child.channelId)).toEqual(["p3", "p2"])+ })})diff --git a/src/web/src/app/api/community/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.tssimilarity index 66%rename from src/web/src/app/api/community/inbox/unreads/route.tsrename to src/web/src/app/api/community/users/me/inbox/unreads/route.tsindex e9a05784b..9fdaf5711 100644--- a/src/web/src/app/api/community/inbox/unreads/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts@@ -11,6 +11,19 @@ import { writeJSON } from "@/lib/middleware/helpers"import { parseBoundedInt } from "@/lib/community/messages"import { avatarInitial } from "@/lib/community/avatar"+function notificationMuteSets(+ settings: Array<{ level: string; serverId: string | null; channelId: string | null }>,+) {+ const mutedServers = new Set<string>()+ const mutedChannels = new Set<string>()+ for (const setting of settings) {+ if (setting.level !== "nothing") continue+ if (setting.channelId) mutedChannels.add(setting.channelId)+ else if (setting.serverId) mutedServers.add(setting.serverId)+ }+ return { mutedServers, mutedChannels }+}+export const GET = withAuth(async (req, ctx) => {const db = getDb(ctx.env.DB)const url = new URL(req.url)@@ -20,18 +33,20 @@ export const GET = withAuth(async (req, ctx) => {MAX_INBOX_PAGE_SIZE,)- // Resolve the viewer's visible channels once (top-level + threads/forum-posts,+ // Resolve the viewer's visible channels once (top-level + child threads,// parent-climbed) and thread the id set into BOTH consumers so neither// recomputes it. Private threads under an invisible parent are excluded.type UnreadRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadChannels>>[number]type SettingRow = Awaited<ReturnType<typeof queries.communityNotificationSetting.getSettings>>[number]type MentionRow = Awaited<ReturnType<typeof queries.communityMention.listUnreadMentions>>[number]type UnreadDmRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadDms>>[number]+ type ForumOpenerRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadForumOpeners>>[number]const { value: fetched, stale } = await readOrStale<{unread: UnreadRow[]settings: SettingRow[]mentions: MentionRow[]unreadDms: UnreadDmRow[]+ forumOpeners: ForumOpenerRow[]}>(async () => {const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)@@ -41,23 +56,37 @@ export const GET = withAuth(async (req, ctx) => {queries.communityMention.listUnreadMentions(db, ctx.userId, { visibleChannelIds }),queries.communityInbox.listUnreadDms(db, ctx.userId),])- return { unread, settings, mentions, unreadDms }+ // Expand only top-level forum parents that have already passed the+ // visibility and notification-mute gates. The shared query receives no+ // global discovery surface — just this bounded parent id set.+ const { mutedServers, mutedChannels } = notificationMuteSets(settings)+ const forumParentIds = [...new Set(+ unread+ .filter(+ (row) =>+ !row.parentChannelId &&+ row.type === "forum" &&+ !mutedServers.has(row.serverId) &&+ !mutedChannels.has(row.channelId),+ )+ .map((row) => row.channelId),+ )]+ const forumOpeners = await queries.communityInbox.listUnreadForumOpeners(+ db,+ ctx.userId,+ forumParentIds,+ )+ return { unread, settings, mentions, unreadDms, forumOpeners }},- { unread: [], settings: [], mentions: [], unreadDms: [] },+ { unread: [], settings: [], mentions: [], unreadDms: [], forumOpeners: [] },{ route: "community/inbox/unreads" },)if (stale) {return writeJSON({ servers: [], dms: [], limit, truncated: false, stale: true })}- const { unread, settings, mentions, unreadDms } = fetched+ const { unread, settings, mentions, unreadDms, forumOpeners } = fetched- const mutedServers = new Set<string>()- const mutedChannels = new Set<string>()- for (const s of settings) {- if (s.level !== "nothing") continue- if (s.channelId) mutedChannels.add(s.channelId)- else if (s.serverId) mutedServers.add(s.serverId)- }+ const { mutedServers, mutedChannels } = notificationMuteSets(settings)const mentionCountByChannel = new Map<string, number>()for (const m of mentions) {@@ -66,10 +95,20 @@ export const GET = withAuth(async (req, ctx) => {mentionCountByChannel.set(cid, (mentionCountByChannel.get(cid) ?? 0) + 1)}- // Split unread rows into top-level channels and child threads/forum-posts.+ // Split unread rows into top-level channels and child threads.// A child nests under its `parentChannelId`; a parent surfaces in the tree// even when it has no direct unread of its own (only unread children).- type UnreadChild = { channelId: string; channelName: string; type: string | null; lastMessageAt: string; mentionCount: number }+ type UnreadChild = {+ channelId: string+ channelName: string+ type: string | null+ lastMessageAt: string+ mentionCount: number+ openerMessageId?: string+ // Private stable-order fields. They are removed from the response below.+ sortSeq: number+ sortId: string+ }type ParentNode = {channelId: stringchannelName: string@@ -83,26 +122,28 @@ export const GET = withAuth(async (req, ctx) => {}const parents = new Map<string, ParentNode>()- const childrenByParent = new Map<string, UnreadChild[]>()+ const childrenByParent = new Map<string, Map<string, UnreadChild>>()for (const row of unread) {if (!row.serverId || !row.channelId || !row.serverName || !row.channelName) continueif (mutedServers.has(row.serverId)) continueif (row.parentChannelId) {- // Child (thread / forum-post). Skip if the child itself is muted; the+ // Child thread. Skip if the child itself is muted; the// parent-mute cascade is applied later (once we know which parents are// muted) so a child under a muted parent is dropped even if it isn't// individually muted.if (mutedChannels.has(row.channelId)) continue- const list = childrenByParent.get(row.parentChannelId) ?? []- list.push({+ const children = childrenByParent.get(row.parentChannelId) ?? new Map<string, UnreadChild>()+ children.set(row.channelId, {channelId: row.channelId,channelName: row.channelName,type: row.type,lastMessageAt: row.lastMessageAt,mentionCount: mentionCountByChannel.get(row.channelId) ?? 0,+ sortSeq: 0,+ sortId: row.channelId,})- childrenByParent.set(row.parentChannelId, list)+ childrenByParent.set(row.parentChannelId, children)} else {if (mutedChannels.has(row.channelId)) continueparents.set(row.channelId, {@@ -119,6 +160,41 @@ export const GET = withAuth(async (req, ctx) => {}}+ // Project unread parent openers as post rows. An opener and unread replies+ // for the same post share one childChannelId, so merge them into one row+ // while retaining the opener id as the parent forum's progressive-read+ // target. The authoritative title is supplied by the opener query.+ for (const opener of forumOpeners) {+ if (mutedChannels.has(opener.childChannelId)) continue+ const parent = parents.get(opener.forumChannelId)+ if (!parent || mutedServers.has(parent.serverId) || mutedChannels.has(parent.channelId)) continue++ const children = childrenByParent.get(opener.forumChannelId) ?? new Map<string, UnreadChild>()+ const existing = children.get(opener.childChannelId)+ if (existing) {+ existing.channelName = opener.title+ existing.type = existing.type ?? "thread"+ existing.openerMessageId = opener.openerMessageId+ if (opener.createdAt >= existing.lastMessageAt) {+ existing.lastMessageAt = opener.createdAt+ existing.sortSeq = opener.openerSeq+ existing.sortId = opener.openerMessageId+ }+ } else {+ children.set(opener.childChannelId, {+ channelId: opener.childChannelId,+ channelName: opener.title,+ type: "thread",+ lastMessageAt: opener.createdAt,+ mentionCount: mentionCountByChannel.get(opener.childChannelId) ?? 0,+ openerMessageId: opener.openerMessageId,+ sortSeq: opener.openerSeq,+ sortId: opener.openerMessageId,+ })+ }+ childrenByParent.set(opener.forumChannelId, children)+ }+// Parents that have an unread child but no direct unread aren't in `unread`,// so their name isn't available — batch-resolve them. `getChannelsByIds` has// no visibility filter, but that's fine: the child already passed visibility,@@ -156,7 +232,7 @@ export const GET = withAuth(async (req, ctx) => {for (const [pid, kids] of childrenByParent) {const parent = parents.get(pid)if (!parent) continue // parent muted or unresolved → drop the subtree- parent.children.push(...kids)+ parent.children.push(...kids.values())}// Resolved-only parents (unread child, no direct unread) need serverName + a@@ -178,7 +254,12 @@ export const GET = withAuth(async (req, ctx) => {for (const parent of parents.values()) {if (!parent.hasDirectUnread && parent.children.length === 0) continueif (!parent.serverName) continue- parent.children.sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))+ parent.children.sort(+ (a, b) =>+ b.lastMessageAt.localeCompare(a.lastMessageAt) ||+ b.sortSeq - a.sortSeq ||+ b.sortId.localeCompare(a.sortId),+ )let bucket = grouped.get(parent.serverId)if (!bucket) {bucket = { serverId: parent.serverId, serverName: parent.serverName, channels: [] }@@ -191,14 +272,26 @@ export const GET = withAuth(async (req, ctx) => {serverId: g.serverId,serverName: g.serverName,channels: g.channels- .sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))+ .sort(+ (a, b) =>+ b.lastMessageAt.localeCompare(a.lastMessageAt) ||+ b.channelId.localeCompare(a.channelId),+ ).map((c) => ({channelId: c.channelId,channelName: c.channelName,type: c.type ?? undefined,lastMessageAt: c.lastMessageAt,mentionCount: c.mentionCount,- children: c.children.map((k) => ({ ...k, type: k.type ?? undefined })),+ hasDirectUnread: c.hasDirectUnread,+ children: c.children.map((k) => ({+ channelId: k.channelId,+ channelName: k.channelName,+ type: k.type ?? undefined,+ lastMessageAt: k.lastMessageAt,+ mentionCount: k.mentionCount,+ ...(k.openerMessageId ? { openerMessageId: k.openerMessageId } : {}),+ })),})),}))allServers.sort((a, b) => {diff --git a/src/web/src/app/api/community/inbox/marked/route.test.ts b/src/web/src/app/api/community/users/me/marks/route.test.tssimilarity index 93%rename from src/web/src/app/api/community/inbox/marked/route.test.tsrename to src/web/src/app/api/community/users/me/marks/route.test.tsindex 9eab82ff4..172f385cc 100644--- a/src/web/src/app/api/community/inbox/marked/route.test.ts+++ b/src/web/src/app/api/community/users/me/marks/route.test.ts@@ -52,7 +52,7 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"-describe("GET /api/community/inbox/marked", () => {+describe("GET /api/community/users/me/marks", () => {beforeEach(() => {vi.clearAllMocks()mockGetChannelsByIds.mockResolvedValue([])@@ -63,7 +63,7 @@ describe("GET /api/community/inbox/marked", () => {it("scopes the query to the viewer's visible channels (no leak of left private channels)", async () => {mockListMarksForUser.mockResolvedValue([])- await GET(new NextRequest("http://localhost/api/community/inbox/marked"))+ await GET(new NextRequest("http://localhost/api/community/users/me/marks"))const opts = mockListMarksForUser.mock.calls[0][2]expect(opts.visibleChannelIds).toEqual(["c1"])})@@ -75,7 +75,7 @@ describe("GET /api/community/inbox/marked", () => {mockListVisibleChannelIds.mockResolvedValue(["c1"])mockListDmChannelIds.mockResolvedValue(["dm1"])mockListMarksForUser.mockResolvedValue([])- await GET(new NextRequest("http://localhost/api/community/inbox/marked"))+ await GET(new NextRequest("http://localhost/api/community/users/me/marks"))const opts = mockListMarksForUser.mock.calls[0][2]expect(opts.visibleChannelIds).toEqual(["c1", "dm1"])})@@ -91,7 +91,7 @@ describe("GET /api/community/inbox/marked", () => {mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/marked"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/marks"))const body = await res.json()expect(body.marked).toHaveLength(1)expect(body.marked[0]).toMatchObject({@@ -109,13 +109,13 @@ describe("GET /api/community/inbox/marked", () => {it("returns empty marked array when none", async () => {mockListMarksForUser.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/marked"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/marks"))expect((await res.json()).marked).toEqual([])})it("clamps over-cap limit and forwards it to the query", async () => {mockListMarksForUser.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/marked?limit=99999"))+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/marks?limit=99999"))const body = await res.json()expect(body.limit).toBe(200) // MAX_INBOX_PAGE_SIZEexpect(mockListMarksForUser).toHaveBeenCalledWith({}, "u1", { limit: 200, visibleChannelIds: ["c1"] })diff --git a/src/web/src/app/api/community/inbox/marked/route.ts b/src/web/src/app/api/community/users/me/marks/route.tssimilarity index 98%rename from src/web/src/app/api/community/inbox/marked/route.tsrename to src/web/src/app/api/community/users/me/marks/route.tsindex 62b2d9a99..301c4ad51 100644--- a/src/web/src/app/api/community/inbox/marked/route.ts+++ b/src/web/src/app/api/community/users/me/marks/route.ts@@ -56,7 +56,7 @@ export const GET = withAuth(async (req, ctx) => {return { rows, channels, servers }},{ rows: [], channels: [], servers: [] },- { route: "community/inbox/marked" },+ { route: "community/marks" },)if (stale) {return writeJSON({ marked: [], limit, stale: true })diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.tsindex efa40393d..363cebed8 100644--- a/src/web/src/app/api/community/users/me/profile/route.ts+++ b/src/web/src/app/api/community/users/me/profile/route.ts@@ -7,6 +7,7 @@ import {BANNER_COLOR_REGEX,WS_EVENTS,validateCommunityName,+ withD1Retry,} from "@alook/shared"import { getDb } from "@/lib/db"import { createAuth } from "@/lib/auth"@@ -17,8 +18,14 @@ import { fanOutStatusUpdate, fanOutToServerMembers } from "@/lib/community/fanouexport const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)const [profile, viewer] = await Promise.all([- queries.communityUserProfile.getProfile(db, ctx.userId),- queries.user.getUserSelf(db, ctx.userId),+ withD1Retry(+ () => queries.communityUserProfile.getProfile(db, ctx.userId),+ { route: "community/profile:self-profile" }+ ),+ withD1Retry(+ () => queries.user.getUserSelf(db, ctx.userId),+ { route: "community/profile:self-user" }+ ),])return writeJSON({aboutMe: profile?.aboutMe ?? "",diff --git a/src/web/src/app/api/community/server-folders/[id]/route.ts b/src/web/src/app/api/community/users/me/server-folders/[id]/route.tssimilarity index 100%rename from src/web/src/app/api/community/server-folders/[id]/route.tsrename to src/web/src/app/api/community/users/me/server-folders/[id]/route.tsdiff --git a/src/web/src/app/api/community/server-folders/reorder/route.ts b/src/web/src/app/api/community/users/me/server-folders/reorder/route.tssimilarity index 100%rename from src/web/src/app/api/community/server-folders/reorder/route.tsrename to src/web/src/app/api/community/users/me/server-folders/reorder/route.tsdiff --git a/src/web/src/app/api/community/server-folders/route.ts b/src/web/src/app/api/community/users/me/server-folders/route.tssimilarity index 100%rename from src/web/src/app/api/community/server-folders/route.tsrename to src/web/src/app/api/community/users/me/server-folders/route.tsdiff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex 307dc8d71..07dba70f2 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -1,1382 +1,10 @@"use client"-import { useCallback, useEffect, useMemo, useRef, useState } from "react"-import { useParams, useRouter, useSearchParams } from "next/navigation"-import { toast } from "sonner"-import { apiFetch, toastApiError } from "@/lib/api/client"-import { ApiError } from "@/lib/errors"-import { useBreakpoint } from "@/hooks/use-mobile"-import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"-import { MessageList } from "@/components/community/message-list"-import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"-import { ForumView, ForumViewSkeleton } from "@/components/community/forum-view"-import type { NewForumPost } from "@/components/community/create-forum-post"-import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"-import { MessageContextSheet } from "@/components/community/message-context-sheet"-import { ThreadOpener } from "@/components/community/thread-opener"-import { AddMembersDialog } from "@/components/community/add-members-dialog"-import type { RightPanel, Msg, OpenProfile, Role } from "@/components/community/_types"-import { canManageServer } from "@/components/community/_types"-import type { MentionType } from "@alook/shared"-import { isForum as isForumType, deriveThreadName, USE_SERVER_DEFAULT } from "@alook/shared"-import { resolveRowPresence } from "@/lib/community/presence"-import { setLastChannel, getLastChannel, clearLastChannel } from "@/lib/community/last-channel"-import { makeUserNameResolver } from "@/lib/community/display-name"-import { avatarInitial } from "@/lib/community/avatar"-import {- useCommunityStore,- useCurrentChannelId,- useCurrentChannelMeta,- useUiHandlers,- useTypingUsersForScope,- useTypingNamesForScope,-} from "@/stores/community"-import { useCurrentUser } from "@/contexts/community/current-user"-import { useServer } from "@/hooks/community/use-servers"-import { useServerMembers } from "@/hooks/community/use-server-members"-import { useChannelMembers, useAddableMembers, useAddChannelMember, useRemoveChannelMember } from "@/hooks/community/use-channel-members"-import { useAddThreadParticipant, useRemoveThreadParticipant } from "@/hooks/community/use-thread-participants"-import { useMessages } from "@/hooks/community/use-messages"-import { useChannelReadStateSnapshot } from "@/hooks/community/use-channel-read-state"-import { useChannelBootstrap } from "@/hooks/community/use-channel-bootstrap"-import { useChannelWatermark } from "@/hooks/community/use-channel-watermark"-import { useEagerChannelRead } from "@/hooks/community/use-eager-channel-read"-import {- useThreads,- useForumPosts,- usePins,-} from "@/hooks/community/use-channel-panels"-import { useNotificationSettings } from "@/hooks/community/use-notification-settings"-import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"-import { useMessageStreamStore } from "@/stores/community/message-stream"-import {- useSendMessage,- useToggleReactionApi,- usePinMessage,- useUnpinMessage,- useToggleMark,- useCreateThread,- useCreateForumPost,- useUpdatePostTags,- useDeleteForumPost,- useSetMemberRole,- useKickMember,- useSetChannelNotif,- useUploadFile,- zipUploadResultsWithDimensions,- toAttachmentVm,- sendNonce,- tempMessageId,- type UploadedAttachment,-} from "@/hooks/community/mutations"-import {- communityWsSubscribe,- communityWsUnsubscribe,- communityWsSendTyping,- communityWsResetTypingThrottle,-} from "@/hooks/community/use-community-ws"+import { useParams } from "next/navigation"+import { ChannelRoute } from "@/components/community/channel-route"-/**- * /c/channels/:serverId/:channelId- *- * - Forum channel: ForumView- * - Text channel: MessageList + Composer + right panels- * - Thread / forum-post opened via URL: child-channel view (breadcrumb + list)- */export default function ChannelPage() {const params = useParams<{ serverId: string; channelId: string }>()const key = `${params.serverId}/${params.channelId}`- return <ChannelView key={key} />-}--function ChannelView() {- const params = useParams<{ serverId: string; channelId: string }>()- const router = useRouter()- const searchParams = useSearchParams()- const serverId = decodeURIComponent(params.serverId)- const channelId = params.channelId- // Remember this as the server's last-opened channel (per-browser navigation- // memory) so re-entering the server restores here instead of the default.- // Pure localStorage write; failures are swallowed in the helper.- useEffect(() => {- setLastChannel(serverId, channelId)- }, [serverId, channelId])- // Cross-channel "jump to message" target, captured ONCE at mount from `?msg=`.- // `ChannelView` is keyed by `serverId/channelId`, so a fresh jump remounts and- // re-reads this. The param is stripped from the URL right after (below) so a- // refresh/back doesn't re-trigger the jump; this frozen copy still drives the- // anchor + scroll for this mount.- const [jumpTargetId] = useState<string | null>(() => searchParams.get("msg"))- const bp = useBreakpoint()- const currentUser = useCurrentUser()- const uiHandlers = useUiHandlers()- const currentChannelId = useCurrentChannelId()- const currentChannelMeta = useCurrentChannelMeta()-- const { server: currentServer } = useServer(serverId)- const membersHook = useServerMembers(serverId)- const onlineUserIds = useOnlineUserIds()- const userStatuses = useCommunityWsStore((s) => s.userStatuses)- // Members enriched with presence — used by the message list's typingUsers- // resolution and the panel roster to render the correct dot.- const members = useMemo(- () =>- membersHook.members.map((m) => {- const liveStatus = userStatuses.get(m.userId)- return {- ...m,- status: resolveRowPresence(m, onlineUserIds, currentUser.id),- statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,- statusText: liveStatus ? liveStatus.text : m.statusText,- }- }),- [membersHook.members, onlineUserIds, currentUser.id, userStatuses],- )- // Type-gate the forum-posts fetch: only forum channels have a valid- // /posts endpoint; text channels return 400. Compute the flag BEFORE the- // hook call so `useForumPosts` can stay disabled for non-forum channels.- const channelInServer = useMemo(() => {- const allChannels = currentServer?.categories?.flatMap((c) => c.channels) ?? []- return allChannels.find((ch) => ch.id === channelId) ?? null- }, [currentServer, channelId])- const isForum = isForumType(channelInServer?.type)- const isChildChannel = !channelInServer && !!currentServer?.categories- // A thread (child channel rooted on a `parentMessageId`) and a forum post- // (child channel with no `parentMessageId`) are both the NOTIFICATION- // dimension: their drawer shows PARTICIPANTS (not an access audience), their- // add button adds a PARTICIPANT, and their @-mention pool is the parent- // channel/forum's members. Since every child channel is one or the other,- // `isNotifyUnit === isChildChannel` — a load-stable value that doesn't flip- // while `currentChannelMeta` hydrates. The thread/post distinction affects- // only labels, handled inline, so a single flag drives all behavior here.- const isNotifyUnit = isChildChannel-- // Local filter for the private-channel Members drawer (the channel audience is- // small, so search is client-side — no scoped search endpoint).- const [memberQuery, setMemberQuery] = useState("")- // Whether the manage-members dialog is open (Add button in the private drawer).- const [manageMembersOpen, setManageMembersOpen] = useState(false)-- // Is the current channel (or its anchor, for a thread) inside a PRIVATE- // category? Drives the Members drawer's data source: private → the channel- // audience via `useChannelMembers`; public → the server roster. The server- // re-checks privacy anyway (`requireChannelAccess`), so an over-eager `true`- // only risks calling the channel endpoint when it wasn't needed — safe.- const currentChannelPrivate = useMemo(() => {- const cats = currentServer?.categories ?? []- // Thread/forum-post: privacy is governed by the anchor channel's category.- const anchorId = isChildChannel- ? (currentChannelMeta?.parentChannelId ?? channelId)- : channelId- const cat = cats.find((c) => c.channels.some((ch) => ch.id === anchorId))- return !!cat?.private- }, [currentServer, isChildChannel, currentChannelMeta, channelId])- // Members drawer read: `/members` for BOTH a private channel and a notify- // unit (thread/post). For a notify unit `/members` resolves the NOTIFY- // (participant) set — same people the old `/participants` read returned — but- // in the unified `MappedMember` shape (status/role/isCreator), so a post's- // panel matches a channel's. A public top-level channel still uses the server- // roster (`members`), so the hook stays gated to private-or-notify-unit.- const channelMembersHook = useChannelMembers(channelId, isNotifyUnit || (currentChannelPrivate && !isNotifyUnit))- const removeThreadParticipantMut = useRemoveThreadParticipant(channelId)- const addThreadParticipantMut = useAddThreadParticipant(channelId)- // Top-level channel/forum add-picker source + mutations (add: any member).- // W-LAZY (necessity plan): the addable-members list feeds ONLY the "add- // members" dialog, so fetch it only while that dialog is open — not eagerly- // on channel open. `manageMembersOpen` gates both the dialog's render and- // this fetch, so opening the dialog triggers the fetch and a plain channel- // switch never does.- const addableChannelMembers = useAddableMembers(- channelId,- manageMembersOpen && currentChannelPrivate && !isNotifyUnit,- )- const addChannelMemberMut = useAddChannelMember(channelId)- const removeChannelMemberMut = useRemoveChannelMember(channelId)- // Notify-unit add-picker source = the parent channel/forum's roster (minus- // current participants + self, computed at dialog build). A thread's parent is- // its channel; a post's parent is its forum. Enabled for both.- const threadParentId = isNotifyUnit ? (currentChannelMeta?.parentChannelId ?? null) : null- const parentChannelMembersHook = useChannelMembers(threadParentId ?? "", !!threadParentId)-- // Members shown in the right-panel Members drawer:- // - thread → its notify participants (mapped to the roster shape).- // - private channel/post → the resolved channel audience (locally filtered).- // - public → the server roster.- // All enriched with live presence for the correct dot.- const panelMembers = useMemo(() => {- const q = memberQuery.trim().toLowerCase()- const withPresence = (m: {- userId: string; name: string; discriminator: string; avatar: string- statusEmoji?: string | null; statusText?: string | null- isCreator?: boolean; source?: "explicit" | "inherited" | "admin"- }) => {- const liveStatus = userStatuses.get(m.userId)- return {- id: m.userId,- userId: m.userId,- name: m.name,- discriminator: m.discriminator,- avatar: m.avatar,- sub: "",- role: "member" as const,- status: resolveRowPresence(m, onlineUserIds, currentUser.id),- statusEmoji: liveStatus ? liveStatus.emoji : (m.statusEmoji ?? null),- statusText: liveStatus ? liveStatus.text : (m.statusText ?? ""),- isCreator: m.isCreator,- source: m.source,- }- }- const matches = (name: string, disc?: string | null) =>- !q || name.toLowerCase().includes(q) || (disc ?? "").toLowerCase().includes(q)-- if (isNotifyUnit) {- // Notify unit → the participant set, now read from `/members` in the- // unified shape (`isCreator` computed server-side against the unit's- // author). Participants are ALL real, creator-removable rows, so drop- // `source` to `undefined` — the notify set has no explicit/inherited/admin- // distinction, and MemberList treats `source === undefined` as removable- // (the same behavior the old `/participants` read gave).- return channelMembersHook.members- .filter((m) => matches(m.name, m.discriminator))- .map((m) => withPresence({ ...m, source: undefined }))- }- if (!currentChannelPrivate) return members- return channelMembersHook.members- .filter((m) => matches(m.name, m.discriminator))- .map((m) => withPresence(m))- }, [- isNotifyUnit,- currentChannelPrivate,- members,- channelMembersHook.members,- memberQuery,- onlineUserIds,- currentUser.id,- userStatuses,- ])-- // Roster passed to the @-mention popover — filters the viewer out.- // `members` still includes the viewer for the roster / typing lookup; only the- // composer needs to drop self (you can't @-mention yourself).- //- // Scoping (nested-membership model): in a private channel/post the popover- // lists only that unit's members; in a thread it lists the parent channel's- // members (the channel-members endpoint climbs a thread to its anchor). Public- // channels keep the whole-server roster. Uses `channelMembersHook.members`- // (unfiltered by the drawer's search box), enriched with live presence to- // match the server-roster path.- const composerMembers = useMemo(() => {- if (!currentChannelPrivate) {- return members.filter((m) => m.userId !== currentUser.id)- }- // Private unit: scope to the unit's roster. A thread/post has NO roster of- // its own — its `channelMembersHook` is disabled — so its mention candidates- // are the parent channel/forum's members (the same source the add-participant- // dialog uses). A private top-level channel/forum uses its own roster.- const scopedRoster = isNotifyUnit ? parentChannelMembersHook.members : channelMembersHook.members- return scopedRoster- .filter((m) => m.userId !== currentUser.id)- .map((m) => {- const liveStatus = userStatuses.get(m.userId)- return {- ...m,- status: resolveRowPresence(m, onlineUserIds, currentUser.id),- statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,- statusText: liveStatus ? liveStatus.text : m.statusText,- }- })- }, [- currentChannelPrivate,- isNotifyUnit,- members,- channelMembersHook.members,- parentChannelMembersHook.members,- onlineUserIds,- currentUser.id,- userStatuses,- ])-- // `/`-autocomplete candidates for both Composer call sites below — single- // server, so no directory hook needed here (see `me/[dmId]/page.tsx` for- // the cross-server DM case).- const channelRefCandidates = useMemo(() => {- const allChannels = currentServer?.categories?.flatMap((c) => c.channels) ?? []- return allChannels.map((ch) => ({- id: ch.id,- name: ch.name,- serverId,- serverName: currentServer?.name ?? "",- }))- }, [currentServer, serverId])- // A jump-open (?msg=) must anchor on the jump target, not the read pointer,- // so it keeps the legacy read-state → ?anchor=jump path. Otherwise use the- // combined bootstrap: ONE request resolves the read pointer AND seeds the- // initial message window, collapsing the old serial read-state → messages- // chain (see plans/community-switch-perf-optimization.md WS2).- const useBootstrap = !jumpTargetId- const bootstrap = useChannelBootstrap(channelId, { enabled: useBootstrap })- const legacySnapshot = useChannelReadStateSnapshot(useBootstrap ? null : channelId)-- // Frozen-once snapshot of the viewer's read pointer for this channel — the- // anchor for the "New" divider AND the mount-time initial scroll target.- // The value NEVER changes during the mount even as the watermark advances.- const readSnapshot = useBootstrap ? bootstrap.readState : legacySnapshot.snapshot- const readSnapshotFetching = useBootstrap ? bootstrap.isFetching : legacySnapshot.isFetching-- // Anchor the initial page on the read pointer so an unread-heavy channel- // opens with a centered window instead of the newest 50. Pass `undefined`- // while the pointer is still resolving — the hook stays disabled until- // the value settles (a bare `null` would fall back to newest-mode too- // early). On the bootstrap path the initial page is pre-seeded, so trust it- // and don't refetch page 0 on mount.- const messagesQuery = useMessages(channelId, {- serverId,- lastReadMessageId: readSnapshotFetching- ? undefined- : (readSnapshot?.lastReadMessageId ?? null),- anchorMessageId: jumpTargetId,- trustSeededInitialPage: useBootstrap && bootstrap.isReady,- })- const {- messages,- isLoading: messagesLoading,- hasMoreOlder: hasMoreMessages,- hasMoreNewer: hasMoreNewerMessages,- isFetchingOlder: isFetchingOlderMessages,- isFetchingNewer: isFetchingNewerMessages,- fetchOlder: fetchOlderMessages,- fetchNewer: fetchNewerMessages,- jumpToPresent,- latestSeq,- } = messagesQuery-- // The message immediately after the viewer's `lastReadMessageId` inside the- // current window. id-first: the invariant guarantees- // `getMessage(lastReadMessageId).createdAt === lastReadAt`, so we only need- // the id to find the anchor. `idx === -1` means the last-read message has- // scrolled off the top of the fetched window — no divider is shown.- //- // Skip past runs of viewer-authored messages. The frozen client snapshot- // doesn't move mid-mount, but the server DOES advance the sender's own- // watermark on every send (see `createMessage` in- // `src/shared/src/db/queries/community/message.ts`) — so without this- // walk, the divider anchors above the viewer's OWN just-sent message,- // which is never "unread" from the sender's perspective.- // `anchorFound` and `newDividerBefore` MUST be computed inside the same- // memo — they used to be two independently-evaluated expressions (a- // `.findIndex` here, a separate `.some` in `anchorInCache` below) that- // read the same `messages`/`readSnapshot` inputs but weren't guaranteed to- // agree on every commit. A real (Playwright-verified) repro showed `mount`- // firing on a frame where the anchor's presence check passed but this- // walk hadn't "caught up" yet, burning the one-shot scroll gate with- // `newDividerBefore: undefined` and permanently missing the divider.- // Deriving both from one loop makes that class of disagreement impossible.- const { newDividerBefore, anchorFound } = useMemo(() => {- if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }- const lastId = readSnapshot.lastReadMessageId- // First-visit case (viewer never read this channel): anchor the- // divider on the first non-self message so users landing from- // inbox / rail see "here's what you missed" instead of the bottom.- // Mirrors the DM view for parity. No anchor id to find — trivially "in- // cache".- if (!lastId) {- for (const m of messages) {- if (m.authorId !== currentUser.id) return { newDividerBefore: m.id, anchorFound: true }- }- return { newDividerBefore: undefined, anchorFound: true }- }- const idx = messages.findIndex((m) => m.id === lastId)- if (idx === -1) return { newDividerBefore: undefined, anchorFound: false }- for (let i = idx + 1; i < messages.length; i++) {- if (messages[i].authorId !== currentUser.id) return { newDividerBefore: messages[i].id, anchorFound: true }- }- return { newDividerBefore: undefined, anchorFound: true }- }, [messages, readSnapshot, currentUser.id])-- // Gates `<MessageList>`'s mount-time scroll action until the anchor- // (`readSnapshot.lastReadMessageId`) is actually present in the loaded- // `messages` — not just until the read-state fetch settles. Without this,- // a stale IDB-hydrated cache (or a same-session anchor drift, e.g.- // returning from a thread after the watermark advanced) can win the race- // against `useMessages`' Fix 3 re-validation: `useScrollAnchor`'s mount- // effect (a `useLayoutEffect`) runs before Fix 3's plain `useEffect` can- // reset the query, burns its one-shot gate on the wrong window, and never- // re-fires once the correct data arrives.- const anchorInCache = anchorFound-- // Scroll root of the message list — needed so `useChannelWatermark`'s- // IntersectionObserver measures against the correct viewport instead of- // the page's default viewport. Set once by `MessageList` via- // `onScrollRoot`.- const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)- useChannelWatermark({ channelId, messages, scrollRootEl })-- // Eager mark-read on open — clears this channel/thread from the inbox the- // moment it's opened, while the frozen `readSnapshot` above keeps the "New"- // divider anchored to the pre-open pointer. Gated on the snapshot having- // settled (fetching done; `null` = never-visited is a valid resolved state).- useEagerChannelRead({- channelId,- serverId,- isChildChannel,- snapshotReady: !readSnapshotFetching,- })-- // `↓ N` unread count for the anchor-window path — server truth- // (`latestSeq - viewerLastReadSeq`). Clamped to 0 in case the read- // pointer somehow overshot latestSeq (e.g. a bot updated latestSeq- // between the two fetches).- const unreadCount = useMemo(() => {- const seenSeq = readSnapshot?.lastReadSeq ?? 0- const diff = latestSeq - seenSeq- return diff > 0 ? diff : 0- }, [latestSeq, readSnapshot])-- const { threads, isLoading: threadsLoading } = useThreads(channelId)- const { posts: forumPosts, isLoading: forumPostsLoading } = useForumPosts(channelId, isForum)- const { pins: pinned, isLoading: pinnedLoading } = usePins(channelId)- const notifs = useNotificationSettings()- const channelNotif = notifs.channel- const typingUsers = useTypingUsersForScope(`ch:${channelId}`)- const typingNames = useTypingNamesForScope(`ch:${channelId}`)-- // Mutations- // Destructure the reference-STABLE mutation methods (TanStack binds- // `.mutate`/`.mutateAsync` in the observer, but returns a NEW wrapper object- // every render — depending on the whole object would bust every downstream- // useMemo/useCallback every render). See doSend / messageActions deps.- const { mutateAsync: sendMessageAsync } = useSendMessage()- const toggleReactionApi = useToggleReactionApi()- const { mutate: pinMessageMutate } = usePinMessage()- const { mutate: unpinMessageMutate } = useUnpinMessage()- const toggleMark = useToggleMark()- const { mutateAsync: createThreadAsync } = useCreateThread()- const createForumPostMut = useCreateForumPost()- const updatePostTagsMut = useUpdatePostTags()- const deleteForumPostMut = useDeleteForumPost()- const setMemberRoleMut = useSetMemberRole()- const kickMemberMut = useKickMember()- const setChannelNotifMut = useSetChannelNotif()- const { mutateAsync: uploadFileAsync } = useUploadFile()-- const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])-- // Set the current channel from URL params- useEffect(() => {- useCommunityStore.getState().setCurrentChannelId(channelId)- return () => { useCommunityStore.getState().setCurrentChannelId(null) }- }, [channelId])-- // ── Subscribe + fetch child-channel meta ──────────────────────────────────- useEffect(() => {- if (!channelId) return- communityWsSubscribe({ channelId })- // Child channel — fetch meta so the breadcrumb shows the new parent name- if (isChildChannel) {- apiFetch<{ id: string; name: string; parentChannelId: string | null; parentMessageId: string | null; creatorId: string | null }>(`/api/community/threads/${channelId}`)- .then((data) =>- useCommunityStore- .getState()- .setCurrentChannelMeta({- name: data.name,- parentChannelId: data.parentChannelId,- parentMessageId: data.parentMessageId,- creatorId: data.creatorId,- }),- )- .catch((e) => {- useCommunityStore.getState().setCurrentChannelMeta(null)- // A channel not in the server tree is either a real thread/forum-post- // (meta fetch succeeds above) or one we can't open: deleted (404) or- // no-longer-accessible — gone private / kicked (403, the threads/:id- // 404-vs-403 contract). Both mean "can't land here" — bounce to the- // server root, which forwards to the first remaining channel, rather- // than strand the user on a dead URL with a misleading "thread" error.- // This is also what makes last-channel restore safe for a remembered- // forum-post id (per-server memory trusts the id; validity is settled- // here): a remembered post that was deleted/hidden degrades to default.- if (e instanceof ApiError && (e.status === 404 || e.status === 403)) {- // BREAK THE REDIRECT LOOP: if this dead id is the server's remembered- // last channel, forget it FIRST — otherwise server-root re-reads it,- // re-navigates here, bounces again… forever (this exact id was just- // written to memory by the mount effect above). Clear only when it- // matches, so an unrelated valid memory is never wiped. With no- // memory, server-root falls to the default channel — one hop, no loop.- if (getLastChannel(serverId) === channelId) clearLastChannel(serverId)- router.replace(`/c/channels/${params.serverId}`)- return- }- toastApiError(e, "Failed to load thread")- })- } else {- useCommunityStore.getState().setCurrentChannelMeta(null)- }- return () => {- communityWsUnsubscribe()- }- }, [channelId, isChildChannel, params.serverId, router, serverId])-- // ── Local UI state ──────────────────────────────────────────────────────- const [rightPanel, setRightPanel] = useState<RightPanel>(null)- const [replyTo, setReplyTo] = useState<{ id: string; authorName: string; text: string } | null>(null)- const [localName, setLocalName] = useState<string | null>(null)- const [searchQuery, setSearchQuery] = useState("")- const [searchResults, setSearchResults] = useState<Msg[]>([])- // Seed the scroll target from the mount-time jump target (if any) so- // `MessageList` scrolls to + highlights the message once the anchored window- // loads it. Unlike the reply-pill path (100ms fixed-timer clear), this is- // cleared by an effect once the row is actually present (below) — the anchor- // page is still being fetched over the network, so a fixed timer would race- // and lose the "guaranteed land".- const [scrollToMessageId, setScrollToMessageId] = useState<string | null>(jumpTargetId)-- // Strip `?msg=` from the URL right after mount so a refresh/back doesn't- // re-trigger the jump. The frozen `jumpTargetId` + seeded `scrollToMessageId`- // still drive this mount's anchor and scroll; this only cleans the address.- useEffect(() => {- if (!jumpTargetId) return- router.replace(`/c/channels/${params.serverId}/${channelId}`, { scroll: false })- // eslint-disable-next-line react-hooks/exhaustive-deps -- run once for this mount's jump- }, [])-- // Clear the jump scroll target once the target row is present in the loaded- // window (guaranteed-land: don't clear on a fixed timer while the anchor page- // is still in flight). Fallback: if the load has fully SETTLED (not- // loading/fetching) and the row still isn't here — e.g. the message was- // deleted between navigation and load, or the anchor fetch failed — the row- // will never appear, so release the state rather than leak it for the mount.- useEffect(() => {- if (!scrollToMessageId) return- if (messages.some((m) => m.id === scrollToMessageId)) {- const t = setTimeout(() => setScrollToMessageId((v) => (v === scrollToMessageId ? null : v)), 1600)- return () => clearTimeout(t)- }- const settled =- !messagesLoading && !isFetchingOlderMessages && !isFetchingNewerMessages- if (settled) setScrollToMessageId((v) => (v === scrollToMessageId ? null : v))- }, [scrollToMessageId, messages, messagesLoading, isFetchingOlderMessages, isFetchingNewerMessages])-- // Channel switch — reset every piece of UI state scoped to the previous- // channel. `ChannelView` is keyed by `serverId/channelId`, so this remounts on- // switch; the effect is a belt-and-suspenders reset. NB: `scrollToMessageId`- // is intentionally NOT reset here — it's seeded from the mount-time jump- // target and cleared by its own effect once the row lands; clearing it here- // would clobber a `?msg=` jump on the first render.- useEffect(() => {- setReplyTo(null)- setRightPanel(null)- setSearchQuery("")- setSearchResults([])- setLocalName(null)- setMemberQuery("")- setManageMembersOpen(false)- }, [channelId])-- const doSearch = useCallback(async (q: string) => {- setSearchQuery(q)- if (!q.trim()) { setSearchResults([]); return }- try {- const params = new URLSearchParams({ q })- if (params) params.set("channelId", channelId)- const data = await apiFetch<{ results: Array<{ message: { id: string; content: string; authorId: string; createdAt: string }; author: { name: string; image: string | null } }> }>(`/api/community/search?${params}`)- setSearchResults(data.results.map((r) => ({- id: r.message.id,- type: "chat" as const,- authorName: r.author.name,- authorAvatar: r.author.image ?? avatarInitial(r.author.name),- content: r.message.content,- createdAt: r.message.createdAt,- })))- } catch (e) {- setSearchResults([])- toastApiError(e, "Search failed")- }- }, [channelId])-- // Find the channel name- const channelName = useMemo(() => {- if (localName) return localName- if (channelInServer) return channelInServer.name- if (currentChannelMeta?.name) return currentChannelMeta.name- const post = forumPosts.find((p) => p.id === channelId)- if (post) return post.name- const thread = threads.find((t) => t.id === channelId)- if (thread) return thread.name- return "channel"- }, [localName, channelInServer, forumPosts, threads, currentChannelMeta, channelId])-- // Pinned message ids- const pinnedIds = useMemo(() => new Set(pinned.map((p) => p.id)), [pinned])-- const togglePanel = (k: Exclude<RightPanel, null>) =>- setRightPanel((p) => (p === k ? null : k))-- const enterThread = useCallback((id: string) => {- // No eager read PUT here — the thread page's `useEagerChannelRead` fires it- // on mount AFTER its read-state snapshot latches, so the "New" divider- // still anchors to the pre-open pointer. A PUT here would race the snapshot.- router.push(`/c/channels/${params.serverId}/${id}`)- }, [router, params.serverId])-- // The message context side sheet's target. A message ref opens it to preview- // a message + surrounding context WITHOUT navigating (Gus #417). The target- // carries the source channel (which may differ from the open one — a- // cross-channel ref) so the sheet resolves that channel's seq and shows its- // name in the header. `label` is the source channel's display name (passed in- // so the sheet needn't refetch metadata).- const [contextTarget, setContextTarget] = useState<- { serverId: string; channelId: string; label: string; seq: number } | null- >(null)- // Chained `#N` refs inside the sheet reopen it on the new seq — same channel- // as the currently-shown one (a `#N` in a previewed message is scoped to that- // message's channel).- const openContextSeq = useCallback((seq: number) => {- setContextTarget((prev) =>- prev ? { ...prev, seq } : { serverId, channelId, label: channelName, seq },- )- }, [serverId, channelId, channelName])-- // Reply clicked inside the context sheet. Same-channel preview → seed THIS- // channel's composer directly. Cross-channel preview → you can't reply here to- // a message that lives in another channel (Gus #449/#452), so hand the target- // off through the store and navigate to that message's channel; its page seeds- // its own composer on arrival (see the pendingReply effect below). Reply stays- // available in both cases — it just routes you to where the reply belongs.- const onSheetReply = useCallback((target: { id: string; authorName: string; text: string }) => {- if (contextTarget && contextTarget.channelId !== channelId) {- useCommunityStore.getState().setPendingReply({ channelId: contextTarget.channelId, target })- setContextTarget(null)- uiHandlers.navigate?.(contextTarget.serverId, contextTarget.channelId)- } else {- setReplyTo(target)- setContextTarget(null)- }- }, [contextTarget, channelId, uiHandlers])-- // Consume a reply handed off from a cross-channel sheet on another page: if a- // pendingReply targets THIS channel, seed the composer once and clear it.- const pendingReply = useCommunityStore((s) => s.pendingReply)- useEffect(() => {- if (pendingReply && pendingReply.channelId === channelId) {- setReplyTo(pendingReply.target)- useCommunityStore.getState().setPendingReply(null)- }- }, [pendingReply, channelId])-- // Same-channel message ref (`/server/channel#N`, channel open) via `jumpToSeq`:- // message loaded in the window → scroll+highlight it in place; not loaded →- // open the context sheet on THIS channel. Reads `messages` lazily off the- // actions ref so the callback stays reference-stable (no memo churn).- const jumpToSeq = useCallback((seq: number) => {- const msg = actionsCtxRef.current.messages.find((m) => m.seq === seq)- if (msg) setScrollToMessageId(msg.id)- else setContextTarget({ serverId, channelId, label: channelName, seq })- }, [serverId, channelId, channelName])- // Cross-channel message ref via `openMessageContext`: open the sheet IN PLACE- // on the target (other) channel — never navigate (Gus #417). The sheet's- // access-checked read path returns not-found for a channel the viewer can't- // see, so a private-channel ref leaks nothing.- const openMessageContext = useCallback(- (target: { serverId: string; channelId: string; label: string; seq: number }) => setContextTarget(target),- [],- )- useEffect(() => {- useCommunityStore.getState().registerUiHandlers({ jumpToSeq, openMessageContext })- return () => useCommunityStore.getState().registerUiHandlers({ jumpToSeq: undefined, openMessageContext: undefined })- }, [jumpToSeq, openMessageContext])-- // Marked-tab (and any cross-channel) deep-link: a `?seq=<n>` on the URL opens- // the context sheet on that message. Unlike the `?msg=` mount-anchor path,- // this is an EFFECT keyed on the seq param — so it fires even when navigating- // to an ALREADY-MOUNTED channel page (Next reuses the component, so a- // mount-once useState read would miss the new param). The sheet reads by- // (channelId, seq) and cold-fetches its own window, so the target row need- // not be in the loaded list. We strip the param right after so a refresh/back- // doesn't re-open it, and re-arm cleanly for the next jump.- const seqParam = searchParams.get("seq")- useEffect(() => {- if (!seqParam) return- const seq = Number(seqParam)- if (!Number.isFinite(seq)) return- setContextTarget({ serverId, channelId, label: channelName, seq })- router.replace(`/c/channels/${params.serverId}/${channelId}`, { scroll: false })- }, [seqParam, serverId, channelId, channelName, router, params.serverId])-- // Stable so it doesn't bust the memoized message rows; reads uiHandlers- // lazily through the actions ref (assigned just below).- const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {- actionsCtxRef.current.uiHandlers.openProfile?.(name, e, discriminator, userId)- }, [])-- // ── Message actions ─────────────────────────────────────────────────────- //- // Swallow send failures at the caller boundary. `useSendMessage`'s `onError`- // already marks the optimistic row `failed: true` AND fires the rate-limit- // toast; we don't need the raw rejection to propagate any further. Letting- // it escape via `mutateAsync` would surface a bare `ApiError` in the Next.js- // error overlay (rate-limit path was the reproducer). Returning `null`- // instead lets thread-create + retry callers detect failure without a- // try/catch each.- const messageScope = useMemo(- () => ({ kind: "channel" as const, id: channelId, serverId }),- [channelId, serverId],- )-- const runAcceptedIntent = useCallback(- async (nonce: string) => {- const streamStore = useMessageStreamStore.getState()- const payload = streamStore.getRetryPayload(messageScope, nonce)- if (!payload) return- let uploadedAttachments: UploadedAttachment[] | undefined- if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {- const projected = payload.message.attachments- if (projected?.length === payload.localUploads.length) {- uploadedAttachments = projected.map((attachment, index) => {- const local = payload.localUploads[index]- return {- url: attachment.url,- filename: local.file.name,- contentType: local.file.type,- size: local.file.size,- width: local.width,- height: local.height,- }- })- }- }- if (payload.localUploads.length > 0 && !uploadedAttachments) {- const results = await Promise.all(- payload.localUploads.map((upload) =>- uploadFileAsync({ target: { channelId }, file: upload.file }).catch((error) => {- toastApiError(error, "Failed to attach file")- return null- }),- ),- )- if (results.some((result) => result === null)) {- streamStore.dispatch(messageScope, { type: "uploadFailed", nonce })- return- }- uploadedAttachments = zipUploadResultsWithDimensions(results, [...payload.localUploads])- streamStore.dispatch(messageScope, {- type: "uploadSettled",- nonce,- attachments: uploadedAttachments.map(toAttachmentVm),- })- }- try {- await sendMessageAsync({- serverId,- channelId,- content: payload.message.content ?? "",- replyToId: payload.message.replyTo?.id,- mentionType: payload.mentionType,- attachments: uploadedAttachments,- nonce,- author: {- id: currentUser.id,- name: currentUser.name,- avatar: currentUser.avatar,- },- })- } catch {- return- }- },- [messageScope, uploadFileAsync, channelId, sendMessageAsync, serverId, currentUser.id, currentUser.name, currentUser.avatar],- )-- // Latest-ref for the values the message actions read at call time. Keeping- // these off the callback deps lets `messageActions` stay reference-STABLE- // across renders (a new `messages` array on every WS tick would otherwise- // rebuild every handler and defeat the memoized message rows). The handlers- // only ever read these lazily on click, so a ref is exactly right.- const actionsCtxRef = useRef<{- messages: Msg[]- pinnedIds: Set<string>- channelName: string- uiHandlers: typeof uiHandlers- }>({ messages, pinnedIds, channelName, uiHandlers })- // Latest-ref write during render is intentional here: the ref only feeds- // click-time reads inside the stable `messageActions` callbacks, never- // render output, so it can't cause a missed update.- /* eslint-disable-next-line react-hooks/immutability -- latest-ref for lazy click reads */- actionsCtxRef.current = { messages, pinnedIds, channelName, uiHandlers }-- const messageActions = useMemo(() => ({- onToggleReaction: (id: string, emoji: string) =>- toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: currentUser.id }),- onReact: (id: string, emoji: string) =>- toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: currentUser.id }),- onReply: (id: string) => {- const m = actionsCtxRef.current.messages.find((x) => x.id === id)- if (m) setReplyTo({ id: m.id, authorName: m.authorName ?? "", text: m.content ?? "" })- },- onPin: (id: string) => {- const isPinned = actionsCtxRef.current.pinnedIds.has(id)- if (isPinned) {- unpinMessageMutate({ channelId, messageId: id }, {- onSuccess: () => toast("Message unpinned"),- onError: (e) => toastApiError(e, "Failed to unpin message"),- })- } else {- pinMessageMutate({ channelId, messageId: id }, {- onSuccess: () => toast("Message pinned"),- onError: (e) => toastApiError(e, "Failed to pin message"),- })- setRightPanel("pinned")- }- },- onMark: (id: string) => toggleMark(channelId, id),- onCreateThread: async (id: string) => {- const m = actionsCtxRef.current.messages.find((x) => x.id === id)- const name = deriveThreadName(m?.content, actionsCtxRef.current.channelName)- try {- const data = await createThreadAsync({ serverId, channelId, messageId: id, name })- router.push(`/c/channels/${params.serverId}/${data.id}`)- } catch (e) {- toastApiError(e, "Failed to create thread")- }- },- onCopy: (id: string) => {- const m = actionsCtxRef.current.messages.find((x) => x.id === id)- if (m?.content) { navigator.clipboard?.writeText(m.content); toast("Copied to clipboard") }- },- onRetry: (id: string) => {- const m = actionsCtxRef.current.messages.find((x) => x.id === id)- if (!m?.clientNonce) return- useMessageStreamStore.getState().dispatch(messageScope, { type: "retry", nonce: m.clientNonce })- void runAcceptedIntent(m.clientNonce)- },- onDismiss: (id: string) => {- const m = actionsCtxRef.current.messages.find((x) => x.id === id)- if (!m?.clientNonce) return- useMessageStreamStore.getState().dispatch(messageScope, {- type: "dismissFailed",- nonce: m.clientNonce,- })- },- onPreviewImage: (url: string) => {- actionsCtxRef.current.uiHandlers.previewImage?.(url)- },- onDownloadFile: (url: string) => {- const a = document.createElement("a")- a.href = url- a.download = url.split("/").pop() ?? "file"- a.click()- },- // Deps are all reference-stable: channelId/currentUser.id (strings),- // toggleReactionApi (useCallback), the mutation METHODS (TanStack binds- // `.mutate`/`.mutateAsync` stably — NOT the whole mutation object, which is- // a new wrapper every render), doSend (useCallback), router/params. Volatile- // reads go through actionsCtxRef. This stability is load-bearing: an unstable- // messageActions busts MessageRow/Message's memo and re-renders every visible- // row on every commit (see message.tsx messagePropsEqual).- }), [serverId, channelId, currentUser.id, toggleReactionApi, unpinMessageMutate, pinMessageMutate, toggleMark, createThreadAsync, messageScope, runAcceptedIntent, router, params.serverId])-- const threadActions = useMemo(- () => ({ ...messageActions, onCreateThread: undefined }),- [messageActions],- )-- // Reference-stable across renders. MUST depend on the RAW roster- // (`membersHook.members`), NOT the presence-enriched `members` (line ~110):- // `makeUserNameResolver` only reads id/name/email, never presence, yet the- // enriched array gets a new identity on every presence/status tick. Keying- // this resolver on it re-created it on every tick and busted every memoized- // message row (react-scan measured MessageImpl re-rendering with- // `props:[resolveUserName]` — ~1/3 of the switch re-render storm). The raw- // roster's identity changes only when membership/names genuinely change.- const resolveUserName = useMemo(- () => makeUserNameResolver(membersHook.members),- [membersHook.members],- )-- // ── Send messages ───────────────────────────────────────────────────────- const acceptMessage = (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType): boolean => {- if (!markdown && !attachments?.length) return false- const nonce = sendNonce()- const createdPreviewUrls: string[] = []- const accepted = useMessageStreamStore.getState().accept(messageScope, {- nonce,- tempId: tempMessageId(),- message: {- type: "chat",- authorId: currentUser.id,- authorName: currentUser.name,- authorAvatar: currentUser.avatar,- content: markdown,- createdAt: new Date().toISOString(),- ...(replyTo ? { replyTo: { id: replyTo.id, authorName: replyTo.authorName, text: replyTo.text.slice(0, 100) } } : {}),- },- localUploads: attachments?.map((attachment) => {- const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)- if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)- return {- file: attachment.file,- previewObjectUrl,- width: attachment.width,- height: attachment.height,- }- }) ?? [],- mentionType,- })- if (!accepted) {- for (const url of createdPreviewUrls) URL.revokeObjectURL(url)- return false- }- void runAcceptedIntent(nonce)- communityWsResetTypingThrottle({ channelId })- setReplyTo(null)- return true- }-- const handleTyping = () => {- communityWsSendTyping({ channelId })- }-- const createForumPost = useCallback(async (post: NewForumPost) => {- const data = await createForumPostMut.mutateAsync({- channelId,- name: post.name,- content: post.content,- attachments: post.attachments,- mentionType: post.mentionType,- })- // A post is its own child channel — open it, same as clicking a post row.- enterThread(data.post.id)- }, [channelId, createForumPostMut, enterThread])-- const myRole = members.find((m) => m.userId === currentUser.id)?.role- // The unit's creator (thread/channel/post) — drives the manage-context- // creator rules. For a thread the id lives on `currentChannelMeta`; for a- // top-level channel/post it's on the channel row in the server tree.- const unitCreatorId = isChildChannel- ? currentChannelMeta?.creatorId- : channelInServer?.creatorId- const viewerIsUnitCreator = !!unitCreatorId && unitCreatorId === currentUser.id- // The drawer's manage affordance:- // - thread/post (notify unit) → add PARTICIPANTS (any participant); rows- // right-click to leave/remove.- // - private top-level channel/forum → add MEMBERS (any member); rows- // right-click to leave (self) / remove (creator).- // Public top-level channels/forums: no manage button (everyone can access).- const showManageButton = isNotifyUnit || currentChannelPrivate- // Whether the drawer is on a scoped (participant/audience) source vs the- // paginated server roster.- const scopedDrawer = isNotifyUnit || currentChannelPrivate- // Row right-click Leave/Remove context. Remove is creator-only on every unit;- // the wired mutation differs by unit (participant vs channel-member).- const manageContext = scopedDrawer- ? {- viewerUserId: currentUser.id,- viewerIsCreator: viewerIsUnitCreator,- unitLabel: currentChannelMeta?.name ?? channelName,- // Return the promise so the confirm dialog can show a loading state and- // surface errors from ONE place (MemberList's confirm catch).- onLeave: (userId: string) =>- (isNotifyUnit ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),- onRemove: (userId: string) =>- (isNotifyUnit ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),- }- : undefined- const panelProps = {- onOpenThread: enterThread,- members: panelMembers,- membersLoading: isNotifyUnit- ? channelMembersHook.isLoading- : currentChannelPrivate ? channelMembersHook.isLoading : membersHook.loading,- membersLoadingMore: scopedDrawer ? false : membersHook.loadingMore,- membersHasMore: scopedDrawer ? false : membersHook.hasMore,- onLoadMoreMembers: scopedDrawer ? undefined : membersHook.loadMore,- // Scoped drawer: local filter (small set). Public: server search.- onSearchMembers: scopedDrawer ? setMemberQuery : membersHook.searchMembers,- onAddMember: showManageButton ? () => setManageMembersOpen(true) : undefined,- manageContext,- pinned,- pinnedLoading,- searchResults,- threads,- threadsLoading,- searchQuery,- myRole,- onSearch: doSearch,- onSetRole: (memberId: string, role: Role) => {- setMemberRoleMut.mutate({ serverId, memberId, role }, {- onSuccess: () => toast("Role updated"),- onError: (e) => toastApiError(e, "Failed to update role"),- })- },- // Return the promise (and success toast) so MemberList's confirm dialog can- // show a loading state; the error is surfaced from MemberList's catch (one- // toast source).- onKickMember: (memberId: string) =>- kickMemberMut.mutateAsync({ serverId, memberId }).then(() => toast("Member kicked")),- // Pinned-message click routes through the same message-ref jump flow- // (scroll-in-place if the message is loaded, else open the context sheet),- // so clicking a pin always gives feedback — even an old, out-of-window one- // that the scroll-only path used to silently no-op on.- onJumpToMessage: (seq: number) => jumpToSeq(seq),- }-- // Add-members dialog (shared), mounted when the drawer's Add button fires.- // - thread/post (notify unit) → candidates = parent channel/forum members- // not yet participating; onAdd = add participant.- // - private top-level channel/forum → candidates = server members not in the- // unit; onAdd = add channel member (targets `channelId` directly).- // The current-member list + leave/remove live in the drawer row right-click- // menu (`manageContext`), not here.- const manageMembersDialog = (() => {- if (!manageMembersOpen) return null- if (isNotifyUnit) {- const participantIds = new Set(channelMembersHook.members.map((m) => m.userId))- const candidates = parentChannelMembersHook.members- .filter((m) => !participantIds.has(m.userId) && m.userId !== currentUser.id)- .map((m) => ({ userId: m.userId, name: m.name ?? null, avatar: m.avatar }))- return (- <AddMembersDialog- title={`Add participants to /${currentChannelMeta?.name ?? channelName}`}- subtitle="Added people are notified of new replies. Anyone with access can already read it."- candidates={candidates}- onAdd={(userId) => addThreadParticipantMut.mutateAsync(userId)}- onClose={() => setManageMembersOpen(false)}- />- )- }- const candidates = addableChannelMembers.members.map((m) => ({- userId: m.userId,- name: m.name ?? null,- avatar: m.avatar,- }))- return (- <AddMembersDialog- title={`Add members to /${channelName}`}- subtitle="Added members can see and post here."- candidates={candidates}- onAdd={(userId) => addChannelMemberMut.mutateAsync(userId)}- onClose={() => setManageMembersOpen(false)}- />- )- })()-- const isPotentialChild = !channelInServer && !!currentServer?.categories- const bodyLoading = isForum ? forumPostsLoading : messagesLoading- const channelHydrated =- currentChannelId === channelId &&- !bodyLoading &&- (!isPotentialChild || currentChannelMeta !== null)- if (!channelHydrated) {- if (isForum) {- return (- <>- <ChannelHeaderSkeleton onBack={bp === "mobile" ? goBack : undefined} />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">- <ForumViewSkeleton />- </main>- </>- )- }- return (- <>- <ChannelHeaderSkeleton onBack={bp === "mobile" ? goBack : undefined} />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">- {/*- `key={channelId}` MUST match the hydrated branches' key below —- verified empirically (react-test-renderer) that a mismatched key- (this branch had none before) is what causes React to treat this- and the hydrated-branch `<MessageList>` as different component- identities, forcing a full unmount/remount instead of a props- update on one instance when `channelHydrated` flips true. With- matching keys, this works correctly even though this early- `return` and the hydrated branches' `return` produce- structurally different JSX trees — React's reconciliation only- needs the position + type + key to line up.- */}- <MessageList key={channelId} channel="" messages={[]} loading={true} onOpenThread={() => { }} />- <ComposerSkeleton />- </main>- </>- )- }-- // ── Child channel view (forum post / thread opened via URL) ─────────────- if (isChildChannel) {- const parentId = currentChannelMeta?.parentChannelId- const parentMessageId = currentChannelMeta?.parentMessageId ?? null- const allChannels = currentServer?.categories?.flatMap((c) => c.channels) ?? []- const parentChannel = parentId ? allChannels.find((ch) => ch.id === parentId) : null- const parentName = parentChannel?.name ?? "channel"- const opener = parentMessageId ? (- <ThreadOpener- parentMessageId={parentMessageId}- onOpenProfile={openProfile}- onPreviewImage={(url) => uiHandlers.previewImage?.(url)}- onDownloadFile={(url) => {- const a = document.createElement("a")- a.href = url- a.download = url.split("/").pop() ?? "file"- a.click()- }}- onJump={- parentId- ? () =>- router.push(- `/c/channels/${params.serverId}/${parentId}?msg=${parentMessageId}`,- )- : undefined- }- />- ) : undefined- return (- <>- <ChannelHeader- channel={parentName}- forum={isForumType(parentChannel?.type)}- rightPanel={rightPanel}- onToggle={togglePanel}- notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}- onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {- onError: (e) => toastApiError(e, "Failed to update notification level"),- })}- onBack={bp === "mobile" ? () => router.back() : undefined}- server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}- tools={{ threads: false }}- breadcrumb={{- label: channelName,- onNavigateBack: () => { if (parentId) router.push(`/c/channels/${params.serverId}/${parentId}`); else router.back() },- onRename: canManageServer(myRole) ? async (name) => {- try {- await apiFetch(`/api/community/channels/${channelId}`, {- method: "PATCH",- body: JSON.stringify({ name }),- })- setLocalName(name)- } catch (e) { toastApiError(e, "Failed to rename") }- } : undefined,- }}- />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">- <MessageList- key={channelId}- channel={channelName}- messages={messages}- loading={messagesLoading}- pinnedIds={pinnedIds}- newDividerBefore={newDividerBefore}- typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}- onOpenThread={() => { }}- {...threadActions}- onOpenProfile={openProfile}- resolveUserName={resolveUserName}- scrollToMessageId={scrollToMessageId}- hero={opener}- onScrollRoot={setScrollRootEl}- viewerUserId={currentUser.id}- // Same gate as the top-level channel view: hold the mount-time- // scroll until the read snapshot resolves and its anchor is loaded,- // so a thread/forum-post opens on the "New" divider too.- initialScrollReady={!readSnapshotFetching && anchorInCache}- hasMore={hasMoreMessages}- isFetchingOlder={isFetchingOlderMessages}- onLoadOlder={fetchOlderMessages}- hasMoreNewer={hasMoreNewerMessages}- isFetchingNewer={isFetchingNewerMessages}- onLoadNewer={fetchNewerMessages}- onJumpToPresent={jumpToPresent}- unreadCount={unreadCount}- onOpenContextSheet={openContextSeq}- />- <div data-onboarding-target="channel-composer" className="shrink-0">- <Composer- channel={channelName}- context="thread"- members={composerMembers}- onSearchMembers={membersHook.searchMembers}- channelRefCandidates={channelRefCandidates}- sendContract="accepted"- onAcceptSend={acceptMessage}- onTyping={handleTyping}- replyingTo={replyTo?.authorName}- onCancelReply={() => setReplyTo(null)}- autoFocus={bp !== "mobile"}- draftKey={`${serverId}/${channelId}`}- />- </div>- </main>-- {rightPanel && (- <CommunityPanelSheet- open- onOpenChange={(v) => { if (!v) setRightPanel(null) }}- kind={rightPanel}- {...panelProps}- onOpenProfile={openProfile}- />- )}- {manageMembersDialog}- <MessageContextSheet- open={contextTarget !== null}- onOpenChange={(v) => { if (!v) setContextTarget(null) }}- channelId={contextTarget?.channelId ?? channelId}- channelLabel={contextTarget?.label}- targetSeq={contextTarget?.seq ?? null}- pinnedIds={pinnedIds}- onOpenContextSheet={openContextSeq}- onOpenProfile={openProfile}- resolveUserName={resolveUserName}- onReply={onSheetReply}- />- </>- )- }-- // ── Forum view ──────────────────────────────────────────────────────────- if (isForum) {- const canManage = canManageServer(myRole)- return (- <>- <ChannelHeader- channel={channelName}- forum- rightPanel={rightPanel}- onToggle={togglePanel}- notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}- onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {- onError: (e) => toastApiError(e, "Failed to update notification level"),- })}- onBack={bp === "mobile" ? goBack : undefined}- server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}- tools={{ threads: false, pinned: false }}- />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">- <ForumView- forumChannelId={channelId}- members={composerMembers}- onSearchMembers={membersHook.searchMembers}- posts={forumPosts}- loading={forumPostsLoading}- onOpenPost={enterThread}- onCreatePost={createForumPost}- canEditPostTags={(post) => canManage || post.authorId === currentUser.id}- savingTagsFor={updatePostTagsMut.isPending ? updatePostTagsMut.variables?.postId ?? null : null}- onEditPostTags={(postId, tags) => {- updatePostTagsMut.mutate(- { forumChannelId: channelId, postId, tags },- { onError: (e) => toastApiError(e, "Failed to save tags") },- )- }}- canDeletePost={(post) => canManage || post.authorId === currentUser.id}- deletingPost={deleteForumPostMut.isPending ? deleteForumPostMut.variables?.postId ?? null : null}- onDeletePost={(post) => {- deleteForumPostMut.mutate(- { forumChannelId: channelId, postId: post.id },- { onError: (e) => toastApiError(e, "Failed to delete post") },- )- }}- />- </main>-- {rightPanel && (- <CommunityPanelSheet- open- onOpenChange={(v) => { if (!v) setRightPanel(null) }}- kind={rightPanel}- {...panelProps}- onOpenProfile={openProfile}- />- )}- {manageMembersDialog}- </>- )- }-- // ── Standard channel view ───────────────────────────────────────────────- return (- <>- <ChannelHeader- channel={channelName}- rightPanel={rightPanel}- onToggle={togglePanel}- notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}- onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {- onError: (e) => toastApiError(e, "Failed to update notification level"),- })}- onBack={bp === "mobile" ? goBack : undefined}- server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}- />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">- <MessageList- // Remount per channel so mount-time initial-scroll fires afresh- // and internal refs (didInitialScrollRef, lastTailIdRef) reset.- key={channelId}- channel={channelName}- messages={messages}- loading={messagesLoading}- pinnedIds={pinnedIds}- newDividerBefore={newDividerBefore}- typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}- onOpenThread={enterThread}- {...messageActions}- onOpenProfile={openProfile}- resolveUserName={resolveUserName}- scrollToMessageId={scrollToMessageId}- onScrollRoot={setScrollRootEl}- viewerUserId={currentUser.id}- // Delay initial scroll until the read-state snapshot resolves AND- // the anchor it names is actually present in `messages` — see- // `anchorInCache`'s doc comment above for the mount-vs-Fix-3 race- // this closes.- initialScrollReady={!readSnapshotFetching && anchorInCache}- hasMore={hasMoreMessages}- isFetchingOlder={isFetchingOlderMessages}- onLoadOlder={fetchOlderMessages}- hasMoreNewer={hasMoreNewerMessages}- isFetchingNewer={isFetchingNewerMessages}- onLoadNewer={fetchNewerMessages}- onJumpToPresent={jumpToPresent}- unreadCount={unreadCount}- onOpenContextSheet={openContextSeq}- />- <div data-onboarding-target="channel-composer" className="shrink-0">- <Composer- channel={channelName}- context="channel"- members={composerMembers}- onSearchMembers={membersHook.searchMembers}- channelRefCandidates={channelRefCandidates}- sendContract="accepted"- onAcceptSend={acceptMessage}- onTyping={handleTyping}- replyingTo={replyTo?.authorName}- onCancelReply={() => setReplyTo(null)}- autoFocus={bp !== "mobile"}- draftKey={`${serverId}/${channelId}`}- />- </div>- </main>-- {rightPanel && (- <CommunityPanelSheet- open- onOpenChange={(v) => { if (!v) setRightPanel(null) }}- kind={rightPanel}- {...panelProps}- onOpenProfile={openProfile}- />- )}- {manageMembersDialog}- <MessageContextSheet- open={contextTarget !== null}- onOpenChange={(v) => { if (!v) setContextTarget(null) }}- channelId={contextTarget?.channelId ?? channelId}- channelLabel={contextTarget?.label}- targetSeq={contextTarget?.seq ?? null}- pinnedIds={pinnedIds}- onOpenContextSheet={openContextSeq}- onOpenProfile={openProfile}- resolveUserName={resolveUserName}- onReply={onSheetReply}- />- </>- )+ return <ChannelRoute key={key} serverParam={params.serverId} channelId={params.channelId} />}diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex c6c3df5ec..adb64c658 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -30,8 +30,9 @@ import { useServer, useServers } from "@/hooks/community/use-servers"import { useServerMembers } from "@/hooks/community/use-server-members"import {consumeVoluntaryLeave,- pickPostEjectDestination,+ runAuthoritativeServerEject,} from "@/components/community/eject-server"+import { clearLastChannel } from "@/lib/community/last-channel"import { usePresence } from "@/hooks/community/use-server-panels"import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"@@ -128,25 +129,25 @@ export default function ServerLayout({ children }: { children: ReactNode }) {// 4. Viewer pasted a URL for a server they were never in (list// finishes loading, id is missing from the start).//- // Gate on `isFetched && !isFetching`, not on `isLoading`. TanStack v5- // `isLoading` is only true on the very first fetch — after any WS- // invalidate, reconnect, or IDB rehydrate, `isLoading=false` even while- // `servers=[]` between refetches. Using `isLoading` alone false-triggered- // this eject on every reload (see the "You're no longer in this server"- // toast on refresh regression). Also gate on the `!ejectedRef` to prevent- // a re-fire while the redirect is in flight.+ // Only a settled SUCCESSFUL snapshot can prove absence. `isFetched` is also+ // true after a first 5xx, while a failed background refetch may retain+ // last-good data; treating either as authoritative ejects valid URLs on a+ // transient read failure. The ref prevents a re-fire during navigation.const serversList = useServers()const ejectedRef = useRef(false)useEffect(() => {if (ejectedRef.current) return- if (!serversList.isFetched || serversList.isFetching) return- const inRail = serversList.servers.some((s) => s.id === serverId)- if (inRail) return- ejectedRef.current = true- const voluntary = consumeVoluntaryLeave(serverId)- if (!voluntary) toast("You're no longer in this server")- router.replace(pickPostEjectDestination(serversList.servers, serverId))- }, [serverId, serversList.isFetched, serversList.isFetching, serversList.servers, router])+ ejectedRef.current = runAuthoritativeServerEject({+ serverId,+ servers: serversList.servers,+ isSuccess: serversList.isSuccess,+ isFetching: serversList.isFetching,+ consumeVoluntaryLeave,+ clearLastChannel,+ toast,+ replace: (destination) => router.replace(destination),+ })+ }, [serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router])// Reset the guard when the URL changes to a NEW server id — otherwise// navigating server → dangling-server → server would leave the ref// latched and skip the eject.diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex b06650a9f..bf62d5c6f 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -3,6 +3,7 @@import { useCallback, useEffect, useMemo, useState } from "react"import { useParams, useSearchParams } from "next/navigation"import { toast } from "sonner"+import { MESSAGE_PREVIEW_LENGTH } from "@alook/shared"import { useBreakpoint } from "@/hooks/use-mobile"import { DmHeader, DmHeaderSkeleton } from "@/components/community/dm-header"import { Avatar } from "@/components/community/avatar"@@ -309,7 +310,7 @@ function DmView() {dmId,content: markdown,replyTo: replyTo- ? { id: replyTo.id, authorName: replyTo.authorName, text: replyTo.text.slice(0, 100) }+ ? { ...replyTo, text: replyTo.text.slice(0, MESSAGE_PREVIEW_LENGTH) }: undefined,attachments,author: {@@ -401,7 +402,6 @@ function DmView() {onLoadNewer={fetchNewerMessages}onJumpToPresent={jumpToPresent}unreadCount={unreadCount}- onOpenContextSheet={setContextSheetSeq}hero={<><div className="relative mb-3 w-fit"><Avatar label={dm.avatar} seed={dm.userId} size={64} /></div>@@ -440,7 +440,6 @@ function DmView() {onOpenChange={(v) => { if (!v) setContextSheetSeq(null) }}channelId={dmId}targetSeq={contextSheetSeq}- onOpenContextSheet={setContextSheetSeq}type="dm"onOpenProfile={openProfile}resolveUserName={resolveUserName}diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex 9ebdaab21..ec1a38980 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -63,8 +63,8 @@ export default function MeLayout({ children }: { children: ReactNode }) {// Mirror channel sidebar-click behavior (channels/layout.tsx:226-236): do// NOT eagerly mark the DM read on click. That fires a bodyless- // `PUT /dm/:id/read` which the server aligns to the DM's tail (see- // api/community/dm/[id]/read/route.ts) — the read-state snapshot then+ // `PUT /channels/:id/read` which the server aligns to the DM's tail (see+ // api/community/channels/[id]/read/route.ts) — the read-state snapshot then// resolves at the tail on mount and `newDividerBefore` computes to// `undefined`, so unread DMs open at the bottom with no NEW divider.//diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 1f06ad547..311764b2e 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -31,6 +31,7 @@ export type SettingsSection =export type Server = {id: string // nanoidname: string+ discriminator?: stringinitial: stringactive: booleanmentions: number@@ -130,7 +131,16 @@ export type Msg = {attachments?: Attachment[]reactions?: Reaction[]replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }- thread?: { id: string; name: string; messageCount: number; lastReplyAt?: string }+ thread?: {+ id: string+ name: string+ messageCount: number+ lastReplyAt?: string+ tags?: string[]+ preview?: string+ participants?: { id: string; name: string; avatar: string }[]+ participantCount?: number+ }// Present only on a friend-approval DM card. Its presence (not the message// `type`) is the discriminator for rendering <BotApprovalCard>.approval?: import("@alook/shared").FriendApprovalPayload@@ -144,7 +154,7 @@ export type Msg = {export type RenderMsg = Msg & { grouped: boolean }// ── Threads / forum ──────────────────────────────────────────────────────────-// Thread/forum-post summaries shown in side panels and forum lists. Actual+// Child-thread summaries shown in side panels and forum lists. Actual// message content for a thread or post is loaded into `ctx.messages` once the// user navigates into the child channel — these summaries don't carry messages.export type Thread = {@@ -154,14 +164,15 @@ export type Thread = {lastMessageAt: stringparent: { authorName: string; text: string }// The root message's per-channel seq, when the thread was created from a- // parent message (omitted for threads with no parent, e.g. forum posts).+ // parent message (omitted only for legacy rootless threads).// Used by `channel-ref-pill.tsx` to match a `/server/channel/#N` ref.parentSeq?: number}-export type ForumPost = Thread & {+export type ForumThread = Thread & {authorId: stringauthorAvatar: string+ openerMessageId: stringtags: string[]preview: string// The post's participant (notify) set — creator first, then whoever@@ -169,6 +180,8 @@ export type ForumPost = Thread & {// present (empty for a post with no participant rows yet, e.g. one created// before the notify-scope change shipped).participants: { id: string; name: string; avatar: string }[]+ // Total participant rows before the card-preview cap is applied.+ participantCount: number}// ── Members / friends / DMs ──────────────────────────────────────────────────@@ -253,8 +266,10 @@ export type Profile = {// resolution and self-detection (never match by non-unique display name).// Optional so mock/older Profile-constructing sites keep type-checking.userId?: string- // 4-digit discriminator hash of user.id (`"0042"`) — undefined while the- // profile fetch is in flight. See computeDiscriminator in @alook/shared.+ // Variable-width (≥4-digit) decimal discriminator derived from user.id+ // (`"0042"`, widens on collision) — undefined while the profile fetch is in+ // flight. Shown at its true width, never re-padded. See computeDiscriminator+ // in @alook/shared.discriminator?: stringavatar: stringrole: string@@ -299,7 +314,7 @@ export type Mention = {}// A single per-user saved ("marked") message, as returned by-// `/api/community/inbox/marked`. Cross-channel newest-first — each row carries+// `/api/community/users/me/marks`. Cross-channel newest-first — each row carries// the serverId + channelId + seq needed to deep-link back to the message// (unlike a Mention, which only opens the channel, a Marked row jumps to the// exact message via the `?msg=<id>` deep-link). `id` is the mark row's own id,@@ -319,19 +334,23 @@ export type Marked = {m: Msg}-// A single unread thread / forum-post nested under its parent channel.+// A single unread child thread nested under its parent channel.type UnreadChild = {channelId: stringchannelName: string- // Raw stored channel type — drives the inbox entity icon (thread/forum_post- // → MessagesSquare). Optional for backward-compat with cached responses.+ // Raw stored channel type — drives the inbox entity icon (thread →+ // MessagesSquare). Optional for backward-compat with cached responses.type?: EntityKindlastMessageAt: stringmentionCount: number+ // Present when this row projects an unread opener from the parent forum.+ // The child id remains the navigation target; this opener id is the parent+ // channel's progressive-read target.+ openerMessageId?: string}// "Unreads" — channels with unread messages, grouped by server. Each channel-// may carry `children` (unread threads/forum-posts) rendered as indented+// may carry `children` (unread child threads) rendered as indented// sub-rows; a parent can appear solely to host unread children.export type UnreadServer = {serverId: stringdiff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex e60aa0fcb..a324d3e13 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -389,7 +389,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {is forced to WRAP below before the runtime/model/awake text has to truncate (Gus #730 — never letthe heatmap squeeze the meta). */}- <div className="flex min-w-[220px] flex-1 flex-col gap-1">+ <div className="flex min-w-55 flex-1 flex-col gap-1"><div className="flex items-center gap-2"><span className="truncate text-[15px] font-medium text-foreground">{bot.name}diff --git a/src/web/src/components/community/channel-add-members-dialog.tsx b/src/web/src/components/community/channel-add-members-dialog.tsxindex cd2369406..525e4a579 100644--- a/src/web/src/components/community/channel-add-members-dialog.tsx+++ b/src/web/src/components/community/channel-add-members-dialog.tsx@@ -13,15 +13,17 @@ import {* remove/leave controls live in the Members drawer's row right-click menu.*/export function ChannelAddMembersDialog({+ serverId,channelId,channelName,onClose,}: {+ serverId: stringchannelId: stringchannelName: stringonClose: () => void}) {- const { members: addable } = useAddableMembers(channelId)+ const { members: addable } = useAddableMembers(serverId, channelId)const addMember = useAddChannelMember(channelId)const candidates = addable.map((m) => ({diff --git a/src/web/src/components/community/channel-header.title-dialog.test.ts b/src/web/src/components/community/channel-header.title-dialog.test.tsnew file mode 100644index 000000000..bfd1fbfa5--- /dev/null+++ b/src/web/src/components/community/channel-header.title-dialog.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it, vi } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"++vi.mock("./create-dialog-shell", async () => {+ const ReactModule = await import("react")+ return {+ CreateDialogShell: ({ title, footer, children }: { title: React.ReactNode; footer?: React.ReactNode; children: React.ReactNode }) => (+ ReactModule.createElement("div", { "data-testid": "create-dialog-shell", role: "dialog" },+ ReactModule.createElement("div", { className: "text-xs font-normal text-muted-foreground" }, title),+ children,+ footer,+ )+ ),+ }+})++import { ChannelHeader } from "./channel-header"++function renderHeader(onRename?: (name: string) => void | Promise<void>, titleRename = true) {+ return TestRenderer.create(+ React.createElement(ChannelHeader, {+ channel: "forum",+ forum: true,+ rightPanel: null,+ onToggle: () => {},+ tools: { threads: false, pinned: false, members: false },+ breadcrumb: { label: "Original title", onRename, titleRename },+ }),+ )+}++describe("ChannelHeader — forum title dialog", () => {+ it("gates the title edit affordance to the creator and keeps normal threads on Rename", () => {+ let renderer: TestRenderer.ReactTestRenderer+ act(() => { renderer = renderHeader() })+ expect(renderer!.root.findAllByProps({ "aria-label": "Edit post title" })).toHaveLength(0)+ act(() => renderer!.unmount())++ act(() => { renderer = renderHeader(vi.fn()) })+ expect(renderer!.root.findAllByProps({ "aria-label": "Edit post title" }).length).toBeGreaterThan(0)+ expect(renderer!.root.findAllByProps({ "aria-label": "Post title" })).toHaveLength(0)+ act(() => renderer!.unmount())++ act(() => { renderer = renderHeader(vi.fn(), false) })+ expect(renderer!.root.findAllByProps({ "aria-label": "Edit post title" })).toHaveLength(0)+ expect(renderer!.root.findAllByProps({ "aria-label": "Rename" }).length).toBeGreaterThan(0)+ act(() => renderer!.unmount())+ })++ it("uses the shared create-dialog shell and hero input for post titles", () => {+ let renderer: TestRenderer.ReactTestRenderer+ act(() => { renderer = renderHeader(vi.fn()) })+ act(() => renderer!.root.findByProps({ "aria-label": "Edit post title" }).props.onClick())++ expect(renderer!.root.findByProps({ "aria-label": "Post title" }).props.className).toContain("text-[30px]")+ expect(renderer!.root.findByProps({ children: "Edit post title" }).props.className).toBe("text-xs font-normal text-muted-foreground")+ expect(renderer!.root.findByProps({ "data-testid": "create-dialog-shell" })).toBeDefined()++ act(() => renderer!.unmount())+ })++ it("prevents duplicate saves and keeps a failed post-title draft open", async () => {+ let rejectRename!: (reason?: unknown) => void+ let resolveRename!: () => void+ const onRename = vi.fn(() => new Promise<void>((resolve, reject) => {+ resolveRename = resolve+ rejectRename = reject+ }))+ let renderer: TestRenderer.ReactTestRenderer+ act(() => { renderer = renderHeader(onRename) })+ act(() => renderer!.root.findByProps({ "aria-label": "Edit post title" }).props.onClick())+ act(() => renderer!.root.findByProps({ "aria-label": "Post title" }).props.onChange({ target: { value: "New title" } }))++ const save = renderer!.root.findByProps({ children: "Save" })+ act(() => { void save.props.onClick() })+ act(() => {+ void save.props.onClick()+ renderer!.root.findByProps({ "aria-label": "Post title" }).props.onKeyDown({+ key: "Enter",+ preventDefault: vi.fn(),+ nativeEvent: { isComposing: false },+ })+ })+ expect(onRename).toHaveBeenCalledOnce()+ expect(renderer!.root.findByProps({ children: "Save" }).props.disabled).toBe(true)++ await act(async () => { rejectRename(new Error("save failed")); await Promise.resolve() })+ expect(renderer!.root.findByProps({ "aria-label": "Post title" }).props.value).toBe("New title")+ expect(renderer!.root.findByProps({ children: "Save" }).props.disabled).toBe(false)++ act(() => { void renderer!.root.findByProps({ children: "Save" }).props.onClick() })+ expect(onRename).toHaveBeenCalledTimes(2)+ await act(async () => { resolveRename(); await Promise.resolve() })++ act(() => renderer!.unmount())+ })+})diff --git a/src/web/src/components/community/channel-header.tsx b/src/web/src/components/community/channel-header.tsxindex 12d81006b..4d97123ff 100644--- a/src/web/src/components/community/channel-header.tsx+++ b/src/web/src/components/community/channel-header.tsx@@ -1,6 +1,6 @@"use client"-import { useEffect, useState } from "react"+import { useEffect, useRef, useState } from "react"import type { LucideIcon } from "lucide-react"import { Bell, BellOff, Pin, Users, MessagesSquare, ChevronLeft, Check, Pencil, MoreHorizontal } from "lucide-react"import { NOTIF_LEVELS, USE_SERVER_DEFAULT, type NotifLevel } from "@alook/shared"@@ -17,6 +17,7 @@ import { SlugHint } from "./slug-hint"import { previewSlug } from "@/lib/community/slug-preview"import { MarbleBackground } from "@/components/avatar"import type { RightPanel } from "./_types"+import { CreateDialogShell } from "./create-dialog-shell"// Skeleton header for the loading frame between route change and channel// metadata arriving. Same h-12 footprint as <ChannelHeader> so the body below@@ -55,7 +56,7 @@ export function ChannelHeader({onSetNotifLevel?: (l: ChannelNotifLevel) => voidonBack?: () => voidforum?: boolean- breadcrumb?: { label: string; onRename?: (name: string) => void; onNavigateBack?: () => void }+ breadcrumb?: { label: string; onRename?: (name: string) => void | Promise<void>; titleRename?: boolean; onNavigateBack?: () => void }server?: { id: string; name: string; icon: string | null }tools?: { threads?: boolean; pinned?: boolean; members?: boolean }}) {@@ -90,7 +91,7 @@ export function ChannelHeader({<ChannelIcon className="shrink-0 text-base text-muted-foreground/60" /><span className="min-w-0 truncate text-base font-medium" title={breadcrumb.label}>{breadcrumb.label}</span>{breadcrumb.onRename && (- <BreadcrumbRename label={breadcrumb.label} onRename={breadcrumb.onRename} />+ <BreadcrumbRename label={breadcrumb.label} onRename={breadcrumb.onRename} titleMode={breadcrumb.titleRename} />)}</>) : (@@ -179,7 +180,7 @@ function ServerCrumb({ id, name, icon, size = 5, className = "" }: { id: string;aria-label={name}title={name}>- {icon ? <img src={icon} alt="" className="size-full object-cover" /> : <><MarbleBackground seed={id} /><span className="relative -translate-x-[1px] [-webkit-text-stroke:0.5px_currentColor]">{avatarInitial(name)}</span></>}+ {icon ? <img src={icon} alt="" className="size-full object-cover" /> : <><MarbleBackground seed={id} /><span className="relative -translate-x-px [-webkit-text-stroke:0.5px_currentColor]">{avatarInitial(name)}</span></>}</span>)}@@ -224,9 +225,11 @@ function ChannelNotifDropdown({ level, onSetLevel }: {)}-function BreadcrumbRename({ label, onRename }: { label: string; onRename: (name: string) => void }) {+function BreadcrumbRename({ label, onRename, titleMode = false }: { label: string; onRename: (name: string) => void | Promise<void>; titleMode?: boolean }) {const [open, setOpen] = useState(false)const [draft, setDraft] = useState(label)+ const [saving, setSaving] = useState(false)+ const savingRef = useRef(false)// Keep the draft mirror in sync with the upstream label whenever the dialog// is closed — covers WS-driven renames and channel switches (the parent// component is reused across channelId changes).@@ -234,17 +237,58 @@ function BreadcrumbRename({ label, onRename }: { label: string; onRename: (name:if (!open) setDraft(label)}, [label, open])const draftPreview = previewSlug(draft)- const save = () => {+ const validDraft = titleMode ? Boolean(draft.trim()) : Boolean(draftPreview.slug)+ const save = async () => {+ if (savingRef.current) returnconst trimmed = draft.trim()- if (draftPreview.slug && trimmed !== label) onRename(trimmed)- setOpen(false)+ if (!validDraft || trimmed === label) {+ setOpen(false)+ return+ }+ savingRef.current = true+ setSaving(true)+ try {+ await onRename(trimmed)+ setOpen(false)+ } catch {+ // The owner surfaces the API error. Keep the dialog and draft open so+ // the user can correct or retry the same title.+ } finally {+ savingRef.current = false+ setSaving(false)+ }}return (<>- <Button variant="ghost" size="icon-sm" onClick={() => { setDraft(label); setOpen(true) }} className="text-muted-foreground hover:text-foreground" aria-label="Rename">+ <Button variant="ghost" size="icon-sm" onClick={() => { setDraft(label); setOpen(true) }} className="text-muted-foreground hover:text-foreground" aria-label={titleMode ? "Edit post title" : "Rename"}><Pencil className="size-3.5" /></Button>{open && (+ titleMode ? (+ <CreateDialogShell+ onClose={() => setOpen(false)}+ title="Edit post title"+ footer={(+ <>+ <Button variant="ghost" size="sm" onClick={() => setOpen(false)} disabled={saving}>Cancel</Button>+ <Button size="sm" onClick={() => void save()} disabled={!validDraft || saving}>Save</Button>+ </>+ )}+ >+ <div className="px-5 pb-5 pt-2">+ <input+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(event) => onEnterSubmit(save)(event)}+ placeholder="Post title"+ aria-label="Post title"+ disabled={saving}+ className="w-full border-0 bg-transparent p-0 text-[30px] font-medium leading-tight tracking-tight shadow-none outline-none placeholder:font-normal placeholder:text-muted-foreground/40 focus-visible:ring-0"+ autoFocus+ />+ </div>+ </CreateDialogShell>+ ) : (<Dialog open onOpenChange={(o) => { if (!o) setOpen(false) }}><DialogContent className="w-105 max-w-[calc(100vw-2rem)] p-0"><DialogHeader className="border-b border-border px-4 py-4">@@ -256,8 +300,9 @@ function BreadcrumbRename({ label, onRename }: { label: string; onRename: (name:<Inputvalue={draft}onChange={(e) => setDraft(e.target.value)}- onKeyDown={onEnterSubmit(save)}+ onKeyDown={(event) => onEnterSubmit(save)(event)}placeholder="thread-name"+ aria-label="Thread name"className="h-10"autoFocus/>@@ -265,11 +310,12 @@ function BreadcrumbRename({ label, onRename }: { label: string; onRename: (name:</label></div><DialogFooter className="mx-0 mb-0 flex-row items-center justify-end gap-2 rounded-b-xl border-t border-border bg-card px-4 py-3">- <Button variant="ghost" size="sm" onClick={() => setOpen(false)}>Cancel</Button>- <Button size="sm" onClick={save} disabled={!draftPreview.slug}>Save</Button>+ <Button variant="ghost" size="sm" onClick={() => setOpen(false)} disabled={saving}>Cancel</Button>+ <Button size="sm" onClick={() => void save()} disabled={!validDraft || saving}>Save</Button></DialogFooter></DialogContent></Dialog>+ ))}</>)diff --git a/src/web/src/components/community/channel-member-view-model.test.ts b/src/web/src/components/community/channel-member-view-model.test.tsnew file mode 100644index 000000000..94e176e26--- /dev/null+++ b/src/web/src/components/community/channel-member-view-model.test.ts@@ -0,0 +1,281 @@+import React, { useEffect } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { AddMembersDialog } from "./add-members-dialog"+import { useChannelMemberViewModel } from "./channel-member-view-model"+import { useAddableMembers, useChannelMembers } from "@/hooks/community/use-channel-members"++const mocks = vi.hoisted(() => ({+ serverMembers: [] as Array<Record<string, unknown>>,+ channelMembers: new Map<string, Array<Record<string, unknown>>>(),+ addableMembers: [] as Array<Record<string, unknown>>,+ onlineUserIds: new Set<string>(),+ userStatuses: new Map<string, { emoji: string | null; text: string }>(),+ serverSearch: vi.fn(),+ loadMore: vi.fn(),+ addChannelMember: vi.fn(),+ removeChannelMember: vi.fn(),+ addThreadParticipant: vi.fn(),+ removeThreadParticipant: vi.fn(),+ setMemberRole: vi.fn(),+ kickMember: vi.fn(),+}))++vi.mock("sonner", () => ({ toast: vi.fn() }))+vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))+vi.mock("@/hooks/community/use-server-members", () => ({+ useServerMembers: () => ({+ members: mocks.serverMembers,+ loading: false,+ loadingMore: false,+ hasMore: true,+ loadMore: mocks.loadMore,+ searchMembers: mocks.serverSearch,+ }),+}))+vi.mock("@/hooks/community/use-channel-members", () => ({+ useChannelMembers: vi.fn((channelId: string) => ({+ members: mocks.channelMembers.get(channelId) ?? [],+ isLoading: false,+ })),+ useAddableMembers: vi.fn(() => ({ members: mocks.addableMembers })),+ useAddChannelMember: () => ({ mutateAsync: mocks.addChannelMember }),+ useRemoveChannelMember: () => ({ mutateAsync: mocks.removeChannelMember }),+}))+vi.mock("@/hooks/community/use-thread-participants", () => ({+ useAddThreadParticipant: () => ({ mutateAsync: mocks.addThreadParticipant }),+ useRemoveThreadParticipant: () => ({ mutateAsync: mocks.removeThreadParticipant }),+}))+vi.mock("@/hooks/community/mutations", () => ({+ useSetMemberRole: () => ({ mutate: mocks.setMemberRole }),+ useKickMember: () => ({ mutateAsync: mocks.kickMember }),+}))+vi.mock("@/stores/community/ws", () => ({+ useOnlineUserIds: () => mocks.onlineUserIds,+ useCommunityWsStore: (selector: (state: { userStatuses: typeof mocks.userStatuses }) => unknown) =>+ selector({ userStatuses: mocks.userStatuses }),+}))+vi.mock("@/components/community/add-members-dialog", () => ({+ AddMembersDialog: vi.fn(() => null),+}))+vi.mock("@/components/community/community-panel-sheet", () => ({+ CommunityPanelSheet: () => null,+}))++const mockedAddMembersDialog = vi.mocked(AddMembersDialog)+const mockedUseAddableMembers = vi.mocked(useAddableMembers)+const mockedUseChannelMembers = vi.mocked(useChannelMembers)++function member(userId: string, name: string, overrides: Record<string, unknown> = {}) {+ return {+ id: `member_${userId}`,+ userId,+ name,+ discriminator: "0001",+ avatar: name.slice(0, 1),+ status: "offline",+ sub: "",+ role: "member",+ statusEmoji: null,+ statusText: "",+ source: "explicit",+ isCreator: false,+ ...overrides,+ }+}++function props(overrides: Record<string, unknown> = {}) {+ return {+ serverId: "server_1",+ channelId: "channel_1",+ channelName: "general",+ currentServer: {+ categories: [{ private: false, channels: [{ id: "channel_1" }, { id: "channel_2" }] }],+ },+ channelInServer: { creatorId: "viewer_1" },+ currentChannelMeta: null,+ isChildChannel: false,+ isNotifyUnit: false,+ currentUser: { id: "viewer_1" },+ ...overrides,+ }+}++const captureModel = vi.fn()++function Harness({ modelProps }: { modelProps: ReturnType<typeof props> }) {+ const model = useChannelMemberViewModel(modelProps)+ useEffect(() => {+ captureModel(model)+ }, [model])+ return model.manageMembersDialog+}++function renderHarness(modelProps: ReturnType<typeof props>) {+ return React.createElement(Harness, { modelProps })+}++function latestModel(): ReturnType<typeof useChannelMemberViewModel> {+ return captureModel.mock.calls.at(-1)![0]+}++describe("useChannelMemberViewModel", () => {+ beforeEach(() => {+ mocks.serverMembers = [+ member("viewer_1", "Viewer", { role: "admin" }),+ member("alice_1", "Alice"),+ ]+ mocks.channelMembers = new Map()+ mocks.addableMembers = []+ mocks.onlineUserIds = new Set()+ mocks.userStatuses = new Map()+ mocks.addChannelMember.mockResolvedValue({})+ mocks.removeChannelMember.mockResolvedValue({})+ mocks.addThreadParticipant.mockResolvedValue({})+ mocks.removeThreadParticipant.mockResolvedValue({})+ mocks.kickMember.mockResolvedValue({})+ })++ afterEach(() => {+ vi.clearAllMocks()+ })++ it("uses the public server roster, excludes self, and keeps the raw-roster resolver stable across presence ticks", () => {+ const modelProps = props()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderHarness(modelProps))+ })++ expect(latestModel().memberPanelProps.members.map((row) => row.userId)).toEqual(["viewer_1", "alice_1"])+ expect(latestModel().composerMembers.map((row) => row.userId)).toEqual(["alice_1"])+ expect(latestModel().memberPanelProps.onSearchMembers).toBe(mocks.serverSearch)+ expect(latestModel().memberPanelProps.onAddMember).toBeUndefined()+ expect(latestModel().myRole).toBe("admin")+ const resolver = latestModel().resolveUserName+ expect(resolver("alice_1")).toBe("Alice")++ mocks.onlineUserIds = new Set(["alice_1"])+ mocks.userStatuses = new Map([["alice_1", { emoji: "🌱", text: "Focused" }]])+ act(() => {+ renderer!.update(renderHarness(modelProps))+ })++ expect(latestModel().resolveUserName).toBe(resolver)+ expect(latestModel().memberPanelProps.members.find((row) => row.userId === "alice_1")).toEqual(+ expect.objectContaining({ status: "online", statusEmoji: "🌱", statusText: "Focused" }),+ )+ })++ it("keeps the private addable query lazy and resets search and dialog state when the channel changes", () => {+ mocks.channelMembers.set("channel_1", [member("viewer_1", "Viewer"), member("alice_1", "Alice")])+ mocks.channelMembers.set("channel_2", [member("viewer_1", "Viewer"), member("bob_1", "Bob")])+ mocks.addableMembers = [member("carol_1", "Carol")]+ const privateServer = {+ categories: [{ private: true, channels: [{ id: "channel_1" }, { id: "channel_2" }] }],+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderHarness(props({ currentServer: privateServer })))+ })+ expect(mockedUseAddableMembers).toHaveBeenLastCalledWith("server_1", "channel_1", false)++ act(() => {+ latestModel().memberPanelProps.onSearchMembers?.("alice")+ latestModel().memberPanelProps.onAddMember?.()+ })+ expect(mockedUseAddableMembers).toHaveBeenLastCalledWith("server_1", "channel_1", true)+ expect(mockedAddMembersDialog).toHaveBeenCalledWith(expect.objectContaining({+ title: "Add members to /general",+ }), undefined)++ act(() => {+ renderer!.update(renderHarness(props({+ channelId: "channel_2",+ channelName: "random",+ currentServer: privateServer,+ })))+ })++ expect(mockedUseAddableMembers).toHaveBeenLastCalledWith("server_1", "channel_2", false)+ expect(mockedUseAddableMembers).not.toHaveBeenCalledWith("server_1", "channel_2", true)+ expect(latestModel().manageMembersDialog).toBeNull()+ expect(latestModel().memberPanelProps.members.map((row) => row.userId)).toEqual(["viewer_1", "bob_1"])+ })++ it("routes private audience management only through channel-member mutations", async () => {+ mocks.channelMembers.set("channel_1", [member("viewer_1", "Viewer"), member("alice_1", "Alice")])+ act(() => {+ TestRenderer.create(renderHarness(props({+ currentServer: { categories: [{ private: true, channels: [{ id: "channel_1" }] }] },+ })))+ })++ await latestModel().memberPanelProps.manageContext?.onRemove("alice_1")+ expect(mocks.removeChannelMember).toHaveBeenCalledWith("alice_1")+ expect(mocks.removeThreadParticipant).not.toHaveBeenCalled()+ expect(latestModel().memberPanelProps.manageContext).toEqual(expect.objectContaining({+ viewerUserId: "viewer_1",+ viewerIsCreator: true,+ unitLabel: "general",+ }))+ })++ it("uses participants for the notify panel and the parent roster for mentions and add candidates", async () => {+ mocks.channelMembers.set("thread_1", [+ member("viewer_1", "Viewer", { isCreator: true }),+ member("alice_1", "Alice"),+ ])+ mocks.channelMembers.set("parent_1", [+ member("viewer_1", "Viewer"),+ member("alice_1", "Alice"),+ member("bob_1", "Bob"),+ ])+ act(() => {+ TestRenderer.create(renderHarness(props({+ channelId: "thread_1",+ channelName: "topic",+ currentServer: { categories: [{ private: true, channels: [{ id: "parent_1" }] }] },+ channelInServer: null,+ currentChannelMeta: { name: "topic", parentChannelId: "parent_1", creatorId: "viewer_1" },+ isChildChannel: true,+ isNotifyUnit: true,+ })))+ })++ expect(mockedUseChannelMembers).toHaveBeenCalledWith("thread_1", true)+ expect(mockedUseChannelMembers).toHaveBeenCalledWith("parent_1", true)+ expect(latestModel().memberPanelProps.members.map((row) => row.userId)).toEqual(["viewer_1", "alice_1"])+ expect(latestModel().memberPanelProps.members.every((row) => row.source === undefined)).toBe(true)+ expect(latestModel().composerMembers.map((row) => row.userId)).toEqual(["alice_1", "bob_1"])++ act(() => {+ latestModel().memberPanelProps.onAddMember?.()+ })+ const dialogProps = mockedAddMembersDialog.mock.calls.at(-1)![0]+ expect(dialogProps.candidates).toEqual([+ expect.objectContaining({ userId: "bob_1", name: "Bob" }),+ ])+ await dialogProps.onAdd("bob_1")+ await latestModel().memberPanelProps.manageContext?.onRemove("alice_1")+ expect(mocks.addThreadParticipant).toHaveBeenCalledWith("bob_1")+ expect(mocks.removeThreadParticipant).toHaveBeenCalledWith("alice_1")+ expect(mocks.addChannelMember).not.toHaveBeenCalled()+ expect(mocks.removeChannelMember).not.toHaveBeenCalled()+ })++ it("preserves server role and kick mutation wiring", async () => {+ act(() => {+ TestRenderer.create(renderHarness(props()))+ })++ latestModel().memberPanelProps.onSetRole?.("member_alice", "admin")+ await latestModel().memberPanelProps.onKickMember?.("member_alice")+ expect(mocks.setMemberRole).toHaveBeenCalledWith({+ serverId: "server_1",+ memberId: "member_alice",+ role: "admin",+ }, expect.any(Object))+ expect(mocks.kickMember).toHaveBeenCalledWith({ serverId: "server_1", memberId: "member_alice" })+ })+})diff --git a/src/web/src/components/community/channel-member-view-model.tsx b/src/web/src/components/community/channel-member-view-model.tsxnew file mode 100644index 000000000..a17b7ffae--- /dev/null+++ b/src/web/src/components/community/channel-member-view-model.tsx@@ -0,0 +1,321 @@+"use client"++import { useEffect, useMemo, useState, type ComponentProps, type ReactNode } from "react"+import { toast } from "sonner"+import { AddMembersDialog } from "@/components/community/add-members-dialog"+import type { CommunityPanelSheet } from "@/components/community/community-panel-sheet"+import type { Member, Role } from "@/components/community/_types"+import { toastApiError } from "@/lib/api/client"+import { makeUserNameResolver } from "@/lib/community/display-name"+import { resolveRowPresence } from "@/lib/community/presence"+import {+ useAddableMembers,+ useAddChannelMember,+ useChannelMembers,+ useRemoveChannelMember,+} from "@/hooks/community/use-channel-members"+import { useServerMembers } from "@/hooks/community/use-server-members"+import {+ useAddThreadParticipant,+ useRemoveThreadParticipant,+} from "@/hooks/community/use-thread-participants"+import { useKickMember, useSetMemberRole } from "@/hooks/community/mutations"+import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"++type PanelProps = ComponentProps<typeof CommunityPanelSheet>++export type ChannelMemberPanelProps = Pick<+ PanelProps,+ | "members"+ | "membersLoading"+ | "membersLoadingMore"+ | "membersHasMore"+ | "onLoadMoreMembers"+ | "onSearchMembers"+ | "onAddMember"+ | "manageContext"+ | "onSetRole"+ | "onKickMember"+ | "myRole"+>++type ServerModel = {+ categories?: Array<{+ private?: number | boolean+ channels: Array<{ id: string }>+ }>+} | null | undefined++type ChannelModel = {+ creatorId?: string | null+} | null++type ChannelMeta = {+ name: string+ parentChannelId: string | null+ creatorId?: string | null+} | null++export function useChannelMemberViewModel({+ serverId,+ channelId,+ channelName,+ currentServer,+ channelInServer,+ currentChannelMeta,+ isChildChannel,+ isNotifyUnit,+ currentUser,+}: {+ serverId: string+ channelId: string+ channelName: string+ currentServer: ServerModel+ channelInServer: ChannelModel+ currentChannelMeta: ChannelMeta+ isChildChannel: boolean+ isNotifyUnit: boolean+ currentUser: { id: string }+}): {+ composerMembers: Member[]+ onSearchComposerMembers: (query: string) => void+ memberPanelProps: ChannelMemberPanelProps+ manageMembersDialog: ReactNode+ resolveUserName: (userId: string) => string+ myRole: Role | undefined+} {+ const membersHook = useServerMembers(serverId)+ const onlineUserIds = useOnlineUserIds()+ const userStatuses = useCommunityWsStore((state) => state.userStatuses)+ const [memberUi, setMemberUi] = useState({ channelId, query: "", dialogOpen: false })+ const memberQuery = memberUi.channelId === channelId ? memberUi.query : ""+ const manageMembersOpen = memberUi.channelId === channelId && memberUi.dialogOpen++ useEffect(() => {+ setMemberUi((current) =>+ current.channelId === channelId && current.query === "" && !current.dialogOpen+ ? current+ : { channelId, query: "", dialogOpen: false },+ )+ }, [channelId])++ const members = useMemo(+ () => membersHook.members.map((member) => {+ const liveStatus = userStatuses.get(member.userId)+ return {+ ...member,+ status: resolveRowPresence(member, onlineUserIds, currentUser.id),+ statusEmoji: liveStatus ? liveStatus.emoji : member.statusEmoji,+ statusText: liveStatus ? liveStatus.text : member.statusText,+ }+ }),+ [currentUser.id, membersHook.members, onlineUserIds, userStatuses],+ )++ const currentChannelPrivate = useMemo(() => {+ const anchorId = isChildChannel+ ? (currentChannelMeta?.parentChannelId ?? channelId)+ : channelId+ const category = currentServer?.categories?.find((candidate) =>+ candidate.channels.some((channel) => channel.id === anchorId),+ )+ return !!category?.private+ }, [channelId, currentChannelMeta, currentServer, isChildChannel])++ const channelMembersHook = useChannelMembers(+ channelId,+ isNotifyUnit || (currentChannelPrivate && !isNotifyUnit),+ )+ const parentChannelId = isNotifyUnit ? currentChannelMeta?.parentChannelId ?? null : null+ const parentChannelMembersHook = useChannelMembers(parentChannelId ?? "", !!parentChannelId)+ const addableChannelMembers = useAddableMembers(+ serverId,+ channelId,+ manageMembersOpen && currentChannelPrivate && !isNotifyUnit,+ )+ const addChannelMemberMut = useAddChannelMember(channelId)+ const removeChannelMemberMut = useRemoveChannelMember(channelId)+ const addThreadParticipantMut = useAddThreadParticipant(channelId)+ const removeThreadParticipantMut = useRemoveThreadParticipant(channelId)+ const setMemberRoleMut = useSetMemberRole()+ const kickMemberMut = useKickMember()++ const panelMembers = useMemo(() => {+ const query = memberQuery.trim().toLowerCase()+ const matches = (name: string, discriminator?: string | null) =>+ !query || name.toLowerCase().includes(query) || (discriminator ?? "").toLowerCase().includes(query)+ const withPresence = (member: {+ userId: string+ name: string+ discriminator: string+ avatar: string+ statusEmoji?: string | null+ statusText?: string | null+ isCreator?: boolean+ source?: "explicit" | "inherited" | "admin"+ }): Member => {+ const liveStatus = userStatuses.get(member.userId)+ return {+ id: member.userId,+ userId: member.userId,+ name: member.name,+ discriminator: member.discriminator,+ avatar: member.avatar,+ sub: "",+ role: "member",+ status: resolveRowPresence(member, onlineUserIds, currentUser.id),+ statusEmoji: liveStatus ? liveStatus.emoji : (member.statusEmoji ?? null),+ statusText: liveStatus ? liveStatus.text : (member.statusText ?? ""),+ isCreator: member.isCreator,+ source: member.source,+ }+ }++ if (isNotifyUnit) {+ return channelMembersHook.members+ .filter((member) => matches(member.name, member.discriminator))+ .map((member) => withPresence({ ...member, source: undefined }))+ }+ if (!currentChannelPrivate) return members+ return channelMembersHook.members+ .filter((member) => matches(member.name, member.discriminator))+ .map(withPresence)+ }, [+ channelMembersHook.members,+ currentChannelPrivate,+ currentUser.id,+ isNotifyUnit,+ memberQuery,+ members,+ onlineUserIds,+ userStatuses,+ ])++ const composerMembers = useMemo(() => {+ if (!currentChannelPrivate) {+ return members.filter((member) => member.userId !== currentUser.id)+ }+ const roster = isNotifyUnit ? parentChannelMembersHook.members : channelMembersHook.members+ return roster+ .filter((member) => member.userId !== currentUser.id)+ .map((member) => {+ const liveStatus = userStatuses.get(member.userId)+ return {+ ...member,+ status: resolveRowPresence(member, onlineUserIds, currentUser.id),+ statusEmoji: liveStatus ? liveStatus.emoji : member.statusEmoji,+ statusText: liveStatus ? liveStatus.text : member.statusText,+ }+ })+ }, [+ channelMembersHook.members,+ currentChannelPrivate,+ currentUser.id,+ isNotifyUnit,+ members,+ onlineUserIds,+ parentChannelMembersHook.members,+ userStatuses,+ ])++ const myRole = members.find((member) => member.userId === currentUser.id)?.role+ const unitCreatorId = isChildChannel+ ? currentChannelMeta?.creatorId+ : channelInServer?.creatorId+ const viewerIsUnitCreator = !!unitCreatorId && unitCreatorId === currentUser.id+ const scopedDrawer = isNotifyUnit || currentChannelPrivate+ const removeMember = isNotifyUnit ? removeThreadParticipantMut : removeChannelMemberMut+ const manageContext = scopedDrawer+ ? {+ viewerUserId: currentUser.id,+ viewerIsCreator: viewerIsUnitCreator,+ unitLabel: currentChannelMeta?.name ?? channelName,+ onLeave: (userId: string) => removeMember.mutateAsync(userId),+ onRemove: (userId: string) => removeMember.mutateAsync(userId),+ }+ : undefined++ const memberPanelProps: ChannelMemberPanelProps = {+ members: panelMembers,+ membersLoading: scopedDrawer ? channelMembersHook.isLoading : membersHook.loading,+ membersLoadingMore: scopedDrawer ? false : membersHook.loadingMore,+ membersHasMore: scopedDrawer ? false : membersHook.hasMore,+ onLoadMoreMembers: scopedDrawer ? undefined : membersHook.loadMore,+ onSearchMembers: scopedDrawer+ ? (query) => setMemberUi({ channelId, query, dialogOpen: manageMembersOpen })+ : membersHook.searchMembers,+ onAddMember: scopedDrawer+ ? () => setMemberUi({ channelId, query: memberQuery, dialogOpen: true })+ : undefined,+ manageContext,+ myRole,+ onSetRole: (memberId: string, role: Role) => {+ setMemberRoleMut.mutate({ serverId, memberId, role }, {+ onSuccess: () => toast("Role updated"),+ onError: (error) => toastApiError(error, "Failed to update role"),+ })+ },+ onKickMember: (memberId: string) =>+ kickMemberMut.mutateAsync({ serverId, memberId }).then(() => toast("Member kicked")),+ }++ const manageMembersDialog = useMemo(() => {+ if (!manageMembersOpen) return null+ if (isNotifyUnit) {+ const participantIds = new Set(channelMembersHook.members.map((member) => member.userId))+ const candidates = parentChannelMembersHook.members+ .filter((member) => !participantIds.has(member.userId) && member.userId !== currentUser.id)+ .map((member) => ({ userId: member.userId, name: member.name ?? null, avatar: member.avatar }))+ return (+ <AddMembersDialog+ title={`Add participants to /${currentChannelMeta?.name ?? channelName}`}+ subtitle="Added people are notified of new replies. Anyone with access can already read it."+ candidates={candidates}+ onAdd={(userId) => addThreadParticipantMut.mutateAsync(userId)}+ onClose={() => setMemberUi({ channelId, query: memberQuery, dialogOpen: false })}+ />+ )+ }+ const candidates = addableChannelMembers.members.map((member) => ({+ userId: member.userId,+ name: member.name ?? null,+ avatar: member.avatar,+ }))+ return (+ <AddMembersDialog+ title={`Add members to /${channelName}`}+ subtitle="Added members can see and post here."+ candidates={candidates}+ onAdd={(userId) => addChannelMemberMut.mutateAsync(userId)}+ onClose={() => setMemberUi({ channelId, query: memberQuery, dialogOpen: false })}+ />+ )+ }, [+ addChannelMemberMut,+ addThreadParticipantMut,+ addableChannelMembers.members,+ channelMembersHook.members,+ channelName,+ channelId,+ currentChannelMeta,+ currentUser.id,+ isNotifyUnit,+ manageMembersOpen,+ memberQuery,+ parentChannelMembersHook.members,+ ])++ const resolveUserName = useMemo(+ () => makeUserNameResolver(membersHook.members),+ [membersHook.members],+ )++ return {+ composerMembers,+ onSearchComposerMembers: membersHook.searchMembers,+ memberPanelProps,+ manageMembersDialog,+ resolveUserName,+ myRole,+ }+}diff --git a/src/web/src/components/community/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channel-route.text-scroll-target.test.tsnew file mode 100644index 000000000..034fe91a6--- /dev/null+++ b/src/web/src/components/community/channel-route.text-scroll-target.test.ts@@ -0,0 +1,374 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { ChannelRoute } from "./channel-route"+import { ForumChannelSurface } from "./forum-channel-surface"+import { MessageList } from "./message-list"+import { useChannelMemberViewModel } from "./channel-member-view-model"+import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"++const { mockRouteModel, mockMemberViewModel } = vi.hoisted(() => ({+ mockRouteModel: {+ server: {+ id: "server_1",+ name: "Server",+ icon: null,+ categories: [{ channels: [{ id: "channel_1", name: "general", type: "text" }] }],+ },+ channel: { id: "channel_1", name: "general", type: "text" },+ parent: null,+ currentChannelMeta: null as null | {+ id: string+ name: string+ parentChannelId: string+ parentMessageId: string | null+ creatorId: string+ },+ isForum: false,+ isChild: false,+ isForumPostChild: false,+ isNotifyUnit: false,+ routeHydrated: true,+ },+ mockMemberViewModel: {+ composerMembers: [],+ onSearchComposerMembers: vi.fn(),+ memberPanelProps: { members: [] },+ manageMembersDialog: null,+ resolveUserName: (userId: string) => userId,+ myRole: "member",+ },+}))++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),+ useSearchParams: () => ({ get: (key: string) => key === "msg" ? "m_target" : null }),+}))+vi.mock("sonner", () => ({ toast: vi.fn() }))+vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))+vi.mock("@/components/community/channel-header", () => ({+ ChannelHeader: () => null,+ ChannelHeaderSkeleton: () => null,+}))+vi.mock("@/components/community/message-list", () => ({ MessageList: vi.fn(() => null) }))+vi.mock("@/components/community/composer", () => ({+ Composer: () => null,+ ComposerSkeleton: () => null,+}))+vi.mock("@/components/community/forum-view", () => ({ ForumViewSkeleton: () => null }))+vi.mock("@/components/community/forum-channel-surface", () => ({+ ForumChannelSurface: vi.fn(() => null),+}))+vi.mock("@/components/community/channel-member-view-model", () => ({+ useChannelMemberViewModel: vi.fn(() => mockMemberViewModel),+}))+vi.mock("@/components/community/channel-shell", () => ({+ ChannelShell: ({ body }: { body: React.ReactNode }) => body,+}))+vi.mock("@/components/community/community-panel-sheet", () => ({ CommunityPanelSheet: () => null }))+vi.mock("@/components/community/message-context-sheet", () => ({ MessageContextSheet: () => null }))+vi.mock("@/components/community/thread-opener", () => ({ ThreadOpener: () => null }))+vi.mock("@/components/community/add-members-dialog", () => ({ AddMembersDialog: () => null }))+vi.mock("@/components/community/_types", () => ({ canManageServer: () => false }))+vi.mock("@alook/shared", () => ({+ isForum: () => false,+ deriveThreadName: () => "thread",+ USE_SERVER_DEFAULT: "default",+}))+vi.mock("@/lib/community/last-channel", () => ({ setLastChannel: vi.fn() }))+vi.mock("@/stores/community", () => {+ const state = {+ pendingReply: null,+ setPendingReply: vi.fn(),+ registerUiHandlers: vi.fn(),+ }+ const useCommunityStore = Object.assign(+ (selector: (value: typeof state) => unknown) => selector(state),+ { getState: () => state },+ )+ return {+ useCommunityStore,+ useCurrentChannelId: () => "channel_1",+ useUiHandlers: () => ({}),+ useTypingUsersForScope: () => [],+ useTypingNamesForScope: () => ({}),+ }+})+vi.mock("@/contexts/community/current-user", () => ({+ useCurrentUser: () => ({ id: "viewer_1", name: "Viewer", avatar: "V" }),+}))+vi.mock("@/hooks/community/use-channel-route-model", () => ({+ useChannelRouteModel: () => mockRouteModel,+}))+vi.mock("@/hooks/community/use-server-members", () => ({+ useServerMembers: () => ({+ members: [],+ loading: false,+ loadingMore: false,+ hasMore: false,+ loadMore: vi.fn(),+ searchMembers: vi.fn(),+ }),+}))+vi.mock("@/hooks/community/use-channel-members", () => ({+ useChannelMembers: () => ({ members: [], isLoading: false }),+ useAddableMembers: () => ({ members: [] }),+ useAddChannelMember: () => ({ mutateAsync: vi.fn() }),+ useRemoveChannelMember: () => ({ mutateAsync: vi.fn() }),+}))+vi.mock("@/hooks/community/use-thread-participants", () => ({+ useAddThreadParticipant: () => ({ mutateAsync: vi.fn() }),+ useRemoveThreadParticipant: () => ({ mutateAsync: vi.fn() }),+}))+vi.mock("@/hooks/community/use-message", () => ({+ useMessage: () => ({ message: null, isLoading: false }),+}))+vi.mock("@/hooks/community/use-channel-message-feed", () => ({+ useChannelMessageFeed: vi.fn(),+}))+vi.mock("@/hooks/community/use-notification-settings", () => ({+ useNotificationSettings: () => ({ channel: {} }),+}))+vi.mock("@/stores/community/ws", () => ({+ useOnlineUserIds: () => new Set(),+ useCommunityWsStore: (selector: (state: { userStatuses: Map<string, unknown> }) => unknown) =>+ selector({ userStatuses: new Map() }),+}))+vi.mock("@/hooks/community/mutations", () => ({+ useSendMessage: () => ({ mutateAsync: vi.fn() }),+ useToggleReactionApi: () => vi.fn(),+ usePinMessage: () => ({ mutate: vi.fn() }),+ useUnpinMessage: () => ({ mutate: vi.fn() }),+ useToggleMark: () => vi.fn(),+ useEditMessage: () => ({ mutate: vi.fn(), mutateAsync: vi.fn() }),+ useCreateThread: () => ({ mutateAsync: vi.fn() }),+ useCreateForumThread: () => ({ mutateAsync: vi.fn() }),+ useUpdatePostTags: () => ({ mutate: vi.fn(), isPending: false }),+ useDeleteForumThread: () => ({ mutate: vi.fn(), isPending: false }),+ useSetMemberRole: () => ({ mutate: vi.fn() }),+ useKickMember: () => ({ mutateAsync: vi.fn() }),+ useSetChannelNotif: () => ({ mutate: vi.fn() }),+ useUploadFile: () => ({ mutateAsync: vi.fn() }),+ zipUploadResultsWithDimensions: () => [],+ sendNonce: () => "nonce_1",+}))+vi.mock("@/hooks/community/use-community-ws", () => ({+ communityWsSendTyping: vi.fn(),+ communityWsResetTypingThrottle: vi.fn(),+}))++const mockedMessageList = vi.mocked(MessageList)+const mockedUseChannelMessageFeed = vi.mocked(useChannelMessageFeed)+const mockedUseChannelMemberViewModel = vi.mocked(useChannelMemberViewModel)+const mockedForumChannelSurface = vi.mocked(ForumChannelSurface)++function feed(overrides: Record<string, unknown> = {}) {+ return {+ messages: [],+ isLoading: false,+ isError: false,+ isFetchingOlder: false,+ isFetchingNewer: false,+ hasMoreOlder: false,+ hasMoreNewer: false,+ fetchOlder: vi.fn(),+ fetchNewer: vi.fn(),+ jumpToPresent: vi.fn(),+ latestSeq: 0,+ readSnapshot: null,+ readSnapshotFetching: false,+ newDividerBefore: undefined,+ anchorInCache: false,+ unreadCount: 0,+ setScrollRootEl: vi.fn(),+ threads: [],+ threadsLoading: false,+ pinned: [],+ pinnedLoading: false,+ ...overrides,+ } as ReturnType<typeof useChannelMessageFeed>+}++function configureThreadRoute() {+ Object.assign(mockRouteModel, {+ channel: null,+ parent: { id: "parent_1", name: "general", type: "text" },+ currentChannelMeta: {+ id: "channel_1",+ name: "thread",+ parentChannelId: "parent_1",+ parentMessageId: "opener_1",+ creatorId: "viewer_1",+ },+ isChild: true,+ isNotifyUnit: true,+ })+ mockRouteModel.server.categories = [{+ channels: [{ id: "parent_1", name: "general", type: "text" }],+ }]+}++describe("ChannelRoute message surface ownership", () => {+ beforeEach(() => {+ vi.useFakeTimers()+ mockedMessageList.mockClear()+ Object.assign(mockRouteModel, {+ server: {+ id: "server_1",+ name: "Server",+ icon: null,+ categories: [{ channels: [{ id: "channel_1", name: "general", type: "text" }] }],+ },+ channel: { id: "channel_1", name: "general", type: "text" },+ parent: null,+ currentChannelMeta: null,+ isForum: false,+ isChild: false,+ isForumPostChild: false,+ isNotifyUnit: false,+ routeHydrated: true,+ })+ })++ afterEach(() => {+ vi.useRealTimers()+ vi.clearAllMocks()+ })++ it("keeps the route anchor until MessageList reports a successful jump", () => {+ let surfaceFeed = feed({ messages: [{ id: "m_unrelated" }] })+ mockedUseChannelMessageFeed.mockImplementation(() => surfaceFeed)+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })++ expect(mockedUseChannelMessageFeed).toHaveBeenCalledTimes(1)+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")++ surfaceFeed = feed({ messages: [{ id: "m_target" }] })+ act(() => {+ renderer!.update(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })++ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")+ act(() => vi.advanceTimersByTime(5000))+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")+ act(() => mockedMessageList.mock.calls.at(-1)?.[0].onScrollTargetConsumed?.("m_target"))+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBeNull()+ })++ it("clears the route anchor only after the authoritative anchor request errors", () => {+ let surfaceFeed = feed({ messages: [{ id: "m_unrelated" }] })+ mockedUseChannelMessageFeed.mockImplementation(() => surfaceFeed)+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })++ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")+ surfaceFeed = feed({ messages: [{ id: "m_unrelated" }], isError: true })+ act(() => {+ renderer!.update(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBeNull()+ })++ it("does not initialize an active message feed for a forum route", () => {+ Object.assign(mockRouteModel, {+ channel: { id: "channel_1", name: "forum", type: "forum" },+ isForum: true,+ })+ mockedUseChannelMessageFeed.mockImplementation(() => feed())++ act(() => {+ TestRenderer.create(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })++ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()+ expect(mockedUseChannelMemberViewModel).toHaveBeenCalledTimes(1)+ expect(mockedForumChannelSurface).toHaveBeenCalledTimes(1)+ expect(mockedForumChannelSurface).toHaveBeenCalledWith(expect.objectContaining({+ channelId: "channel_1",+ serverId: "server_1",+ }), undefined)+ })++ it("initializes only the child feed for a thread route", () => {+ configureThreadRoute()+ mockedUseChannelMessageFeed.mockImplementation(() => feed({ anchorInCache: true }))++ act(() => {+ TestRenderer.create(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })++ expect(mockedUseChannelMessageFeed).toHaveBeenCalledTimes(1)+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({+ channelId: "channel_1",+ isChildChannel: true,+ }))+ })++ it("keeps a child target through warm cache and 5000ms until MessageList consumes it", () => {+ configureThreadRoute()+ let childFeed = feed({ messages: [{ id: "m_unrelated" }], anchorInCache: true })+ mockedUseChannelMessageFeed.mockImplementation(() => childFeed)+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })++ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")+ childFeed = feed({ messages: [{ id: "m_target" }], anchorInCache: true })+ act(() => {+ renderer!.update(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })+ act(() => vi.advanceTimersByTime(5000))+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")+ act(() => mockedMessageList.mock.calls.at(-1)?.[0].onScrollTargetConsumed?.("m_target"))+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBeNull()+ })++ it("clears a missing child target only after the child feed errors", () => {+ configureThreadRoute()+ let childFeed = feed({ messages: [{ id: "m_unrelated" }], anchorInCache: true })+ mockedUseChannelMessageFeed.mockImplementation(() => childFeed)+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")++ childFeed = feed({ messages: [{ id: "m_unrelated" }], isError: true, anchorInCache: true })+ act(() => {+ renderer!.update(+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),+ )+ })+ expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBeNull()+ })+})diff --git a/src/web/src/components/community/channel-route.tsx b/src/web/src/components/community/channel-route.tsxnew file mode 100644index 000000000..d6aae428e--- /dev/null+++ b/src/web/src/components/community/channel-route.tsx@@ -0,0 +1,268 @@+"use client"++import { useCallback, useEffect, useMemo, useState } from "react"+import { useRouter, useSearchParams } from "next/navigation"+import { toastApiError } from "@/lib/api/client"+import { useBreakpoint } from "@/hooks/use-mobile"+import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"+import { MessageList } from "@/components/community/message-list"+import { ComposerSkeleton } from "@/components/community/composer"+import { ForumViewSkeleton } from "@/components/community/forum-view"+import { TextChannelSurface } from "@/components/community/text-channel-surface"+import { ThreadChannelSurface } from "@/components/community/thread-channel-surface"+import { ForumChannelSurface } from "@/components/community/forum-channel-surface"+import { useChannelMemberViewModel } from "@/components/community/channel-member-view-model"+import type { OpenProfile } from "@/components/community/_types"+import { canManageServer } from "@/components/community/_types"+import { USE_SERVER_DEFAULT } from "@alook/shared"+import { setLastChannel } from "@/lib/community/last-channel"+import { resolveChannelDisplayName } from "@/lib/community/channel-display-name"+import {+ useCurrentChannelId,+ useUiHandlers,+} from "@/stores/community"+import { useCurrentUser } from "@/contexts/community/current-user"+import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"+import { useMessage } from "@/hooks/community/use-message"+import { useNotificationSettings } from "@/hooks/community/use-notification-settings"+import { useSetChannelNotif } from "@/hooks/community/mutations"++/**+ * /c/channels/:serverId/:channelId+ *+ * - Forum channel: ForumView+ * - Text channel: MessageList + Composer + right panels+ * - Child thread opened via URL: child-channel view (breadcrumb + list)+ */+export function ChannelRoute({ serverParam, channelId }: { serverParam: string; channelId: string }) {+ const router = useRouter()+ const searchParams = useSearchParams()+ const serverId = decodeURIComponent(serverParam)+ // Remember this as the server's last-opened channel (per-browser navigation+ // memory) so re-entering the server restores here instead of the default.+ // Pure localStorage write; failures are swallowed in the helper.+ useEffect(() => {+ setLastChannel(serverId, channelId)+ }, [serverId, channelId])+ // Cross-channel "jump to message" target, captured ONCE at mount from `?msg=`.+ // `ChannelView` is keyed by `serverId/channelId`, so a fresh jump remounts and+ // re-reads this. The param is stripped from the URL right after (below) so a+ // refresh/back doesn't re-trigger the jump; this frozen copy still drives the+ // anchor + scroll for this mount.+ const [jumpTargetId] = useState<string | null>(() => searchParams.get("msg"))+ const bp = useBreakpoint()+ const currentUser = useCurrentUser()+ const uiHandlers = useUiHandlers()+ const currentChannelId = useCurrentChannelId()+ const routeModel = useChannelRouteModel(serverId, serverParam, channelId)+ const {+ server: currentServer,+ channel: channelInServer,+ parent: parentChannelInServer,+ currentChannelMeta,+ isForum,+ isChild: isChildChannel,+ isForumPostChild,+ isNotifyUnit,+ } = routeModel+ const { message: forumPostOpener, isLoading: forumPostOpenerLoading } = useMessage(+ isForumPostChild ? currentChannelMeta?.parentMessageId : null,+ )+ const channelName = useMemo(() => resolveChannelDisplayName({+ forumPostTitle: isForumPostChild ? forumPostOpener?.content : null,+ topLevelName: channelInServer?.name,+ childChannelName: isForumPostChild ? null : currentChannelMeta?.name,+ forumListName: null,+ threadListName: null,+ fallback: isForumPostChild ? "Post" : "channel",+ }), [channelInServer, currentChannelMeta, forumPostOpener, isForumPostChild])+ const memberViewModel = useChannelMemberViewModel({+ serverId,+ channelId,+ channelName,+ currentServer,+ channelInServer,+ currentChannelMeta,+ isChildChannel,+ isNotifyUnit,+ currentUser,+ })+ const {+ composerMembers,+ onSearchComposerMembers,+ memberPanelProps,+ manageMembersDialog,+ resolveUserName,+ myRole,+ } = memberViewModel++ // `/`-autocomplete candidates for both Composer call sites below — single+ // server, so no directory hook needed here (see `me/[dmId]/page.tsx` for+ // the cross-server DM case).+ const channelRefCandidates = useMemo(() => {+ const allChannels = currentServer?.categories?.flatMap((c) => c.channels) ?? []+ return allChannels.map((ch) => ({+ id: ch.id,+ name: ch.name,+ serverId,+ serverName: currentServer?.name ?? "",+ }))+ }, [currentServer, serverId])+ const notifs = useNotificationSettings()+ const channelNotif = notifs.channel+ const { mutate: setChannelNotif } = useSetChannelNotif()++ const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])+ const goRouteBack = useCallback(() => { router.back() }, [router])+ const setNotificationLevel = useCallback((level: ChannelNotifLevel) => {+ setChannelNotif({ channelId, level }, {+ onError: (error) => toastApiError(error, "Failed to update notification level"),+ })+ }, [channelId, setChannelNotif])++ // Strip `?msg=` from the URL right after mount so a refresh/back doesn't+ // re-trigger the jump. The frozen `jumpTargetId` still seeds the mounted+ // message controller for this mount; this only cleans the address.+ useEffect(() => {+ if (!jumpTargetId) return+ router.replace(`/c/channels/${serverParam}/${channelId}`, { scroll: false })+ // eslint-disable-next-line react-hooks/exhaustive-deps -- run once for this mount's jump+ }, [])++ const enterThread = useCallback((id: string) => {+ // No eager read PUT here — the thread page's `useEagerChannelRead` fires it+ // on mount AFTER its read-state snapshot latches, so the "New" divider+ // still anchors to the pre-open pointer. A PUT here would race the snapshot.+ router.push(`/c/channels/${serverParam}/${id}`)+ }, [router, serverParam])++ const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {+ uiHandlers.openProfile?.(name, e, discriminator, userId)+ }, [uiHandlers])++ const channelHydrated =+ currentChannelId === channelId &&+ routeModel.routeHydrated &&+ (!isForumPostChild || !forumPostOpenerLoading)+ if (!channelHydrated) {+ if (isForum) {+ return (+ <>+ <ChannelHeaderSkeleton onBack={bp === "mobile" ? goBack : undefined} />+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ <ForumViewSkeleton />+ </main>+ </>+ )+ }+ return (+ <>+ <ChannelHeaderSkeleton onBack={bp === "mobile" ? goBack : undefined} />+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ {/*+ `key={channelId}` MUST match the hydrated branches' key below —+ verified empirically (react-test-renderer) that a mismatched key+ (this branch had none before) is what causes React to treat this+ and the hydrated-branch `<MessageList>` as different component+ identities, forcing a full unmount/remount instead of a props+ update on one instance when `channelHydrated` flips true. With+ matching keys, this works correctly even though this early+ `return` and the hydrated branches' `return` produce+ structurally different JSX trees — React's reconciliation only+ needs the position + type + key to line up.+ */}+ <MessageList key={channelId} channel="" messages={[]} loading={true} onOpenThread={() => { }} />+ <ComposerSkeleton />+ </main>+ </>+ )+ }++ // ── Child channel view (forum post / thread opened via URL) ─────────────+ if (isChildChannel) {+ return (+ <ThreadChannelSurface+ channelId={channelId}+ serverId={serverId}+ serverParam={serverParam}+ channelName={channelName}+ viewer={currentUser}+ anchorMessageId={jumpTargetId}+ parentChannelId={currentChannelMeta?.parentChannelId ?? null}+ parentMessageId={currentChannelMeta?.parentMessageId ?? null}+ parentChannelName={parentChannelInServer?.name ?? "channel"}+ parentIsForum={isForumPostChild}+ childCreatorId={currentChannelMeta?.creatorId}+ canRenameThread={canManageServer(myRole)}+ headerServer={bp === "mobile" && currentServer+ ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon }+ : undefined}+ notificationLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}+ onSetNotificationLevel={setNotificationLevel}+ onBack={bp === "mobile" ? goRouteBack : undefined}+ onLoadingBack={bp === "mobile" ? goBack : undefined}+ composerMembers={composerMembers}+ onSearchComposerMembers={onSearchComposerMembers}+ channelRefCandidates={channelRefCandidates}+ memberPanelProps={memberPanelProps}+ manageMembersDialog={manageMembersDialog}+ uiHandlers={uiHandlers}+ onOpenChild={enterThread}+ onOpenProfile={openProfile}+ resolveUserName={resolveUserName}+ />+ )+ }++ // ── Forum view ──────────────────────────────────────────────────────────+ if (isForum) {+ return (+ <ForumChannelSurface+ serverId={serverId}+ channelId={channelId}+ channelName={channelName}+ viewer={currentUser}+ viewerRole={myRole}+ headerServer={bp === "mobile" && currentServer+ ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon }+ : undefined}+ notificationLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}+ onSetNotificationLevel={setNotificationLevel}+ onBack={bp === "mobile" ? goBack : undefined}+ composerMembers={composerMembers}+ onSearchComposerMembers={onSearchComposerMembers}+ memberPanelProps={memberPanelProps}+ manageMembersDialog={manageMembersDialog}+ onOpenPost={enterThread}+ onOpenProfile={openProfile}+ />+ )+ }++ // ── Standard channel view ───────────────────────────────────────────────+ return (+ <TextChannelSurface+ channelId={channelId}+ serverId={serverId}+ serverParam={serverParam}+ channelName={channelName}+ viewer={currentUser}+ anchorMessageId={jumpTargetId}+ headerServer={bp === "mobile" && currentServer+ ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon }+ : undefined}+ notificationLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}+ onSetNotificationLevel={setNotificationLevel}+ onBack={bp === "mobile" ? goBack : undefined}+ composerMembers={composerMembers}+ onSearchComposerMembers={onSearchComposerMembers}+ channelRefCandidates={channelRefCandidates}+ memberPanelProps={memberPanelProps}+ manageMembersDialog={manageMembersDialog}+ uiHandlers={uiHandlers}+ onOpenThread={enterThread}+ onOpenProfile={openProfile}+ resolveUserName={resolveUserName}+ />+ )+}diff --git a/src/web/src/components/community/channel-shell.tsx b/src/web/src/components/community/channel-shell.tsxnew file mode 100644index 000000000..f29293c28--- /dev/null+++ b/src/web/src/components/community/channel-shell.tsx@@ -0,0 +1,16 @@+import type { ReactNode } from "react"++/** Shared route chrome. Business surfaces own every hook and provide slots. */+export function ChannelShell({ header, body, panels, dialogs }: {+ header: ReactNode+ body: ReactNode+ panels?: ReactNode+ dialogs?: ReactNode+}) {+ return <>+ {header}+ {body}+ {panels}+ {dialogs}+ </>+}diff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsxindex c901e483a..96c0607d4 100644--- a/src/web/src/components/community/channel-sidebar.tsx+++ b/src/web/src/components/community/channel-sidebar.tsx@@ -34,7 +34,7 @@ type Dialog =// right-click) creates; channels right-click to edit/delete. A private category only// lets admins create channels — non-admins are blocked via onBlockedCreate.export const ChannelSidebar = memo(function ChannelSidebar({- tree, serverName, serverIcon, activeChannel, setActiveChannel, noHeader, onOpenSettings,+ tree, serverName, activeChannel, setActiveChannel, noHeader, onOpenSettings,isAdmin = true, currentUserId, onBlockedCreate, mutedChannels, loading,onCreateChannel, onCreateCategory, onDeleteChannel, onDeleteCategory,onUpdateCategory, onRenameChannel, onReorderCategories, onReorderChannels,@@ -329,6 +329,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({)}{dialog?.kind === "manage-members" && serverId && (<ChannelAddMembersDialog+ serverId={serverId}channelId={dialog.channelId}channelName={dialog.channelName}onClose={() => setDialog(null)}diff --git a/src/web/src/components/community/community-inbox-popover.test.ts b/src/web/src/components/community/community-inbox-popover.test.tsnew file mode 100644index 000000000..58b6542cf--- /dev/null+++ b/src/web/src/components/community/community-inbox-popover.test.ts@@ -0,0 +1,103 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, expectTypeOf, it, vi } from "vitest"+import { InboxPopover } from "./community-inbox-popover"+import type { UnreadServer } from "./_types"++vi.mock("@/components/ui/tabs", () => ({+ Tabs: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+ TabsList: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+ TabsTrigger: ({ children }: { children: React.ReactNode }) => React.createElement("button", null, children),+ TabsContent: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+}))++function textOf(node: TestRenderer.ReactTestInstance | string | number): string {+ if (typeof node === "string" || typeof node === "number") return String(node)+ return node.children.map((child) => textOf(child)).join("")+}++function unreadFixture(): UnreadServer[] {+ return [{+ serverId: "s1",+ serverName: "Server",+ channels: [{+ channelId: "f1",+ channelName: "Forum",+ type: "forum",+ lastMessageAt: "2026-08-07T10:00:00.000Z",+ mentionCount: 0,+ children: [+ {+ channelId: "p1",+ channelName: "Full authoritative opener content",+ type: "thread",+ lastMessageAt: "2026-08-07T10:00:00.000Z",+ mentionCount: 0,+ openerMessageId: "m1",+ },+ {+ channelId: "t1",+ channelName: "Reply-only thread",+ type: "thread",+ lastMessageAt: "2026-08-07T09:00:00.000Z",+ mentionCount: 0,+ },+ ],+ }],+ }]+}++function popover(onOpenChannel: ReturnType<typeof vi.fn>, onOpenForumThread: ReturnType<typeof vi.fn>) {+ return React.createElement(InboxPopover, {+ unreads: unreadFixture(),+ unreadDms: [],+ mentions: [],+ marked: [],+ onOpenChannel,+ onOpenForumThread,+ })+}++describe("InboxPopover forum post rows", () => {+ it("requires the forum-thread callback so opener-backed buttons cannot be inert", () => {+ expectTypeOf<Parameters<typeof InboxPopover>[0]>().toMatchTypeOf<{+ onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void+ }>()+ })++ it("renders the authoritative opener title and passes parent/opener targets", async () => {+ const onOpenChannel = vi.fn()+ const onOpenForumThread = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(popover(onOpenChannel, onOpenForumThread))+ })++ const row = renderer.root+ .findAllByType("button")+ .find((button) => textOf(button).includes("Full authoritative opener content"))+ expect(row).toBeDefined()+ await act(async () => row!.props.onClick())++ expect(onOpenForumThread).toHaveBeenCalledWith("s1", "f1", "p1", "m1")+ expect(onOpenChannel).not.toHaveBeenCalledWith("s1", "p1")+ })++ it("keeps reply-only child rows on the existing channel callback", async () => {+ const onOpenChannel = vi.fn()+ const onOpenForumThread = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(popover(onOpenChannel, onOpenForumThread))+ })++ const row = renderer.root+ .findAllByType("button")+ .find((button) => textOf(button).includes("Reply-only thread"))+ expect(row).toBeDefined()+ await act(async () => row!.props.onClick())++ expect(onOpenChannel).toHaveBeenCalledWith("s1", "t1")+ expect(onOpenForumThread).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex 9e575005f..bf52c1ded 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -19,11 +19,12 @@ function MentionBadge({ count }: { count: number }) {)}-function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {+function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, onOpenDm }: {servers: UnreadServer[]dms: UnreadDm[]loading?: booleanonOpenChannel?: (serverId: string, channelId: string) => void+ onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => voidonOpenDm?: (dmId: string) => void}) {const nothingUnread = servers.length === 0 && dms.length === 0@@ -61,11 +62,17 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {<MentionBadge count={c.mentionCount} /><ChevronRight className="size-4 shrink-0 text-muted-foreground" /></button>- {/* Unread threads / forum-posts, indented under their parent. */}+ {/* Unread child threads, indented under their parent. */}{c.children.map((child) => (<buttonkey={child.channelId}- onClick={() => onOpenChannel?.(s.serverId, child.channelId)}+ onClick={() => {+ if (child.openerMessageId) {+ onOpenForumThread(s.serverId, c.channelId, child.channelId, child.openerMessageId)+ } else {+ onOpenChannel?.(s.serverId, child.channelId)+ }+ }}className="flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm hover:bg-accent"><EntityIcon kind={child.type} className="size-3.5 shrink-0 text-muted-foreground" />@@ -180,6 +187,7 @@ export function InboxPopover({markedLoading,loading,onOpenChannel,+ onOpenForumThread,onOpenDm,onOpenMention,onOpenMarked,@@ -195,6 +203,7 @@ export function InboxPopover({markedLoading?: booleanloading?: booleanonOpenChannel?: (serverId: string, channelId: string) => void+ onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => voidonOpenDm?: (dmId: string) => voidonOpenMention?: (m: Mention) => voidonOpenMarked?: (m: Marked) => void@@ -242,7 +251,7 @@ export function InboxPopover({<TabsTrigger value="marked">Marked</TabsTrigger></TabsList><TabsContent value="unreads" className="min-h-0 flex-1">- <UnreadsTab servers={unreads} dms={unreadDms} loading={loading} onOpenChannel={onOpenChannel} onOpenDm={onOpenDm} />+ <UnreadsTab servers={unreads} dms={unreadDms} loading={loading} onOpenChannel={onOpenChannel} onOpenForumThread={onOpenForumThread} onOpenDm={onOpenDm} /></TabsContent><TabsContent value="mentions" className="min-h-0 flex-1"><MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} />diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex 324395e17..dab06cd45 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -70,6 +70,8 @@ export function clipboardFiles(items: DataTransferItemList | undefined): File[]return files}+type ComposerMode = "chat" | "forumThreadBody"+export type ComposerHandle = {focusEditor: () => voidsubmitNow: () => void@@ -101,24 +103,28 @@ type ComposerBaseProps = {// Auto-focus the editor on mount and on channel change. Desktop only —// callers pass `bp !== "mobile"` to avoid unexpected soft-keyboard pop-up.autoFocus?: boolean- // Placeholder override — used by `forumPostBody` to swap the chat-composer+ // `"chat"` (default) — Enter sends, Shift+Enter newline, `send()` clears.+ // `"forumThreadBody"` — inverted: Enter newline, Shift+Enter submits; `send()`+ // does NOT clear so the parent can await mutation success before resetting.+ mode?: ComposerMode+ // Placeholder override — used by `forumThreadBody` to swap the chat-composer// relic string. Falls back to the mode-derived default when absent.placeholder?: string// Hide the composer's built-in emoji-picker button (bottom-right). Used by- // the forum-post composer, where emoji is dropped from the compose surface.+ // the create-post composer, where emoji is dropped from the compose surface.hideEmoji?: boolean// Hide the composer's built-in attach button (bottom-left). Used by the- // forum-post composer, which renders its own attach button in the footer+ // create-post composer, which renders its own attach button in the footer// row and drives it through `ComposerHandle.openFilePicker()`.hideAttach?: boolean// Fires only on emptiness-state transitions (`hasContent` flips), not every- // keystroke. Used by the forum-post orchestrator to drive the footer button's+ // keystroke. Used by the create-post orchestrator to drive the footer button's// `disabled` state without mirroring editor content in parent React state.onDirty?: (hasContent: boolean) => void// When set, the composer persists its unsent text under this localStorage// scope (per channel/DM) and restores it on mount — the view remounts on// every channel switch (keyed by id), so this is what survives navigation.- // Text only; attachments/replies are not cached. Omitted for forumPostBody+ // Text only; attachments/replies are not cached. Omitted for forumThreadBody// (the parent owns that draft lifecycle).draftKey?: string}@@ -132,7 +138,7 @@ type ComposerAcceptedSend = {type ComposerDeferredSend = {sendContract: "deferred"- mode: "forumPostBody"+ mode: "forumThreadBody"onDeferredSubmit: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => void | Promise<void>onAcceptSend?: never}@@ -142,7 +148,7 @@ export type ComposerProps = ComposerBaseProps & (ComposerAcceptedSend | Composer// Composer — plain-text TipTap editor with a chat-style @-mention popover.// Users type raw markdown which MessageBody/Streamdown renders on display.// In `mode="chat"` (default) Enter sends, Shift+Enter adds a newline. In-// `mode="forumPostBody"` the mapping is inverted (Enter = newline,+// `mode="forumThreadBody"` the mapping is inverted (Enter = newline,// Shift+Enter = submit) to match /w's issue-sheet convention. While the// mention popover is open Enter/Tab/Arrow keys drive selection instead.// @everyone is a virtual candidate in channel + thread contexts@@ -167,7 +173,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompoonDirty,draftKey,}, ref) {- const isForumPostBody = mode === "forumPostBody"+ const isForumThreadBody = mode === "forumThreadBody"const {pendingFiles,setPendingFiles,@@ -310,7 +316,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompoeditorProps: {attributes: {class: "outline-none",- enterkeyhint: isForumPostBody ? "enter" : "send",+ enterkeyhint: isForumThreadBody ? "enter" : "send",},handleKeyDown: (_view, event) => {// editorProps.handleKeyDown runs BEFORE the suggestion plugin's keymap,@@ -324,7 +330,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompochannelRefPopupRef.current.items.length > 0 && channelRefPopupRef.current.command !== nullif (mentionOpen || channelRefOpen) return false- if (isForumPostBody) {+ if (isForumThreadBody) {if (event.key === "Enter" && event.shiftKey && !event.isComposing) {event.preventDefault()send()@@ -376,7 +382,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompofireTyping()emitDirtyTransition()const key = draftKeyRef.current- if (key && !isForumPostBody) {+ if (key && !isForumThreadBody) {// Persist the ProseMirror doc (JSON), not plain text — so @mention /// channel-ref pill nodes survive the round-trip and restore as pills,// not inert `@label` text.@@ -391,7 +397,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// change. Uses the paste pipeline so paragraph/hard-break structure round-// trips exactly like `getText({blockSeparator:"\n\n"})` serialized it.useEffect(() => {- if (!editor || isForumPostBody || !draftKey) return+ if (!editor || isForumThreadBody || !draftKey) returnconst doc = readComposerDraft(draftKey)if (!doc) returnrestoringDraftRef.current = true@@ -450,10 +456,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo} else {void onDeferredSubmit?.(markdown, attachments, mentionType)}- // In forumPostBody mode the parent needs to await mutation success before+ // In forumThreadBody mode the parent needs to await mutation success before// clearing — otherwise a failed create wipes the user's typed content.// Reset is delegated to the parent via `resetAfterSubmit()` on the ref.- if (isForumPostBody) return+ if (isForumThreadBody) returneditor.commands.clearContent()if (draftKeyRef.current) clearComposerDraft(draftKeyRef.current)transferPendingFiles()@@ -481,12 +487,12 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// Auto-focus on mount + on channel switch. `<Composer>` is not remounted// per channel (only `<MessageList>` is keyed by channelId), so keying this// effect on `channel` is what refocuses when the user navigates channels.- // Skipped in forumPostBody mode — the parent controls focus (starts on the+ // Skipped in forumThreadBody mode — the parent controls focus (starts on the// title, jumps to the body on Enter).useEffect(() => {- if (!autoFocus || !editor || isForumPostBody) return+ if (!autoFocus || !editor || isForumThreadBody) returneditor.commands.focus("end")- }, [autoFocus, editor, channel, isForumPostBody])+ }, [autoFocus, editor, channel, isForumThreadBody])// Focus the editor when a reply is initiated. Clicking "reply" on a message// sets `replyingTo` on the parent but doesn't touch the composer, so without@@ -499,8 +505,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompouseEffect(() => {const opened = !prevReplyingToRef.current && !!replyingToprevReplyingToRef.current = replyingTo- if (opened && editor && !isForumPostBody) editor.commands.focus("end")- }, [replyingTo, editor, isForumPostBody])+ if (opened && editor && !isForumThreadBody) editor.commands.focus("end")+ }, [replyingTo, editor, isForumThreadBody])// Refocus editor after a drop so the user can start typing without// clicking. The drop landed on the composer container — the intent is@@ -512,7 +518,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Comporeturn (<div- className={isForumPostBody ? "relative" : "relative px-3 pb-3 pt-0"}+ className={isForumThreadBody ? "relative" : "relative px-3 pb-3 pt-0"}onDragEnter={handleDragEnter}onDragLeave={handleDragLeave}onDragOver={handleDragOver}@@ -553,7 +559,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo</div>)}- <div className={`relative ${isForumPostBody ? "bg-transparent ring-0" : "bg-muted shadow-(--e1) ring-1 ring-border/40 transition-shadow focus-within:ring-2 focus-within:ring-ring/60"} ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>+ <div className={`relative ${isForumThreadBody ? "bg-transparent ring-0" : "bg-muted shadow-(--e1) ring-1 ring-border/40 transition-shadow focus-within:ring-2 focus-within:ring-ring/60"} ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>{dragging && (<divclassName={`pointer-events-none absolute inset-0 z-10 grid place-items-center border-2 border-dashed border-ring bg-background/80 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}@@ -568,8 +574,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompoonChange={handleFileSelect}className="hidden"/>- <div className={`chat-composer relative py-3 ${isForumPostBody ? "px-2" : "px-12"}`} data-testid={tid.composerInput}>- <EditorContent editor={editor} className={`${isForumPostBody ? "max-h-60" : "max-h-40"} overflow-y-auto thin-scrollbar text-base chat-input-line-height outline-none`} />+ <div className={`chat-composer relative py-3 ${isForumThreadBody ? "px-2" : "px-12"}`} data-testid={tid.composerInput}>+ <EditorContent editor={editor} className={`${isForumThreadBody ? "max-h-60" : "max-h-40"} overflow-y-auto thin-scrollbar text-base chat-input-line-height outline-none`} /></div>{/* Attach button — fixed bottom-left */}{!hideAttach && (diff --git a/src/web/src/components/community/create-forum-post.test.ts b/src/web/src/components/community/create-forum-thread.test.tssimilarity index 87%rename from src/web/src/components/community/create-forum-post.test.tsrename to src/web/src/components/community/create-forum-thread.test.tsindex ba1d16414..260d145f7 100644--- a/src/web/src/components/community/create-forum-post.test.ts+++ b/src/web/src/components/community/create-forum-thread.test.ts@@ -1,5 +1,5 @@/**- * Server-render probes for CreateForumPost. Composer is mocked because it+ * Server-render probes for CreateForumThread. Composer is mocked because it* mounts a real tiptap editor (needs DOM); everything else here is pure JSX* that renderToStaticMarkup can walk.*/@@ -24,11 +24,11 @@ vi.mock("@/hooks/community/mutations/uploads", () => ({zipUploadResultsWithDimensions: () => [],}))-import { CreateForumPost } from "./create-forum-post"+import { CreateForumThread } from "./create-forum-thread"-function render(over: Partial<Parameters<typeof CreateForumPost>[0]> = {}) {+function render(over: Partial<Parameters<typeof CreateForumThread>[0]> = {}) {return renderToStaticMarkup(- createElement(CreateForumPost, {+ createElement(CreateForumThread, {forumChannelId: "cha_forum",members: [],onCancel: () => {},@@ -38,7 +38,7 @@ function render(over: Partial<Parameters<typeof CreateForumPost>[0]> = {}) {)}-describe("CreateForumPost — copy + structure", () => {+describe("CreateForumThread — copy + structure", () => {it("renders the region role + label so keyboard/SR users land in a named region", () => {const html = render()expect(html).toContain('role="region"')@@ -51,10 +51,10 @@ describe("CreateForumPost — copy + structure", () => {expect(html).not.toContain('placeholder="Title"')})- it("renders the composer in forumPostBody mode with hideEmoji + the body placeholder", () => {+ it("renders the composer in forumThreadBody mode with hideEmoji + the body placeholder", () => {const html = render()expect(html).toContain('data-testid="mock-composer"')- expect(html).toContain('data-mode="forumPostBody"')+ expect(html).toContain('data-mode="forumThreadBody"')expect(html).toContain('data-send-contract="deferred"')expect(html).toContain('data-has-deferred-submit="true"')expect(html).toContain('data-hide-emoji="true"')diff --git a/src/web/src/components/community/create-forum-post.tsx b/src/web/src/components/community/create-forum-thread.tsxsimilarity index 93%rename from src/web/src/components/community/create-forum-post.tsxrename to src/web/src/components/community/create-forum-thread.tsxindex 4cc31b215..080659127 100644--- a/src/web/src/components/community/create-forum-post.tsx+++ b/src/web/src/components/community/create-forum-thread.tsx@@ -24,14 +24,15 @@ import {// A forum post's body IS the first message in its thread — content plus any// attachments and the audience-broadcast `mentionType` extracted from the body// text. Tags are added AFTER creation from the post card's tag dialog, not here.-export type NewForumPost = {+export type NewForumThread = {+ nonce: stringname: stringcontent: stringattachments?: UploadedAttachment[]mentionType?: MentionType}-export function CreateForumPost({+export function CreateForumThread({forumChannelId,members,onSearchMembers,@@ -47,7 +48,7 @@ export function CreateForumPost({// Async — the page owns the mutation call + `enterThread` navigation. This// handler either resolves (success — child clears its state) or rejects// (failure — child toasts and preserves state for retry).- onCreatePost: (post: NewForumPost) => Promise<void>+ onCreatePost: (post: NewForumThread) => Promise<void>}) {const [title, setTitle] = useState("")const [bodyHasContent, setBodyHasContent] = useState(false)@@ -65,6 +66,7 @@ export function CreateForumPost({// create failure. Mutation-only (ref, not state) — read inside the async// submit path. Cleared after a successful create.const uploadedCacheRef = useRef<Map<File, UploadedAttachment>>(new Map())+ const commandNonceRef = useRef(crypto.randomUUID())const canSubmit = title.trim().length > 0 && bodyHasContent@@ -93,6 +95,8 @@ export function CreateForumPost({const res = await uploadFile.mutateAsync({target: { channelId: forumChannelId },file: att.file,+ width: att.width,+ height: att.height,})uploadedCacheRef.current.set(att.file, res)return res@@ -102,6 +106,7 @@ export function CreateForumPost({}try {await onCreatePost({+ nonce: commandNonceRef.current,name: title.trim(),content: markdown,attachments: uploaded.length > 0 ? uploaded : undefined,@@ -112,6 +117,7 @@ export function CreateForumPost({return}uploadedCacheRef.current.clear()+ commandNonceRef.current = crypto.randomUUID()bodyComposerRef.current?.resetAfterSubmit()setTitle("")} catch (e) {@@ -142,7 +148,7 @@ export function CreateForumPost({<inputvalue={title}onChange={(e) => setTitle(e.target.value)}- onKeyDown={onEnterSubmit(focusBody, { onEscape: onCancelGuarded })}+ onKeyDown={(event) => onEnterSubmit(focusBody, { onEscape: onCancelGuarded })(event)}placeholder="New post"autoFocusmaxLength={MAX_CHANNEL_NAME_LENGTH}@@ -160,7 +166,7 @@ export function CreateForumPost({<ComposersendContract="deferred"ref={bodyComposerRef}- mode="forumPostBody"+ mode="forumThreadBody"hideEmojihideAttachchannel=""diff --git a/src/web/src/components/community/eject-server.test.ts b/src/web/src/components/community/eject-server.test.tsindex 260cded94..0646f2045 100644--- a/src/web/src/components/community/eject-server.test.ts+++ b/src/web/src/components/community/eject-server.test.ts@@ -1,10 +1,13 @@-import { describe, it, expect } from "vitest"+import { describe, it, expect, vi } from "vitest"import {markVoluntaryLeave,consumeVoluntaryLeave,pickPostEjectDestination,+ runAuthoritativeServerEject,+ isDefinitiveChildMetaFailure,} from "./eject-server"import type { Server } from "./_types"+import { ApiError } from "@/lib/errors"function makeServer(id: string): Server {return {@@ -33,6 +36,67 @@ describe("voluntary-leave marker", () => {})})+describe("runAuthoritativeServerEject", () => {+ const target = { id: "srv_target" } as Server+ const callbacks = () => ({+ consumeVoluntaryLeave: vi.fn(() => false),+ clearLastChannel: vi.fn(),+ toast: vi.fn(),+ replace: vi.fn(),+ })++ it("keeps the URL and last-channel through first 500, then accepts a success containing the target", () => {+ const sideEffects = callbacks()+ expect(runAuthoritativeServerEject({+ serverId: target.id, servers: [], isSuccess: false, isFetching: false, ...sideEffects,+ })).toBe(false)+ expect(runAuthoritativeServerEject({+ serverId: target.id, servers: [target], isSuccess: true, isFetching: false, ...sideEffects,+ })).toBe(false)+ expect(sideEffects.replace).not.toHaveBeenCalled()+ expect(sideEffects.toast).not.toHaveBeenCalled()+ expect(sideEffects.clearLastChannel).not.toHaveBeenCalled()+ })++ it("does not eject from last-good data when a refetch errors", () => {+ const sideEffects = callbacks()+ expect(runAuthoritativeServerEject({+ serverId: target.id, servers: [target], isSuccess: false, isFetching: false, ...sideEffects,+ })).toBe(false)+ expect(sideEffects.replace).not.toHaveBeenCalled()+ expect(sideEffects.toast).not.toHaveBeenCalled()+ expect(sideEffects.clearLastChannel).not.toHaveBeenCalled()+ })++ it("does not decide absence while a successful snapshot is still fetching", () => {+ const sideEffects = callbacks()+ expect(runAuthoritativeServerEject({+ serverId: target.id, servers: [], isSuccess: true, isFetching: true, ...sideEffects,+ })).toBe(false)+ expect(sideEffects.replace).not.toHaveBeenCalled()+ })++ it("ejects, clears memory, and toasts only when settled success explicitly lacks the target", () => {+ const sideEffects = callbacks()+ const remaining = { id: "srv_remaining" } as Server+ expect(runAuthoritativeServerEject({+ serverId: target.id, servers: [remaining], isSuccess: true, isFetching: false, ...sideEffects,+ })).toBe(true)+ expect(sideEffects.clearLastChannel).toHaveBeenCalledWith(target.id)+ expect(sideEffects.toast).toHaveBeenCalledWith("You're no longer in this server")+ expect(sideEffects.replace).toHaveBeenCalledWith("/c/channels/srv_remaining")+ })+})++describe("isDefinitiveChildMetaFailure", () => {+ it("keeps the existing 403/404 bounce boundary without treating 5xx as absence", () => {+ expect(isDefinitiveChildMetaFailure(new ApiError("forbidden", 403))).toBe(true)+ expect(isDefinitiveChildMetaFailure(new ApiError("missing", 404))).toBe(true)+ expect(isDefinitiveChildMetaFailure(new ApiError("transient", 500))).toBe(false)+ expect(isDefinitiveChildMetaFailure(new Error("network"))).toBe(false)+ })+})+describe("pickPostEjectDestination", () => {it("returns the first other server when one remains", () => {const servers = [makeServer("srv_ejected"), makeServer("srv_next"), makeServer("srv_third")]diff --git a/src/web/src/components/community/eject-server.ts b/src/web/src/components/community/eject-server.tsindex 633d04ac1..1f324271a 100644--- a/src/web/src/components/community/eject-server.ts+++ b/src/web/src/components/community/eject-server.ts@@ -1,4 +1,5 @@import type { Server } from "./_types"+import { ApiError } from "@/lib/errors"// Module-scoped marker set. The "Leave" button in the server rail marks// the server id here BEFORE firing the mutation; the layout's eject effect@@ -20,6 +21,10 @@ export function consumeVoluntaryLeave(serverId: string): boolean {return voluntaryLeaves.delete(serverId)}+export function isDefinitiveChildMetaFailure(error: unknown): boolean {+ return error instanceof ApiError && (error.status === 403 || error.status === 404)+}+// Pure destination picker for the post-eject redirect. When the viewer// has any other servers, the first (railOrder-sorted from the API) wins.// Otherwise the DM home is the only safe landing spot.@@ -31,3 +36,26 @@ export function pickPostEjectDestination(if (remaining.length === 0) return "/c/me"return `/c/channels/${remaining[0].id}`}++export function runAuthoritativeServerEject(args: {+ serverId: string+ servers: readonly Server[]+ isSuccess: boolean+ isFetching: boolean+ consumeVoluntaryLeave: (serverId: string) => boolean+ clearLastChannel: (serverId: string) => void+ toast: (message: string) => void+ replace: (destination: string) => void+}): boolean {+ // Absence is authoritative only on a settled successful snapshot. A first+ // failure has isFetched=true in TanStack, and a failed background refetch can+ // retain last-good data; neither may become an existence/membership verdict.+ if (!args.isSuccess || args.isFetching) return false+ if (args.servers.some((server) => server.id === args.serverId)) return false++ args.clearLastChannel(args.serverId)+ const voluntary = args.consumeVoluntaryLeave(args.serverId)+ if (!voluntary) args.toast("You're no longer in this server")+ args.replace(pickPostEjectDestination(args.servers, args.serverId))+ return true+}diff --git a/src/web/src/components/community/entity-icon.test.ts b/src/web/src/components/community/entity-icon.test.tsindex ed1d20899..25ce312ef 100644--- a/src/web/src/components/community/entity-icon.test.ts+++ b/src/web/src/components/community/entity-icon.test.ts@@ -13,8 +13,7 @@ describe("getEntityIcon", () => {expect(getEntityIcon("forum")).toBe(ListChevronsUpDown)})- it("thread and forum_post → MessagesSquare", () => {+ it("thread → MessagesSquare", () => {expect(getEntityIcon("thread")).toBe(MessagesSquare)- expect(getEntityIcon("forum_post")).toBe(MessagesSquare)})})diff --git a/src/web/src/components/community/entity-icon.tsx b/src/web/src/components/community/entity-icon.tsxindex 42e17a61f..df9ce58f2 100644--- a/src/web/src/components/community/entity-icon.tsx+++ b/src/web/src/components/community/entity-icon.tsx@@ -3,11 +3,11 @@ import { ChannelIcon } from "./channel-icon"/*** Every community entity that gets a leading glyph, keyed by its RAW stored- * type string. `ChannelType` is only `"text" | "forum"`, but children carry- * `"thread"` / `"forum_post"` — so this wider union takes the raw value- * straight off the row without a lossy cast.+ * type string. `ChannelType` is only `"text" | "forum"`, but a child channel+ * carries `"thread"` — so this wider union takes the raw value straight off+ * the row without a lossy cast.*/-export type EntityKind = "text" | "forum" | "thread" | "forum_post"+export type EntityKind = "text" | "forum" | "thread"type IconComponent = (props: { className?: string }) => React.ReactNode@@ -23,7 +23,6 @@ export function getEntityIcon(kind: EntityKind | undefined): IconComponent {case "forum":return ListChevronsUpDowncase "thread":- case "forum_post":return MessagesSquaredefault:return ChannelIcon@@ -37,7 +36,7 @@ export function getEntityIcon(kind: EntityKind | undefined): IconComponent {** text | undefined → ChannelIcon (the custom slash glyph)* forum → ListChevronsUpDown- * thread | forum_post → MessagesSquare+ * thread → MessagesSquare** Accepts `className` only — matching `ChannelIcon` — so both `size-*` and* `text-*` call sites keep working.@@ -47,7 +46,6 @@ export function EntityIcon({ kind, className }: { kind: EntityKind | undefined;case "forum":return <ListChevronsUpDown className={className} />case "thread":- case "forum_post":return <MessagesSquare className={className} />default:return <ChannelIcon className={className} />diff --git a/src/web/src/components/community/forum-channel-surface.test.ts b/src/web/src/components/community/forum-channel-surface.test.tsnew file mode 100644index 000000000..0cfd812c0--- /dev/null+++ b/src/web/src/components/community/forum-channel-surface.test.ts@@ -0,0 +1,231 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { ChannelHeader } from "./channel-header"+import { CommunityPanelSheet } from "./community-panel-sheet"+import { ForumChannelSurface } from "./forum-channel-surface"+import { ForumSurface } from "./forum-surface"++const mocks = vi.hoisted(() => ({+ createForumThread: vi.fn(),+ updatePostTags: vi.fn(),+ deleteForumThread: vi.fn(),+ readState: vi.fn(() => ({ snapshot: null, isFetching: false })),+ eagerRead: vi.fn(),+ activeMessageFeed: vi.fn(() => { throw new Error("forum must not initialize an active message feed") }),+}))++vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))+vi.mock("@/hooks/community/use-channel-message-feed", () => ({+ useChannelMessageFeed: mocks.activeMessageFeed,+}))+vi.mock("@/hooks/community/use-channel-read-state", () => ({+ useChannelReadStateSnapshot: mocks.readState,+}))+vi.mock("@/hooks/community/use-eager-channel-read", () => ({+ useEagerChannelRead: mocks.eagerRead,+}))+vi.mock("@/hooks/community/mutations", () => ({+ useCreateForumThread: () => ({ mutateAsync: mocks.createForumThread }),+ useUpdatePostTags: () => ({+ mutate: mocks.updatePostTags,+ isPending: true,+ variables: { threadId: "post_saving" },+ }),+ useDeleteForumThread: () => ({+ mutate: mocks.deleteForumThread,+ isPending: true,+ variables: { threadId: "post_deleting" },+ }),+}))+vi.mock("@/components/community/_types", async (importOriginal) => {+ const original = await importOriginal<typeof import("./_types")>()+ return { ...original, canManageServer: (role: string | undefined) => role === "owner" || role === "admin" }+})+vi.mock("@/components/community/channel-header", () => ({+ ChannelHeader: vi.fn(() => null),+}))+vi.mock("@/components/community/channel-shell", () => ({+ ChannelShell: ({ header, body, panels, dialogs }: {+ header: React.ReactNode+ body: React.ReactNode+ panels?: React.ReactNode+ dialogs?: React.ReactNode+ }) => React.createElement(React.Fragment, null, header, body, panels, dialogs),+}))+vi.mock("@/components/community/community-panel-sheet", () => ({+ CommunityPanelSheet: vi.fn(() => null),+}))+vi.mock("@/components/community/forum-surface", () => ({+ ForumSurface: vi.fn(() => null),+}))++const mockedChannelHeader = vi.mocked(ChannelHeader)+const mockedCommunityPanelSheet = vi.mocked(CommunityPanelSheet)+const mockedForumSurface = vi.mocked(ForumSurface)++function surfaceProps(overrides: Record<string, unknown> = {}) {+ return {+ channelId: "forum_1",+ serverId: "srv_1",+ channelName: "ideas",+ viewer: { id: "viewer_1" },+ viewerRole: "member" as const,+ notificationLevel: "Use Server Default" as const,+ onSetNotificationLevel: vi.fn(),+ composerMembers: [],+ onSearchComposerMembers: vi.fn(),+ memberPanelProps: { members: [] },+ manageMembersDialog: React.createElement("span", { "data-manage-dialog": true }),+ onOpenPost: vi.fn(),+ onOpenProfile: vi.fn(),+ ...overrides,+ }+}++describe("ForumChannelSurface ownership", () => {+ beforeEach(() => {+ mocks.createForumThread.mockResolvedValue({ threadId: "post_new" })+ mocks.readState.mockReturnValue({ snapshot: null, isFetching: false })+ })++ afterEach(() => {+ vi.clearAllMocks()+ })++ it("owns forum create, tag, delete, permissions, and pending wiring without an active message feed", async () => {+ const props = surfaceProps()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(ForumChannelSurface, props))+ })++ expect(mocks.activeMessageFeed).not.toHaveBeenCalled()+ const forumProps = mockedForumSurface.mock.calls.at(-1)![0]+ expect(forumProps).toEqual(expect.objectContaining({+ forumChannelId: "forum_1",+ members: props.composerMembers,+ onSearchMembers: props.onSearchComposerMembers,+ onOpenPost: props.onOpenPost,+ savingTagsFor: "post_saving",+ deletingPost: "post_deleting",+ }))+ const ownPost = {+ id: "post_1",+ authorId: "viewer_1",+ openerMessageId: "opener_1",+ } as Parameters<NonNullable<typeof forumProps.canEditPostTags>>[0]+ const otherPost = { ...ownPost, authorId: "other_1" }+ expect(forumProps.canEditPostTags?.(ownPost)).toBe(true)+ expect(forumProps.canEditPostTags?.(otherPost)).toBe(false)+ expect(forumProps.canDeletePost?.(ownPost)).toBe(true)+ expect(forumProps.canDeletePost?.(otherPost)).toBe(false)++ await forumProps.onCreatePost?.({+ nonce: "nonce_1",+ name: "New post",+ content: "Body",+ attachments: [],+ mentionType: "everyone",+ })+ expect(mocks.createForumThread).toHaveBeenCalledWith({+ nonce: "nonce_1",+ channelId: "forum_1",+ name: "New post",+ content: "Body",+ attachments: [],+ mentionType: "everyone",+ })+ expect(props.onOpenPost).toHaveBeenCalledWith("post_new")++ act(() => {+ forumProps.onEditPostTags?.(ownPost, ["shipped"])+ forumProps.onDeletePost?.(ownPost)+ })+ expect(mocks.updatePostTags).toHaveBeenCalledWith({+ forumChannelId: "forum_1",+ threadId: "post_1",+ openerMessageId: "opener_1",+ tags: ["shipped"],+ }, expect.any(Object))+ expect(mocks.deleteForumThread).toHaveBeenCalledWith({+ forumChannelId: "forum_1",+ threadId: "post_1",+ }, expect.any(Object))+ expect(renderer!.root.findByProps({ "data-manage-dialog": true })).toBeTruthy()+ })++ it("allows server managers to edit and delete other authors' posts", () => {+ act(() => {+ TestRenderer.create(React.createElement(ForumChannelSurface, surfaceProps({ viewerRole: "admin" })))+ })+ const forumProps = mockedForumSurface.mock.calls.at(-1)![0]+ const otherPost = { id: "post_2", authorId: "other_1", openerMessageId: "opener_2" } as Parameters<NonNullable<typeof forumProps.canEditPostTags>>[0]+ expect(forumProps.canEditPostTags?.(otherPost)).toBe(true)+ expect(forumProps.canDeletePost?.(otherPost)).toBe(true)+ })++ it("waits for the read snapshot and eagerly reads each forum without an active message feed", () => {+ mocks.readState.mockReturnValue({ snapshot: null, isFetching: true })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(ForumChannelSurface, surfaceProps()))+ })++ expect(mocks.readState).toHaveBeenLastCalledWith("forum_1")+ expect(mocks.eagerRead).toHaveBeenLastCalledWith({+ channelId: "forum_1",+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: false,+ })++ mocks.readState.mockReturnValue({ snapshot: null, isFetching: false })+ act(() => {+ renderer!.update(React.createElement(ForumChannelSurface, surfaceProps()))+ })+ expect(mocks.eagerRead).toHaveBeenLastCalledWith({+ channelId: "forum_1",+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: true,+ })++ act(() => {+ renderer!.update(React.createElement(+ ForumChannelSurface,+ surfaceProps({ channelId: "forum_2", serverId: "srv_2" }),+ ))+ })+ expect(mocks.readState).toHaveBeenLastCalledWith("forum_2")+ expect(mocks.eagerRead).toHaveBeenLastCalledWith({+ channelId: "forum_2",+ serverId: "srv_2",+ isChildChannel: false,+ snapshotReady: true,+ })+ expect(mocks.activeMessageFeed).not.toHaveBeenCalled()+ })++ it("resets the right panel when channelId changes without relying on an outer remount", () => {+ const firstProps = surfaceProps()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(ForumChannelSurface, firstProps))+ })+ act(() => {+ mockedChannelHeader.mock.calls.at(-1)![0].onToggle("members")+ })+ expect(mockedCommunityPanelSheet.mock.calls.at(-1)![0]).toEqual(expect.objectContaining({ kind: "members" }))++ act(() => {+ renderer!.update(React.createElement(+ ForumChannelSurface,+ surfaceProps({ channelId: "forum_2", channelName: "roadmap" }),+ ))+ })++ expect(mockedChannelHeader.mock.calls.at(-1)![0].rightPanel).toBeNull()+ expect(renderer!.root.findAllByType(CommunityPanelSheet)).toHaveLength(0)+ })+})diff --git a/src/web/src/components/community/forum-channel-surface.tsx b/src/web/src/components/community/forum-channel-surface.tsxnew file mode 100644index 000000000..882ce4cd6--- /dev/null+++ b/src/web/src/components/community/forum-channel-surface.tsx@@ -0,0 +1,156 @@+"use client"++import { useCallback, useEffect, useState, type ReactNode } from "react"+import { toastApiError } from "@/lib/api/client"+import { canManageServer, type OpenProfile, type RightPanel, type Role } from "@/components/community/_types"+import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channel-header"+import { ChannelShell } from "@/components/community/channel-shell"+import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"+import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"+import type { NewForumThread } from "@/components/community/create-forum-thread"+import { ForumSurface } from "@/components/community/forum-surface"+import type { Member } from "@/components/community/_types"+import {+ useCreateForumThread,+ useDeleteForumThread,+ useUpdatePostTags,+} from "@/hooks/community/mutations"+import { useChannelReadStateSnapshot } from "@/hooks/community/use-channel-read-state"+import { useEagerChannelRead } from "@/hooks/community/use-eager-channel-read"++export function ForumChannelSurface({+ serverId,+ channelId,+ channelName,+ viewer,+ viewerRole,+ headerServer,+ notificationLevel,+ onSetNotificationLevel,+ onBack,+ composerMembers,+ onSearchComposerMembers,+ memberPanelProps,+ manageMembersDialog,+ onOpenPost,+ onOpenProfile,+}: {+ serverId: string+ channelId: string+ channelName: string+ viewer: { id: string }+ viewerRole: Role | undefined+ headerServer?: { id: string; name: string; icon: string | null }+ notificationLevel: ChannelNotifLevel+ onSetNotificationLevel: (level: ChannelNotifLevel) => void+ onBack?: () => void+ composerMembers: Member[]+ onSearchComposerMembers?: (query: string) => void+ memberPanelProps: ChannelMemberPanelProps+ manageMembersDialog: ReactNode+ onOpenPost: (postId: string) => void+ onOpenProfile: OpenProfile+}) {+ const readState = useChannelReadStateSnapshot(channelId)+ useEagerChannelRead({+ channelId,+ serverId,+ isChildChannel: false,+ snapshotReady: !readState.isFetching,+ })+ const [panelState, setPanelState] = useState<{ channelId: string; panel: RightPanel }>({+ channelId,+ panel: null,+ })+ const rightPanel = panelState.channelId === channelId ? panelState.panel : null+ const createForumThreadMut = useCreateForumThread()+ const updatePostTagsMut = useUpdatePostTags()+ const deleteForumThreadMut = useDeleteForumThread()++ useEffect(() => {+ setPanelState((current) =>+ current.channelId === channelId && current.panel === null+ ? current+ : { channelId, panel: null },+ )+ }, [channelId])++ const togglePanel = useCallback((panel: Exclude<RightPanel, null>) => {+ setPanelState((current) => ({+ channelId,+ panel: current.channelId === channelId && current.panel === panel ? null : panel,+ }))+ }, [channelId])+ const createForumThread = useCallback(async (post: NewForumThread) => {+ const data = await createForumThreadMut.mutateAsync({+ nonce: post.nonce,+ channelId,+ name: post.name,+ content: post.content,+ attachments: post.attachments,+ mentionType: post.mentionType,+ })+ onOpenPost(data.threadId)+ }, [channelId, createForumThreadMut, onOpenPost])+ const canManage = canManageServer(viewerRole)++ return (+ <ChannelShell+ header={(+ <ChannelHeader+ channel={channelName}+ forum+ rightPanel={rightPanel}+ onToggle={togglePanel}+ notifLevel={notificationLevel}+ onSetNotifLevel={onSetNotificationLevel}+ onBack={onBack}+ server={headerServer}+ tools={{ threads: false, pinned: false }}+ />+ )}+ body={(+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ <ForumSurface+ serverId={serverId}+ forumChannelId={channelId}+ members={composerMembers}+ onSearchMembers={onSearchComposerMembers}+ onOpenPost={onOpenPost}+ onCreatePost={createForumThread}+ canEditPostTags={(post) => canManage || post.authorId === viewer.id}+ savingTagsFor={updatePostTagsMut.isPending ? updatePostTagsMut.variables?.threadId ?? null : null}+ onEditPostTags={(post, tags) => {+ updatePostTagsMut.mutate(+ { forumChannelId: channelId, threadId: post.id, openerMessageId: post.openerMessageId, tags },+ { onError: (error) => toastApiError(error, "Failed to update tags") },+ )+ }}+ canDeletePost={(post) => canManage || post.authorId === viewer.id}+ deletingPost={deleteForumThreadMut.isPending ? deleteForumThreadMut.variables?.threadId ?? null : null}+ onDeletePost={(post) => {+ deleteForumThreadMut.mutate(+ { forumChannelId: channelId, threadId: post.id },+ { onError: (error) => toastApiError(error, "Failed to delete post") },+ )+ }}+ />+ </main>+ )}+ panels={rightPanel && (+ <CommunityPanelSheet+ open+ onOpenChange={(open) => { if (!open) setPanelState({ channelId, panel: null }) }}+ kind={rightPanel}+ {...memberPanelProps}+ pinned={[]}+ searchResults={[]}+ threads={[]}+ onOpenThread={onOpenPost}+ onOpenProfile={onOpenProfile}+ />+ )}+ dialogs={manageMembersDialog}+ />+ )+}diff --git a/src/web/src/components/community/forum-child-header.contract.test.ts b/src/web/src/components/community/forum-child-header.contract.test.tsnew file mode 100644index 000000000..5823c2735--- /dev/null+++ b/src/web/src/components/community/forum-child-header.contract.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from "vitest"+import fs from "node:fs"+import path from "node:path"+import { fileURLToPath } from "node:url"++const componentDirectory = path.dirname(fileURLToPath(import.meta.url))++describe("forum child header wiring", () => {+ it("keeps opener/list edit affordances absent and gates title editing to the creator", () => {+ const route = fs.readFileSync(path.join(componentDirectory, "channel-route.tsx"), "utf8")+ const surface = fs.readFileSync(path.join(componentDirectory, "thread-channel-surface.tsx"), "utf8")+ const forumView = fs.readFileSync(path.join(componentDirectory, "forum-view.tsx"), "utf8")++ expect(route).toContain("<ThreadChannelSurface")+ expect(surface).toContain("parentMessageId && !parentIsForum")+ expect(surface).toContain("childCreatorId === viewer.id")+ expect(surface).toContain("titleRename: parentIsForum")+ expect(surface).toContain("messageId: parentMessageId")+ expect(forumView).not.toContain("Edit post")+ expect(forumView).not.toMatch(/\bonEditPost(?:\?|\s|=)/)+ })+})diff --git a/src/web/src/components/community/forum-surface.tsx b/src/web/src/components/community/forum-surface.tsxnew file mode 100644index 000000000..76a05cc37--- /dev/null+++ b/src/web/src/components/community/forum-surface.tsx@@ -0,0 +1,39 @@+"use client"++import type { NewForumThread } from "./create-forum-thread"+import type { ForumThread, Member } from "./_types"+import { ForumView } from "./forum-view"+import { useForumFeed } from "@/hooks/community/use-forum-feed"++export function ForumSurface({ serverId, forumChannelId, ...props }: {+ serverId: string+ forumChannelId: string+ members: Member[]+ onSearchMembers?: (query: string) => void+ onOpenPost: (id: string) => void+ onCreatePost?: (post: NewForumThread) => Promise<void>+ onEditPostTags?: (post: ForumThread, tags: string[]) => void+ canEditPostTags?: (post: ForumThread) => boolean+ savingTagsFor?: string | null+ onDeletePost?: (post: ForumThread) => void+ canDeletePost?: (post: ForumThread) => boolean+ deletingPost?: string | null+}) {+ const feed = useForumFeed(serverId, forumChannelId)+ return <ForumView+ forumChannelId={forumChannelId}+ {...props}+ posts={feed.posts}+ loading={feed.isLoading}+ tag={feed.tag}+ availableTags={feed.availableTags}+ onTagChange={feed.selectTag}+ hasMore={feed.hasMoreOlder}+ loadingMore={feed.isFetchingOlder}+ onLoadMore={feed.fetchOlder}+ onEditPostTags={(threadId, tags) => {+ const post = feed.posts.find((candidate) => candidate.id === threadId)+ if (post) props.onEditPostTags?.(post, tags)+ }}+ />+}diff --git a/src/web/src/components/community/forum-view.scroll.test.ts b/src/web/src/components/community/forum-view.scroll.test.tsnew file mode 100644index 000000000..29c67495a--- /dev/null+++ b/src/web/src/components/community/forum-view.scroll.test.ts@@ -0,0 +1,88 @@+import { act, create, type ReactTestRenderer } from "react-test-renderer"+import { createElement } from "react"+import { beforeEach, describe, expect, it, vi } from "vitest"+import type { ForumThread } from "./_types"++const scrollToIndex = vi.fn()+let requestOlder: (() => void) | undefined+vi.mock("@tanstack/react-virtual", () => ({+ useVirtualizer: ({ count }: { count: number }) => ({+ options: { scrollMargin: 0 },+ scrollToIndex,+ getTotalSize: () => count * 160,+ getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 160 })),+ measureElement: () => {},+ }),+}))+vi.mock("@/hooks/community/use-virtual-cursor-sentinel", () => ({+ useVirtualCursorSentinel: ({ onLoad }: { onLoad?: () => void }) => {+ requestOlder = onLoad+ return () => {}+ },+}))++const post = (id: string): ForumThread => ({+ id,+ name: id,+ messageCount: 1,+ lastMessageAt: "2026-08-07T00:00:00.000Z",+ parent: { authorName: "Alice", text: "root" },+ authorId: "alice",+ authorAvatar: "A",+ openerMessageId: `m_${id}`,+ tags: [],+ preview: "preview",+ participants: [],+ participantCount: 1,+})++describe("ForumView scroll anchoring", () => {+ let ForumView: typeof import("./forum-view").ForumView+ const root = { scrollHeight: 300, scrollTop: 20, clientHeight: 200 }+ const props = (posts: ForumThread[], tag = "All", loadingMore = false) => ({+ forumChannelId: "forum_1",+ members: [],+ posts,+ tag,+ loadingMore,+ onTagChange: () => {},+ onOpenPost: () => {},+ onLoadMore: vi.fn(),+ })++ beforeEach(async () => {+ vi.resetModules()+ scrollToIndex.mockReset()+ requestOlder = undefined+ root.scrollHeight = 300+ root.scrollTop = 20+ ForumView = (await import("./forum-view")).ForumView+ })++ it("aligns the newest post to the end on first load and again after a tag switch", async () => {+ let view: ReactTestRenderer+ await act(async () => {+ view = create(createElement(ForumView, props([post("p1"), post("p2")])), {+ createNodeMock: (element) => element.props.role === "main" ? root : {},+ })+ })+ expect(scrollToIndex).toHaveBeenLastCalledWith(1, { align: "end" })+ scrollToIndex.mockClear()+ await act(async () => { view!.update(createElement(ForumView, props([post("p3")], "bug"))) })+ expect(scrollToIndex).toHaveBeenCalledWith(0, { align: "end" })+ })++ it("preserves the visible rows by applying the scroll-height delta after older posts prepend", async () => {+ let view: ReactTestRenderer+ await act(async () => {+ view = create(createElement(ForumView, props([post("p2"), post("p3")])), {+ createNodeMock: (element) => element.props.role === "main" ? root : {},+ })+ })+ act(() => requestOlder?.())+ await act(async () => { view!.update(createElement(ForumView, props([post("p2"), post("p3")], "All", true))) })+ root.scrollHeight = 500+ await act(async () => { view!.update(createElement(ForumView, props([post("p1"), post("p2"), post("p3")]))) })+ expect(root.scrollTop).toBe(220)+ })+})diff --git a/src/web/src/components/community/forum-view.test.ts b/src/web/src/components/community/forum-view.test.tsindex d6bf41785..89b284d9e 100644--- a/src/web/src/components/community/forum-view.test.ts+++ b/src/web/src/components/community/forum-view.test.ts@@ -3,11 +3,11 @@ import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { ForumView } from "./forum-view"import { tid } from "@/lib/community/testids"-import type { ForumPost } from "./_types"+import type { ForumThread } from "./_types"const LAST_AT = "2020-01-01T00:00:00.000Z"-function makePost(over: Partial<ForumPost> = {}): ForumPost {+function makePost(over: Partial<ForumThread> = {}): ForumThread {return {id: "p1",name: "A post title",@@ -23,12 +23,14 @@ function makePost(over: Partial<ForumPost> = {}): ForumPost {}}-function render(posts: ForumPost[]): string {+function render(posts: ForumThread[]): string {return renderToStaticMarkup(createElement(ForumView, {forumChannelId: "cha_forum",members: [],posts,+ tag: "All",+ onTagChange: () => {},onOpenPost: () => {},}))@@ -37,14 +39,16 @@ function render(posts: ForumPost[]): string {// Render with the delete affordance wired. `canDeletePost` decides per-post// visibility; `deletingPost` is the in-flight post id (button disabled).function renderWithDelete(- posts: ForumPost[],- opts: { canDeletePost?: (p: ForumPost) => boolean; deletingPost?: string | null } = {},+ posts: ForumThread[],+ opts: { canDeletePost?: (p: ForumThread) => boolean; deletingPost?: string | null } = {},): string {return renderToStaticMarkup(createElement(ForumView, {forumChannelId: "cha_forum",members: [],posts,+ tag: "All",+ onTagChange: () => {},onOpenPost: () => {},onDeletePost: () => {},canDeletePost: opts.canDeletePost ?? (() => true),@@ -57,7 +61,7 @@ describe("ForumView post card header", () => {it("solo post renders the creator name and no participant AvatarGroup", () => {const html = render([makePost()])expect(html).toContain(">Alice<")- expect(html).not.toContain(tid.forumPostAvatars("p1"))+ expect(html).not.toContain(tid.forumThreadAvatars("p1"))})it("renders the creator name and time before the participant AvatarGroup in markup order", () => {@@ -70,7 +74,7 @@ describe("ForumView post card header", () => {],}),])- const groupTid = tid.forumPostAvatars("p1")+ const groupTid = tid.forumThreadAvatars("p1")expect(html).toContain(groupTid)expect(html.indexOf(">Alice<")).toBeGreaterThanOrEqual(0)expect(html.indexOf(">Alice<")).toBeLessThan(html.indexOf(groupTid))@@ -95,32 +99,43 @@ describe("ForumView post card header", () => {}),])expect(withOthers).toContain("· ")- expect(withOthers).toContain(tid.forumPostAvatars("p1"))+ expect(withOthers).toContain(tid.forumThreadAvatars("p1"))+ })++ it("does not invent overflow when the author is absent from a capped five-person preview", () => {+ const participants = Array.from({ length: 5 }, (_, index) => ({+ id: `usr_${index}`,+ name: `Person ${index}`,+ avatar: `P${index}`,+ }))+ const html = render([makePost({ participants, participantCount: 6 })])+ expect(html).toContain(tid.forumThreadAvatars("p1"))+ expect(html).not.toContain(">+1<")})})describe("ForumView post delete button", () => {it("renders the delete button (with aria-label + testid) when canDeletePost is true", () => {const html = renderWithDelete([makePost()], { canDeletePost: () => true })- expect(html).toContain(tid.forumPostDeleteBtn("p1"))+ expect(html).toContain(tid.forumThreadDeleteBtn("p1"))expect(html).toContain('aria-label="Delete post"')})it("does not render the delete button when canDeletePost is false", () => {const html = renderWithDelete([makePost()], { canDeletePost: () => false })- expect(html).not.toContain(tid.forumPostDeleteBtn("p1"))+ expect(html).not.toContain(tid.forumThreadDeleteBtn("p1"))})it("does not render the delete button when onDeletePost is absent", () => {// render() wires onOpenPost only — no delete handler → no button.const html = render([makePost()])- expect(html).not.toContain(tid.forumPostDeleteBtn("p1"))+ expect(html).not.toContain(tid.forumThreadDeleteBtn("p1"))})it("disables the delete button for the post whose delete is in flight", () => {const html = renderWithDelete([makePost()], { deletingPost: "p1" })// The disabled attribute rides on the button carrying the delete testid.- const btnIdx = html.indexOf(tid.forumPostDeleteBtn("p1"))+ const btnIdx = html.indexOf(tid.forumThreadDeleteBtn("p1"))expect(btnIdx).toBeGreaterThanOrEqual(0)// renderToStaticMarkup emits a bare `disabled` attribute for disabled={true}.const around = html.slice(Math.max(0, btnIdx - 200), btnIdx + 200)@@ -143,6 +158,12 @@ describe("ForumView filter bar / composer swap", () => {// The composer's aria-label region only exists in composing mode.expect(html).not.toContain('aria-label="Create post"')})++ it("renders the server-query tag controls from the unfiltered result", () => {+ const html = render([makePost({ tags: ["bug", "help"] })])+ expect(html).toContain("#bug")+ expect(html).toContain("#help")+ })})describe("ForumView post card messageCount guard", () => {diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsxindex 6d25b4011..ee2766bec 100644--- a/src/web/src/components/community/forum-view.tsx+++ b/src/web/src/components/community/forum-view.tsx@@ -1,6 +1,7 @@"use client"-import { useRef, useState } from "react"+import { useLayoutEffect, useRef, useState } from "react"+import { useVirtualizer } from "@tanstack/react-virtual"import { MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"import { Button } from "@/components/ui/button"import { formatRelativeTime } from "./format-time"@@ -9,15 +10,17 @@ import { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "./avatar"import { AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar"import { EmptyState } from "./empty-state"-import { CreateForumPost, type NewForumPost } from "./create-forum-post"+import { CreateForumThread, type NewForumThread } from "./create-forum-thread"import { PostTagDialog } from "./post-tag-dialog"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { tid } from "@/lib/community/testids"-import type { ForumPost, Member } from "./_types"+import type { ForumThread, Member } from "./_types"+import { VirtualRows } from "./virtual-cursor-list"+import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"// Max member avatars shown in a post card's AvatarGroup before collapsing to a// "+N" bubble. Creator is always first.-const MAX_AVATARS = 4+const MAX_AVATARS = 5// Forum channel body — rendered under the shared ChannelHeader. A feed of posts;// each post opens as a thread. The filter bar's tag chips are DERIVED from the@@ -28,43 +31,87 @@ export function ForumView({forumChannelId,members,onSearchMembers,- posts, loading, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,+ posts, loading, tag, availableTags = [], onTagChange, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,+ hasMore, loadingMore, onLoadMore,onDeletePost, canDeletePost, deletingPost,}: {forumChannelId: stringmembers: Member[]onSearchMembers?: (query: string) => void- posts: ForumPost[]+ posts: ForumThread[]loading?: boolean+ tag: string+ availableTags?: string[]+ onTagChange: (tag: string) => void+ hasMore?: boolean+ loadingMore?: boolean+ onLoadMore?: () => voidonOpenPost: (id: string) => void// Async — page owns the mutation + `enterThread` navigation and either- // resolves or rejects. `CreateForumPost` catches rejection to toast and+ // resolves or rejects. `CreateForumThread` catches rejection to toast and// preserve composer state for retry.- onCreatePost?: (post: NewForumPost) => Promise<void>+ onCreatePost?: (post: NewForumThread) => Promise<void>// Save handler for a single post's tags. Absent → tag editing disabled.- onEditPostTags?: (postId: string, tags: string[]) => void+ onEditPostTags?: (threadId: string, tags: string[]) => void// Whether the current user may edit a given post's tags (creator or manager).- canEditPostTags?: (post: ForumPost) => boolean+ canEditPostTags?: (post: ForumThread) => boolean// The post id whose tag save is in flight, if any.savingTagsFor?: string | null// Delete handler for a single post. Absent → delete disabled.- onDeletePost?: (post: ForumPost) => void+ onDeletePost?: (post: ForumThread) => void// Whether the current user may delete a given post (creator or manager).- canDeletePost?: (post: ForumPost) => boolean+ canDeletePost?: (post: ForumThread) => boolean// The post id whose delete is in flight, if any.deletingPost?: string | null}) {- const [tag, setTag] = useState("All")const [composing, setComposing] = useState(false)- const [editingTagsFor, setEditingTagsFor] = useState<ForumPost | null>(null)- const [deletingFor, setDeletingFor] = useState<ForumPost | null>(null)+ const [editingTagsFor, setEditingTagsFor] = useState<ForumThread | null>(null)+ const [deletingFor, setDeletingFor] = useState<ForumThread | null>(null)const newPostTriggerRef = useRef<HTMLButtonElement>(null)-- // Deduped union of every post's tags — the forum's tag list is derived, not- // stored. Only rendered when non-empty.- const allTags = [...new Set(posts.flatMap((p) => p.tags))].sort()-- const filtered = tag === "All" ? posts : posts.filter((p) => p.tags.includes(tag))+ const scrollRef = useRef<HTMLDivElement>(null)+ const alignedTagRef = useRef<string | null>(null)+ const prependSnapshotRef = useRef<{ height: number; top: number } | null>(null)+ const wasLoadingMoreRef = useRef(loadingMore)+ // eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx+ const virtualizer = useVirtualizer({+ count: posts.length,+ getScrollElement: () => scrollRef.current,+ estimateSize: () => 160,+ getItemKey: (index) => posts[index]?.id ?? index,+ overscan: 5,+ initialRect: { width: 0, height: 800 },+ })+ const filterTags = availableTags.length > 0+ ? availableTags+ : [...new Set(posts.flatMap((post) => post.tags))]+ useLayoutEffect(() => {+ if (posts.length === 0 || alignedTagRef.current === tag) return+ alignedTagRef.current = tag+ virtualizer.scrollToIndex(posts.length - 1, { align: "end" })+ }, [posts.length, tag, virtualizer])+ useLayoutEffect(() => {+ const wasLoading = wasLoadingMoreRef.current+ wasLoadingMoreRef.current = loadingMore+ const snapshot = prependSnapshotRef.current+ const root = scrollRef.current+ if (!wasLoading || loadingMore || !snapshot || !root) return+ root.scrollTop = snapshot.top + (root.scrollHeight - snapshot.height)+ prependSnapshotRef.current = null+ }, [loadingMore, posts.length])+ const loadOlder = () => {+ const root = scrollRef.current+ if (root && !prependSnapshotRef.current) {+ prependSnapshotRef.current = { height: root.scrollHeight, top: root.scrollTop }+ }+ onLoadMore?.()+ }+ const olderSentinelRef = useVirtualCursorSentinel({+ scrollRef,+ hasMore,+ isFetching: loadingMore,+ onLoad: loadOlder,+ edge: "start",+ })const closeCompose = () => {setComposing(false)@@ -79,7 +126,7 @@ export function ForumView({{/* Composer OR filter bar in the same slot — swapping (not stacking)keeps the post list below anchored. */}{composing ? (- <CreateForumPost+ <CreateForumThreadforumChannelId={forumChannelId}members={members}onSearchMembers={onSearchMembers}@@ -93,16 +140,16 @@ export function ForumView({) : (<div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-2"><div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">- {allTags.length > 0 && (+ {filterTags.length > 0 && (<>- <Badge variant={tag === "All" ? "default" : "secondary"} className="shrink-0 cursor-pointer" render={<button onClick={() => setTag("All")} />}>All</Badge>- {allTags.map((t) => (+ <Badge variant={tag === "All" ? "default" : "secondary"} className="shrink-0 cursor-pointer" render={<button onClick={() => onTagChange("All")} />}>All</Badge>+ {filterTags.map((t) => (<Badgekey={t}variant={tag === t ? "default" : "secondary"}className="shrink-0 cursor-pointer"data-testid={tid.forumTagChip(t)}- render={<button onClick={() => setTag(t)} />}+ render={<button onClick={() => onTagChange(t)} />}>{`#${t}`}</Badge>@@ -116,28 +163,33 @@ export function ForumView({</div>)}- <main className="flex-1 overflow-y-auto thin-scrollbar p-4">+ <div ref={scrollRef} role="main" className="flex-1 overflow-y-auto thin-scrollbar p-4">{loading && posts.length === 0 ? (<ForumListSkeleton />- ) : filtered.length === 0 ? (+ ) : posts.length === 0 ? (<EmptyState icon={ListChevronsUpDown} label="No posts with this tag yet. Start one with New Post." />) : (- <div className="flex flex-col gap-3">- {filtered.map((p) => {+ <>+ <div ref={olderSentinelRef} className="h-px" aria-hidden />+ <VirtualRows+ items={posts}+ virtualizer={virtualizer}+ itemKey={(post) => post.id}+ renderItem={(p) => {const canEdit = !!onEditPostTags && (canEditPostTags?.(p) ?? false)const canDelete = !!onDeletePost && (canDeletePost?.(p) ?? false)const others = p.participants.filter((m) => m.id !== p.authorId)const shown = others.slice(0, MAX_AVATARS)- const overflow = others.length - shown.length+ const overflow = Math.max(0, p.participantCount - 1 - shown.length)return (<divkey={p.id}role="button"tabIndex={0}- data-testid={tid.forumPostCard(p.id)}+ data-testid={tid.forumThreadCard(p.id)}onClick={() => onOpenPost(p.id)}onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onOpenPost(p.id) } }}- className="group/card flex cursor-pointer flex-col gap-2 rounded-lg border border-border bg-card p-4 text-left transition-colors hover:border-primary/40 hover:bg-accent/40"+ className="group/card mb-3 flex cursor-pointer flex-col gap-2 rounded-lg border border-border bg-card p-4 text-left transition-colors hover:border-primary/40 hover:bg-accent/40"><div className="flex items-center gap-2"><Avatar label={p.authorAvatar} seed={p.authorId} size={24} />@@ -146,7 +198,7 @@ export function ForumView({{others.length > 0 && (<><span className="h-4 w-px shrink-0 bg-border" aria-hidden />- <AvatarGroup data-testid={tid.forumPostAvatars(p.id)}>+ <AvatarGroup data-testid={tid.forumThreadAvatars(p.id)}>{shown.map((m) => (<Avatar key={m.id} label={m.avatar} seed={m.id} size={24} ringColor="var(--card)" />))}@@ -157,7 +209,7 @@ export function ForumView({{canEdit && (<buttontype="button"- data-testid={tid.forumPostTagBtn(p.id)}+ data-testid={tid.forumThreadTagBtn(p.id)}onClick={(e) => { e.stopPropagation(); setEditingTagsFor(p) }}className="ml-auto grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover/card:opacity-100"aria-label="Edit tags"@@ -168,7 +220,7 @@ export function ForumView({{canDelete && (<buttontype="button"- data-testid={tid.forumPostDeleteBtn(p.id)}+ data-testid={tid.forumThreadDeleteBtn(p.id)}disabled={deletingPost === p.id}onClick={(e) => { e.stopPropagation(); setDeletingFor(p) }}className={`${canEdit ? "" : "ml-auto "}grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-destructive focus-visible:opacity-100 group-hover/card:opacity-100 disabled:cursor-not-allowed disabled:opacity-50`}@@ -190,10 +242,11 @@ export function ForumView({</div></div>)- })}- </div>+ }}+ />+ </>)}- </main>+ </div>{editingTagsFor && (<PostTagDialog@@ -201,7 +254,7 @@ export function ForumView({onOpenChange={(v) => { if (!v) setEditingTagsFor(null) }}postName={editingTagsFor.name}current={editingTagsFor.tags}- allTags={allTags}+ allTags={availableTags}saving={savingTagsFor === editingTagsFor.id}onSave={(tags) => { onEditPostTags?.(editingTagsFor.id, tags); setEditingTagsFor(null) }}/>diff --git a/src/web/src/components/community/message-channel-controller.tsx b/src/web/src/components/community/message-channel-controller.tsxnew file mode 100644index 000000000..1db7ad3c8--- /dev/null+++ b/src/web/src/components/community/message-channel-controller.tsx@@ -0,0 +1,512 @@+"use client"++import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"+import { useRouter, useSearchParams } from "next/navigation"+import { toast } from "sonner"+import { deriveThreadName, MESSAGE_PREVIEW_LENGTH, type MentionType } from "@alook/shared"+import { apiFetch, toastApiError } from "@/lib/api/client"+import { avatarInitial } from "@/lib/community/avatar"+import type { Msg } from "@/components/community/_types"+import type { SendAttachment } from "@/components/community/composer"+import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"+import {+ useCommunityStore,+ useTypingNamesForScope,+ useTypingUsersForScope,+} from "@/stores/community"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import {+ sendNonce,+ tempMessageId,+ toAttachmentVm,+ useCreateThread,+ useEditMessage,+ usePinMessage,+ useSendMessage,+ useToggleMark,+ useToggleReactionApi,+ useUnpinMessage,+ useUploadFile,+ zipUploadResultsWithDimensions,+ type UploadedAttachment,+} from "@/hooks/community/mutations"+import {+ communityWsResetTypingThrottle,+ communityWsSendTyping,+} from "@/hooks/community/use-community-ws"++type MessageFeed = ReturnType<typeof useChannelMessageFeed>++type Viewer = {+ id: string+ name: string+ avatar: string+}++type MessageUiHandlers = {+ navigate?: (serverId: string, channelId: string) => void+ previewImage?: (url: string) => void+}++export function MessageChannelController({+ channelId,+ serverId,+ serverParam,+ channelName,+ viewer,+ anchorMessageId,+ feed,+ uiHandlers,+ onOpenThread,+ onOpenPinned,+ resolveUserName,+ children,+}: {+ channelId: string+ serverId: string+ serverParam: string+ channelName: string+ viewer: Viewer+ anchorMessageId: string | null+ feed: MessageFeed+ uiHandlers: MessageUiHandlers+ onOpenThread: (threadId: string) => void+ onOpenPinned: () => void+ resolveUserName: (userId: string) => string+ children: (controller: MessageChannelControllerValue) => ReactNode+}) {+ const router = useRouter()+ const searchParams = useSearchParams()+ const [replyTo, setReplyTo] = useState<{ id: string; authorName: string; text: string } | null>(null)+ const [searchQuery, setSearchQuery] = useState("")+ const [searchResults, setSearchResults] = useState<Msg[]>([])+ const [scrollTargetId, setScrollTargetId] = useState<string | null>(anchorMessageId)+ const [contextTarget, setContextTarget] = useState<{+ serverId: string+ channelId: string+ label: string+ seq: number+ } | null>(null)+ const { mutateAsync: sendMessageAsync } = useSendMessage()+ const toggleReactionApi = useToggleReactionApi()+ const { mutate: pinMessageMutate } = usePinMessage()+ const { mutate: unpinMessageMutate } = useUnpinMessage()+ const toggleMark = useToggleMark()+ const { mutate: editMessage } = useEditMessage()+ const { mutateAsync: createThreadAsync } = useCreateThread()+ const { mutateAsync: uploadFileAsync } = useUploadFile()+ const typingUserIds = useTypingUsersForScope(`ch:${channelId}`)+ const typingNames = useTypingNamesForScope(`ch:${channelId}`)+ const pinnedIds = useMemo(() => new Set(feed.pinned.map((message) => message.id)), [feed.pinned])+ const consumeScrollTarget = useCallback((targetId: string) => {+ setScrollTargetId((current) => (current === targetId ? null : current))+ }, [])++ useEffect(() => {+ if (!scrollTargetId) return+ if (feed.messages.some((message) => message.id === scrollTargetId)) return+ if (feed.isError) {+ setScrollTargetId((current) => (current === scrollTargetId ? null : current))+ }+ }, [+ scrollTargetId,+ feed.messages,+ feed.isError,+ ])++ useEffect(() => {+ setReplyTo(null)+ setSearchQuery("")+ setSearchResults([])+ setContextTarget(null)+ }, [channelId])++ const search = useCallback(async (query: string) => {+ setSearchQuery(query)+ if (!query.trim()) {+ setSearchResults([])+ return+ }+ try {+ const params = new URLSearchParams({ q: query, channelId })+ const data = await apiFetch<{+ results: Array<{+ message: { id: string; content: string; authorId: string; createdAt: string }+ author: { name: string; image: string | null }+ }>+ }>(`/api/community/messages/search?${params}`)+ setSearchResults(data.results.map((result) => ({+ id: result.message.id,+ type: "chat" as const,+ authorName: result.author.name,+ authorAvatar: result.author.image ?? avatarInitial(result.author.name),+ content: result.message.content,+ createdAt: result.message.createdAt,+ })))+ } catch (error) {+ setSearchResults([])+ toastApiError(error, "Search failed")+ }+ }, [channelId])++ const openContextSeq = useCallback((seq: number) => {+ setContextTarget((current) =>+ current ? { ...current, seq } : { serverId, channelId, label: channelName, seq },+ )+ }, [serverId, channelId, channelName])++ const onSheetReply = useCallback((target: { id: string; authorName: string; text: string }) => {+ if (contextTarget && contextTarget.channelId !== channelId) {+ useCommunityStore.getState().setPendingReply({ channelId: contextTarget.channelId, target })+ setContextTarget(null)+ uiHandlers.navigate?.(contextTarget.serverId, contextTarget.channelId)+ return+ }+ setReplyTo(target)+ setContextTarget(null)+ }, [contextTarget, channelId, uiHandlers])++ const pendingReply = useCommunityStore((state) => state.pendingReply)+ useEffect(() => {+ if (!pendingReply || pendingReply.channelId !== channelId) return+ setReplyTo(pendingReply.target)+ useCommunityStore.getState().setPendingReply(null)+ }, [pendingReply, channelId])++ const actionContext = useRef({+ messages: feed.messages,+ pinnedIds,+ channelName,+ uiHandlers,+ onOpenThread,+ onOpenPinned,+ })+ useLayoutEffect(() => {+ actionContext.current = {+ messages: feed.messages,+ pinnedIds,+ channelName,+ uiHandlers,+ onOpenThread,+ onOpenPinned,+ }+ }, [feed.messages, pinnedIds, channelName, uiHandlers, onOpenThread, onOpenPinned])++ const jumpToSeq = useCallback((seq: number) => {+ const message = actionContext.current.messages.find((item) => item.seq === seq)+ if (message) setScrollTargetId(message.id)+ else setContextTarget({ serverId, channelId, label: channelName, seq })+ }, [serverId, channelId, channelName])++ const openMessageContext = useCallback(+ (target: { serverId: string; channelId: string; label: string; seq: number }) => setContextTarget(target),+ [],+ )++ useEffect(() => {+ useCommunityStore.getState().registerUiHandlers({ jumpToSeq, openMessageContext })+ return () => useCommunityStore.getState().registerUiHandlers({ jumpToSeq: undefined, openMessageContext: undefined })+ }, [jumpToSeq, openMessageContext])++ const seqParam = searchParams.get("seq")+ useEffect(() => {+ if (!seqParam) return+ const seq = Number(seqParam)+ if (!Number.isFinite(seq)) return+ setContextTarget({ serverId, channelId, label: channelName, seq })+ router.replace(`/c/channels/${serverParam}/${channelId}`, { scroll: false })+ }, [seqParam, serverId, channelId, channelName, router, serverParam])++ const messageScope = useMemo(+ () => ({ kind: "channel" as const, id: channelId, serverId }),+ [channelId, serverId],+ )++ const runAcceptedIntent = useCallback(+ async (nonce: string) => {+ const streamStore = useMessageStreamStore.getState()+ const payload = streamStore.getRetryPayload(messageScope, nonce)+ if (!payload) return+ let uploadedAttachments: UploadedAttachment[] | undefined+ if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {+ const projected = payload.message.attachments+ if (projected?.length === payload.localUploads.length) {+ uploadedAttachments = projected.map((attachment, index) => {+ const local = payload.localUploads[index]+ return {+ id: attachment.url.slice(attachment.url.lastIndexOf("/") + 1),+ filename: local.file.name,+ contentType: local.file.type,+ size: local.file.size,+ width: local.width,+ height: local.height,+ }+ })+ }+ }+ if (payload.localUploads.length > 0 && !uploadedAttachments) {+ const results = await Promise.all(+ payload.localUploads.map((upload) =>+ uploadFileAsync({+ target: { channelId },+ file: upload.file,+ width: upload.width,+ height: upload.height,+ }).catch((error) => {+ toastApiError(error, "Failed to attach file")+ return null+ }),+ ),+ )+ if (results.some((result) => result === null)) {+ streamStore.dispatch(messageScope, { type: "uploadFailed", nonce })+ return+ }+ uploadedAttachments = zipUploadResultsWithDimensions(results, [...payload.localUploads])+ streamStore.dispatch(messageScope, {+ type: "uploadSettled",+ nonce,+ attachments: uploadedAttachments.map((attachment) =>+ toAttachmentVm(channelId, attachment)),+ })+ }+ try {+ await sendMessageAsync({+ serverId,+ channelId,+ content: payload.message.content ?? "",+ replyToId: payload.message.replyTo?.id,+ mentionType: payload.mentionType,+ attachments: uploadedAttachments,+ nonce,+ author: {+ id: viewer.id,+ name: viewer.name,+ avatar: viewer.avatar,+ },+ })+ } catch {+ return+ }+ },+ [messageScope, uploadFileAsync, channelId, sendMessageAsync, serverId, viewer.id, viewer.name, viewer.avatar],+ )++ const messageActions = useMemo(() => ({+ onToggleReaction: (id: string, emoji: string) =>+ toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewer.id }),+ onReact: (id: string, emoji: string) =>+ toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewer.id }),+ onReply: (id: string) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (message) {+ setReplyTo({+ id: message.id,+ authorName: message.authorName ?? "",+ text: message.content ?? "",+ })+ }+ },+ onPin: (id: string) => {+ if (actionContext.current.pinnedIds.has(id)) {+ unpinMessageMutate({ channelId, messageId: id }, {+ onSuccess: () => toast("Message unpinned"),+ onError: (error) => toastApiError(error, "Failed to unpin message"),+ })+ return+ }+ pinMessageMutate({ channelId, messageId: id }, {+ onSuccess: () => toast("Message pinned"),+ onError: (error) => toastApiError(error, "Failed to pin message"),+ })+ actionContext.current.onOpenPinned()+ },+ onMark: (id: string) => toggleMark(channelId, id),+ onCreateThread: async (id: string) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ const name = deriveThreadName(message?.content, actionContext.current.channelName)+ try {+ const data = await createThreadAsync({ serverId, channelId, messageId: id, name })+ actionContext.current.onOpenThread(data.id)+ } catch (error) {+ toastApiError(error, "Failed to create thread")+ }+ },+ onCopy: (id: string) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.content) return+ void navigator.clipboard?.writeText(message.content)+ toast("Copied to clipboard")+ },+ onEdit: (id: string) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.content || message.authorId !== viewer.id || message.seq === undefined) return+ const content = window.prompt("Edit message", message.content)+ if (!content || content === message.content) return+ editMessage({ serverId, channelId, messageId: id, content }, {+ onError: (error) => toastApiError(error, "Failed to edit message"),+ })+ },+ onRetry: (id: string) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.clientNonce) return+ useMessageStreamStore.getState().dispatch(messageScope, {+ type: "retry",+ nonce: message.clientNonce,+ })+ void runAcceptedIntent(message.clientNonce)+ },+ onDismiss: (id: string) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.clientNonce) return+ useMessageStreamStore.getState().dispatch(messageScope, {+ type: "dismissFailed",+ nonce: message.clientNonce,+ })+ },+ onPreviewImage: (url: string) => actionContext.current.uiHandlers.previewImage?.(url),+ onDownloadFile: (url: string) => {+ const link = document.createElement("a")+ link.href = url+ link.download = url.split("/").pop() ?? "file"+ link.click()+ },+ }), [+ channelId,+ serverId,+ viewer.id,+ toggleReactionApi,+ unpinMessageMutate,+ pinMessageMutate,+ toggleMark,+ createThreadAsync,+ editMessage,+ messageScope,+ runAcceptedIntent,+ ])++ const acceptMessage = useCallback((+ markdown: string,+ attachments?: SendAttachment[],+ mentionType?: MentionType,+ ): boolean => {+ if (!markdown && !attachments?.length) return false+ const nonce = sendNonce()+ const createdPreviewUrls: string[] = []+ const accepted = useMessageStreamStore.getState().accept(messageScope, {+ nonce,+ tempId: tempMessageId(),+ message: {+ type: "chat",+ authorId: viewer.id,+ authorName: viewer.name,+ authorAvatar: viewer.avatar,+ content: markdown,+ createdAt: new Date().toISOString(),+ ...(replyTo ? { replyTo: { ...replyTo, text: replyTo.text.slice(0, MESSAGE_PREVIEW_LENGTH) } } : {}),+ },+ localUploads: attachments?.map((attachment) => {+ const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)+ if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)+ return {+ file: attachment.file,+ previewObjectUrl,+ width: attachment.width,+ height: attachment.height,+ }+ }) ?? [],+ mentionType,+ })+ if (!accepted) {+ for (const url of createdPreviewUrls) URL.revokeObjectURL(url)+ return false+ }+ void runAcceptedIntent(nonce)+ communityWsResetTypingThrottle({ channelId })+ setReplyTo(null)+ return true+ }, [channelId, messageScope, replyTo, runAcceptedIntent, viewer.avatar, viewer.id, viewer.name])++ const value = useMemo<MessageChannelControllerValue>(() => ({+ feed,+ pinnedIds,+ replyTo,+ setReplyTo,+ searchQuery,+ searchResults,+ search,+ scrollTargetId,+ setScrollTargetId,+ consumeScrollTarget,+ contextTarget,+ setContextTarget,+ openContextSeq,+ onSheetReply,+ jumpToSeq,+ messageActions,+ threadActions: { ...messageActions, onCreateThread: undefined },+ acceptMessage,+ handleTyping: () => communityWsSendTyping({ channelId }),+ typingUsers: typingUserIds.map((id) => typingNames[id] ?? resolveUserName(id)),+ }), [+ feed,+ pinnedIds,+ replyTo,+ searchQuery,+ searchResults,+ search,+ scrollTargetId,+ consumeScrollTarget,+ contextTarget,+ openContextSeq,+ onSheetReply,+ jumpToSeq,+ messageActions,+ acceptMessage,+ channelId,+ typingUserIds,+ typingNames,+ resolveUserName,+ ])++ // eslint-disable-next-line react-hooks/refs -- render prop receives callbacks that read the latest ref only on user actions+ return children(value)+}++export type MessageChannelControllerValue = {+ feed: MessageFeed+ pinnedIds: Set<string>+ replyTo: { id: string; authorName: string; text: string } | null+ setReplyTo: (reply: { id: string; authorName: string; text: string } | null) => void+ searchQuery: string+ searchResults: Msg[]+ search: (query: string) => void+ scrollTargetId: string | null+ setScrollTargetId: (targetId: string | null) => void+ consumeScrollTarget: (targetId: string) => void+ contextTarget: { serverId: string; channelId: string; label: string; seq: number } | null+ setContextTarget: (target: { serverId: string; channelId: string; label: string; seq: number } | null) => void+ openContextSeq: (seq: number) => void+ onSheetReply: (target: { id: string; authorName: string; text: string }) => void+ jumpToSeq: (seq: number) => void+ messageActions: {+ onToggleReaction: (id: string, emoji: string) => void+ onReact: (id: string, emoji: string) => void+ onReply: (id: string) => void+ onPin: (id: string) => void+ onMark: (id: string) => void+ onCreateThread: (id: string) => Promise<void>+ onCopy: (id: string) => void+ onEdit: (id: string) => void+ onRetry: (id: string) => void+ onDismiss: (id: string) => void+ onPreviewImage: (url: string) => void+ onDownloadFile: (url: string) => void+ }+ threadActions: Omit<MessageChannelControllerValue["messageActions"], "onCreateThread"> & {+ onCreateThread: undefined+ }+ acceptMessage: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => boolean+ handleTyping: () => void+ typingUsers: string[]+}diff --git a/src/web/src/components/community/message-context-sheet.tsx b/src/web/src/components/community/message-context-sheet.tsxindex 1e17d2488..8615d3ec2 100644--- a/src/web/src/components/community/message-context-sheet.tsx+++ b/src/web/src/components/community/message-context-sheet.tsx@@ -30,16 +30,15 @@ const CONTEXT_LIMIT = 11type ScopeType = "channel" | "dm"-function seqLookupUrl(type: ScopeType, id: string, seq: number): string {- return type === "dm"- ? `/api/community/dm/${id}/messages/seq/${seq}`- : `/api/community/channels/${id}/messages/seq/${seq}`+// A DM (type=dm) and a thread are channel rows in the same id-space, so both+// resolve through the one canonical door — no per-type URL fork. `type` is kept+// in the signatures for call-site clarity but no longer branches the path.+function seqLookupUrl(_type: ScopeType, id: string, seq: number): string {+ return `/api/community/channels/${id}/messages/seq/${seq}`}-function anchorFetchUrl(type: ScopeType, id: string, anchor: string, limit: number): string {- const base = type === "dm"- ? `/api/community/dm/${id}/messages`- : `/api/community/channels/${id}/messages`+function anchorFetchUrl(_type: ScopeType, id: string, anchor: string, limit: number): string {+ const base = `/api/community/channels/${id}/messages`return `${base}?anchor=${encodeURIComponent(anchor)}&limit=${limit}`}@@ -120,7 +119,6 @@ export function MessageContextSheet({channelLabel,targetSeq,pinnedIds,- onOpenContextSheet,onOpenProfile,resolveUserName,onReply,@@ -135,7 +133,6 @@ export function MessageContextSheet({channelLabel?: stringtargetSeq: number | nullpinnedIds?: Set<string>- onOpenContextSheet?: (seq: number) => voidonOpenProfile?: OpenProfileresolveUserName?: (userId: string) => string// Fired when Reply is clicked in the sheet. Parent should seed its@@ -434,7 +431,6 @@ export function MessageContextSheet({onCreateThread={type === "channel" ? onCreateThreadId : undefined}onPreviewImage={onPreviewImage}onDownloadFile={onDownloadFile}- onOpenContextSheet={onOpenContextSheet}/>)}</div>@@ -459,7 +455,6 @@ function ContextRows({onCreateThread,onPreviewImage,onDownloadFile,- onOpenContextSheet,}: {rows: RenderMsg[]anchorId: string | null@@ -476,7 +471,6 @@ function ContextRows({onCreateThread?: (id: string) => voidonPreviewImage: (url: string) => voidonDownloadFile: (url: string) => void- onOpenContextSheet?: (seq: number) => void}) {// Single-message share from the peek sheet. The sheet has no select-mode// context (it's a read-only preview), so Share opens the dialog directly on@@ -541,7 +535,7 @@ function ContextSkeleton() {<Skeleton className="h-4 w-24 rounded" /><Skeleton className="h-3 w-14 rounded" /></div>- <Skeleton className="h-3.5 w-full max-w-[240px] rounded" />+ <Skeleton className="h-3.5 w-full max-w-60 rounded" /></div></div>))}diff --git a/src/web/src/components/community/message-list-items.test.ts b/src/web/src/components/community/message-list-items.test.tsindex 8d9436616..e8ef30437 100644--- a/src/web/src/components/community/message-list-items.test.ts+++ b/src/web/src/components/community/message-list-items.test.ts@@ -224,6 +224,31 @@ describe("flattenMessageItems", () => {const keys = items.map((i) => i.key)expect(new Set(keys).size).toBe(keys.length)})++ it("keeps the FlatItem key stable across temp id, server id, and GET refetch", () => {+ const keyFor = (message: Msg) =>+ flattenMessageItems([message], undefined).find((item) => item.kind === "message")!.key+ const optimistic = msg({ id: "temp_1", authorId: "u_me", clientNonce: "nonce-1" })+ const reconciled = { ...optimistic, id: "message_1", seq: 8 }+ const refetched = { ...reconciled, content: "canonical", createdAt: "2026-01-01T10:00:01.000Z" }+ expect(keyFor(optimistic)).toBe(keyFor(reconciled))+ expect(keyFor(reconciled)).toBe(keyFor(refetched))+ })++ it("pairs nonce identity with author and rejects server fallback nonces", () => {+ const keys = flattenMessageItems(+ [+ msg({ id: "m1", authorId: "u1", clientNonce: "same" }),+ msg({ id: "m2", authorId: "u2", clientNonce: "same" }),+ msg({ id: "m3", authorId: "u3", clientNonce: "srv:fallback" }),+ msg({ id: "m4", authorId: "u4" }),+ ],+ undefined,+ ).filter((item) => item.kind === "message").map((item) => item.key)+ expect(keys[0]).not.toBe(keys[1])+ expect(keys[2]).toBe("msg:id:m3")+ expect(keys[3]).toBe("msg:id:m4")+ })})describe("estimateRowHeight", () => {@@ -302,6 +327,18 @@ describe("estimateRowHeight", () => {).find((i) => i.kind === "message")!expect(estimateRowHeight(withImage)).toBeGreaterThan(estimateRowHeight(withoutImage))})++ it("reserves reply-header height before measurement", () => {+ const withoutReply = flattenMessageItems([msg({ id: "m1" })], undefined)+ .find((item) => item.kind === "message")!+ const withReply = flattenMessageItems([+ msg({+ id: "m1",+ replyTo: { id: "reply_1", authorName: "Bob", text: "preview" },+ }),+ ], undefined).find((item) => item.kind === "message")!+ expect(estimateRowHeight(withReply) - estimateRowHeight(withoutReply)).toBe(28)+ })})describe("computeBelowCount", () => {diff --git a/src/web/src/components/community/message-list-items.ts b/src/web/src/components/community/message-list-items.tsindex ca03a47b0..4c2fd6fa1 100644--- a/src/web/src/components/community/message-list-items.ts+++ b/src/web/src/components/community/message-list-items.ts@@ -1,6 +1,12 @@import { dateKey, formatDateLabel } from "./format-time"import type { Msg, RenderMsg } from "./_types"+function messageDisplayKey(message: Msg): string {+ const nonce = message.clientNonce+ if (!message.authorId || !nonce || nonce.startsWith("srv:")) return `msg:id:${message.id}`+ return `msg:client:${JSON.stringify([message.authorId, nonce])}`+}+// Pure list-prep logic for the virtualized `MessageList` — split out of// `message-list.tsx` (a "use client" component) into its own module with no// React/JSX so `use-scroll-anchor.ts` can import `FlatItem`/`estimateRowHeight`@@ -81,7 +87,7 @@ export function flattenMessageItems(const isPendingWindowFirst = !seenFirstMessage && hasMoreOlder && m.type === "chat"const grouped = isPendingWindowFirst || !!(prev && m.type === "chat" && !m.replyTo && !showDateDivider && prev.authorName === m.authorName&& prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < MESSAGE_GROUP_WINDOW_MS)- items.push({ kind: "message", m: { ...m, grouped }, key: `msg:${m.id}` })+ items.push({ kind: "message", m: { ...m, grouped }, key: messageDisplayKey(m) })seenFirstMessage = trueprev = m}@@ -106,6 +112,7 @@ const ATTACHMENT_FALLBACK_ESTIMATE_PX = 200const EMBED_ESTIMATE_PX = 120const REACTIONS_ESTIMATE_PX = 32const THREAD_PREVIEW_ESTIMATE_PX = 36+const REPLY_HEADER_ESTIMATE_PX = 28function estimateTextHeight(content: string | undefined): number {if (!content) return 0@@ -133,6 +140,7 @@ export function estimateRowHeight(item: FlatItem): number {if (item.kind === "new-divider") return item.dateLabel ? DATE_DIVIDER_ESTIMATE_PX : NEW_DIVIDER_ESTIMATE_PXconst m = item.mlet height = MESSAGE_BASE_ESTIMATE_PX + estimateTextHeight(m.content) + estimateAttachmentsHeight(m)+ if (m.replyTo) height += REPLY_HEADER_ESTIMATE_PXif (m.embeds?.length) height += EMBED_ESTIMATE_PX * m.embeds.lengthif (m.reactions?.length) height += REACTIONS_ESTIMATE_PXif (m.thread) height += THREAD_PREVIEW_ESTIMATE_PXdiff --git a/src/web/src/components/community/message-list.jump-target.test.ts b/src/web/src/components/community/message-list.jump-target.test.tsnew file mode 100644index 000000000..8f46a091e--- /dev/null+++ b/src/web/src/components/community/message-list.jump-target.test.ts@@ -0,0 +1,183 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { MessageList } from "./message-list"++const mocks = vi.hoisted(() => {+ const scrollToIndex = vi.fn()+ const scrollToEnd = vi.fn()+ const onScrollTargetConsumed = vi.fn()+ return {+ scrollToIndex,+ scrollToEnd,+ onScrollTargetConsumed,+ virtualizer: {+ scrollToIndex,+ scrollToEnd,+ isAtEnd: () => true,+ range: null,+ },+ }+})++vi.mock("@tanstack/react-virtual", () => ({+ useVirtualizer: () => mocks.virtualizer,+}))+vi.mock("@/hooks/community/use-virtual-cursor-sentinel", () => ({+ useVirtualCursorSentinel: () => vi.fn(),+}))+vi.mock("./virtual-cursor-list", () => ({+ VirtualRows: ({ items, renderItem }: {+ items: Array<{ key: string }>+ renderItem: (item: { key: string }) => React.ReactNode+ }) => React.createElement(React.Fragment, null, ...items.map((item) => renderItem(item))),+}))+vi.mock("./message-row", () => ({+ MessageRow: ({ m, highlighted }: { m: { id: string }; highlighted: boolean }) =>+ React.createElement("div", { "data-row-id": m.id, "data-highlighted": highlighted }),+}))+vi.mock("./message-share-dialog", () => ({ MessageShareDialog: () => null }))+vi.mock("./typing-indicator", () => ({ TypingIndicator: () => null }))++const target = {+ id: "m_target",+ type: "chat" as const,+ authorId: "user_2",+ authorName: "Alice",+ content: "Target",+ createdAt: new Date(0).toISOString(),+}++const unrelated = {+ ...target,+ id: "m_other",+ content: "Other",+}++const newer = {+ ...target,+ id: "m_newer",+ content: "Newer",+ createdAt: new Date(1).toISOString(),+}++function render(+ messages: typeof target[],+ scrollToMessageId: string | null,+ loading = false,+ initialScrollReady = true,+) {+ return React.createElement(MessageList, {+ channel: "general",+ messages,+ loading,+ initialScrollReady,+ hasMoreNewer: true,+ scrollToMessageId,+ onScrollTargetConsumed: mocks.onScrollTargetConsumed,+ onOpenThread: vi.fn(),+ })+}++const visibleTargetNode = {+ dataset: { msgId: "m_target" },+ getBoundingClientRect: () => ({ top: 300, bottom: 400 }),+}++function createNodeMock(element: { props?: { className?: string } }) {+ if (element.props?.className?.includes("thin-scrollbar")) {+ return {+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ offsetHeight: 48,+ clientHeight: 800,+ scrollTop: 0,+ querySelectorAll: () => [visibleTargetNode],+ getBoundingClientRect: () => ({ top: 0, bottom: 800 }),+ }+ }+ return {+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ offsetHeight: 48,+ clientHeight: 800,+ scrollTop: 0,+ }+}++function highlighted(renderer: TestRenderer.ReactTestRenderer) {+ return renderer.root.findByProps({ "data-row-id": "m_target" }).props["data-highlighted"]+}++describe("MessageList pending jump target", () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.stubGlobal("window", {+ setTimeout,+ requestAnimationFrame: (callback: FrameRequestCallback) => {+ callback(0)+ return 1+ },+ cancelAnimationFrame: vi.fn(),+ })+ vi.stubGlobal("ResizeObserver", class {+ observe() {}+ disconnect() {}+ })+ mocks.scrollToIndex.mockClear()+ mocks.scrollToEnd.mockClear()+ mocks.onScrollTargetConsumed.mockClear()+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ vi.useRealTimers()+ })++ it("waits for the target row, jumps once, and resets after null", () => {+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(render([unrelated], "m_target", false, false), { createNodeMock })+ })+ expect(mocks.scrollToEnd).not.toHaveBeenCalled()+ expect(mocks.scrollToIndex).not.toHaveBeenCalled()+ expect(mocks.onScrollTargetConsumed).not.toHaveBeenCalled()++ act(() => {+ renderer!.update(render([unrelated, target], "m_target", false, false))+ })+ expect(mocks.scrollToEnd).toHaveBeenCalledOnce()+ expect(mocks.scrollToIndex).toHaveBeenCalledOnce()+ expect(mocks.scrollToEnd.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.scrollToIndex.mock.invocationCallOrder[0],+ )+ expect(mocks.scrollToIndex).toHaveBeenCalledWith(2, { align: "center", behavior: "auto" })+ expect(mocks.onScrollTargetConsumed).toHaveBeenCalledOnce()+ expect(mocks.onScrollTargetConsumed).toHaveBeenCalledWith("m_target")+ expect(highlighted(renderer!)).toBe(true)++ act(() => {+ renderer!.update(render([unrelated, target, newer], "m_target", false, false))+ })+ expect(mocks.scrollToIndex).toHaveBeenCalledOnce()+ expect(mocks.onScrollTargetConsumed).toHaveBeenCalledOnce()++ act(() => vi.advanceTimersByTime(800))++ act(() => {+ renderer!.update(render([unrelated, target, newer], null, false, false))+ })+ act(() => {+ renderer!.update(render([unrelated, target, newer], "m_target", false, false))+ })+ expect(mocks.scrollToIndex).toHaveBeenCalledTimes(2)+ expect(mocks.onScrollTargetConsumed).toHaveBeenCalledTimes(2)+ act(() => vi.advanceTimersByTime(800))+ expect(highlighted(renderer!)).toBe(true)+ act(() => vi.advanceTimersByTime(799))+ expect(highlighted(renderer!)).toBe(true)+ act(() => vi.advanceTimersByTime(1))+ expect(highlighted(renderer!)).toBe(false)+ })+})diff --git a/src/web/src/components/community/message-list.older-load.test.ts b/src/web/src/components/community/message-list.older-load.test.tsindex c937408ac..696e11853 100644--- a/src/web/src/components/community/message-list.older-load.test.ts+++ b/src/web/src/components/community/message-list.older-load.test.ts@@ -12,21 +12,28 @@ import { MessageList } from "./message-list"// observer, which would re-fire against the still-visible sentinel and trigger// the next fetch — draining every older page in one go.//-// This drives the real observer callback: intersect once, flip-// `isFetchingOlder` true→false across re-renders (what a real fetch does), and-// assert `onLoadOlder` fires exactly ONCE, not once per re-render.+// This drives the real observer callback, including the user-visible failure:+// a second intersection arrives while the previous page is still fetching and+// the sentinel stays visible after settle. That busy demand must replay once+// without needing a synthetic third intersection or cascading through history.describe("MessageList — older-load sentinel does not cascade", () => {it("fires onLoadOlder once per intersection, not on every fetch-state re-render", () => {// Capture the observer callback so the test can drive intersections itself.let ioCallback: ((entries: Array<{ isIntersecting: boolean }>) => void) | null = null+ let scrollListener: (() => void) | null = null+ const removeScrollListener = vi.fn()const mockScrollEl = {scrollHeight: 1000,- scrollTop: 0,+ scrollTop: 500,clientHeight: 500,firstElementChild: null,scrollTo: () => {},- addEventListener: () => {},- removeEventListener: () => {},+ addEventListener: (event: string, listener: () => void) => {+ if (event === "scroll") scrollListener = listener+ },+ removeEventListener: (event: string, listener: () => void) => {+ if (event === "scroll") removeScrollListener(listener)+ },getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),querySelector: () => null,querySelectorAll: () => [],@@ -75,6 +82,7 @@ describe("MessageList — older-load sentinel does not cascade", () => {})expect(ioCallback).not.toBeNull()+ expect(scrollListener).not.toBeNull()// Sentinel scrolls into view → the first (and only) legitimate load.act(() => {@@ -95,23 +103,78 @@ describe("MessageList — older-load sentinel does not cascade", () => {})expect(onLoadOlder).toHaveBeenCalledTimes(1)- // While a fetch is in flight, a genuine intersection must be ignored- // (guarded by isFetchingOlder read from the ref).+ // Busy upward movement that remains outside the near-top boundary does+ // not queue a demand.act(() => {renderer!.update(render(true))})act(() => {- ioCallback!([{ isIntersecting: true }])+ mockScrollEl.scrollTop = 250+ scrollListener!()})expect(onLoadOlder).toHaveBeenCalledTimes(1)+ act(() => renderer!.update(render(false)))+ expect(onLoadOlder).toHaveBeenCalledTimes(1)- // Once the fetch settles, the next real intersection loads the next page.+ // The user now flings from far away to scrollTop=0 while fetching. The+ // sentinel was already intersecting, so there is NO second IO callback;+ // the captured scroll fallback must queue one demand. Repeated busy+ // upward scrolls coalesce into that same one slot.act(() => {+ renderer!.update(render(true))+ })+ act(() => {+ mockScrollEl.scrollTop = 0+ scrollListener!()+ mockScrollEl.scrollTop = 150+ scrollListener!()+ mockScrollEl.scrollTop = 0+ scrollListener!()+ })+ expect(onLoadOlder).toHaveBeenCalledTimes(1)++ // Settle replays exactly once without a fabricated IO callback.+ act(() => renderer!.update(render(false)))+ expect(onLoadOlder).toHaveBeenCalledTimes(2)++ // Continued re-renders while the sentinel remains visible do not drain+ // more history: replay clears pending before calling the loader.+ act(() => {+ renderer!.update(render(false))renderer!.update(render(false))})+ expect(onLoadOlder).toHaveBeenCalledTimes(2)++ // A queued busy demand is discarded when history ends.+ act(() => {+ renderer!.update(render(true))+ })act(() => {ioCallback!([{ isIntersecting: true }])})+ act(() => {+ renderer!.update(React.createElement(MessageList, {+ channel: "general", messages, loading: false, hasMore: false,+ onLoadOlder, isFetchingOlder: false, onOpenThread: vi.fn(),+ }))+ })+ expect(onLoadOlder).toHaveBeenCalledTimes(2)++ // Re-mount, queue real pending work, then unmount before settle. Cleanup+ // removes the listener and the abandoned demand can never replay.+ act(() => renderer!.unmount())+ ioCallback = null+ scrollListener = null+ mockScrollEl.scrollTop = 500+ act(() => {+ renderer = TestRenderer.create(render(true), {+ createNodeMock: (node) => (node.type === "div" ? mockScrollEl : genericMock),+ })+ })+ act(() => ioCallback!([{ isIntersecting: true }]))+ expect(onLoadOlder).toHaveBeenCalledTimes(2)+ act(() => renderer!.unmount())+ expect(removeScrollListener).toHaveBeenCalled()expect(onLoadOlder).toHaveBeenCalledTimes(2)} finally {g.ResizeObserver = prevROdiff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxindex d53dcdfa3..a9e96f429 100644--- a/src/web/src/components/community/message-list.tsx+++ b/src/web/src/components/community/message-list.tsx@@ -14,6 +14,8 @@ import type { RenderMsg } from "./_types"import { NumberTicker } from "@/components/ui/number-ticker"import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"import { flattenMessageItems } from "./message-list-items"+import { VirtualRows } from "./virtual-cursor-list"+import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"import type { Msg, OpenProfile } from "./_types"// Channel message list — welcome hero, date dividers, messages (with the NEW divider),@@ -21,10 +23,11 @@ import type { Msg, OpenProfile } from "./_types"export function MessageList({channel, messages, loading, pinnedIds, newDividerBefore, typingUsers, onOpenThread, onOpenProfile,onToggleReaction, onReact,- onReply, onPin, onMark, onCreateThread, onCopy, onRetry, onDismiss, onPreviewImage, onDownloadFile,+ onReply, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss, onPreviewImage, onDownloadFile,resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,+ onScrollTargetConsumed,hasMore, isFetchingOlder, onLoadOlder,- hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount, onOpenContextSheet,+ hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount,}: {channel: stringmessages: Msg[]@@ -41,6 +44,7 @@ export function MessageList({onMark?: (id: string) => voidonCreateThread?: (id: string) => voidonCopy?: (id: string) => void+ onEdit?: (id: string) => voidonRetry?: (id: string) => voidonDismiss?: (id: string) => voidonPreviewImage?: (name: string) => void@@ -71,6 +75,7 @@ export function MessageList({// stale `newDividerBefore = undefined` and snaps to bottom before the// anchor is known.initialScrollReady?: boolean+ onScrollTargetConsumed?: (id: string) => void// Reverse-infinite scroll. When `hasMore` is true a top sentinel is// rendered; when it enters the viewport (via IntersectionObserver on the// scroll root) `onLoadOlder()` fires. The prepended rows are scroll-@@ -95,10 +100,6 @@ export function MessageList({// the `↓ N` badge when `hasMoreNewer` is true — DOM math can't see rows// that haven't been fetched yet.unreadCount?: number- // Fired when a message ref pill (`#NUMBER`) is clicked and the target- // isn't in the currently loaded window — the owner opens the context- // sheet (see `MessageContextSheet`). If omitted, the click is a no-op.- onOpenContextSheet?: (seq: number) => void}) {const [jumped, setJumped] = useState<string | null>(null)@@ -107,6 +108,9 @@ export function MessageList({// ticks, presence updates, etc.) doesn't re-walk the full message list// every time.const items = useMemo(() => flattenMessageItems(messages, newDividerBefore, !!hasMore), [messages, newDividerBefore, hasMore])+ const scrollTargetLoaded = !!scrollToMessageId+ && messages.some((message) => message.id === scrollToMessageId)+ const scrollAnchorReady = scrollToMessageId ? scrollTargetLoaded : initialScrollReady// ── Multi-message "share as image" (Gus uiux #128/#142) ──────────────────// Clicking Share on a row enters select mode with that row pre-selected; more@@ -213,7 +217,7 @@ export function MessageList({const { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo: jumpToIndex, onImageLoad } = useScrollAnchor({items,newDividerBefore,- initialScrollReady,+ initialScrollReady: scrollAnchorReady,hasMoreNewer,viewerUserId,heroHeight,@@ -247,38 +251,13 @@ export function MessageList({// history in one scroll). Instead: create the observer ONCE per scroll// container and read the mutable guards from refs, so it only fires on a// genuine scroll-in transition.- const topSentinelRef = useRef<HTMLDivElement>(null)- const loadOlderStateRef = useRef({ onLoadOlder, hasMore, isFetchingOlder })- // Sync the latest guards into the ref after each commit — the observer- // callback (which reads it) only fires asynchronously, so a post-render- // write is behavior-identical while keeping the ref untouched during render.- useEffect(() => {- loadOlderStateRef.current = { onLoadOlder, hasMore, isFetchingOlder }+ const topSentinelRef = useVirtualCursorSentinel({+ scrollRef,+ hasMore,+ isFetching: isFetchingOlder,+ onLoad: onLoadOlder,+ edge: "start",})- useEffect(() => {- const el = topSentinelRef.current- const root = scrollRef.current- if (!el || !root) return- const observer = new IntersectionObserver(- (entries) => {- const { onLoadOlder, hasMore, isFetchingOlder } = loadOlderStateRef.current- if (!onLoadOlder || !hasMore || isFetchingOlder) return- for (const entry of entries) {- if (entry.isIntersecting) {- onLoadOlder()- break- }- }- },- { root, rootMargin: "200px" },- )- observer.observe(el)- return () => observer.disconnect()- // Re-observe only when the sentinel node mounts/unmounts (it's absent- // while `hasMore` is false) or the scroll container changes — never on a- // fetch-state tick. `hasMore` gates whether the sentinel node renders at- // all, so it belongs here to (re-)attach when history reappears.- }, [hasMore, scrollRef])// Bottom sentinel — symmetric to the top one. Only mounted when the loaded// window is not tail-attached (`hasMoreNewer === true`). Appended rows from@@ -290,32 +269,13 @@ export function MessageList({// mutable guards from a ref so a fetch-state tick never recreates the// observer (which would re-fire against the still-visible sentinel and// cascade through all newer pages).- const bottomSentinelRef = useRef<HTMLDivElement>(null)- const loadNewerStateRef = useRef({ onLoadNewer, hasMoreNewer, isFetchingNewer })- // Same post-commit ref sync as the top sentinel — see comment above.- useEffect(() => {- loadNewerStateRef.current = { onLoadNewer, hasMoreNewer, isFetchingNewer }+ const bottomSentinelRef = useVirtualCursorSentinel({+ scrollRef,+ hasMore: hasMoreNewer,+ isFetching: isFetchingNewer,+ onLoad: onLoadNewer,+ edge: "end",})- useEffect(() => {- const el = bottomSentinelRef.current- const root = scrollRef.current- if (!el || !root) return- const observer = new IntersectionObserver(- (entries) => {- const { onLoadNewer, hasMoreNewer, isFetchingNewer } = loadNewerStateRef.current- if (!onLoadNewer || !hasMoreNewer || isFetchingNewer) return- for (const entry of entries) {- if (entry.isIntersecting) {- onLoadNewer()- break- }- }- },- { root, rootMargin: "200px" },- )- observer.observe(el)- return () => observer.disconnect()- }, [hasMoreNewer, scrollRef])// `jumpTo` — click a reply pill, scroll to (and briefly highlight) an// earlier message. Replaces the old `querySelector('[data-msg-id="..."]')`@@ -326,15 +286,68 @@ export function MessageList({// this is a documented no-op — same limitation the old DOM lookup had (it// also required the row to be loaded, just not further required it to be// within the virtualization window).- const jumpTo = useCallback((id: string) => {+ const jumpClearTimerRef = useRef<number | null>(null)+ const jumpVisibilityFrameRef = useRef<number | null>(null)+ const jumpTo = useCallback((id: string, behavior: ScrollBehavior = "smooth") => {+ if (jumpClearTimerRef.current !== null) clearTimeout(jumpClearTimerRef.current)+ if (jumpVisibilityFrameRef.current !== null) window.cancelAnimationFrame(jumpVisibilityFrameRef.current)setJumped(id)- jumpToIndex(id)- window.setTimeout(() => setJumped((v) => (v === id ? null : v)), 1600)- }, [jumpToIndex])+ jumpToIndex(id, behavior)+ let attempts = 0+ const armClear = () => {+ jumpVisibilityFrameRef.current = null+ const timeout = window.setTimeout(() => {+ setJumped((v) => (v === id ? null : v))+ if (jumpClearTimerRef.current === timeout) jumpClearTimerRef.current = null+ }, 1600)+ jumpClearTimerRef.current = timeout+ }+ const waitUntilVisible = () => {+ const root = scrollRef.current+ const row = root+ ? Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((element) => element.dataset.msgId === id)+ : undefined+ if (root && row) {+ const rootRect = root.getBoundingClientRect()+ const rowRect = row.getBoundingClientRect()+ if (rowRect.bottom > rootRect.top && rowRect.top < rootRect.bottom) {+ armClear()+ return+ }+ }+ attempts += 1+ if (attempts >= 120) {+ armClear()+ return+ }+ jumpVisibilityFrameRef.current = window.requestAnimationFrame(waitUntilVisible)+ }+ jumpVisibilityFrameRef.current = window.requestAnimationFrame(waitUntilVisible)+ }, [jumpToIndex, scrollRef])+ useEffect(() => () => {+ if (jumpClearTimerRef.current !== null) clearTimeout(jumpClearTimerRef.current)+ if (jumpVisibilityFrameRef.current !== null) window.cancelAnimationFrame(jumpVisibilityFrameRef.current)+ }, [])+ const consumedScrollTargetRef = useRef<string | null>(null)useEffect(() => {- if (scrollToMessageId) jumpTo(scrollToMessageId)- }, [scrollToMessageId, jumpTo])+ if (!scrollToMessageId) {+ consumedScrollTargetRef.current = null+ return+ }+ if (consumedScrollTargetRef.current === scrollToMessageId) return+ if (!scrollTargetLoaded || !heroMeasured) return+ consumedScrollTargetRef.current = scrollToMessageId+ jumpTo(scrollToMessageId, "auto")+ onScrollTargetConsumed?.(scrollToMessageId)+ }, [+ scrollToMessageId,+ scrollTargetLoaded,+ heroMeasured,+ jumpTo,+ onScrollTargetConsumed,+ ])// ↓ N pill precedence:// - When there are messages the client hasn't fetched yet@@ -419,22 +432,12 @@ export function MessageList({)}</div>- <div style={{ height: virtualizer.getTotalSize(), position: "relative", width: "100%" }}>- {virtualizer.getVirtualItems().map((virtualRow) => {- const item = items[virtualRow.index]- return (- <div- key={item.key}- data-index={virtualRow.index}- ref={virtualizer.measureElement}- style={{- position: "absolute",- top: 0,- left: 0,- width: "100%",- transform: `translateY(${virtualRow.start - virtualizer.options.scrollMargin}px)`,- }}- >+ <VirtualRows+ items={items}+ virtualizer={virtualizer}+ itemKey={(item) => item.key}+ renderItem={(item) => (+ <>{item.kind === "date-divider" && <DateDivider label={item.label} />}{item.kind === "new-divider" && <NewDivider dateLabel={item.dateLabel} />}{item.kind === "message" && (@@ -457,6 +460,7 @@ export function MessageList({onMarkId={onMark}onCreateThreadId={onCreateThread}onCopyId={onCopy}+ onEditId={item.m.authorId === viewerUserId ? onEdit : undefined}onRetryId={onRetry}onDismissId={onDismiss}onJumpToId={jumpTo}@@ -471,10 +475,9 @@ export function MessageList({/></div>)}- </div>- )- })}- </div>+ </>+ )}+ />{hasMoreNewer && (<divdiff --git a/src/web/src/components/community/message-markdown.test.ts b/src/web/src/components/community/message-markdown.test.tsindex e4dedabed..831019c86 100644--- a/src/web/src/components/community/message-markdown.test.ts+++ b/src/web/src/components/community/message-markdown.test.ts@@ -21,8 +21,10 @@ describe("mentionNameFromText", () => {expect(mentionNameFromText("@Gus#0042")).toBe("Gus")})- it("leaves a 5+ digit trailing run alone (not a valid discriminator)", () => {- expect(mentionNameFromText("@Gus#00423")).toBe("Gus#00423")+ it("strips a widened 5+ digit discriminator (variable-width disc)", () => {+ // Variable-width disc (A): a 5-digit tag is valid, so it strips off the+ // display name just like a 4-digit one.+ expect(mentionNameFromText("@Gus#00423")).toBe("Gus")})it("leaves @everyone as-is (no discriminator to strip)", () => {diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsxindex 1ca259932..5a66feffb 100644--- a/src/web/src/components/community/message-markdown.tsx+++ b/src/web/src/components/community/message-markdown.tsx@@ -59,7 +59,7 @@ export const MD_LITERAL_TAGS = ["mention", "channelref", "serverref"]// `Member.name`/`Msg.authorName` for the profile-card lookup in// shell-frame.tsx's `openProfile`. Exported for tests.export function mentionNameFromText(text: string): string {- return text.replace(/^@/, "").replace(/#\d{4}$/, "")+ return text.replace(/^@/, "").replace(/#\d{4,}$/, "")}export const MD_COMPONENTS = {diff --git a/src/web/src/components/community/message-menu.test.ts b/src/web/src/components/community/message-menu.test.tsindex 3d8748302..2d80557e9 100644--- a/src/web/src/components/community/message-menu.test.ts+++ b/src/web/src/components/community/message-menu.test.ts@@ -22,16 +22,23 @@ describe("messageMenuItems", () => {expect(onShare).toHaveBeenCalledOnce()})+ it("includes Edit Message only when the author-scoped handler is provided", () => {+ expect(messageMenuItems({}).some((it) => it.label === "Edit Message")).toBe(false)+ const onEdit = vi.fn()+ messageMenuItems({ onEdit }).find((it) => it.label === "Edit Message")?.onClick?.()+ expect(onEdit).toHaveBeenCalledOnce()+ })+it("gives only the high-frequency actions (Reply, Share) an icon; the rest text-only", () => {// Locked spec (uiux #14): single list; icons only on Reply + Share as// navigation anchors; low-freq actions are text (icon slot → placeholder).const items = messageMenuItems({onReply: () => {}, onShare: () => {}, onAddReaction: () => {},- onCreateThread: () => {}, onPin: () => {}, onCopy: () => {},+ onCreateThread: () => {}, onPin: () => {}, onCopy: () => {}, onEdit: () => {},})const iconLabels = items.filter((it) => it.icon).map((it) => it.label)expect(iconLabels).toEqual(["Reply", "Share as Image"])- for (const label of ["Add Reaction", "Create Thread", "Pin Message", "Copy Text"]) {+ for (const label of ["Add Reaction", "Create Thread", "Pin Message", "Copy Text", "Edit Message"]) {expect(items.find((it) => it.label === label)?.icon).toBeUndefined()}})@@ -39,9 +46,9 @@ describe("messageMenuItems", () => {it("keeps the original row order — icons don't reorder the list (uiux #19)", () => {const labels = messageMenuItems({onReply: () => {}, onShare: () => {}, onAddReaction: () => {},- onCreateThread: () => {}, onPin: () => {}, onCopy: () => {},+ onCreateThread: () => {}, onPin: () => {}, onCopy: () => {}, onEdit: () => {},}).map((it) => it.label)- expect(labels).toEqual(["Add Reaction", "Reply", "Create Thread", "Pin Message", "Copy Text", "Share as Image"])+ expect(labels).toEqual(["Add Reaction", "Reply", "Create Thread", "Pin Message", "Copy Text", "Edit Message", "Share as Image"])expect(labels).not.toContain("sep")})diff --git a/src/web/src/components/community/message-menu.tsx b/src/web/src/components/community/message-menu.tsxindex 3f9309240..4fdddca39 100644--- a/src/web/src/components/community/message-menu.tsx+++ b/src/web/src/components/community/message-menu.tsx@@ -29,6 +29,7 @@ export function messageMenuItems(handlers: {marked?: booleanonCreateThread?: () => voidonCopy?: () => void+ onEdit?: () => voidonShare?: () => void}): Item[] {const items: Item[] = []@@ -47,6 +48,7 @@ export function messageMenuItems(handlers: {? { label: "Unmark", onClick: handlers.onMark }: { label: "Mark", onClick: handlers.onMark })if (handlers.onCopy) items.push({ label: "Copy Text", onClick: handlers.onCopy })+ if (handlers.onEdit) items.push({ label: "Edit Message", onClick: handlers.onEdit })if (handlers.onShare) items.push({ label: "Share as Image", icon: Share, onClick: handlers.onShare })return items}diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/message-row.tsxindex e33c2a3e5..52d62fbe7 100644--- a/src/web/src/components/community/message-row.tsx+++ b/src/web/src/components/community/message-row.tsx@@ -28,6 +28,7 @@ export interface MessageRowProps {onMarkId?: (id: string) => voidonCreateThreadId?: (id: string) => voidonCopyId?: (id: string) => void+ onEditId?: (id: string) => voidonRetryId?: (id: string) => voidonDismissId?: (id: string) => voidonJumpToId?: (id: string) => void@@ -51,7 +52,7 @@ function MessageRowImpl(props: MessageRowProps) {const {m, pinned, highlighted, onOpenThread, onOpenProfile,onToggleReactionId, onReactId, onReplyId, onPinId, onMarkId, onCreateThreadId,- onCopyId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onDownloadFile,+ onCopyId, onEditId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onDownloadFile,resolveUserName, onImageLoad,selectMode, selected, onToggleSelectId, onEnterSelectId, onShareSingleId,} = props@@ -71,6 +72,7 @@ function MessageRowImpl(props: MessageRowProps) {const onMark = useCallback(() => onMarkId?.(id), [onMarkId, id])const onCreateThread = useCallback(() => onCreateThreadId?.(id), [onCreateThreadId, id])const onCopy = useCallback(() => onCopyId?.(id), [onCopyId, id])+ const onEdit = useCallback(() => onEditId?.(id), [onEditId, id])const onRetry = useCallback(() => onRetryId?.(id), [onRetryId, id])const onDismiss = useCallback(() => onDismissId?.(id), [onDismissId, id])const onJumpReply = useCallback(() => { if (replyToId) onJumpToId?.(replyToId) }, [onJumpToId, replyToId])@@ -98,6 +100,7 @@ function MessageRowImpl(props: MessageRowProps) {onMark={onMarkId ? onMark : undefined}onCreateThread={onCreateThreadId ? onCreateThread : undefined}onCopy={onCopyId ? onCopy : undefined}+ onEdit={onEditId ? onEdit : undefined}onRetry={onRetryId ? onRetry : undefined}onDismiss={onDismissId ? onDismiss : undefined}onPreviewImage={onPreviewImage}diff --git a/src/web/src/components/community/message-share-dialog.tsx b/src/web/src/components/community/message-share-dialog.tsxindex 9ab07342c..86bb003d7 100644--- a/src/web/src/components/community/message-share-dialog.tsx+++ b/src/web/src/components/community/message-share-dialog.tsx@@ -196,7 +196,7 @@ export function MessageShareDialog({ m, open, onClose }: {<divref={(el) => { bodyRefs.current.set(msg.id, el) }}onMouseUp={() => onBodyMouseUp(msg.id)}- className="max-h-[41rem] overflow-hidden line-clamp-[32] [&_mark[data-hl]]:bg-[rgba(255,208,92,0.5)] [&_mark[data-hl]]:[border-radius:2px] [&_mark[data-hl]]:[padding:0_1px] [&_mark[data-hl]]:[box-decoration-break:clone] [&_mark[data-hl]]:[-webkit-box-decoration-break:clone] [&_mark[data-hl]]:text-inherit"+ className="max-h-164 overflow-hidden line-clamp-32 [&_mark[data-hl]]:rounded-xs [&_mark[data-hl]]:bg-[rgba(255,208,92,0.5)] [&_mark[data-hl]]:p-[0_1px] [&_mark[data-hl]]:[box-decoration-break:clone] [&_mark[data-hl]]:[-webkit-box-decoration-break:clone] [&_mark[data-hl]]:text-inherit"><MessageBody text={msg.content} /></div>diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex 0e7a55de0..6fc22e15e 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -48,7 +48,7 @@ export function messageCanShare(m: RenderMsg, compact?: boolean): boolean {function MessageImpl({m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,- onToggleReaction, onReact, onReply, onPin, onMark, onCreateThread, onCopy, onRetry, onDismiss,+ onToggleReaction, onReact, onReply, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss,onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad,selectMode, selected, onToggleSelect, onEnterSelect, onShareSingle,}: {@@ -68,6 +68,7 @@ function MessageImpl({onMark?: () => voidonCreateThread?: () => voidonCopy?: () => void+ onEdit?: () => voidonRetry?: () => voidonDismiss?: () => voidonPreviewImage?: (name: string) => void@@ -130,7 +131,7 @@ function MessageImpl({onReply, onPin, pinned,onMark, marked: markedData?.marked ?? false,onCreateThread: m.thread ? undefined : onCreateThread,- onCopy,+ onCopy, onEdit,// Share: enter multi-select (main list) if wired, else direct single-share// (context-sheet). Undefined only when the surface wired NEITHER.onShare: canShare ? (onEnterSelect ?? onShareSingle) : undefined,@@ -499,6 +500,7 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {prev.onMark === next.onMark &&prev.onCreateThread === next.onCreateThread &&prev.onCopy === next.onCopy &&+ prev.onEdit === next.onEdit &&prev.onRetry === next.onRetry &&prev.onDismiss === next.onDismiss &&prev.onPreviewImage === next.onPreviewImage &&diff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/server-rail.tsxindex d02f812dd..387ceefc5 100644--- a/src/web/src/components/community/server-rail.tsx+++ b/src/web/src/components/community/server-rail.tsx@@ -210,7 +210,7 @@ export const ServerRail = memo(function ServerRail({s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",].join(" ")}>- {s.icon ? <img src={s.icon} alt={s.name} className="size-full object-cover" /> : <><MarbleBackground seed={s.id} /><span className="relative -translate-x-[2px] [-webkit-text-stroke:0.5px_currentColor]">{s.initial}</span></>}+ {s.icon ? <img src={s.icon} alt={s.name} className="size-full object-cover" /> : <><MarbleBackground seed={s.id} /><span className="relative -translate-x-0.5 [-webkit-text-stroke:0.5px_currentColor]">{s.initial}</span></>}</span>) : (<span key={idx} className="aspect-square rounded-sm bg-card/50" />@@ -229,7 +229,7 @@ export const ServerRail = memo(function ServerRail({icon ? "bg-secondary text-foreground" : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]",].join(" ")}>- {icon ? <img src={icon} alt={s.name} className="size-full object-cover" /> : <><MarbleBackground seed={s.id} /><span className="relative -translate-x-[2px] [-webkit-text-stroke:0.5px_currentColor]">{s.initial}</span></>}+ {icon ? <img src={icon} alt={s.name} className="size-full object-cover" /> : <><MarbleBackground seed={s.id} /><span className="relative -translate-x-0.5 [-webkit-text-stroke:0.5px_currentColor]">{s.initial}</span></>}</div>)})()}diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex d7c7c62c0..6304a37de 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -58,6 +58,7 @@ import {useDeleteMention,useUnmarkMessage,useUpdateProfile,+ useReadForumThreadFromInbox,useUploadUserAvatar,} from "@/hooks/community/mutations"import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"@@ -157,6 +158,7 @@ export function ShellFrame({const { accept: acceptDmMessage } = useDmMessageSender()const markAllInboxRead = useMarkAllInboxRead()const deleteMention = useDeleteMention()+ const { mutate: readForumThreadFromInbox } = useReadForumThreadFromInbox()const updateProfile = useUpdateProfile()const uploadUserAvatar = useUploadUserAvatar()@@ -488,6 +490,19 @@ export function ShellFrame({[router, watchInboxItem],)+ const openForumThreadFromInbox = useCallback(+ (sid: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => {+ // Start the parent progressive read first, but never gate opening the+ // child on network success. The mutation has no optimistic trim: success+ // refreshes Inbox/server aggregates, while failure toasts and leaves the+ // opener unread for a later retry.+ watchInboxItem(`channel:${childChannelId}`)+ readForumThreadFromInbox({ parentChannelId, openerMessageId })+ router.push(`/c/channels/${sid}/${childChannelId}`)+ },+ [readForumThreadFromInbox, router, watchInboxItem],+ )+// A Marked row is cross-channel — clicking one navigates to the message's// channel AND opens the context sheet on it (Gus: always land on the channel// so you see WHERE the message lives, then the sheet shows it + its context;@@ -538,6 +553,7 @@ export function ShellFrame({markedLoading={inboxMarked.isLoading}loading={inboxLoading}onOpenChannel={openServerChannel}+ onOpenForumThread={openForumThreadFromInbox}onOpenDm={openInboxDm}onOpenMention={(mention) => {if (mention.serverId && mention.channelId) openServerChannel(mention.serverId, mention.channelId, `mention:${mention.id}`)diff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/sortable-server.tsxindex 241665494..664835430 100644--- a/src/web/src/components/community/sortable-server.tsx+++ b/src/web/src/components/community/sortable-server.tsx@@ -130,7 +130,7 @@ function SortableServerImpl({) : (<><MarbleBackground seed={server.id} />- <span className="relative -translate-x-[2px] [-webkit-text-stroke:0.5px_currentColor]">+ <span className="relative -translate-x-0.5 [-webkit-text-stroke:0.5px_currentColor]">{server.initial}</span></>diff --git a/src/web/src/components/community/text-channel-surface.test.ts b/src/web/src/components/community/text-channel-surface.test.tsnew file mode 100644index 000000000..e230d10c5--- /dev/null+++ b/src/web/src/components/community/text-channel-surface.test.ts@@ -0,0 +1,239 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { MessageChannelController } from "./message-channel-controller"+import type { MessageChannelControllerValue } from "./message-channel-controller"+import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"++const mutationMocks = vi.hoisted(() => ({+ sendMessage: vi.fn(),+ toggleReaction: vi.fn(),+ pinMessage: vi.fn(),+ unpinMessage: vi.fn(),+ toggleMark: vi.fn(),+ editMessage: vi.fn(),+ createThread: vi.fn(async () => ({ id: "thread_1" })),+ uploadFile: vi.fn(),+}))++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),+ useSearchParams: () => ({ get: () => null }),+}))+vi.mock("sonner", () => ({ toast: vi.fn() }))+vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))+vi.mock("@alook/shared", () => ({ deriveThreadName: () => "thread" }))+vi.mock("@/stores/community", () => {+ const state = {+ pendingReply: null,+ setPendingReply: vi.fn(),+ registerUiHandlers: vi.fn(),+ }+ const useCommunityStore = Object.assign(+ (selector: (value: typeof state) => unknown) => selector(state),+ { getState: () => state },+ )+ return {+ useCommunityStore,+ useTypingUsersForScope: () => [],+ useTypingNamesForScope: () => ({}),+ }+})+vi.mock("@/hooks/community/mutations", () => ({+ useSendMessage: () => ({ mutateAsync: mutationMocks.sendMessage }),+ useToggleReactionApi: () => mutationMocks.toggleReaction,+ usePinMessage: () => ({ mutate: mutationMocks.pinMessage }),+ useUnpinMessage: () => ({ mutate: mutationMocks.unpinMessage }),+ useToggleMark: () => mutationMocks.toggleMark,+ useEditMessage: () => ({ mutate: mutationMocks.editMessage }),+ useCreateThread: () => ({ mutateAsync: mutationMocks.createThread }),+ useUploadFile: () => ({ mutateAsync: mutationMocks.uploadFile }),+ zipUploadResultsWithDimensions: () => [],+ sendNonce: () => "nonce_1",+}))+vi.mock("@/hooks/community/use-community-ws", () => ({+ communityWsSendTyping: vi.fn(),+ communityWsResetTypingThrottle: vi.fn(),+}))++function feed(overrides: Record<string, unknown> = {}) {+ return {+ messages: [],+ isLoading: false,+ isError: false,+ isFetchingOlder: false,+ isFetchingNewer: false,+ pinned: [],+ ...overrides,+ } as ReturnType<typeof useChannelMessageFeed>+}++function renderController(+ messageFeed: ReturnType<typeof useChannelMessageFeed>,+ targetId = "m_target",+ callbacks: {+ onOpenThread?: (threadId: string) => void+ onOpenPinned?: () => void+ passivePinVersion?: number+ } = {},+) {+ return React.createElement(+ MessageChannelController,+ {+ channelId: "channel_1",+ serverId: "server_1",+ serverParam: "server_1",+ channelName: "general",+ viewer: { id: "viewer_1", name: "Viewer", avatar: "V" },+ anchorMessageId: targetId,+ feed: messageFeed,+ uiHandlers: {},+ onOpenThread: callbacks.onOpenThread ?? vi.fn(),+ onOpenPinned: callbacks.onOpenPinned ?? vi.fn(),+ resolveUserName: (userId: string) => userId,+ },+ (controller) => React.createElement(PassiveActionProbe, {+ controller,+ pinVersion: callbacks.passivePinVersion ?? 0,+ }),+ )+}++function PassiveActionProbe({+ controller,+ pinVersion,+}: {+ controller: MessageChannelControllerValue+ pinVersion: number+}) {+ React.useEffect(() => {+ if (pinVersion > 0) controller.messageActions.onPin("m_target")+ }, [controller.messageActions, pinVersion])+ return React.createElement(ControllerProbe, { controller })+}++function ControllerProbe({ controller }: { controller: MessageChannelControllerValue }) {+ return React.createElement("div", {+ "data-scroll-target": controller.scrollTargetId,+ onClick: () => controller.consumeScrollTarget("m_target"),+ })+}++describe("MessageChannelController scroll target ownership", () => {+ beforeEach(() => {+ vi.useFakeTimers()+ })++ afterEach(() => {+ vi.useRealTimers()+ vi.clearAllMocks()+ })++ it("passes the route anchor through while the feed is loading", () => {+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(renderController(feed({ isLoading: true })))+ })++ expect(renderer!.root.findByType("div").props["data-scroll-target"]).toBe("m_target")+ })++ it("keeps a loaded target until MessageList reports consumption", () => {+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(renderController(feed({ messages: [{ id: "m_target" }] })))+ })++ expect(renderer!.root.findByType("div").props["data-scroll-target"]).toBe("m_target")+ act(() => vi.advanceTimersByTime(5000))+ expect(renderer!.root.findByType("div").props["data-scroll-target"]).toBe("m_target")+ act(() => renderer!.root.findByType("div").props.onClick())+ expect(renderer!.root.findByType("div").props["data-scroll-target"]).toBeNull()+ })++ it("keeps a missing target across warm cache until the anchor request errors", () => {+ let messageFeed = feed({ messages: [{ id: "m_unrelated" }] })+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(renderController(messageFeed))+ })++ expect(renderer!.root.findByType("div").props["data-scroll-target"]).toBe("m_target")+ messageFeed = feed({ messages: [{ id: "m_unrelated" }], isError: true })+ act(() => renderer!.update(renderController(messageFeed)))+ expect(renderer!.root.findByType("div").props["data-scroll-target"]).toBeNull()+ })++ it("does not start a visual highlight timer for a loaded target", () => {+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(renderController(feed({ messages: [{ id: "m_target" }] })))+ })+ expect(vi.getTimerCount()).toBe(0)+ act(() => renderer!.unmount())+ })++ it("keeps message action references stable while calling the latest surface callbacks", async () => {+ const firstOpenThread = vi.fn()+ const firstOpenPinned = vi.fn()+ const latestOpenThread = vi.fn()+ const latestOpenPinned = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(renderController(+ feed({ messages: [{ id: "m_target", content: "first" }] }),+ "m_target",+ { onOpenThread: firstOpenThread, onOpenPinned: firstOpenPinned },+ ))+ })+ const firstActions = renderer!.root.findByType(ControllerProbe).props.controller.messageActions++ act(() => {+ renderer!.update(renderController(+ feed({ messages: [{ id: "m_target", content: "latest" }] }),+ "m_target",+ { onOpenThread: latestOpenThread, onOpenPinned: latestOpenPinned },+ ))+ })+ const latestActions = renderer!.root.findByType(ControllerProbe).props.controller.messageActions++ expect(latestActions).toBe(firstActions)+ act(() => latestActions.onPin("m_target"))+ expect(latestOpenPinned).toHaveBeenCalledTimes(1)+ expect(firstOpenPinned).not.toHaveBeenCalled()+ await act(async () => {+ await latestActions.onCreateThread("m_target")+ })+ expect(latestOpenThread).toHaveBeenCalledWith("thread_1")+ expect(firstOpenThread).not.toHaveBeenCalled()+ })++ it("updates latest action callbacks before descendant passive effects run", () => {+ const firstOpenPinned = vi.fn()+ const latestOpenPinned = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(renderController(+ feed({ messages: [{ id: "m_target" }] }),+ "m_target",+ { onOpenPinned: firstOpenPinned },+ ))+ })+ act(() => {+ renderer!.update(renderController(+ feed({ messages: [{ id: "m_target" }] }),+ "m_target",+ { onOpenPinned: latestOpenPinned, passivePinVersion: 1 },+ ))+ })++ expect(latestOpenPinned).toHaveBeenCalledTimes(1)+ expect(firstOpenPinned).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/community/text-channel-surface.tsx b/src/web/src/components/community/text-channel-surface.tsxnew file mode 100644index 000000000..ed1f504e3--- /dev/null+++ b/src/web/src/components/community/text-channel-surface.tsx@@ -0,0 +1,190 @@+"use client"++import { useEffect, useState, type ComponentProps, type ReactNode } from "react"+import { useBreakpoint } from "@/hooks/use-mobile"+import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"+import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channel-header"+import { ChannelShell } from "@/components/community/channel-shell"+import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"+import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"+import { Composer } from "@/components/community/composer"+import { MessageContextSheet } from "@/components/community/message-context-sheet"+import { MessageList } from "@/components/community/message-list"+import {+ MessageChannelController,+} from "@/components/community/message-channel-controller"+import type { OpenProfile, RightPanel } from "@/components/community/_types"++export function TextChannelSurface({+ channelId,+ serverId,+ serverParam,+ channelName,+ viewer,+ anchorMessageId,+ headerServer,+ notificationLevel,+ onSetNotificationLevel,+ onBack,+ composerMembers,+ onSearchComposerMembers,+ channelRefCandidates,+ memberPanelProps,+ manageMembersDialog,+ uiHandlers,+ onOpenThread,+ onOpenProfile,+ resolveUserName,+}: {+ channelId: string+ serverId: string+ serverParam: string+ channelName: string+ viewer: { id: string; name: string; avatar: string }+ anchorMessageId: string | null+ headerServer?: { id: string; name: string; icon: string | null }+ notificationLevel: ChannelNotifLevel+ onSetNotificationLevel: (level: ChannelNotifLevel) => void+ onBack?: () => void+ composerMembers: ComponentProps<typeof Composer>["members"]+ onSearchComposerMembers: ComponentProps<typeof Composer>["onSearchMembers"]+ channelRefCandidates: ComponentProps<typeof Composer>["channelRefCandidates"]+ memberPanelProps: ChannelMemberPanelProps+ manageMembersDialog: ReactNode+ uiHandlers: {+ navigate?: (serverId: string, channelId: string) => void+ previewImage?: (url: string) => void+ }+ onOpenThread: (threadId: string) => void+ onOpenProfile: OpenProfile+ resolveUserName: (userId: string) => string+}) {+ const breakpoint = useBreakpoint()+ const [rightPanel, setRightPanel] = useState<RightPanel>(null)+ const feed = useChannelMessageFeed({+ channelId,+ serverId,+ viewerUserId: viewer.id,+ isChildChannel: false,+ anchorMessageId,+ })+ useEffect(() => {+ setRightPanel(null)+ }, [channelId])++ const togglePanel = (panel: Exclude<RightPanel, null>) => {+ setRightPanel((current) => current === panel ? null : panel)+ }++ return (+ <MessageChannelController+ channelId={channelId}+ serverId={serverId}+ serverParam={serverParam}+ channelName={channelName}+ viewer={viewer}+ anchorMessageId={anchorMessageId}+ feed={feed}+ uiHandlers={uiHandlers}+ onOpenThread={onOpenThread}+ onOpenPinned={() => setRightPanel("pinned")}+ resolveUserName={resolveUserName}+ >+ {(controller) => (+ <ChannelShell+ header={(+ <ChannelHeader+ channel={channelName}+ rightPanel={rightPanel}+ onToggle={togglePanel}+ notifLevel={notificationLevel}+ onSetNotifLevel={onSetNotificationLevel}+ onBack={onBack}+ server={headerServer}+ />+ )}+ body={(+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ <MessageList+ key={channelId}+ channel={channelName}+ messages={feed.messages}+ loading={feed.isLoading}+ pinnedIds={controller.pinnedIds}+ newDividerBefore={feed.newDividerBefore}+ typingUsers={controller.typingUsers}+ onOpenThread={onOpenThread}+ {...controller.messageActions}+ onOpenProfile={onOpenProfile}+ resolveUserName={resolveUserName}+ scrollToMessageId={controller.scrollTargetId}+ onScrollRoot={feed.setScrollRootEl}+ viewerUserId={viewer.id}+ initialScrollReady={!feed.readSnapshotFetching && feed.anchorInCache}+ onScrollTargetConsumed={controller.consumeScrollTarget}+ hasMore={feed.hasMoreOlder}+ isFetchingOlder={feed.isFetchingOlder}+ onLoadOlder={feed.fetchOlder}+ hasMoreNewer={feed.hasMoreNewer}+ isFetchingNewer={feed.isFetchingNewer}+ onLoadNewer={feed.fetchNewer}+ onJumpToPresent={feed.jumpToPresent}+ unreadCount={feed.unreadCount}+ />+ <div data-onboarding-target="channel-composer" className="shrink-0">+ <Composer+ channel={channelName}+ context="channel"+ members={composerMembers}+ onSearchMembers={onSearchComposerMembers}+ channelRefCandidates={channelRefCandidates}+ sendContract="accepted"+ onAcceptSend={controller.acceptMessage}+ onTyping={controller.handleTyping}+ replyingTo={controller.replyTo?.authorName}+ onCancelReply={() => controller.setReplyTo(null)}+ autoFocus={breakpoint !== "mobile"}+ draftKey={`${serverId}/${channelId}`}+ />+ </div>+ </main>+ )}+ panels={rightPanel && (+ <CommunityPanelSheet+ open+ onOpenChange={(open) => { if (!open) setRightPanel(null) }}+ kind={rightPanel}+ {...memberPanelProps}+ pinned={feed.pinned}+ pinnedLoading={feed.pinnedLoading}+ searchResults={controller.searchResults}+ searchQuery={controller.searchQuery}+ threads={feed.threads}+ threadsLoading={feed.threadsLoading}+ onOpenThread={onOpenThread}+ onOpenProfile={onOpenProfile}+ onJumpToMessage={controller.jumpToSeq}+ onSearch={controller.search}+ />+ )}+ dialogs={(+ <>+ {manageMembersDialog}+ <MessageContextSheet+ open={controller.contextTarget !== null}+ onOpenChange={(open) => { if (!open) controller.setContextTarget(null) }}+ channelId={controller.contextTarget?.channelId ?? channelId}+ channelLabel={controller.contextTarget?.label}+ targetSeq={controller.contextTarget?.seq ?? null}+ pinnedIds={controller.pinnedIds}+ onOpenProfile={onOpenProfile}+ resolveUserName={resolveUserName}+ onReply={controller.onSheetReply}+ />+ </>+ )}+ />+ )}+ </MessageChannelController>+ )+}diff --git a/src/web/src/components/community/thread-channel-surface.test.ts b/src/web/src/components/community/thread-channel-surface.test.tsnew file mode 100644index 000000000..1a34cdd9c--- /dev/null+++ b/src/web/src/components/community/thread-channel-surface.test.ts@@ -0,0 +1,377 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { ThreadChannelSurface } from "./thread-channel-surface"+import { ChannelHeader } from "./channel-header"+import { CommunityPanelSheet } from "./community-panel-sheet"+import { Composer } from "./composer"+import { MessageContextSheet } from "./message-context-sheet"+import { MessageList } from "./message-list"+import { ThreadOpener } from "./thread-opener"+import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"+import type { MessageChannelControllerValue } from "./message-channel-controller"++const mocks = vi.hoisted(() => ({+ router: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },+ apiFetch: vi.fn(),+ toastApiError: vi.fn(),+ editMessage: vi.fn(),+ acceptMessage: vi.fn(() => true),+ handleTyping: vi.fn(),+ setReplyTo: vi.fn(),+ jumpToSeq: vi.fn(),+ search: vi.fn(),+ setContextTarget: vi.fn(),+}))++vi.mock("next/navigation", () => ({ useRouter: () => mocks.router }))+vi.mock("@/lib/api/client", () => ({+ apiFetch: mocks.apiFetch,+ toastApiError: mocks.toastApiError,+}))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))+vi.mock("@/hooks/community/use-channel-message-feed", () => ({+ useChannelMessageFeed: vi.fn(),+}))+vi.mock("@/hooks/community/mutations", () => ({+ useEditMessage: () => ({ mutateAsync: mocks.editMessage }),+}))+vi.mock("@/components/community/channel-header", () => ({+ ChannelHeader: vi.fn(() => null),+ ChannelHeaderSkeleton: vi.fn(() => null),+}))+vi.mock("@/components/community/channel-shell", () => ({+ ChannelShell: ({+ header,+ body,+ panels,+ dialogs,+ }: {+ header: React.ReactNode+ body: React.ReactNode+ panels?: React.ReactNode+ dialogs?: React.ReactNode+ }) => React.createElement(React.Fragment, null, header, body, panels, dialogs),+}))+vi.mock("@/components/community/community-panel-sheet", () => ({+ CommunityPanelSheet: vi.fn(() => null),+}))+vi.mock("@/components/community/composer", () => ({+ Composer: vi.fn(() => null),+ ComposerSkeleton: vi.fn(() => null),+}))+vi.mock("@/components/community/message-context-sheet", () => ({+ MessageContextSheet: vi.fn(() => null),+}))+vi.mock("@/components/community/message-list", () => ({+ MessageList: vi.fn(() => null),+}))+vi.mock("@/components/community/thread-opener", () => ({+ ThreadOpener: vi.fn(() => null),+}))+vi.mock("@/components/community/message-channel-controller", () => ({+ MessageChannelController: ({+ feed: messageFeed,+ children,+ }: {+ feed: ReturnType<typeof useChannelMessageFeed>+ children: (controller: MessageChannelControllerValue) => React.ReactNode+ }) => children({+ feed: messageFeed,+ pinnedIds: new Set(["pinned_1"]),+ replyTo: { id: "reply_1", authorName: "Alice", text: "hello" },+ setReplyTo: mocks.setReplyTo,+ searchQuery: "query",+ searchResults: [{ id: "search_1", type: "chat" }],+ search: mocks.search,+ scrollTargetId: "m_target",+ setScrollTargetId: vi.fn(),+ consumeScrollTarget: vi.fn(),+ contextTarget: { serverId: "server_1", channelId: "source_1", label: "source", seq: 4 },+ setContextTarget: mocks.setContextTarget,+ openContextSeq: vi.fn(),+ onSheetReply: vi.fn(),+ jumpToSeq: mocks.jumpToSeq,+ messageActions: {+ onToggleReaction: vi.fn(),+ onReact: vi.fn(),+ onReply: vi.fn(),+ onPin: vi.fn(),+ onMark: vi.fn(),+ onCreateThread: vi.fn(),+ onCopy: vi.fn(),+ onEdit: vi.fn(),+ onRetry: vi.fn(),+ onPreviewImage: vi.fn(),+ onDownloadFile: vi.fn(),+ },+ threadActions: {+ onToggleReaction: vi.fn(),+ onReact: vi.fn(),+ onReply: vi.fn(),+ onPin: vi.fn(),+ onMark: vi.fn(),+ onCreateThread: undefined,+ onCopy: vi.fn(),+ onEdit: vi.fn(),+ onRetry: vi.fn(),+ onPreviewImage: vi.fn(),+ onDownloadFile: vi.fn(),+ },+ acceptMessage: mocks.acceptMessage,+ handleTyping: mocks.handleTyping,+ typingUsers: ["Alice"],+ }),+}))++const mockedChannelHeader = vi.mocked(ChannelHeader)+const mockedCommunityPanelSheet = vi.mocked(CommunityPanelSheet)+const mockedComposer = vi.mocked(Composer)+const mockedMessageContextSheet = vi.mocked(MessageContextSheet)+const mockedMessageList = vi.mocked(MessageList)+const mockedUseChannelMessageFeed = vi.mocked(useChannelMessageFeed)++function feed(overrides: Record<string, unknown> = {}) {+ return {+ messages: [{ id: "message_1", type: "chat" }],+ isLoading: false,+ isError: false,+ isFetchingOlder: false,+ isFetchingNewer: false,+ hasMoreOlder: false,+ hasMoreNewer: false,+ fetchOlder: vi.fn(),+ fetchNewer: vi.fn(),+ jumpToPresent: vi.fn(),+ readSnapshotFetching: false,+ anchorInCache: true,+ newDividerBefore: undefined,+ unreadCount: 0,+ setScrollRootEl: vi.fn(),+ threads: [{ id: "child_2" }],+ threadsLoading: false,+ pinned: [{ id: "pinned_1", type: "chat" }],+ pinnedLoading: false,+ ...overrides,+ } as ReturnType<typeof useChannelMessageFeed>+}++function surfaceProps(overrides: Record<string, unknown> = {}) {+ return {+ channelId: "thread_1",+ serverId: "server_1",+ serverParam: "server_1",+ channelName: "Thread name",+ viewer: { id: "viewer_1", name: "Viewer", avatar: "V" },+ anchorMessageId: "m_target",+ parentChannelId: "parent_1",+ parentMessageId: "opener_1",+ parentChannelName: "general",+ parentIsForum: false,+ childCreatorId: "viewer_1",+ canRenameThread: true,+ notificationLevel: "default" as const,+ onSetNotificationLevel: vi.fn(),+ onBack: vi.fn(),+ onLoadingBack: vi.fn(),+ composerMembers: [{ id: "member_1", userId: "member_1", name: "Alice" }],+ onSearchComposerMembers: vi.fn(),+ channelRefCandidates: [{ id: "parent_1", name: "general", serverId: "server_1", serverName: "Server" }],+ memberPanelProps: {+ members: [],+ membersLoading: false,+ membersLoadingMore: false,+ membersHasMore: false,+ },+ manageMembersDialog: React.createElement("span", { "data-manage-dialog": true }),+ uiHandlers: { previewImage: vi.fn() },+ onOpenChild: vi.fn(),+ onOpenProfile: vi.fn(),+ resolveUserName: (userId: string) => userId,+ ...overrides,+ }+}++function renderSurface(overrides: Record<string, unknown> = {}) {+ return React.createElement(ThreadChannelSurface, surfaceProps(overrides))+}++describe("ThreadChannelSurface ownership", () => {+ beforeEach(() => {+ mockedUseChannelMessageFeed.mockReturnValue(feed())+ mocks.apiFetch.mockResolvedValue({})+ mocks.editMessage.mockResolvedValue({})+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ vi.clearAllMocks()+ })++ it("owns the child feed and preserves opener, message-list, and composer wiring", () => {+ const props = surfaceProps()++ act(() => {+ TestRenderer.create(React.createElement(ThreadChannelSurface, props))+ })++ expect(mockedUseChannelMessageFeed).toHaveBeenCalledTimes(1)+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith({+ channelId: "thread_1",+ serverId: "server_1",+ viewerUserId: "viewer_1",+ isChildChannel: true,+ anchorMessageId: "m_target",+ })+ const messageListProps = mockedMessageList.mock.calls.at(-1)![0]+ const opener = messageListProps.hero as React.ReactElement<React.ComponentProps<typeof ThreadOpener>>+ expect(opener.type).toBe(ThreadOpener)+ expect(opener.props).toEqual(expect.objectContaining({+ parentMessageId: "opener_1",+ onOpenProfile: props.onOpenProfile,+ }))+ act(() => opener.props.onJump?.())+ expect(mocks.router.push).toHaveBeenCalledWith("/c/channels/server_1/parent_1?msg=opener_1")+ act(() => opener.props.onPreviewImage?.("https://example.test/image.png"))+ expect(props.uiHandlers.previewImage).toHaveBeenCalledWith("https://example.test/image.png")+ const anchor = { href: "", download: "", click: vi.fn() }+ vi.stubGlobal("document", { createElement: vi.fn(() => anchor) })+ act(() => opener.props.onDownloadFile?.("https://example.test/report.pdf"))+ expect(anchor).toEqual(expect.objectContaining({+ href: "https://example.test/report.pdf",+ download: "report.pdf",+ }))+ expect(anchor.click).toHaveBeenCalledTimes(1)++ expect(mockedMessageList).toHaveBeenCalledWith(expect.objectContaining({+ channel: "Thread name",+ messages: expect.arrayContaining([expect.objectContaining({ id: "message_1" })]),+ scrollToMessageId: "m_target",+ initialScrollReady: true,+ onCreateThread: undefined,+ hero: expect.anything(),+ }), undefined)+ const composerProps = mockedComposer.mock.calls.at(-1)![0]+ expect(composerProps).toEqual(expect.objectContaining({+ channel: "Thread name",+ context: "thread",+ members: props.composerMembers,+ onSearchMembers: props.onSearchComposerMembers,+ channelRefCandidates: props.channelRefCandidates,+ replyingTo: "Alice",+ autoFocus: true,+ draftKey: "server_1/thread_1",+ sendContract: "accepted",+ onAcceptSend: mocks.acceptMessage,+ onTyping: mocks.handleTyping,+ }))+ act(() => composerProps.onCancelReply?.())+ expect(mocks.setReplyTo).toHaveBeenCalledWith(null)+ })++ it("preserves regular-thread breadcrumb, rename, panel, and dialog wiring", async () => {+ const props = surfaceProps()+ let renderer: TestRenderer.ReactTestRenderer++ act(() => {+ renderer = TestRenderer.create(React.createElement(ThreadChannelSurface, props))+ })+ let headerProps = mockedChannelHeader.mock.calls.at(-1)![0]+ expect(headerProps).toEqual(expect.objectContaining({ channel: "general", forum: false }))+ expect(headerProps).toEqual(expect.objectContaining({+ notifLevel: "default",+ onSetNotifLevel: props.onSetNotificationLevel,+ onBack: props.onBack,+ }))+ expect(headerProps.breadcrumb).toEqual(expect.objectContaining({+ label: "Thread name",+ titleRename: false,+ onRename: expect.any(Function),+ }))++ await act(async () => {+ await headerProps.breadcrumb?.onRename?.("Renamed thread")+ })+ expect(mocks.apiFetch).toHaveBeenCalledWith("/api/community/channels/thread_1", {+ method: "PATCH",+ body: JSON.stringify({ name: "Renamed thread" }),+ })+ headerProps = mockedChannelHeader.mock.calls.at(-1)![0]+ expect(headerProps.breadcrumb?.label).toBe("Renamed thread")+ act(() => headerProps.breadcrumb?.onNavigateBack())+ expect(mocks.router.push).toHaveBeenCalledWith("/c/channels/server_1/parent_1")++ act(() => headerProps.onToggle("pinned"))+ const panelProps = mockedCommunityPanelSheet.mock.calls.at(-1)![0]+ expect(panelProps).toEqual(expect.objectContaining({+ kind: "pinned",+ pinned: expect.arrayContaining([expect.objectContaining({ id: "pinned_1" })]),+ searchQuery: "query",+ onOpenThread: props.onOpenChild,+ onJumpToMessage: mocks.jumpToSeq,+ onSearch: mocks.search,+ }))+ const contextProps = mockedMessageContextSheet.mock.calls.at(-1)![0]+ expect(contextProps).toEqual(expect.objectContaining({+ open: true,+ channelId: "source_1",+ channelLabel: "source",+ targetSeq: 4,+ onOpenProfile: props.onOpenProfile,+ }))+ act(() => contextProps.onOpenChange(false))+ expect(mocks.setContextTarget).toHaveBeenCalledWith(null)+ expect(renderer!.root.findByProps({ "data-manage-dialog": true })).toBeTruthy()+ })++ it("uses the forum opener-message rename path only for the post creator", async () => {+ act(() => {+ TestRenderer.create(renderSurface({ parentIsForum: true, channelName: "Post title" }))+ })+ let headerProps = mockedChannelHeader.mock.calls.at(-1)![0]+ expect(headerProps).toEqual(expect.objectContaining({ channel: "general", forum: true }))+ expect(headerProps.breadcrumb).toEqual(expect.objectContaining({+ label: "Post title",+ titleRename: true,+ onRename: expect.any(Function),+ }))+ expect(mockedMessageList.mock.calls.at(-1)![0].hero).toBeUndefined()++ await act(async () => {+ await headerProps.breadcrumb?.onRename?.("Renamed post")+ })+ expect(mocks.editMessage).toHaveBeenCalledWith({+ serverId: "server_1",+ channelId: "parent_1",+ messageId: "opener_1",+ content: "Renamed post",+ forumChannelId: "parent_1",+ })++ act(() => {+ TestRenderer.create(renderSurface({ parentIsForum: true, childCreatorId: "other_user" }))+ })+ headerProps = mockedChannelHeader.mock.calls.at(-1)![0]+ expect(headerProps.breadcrumb?.onRename).toBeUndefined()+ })++ it("preserves rename errors for regular threads and forum posts", async () => {+ const threadError = new Error("thread rename failed")+ mocks.apiFetch.mockRejectedValueOnce(threadError)+ act(() => {+ TestRenderer.create(renderSurface())+ })+ const threadRename = mockedChannelHeader.mock.calls.at(-1)![0].breadcrumb?.onRename+ await expect(threadRename?.("Broken thread")).rejects.toBe(threadError)+ expect(mocks.toastApiError).toHaveBeenCalledWith(threadError, "Failed to rename")++ const postError = new Error("post rename failed")+ mocks.editMessage.mockRejectedValueOnce(postError)+ act(() => {+ TestRenderer.create(renderSurface({ parentIsForum: true }))+ })+ const postRename = mockedChannelHeader.mock.calls.at(-1)![0].breadcrumb?.onRename+ await expect(postRename?.("Broken post")).rejects.toBe(postError)+ expect(mocks.toastApiError).toHaveBeenCalledWith(postError, "Failed to edit post")+ })+})diff --git a/src/web/src/components/community/thread-channel-surface.tsx b/src/web/src/components/community/thread-channel-surface.tsxnew file mode 100644index 000000000..fd016fe58--- /dev/null+++ b/src/web/src/components/community/thread-channel-surface.tsx@@ -0,0 +1,289 @@+"use client"++import { useCallback, useEffect, useState, type ComponentProps, type ReactNode } from "react"+import { useRouter } from "next/navigation"+import { toastApiError, apiFetch } from "@/lib/api/client"+import { useBreakpoint } from "@/hooks/use-mobile"+import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"+import { useEditMessage } from "@/hooks/community/mutations"+import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"+import { ChannelShell } from "@/components/community/channel-shell"+import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"+import { Composer, ComposerSkeleton } from "@/components/community/composer"+import { MessageChannelController } from "@/components/community/message-channel-controller"+import { MessageContextSheet } from "@/components/community/message-context-sheet"+import { MessageList } from "@/components/community/message-list"+import { ThreadOpener } from "@/components/community/thread-opener"+import type { OpenProfile, RightPanel } from "@/components/community/_types"+import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"++const ignoreNestedThread = () => {}++export function ThreadChannelSurface({+ channelId,+ serverId,+ serverParam,+ channelName,+ viewer,+ anchorMessageId,+ parentChannelId,+ parentMessageId,+ parentChannelName,+ parentIsForum,+ childCreatorId,+ canRenameThread,+ headerServer,+ notificationLevel,+ onSetNotificationLevel,+ onBack,+ onLoadingBack,+ composerMembers,+ onSearchComposerMembers,+ channelRefCandidates,+ memberPanelProps,+ manageMembersDialog,+ uiHandlers,+ onOpenChild,+ onOpenProfile,+ resolveUserName,+}: {+ channelId: string+ serverId: string+ serverParam: string+ channelName: string+ viewer: { id: string; name: string; avatar: string }+ anchorMessageId: string | null+ parentChannelId: string | null+ parentMessageId: string | null+ parentChannelName: string+ parentIsForum: boolean+ childCreatorId?: string | null+ canRenameThread: boolean+ headerServer?: { id: string; name: string; icon: string | null }+ notificationLevel: ChannelNotifLevel+ onSetNotificationLevel: (level: ChannelNotifLevel) => void+ onBack?: () => void+ onLoadingBack?: () => void+ composerMembers: ComponentProps<typeof Composer>["members"]+ onSearchComposerMembers: ComponentProps<typeof Composer>["onSearchMembers"]+ channelRefCandidates: ComponentProps<typeof Composer>["channelRefCandidates"]+ memberPanelProps: ChannelMemberPanelProps+ manageMembersDialog: ReactNode+ uiHandlers: {+ navigate?: (serverId: string, channelId: string) => void+ previewImage?: (url: string) => void+ }+ onOpenChild: (childId: string) => void+ onOpenProfile: OpenProfile+ resolveUserName: (userId: string) => string+}) {+ const router = useRouter()+ const breakpoint = useBreakpoint()+ const [rightPanel, setRightPanel] = useState<RightPanel>(null)+ const [localName, setLocalName] = useState<string | null>(null)+ const { mutateAsync: editMessageAsync } = useEditMessage()+ const feed = useChannelMessageFeed({+ channelId,+ serverId,+ viewerUserId: viewer.id,+ isChildChannel: true,+ anchorMessageId,+ })+ const displayName = localName ?? channelName++ useEffect(() => {+ setRightPanel(null)+ setLocalName(null)+ }, [channelId])++ const togglePanel = useCallback((panel: Exclude<RightPanel, null>) => {+ setRightPanel((current) => current === panel ? null : panel)+ }, [])+ const openPinned = useCallback(() => setRightPanel("pinned"), [])+ const navigateBack = useCallback(() => {+ if (parentChannelId) {+ router.push(`/c/channels/${serverParam}/${parentChannelId}`)+ return+ }+ router.back()+ }, [parentChannelId, router, serverParam])+ const rename = parentIsForum && parentChannelId && parentMessageId && childCreatorId === viewer.id+ ? async (name: string) => {+ try {+ await editMessageAsync({+ serverId,+ channelId: parentChannelId,+ messageId: parentMessageId,+ content: name,+ forumChannelId: parentChannelId,+ })+ } catch (error) {+ toastApiError(error, "Failed to edit post")+ throw error+ }+ }+ : !parentIsForum && canRenameThread+ ? async (name: string) => {+ try {+ await apiFetch(`/api/community/channels/${channelId}`, {+ method: "PATCH",+ body: JSON.stringify({ name }),+ })+ setLocalName(name)+ } catch (error) {+ toastApiError(error, "Failed to rename")+ throw error+ }+ }+ : undefined++ if (feed.isLoading) {+ return (+ <>+ <ChannelHeaderSkeleton onBack={onLoadingBack} />+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ <MessageList key={channelId} channel="" messages={[]} loading onOpenThread={ignoreNestedThread} />+ <ComposerSkeleton />+ </main>+ </>+ )+ }++ const opener = parentMessageId && !parentIsForum ? (+ <ThreadOpener+ parentMessageId={parentMessageId}+ onOpenProfile={onOpenProfile}+ onPreviewImage={(url) => uiHandlers.previewImage?.(url)}+ onDownloadFile={(url) => {+ const link = document.createElement("a")+ link.href = url+ link.download = url.split("/").pop() ?? "file"+ link.click()+ }}+ onJump={parentChannelId+ ? () => router.push(`/c/channels/${serverParam}/${parentChannelId}?msg=${parentMessageId}`)+ : undefined}+ />+ ) : undefined++ return (+ <MessageChannelController+ channelId={channelId}+ serverId={serverId}+ serverParam={serverParam}+ channelName={displayName}+ viewer={viewer}+ anchorMessageId={anchorMessageId}+ feed={feed}+ uiHandlers={uiHandlers}+ onOpenThread={ignoreNestedThread}+ onOpenPinned={openPinned}+ resolveUserName={resolveUserName}+ >+ {(controller) => (+ <ChannelShell+ header={(+ <ChannelHeader+ channel={parentChannelName}+ forum={parentIsForum}+ rightPanel={rightPanel}+ onToggle={togglePanel}+ notifLevel={notificationLevel}+ onSetNotifLevel={onSetNotificationLevel}+ onBack={onBack}+ server={headerServer}+ tools={{ threads: false }}+ breadcrumb={{+ label: displayName,+ titleRename: parentIsForum,+ onNavigateBack: navigateBack,+ onRename: rename,+ }}+ />+ )}+ body={(+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ <MessageList+ key={channelId}+ channel={displayName}+ messages={controller.feed.messages}+ loading={controller.feed.isLoading}+ pinnedIds={controller.pinnedIds}+ newDividerBefore={controller.feed.newDividerBefore}+ typingUsers={controller.typingUsers}+ onOpenThread={ignoreNestedThread}+ {...controller.threadActions}+ onOpenProfile={onOpenProfile}+ resolveUserName={resolveUserName}+ scrollToMessageId={controller.scrollTargetId}+ hero={opener}+ onScrollRoot={controller.feed.setScrollRootEl}+ viewerUserId={viewer.id}+ initialScrollReady={!controller.feed.readSnapshotFetching && controller.feed.anchorInCache}+ onScrollTargetConsumed={controller.consumeScrollTarget}+ hasMore={controller.feed.hasMoreOlder}+ isFetchingOlder={controller.feed.isFetchingOlder}+ onLoadOlder={controller.feed.fetchOlder}+ hasMoreNewer={controller.feed.hasMoreNewer}+ isFetchingNewer={controller.feed.isFetchingNewer}+ onLoadNewer={controller.feed.fetchNewer}+ onJumpToPresent={controller.feed.jumpToPresent}+ unreadCount={controller.feed.unreadCount}+ />+ <div data-onboarding-target="channel-composer" className="shrink-0">+ <Composer+ channel={displayName}+ context="thread"+ members={composerMembers}+ onSearchMembers={onSearchComposerMembers}+ channelRefCandidates={channelRefCandidates}+ sendContract="accepted"+ onAcceptSend={controller.acceptMessage}+ onTyping={controller.handleTyping}+ replyingTo={controller.replyTo?.authorName}+ onCancelReply={() => controller.setReplyTo(null)}+ autoFocus={breakpoint !== "mobile"}+ draftKey={`${serverId}/${channelId}`}+ />+ </div>+ </main>+ )}+ panels={rightPanel && (+ <CommunityPanelSheet+ open+ onOpenChange={(open) => { if (!open) setRightPanel(null) }}+ kind={rightPanel}+ {...memberPanelProps}+ pinned={controller.feed.pinned}+ pinnedLoading={controller.feed.pinnedLoading}+ searchResults={controller.searchResults}+ searchQuery={controller.searchQuery}+ threads={controller.feed.threads}+ threadsLoading={controller.feed.threadsLoading}+ onOpenThread={onOpenChild}+ onJumpToMessage={controller.jumpToSeq}+ onSearch={controller.search}+ onOpenProfile={onOpenProfile}+ />+ )}+ dialogs={(+ <>+ {manageMembersDialog}+ <MessageContextSheet+ open={controller.contextTarget !== null}+ onOpenChange={(open) => { if (!open) controller.setContextTarget(null) }}+ channelId={controller.contextTarget?.channelId ?? channelId}+ channelLabel={controller.contextTarget?.label}+ targetSeq={controller.contextTarget?.seq ?? null}+ pinnedIds={controller.pinnedIds}+ onOpenProfile={onOpenProfile}+ resolveUserName={resolveUserName}+ onReply={controller.onSheetReply}+ />+ </>+ )}+ />+ )}+ </MessageChannelController>+ )+}diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsxindex f5264e7b6..5ca46ae14 100644--- a/src/web/src/components/community/thread-opener.tsx+++ b/src/web/src/components/community/thread-opener.tsx@@ -22,7 +22,7 @@ import type { OpenProfile } from "./_types"//// The parent lives in the OUTER channel — since server membership grants// channel access, any thread viewer can fetch it via the shared endpoint.-// Fetching client-side (rather than embedding in the /threads/[id] response)+// Fetching client-side (rather than embedding in the channels/[id] response)// keeps the parent live: an edit or reaction on the source message would// reflect here without a page reload once the mutation invalidates this key.export function ThreadOpener({diff --git a/src/web/src/components/community/use-channel-tree.ts b/src/web/src/components/community/use-channel-tree.tsindex 0599f9227..91c0cdde6 100644--- a/src/web/src/components/community/use-channel-tree.ts+++ b/src/web/src/components/community/use-channel-tree.ts@@ -193,9 +193,6 @@ export function useChannelTree(categories: Category[]) {const renameCategory = useCallback((id: string, name: string) =>setCatNames((prev) => (prev[id] === name ? prev : { ...prev, [id]: name })), [])- const catPrivateRef = useRef(catPrivate)- catPrivateRef.current = catPrivate-const onDragOver = useCallback((e: DragEndEvent) => {const { active, over } = eif (!over || isCat(String(active.id))) return // category drags handled on drop@@ -206,12 +203,12 @@ export function useChannelTree(categories: Category[]) {// visibility would silently widen/tighten. Same-class cross-category// moves still follow the cursor. `onDragEnd` toasts on a blocked attempt.if (fromCat && toCat && fromCat !== toCat &&- !!catPrivateRef.current[fromCat] !== !!catPrivateRef.current[toCat]) {+ !!catPrivate[fromCat] !== !!catPrivate[toCat]) {return prev}return moveChannelAcrossCategories(prev, String(active.id), String(over.id))})- }, [])+ }, [catPrivate])const onDragEnd = useCallback((e: DragEndEvent) => {const { active, over } = ediff --git a/src/web/src/components/community/virtual-cursor-list.tsx b/src/web/src/components/community/virtual-cursor-list.tsxnew file mode 100644index 000000000..435a7fea1--- /dev/null+++ b/src/web/src/components/community/virtual-cursor-list.tsx@@ -0,0 +1,40 @@+"use client"++import type { ReactNode } from "react"+import type { Virtualizer } from "@tanstack/react-virtual"++export function VirtualRows<T>({+ items,+ virtualizer,+ itemKey,+ renderItem,+}: {+ items: T[]+ virtualizer: Virtualizer<HTMLDivElement, Element>+ itemKey: (item: T) => string+ renderItem: (item: T, index: number) => ReactNode+}) {+ return (+ <div style={{ height: virtualizer.getTotalSize(), position: "relative", width: "100%" }}>+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const item = items[virtualRow.index]+ return (+ <div+ key={itemKey(item)}+ data-index={virtualRow.index}+ ref={virtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ transform: `translateY(${virtualRow.start - virtualizer.options.scrollMargin}px)`,+ }}+ >+ {renderItem(item, virtualRow.index)}+ </div>+ )+ })}+ </div>+ )+}diff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsxindex 4206affdb..c2df7fb15 100644--- a/src/web/src/components/home/landing-shell-motion.tsx+++ b/src/web/src/components/home/landing-shell-motion.tsx@@ -876,6 +876,7 @@ function PrototypeUserBar({unreadDms={[]}mentions={[]}marked={[]}+ onOpenForumThread={() => {}}/></div>)}diff --git a/src/web/src/hooks/community/facade-membership-composition.test.ts b/src/web/src/hooks/community/facade-membership-composition.test.tsnew file mode 100644index 000000000..f3ba707d8--- /dev/null+++ b/src/web/src/hooks/community/facade-membership-composition.test.ts@@ -0,0 +1,63 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"++const apiFetchMock = vi.fn()+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))++import { addableMembersQueryFn } from "./use-channel-members"+import { invitableFriendsQueryFn } from "./use-invitable-friends"++const alice = { id: "membership_1", userId: "alice", name: "Alice", discriminator: "0001", avatar: "a", status: "offline", sub: "", role: "member" }+const bob = { id: "membership_2", userId: "bob", name: "Bob", discriminator: "0002", avatar: "b", status: "offline", sub: "", role: "member" }++describe("membership facade composition", () => {+ beforeEach(() => { vi.clearAllMocks() })++ it("pages the canonical server roster before subtracting channel members", async () => {+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url.includes("/members?limit=200&cursor=")) return { members: [bob], hasMore: false }+ if (url.includes("/servers/s1/members?")) return { members: [alice], hasMore: true, cursor: "next" }+ if (url === "/api/community/channels/c1/members") return { members: [{ userId: "alice" }] }+ throw new Error(`unexpected ${url}`)+ })+ await expect(addableMembersQueryFn("s1", "c1")).resolves.toEqual({+ members: [{ userId: "bob", name: "Bob", discriminator: "0002", avatar: "b" }],+ })+ })++ it("subtracts canonical server members from accepted friends", async () => {+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url === "/api/community/friends/accepted") return { friends: [{ ...alice, id: "friend_1" }, { ...bob, id: "friend_2" }] }+ if (url.includes("/api/community/servers/s1/members?")) return { members: [alice], hasMore: false }+ throw new Error(`unexpected ${url}`)+ })+ const result = await invitableFriendsQueryFn("s1")+ expect(result.friends.map((friend) => friend.userId)).toEqual(["bob"])+ })++ it("rejects a stale accepted-friends read instead of caching a false-empty candidate set", async () => {+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url === "/api/community/friends/accepted") return { friends: [], stale: true }+ if (url.includes("/api/community/servers/s1/members?")) return { members: [], hasMore: false }+ throw new Error(`unexpected ${url}`)+ })+ await expect(invitableFriendsQueryFn("s1")).rejects.toThrow("stale D1 read")+ })++ it("keeps last-good candidates when a QueryClient refetch gets a stale response", async () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const key = communityKeys.invitableFriends("s1")+ const lastGood = { friends: [{ ...bob, id: "friend_2" }] }+ client.setQueryData(key, lastGood)+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url === "/api/community/friends/accepted") return { friends: [], stale: true }+ if (url.includes("/api/community/servers/s1/members?")) return { members: [], hasMore: false }+ throw new Error(`unexpected ${url}`)+ })++ await expect(client.fetchQuery({ queryKey: key, queryFn: () => invitableFriendsQueryFn("s1") })).rejects.toThrow("stale D1 read")+ expect(client.getQueryData(key)).toEqual(lastGood)+ client.clear()+ })+})diff --git a/src/web/src/hooks/community/fetch-all-server-members.ts b/src/web/src/hooks/community/fetch-all-server-members.tsnew file mode 100644index 000000000..53372b88a--- /dev/null+++ b/src/web/src/hooks/community/fetch-all-server-members.ts@@ -0,0 +1,25 @@+import { MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"+import type { Member } from "@/components/community/_types"+import { apiFetch } from "@/lib/api/client"++type MembersPage = {+ members: Member[]+ hasMore: boolean+ cursor?: string+}++export async function fetchAllServerMembers(serverId: string): Promise<Member[]> {+ const members: Member[] = []+ let cursor: string | undefined+ do {+ const params = new URLSearchParams({ limit: String(MAX_MEMBERS_PAGE_SIZE) })+ if (cursor) params.set("cursor", cursor)+ const page = await apiFetch<MembersPage>(+ `/api/community/servers/${encodeURIComponent(serverId)}/members?${params}`,+ )+ members.push(...page.members)+ cursor = page.hasMore ? page.cursor : undefined+ if (page.hasMore && !cursor) throw new Error("members page missing cursor")+ } while (cursor)+ return members+}diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.tsindex 3b278256d..a6f34752f 100644--- a/src/web/src/hooks/community/mutations/channels.test.ts+++ b/src/web/src/hooks/community/mutations/channels.test.ts@@ -269,15 +269,15 @@ describe("useCreateChannel — optimistic pending row", () => {expect(invalidateSpy.mock.calls.some((c) => matchesServerKey(c[0] ?? {}))).toBe(true)})- it("POSTs { categoryId, name, type } to the channels endpoint", async () => {+ it("POSTs { type, serverId, categoryId, name } to the unified create door", async () => {seed([{ id: "cat_1", name: "General", channels: [] }])apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })const mod = await load()mod.useCreateChannel()await runMutation({ serverId: "s1", categoryId: "cat_1", name: "hi", type: "text" })expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/servers/s1/channels",- { method: "POST", body: JSON.stringify({ categoryId: "cat_1", name: "hi", type: "text" }) },+ "/api/community/channels",+ { method: "POST", body: JSON.stringify({ type: "text", serverId: "s1", categoryId: "cat_1", name: "hi" }) },)})@@ -295,8 +295,8 @@ describe("useCreateChannel — optimistic pending row", () => {await capturedConfig!.mutationFn!({ serverId: "s1", categoryId: "", name: "top", type: "text" })expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/servers/s1/channels",- { method: "POST", body: JSON.stringify({ categoryId: null, name: "top", type: "text" }) },+ "/api/community/channels",+ { method: "POST", body: JSON.stringify({ type: "text", serverId: "s1", categoryId: null, name: "top" }) },)})@@ -325,8 +325,8 @@ describe("useCreateChannel — optimistic pending row", () => {await capturedConfig!.mutationFn!({ serverId: "s1", categoryId: UNCATEGORIZED_CATEGORY_ID, name: "top", type: "text" })// But the wire request sends categoryId: null — never the synthetic id.expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/servers/s1/channels",- { method: "POST", body: JSON.stringify({ categoryId: null, name: "top", type: "text" }) },+ "/api/community/channels",+ { method: "POST", body: JSON.stringify({ type: "text", serverId: "s1", categoryId: null, name: "top" }) },)})})diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 9921242d9..6dbc9fb45 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -55,9 +55,11 @@ export function useCreateChannel() {// send `null` so the server doesn't 404 on `getCategory`. onMutate still// uses the bucket to place the optimistic row in the cache.const apiCategoryId = isUncategorizedTarget(categoryId) ? null : categoryId+ // Unified create door (route/disc create-door step): POST /channels with a+ // type-discriminated descriptor. text/forum carries serverId + name.return apiFetch<CreateChannelResult>(- `/api/community/servers/${serverId}/channels`,- { method: "POST", body: JSON.stringify({ categoryId: apiCategoryId, name, type }) },+ `/api/community/channels`,+ { method: "POST", body: JSON.stringify({ type, serverId, categoryId: apiCategoryId, name }) },)},onMutate: async (args) => {diff --git a/src/web/src/hooks/community/mutations/dm.ts b/src/web/src/hooks/community/mutations/dm.tsindex f14801d0a..e2f31bfae 100644--- a/src/web/src/hooks/community/mutations/dm.ts+++ b/src/web/src/hooks/community/mutations/dm.ts@@ -16,9 +16,11 @@ export function useCreateOrGetDm() {const queryClient = useQueryClient()return useMutation<CreateOrGetDmResult, Error, CreateOrGetDmArgs>({mutationFn: async ({ userId }) => {- return apiFetch<CreateOrGetDmResult>("/api/community/dm", {+ // Unified create door (route/disc create-door step): POST /channels with+ // {type:"dm", userId} → get-or-create DM by peer identity.+ return apiFetch<CreateOrGetDmResult>("/api/community/channels", {method: "POST",- body: JSON.stringify({ userId }),+ body: JSON.stringify({ type: "dm", userId }),})},onSuccess: () => {diff --git a/src/web/src/hooks/community/mutations/folders.ts b/src/web/src/hooks/community/mutations/folders.tsindex ef9dec88f..36332ffb0 100644--- a/src/web/src/hooks/community/mutations/folders.ts+++ b/src/web/src/hooks/community/mutations/folders.ts@@ -41,7 +41,7 @@ export function useCreateServerFolderWith() {// both here and in `onMutate` below.const serverIds = [...new Set([serverIdA, serverIdB])]return apiFetch<CreateServerFolderWithResult>(- "/api/community/server-folders",+ "/api/community/users/me/server-folders",{method: "POST",body: JSON.stringify({ name: "Group", serverIds }),@@ -116,10 +116,10 @@ export function useUpdateFolderItems() {>({mutationFn: async ({ folderId, serverIds }) => {if (serverIds.length === 0) {- await apiFetch(`/api/community/server-folders/${folderId}`, { method: "DELETE" })+ await apiFetch(`/api/community/users/me/server-folders/${folderId}`, { method: "DELETE" })return}- await apiFetch(`/api/community/server-folders/${folderId}`, {+ await apiFetch(`/api/community/users/me/server-folders/${folderId}`, {method: "PATCH",body: JSON.stringify({ serverIds }),})@@ -171,7 +171,7 @@ export function useDeleteServerFolder() {{ snapshot: FoldersResponse | undefined }>({mutationFn: async ({ folderId }) => {- await apiFetch(`/api/community/server-folders/${folderId}`, { method: "DELETE" })+ await apiFetch(`/api/community/users/me/server-folders/${folderId}`, { method: "DELETE" })},onMutate: async (args) => {const key = communityKeys.folders()@@ -201,7 +201,7 @@ export function useReorderFolders() {{ snapshot: FoldersResponse | undefined }>({mutationFn: async ({ folderIds }) => {- await apiFetch("/api/community/server-folders/reorder", {+ await apiFetch("/api/community/users/me/server-folders/reorder", {method: "PATCH",body: JSON.stringify({ folderIds }),})diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.tsindex aaf501028..3b5c3ab79 100644--- a/src/web/src/hooks/community/mutations/forum.test.ts+++ b/src/web/src/hooks/community/mutations/forum.test.ts@@ -6,8 +6,6 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"-import type { ForumPostsResponse } from "@/hooks/community/use-channel-panels"-import type { ForumPost } from "@/components/community/_types"vi.mock("react", () => ({useRef: (initial: unknown) => ({ current: initial }),@@ -70,49 +68,39 @@ beforeEach(() => {capturedQc = new QueryClient()})-function makePost(id: string): ForumPost {- return {- id,- name: `post ${id}`,- messageCount: 1,- lastMessageAt: "2026-07-03T00:00:00.000Z",- parent: { authorName: "Alice", text: "root" },- authorId: "usr_alice",- authorAvatar: "A",- tags: [],- preview: "preview",- participants: [{ id: "usr_alice", name: "Alice", avatar: "A" }],- }-}--describe("useCreateForumPost", () => {+describe("useCreateForumThread", () => {it("POSTs JSON with name + content only when no attachments/mentionType are provided", async () => {- const { useCreateForumPost } = await load()- useCreateForumPost()- const created = makePost("p_new")- apiFetchMock.mockResolvedValueOnce({ post: created })+ const { useCreateForumThread } = await load()+ useCreateForumThread()+ apiFetchMock.mockResolvedValueOnce({ threadId: "p_new" })- await runMutation({ channelId: "forum_1", name: "hi", content: "body" })+ await runMutation({ nonce: "command_1", channelId: "forum_1", name: "hi", content: "body" })- expect(apiFetchMock).toHaveBeenCalledTimes(1)+ expect(apiFetchMock).toHaveBeenCalledTimes(2)const [path, init] = apiFetchMock.mock.calls[0]- expect(path).toBe("/api/community/channels/forum_1/posts")+ expect(path).toBe("/api/community/channels/forum_1/messages")expect((init as { method?: string }).method).toBe("POST")const body = JSON.parse((init as { body: string }).body)- expect(body.name).toBe("hi")- expect(body.content).toBe("body")- // Non-present fields serialize as `undefined` → dropped by JSON.stringify.+ expect(body.content).toBe("hi")+ expect(body.nonce).toBe("command_1:opener")expect(body.attachments).toBeUndefined()expect(body.mentionType).toBeUndefined()+ const [replyPath, replyInit] = apiFetchMock.mock.calls[1]+ expect(replyPath).toBe("/api/community/channels/p_new/messages")+ const replyBody = JSON.parse((replyInit as { body: string }).body)+ expect(replyBody.content).toBe("body")+ expect(replyBody.nonce).toBe("command_1:reply")})- it("threads attachments + mentionType through to the request body", async () => {- const { useCreateForumPost } = await load()- useCreateForumPost()- apiFetchMock.mockResolvedValueOnce({ post: makePost("p_new") })+ it("threads attachment IDS + mentionType through to the request body (reserve-by-id)", async () => {+ const { useCreateForumThread } = await load()+ useCreateForumThread()+ apiFetchMock.mockResolvedValueOnce({ threadId: "p_new" })+ // Reserve-by-id: the client holds full upload descriptors but sends only+ // the pending-row ids; dimensions already rode the upload (single source).const attachments = [{- url: "/api/community/media/abc.png",+ id: "att_1",filename: "abc.png",contentType: "image/png",size: 100,@@ -120,6 +108,7 @@ describe("useCreateForumPost", () => {height: 10,}]await runMutation({+ nonce: "command_1",channelId: "forum_1",name: "heads up",content: "Heads up @everyone",@@ -129,55 +118,71 @@ describe("useCreateForumPost", () => {const [, init] = apiFetchMock.mock.calls[0]const body = JSON.parse((init as { body: string }).body)- expect(body.attachments).toEqual(attachments)+ expect(body.attachments).toEqual(["att_1"])expect(body.mentionType).toBe("everyone")})- it("prepends the fresh post to the forum's cached list on success", async () => {- const { useCreateForumPost } = await load()- useCreateForumPost()- capturedQc.setQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"), {- posts: [makePost("p_old")],- })- const fresh = makePost("p_new")- apiFetchMock.mockResolvedValueOnce({ post: fresh })+ it("invalidates the composed forum list on success", async () => {+ const { useCreateForumThread } = await load()+ useCreateForumThread()+ capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })+ apiFetchMock.mockResolvedValueOnce({ threadId: "p_new" })- await runMutation({ channelId: "forum_1", name: "n", content: "c" })+ await runMutation({ nonce: "command_1", channelId: "forum_1", name: "n", content: "c" })- const cache = capturedQc.getQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"))- expect(cache?.posts.map((p) => p.id)).toEqual(["p_new", "p_old"])+ expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)})})-describe("useDeleteForumPost", () => {- it("DELETEs the post channel and removes it from the forum's cached list on success", async () => {- const { useDeleteForumPost } = await load()- useDeleteForumPost()+describe("useUpdatePostTags", () => {+ it("PUTs normalized tags and invalidates every message-feed variant", async () => {+ const { useUpdatePostTags } = await load()+ useUpdatePostTags()+ capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })+ const bugKey = [...communityKeys.channelMessages("forum_1"), "tag", "bug"] as const+ capturedQc.setQueryData(bugKey, { pages: [], pageParams: [] })+ apiFetchMock.mockResolvedValueOnce({ tags: ["bug", "p0"] })- capturedQc.setQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"), {- posts: [makePost("p1"), makePost("p2"), makePost("p3")],+ await runMutation({+ forumChannelId: "forum_1",+ threadId: "p2",+ openerMessageId: "m_p2",+ tags: [" Bug ", "P0", "bug"],})++ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/messages/m_p2/tags", {+ method: "PUT",+ body: JSON.stringify({ tags: ["bug", "p0"] }),+ })+ expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)+ expect(capturedQc.getQueryState(bugKey)?.isInvalidated).toBe(true)+ })+})++describe("useDeleteForumThread", () => {+ it("DELETEs the post channel and invalidates the canonical feed on success", async () => {+ const { useDeleteForumThread } = await load()+ useDeleteForumThread()++ capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })apiFetchMock.mockResolvedValueOnce(undefined)- await runMutation({ forumChannelId: "forum_1", postId: "p2" })+ await runMutation({ forumChannelId: "forum_1", threadId: "p2" })expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/p2", { method: "DELETE" })- const cache = capturedQc.getQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"))- expect(cache?.posts.map((p) => p.id)).toEqual(["p1", "p3"])+ expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)})it("leaves the cache untouched when the DELETE fails", async () => {- const { useDeleteForumPost } = await load()- useDeleteForumPost()+ const { useDeleteForumThread } = await load()+ useDeleteForumThread()- capturedQc.setQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"), {- posts: [makePost("p1"), makePost("p2")],- })+ const before = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }+ capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), before)apiFetchMock.mockRejectedValueOnce(new Error("500"))- await runMutationExpectError({ forumChannelId: "forum_1", postId: "p2" })+ await runMutationExpectError({ forumChannelId: "forum_1", threadId: "p2" })- const cache = capturedQc.getQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"))- expect(cache?.posts.map((p) => p.id)).toEqual(["p1", "p2"])+ expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(before)})})diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.tsindex 320d5daa0..35cd7e4d8 100644--- a/src/web/src/hooks/community/mutations/forum.ts+++ b/src/web/src/hooks/community/mutations/forum.ts@@ -3,47 +3,48 @@import { useMutation, useQueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { ForumPost } from "@/components/community/_types"-import type { ForumPostsResponse } from "@/hooks/community/use-channel-panels"import type { UploadedAttachment } from "@/hooks/community/mutations/uploads"import type { MentionType } from "@alook/shared"-export type CreateForumPostArgs = {+export type CreateForumThreadArgs = {+ nonce: stringchannelId: stringname: stringcontent: string- // Pre-uploaded R2 URLs (not raw files) — the client uploads via- // `useUploadFile` before firing this mutation, and the server persists them- // as `community_message_attachment` rows on the post's first message.+ // Pre-uploaded pending attachments — the client uploads via `useUploadFile`+ // (creating pending rows) before firing this mutation and passes the+ // descriptors here; only their `id`s reach the server (reserve-by-id,+ // route/disc step 2b), which links them onto the post's first message.attachments?: UploadedAttachment[]// Propagated to the first message so `@everyone` audience broadcast// fires end-to-end.mentionType?: MentionType}-export type CreateForumPostResult = { post: ForumPost }+export type CreateForumThreadResult = { threadId: string }-export function useCreateForumPost() {+export function useCreateForumThread() {const queryClient = useQueryClient()- return useMutation<CreateForumPostResult, Error, CreateForumPostArgs>({- mutationFn: async ({ channelId, name, content, attachments, mentionType }) => {- return apiFetch<CreateForumPostResult>(- `/api/community/channels/${channelId}/posts`,+ return useMutation<CreateForumThreadResult, Error, CreateForumThreadArgs>({+ mutationFn: async ({ nonce, channelId, name, content, attachments, mentionType }) => {+ // Server receives only the attachment IDS (reserve-by-id); dimensions+ // already rode the upload, so they are not re-sent.+ const attachmentIds = attachments?.map((a) => a.id)+ const structure = await apiFetch<CreateForumThreadResult>(+ `/api/community/channels/${channelId}/messages`,{method: "POST",- body: JSON.stringify({ name, content, attachments, mentionType }),+ body: JSON.stringify({ content: name, attachments: attachmentIds, mentionType, nonce: `${nonce}:opener` }),},)+ await apiFetch(`/api/community/channels/${structure.threadId}/messages`, {+ method: "POST",+ body: JSON.stringify({ content, attachments: attachmentIds, nonce: `${nonce}:reply` }),+ })+ return structure},onSuccess: (data, args) => {- // Prepend the fresh post to the cached list — the server-side WS- // `child_create` also invalidates, but here we win the same-tab race.- queryClient.setQueryData<ForumPostsResponse | undefined>(- communityKeys.forumPosts(args.channelId),- (prev) =>- prev- ? { ...prev, posts: [data.post, ...prev.posts] }- : { posts: [data.post] },- )+ void data+ void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.channelId) })},})}@@ -51,72 +52,60 @@ export function useCreateForumPost() {export type UpdatePostTagsArgs = {// The parent forum channel — the cache key the post list lives under.forumChannelId: string- // The post channel whose tags are being edited.- postId: string+ // The post/thread card being patched in cache.+ threadId: string+ // Tags are a resource of the forum opener message, never of the child thread.+ openerMessageId: stringtags: string[]}/**- * Edit a single forum post's tags. PATCHes the post channel (creator or manager+ * Edit a single forum post's tags. PUTs the opener-message tag resource (author or manager* gated server-side), then patches the post's row in the forum's cached list so- * the card + the derived tag filter bar update without a refetch.+ * the card + the derived tag filter bar update on success without a refetch.*/export function useUpdatePostTags() {const queryClient = useQueryClient()return useMutation<{ tags: string[] }, Error, UpdatePostTagsArgs>({- mutationFn: async ({ postId, tags }) => {+ mutationFn: async ({ openerMessageId, tags }) => {const normalized = [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))]- await apiFetch(`/api/community/channels/${postId}`, {- method: "PATCH",- body: JSON.stringify({ forumTags: JSON.stringify(normalized) }),+ await apiFetch(`/api/community/messages/${openerMessageId}/tags`, {+ method: "PUT",+ body: JSON.stringify({ tags: normalized }),})return { tags: normalized }},onSuccess: (data, args) => {- queryClient.setQueryData<ForumPostsResponse | undefined>(- communityKeys.forumPosts(args.forumChannelId),- (prev) =>- prev- ? {- ...prev,- posts: prev.posts.map((p) =>- p.id === args.postId ? { ...p, tags: data.tags } : p,- ),- }- : prev,- )+ void data+ // Prefix invalidation covers the unfiltered list and every tag variant.+ // This is required when the edited+ // post loses the currently-selected tag and must leave that result set.+ void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.forumChannelId) })},})}-export type DeleteForumPostArgs = {+export type DeleteForumThreadArgs = {// The parent forum channel — the cache key the post list lives under.forumChannelId: string// The post channel being deleted.- postId: string+ threadId: string}/**- * Delete a single forum post. A post IS a `forum_post` child channel, so this- * DELETEs the channel (creator or manager gated server-side — see the DELETE- * route's forum_post carve-out). On success (204) the post is filtered out of+ * Delete a single forum thread through the canonical child-channel resource.+ * On success (204) the post is filtered out of* the forum's cached list so the card disappears without a refetch; the* server-side WS `channel.delete` also invalidates for other clients.*/-export function useDeleteForumPost() {+export function useDeleteForumThread() {const queryClient = useQueryClient()- return useMutation<void, Error, DeleteForumPostArgs>({- mutationFn: async ({ postId }) => {- await apiFetch(`/api/community/channels/${postId}`, { method: "DELETE" })+ return useMutation<void, Error, DeleteForumThreadArgs>({+ mutationFn: async ({ threadId }) => {+ await apiFetch(`/api/community/channels/${threadId}`, { method: "DELETE" })},onSuccess: (_data, args) => {- queryClient.setQueryData<ForumPostsResponse | undefined>(- communityKeys.forumPosts(args.forumChannelId),- (prev) =>- prev- ? { ...prev, posts: prev.posts.filter((p) => p.id !== args.postId) }- : prev,- )+ void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.forumChannelId) })},})}diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex 5423a3a50..fd8eced37 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -10,6 +10,7 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import type { Msg } from "@/components/community/_types"// ── React shim (mirrors use-community-ws.test.ts) ────────────────────────let refs: Map<string, { current: unknown }> = new Map()@@ -97,13 +98,27 @@ async function loadMod() {return await import("./messages")}-function makeCache(msgs: { id: string; failed?: boolean; reactions?: unknown[] }[] = []) {+function makeCache(msgs: Array<{ id: string } & Record<string, unknown>> = []) {return {pages: [{ messages: msgs, hasMore: false }],pageParams: [null],}}+function postedMessage(id: string, seq: number) {+ return {+ id,+ seq,+ createdAt: "2026-08-07T10:00:00.000Z",+ content: "canonical content",+ authorId: "u_me",+ authorName: "Canonical Name",+ authorImage: "https://avatar.test/me.png",+ type: "default",+ embeds: [{ title: "Canonical embed" }],+ }+}+beforeEach(() => {apiFetchMock.mockReset()toastMock.mockReset()@@ -115,12 +130,66 @@ beforeEach(() => {callbackCounter = 0})+describe("useEditMessage", () => {+ it("optimistically patches content and rolls back when PATCH fails", async () => {+ const key = communityKeys.channelMessages("ch_1")+ const messageKey = communityKeys.message("m1")+ capturedQc.setQueryData(key, makeCache([{ id: "m1", content: "old" }]))+ capturedQc.setQueryData(messageKey, { id: "m1", content: "old" })+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))+ const mod = await loadMod()+ mod.useEditMessage()++ await runMutation({ serverId: "s1", channelId: "ch_1", messageId: "m1", content: "new" }).catch(() => {})++ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/messages/m1", {+ method: "PATCH",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ content: "new" }),+ })+ const cache = capturedQc.getQueryData<{ pages: { messages: { content?: string }[] }[] }>(key)+ expect(cache?.pages[0].messages[0]?.content).toBe("old")+ expect(capturedQc.getQueryData<{ content: string }>(messageKey)?.content).toBe("old")+ })++ it("optimistically patches the single-message cache used by a post header", async () => {+ const messageKey = communityKeys.message("opener_1")+ capturedQc.setQueryData(messageKey, { id: "opener_1", content: "Old title" })+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await loadMod()+ mod.useEditMessage()++ await runMutation({+ serverId: "s1", channelId: "forum_1", messageId: "opener_1", content: "New title", forumChannelId: "forum_1",+ })++ expect(capturedQc.getQueryData<{ content: string }>(messageKey)?.content).toBe("New title")+ })++ it("invalidates every forum summary variant after an opener edit", async () => {+ const root = communityKeys.channelMessages("forum_1")+ const bug = [...root, "tag", "bug"] as const+ capturedQc.setQueryData(root, { pages: [], pageParams: [] })+ capturedQc.setQueryData(bug, { pages: [], pageParams: [] })+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await loadMod()+ mod.useEditMessage()++ await runMutation({+ serverId: "s1", channelId: "forum_1", messageId: "opener_1", content: "new", forumChannelId: "forum_1",+ })++ expect(capturedQc.getQueryState(root)?.isInvalidated).toBe(true)+ expect(capturedQc.getQueryState(bug)?.isInvalidated).toBe(true)+ })+})+// ── useSendMessage ────────────────────────────────────────────────────────describe("useSendMessage — happy path", () => {it("keeps Query base-only and acknowledges the accepted overlay intent", async () => {capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))- apiFetchMock.mockResolvedValueOnce({ message: { id: "server_id_1", seq: 9 } })+ apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })const mod = await loadMod()const stream = await import("@/stores/community/message-stream")@@ -137,12 +206,21 @@ describe("useSendMessage — happy path", () => {author: { id: "u_me", name: "me", avatar: "M" },})- const cache = capturedQc.getQueryData<{ pages: { messages: { id: string }[] }[] }>(+ const cache = capturedQc.getQueryData<{ pages: { messages: Msg[] }[] }>(communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].messages).toEqual([])expect(stream.getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")).toEqual(- expect.objectContaining({ status: "acked", serverMessageId: "server_id_1", serverSeq: 9 }),+ expect.objectContaining({+ status: "acked",+ serverMessageId: "server_id_1",+ serverSeq: 9,+ message: expect.objectContaining({+ authorName: "Canonical Name",+ content: "canonical content",+ embeds: [{ title: "Canonical embed" }],+ }),+ }),)})})@@ -213,7 +291,7 @@ async function acceptDmIntent(nonce = "n1") {describe("useSendDmMessage — overlay terminal emitter", () => {it("keeps Query base-only and emits exactly one postAck", async () => {capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))- apiFetchMock.mockResolvedValueOnce({ message: { id: "server_1", seq: 8 } })+ apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_1", 8) })const mod = await loadMod()const stream = await acceptDmIntent()const dispatch = vi.spyOn(stream.useMessageStreamStore.getState(), "dispatch")@@ -224,7 +302,17 @@ describe("useSendDmMessage — overlay terminal emitter", () => {expect(dispatch).toHaveBeenCalledTimes(1)expect(dispatch).toHaveBeenCalledWith({ kind: "dm", id: "dm_1" },- { type: "postAck", nonce: "n1", serverMessageId: "server_1", serverSeq: 8 },+ {+ type: "postAck",+ nonce: "n1",+ message: expect.objectContaining({+ id: "server_1",+ seq: 8,+ authorName: "Canonical Name",+ content: "canonical content",+ clientNonce: "n1",+ }),+ },)})@@ -936,9 +1024,60 @@ describe("useAdvanceChannelWatermark", () => {})})+describe("useReadForumThreadFromInbox", () => {+ it("PUTs the exact opener target to the parent forum immediately", async () => {+ apiFetchMock.mockResolvedValue(undefined)+ const mod = await loadMod()+ mod.useReadForumThreadFromInbox()++ await runMutation({ parentChannelId: "forum_1", openerMessageId: "opener_42" })++ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/forum_1/read", {+ method: "PUT",+ body: JSON.stringify({ lastReadMessageId: "opener_42" }),+ })+ })++ it("has no optimistic cache mutation and invalidates inbox + servers only after success", async () => {+ apiFetchMock.mockResolvedValue(undefined)+ const before = { servers: [{ serverId: "s1", channels: [{ channelId: "forum_1" }] }] }+ capturedQc.setQueryData(communityKeys.inboxUnreads(), before)+ const setSpy = vi.spyOn(capturedQc, "setQueryData")+ const invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")+ const mod = await loadMod()+ mod.useReadForumThreadFromInbox()++ await runMutation({ parentChannelId: "forum_1", openerMessageId: "opener_42" })++ expect(setSpy).not.toHaveBeenCalled()+ expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual(before)+ const invalidated = invalidateSpy.mock.calls.map((call) => call[0]?.queryKey)+ expect(invalidated).toContainEqual(communityKeys.inbox())+ expect(invalidated).toContainEqual(communityKeys.servers())+ })++ it("keeps cache intact, skips success invalidation, and toasts when the PUT fails", async () => {+ const error = new Error("parent read failed")+ apiFetchMock.mockRejectedValue(error)+ const before = { servers: [{ serverId: "s1", channels: [{ channelId: "forum_1" }] }] }+ capturedQc.setQueryData(communityKeys.inboxUnreads(), before)+ const setSpy = vi.spyOn(capturedQc, "setQueryData")+ const invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")+ const mod = await loadMod()+ mod.useReadForumThreadFromInbox()++ await runMutation({ parentChannelId: "forum_1", openerMessageId: "opener_42" }).catch(() => {})++ expect(setSpy).not.toHaveBeenCalled()+ expect(invalidateSpy).not.toHaveBeenCalled()+ expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual(before)+ expect(toastMock).toHaveBeenCalledWith("parent read failed")+ })+})+// ── useAdvanceDmWatermark — DM sibling of the channel wrapper ───────────describe("useAdvanceDmWatermark", () => {- it("returns a callable that PUTs { lastReadMessageId } to the DM read route", async () => {+ it("returns a callable that PUTs { lastReadMessageId } to the canonical channels read route", async () => {vi.useFakeTimers()try {apiFetchMock.mockResolvedValue(undefined)@@ -951,7 +1090,7 @@ describe("useAdvanceDmWatermark", () => {(c) => (c[1] as { method?: string })?.method === "PUT",)expect(put).toBeDefined()- expect(put![0] as string).toBe("/api/community/dm/dm_1/read")+ expect(put![0] as string).toBe("/api/community/channels/dm_1/read")expect((put![1] as RequestInit).body).toBe(JSON.stringify({ lastReadMessageId: "m_42" }),)@@ -979,19 +1118,17 @@ describe("useAdvanceDmWatermark", () => {const puts = apiFetchMock.mock.calls.filter((c) => (c[1] as { method?: string })?.method === "PUT",)+ // DM and channel now share the canonical /channels/{id}/read URL, so the+ // two schedules are distinguished by BODY, not path — the point is the+ // shared debounce map (keyed `dm:x` vs the channel's own key) does NOT+ // alias them into one PUT.expect(puts).toHaveLength(2)- const dmPut = puts.find((c) => (c[0] as string).startsWith("/api/community/dm/"))- const chPut = puts.find((c) =>- (c[0] as string).startsWith("/api/community/channels/"),- )- expect(dmPut).toBeDefined()- expect(chPut).toBeDefined()- expect((dmPut![1] as RequestInit).body).toBe(- JSON.stringify({ lastReadMessageId: "m_dm" }),- )- expect((chPut![1] as RequestInit).body).toBe(- JSON.stringify({ lastReadMessageId: "m_ch" }),- )+ const bodies = puts.map((c) => (c[1] as RequestInit).body)+ expect(bodies).toContain(JSON.stringify({ lastReadMessageId: "m_dm" }))+ expect(bodies).toContain(JSON.stringify({ lastReadMessageId: "m_ch" }))+ for (const c of puts) {+ expect(c[0] as string).toBe("/api/community/channels/x/read")+ }} finally {vi.useRealTimers()}@@ -1054,9 +1191,9 @@ describe("useMarkAllInboxRead", () => {expect(posts).toHaveLength(3)const paths = posts.map((c) => c[0] as string).sort()expect(paths).toEqual([- "/api/community/inbox/dms/read-all",- "/api/community/inbox/mentions/read-all",- "/api/community/inbox/unreads/read-all",+ "/api/community/users/me/inbox/dms/read-all",+ "/api/community/users/me/inbox/mentions/read-all",+ "/api/community/users/me/inbox/unreads/read-all",])})diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 5422b8090..dfb322f93 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -11,6 +11,10 @@ import { apiFetch, toastApiError } from "@/lib/api/client"import { ApiError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"+import {+ projectPostedMessage,+ type PostedMessage,+} from "@/lib/community/message-wire"import { useCommunityStore } from "@/stores/community"import { useMessageStreamStore } from "@/stores/community/message-stream"import { getMessageOverlay } from "@/stores/community/message-stream"@@ -23,8 +27,7 @@ import type { Msg, Attachment } from "@/components/community/_types"import type { MessagesPage } from "@/hooks/community/use-messages"import type { PinsResponse } from "@/hooks/community/use-channel-panels"import type { MarkedResponse, MessageMarkedResponse } from "@/hooks/community/use-inbox"-import type { MentionType } from "@alook/shared"-import { isBlocked } from "@alook/shared"+import { isBlocked, type MentionType } from "@alook/shared"/*** Message-scoped mutation hooks — the split of the God-context's@@ -47,20 +50,107 @@ import { isBlocked } from "@alook/shared"type PageCache = InfiniteData<MessagesPage>+function patchContentById(cache: PageCache | undefined, id: string, content: string): PageCache | undefined {+ if (!cache) return cache+ let touched = false+ const pages = cache.pages.map((page) => ({+ ...page,+ messages: page.messages.map((message) => {+ if (message.id !== id) return message+ touched = true+ return { ...message, content }+ }),+ }))+ return touched ? { ...cache, pages } : cache+}++type EditMessageArgs = {+ serverId: string+ channelId: string+ messageId: string+ content: string+ forumChannelId?: string+}++type EditMessageContext = {+ previous: PageCache | undefined+ previousContent: string | undefined+ key: readonly unknown[]+ scope: MessageScope+ previousMessage: { content: string } | undefined+ messageKey: readonly unknown[]+}++export function useEditMessage() {+ const queryClient = useQueryClient()+ return useMutation<void, Error, EditMessageArgs, EditMessageContext>({+ mutationFn: async ({ messageId, content }) => {+ await apiFetch(`/api/community/messages/${messageId}`, {+ method: "PATCH",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ content }),+ })+ },+ onMutate: async ({ serverId, channelId, messageId, content }) => {+ const key = communityKeys.channelMessages(channelId)+ const scope: MessageScope = { kind: "channel", id: channelId, serverId }+ const messageKey = communityKeys.message(messageId)+ await Promise.all([+ queryClient.cancelQueries({ queryKey: key }),+ queryClient.cancelQueries({ queryKey: messageKey }),+ ])+ const previous = queryClient.getQueryData<PageCache>(key)+ const previousMessage = queryClient.getQueryData<{ content: string }>(messageKey)+ const previousContent = currentMaterializedMessage(previous, scope, messageId)?.content+ queryClient.setQueryData<PageCache>(key, (cache) => patchContentById(cache, messageId, content))+ queryClient.setQueryData<{ content: string }>(messageKey, (message) => message ? { ...message, content } : message)+ useMessageStreamStore.getState().dispatch(scope, {+ type: "messageEdited",+ messageId,+ content,+ })+ return { previous, previousContent, key, scope, previousMessage, messageKey }+ },+ onError: (_error, _variables, context) => {+ if (!context) return+ queryClient.setQueryData(context.key, context.previous)+ if (context.previousContent !== undefined) {+ useMessageStreamStore.getState().dispatch(context.scope, {+ type: "messageEdited",+ messageId: _variables.messageId,+ content: context.previousContent,+ })+ }+ queryClient.setQueryData(context.messageKey, context.previousMessage)+ },+ onSuccess: (_data, variables) => {+ if (variables.forumChannelId) void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(variables.forumChannelId) })+ },+ })+}+/*** Materialize the attachment view-model from the API attachment shape.* Mirrors the old context's conversion at `postWithOptimisticInsert`.* Exported for direct unit testing — see `to-attachment-vm.test.ts`.*/export function toAttachmentVm(- a: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number },+ channelId: string,+ a: { id: string; filename: string; contentType: string; size: number; width?: number; height?: number },): Attachment {+ // Reserve-by-id (route/disc step 2b): the server no longer returns a `url` for+ // a fresh upload — it returns the attachment `id`. The display URL is+ // id-addressed (the canonical `channels/{id}/attachments/{attachmentId}` door)+ // and derived HERE client-side, matching what the server's read path emits via+ // `attachmentUrl`. This keeps the optimistic row's image src identical to the+ // reconciled row that arrives over WS.+ const url = `/api/community/channels/${channelId}/attachments/${a.id}`const isImage = isInlineAttachmentContentType(a.contentType)- if (isImage) return { kind: "image", name: a.filename, url: a.url, width: a.width, height: a.height }+ if (isImage) return { kind: "image", name: a.filename, url, width: a.width, height: a.height }return {kind: "file",name: a.filename,- url: a.url,+ url,size: a.size ? `${Math.round(a.size / 1024)} KB` : "",}}@@ -89,8 +179,13 @@ export type SendMessageArgs = {channelId: stringcontent: stringreplyToId?: string+ replyTo?: Msg["replyTo"]mentionType?: MentionType- attachments?: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]+ // Reserve-by-id: pre-uploaded pending-attachment descriptors. Only `id` is+ // sent to the server (in an id array); the rest drive the optimistic VM+ // (whose url is derived client-side from `id`). No `url` field — the upload+ // no longer returns one.+ attachments?: { id: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]author: { id: string; name: string; avatar: string }// Idempotency nonce. Omitted on a fresh send (the hook mints one); the// retry-pill caller passes the failed row's nonce back so the resend reuses@@ -102,7 +197,7 @@ export type SendMessageArgs = {// the same nonce — `message` is the canonical (original) row, nothing new was// inserted. The caller treats it as success (reconcile the optimistic row,// clear the failed pill), never as a failure to resend.-export type SendMessageResult = { message: { id: string; seq: number }; deduped?: boolean }+export type SendMessageResult = { message: PostedMessage; deduped?: boolean }/*** Channel/thread send. The server infers thread-vs-channel routing from the@@ -115,12 +210,22 @@ export function useSendMessage() {Error,SendMessageArgs>({- mutationFn: async ({ channelId, content, replyToId, mentionType, attachments, nonce }) => {+ mutationFn: async ({ channelId, content, replyToId, replyTo, mentionType, attachments, nonce }) => {+ // Server receives only the attachment IDS (reserve-by-id); the rest of the+ // descriptor is client-only (optimistic VM). Dimensions already rode the+ // upload, so they are NOT re-sent here (single-source guard).+ const attachmentIds = attachments?.map((a) => a.id)return apiFetch<SendMessageResult>(`/api/community/channels/${channelId}/messages`,{method: "POST",- body: JSON.stringify({ content, replyToId, mentionType, attachments, nonce }),+ body: JSON.stringify({+ content,+ replyToId: replyTo?.id ?? replyToId,+ mentionType,+ attachments: attachmentIds,+ nonce,+ }),},)},@@ -152,8 +257,7 @@ export function useSendMessage() {{type: "postAck",nonce: args.nonce,- serverMessageId: data.message.id,- serverSeq: data.message.seq,+ message: projectPostedMessage(data.message, args.nonce),},)},@@ -166,7 +270,10 @@ export type SendDmMessageArgs = {dmId: stringcontent: stringreplyToId?: string- attachments?: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]+ replyTo?: Msg["replyTo"]+ // Reserve-by-id (see SendMessageArgs.attachments): id-bearing descriptors;+ // only `id` reaches the server.+ attachments?: { id: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]nonce: string}@@ -176,12 +283,18 @@ export function useSendDmMessage() {Error,SendDmMessageArgs>({- mutationFn: async ({ dmId, content, replyToId, attachments, nonce }) => {+ mutationFn: async ({ dmId, content, replyToId, replyTo, attachments, nonce }) => {+ const attachmentIds = attachments?.map((a) => a.id)return apiFetch<SendMessageResult>(- `/api/community/dm/${dmId}/messages`,+ `/api/community/channels/${dmId}/messages`,{method: "POST",- body: JSON.stringify({ content, replyToId, attachments, nonce }),+ body: JSON.stringify({+ content,+ replyToId: replyTo?.id ?? replyToId,+ attachments: attachmentIds,+ nonce,+ }),},)},@@ -211,8 +324,7 @@ export function useSendDmMessage() {{type: "postAck",nonce: args.nonce,- serverMessageId: data.message.id,- serverSeq: data.message.seq,+ message: projectPostedMessage(data.message, args.nonce),},)},@@ -469,7 +581,7 @@ export function useUnpinMessage() {//// mark ≠ pin: a pin is channel-scoped and shared; a mark is the viewer's own// private saved-messages set. So these hit a distinct per-user route-// (`/api/community/marks`, self-scoped by ctx.userId server-side), never the+// (`/api/community/messages/{id}/marks`, self-scoped by ctx.userId server-side), never the// pins route. The ⋯ menu's Mark/Unmark label is driven by `useMessageMarked`// (a lazy single-row read on menu-open); these mutations flip that per-message// cache optimistically so the label updates instantly, and prune the Marked@@ -481,9 +593,11 @@ export function useMarkMessage() {const queryClient = useQueryClient()return useMutation<void, Error, MarkMessageArgs, { prev: MessageMarkedResponse | undefined }>({mutationFn: async ({ channelId, messageId }) => {- await apiFetch(`/api/community/marks`, {- method: "POST",- body: JSON.stringify({ channelId, messageId }),+ // Message-keyed mark door (route/disc marks relocation): messageId in path,+ // channelId in body (the membership + belongs-to-channel gate). PUT = mark.+ await apiFetch(`/api/community/messages/${messageId}/marks`, {+ method: "PUT",+ body: JSON.stringify({ channelId }),})},onMutate: async ({ messageId }) => {@@ -515,7 +629,7 @@ export function useUnmarkMessage() {prevList: MarkedResponse | undefined}>({mutationFn: async ({ messageId }) => {- await apiFetch(`/api/community/marks/${messageId}`, { method: "DELETE" })+ await apiFetch(`/api/community/messages/${messageId}/marks`, { method: "DELETE" })},onMutate: async ({ messageId }) => {const markedKey = communityKeys.messageMarked(messageId)@@ -581,9 +695,11 @@ export function useCreateThread() {const queryClient = useQueryClient()return useMutation<CreateThreadResult, Error, CreateThreadArgs>({mutationFn: async ({ messageId, name }) => {+ // Unified create door (route/disc create-door step): POST /channels with+ // {type:"thread", messageId, name} → get-or-create thread by root message.return apiFetch<CreateThreadResult>(- `/api/community/messages/${messageId}/threads`,- { method: "POST", body: JSON.stringify({ name }) },+ `/api/community/channels`,+ { method: "POST", body: JSON.stringify({ type: "thread", messageId, name }) },)},onSuccess: (data, args) => {@@ -704,11 +820,11 @@ export type ScheduleMarkReadOpts = {* unique strings without a discriminated-union tag on `PendingRead`.*/function resolveReadEndpoint(key: string): string {- if (key.startsWith("dm:")) {- const dmId = key.slice(3)- return `/api/community/dm/${dmId}/read`- }- return `/api/community/channels/${key}/read`+ // DM and channel both resolve through the one canonical read door (a DM is a+ // channel row in the same id-space); the `dm:` key prefix only strips to the+ // channelId, no per-type URL fork.+ const channelId = key.startsWith("dm:") ? key.slice(3) : key+ return `/api/community/channels/${channelId}/read`}/**@@ -857,11 +973,46 @@ export function useAdvanceChannelWatermark(): (}}+// ── Read a forum opener from Inbox ──────────────────────────────────────++export type ReadForumThreadFromInboxArgs = {+ parentChannelId: string+ openerMessageId: string+}++/**+ * Immediate progressive read used only by an opener-backed Inbox row.+ *+ * Unlike viewport watermarks this is not debounced: the click starts the+ * parent read and navigation immediately. There is deliberately no onMutate+ * cache trim. Success refreshes Inbox/server aggregates; failure keeps the+ * unread row and only reports the error.+ */+export function useReadForumThreadFromInbox() {+ const queryClient = useQueryClient()+ return useMutation<void, Error, ReadForumThreadFromInboxArgs>({+ mutationFn: async ({ parentChannelId, openerMessageId }) => {+ await apiFetch(`/api/community/channels/${parentChannelId}/read`, {+ method: "PUT",+ body: JSON.stringify({ lastReadMessageId: openerMessageId }),+ })+ },+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })+ },+ onError: (error) => {+ toastApiError(error, "Failed to mark forum post read")+ },+ })+}+// ── Advance DM watermark (progressive read) ───────────────────────────────/*** DM sibling of `useAdvanceChannelWatermark` — a thin wrapper that PUTs- * `{ lastReadMessageId }` to `/api/community/dm/:id/read`. Same debounce+ * `{ lastReadMessageId }` to `/api/community/channels/:id/read` (DM and+ * channel share the one canonical read door). Same debounce* primitive underneath (`scheduleMarkRead`), keyed by `"dm:<dmId>"` so* DM and channel schedules never alias each other in the shared pending* map.@@ -895,7 +1046,7 @@ export function useMarkDmRead() {const queryClient = useQueryClient()return useMutation<void, Error, MarkDmReadArgs, { snapshot: unknown } | undefined>({mutationFn: async ({ dmId }) => {- await apiFetch(`/api/community/dm/${dmId}/read`, { method: "PUT" })+ await apiFetch(`/api/community/channels/${dmId}/read`, { method: "PUT" })},onMutate: async (args) => {const key = communityKeys.dms()@@ -920,9 +1071,9 @@ export function useMarkAllInboxRead() {return useMutation<void, Error, void>({mutationFn: async () => {await Promise.all([- apiFetch("/api/community/inbox/mentions/read-all", { method: "POST" }),- apiFetch("/api/community/inbox/unreads/read-all", { method: "POST" }),- apiFetch("/api/community/inbox/dms/read-all", { method: "POST" }),+ apiFetch("/api/community/users/me/inbox/mentions/read-all", { method: "POST" }),+ apiFetch("/api/community/users/me/inbox/unreads/read-all", { method: "POST" }),+ apiFetch("/api/community/users/me/inbox/dms/read-all", { method: "POST" }),])},onMutate: async () => {@@ -954,7 +1105,7 @@ export function useDeleteMention() {const queryClient = useQueryClient()return useMutation<void, Error, DeleteMentionArgs, { snapshot: unknown }>({mutationFn: async ({ mentionId }) => {- await apiFetch(`/api/community/inbox/mentions/${mentionId}`, { method: "DELETE" })+ await apiFetch(`/api/community/users/me/inbox/mentions/${mentionId}`, { method: "DELETE" })},onMutate: async (args) => {const key = communityKeys.inboxMentions()diff --git a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts b/src/web/src/hooks/community/mutations/to-attachment-vm.test.tsindex 322316ff6..3a2862607 100644--- a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts+++ b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts@@ -1,56 +1,75 @@import { describe, it, expect } from "vitest"import { toAttachmentVm } from "./messages"-// `toAttachmentVm` materializes the optimistic-send attachment view model-// from the uploaded-attachment shape. Its image branch must carry-// width/height through — this is one of the silent-drop sites flagged in-// plans/attachment-image-dimensions.md's plan review (an object literal-// omitting an optional field produces no typecheck error).+// `toAttachmentVm` materializes the optimistic-send attachment view model from+// the uploaded-attachment shape. Reserve-by-id (route/disc step 2b): the input+// carries the pending-row `id` (no server url), and the display url is derived+// CLIENT-side from (channelId, id) — matching the id-addressed+// `channels/{id}/attachments/{attachmentId}` door the server read path emits.+// The image branch must carry width/height through — a silent-drop site flagged+// in plans/attachment-image-dimensions.md's plan review.describe("toAttachmentVm", () => {- it("carries width/height through on an image attachment", () => {- const result = toAttachmentVm({- url: "/media/a.png",+ it("carries width/height through on an image attachment + derives the id-addressed url", () => {+ const result = toAttachmentVm("c1", {+ id: "att_1",filename: "a.png",contentType: "image/png",size: 1000,width: 1920,height: 1080,})- expect(result).toEqual({ kind: "image", name: "a.png", url: "/media/a.png", width: 1920, height: 1080 })+ expect(result).toEqual({+ kind: "image",+ name: "a.png",+ url: "/api/community/channels/c1/attachments/att_1",+ width: 1920,+ height: 1080,+ })})it("leaves width/height undefined for an image attachment with no dimensions on file", () => {- const result = toAttachmentVm({- url: "/media/a.png",+ const result = toAttachmentVm("c1", {+ id: "att_1",filename: "a.png",contentType: "image/png",size: 1000,})- expect(result).toEqual({ kind: "image", name: "a.png", url: "/media/a.png", width: undefined, height: undefined })+ expect(result).toEqual({+ kind: "image",+ name: "a.png",+ url: "/api/community/channels/c1/attachments/att_1",+ width: undefined,+ height: undefined,+ })})it("never adds width/height to a file-kind attachment", () => {- const result = toAttachmentVm({- url: "/media/a.pdf",+ const result = toAttachmentVm("c1", {+ id: "att_2",filename: "a.pdf",contentType: "application/pdf",size: 2048,})- expect(result).toEqual({ kind: "file", name: "a.pdf", url: "/media/a.pdf", size: "2 KB" })+ expect(result).toEqual({+ kind: "file",+ name: "a.pdf",+ url: "/api/community/channels/c1/attachments/att_2",+ size: "2 KB",+ })})it.each(["image/svg+xml", "image/x-forged"])("materializes unsafe %s attachments as file-kind",(contentType) => {- const result = toAttachmentVm({- url: "/media/unsafe.img",+ const result = toAttachmentVm("c1", {+ id: "att_3",filename: "unsafe.img",contentType,size: 2048,width: 1920,height: 1080,})- expect(result).toEqual({ kind: "file", name: "unsafe.img", url: "/media/unsafe.img", size: "2 KB" })+ expect(result).toEqual({ kind: "file", name: "unsafe.img", url: "/api/community/channels/c1/attachments/att_3", size: "2 KB" })},)})diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.tsindex c2a86d745..7be09cd7c 100644--- a/src/web/src/hooks/community/mutations/uploads.ts+++ b/src/web/src/hooks/community/mutations/uploads.ts@@ -16,13 +16,21 @@ export type UploadTarget = {threadId?: string}-export type UploadFileArgs = { target: UploadTarget; file: File }+export type UploadFileArgs = { target: UploadTarget; file: File; width?: number; height?: number }+// Reserve-by-id (route/disc step 2b): the upload now creates a PENDING+// attachment row and returns its stable `id` (mirroring the bot flow). The+// composer holds the id in-memory and passes it to `send`; the server links it+// via reserve. The old `url` field is gone — the display URL is id-addressed+// and derived client-side (see `toAttachmentVm`). Image dimensions ride the+// UPLOAD request (single source) and echo back here for the optimistic VM.export type UploadFileResult = {- url: string+ id: stringfilename: stringcontentType: stringsize: number+ width?: number+ height?: number}export type UploadedAttachment = UploadFileResult & { width?: number; height?: number }@@ -52,19 +60,27 @@ export function zipUploadResultsWithDimensions(}function uploadPath(target: UploadTarget): string | null {- if (target.threadId) return `/api/community/threads/${target.threadId}/upload`- if (target.dmId) return `/api/community/dm/${target.dmId}/upload`- if (target.channelId) return `/api/community/channels/${target.channelId}/upload`- return null+ // Thread / DM / channel are all channel rows in one id-space → one upload+ // door. Whichever id the target carries, it's a channelId to channels/{id}.+ // Canonical attachments door (route/disc trunk): POST channels/{id}/attachments+ // (re-pointed off the old channels/{id}/upload, which stays alive through the+ // deploy window and is deleted at the flat-delete step). Response shape is+ // unchanged — the human arm still returns the `{ url, filename, ... }` carrier.+ const id = target.threadId ?? target.dmId ?? target.channelId+ return id ? `/api/community/channels/${id}/attachments` : null}export function useUploadFile() {return useMutation<UploadFileResult, Error, UploadFileArgs>({- mutationFn: async ({ target, file }) => {+ mutationFn: async ({ target, file, width, height }) => {const path = uploadPath(target)if (!path) throw new Error("Upload target requires channelId, dmId, or threadId")const formData = new FormData()formData.append("file", file)+ // Image dimensions ride the upload body (single source — written onto the+ // pending row server-side; never re-sent on the message `send`).+ if (width !== undefined) formData.append("width", String(width))+ if (height !== undefined) formData.append("height", String(height))const res = await fetch(path, {method: "POST",body: formData,diff --git a/src/web/src/hooks/community/use-channel-bootstrap.test.ts b/src/web/src/hooks/community/use-channel-bootstrap.test.tsdeleted file mode 100644index fbf06c386..000000000--- a/src/web/src/hooks/community/use-channel-bootstrap.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { describe, it, expect } from "vitest"-import { buildMessagesSeed } from "./use-channel-bootstrap"--// The seed shape is load-bearing: useMessages' getNext/PreviousPageParam and-// anchor-revalidation read `pageParams`, and WS inserts patch `pages[0]` using-// the anchor-mode envelope. A wrong shape silently breaks pagination / live-// updates. See plans/community-switch-perf-optimization.md WS2.--function resp(over: Record<string, unknown> = {}) {- return {- readState: { lastReadMessageId: "m_10", lastReadAt: "t", lastReadSeq: 10 },- anchorMode: "anchor" as const,- anchorMessageId: "m_10",- messages: [{ id: "m_10", type: "chat" as const }],- latestSeq: 20,- hasMoreOlder: true,- hasMoreNewer: true,- olderCursor: "oc",- newerCursor: "nc",- ...over,- } as Parameters<typeof buildMessagesSeed>[0]-}--describe("buildMessagesSeed", () => {- it("seeds a single page with the mandatory anchor pageParam", () => {- const seed = buildMessagesSeed(resp())- expect(seed.pages).toHaveLength(1)- expect(seed.pageParams).toEqual([{ mode: "anchor", anchor: "m_10" }])- })-- it("carries the anchor-mode envelope (hasMoreOlder/Newer + cursors) for WS-patch compat", () => {- const seed = buildMessagesSeed(resp())- const page = seed.pages[0]- expect(page.hasMoreOlder).toBe(true)- expect(page.hasMoreNewer).toBe(true)- expect(page.olderCursor).toBe("oc")- expect(page.newerCursor).toBe("nc")- expect(page.latestSeq).toBe(20)- // Never the legacy `hasMore` field — that would misroute getNextPageParam.- expect(page.hasMore).toBeUndefined()- })-- it("uses a newest pageParam when the server fell back (deleted/absent anchor)", () => {- const seed = buildMessagesSeed(resp({ anchorMode: "newest", anchorMessageId: null }))- expect(seed.pageParams).toEqual([{ mode: "newest" }])- })-- it("uses newest when anchorMode is anchor but the id is missing (defensive)", () => {- const seed = buildMessagesSeed(resp({ anchorMode: "anchor", anchorMessageId: null }))- expect(seed.pageParams).toEqual([{ mode: "newest" }])- })-})diff --git a/src/web/src/hooks/community/use-channel-bootstrap.ts b/src/web/src/hooks/community/use-channel-bootstrap.tsdeleted file mode 100644index c6f83f9e9..000000000--- a/src/web/src/hooks/community/use-channel-bootstrap.ts+++ /dev/null@@ -1,122 +0,0 @@-"use client"--import { useEffect, useRef, useState } from "react"-import { useQuery, useQueryClient, type InfiniteData } from "@tanstack/react-query"-import { apiFetch } from "@/lib/api/client"-import { communityKeys } from "@/lib/query-keys"-import type { ChannelReadStateSnapshot } from "./use-channel-read-state"-import type { MessagesPage, MessagesPageParam } from "./use-messages"--// Response of GET /api/community/channels/:id/bootstrap — the read pointer plus-// the initial (anchor-centered or newest) message window, in one round-trip.-// See plans/community-switch-perf-optimization.md (WS2).-type ChannelBootstrapResponse = {- readState: ChannelReadStateSnapshot- anchorMode: "anchor" | "newest"- anchorMessageId: string | null-} & MessagesPage--/**- * Build the `InfiniteData` seed for `channelMessages(id)` from a bootstrap- * response. Pure + exported so the seed shape (mandatory `pageParams`, anchor- * vs newest mode, anchor-mode envelope) is unit-tested without a render loop.- */-export function buildMessagesSeed(- data: ChannelBootstrapResponse,-): InfiniteData<MessagesPage, MessagesPageParam> {- const page: MessagesPage = {- messages: data.messages as MessagesPage["messages"],- latestSeq: data.latestSeq,- hasMoreOlder: data.hasMoreOlder,- hasMoreNewer: data.hasMoreNewer,- olderCursor: data.olderCursor,- newerCursor: data.newerCursor,- }- const pageParam: MessagesPageParam =- data.anchorMode === "anchor" && data.anchorMessageId- ? { mode: "anchor", anchor: data.anchorMessageId }- : { mode: "newest" }- return { pages: [page], pageParams: [pageParam] }-}--/**- * De-serialized channel open. Replaces the read-state → gated messages serial- * chain on the INITIAL window: one request seeds both the read-state snapshot- * cache and the `channelMessages` infinite-query cache, so `useMessages` can- * paginate + WS-patch from the seed without a second round-trip.- *- * Skipped when `jumpTargetId` is set — a jump-open must anchor on the jump- * target, not the read pointer, and the seed-then-trust mechanism would- * otherwise override it (the page keeps the legacy read-state + ?anchor=jump- * path in that case).- *- * Freeze-once: the returned `readState` latches the first resolved value for- * the mount (like `useChannelReadStateSnapshot`'s `snapshotRef`), so a refetch- * returning an advanced pointer never walks the "New" divider down the list.- */-export function useChannelBootstrap(- channelId: string | null | undefined,- opts?: { enabled?: boolean },-): {- readState: ChannelReadStateSnapshot | null- isFetching: boolean- isReady: boolean-} {- const queryClient = useQueryClient()- const enabled = !!channelId && (opts?.enabled ?? true)-- const query = useQuery<ChannelBootstrapResponse>({- queryKey: channelId- ? communityKeys.channelBootstrap(channelId)- : ["community", "channel", "__none__", "bootstrap"],- queryFn: async () => {- const data = await apiFetch<ChannelBootstrapResponse>(- `/api/community/channels/${channelId}/bootstrap`,- )- // Seed the message infinite-query cache so `useMessages` mounts on a- // trusted first window instead of refetching it. The pageParams entry is- // mandatory: getNextPageParam/getPreviousPageParam + anchor-revalidation- // read it. Newest fallback seeds a `{ mode: "newest" }` param.- queryClient.setQueryData(communityKeys.channelMessages(channelId!), buildMessagesSeed(data))- // Seed the read-state snapshot cache too, so any consumer of that key- // reads the same pointer without its own network fetch.- queryClient.setQueryData(- communityKeys.channelReadStateSnapshot(channelId!),- data.readState,- )- return data- },- enabled,- staleTime: Infinity,- gcTime: 0,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- retry: 1,- })-- // Freeze the first resolved read pointer for the mount (see hook doc).- const readRef = useRef<ChannelReadStateSnapshot | null>(null)- const lastChannelIdRef = useRef<string | null | undefined>(channelId)- /* eslint-disable react-hooks/refs -- sync channel-switch reset, mirrors use-channel-read-state */- if (lastChannelIdRef.current !== channelId) {- readRef.current = null- lastChannelIdRef.current = channelId- }- /* eslint-enable react-hooks/refs */- const [, force] = useState(0)- useEffect(() => {- if (readRef.current !== null) return- if (query.data?.readState) {- readRef.current = query.data.readState- force((n) => n + 1)- }- }, [query.data])-- /* eslint-disable react-hooks/refs -- latched read pointer */- return {- readState: readRef.current ?? query.data?.readState ?? null,- isFetching: query.isFetching,- isReady: query.isSuccess,- }- /* eslint-enable react-hooks/refs */-}diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsindex a76f65178..716d20374 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -5,6 +5,7 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { CommunityRole } from "@alook/shared"import type { CommunityUserCore } from "@/components/community/_types"+import { fetchAllServerMembers } from "./fetch-all-server-members"// Canonical member shape (superset of the pre-audience roster). `source` tags// why the user is in the channel: "explicit" (added member or creator),@@ -35,6 +36,24 @@ export type AddableMember = {const EMPTY_MEMBERS: readonly ChannelMember[] = Object.freeze([])const EMPTY_ADDABLE: readonly AddableMember[] = Object.freeze([])+export async function addableMembersQueryFn(serverId: string, channelId: string): Promise<{ members: AddableMember[] }> {+ const [serverMembers, channelData] = await Promise.all([+ fetchAllServerMembers(serverId),+ apiFetch<{ members: ChannelMember[] }>(`/api/community/channels/${encodeURIComponent(channelId)}/members`),+ ])+ const present = new Set(channelData.members.map((member) => member.userId))+ return {+ members: serverMembers+ .filter((member) => !present.has(member.userId))+ .map((member) => ({+ userId: member.userId,+ name: member.name,+ discriminator: member.discriminator,+ avatar: member.avatar,+ })),+ }+}+/** Current roster of a private-category channel. */export function useChannelMembers(channelId: string,@@ -53,16 +72,14 @@ export function useChannelMembers(/** Server members not yet in the channel — the add picker. */export function useAddableMembers(+ serverId: string,channelId: string,enabled = true,): UseQueryResult<{ members: AddableMember[] }> & { members: AddableMember[] } {const query = useQuery({queryKey: communityKeys.channelAddableMembers(channelId),- queryFn: () =>- apiFetch<{ members: AddableMember[] }>(- `/api/community/channels/${encodeURIComponent(channelId)}/addable-members`,- ),- enabled: enabled && !!channelId,+ queryFn: () => addableMembersQueryFn(serverId, channelId),+ enabled: enabled && !!serverId && !!channelId,})return { ...query, members: query.data?.members ?? (EMPTY_ADDABLE as AddableMember[]) }}diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.tsnew file mode 100644index 000000000..233b25126--- /dev/null+++ b/src/web/src/hooks/community/use-channel-message-feed.ts@@ -0,0 +1,81 @@+"use client"++import { useMemo, useState } from "react"+import { useChannelReadStateSnapshot } from "./use-channel-read-state"+import { useChannelWatermark } from "./use-channel-watermark"+import { useEagerChannelRead } from "./use-eager-channel-read"+import { useMessages } from "./use-messages"+import { usePins, useThreads } from "./use-channel-panels"++export function useChannelMessageFeed({+ channelId,+ serverId,+ viewerUserId,+ isChildChannel,+ anchorMessageId,+}: {+ channelId: string | null+ serverId: string+ viewerUserId: string+ isChildChannel: boolean+ anchorMessageId: string | null+}) {+ const readState = useChannelReadStateSnapshot(channelId)+ const readSnapshot = readState.snapshot+ const messagesQuery = useMessages(channelId, {+ serverId,+ lastReadMessageId: readState.isFetching+ ? undefined+ : (readSnapshot?.lastReadMessageId ?? null),+ anchorMessageId,+ })+ const { newDividerBefore, anchorFound } = useMemo(() => {+ if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }+ const lastId = readSnapshot.lastReadMessageId+ if (!lastId) {+ for (const message of messagesQuery.messages) {+ if (message.authorId !== viewerUserId) {+ return { newDividerBefore: message.id, anchorFound: true }+ }+ }+ return { newDividerBefore: undefined, anchorFound: true }+ }+ const index = messagesQuery.messages.findIndex((message) => message.id === lastId)+ if (index === -1) return { newDividerBefore: undefined, anchorFound: false }+ for (let i = index + 1; i < messagesQuery.messages.length; i++) {+ if (messagesQuery.messages[i].authorId !== viewerUserId) {+ return { newDividerBefore: messagesQuery.messages[i].id, anchorFound: true }+ }+ }+ return { newDividerBefore: undefined, anchorFound: true }+ }, [messagesQuery.messages, readSnapshot, viewerUserId])+ const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)+ useChannelWatermark({ channelId, messages: messagesQuery.messages, scrollRootEl })+ useEagerChannelRead({+ channelId,+ serverId,+ isChildChannel,+ snapshotReady: !readState.isFetching,+ })+ const unreadCount = useMemo(() => {+ const difference = messagesQuery.latestSeq - (readSnapshot?.lastReadSeq ?? 0)+ return Math.max(0, difference)+ }, [messagesQuery.latestSeq, readSnapshot])+ const threadsQuery = useThreads(channelId)+ const pinsQuery = usePins(channelId)++ return {+ ...messagesQuery,+ readSnapshot,+ readSnapshotFetching: readState.isFetching,+ newDividerBefore,+ anchorInCache: anchorFound,+ unreadCount,+ scrollRootEl,+ setScrollRootEl,+ threads: threadsQuery.threads,+ threadsLoading: threadsQuery.isLoading,+ pinned: pinsQuery.pins,+ pinnedLoading: pinsQuery.isLoading,+ }+}diff --git a/src/web/src/hooks/community/use-channel-panels.test.ts b/src/web/src/hooks/community/use-channel-panels.test.tsindex dd8d6392a..6e448bb18 100644--- a/src/web/src/hooks/community/use-channel-panels.test.ts+++ b/src/web/src/hooks/community/use-channel-panels.test.ts@@ -13,15 +13,23 @@ beforeEach(() => {describe("useThreads / threadsQueryFn", () => {it("fetches from /channels/:id/threads and returns { threads }", async () => {- apiFetchMock.mockResolvedValueOnce({ threads: [{ id: "t_1" }] })+ apiFetchMock+ .mockResolvedValueOnce({ threads: [{ id: "t_1", name: "t", type: "thread", creatorId: "u1", parentMessageId: "m1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })+ .mockResolvedValueOnce({ messages: [{ id: "m1", channelId: "ch_1", content: "root", seq: 1, authorId: "u1", authorName: "A", authorImage: null }], firstMessages: [] })+ .mockResolvedValueOnce({ tags: [] })+ .mockResolvedValueOnce({ participants: [] })const { threadsQueryFn } = await import("./use-channel-panels")const data = await threadsQueryFn("ch_1")()expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/threads")+ expect(apiFetchMock).not.toHaveBeenCalledWith("/api/community/channels/ch_1/posts")expect(data.threads).toHaveLength(1)})it("populates queryClient at communityKeys.threads(channelId)", async () => {apiFetchMock.mockResolvedValueOnce({ threads: [] })+ .mockResolvedValueOnce({ messages: [], firstMessages: [] })+ .mockResolvedValueOnce({ tags: [] })+ .mockResolvedValueOnce({ participants: [] })const { threadsQueryFn } = await import("./use-channel-panels")const qc = new QueryClient()const key = communityKeys.threads("ch_1")@@ -30,25 +38,6 @@ describe("useThreads / threadsQueryFn", () => {})})-describe("useForumPosts / forumPostsQueryFn", () => {- it("fetches from /channels/:id/posts and returns { posts }", async () => {- apiFetchMock.mockResolvedValueOnce({ posts: [{ id: "p_1" }] })- const { forumPostsQueryFn } = await import("./use-channel-panels")- const data = await forumPostsQueryFn("ch_1")()- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/posts")- expect(data.posts).toHaveLength(1)- })-- it("populates queryClient at communityKeys.forumPosts(channelId)", async () => {- apiFetchMock.mockResolvedValueOnce({ posts: [] })- const { forumPostsQueryFn } = await import("./use-channel-panels")- const qc = new QueryClient()- const key = communityKeys.forumPosts("ch_1")- await qc.fetchQuery({ queryKey: key, queryFn: forumPostsQueryFn("ch_1") })- expect(qc.getQueryData(key)).toEqual({ posts: [] })- })-})-describe("usePins / pinsQueryFn", () => {it("fetches from /channels/:id/pins and returns { pins }", async () => {apiFetchMock.mockResolvedValueOnce({ pins: [{ id: "m_1" }] })diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.tsindex 1d469973b..8bd4340de 100644--- a/src/web/src/hooks/community/use-channel-panels.ts+++ b/src/web/src/hooks/community/use-channel-panels.ts@@ -3,11 +3,10 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { Thread, ForumPost, Msg } from "@/components/community/_types"+import type { Thread, Msg } from "@/components/community/_types"// Frozen empty fallbacks — see `use-servers.ts` for the rationale.const EMPTY_THREADS: readonly Thread[] = Object.freeze([])-const EMPTY_FORUM_POSTS: readonly ForumPost[] = Object.freeze([])const EMPTY_PINS: readonly Msg[] = Object.freeze([])/**@@ -21,8 +20,68 @@ const EMPTY_PINS: readonly Msg[] = Object.freeze([])*/export type ThreadsResponse = { threads: Thread[] }-export const threadsQueryFn = (channelId: string) => () =>- apiFetch<ThreadsResponse>(`/api/community/channels/${channelId}/threads`)+type RawThread = {+ id: string+ name: string+ type: string+ creatorId: string | null+ parentMessageId: string | null+ messageCount: number | null+ lastMessageAt: string | null+ createdAt: string+}+type BatchMessage = {+ id: string+ channelId: string+ content: string+ seq: number+ authorId: string+ authorName: string+ authorImage: string | null+}+type ParticipantRow = { channelId: string; userId: string; userName: string | null; userImage: string | null; addedAt: string; participantCount?: number }++async function loadThreadResources(channelId: string, tag?: string | null) {+ const query = tag ? `?tag=${encodeURIComponent(tag)}` : ""+ const { threads } = await apiFetch<{ threads: RawThread[] }>(`/api/community/channels/${channelId}/threads${query}`)+ const openerIds = threads.map((thread) => thread.parentMessageId).filter((id): id is string => !!id)+ const threadIds = threads.map((thread) => thread.id)+ const [messageBatch, tagBatch, participantBatch] = await Promise.all([+ apiFetch<{ messages: BatchMessage[]; firstMessages: BatchMessage[] }>("/api/community/messages/batch", {+ method: "POST",+ body: JSON.stringify({ channelId, ids: openerIds, firstInChannelIds: threadIds }),+ }),+ apiFetch<{ tags: { messageId: string; tag: string }[] }>("/api/community/messages/tags/batch", {+ method: "POST",+ body: JSON.stringify({ channelId, messageIds: openerIds }),+ }),+ apiFetch<{ participants: ParticipantRow[] }>("/api/community/channels/participants/batch", {+ method: "POST",+ body: JSON.stringify({ parentChannelId: channelId, channelIds: threadIds }),+ }),+ ])+ return { threads, openerIds, ...messageBatch, ...tagBatch, ...participantBatch }+}++export const threadsQueryFn = (channelId: string) => async () => {+ const data = await loadThreadResources(channelId)+ const openerMap = new Map(data.messages.map((message) => [message.id, message]))+ const firstMap = new Map(data.firstMessages.map((message) => [message.channelId, message]))+ return {+ threads: data.threads.map((thread): Thread => {+ const opener = thread.parentMessageId ? openerMap.get(thread.parentMessageId) : undefined+ const first = firstMap.get(thread.id)+ return {+ id: thread.id,+ name: thread.name,+ messageCount: thread.messageCount ?? 0,+ lastMessageAt: thread.lastMessageAt ?? thread.createdAt,+ parent: { authorName: opener?.authorName ?? "", text: (opener?.content ?? first?.content ?? "").slice(0, 100) },+ ...(opener ? { parentSeq: opener.seq } : {}),+ }+ }),+ }+}export function useThreads(channelId: string | null): UseQueryResult<ThreadsResponse> & {threads: Thread[]@@ -39,37 +98,12 @@ export function useThreads(channelId: string | null): UseQueryResult<ThreadsResp}}-/**- * Fetches the forum-post listing for a `type='forum'` channel. Server-side- * resolves creator + first-message + counts; the payload is display-ready.- */-export type ForumPostsResponse = { posts: ForumPost[] }--export const forumPostsQueryFn = (channelId: string) => () =>- apiFetch<ForumPostsResponse>(`/api/community/channels/${channelId}/posts`)--/**- * Fetches forum posts. Only enabled when the channel is a `forum` — otherwise- * the server returns 400 "channel is not a forum" and TanStack Query would- * retry it. Callers must pass the channel's type gate; passing `false` (or a- * null channelId) leaves the query disabled and no request fires.- */-export function useForumPosts(- channelId: string | null,- isForum: boolean = true,-): UseQueryResult<ForumPostsResponse> & { posts: ForumPost[] } {- const enabled = !!channelId && isForum- const query = useQuery({- queryKey: enabled ? communityKeys.forumPosts(channelId!) : communityKeys.forumPosts("__none__"),- queryFn: enabled- ? forumPostsQueryFn(channelId!)- : (() => Promise.reject(new Error("disabled"))),- enabled,+export function useForumTags(channelId: string | null, enabled: boolean) {+ return useQuery({+ queryKey: communityKeys.forumTags(channelId ?? "__none__"),+ queryFn: () => apiFetch<{ tags: string[] }>(`/api/community/channels/${channelId}/messages/tags`),+ enabled: !!channelId && enabled,})- return {- ...query,- posts: query.data?.posts ?? (EMPTY_FORUM_POSTS as ForumPost[]),- }}/**diff --git a/src/web/src/hooks/community/use-channel-ref-directory.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.test.tsindex 0ee1a13aa..b59eccbb3 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.test.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.test.ts@@ -3,8 +3,8 @@ import { buildChannelRefDirectory } from "./use-channel-ref-directory"import type { Server, Category } from "@/components/community/_types"import type { ServerDetail } from "./use-servers"-function server(id: string, name: string): Server {- return { id, name, initial: name[0], active: false, mentions: 0 }+function server(id: string, name: string, discriminator = "0001"): Server {+ return { id, name, discriminator, initial: name[0], active: false, mentions: 0 }}function detail(id: string, name: string, categories: Category[]): ServerDetail {@@ -33,6 +33,7 @@ describe("buildChannelRefDirectory", () => {{id: "s1",name: "Studio",+ discriminator: "0001",channels: [{ id: "c1", name: "general" },{ id: "c2", name: "random" },@@ -47,8 +48,8 @@ describe("buildChannelRefDirectory", () => {const detailsById = { s1: detail("s1", "Studio", [category("cat1", [{ id: "c1", name: "general" }])]) }const directory = buildChannelRefDirectory(servers, detailsById)expect(directory).toEqual([- { id: "s1", name: "Studio", channels: [{ id: "c1", name: "general" }] },- { id: "s2", name: "Other", channels: [] },+ { id: "s1", name: "Studio", discriminator: "0001", channels: [{ id: "c1", name: "general" }] },+ { id: "s2", name: "Other", discriminator: "0001", channels: [] },])})diff --git a/src/web/src/hooks/community/use-channel-ref-directory.ts b/src/web/src/hooks/community/use-channel-ref-directory.tsindex ea271c9ba..69f174a11 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts@@ -22,7 +22,7 @@ export function buildChannelRefDirectory(return servers.map((s) => {const detail = detailsById[s.id]const channels = detail?.categories?.flatMap((c) => c.channels.map((ch) => ({ id: ch.id, name: ch.name }))) ?? []- return { id: s.id, name: s.name, channels }+ return { id: s.id, name: s.name, discriminator: s.discriminator ?? "", channels }})}diff --git a/src/web/src/hooks/community/use-channel-route-model.test.ts b/src/web/src/hooks/community/use-channel-route-model.test.tsnew file mode 100644index 000000000..21233d7ae--- /dev/null+++ b/src/web/src/hooks/community/use-channel-route-model.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest"+import { buildChannelRouteModel } from "./use-channel-route-model"++const server = {+ id: "s1",+ name: "Server",+ categories: [{+ id: "cat1",+ name: "Channels",+ private: false,+ channels: [+ { id: "text1", name: "general", type: "text" },+ { id: "forum1", name: "forum", type: "forum" },+ ],+ }],+} as never++describe("buildChannelRouteModel", () => {+ it("classifies a top-level forum without treating it as a notify unit", () => {+ const model = buildChannelRouteModel(server, null, "forum1")+ expect(model).toMatchObject({ isForum: true, isChild: false, isNotifyUnit: false, routeHydrated: true })+ })++ it("classifies a child under a forum as a forum post", () => {+ const meta = { name: "post", parentChannelId: "forum1", parentMessageId: "m1", creatorId: "u1" }+ const model = buildChannelRouteModel(server, meta, "post1", { channelId: "post1", settled: true })+ expect(model).toMatchObject({ isForum: false, isChild: true, isForumPostChild: true, isNotifyUnit: true, routeHydrated: true })+ expect(model.parent?.id).toBe("forum1")+ })++ it("keeps an unresolved child unhydrated until authoritative meta settles", () => {+ expect(buildChannelRouteModel(server, null, "missing").routeHydrated).toBe(false)+ })++ it("does not consume child A metadata while child B is unresolved", () => {+ const stale = { name: "A", parentChannelId: "forum1", parentMessageId: "m1", creatorId: "u1" }+ const model = buildChannelRouteModel(server, stale, "post-b", { channelId: "post-a", settled: true })+ expect(model.currentChannelMeta).toBeNull()+ expect(model.parent).toBeNull()+ expect(model.isForumPostChild).toBe(false)+ expect(model.metaSettled).toBe(false)+ expect(model.routeHydrated).toBe(false)+ })++ it("derives the child subtype only after that child's metadata settles", () => {+ const meta = { name: "B", parentChannelId: "forum1", parentMessageId: "m2", creatorId: "u2" }+ const model = buildChannelRouteModel(server, meta, "post-b", { channelId: "post-b", settled: true })+ expect(model.parent?.id).toBe("forum1")+ expect(model.isForumPostChild).toBe(true)+ expect(model.routeHydrated).toBe(true)+ })+})diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsnew file mode 100644index 000000000..2043bffe0--- /dev/null+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -0,0 +1,88 @@+"use client"++import { useEffect, useMemo, useState } from "react"+import { useRouter } from "next/navigation"+import { isForum as isForumType } from "@alook/shared"+import { useServer } from "./use-servers"+import { useCommunityStore, useCurrentChannelMeta } from "@/stores/community"+import { apiFetch, toastApiError } from "@/lib/api/client"+import { isDefinitiveChildMetaFailure } from "@/components/community/eject-server"+import { clearLastChannel, getLastChannel } from "@/lib/community/last-channel"+import { communityWsSubscribe, communityWsUnsubscribe } from "./use-community-ws"++type Server = ReturnType<typeof useServer>["server"]+type ChannelMeta = ReturnType<typeof useCurrentChannelMeta>++export function buildChannelRouteModel(+ server: Server,+ currentChannelMeta: ChannelMeta,+ channelId: string,+ metaState: { channelId: string; settled: boolean } | null = null,+) {+ const channels = server?.categories?.flatMap((category) => category.channels) ?? []+ const channel = channels.find((candidate) => candidate.id === channelId) ?? null+ const isChild = !channel && !!server?.categories+ const metaSettled = !isChild || (metaState?.channelId === channelId && metaState.settled)+ const channelMeta = !isChild || metaState?.channelId === channelId ? currentChannelMeta : null+ const parent = channelMeta?.parentChannelId+ ? channels.find((candidate) => candidate.id === channelMeta.parentChannelId) ?? null+ : null+ return {+ server,+ channel,+ parent,+ currentChannelMeta: channelMeta,+ isForum: isForumType(channel?.type),+ isChild,+ isForumPostChild: isChild && isForumType(parent?.type),+ isNotifyUnit: isChild,+ metaSettled,+ routeHydrated: !!server?.categories && metaSettled && (!isChild || channelMeta !== null),+ }+}++export function useChannelRouteModel(serverId: string, serverParam: string, channelId: string) {+ const router = useRouter()+ const { server } = useServer(serverId)+ const currentChannelMeta = useCurrentChannelMeta()+ const [metaState, setMetaState] = useState<{ channelId: string; settled: boolean } | null>(null)+ const model = useMemo(+ () => buildChannelRouteModel(server, currentChannelMeta, channelId, metaState),+ [channelId, currentChannelMeta, metaState, server],+ )+ useEffect(() => {+ useCommunityStore.getState().setCurrentChannelId(channelId)+ return () => { useCommunityStore.getState().setCurrentChannelId(null) }+ }, [channelId])+ useEffect(() => {+ communityWsSubscribe({ channelId })+ if (!model.isChild) {+ setMetaState({ channelId, settled: true })+ useCommunityStore.getState().setCurrentChannelMeta(null)+ return () => communityWsUnsubscribe()+ }+ setMetaState({ channelId, settled: false })+ let active = true+ apiFetch<{ name: string; parentChannelId: string | null; parentMessageId: string | null; creatorId: string | null }>(`/api/community/channels/${channelId}`)+ .then((data) => {+ if (!active) return+ useCommunityStore.getState().setCurrentChannelMeta(data)+ setMetaState({ channelId, settled: true })+ })+ .catch((error) => {+ if (!active) return+ useCommunityStore.getState().setCurrentChannelMeta(null)+ if (isDefinitiveChildMetaFailure(error)) {+ if (getLastChannel(serverId) === channelId) clearLastChannel(serverId)+ router.replace(`/c/channels/${serverParam}`)+ } else {+ toastApiError(error, "Failed to load thread")+ }+ })+ return () => {+ active = false+ communityWsUnsubscribe()+ }+ }, [channelId, model.isChild, router, serverId, serverParam])+ return model+}diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex 2612aae40..77279b444 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -10,6 +10,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient } from "@tanstack/react-query"import type {CommunityMessageCreate,+ CommunityMessageEdited,CommunityReactionAdd,CommunityMemberJoin,CommunityMemberUpdate,@@ -153,6 +154,7 @@ function messageCreate(channelId: string, msgId = "m_1"): CommunityMessageCreateauthorId: "u_author",authorName: "author",content: "hi",+ seq: 1,createdAt: "2026-07-03T00:00:00.000Z",},}@@ -186,7 +188,7 @@ describe("useCommunityWs — message.create", () => {capturedOnMessage!(messageCreate("ch_1"))- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].messages).toEqual([])@@ -212,6 +214,27 @@ describe("useCommunityWs — message.create", () => {expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(1)})+ it("keeps forum query variants base-only and stages a new opener in the overlay", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "forum_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()+ const allKey = communityKeys.channelMessages("forum_1")+ const bugKey = [...allKey, "tag", "bug"] as const+ const empty = { pages: [{ messages: [], hasMore: false }], pageParams: [null] }+ capturedQueryClient.setQueryData(allKey, empty)+ capturedQueryClient.setQueryData(bugKey, empty)++ capturedOnMessage!(messageCreate("forum_1"))++ expect(capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)+ expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)+ expect(getMessageOverlay({ kind: "channel", id: "forum_1", serverId: "s1" }).liveById).toHaveLength(1)+ })+it("does NOT patch a channel we aren't focused on", async () => {await mountHook()capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_other"), {@@ -225,13 +248,13 @@ describe("useCommunityWs — message.create", () => {expect(cache?.pages[0].messages).toEqual([])})- it("invalidates threadParticipants for the focused channel (live panel growth)", async () => {- // A thread/forum_post enrolls the sender + mentioned users as participants- // server-side; the panel must refetch so a new speaker appears without a- // manual refresh.+ it("invalidates channelMembers for a focused child channel", async () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")- useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ const store = useCommunityStore.getState()+ store.setCurrentChannelId("ch_1")+ store.setCurrentChannelMeta({ name: "thread", parentChannelId: "parent_1" })+ store.subscribe({ channelId: "ch_1" })refCounter = 0stateCounter = 0callbackCounter = 0@@ -240,17 +263,45 @@ describe("useCommunityWs — message.create", () => {const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")capturedOnMessage!(messageCreate("ch_1"))- expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })+ expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })})- it("does NOT invalidate threadParticipants for an unfocused channel", async () => {+ it("does NOT invalidate channelMembers for a focused top-level channel", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ const store = useCommunityStore.getState()+ store.setCurrentChannelId("ch_1")+ store.subscribe({ channelId: "ch_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()++ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ capturedOnMessage!(messageCreate("ch_1"))++ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })+ })++ it("does NOT invalidate channelMembers for an unfocused channel", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ const store = useCommunityStore.getState()+ store.setCurrentChannelId("ch_1")+ store.setCurrentChannelMeta({ name: "thread", parentChannelId: "parent_1" })+ store.subscribe({ channelId: "ch_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0await mountHook()+const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")capturedOnMessage!(messageCreate("ch_other"))- const calls = spy.mock.calls.filter(- (c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(communityKeys.threadParticipants("ch_other")),- )- expect(calls).toHaveLength(0)++ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_other") })+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_other") })})it("dedupes by messageId — a repeat event is a no-op", async () => {@@ -906,7 +957,7 @@ describe("useCommunityWs — member events", () => {})describe("useCommunityWs — channel.member_add/remove → invalidate rosters", () => {- it("member_add invalidates channelMembers AND threadParticipants (forum_post add-participant path)", async () => {+ it("member_add invalidates channelMembers AND threadParticipants for a child thread", async () => {await mountHook()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")capturedOnMessage!({@@ -1140,7 +1191,7 @@ describe("useCommunityWs — machines", () => {})describe("useCommunityWs — child channel events", () => {- it("child_create invalidates threads + forumPosts", async () => {+ it("child_create without a parentMessageId only invalidates threads", async () => {await mountHook()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")const event: CommunityChildChannelCreate = {@@ -1156,7 +1207,8 @@ describe("useCommunityWs — child channel events", () => {capturedOnMessage!(event)const keys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[])expect(keys.some((k) => k?.includes("threads"))).toBe(true)- expect(keys.some((k) => k?.includes("posts"))).toBe(true)+ expect(keys.some((k) => k?.includes("forum-threads"))).toBe(false)+ expect(keys).not.toContainEqual(communityKeys.channelMessages("ch_1"))})})@@ -1214,11 +1266,12 @@ describe("useCommunityWs — DM message.create", () => {authorName: "a",content: "hi",type: "chat",+ seq: 1,createdAt: "2026-07-03T00:00:00.000Z",},}capturedOnMessage!(event)- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(communityKeys.dmMessages("dm_1"),)expect(cache?.pages[0].messages).toEqual([])@@ -1275,16 +1328,15 @@ describe("useCommunityWs — non-community events bail", () => {// ── Regression #3 — channel.delete evicts channel-scoped caches ─────────describe("useCommunityWs — channel.delete evicts channel-scoped caches", () => {- it("removes channelMessages, pins, threads, and forumPosts for the deleted channel", async () => {+ it("removes channelMessages, pins, and threads for the deleted channel", async () => {await mountHook()- // Seed all four caches for the target channel so we can observe eviction.+ // Seed every canonical cache for the target channel so we can observe eviction.capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_dead"), {pages: [{ messages: [{ id: "m_1" }], hasMore: false }],pageParams: [null],})capturedQueryClient.setQueryData(communityKeys.pins("ch_dead"), { pins: [{ id: "p" }] })capturedQueryClient.setQueryData(communityKeys.threads("ch_dead"), { threads: [{ id: "t" }] })- capturedQueryClient.setQueryData(communityKeys.forumPosts("ch_dead"), { posts: [{ id: "fp" }] })const event: CommunityChannelDelete = {type: "community:channel.delete",@@ -1296,24 +1348,24 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("ch_dead"))).toBeUndefined()expect(capturedQueryClient.getQueryData(communityKeys.pins("ch_dead"))).toBeUndefined()expect(capturedQueryClient.getQueryData(communityKeys.threads("ch_dead"))).toBeUndefined()- expect(capturedQueryClient.getQueryData(communityKeys.forumPosts("ch_dead"))).toBeUndefined()})})// ── Regression #4 — child_create seeds messageCount: 0 ──────────────────describe("useCommunityWs — child_create patches parent thread badge with count 0", () => {- it("stamps messageCount: 0 on the parent message's thread stub", async () => {+ it("message.create then child_create patches the opener into a forum card", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_parent" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0await mountHook()- // Seed the parent channel's messages cache with the parent message.capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {- pages: [- {- messages: [{ id: "m_parent", content: "hello" }],- hasMore: false,- },- ],+ pages: [{ messages: [], hasMore: false }],pageParams: [null],})+ capturedOnMessage!(messageCreate("ch_parent", "m_parent"))const event: CommunityChildChannelCreate = {type: "community:channel.child_create",@@ -1331,13 +1383,64 @@ describe("useCommunityWs — child_create patches parent thread badge with countconst cache = capturedQueryClient.getQueryData<{pages: { messages: { id: string; thread?: { id: string; name: string; messageCount: number } }[] }[]}>(communityKeys.channelMessages("ch_parent"))- expect(cache?.pages[0].messages[0].thread).toEqual({+ expect(cache?.pages[0].messages).toEqual([])+ const overlay = getMessageOverlay({ kind: "channel", id: "ch_parent", serverId: "s1" })+ expect(overlay.liveById.get("m_parent")?.thread).toEqual({id: "ch_thread",name: "New thread",messageCount: 0,})})+ it("child_create then message.create invalidates and preserves the enriched forum card", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_parent" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()+ const parentMessagesKey = communityKeys.channelMessages("ch_parent")+ capturedQueryClient.setQueryData(parentMessagesKey, {+ pages: [{ messages: [], hasMore: false }],+ pageParams: [null],+ })+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ const event: CommunityChildChannelCreate = {+ type: "community:channel.child_create",+ parentChannelId: "ch_parent",+ parentMessageId: "m_parent",+ channel: {+ id: "ch_thread",+ name: "New thread",+ type: "thread",+ createdAt: "2026-07-03T00:00:00.000Z",+ },+ }++ capturedOnMessage!(event)+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: parentMessagesKey })++ capturedQueryClient.setQueryData(parentMessagesKey, {+ pages: [{+ messages: [{+ id: "m_parent",+ content: "hello",+ thread: { id: "ch_thread", name: "New thread", messageCount: 0 },+ }],+ hasMore: false,+ }],+ pageParams: [null],+ })+ capturedOnMessage!(messageCreate("ch_parent", "m_parent"))++ const cache = capturedQueryClient.getQueryData<{+ pages: { messages: { id: string; thread?: { id: string } }[] }[]+ }>(parentMessagesKey)+ expect(cache?.pages[0].messages).toHaveLength(1)+ expect(cache?.pages[0].messages[0].thread?.id).toBe("ch_thread")+ })+it("child_update still applies the reported messageCount unchanged", async () => {await mountHook()capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {@@ -1580,6 +1683,7 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {authorName: "bot",content: "done",type: "chat",+ seq: 1,createdAt: "2026-07-03T00:00:00.000Z",},} as CommunityMessageCreate)@@ -1593,9 +1697,17 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {// ── channel.delete invalidates the parent forum list (post deletion) ────────describe("useCommunityWs — channel.delete refreshes the parent forum feed", () => {- it("invalidates the parent's forumPosts + threads lists when parentChannelId is present", async () => {+ it("invalidates the parent's message feed + threads list when parentChannelId is present", async () => {await mountHook()const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ const allKey = communityKeys.channelMessages("forum_1")+ const bugKey = [...allKey, "tag", "bug"] as const+ const page = {+ pages: [{ messages: [{ id: "opener_1", thread: { id: "post_1" } }], hasMore: false }],+ pageParams: [null],+ }+ capturedQueryClient.setQueryData(allKey, page)+ capturedQueryClient.setQueryData(bugKey, page)const event: CommunityChannelDelete = {type: "community:channel.delete",@@ -1606,14 +1718,16 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()capturedOnMessage!(event)const invalidatedKeys = invalidateSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))- expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.forumPosts("forum_1")))+ expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.channelMessages("forum_1")))expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.threads("forum_1")))+ expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)+ expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)})it("does not throw and still evicts own caches when parentChannelId is absent (legacy event)", async () => {await mountHook()- // Seed the deleted channel's own caches so we can assert eviction.- capturedQueryClient.setQueryData(communityKeys.forumPosts("post_1"), { posts: [] })+ // Seed the deleted channel's own message cache so we can assert eviction.+ capturedQueryClient.setQueryData(communityKeys.channelMessages("post_1"), { pages: [], pageParams: [] })const removeSpy = vi.spyOn(capturedQueryClient, "removeQueries")const event: CommunityChannelDelete = {@@ -1624,7 +1738,46 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()expect(() => capturedOnMessage!(event)).not.toThrow()const removedKeys = removeSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))- expect(removedKeys).toContain(JSON.stringify(communityKeys.forumPosts("post_1")))+ expect(removedKeys).toContain(JSON.stringify(communityKeys.channelMessages("post_1")))+ })+})++describe("useCommunityWs — message edit refreshes forum opener summary", () => {+ it("invalidates the parent thread list for an opener edit, but not for an ordinary reply", async () => {+ await mountHook()+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ const opener: CommunityMessageEdited = {+ type: "community:message.edited",+ channelId: "post_1",+ messageId: "opener_1",+ content: "new title",+ parentChannelId: "forum_1",+ }+ capturedQueryClient.setQueryData(communityKeys.message("opener_1"), {+ id: "opener_1",+ content: "old title",+ })+ const allKey = communityKeys.channelMessages("forum_1")+ const bugKey = [...allKey, "tag", "bug"] as const+ const forumPage = { pages: [{ messages: [{ id: "opener_1", content: "old title" }] }], pageParams: [null] }+ capturedQueryClient.setQueryData(allKey, forumPage)+ capturedQueryClient.setQueryData(bugKey, forumPage)+ capturedOnMessage!(opener)+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMessages("forum_1") })+ expect(capturedQueryClient.getQueryState(allKey)?.isInvalidated).toBe(true)+ expect(capturedQueryClient.getQueryState(bugKey)?.isInvalidated).toBe(true)+ expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(allKey)?.pages[0].messages[0].content).toBe("new title")+ expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(bugKey)?.pages[0].messages[0].content).toBe("new title")+ expect(capturedQueryClient.getQueryData<{ content: string }>(communityKeys.message("opener_1"))?.content).toBe("new title")++ invalidateSpy.mockClear()+ capturedOnMessage!({+ type: "community:message.edited",+ channelId: "post_1",+ messageId: "reply_1",+ content: "edited reply",+ } satisfies CommunityMessageEdited)+ expect(invalidateSpy).not.toHaveBeenCalled()})})@@ -1656,6 +1809,7 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =authorId: "u_someone_else",authorName: "them",content: "hi",+ seq: 1,createdAt: "2026-07-03T00:00:00.000Z",},}@@ -1681,6 +1835,7 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =authorId: "u_me",authorName: "me",content: "hi",+ seq: 1,createdAt: "2026-07-03T00:00:00.000Z",},}@@ -1707,6 +1862,7 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =authorName: "a",content: "hi",type: "chat",+ seq: 1,createdAt: "2026-07-03T00:00:00.000Z",},}diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 5b485d8c0..160b62981 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -176,6 +176,32 @@ function patchApprovalInCache(return { ...cache, pages }}+function patchMessageContentInCache(cache: PageCache | undefined, messageId: string, content: string): PageCache | undefined {+ if (!cache) return cache+ let touched = false+ const pages = cache.pages.map((page) => ({+ ...page,+ messages: page.messages.map((message) => {+ if (message.id !== messageId) return message+ touched = true+ return { ...message, content }+ }),+ }))+ return touched ? { ...cache, pages } : cache+}++function removeThreadFromCache(cache: PageCache | undefined, threadId: string): PageCache | undefined {+ if (!cache) return cache+ let touched = false+ const pages = cache.pages.map((page) => {+ const messages = page.messages.filter((message) => message.thread?.id !== threadId)+ if (messages.length === page.messages.length) return page+ touched = true+ return { ...page, messages }+ })+ return touched ? { ...cache, pages } : cache+}+function applyReactionToCache(cache: PageCache | undefined,event: CommunityReactionAdd | CommunityReactionRemove,@@ -350,7 +376,8 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {(msg: { type: string;[key: string]: unknown }) => {if (!isCommunityEvent(msg)) returnconst event = msg as CommunityWsEvent- const sub = useCommunityStore.getState().subscription+ const communityStore = useCommunityStore.getState()+ const sub = communityStore.subscriptionconst wsStore = useCommunityWsStore.getState()const cbs = callbacksRef.current// A DM is a channel now — every message/typing/reaction event carries a@@ -393,17 +420,15 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// regular channel (`ch:`) so the pill clears in the right bucket.clearTypingIndicator(typingScopeKey(event, sub), event.message.authorId)- // 1) Patch the focused channel/dm page cache if the event matches.- // A DM is a channel, distinguished only by which subscription slot- // its channelId lands in.- if (event.channelId === sub.channelId) {- // A thread/forum_post enrolls its sender + mentioned users as- // participants server-side on send. That set IS its Members panel,- // so refetch it live — otherwise a new speaker/mention only appears- // after a manual refresh. No-op for a plain channel (whose panel is- // the access roster, not participants); the query is disabled there.+ // 1) A child channel enrolls its sender and mentioned users in its+ // member set server-side, so refresh an open child roster live.+ if (+ event.channelId === sub.channelId &&+ communityStore.currentChannelId === event.channelId &&+ communityStore.currentChannelMeta?.parentChannelId+ ) {void queryClient.invalidateQueries({- queryKey: communityKeys.threadParticipants(event.channelId),+ queryKey: communityKeys.channelMembers(event.channelId),})}@@ -444,7 +469,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// defensively).case "community:unread.bump": {const viewerId = viewerUserIdRef.current- // The sidebar row to light: a thread/forum-post message has no+ // The sidebar row to light: a child-thread message has no// independent tree row, so its dot lights the PARENT channel// (`railChannelId`); a plain channel is its own row. Fall back to// `channelId` for older frames that predate `railChannelId`.@@ -501,8 +526,8 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// `channelMessages(id)`, a DM channel's under `dmMessages(id)` — patch// both keys; the one that doesn't exist receives `undefined` and the// updater returns it, a harmless no-op.- queryClient.setQueryData<PageCache>(- communityKeys.channelMessages(event.channelId),+ queryClient.setQueriesData<PageCache>(+ { queryKey: communityKeys.channelMessages(event.channelId) },(c) => applyReactionToCache(c, event, viewerId),)queryClient.setQueryData<PageCache>(@@ -580,23 +605,25 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}- // ── Child channels (threads + forum posts) ──────────────────────+ // ── Child threads ──────────────────────────────────────────────case "community:channel.child_create":case "community:channel.child_update": {- // Cheap invalidate for the thread + forum-post lists. The parent+ // Cheap invalidate for the child-thread lists. The parent// messages list also needs an update because the parent message's// thread indicator (`msg.thread`) changes — do a targeted// setQueryData patch when we know parentMessageId.void queryClient.invalidateQueries({queryKey: communityKeys.threads(event.parentChannelId),})- void queryClient.invalidateQueries({- queryKey: communityKeys.forumPosts(event.parentChannelId),- })if (event.type === "community:channel.child_create") {+ const parentMessagesKey = communityKeys.channelMessages(event.parentChannelId)+ const parentMessages = queryClient.getQueryData<PageCache>(parentMessagesKey)+ const openerCached = !!event.parentMessageId && parentMessages?.pages.some((page) =>+ page.messages.some((message) => message.id === event.parentMessageId),+ )if (event.parentMessageId) {- queryClient.setQueryData<PageCache>(- communityKeys.channelMessages(event.parentChannelId),+ queryClient.setQueriesData<PageCache>(+ { queryKey: parentMessagesKey },(cache) => {if (!cache) return cachelet touched = false@@ -648,13 +675,16 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {}}}+ if (event.parentMessageId && !openerCached) {+ void queryClient.invalidateQueries({ queryKey: parentMessagesKey })+ }} else {// child_update — sync counts/name on the parent message's thread// indicator if the update carries them.const changes = event.changesif (changes.messageCount !== undefined || changes.name !== undefined) {- queryClient.setQueryData<PageCache>(- communityKeys.channelMessages(event.parentChannelId),+ queryClient.setQueriesData<PageCache>(+ { queryKey: communityKeys.channelMessages(event.parentChannelId) },(cache) => {if (!cache) return cachelet touched = false@@ -785,7 +815,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {case "community:category.reorder": {// #3: on channel.delete, evict every channel-scoped cache before// invalidating the server. Without this the messages/pins/threads/- // forum-posts caches for the dead channel linger forever — a+ // child-thread caches for the dead channel linger forever — a// subsequent same-id revive (rare, but the server can reuse ids)// would surface stale rows.if (event.type === "community:channel.delete") {@@ -803,15 +833,16 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {queryClient.removeQueries({queryKey: communityKeys.threads(event.channelId),})- queryClient.removeQueries({- queryKey: communityKeys.forumPosts(event.channelId),- })- // When a child (forum_post / thread) is deleted, refresh the+ // When a child thread is deleted, refresh the// PARENT's list so the deleted card disappears from the feed on// every client. Absent on older events / top-level channels.if (event.parentChannelId) {+ queryClient.setQueriesData<PageCache>(+ { queryKey: communityKeys.channelMessages(event.parentChannelId) },+ (cache) => removeThreadFromCache(cache, event.channelId),+ )void queryClient.invalidateQueries({- queryKey: communityKeys.forumPosts(event.parentChannelId),+ queryKey: communityKeys.channelMessages(event.parentChannelId),})void queryClient.invalidateQueries({queryKey: communityKeys.threads(event.parentChannelId),@@ -848,7 +879,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })- queryClient.removeQueries({ queryKey: communityKeys.forumPosts(event.channelId) })}void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })// Refetch the channel roster so an open private-channel Members drawer@@ -858,7 +888,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// a peer's add/remove changes it too, so an open add dialog doesn't// offer a just-added member (whose Add would 400) or hide a removed one.void queryClient.invalidateQueries({ queryKey: communityKeys.channelAddableMembers(event.channelId) })- // A forum_post's "Add participant" emits this same MEMBER_ADD event —+ // A forum thread's "Add participant" emits this same MEMBER_ADD event —// its Members panel is the participant set, so refetch it too. No-op// for a plain channel (participants query disabled there).void queryClient.invalidateQueries({ queryKey: communityKeys.threadParticipants(event.channelId) })@@ -1002,6 +1032,40 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}+ case "community:message.edited": {+ queryClient.setQueryData<{ content: string }>(+ communityKeys.message(event.messageId),+ (message) => message ? { ...message, content: event.content } : message,+ )+ queryClient.setQueriesData<PageCache>(+ { queryKey: communityKeys.channelMessages(event.channelId) },+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),+ )+ queryClient.setQueryData<PageCache>(+ communityKeys.dmMessages(event.channelId),+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),+ )+ const streamStore = useMessageStreamStore.getState()+ for (const entry of streamStore.entries.values()) {+ if (entry.scope.id !== event.channelId) continue+ streamStore.dispatch(entry.scope, {+ type: "messageEdited",+ messageId: event.messageId,+ content: event.content,+ })+ }+ if (event.parentChannelId) {+ queryClient.setQueriesData<PageCache>(+ { queryKey: communityKeys.channelMessages(event.parentChannelId) },+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),+ )+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelMessages(event.parentChannelId),+ })+ }+ return+ }+// ── Presence — no cache; write to WS store ──────────────────────case "community:presence.update": {useCommunityWsStore.getState().setPresence(event.userId, event.online)diff --git a/src/web/src/hooks/community/use-dm-message-sender.test.ts b/src/web/src/hooks/community/use-dm-message-sender.test.tsindex 311514c9d..e8a9afa04 100644--- a/src/web/src/hooks/community/use-dm-message-sender.test.ts+++ b/src/web/src/hooks/community/use-dm-message-sender.test.ts@@ -12,10 +12,10 @@ const postMock = vi.fn()vi.mock("@/hooks/community/mutations", () => ({sendNonce: () => "fresh_nonce",tempMessageId: () => "temp_fresh",- toAttachmentVm: (attachment: { url: string; filename: string }) => ({+ toAttachmentVm: (channelId: string, attachment: { id: string; filename: string }) => ({kind: "file" as const,name: attachment.filename,- url: attachment.url,+ url: `/api/community/channels/${channelId}/attachments/${attachment.id}`,size: "1 KB",}),zipUploadResultsWithDimensions: (results: unknown[]) => results.filter(Boolean),@@ -125,7 +125,7 @@ describe("useDmMessageSender", () => {it("reuses settled remote attachments on retry without uploading twice", async () => {uploadMock.mockResolvedValueOnce({- url: "https://files.example/x.txt",+ id: "att_x",filename: "x.txt",contentType: "text/plain",size: 1,@@ -158,7 +158,7 @@ describe("useDmMessageSender", () => {content: "file",replyToId: undefined,attachments: [{- url: "https://files.example/x.txt",+ id: "att_x",filename: "x.txt",contentType: "text/plain",size: 1,@@ -175,8 +175,16 @@ describe("useDmMessageSender", () => {useMessageStreamStore.getState().dispatch(scope, {type: "postAck",nonce: args.nonce,- serverMessageId: "server_1",- serverSeq: 11,+ message: {+ id: "server_1",+ seq: 11,+ type: "chat",+ authorId: "u_me",+ authorName: "Me",+ content: "out of view",+ createdAt: "2026-08-07T10:00:00.000Z",+ clientNonce: args.nonce,+ },})return { message: { id: "server_1", seq: 11 } }})diff --git a/src/web/src/hooks/community/use-dm-message-sender.ts b/src/web/src/hooks/community/use-dm-message-sender.tsindex 499c6ab10..481185b77 100644--- a/src/web/src/hooks/community/use-dm-message-sender.ts+++ b/src/web/src/hooks/community/use-dm-message-sender.ts@@ -58,7 +58,7 @@ export function useDmMessageSender() {uploadedAttachments = projected.map((attachment, index) => {const local = payload.localUploads[index]return {- url: attachment.url,+ id: attachment.url.slice(attachment.url.lastIndexOf("/") + 1),filename: local.file.name,contentType: local.file.type,size: local.file.size,@@ -72,7 +72,12 @@ export function useDmMessageSender() {if (payload.localUploads.length > 0 && !uploadedAttachments) {const results = await Promise.all(payload.localUploads.map((upload) =>- uploadFileAsync({ target: { dmId }, file: upload.file }).catch((error) => {+ uploadFileAsync({+ target: { dmId },+ file: upload.file,+ width: upload.width,+ height: upload.height,+ }).catch((error) => {toastApiError(error, "Failed to attach file")return null}),@@ -86,7 +91,8 @@ export function useDmMessageSender() {streamStore.dispatch(scope, {type: "uploadSettled",nonce,- attachments: uploadedAttachments.map(toAttachmentVm),+ attachments: uploadedAttachments.map((attachment) =>+ toAttachmentVm(dmId, attachment)),})}diff --git a/src/web/src/hooks/community/use-dm-read-state.ts b/src/web/src/hooks/community/use-dm-read-state.tsindex 2d1d273f0..d30e4dcc2 100644--- a/src/web/src/hooks/community/use-dm-read-state.ts+++ b/src/web/src/hooks/community/use-dm-read-state.ts@@ -7,7 +7,9 @@ import { communityKeys } from "@/lib/query-keys"/*** The DM read-state snapshot returned by- * `GET /api/community/dm/:id/read-state`. Fields default to `null` / `0`+ * `GET /api/community/channels/:id/read-state` (a DM is a channel row; the+ * whole DM surface reads through the one canonical door). Fields default to+ * `null` / `0`* when the viewer has never opened this DM.*/export type DmReadStateSnapshot = {@@ -41,7 +43,7 @@ export function useDmReadStateSnapshot(dmId: string | null | undefined): {: ["community", "dm", "__none__", "read-state-snapshot"],queryFn: async () => {return apiFetch<DmReadStateSnapshot>(- `/api/community/dm/${dmId}/read-state`,+ `/api/community/channels/${dmId}/read-state`,)},enabled: !!dmId,diff --git a/src/web/src/hooks/community/use-dms.test.ts b/src/web/src/hooks/community/use-dms.test.tsindex 2e7d9dd7c..1014b1743 100644--- a/src/web/src/hooks/community/use-dms.test.ts+++ b/src/web/src/hooks/community/use-dms.test.ts@@ -12,14 +12,14 @@ beforeEach(() => {})describe("useDms / dmsQueryFn", () => {- it("returns the DM conversations from GET /api/community/dm", async () => {+ it("returns the DM conversations from GET /api/community/users/me/dms", async () => {const conversations = [{ id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0000", avatar: "A", status: "offline", preview: "" },]apiFetchMock.mockResolvedValueOnce({ conversations })const { dmsQueryFn } = await import("./use-dms")const data = await dmsQueryFn()- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/dm")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/dms")expect(data.conversations).toEqual(conversations)})diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex 2b9cc0332..a2009a0a5 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -19,7 +19,7 @@ export type DmsResponse = { conversations: DM[] }const EMPTY_DMS: readonly DM[] = Object.freeze([])export const dmsQueryFn = () =>- apiFetch<DmsResponse>("/api/community/dm")+ apiFetch<DmsResponse>("/api/community/users/me/dms")export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {const query = useQuery({diff --git a/src/web/src/hooks/community/use-eager-channel-read.test.ts b/src/web/src/hooks/community/use-eager-channel-read.test.tsindex 57a74105a..91e444aa9 100644--- a/src/web/src/hooks/community/use-eager-channel-read.test.ts+++ b/src/web/src/hooks/community/use-eager-channel-read.test.ts@@ -106,7 +106,38 @@ describe("useEagerChannelRead — rail-badge fan-out gate", () => {})})- it("uses the thread endpoint for a child channel", async () => {+ it("does not repeat a PUT for the same channel and fires once after a channel switch", async () => {+ const hook = await loadHook()+ const render = (channelId: string) => {+ refCounter = 0+ pendingEffects = []+ hook({+ channelId,+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: true,+ })+ flushEffects()+ }++ render("ch_1")+ await settle()+ render("ch_1")+ await settle()+ expect(apiFetchMock).toHaveBeenCalledTimes(1)++ render("ch_2")+ await settle()+ expect(apiFetchMock).toHaveBeenCalledTimes(2)+ expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/ch_2/read", {+ method: "PUT",+ })+ })++ it("uses the unified channels/[id]/read trunk for a child channel too (a thread IS a channel)", async () => {+ // The per-type /threads/:id/read split is retired — all kinds mark read via+ // channels/[id]/read, which dispatches by surface. isChildChannel no longer+ // picks the endpoint.const useHook = await loadHook()useHook({channelId: "th_9",@@ -116,7 +147,7 @@ describe("useEagerChannelRead — rail-badge fan-out gate", () => {})flushEffects()await settle()- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/threads/th_9/read", {+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/th_9/read", {method: "PUT",})})diff --git a/src/web/src/hooks/community/use-eager-channel-read.ts b/src/web/src/hooks/community/use-eager-channel-read.tsindex 3c7dd5c9f..6c1395b61 100644--- a/src/web/src/hooks/community/use-eager-channel-read.ts+++ b/src/web/src/hooks/community/use-eager-channel-read.ts@@ -27,9 +27,11 @@ import type { ServersResponse } from "@/hooks/community/use-servers"* `lastReadAt < message.createdAt` rule, can never be regressed by a later* older watermark PUT.*- * `isChildChannel` picks the endpoint — threads/forum-posts read through- * `/threads/:id/read`, top-level channels through `/channels/:id/read`. Both- * accept an empty body as mass mark-read and both batch the mention clear.+ * All channel kinds (top-level and child thread) mark read through the one+ * `/channels/:id/read` trunk — a thread IS a channel, and the unified handler+ * dispatches by surface (DM ids run the block gate). The old per-type+ * `/threads/:id/read` split is retired. Empty body = mass mark-read + batched+ * mention clear.** Note: `lastReadSeq` (the numeric bot-wake cursor) is intentionally NOT* touched here — human read routes don't bump it; that divergence is a@@ -56,10 +58,7 @@ export function useEagerChannelRead({if (firedForRef.current === channelId) returnfiredForRef.current = channelId- const endpoint = isChildChannel- ? `/api/community/threads/${channelId}/read`- : `/api/community/channels/${channelId}/read`- void apiFetch(endpoint, { method: "PUT" })+ void apiFetch(`/api/community/channels/${channelId}/read`, { method: "PUT" }).then(() => {// Always refresh the inbox feeds — the mass mark-read cleared them.void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })diff --git a/src/web/src/hooks/community/use-eager-dm-read.ts b/src/web/src/hooks/community/use-eager-dm-read.tsindex 2d0779250..b9f49bbf2 100644--- a/src/web/src/hooks/community/use-eager-dm-read.ts+++ b/src/web/src/hooks/community/use-eager-dm-read.ts@@ -39,7 +39,7 @@ export function useEagerDmRead({prev ? { ...prev, dms: prev.dms.filter((d) => d.channelId !== dmId) } : prev,)- void apiFetch(`/api/community/dm/${dmId}/read`, { method: "PUT" })+ void apiFetch(`/api/community/channels/${dmId}/read`, { method: "PUT" }).then(() => {void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })diff --git a/src/web/src/hooks/community/use-folders.test.ts b/src/web/src/hooks/community/use-folders.test.tsindex ac36b1b79..72c57cf2d 100644--- a/src/web/src/hooks/community/use-folders.test.ts+++ b/src/web/src/hooks/community/use-folders.test.ts@@ -25,7 +25,7 @@ describe("useFolders / foldersQueryFn", () => {})const { foldersQueryFn } = await import("./use-folders")const data = await foldersQueryFn()- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/server-folders")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/server-folders")expect(data.folders[0].servers[0].initial).toBe("A")expect(data.folders[0].position).toBe(2)})diff --git a/src/web/src/hooks/community/use-folders.ts b/src/web/src/hooks/community/use-folders.tsindex e6c678d5e..d2b7c74f8 100644--- a/src/web/src/hooks/community/use-folders.ts+++ b/src/web/src/hooks/community/use-folders.ts@@ -26,7 +26,7 @@ export type FoldersResponse = { folders: CommunityFolder[] }const EMPTY_FOLDERS: readonly CommunityFolder[] = Object.freeze([])export const foldersQueryFn = async (): Promise<FoldersResponse> => {- const data = await apiFetch<{ folders: RawFolder[] }>("/api/community/server-folders")+ const data = await apiFetch<{ folders: RawFolder[] }>("/api/community/users/me/server-folders")const folders: CommunityFolder[] = data.folders.map((f) => ({id: f.id,name: f.name,diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsnew file mode 100644index 000000000..03c0f9786--- /dev/null+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -0,0 +1,52 @@+"use client"++import { useCallback, useEffect, useMemo, useState } from "react"+import { avatarInitial } from "@/lib/community/avatar"+import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"+import { useForumTags } from "./use-channel-panels"+import { useMessages } from "./use-messages"++export function useForumFeed(serverId: string, channelId: string) {+ const [tag, setTag] = useState(() => {+ if (typeof window === "undefined") return "All"+ try { return readForumTagSelection(window.localStorage, channelId) }+ catch { return "All" }+ })+ const tagsQuery = useForumTags(channelId, true)+ useEffect(() => {+ if (!tagsQuery.isSuccess || tag === "All") return+ if (validateForumTagSelection(tag, tagsQuery.data.tags) !== "All") return+ setTag("All")+ try { writeForumTagSelection(window.localStorage, channelId, "All") } catch { }+ }, [channelId, tag, tagsQuery.data, tagsQuery.isSuccess])+ const selectTag = useCallback((next: string) => {+ setTag(next)+ try { writeForumTagSelection(window.localStorage, channelId, next) } catch { }+ }, [channelId])+ const feed = useMessages(channelId, {+ serverId,+ lastReadMessageId: null,+ anchorMessageId: null,+ tag: tag === "All" ? null : tag,+ })+ const posts = useMemo(() => feed.messages.flatMap((message) => {+ const thread = message.thread+ if (!thread) return []+ return [{+ id: thread.id,+ name: message.content ?? thread.name,+ messageCount: thread.messageCount,+ lastMessageAt: thread.lastReplyAt ?? message.createdAt ?? "",+ parent: { authorName: message.authorName ?? "", text: thread.preview ?? "" },+ authorId: message.authorId ?? "",+ authorAvatar: message.authorAvatar ?? avatarInitial(message.authorName ?? ""),+ openerMessageId: message.id,+ tags: thread.tags ?? [],+ preview: thread.preview ?? "",+ participants: thread.participants ?? [],+ participantCount: thread.participantCount ?? 0,+ }]+ }), [feed.messages])++ return { ...feed, posts, tag, selectTag, availableTags: tagsQuery.data?.tags ?? [] }+}diff --git a/src/web/src/hooks/community/use-friends.test.ts b/src/web/src/hooks/community/use-friends.test.tsindex 50f6ffbd3..4dbce30fb 100644--- a/src/web/src/hooks/community/use-friends.test.ts+++ b/src/web/src/hooks/community/use-friends.test.ts@@ -12,28 +12,36 @@ beforeEach(() => {})describe("useFriends / friendsQueryFn", () => {- it("fetches friends+blocked and pending in parallel and merges", async () => {- apiFetchMock- .mockImplementationOnce(async (url: string) => {- expect(url).toBe("/api/community/friends")- return { friends: [{ id: "f_1", name: "n", discriminator: "0000", avatar: "a", status: "offline", sub: "" }], blocked: [{ id: "b_1", name: "b", avatar: "a" }] }- })- .mockImplementationOnce(async (url: string) => {- expect(url).toBe("/api/community/friends/pending")- return { pending: [{ id: "p_1", userId: "u_1", name: "n", avatar: "a", kind: "incoming" }] }- })+ it("fetches accepted + blocked + pending buckets in parallel and merges", async () => {+ // Legacy aggregate GET /friends retired — each bucket from its sub-resource.+ const byUrl: Record<string, unknown> = {+ "/api/community/friends/accepted": { friends: [{ id: "f_1", name: "n", discriminator: "0000", avatar: "a", status: "offline", sub: "" }] },+ "/api/community/friends/blocked": { blocked: [{ id: "b_1", name: "b", avatar: "a" }] },+ "/api/community/friends/pending": { pending: [{ id: "p_1", userId: "u_1", name: "n", avatar: "a", kind: "incoming" }] },+ }+ apiFetchMock.mockImplementation(async (url: string) => {+ if (!(url in byUrl)) throw new Error(`unexpected url ${url}`)+ return byUrl[url]+ })const { friendsQueryFn } = await import("./use-friends")const data = await friendsQueryFn()expect(data.friends).toHaveLength(1)expect(data.blocked).toHaveLength(1)expect(data.pending).toHaveLength(1)- expect(apiFetchMock).toHaveBeenCalledTimes(2)+ expect(apiFetchMock).toHaveBeenCalledTimes(3)+ const urls = apiFetchMock.mock.calls.map((c) => c[0]).sort()+ expect(urls).toEqual([+ "/api/community/friends/accepted",+ "/api/community/friends/blocked",+ "/api/community/friends/pending",+ ])})it("populates queryClient at communityKeys.friends() and is invalidated by prefix", async () => {apiFetchMock- .mockResolvedValueOnce({ friends: [], blocked: [] })+ .mockResolvedValueOnce({ friends: [] })+ .mockResolvedValueOnce({ blocked: [] }).mockResolvedValueOnce({ pending: [] })const { friendsQueryFn } = await import("./use-friends")const qc = new QueryClient()diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.tsindex c48b0a9e2..3ec82f854 100644--- a/src/web/src/hooks/community/use-friends.ts+++ b/src/web/src/hooks/community/use-friends.ts@@ -41,13 +41,18 @@ const EMPTY_PENDING: readonly PendingRequest[] = Object.freeze([])const EMPTY_BLOCKED: readonly BlockedUser[] = Object.freeze([])export const friendsQueryFn = async (): Promise<FriendsResponse> => {- const [friendsData, pendingData] = await Promise.all([- apiFetch<{ friends: Friend[]; blocked: BlockedUser[]; stale?: boolean }>("/api/community/friends").then(throwIfStale),+ // The legacy aggregate GET /friends ({friends,blocked}) is retired — read each+ // bucket from its own sub-resource endpoint (friends/accepted · friends/blocked+ // · friends/pending) and compose the same triad. Same query key / cache grain+ // as before, so mutations still fire one invalidation.+ const [acceptedData, blockedData, pendingData] = await Promise.all([+ apiFetch<{ friends: Friend[]; stale?: boolean }>("/api/community/friends/accepted").then(throwIfStale),+ apiFetch<{ blocked: BlockedUser[]; stale?: boolean }>("/api/community/friends/blocked").then(throwIfStale),apiFetch<{ pending: PendingRequest[]; stale?: boolean }>("/api/community/friends/pending").then(throwIfStale),])return {- friends: friendsData.friends,- blocked: friendsData.blocked,+ friends: acceptedData.friends,+ blocked: blockedData.blocked,pending: pendingData.pending,}}diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.tsindex f5be15c0b..d3f9300e5 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts@@ -67,7 +67,7 @@ describe("inboxItemPresent", () => {expect(inboxItemPresent(lists, "channel:c2")).toBe(false)})- it("finds a channel:<id> that is a nested child (thread / forum-post)", () => {+ it("finds a channel:<id> that is a nested child thread", () => {const lists: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1", children: ["t1"] }])] }expect(inboxItemPresent(lists, "channel:t1")).toBe(true)})@@ -139,16 +139,44 @@ describe("useInboxAutoCollapse", () => {expect(hook.current.open).toBe(false)})- it("keeps the popover open when a watched channel persists (navigate-only forum parent)", async () => {+ it("keeps the popover open when a watched forum parent remains to host an unread child", async () => {const withForum: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["p1"] }])] }const hook = await renderHook(withForum)await hook.call(() => hook.current.onOpenChange(true))await hook.call(() => hook.current.watchItem("channel:forum1"))- // Re-render with the parent still present (posts unread) → stays open.+ // The parent's own opener unread is gone, but it remains to host p1.await hook.rerender({ ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["p1"] }])] })expect(hook.current.open).toBe(true)})+ it("collapses an opener-only forum thread after the successful parent refresh removes it", async () => {+ const withOpener = { ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["post1"] }])] }+ const hook = await renderHook(withOpener)+ await hook.call(() => hook.current.onOpenChange(true))+ await hook.call(() => hook.current.watchItem("channel:post1"))++ // Parent progressive read consumes the opener; there are no child replies,+ // so the nested thread row leaves the Inbox immediately after refetch.+ await hook.rerender(EMPTY)+ expect(hook.current.open).toBe(false)+ })++ it("keeps an opener-plus-reply thread until the child eager read consumes replies", async () => {+ const withPost = { ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["post1"] }])] }+ const hook = await renderHook(withPost)+ await hook.call(() => hook.current.onOpenChange(true))+ await hook.call(() => hook.current.watchItem("channel:post1"))++ // Parent read removes the opener projection, but the same deduped child row+ // remains because it still has unread replies.+ await hook.rerender(withPost)+ expect(hook.current.open).toBe(true)++ // The destination child's existing eager read then removes the reply row.+ await hook.rerender(EMPTY)+ expect(hook.current.open).toBe(false)+ })+it("collapses when a watched DM leaves the list", async () => {const withD1: InboxLists = { ...EMPTY, unreadDms: [dm("d1")] }const hook = await renderHook(withD1)diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.tsindex e1aea95ff..912bb8e4a 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts@@ -7,9 +7,9 @@ import type { Mention, UnreadDm, UnreadServer } from "@/components/community/_ty* Inbox auto-collapse.** The inbox popover should close by itself the moment the row the user clicked- * leaves the list — and only then. Clicking a row that merely navigates (e.g. a- * forum-channel parent, whose unread posts aren't read by visiting the listing)- * keeps its `channel:<id>` row present, so the popover stays open.+ * leaves the list — and only then. A forum parent can remain after its own+ * opener messages are read when it still hosts unread child channels, so the+ * popover stays open while that exact `channel:<id>` row is present.** The mechanism: record the clicked row's key (a "pending close" marker held in* a ref so setting it doesn't render), then watch the inbox lists. When that@@ -17,7 +17,7 @@ import type { Mention, UnreadDm, UnreadServer } from "@/components/community/_ty** Row → key:* - DM row → `dm:<channelId>` (a DM is a channel)- * - channel row → `channel:<channelId>` (top-level OR nested thread/forum-post)+ * - channel row → `channel:<channelId>` (top-level or nested child thread)* - mention row → `mention:<mention.id>`*/diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.tsindex 4202fd2e0..cdc71e604 100644--- a/src/web/src/hooks/community/use-inbox.test.ts+++ b/src/web/src/hooks/community/use-inbox.test.ts@@ -18,7 +18,7 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {const qc = new QueryClient()const key = communityKeys.inboxUnreads()await qc.fetchQuery({ queryKey: key, queryFn: inboxUnreadsQueryFn })- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/inbox/unreads")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/inbox/unreads")expect(qc.getQueryData(key)).toEqual({ servers: [], dms: [] })})})@@ -30,7 +30,7 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {const qc = new QueryClient()const key = communityKeys.inboxMentions()await qc.fetchQuery({ queryKey: key, queryFn: inboxMentionsQueryFn })- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/inbox/mentions")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/inbox/mentions")expect(qc.getQueryData(key)).toEqual({ mentions: [] })})})diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex e07e18542..98980703d 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -35,7 +35,7 @@ const EMPTY_MARKED: readonly Marked[] = Object.freeze([])export type UnreadsResponse = { servers: UnreadServer[]; dms: UnreadDm[] }export const inboxUnreadsQueryFn = () =>- apiFetch<UnreadsResponse & { stale?: boolean }>("/api/community/inbox/unreads").then(throwIfStale)+ apiFetch<UnreadsResponse & { stale?: boolean }>("/api/community/users/me/inbox/unreads").then(throwIfStale)export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {servers: UnreadServer[]@@ -56,7 +56,7 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {export type MentionsResponse = { mentions: Mention[] }export const inboxMentionsQueryFn = () =>- apiFetch<MentionsResponse & { stale?: boolean }>("/api/community/inbox/mentions").then(throwIfStale)+ apiFetch<MentionsResponse & { stale?: boolean }>("/api/community/users/me/inbox/mentions").then(throwIfStale)export function useInboxMentions(): UseQueryResult<MentionsResponse> & {mentions: Mention[]@@ -75,7 +75,7 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {export type MarkedResponse = { marked: Marked[] }const inboxMarkedQueryFn = () =>- apiFetch<MarkedResponse & { stale?: boolean }>("/api/community/inbox/marked").then(throwIfStale)+ apiFetch<MarkedResponse & { stale?: boolean }>("/api/community/users/me/marks").then(throwIfStale)/*** The Marked feed is lazy — unlike unreads/mentions (which the shell reads@@ -103,7 +103,7 @@ export type MessageMarkedResponse = { marked: boolean }const messageMarkedQueryFn = (messageId: string) => () =>apiFetch<MessageMarkedResponse & { stale?: boolean }>(- `/api/community/marks/${messageId}`,+ `/api/community/messages/${messageId}/marks`,).then(throwIfStale)/**diff --git a/src/web/src/hooks/community/use-invitable-friends.ts b/src/web/src/hooks/community/use-invitable-friends.tsindex b15c10afa..bf70d8a64 100644--- a/src/web/src/hooks/community/use-invitable-friends.ts+++ b/src/web/src/hooks/community/use-invitable-friends.ts@@ -4,6 +4,7 @@ import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { Friend } from "@/components/community/_types"+import { fetchAllServerMembers } from "./fetch-all-server-members"/*** Friends of the viewer who are NOT already members of `serverId` — feeds@@ -20,16 +21,23 @@ export type InvitableFriendsResponse = {const EMPTY: readonly Friend[] = Object.freeze([])+export async function invitableFriendsQueryFn(serverId: string): Promise<InvitableFriendsResponse> {+ const [accepted, members] = await Promise.all([+ apiFetch<{ friends: Friend[]; stale?: boolean }>("/api/community/friends/accepted"),+ fetchAllServerMembers(serverId),+ ])+ if (accepted.stale) throw new Error("stale D1 read")+ const memberIds = new Set(members.map((member) => member.userId))+ return { friends: accepted.friends.filter((friend) => !friend.userId || !memberIds.has(friend.userId)) }+}+export function useInvitableFriends(serverId: string,enabled = true,): UseQueryResult<InvitableFriendsResponse> & { friends: Friend[] } {const query = useQuery({queryKey: communityKeys.invitableFriends(serverId),- queryFn: () =>- apiFetch<InvitableFriendsResponse>(- `/api/community/servers/${encodeURIComponent(serverId)}/invitable-friends`,- ),+ queryFn: () => invitableFriendsQueryFn(serverId),enabled: enabled && !!serverId,})return {diff --git a/src/web/src/hooks/community/use-messages.test.ts b/src/web/src/hooks/community/use-messages.test.tsindex 26c4563c4..493446839 100644--- a/src/web/src/hooks/community/use-messages.test.ts+++ b/src/web/src/hooks/community/use-messages.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient, type InfiniteData } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import type { Msg } from "@/components/community/_types"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -107,7 +108,7 @@ describe("dmMessagesQueryFn", () => {const { dmMessagesQueryFn } = await loadHook()apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })await dmMessagesQueryFn("dm_1")({ pageParam: { mode: "newest" } })- expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/dm/dm_1/messages")+ expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/dm_1/messages")})it("older cursor → ?cursor", async () => {@@ -117,7 +118,7 @@ describe("dmMessagesQueryFn", () => {pageParam: { mode: "older", cursor: "cur_1" },})expect(apiFetchMock).toHaveBeenLastCalledWith(- "/api/community/dm/dm_1/messages?cursor=cur_1",+ "/api/community/channels/dm_1/messages?cursor=cur_1",)})@@ -141,6 +142,18 @@ describe("dmMessagesQueryFn", () => {})})+describe("messageMatchesTag", () => {+ it("keeps untagged live rows out of tagged forum variants", async () => {+ const { messageMatchesTag } = await loadHook()+ const untagged = { id: "m1", type: "chat", thread: { tags: [] } } as Msg+ const tagged = { id: "m2", type: "chat", thread: { tags: ["bug"] } } as Msg++ expect(messageMatchesTag(untagged, null)).toBe(true)+ expect(messageMatchesTag(untagged, "bug")).toBe(false)+ expect(messageMatchesTag(tagged, "bug")).toBe(true)+ })+})+// ── mergeMessagesPages reducer ──────────────────────────────────────────//// Pages may arrive out of order — anchor first, then interleaveddiff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 1e3767f57..b02e26a37 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -60,8 +60,9 @@ export type MessagesPageParam =| { mode: "older"; cursor: string }| { mode: "newer"; cursor: string }-function buildMessagesUrl(base: string, pageParam: MessagesPageParam): string {+function buildMessagesUrl(base: string, pageParam: MessagesPageParam, tag?: string | null): string {const params = new URLSearchParams()+ if (tag) params.set("tag", tag)switch (pageParam.mode) {case "newest":break@@ -83,10 +84,10 @@ function buildMessagesUrl(base: string, pageParam: MessagesPageParam): string {}export const channelMessagesQueryFn =- (channelId: string) =>+ (channelId: string, tag?: string | null) =>async ({ pageParam }: { pageParam: MessagesPageParam }): Promise<MessagesPage> => {return apiFetch<MessagesPage>(- buildMessagesUrl(`/api/community/channels/${channelId}/messages`, pageParam),+ buildMessagesUrl(`/api/community/channels/${channelId}/messages`, pageParam, tag),)}@@ -94,10 +95,14 @@ export const dmMessagesQueryFn =(dmId: string) =>async ({ pageParam }: { pageParam: MessagesPageParam }): Promise<MessagesPage> => {return apiFetch<MessagesPage>(- buildMessagesUrl(`/api/community/dm/${dmId}/messages`, pageParam),+ buildMessagesUrl(`/api/community/channels/${dmId}/messages`, pageParam),)}+export function messageMatchesTag(message: Msg, tag?: string | null): boolean {+ return !tag || message.thread?.tags?.includes(tag) === true+}+/*** Merge all pages into a single chronological ASC list, deduping by id.* Extracted so tests can drive the reducer without spinning up a full hook.@@ -161,6 +166,8 @@ type MessagesReturn = Omit<UseInfiniteQueryResult<PageCache, Error>, "isLoading"}type MessagesOpts = {+ /** Server-side message-tag filter. Null/undefined means the complete set. */+ tag?: string | null/*** Anchor for the initial fetch. Undefined = read-state not resolved yet;* the hook stays disabled until this becomes a value or `null`. `null`@@ -176,14 +183,6 @@ type MessagesOpts = {* read snapshot resolves must NOT leave the query disabled.*/anchorMessageId?: string | null- /**- * When true, the initial page is trusted from a pre-seeded cache (the channel- * bootstrap wrote `channelMessages(id)` before this hook mounted), so the- * hook must NOT refetch page 0 on mount — otherwise the de-serialization win- * is lost (bootstrap + a redundant messages fetch). Pagination (older/newer)- * still refetches normally. Only affects the initial window.- */- trustSeededInitialPage?: boolean}type ChannelMessagesOpts = MessagesOpts & {@@ -255,15 +254,6 @@ function useMessagesInner(return { mode: "newer", cursor }},enabled,- // Trust a bootstrap-seeded initial window: treat it as fresh so the hook- // doesn't refetch page 0 on mount (otherwise the de-serialization win is- // lost — bootstrap + a redundant messages fetch). Pagination still fetches- // older/newer via getNext/PreviousPageParam. Without a seed these fall to- // the library defaults (staleTime 0, refetchOnMount true), so the- // non-bootstrap paths (DM, jump, forum) are unchanged.- ...(opts?.trustSeededInitialPage- ? { staleTime: Infinity, refetchOnMount: false as const }- : {}),})// Flush any pending mark-read on scope switch / unmount so the 500ms@@ -511,7 +501,7 @@ function useMessagesInner(// Instant channel switch: a warm channel already has its newest-tail// hydrated into `messages` (from the persisted `channelMessages` cache)// before the read anchor resolves. Those rows must paint immediately rather- // than wait on the bootstrap/read-snapshot round-trip — switching must not+ // than wait on the read-snapshot round-trip — switching must not// happen on a network timescale. So only report loading when there is// genuinely nothing to show yet.//@@ -550,11 +540,12 @@ export function useMessages(channelId: string | null,opts: ChannelMessagesOpts,): MessagesReturn {- const queryKey = communityKeys.channelMessages(channelId ?? "__none__")+ const baseKey = communityKeys.channelMessages(channelId ?? "__none__")+ const queryKey = opts.tag ? [...baseKey, "tag", opts.tag] as const : baseKeyconst base = useMessagesInner(channelId,queryKey,- channelMessagesQueryFn(channelId ?? "__none__"),+ channelMessagesQueryFn(channelId ?? "__none__", opts?.tag),opts,)const scope = useMemo<MessageScope>(() => ({@@ -577,8 +568,9 @@ export function useMessages(})}, [canonicalBase, channelId, scope])const messages = useMemo(- () => materializeMessageStream(canonicalBase, overlay),- [canonicalBase, overlay],+ () => materializeMessageStream(canonicalBase, overlay).filter((message) =>+ messageMatchesTag(message, opts.tag)),+ [canonicalBase, opts.tag, overlay],)return { ...base, messages }}diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex bc1f4b6e8..8da0013ba 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -352,7 +352,7 @@ export function useScrollAnchor({virtualizer: Virtualizer<HTMLDivElement, Element>belowCount: numberscrollToBottom: () => void- jumpTo: (messageId: string) => void+ jumpTo: (messageId: string, behavior?: ScrollBehavior) => voidonImageLoad: () => void} {const scrollRef = useRef<HTMLDivElement>(null)@@ -517,13 +517,13 @@ export function useScrollAnchor({if (virtualizer.isAtEnd(NEAR_BOTTOM_PX)) virtualizer.scrollToEnd()}, [virtualizer])- const jumpTo = useCallback((messageId: string) => {+ const jumpTo = useCallback((messageId: string, behavior: ScrollBehavior = "smooth") => {const idx = findMessageIndex(items, messageId)// Target not in the currently loaded page window — same limitation the// pre-virtualization `querySelector` lookup had (it also required the// row to be loaded); documented no-op, not a new failure mode.if (idx === null) return- virtualizer.scrollToIndex(idx, { align: "center", behavior: "smooth" })+ virtualizer.scrollToIndex(idx, { align: "center", behavior })}, [items, virtualizer])return { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo, onImageLoad }diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.tsindex ce49eee3c..91e854cf2 100644--- a/src/web/src/hooks/community/use-servers.test.ts+++ b/src/web/src/hooks/community/use-servers.test.ts@@ -15,8 +15,8 @@ describe("useServers / serversQueryFn", () => {it("materialises raw server rows into render-ready Server shape", async () => {apiFetchMock.mockResolvedValueOnce({servers: [- { id: "srv_1", name: "Alook", icon: null, role: "owner", mentions: 3 },- { id: "srv_2", name: "Beta", icon: null, role: "member" },+ { id: "srv_1", name: "Alook", discriminator: "0042", icon: null, role: "owner", mentions: 3 },+ { id: "srv_2", name: "Beta", discriminator: "12345", icon: null, role: "member" },],})const { serversQueryFn } = await import("./use-servers")@@ -26,6 +26,7 @@ describe("useServers / serversQueryFn", () => {expect(data.servers[0].isOwner).toBe(true)expect(data.servers[0].mentions).toBe(3)expect(data.servers[0].active).toBe(false)+ expect(data.servers[0].discriminator).toBe("0042")// `unread` has been removed from the Server type — the mapper must not// project it. Pin the invariant so a future revival gets caught.expect((data.servers[0] as { unread?: boolean }).unread).toBeUndefined()@@ -37,8 +38,8 @@ describe("useServers / serversQueryFn", () => {it("preserves mentions when provided; defaults to 0 when omitted", async () => {apiFetchMock.mockResolvedValueOnce({servers: [- { id: "srv_1", name: "A", icon: null, mentions: 7 },- { id: "srv_2", name: "B", icon: null }, // no mentions key+ { id: "srv_1", name: "A", discriminator: "0001", icon: null, mentions: 7 },+ { id: "srv_2", name: "B", discriminator: "0002", icon: null }, // no mentions key],})const { serversQueryFn } = await import("./use-servers")@@ -58,18 +59,39 @@ describe("useServers / serversQueryFn", () => {})describe("useServer / serverQueryFn", () => {- it("returns a single server detail from GET /api/community/servers/:id", async () => {- const detail = { id: "srv_1", name: "Alook", description: "", icon: null, ownerId: "u_1", categories: [] }- apiFetchMock.mockResolvedValueOnce(detail)+ it("composes a single server detail from canonical resources", async () => {+ const detail = { id: "srv_1", name: "Alook", description: "", icon: null, ownerId: "u_1" }+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url === "/api/community/servers") return { servers: [{ ...detail, discriminator: "0001" }] }+ if (url.endsWith("/categories")) return { categories: [{ id: "cat_1", name: "Main", private: 0 }] }+ if (url.endsWith("/channels")) return { channels: [+ { id: "ch_1", name: "general", categoryId: "cat_1" },+ { id: "ch_2", name: "loose", categoryId: null },+ ] }+ if (url.endsWith("/unreads")) return { channelIds: ["ch_1"] }+ throw new Error(`unexpected ${url}`)+ })const { serverQueryFn } = await import("./use-servers")const data = await serverQueryFn("srv_1")()- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1")- expect(data).toEqual(detail)+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/categories")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/channels")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/unreads")+ expect(data).toEqual({ ...detail, categories: [+ { id: "cat_1", name: "Main", private: 0, channels: [{ id: "ch_1", name: "general", categoryId: "cat_1", active: false, unread: true }] },+ { id: "__uncategorized__", name: "", private: 0, channels: [{ id: "ch_2", name: "loose", categoryId: null, active: false, unread: false }] },+ ] })})it("nests the server(id) key under servers() so prefix invalidation cascades", async () => {const detail = { id: "srv_1", name: "Alook", description: "", icon: null, ownerId: "u_1", categories: [] }- apiFetchMock.mockResolvedValueOnce(detail)+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url === "/api/community/servers") return { servers: [{ ...detail, discriminator: "0001" }] }+ if (url.endsWith("/categories")) return { categories: [] }+ if (url.endsWith("/channels")) return { channels: [] }+ if (url.endsWith("/unreads")) return { channelIds: [] }+ throw new Error(`unexpected ${url}`)+ })const { serverQueryFn } = await import("./use-servers")const qc = new QueryClient()const key = communityKeys.server("srv_1")@@ -79,4 +101,17 @@ describe("useServer / serverQueryFn", () => {await qc.invalidateQueries({ queryKey: communityKeys.servers() })expect(qc.getQueryState(key)?.isInvalidated).toBe(true)})++ it("rejects a stale raw unread read instead of caching false read badges", async () => {+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url === "/api/community/servers") return { servers: [{ id: "srv_1", name: "Alook", discriminator: "0001", icon: null, ownerId: "u_1" }] }+ if (url.endsWith("/categories")) return { categories: [] }+ if (url.endsWith("/channels")) return { channels: [{ id: "ch_1", name: "general", categoryId: null }] }+ if (url.endsWith("/unreads")) return { channelIds: [], stale: true }+ throw new Error(`unexpected ${url}`)+ })++ const { serverQueryFn } = await import("./use-servers")+ await expect(serverQueryFn("srv_1")()).rejects.toThrow("stale D1 read")+ })})diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.tsindex eab0da8c6..491b4f41b 100644--- a/src/web/src/hooks/community/use-servers.ts+++ b/src/web/src/hooks/community/use-servers.ts@@ -4,8 +4,8 @@ import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"-import { isServerOwner } from "@alook/shared"-import type { Server, Category } from "@/components/community/_types"+import { isServerOwner, UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"+import type { Server, Category, Channel } from "@/components/community/_types"/*** Fetches the sidebar list of servers the current user is in.@@ -19,9 +19,12 @@ import type { Server, Category } from "@/components/community/_types"type RawServerRow = {id: stringname: string+ discriminator: stringicon: string | nullrole?: stringmentions?: number+ description?: string | null+ ownerId: string}export type ServersResponse = { servers: Server[] }@@ -36,6 +39,7 @@ export const serversQueryFn = async (): Promise<ServersResponse> => {const servers: Server[] = data.servers.map((s) => ({id: s.id,name: s.name,+ discriminator: s.discriminator,initial: avatarInitial(s.name),active: false,// Defensive fallback: the API always projects `mentions` now, but during@@ -83,8 +87,41 @@ export type ServerDetail = {categories: Category[]}-export const serverQueryFn = (serverId: string) => () =>- apiFetch<ServerDetail>(`/api/community/servers/${serverId}`)+type RawChannel = Channel & { categoryId: string | null }+type UnreadResponse = {+ stale?: boolean+ channelIds: string[]+}++export const serverQueryFn = (serverId: string) => async (): Promise<ServerDetail> => {+ const [serverData, categoryData, channelData, unreadData] = await Promise.all([+ apiFetch<{ servers: RawServerRow[] }>("/api/community/servers"),+ apiFetch<{ categories: Array<Omit<Category, "channels"> & { serverId?: string }> }>(`/api/community/servers/${serverId}/categories`),+ apiFetch<{ channels: RawChannel[] }>(`/api/community/servers/${serverId}/channels`),+ apiFetch<UnreadResponse>(`/api/community/servers/${serverId}/unreads`),+ ])+ if (unreadData.stale) throw new Error("stale D1 read")+ const server = serverData.servers.find((row) => row.id === serverId)+ if (!server) throw new Error("server not found")+ const unreadIds = new Set(unreadData.channelIds)+ const channels = channelData.channels.map((channel) => ({ ...channel, active: false, unread: unreadIds.has(channel.id) }))+ const categories: Category[] = categoryData.categories.map((category) => ({+ ...category,+ channels: channels.filter((channel) => channel.categoryId === category.id),+ }))+ const uncategorized = channels.filter((channel) => !channel.categoryId)+ if (uncategorized.length > 0) {+ categories.push({ id: UNCATEGORIZED_CATEGORY_ID, name: "", private: 0, channels: uncategorized })+ }+ return {+ id: server.id,+ name: server.name,+ description: server.description ?? "",+ icon: server.icon,+ ownerId: server.ownerId,+ categories,+ }+}/*** Fetches the detail (categories + channels) for one server. Pass `null` fordiff --git a/src/web/src/hooks/community/use-virtual-cursor-sentinel.test.ts b/src/web/src/hooks/community/use-virtual-cursor-sentinel.test.tsnew file mode 100644index 000000000..1e36f0d25--- /dev/null+++ b/src/web/src/hooks/community/use-virtual-cursor-sentinel.test.ts@@ -0,0 +1,115 @@+import React, { useRef } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++import { useVirtualCursorSentinel } from "./use-virtual-cursor-sentinel"++type Props = {+ edge: "start" | "end"+ hasMore: boolean+ isFetching: boolean+ onLoad: () => void+}++type FakeElement = {+ id: string+ scrollTop: number+ scrollHeight: number+ clientHeight: number+ addEventListener: ReturnType<typeof vi.fn>+ removeEventListener: ReturnType<typeof vi.fn>+}++let intersectionCallback: IntersectionObserverCallback+let disconnect: ReturnType<typeof vi.fn>+let observed: Element | undefined++function Harness(props: Props) {+ const scrollRef = useRef<HTMLDivElement>(null)+ const sentinelRef = useVirtualCursorSentinel({ scrollRef, ...props })+ return React.createElement(+ "div",+ { ref: scrollRef, id: "scroll" },+ React.createElement("div", { ref: sentinelRef, id: "sentinel" }),+ )+}++async function render(props: Props) {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Harness, props), {+ createNodeMock: (element) => ({+ id: element.props.id,+ scrollTop: 0,+ scrollHeight: 1_000,+ clientHeight: 400,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ } satisfies FakeElement),+ })+ })+ return {+ rerender: async (next: Props) => act(async () => {+ renderer.update(React.createElement(Harness, next))+ }),+ unmount: async () => act(async () => renderer.unmount()),+ }+}++function intersect(isIntersecting: boolean) {+ act(() => {+ intersectionCallback(+ [{ isIntersecting, target: observed } as IntersectionObserverEntry],+ {} as IntersectionObserver,+ )+ })+}++describe.each(["start", "end"] as const)("useVirtualCursorSentinel (%s edge)", (edge) => {+ beforeEach(() => {+ disconnect = vi.fn()+ observed = undefined+ class FakeIntersectionObserver {+ constructor(callback: IntersectionObserverCallback) {+ intersectionCallback = callback+ }+ observe(element: Element) { observed = element }+ disconnect() { disconnect() }+ }+ vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver)+ })++ afterEach(() => vi.unstubAllGlobals())++ it("loads on a true intersection and ignores false entries", async () => {+ const onLoad = vi.fn()+ await render({ edge, hasMore: true, isFetching: false, onLoad })+ intersect(false)+ expect(onLoad).not.toHaveBeenCalled()+ intersect(true)+ expect(onLoad).toHaveBeenCalledTimes(1)+ })++ it("replays one busy demand once after settle without cascading", async () => {+ const onLoad = vi.fn()+ const view = await render({ edge, hasMore: true, isFetching: true, onLoad })+ intersect(true)+ intersect(true)+ expect(onLoad).not.toHaveBeenCalled()++ await view.rerender({ edge, hasMore: true, isFetching: false, onLoad })+ expect(onLoad).toHaveBeenCalledTimes(1)+ await view.rerender({ edge, hasMore: true, isFetching: false, onLoad })+ expect(onLoad).toHaveBeenCalledTimes(1)+ })++ it("clears pending demand when hasMore becomes false and disconnects on unmount", async () => {+ const onLoad = vi.fn()+ const view = await render({ edge, hasMore: true, isFetching: true, onLoad })+ intersect(true)+ await view.rerender({ edge, hasMore: false, isFetching: false, onLoad })+ expect(onLoad).not.toHaveBeenCalled()+ await view.unmount()+ expect(disconnect).toHaveBeenCalled()+ })+})diff --git a/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts b/src/web/src/hooks/community/use-virtual-cursor-sentinel.tsnew file mode 100644index 000000000..041b3516f--- /dev/null+++ b/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts@@ -0,0 +1,77 @@+"use client"++import { useEffect, useRef, type RefObject } from "react"++export function useVirtualCursorSentinel({+ scrollRef,+ hasMore,+ isFetching,+ onLoad,+ edge,+}: {+ scrollRef: RefObject<HTMLElement | null>+ hasMore?: boolean+ isFetching?: boolean+ onLoad?: () => void+ edge: "start" | "end"+}) {+ const sentinelRef = useRef<HTMLDivElement>(null)+ const stateRef = useRef({ onLoad, hasMore, isFetching })+ const intersectingRef = useRef(false)+ const pendingDemandRef = useRef(false)+ const wasFetchingRef = useRef(isFetching)++ useEffect(() => { stateRef.current = { onLoad, hasMore, isFetching } })+ useEffect(() => {+ const wasFetching = wasFetchingRef.current+ wasFetchingRef.current = isFetching+ if (!hasMore) {+ pendingDemandRef.current = false+ intersectingRef.current = false+ return+ }+ if (wasFetching && !isFetching && pendingDemandRef.current && intersectingRef.current && onLoad) {+ pendingDemandRef.current = false+ onLoad()+ }+ }, [hasMore, isFetching, onLoad])++ useEffect(() => {+ const element = sentinelRef.current+ const root = scrollRef.current+ if (!element || !root) return+ const observer = new IntersectionObserver((entries) => {+ const state = stateRef.current+ for (const entry of entries) {+ intersectingRef.current = entry.isIntersecting+ if (!entry.isIntersecting || !state.onLoad || !state.hasMore) continue+ if (state.isFetching) pendingDemandRef.current = true+ else state.onLoad()+ break+ }+ }, { root, rootMargin: "200px" })+ let lastScrollTop = root.scrollTop+ const onScroll = () => {+ const next = root.scrollTop+ const movingTowardEdge = edge === "start" ? next < lastScrollTop : next > lastScrollTop+ lastScrollTop = next+ const nearEdge = edge === "start"+ ? next <= 200+ : root.scrollHeight - root.clientHeight - next <= 200+ const state = stateRef.current+ if (movingTowardEdge && nearEdge && intersectingRef.current && state.hasMore && state.isFetching) {+ pendingDemandRef.current = true+ }+ }+ observer.observe(element)+ root.addEventListener("scroll", onScroll, { passive: true })+ return () => {+ pendingDemandRef.current = false+ intersectingRef.current = false+ root.removeEventListener("scroll", onScroll)+ observer.disconnect()+ }+ }, [edge, hasMore, scrollRef])++ return sentinelRef+}diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex 79a4649e2..936fe7008 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -430,7 +430,8 @@ describe("createAuth databaseHooks — user.create.before", () => {const result = await beforeHook({ id: "u_collide", name: "dana", email: "[email protected]" })expect(result.data.discriminator).not.toBe(unsalted)- expect(result.data.discriminator).toBe(computeDiscriminator("u_collide:1"))+ // Salt scheme is now `id:width:attempt`; the first retry stays at width 4.+ expect(result.data.discriminator).toBe(computeDiscriminator("u_collide:4:1", 4))expect(result.data.discriminator).toMatch(/^\d{4}$/)})})diff --git a/src/web/src/lib/community/channel-display-name.test.ts b/src/web/src/lib/community/channel-display-name.test.tsnew file mode 100644index 000000000..8e13fcfee--- /dev/null+++ b/src/web/src/lib/community/channel-display-name.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest"+import { resolveChannelDisplayName } from "./channel-display-name"++describe("resolveChannelDisplayName", () => {+ it("uses opener content for a forum post instead of the copied child channel name", () => {+ expect(resolveChannelDisplayName({+ forumPostTitle: "Edited post title",+ childChannelName: "stale-created-title",+ })).toBe("Edited post title")+ })++ it("does not expose a stale child channel name while the opener is unavailable", () => {+ expect(resolveChannelDisplayName({+ childChannelName: null,+ fallback: "Post",+ })).toBe("Post")+ })++ it("keeps ordinary thread renames local-first", () => {+ expect(resolveChannelDisplayName({+ localName: "Renamed thread",+ childChannelName: "old-thread-name",+ })).toBe("Renamed thread")+ })+})diff --git a/src/web/src/lib/community/channel-display-name.ts b/src/web/src/lib/community/channel-display-name.tsnew file mode 100644index 000000000..7d6e05615--- /dev/null+++ b/src/web/src/lib/community/channel-display-name.ts@@ -0,0 +1,18 @@+export function resolveChannelDisplayName(args: {+ localName?: string | null+ forumPostTitle?: string | null+ topLevelName?: string | null+ childChannelName?: string | null+ forumListName?: string | null+ threadListName?: string | null+ fallback?: string+}): string {+ return args.localName+ ?? args.forumPostTitle+ ?? args.topLevelName+ ?? args.forumListName+ ?? args.threadListName+ ?? args.childChannelName+ ?? args.fallback+ ?? "channel"+}diff --git a/src/web/src/lib/community/channel-ref.test.ts b/src/web/src/lib/community/channel-ref.test.tsindex 1d31006e7..c87b1914e 100644--- a/src/web/src/lib/community/channel-ref.test.ts+++ b/src/web/src/lib/community/channel-ref.test.ts@@ -5,6 +5,7 @@ const directory: ChannelRefDirectory = [{id: "srv_studio",name: "studio",+ discriminator: "0042",channels: [{ id: "chn_general", name: "general" },{ id: "chn_random", name: "random" },@@ -13,42 +14,45 @@ const directory: ChannelRefDirectory = [{id: "srv_other",name: "other",+ discriminator: "12345",channels: [{ id: "chn_dup", name: "general" }],},]describe("resolveChannelRefBase", () => {- it("resolves a bare /server/channel by id for both segments", () => {- const resolved = resolveChannelRefBase(directory, "/srv_studio/chn_general")+ it("resolves a channel id under a handled server", () => {+ const resolved = resolveChannelRefBase(directory, "/studio#0042/chn_general")expect(resolved?.server.id).toBe("srv_studio")expect(resolved?.channel.id).toBe("chn_general")expect(resolved?.threadRootSeq).toBeUndefined()})- it("resolves by exact display name for both segments", () => {- const resolved = resolveChannelRefBase(directory, "/studio/general")+ it("resolves by exact server handle and channel name", () => {+ const resolved = resolveChannelRefBase(directory, "/studio#0042/general")expect(resolved?.server.id).toBe("srv_studio")expect(resolved?.channel.id).toBe("chn_general")})- it("id match takes precedence over a colliding name match", () => {- // A server literally named "srv_studio" would collide with the id lookup- // for the first directory entry — id-first precedence must win.+ it("resolves a handled server with index-aligned ASCII case folding", () => {+ expect(resolveChannelRefBase(directory, "/STUDIO#0042/general")?.server.id).toBe("srv_studio")+ })++ it("rejects a raw server id even when it matches a directory row", () => {const collidingDirectory: ChannelRefDirectory = [- { id: "srv_studio", name: "studio", channels: [{ id: "chn_general", name: "general" }] },- { id: "srv_named_like_id", name: "srv_studio", channels: [{ id: "chn_other", name: "other" }] },+ { id: "srv_studio", name: "studio", discriminator: "0042", channels: [{ id: "chn_general", name: "general" }] },+ { id: "srv_named_like_id", name: "srv_studio", discriminator: "0002", channels: [{ id: "chn_other", name: "other" }] },]- const resolved = resolveChannelRefBase(collidingDirectory, "/srv_studio/chn_general")- expect(resolved?.server.id).toBe("srv_studio")+ expect(resolveChannelRefBase(collidingDirectory, "/srv_studio/chn_general")).toBeNull()})- it("two same-named servers resolve to the first one in directory order", () => {+ it("two same-named servers require a discriminator instead of selecting the first", () => {const dupServers: ChannelRefDirectory = [- { id: "srv_a", name: "dup", channels: [{ id: "chn_a", name: "general" }] },- { id: "srv_b", name: "dup", channels: [{ id: "chn_b", name: "general" }] },+ { id: "srv_a", name: "dup", discriminator: "0042", channels: [{ id: "chn_a", name: "general" }] },+ { id: "srv_b", name: "dup", discriminator: "12345", channels: [{ id: "chn_b", name: "general" }] },]- const resolved = resolveChannelRefBase(dupServers, "/dup/general")- expect(resolved?.server.id).toBe("srv_a")+ expect(resolveChannelRefBase(dupServers, "/dup/general")).toBeNull()+ expect(resolveChannelRefBase(dupServers, "/DUP#0042/general")?.server.id).toBe("srv_a")+ expect(resolveChannelRefBase(dupServers, "/dup#12345/general")?.server.id).toBe("srv_b")})it("two same-named channels within one server resolve to the first one in array order", () => {@@ -56,32 +60,33 @@ describe("resolveChannelRefBase", () => {{id: "srv_studio",name: "studio",+ discriminator: "0042",channels: [{ id: "chn_first", name: "dup" },{ id: "chn_second", name: "dup" },],},]- const resolved = resolveChannelRefBase(dupChannels, "/studio/dup")+ const resolved = resolveChannelRefBase(dupChannels, "/studio#0042/dup")expect(resolved?.channel.id).toBe("chn_first")})it("returns null when the server isn't in the directory", () => {- expect(resolveChannelRefBase(directory, "/nope/general")).toBeNull()+ expect(resolveChannelRefBase(directory, "/nope#0042/general")).toBeNull()})it("returns null when the channel isn't in the resolved server", () => {- expect(resolveChannelRefBase(directory, "/studio/nope")).toBeNull()+ expect(resolveChannelRefBase(directory, "/studio#0042/nope")).toBeNull()})it("resolves the thread form /server/channel/#42 and surfaces threadRootSeq: 42", () => {- const resolved = resolveChannelRefBase(directory, "/studio/general/#42")+ const resolved = resolveChannelRefBase(directory, "/studio#0042/general/#42")expect(resolved?.channel.id).toBe("chn_general")expect(resolved?.threadRootSeq).toBe(42)})it("resolves the thread-reply form /server/channel/#5#42 and surfaces both threadRootSeq and seq", () => {- const resolved = resolveChannelRefBase(directory, "/studio/general/#5#42")+ const resolved = resolveChannelRefBase(directory, "/studio#0042/general/#5#42")expect(resolved?.channel.id).toBe("chn_general")expect(resolved?.threadRootSeq).toBe(5)expect(resolved?.seq).toBe(42)@@ -94,28 +99,33 @@ describe("resolveChannelRefBase", () => {})describe("resolveServerRefBase", () => {- it("resolves a bare /server by id", () => {- expect(resolveServerRefBase(directory, "/srv_studio")?.id).toBe("srv_studio")+ it("rejects a raw server id", () => {+ expect(resolveServerRefBase(directory, "/srv_studio")).toBeNull()})- it("resolves a bare /server by exact display name", () => {- expect(resolveServerRefBase(directory, "/studio")?.id).toBe("srv_studio")+ it("rejects a bare server display name", () => {+ expect(resolveServerRefBase(directory, "/studio")).toBeNull()})- it("id match takes precedence over a colliding name match", () => {+ it("does not treat an id-shaped segment as a server identity", () => {const collidingDirectory: ChannelRefDirectory = [- { id: "srv_studio", name: "studio", channels: [] },- { id: "srv_named_like_id", name: "srv_studio", channels: [] },+ { id: "srv_studio", name: "studio", discriminator: "0042", channels: [] },+ { id: "srv_named_like_id", name: "srv_studio", discriminator: "0002", channels: [] },]- expect(resolveServerRefBase(collidingDirectory, "/srv_studio")?.id).toBe("srv_studio")+ expect(resolveServerRefBase(collidingDirectory, "/srv_studio")).toBeNull()})it("returns null when the server isn't in the directory", () => {- expect(resolveServerRefBase(directory, "/nope")).toBeNull()+ expect(resolveServerRefBase(directory, "/nope#0042")).toBeNull()+ })++ it("resolves four-digit and expanded handles case-insensitively", () => {+ expect(resolveServerRefBase(directory, "/STUDIO#0042")?.id).toBe("srv_studio")+ expect(resolveServerRefBase(directory, "/other#12345")?.id).toBe("srv_other")})it("returns null for a multi-segment ref — that's channelRef's job, not serverRef's", () => {- expect(resolveServerRefBase(directory, "/studio/general")).toBeNull()+ expect(resolveServerRefBase(directory, "/studio#0042/general")).toBeNull()})it("returns null for malformed input", () => {diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.tsindex a3c78b7cd..aad23971a 100644--- a/src/web/src/lib/community/channel-ref.ts+++ b/src/web/src/lib/community/channel-ref.ts@@ -1,4 +1,4 @@-import { parseRef } from "@alook/shared"+import { parseNameAndTag, parseRef } from "@alook/shared"/*** Client-side "directory" of every channel-ref-resolvable server + channel —@@ -6,15 +6,14 @@ import { parseRef } from "@alook/shared"* a fresh fetch per ref. Scoped to whatever servers/channels the client* already has loaded.*- * This file is used by `/c` UI only and MAY accept raw ids (message-ref- * pill rendering, in-window navigation both round-trip channel ids). The- * agent-facing resolver (`resolveChannelByNameForMember`) does NOT accept- * ids — do not use this helper on agent code paths.+ * This file is used by `/c` UI only. Real-server segments still obey the+ * public ref contract and require a name#discriminator handle.*/type ChannelRefDirectoryChannel = { id: string; name: string }export type ChannelRefDirectoryServer = {id: stringname: string+ discriminator: stringchannels: ChannelRefDirectoryChannel[]}export type ChannelRefDirectory = ChannelRefDirectoryServer[]@@ -28,20 +27,10 @@ export type ResolvedChannelRef = {/*** Resolve a raw `/server/channel` (or `/server/channel/#N`) ref string- * against an already-fetched client-side directory. UI-only: tries id- * first, then exact name — the id fallback exists here because pill links- * and in-window navigation store raw channel ids. Purely in-memory (no- * network call) and no ambiguity error. The agent-facing resolver is- * strictly name-only; this helper must not be used on agent code paths.- *- * Ambiguity tie-break (deliberately simpler than the backend): server/channel- * names aren't unique in the schema, and the backend surfaces 2+ name matches- * as a `hint`-carrying 400 the caller must resolve. This function does NOT- * replicate that — it takes the FIRST match in `directory`/`channels` array- * order (plain `Array.prototype.find` semantics) and stops. A duplicate-name- * collision is rare, and the consequence here is just "click navigates to the- * other same-named channel" — not data loss — so this is an accepted,- * documented simplification, not a bug.+ * against an already-fetched client-side directory. Server identity is an+ * exact name#discriminator handle, case-insensitive on name, matching the+ * database unique index. Channel ids remain accepted inside that resolved+ * server for UI-internal navigation.** Returns `null` on any miss (unknown server, unknown channel, or malformed* ref) — this is the false-positive guard the caller (`describeChannelRefPillView`)@@ -58,9 +47,7 @@ export function resolveChannelRefBase(return null}- const server =- directory.find((s) => s.id === parsed.server) ??- directory.find((s) => s.name === parsed.server)+ const server = resolveDirectoryServer(directory, parsed.server)if (!server) return nullconst channel =@@ -79,9 +66,7 @@ export function resolveChannelRefBase(/*** Resolve a bare `/server` ref (one segment, no channel — `parseRef` throws* on this shape since it requires `/<server>/<channel>`) against the- * already-fetched directory. UI-only: id-then-exact-name lookup with the- * same duplicate-name simplification as `resolveChannelRefBase` — see that- * function's doc comment. Not for agent code paths.+ * already-fetched directory. Only a name#discriminator handle resolves.*/export function resolveServerRefBase(directory: ChannelRefDirectory,@@ -91,9 +76,21 @@ export function resolveServerRefBase(const body = ref.slice(1)if (!body || body.includes("/")) return null- return (- directory.find((s) => s.id === body) ??- directory.find((s) => s.name === body) ??- null- )+ return resolveDirectoryServer(directory, body)+}++function resolveDirectoryServer(+ directory: ChannelRefDirectory,+ segment: string,+): ChannelRefDirectoryServer | null {+ const handle = parseNameAndTag(segment)+ if (!handle) return null+ return directory.find((server) =>+ asciiNoCase(server.name) === asciiNoCase(handle.name)+ && server.discriminator === handle.discriminator+ ) ?? null+}++function asciiNoCase(value: string): string {+ return value.replace(/[A-Z]/g, (char) => char.toLowerCase())}diff --git a/src/web/src/lib/community/channel-write-guard.test.ts b/src/web/src/lib/community/channel-write-guard.test.tsindex 9f07421e3..db8d1fe7a 100644--- a/src/web/src/lib/community/channel-write-guard.test.ts+++ b/src/web/src/lib/community/channel-write-guard.test.ts@@ -8,18 +8,12 @@ import {} from "./channel-write-guard"describe("requireMessageBearingSurface", () => {- it("accepts message-bearing surfaces (text, forum_post, thread)", () => {- for (const t of ["text", "forum_post", "thread"]) {+ it("accepts text/forum/thread — every stored type except dm", () => {+ for (const t of ["text", "forum", "thread"]) {expect(requireMessageBearingSurface(t).ok).toBe(true)}})- it("rejects a forum top-level (post index, not a message surface) with 400", () => {- const r = requireMessageBearingSurface("forum")- expect(r.ok).toBe(false)- if (!r.ok) expect(r.status).toBe(400)- })-it("rejects a DM hitting a generic channel route with 400 (block-bypass guard)", () => {const r = requireMessageBearingSurface("dm")expect(r.ok).toBe(false)@@ -30,41 +24,36 @@ describe("requireMessageBearingSurface", () => {expect(requireMessageBearingSurface(null).ok).toBe(false)expect(requireMessageBearingSurface(undefined).ok).toBe(false)expect(requireMessageBearingSurface("bogus").ok).toBe(false)+ expect(requireMessageBearingSurface("forum_post").ok).toBe(false)})})describe("rejectDmOnGenericChannelRoute", () => {it("rejects only dm; passes every non-dm type", () => {expect(rejectDmOnGenericChannelRoute("dm").ok).toBe(false)- for (const t of ["text", "forum", "forum_post", "thread", null, undefined]) {+ for (const t of ["text", "forum", "thread", null, undefined]) {expect(rejectDmOnGenericChannelRoute(t).ok).toBe(true)}})})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"]) {+ it("accepts every message-bearing surface incl. dm and forum (reacting in a DM is legit)", () => {+ for (const t of ["text", "forum", "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"]) {+ it("accepts text/thread/forum", () => {+ for (const t of ["text", "forum", "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]) {+ it("rejects dm (governance model does not fit) with 400", () => {+ for (const t of ["dm", null, undefined]) {const r = requirePinnableSurface(t)expect(r.ok).toBe(false)if (!r.ok) expect(r.status).toBe(400)@@ -73,13 +62,12 @@ describe("requirePinnableSurface", () => {})describe("requireChildSurface", () => {- it("accepts thread and forum_post", () => {+ it("accepts thread", () => {expect(requireChildSurface("thread").ok).toBe(true)- expect(requireChildSurface("forum_post").ok).toBe(true)})- it("rejects top-level and dm types with 400", () => {- for (const t of ["text", "forum", "dm", null, undefined]) {+ it("rejects top-level, dm, and forum_post (no longer a valid type) with 400", () => {+ for (const t of ["text", "forum", "dm", "forum_post", null, undefined]) {const r = requireChildSurface(t)expect(r.ok).toBe(false)if (!r.ok) expect(r.status).toBe(400)diff --git a/src/web/src/lib/community/channel-write-guard.ts b/src/web/src/lib/community/channel-write-guard.tsindex 7ec20ae15..0b902bb66 100644--- a/src/web/src/lib/community/channel-write-guard.ts+++ b/src/web/src/lib/community/channel-write-guard.ts@@ -1,4 +1,4 @@-import { isMessageBearingSurface, isThread, isForumPost, isDm } from "@alook/shared"+import { isMessageBearingSurface, isThread, isDm } from "@alook/shared"type GuardOk = { ok: true }type GuardErr = { ok: false; status: 400; error: string }@@ -11,7 +11,7 @@ export function rejectDmOnGenericChannelRoute(channelType: string | null | undefreturn {ok: false,status: 400,- error: "this is a direct message — use the DM endpoints (/api/community/dm/[id]/*), which enforce block checks.",+ error: "this is a direct message — address it through the canonical channel door (/api/community/channels/[id]/*), which dispatches DM block checks by surface trait.",}}@@ -22,7 +22,7 @@ export function requireMessageBearingSurface(channelType: string | null | undefireturn {ok: false,status: 400,- error: "cannot post a message here — a forum top-level holds posts, not messages. Create a post (a title is required).",+ error: "cannot post a message here",}}@@ -31,13 +31,13 @@ export function requireReactableSurface(channelType: string | null | undefined):return {ok: false,status: 400,- error: "a forum top-level holds posts, not messages — nothing to react to here",+ error: "nothing to react to here",}}export function requireChildSurface(channelType: string | null | undefined): WriteGuardResult {- if (isThread(channelType) || isForumPost(channelType)) return pass- return { ok: false, status: 400, error: "not a thread or forum post" }+ if (isThread(channelType)) return pass+ return { ok: false, status: 400, error: "not a thread" }}export function requirePinnableSurface(channelType: string | null | undefined): WriteGuardResult {@@ -45,7 +45,7 @@ export function requirePinnableSurface(channelType: string | null | undefined):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 { ok: false, status: 400, error: "nothing to pin here" }}return pass}diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.tsindex 2aef4d31b..0e6906989 100644--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts@@ -3,6 +3,7 @@ import { unified } from "unified"import remarkParse from "remark-parse"import type { Root, PhrasingContent } from "mdast"import { chatSyntaxPlugin } from "./chat-syntax-plugin"+import { buildCliSystemPrompt } from "../../../../daemon/src/drivers/systemPrompt"import type { MentionNode, ChannelRefNode, ServerRefNode } from "./chat-syntax-plugin"function parse(md: string): Root {@@ -16,6 +17,28 @@ function paragraphChildren(tree: Root): PhrasingContent[] {return para.children}+describe("CLI prompt ref examples — tokenizer contract", () => {+ it("turns every emitted copyable example into the intended ref pill", () => {+ const prompt = buildCliSystemPrompt({+ agentId: "agent_1",+ workspacePath: "/tmp/workspace",+ } as Parameters<typeof buildCliSystemPrompt>[0])+ const examples = prompt.split("\n").filter((line) =>+ line.startsWith("/Alook#1234") || line.startsWith("/.dm/alice#0042"),+ )++ expect(examples).toHaveLength(6)+ for (const example of examples) {+ const children = paragraphChildren(parse(example))+ expect(children).toHaveLength(1)+ expect(children[0]).toMatchObject({+ type: example === "/Alook#1234" ? "serverRef" : "channelRef",+ value: example,+ })+ }+ })+})+describe("chatSyntaxPlugin — mention", () => {it("a hand-typed bare @name (no #dddd) is NOT a mention — stays plain text", () => {const children = paragraphChildren(parse("hi @Lindsay"))@@ -51,14 +74,14 @@ describe("chatSyntaxPlugin — mention", () => {expect(mentions.map((m) => `${m.value}#${m.discriminator}`)).toEqual(["@Alice#0001", "@Bob#0002"])})- it("does not truncate a 5+ digit run into a false-positive discriminator (still not a mention)", () => {- // "#00423" is not a 4-digit tag, so "@Gus#00423" is NOT a mention. A bare- // `#N` is no longer a message ref (message-ref-upgrade.md), so the run stays- // plain text. The key guarantee this test protects is unchanged: it is NOT- // parsed as a mention with a truncated discriminator.+ it("treats a 5+ digit run as a widened discriminator (variable-width disc), never truncated", () => {+ // Variable-width disc (A): "#00423" is now a valid 5-digit tag, so+ // "@Gus#00423" IS a mention carrying the FULL 5-digit disc — never+ // truncated to a 4-digit "0042". Prose like "issue #12345" is still safe:+ // no "@" prefix + the "#" is space-preceded, so it isn't swallowed.const children = paragraphChildren(parse("hi @Gus#00423"))- expect(children.some((c) => c.type === "mention")).toBe(false)- expect(children.every((c) => c.type === "text")).toBe(true)+ const mention = children.find((c) => c.type === "mention")+ expect(mention).toMatchObject({ type: "mention", value: "@Gus", discriminator: "00423" })})it("flags @everyone", () => {@@ -104,14 +127,14 @@ describe("chatSyntaxPlugin — mention", () => {describe("chatSyntaxPlugin — channelRef", () => {it("wraps /server/channel preceded by a space or at start-of-string", () => {- expect(paragraphChildren(parse("see /studio/general"))[1]).toMatchObject({ type: "channelRef", value: "/studio/general" })- expect(paragraphChildren(parse("/studio/general"))[0]).toMatchObject({ type: "channelRef", value: "/studio/general" })+ expect(paragraphChildren(parse("see /studio#0042/general"))[1]).toMatchObject({ type: "channelRef", value: "/studio#0042/general" })+ expect(paragraphChildren(parse("/studio#0042/general"))[0]).toMatchObject({ type: "channelRef", value: "/studio#0042/general" })})- it("leaves text/studio/general (no leading space) untouched", () => {- const children = paragraphChildren(parse("text/studio/general"))+ it("leaves text/studio#0042/general (no leading space) untouched", () => {+ const children = paragraphChildren(parse("text/studio#0042/general"))expect(children).toHaveLength(1)- expect(children[0]).toMatchObject({ type: "text", value: "text/studio/general" })+ expect(children[0]).toMatchObject({ type: "text", value: "text/studio#0042/general" })})it("does NOT wrap a 3+-segment docs-style path — trailing /segment fails the terminator boundary", () => {@@ -120,46 +143,46 @@ describe("chatSyntaxPlugin — channelRef", () => {})it("still wraps a 2-segment ref followed by punctuation (period, comma, close-paren)", () => {- const children = paragraphChildren(parse("see /studio/general."))+ const children = paragraphChildren(parse("see /studio#0042/general."))expect(children.map((c) => c.type)).toEqual(["text", "channelRef", "text"])- expect(children[1]).toMatchObject({ value: "/studio/general" })+ expect(children[1]).toMatchObject({ value: "/studio#0042/general" })expect(children[2]).toMatchObject({ type: "text", value: "." })})- it("wraps the thread form /studio/general/#42", () => {- const children = paragraphChildren(parse("see /studio/general/#42"))- expect(children[1]).toMatchObject({ type: "channelRef", value: "/studio/general/#42" })+ it("wraps the thread form /studio#0042/general/#42", () => {+ const children = paragraphChildren(parse("see /studio#0042/general/#42"))+ expect(children[1]).toMatchObject({ type: "channelRef", value: "/studio#0042/general/#42" })})- it("wraps the thread-reply form /studio/general/#5#42 as a single channelRef node", () => {- const children = paragraphChildren(parse("see /studio/general/#5#42 done"))+ it("wraps the thread-reply form /studio#0042/general/#5#42 as a single channelRef node", () => {+ const children = paragraphChildren(parse("see /studio#0042/general/#5#42 done"))const refs = children.filter((c): c is ChannelRefNode => c.type === "channelRef")expect(refs).toHaveLength(1)- expect(refs[0]).toMatchObject({ type: "channelRef", value: "/studio/general/#5#42" })+ expect(refs[0]).toMatchObject({ type: "channelRef", value: "/studio#0042/general/#5#42" })})- it("wraps the channel-message form /studio/general#42 (seq glued to the channel)", () => {+ it("wraps the channel-message form /studio#0042/general#42 (seq glued to the channel)", () => {// message-ref-upgrade.md: `/server/channel#N` is a channel-MESSAGE ref. The// 2nd segment stops at `#` (REF_SEG excludes `#`), so `#42` falls into the// suffix group — the whole span is ONE channelRef (rendered as a pill with a// trailing `#42` cursor, resolved.seq = 42).- const children = paragraphChildren(parse("see /studio/general#42 done"))+ const children = paragraphChildren(parse("see /studio#0042/general#42 done"))const refs = children.filter((c): c is ChannelRefNode => c.type === "channelRef")expect(refs).toHaveLength(1)- expect(refs[0]).toMatchObject({ type: "channelRef", value: "/studio/general#42" })+ expect(refs[0]).toMatchObject({ type: "channelRef", value: "/studio#0042/general#42" })})it("does not wrap a mid-string path as a channelRef, and a bare #N is now plain text", () => {// The channelRef pass requires a leading space, so `text/.../#5#42` is NOT a// channelRef. And a bare `#42` is no longer a message ref (message-ref-// upgrade.md), so nothing pills — the whole run is plain text.- const children = paragraphChildren(parse("text/studio/general/#5#42"))+ const children = paragraphChildren(parse("text/studio#0042/general/#5#42"))expect(children.some((c) => c.type === "channelRef")).toBe(false)expect(children.every((c) => c.type === "text")).toBe(true)})it("leaves a channel-ref-shaped path inside inline code literal", () => {- const children = paragraphChildren(parse("`/studio/general`"))+ const children = paragraphChildren(parse("`/studio#0042/general`"))expect(children.map((c) => c.type)).toEqual(["inlineCode"])})@@ -175,76 +198,76 @@ describe("chatSyntaxPlugin — channelRef", () => {it("wraps a ref with a Chinese channel name — slugify preserves CJK, the charset must match it", () => {// The bug Shelly reported (#194): names are slugified display names, not// nanoid ids; slugify keeps CJK/emoji, so an ASCII-only charset dropped the pill.- expect(paragraphChildren(parse("see /Gus/架构"))[1]).toMatchObject({ type: "channelRef", value: "/Gus/架构" })- expect(paragraphChildren(parse("/Gus/架构"))[0]).toMatchObject({ type: "channelRef", value: "/Gus/架构" })+ expect(paragraphChildren(parse("see /Gus#0042/架构"))[1]).toMatchObject({ type: "channelRef", value: "/Gus#0042/架构" })+ expect(paragraphChildren(parse("/Gus#0042/架构"))[0]).toMatchObject({ type: "channelRef", value: "/Gus#0042/架构" })})it("wraps a ref with emoji in the server segment (slugify keeps emoji, e.g. \"总部 🎉\" → \"总部-🎉\")", () => {- const children = paragraphChildren(parse("go /总部-🎉/general now"))- expect(children.find((c) => c.type === "channelRef")).toMatchObject({ value: "/总部-🎉/general" })+ const children = paragraphChildren(parse("go /总部-🎉#0042/general now"))+ expect(children.find((c) => c.type === "channelRef")).toMatchObject({ value: "/总部-🎉#0042/general" })})it("wraps a ref with accented-Latin name (café)", () => {- expect(paragraphChildren(parse("see /studio/café done"))[1]).toMatchObject({ type: "channelRef", value: "/studio/café" })+ expect(paragraphChildren(parse("see /studio#0042/café done"))[1]).toMatchObject({ type: "channelRef", value: "/studio#0042/café" })})- it("wraps the thread form on a Unicode name — /Gus/架构/#42", () => {- expect(paragraphChildren(parse("see /Gus/架构/#42"))[1]).toMatchObject({ type: "channelRef", value: "/Gus/架构/#42" })+ it("wraps the thread form on a Unicode name — /Gus#0042/架构/#42", () => {+ expect(paragraphChildren(parse("see /Gus#0042/架构/#42"))[1]).toMatchObject({ type: "channelRef", value: "/Gus#0042/架构/#42" })})it("still terminates a Unicode ref at a trailing ASCII period — the period is not swallowed", () => {// Regression guard for the Unicode charset: the segment class must stay// disjoint from the terminator punctuation, else a greedy match eats the `.`.- const children = paragraphChildren(parse("see /Gus/架构."))+ const children = paragraphChildren(parse("see /Gus#0042/架构."))expect(children.map((c) => c.type)).toEqual(["text", "channelRef", "text"])- expect(children[1]).toMatchObject({ value: "/Gus/架构" })+ expect(children[1]).toMatchObject({ value: "/Gus#0042/架构" })expect(children[2]).toMatchObject({ type: "text", value: "." })})it("terminates a Unicode ref at a trailing FULL-WIDTH period 。 — the most common CJK sentence ender", () => {// Blair's QA flag: a Chinese sentence ends in 。, so the ref-in-a-sentence- // shape `看 /Gus/架构。` is extremely common. The full-width 。 must be a+ // shape `看 /Gus#0042/架构。` is extremely common. The full-width 。 must be a// terminator (in BOTH the segment-exclusion and the lookahead — the segment// is greedy, so lookahead-only would let it swallow the 。), else the pill// target becomes "架构。" and click/highlight mis-targets the real channel.- const children = paragraphChildren(parse("看 /Gus/架构。"))+ const children = paragraphChildren(parse("看 /Gus#0042/架构。"))expect(children.map((c) => c.type)).toEqual(["text", "channelRef", "text"])- expect(children[1]).toMatchObject({ value: "/Gus/架构" })+ expect(children[1]).toMatchObject({ value: "/Gus#0042/架构" })expect(children[2]).toMatchObject({ type: "text", value: "。" })})it("terminates at other full-width CJK terminators (!? etc.)", () => {- expect(paragraphChildren(parse("用 /Gus/架构!"))[1]).toMatchObject({ value: "/Gus/架构" })- expect(paragraphChildren(parse("是 /Gus/架构?好"))[1]).toMatchObject({ value: "/Gus/架构" })+ expect(paragraphChildren(parse("用 /Gus#0042/架构!"))[1]).toMatchObject({ value: "/Gus#0042/架构" })+ expect(paragraphChildren(parse("是 /Gus#0042/架构?好"))[1]).toMatchObject({ value: "/Gus#0042/架构" })})})describe("chatSyntaxPlugin — serverRef", () => {it("wraps a bare /server preceded by a space or at start-of-string", () => {- expect(paragraphChildren(parse("check /studio"))[1]).toMatchObject({ type: "serverRef", value: "/studio" })- expect(paragraphChildren(parse("/studio"))[0]).toMatchObject({ type: "serverRef", value: "/studio" })+ expect(paragraphChildren(parse("check /studio#0042"))[1]).toMatchObject({ type: "serverRef", value: "/studio#0042" })+ expect(paragraphChildren(parse("/studio#0042"))[0]).toMatchObject({ type: "serverRef", value: "/studio#0042" })})it("does not double-match the first segment of a /server/channel ref", () => {- const children = paragraphChildren(parse("see /studio/general"))+ const children = paragraphChildren(parse("see /studio#0042/general"))expect(children.map((c) => c.type)).toEqual(["text", "channelRef"])expect(children.some((c) => c.type === "serverRef")).toBe(false)})- it("leaves text/studio (no leading space) untouched", () => {- const children = paragraphChildren(parse("text/studio"))+ it("leaves text/studio#0042 (no leading space) untouched", () => {+ const children = paragraphChildren(parse("text/studio#0042"))expect(children).toHaveLength(1)- expect(children[0]).toMatchObject({ type: "text", value: "text/studio" })+ expect(children[0]).toMatchObject({ type: "text", value: "text/studio#0042" })})it("still wraps a bare ref followed by punctuation", () => {- const children = paragraphChildren(parse("see /studio."))+ const children = paragraphChildren(parse("see /studio#0042."))expect(children.map((c) => c.type)).toEqual(["text", "serverRef", "text"])- expect(children[1]).toMatchObject({ value: "/studio" })+ expect(children[1]).toMatchObject({ value: "/studio#0042" })})it("leaves a server-ref-shaped path inside inline code literal", () => {- const children = paragraphChildren(parse("`/studio`"))+ const children = paragraphChildren(parse("`/studio#0042`"))expect(children.map((c) => c.type)).toEqual(["inlineCode"])})@@ -255,18 +278,18 @@ describe("chatSyntaxPlugin — serverRef", () => {})it("wraps a bare Unicode /server ref (Chinese, emoji)", () => {- expect(paragraphChildren(parse("check /架构"))[1]).toMatchObject({ type: "serverRef", value: "/架构" })- expect(paragraphChildren(parse("check /总部-🎉 here"))[1]).toMatchObject({ type: "serverRef", value: "/总部-🎉" })+ expect(paragraphChildren(parse("check /架构#0042"))[1]).toMatchObject({ type: "serverRef", value: "/架构#0042" })+ expect(paragraphChildren(parse("check /总部-🎉#0042 here"))[1]).toMatchObject({ type: "serverRef", value: "/总部-🎉#0042" })})it("terminates a Unicode /server ref at trailing punctuation (ASCII + full-width)", () => {- const ascii = paragraphChildren(parse("check /架构."))+ const ascii = paragraphChildren(parse("check /架构#0042."))expect(ascii.map((c) => c.type)).toEqual(["text", "serverRef", "text"])- expect(ascii[1]).toMatchObject({ value: "/架构" })+ expect(ascii[1]).toMatchObject({ value: "/架构#0042" })- const cjk = paragraphChildren(parse("去 /架构。"))+ const cjk = paragraphChildren(parse("去 /架构#0042。"))expect(cjk.map((c) => c.type)).toEqual(["text", "serverRef", "text"])- expect(cjk[1]).toMatchObject({ value: "/架构" })+ expect(cjk[1]).toMatchObject({ value: "/架构#0042" })expect(cjk[2]).toMatchObject({ type: "text", value: "。" })})})@@ -290,16 +313,16 @@ describe("chatSyntaxPlugin — message ref (full-path only; bare #N deprecated)"})it("a channel-message ref /server/channel#N is a channelRef carrying the seq", () => {- const children = paragraphChildren(parse("see /studio/general#42 done"))+ const children = paragraphChildren(parse("see /studio#0042/general#42 done"))const ref = children.find((c): c is ChannelRefNode => c.type === "channelRef")- expect(ref).toMatchObject({ type: "channelRef", value: "/studio/general#42" })+ expect(ref).toMatchObject({ type: "channelRef", value: "/studio#0042/general#42" })})it("a thread-message ref /server/channel/#N#M stays a single channelRef", () => {- const children = paragraphChildren(parse("see /studio/general/#5#42 done"))+ const children = paragraphChildren(parse("see /studio#0042/general/#5#42 done"))const refs = children.filter((c): c is ChannelRefNode => c.type === "channelRef")expect(refs).toHaveLength(1)- expect(refs[0]).toMatchObject({ value: "/studio/general/#5#42" })+ expect(refs[0]).toMatchObject({ value: "/studio#0042/general/#5#42" })})it("a valid @name#0042 handle is still a mention, never split (mention pass runs first)", () => {@@ -331,30 +354,30 @@ describe("chatSyntaxPlugin — message ref (full-path only; bare #N deprecated)"describe("chatSyntaxPlugin — mixed", () => {it("handles a mix of mention, channelRef, and unrelated formatting in one message", () => {- const children = paragraphChildren(parse("Here's the **setup**: `pnpm install` ping @Gus#0042 in /studio/dev"))+ const children = paragraphChildren(parse("Here's the **setup**: `pnpm install` ping @Gus#0042 in /studio#0042/dev"))const types = children.map((c) => c.type)expect(types).toContain("strong")expect(types).toContain("inlineCode")const mention = children.find((c): c is MentionNode => c.type === "mention")expect(mention).toMatchObject({ value: "@Gus", discriminator: "0042" })const channelRef = children.find((c): c is ChannelRefNode => c.type === "channelRef")- expect(channelRef).toMatchObject({ value: "/studio/dev" })+ expect(channelRef).toMatchObject({ value: "/studio#0042/dev" })})it("handles a mention and a bare serverRef together", () => {- const children = paragraphChildren(parse("ping @Gus#0042, see /studio for context"))+ const children = paragraphChildren(parse("ping @Gus#0042, see /studio#0042 for context"))const mention = children.find((c): c is MentionNode => c.type === "mention")expect(mention).toMatchObject({ value: "@Gus", discriminator: "0042" })const serverRef = children.find((c): c is ServerRefNode => c.type === "serverRef")- expect(serverRef).toMatchObject({ value: "/studio" })+ expect(serverRef).toMatchObject({ value: "/studio#0042" })})it("handles mention, a full-path message ref, and a channel ref together", () => {- const children = paragraphChildren(parse("@Alice#0001 check /studio/general#42 in /studio/dev"))+ const children = paragraphChildren(parse("@Alice#0001 check /studio#0042/general#42 in /studio#0042/dev"))const mention = children.find((c): c is MentionNode => c.type === "mention")expect(mention).toMatchObject({ value: "@Alice", discriminator: "0001" })const refs = children.filter((c): c is ChannelRefNode => c.type === "channelRef")// Two channelRefs: the message ref (with seq) and the plain channel ref.- expect(refs.map((r) => r.value)).toEqual(["/studio/general#42", "/studio/dev"])+ expect(refs.map((r) => r.value)).toEqual(["/studio#0042/general#42", "/studio#0042/dev"])})})diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.tsindex d180cc1d9..66e07fffc 100644--- a/src/web/src/lib/community/chat-syntax-plugin.ts+++ b/src/web/src/lib/community/chat-syntax-plugin.ts@@ -6,8 +6,8 @@ import type { Plugin } from "unified"import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"import type { SpoilerNode } from "./spoiler-syntax"-// Chat-only syntax (`||spoiler||`, `@mention`, `/server/channel` and bare-// `/server` refs), parsed as real markdown AST nodes rather than+// Chat-only syntax (`||spoiler||`, `@mention`, `/server#disc/channel` and bare+// `/server#disc` refs), parsed as real markdown AST nodes rather than// string-spliced HTML tags fed through `rehype-raw`. `channelRef`/`serverRef`// content is a nanoid charset (`[A-Za-z0-9_-]`); a member `mention` is// `@<name>#dddd` where the name may contain spaces but never a markdown@@ -19,26 +19,25 @@ import type { SpoilerNode } from "./spoiler-syntax"// comment for why find-and-replace cannot handle spoilers containing nested// formatting.-// Mirrors `CHANNEL_REF_REGEX`'s old doc comment: matches a `/server/channel`,-// `/server/channel/#N` (thread), or `/server/channel/#N#M` (thread reply,+// Matches a `/server#disc/channel`, `/server#disc/channel/#N` (thread), or+// `/server#disc/channel/#N#M` (thread reply,// see plans/agent-thread-emoji-react.md) ref — the CLI's path grammar// (`parseRef`/`formatRef` in `community-cli-contract.ts`). Segment charset// `[^\s/#.,;:!?)\]]+` = "any char slugify can emit, minus the terminator-// punctuation": server/channel names travel on the wire as their SLUGIFIED-// DISPLAY NAME, not an id (see the round-trip contract in-// `channel-ref-extension.ts`'s `renderText` doc + `slugify.ts`), and slugify-// preserves Unicode — it strips only `/` and `#` and collapses whitespace. So+// punctuation": server names travel with their required discriminator and+// channel names remain wire names rather than ids. Name segments preserve+// Unicode; normalization strips only `/` and `#` and collapses whitespace. So// the base of the class is the inverse of what slugify removes (everything// except whitespace, `/`, `#`), which is what lets non-ASCII names-// (`/Gus/架构`, `/总部-🎉/general`, `/studio/café`) render as pills like their+// (`/Gus#0042/架构`, `/总部-🎉#0042/general`, `/studio#0042/café`) render as pills like their// ASCII kin — matching the `\p{L}` + `u` treatment `MENTION_RE` already uses// for `@names`. We ALSO exclude the trailing-boundary punctuation (`REF_TERM`// below) from the segment class: the old ASCII class `[A-Za-z0-9_-]` happened// to be disjoint from the terminator set, and that disjointness is// load-bearing — the segment class `[^\s/#…]+` is GREEDY, so without excluding// a terminator char from the segment it gets eaten BEFORE the lookahead can-// fire (a greedy segment swallows the sentence period in `/studio/general.`;-// same for the full-width `。` in `看 /Gus/架构。`). So a terminator must live+// fire (a greedy segment swallows the sentence period in `/studio#0042/general.`;+// same for the full-width `。` in `看 /Gus#0042/架构。`). So a terminator must live// in BOTH places: excluded from the segment (so the match stops there) AND// present in the lookahead (so stopping there is legal). slugify never emits a// leading/trailing terminator anyway, and a mid-name terminator is a rare@@ -49,8 +48,8 @@ import type { SpoilerNode } from "./spoiler-syntax"// as the segment-class exclusion (`REF_SEG`) and the trailing lookahead, so// the two can't drift out of the disjointness the boundary relies on. It// covers ASCII `.,;:!?)]` AND the common FULL-WIDTH CJK sentence punctuation-// `。!?;:、)】`: a Chinese sentence ends in `。`, so `看 /Gus/架构。` must-// yield pill `/Gus/架构` + literal `。`, not swallow the period — full-width+// `。!?;:、)】`: a Chinese sentence ends in `。`, so `看 /Gus#0042/架构。` must+// yield pill `/Gus#0042/架构` + literal `。`, not swallow the period — full-width// terminators matter MORE here since this fix targets CJK names (Blair's QA// flag). Kept as a string spliced into `new RegExp(...)` so the shared set is// declared once.@@ -68,24 +67,25 @@ import type { SpoilerNode } from "./spoiler-syntax"// group did. `u` flag for correct astral/emoji handling.const REF_TERM = ".,;:!?)\\]\\u3002\\uFF01\\uFF1F\\uFF1B\\uFF1A\\u3001\\uFF09\\u3011"const REF_SEG = `[^\\s/#${REF_TERM}]+`-// `/server/channel` plus an optional message/thread suffix. The suffix has two+const HANDLE_SEG = `${REF_SEG}#\\d{4,}`+// `/server#disc/channel` plus an optional message/thread suffix. The suffix has two// branches (message-ref-upgrade.md):// `#\d+` — a channel-MESSAGE ref, seq glued straight to the channel-// (`/server/channel#N`). Single seq ONLY — `#N#M` without a+// (`/server#disc/channel#N`). Single seq ONLY — `#N#M` without a// slash is not a valid form (Cecilia #295, load-bearing).-// `/#\d+(?:#\d+)?` — a THREAD (`/server/channel/#N`) or thread-message-// (`/server/channel/#N#M`) ref; the inner `#M` lives only+// `/#\d+(?:#\d+)?` — a THREAD (`/server#disc/channel/#N`) or thread-message+// (`/server#disc/channel/#N#M`) ref; the inner `#M` lives only// on this slash branch.// `REF_SEG` excludes `#`, so the 2nd segment stops at the `#` and the seq falls// cleanly into the suffix group. The leading `(?<=^|\s)` prefix-anchor means this// only ever matches a full path — never a bare `#` — which is what lets us drop// the old bare-`#N` MESSAGE_REF pass and root-solve the disambiguation Gus flagged.-const CHANNEL_REF_RE = new RegExp(`(?<=^|\\s)/${REF_SEG}/${REF_SEG}(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu")+const CHANNEL_REF_RE = new RegExp(`(?<=^|\\s)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu")// A bare `/server` ref — one segment, no channel. Same boundary lookaround as// `CHANNEL_REF_RE` (leading `(?<=^|\s)`, trailing `REF_TERM`), which already// excludes being followed by another `/segment` — so this never double-matches-// the first segment of a genuine `/server/channel` ref (that trailing boundary+// the first segment of a genuine `/server#disc/channel` ref (that trailing boundary// fails when the next char is `/`, and the segment class backtracking can't// produce a shorter match that satisfies it either, since every character up// to the next `/` is in the segment charset). Same `REF_SEG`/`REF_TERM` +@@ -93,10 +93,10 @@ const CHANNEL_REF_RE = new RegExp(`(?<=^|\\s)/${REF_SEG}/${REF_SEG}(?:#\\d+|/#\\// terminators). Registered after `CHANNEL_REF_RE` in `chatSyntaxPlugin`'s// pairs list purely for readability (server-only is the "smaller" grammar);// the boundary already makes the ordering non-load-bearing for correctness.-const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${REF_SEG}(?=\\s|$|[${REF_TERM}])`, "gu")+const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu")// (The old bare-`#N` MESSAGE_REF_RE was removed in message-ref-upgrade.md — a-// message ref is now always the full path `/server/channel#N`, matched by+// message ref is now always the full path `/server#disc/channel#N`, matched by// CHANNEL_REF_RE's suffix group above. A bare `#N` now renders as plain text.// This kills the fragile "works only because it's the last consumption pass"// disambiguation: the prefix-anchored full-path form can't collide with a bare@@ -118,11 +118,12 @@ const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${REF_SEG}(?=\\s|$|[${REF_TERM}])`,// name-run may safely include spaces/unicode: `[^@#\n\r]*[^@#\n\r\s]`. The// final class forces the name-run to END in a non-whitespace char, so// ordinary prose like `@bob check issue #0042` is NOT swallowed into one-// pill (the only `#` there is space-preceded). `(?!\d)` after `#dddd` stops-// a 5+-digit run from matching a 4-digit tag (`@Gus#00423`). A hand-typed-// bare `@Alice` (no tag) is intentionally NOT a mention — it stays text.+// pill (the only `#` there is space-preceded). The tag is `#dddd` with 4++// digits (variable-width disc); the digit run is greedy so a widened 5+-digit+// tag matches in full. A hand-typed bare `@Alice` (no tag) is intentionally+// NOT a mention — it stays text.const MENTION_RE =- /@everyone(?![\p{L}\p{N}_-])|@[^@#\n\r]*[^@#\n\r\s]#\d{4}(?!\d)/gu+ /@everyone(?![\p{L}\p{N}_-])|@[^@#\n\r]*[^@#\n\r\s]#\d{4,}/gu/** mdast node produced by `@name`/`@name#0042`/`@everyone`. */export interface MentionNode {@@ -130,11 +131,11 @@ export interface MentionNode {/** Display name — `#dddd` discriminator, if present, is stripped from here (matches the old `<mention>` tag's content). */value: stringeveryone: boolean- /** The 4-digit discriminator, if the mention carried one (never set for `@everyone`). */+ /** The discriminator (4+ decimal digits), if the mention carried one (never set for `@everyone`). */discriminator?: string}-/** mdast node produced by a `/server/channel` or `/server/channel/#N` ref. */+/** mdast node produced by a `/server#disc/channel` or `/server#disc/channel/#N` ref. */export interface ChannelRefNode {type: "channelRef"value: string@@ -161,7 +162,7 @@ declare module "mdast" {// `ignore` list mirrors mdast-util-find-and-replace's own default protection// for GFM autolinks/definitions, plus `code`/`inlineCode` so `@fake-mention`,-// `#0042`, `/server/channel`, and `||spoiler||` all stay literal inside a+// `#0042`, `/server#disc/channel`, and `||spoiler||` all stay literal inside a// code span or fenced code block — replacing the old `preprocessMarkdown`'s// manual stash/unstash sentinel dance, which existed only because that// implementation operated on a raw string before markdown parsing.@@ -170,8 +171,8 @@ const IGNORE_NODE_TYPES = ["code", "inlineCode", "link", "linkReference"]function mentionReplacer(value: string): MentionNode {const everyone = value === "@everyone"if (everyone) return { type: "mention", value, everyone: true }- const tag = /#(\d{4})$/.exec(value)- const bare = value.replace(/#\d{4}$/, "")+ const tag = /#(\d{4,})$/.exec(value)+ const bare = value.replace(/#\d{4,}$/, "")return tag ? { type: "mention", value: bare, everyone: false, discriminator: tag[1] } : { type: "mention", value: bare, everyone: false }}@@ -205,7 +206,7 @@ export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this[MENTION_RE, mentionReplacer as unknown as (value: string, ...rest: unknown[]) => PhrasingContent | string | false],[CHANNEL_REF_RE, channelRefReplacer as unknown as (value: string) => PhrasingContent],// Runs as its own pass AFTER the channelRef pass above — by then every- // `/server/channel` span is already a `channelRef` element (no longer+ // `/server#disc/channel` span is already a `channelRef` element (no longer// a `text` node `findAndReplace` visits), so this pass only ever sees// genuine bare `/server` refs among the remaining text.[SERVER_REF_RE, serverRefReplacer as unknown as (value: string) => PhrasingContent],diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.tsnew file mode 100644index 000000000..88f7f485d--- /dev/null+++ b/src/web/src/lib/community/create-channels.test.ts@@ -0,0 +1,312 @@+import { describe, it, expect, vi, beforeEach } from "vitest"++const mockCreateCommunityMessage = vi.fn()+const mockCreateChannel = vi.fn()+const mockGetThreadChannelByParentMessage = vi.fn()+const mockHardDeleteMessage = vi.fn()+const mockAddThreadParticipants = vi.fn()+const mockFanOutToChannel = vi.fn()+const mockDeleteChannel = vi.fn()+const mockListMessageAttachments = vi.fn()+const mockRebindPendingAttachmentsToChild = vi.fn()++vi.mock("@/lib/community/message-handler", () => ({+ createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),+}))++vi.mock("@/lib/community/fanout", () => ({+ fanOutToServerMembers: vi.fn(),+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),+}))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityChannel: {+ ...actual.queries.communityChannel,+ createChannel: (...a: unknown[]) => mockCreateChannel(...a),+ getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),+ deleteChannel: (...a: unknown[]) => mockDeleteChannel(...a),+ },+ communityMessage: {+ ...actual.queries.communityMessage,+ hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),+ },+ communityAttachment: {+ ...actual.queries.communityAttachment,+ listMessageAttachments: (...a: unknown[]) => mockListMessageAttachments(...a),+ rebindPendingAttachmentsToChild: (...a: unknown[]) => mockRebindPendingAttachmentsToChild(...a),+ },+ communityThread: {+ ...actual.queries.communityThread,+ addThreadParticipants: (...a: unknown[]) => mockAddThreadParticipants(...a),+ },+ },+ }+})++import { createMessageWithThread } from "./create-channels"++describe("createMessageWithThread (phase2 forum≡thread — atomic-by-compensation primitive)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ // vi.clearAllMocks() only clears call history, NOT a prior test's+ // mockRejectedValue/mockResolvedValue implementation — reset the two+ // compensating-delete mocks to a resolved default every test so a+ // rejection set by one failure-path test can never silently leak into+ // the next; any test exercising a rollback failure overrides explicitly.+ mockDeleteChannel.mockResolvedValue(undefined)+ mockHardDeleteMessage.mockResolvedValue(undefined)+ mockRebindPendingAttachmentsToChild.mockResolvedValue(true)+ })++ it("inserts the opener message into the PARENT channel, then opens a fresh thread rooted on it", async () => {+ mockCreateCommunityMessage.mockResolvedValue({+ ok: true,+ row: { id: "msg_1", content: "hello world", channelId: "forum_1" },+ attachments: [],+ })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "hello world" })++ const res = await createMessageWithThread({+ db: {} as any,+ authorId: "u1",+ parentChannelId: "forum_1",+ serverId: "s1",+ body: { content: "hello world" },+ })++ expect(res.ok).toBe(true)+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ authorId: "u1",+ target: { kind: "channel", channelId: "forum_1", serverId: "s1" },+ }),+ )+ expect(mockCreateChannel).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ serverId: "s1",+ parentChannelId: "forum_1",+ parentMessageId: "msg_1",+ type: "thread",+ creatorId: "u1",+ }),+ )+ if (res.ok) {+ expect(res.message.id).toBe("msg_1")+ expect(res.thread.id).toBe("th_1")+ }+ })++ it("threadName is ALWAYS truncated to MAX_CHANNEL_NAME_LENGTH (100), even when explicitly passed a longer string — the thread's `name` column is a channel-naming field, bounded like any other channel name, regardless of how long a post's title (up to MAX_MESSAGE_CONTENT_LENGTH=4000) happens to be", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "short", channelId: "forum_1" }, attachments: [] })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "x" })+ const longTitle = "x".repeat(4000)++ await createMessageWithThread({+ db: {} as any,+ authorId: "u1",+ parentChannelId: "forum_1",+ serverId: "s1",+ body: { content: "short" },+ threadName: longTitle,+ })++ const [, createChannelArgs] = mockCreateChannel.mock.calls[0]+ expect(createChannelArgs.name.length).toBe(100)+ })++ it("fresh-create seeds the author as a SPOKE participant and fires CHILD_CHANNEL_CREATE by default", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "hi" })++ await createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },+ })++ expect(mockAddThreadParticipants).toHaveBeenCalledWith(+ expect.anything(), "th_1", [{ userId: "u1", source: "spoke" }],+ )+ expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)+ })++ it("suppressBroadcast passes through to createCommunityMessage; suppressThreadFanout independently silences ONLY the thread's own CHILD_CHANNEL_CREATE — enroll still runs unconditionally", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "hi" })++ await createMessageWithThread({+ db: {} as any,+ authorId: "u1",+ parentChannelId: "forum_1",+ serverId: "s1",+ body: { content: "hi" },+ suppressBroadcast: true,+ suppressThreadFanout: true,+ })++ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(+ expect.objectContaining({ suppressBroadcast: true }),+ )+ // Enroll (structural core) is NOT gated by either suppress switch.+ expect(mockAddThreadParticipants).toHaveBeenCalledTimes(1)+ // But the thread's own broadcast IS silenced.+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("a concurrent-race re-select (not a fresh create) skips seed + fan-out entirely", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })+ // creatorId !== authorId ("u2") → this actor lost the race, re-selected someone else's row.+ mockCreateChannel.mockRejectedValue(Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT" }))+ mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "th_1", creatorId: "u2", createdAt: "t0", name: "hi" })++ const res = await createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },+ })++ expect(res.ok).toBe(true)+ expect(mockAddThreadParticipants).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ expect(mockHardDeleteMessage).not.toHaveBeenCalled()+ })++ it("same-nonce replay returns the existing thread without rebinding or broadcasting", async () => {+ mockCreateCommunityMessage.mockResolvedValue({+ ok: true,+ row: { id: "msg_1", content: "Title", channelId: "forum_1" },+ attachments: [],+ deduped: true,+ })+ mockGetThreadChannelByParentMessage.mockResolvedValue({+ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title",+ })+ mockListMessageAttachments.mockResolvedValue([])++ const res = await createMessageWithThread({+ db: {} as any,+ authorId: "u1",+ parentChannelId: "forum_1",+ serverId: "s1",+ body: { content: "Title" },+ pendingAttachmentIdsToRebind: ["att_1"],+ clientNonce: "nonce_1",+ })++ expect(res).toEqual(expect.objectContaining({+ ok: true,+ deduped: true,+ thread: expect.objectContaining({ id: "th_1" }),+ }))+ expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)+ expect(mockCreateChannel).not.toHaveBeenCalled()+ expect(mockAddThreadParticipants).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ expect(mockRebindPendingAttachmentsToChild).not.toHaveBeenCalled()+ })++ it("returns the message-handler's error verbatim without touching the thread path at all", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: false, status: 400, error: "content or attachments required" })++ const res = await createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "" },+ })++ expect(res).toEqual({ ok: false, status: 400, error: "content or attachments required" })+ expect(mockCreateChannel).not.toHaveBeenCalled()+ })++ it("compensates with hardDeleteMessage when the thread-open throws unrecoverably (no orphan message left behind)", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })+ mockCreateChannel.mockRejectedValue(new Error("D1 outage"))++ await expect(+ createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },+ }),+ ).rejects.toThrow("D1 outage")++ expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")+ })++ it("when the compensating hardDelete ALSO fails, logs both errors but re-throws the ORIGINAL thread-open error (never masks the real cause, never fails silently)", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })+ mockCreateChannel.mockRejectedValue(new Error("D1 outage"))+ mockHardDeleteMessage.mockRejectedValue(new Error("rollback also down"))++ await expect(+ createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },+ }),+ ).rejects.toThrow("D1 outage")++ expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")+ })++ it("rebinds pending attachments from the forum to the fresh child thread", async () => {+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [] })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })++ const res = await createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1",+ body: { content: "Title" }, pendingAttachmentIdsToRebind: ["att_1"],+ })++ expect(res.ok).toBe(true)+ expect(mockRebindPendingAttachmentsToChild).toHaveBeenCalledWith(expect.anything(), {+ ids: ["att_1"], uploaderId: "u1", parentTargetId: "forum_1", childTargetId: "th_1",+ })+ })++ it("compensates the fresh opener and thread when attachment rebind is rejected", async () => {+ const broadcast = vi.fn()+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [], broadcast })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })+ mockRebindPendingAttachmentsToChild.mockResolvedValue(false)++ const res = await createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1",+ body: { content: "Title" }, pendingAttachmentIdsToRebind: ["stolen"],+ })++ expect(res).toEqual({ ok: false, status: 400, error: "attachment not found or not attachable to this thread" })+ expect(mockDeleteChannel).toHaveBeenCalledWith(expect.anything(), "th_1")+ expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")+ expect(broadcast).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("attempts both compensations and never publishes when rebind throws", async () => {+ const broadcast = vi.fn()+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [], broadcast })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })+ mockRebindPendingAttachmentsToChild.mockRejectedValue(new Error("rebind failed"))+ mockDeleteChannel.mockRejectedValue(new Error("delete thread failed"))++ await expect(createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1",+ body: { content: "Title" }, pendingAttachmentIdsToRebind: ["att_1"],+ })).rejects.toThrow("rebind failed")++ expect(mockDeleteChannel).toHaveBeenCalledWith(expect.anything(), "th_1")+ expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")+ expect(broadcast).not.toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("publishes the opener only after structure and participants commit", async () => {+ const broadcast = vi.fn(async () => undefined)+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [], broadcast })+ mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })++ await createMessageWithThread({+ db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "Title" },+ })++ expect(mockAddThreadParticipants.mock.invocationCallOrder[0]).toBeLessThan(mockRebindPendingAttachmentsToChild.mock.invocationCallOrder[0])+ expect(mockRebindPendingAttachmentsToChild.mock.invocationCallOrder[0]).toBeLessThan(broadcast.mock.invocationCallOrder[0])+ expect(broadcast.mock.invocationCallOrder[0]).toBeLessThan(mockFanOutToChannel.mock.invocationCallOrder[0])+ })+})diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.tsnew file mode 100644index 000000000..f157d70c0--- /dev/null+++ b/src/web/src/lib/community/create-channels.ts@@ -0,0 +1,490 @@+import {+ queries,+ canManageServer,+ isChannelType,+ channelCreation,+ MAX_CHANNEL_NAME_LENGTH,+ MAX_CHANNEL_TOPIC_LENGTH,+ WS_EVENTS,+ slugify,+ PARTICIPANT_SOURCE,+ createLogger,+ type ChannelType,+ type StoredChannelType,+ type Database,+} from "@alook/shared"+import { fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"+import { createWithCollisionPolicy } from "@/lib/community/create-collision"+import { logAudit } from "@/lib/community/audit"+import { requireServerMember, requireChannelMember } from "@/lib/community/permissions"+import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"+import { guardDmOpen } from "@/lib/community/dm-guard"+import { createCommunityMessage, type IncomingMessageBody } from "@/lib/community/message-handler"+import { attachmentUrl } from "@/lib/community/storage"++const log = createLogger({ service: "community-create-channels" })++/**+ * Single-source creation cores for the `POST /channels` create door (route/disc+ * trunk 接口树统一, create-door step). Each function is the exact body that used+ * to live inline in one legacy create entry — extracted so the door and the+ * (transitionally kept-alive) legacy route call ONE code path, making their+ * equivalence structural rather than a copy that can drift. The door dispatches+ * on the requested type's creation trait; these are the per-type attempt ++ * side-effect shapes those traits parameterize.+ *+ * Boundary (createWithCollisionPolicy doc): text/forum are reject-on-collision+ * (by-name), thread is get-or-create (by root-message anchor); DM is get-or-create+ * by user-pair IDENTITY — a different key space — so it stays on createOrGetDM and+ * is NOT wired through createWithCollisionPolicy (folding it would compress two+ * collision-key axes into one value = false convergence).+ */++export type CreateChannelResult<T> =+ | { ok: true; value: T }+ | { ok: false; status: number; error: string }++/**+ * Create a top-level text/forum channel under a server (reject-on-collision).+ * Byte-identical to the former servers/[id]/channels POST body.+ */+export async function createServerChannelForUser(+ db: Database,+ params: {+ serverId: string+ actorUserId: string+ name?: unknown+ type?: unknown+ categoryId?: unknown+ topic?: unknown+ },+): Promise<CreateChannelResult<{ id: string; name: string; type: ChannelType; categoryId: string | null; topic?: string; position: number; createdAt: number }>> {+ const { serverId, actorUserId } = params++ const auth = await requireServerMember(db, serverId, actorUserId)+ if (!auth.ok) return { ok: false, status: auth.status, error: auth.error }+ const member = auth.value!++ if (!params.name || typeof params.name !== "string") {+ return { ok: false, status: 400, error: "name is required" }+ }+ const trimmed = params.name.trim()+ if (!trimmed || trimmed.length > MAX_CHANNEL_NAME_LENGTH) {+ return { ok: false, status: 400, error: `name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters` }+ }+ const name = slugify(trimmed)+ if (!name) {+ return { ok: false, status: 400, error: "name is required" }+ }+ if (params.type !== undefined && !isChannelType(params.type)) {+ return { ok: false, status: 400, error: "type must be 'text' or 'forum'" }+ }+ const type = params.type as ChannelType | undefined+ if (params.topic !== undefined) {+ if (typeof params.topic !== "string") return { ok: false, status: 400, error: "topic must be a string" }+ if (params.topic.length > MAX_CHANNEL_TOPIC_LENGTH) {+ return { ok: false, status: 400, error: `topic must be ≤ ${MAX_CHANNEL_TOPIC_LENGTH} characters` }+ }+ }+ const topic = params.topic as string | undefined+ const categoryId = typeof params.categoryId === "string" ? params.categoryId : undefined++ // Who may create depends on the target location:+ // - uncategorized OR public category → admin/owner only+ // - private category → any server member (they own the channel + its roster)+ const isAdmin = canManageServer(member.role)+ let isPrivateCategory = false+ if (categoryId) {+ const category = await queries.communityCategory.getCategory(db, categoryId)+ if (!category || category.serverId !== serverId) {+ return { ok: false, status: 404, error: "category not found" }+ }+ isPrivateCategory = !!category.private+ }+ if (!isPrivateCategory && !isAdmin) {+ return { ok: false, status: 403, error: "admin permission required" }+ }++ const effectiveType: StoredChannelType = type === "forum" ? "forum" : "text"+ const createResult = await createWithCollisionPolicy(channelCreation(effectiveType), {+ attempt: () => queries.communityChannel.createChannel(db, {+ serverId,+ categoryId: categoryId || null,+ name,+ type,+ topic,+ creatorId: actorUserId,+ }),+ onReject: () => ({ status: 409, error: "a channel with this name already exists" }),+ })+ if (!createResult.ok) return { ok: false, status: createResult.status, error: createResult.error }+ const row = createResult.value++ if (isPrivateCategory) {+ await queries.communityChannel.createChannelMember(db, {+ channelId: row.id,+ userId: actorUserId,+ addedBy: actorUserId,+ })+ }++ const channel = {+ id: row.id,+ name: row.name,+ type: row.type as ChannelType,+ categoryId: row.categoryId,+ topic: row.topic ?? undefined,+ position: row.position ?? 0,+ createdAt: row.createdAt,+ }++ if (isPrivateCategory) {+ await fanOutToChannel(row.id, {+ type: WS_EVENTS.CHANNEL_CREATE,+ serverId,+ channel,+ })+ } else {+ await fanOutToServerMembers(serverId, {+ type: WS_EVENTS.CHANNEL_CREATE,+ serverId,+ channel,+ })+ }++ logAudit(db, {+ serverId,+ actorId: actorUserId,+ action: "channel_create",+ targetType: "channel",+ targetId: channel.id,+ })++ return { ok: true, value: channel }+}++/**+ * Create-or-get a DM channel for a user pair (get-or-create by peer identity).+ * Byte-identical to the former dm/route POST body.+ */+export async function createDmForUser(+ db: Database,+ params: { actorUserId: string; peerUserId?: unknown },+): Promise<CreateChannelResult<Awaited<ReturnType<typeof queries.communityDm.createOrGetDM>>>> {+ if (!params.peerUserId || typeof params.peerUserId !== "string") {+ return { ok: false, status: 400, error: "userId is required" }+ }++ // Default callerKind ("human") — 404-on-friend-failure preserved exactly.+ const guard = await guardDmOpen(db, params.actorUserId, params.peerUserId)+ if (!guard.ok) return { ok: false, status: guard.status, error: guard.error }++ const dm = await queries.communityDm.createOrGetDM(db, {+ userId1: params.actorUserId,+ userId2: params.peerUserId,+ })++ return { ok: true, value: dm }+}++/**+ * Create-or-get a thread rooted on a top-level channel message (get-or-create by+ * the root message anchor). Folds the former messages/[id]/threads POST body but+ * unifies its behavior with the send-path thread create: the legacy route+ * hand-rolled a 409 "already has a thread" pre-check; that 409 was never a+ * consumed signal (no caller branched on it — Ingaborg #472), so the trait's+ * get-or-create (return the existing thread) is strictly more useful. One thread+ * semantics now, shared with resolve-ref's createThreadIfMissing.+ */+export async function createThreadForUser(+ db: Database,+ params: { messageId: string; actorUserId: string; name?: unknown },+): Promise<CreateChannelResult<Awaited<ReturnType<typeof queries.communityChannel.createChannel>>>> {+ const { messageId, actorUserId } = params++ const message = await queries.communityMessage.getMessage(db, messageId)+ if (!message) return { ok: false, status: 404, error: "message not found" }+ if (!message.channelId) return { ok: false, status: 400, error: "message is not in a channel" }++ const auth = await requireChannelMember(db, message.channelId, actorUserId)+ if (!auth.ok) return { ok: false, status: auth.status, error: auth.error }+ const channel = auth.value++ // Threads may only root on a TOP-LEVEL channel's message (privacy anchor climb+ // can't resolve a grandchild). The UI already forbids this; enforce on the API.+ if (channel.parentChannelId) {+ return { ok: false, status: 400, error: "can't start a thread on a message in a thread or forum post" }+ }++ // A thread roots on a real message → the anchor's channel must be message-bearing+ // (a `forum` top-level is a post index, not a message surface).+ const bearing = requireMessageBearingSurface(channel.type)+ if (!bearing.ok) return { ok: false, status: bearing.status, error: bearing.error }++ if (!params.name || typeof params.name !== "string") return { ok: false, status: 400, error: "name is required" }+ const name = params.name.trim()+ if (!name || name.length > MAX_CHANNEL_NAME_LENGTH) {+ return { ok: false, status: 400, error: `name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters` }+ }++ // Get-or-create by the root-message anchor, matching the send-path exactly+ // (resolve-ref createThreadIfMissing) — ONE thread semantics on BOTH axes,+ // result AND side effects. Probe for the existing thread first and early-return+ // it with ZERO seed/fan-out (Ingaborg #478): the participant seed + the+ // CHILD_CHANNEL_CREATE broadcast are FRESH-CREATE side effects. Running them on+ // a re-select would emit a spurious "new child channel" broadcast every time a+ // message that already has a thread is re-created (the former 409 route errored+ // before any side effect; the send-path early-returns). The createWithCollisionPolicy+ // below still guards the concurrent-create race (two creators past this probe+ // at once → the loser hits the unique index → refetchWinner), and that rare+ // re-select is side-effect-free for the same reason.+ const existingThread = await queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId, messageId)+ if (existingThread) return { ok: true, value: existingThread }++ const threadResult = await createWithCollisionPolicy(channelCreation("thread"), {+ attempt: () => queries.communityChannel.createChannel(db, {+ serverId: channel.serverId,+ parentChannelId: message.channelId!,+ parentMessageId: messageId,+ name,+ type: "thread",+ creatorId: actorUserId,+ }),+ refetchWinner: () => queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId!, messageId),+ })+ // get-or-create never returns a structured failure — a !ok is unreachable for+ // this policy (it creates or re-selects, else throws); map to 404 defensively.+ if (!threadResult.ok) return { ok: false, status: 404, error: "thread not found" }+ const childChannel = threadResult.value+ // Fresh-create vs concurrent-race re-select (rare — both creators passed the+ // probe above before either inserted, so the loser's attempt() threw and+ // refetchWinner returned the OTHER creator's row). Only the winner whose row+ // this actor created (creatorId === actorUserId) is a fresh create; a+ // re-selected row was created by someone else who already ran these side+ // effects. Keeps re-select side-effect-free on the race path too.+ const isFreshCreate = childChannel.creatorId === actorUserId++ // Seed the NOTIFY set on a fresh create only: creator (spoke) + original author+ // (added, if still a member — else a private channel's thread could leak to+ // someone who lost access). Idempotent per (channel,user) via onConflictDoNothing.+ if (isFreshCreate) {+ const seedRows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.ADDED }[] = [+ { userId: actorUserId, source: PARTICIPANT_SOURCE.SPOKE },+ ]+ if (message.authorId !== actorUserId) {+ const authorStillMember = await requireChannelMember(db, message.channelId, message.authorId)+ if (authorStillMember.ok) seedRows.push({ userId: message.authorId, source: PARTICIPANT_SOURCE.ADDED })+ }+ await queries.communityThread.addThreadParticipants(db, childChannel.id, seedRows)++ fanOutToChannel(message.channelId, {+ type: WS_EVENTS.CHILD_CHANNEL_CREATE,+ parentChannelId: message.channelId,+ channel: {+ id: childChannel.id,+ name: childChannel.name,+ type: "thread" as const,+ creatorId: actorUserId,+ createdAt: childChannel.createdAt,+ },+ parentMessageId: messageId,+ }, { excludeUserId: actorUserId })+ }++ return { ok: true, value: childChannel }+}++type CreateMessageSuccess = Extract<Awaited<ReturnType<typeof createCommunityMessage>>, { ok: true }>++export type CreateMessageWithThreadResult =+ | {+ ok: true+ message: CreateMessageSuccess["row"]+ attachments: CreateMessageSuccess["attachments"]+ thread: Awaited<ReturnType<typeof queries.communityChannel.createChannel>>+ deduped?: boolean+ }+ | { ok: false; status: number; error: string }++export async function createMessageWithThread(params: {+ db: Database+ authorId: string+ parentChannelId: string+ serverId: string+ body: IncomingMessageBody+ threadName?: string+ suppressBroadcast?: boolean+ suppressThreadFanout?: boolean+ attachmentIds?: string[]+ pendingAttachmentIdsToRebind?: string[]+ clientNonce?: string+ source?: "cli" | "daemon-http" | "web"+}): Promise<CreateMessageWithThreadResult> {+ const { db, authorId, parentChannelId, serverId } = params++ const created = await createCommunityMessage({+ db,+ authorId,+ target: { kind: "channel", channelId: parentChannelId, serverId },+ body: params.body,+ source: params.source,+ attachmentIds: params.attachmentIds,+ clientNonce: params.clientNonce,+ suppressBroadcast: params.suppressBroadcast,+ deferBroadcast: true,+ })+ if (!created.ok) return { ok: false, status: created.status, error: created.error }+ const messageId = created.row.id++ if (created.deduped) {+ const thread = await queries.communityChannel.getThreadChannelByParentMessage(+ db,+ parentChannelId,+ messageId,+ )+ if (!thread) throw new Error("deduped forum opener is missing its thread")+ // Structure replay is already complete. Do not touch attachment rows here:+ // they may be pending on this thread (reply previously failed) or already+ // bound to the deduped reply (whole command previously succeeded).+ const storedAttachments = await queries.communityAttachment.listMessageAttachments(db, messageId)+ const toCreatedAttachment = (row: (typeof storedAttachments)[number]) => ({+ ...row,+ url: attachmentUrl(row.targetId, row.id),+ })+ return {+ ok: true,+ message: created.row,+ attachments: storedAttachments.map(toCreatedAttachment),+ thread,+ deduped: true,+ }+ }++ // Always truncated to MAX_CHANNEL_NAME_LENGTH — the thread's `name` column+ // is a channel-naming field (display-only, but still bounded like every+ // other channel name), regardless of how long the caller-supplied+ // threadName or the opener's own content happens to be (e.g. a post's+ // title can be up to MAX_MESSAGE_CONTENT_LENGTH — do not let that length+ // leak into this field uncapped).+ const threadName = (params.threadName?.trim() || created.row.content?.trim() || "thread").slice(0, MAX_CHANNEL_NAME_LENGTH)++ let threadResult: Awaited<ReturnType<typeof createWithCollisionPolicy<Awaited<ReturnType<typeof queries.communityChannel.createChannel>>>>>+ try {+ threadResult = await createWithCollisionPolicy(channelCreation("thread"), {+ attempt: () => queries.communityChannel.createChannel(db, {+ serverId,+ parentChannelId,+ parentMessageId: messageId,+ name: threadName,+ type: "thread",+ creatorId: authorId,+ }),+ refetchWinner: () => queries.communityChannel.getThreadChannelByParentMessage(db, parentChannelId, messageId),+ })+ } catch (err) {+ // Compensate: the message was inserted but its thread never opened — no+ // caller may see a message that's supposed to have a thread but doesn't.+ // If the compensating hardDelete ALSO throws (same D1 outage the+ // thread-open was recovering from), log BOTH and re-throw the ORIGINAL+ // thread-open error — it's the one the caller cares about; matches+ // message-handler.ts's attachment-reserve rollback shape exactly (never+ // let a secondary rollback failure mask the real cause, and never fail+ // silently — Aigneis #670/#680).+ try {+ await queries.communityMessage.hardDeleteMessage(db, messageId)+ } catch (rollbackErr) {+ log.error("thread_open_rollback_failed", {+ messageId,+ threadOpenErr: err instanceof Error ? err.message : String(err),+ rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ })+ }+ throw err+ }+ if (!threadResult.ok) {+ try {+ await queries.communityMessage.hardDeleteMessage(db, messageId)+ } catch (rollbackErr) {+ log.error("thread_open_rollback_failed", {+ messageId,+ threadOpenErr: threadResult.error,+ rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ })+ }+ return { ok: false, status: 404, error: "thread not found" }+ }+ const childChannel = threadResult.value+ const isFreshCreate = childChannel.creatorId === authorId++ const compensateFreshStructure = async (cause: unknown) => {+ if (isFreshCreate) {+ try {+ await queries.communityChannel.deleteChannel(db, childChannel.id)+ } catch (rollbackErr) {+ log.error("thread_rollback_delete_channel_failed", {+ messageId,+ cause: cause instanceof Error ? cause.message : String(cause),+ rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ })+ }+ try {+ await queries.communityMessage.hardDeleteMessage(db, messageId)+ } catch (rollbackErr) {+ log.error("thread_rollback_delete_opener_failed", {+ messageId,+ cause: cause instanceof Error ? cause.message : String(cause),+ rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ })+ }+ }+ }++ if (isFreshCreate) {+ try {+ await queries.communityThread.addThreadParticipants(db, childChannel.id, [+ { userId: authorId, source: PARTICIPANT_SOURCE.SPOKE },+ ])+ } catch (err) {+ await compensateFreshStructure(err)+ throw err+ }+ }++ let rebound: boolean+ try {+ rebound = await queries.communityAttachment.rebindPendingAttachmentsToChild(db, {+ ids: params.pendingAttachmentIdsToRebind ?? [],+ uploaderId: authorId,+ parentTargetId: parentChannelId,+ childTargetId: childChannel.id,+ })+ } catch (err) {+ await compensateFreshStructure(err)+ throw err+ }+ if (!rebound) {+ await compensateFreshStructure("attachment rebind rejected")+ return { ok: false, status: 400, error: "attachment not found or not attachable to this thread" }+ }++ if (isFreshCreate) {+ await created.broadcast?.()++ if (!params.suppressThreadFanout) {+ await fanOutToChannel(parentChannelId, {+ type: WS_EVENTS.CHILD_CHANNEL_CREATE,+ parentChannelId,+ channel: {+ id: childChannel.id,+ name: childChannel.name,+ type: "thread" as const,+ creatorId: authorId,+ createdAt: childChannel.createdAt,+ },+ parentMessageId: messageId,+ }, { excludeUserId: authorId })+ }+ }++ return { ok: true, message: created.row, attachments: created.attachments, thread: childChannel }+}diff --git a/src/web/src/lib/community/create-collision.test.ts b/src/web/src/lib/community/create-collision.test.tsindex c0217e128..1b10e3bb4 100644--- a/src/web/src/lib/community/create-collision.test.ts+++ b/src/web/src/lib/community/create-collision.test.ts@@ -9,48 +9,6 @@ function uniqueErr(): Error {}describe("createWithCollisionPolicy — trait-keyed create collision dispatch (B4)", () => {- describe("pure-create (forum_post): bump-and-retry, never merge", () => {- it("returns the created value on a clean first attempt", async () => {- const attempt = vi.fn().mockResolvedValue({ id: "p1" })- const res = await createWithCollisionPolicy("pure-create", { attempt })- expect(res).toEqual({ ok: true, value: { id: "p1" } })- expect(attempt).toHaveBeenCalledTimes(1)- })-- it("re-runs attempt (re-bump) on a unique collision, then succeeds", async () => {- const attempt = vi- .fn()- .mockRejectedValueOnce(uniqueErr())- .mockRejectedValueOnce(uniqueErr())- .mockResolvedValueOnce({ id: "p3" })- const res = await createWithCollisionPolicy("pure-create", { attempt })- expect(res).toEqual({ ok: true, value: { id: "p3" } })- expect(attempt).toHaveBeenCalledTimes(3)- })-- it("NEVER re-selects a winner — pure-create ignores refetchWinner even if supplied", async () => {- const refetchWinner = vi.fn().mockResolvedValue({ id: "someone-elses" })- const attempt = vi.fn().mockRejectedValueOnce(uniqueErr()).mockResolvedValueOnce({ id: "mine" })- const res = await createWithCollisionPolicy("pure-create", { attempt, refetchWinner })- // The 2nd attempt (re-bump) wins — the caller's OWN row, not the winner.- expect(res).toEqual({ ok: true, value: { id: "mine" } })- expect(refetchWinner).not.toHaveBeenCalled()- })-- it("gives up with 409 after maxAttempts collisions (index-missing / pathological)", async () => {- const attempt = vi.fn().mockRejectedValue(uniqueErr())- const res = await createWithCollisionPolicy("pure-create", { attempt, maxAttempts: 3 })- expect(res.ok).toBe(false)- if (!res.ok) expect(res.status).toBe(409)- expect(attempt).toHaveBeenCalledTimes(3)- })-- it("re-throws a non-unique error (real failure, not a collision)", async () => {- const attempt = vi.fn().mockRejectedValue(new Error("boom"))- await expect(createWithCollisionPolicy("pure-create", { attempt })).rejects.toThrow("boom")- })- })-describe("get-or-create (thread/dm-anchor): fetch the winner, never make a second", () => {it("returns the created value on a clean attempt", async () => {const attempt = vi.fn().mockResolvedValue({ id: "t1" })@@ -95,9 +53,9 @@ describe("createWithCollisionPolicy — trait-keyed create collision dispatch (B})})- // Aigneis's "three contracts don't cross" — each value's collision end-state is- // strictly its own: pure-create bumps (N distinct), get-or-create fetches (1- // shared), reject-on-collision 409s (0 new). The per-value tests above already- // assert none leaks another's behavior (pure-create ignores refetchWinner;- // reject ignores both bump and refetch; get-or-create doesn't re-attempt).+ // Aigneis's "contracts don't cross" — each value's collision end-state is+ // strictly its own: get-or-create fetches (1 shared), reject-on-collision+ // 409s (0 new). The per-value tests above already assert neither leaks the+ // other's behavior (reject ignores both bump and refetch; get-or-create+ // doesn't re-attempt).})diff --git a/src/web/src/lib/community/create-collision.ts b/src/web/src/lib/community/create-collision.tsindex bd640d9b1..5ad766c85 100644--- a/src/web/src/lib/community/create-collision.ts+++ b/src/web/src/lib/community/create-collision.ts@@ -1,13 +1,12 @@import { isUniqueConstraintError, type CreationTrait } from "@alook/shared"/**- * The single collision-handling strategy for CREATING a channel, dispatched on- * the channel type's `creation` trait (B4 convergence正题). Before this, "what a- * name/anchor collision means" was hand-rolled in three places with three shapes:- * - forum_post: dedupe-bump the slug and retry the insert (pure-create)+ * The single collision-handling strategy for CREATING a channel, dispatched+ * on the channel type's `creation` trait. "What a name/anchor collision+ * means" is hand-rolled in two shapes:* - thread: catch the unique-conflict and re-SELECT the winner (get-or-create)* - top-level text/forum: let the unique index 409 (reject-on-collision)- * They collide on DIFFERENT keys (name / parent_message_id / server-name), so the+ * They collide on DIFFERENT keys (parent_message_id / server-name), so the* per-type CHANNEL-SHAPE construction stays with each caller — only the COLLISION* POLICY converges here, parameterized by callbacks the caller supplies. (DM is* NOT wired in this round: its collision is identity-collision on a user-pair, a@@ -22,11 +21,6 @@ import { isUniqueConstraintError, type CreationTrait } from "@alook/shared"* the race. Returns null if it somehow can't be found.* - `onReject()`: (reject-on-collision only) the structured error to return when* the create is refused.- * - `maxAttempts`: (pure-create only) bump-retry cap.- *- * ⚠ pure-create's race-safety REQUIRES the partial-unique index that makes- * `attempt()` throw on a concurrent duplicate (migration, B4b). Without it a race- * silently double-inserts — this dispatch is only correct once that index exists.*/export type CollisionOutcome<T> =@@ -39,7 +33,6 @@ export async function createWithCollisionPolicy<T>(attempt: () => Promise<T>refetchWinner?: () => Promise<T | null>onReject?: () => { status: 400 | 409; error: string }- maxAttempts?: number},): Promise<CollisionOutcome<T>> {switch (creation) {@@ -57,29 +50,6 @@ export async function createWithCollisionPolicy<T>(throw err}}- case "pure-create": {- // Each create is a distinct unit; a collision means "this name is taken" →- // the caller re-derives a bumped name inside `attempt()` on the next pass- // and retries. NEVER re-select the winner (that's get-or-create — it would- // silently hand this caller someone else's unit). The cap stops an unbounded- // loop if the index is missing (a mis-shipped B4a without B4b) or contention- // is pathological.- const max = handlers.maxAttempts ?? 8- let attempts = 0- // eslint-disable-next-line no-constant-condition- while (true) {- try {- return { ok: true, value: await handlers.attempt() }- } catch (err) {- attempts++- if (isUniqueConstraintError(err) && attempts < max) continue- if (isUniqueConstraintError(err)) {- return { ok: false, status: 409, error: "could not allocate a unique name after repeated collisions" }- }- throw err- }- }- }case "reject-on-collision": {// A same-name create is refused (the unique index 409s). Surface the// caller's structured rejection rather than merging or bumping.diff --git a/src/web/src/lib/community/create-community-message-allowlist.test.ts b/src/web/src/lib/community/create-community-message-allowlist.test.tsnew file mode 100644index 000000000..fd7f2d910--- /dev/null+++ b/src/web/src/lib/community/create-community-message-allowlist.test.ts@@ -0,0 +1,67 @@+import { describe, it, expect } from "vitest"+import { readdirSync, readFileSync } from "fs"+import { join, relative, sep } from "path"++/**+ * ③ shrink-gate (route/disc trunk — flat-tree deletion). `createCommunityMessage`+ * is the single write funnel; every caller must be an INTENDED door. This test+ * enumerates the actual direct callers across the whole source tree and asserts+ * the set equals a hand-maintained allowlist — a NEW caller (e.g. a re-added flat+ * verb, or a route that should have folded into the canonical door) fails the+ * test until it's consciously added here. That's the point: the allowlist is the+ * positive proof that the flat tree stayed deleted and no fourth door-bypass+ * caller crept in (Melly #346 / Aigneis ③).+ *+ * Paths are repo-relative to src/web (the vitest cwd). `message-handler.ts` is+ * excluded — it DEFINES createCommunityMessage, it doesn't call it.+ */+const ALLOWLIST = [+ // The canonical id-in-path message door (human + bot, folds flat `send` and+ // the former dm/[id]/messages route — DM now flows through this one tree).+ "src/app/api/community/channels/[id]/messages/route.ts",+ // Bot enrollment welcome message (server owner adds a bot → greeting).+ "src/app/api/community/servers/[id]/bots/route.ts",+ // phase2 forum≡thread step 1: the atomic-by-compensation "message+thread"+ // primitive — shared by the send-fold (step 4) and the existing-data+ // migration (step 5) to open a message with its own auto-created thread.+ "src/lib/community/create-channels.ts",+].sort()++function walk(dir: string, acc: string[] = []): string[] {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name)+ if (entry.isDirectory()) {+ if (entry.name === "node_modules" || entry.name === ".next") continue+ walk(full, acc)+ } else if (entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {+ acc.push(full)+ }+ }+ return acc+}++describe("createCommunityMessage caller allowlist (③ shrink-gate)", () => {+ it("only the intended doors call createCommunityMessage — no flat-verb / bypass caller", () => {+ // Resolve @alook/web's `src` regardless of vitest cwd (repo root vs package).+ // This file is at src/lib/community/, so climb two levels to `src`.+ const srcRoot = join(__dirname, "..", "..")+ const files = walk(srcRoot)+ const callers: string[] = []+ for (const file of files) {+ const repoRelativePath = `src/${relative(srcRoot, file).split(sep).join("/")}`+ if (repoRelativePath === "src/lib/community/message-handler.ts") continue // defines it+ // Strip `//` line comments and `/* */` block comments so a doc mention of+ // the funnel (e.g. "the MessageTarget for createCommunityMessage") is not+ // counted as a caller — only a real invocation `createCommunityMessage(`.+ const src = readFileSync(file, "utf8")+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/\/\/.*$/gm, "")+ // A direct call: `createCommunityMessage(` with no intervening space (a+ // call site, not the import binding or a JSDoc reference).+ if (/\bcreateCommunityMessage\(/.test(src)) {+ callers.push(repoRelativePath)+ }+ }+ expect(callers.sort()).toEqual(ALLOWLIST)+ })+})diff --git a/src/web/src/lib/community/create-forum-post.ts b/src/web/src/lib/community/create-forum-post.tsdeleted file mode 100644index e1aaa5888..000000000--- a/src/web/src/lib/community/create-forum-post.ts+++ /dev/null@@ -1,161 +0,0 @@-import {- queries,- slugify,- channelCreation,- MAX_CHANNEL_NAME_LENGTH,- MAX_MESSAGE_CONTENT_LENGTH,- type Database,-} from "@alook/shared"-import { createCommunityMessage } from "./message-handler"-import { createWithCollisionPolicy } from "./create-collision"--/**- * Shared core for CREATING a forum post — the single implementation both the- * human New-Post route (`channels/[id]/posts` POST) and the bot verb- * (`createPost` POST, `alook message post`) call. Extracting it is the B4- * creation-axis convergence: "what a name collision means" is chosen ONCE, by- * dispatching on the forum-post type's `creation` trait, instead of each caller- * hand-rolling slug dedupe + create + first-message.- *- * `forum_post`'s creation trait is `pure-create`: each post is a distinct unit,- * and a slug collision BUMPS a new slug (`ideas` → `ideas-2`) and retries the- * insert — it NEVER merges into an existing post (that would be get-or-create,- * a thread/DM contract). The retry loop below catches the partial-unique-index- * violation and re-bumps.- *- * ⚠ SHIP-ORDER CONSTRAINT (Aigneis / Blondie, thread /Alook/discuss/#462): the- * bump-retry's RACE-safety depends on the `(parent_channel_id, name)` partial- * unique index (migration 0078, B4b). WITHOUT that index a concurrent- * same-title create silently double-inserts (the original race — two posts,- * both "succeed", sharing a slug, breaking name addressing). So this handler is- * only correct once that index exists: B4a (this code) MUST NOT ship without- * B4b (the index). The best-effort `dedupeChildChannelSlug` pre-check narrows- * the window but does NOT close it — only the index does.- */--export type CreateForumPostInput = {- db: Database- /** The parent forum channel (already membership-gated + asserted type=forum by the caller). */- forumChannelId: string- serverId: string- /** The post creator (human userId or bot userId). */- authorId: string- /** Raw, pre-slugify title — its slug becomes the post's addressing name; the- * original is captured verbatim into `display_title`. */- rawTitle: string- /** Post body text (may be empty when attachments carry the content). */- content: string- /** Attachment payloads (human route) — pending-id reservation is the bot route's concern. */- attachments?: unknown- mentionType?: unknown- /** Bot-reserved attachment ids, validated by the caller (bot route). */- attachmentIds?: string[]- clientNonce?: string-}--// The success shape of createCommunityMessage — narrowed to its `ok:true` arm so-// we can reuse its exact `row`/`attachments` types without re-declaring them.-type CreateMessageSuccess = Extract<Awaited<ReturnType<typeof createCommunityMessage>>, { ok: true }>--type CreatedChannel = Awaited<ReturnType<typeof queries.communityChannel.createChannel>>--export type CreateForumPostResult =- | { ok: true; postChannel: CreatedChannel; messageRow: CreateMessageSuccess["row"]; attachments: CreateMessageSuccess["attachments"] }- | { ok: false; status: 400 | 409; error: string }--// How many times to re-bump a colliding slug before giving up. A forum with-// this many same-titled posts racing at once is pathological; the cap stops an-// unbounded loop if something (e.g. a missing index in a mis-shipped B4a) makes-// every insert collide.-const MAX_SLUG_BUMP_ATTEMPTS = 8--/**- * Validate + create a forum post. Returns a structured error (never throws) for- * the caller to translate into its surface's response shape. Does NOT do the- * WS/fanout side effects beyond what `createCommunityMessage` fires — the caller- * owns its own CHILD_CHANNEL_CREATE emission + response projection.- */-export async function createForumPost(input: CreateForumPostInput): Promise<CreateForumPostResult> {- const { db, forumChannelId, serverId, authorId, rawTitle, content } = input-- // ── validation (shared by both callers) ──────────────────────────────────- const trimmedTitle = rawTitle.trim()- if (trimmedTitle.length === 0) return { ok: false, status: 400, error: "title is required" }- if (trimmedTitle.length > MAX_CHANNEL_NAME_LENGTH) {- return { ok: false, status: 400, error: `title must be 1-${MAX_CHANNEL_NAME_LENGTH} characters` }- }- const baseSlug = slugify(trimmedTitle)- if (!baseSlug) return { ok: false, status: 400, error: "title must contain at least one addressable character" }-- const hasContent = content.trim().length > 0- const hasAttachments =- (Array.isArray(input.attachments) && input.attachments.length > 0) ||- (Array.isArray(input.attachmentIds) && input.attachmentIds.length > 0)- // opener-body contract (thread consensus): a post needs text OR an attachment- // — an attachment-only post is legitimate (the attachment is its body).- if (!hasContent && !hasAttachments) return { ok: false, status: 400, error: "post is empty" }- if (hasContent && content.length > MAX_MESSAGE_CONTENT_LENGTH) {- return { ok: false, status: 400, error: `content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters` }- }-- // ── collision handling via the shared trait-keyed strategy (B4 convergence) ──- // forum_post's creation trait is pure-create → createWithCollisionPolicy runs- // the bump-retry loop: each `attempt` re-derives a deduped slug and inserts;- // a concurrent unique-constraint collision re-bumps (never re-selects a- // winner — that's get-or-create). The SAME dispatch serves thread-create- // (get-or-create) and top-level create (reject-on-collision); only this- // callback (the forum_post channel-shape) is post-specific.- const channelResult = await createWithCollisionPolicy<CreatedChannel>(channelCreation("forum_post"), {- maxAttempts: MAX_SLUG_BUMP_ATTEMPTS,- attempt: async () => {- // Best-effort snapshot dedupe narrows the collision window; the partial- // unique index (B4b) is what actually guarantees uniqueness under a race,- // and is what makes this insert throw so the policy re-bumps. Re-run per- // attempt against the now-updated table.- const candidateSlug = await queries.communityChannel.dedupeChildChannelSlug(db, forumChannelId, baseSlug)- return queries.communityChannel.createChannel(db, {- serverId,- parentChannelId: forumChannelId,- name: candidateSlug,- type: "forum_post",- creatorId: authorId,- // Display-only original title, captured BEFORE slugify (B0 decision, now- // persisted in B4b's display_title column). `trimmedTitle` is the raw- // human input ("Q3 planning / roadmap"), NOT the lossy slug — the point- // is preserving what slugify destroys. Never an addressing axis.- displayTitle: trimmedTitle,- })- },- })- if (!channelResult.ok) return channelResult- const postChannel = channelResult.value-- // First message = the post body, routed kind:"forum_post" so notify-set enroll- // runs (creator "spoke" + @-mentioned "mention"), matching a thread.- // skipChildChannelUpdate: the caller emits its own CHILD_CHANNEL_CREATE.- const created = await createCommunityMessage({- db,- authorId,- target: { kind: "forum_post", channelId: postChannel.id, parentChannelId: forumChannelId, serverId },- body: { content, attachments: input.attachments, mentionType: input.mentionType },- attachmentIds: input.attachmentIds,- clientNonce: input.clientNonce,- skipChildChannelUpdate: true,- })- if (!created.ok) {- // First-message failed — the post channel exists but has no body. Surface- // the error. NOTE: full orphan-avoidance (folding channel + first-message- // into ONE atomic batch) is a tracked hardening follow-up (Ingaborg's owed- // work), NOT B4a — createCommunityMessage claims a seq in its own statement- // so it can't fuse into the createChannel insert without the batch rework.- // Non-regression: the human New-Post route has this same window today.- return { ok: false, status: created.status, error: created.error }- }-- return {- ok: true,- postChannel,- messageRow: created.row,- attachments: created.attachments,- }-}diff --git a/src/web/src/lib/community/dm-guard.ts b/src/web/src/lib/community/dm-guard.tsindex 5fbce225d..9ac86df3a 100644--- a/src/web/src/lib/community/dm-guard.ts+++ b/src/web/src/lib/community/dm-guard.ts@@ -7,8 +7,8 @@ export type GuardDmOpenResult =| { ok: false; status: 400 | 403 | 404; error: string; code?: string }/**- * Shared DM-open gate (debt #9), extracted verbatim from the human DM route- * (`/api/community/dm` POST) so bot DM-open goes through the SAME gating a+ * Shared DM-open gate (debt #9), shared with the human DM create door+ * (`POST /api/community/channels`, `type: "dm"`) so bot DM-open uses the SAME gating a* human does — not a looser path. Single signature, one opts flag:* `callerKind` defaults to `"human"` (preserves existing behavior for the* human route with zero call-site changes).diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.tsindex f28c20ea7..47ef1f91f 100644--- a/src/web/src/lib/community/enrich-messages.ts+++ b/src/web/src/lib/community/enrich-messages.ts@@ -1,7 +1,8 @@-import { queries } from "@alook/shared"+import { queries, withD1Retry } from "@alook/shared"import type { getDb } from "@/lib/db"import { groupAttachments, groupReactions } from "@/lib/community/messages"import { mapMessageForApi } from "@/lib/community/message-payload"+import { avatarInitial } from "@/lib/community/avatar"// Message enrichment shared by the channel messages route, the channel// bootstrap route, and the DM messages route (previously three near-identical@@ -15,7 +16,7 @@ import { mapMessageForApi } from "@/lib/community/message-payload"type Db = ReturnType<typeof getDb>-export type MessageScope = { channelId: string; isDm?: boolean }+export type MessageScope = { channelId: string; isDm?: boolean; isForum?: boolean }export async function enrichMessages(db: Db,@@ -35,11 +36,16 @@ export async function enrichMessages(? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId): Promise.resolve([]),replyToIds.length > 0- ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId: scope.channelId })+ ? withD1Retry(+ () => queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId: scope.channelId }),+ { route: "community/messages:reply-enrichment" },+ ): Promise.resolve([]),// Thread indicators only exist for non-DM channel-scoped messages.!isDm- ? queries.communityChannel.listChildChannels(db, scope.channelId)+ ? scope.isForum+ ? queries.communityChannel.listChildChannelsByParentMessageIds(db, scope.channelId, messageIds)+ : queries.communityChannel.listChildChannels(db, scope.channelId): Promise.resolve([]),queries.communityMessage.getLatestMessageSeq(db, { channelId: scope.channelId }),// Friend-approval cards only ever live in DMs — skip the hydration query@@ -53,10 +59,54 @@ export async function enrichMessages(const reactionsByMessage = groupReactions(allReactions, userId)const replyMap = new Map(replyMessages.map((m) => [m.id, m]))+ const threadIds = childChannels.map((channel) => channel.id)+ const [forumTags, forumFirstMessages, forumParticipants] = scope.isForum && messageIds.length > 0+ ? await Promise.all([+ queries.communityMessageTag.listTagsForMessages(db, messageIds),+ queries.communityMessage.getFirstMessageByChannelIds(db, threadIds),+ queries.communityThread.listParticipantsForChannels(db, threadIds, 5),+ ])+ : [[], [], []]+ const tagsByMessage = new Map<string, string[]>()+ for (const row of forumTags) {+ tagsByMessage.set(row.messageId, [...(tagsByMessage.get(row.messageId) ?? []), row.tag])+ }+ const firstByChannel = new Map(forumFirstMessages.map((message) => [message.channelId, message]))+ const participantsByChannel = new Map<string, Array<{ id: string; name: string; avatar: string }>>()+ const participantCountByChannel = new Map<string, number>()+ for (const row of forumParticipants) {+ participantCountByChannel.set(+ row.channelId,+ "participantCount" in row ? Number(row.participantCount) : 0,+ )+ participantsByChannel.set(row.channelId, [+ ...(participantsByChannel.get(row.channelId) ?? []),+ {+ id: row.userId,+ name: row.userName ?? "",+ avatar: row.userImage ?? avatarInitial(row.userName ?? ""),+ },+ ])+ }+const threadByMessageId = new Map(childChannels.filter((c) => c.parentMessageId)- .map((c) => [c.parentMessageId!, { id: c.id, name: c.name, messageCount: c.messageCount ?? 0 }] as const),+ .map((c) => {+ const first = firstByChannel.get(c.id)+ return [c.parentMessageId!, {+ id: c.id,+ name: c.name,+ messageCount: c.messageCount ?? 0,+ lastReplyAt: c.lastMessageAt ?? c.createdAt,+ ...(scope.isForum ? {+ tags: tagsByMessage.get(c.parentMessageId!) ?? [],+ preview: (first?.content ?? "").slice(0, 100),+ participants: participantsByChannel.get(c.id) ?? [],+ participantCount: participantCountByChannel.get(c.id) ?? 0,+ } : {}),+ }] as const+ }),)const messages = items.map((r) =>diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 41f6e829e..87bd25cd5 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -43,13 +43,13 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s/*** Resolves the recipient set for a channel event.*- * - THREAD (`type="thread"`) or FORUM_POST (`type="forum_post"`) → the unit's- * NOTIFY set (its participant rows). Both are the notification dimension:- * message events reach only participants (join by spoke/mention/added), NOT- * the whole parent channel or server, and NOT admins (never auto-participants).- * A public post therefore no longer blasts the whole server, and a private- * post no longer pings every roster member on every message — only the people- * actually involved. Nested-membership model.+ * - THREAD (`type="thread"`, including a post — a thread rooted directly+ * under a forum) → the unit's NOTIFY set (its participant rows) — the+ * notification dimension: message events reach only participants (join by+ * spoke/mention/added), NOT the whole parent channel or server, and NOT+ * admins (never auto-participants). A public post therefore doesn't blast+ * the whole server, and a private post doesn't ping every roster member on+ * every message — only the people actually involved.* - DM (`type="dm"`) → its two `relation='access'` members. A DM has* `server_id = NULL`, so it must NOT fall through to the server-scoped* resolver (which would query `server_id = NULL` and return an empty set).@@ -72,7 +72,7 @@ async function getChannelRecipientUserIds(db: Database, channelId: string): Promconst reach = isStoredChannelType(type) ? channelReach(type) : "server-or-roster"switch (reach) {case "participant-set":- // Thread / forum_post: the unit's notify (participant) rows — the same set+ // Child thread: the unit's notify (participant) rows — the same set// the send-path enroll writes into.return withD1Retry(() => queries.communityThread.listThreadParticipantUserIds(db, channelId),@@ -102,7 +102,7 @@ async function getChannelRecipientUserIds(db: Database, channelId: string): Prom* Public wrapper so `message-handler` can resolve a channel's recipient set* ONCE and share it between the unfiltered `MESSAGE_CREATE` fan-out and the* level-filtered notify pipeline (no second membership query). Same split as- * `getChannelRecipientUserIds` (thread/forum_post → participants; dm → access+ * `getChannelRecipientUserIds` (child thread → participants; dm → access* members; channel/forum → scope audience).*/export async function resolveChannelRecipients(db: Database, channelId: string): Promise<string[]> {diff --git a/src/web/src/lib/community/forum-tag-selection.test.ts b/src/web/src/lib/community/forum-tag-selection.test.tsnew file mode 100644index 000000000..dbe69d6b1--- /dev/null+++ b/src/web/src/lib/community/forum-tag-selection.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it, vi } from "vitest"+import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "./forum-tag-selection"++describe("forum tag selection", () => {+ it("defaults to All and scopes persisted selections by channel", () => {+ const getItem = vi.fn((key: string) => key.endsWith("forum-a") ? "bug" : null)+ expect(readForumTagSelection({ getItem }, "forum-a")).toBe("bug")+ expect(readForumTagSelection({ getItem }, "forum-b")).toBe("All")+ })++ it("stores a selected tag and removes All", () => {+ const storage = { setItem: vi.fn(), removeItem: vi.fn() }+ writeForumTagSelection(storage, "forum-a", "bug")+ expect(storage.setItem).toHaveBeenCalledWith("alook:forum-tag:forum-a", "bug")+ writeForumTagSelection(storage, "forum-a", "All")+ expect(storage.removeItem).toHaveBeenCalledWith("alook:forum-tag:forum-a")+ })++ it("keeps a restored tag only after it exists in the scoped distinct set", () => {+ expect(validateForumTagSelection("bug", ["bug", "feature"])).toBe("bug")+ expect(validateForumTagSelection("gone", ["bug", "feature"])).toBe("All")+ })+})diff --git a/src/web/src/lib/community/forum-tag-selection.ts b/src/web/src/lib/community/forum-tag-selection.tsnew file mode 100644index 000000000..bf5382a6d--- /dev/null+++ b/src/web/src/lib/community/forum-tag-selection.ts@@ -0,0 +1,14 @@+const keyFor = (channelId: string) => `alook:forum-tag:${channelId}`++export function readForumTagSelection(storage: Pick<Storage, "getItem">, channelId: string): string {+ return storage.getItem(keyFor(channelId)) || "All"+}++export function writeForumTagSelection(storage: Pick<Storage, "setItem" | "removeItem">, channelId: string, tag: string): void {+ if (tag === "All") storage.removeItem(keyFor(channelId))+ else storage.setItem(keyFor(channelId), tag)+}++export function validateForumTagSelection(tag: string, availableTags: string[]): string {+ return tag === "All" || availableTags.includes(tag) ? tag : "All"+}diff --git a/src/web/src/lib/community/friend-cards.ts b/src/web/src/lib/community/friend-cards.tsnew file mode 100644index 000000000..06081e83e--- /dev/null+++ b/src/web/src/lib/community/friend-cards.ts@@ -0,0 +1,65 @@+import type { FriendCard } from "@alook/shared"+import { wsDoFetch } from "@/lib/broadcast"++/** The peer-row shape the friendship bucket queries project (listAgentFriends). */+export type FriendPeerRow = {+ peerUserId: string+ name: string+ discriminator: string | null+ aboutMe?: string | null+ statusText?: string | null+ statusEmoji?: string | null+}++/**+ * Bulk WS presence check — one `/presence/users` round-trip across every peer+ * id. Best-effort: any failure defaults everyone offline (presence is a live+ * nicety, never blocks the list). Extracted from the pre-fold flat `listFriends`+ * verb so the split bucket endpoints (friends/accepted, friends/pending) share+ * one presence path instead of each re-implementing it.+ */+export async function resolvePresence(+ env: Parameters<typeof wsDoFetch>[0],+ peerIds: string[],+ label: string,+): Promise<Set<string>> {+ const unique = [...new Set(peerIds)]+ if (unique.length === 0) return new Set()+ try {+ const resp = await wsDoFetch(+ env,+ "/presence/users",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ids: unique }),+ },+ { label },+ )+ if (resp.ok) {+ const data = (await resp.json()) as { online: string[] }+ if (Array.isArray(data.online)) return new Set(data.online)+ }+ } catch {+ /* presence best-effort — default everyone offline */+ }+ return new Set()+}++/**+ * Project a friendship peer row to the lean bot `FriendCard` (the shape+ * `alook friend list` renders). `presence` is looked up in the pre-resolved+ * online set. Identical mapping to the pre-fold flat verb's `toCard`, lifted so+ * every bucket endpoint's bot arm emits the same card.+ */+export function toFriendCard(row: FriendPeerRow, onlineSet: Set<string>): FriendCard {+ return {+ userId: row.peerUserId,+ handle: `${row.name}#${row.discriminator ?? "0000"}`,+ name: row.name,+ bio: row.aboutMe ?? null,+ statusText: row.statusText ?? null,+ statusEmoji: row.statusEmoji ?? null,+ presence: onlineSet.has(row.peerUserId) ? "online" : "offline",+ }+}diff --git a/src/web/src/lib/community/list-channels.ts b/src/web/src/lib/community/list-channels.tsnew file mode 100644index 000000000..0abb4e8b2--- /dev/null+++ b/src/web/src/lib/community/list-channels.ts@@ -0,0 +1,83 @@+import {+ queries,+ formatCanonicalRef,+ formatHandle,+ type StoredChannelType,+} from "@alook/shared"+import type {+ CommunityCliChannelGroup as ChannelGroup,+ ChannelListItem,+} from "@alook/shared"+import type { getDb } from "@/lib/db"++/**+ * Shared per-server channel-list builder for the bot arm of `GET+ * servers/[id]/channels` (single server) and `GET servers/channels` (all of a+ * bot's servers). Extracted from the pre-fold flat `listChannels` verb so the+ * two dual-actor doors emit an identical `ChannelGroup[]` shape — the folded+ * verb had this logic inline; centralizing it keeps the single/all-servers arms+ * from drifting.+ *+ * Top-level channels only (`listChannelsForMember` filters `parentChannelId IS+ * NULL`) — same visibility a human sees. Channels bucket by `categoryId`+ * (uncategorized first, then categories by position); empty category groups are+ * dropped so a private-category name never leaks. The ref is emitted through the+ * single canonical emitter (`formatCanonicalRef`), the same one send/read/ack+ * resolve against, so the list can't drift from how a ref addresses.+ */+export async function buildServerChannelGroups(+ db: ReturnType<typeof getDb>,+ server: { id: string; name: string; discriminator: string },+ memberUserId: string,+): Promise<ChannelGroup[]> {+ const [rows, categories] = await Promise.all([+ queries.communityChannel.listChannelsForMember(db, server.id, memberUserId),+ queries.communityCategory.listCategoriesByServer(db, server.id),+ ])++ const categoryById = new Map<string, { id: string; name: string; position: number | null; private: number | null }>()+ for (const c of categories) categoryById.set(c.id, c)++ const uncategorized: ChannelListItem[] = []+ const byCategory = new Map<string, ChannelListItem[]>()++ // rows come from `listChannelsForMember` already ordered by+ // `communityChannel.position asc`; bucket into groups preserving that+ // per-bucket order.+ for (const c of rows) {+ const cat = c.categoryId ? categoryById.get(c.categoryId) : null+ const isPrivate = !!(cat && (cat.private ?? 0) === 1)+ const ref = formatCanonicalRef({+ type: (c.type ?? "text") as StoredChannelType,+ serverHandle: formatHandle(server.name, server.discriminator),+ name: c.name,+ })+ const item: ChannelListItem = {+ ref: ref!,+ name: c.name,+ type: c.type,+ visibility: isPrivate ? "private" : "public",+ }+ if (!c.categoryId || !cat) {+ uncategorized.push(item)+ } else {+ const bucket = byCategory.get(c.categoryId) ?? []+ bucket.push(item)+ byCategory.set(c.categoryId, bucket)+ }+ }++ const serverGroups: ChannelGroup[] = []+ if (uncategorized.length > 0) {+ serverGroups.push({ category: null, channels: uncategorized })+ }+ for (const cat of categories) {+ const items = byCategory.get(cat.id)+ if (!items || items.length === 0) continue+ serverGroups.push({+ category: { name: cat.name, private: (cat.private ?? 0) === 1 },+ channels: items,+ })+ }+ return serverGroups+}diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex aaa9dcd39..c4b381a04 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -33,7 +33,7 @@ const MENTION_LIMIT = 8// (`renderHTML`) and the rendered pill (message-markdown.tsx) both strip it// for display only.function mentionDisplayLabel(label: string): string {- return label.replace(/#\d{4}$/, "")+ return label.replace(/#\d{4,}$/, "")}// Pure ranker — exported for tests. Items are everyone/here followed bydiff --git a/src/web/src/lib/community/message-door.test.ts b/src/web/src/lib/community/message-door.test.tsnew file mode 100644index 000000000..ccd514628--- /dev/null+++ b/src/web/src/lib/community/message-door.test.ts@@ -0,0 +1,144 @@+import { describe, it, expect, vi, beforeEach } from "vitest"++const mockResolveTargetForMember = vi.fn()+const mockRequireMessageSurfaceAccess = vi.fn()+const mockRequireMessageBearingSurface = vi.fn()++vi.mock("./resolve-ref", () => ({+ resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),+}))+vi.mock("./permissions", () => ({+ requireMessageSurfaceAccess: (...a: unknown[]) => mockRequireMessageSurfaceAccess(...a),+}))+vi.mock("./channel-write-guard", () => ({+ requireMessageBearingSurface: (...a: unknown[]) => mockRequireMessageBearingSurface(...a),+}))++import { parseTargetDescriptor, resolveMessageTarget } from "./message-door"++const db = {} as never++describe("parseTargetDescriptor — id-xor-ref (Aigneis #190)", () => {+ it("accepts { id } alone", () => {+ expect(parseTargetDescriptor({ id: "c1" })).toEqual({ ok: true, value: { id: "c1" } })+ })++ it("accepts { ref } alone, threading create-if-missing (ref arm only)", () => {+ expect(parseTargetDescriptor({ ref: "/s/c", createDmIfMissing: true })).toEqual({+ ok: true,+ value: { ref: "/s/c", createDmIfMissing: true, createThreadIfMissing: undefined },+ })+ })++ it("rejects neither field", () => {+ expect(parseTargetDescriptor({})).toMatchObject({ ok: false, status: 400 })+ })++ it("rejects both fields (must be exactly one)", () => {+ expect(parseTargetDescriptor({ id: "c1", ref: "/s/c" })).toMatchObject({ ok: false, status: 400 })+ })++ it("rejects create-if-missing on the { id } arm (resolve≠create, structural)", () => {+ expect(parseTargetDescriptor({ id: "c1", createDmIfMissing: true })).toMatchObject({+ ok: false,+ status: 400,+ })+ expect(parseTargetDescriptor({ id: "c1", createThreadIfMissing: true })).toMatchObject({+ ok: false,+ status: 400,+ })+ })+})++describe("resolveMessageTarget — single mask output + surface→target (Aigneis ④)", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockRequireMessageBearingSurface.mockReturnValue({ ok: true })+ })++ it("id arm: passes the raw id THROUGH requireMessageSurfaceAccess (never trusts a web-sent id)", async () => {+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "c1", type: "text", serverId: "s1", parentChannelId: null } },+ })+ const res = await resolveMessageTarget(db, "u1", { id: "c1" }, "human")+ // The id did NOT skip the mask — the gate was invoked with it.+ expect(mockRequireMessageSurfaceAccess).toHaveBeenCalledWith(db, "c1", "u1")+ expect(mockResolveTargetForMember).not.toHaveBeenCalled()+ expect(res).toEqual({ ok: true, value: { target: { kind: "channel", channelId: "c1", serverId: "s1" }, isDm: false } })+ })++ it("ref arm: resolves then passes the resolved id through the SAME mask", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "c1" })+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "c1", type: "text", serverId: "s1", parentChannelId: null } },+ })+ const res = await resolveMessageTarget(db, "u1", { ref: "/s/c" }, "bot")+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(db, "u1", "/s/c", {+ createDmIfMissing: undefined,+ createThreadIfMissing: undefined,+ callerKind: "bot",+ })+ // Resolved id went through the same single mask output.+ expect(mockRequireMessageSurfaceAccess).toHaveBeenCalledWith(db, "c1", "u1")+ expect(res.ok).toBe(true)+ })++ it("mask failure propagates verbatim (opaque 404 / 403 from the gate)", async () => {+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: false, status: 404, error: "not found" })+ const res = await resolveMessageTarget(db, "u1", { id: "c1" }, "human")+ expect(res).toEqual({ ok: false, status: 404, error: "not found" })+ })++ it("dm surface → dm-kind target, otherUserId consumed from the dispatch peer (no re-query)", async () => {+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "dm", dm: { id: "d1", otherUserId: "u2" } },+ })+ const res = await resolveMessageTarget(db, "u1", { id: "d1" }, "human")+ expect(res).toEqual({ ok: true, value: { target: { kind: "dm", channelId: "d1", otherUserId: "u2" }, isDm: true } })+ // No bearing guard on the DM arm (a DM is a valid target).+ expect(mockRequireMessageBearingSurface).not.toHaveBeenCalled()+ })++ it("channel + parentChannelId + type thread → thread-kind target", async () => {+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "t1", type: "thread", serverId: "s1", parentChannelId: "p1" } },+ })+ const res = await resolveMessageTarget(db, "u1", { id: "t1" }, "human")+ expect(res).toMatchObject({ ok: true, value: { target: { kind: "thread", channelId: "t1", parentChannelId: "p1", serverId: "s1" } } })+ })++ it("bearing guard failure (e.g. forum top-level) → error, no target", async () => {+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "f1", type: "forum", serverId: "s1", parentChannelId: null } },+ })+ mockRequireMessageBearingSurface.mockReturnValue({ ok: false, status: 400, error: "not message-bearing" })+ const res = await resolveMessageTarget(db, "u1", { id: "f1" }, "human")+ expect(res).toMatchObject({ ok: false, status: 400 })+ })++ it("ref-resolve error (incl ambiguous-server hint) is threaded through, mask NOT reached", async () => {+ mockResolveTargetForMember.mockResolvedValue({ error: 400, message: "ambiguous server name", hint: [{ id: "s1" }] })+ const res = await resolveMessageTarget(db, "u1", { ref: "/gaming/c" }, "bot")+ expect(res).toMatchObject({ ok: false, status: 400, error: "ambiguous server name", hint: [{ id: "s1" }] })+ expect(mockRequireMessageSurfaceAccess).not.toHaveBeenCalled()+ })++ it("create-if-missing flags flow ONLY on the ref arm into resolveTargetForMember", async () => {+ mockResolveTargetForMember.mockResolvedValue({ kind: "dm", channelId: "d1", otherUserId: "u2" })+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "dm", dm: { id: "d1", otherUserId: "u2" } },+ })+ await resolveMessageTarget(db, "u1", { ref: "/.dm/bob#0001", createDmIfMissing: true }, "bot")+ expect(mockResolveTargetForMember).toHaveBeenCalledWith(db, "u1", "/.dm/bob#0001", {+ createDmIfMissing: true,+ createThreadIfMissing: undefined,+ callerKind: "bot",+ })+ })+})diff --git a/src/web/src/lib/community/message-door.ts b/src/web/src/lib/community/message-door.tsnew file mode 100644index 000000000..100167202--- /dev/null+++ b/src/web/src/lib/community/message-door.ts@@ -0,0 +1,160 @@+import type { Database } from "@alook/shared"+import { resolveTargetForMember, type TargetResolution } from "./resolve-ref"+import { requireMessageSurfaceAccess } from "./permissions"+import { requireMessageBearingSurface } from "./channel-write-guard"+import { type MessageTarget } from "./message-handler"++/**+ * Door result. Unlike `permissions.Result` (whose status is 401|403|404 — the+ * existence/authz codes), the door also surfaces 400 (bad descriptor / malformed+ * ref) and the resolve layer's 400/404, so it carries an open numeric status.+ */+type DoorResult<T> =+ | { ok: true; value: T }+ | { ok: false; status: number; error: string; hint?: unknown }++/**+ * The one-door target descriptor (Gener #744 / Aigneis #190).+ *+ * A message request addresses its target by EXACTLY ONE of:+ * - `id` — an already-resolved channelId (the web client holds it).+ * - `ref` — a `/server/channel` etc. ref string (CLI/bot hold this).+ *+ * EXPLICIT xor, not a sniffed unified field: disambiguating a disc-shaped id+ * from a `/`-bearing ref by FORM is a coincidence that breaks the day id+ * encoding changes or ref syntax grows — the field name is the contract+ * (Aigneis #190 / Melly #187). `id` is the degenerate, already-resolved case of+ * `ref`; both land on the SAME trunk.+ *+ * `createDmIfMissing` / `createThreadIfMissing` live ONLY on the ref arm — an+ * `id` already names an existing row, so create-if-missing is meaningless there;+ * keeping them off the id arm makes resolve≠create a type-level invariant (the+ * id arm structurally cannot create).+ */+export type MessageTargetDescriptor =+ | { id: string; ref?: undefined }+ | {+ ref: string+ id?: undefined+ createDmIfMissing?: boolean+ createThreadIfMissing?: boolean+ }++export type DoorTarget = {+ /** The MessageTarget for createCommunityMessage (kind + ids). */+ target: MessageTarget+ /** True when the resolved surface is a DM — callers pass this to enrichMessages. */+ isDm: boolean+}++/**+ * Validate a raw body's target descriptor into the id-xor-ref union.+ * Rejects: neither field, both fields, wrong types, and create-if-missing on+ * the id arm (structurally forbidden — resolve≠create).+ */+export function parseTargetDescriptor(body: unknown): DoorResult<MessageTargetDescriptor> {+ const b = (body ?? {}) as Record<string, unknown>+ const hasId = typeof b.id === "string" && b.id.length > 0+ const hasRef = typeof b.ref === "string" && b.ref.length > 0++ if (hasId && hasRef) return err(400, "target must be exactly one of { id } or { ref }, not both")+ if (!hasId && !hasRef) return err(400, "target requires one of { id } or { ref }")++ if (hasId) {+ // create-if-missing is meaningless on an already-resolved id; reject rather+ // than silently ignore, so the id arm can never carry a create intent.+ if (b.createDmIfMissing || b.createThreadIfMissing) {+ return err(400, "create-if-missing is only valid with { ref }, not { id }")+ }+ return ok({ id: b.id as string })+ }+ return ok({+ ref: b.ref as string,+ createDmIfMissing: b.createDmIfMissing === true || undefined,+ createThreadIfMissing: b.createThreadIfMissing === true || undefined,+ })+}++function ok<T>(value: T): DoorResult<T> {+ return { ok: true, value }+}+function err(status: number, error: string): DoorResult<never> {+ return { ok: false, status, error }+}++/**+ * Resolve a target descriptor to a MessageTarget, applying the SINGLE+ * existence-mask output both arms share (Aigneis ④, the hard red line).+ *+ * ⚠ The id arm does NOT trust the caller-supplied id: a web-sent id is put+ * through the EXACT same `requireMessageSurfaceAccess` gate as a ref-resolved+ * id. "id is web-trusted, skip the mask" would be strictly worse than the old+ * two-door inconsistency — an id door with no mask. So both arms:+ * 1. arrive at a channelId (id: direct; ref: resolveTargetForMember),+ * 2. pass through requireMessageSurfaceAccess (one collapse point, one opaque+ * 404 body — a stranger constructing an unreachable id eats the same four+ * cells: unknown→404 / non-member→403 / DM-non-participant→404 / blocked→403),+ * 3. build the MessageTarget from (surface + channel.type).+ *+ * The ONLY id/ref asymmetry is create-if-missing on the ref arm (Ingaborg #193):+ * a ref with a create flag may materialize its target (explicit verb); every+ * other side effect is byte-identical between the two forms.+ */+export async function resolveMessageTarget(+ db: Database,+ userId: string,+ descriptor: MessageTargetDescriptor,+ callerKind: "human" | "bot",+): Promise<DoorResult<DoorTarget>> {+ let channelId: string++ if (descriptor.ref !== undefined) {+ const resolved: TargetResolution = await resolveTargetForMember(db, userId, descriptor.ref, {+ createDmIfMissing: descriptor.createDmIfMissing,+ createThreadIfMissing: descriptor.createThreadIfMissing,+ callerKind,+ })+ if ("error" in resolved) {+ // Preserve the ambiguous-server-name candidate `hint` the CLI consumes+ // (resolveErrorResponse used to carry it) — dropping it would be a+ // silent CLI-facing regression.+ return { ok: false, status: resolved.error, error: resolved.message, hint: resolved.hint }+ }+ channelId = resolved.channelId+ } else {+ channelId = descriptor.id+ }++ // SINGLE mask output — both arms converge here (Aigneis ④).+ const access = await requireMessageSurfaceAccess(db, channelId, userId)+ if (!access.ok) return access++ if (access.value.surface === "dm") {+ // otherUserId consumed from the dispatch's DM peer — no re-query (Blondie #28).+ return ok({+ target: { kind: "dm", channelId, otherUserId: access.value.dm.otherUserId },+ isDm: true,+ })+ }++ const channel = access.value.channel+ const bearing = requireMessageBearingSurface(channel.type)+ if (!bearing.ok) return err(bearing.status, bearing.error)++ // A top-level `forum` channel gets its OWN kind (not the generic+ // "channel") so the send layer can dispatch "does this open a thread" off+ // the target's structural kind — the same channel.type this function+ // already resolved — instead of a body-field trigger.+ const target: MessageTarget = channel.parentChannelId+ ? {+ kind: "thread",+ channelId,+ parentChannelId: channel.parentChannelId,+ serverId: channel.serverId,+ }+ : channel.type === "forum"+ ? { kind: "forum", channelId, serverId: channel.serverId }+ : { kind: "channel", channelId, serverId: channel.serverId }++ return ok({ target, isDm: false })+}diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex fdd45413b..18bbf4fd7 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -5,7 +5,6 @@ const mockGetMessage = vi.fn()const mockGetMessageInScope = vi.fn()const mockHardDeleteMessage = vi.fn()const mockGetUserInternal = vi.fn()-const mockCreateAttachment = vi.fn()const mockReserveAttachmentsForMessage = vi.fn()const mockUnreserveAttachments = vi.fn()const mockListByMessageIds = vi.fn()@@ -38,7 +37,6 @@ vi.mock("@alook/shared", async () => {hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),},communityAttachment: {- createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),reserveAttachmentsForMessage: (...a: unknown[]) => mockReserveAttachmentsForMessage(...a),unreserveAttachments: (...a: unknown[]) => mockUnreserveAttachments(...a),listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),@@ -400,7 +398,6 @@ describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-conditiexpect(result).toEqual({ ok: false, status: 409, error: "seq_conflict" })// Lost the race — none of the downstream pipeline steps should fire.expect(mockGetMessage).not.toHaveBeenCalled()- expect(mockCreateAttachment).not.toHaveBeenCalled()expect(mockCreateMentions).not.toHaveBeenCalled()expect(mockFanOutToChannel).not.toHaveBeenCalled()expect(mockFanOutToDM).not.toHaveBeenCalled()@@ -453,32 +450,37 @@ describe("createCommunityMessage — attachment width/height reach the live WS bmockBroadcastToUser.mockResolvedValue(undefined)})- it("includes width/height on an image attachment in the MESSAGE_CREATE broadcast payload", async () => {+ it("includes width/height on an image attachment in the MESSAGE_CREATE broadcast payload (reserve-by-id)", async () => {+ // Reserve-by-id (route/disc step 2b): dimensions are written onto the+ // pending row at UPLOAD (single source) and reach the broadcast when the+ // reserved rows are re-read via listByMessageIds after the reserve. There is+ // no url-carried body path anymore — the caller passes attachmentIds.mockCreateMessage.mockResolvedValue({ id: "msg_1" })- mockCreateAttachment.mockResolvedValue({- id: "att_1",- filename: "photo.png",- r2Key: "channel/c1/uuid/photo.png",- contentType: "image/png",- size: 1000,- width: 1920,- height: 1080,- })+ mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])+ mockListByMessageIds.mockResolvedValue([+ {+ id: "att_1",+ messageId: "msg_1",+ targetId: "c1",+ filename: "photo.png",+ r2Key: "channel/c1/uuid/photo.png",+ contentType: "image/png",+ size: 1000,+ width: 1920,+ height: 1080,+ position: 0,+ },+ ])mockGetMessage.mockResolvedValue(messageRow())await createCommunityMessage({db: {} as never,authorId: "author_1",target: { kind: "channel", channelId: "c1", serverId: "srv_1" },- body: {- content: "hello",- attachments: [- { url: "/api/community/media/channel/c1/uuid/photo.png", filename: "photo.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },- ],- },+ body: { content: "hello" },+ attachmentIds: ["att_1"],})- expect(mockCreateAttachment).toHaveBeenCalledWith({}, expect.objectContaining({ width: 1920, height: 1080, r2Key: "channel/c1/uuid/photo.png" }))expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)const [, event] = mockFanOutToChannel.mock.calls[0]!expect(event.message.attachments).toEqual([@@ -710,15 +712,16 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad])})- it("forum_post: author joins as 'spoke' just like a thread (notify-scoped)", async () => {- // A forum_post enrolls participants identically to a thread — a message in- // a post notifies only its participants, not the whole server/roster.+ it("thread first reply: author joins as 'spoke' (notify-scoped)", async () => {+ // A thread's first reply (a post's old "body message") enrolls+ // participants — a message notifies only its participants, not the+ // whole server/roster.mockGetMessage.mockResolvedValue(messageRow({ content: "first reply", channelId: "p1" }))await createCommunityMessage({db: {} as never,authorId: "author_1",- target: { kind: "forum_post", channelId: "p1", parentChannelId: "forum_1", serverId: "srv_1" },+ target: { kind: "thread", channelId: "p1", parentChannelId: "forum_1", serverId: "srv_1" },body: { content: "first reply" },})@@ -728,14 +731,14 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-adexpect(mockCreateChannelMember).not.toHaveBeenCalled()})- it("forum_post: an in-audience @mention enrolls as a participant", async () => {+ it("thread under a forum: an in-audience @mention enrolls as a participant", async () => {mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Cara#0002", channelId: "p1" }))await createCommunityMessage({db: {} as never,authorId: "author_1",- target: { kind: "forum_post", channelId: "p1", parentChannelId: "forum_1", serverId: "srv_1" },+ target: { kind: "thread", channelId: "p1", parentChannelId: "forum_1", serverId: "srv_1" },body: { content: "hey @Cara#0002" },})@@ -745,19 +748,19 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad])})- it("forum_post + skipChildChannelUpdate: enroll STILL runs, but the parent CHILD_CHANNEL_UPDATE is suppressed", async () => {- // The forum-post CREATE path routes the first message as kind:"forum_post"- // (so an @-mentioned user enrolls as a participant → appears in members),- // AND sets skipChildChannelUpdate to avoid colliding with its own- // CHILD_CHANNEL_CREATE. Enroll and the WS tick are decoupled: enroll runs,- // the tick does not.+ it("thread under a forum + skipChildChannelUpdate: enroll STILL runs, but the parent CHILD_CHANNEL_UPDATE is suppressed", async () => {+ // The post-opening CREATE path (createMessageWithThread) routes its+ // reply as kind:"thread" (so an @-mentioned user enrolls as a+ // participant → appears in members), AND sets skipChildChannelUpdate to+ // avoid colliding with its own CHILD_CHANNEL_CREATE. Enroll and the WS+ // tick are decoupled: enroll runs, the tick does not.mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])mockGetMessage.mockResolvedValue(messageRow({ content: "welcome @Cara#0002", channelId: "p1" }))await createCommunityMessage({db: {} as never,authorId: "author_1",- target: { kind: "forum_post", channelId: "p1", parentChannelId: "forum_1", serverId: "srv_1" },+ target: { kind: "thread", channelId: "p1", parentChannelId: "forum_1", serverId: "srv_1" },body: { content: "welcome @Cara#0002" },skipChildChannelUpdate: true,})@@ -792,6 +795,42 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-adkind: "mention",})})++ it("suppressBroadcast (migration-backfill mode): STRUCTURAL core runs (enroll + mention rows), real-time delivery shell is fully dropped", async () => {+ // The existing-data migration's atomic primitive needs a create that+ // persists the message + enrolls participants + writes mention rows but+ // fires ZERO real-time WS (no ping / no M×N frames on historical+ // backfill). This proves the shell-OFF capability keeps the structural core+ // — unlike skipMentions, which would ALSO drop enroll (the 213-218 class bug+ // this whole knob-split guards against).+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])+ mockGetMessage.mockResolvedValue(messageRow({ content: "welcome @Cara#0002", channelId: "p1" }))++ const result = await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "thread", channelId: "p1", parentChannelId: "forum_1", serverId: "srv_1" },+ body: { content: "welcome @Cara#0002" },+ suppressBroadcast: true,+ })++ // Structural core KEPT: participant enroll (reach-axis write) still runs...+ expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "p1", [+ { userId: "author_1", source: "spoke" },+ { userId: "cara_1", source: "mention" },+ ])+ // ...and mention ROW persistence still runs (rows are not a broadcast).+ expect(mockCreateMentions).toHaveBeenCalledWith({}, {+ messageId: "msg_1",+ userIds: ["cara_1"],+ kind: "mention",+ })+ // Real-time delivery shell FULLY dropped: no WS fan-out of any kind.+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ // ...and no deferred thunk handed back either (unlike deferBroadcast).+ expect(result.ok).toBe(true)+ if (result.ok) expect(result.broadcast).toBeUndefined()+ })})describe("createCommunityMessage — attachment reservation-first flow (agent path)", () => {@@ -990,6 +1029,7 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa{id: "att_1",filename: "photo.png",+ targetId: "c1",r2Key: "channel/c1/uuid/photo.png",contentType: "image/png",size: 100,@@ -1014,7 +1054,9 @@ describe("createCommunityMessage — attachment reservation-first flow (agent paexpect.objectContaining({id: "att_1",filename: "photo.png",- url: "/api/community/media/channel/c1/uuid/photo.png",+ // id-addressed render URL (attachments fold) — served by the canonical+ // channels/{targetId}/attachments/{attachmentId} door.+ url: "/api/community/channels/c1/attachments/att_1",}),])expect(mockUnreserveAttachments).not.toHaveBeenCalled()diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 49c523c50..a3ae6624e 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -17,7 +17,7 @@ import type { Database } from "@alook/shared"import { fanOutToChannel, resolveChannelRecipients } from "./fanout"import { dispatchMessageNotify } from "./notify"import { mapMessageForWs } from "./message-payload"-import { mediaUrlFromKey } from "./storage"+import { attachmentUrl } from "./storage"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "./audit"const log = createLogger({ service: "community-message-handler" })@@ -30,13 +30,17 @@ export type MessageTarget =parentChannelId: stringserverId: string}- | {- kind: "forum_post"- channelId: string- parentChannelId: string- serverId: string- }| { kind: "dm"; channelId: string; otherUserId: string }+ // A top-level `forum`-type channel (parentChannelId is null — it's still+ // the addressed channel itself, not a child under it; peer to "channel",+ // not to "thread" which carries a parent). Split out from the generic+ // "channel" kind so the SEND layer can dispatch "does this send open a+ // thread" off the target's own structural kind — the same channel.type the+ // door already resolved — instead of an ad-hoc body field. A body field's+ // presence is a client choice, decoupled from the channel's actual type;+ // branching on the target's own kind here means there is only ever one+ // axis deciding this, not two that can drift apart.+ | { kind: "forum"; channelId: string; serverId: string }export function isDmTarget<T extends { kind: string }>(target: T): target is Extract<T, { kind: "dm" }>export function isDmTarget(kind: string): boolean@@ -56,43 +60,19 @@ export function isChannelTarget(target: { kind: string } | string): boolean {return (typeof target === "string" ? target : target.kind) === "channel"}-// A thread and a forum_post share the same notify + parent-tick behavior: both-// enroll participants (spoke/mention) and both fire the parent CHILD_CHANNEL_UPDATE-// via their `parentChannelId`. This narrows to the two variants that carry one.+// A thread enrolls participants (spoke/mention) and fires the parent+// CHILD_CHANNEL_UPDATE via its `parentChannelId`. This narrows to the one+// variant that carries one.function hasParentChannel(target: MessageTarget,-): target is Extract<MessageTarget, { kind: "thread" | "forum_post" }> {- return target.kind === "thread" || target.kind === "forum_post"-}--type IncomingAttachment = {- /**- * Full routable URL as returned by the human upload response- * (`/api/community/media/<key>`). The handler strips the `MEDIA_URL_PREFIX`- * to derive the stored `r2Key`. Kept on the wire (rather than switching- * clients to a raw key) so the human-composer POST shape stays unchanged.- */- url: string- filename: string- contentType: string- size: number- width?: number- height?: number-}--const MEDIA_URL_PREFIX = "/api/community/media/"--function r2KeyFromUrl(url: string): string | null {- if (!url.startsWith(MEDIA_URL_PREFIX)) return null- const rest = url.slice(MEDIA_URL_PREFIX.length)- return rest.length > 0 ? rest : null+): target is Extract<MessageTarget, { kind: "thread" }> {+ return target.kind === "thread"}export type IncomingMessageBody = {content?: unknownreplyToId?: unknownmentionType?: unknown- attachments?: unknown}type CreatedAttachment = {@@ -105,8 +85,37 @@ type CreatedAttachment = {height?: number | null}-function attachmentTargetId(target: MessageTarget): string {- return target.channelId+async function hydrateStoredAttachments(db: Database, messageId: string): Promise<CreatedAttachment[]> {+ const rows = await queries.communityAttachment.listByMessageIds(db, [messageId])+ return rows.map((row) => ({+ id: row.id,+ filename: row.filename,+ url: attachmentUrl(row.targetId, row.id),+ contentType: row.contentType,+ size: row.size,+ width: row.width,+ height: row.height,+ }))+}++export async function getCommunityMessageReplay(params: {+ db: Database+ authorId: string+ channelId: string+ clientNonce?: string+}): Promise<CreateMessageOk | null> {+ if (params.clientNonce === undefined) return null+ const existing = await withD1Retry(+ () => queries.communityMessage.getMessageByAuthorAndNonce(params.db, params.authorId, params.clientNonce!),+ { route: "message-handler:nonce-precheck" },+ )+ if (!existing || existing.channelId !== params.channelId) return null+ return {+ ok: true,+ row: existing,+ attachments: await hydrateStoredAttachments(params.db, existing.id),+ deduped: true,+ }}type FullMessageRow = NonNullable<@@ -191,13 +200,12 @@ export async function createCommunityMessage(params: {*/includeAuthorInFanout?: boolean/**- * Agent-attachment path: pending attachment ids the caller has already- * validated against (uploader, kind, target). When present, the handler- * pre-mints the message id, reserves the pending rows in a single- * atomic UPDATE, then inserts the message — compensating unreserves on- * every failure path so no message row is ever committed with a partial- * attachment set. Mutually exclusive with `body.attachments`, which is the- * human-composer path.+ * Reserve-by-id attachment path (the ONLY attachment path — human web and bot+ * both use it, route/disc step 2b). Pending attachment ids the caller has+ * already validated against (uploader, target). When present, the handler+ * pre-mints the message id, reserves the pending rows in a single atomic+ * UPDATE, then inserts the message — compensating unreserves on every failure+ * path so no message row is ever committed with a partial attachment set.*/attachmentIds?: string[]/**@@ -208,14 +216,35 @@ export async function createCommunityMessage(params: {* conflict — broadcasting before that commit would show a phantom card.*/deferBroadcast?: boolean+ /**+ * Migration-backfill mode: DROP every WS side effect entirely (MESSAGE_CREATE+ * fan-out, notify push, bot wake, CHILD_CHANNEL_UPDATE) — historical backfill+ * must not ping anyone or push M×N real-time frames. UNLIKE `deferBroadcast`,+ * which hands the caller a thunk to fire later, this simply never runs the+ * broadcast at all.+ *+ * CRITICAL (Aigneis #133 / Melly #135 / message-handler decouple at+ * `skipChildChannelUpdate`): this closes ONLY the real-time DELIVERY shell.+ * The STRUCTURAL core — the message row, thread open, and the notify-set+ * ENROLL (`addThreadParticipants`, the reach-axis participant write) + mention+ * ROW writes — all run inline ABOVE the broadcast block and are NOT gated by+ * this flag. Do NOT reach for `skipMentions` to silence a backfill: that flag+ * ALSO closes enroll + mention rows (`!skipMentions` at the enroll gate), which+ * would silently drop the migrated thread's participant set. Keep this flag+ * about DELIVERY only, so a migrated post's participants (opener + each reply's+ * author/mention) are identical to the new-build path.+ *+ * Built for the forum carrier-swap migration entry (route/disc trunk); no+ * real-time caller passes it, so real-time create behavior is unchanged.+ */+ suppressBroadcast?: boolean/*** Suppress ONLY the parent `CHILD_CHANNEL_UPDATE` WS emission — participant- * enroll (the notify-set write) still runs per `kind`. The forum-post CREATE- * path opts in: it routes the post's first message as `kind:"forum_post"` so- * mentioned users enroll as participants, but must not fire- * CHILD_CHANNEL_UPDATE because it already emits its own CHILD_CHANNEL_CREATE- * for the new post (the two would collide). Decouples enroll from the WS tick- * so dodging the collision no longer silently skips enrollment.+ * enroll (the notify-set write) still runs per `kind`. A thread-open's+ * first message opts in when the caller already emits its own+ * CHILD_CHANNEL_CREATE for the new thread (the two would otherwise+ * collide). Decouples enroll from the WS tick so dodging the collision no+ * longer silently skips enrollment.*/skipChildChannelUpdate?: boolean/**@@ -247,6 +276,7 @@ export async function createCommunityMessage(params: {skipWake,includeAuthorInFanout,deferBroadcast,+ suppressBroadcast,attachmentIds,skipChildChannelUpdate,clientNonce,@@ -262,13 +292,13 @@ export async function createCommunityMessage(params: {}}- const incomingAttachments = Array.isArray(body.attachments)- ? (body.attachments as IncomingAttachment[])- : undefined- if (- incomingAttachments &&- incomingAttachments.length > MAX_ATTACHMENTS_PER_MESSAGE- ) {+ // Reserve-by-id is the SINGLE attachment path (route/disc step 2b unified the+ // human composer onto the bot flow): every caller — human web AND bot — passes+ // pre-uploaded pending-row ids via `attachmentIds`; the route already validated+ // them against (uploader, target). There is no longer a url-carried inline+ // attachment path.+ const attachmentIdCount = Array.isArray(attachmentIds) ? attachmentIds.length : 0+ if (attachmentIdCount > MAX_ATTACHMENTS_PER_MESSAGE) {return {ok: false,status: 400,@@ -279,12 +309,8 @@ export async function createCommunityMessage(params: {// A message needs either text content OR at least one attachment. Empty// both means the client wired something wrong — but a bare// attachments-only send is a legitimate flow (drop an image, hit Enter).- // Agent-attachment path uses `attachmentIds` (pending rows reserved by- // reservation-first flow), NOT `body.attachments`; both count as- // "attachment present" for this guard.- const hasAgentAttachments = Array.isArray(attachmentIds) && attachmentIds.length > 0- const hasHumanAttachments = !!incomingAttachments && incomingAttachments.length > 0- if (content.trim().length === 0 && !hasHumanAttachments && !hasAgentAttachments) {+ const hasAttachments = attachmentIdCount > 0+ if (content.trim().length === 0 && !hasAttachments) {return { ok: false, status: 400, error: "content or attachments required" }}@@ -295,13 +321,8 @@ export async function createCommunityMessage(params: {// race where two concurrent first-sends both pass this check is caught at// insert time by the partial-unique-index handler below.if (clientNonce !== undefined) {- const existing = await withD1Retry(- () => queries.communityMessage.getMessageByAuthorAndNonce(db, authorId, clientNonce),- { route: "message-handler:nonce-precheck" },- )- if (existing) {- return { ok: true, row: existing, attachments: [], deduped: true }- }+ const replay = await getCommunityMessageReplay({ db, authorId, channelId: target.channelId, clientNonce })+ if (replay) return replay}// A client-supplied `replyToId` must reference a message IN THE TARGET@@ -400,7 +421,13 @@ export async function createCommunityMessage(params: {{ route: "message-handler:nonce-insert-race" },)if (existing) {- return { ok: true, row: existing, attachments: [], deduped: true }+ if (existing.channelId !== target.channelId) throw err+ return {+ ok: true,+ row: existing,+ attachments: await hydrateStoredAttachments(db, existing.id),+ deduped: true,+ }}}throw err@@ -474,52 +501,23 @@ export async function createCommunityMessage(params: {}}- // Human-composer path: insert attachment rows now that the message exists.- // Agent path: rows were already reserved and pointed at `created.id` via- // the pre-minted id, so no additional INSERT is needed here.+ // Reserve-by-id path (human web AND bot): the pending rows were reserved and+ // pointed at `created.id` above via `reserveAttachmentsForMessage`, so no+ // INSERT is needed here — just project the linked rows for the response. The+ // row already carries its dimensions (written at upload time, the single+ // source), so the display URL is derived id-addressed via `attachmentUrl`.let attachments: CreatedAttachment[] = []if (reserveIds) {const rows = await queries.communityAttachment.listByMessageIds(db, [created.id])attachments = rows.map((r) => ({id: r.id,filename: r.filename,- url: mediaUrlFromKey(r.r2Key),+ url: attachmentUrl(r.targetId, r.id),contentType: r.contentType,size: r.size,width: r.width,height: r.height,}))- } else if (incomingAttachments?.length) {- const targetId = attachmentTargetId(target)- attachments = await Promise.all(- incomingAttachments.map(async (att, idx) => {- const r2Key = r2KeyFromUrl(att.url)- if (!r2Key) {- throw new Error(`attachment url outside /api/community/media/: ${att.url}`)- }- const row = await queries.communityAttachment.createAttachment(db, {- messageId: created.id,- uploaderId: authorId,- targetId,- r2Key,- filename: att.filename,- position: idx,- contentType: att.contentType,- size: att.size,- width: att.width,- height: att.height,- })- return {- id: row.id,- filename: row.filename,- url: mediaUrlFromKey(row.r2Key),- contentType: row.contentType,- size: row.size,- width: row.width,- height: row.height,- }- }),- )}const row = await withD1Retry(@@ -674,23 +672,22 @@ export async function createCommunityMessage(params: {// Mention beats reply — never double-count the same user.for (const id of mentionTargets) replyTargets.delete(id)- // Thread / forum_post participation (notification dimension). Both units'- // NOTIFY set is their participant rows — join by:+ // Thread participation (notification dimension). A thread's NOTIFY set is+ // its participant rows — join by:// - speaking: the author becomes a participant (source "spoke").// - @mention: an explicitly mentioned/replied audience member becomes a// participant (source "mention"). `mentionTargets`/`replyTargets` are// already scoped to the unit's audience by the block above.// Admins are NOT auto-added — only real participation joins the set. System /- // card messages (`skipMentions`) don't add the author. A forum post is- // enrolled exactly like a thread so it notifies only its participants.+ // card messages (`skipMentions`) don't add the author.// Enroll gate = the REACH axis (B2): a message enrolls participants iff its// channel's reach is `participant-set`. This is the WRITE side of red-line ③ —// it keys on the SAME reach value that the fan-out recipient set and the// agent-inbox deliverable narrowing (the READ side, who's-participant) key on,// so who-enrolls and who's-read can never drift (the class of bug the agent// thread-inbox deadlock was). `target.kind` is the channel's stored type here- // (channel/thread/forum_post/dm). NOT folded with `hasParentChannel` below:- // that is a distinct STRUCTURAL fact ("has a parent channel" → railChannelId /+ // (channel/thread/forum/dm). NOT folded with `hasParentChannel` below: that+ // is a distinct STRUCTURAL fact ("has a parent channel" → railChannelId /// parent CHILD_CHANNEL_UPDATE tick), which merely coincides with participant-set// for today's types — a future type could have a parent but server reach, or// participant reach without a parent, so the two rules stay separate.@@ -847,6 +844,12 @@ export async function createCommunityMessage(params: {}}+ // Migration-backfill mode drops the real-time delivery shell entirely — the+ // structural core (row + thread + enroll + mention rows) already committed+ // inline above; `doBroadcast` is never run and no thunk is handed back.+ if (suppressBroadcast) {+ return { ok: true, row, attachments }+ }if (deferBroadcast) {return { ok: true, row, attachments, broadcast: doBroadcast }}diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.tsindex e3bdb6aa6..4db5ffe1e 100644--- a/src/web/src/lib/community/message-payload.test.ts+++ b/src/web/src/lib/community/message-payload.test.ts@@ -106,6 +106,15 @@ describe("mapMessageForApi", () => {const withoutThread = mapMessageForApi(baseRow, emptyApiCtx)expect(withoutThread.thread).toBeUndefined()})++ it("returns client-provided nonces and filters srv fallbacks", () => {+ expect(mapMessageForApi({ ...baseRow, clientNonce: "client-1" }, emptyApiCtx).clientNonce)+ .toBe("client-1")+ expect(mapMessageForApi({ ...baseRow, clientNonce: "srv:fallback" }, emptyApiCtx).clientNonce)+ .toBeUndefined()+ expect(mapMessageForApi({ ...baseRow, clientNonce: null }, emptyApiCtx).clientNonce)+ .toBeUndefined()+ })})describe("mapMessageForWs", () => {diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.tsindex b682abdc8..aa8dc84af 100644--- a/src/web/src/lib/community/message-payload.ts+++ b/src/web/src/lib/community/message-payload.ts@@ -37,6 +37,7 @@ export type MessageRow = {embeds: unknownseq: numbercreatedAt: string+ clientNonce?: string | null/** Friend-approval card back-ref — set only on approval card messages. */friendshipId?: string | null}@@ -49,7 +50,16 @@ type UiReaction = { emoji: string; count: number; me: boolean; userIds: string[]type ReplyPreview = { id: string; authorName: string; text: string; deleted?: boolean }-type ThreadPreview = { id: string; name: string; messageCount: number }+type ThreadPreview = {+ id: string+ name: string+ messageCount: number+ lastReplyAt?: string+ tags?: string[]+ preview?: string+ participants?: { id: string; name: string; avatar: string }[]+ participantCount?: number+}/** Common fields shared by both API and WS variants — derived exactly once. */function coreFields(row: MessageRow) {@@ -119,14 +129,17 @@ export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {const core = coreFields(row)const thread = ctx.threadByMessageId?.get(row.id)const approval = ctx.approvalByMessageId?.get(row.id)+ const clientNonce =+ row.clientNonce && !row.clientNonce.startsWith("srv:") ? row.clientNonce : undefinedreturn {...core,...splitType(row.type),+ ...(clientNonce ? { clientNonce } : {}),replyTo: resolveReply(row, ctx.replyMap),embeds: row.embeds,attachments: ctx.attachmentsByMessage[row.id]?.length ? ctx.attachmentsByMessage[row.id] : undefined,reactions: ctx.reactionsByMessage[row.id]?.length ? ctx.reactionsByMessage[row.id] : undefined,- thread: thread ? { id: thread.id, name: thread.name, messageCount: thread.messageCount } : undefined,+ thread,approval,}}diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.tsindex 8a2d2e6cd..c953d9dc2 100644--- a/src/web/src/lib/community/message-stream.test.ts+++ b/src/web/src/lib/community/message-stream.test.ts@@ -72,6 +72,10 @@ function canonical(return message(id, seq, { clientNonce: nonce, authorName: "Canonical", ...extra })}+function ack(nonce = "n1", id = "m1", seq = 11, extra: Partial<Msg> = {}): MessageOverlayEvent {+ return { type: "postAck", nonce, message: canonical(id, seq, nonce, extra) }+}+describe("message stream monotonic visibility", () => {it("keeps a pending row when an anchor snapshot started first and resolves without it", () => {let state = submit(emptyMessageOverlay())@@ -86,24 +90,24 @@ describe("message stream monotonic visibility", () => {it.each([["ack → WS → stale snapshot", [- { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ ack(),{ type: "wsMessage", message: canonical() },{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },]],["WS → ack → stale snapshot", [{ type: "wsMessage", message: canonical() },- { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ ack(),{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },]],["stale snapshot → ack → delayed WS", [{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },- { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ ack(),{ type: "wsMessage", message: canonical() },]],["WS → stale snapshot → ack", [{ type: "wsMessage", message: canonical() },{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },- { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ ack(),]],] satisfies Array<[string, MessageOverlayEvent[]]>) ("%s always materializes exactly one canonical row",@@ -125,6 +129,98 @@ describe("message stream monotonic visibility", () => {expect(state.liveById.size).toBe(1)})+ it("retains WS canonical rows when different authors reuse the same nonce", () => {+ let state = apply(emptyMessageOverlay(), {+ type: "wsMessage",+ message: canonical("m1", 11, "same", { authorId: "u1" }),+ }).state+ state = apply(state, {+ type: "wsMessage",+ message: canonical("m2", 12, "same", { authorId: "u2" }),+ }).state++ expect(materializeMessageStream([], state).map(({ id, authorId }) => [id, authorId])).toEqual([+ ["m1", "u1"],+ ["m2", "u2"],+ ])+ })++ it("retains GET base rows when different authors reuse the same nonce", () => {+ const base = [+ canonical("m1", 11, "same", { authorId: "u1" }),+ canonical("m2", 12, "same", { authorId: "u2" }),+ ]++ expect(materializeMessageStream(base, emptyMessageOverlay()).map(({ id, authorId }) => [id, authorId])).toEqual([+ ["m1", "u1"],+ ["m2", "u2"],+ ])+ })++ it("does not use srv-prefixed nonce values as canonical identity", () => {+ let state = apply(emptyMessageOverlay(), {+ type: "wsMessage",+ message: canonical("m1", 11, "srv:fallback", { authorId: "u1" }),+ }).state+ state = apply(state, {+ type: "wsMessage",+ message: canonical("m2", 12, "srv:fallback", { authorId: "u1" }),+ }).state+ const base = [+ canonical("m3", 13, "srv:fallback", { authorId: "u1" }),+ canonical("m4", 14, "srv:fallback", { authorId: "u1" }),+ ]++ expect(ids([], state)).toEqual(["m1", "m2"])+ expect(ids(base, emptyMessageOverlay())).toEqual(["m3", "m4"])+ })++ it("does not settle a viewer outbox intent from a peer WS row with the same nonce", () => {+ let state = submit(emptyMessageOverlay(), intent("same", 1, {+ message: { ...localMessage("mine"), authorId: "u1" },+ }))+ state = apply(state, {+ type: "wsMessage",+ message: canonical("m2", 12, "same", { authorId: "u2" }),+ }).state++ expect(state.outboxByNonce.has("same")).toBe(true)+ expect(ids([], state)).toEqual(["m2", "temp_same"])+ })++ it("does not settle a viewer outbox intent from a peer base row with the same nonce", () => {+ let state = submit(emptyMessageOverlay(), intent("same", 1, {+ message: { ...localMessage("mine"), authorId: "u1" },+ }))+ const peer = canonical("m2", 12, "same", { authorId: "u2" })+ state = apply(state, { type: "baseChanged", messages: [peer] }).state++ expect(state.outboxByNonce.has("same")).toBe(true)+ expect(ids([peer], state)).toEqual(["m2", "temp_same"])+ })++ it("retains server-id WS settlement when the canonical row omits the nonce", () => {+ let state = submit(emptyMessageOverlay())+ state = apply(state, ack()).state+ state = apply(state, {+ type: "wsMessage",+ message: message("m1", 11, { authorId: "u1", authorName: "Canonical" }),+ }).state++ expect(state.outboxByNonce.size).toBe(0)+ expect(ids([], state)).toEqual(["m1"])+ })++ it("retains server-id base settlement when the canonical row omits the nonce", () => {+ let state = submit(emptyMessageOverlay())+ state = apply(state, ack()).state+ const base = [message("m1", 11, { authorId: "u1", authorName: "Canonical" })]+ state = apply(state, { type: "baseChanged", messages: base }).state++ expect(state.outboxByNonce.size).toBe(0)+ expect(ids(base, state)).toEqual(["m1"])+ })+it("materializes an outbox row synchronously when base/pages are absent", () => {const state = submit(emptyMessageOverlay())expect(ids([], state)).toEqual(["temp_n1"])@@ -173,25 +269,47 @@ describe("message stream monotonic visibility", () => {expect(state.outboxByNonce.size).toBe(1)expect(state.outboxByNonce.get("n1")?.status).toBe("pending")- state = apply(state, {- type: "postAck",- nonce: "n1",- serverMessageId: "m1",- serverSeq: 11,- }).state+ state = apply(state, ack()).statestate = apply(state, { type: "wsMessage", message: canonical() }).stateexpect(ids([], state)).toEqual(["m1"])expect(state.outboxByNonce.size).toBe(0)})+ it("merges the full POST canonical row into the intent while retaining optimistic reply and attachments", () => {+ const replyTo = { id: "reply_1", authorName: "Reply Author", text: "preview" }+ const attachments: Msg["attachments"] = [{ kind: "image", name: "image.png", url: "/local/image" }]+ let state = submit(emptyMessageOverlay(), intent("n1", 1, {+ message: { ...localMessage("optimistic"), replyTo, attachments },+ }))++ state = apply(state, ack("n1", "m1", 11, {+ authorName: "Canonical Author",+ authorAvatar: "canonical-avatar",+ content: "canonical content",+ createdAt: "2026-08-07T10:00:00.000Z",+ embeds: [{ title: "Canonical embed" }],+ })).state++ expect(materializeMessageStream([], state)).toEqual([+ expect.objectContaining({+ id: "m1",+ seq: 11,+ authorName: "Canonical Author",+ authorAvatar: "canonical-avatar",+ content: "canonical content",+ createdAt: "2026-08-07T10:00:00.000Z",+ embeds: [{ title: "Canonical embed" }],+ replyTo,+ attachments,+ clientNonce: "n1",+ failed: false,+ }),+ ])+ })+it("does not treat latestSeq as proof that an anchor window contains the row", () => {let state = submit(emptyMessageOverlay())- state = apply(state, {- type: "postAck",- nonce: "n1",- serverMessageId: "m1",- serverSeq: 11,- }).state+ state = apply(state, ack()).statestate = apply(state, {type: "baseChanged",messages: [message("anchor", 50)],@@ -204,12 +322,7 @@ describe("message stream monotonic visibility", () => {it("settles an exact base hit into a bounded fallback that survives later window omission", () => {let state = submit(emptyMessageOverlay())- state = apply(state, {- type: "postAck",- nonce: "n1",- serverMessageId: "m1",- serverSeq: 11,- }).state+ state = apply(state, ack()).statestate = apply(state, {type: "baseChanged",messages: [canonical("m1", 11, "n1", { content: "from base" })],@@ -264,12 +377,7 @@ describe("message stream monotonic visibility", () => {"m10", "m20", "temp_n1", "temp_n2",])- state = apply(state, {- type: "postAck",- nonce: "n2",- serverMessageId: "m15",- serverSeq: 15,- }).state+ state = apply(state, ack("n2", "m15", 15)).stateexpect(ids([message("m20", 20), message("m10", 10)], state)).toEqual(["m10", "m15", "m20", "temp_n1",])@@ -295,6 +403,36 @@ describe("message stream monotonic visibility", () => {expect(state.outboxByNonce.has("n2")).toBe(true)})+ it("does not refresh a live row from a peer row with the same nonce", () => {+ const state = apply(emptyMessageOverlay(), {+ type: "wsMessage",+ message: canonical("m1", 11, "same", { authorId: "u1", content: "original" }),+ }).state+ const transition = apply(state, {+ type: "liveRefreshed",+ message: canonical("m2", 12, "same", { authorId: "u2", content: "peer" }),+ })++ expect(transition.state).toBe(state)+ expect(transition.state.liveById.get("m1")?.content).toBe("original")+ expect(transition.state.liveById.has("m2")).toBe(false)+ })++ it("patches edited content across live and acknowledged outbox rows", () => {+ let state = submit(emptyMessageOverlay(), intent("n1", 1))+ state = apply(state, ack()).state+ state = apply(state, {+ type: "wsMessage",+ message: canonical("m2", 12, "n2", { content: "before" }),+ }).state++ state = apply(state, { type: "messageEdited", messageId: "m1", content: "outbox edit" }).state+ state = apply(state, { type: "messageEdited", messageId: "m2", content: "live edit" }).state++ expect(state.outboxByNonce.get("n1")?.message.content).toBe("outbox edit")+ expect(state.liveById.get("m2")?.content).toBe("live edit")+ })+it("bounds canonical live deltas to the existing 500-row live-tail scale", () => {let state = emptyMessageOverlay()for (let seq = 1; seq <= MAX_LIVE_MESSAGE_DELTAS + 2; seq++) {@@ -348,12 +486,7 @@ describe("attachment ownership effects", () => {nonce: "files",attachments: [{ kind: "file", name: "notes.txt", url: "/media/notes", size: "1 KB" }],}).state- const acked = apply(state, {- type: "postAck",- nonce: "files",- serverMessageId: "mf",- serverSeq: 20,- })+ const acked = apply(state, ack("files", "mf", 20))expect(acked.effects).toEqual([{ type: "revokeObjectUrl", url: "blob:a" },{ type: "revokeObjectUrl", url: "blob:b" },@@ -387,12 +520,7 @@ describe("attachment ownership effects", () => {{ type: "revokeObjectUrl", url: "blob:a" },{ type: "revokeObjectUrl", url: "blob:b" },])- const lateAck = apply(ws.state, {- type: "postAck",- nonce: "files",- serverMessageId: "mf",- serverSeq: 20,- })+ const lateAck = apply(ws.state, ack("files", "mf", 20))expect(lateAck.effects).toEqual([])})@@ -430,12 +558,7 @@ describe("attachment ownership effects", () => {it("emits cleanup exactly once for canonical base absorption and clear", () => {const state = submit(emptyMessageOverlay(), attachedIntent())- const acked = apply(state, {- type: "postAck",- nonce: "files",- serverMessageId: "mf",- serverSeq: 20,- })+ const acked = apply(state, ack("files", "mf", 20))expect(acked.effects).toHaveLength(2)const absorbed = apply(acked.state, { type: "baseChanged", messages: [canonical("mf", 20, "files")] })expect(absorbed.effects).toEqual([])diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.tsindex e4ad52af5..3a7acae12 100644--- a/src/web/src/lib/community/message-stream.ts+++ b/src/web/src/lib/community/message-stream.ts@@ -63,12 +63,13 @@ export type MessageOverlayEvent =| { type: "submit"; intent: NewOutboxIntent }| { type: "uploadSettled"; nonce: string; attachments: Msg["attachments"] }| { type: "uploadFailed"; nonce: string }- | { type: "postAck"; nonce: string; serverMessageId: string; serverSeq: number }+ | { type: "postAck"; nonce: string; message: CanonicalMessage }| { type: "postFail"; nonce: string }| { type: "terminalReject"; nonce: string }| { type: "retry"; nonce: string }| { type: "wsMessage"; message: CanonicalMessage }| { type: "liveRefreshed"; message: CanonicalMessage }+ | { type: "messageEdited"; messageId: string; content: string }| { type: "baseChanged"; messages: CanonicalMessage[]; latestSeq?: number }| { type: "dismissFailed"; nonce: string }| { type: "clear" }@@ -114,6 +115,15 @@ function canonicalDeltaOrder(a: CanonicalMessage, b: CanonicalMessage): number {return a.seq - b.seq}+function compoundIdentity(+ message: Pick<Msg, "authorId" | "clientNonce">,+): string | undefined {+ if (!message.authorId || !message.clientNonce || message.clientNonce.startsWith("srv:")) {+ return undefined+ }+ return JSON.stringify([message.authorId, message.clientNonce])+}+function trimLiveDeltas(liveById: Map<string, CanonicalMessage>): void {const overflow = liveById.size - MAX_LIVE_MESSAGE_DELTASif (overflow <= 0) return@@ -125,10 +135,10 @@ function upsertLiveCanonical(liveById: Map<string, CanonicalMessage>,message: CanonicalMessage,): void {- const nonce = message.clientNonce- if (nonce) {+ const identity = compoundIdentity(message)+ if (identity) {for (const [id, current] of liveById) {- if (id !== message.id && current.clientNonce === nonce) liveById.delete(id)+ if (id !== message.id && compoundIdentity(current) === identity) liveById.delete(id)}}liveById.set(message.id, { ...message, failed: false })@@ -172,15 +182,15 @@ function localUploadAttachments(function upsertMaterialized(byId: Map<string, MaterializedEntry>,- idByNonce: Map<string, string>,+ idByIdentity: Map<string, string>,entry: MaterializedEntry,): void {const { message } = entry- const nonce = message.clientNonce- if (nonce) {- const priorId = idByNonce.get(nonce)+ const identity = compoundIdentity(message)+ if (identity) {+ const priorId = idByIdentity.get(identity)if (priorId && priorId !== message.id) byId.delete(priorId)- idByNonce.set(nonce, message.id)+ idByIdentity.set(identity, message.id)}byId.set(message.id, entry)}@@ -208,21 +218,21 @@ export function materializeMessageStream(overlay: MessageOverlayState,): Msg[] {const byId = new Map<string, MaterializedEntry>()- const idByNonce = new Map<string, string>()+ const idByIdentity = new Map<string, string>()// Later sources replace earlier presentation for the same id/nonce:// optimistic outbox < complete WS row < complete base row.for (const intent of overlay.outboxByNonce.values()) {- upsertMaterialized(byId, idByNonce, {+ upsertMaterialized(byId, idByIdentity, {message: materializeIntent(intent),localOrdinal: intent.status === "acked" ? undefined : intent.localOrdinal,})}for (const message of overlay.liveById.values()) {- upsertMaterialized(byId, idByNonce, { message })+ upsertMaterialized(byId, idByIdentity, { message })}for (const message of baseMessages) {- upsertMaterialized(byId, idByNonce, { message })+ upsertMaterialized(byId, idByIdentity, { message })}return [...byId.values()].sort(materializedOrder).map((entry) => entry.message)@@ -294,13 +304,21 @@ export function reduceMessageOverlay(const intent = state.outboxByNonce.get(event.nonce)if (!intent) return unchanged(state)const outboxByNonce = new Map(state.outboxByNonce)+ const canonical = event.messageoutboxByNonce.set(event.nonce, {...intent,status: "acked",- serverMessageId: event.serverMessageId,- serverSeq: event.serverSeq,+ serverMessageId: canonical.id,+ serverSeq: canonical.seq,localUploads: [],- message: { ...intent.message, failed: false },+ message: {+ ...intent.message,+ ...canonical,+ clientNonce: event.nonce,+ replyTo: canonical.replyTo ?? intent.message.replyTo,+ attachments: canonical.attachments ?? intent.message.attachments,+ failed: false,+ },})return {state: { ...state, outboxByNonce },@@ -338,13 +356,17 @@ export function reduceMessageOverlay(const liveById = new Map(state.liveById)const outboxByNonce = new Map(state.outboxByNonce)const effects: MessageOverlayEffect[] = []- const nonce = event.message.clientNonce+ const eventIdentity = compoundIdentity(event.message)for (const [intentNonce, intent] of outboxByNonce) {- const matchesNonce = nonce !== undefined && intentNonce === nonce- const matchesServerId = intent.serverMessageId !== undefined- && intent.serverMessageId === event.message.id- if (!matchesNonce && !matchesServerId) continue+ if (intent.message.authorId !== event.message.authorId) continue+ const intentIdentity = compoundIdentity({+ authorId: intent.message.authorId,+ clientNonce: intentNonce,+ })+ const matchesIdentity = eventIdentity !== undefined && eventIdentity === intentIdentity+ const matchesServerId = intent.serverMessageId === event.message.id+ if (!matchesIdentity && !matchesServerId) continueoutboxByNonce.delete(intentNonce)effects.push(...revokeEffects(intent))}@@ -359,9 +381,10 @@ export function reduceMessageOverlay(let existingId: string | undefinedif (state.liveById.has(event.message.id)) {existingId = event.message.id- } else if (event.message.clientNonce) {+ } else {+ const identity = compoundIdentity(event.message)for (const [id, message] of state.liveById) {- if (message.clientNonce === event.message.clientNonce) {+ if (identity && compoundIdentity(message) === identity) {existingId = idbreak}@@ -375,25 +398,59 @@ export function reduceMessageOverlay(return { state: { ...state, liveById }, effects: [] }}+ case "messageEdited": {+ let changed = false+ const liveById = new Map(state.liveById)+ const live = liveById.get(event.messageId)+ if (live) {+ liveById.set(event.messageId, { ...live, content: event.content })+ changed = true+ }+ const outboxByNonce = new Map(state.outboxByNonce)+ for (const [nonce, intent] of outboxByNonce) {+ if ((intent.serverMessageId ?? intent.tempId) !== event.messageId) continue+ outboxByNonce.set(nonce, {+ ...intent,+ message: { ...intent.message, content: event.content },+ })+ changed = true+ }+ return changed+ ? { state: { ...state, liveById, outboxByNonce }, effects: [] }+ : unchanged(state)+ }+case "baseChanged": {const baseById = new Map(event.messages.map((message) => [message.id, message]))- const baseByNonce = new Map(- event.messages.flatMap((message) =>- message.clientNonce ? [[message.clientNonce, message] as const] : []),+ const baseByIdentity = new Map(+ event.messages.flatMap((message) => {+ const identity = compoundIdentity(message)+ return identity ? [[identity, message] as const] : []+ }),)const liveById = new Map(state.liveById)const outboxByNonce = new Map(state.outboxByNonce)const effects: MessageOverlayEffect[] = []for (const message of state.liveById.values()) {+ const identity = compoundIdentity(message)const canonical = baseById.get(message.id)- ?? (message.clientNonce ? baseByNonce.get(message.clientNonce) : undefined)+ ?? (identity ? baseByIdentity.get(identity) : undefined)if (canonical) upsertLiveCanonical(liveById, canonical)}for (const [nonce, intent] of outboxByNonce) {- const canonical = intent.serverMessageId- ? baseById.get(intent.serverMessageId) ?? baseByNonce.get(nonce)- : baseByNonce.get(nonce)+ const canonicalById = intent.serverMessageId+ ? baseById.get(intent.serverMessageId)+ : undefined+ const identity = compoundIdentity({+ authorId: intent.message.authorId,+ clientNonce: nonce,+ })+ const canonical = canonicalById?.authorId === intent.message.authorId+ ? canonicalById+ : identity+ ? baseByIdentity.get(identity)+ : undefinedif (!canonical) continueoutboxByNonce.delete(nonce)upsertLiveCanonical(liveById, canonical)diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.tsindex 04f6e017e..f7e513f63 100644--- a/src/web/src/lib/community/message-wire.ts+++ b/src/web/src/lib/community/message-wire.ts@@ -6,6 +6,18 @@ import type { CanonicalMessage } from "@/lib/community/message-stream"type UiEmbed = NonNullable<Msg["embeds"]>[number]+export type PostedMessage = {+ id: string+ seq: number+ createdAt: string+ content: string | null+ authorId: string+ authorName: string+ authorImage: string | null+ type: string | null+ embeds: unknown+}+function stringValue(value: unknown): string | undefined {return typeof value === "string" ? value : undefined}@@ -117,3 +129,32 @@ export function projectCommunityMessageCreate(...(attachments?.length ? { attachments } : {}),}}++export function projectPostedMessage(+ message: PostedMessage,+ clientNonce: string,+): CanonicalMessage {+ const embeds = Array.isArray(message.embeds)+ ? message.embeds.flatMap((embed) => {+ const projected = projectEmbed(embed)+ return projected ? [projected] : []+ })+ : undefined+ const type = message.type === "thread_created"+ ? { type: "system" as const, systemKind: "thread" as const }+ : message.type === "system"+ ? { type: "system" as const }+ : { type: "chat" as const }+ return {+ id: message.id,+ seq: message.seq,+ ...type,+ authorId: message.authorId,+ authorName: message.authorName,+ authorAvatar: message.authorImage || avatarInitial(message.authorName),+ content: message.content ?? "",+ createdAt: message.createdAt,+ clientNonce,+ ...(embeds?.length ? { embeds } : {}),+ }+}diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.tsindex 55f616ce5..7485eaed6 100644--- a/src/web/src/lib/community/messages.test.ts+++ b/src/web/src/lib/community/messages.test.ts@@ -48,36 +48,37 @@ describe("buildSinceResponse", () => {})})-// `groupAttachments` derives `url` from `r2Key` via the shared-// `mediaUrlFromKey` helper — the DB row itself no longer carries a `url`-// column (plan agent-attachment-pipeline.md). `width`/`height` are optional-// on the output shape, so we assert on the actual returned object rather than-// relying on the declared type to catch a missing field.+// `groupAttachments` derives the render `url` from the row's `targetId` + `id`+// via the shared `attachmentUrl` helper — the URL is id-addressed and served by+// the canonical `channels/{id}/attachments/{attachmentId}` door (route/disc+// attachments fold). The DB row carries no `url` column. `width`/`height` are+// optional on the output shape, so we assert on the actual returned object+// rather than relying on the declared type to catch a missing field.describe("groupAttachments", () => {it("projects width/height onto an image-kind entry when present on the row", () => {const result = groupAttachments([- { messageId: "m1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },+ { id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },])expect(result.m1).toEqual([- { kind: "image", name: "a.png", url: "/api/community/media/channel/c1/uuid/a.png", width: 1920, height: 1080 },+ { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", width: 1920, height: 1080 },])})it("leaves width/height undefined on an image-kind entry when the row has none", () => {const result = groupAttachments([- { messageId: "m1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: null, height: null },+ { id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: null, height: null },])expect(result.m1).toEqual([- { kind: "image", name: "a.png", url: "/api/community/media/channel/c1/uuid/a.png", width: undefined, height: undefined },+ { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", width: undefined, height: undefined },])})it("never adds width/height to a file-kind entry, even if present on the row", () => {const result = groupAttachments([- { messageId: "m1", filename: "a.pdf", r2Key: "channel/c1/uuid/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },+ { id: "att1", messageId: "m1", targetId: "c1", filename: "a.pdf", r2Key: "channel/c1/uuid/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },])expect(result.m1).toEqual([- { kind: "file", name: "a.pdf", url: "/api/community/media/channel/c1/uuid/a.pdf", size: "2.0 KB" },+ { kind: "file", name: "a.pdf", url: "/api/community/channels/c1/attachments/att1", size: "2.0 KB" },])})@@ -85,21 +86,21 @@ describe("groupAttachments", () => {"materializes unsafe %s attachments as file-kind",(contentType) => {const result = groupAttachments([- { messageId: "m1", filename: "unsafe.img", r2Key: "channel/c1/uuid/unsafe.img", contentType, size: 2048, width: 1920, height: 1080 },+ { id: "att1", messageId: "m1", targetId: "c1", filename: "unsafe.img", r2Key: "channel/c1/uuid/unsafe.img", contentType, size: 2048, width: 1920, height: 1080 },])expect(result.m1).toEqual([- { kind: "file", name: "unsafe.img", url: "/api/community/media/channel/c1/uuid/unsafe.img", size: "2.0 KB" },+ { kind: "file", name: "unsafe.img", url: "/api/community/channels/c1/attachments/att1", size: "2.0 KB" },])},)it("skips pending rows (messageId=null) so agent-uploaded pending attachments never surface", () => {const result = groupAttachments([- { messageId: null, filename: "pending.png", r2Key: "channel/c1/uuid/pending.png", contentType: "image/png", size: 100, width: null, height: null },- { messageId: "m1", filename: "linked.png", r2Key: "channel/c1/uuid/linked.png", contentType: "image/png", size: 100, width: null, height: null },+ { id: "att0", messageId: null, targetId: "c1", filename: "pending.png", r2Key: "channel/c1/uuid/pending.png", contentType: "image/png", size: 100, width: null, height: null },+ { id: "att1", messageId: "m1", targetId: "c1", filename: "linked.png", r2Key: "channel/c1/uuid/linked.png", contentType: "image/png", size: 100, width: null, height: null },])expect(result).toEqual({- m1: [{ kind: "image", name: "linked.png", url: "/api/community/media/channel/c1/uuid/linked.png", width: undefined, height: undefined }],+ m1: [{ kind: "image", name: "linked.png", url: "/api/community/channels/c1/attachments/att1", width: undefined, height: undefined }],})})})diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.tsindex 9a536d34e..b8460d630 100644--- a/src/web/src/lib/community/messages.ts+++ b/src/web/src/lib/community/messages.ts@@ -1,6 +1,6 @@import { DEFAULT_MESSAGE_PAGE_SIZE, MAX_MESSAGE_PAGE_SIZE } from "@alook/shared"-import { mediaUrlFromKey } from "./storage"import { isInlineAttachmentContentType } from "./attachment-content-type"+import { attachmentUrl } from "./storage"// Format file sizes for displayfunction formatBytes(bytes: number): string {@@ -153,7 +153,7 @@ export function buildMemberPaginatedResponse<T extends { joinedAt: string; id: s// with `messageId = null` (pending, not yet linked to a message) are skipped —// the read paths never surface them.export function groupAttachments(- attachments: Array<{ messageId: string | null; filename: string; r2Key: string; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>+ attachments: Array<{ id: string; messageId: string | null; targetId: string; filename: string; r2Key: string; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> {const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> = {}for (const a of attachments) {@@ -162,7 +162,7 @@ export function groupAttachments(const entry = {kind,name: a.filename,- url: mediaUrlFromKey(a.r2Key),+ url: attachmentUrl(a.targetId, a.id),...(kind === "file" && a.size ? { size: formatBytes(a.size) } : {}),...(kind === "image" ? { width: a.width ?? undefined, height: a.height ?? undefined } : {}),} as { kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }diff --git a/src/web/src/lib/community/notify.ts b/src/web/src/lib/community/notify.tsindex 5fa2dfd46..c442152e1 100644--- a/src/web/src/lib/community/notify.ts+++ b/src/web/src/lib/community/notify.ts@@ -64,8 +64,8 @@ export function shouldDeliver(level: NotificationLevelValue, wasMentioned: boole* Fire-and-forget: absorbs all failures (the message already synced via* `MESSAGE_CREATE`; a level-resolution blip must never fail the send).*- * @param channelId the message's channel scope. Every scope (channel, thread,- * forum_post, AND dm) resolves its per-recipient level here — there is NO+ * @param channelId the message's channel scope. Every scope (channel, child+ * thread, AND dm) resolves its per-recipient level here — there is NO* channelId-nullness bypass (main's DMs are channels with a channelId; a DM's* level is self-contained and defaults to `all`, so routing it through the* resolver both honors an explicit per-DM mute and never inherits a@@ -87,7 +87,7 @@ export async function dispatchMessageNotify(* patches the right server tree/rail (inbox-dot-ws-driven). Undefined for* a DM (no server). From the caller's `target.serverId`, no extra query. */serverId?: string- /** Sidebar-locatable row = `parentChannelId ?? channelId` (thread/forum-post+ /** Sidebar-locatable row = `parentChannelId ?? channelId` (child-thread* light the parent row). From the caller's target, no extra query. */railChannelId?: string},diff --git a/src/web/src/lib/community/permissions.test.ts b/src/web/src/lib/community/permissions.test.tsindex 88eeb88bb..32f0f8dd9 100644--- a/src/web/src/lib/community/permissions.test.ts+++ b/src/web/src/lib/community/permissions.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"const getMember = vi.fn()const getChannelForMember = vi.fn()+const getChannel = vi.fn()const resolveChannelAccessContext = vi.fn()const getDM = vi.fn()const getDMPeer = vi.fn()@@ -15,6 +16,7 @@ vi.mock("@alook/shared", async () => {communityMember: { getMember: (...a: unknown[]) => getMember(...a) },communityChannel: {getChannelForMember: (...a: unknown[]) => getChannelForMember(...a),+ getChannel: (...a: unknown[]) => getChannel(...a),resolveChannelAccessContext: (...a: unknown[]) => resolveChannelAccessContext(...a),},communityDm: {@@ -33,6 +35,7 @@ import {requireChannelAccess,requireDMAccess,requireNotBlocked,+ requireMessageSurfaceAccess,} from "./permissions"// Build a resolveChannelAccessContext return row. `anchor` defaults to the@@ -302,3 +305,73 @@ describe("requireNotBlocked", () => {})})++describe("requireMessageSurfaceAccess — id-in-path trunk dispatch (surface axis not flattened)", () => {+ beforeEach(() => {+ getChannel.mockReset()+ getChannelForMember.mockReset()+ getDM.mockReset()+ getDMPeer.mockReset()+ isBlocked.mockReset()+ })++ it("unknown channel id → single 404 on every surface (existence-masked)", async () => {+ getChannel.mockResolvedValue(null)+ const res = await requireMessageSurfaceAccess(db, "nope", "u1")+ expect(res).toEqual({ ok: false, status: 404, error: "not found" })+ })++ it("DM id → routes to requireDMAccess (block check runs — closes the P0), ok when a participant & not blocked", async () => {+ getChannel.mockResolvedValue({ id: "d1", type: "dm" })+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })+ isBlocked.mockResolvedValue(false)+ const res = await requireMessageSurfaceAccess(db, "d1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.surface).toBe("dm")+ // The block check that the plain-channel path never ran — now on the DM arm.+ expect(isBlocked).toHaveBeenCalledWith(db, "u1", "u2")+ })++ it("DM id, blocked participant → 403 (a legit known-participant 403, not existence disclosure)", async () => {+ getChannel.mockResolvedValue({ id: "d1", type: "dm" })+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })+ getDMPeer.mockResolvedValue({ otherUserId: "u2" })+ isBlocked.mockResolvedValue(true)+ const res = await requireMessageSurfaceAccess(db, "d1", "u1")+ expect(res).toEqual({ ok: false, status: 403, error: "blocked" })+ })++ it("DM id, non-participant → 404 with OPAQUE body (masks DM existence — same text as unknown-id 404, not 'dm not found')", async () => {+ getChannel.mockResolvedValue({ id: "d1", type: "dm" })+ getDM.mockResolvedValue({ id: "d1", lastMessageAt: null, createdAt: "2026-06-30" })+ getDMPeer.mockResolvedValue(null)+ const res = await requireMessageSurfaceAccess(db, "d1", "u1")+ // ④ (Aigneis #157): byte-identical to the unknown-id 404 body — a stranger+ // must not read "dm not found" and learn the id IS a DM.+ expect(res).toEqual({ ok: false, status: 404, error: "not found" })+ })++ it("channel id, known but non-member → 403 (the unknown case already 404'd above, so 403 = real non-member)", async () => {+ getChannel.mockResolvedValue({ id: "c1", type: "text" })+ getChannelForMember.mockResolvedValue(null) // known (getChannel found it) but caller not a member+ const res = await requireMessageSurfaceAccess(db, "c1", "u1")+ expect(res).toEqual({ ok: false, status: 403, error: "forbidden" })+ })++ it("channel id, member → ok, surface=channel", async () => {+ getChannel.mockResolvedValue({ id: "c1", type: "text" })+ getChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })+ const res = await requireMessageSurfaceAccess(db, "c1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.surface).toBe("channel")+ })++ it("thread id (child channel) → channel arm, member gate (thread inherits parent audience)", async () => {+ getChannel.mockResolvedValue({ id: "t1", type: "thread" })+ getChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })+ const res = await requireMessageSurfaceAccess(db, "t1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.surface).toBe("channel")+ })+})diff --git a/src/web/src/lib/community/permissions.ts b/src/web/src/lib/community/permissions.tsindex a5a07bc2b..a454f0b96 100644--- a/src/web/src/lib/community/permissions.ts+++ b/src/web/src/lib/community/permissions.ts@@ -1,4 +1,10 @@-import { queries, canManageServer, canSeePrivateChannel, withD1Retry } from "@alook/shared"+import {+ queries,+ canManageServer,+ canSeePrivateChannel,+ visibilityIsDmParticipant,+ withD1Retry,+} from "@alook/shared"import type { Database } from "@alook/shared"type PermissionError =@@ -78,7 +84,7 @@ export type ChannelAccess = {* - public/uncategorized → access; canManage only for admins* - private → access iff creator or added member (admins have NO implicit* content access); canManage iff admin (who can see it) or the unit creator- * Threads AND forum posts inherit their parent anchor's audience (the context+ * Child threads inherit their parent anchor's audience (the context* query climbs `parentChannelId`); a forum/top-level channel owns its roster.** Because access now requires membership/creator even for admins, an admin who@@ -158,6 +164,77 @@ export async function requireDMAccess(})}+export type MessageSurfaceAccess =+ | { surface: "dm"; dm: DMAccess }+ | {+ surface: "channel"+ channel: NonNullable<Awaited<ReturnType<typeof queries.communityChannel.getChannelForMember>>>+ }++/**+ * Unified message-surface access gate for the id-in-path trunk+ * (`channels/[id]/*`). One channelId, dispatched to the RIGHT per-surface gate+ * by the channel's stored type — because a DM is a `type='dm'` row in the same+ * channel id-space, so feeding a DM's id to the plain `requireChannelMember`+ * path would pass (it has no block check) and let a BLOCKED user still act. The+ * trunk must therefore route a DM id to `requireDMAccess`, not collapse every+ * surface onto one gate.+ *+ * ⚠ Surface axis is orthogonal to the type tree (Aigneis #142 / B3): unifying+ * the ROUTE structure must NOT flatten the per-surface no-access contract. Each+ * arm keeps its own existence-mask discipline BY CONSTRUCTION:+ * - **dm** → `requireDMAccess`: unknown / non-participant → 404 (masks DM+ * existence); a real, known participant who is blocked → 403 (a legitimate+ * 403 that doesn't disclose existence to a stranger).+ * - **channel / thread / forum(_post)** → the two-step contract sibling+ * channel routes honor: unknown channel → 404, known channel + non-member →+ * 403. `requireChannelMember` alone collapses both to 403 (the JOIN can't+ * tell them apart), so the 404 is produced HERE by the explicit getChannel+ * probe first — preserving the human 403/404 split.+ *+ * The dm-block fold (requireDMAccess) is exactly the P0 the trunk closes: the+ * old plain-channel message path never ran it.+ */+export async function requireMessageSurfaceAccess(+ db: Database,+ channelId: string,+ userId: string,+): Promise<Result<MessageSurfaceAccess>> {+ // One existence probe, reused for the type dispatch AND the channel-arm's+ // 404 leg — so an unknown id is a single 404 on every surface.+ const channel = await queries.communityChannel.getChannel(db, channelId)+ if (!channel) return err(404, "not found")++ // Dispatch on the VISIBILITY trait, not a bare `type === "dm"` literal — the+ // DM-participant visibility rule lives once in the trait table+ // (visibilityIsDmParticipant, B3 "instead of each re-testing type==='dm'"),+ // and this gate consumes it. Keeps who-is-a-dm / how-it-gates single-source+ // (route dispatch consumes CHANNEL_TRAITS, never re-derives a parallel+ // type→route judgement) and avoids seeding a literal type-switch the later+ // forum/thread arms would copy into a parallel type tree.+ if (visibilityIsDmParticipant(channel.type)) {+ const dm = await requireDMAccess(db, channelId, userId)+ if (!dm.ok) {+ // ④ opaque 404 (Aigneis #157): a 404 here and the top-level unknown-id+ // 404 must be byte-identical in body, not just status — else a stranger+ // holding a real DM's id reads "dm not found" and learns the id IS a DM.+ // The whole point of this gate is a UNIFIED no-access contract, so don't+ // leak the surface word through the 404 text. A 403 (blocked) is a+ // legitimate known-participant state and stays distinguishable.+ if (dm.status === 404) return err(404, "not found")+ return dm+ }+ return ok({ surface: "dm", dm: dm.value })+ }++ // channel / thread / forum: the id is known (probe above), so+ // requireChannelMember's collapse-to-403 now only fires for a real+ // non-member — the unknown case already 404'd. Preserves the 403/404 split.+ const member = await requireChannelMember(db, channelId, userId)+ if (!member.ok) return member+ return ok({ surface: "channel", channel: member.value })+}+/*** Verify neither user has blocked the other. Returns an error if blocked, ok* otherwise. Kept exported for two non-DM callers where the participantsdiff --git a/src/web/src/lib/community/resolve-ref.test.ts b/src/web/src/lib/community/resolve-ref.test.tsindex 5c5af3fb3..671bab243 100644--- a/src/web/src/lib/community/resolve-ref.test.ts+++ b/src/web/src/lib/community/resolve-ref.test.ts@@ -11,7 +11,6 @@ const mockResolveChannelByNameForMember = vi.fn()const mockGetMessageByChannelAndSeq = vi.fn()const mockGetThreadChannelByParentMessage = vi.fn()const mockCreateThreadChannel = vi.fn()-const mockGetChildChannelByName = vi.fn()const mockIsUniqueConstraintError = vi.fn(() => false)vi.mock("@alook/shared", async () => {@@ -39,7 +38,6 @@ vi.mock("@alook/shared", async () => {resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),createThreadChannel: (...a: unknown[]) => mockCreateThreadChannel(...a),- getChildChannelByName: (...a: unknown[]) => mockGetChildChannelByName(...a),},communityMessage: {getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),@@ -63,7 +61,7 @@ describe("resolveTargetForMember", () => {})it("400 rejects a ref carrying a pinned #N message seq", async () => {- const res = await resolveTargetForMember(db, "u_1", "/studio/general#5")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general#5")expect(res).toMatchObject({ error: 400 })expect((res as { message: string }).message).toMatch(/must not pin/)})@@ -123,37 +121,30 @@ describe("resolveTargetForMember", () => {})})- describe("channel refs (/server/channel)", () => {+ describe("channel refs (/server#disc/channel)", () => {it("404 server not found", async () => {mockResolveServerByNameForMember.mockResolvedValue([])- const res = await resolveTargetForMember(db, "u_1", "/studio/general")- expect(res).toEqual({ error: 404, message: "server not found: studio" })+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general")+ expect(res).toEqual({ error: 404, message: "server not found" })})- it("400 ambiguous server name returns hint list", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }, { id: "srv_2" }])+ it("400 rejects a bare server name before any lookup", async () => {const res = await resolveTargetForMember(db, "u_1", "/studio/general")- expect(res).toEqual({- error: 400,- message: "ambiguous server name",- hint: [- { id: "srv_1", path: "/srv_1/general" },- { id: "srv_2", path: "/srv_2/general" },- ],- })+ expect(res).toEqual({ error: 400, message: "malformed channel ref" })+ expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()})it("404 channel not found", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([])- const res = await resolveTargetForMember(db, "u_1", "/studio/general")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general")expect(res).toEqual({ error: 404, message: "channel not found: general" })})it("resolves a plain channel ref to { kind: channel, channelId }", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])- const res = await resolveTargetForMember(db, "u_1", "/studio/general")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general")expect(res).toEqual({ kind: "channel", channelId: "ch_1" })})@@ -163,7 +154,7 @@ describe("resolveTargetForMember", () => {// unreachable via the name path.mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_top" }])- const res = await resolveTargetForMember(db, "u_1", "/studio/general")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general")expect(res).toEqual({ kind: "channel", channelId: "ch_top" })expect(mockResolveChannelByNameForMember).toHaveBeenCalledWith(db, "srv_1", "u_1", "general")})@@ -173,19 +164,19 @@ describe("resolveTargetForMember", () => {// Name-only resolver returns [] when the segment is an id — the DB// lookup misses because the row's `name` column doesn't match the id.mockResolveChannelByNameForMember.mockResolvedValue([])- const res = await resolveTargetForMember(db, "u_1", "/studio/mFUplbfFL7PIzeiaP3Ysg")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/mFUplbfFL7PIzeiaP3Ysg")expect(res).toEqual({ error: 404, message: "channel not found: mFUplbfFL7PIzeiaP3Ysg" })})it("404 channel not found when caller passes a raw thread id (id refs rejected)", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([])- const res = await resolveTargetForMember(db, "u_1", "/studio/WyHlYFioUV_V9oRZXlSir")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/WyHlYFioUV_V9oRZXlSir")expect(res).toEqual({ error: 404, message: "channel not found: WyHlYFioUV_V9oRZXlSir" })})})- describe("thread refs (/server/channel/#N)", () => {+ describe("thread refs (/server#disc/channel/#N)", () => {beforeEach(() => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])@@ -193,14 +184,14 @@ describe("resolveTargetForMember", () => {it("404 when the root message (seq #N) doesn't exist", async () => {mockGetMessageByChannelAndSeq.mockResolvedValue(null)- const res = await resolveTargetForMember(db, "u_1", "/studio/general/#7")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general/#7")expect(res).toEqual({ error: 404, message: "no message with seq #7 in this channel" })})it("resolves to the existing thread channel when one already exists", async () => {mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_1" })mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "thread_1" })- const res = await resolveTargetForMember(db, "u_1", "/studio/general/#7")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general/#7")expect(res).toEqual({ kind: "channel", channelId: "thread_1" })expect(mockCreateThreadChannel).not.toHaveBeenCalled()})@@ -208,7 +199,7 @@ describe("resolveTargetForMember", () => {it("404 thread not found when missing and createThreadIfMissing is false", async () => {mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_1" })mockGetThreadChannelByParentMessage.mockResolvedValue(null)- const res = await resolveTargetForMember(db, "u_1", "/studio/general/#7")+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general/#7")expect(res).toEqual({ error: 404, message: "thread not found" })})@@ -216,7 +207,7 @@ describe("resolveTargetForMember", () => {mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_1" })mockGetThreadChannelByParentMessage.mockResolvedValue(null)mockCreateThreadChannel.mockResolvedValue({ id: "thread_new" })- const res = await resolveTargetForMember(db, "u_1", "/studio/general/#7", { createThreadIfMissing: true })+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general/#7", { createThreadIfMissing: true })expect(res).toEqual({ kind: "channel", channelId: "thread_new" })expect(mockCreateThreadChannel).toHaveBeenCalledWith(db, "ch_1", "msg_1", "u_1")})@@ -228,7 +219,7 @@ describe("resolveTargetForMember", () => {.mockResolvedValueOnce({ id: "thread_winner" })mockCreateThreadChannel.mockRejectedValue(new Error("unique constraint failed"))mockIsUniqueConstraintError.mockReturnValue(true)- const res = await resolveTargetForMember(db, "u_1", "/studio/general/#7", { createThreadIfMissing: true })+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/general/#7", { createThreadIfMissing: true })expect(res).toEqual({ kind: "channel", channelId: "thread_winner" })})@@ -238,48 +229,19 @@ describe("resolveTargetForMember", () => {mockCreateThreadChannel.mockRejectedValue(new Error("boom"))mockIsUniqueConstraintError.mockReturnValue(false)await expect(- resolveTargetForMember(db, "u_1", "/studio/general/#7", { createThreadIfMissing: true })+ resolveTargetForMember(db, "u_1", "/studio#0042/general/#7", { createThreadIfMissing: true })).rejects.toThrow("boom")})})- describe("forum-post refs (/server/forum/post)", () => {- beforeEach(() => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- // The parent forum resolves as a top-level channel.- mockResolveChannelByNameForMember.mockResolvedValue([{ id: "forum_1", name: "ideas" }])- })-- it("resolves a forum post by name under its forum", async () => {- mockGetChildChannelByName.mockResolvedValue([{ id: "post_1", name: "my-post" }])- const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/my-post")- expect(res).toEqual({ kind: "channel", channelId: "post_1" })- expect(mockGetChildChannelByName).toHaveBeenCalledWith(db, "forum_1", "my-post")- })-- it("404 when no post with that name exists under the forum", async () => {- mockGetChildChannelByName.mockResolvedValue([])- const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/ghost")- expect(res).toEqual({ error: 404, message: "post not found: ghost" })- })-- it("400 ambiguous (never silently picks) when >1 post shares the name", async () => {- mockGetChildChannelByName.mockResolvedValue([- { id: "post_1", name: "dupe" },- { id: "post_2", name: "dupe" },- ])- const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/dupe")- expect(res).toMatchObject({ error: 400 })- expect((res as { message: string }).message).toMatch(/ambiguous post name "dupe"/)- // Critically: no channelId is returned — the caller cannot mis-route.- expect(res).not.toHaveProperty("channelId")- })-- it("404 when the parent forum itself doesn't resolve", async () => {- mockResolveChannelByNameForMember.mockResolvedValue([])- const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/my-post")- expect(res).toEqual({ error: 404, message: "channel not found: ideas" })- expect(mockGetChildChannelByName).not.toHaveBeenCalled()+ describe("the old forum-post ref shape (/server/forum/post) is GONE, not routed", () => {+ it("400 malformed — never resolves to a channel (no-compat, phase2 forum≡thread)", async () => {+ // A post is now addressed like any other thread (by-root-seq); the old+ // 3-segment-no-hash form no longer parses at all, so resolution never+ // even reaches the server/channel lookups.+ const res = await resolveTargetForMember(db, "u_1", "/studio#0042/ideas/my-post")+ expect(res).toEqual({ error: 400, message: "malformed channel ref" })+ expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()})})})diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.tsindex 7f19e8766..7126f2aef 100644--- a/src/web/src/lib/community/resolve-ref.ts+++ b/src/web/src/lib/community/resolve-ref.ts@@ -1,5 +1,5 @@import { NextResponse } from "next/server"-import { queries, parseRef, DM_SERVER, parseNameAndTag, channelCreation } from "@alook/shared"+import { queries, parseRef, DM_SERVER, parseNameAndTag, channelCreation, withD1Retry } from "@alook/shared"import type { Database } from "@alook/shared"import { guardDmOpen } from "./dm-guard"import { createWithCollisionPolicy } from "./create-collision"@@ -19,8 +19,8 @@ export interface ResolveTargetOpts {}/**- * Resolve a CLI path ref (`ChannelRef`, e.g. `/studio/general`,- * `/studio/general/#42`, `/.dm/gusye#1231`) to a concrete channel/DM id,+ * Resolve a CLI path ref (`ChannelRef`, e.g. `/studio#0042/general`,+ * `/studio#0042/general/#42`, `/.dm/gusye#1231`) to a concrete channel/DM id,* scoped to `userId`'s memberships. Threads flatten to `{ kind: "channel",* channelId: <thread's own id> }` (debt #10 — threads ARE channels); the* caller (the `send` route) is responsible for reconstructing the full@@ -31,10 +31,9 @@ export interface ResolveTargetOpts {* Channel names are unique per server for top-level channels (migration* 0057's partial-unique index `idx_channel_server_name`) — the resolver* enforces the same invariant by matching only where `parentChannelId IS- * NULL`. Threads and forum posts are unreachable from this helper by name- * or id; use the canonical `#seq` grammar to descend into a thread. Server- * NAME ambiguity is still possible (server names are non-unique) and still- * returns `{ error: 400, hint: [...] }` so the agent can pick.+ * NULL`. A thread is unreachable from this helper by name or id; use the+ * canonical `#seq` grammar to descend into one. Real-server refs require a+ * unique name#discriminator handle; bare names and internal ids are rejected.* `createDmIfMissing`/`createThreadIfMissing` are both `true` for `send`* only — every other route passes `false` so a stale ref never materializes* a DM/thread row as a side effect of a read.@@ -52,7 +51,7 @@ export async function resolveTargetForMember(return { error: 400, message: "malformed channel ref" }}- // Message-pin form (`/server/channel#N`) has no use in this API surface —+ // Message-pin form (`/server#disc/channel#N`) has no use in this API surface —// every endpoint that needs to pin a message takes a separate `seq` field// (`resolve`, `read`). Reject rather than silently ignoring the `#N`.if (parsed.seq !== undefined) {@@ -90,49 +89,20 @@ export async function resolveTargetForMember(}// Channel form: resolve server, then channel, both scoped to membership.- const servers = await queries.communityServer.resolveServerByNameForMember(db, userId, parsed.server)- if (servers.length === 0) return { error: 404, message: `server not found: ${parsed.server}` }- if (servers.length > 1) {- return {- error: 400,- message: "ambiguous server name",- hint: servers.map((s) => ({ id: s.id, path: `/${s.id}/${parsed.channel}` })),- }- }+ const servers = await withD1Retry(+ () => queries.communityServer.resolveServerByNameForMember(db, userId, parsed.server),+ { route: "community/resolve-ref:server" }+ )+ if (servers.length === 0) return { error: 404, message: "server not found" }const serverId = servers[0]!.id- const matches = await queries.communityChannel.resolveChannelByNameForMember(db, serverId, userId, parsed.channel)+ const matches = await withD1Retry(+ () => queries.communityChannel.resolveChannelByNameForMember(db, serverId, userId, parsed.channel),+ { route: "community/resolve-ref:channel" }+ )if (matches.length === 0) return { error: 404, message: `channel not found: ${parsed.channel}` }const channel = matches[0]!- // Forum-post form (`/server/forum/post`) — the resolved `channel` is the- // parent forum; descend to the `forum_post` child by name. Runs parallel to- // the thread branch below (do NOT fold them: a thread anchors on a root-msg- // seq, a post on its own name). Post names are NOT unique within a forum, so- // >1 match is an ambiguous ref — return 400 + candidates, NEVER silently pick- // one (mirrors the ambiguous-server-name behavior above). A forum post- // inherits its forum's access; `requireChannelMember`/`requireChannelAccess`- // at the call site climb `parentChannelId` to gate on the forum's roster.- if (parsed.childChannelName !== undefined) {- const posts = await queries.communityChannel.getChildChannelByName(db, channel.id, parsed.childChannelName)- if (posts.length === 0) {- return { error: 404, message: `post not found: ${parsed.childChannelName}` }- }- if (posts.length > 1) {- // Ambiguous: >1 post shares this name (only possible for legacy dupes- // predating create-time dedup). The red line is met by refusing — we- // NEVER silently pick one. A name-based hint can't disambiguate here- // (the candidates' name-anchor paths are identical), so we report the- // count instead of fabricating useless identical paths; a one-time- // slug-dedup migration on legacy posts is the clean fix (deferred).- return {- error: 400,- message: `ambiguous post name "${parsed.childChannelName}" in ${parsed.channel} — ${posts.length} posts share this name; rename the duplicates to address them by name`,- }- }- return { kind: "channel", channelId: posts[0]!.id }- }-if (parsed.threadRootSeq === undefined) {return { kind: "channel", channelId: channel.id }}@@ -149,21 +119,23 @@ export async function resolveTargetForMember(return { error: 400, message: "can't start a thread inside a thread or forum post" }}- // Thread form (`/server/channel/#N`) — translate the root seq to the+ // Thread form (`/server#disc/channel/#N`) — translate the root seq to the// parent message's id, then find (or create) the thread's own channel row.- const rootMessage = await queries.communityMessage.getMessageByChannelAndSeq(- db,- { channelId: channel.id },- parsed.threadRootSeq+ const rootMessage = await withD1Retry(+ () => queries.communityMessage.getMessageByChannelAndSeq(+ db,+ { channelId: channel.id },+ parsed.threadRootSeq!+ ),+ { route: "community/resolve-ref:root-message" })if (!rootMessage || parsed.threadRootSeq === 0) {return { error: 404, message: `no message with seq #${parsed.threadRootSeq} in this channel` }}- const existingThread = await queries.communityChannel.getThreadChannelByParentMessage(- db,- channel.id,- rootMessage.id+ const existingThread = await withD1Retry(+ () => queries.communityChannel.getThreadChannelByParentMessage(db, channel.id, rootMessage.id),+ { route: "community/resolve-ref:thread" })if (existingThread) return { kind: "channel", channelId: existingThread.id }@@ -174,13 +146,11 @@ export async function resolveTargetForMember(// Thread create via the shared trait-keyed collision policy (B4): thread's// creation trait is get-or-create — a concurrent create that loses the race on// the parent_message_id anchor (unique index, migration 0052) re-selects the- // winner rather than making a second thread. This is the SAME dispatch- // forum_post (pure-create) and top-level channels (reject-on-collision) use;- // only these callbacks (the thread channel-shape + its anchor refetch) are- // thread-specific. Anchor-collision (parent_message_id) and name-collision are- // both "a structure anchor was taken → fetch the winner" — one get-or-create- // value covers both; DM's identity-collision is a different key space and is- // NOT wired here.+ // winner rather than making a second thread. Top-level channels+ // (reject-on-collision) use the same dispatch with a different collision+ // contract; only these callbacks (the thread channel-shape + its anchor+ // refetch) are thread-specific. DM's identity-collision is a different key+ // space and is NOT wired here.const threadResult = await createWithCollisionPolicy(channelCreation("thread"), {attempt: () => queries.communityChannel.createThreadChannel(db, channel.id, rootMessage.id, userId),refetchWinner: () => queries.communityChannel.getThreadChannelByParentMessage(db, channel.id, rootMessage.id),diff --git a/src/web/src/lib/community/slug-preview.ts b/src/web/src/lib/community/slug-preview.tsindex cd4df4dc3..444aa4c7e 100644--- a/src/web/src/lib/community/slug-preview.ts+++ b/src/web/src/lib/community/slug-preview.ts@@ -9,7 +9,7 @@ export type SlugPreview = {}/**- * Client-side mirror of what every server/channel/forum-post name route+ * Client-side mirror of what every server/channel name route* does server-side (`trim()` then `slugify()`), so the preview shown here* is byte-identical to what actually gets stored.*/diff --git a/src/web/src/lib/community/storage.test.ts b/src/web/src/lib/community/storage.test.tsindex a295cf254..a179694ab 100644--- a/src/web/src/lib/community/storage.test.ts+++ b/src/web/src/lib/community/storage.test.ts@@ -3,7 +3,7 @@ import {buildMediaKey,buildUserAvatarKey,buildBotAvatarKey,- mediaUrlFromKey,+ attachmentUrl,sanitizeAttachmentFilename,userAvatarUrl,botAvatarUrl,@@ -83,8 +83,8 @@ describe("buildMediaKey", () => {})})-describe("mediaUrlFromKey", () => {- it("prepends the media route prefix without adding a slash", () => {- expect(mediaUrlFromKey("channel/c1/uuid/a.png")).toBe("/api/community/media/channel/c1/uuid/a.png")+describe("attachmentUrl", () => {+ it("builds the id-addressed canonical attachments-door URL from targetId + attachmentId", () => {+ expect(attachmentUrl("c1", "att_1")).toBe("/api/community/channels/c1/attachments/att_1")})})diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.tsindex 8403f2ade..12b0b3ffd 100644--- a/src/web/src/lib/community/storage.ts+++ b/src/web/src/lib/community/storage.ts@@ -9,20 +9,24 @@export function sanitizeAttachmentFilename(input: string): string {const cleaned = input.replace(/\.\./g, "_")- // eslint-disable-next-line no-control-regex.replace(/[\/\x00-\x1f\x7f]/g, "_")if (cleaned.length === 0) return "_"return cleaned.length > 255 ? cleaned.slice(0, 255) : cleaned}/**- * Derive the routable media URL from a stored R2 key. Every read-side call- * site (`groupAttachments`, `mapMessageForApi`, `mapMessageForWs`) goes- * through this helper so the `/api/community/media/` prefix lives in one- * place.+ * Read/render URL for a persisted attachment, served by the canonical+ * `GET /api/community/channels/{targetId}/attachments/{attachmentId}` door.+ * Every read-side call site (`groupAttachments`, the reserve/incoming arms of+ * the message-create handler) builds display URLs through this helper so the+ * id-addressed attachment scheme lives in one place.+ *+ * The `{targetId}` path segment is a routing anchor only — the download door+ * authorizes from the attachment ROW's own channel, never from the path — so a+ * stale/forged targetId can't reach another row's bytes.*/-export function mediaUrlFromKey(r2Key: string): string {- return `/api/community/media/${r2Key}`+export function attachmentUrl(targetId: string, attachmentId: string): string {+ return `/api/community/channels/${targetId}/attachments/${attachmentId}`}// R2 storage key buildersdiff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 1f9041406..76fea1912 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -30,13 +30,13 @@ export const tid = {messageShareCopy: `community-message-share-copy`,threadIndicator: (msgId: string) => `community-thread-indicator-${msgId}`,railUnreadBadge: (serverId: string) => `community-rail-unread-badge-${serverId}`,- // Forum post feed (ForumView). `forumPostCard` is the whole clickable card;- // `forumPostTagBtn` is the hover-revealed tag-edit icon; `forumPostDeleteBtn`- // is the hover-revealed delete icon; `forumPostAvatars` wraps the participant+ // Forum post feed (ForumView). `forumThreadCard` is the whole clickable card;+ // `forumThreadTagBtn` is the hover-revealed tag-edit icon; `forumThreadDeleteBtn`+ // is the hover-revealed delete icon; `forumThreadAvatars` wraps the participant// AvatarGroup; `forumTagChip` is a filter-bar tag chip.- forumPostCard: (id: string) => `community-forum-post-${id}`,- forumPostTagBtn: (id: string) => `community-forum-post-tag-btn-${id}`,- forumPostDeleteBtn: (id: string) => `community-forum-post-delete-btn-${id}`,- forumPostAvatars: (id: string) => `community-forum-post-avatars-${id}`,+ forumThreadCard: (id: string) => `community-forum-post-${id}`,+ forumThreadTagBtn: (id: string) => `community-forum-post-tag-btn-${id}`,+ forumThreadDeleteBtn: (id: string) => `community-forum-post-delete-btn-${id}`,+ forumThreadAvatars: (id: string) => `community-forum-post-avatars-${id}`,forumTagChip: (tag: string) => `community-forum-tag-chip-${tag}`,} as constdiff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.tsindex 212d71596..66d6f6bb3 100644--- a/src/web/src/lib/community/upload.test.ts+++ b/src/web/src/lib/community/upload.test.ts@@ -15,6 +15,7 @@ const mockGetDb = vi.fn(() => ({ __db: true }))vi.mock("@/lib/db", () => ({ getDb: (...a: unknown[]) => mockGetDb(...a) }))const mockGetChannelType = vi.fn()+const mockCreatePendingAttachment = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {@@ -25,10 +26,22 @@ vi.mock("@alook/shared", async () => {...actual.queries.communityChannel,getChannelType: (...a: unknown[]) => mockGetChannelType(...a),},+ communityAttachment: {+ ...actual.queries.communityAttachment,+ createPendingAttachment: (...a: unknown[]) => mockCreatePendingAttachment(...a),+ },},}})+// runAttachmentUpload now owns access + surface dispatch via+// requireMessageSurfaceAccess (kind is DERIVED from its returned surface ++// channel.type, no separate getChannelType re-query). Mock it to drive each arm.+const mockRequireMessageSurfaceAccess = vi.fn()+vi.mock("./permissions", () => ({+ requireMessageSurfaceAccess: (...a: unknown[]) => mockRequireMessageSurfaceAccess(...a),+}))+import {handleAttachmentUpload,handleServerIconUpload,@@ -360,7 +373,9 @@ describe("handleBotAvatarUpload", () => {describe("runAttachmentUpload", () => {beforeEach(() => {vi.clearAllMocks()- mockGetChannelType.mockResolvedValue("text")+ // Reserve-by-id: the human arm now creates a pending row at upload and+ // returns its id. Default the query to echo a stable id.+ mockCreatePendingAttachment.mockResolvedValue({ id: "att_1", filename: "hi.png" })})function ctxWith(env: Env, params: Record<string, string> | undefined) {@@ -372,32 +387,38 @@ describe("runAttachmentUpload", () => {}}+ // Drive the surface dispatch: `surface="dm"` or `surface="channel"` with a+ // channel row carrying `.type`. kind is DERIVED from these (no getChannelType).+ function surfaceChannel(type: string) {+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "channel", channel: { id: "c1", type } },+ })+ }+ function surfaceDm() {+ mockRequireMessageSurfaceAccess.mockResolvedValue({+ ok: true,+ value: { surface: "dm", dm: { id: "d1" } },+ })+ }+it("returns 400 when the route id param is missing", async () => {const put = vi.fn()- const perm = vi.fn()const res = await runAttachmentUpload(reqWithFile(fakeFile("hi.png", "image/png", 10)),ctxWith(envWithR2(put), undefined),- "channel",- perm as never,)expect(res.status).toBe(400)- expect(perm).not.toHaveBeenCalled()+ expect(mockRequireMessageSurfaceAccess).not.toHaveBeenCalled()expect(put).not.toHaveBeenCalled()})- it("forwards permission-check failures with the reported status + error", async () => {+ it("forwards surface-access failures with the reported status + error", async () => {const put = vi.fn()- const perm = vi.fn().mockResolvedValue({- ok: false,- status: 403,- error: "forbidden",- })+ mockRequireMessageSurfaceAccess.mockResolvedValue({ ok: false, status: 403, error: "forbidden" })const res = await runAttachmentUpload(reqWithFile(fakeFile("hi.png", "image/png", 10)),ctxWith(envWithR2(put), { id: "c1" }),- "channel",- perm as never,)expect(res.status).toBe(403)const body = (await res.json()) as { error: string }@@ -405,28 +426,37 @@ describe("runAttachmentUpload", () => {expect(put).not.toHaveBeenCalled()})- it("hands off to handleAttachmentUpload with the resolved kind + id, returns the URL", async () => {- // Happy path — permission passes, streaming upload succeeds, response- // shape mirrors what the three route files used to build inline.+ it("channel (text) surface → kind 'channel', channel/ R2 prefix, creates a pending row + returns its id (reserve-by-id)", async () => {+ // Happy path — access passes, streaming upload succeeds, a PENDING row is+ // created and its id returned (reserve-by-id, route/disc step 2b). A text+ // channel derives kind="channel" (== what the old channels/[id]/upload+ // passed). NO `url` in the response anymore — the display url is id-addressed+ // and derived client-side.+ surfaceChannel("text")const put = vi.fn().mockResolvedValue(undefined)- const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "c1" } })const res = await runAttachmentUpload(reqWithFile(fakeFile("hi.png", "image/png", 10)),ctxWith(envWithR2(put), { id: "c1" }),- "channel",- perm as never,)expect(res.status).toBe(200)const body = (await res.json()) as {- url: string+ id: string+ url?: stringfilename: stringcontentType: stringsize: number}+ expect(body.id).toBe("att_1")expect(body.filename).toBe("hi.png")expect(body.contentType).toBe("image/png")expect(body.size).toBe(10)- expect(body.url).toMatch(/^\/api\/community\/media\/channel\/c1\/[0-9a-f-]+\/hi\.png$/)+ // Single-source: the upload response carries NO url (client derives it).+ expect(body.url).toBeUndefined()+ // Pending row created with the credential uploaderId + resolved target.+ expect(mockCreatePendingAttachment).toHaveBeenCalledWith(+ { __db: true },+ expect.objectContaining({ uploaderId: "u1", targetId: "c1" }),+ )expect(put).toHaveBeenCalledOnce()// Known-length R2 body rule applies here too — the shared helper must not// hand R2 an unknown-length ReadableStream or buffer into ArrayBuffer.@@ -437,71 +467,79 @@ describe("runAttachmentUpload", () => {expect(streamed).not.toBeInstanceOf(ArrayBuffer)})- it("routes 'dm' kind through the dm/ R2 prefix", async () => {+ it("threads client-supplied image dimensions onto the pending row (single source = upload)", async () => {+ surfaceChannel("text")const put = vi.fn().mockResolvedValue(undefined)- const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "d1" } })- const res = await runAttachmentUpload(- reqWithFile(fakeFile("hi.png", "image/png", 10)),- ctxWith(envWithR2(put), { id: "d1" }),- "dm",- perm as never,- )+ // reqWithFile only stubs `get('file')`; extend it to also return w/h so the+ // form-dimension parse in readFile sees them.+ const req = reqWithFile(fakeFile("hi.png", "image/png", 10))+ req.formData = (async () => {+ const real = new FormData()+ Object.defineProperty(real, "get", {+ value: (key: string) =>+ key === "file"+ ? fakeFile("hi.png", "image/png", 10)+ : key === "width"+ ? "1920"+ : key === "height"+ ? "1080"+ : null,+ })+ return real+ }) as typeof req.formData+ const res = await runAttachmentUpload(req, ctxWith(envWithR2(put), { id: "c1" }))expect(res.status).toBe(200)- const [key] = put.mock.calls[0]- expect(key).toMatch(/^dm\/d1\//)+ const body = (await res.json()) as { width?: number; height?: number }+ expect(body.width).toBe(1920)+ expect(body.height).toBe(1080)+ expect(mockCreatePendingAttachment).toHaveBeenCalledWith(+ { __db: true },+ expect.objectContaining({ width: 1920, height: 1080 }),+ )})- it("routes 'thread' kind through the thread/ R2 prefix", async () => {- mockGetChannelType.mockResolvedValue("thread")+ it("dm surface → kind 'dm', dm/ R2 prefix (== old dm/[id]/upload's kind, buildMediaKey parity)", async () => {+ surfaceDm()const put = vi.fn().mockResolvedValue(undefined)- const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "t1" } })const res = await runAttachmentUpload(reqWithFile(fakeFile("hi.png", "image/png", 10)),- ctxWith(envWithR2(put), { id: "t1" }),- "thread",- perm as never,+ ctxWith(envWithR2(put), { id: "d1" }),)expect(res.status).toBe(200)const [key] = put.mock.calls[0]- expect(key).toMatch(/^thread\/t1\//)+ expect(key).toMatch(/^dm\/d1\//)})- it("rejects a 'channel' upload targeted at a forum top-level with 400", async () => {- mockGetChannelType.mockResolvedValue("forum")- const put = vi.fn()- const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "c1" } })+ it("channel surface + type 'thread' → kind 'thread', thread/ R2 prefix (== old threads/[id]/upload's kind)", async () => {+ surfaceChannel("thread")+ const put = vi.fn().mockResolvedValue(undefined)const res = await runAttachmentUpload(reqWithFile(fakeFile("hi.png", "image/png", 10)),ctxWith(envWithR2(put), { id: "c1" }),- "channel",- perm as never,)- expect(res.status).toBe(400)- expect(put).not.toHaveBeenCalled()+ expect(res.status).toBe(200)+ const [key] = put.mock.calls[0]+ expect(key).toMatch(/^thread\/c1\//)})- it("rejects a 'channel' upload targeted at a DM channel id with 400 (block-bypass guard)", async () => {- mockGetChannelType.mockResolvedValue("dm")- const put = vi.fn()- const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "c1" } })+ it("channel surface + forum top-level → kind 'channel' (phase2 forum≡thread write-guard reversal — forum is now a message-bearing surface)", async () => {+ surfaceChannel("forum")+ const put = vi.fn().mockResolvedValue(undefined)const res = await runAttachmentUpload(reqWithFile(fakeFile("hi.png", "image/png", 10)),ctxWith(envWithR2(put), { id: "c1" }),- "channel",- perm as never,)- expect(res.status).toBe(400)- expect(put).not.toHaveBeenCalled()+ expect(res.status).toBe(200)+ const [key] = put.mock.calls[0]+ expect(key).toMatch(/^channel\/c1\//)})it("forwards handleAttachmentUpload errors (e.g. oversize) unchanged", async () => {+ surfaceChannel("text")const put = vi.fn()- const perm = vi.fn().mockResolvedValue({ ok: true, value: { id: "c1" } })const res = await runAttachmentUpload(reqWithFile(fakeFile("big.png", "image/png", MAX_ATTACHMENT_SIZE_BYTES + 1)),ctxWith(envWithR2(put), { id: "c1" }),- "channel",- perm as never,)expect(res.status).toBe(413)expect(put).not.toHaveBeenCalled()diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.tsindex 6bb1e93ed..31655f35b 100644--- a/src/web/src/lib/community/upload.ts+++ b/src/web/src/lib/community/upload.ts@@ -4,23 +4,25 @@ import {MAX_SERVER_ICON_SIZE_BYTES,ALLOWED_ICON_MIME_TYPES,queries,+ createLogger,} from "@alook/shared"import { requireMessageBearingSurface, requireChildSurface } from "./channel-write-guard"-import type { Database } from "@alook/shared"+import { isThread } from "@alook/shared"+import { requireMessageSurfaceAccess } from "./permissions"import { writeError, writeJSON } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import type { AuthContext } from "@/lib/middleware/auth"-import type { Result } from "./permissions"import {buildMediaKey,buildServerIconKey,buildUserAvatarKey,buildBotAvatarKey,- mediaUrlFromKey,+ serverIconUrl,userAvatarUrl,botAvatarUrl,} from "./storage"-import { isChannelTarget, isDmTarget } from "./message-handler"++const log = createLogger({ service: "community-attachment-upload" })type UploadOk = {ok: true@@ -47,6 +49,11 @@ type AttachmentUploadOk = {filename: stringcontentType: stringsize: number+ // Client-computed image dimensions carried on the upload body (thumbnail at+ // file-pick). undefined for non-images and bot uploads. Written onto the+ // pending row at upload — the single source of an attachment's dimensions.+ width?: number+ height?: number}export type AttachmentUploadResult = AttachmentUploadOk | UploadErr@@ -69,7 +76,24 @@ function mimeAllowed(contentType: string, allowed: readonly string[]): boolean {)}-async function readFile(req: NextRequest): Promise<File | UploadErr> {+/**+ * Parsed upload form: the `file` plus optional client-computed image+ * dimensions. `width`/`height` are computed browser-side (thumbnail) at+ * file-pick time and ride the SAME multipart body as the file — a `FormData`+ * body can only be read once, so they're extracted here alongside the file.+ * Absent/non-numeric → undefined (a bot upload never sends them; a non-image+ * has none). This is the SINGLE source of an attachment's dimensions: they are+ * written onto the pending row at upload time and never re-supplied on send.+ */+type ParsedUpload = { file: File; width?: number; height?: number }++function parseDimension(raw: FormDataEntryValue | null): number | undefined {+ if (typeof raw !== "string") return undefined+ const n = Number(raw)+ return Number.isInteger(n) && n >= 0 ? n : undefined+}++async function readFile(req: NextRequest): Promise<ParsedUpload | UploadErr> {let formData: FormDatatry {formData = await req.formData()@@ -78,15 +102,21 @@ async function readFile(req: NextRequest): Promise<File | UploadErr> {}const file = formData.get("file") as File | nullif (!file) return { ok: false, response: writeError("no file provided", 400) }- return file+ return {+ file,+ width: parseDimension(formData.get("width")),+ height: parseDimension(formData.get("height")),+ }}/*** Validate + upload an attachment for a channel / DM / thread.*- * Enforces `MAX_ATTACHMENT_SIZE_BYTES`.- * Returns the R2 key + a `/api/community/media/<key>` URL that the auth-gated- * media route can serve.+ * Enforces `MAX_ATTACHMENT_SIZE_BYTES` and `ALLOWED_ATTACHMENT_MIME_PREFIXES`.+ * Returns the stored R2 key + parsed metadata (filename, content-type, size,+ * and any client-supplied image dimensions). The caller persists a pending+ * attachment row keyed by that r2Key; reads then serve it through the canonical+ * `channels/{id}/attachments/{attachmentId}` door (there is no `/media/` route).** R2 requires stream bodies to have a known length. Passing the `File` itself* preserves that length for the Workers runtime while avoiding an explicit@@ -100,9 +130,9 @@ export async function handleAttachmentUpload(targetId: string,uploaderTag: UploaderTag,): Promise<AttachmentUploadResult> {- const fileOrErr = await readFile(req)- if ("ok" in fileOrErr && fileOrErr.ok === false) return fileOrErr- const file = fileOrErr as File+ const parsed = await readFile(req)+ if ("ok" in parsed && parsed.ok === false) return parsed+ const { file, width, height } = parsed as ParsedUploadif (file.size > MAX_ATTACHMENT_SIZE_BYTES) {return {@@ -132,6 +162,8 @@ export async function handleAttachmentUpload(filename: file.name,contentType,size: file.size,+ width,+ height,}}@@ -144,9 +176,9 @@ export async function handleServerIconUpload(env: Env,serverId: string,): Promise<UploadResult> {- const fileOrErr = await readFile(req)- if ("ok" in fileOrErr && fileOrErr.ok === false) return fileOrErr- const file = fileOrErr as File+ const parsed = await readFile(req)+ if ("ok" in parsed && parsed.ok === false) return parsed+ const { file } = parsed as ParsedUploadif (file.size > MAX_SERVER_ICON_SIZE_BYTES) {return {@@ -172,7 +204,12 @@ export async function handleServerIconUpload(ok: true,id: fileId,key,- url: `/api/community/media/${key}`,+ // Canonical icon serve route (the media/[...key] catch-all is deleted in the+ // route/disc media-delete step). The icon POST route reads `.key` and builds+ // its own `serverIconUrl` for the response, so this `url` isn't consumed+ // today — but keep it pointed at the real route so no future caller picks up+ // a dead `/media/` path.+ url: serverIconUrl({ id: serverId, icon: key }) ?? "",filename: file.name,contentType: file.type,size: file.size,@@ -193,9 +230,9 @@ async function handleAvatarUpload(key: string,url: string,): Promise<UploadResult> {- const fileOrErr = await readFile(req)- if ("ok" in fileOrErr && fileOrErr.ok === false) return fileOrErr- const file = fileOrErr as File+ const parsed = await readFile(req)+ if ("ok" in parsed && parsed.ok === false) return parsed+ const { file } = parsed as ParsedUploadif (file.size > MAX_SERVER_ICON_SIZE_BYTES) {return {@@ -218,9 +255,7 @@ async function handleAvatarUpload(ok: true,id: ownerId,key,- // Not `/api/community/media/${key}` — that catch-all route only recognizes- // channel/thread/dm/server-icon kinds and would 404. `url` is the real- // routable dedicated avatar route (`userAvatarUrl`/`botAvatarUrl`).+ // Avatar uploads return their dedicated routable URL.url,filename: file.name,contentType: file.type,@@ -245,52 +280,116 @@ export function handleBotAvatarUpload(}/**- * Route body shared by the three attachment-upload endpoints- * (`channels/[id]/upload`, `dm/[id]/upload`, `threads/[id]/upload`). Parses- * the `id` param, runs the caller-supplied permission check, then hands off- * to `handleAttachmentUpload`. Keeping the three route files thin also keeps- * their URLs distinct — we deliberately did not collapse to a single route.+ * Shared body for the unified attachment-upload trunk. One `id`, dispatched by+ * the channel's surface — the three old per-type routes+ * (`channels/[id]/upload`, `dm/[id]/upload`, `threads/[id]/upload`) have+ * collapsed onto this one; the DM/thread routes are now deleted and the web+ * client uploads through `channels/[id]/upload` for every surface.+ *+ * Access + surface come from `requireMessageSurfaceAccess` (the same dispatch+ * the read/read-state routes use), so a DM id runs `requireDMAccess` (block+ * gate) — closing the incidental P0 the trunk covers.+ *+ * `kind` (which feeds `buildMediaKey` → the R2 key path, so its VALUE is+ * load-bearing, not just its guard) is DERIVED from `(surface, channel.type)`+ * consumed from the dispatch's return — NOT re-queried via a second+ * `getChannelType` (that would be a mini re-derive + extra hop; the dispatch+ * already fetched the row). `surface` alone is lossy (thread and text both+ * present as `surface="channel"`), so the channel arm splits on `channel.type`:+ * - dm → kind "dm" (a DM is a legitimate+ * attachment target — no bearing guard)+ * - channel + thread → kind "thread" (requireChildSurface)+ * - channel + text/forum(-top) → kind "channel" (requireMessageBearingSurface)+ * These map byte-for-byte to what the three routes passed before, so new+ * uploads land under the same R2 key prefix (existing attachments read from the+ * stored `r2_key` column and are unaffected — the derivation is write-only).*/export async function runAttachmentUpload(req: NextRequest,ctx: AuthContext & { params?: Record<string, string> },- kind: AttachmentKind,- permissionCheck: (db: Database, id: string, userId: string) => Promise<Result<unknown>>,): Promise<NextResponse> {const id = ctx.params?.id- if (!id) {- const label =- isChannelTarget(kind) ? "channel id" : isDmTarget(kind) ? "dm id" : "id"- return writeError(`missing ${label}`, 400)- }+ if (!id) return writeError("missing channel id", 400)const db = getDb(ctx.env.DB)- const auth = await permissionCheck(db, id, ctx.userId)+ const auth = await requireMessageSurfaceAccess(db, id, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- if (kind === "channel") {- const channelType = await queries.communityChannel.getChannelType(db, id)- const surface = requireMessageBearingSurface(channelType)- if (!surface.ok) return writeError(surface.error, surface.status)- } else if (kind === "thread") {- const channelType = await queries.communityChannel.getChannelType(db, id)- const child = requireChildSurface(channelType)- if (!child.ok) return writeError(child.error, child.status)+ // Derive kind + apply the per-surface guard from the dispatch's return — no+ // re-query. The DM arm needs no surface guard (a DM is a valid target).+ let kind: AttachmentKind+ if (auth.value.surface === "dm") {+ kind = "dm"+ } else {+ const channelType = auth.value.channel.type+ if (isThread(channelType)) {+ const child = requireChildSurface(channelType)+ if (!child.ok) return writeError(child.error, child.status)+ kind = "thread"+ } else {+ const surface = requireMessageBearingSurface(channelType)+ if (!surface.ok) return writeError(surface.error, surface.status)+ kind = "channel"+ }}- const result = await handleAttachmentUpload(req, ctx.env, kind, id, {- uploader: "user",- uploaderUserId: ctx.userId,- })- if (!result.ok) return result.response-- // Human web client tracks attachments in-memory until send, so no id is- // returned here — parity with the pre-refactor shape. `url` is derived- // from the stored key via the shared helper.- return writeJSON({- url: mediaUrlFromKey(result.r2Key),- filename: result.filename,- contentType: result.contentType,- size: result.size,- })+ // Track any R2 blob written before the D1 insert throws so the catch can+ // best-effort delete it (mirrors the bot upload route's orphan-cleanup).+ let r2KeyToCleanUp: string | null = null+ try {+ const result = await handleAttachmentUpload(req, ctx.env, kind, id, {+ uploader: "user",+ uploaderUserId: ctx.userId,+ })+ if (!result.ok) return result.response+ r2KeyToCleanUp = result.r2Key++ // Reserve-by-id (route/disc step 2b): the human composer now mirrors the+ // bot flow — the upload creates a PENDING row (messageId = NULL) and returns+ // its stable id. The composer holds the id in-memory and passes it to `send`,+ // where `reserveAttachmentsForMessage` links it. `uploaderId` is the+ // credential user (self-scope, never from the body); `send` re-verifies the+ // id against (uploader, target) before reserving, so a stolen id can't be+ // attached to another user's message. Image dimensions are written HERE (the+ // single source — they never ride the send body) so the pending row is a+ // self-contained, complete entity at upload time; `reserve` only links it.+ const row = await queries.communityAttachment.createPendingAttachment(db, {+ uploaderId: ctx.userId,+ targetId: id,+ r2Key: result.r2Key,+ filename: result.filename,+ contentType: result.contentType,+ size: result.size,+ width: result.width,+ height: result.height,+ })++ return writeJSON({+ id: row.id,+ filename: row.filename,+ contentType: result.contentType,+ size: result.size,+ ...(result.width !== undefined ? { width: result.width } : {}),+ ...(result.height !== undefined ? { height: result.height } : {}),+ })+ } catch (err) {+ if (r2KeyToCleanUp !== null) {+ try {+ await ctx.env.COMMUNITY_MEDIA.delete(r2KeyToCleanUp)+ } catch (cleanupErr) {+ log.error("attachment_upload_r2_cleanup_failed", {+ route: "channels/[id]/attachments",+ userId: ctx.userId,+ r2Key: r2KeyToCleanUp,+ cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),+ })+ }+ }+ log.error("attachment_upload_failure", {+ route: "channels/[id]/attachments",+ userId: ctx.userId,+ cause: err instanceof Error ? err.stack ?? err.message : String(err),+ })+ return writeError("internal error", 500)+ }}diff --git a/src/web/src/lib/middleware/community-actor.test.ts b/src/web/src/lib/middleware/community-actor.test.tsindex 02b124c13..5a2f5231e 100644--- a/src/web/src/lib/middleware/community-actor.test.ts+++ b/src/web/src/lib/middleware/community-actor.test.ts@@ -79,7 +79,7 @@ describe("withCommunityActor", () => {const res = await wrapped(new NextRequest("http://localhost/x"))expect(res.status).toBe(200)const body = (await res.json()) as { actor: CommunityActor }- expect(body.actor).toEqual({ kind: "human", userId: "human_1", email: "[email protected]", workspaceId: "ws_1" })+ expect(body.actor).toEqual({ kind: "human", userId: "human_1", email: "[email protected]", workspaceId: "ws_1", isBot: false })// Bot resolution must not have been attempted for a non-crk_ request.expect(mockResolveBotActor).not.toHaveBeenCalled()})diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.tsindex 167a984a0..eb09ce45d 100644--- a/src/web/src/lib/middleware/community-actor.ts+++ b/src/web/src/lib/middleware/community-actor.ts@@ -27,6 +27,15 @@ export type CommunityActor =email: string/** Present on the `al_`/session human path; absent for a bot. */workspaceId?: string+ /**+ * The session user's `isBot` flag, carried through from withAuth's+ * AuthContext. Always false in production (a bot session is rejected at+ * 401 before the handler runs) — this is the belt-and-suspenders signal+ * friend-graph write routes assert as a last-line backstop against a+ * future auth regression (see friends/request). Preserved here so the+ * dual-actor fold doesn't drop the guard withAuth's context exposed.+ */+ isBot?: boolean}| {kind: "bot"@@ -118,6 +127,7 @@ export function withCommunityActor(handler: CommunityActorHandler) {userId: humanCtx.userId,email: humanCtx.email,workspaceId: humanCtx.workspaceId,+ isBot: humanCtx.user?.isBot,},params: humanCtx.params,})diff --git a/src/web/src/lib/middleware/community-daemon-auth.test.ts b/src/web/src/lib/middleware/community-daemon-auth.test.tsindex 05daa65df..75fb3882e 100644--- a/src/web/src/lib/middleware/community-daemon-auth.test.ts+++ b/src/web/src/lib/middleware/community-daemon-auth.test.ts@@ -9,6 +9,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))const mockFindActiveCredential = vi.fn()vi.mock("@alook/shared", () => ({+ withD1Retry: (fn: () => Promise<unknown>) => fn(),queries: {communityMachine: {findActiveCredentialByBearer: (...a: unknown[]) => mockFindActiveCredential(...a),diff --git a/src/web/src/lib/middleware/community-daemon-auth.ts b/src/web/src/lib/middleware/community-daemon-auth.tsindex f752542ce..76df45f6e 100644--- a/src/web/src/lib/middleware/community-daemon-auth.ts+++ b/src/web/src/lib/middleware/community-daemon-auth.ts@@ -1,6 +1,6 @@import { NextRequest, NextResponse } from "next/server"import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries } from "@alook/shared"+import { queries, withD1Retry } from "@alook/shared"import { getDb } from "@/lib/db"interface CommunityDaemonAuthContext {@@ -48,7 +48,10 @@ export function withCommunityDaemonAuth(handler: CommunityDaemonAuthenticatedHanconst cloudflareEnv = env as Envconst db = getDb(cloudflareEnv.DB)- const active = await queries.communityMachine.findActiveCredentialByBearer(db, raw)+ const active = await withD1Retry(+ () => queries.communityMachine.findActiveCredentialByBearer(db, raw),+ { route: "community/daemon-auth:credential" }+ )if (!active) {return NextResponse.json({ error: "credential revoked or unknown" }, { status: 401 })}diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.tsindex 9bb845500..37ca6fe71 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -60,11 +60,11 @@ describe("communityKeys", () => {"c1","threads",])- expect(communityKeys.forumPosts("c1")).toEqual([+ expect(communityKeys.forumTags("c1")).toEqual(["community","channel","c1",- "posts",+ "forum-tags",])})diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex 1b47a8cac..569aad178 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -67,19 +67,13 @@ export const communityKeys = {[...communityKeys.all, "channel", channelId, "pins"] as const,threads: (channelId: string) =>[...communityKeys.all, "channel", channelId, "threads"] as const,- forumPosts: (channelId: string) =>- [...communityKeys.all, "channel", channelId, "posts"] as const,+ forumTags: (channelId: string) =>+ [...communityKeys.all, "channel", channelId, "forum-tags"] as const,// #3: the viewer's `communityReadState` row for a single channel, fetched// once per channel mount and frozen thereafter so the "New" divider stays// anchored while the watermark advances.channelReadStateSnapshot: (channelId: string) =>[...communityKeys.all, "channel", channelId, "read-state-snapshot"] as const,- // Channel-open bootstrap (read pointer + initial message window in one- // request). Frozen per mount like the snapshot; gcTime:0 so a fresh mount- // re-fetches. Distinct key so it doesn't collide with the seeded- // channelMessages / read-state-snapshot caches it writes.- channelBootstrap: (channelId: string) =>- [...communityKeys.all, "channel", channelId, "bootstrap"] as const,// DM sibling of `channelReadStateSnapshot`. Same freeze semantics — the// hook latches the first non-null response so the "New" divider anchor// stays put while the progressive watermark advances.@@ -126,4 +120,3 @@ export const communityKeys = {profile: (userId: string) =>[...communityKeys.all, "profile", userId] as const,} as const-diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.tsindex 09cf920a7..00b5e529d 100644--- a/src/web/src/lib/query-persister.test.ts+++ b/src/web/src/lib/query-persister.test.ts@@ -46,10 +46,10 @@ describe("shouldPersistQueryKey", () => {expect(shouldPersistQueryKey(communityKeys.inbox())).toBe(false)})- it("does NOT persist pins/threads/forum posts (message-related but ephemeral)", () => {+ it("does NOT persist pins/threads/forum tags (message-related but ephemeral)", () => {expect(shouldPersistQueryKey(communityKeys.pins("ch_1"))).toBe(false)expect(shouldPersistQueryKey(communityKeys.threads("ch_1"))).toBe(false)- expect(shouldPersistQueryKey(communityKeys.forumPosts("ch_1"))).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.forumTags("ch_1"))).toBe(false)})it("returns false for keys outside the community namespace", () => {diff --git a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts b/src/web/src/test/e2e-ui/02-server-channel-message.spec.tsindex dc0ceff83..3355def44 100644--- a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts+++ b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts@@ -78,7 +78,7 @@ test("server → channel → message", async ({ asUser }) => {let releaseMessages!: () => voidconst messagesGate = new Promise<void>((resolve) => { releaseMessages = resolve })let intercepted = false- await page.route("**/api/community/channels/*/bootstrap*", async (route) => {+ await page.route("**/api/community/channels/*/messages*", async (route) => {if (route.request().method() !== "GET") {await route.continue()return@@ -93,7 +93,7 @@ test("server → channel → message", async ({ asUser }) => {await expect(composerEditable(page)).toContainText(draft)await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(1)await expect(page.getByTestId(tid.message(imePayload.message.id))).toHaveCount(1)- await page.unroute("**/api/community/channels/*/bootstrap*")+ await page.unroute("**/api/community/channels/*/messages*")const restored = composerEditable(page)await restored.click()diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex 7612fd90f..04fb9836e 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -20,7 +20,7 @@ test.describe.serial("direct messages", () => {const responsePromise = alice.page.waitForResponse((response) => {const pathname = new URL(response.url()).pathnamereturn response.request().method() === "POST"- && pathname === `/api/community/dm/${dmId}/messages`+ && pathname === `/api/community/channels/${dmId}/messages`})await sendMessage(alice.page, body)const response = await responsePromisediff --git a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.tsindex 1e450cc97..96969c7b1 100644--- a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts+++ b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts@@ -4,7 +4,7 @@ import {seedServer,seedChannel,seedJoinServer,- seedForumPost,+ seedForumThread,seedMessage,seedDm,seedDmMessage,@@ -19,14 +19,14 @@ import {test.describe.serial("forum post tags + participant avatars", () => {let serverId: stringlet forumId: string- let postId: string+ let threadId: stringtest.beforeAll(async () => {serverId = await seedServer("alice", `Forum ${Date.now()}`)forumId = await seedChannel("alice", serverId, "ideas", "forum")// Bob joins the server so he's a candidate participant / viewer.await seedJoinServer("alice", "bob", serverId)- postId = await seedForumPost("alice", forumId, `Bug ${Date.now()}`, "first post body")+ threadId = await seedForumThread("alice", forumId, `Bug ${Date.now()}`, "first post body")})test("creator edits a post's tags from the card; the filter bar derives the union", async ({ asUser }) => {@@ -34,7 +34,7 @@ test.describe.serial("forum post tags + participant avatars", () => {await page.goto(`/c/channels/${serverId}/${forumId}`)await page.waitForURL(new RegExp(forumId), { timeout: 20_000, waitUntil: "commit" })- const card = page.getByTestId(tid.forumPostCard(postId))+ const card = page.getByTestId(tid.forumThreadCard(threadId))await expect(card).toBeVisible({ timeout: 20_000 })// No tags yet → no filter-bar chip for the post's future tags.@@ -42,7 +42,7 @@ test.describe.serial("forum post tags + participant avatars", () => {// Hover reveals the tag-edit icon; open the dialog and add two tags.await card.hover()- await page.getByTestId(tid.forumPostTagBtn(postId)).click()+ await page.getByTestId(tid.forumThreadTagBtn(threadId)).click()await expect(page.getByTestId(tid.forumTagDialog)).toBeVisible({ timeout: 10_000 })for (const t of ["alpha", "beta"]) {await page.getByPlaceholder("new-tag").fill(t)@@ -56,7 +56,7 @@ test.describe.serial("forum post tags + participant avatars", () => {// Remove one tag → the filter bar's union drops it.await card.hover()- await page.getByTestId(tid.forumPostTagBtn(postId)).click()+ await page.getByTestId(tid.forumThreadTagBtn(threadId)).click()await expect(page.getByTestId(tid.forumTagDialog)).toBeVisible({ timeout: 10_000 })// The active (selected) chips carry a remove affordance; click #beta to// deselect, then save.@@ -72,11 +72,11 @@ test.describe.serial("forum post tags + participant avatars", () => {await page.goto(`/c/channels/${serverId}/${forumId}`)await page.waitForURL(new RegExp(forumId), { timeout: 20_000, waitUntil: "commit" })- const card = page.getByTestId(tid.forumPostCard(postId))+ const card = page.getByTestId(tid.forumThreadCard(threadId))await expect(card).toBeVisible({ timeout: 20_000 })await card.hover()// Bob is neither the post creator nor a server manager → no tag icon.- await expect(page.getByTestId(tid.forumPostTagBtn(postId))).toHaveCount(0)+ await expect(page.getByTestId(tid.forumThreadTagBtn(threadId))).toHaveCount(0)})test("post card shows a participant AvatarGroup once a second person joins", async ({ asUser }) => {@@ -84,14 +84,14 @@ test.describe.serial("forum post tags + participant avatars", () => {// spoke). Seeded via API (a forum post's own channel accepts messages at// the channel messages route); the enrollment path is the product code// under test, and the card render is what this journey asserts.- await seedMessage("bob", postId, `bob joins ${Date.now()}`)+ await seedMessage("bob", threadId, `bob joins ${Date.now()}`)// Alice opens the forum list: the post now has >1 participant, so the card// renders the participant AvatarGroup (creator + Bob).const alice = await asUser("alice")await alice.page.goto(`/c/channels/${serverId}/${forumId}`)await alice.page.waitForURL(new RegExp(forumId), { timeout: 20_000, waitUntil: "commit" })- await expect(alice.page.getByTestId(tid.forumPostAvatars(postId))).toBeVisible({ timeout: 20_000 })+ await expect(alice.page.getByTestId(tid.forumThreadAvatars(threadId))).toBeVisible({ timeout: 20_000 })})})diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.tsindex 372d8121d..f07488c6d 100644--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts@@ -9,7 +9,7 @@ import {seedJoinServer,seedMessage,seedThread,- seedForumPost,+ seedForumThread,seedDm,memberInfo,} from "./_fixtures/seed"@@ -64,7 +64,7 @@ test.describe.serial("mentions — candidate scope", () => {// to the FORUM, not the post — posts reject access-member adds and derive// their mention pool from the parent forum's audience.await seedChannelMember("alice", privateForumId, userId("bob"))- privatePostId = await seedForumPost("alice", privateForumId, `Post ${Date.now()}`, "post body")+ privatePostId = await seedForumThread("alice", privateForumId, `Post ${Date.now()}`, "post body")// A thread rooted on a message in the private channel — its scope is the// PARENT channel's audience (alice+bob), NOT its own participant set.diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex d7c9379cb..53b9cefc5 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -51,7 +51,7 @@ export async function seedChannel(type?: "text" | "forum",categoryId?: string,): Promise<string> {- const res = await post(owner, `/api/community/servers/${serverId}/channels`, { name, type, categoryId })+ const res = await post(owner, "/api/community/channels", { serverId, name, type, categoryId })const data = (await res.json()) as { channel: { id: string } }return data.channel.id}@@ -102,7 +102,7 @@ export async function seedChannelMember(owner: UserKey, channelId: string, userI}export async function seedDm(from: UserKey, targetUserId: string): Promise<string> {- const res = await post(from, "/api/community/dm", { userId: targetUserId })+ const res = await post(from, "/api/community/channels", { type: "dm", userId: targetUserId })const data = (await res.json()) as { conversation: { id: string } }return data.conversation.id}@@ -110,7 +110,7 @@ export async function seedDm(from: UserKey, targetUserId: string): Promise<strin// Post a DM message via API so the conversation shows in both sidebars with a// preview. Returns the message id.export async function seedDmMessage(author: UserKey, dmId: string, content: string): Promise<string> {- const res = await post(author, `/api/community/dm/${dmId}/messages`, { content })+ const res = await post(author, `/api/community/channels/${dmId}/messages`, { content })const data = (await res.json()) as { message: { id: string } }return data.message.id}@@ -123,7 +123,7 @@ export async function seedBlock(blocker: UserKey, targetUserId: string): Promise// user, from the requester's friends list. Used to recover idempotently when a// re-run (Playwright retry) finds the pair already friends.async function findFriendshipId(requester: UserKey, targetUserId: string): Promise<string | undefined> {- const res = await fetch(`${WEB_URL}/api/community/friends`, {+ const res = await fetch(`${WEB_URL}/api/community/friends/accepted`, {headers: { Cookie: sessionCookie(requester), Origin: WEB_URL },})if (!res.ok) return undefined@@ -168,22 +168,30 @@ export async function seedMessage(author: UserKey, channelId: string, content: s// Create a forum post (a child channel of a `type:"forum"` channel) via API.// Returns the post's own channel id. The creator is enrolled as a participant// server-side. Use when a spec needs an existing post before driving the UI.-export async function seedForumPost(+export async function seedForumThread(author: UserKey,forumChannelId: string,name: string,content: string,): Promise<string> {- const res = await post(author, `/api/community/channels/${forumChannelId}/posts`, { name, content })- const data = (await res.json()) as { post: { id: string } }- return data.post.id+ const nonce = `e2e:${crypto.randomUUID()}`+ const structure = await post(author, `/api/community/channels/${forumChannelId}/messages`, {+ content: name,+ nonce: `${nonce}:opener`,+ })+ const data = (await structure.json()) as { threadId: string }+ await post(author, `/api/community/channels/${data.threadId}/messages`, {+ content,+ nonce: `${nonce}:reply`,+ })+ return data.threadId}// Create a thread rooted on an existing message. Returns the thread's own// child-channel id. A thread has NO roster of its own — its @-mention scope is// the PARENT channel's audience — which is exactly what the scope spec probes.export async function seedThread(author: UserKey, messageId: string, name: string): Promise<string> {- const res = await post(author, `/api/community/messages/${messageId}/threads`, { name })+ const res = await post(author, "/api/community/channels", { type: "thread", messageId, name })const data = (await res.json()) as { id: string }return data.id}diff --git a/src/web/src/test/e2e/community-server-discriminator-unique.test.ts b/src/web/src/test/e2e/community-server-discriminator-unique.test.tsnew file mode 100644index 000000000..4a8f38ff1--- /dev/null+++ b/src/web/src/test/e2e/community-server-discriminator-unique.test.ts@@ -0,0 +1,276 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { sqlRun, sqlQuery } from "@alook/test-utils"+import { computeDiscriminator, createDb, queries } from "@alook/shared"+import { resolveTargetForMember } from "../../lib/community/resolve-ref"++/**+ * Real-DB existence oracle for the community-server discriminator unique index+ * (`idx_community_server_name_discriminator`, migration 0080). Verifies the+ * LOAD-BEARING half of server-handle uniqueness that the allocator unit test+ * can't: that the DB index ACTUALLY throws on a duplicate `(name COLLATE+ * NOCASE, discriminator)` — not that `withUniqueDiscriminator` re-salts GIVEN a+ * throw (that's the mocked user.test.ts half).+ *+ * EXISTENCE-COUNT oracle, not error-absence (Aigneis #18/#61 form): two inserts+ * of the same `name#disc` must leave exactly ONE row (the 2nd is refused), and+ * a bumped disc must leave TWO distinct rows — never a silent double-insert of+ * the same handle. This is the never-drop worst side (a "unique" handle that+ * silently isn't) proven avoided; the allocator's throw-at-cap is its loud+ * terminal. Connects directly to local D1, same as forum-post-slug-unique.test.ts.+ */++const owner = "e2e_srvdisc_owner"+const ids = [+ "e2e_srvdisc_s1",+ "e2e_srvdisc_s2",+ "e2e_srvdisc_s3",+ "e2e_srvdisc_s4",+ "e2e_srvdisc_s5",+]+const TS = "2026-08-04T00:00:00.000Z"++function createRealQueryDb() {+ const binding = {+ prepare(query: string) {+ return {+ bind(...params: unknown[]) {+ return {+ async all() {+ return { results: sqlQuery(query, ...params) }+ },+ async raw() {+ return sqlQuery<Record<string, unknown>>(query, ...params).map(Object.values)+ },+ }+ },+ }+ },+ }+ return createDb(binding as never)+}++function insertServer(id: string, name: string, disc: string): void {+ sqlRun(+ `INSERT INTO community_server (id, name, discriminator, description, owner_id, created_at)+ VALUES (?, ?, ?, '', ?, ?)`,+ id, name, disc, owner, TS,+ )+}++function cleanup(): void {+ sqlRun(`DELETE FROM community_server WHERE id IN (${ids.map(() => "?").join(",")})`, ...ids)+ sqlRun(`DELETE FROM user WHERE id = ?`, owner)+}++beforeAll(() => {+ cleanup()+ sqlRun(`INSERT INTO user (id, email, name) VALUES (?, ?, ?)`, owner, `${owner}@example.com`, "Srv Disc Owner")+})++afterAll(cleanup)++describe("idx_community_server_name_discriminator — server handle uniqueness (migration 0080)", () => {+ it("refuses a duplicate (name, discriminator) server — existence count stays 1, no silent double-insert", () => {+ insertServer(ids[0]!, "e2e_srvdisc_gaming", "0001")+ // Second insert of the SAME name#disc → the index refuses it.+ expect(() => insertServer(ids[1]!, "e2e_srvdisc_gaming", "0001")).toThrow(/UNIQUE constraint failed/i)++ // Existence oracle: exactly ONE gaming#0001 exists — the refused insert did+ // NOT silently create a second (the never-drop worst side: a handle that+ // resolves to two servers nondeterministically).+ const rows = sqlQuery<{ id: string }>(+ `SELECT id FROM community_server WHERE name = ? AND discriminator = ?`,+ "e2e_srvdisc_gaming", "0001",+ )+ expect(rows).toHaveLength(1)+ })++ it("allows the same name with a DIFFERENT discriminator — N distinct handles, never a merge", () => {+ // The allocator's response to the collision above: re-salt to a fresh disc+ // and retry. Two same-name servers coexist, disambiguated by disc.+ insertServer(ids[2]!, "e2e_srvdisc_gaming", "0002")+ const rows = sqlQuery<{ discriminator: string }>(+ `SELECT discriminator FROM community_server WHERE name = ? ORDER BY discriminator`,+ "e2e_srvdisc_gaming",+ )+ expect(rows.map((r) => r.discriminator)).toEqual(["0001", "0002"]) // 2 distinct, not merged+ })++ it("folds name case-insensitively (COLLATE NOCASE) — Alook#0001 and alook#0001 collide", () => {+ // The index MUST fold case identically to resolveServerByNameForMember's+ // lookup (the index/resolver alignment migration 0075 established), else a+ // ref differing only in case would resolve to a different-cased twin.+ insertServer(ids[3]!, "E2E_SrvDisc_Cased", "0007")+ expect(() => insertServer(ids[4]!, "e2e_srvdisc_cased", "0007")).toThrow(/UNIQUE constraint failed/i)++ const rows = sqlQuery<{ id: string }>(+ `SELECT id FROM community_server WHERE name = ? COLLATE NOCASE AND discriminator = ?`,+ "e2e_srvdisc_cased", "0007",+ )+ expect(rows).toHaveLength(1) // the case-variant twin was refused+ })+})++const resolveOwner = "e2e_srvresolve_owner"+const resolveMember = "e2e_srvresolve_member"+const resolveOutsider = "e2e_srvresolve_outsider"+const resolveServer4 = "e2e_srvresolve_s4"+const resolveServer5 = "e2e_srvresolve_s5"+const resolveChannel4 = "e2e_srvresolve_c4"+const resolveChannel5 = "e2e_srvresolve_c5"++function resolveCleanup(): void {+ sqlRun(+ `DELETE FROM community_server WHERE id IN (?, ?)`,+ resolveServer4, resolveServer5,+ )+ sqlRun(+ `DELETE FROM user WHERE id IN (?, ?, ?)`,+ resolveOwner, resolveMember, resolveOutsider,+ )+}++describe("resolveServerByNameForMember — real D1 handle and membership behavior", () => {+ beforeAll(() => {+ resolveCleanup()+ for (const id of [resolveOwner, resolveMember, resolveOutsider]) {+ sqlRun(+ `INSERT INTO user (id, email, name) VALUES (?, ?, ?)`,+ id, `${id}@example.com`, id,+ )+ }+ sqlRun(+ `INSERT INTO community_server (id, name, discriminator, description, owner_id, created_at)+ VALUES (?, ?, ?, '', ?, ?), (?, ?, ?, '', ?, ?)`,+ resolveServer4, "E2E_Resolve_Studio", "0042", resolveOwner, TS,+ resolveServer5, "e2e_resolve_studio", "12345", resolveOwner, TS,+ )+ sqlRun(+ `INSERT INTO community_server_member (id, server_id, user_id, role, joined_at)+ VALUES (?, ?, ?, 'member', ?), (?, ?, ?, 'member', ?)`,+ "e2e_srvresolve_m4", resolveServer4, resolveMember, TS,+ "e2e_srvresolve_m5", resolveServer5, resolveMember, TS,+ )+ sqlRun(+ `INSERT INTO community_channel (id, server_id, name, type, created_at)+ VALUES (?, ?, 'general', 'text', ?), (?, ?, 'general', 'text', ?)`,+ resolveChannel4, resolveServer4, TS,+ resolveChannel5, resolveServer5, TS,+ )+ })+ afterAll(resolveCleanup)++ it("resolves same-name 4-digit and expanded handles uniquely with NOCASE names", async () => {+ const db = createRealQueryDb()+ await expect(+ queries.communityServer.resolveServerByNameForMember(+ db, resolveMember, "e2e_resolve_studio#0042",+ ),+ ).resolves.toEqual([+ { id: resolveServer4, name: "E2E_Resolve_Studio", discriminator: "0042" },+ ])+ await expect(+ queries.communityServer.resolveServerByNameForMember(+ db, resolveMember, "E2E_RESOLVE_STUDIO#12345",+ ),+ ).resolves.toEqual([+ { id: resolveServer5, name: "e2e_resolve_studio", discriminator: "12345" },+ ])+ })++ it("rejects a bare name even when it matches member servers", async () => {+ const rows = await queries.communityServer.resolveServerByNameForMember(+ createRealQueryDb(), resolveMember, "E2E_RESOLVE_STUDIO",+ )+ expect(rows).toEqual([])+ })++ it("masks a non-member real handle exactly like a nonexistent handle", async () => {+ const db = createRealQueryDb()+ const real = await resolveTargetForMember(+ db, resolveOutsider, "/E2E_Resolve_Studio#0042/general",+ )+ const missing = await resolveTargetForMember(+ db, resolveOutsider, "/E2E_Resolve_Studio#99999/general",+ )+ expect(real).toEqual({ error: 404, message: "server not found" })+ expect(missing).toEqual(real)+ })+})++/**+ * Real-DB widen oracle for (A) variable-width allocation — the load-bearing+ * proof Aigneis #91 / Ingaborg #93 required, driving the REAL allocator+ * (`withUniqueDiscriminator`) against real D1, NOT a mock. Proves:+ * (i) never-cap: when every width-4 salt the allocator tries is already taken,+ * it WIDENS to a 5-digit discriminator instead of throwing at a cap.+ * (ii) loud / never-silent-dup: the win is a real INSERT that survived the real+ * UNIQUE index — the taken width-4 rows are NOT overwritten or duplicated.+ * The (A)-vs-(B) behavior reversal: (B) threw at the cap, (A) widens.+ */+const wOwner = "e2e_widen_owner"+const wName = "e2e_widen_saturated"+// The exact seed the allocator will use for a given (id, width, attempt).+const wId = "e2e_widen_server_id"+const width4Salts = [+ computeDiscriminator(wId), // bare id, width 4, attempt 0+ computeDiscriminator(`${wId}:4:1`, 4),+ computeDiscriminator(`${wId}:4:2`, 4),+ computeDiscriminator(`${wId}:4:3`, 4),+ computeDiscriminator(`${wId}:4:4`, 4),+]+const distinctWidth4 = [...new Set(width4Salts)]+const wSquatIds = distinctWidth4.map((_, i) => `e2e_widen_squat_${i}`)+const wWinId = "e2e_widen_winner"++function widenCleanup(): void {+ sqlRun(+ `DELETE FROM community_server WHERE id IN (${[...wSquatIds, wWinId].map(() => "?").join(",")})`,+ ...wSquatIds, wWinId,+ )+ sqlRun(`DELETE FROM user WHERE id = ?`, wOwner)+}++describe("withUniqueDiscriminator widen — never-cap, loud (A: variable-width)", () => {+ beforeAll(() => {+ widenCleanup()+ sqlRun(`INSERT INTO user (id, email, name) VALUES (?, ?, ?)`, wOwner, `${wOwner}@example.com`, "Widen Owner")+ // Squat EVERY width-4 salt the allocator will try for (wId, wName) so the+ // width-4 budget is fully saturated and it must widen to 5 digits. Two salts+ // can hash to the same 4-digit value — occupy each DISTINCT value once (the+ // unique index would reject a duplicate value anyway).+ distinctWidth4.forEach((disc, i) => insertServer(wSquatIds[i]!, wName, disc))+ })+ afterAll(widenCleanup)++ it("widens to a 5-digit discriminator when all width-4 salts are taken (never caps, never dups)", async () => {+ // Drive the REAL allocator; its insertFn does a REAL INSERT that hits the+ // REAL unique index. `_db` is unused by withUniqueDiscriminator.+ const winning = await queries.user.withUniqueDiscriminator(+ {} as never,+ { id: wId, name: wName },+ async (discriminator: string) => {+ insertServer(wWinId, wName, discriminator) // throws on UNIQUE collision → allocator re-salts+ return discriminator+ },+ )++ // (i) never-cap: the winning disc widened past 4 digits.+ expect(winning.length).toBe(5)+ expect(width4Salts).not.toContain(winning)++ // (ii) never-silent-dup: exactly ONE row holds the winning handle, and the+ // 5 squatted width-4 rows are all still present + untouched (N+1 total, no+ // overwrite of a taken width-4 handle).+ const win = sqlQuery<{ id: string }>(+ `SELECT id FROM community_server WHERE name = ? AND discriminator = ?`,+ wName, winning,+ )+ expect(win.map((r) => r.id)).toEqual([wWinId])+ const all = sqlQuery<{ c: number }>(+ `SELECT COUNT(*) AS c FROM community_server WHERE name = ?`,+ wName,+ )+ expect(all[0]!.c).toBe(distinctWidth4.length + 1) // squatted width-4 + 1 widened winner+ })+})diff --git a/src/web/src/test/e2e/forum-post-slug-unique.test.ts b/src/web/src/test/e2e/forum-post-slug-unique.test.tsdeleted file mode 100644index 10ebb9b86..000000000--- a/src/web/src/test/e2e/forum-post-slug-unique.test.ts+++ /dev/null@@ -1,112 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { sqlRun, sqlQuery } from "@alook/test-utils"--/**- * Real-DB existence oracle for the forum-post slug unique index- * (`idx_forum_post_parent_name`, migration 0078). This verifies the- * LOAD-BEARING half of pure-create's concurrent no-merge contract that the- * create-collision unit test can't: that the DB index ACTUALLY throws on a- * duplicate `(parent_channel_id, name)` for a forum_post — not that the policy- * re-bumps GIVEN a throw (that's the unit test's mocked half).- *- * The oracle is EXISTENCE-COUNT, not error-absence (Aigneis's #18 form): two- * inserts of the same forum-post slug must leave exactly ONE row (the 2nd is- * refused), and the bumped-slug retry must leave TWO distinct rows — never a- * silent double-insert of the same slug (the original race this whole B4 guards).- * Connects directly to the local D1 sqlite (bypassing the query wrapper), same- * as community-bot-owner-fk.test.ts.- */--const forumA = "e2e_slug_forum_a"-const forumB = "e2e_slug_forum_b"-const srv = "e2e_slug_srv"-const owner = "e2e_slug_owner"-const ids = ["e2e_slug_p1", "e2e_slug_p2", "e2e_slug_p3", "e2e_slug_p4", "e2e_slug_p5"]-const TS = "2026-08-04T00:00:00.000Z"--function insertPost(id: string, parent: string, name: string, type = "forum_post"): void {- sqlRun(- `INSERT INTO community_channel (id, server_id, parent_channel_id, name, type, created_at)- VALUES (?, ?, ?, ?, ?, ?)`,- id, srv, parent, name, type, TS,- )-}--// FK parents: a user (server owner) → a server → the two top-level forum-// channels the posts hang under. The e2e connection enforces foreign keys, so-// these must exist before any forum_post row references them.-function cleanup(): void {- sqlRun(`DELETE FROM community_channel WHERE id IN (${ids.map(() => "?").join(",")})`, ...ids)- sqlRun(`DELETE FROM community_channel WHERE id IN (?, ?)`, forumA, forumB)- sqlRun(`DELETE FROM community_server WHERE id = ?`, srv)- sqlRun(`DELETE FROM user WHERE id = ?`, owner)-}--beforeAll(() => {- cleanup()- sqlRun(`INSERT INTO user (id, email, name) VALUES (?, ?, ?)`, owner, `${owner}@example.com`, "Slug Owner")- sqlRun(- `INSERT INTO community_server (id, name, description, owner_id, created_at) VALUES (?, ?, ?, ?, ?)`,- srv, "Slug Srv", "", owner, TS,- )- // Two top-level forum channels (parent_channel_id NULL) — the posts' anchors.- sqlRun(- `INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, ?, ?, 'forum', ?)`,- forumA, srv, "forum-a", TS,- )- sqlRun(- `INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, ?, ?, 'forum', ?)`,- forumB, srv, "forum-b", TS,- )-})--afterAll(cleanup)--describe("idx_forum_post_parent_name — forum-post slug uniqueness (migration 0078)", () => {- it("refuses a duplicate (parent, name) forum_post — existence count stays 1, no silent double-insert", () => {- insertPost(ids[0]!, forumA, "ideas")- // Second insert of the SAME slug under the SAME forum → the index refuses it.- expect(() => insertPost(ids[1]!, forumA, "ideas")).toThrow(/UNIQUE constraint failed/i)-- // Existence oracle: exactly ONE "ideas" post exists under forumA — the- // refused insert did NOT silently create a second (the original race).- const rows = sqlQuery<{ id: string }>(- `SELECT id FROM community_channel WHERE parent_channel_id = ? AND name = ? AND type = 'forum_post'`,- forumA, "ideas",- )- expect(rows).toHaveLength(1)- })-- it("a bumped slug creates a SECOND distinct post — pure-create yields N distinct, never a merge", () => {- // The pure-create policy's response to the collision above: bump to- // `ideas-2` and retry. That must succeed → two distinct addressable posts.- insertPost(ids[2]!, forumA, "ideas-2")- const rows = sqlQuery<{ name: string }>(- `SELECT name FROM community_channel WHERE parent_channel_id = ? AND type = 'forum_post' ORDER BY name`,- forumA,- )- expect(rows.map((r) => r.name)).toEqual(["ideas", "ideas-2"]) // 2 distinct, N-distinct not merged- })-- it("does NOT restrict the same slug under a DIFFERENT forum (index is per-parent)", () => {- // Same name "ideas" under forumB is legal — the anchor is (parent, name).- expect(() => insertPost(ids[3]!, forumB, "ideas")).not.toThrow()- const rows = sqlQuery<{ id: string }>(- `SELECT id FROM community_channel WHERE name = ? AND type = 'forum_post'`,- "ideas",- )- expect(rows).toHaveLength(2) // one per forum- })-- it("does NOT restrict a duplicate name for a NON-forum_post child (WHERE type='forum_post' scoping — no thread false-positive)", () => {- // A thread (or any non-forum_post child) may share a name freely — the- // partial index's WHERE clause excludes it, so blanket-uniqueness never- // wrongly rejects a legal duplicate thread name.- insertPost(ids[4]!, forumA, "ideas", "thread")- const threadRows = sqlQuery<{ id: string }>(- `SELECT id FROM community_channel WHERE parent_channel_id = ? AND name = ? AND type = 'thread'`,- forumA, "ideas",- )- expect(threadRows).toHaveLength(1) // the thread inserted fine despite forum_post "ideas" existing- })-})diff --git a/src/web/src/test/e2e/user-discriminator-unique.test.ts b/src/web/src/test/e2e/user-discriminator-unique.test.tsnew file mode 100644index 000000000..fde1b0839--- /dev/null+++ b/src/web/src/test/e2e/user-discriminator-unique.test.ts@@ -0,0 +1,79 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { sqlRun, sqlQuery } from "@alook/test-utils"++/**+ * Real-DB existence oracle for the user discriminator unique index+ * (`idx_user_name_discriminator`, migration 0055). Backfills a coverage gap:+ * before this, only the MOCKED `withUniqueDiscriminator` retry test existed+ * (user.test.ts) — nothing asserted the DB index actually fires on a duplicate+ * `(name COLLATE NOCASE, discriminator)`. This is the user-side twin of+ * community-server-discriminator-unique.test.ts; the two share the allocator.+ *+ * EXISTENCE-COUNT oracle (Aigneis #18 form). The user index differs from the+ * server one in TWO ways this test pins: (1) it is PARTIAL (`WHERE deletedAt IS+ * NULL`) — a soft-deleted user's handle can be reissued; (2) NOCASE folding, so+ * a handle lookup can't match two live rows nondeterministically. Direct local+ * D1, same as forum-post-slug-unique.test.ts.+ *+ * ★ Probe-path coverage (Aigneis #91 / Ingaborg #93): the Better-Auth email+ * signup exit (`probeAvailableDiscriminator`) can't wrap its own insert, so its+ * LOUD terminal is DOWNSTREAM at Better-Auth's insert hitting THIS index. That+ * index-fires-on-duplicate is exactly what test 1 below proves; the probe's+ * WIDEN behaviour (never caps at 4, returns a wider disc when width-4 is+ * saturated) is proven in the mocked unit test (user.test.ts) — together they+ * cover "probe widens + its downstream insert is loud, never a silent dup",+ * without a brittle Drizzle shim to run probe end-to-end here.+ */++const ids = [+ "e2e_udisc_u1",+ "e2e_udisc_u2",+ "e2e_udisc_u3",+ "e2e_udisc_u4",+ "e2e_udisc_u5",+]++function insertUser(id: string, name: string, disc: string, deletedAt: string | null = null): void {+ sqlRun(+ `INSERT INTO user (id, email, name, discriminator, deletedAt) VALUES (?, ?, ?, ?, ?)`,+ id, `${id}@example.com`, name, disc, deletedAt,+ )+}++function cleanup(): void {+ sqlRun(`DELETE FROM user WHERE id IN (${ids.map(() => "?").join(",")})`, ...ids)+}++beforeAll(cleanup)+afterAll(cleanup)++describe("idx_user_name_discriminator — user handle uniqueness (migration 0055)", () => {+ it("refuses a duplicate (name, discriminator) among LIVE users — existence count stays 1", () => {+ insertUser(ids[0]!, "e2e_udisc_alice", "0042")+ expect(() => insertUser(ids[1]!, "e2e_udisc_alice", "0042")).toThrow(/UNIQUE constraint failed/i)++ const rows = sqlQuery<{ id: string }>(+ `SELECT id FROM user WHERE name = ? AND discriminator = ? AND deletedAt IS NULL`,+ "e2e_udisc_alice", "0042",+ )+ expect(rows).toHaveLength(1)+ })++ it("folds name case-insensitively (COLLATE NOCASE) — Alice#0042 and alice#0042 collide", () => {+ insertUser(ids[2]!, "e2e_udisc_Bob", "0100")+ expect(() => insertUser(ids[3]!, "e2e_udisc_bob", "0100")).toThrow(/UNIQUE constraint failed/i)+ })++ it("PARTIAL index (WHERE deletedAt IS NULL) — a soft-deleted user's handle can be reissued", () => {+ // Soft-delete the first alice, then a NEW live alice#0042 must be allowed:+ // the deleted row is outside the partial index, so its handle frees up.+ sqlRun(`UPDATE user SET deletedAt = ? WHERE id = ?`, "2026-08-04T01:00:00.000Z", ids[0]!)+ expect(() => insertUser(ids[4]!, "e2e_udisc_alice", "0042")).not.toThrow()++ const live = sqlQuery<{ id: string }>(+ `SELECT id FROM user WHERE name = ? AND discriminator = ? AND deletedAt IS NULL`,+ "e2e_udisc_alice", "0042",+ )+ expect(live.map((r) => r.id)).toEqual([ids[4]]) // exactly the reissued live row+ })+})diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex ea44ee280..ee636c3ea 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -275,17 +275,17 @@ vi.mock("@alook/shared", () => {createLogger: () => noopLogger,withD1Retry: async <T>(fn: () => Promise<T>): Promise<T> => fn(),// Real reach-trait impls — fanOutTyping's recipient split dispatches on- // channelReach (B2 reach axis single source) to route a thread/forum_post to- // the participant set, a dm to its members, else the access audience. Mirror+ // channelReach (B2 reach axis single source) to route a thread to the+ // participant set, a dm to its members, else the access audience. Mirror// the real CHANNEL_TRAITS reach values + the stored-type guard.channelReach: (t: string) =>- t === "forum_post" || t === "thread"+ t === "thread"? "participant-set": t === "dm"? "dm-pair": "server-or-roster",isStoredChannelType: (t: unknown) =>- t === "text" || t === "forum" || t === "forum_post" || t === "thread" || t === "dm",+ t === "text" || t === "forum" || t === "thread" || t === "dm",// Minimal `readOrStale` shim — bypasses the classifier so tests can// inject arbitrary Error shapes at the query-fn boundary and observe// fail-closed semantics. Real production behavior (retry then fallback)@@ -2775,30 +2775,6 @@ describe("WebSocketDurableObject", () => {expect(mockStubFetch).toHaveBeenCalledTimes(1)})- it("forum_post: typing fans out to PARTICIPANTS, not the whole server", async () => {- const { durable, env } = createDO()- mockGetChannelForMember.mockResolvedValueOnce({ id: "post-1", serverId: "server-1" })- mockGetChannelType.mockResolvedValueOnce("forum_post")- mockListThreadParticipantUserIds.mockResolvedValueOnce(["sender-1", "part-1"])-- const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })-- await durable.webSocketMessage(- ws as any,- JSON.stringify({ type: "community:typing.start", channelId: "post-1" }),- )- await flush()-- // A public forum post reaches only its participants — same path as a- // message fan-out — never the access-audience resolver (the whole server).- expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "post-1")- expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:part-1")- expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")- expect(mockStubFetch).toHaveBeenCalledTimes(1)- })-it("does not fan out when sender is not a participant of the target DM", async () => {const { durable, env } = createDO()// A DM is a type=dm channel now; a non-member sender can't see it, sodiff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.tsindex 994ef37c2..bc3481094 100644--- a/tests/integration/daemon/control-plane.test.ts+++ b/tests/integration/daemon/control-plane.test.ts@@ -9,7 +9,7 @@* → sendWakeToMachine → alook-ws-do (real DO) → the daemon's real* `WsControlChannel`, over a real WebSocket, receives `agent:wake`* → the test (playing the "agent" — no CLI spawned) replies via the- * real `enroll-agent` → `inboxPull`/`ack`/`send` HTTP chain+ * real `enroll-agent` → canonical pull/ack/send HTTP chain* → the reply is visible via a real read of the channel.** Requires `wrangler dev` (`@alook/web`), `@alook/ws-do dev`, and@@ -159,11 +159,8 @@ describe("daemon control plane — real ws-do wake round-trip", () => {expect(wake.agentId).toBe(fixture.bot.botUserId)// Acting as the "agent" (no CLI spawned): mint the runner key, then- // pull the backlog, ack it, and send a reply — all real HTTP against the- // flat /api/community/* bot verbs, exactly what a real agent's CLI would do.- // (The `agent/*` path layer was removed when the bot verbs moved flat; this- // test still hard-coded the stale `agent/*` paths → 404 HTML → the red on- // main + here until this fix. enroll-agent stays under daemon/, unchanged.)+ // pull the backlog, ack it, and send a reply through the canonical HTTP+ // resources exactly as a real agent's CLI would do.const enrollRes = await fetchWithRetry(`${APP_URL}/api/community/daemon/enroll-agent`, {method: "POST",headers: { Authorization: `Bearer ${fixture.paired.credential}`, "content-type": "application/json" },@@ -173,19 +170,19 @@ describe("daemon control plane — real ws-do wake round-trip", () => {const { runnerKey } = (await enrollRes.json()) as { runnerKey: string; expiresAt: string | null }expect(runnerKey.startsWith("crk_")).toBe(true)- const pullRes = await fetchWithRetry(`${APP_URL}/api/community/inboxPull`, {+ const pullRes = await fetchWithRetry(`${APP_URL}/api/community/users/me/inbox/pull`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({}),})- await assertResOk(pullRes, "inboxPull (:167 enroll→pull hop)")+ await assertResOk(pullRes, "inbox pull (enroll→pull hop)")// Wire `seq` is formatted `"#N"` (see `formatSeq`/`toAgentMessages`) —// the ack cursor schema wants the bare number back (`parseSeq`).const pulled = (await pullRes.json()) as { messages: Array<{ seq: string; channel: string }> }expect(pulled.messages.length).toBeGreaterThan(0)const lastPulled = pulled.messages[pulled.messages.length - 1]!- const ackRes = await fetchWithRetry(`${APP_URL}/api/community/ack`, {+ const ackRes = await fetchWithRetry(`${APP_URL}/api/community/users/me/inbox/ack`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({ cursors: [{ channel: lastPulled.channel, seq: parseSeq(lastPulled.seq) }] }),@@ -193,10 +190,10 @@ describe("daemon control plane — real ws-do wake round-trip", () => {expect(ackRes.ok).toBe(true)const replyText = `reply from the real credential chain ${nanoid()}`- const sendRes = await fetchWithRetry(`${APP_URL}/api/community/send`, {+ const sendRes = await fetchWithRetry(`${APP_URL}/api/community/channels/resolve/messages`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },- body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelName}`, content: { text: replyText } }),+ body: JSON.stringify({ channel: `/${fixture.serverHandle}/${fixture.channelName}`, content: { text: replyText } }),})expect(sendRes.ok).toBe(true)const sendBody = (await sendRes.json()) as { state: string }@@ -285,27 +282,27 @@ describe("daemon control plane — real ws-do wake round-trip", () => {expect(enrollRes.ok).toBe(true)const { runnerKey } = (await enrollRes.json()) as { runnerKey: string }- const pullRes = await fetchWithRetry(`${APP_URL}/api/community/inboxPull`, {+ const pullRes = await fetchWithRetry(`${APP_URL}/api/community/users/me/inbox/pull`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({}),})- await assertResOk(pullRes, "inboxPull (:279 multi-bot enroll→pull)")+ await assertResOk(pullRes, "inbox pull (multi-bot enroll→pull)")const pulled = (await pullRes.json()) as { messages: Array<{ seq: string; channel: string }> }expect(pulled.messages.length).toBeGreaterThan(0)const lastPulled = pulled.messages[pulled.messages.length - 1]!- await fetchWithRetry(`${APP_URL}/api/community/ack`, {+ await fetchWithRetry(`${APP_URL}/api/community/users/me/inbox/ack`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },body: JSON.stringify({ cursors: [{ channel: lastPulled.channel, seq: parseSeq(lastPulled.seq) }] }),})const replyText = `reply from ${bot.botUserId} ${nanoid()}`- const sendRes = await fetchWithRetry(`${APP_URL}/api/community/send`, {+ const sendRes = await fetchWithRetry(`${APP_URL}/api/community/channels/resolve/messages`, {method: "POST",headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },- body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelName}`, content: { text: replyText } }),+ body: JSON.stringify({ channel: `/${fixture.serverHandle}/${fixture.channelName}`, content: { text: replyText } }),})expect(sendRes.ok).toBe(true)const sendBody = (await sendRes.json()) as { state: string }diff --git a/tests/integration/daemon/credential-chain.test.ts b/tests/integration/daemon/credential-chain.test.tsindex 5359a8d53..4ba458f37 100644--- a/tests/integration/daemon/credential-chain.test.ts+++ b/tests/integration/daemon/credential-chain.test.ts@@ -39,9 +39,8 @@ beforeAll(async () => {expect(enrollRes.ok).toBe(true); ({ runnerKey } = (await enrollRes.json()) as { runnerKey: string })- // Upstream is the real web app's origin — the proxy itself rewrites- // `/api/*` → `/api/community/agent/*` (mirrors `createDaemon`'s- // `upstreamBaseUrl: opts.serverUrl` wiring).+ // Upstream is the real web app's origin. The client sends canonical+ // `/api/community/*` REST paths and the proxy preserves them unchanged.broker = new CredentialBroker({ upstreamBaseUrl: APP_URL })proxy = await startCredentialProxy(broker)}, 30_000)@@ -53,23 +52,23 @@ afterAll(async () => {})describe("daemon credential chain — real local proxy against the real web app", () => {- it("a valid per-launch voucher reaches the real /api/community/agent/read route and gets a well-formed response", async () => {+ it("a valid per-launch voucher reaches the canonical channel-messages read door", async () => {const reg = broker.mint(fixture.bot.botUserId, "launch-1", ["read", "send"], runnerKey)const api = createProxyServerApi({ proxyUrl: proxy.url, voucher: reg.voucher })const page = await api.read({agentId: fixture.bot.botUserId,- channel: `/${fixture.serverId}/${fixture.channelName}`,+ channel: `/${fixture.serverHandle}/${fixture.channelName}`,})expect(Array.isArray(page.items)).toBe(true)expect(typeof page.hasMore).toBe("boolean")})- it("rejects a forged/unknown voucher AT THE PROXY — distinct from what the real upstream would return for a bad crk_, proving upstream was never reached", async () => {+ it("auth-before-shape: rejects a forged voucher with 401 before examining the deleted flat path", async () => {const res = await fetch(`${proxy.url}/api/read`, {method: "POST",headers: { Authorization: "Bearer vch_this_was_never_minted", "content-type": "application/json" },- body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelName}` }),+ body: JSON.stringify({ channel: `/${fixture.serverHandle}/${fixture.channelName}` }),})expect(res.status).toBe(401)const body = (await res.json()) as { error: string; code: string }diff --git a/tests/integration/daemon/seed-helpers.ts b/tests/integration/daemon/seed-helpers.tsindex cca973d6c..54a581078 100644--- a/tests/integration/daemon/seed-helpers.ts+++ b/tests/integration/daemon/seed-helpers.ts@@ -6,6 +6,7 @@*/import { randomUUID } from "crypto"import {+ sqlQuery,sqlRun,pairAndActivateMachine,seedCommunityBot,@@ -15,6 +16,7 @@ import {type PairedMachine,type SeededCommunityBot,} from "@alook/test-utils"+import { computeDiscriminator, formatHandle } from "@alook/shared"export function nanoid() {return randomUUID().replace(/-/g, "").slice(0, 21)@@ -22,12 +24,13 @@ export function nanoid() {export interface DaemonItFixture {serverId: string+ serverHandle: stringchannelId: string/*** Top-level channel NAME — the only way agent surfaces address a channel.* `resolveChannelByNameForMember` is name-only (migration 0057's partial- * unique index; agent refs never accept ids), so agent-facing routes- * (`/api/community/agent/*`) must build the ref as `/serverId/channelName`,+ * unique index; agent refs never accept ids), so canonical community REST+ * agent doors receive the ref as `/serverHandle/channelName`,* while the `/c` UI REST routes (`/api/community/channels/:id/*`) still key* on `channelId`.*/@@ -39,16 +42,25 @@ export interface DaemonItFixture {export async function seedPairedBot(seed: TestSeed, cookie: string): Promise<DaemonItFixture> {const now = new Date().toISOString()const serverId = `srv_${nanoid()}`+ const serverName = `Daemon IT Server ${serverId.slice(-8)}`+ const serverDiscriminator = computeDiscriminator(serverId)const channelId = `chn_${nanoid()}`const channelName = "general"sqlRun(- `INSERT INTO community_server (id, name, description, owner_id, created_at) VALUES (?, ?, ?, ?, ?)`,+ `INSERT INTO community_server (id, name, discriminator, description, owner_id, created_at) VALUES (?, ?, ?, ?, ?, ?)`,serverId,- "Daemon IT Server",+ serverName,+ serverDiscriminator,"",seed.userId,now,)+ const [server] = sqlQuery<{ name: string; discriminator: string }>(+ `SELECT name, discriminator FROM community_server WHERE id = ?`,+ serverId,+ )+ if (!server) throw new Error(`seedPairedBot: server ${serverId} was not persisted`)+ const serverHandle = formatHandle(server.name, server.discriminator)sqlRun(`INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, ?, ?)`,`mem_${nanoid()}`,@@ -70,7 +82,7 @@ export async function seedPairedBot(seed: TestSeed, cookie: string): Promise<Daeconst paired = await pairAndActivateMachine(cookie)const bot = seedCommunityBot({ ownerUserId: seed.userId, serverId, machineId: paired.machineId, runtime: "claude" })- return { serverId, channelId, channelName, paired, bot }+ return { serverId, serverHandle, channelId, channelName, paired, bot }}export function cleanupPairedBot(seed: TestSeed, fixture: DaemonItFixture): void {diff --git a/tests/utils/src/community.ts b/tests/utils/src/community.tsindex 624899561..3a0c9f769 100644--- a/tests/utils/src/community.ts+++ b/tests/utils/src/community.ts@@ -177,10 +177,10 @@ export interface SeededDm {}export async function seedDmViaApi(cookie: string, opts: { userId: string }): Promise<SeededDm> {- const res = await sessionRequest("/api/community/dm", cookie, {+ const res = await sessionRequest("/api/community/channels", cookie, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ userId: opts.userId }),+ body: JSON.stringify({ type: "dm", userId: opts.userId }),})if (!res.ok) throw new Error(`seedDmViaApi failed (${res.status})`)const data = (await res.json()) as { conversation: { id: string } }