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
fix(community): forum-post participant notify scope, per-post tags, presence flicker, CLI detection (#383)
Gener8230dc83e192
diff --git a/src/daemon/src/drivers/copilot.ts b/src/daemon/src/drivers/copilot.tsindex 721214bdf..4fc44de25 100644--- a/src/daemon/src/drivers/copilot.ts+++ b/src/daemon/src/drivers/copilot.ts@@ -31,6 +31,14 @@ export class CopilotDriver implements Driver {private sessionId: string | null = null;probe() {+ // Detection is `copilot --version` via the shared probe. On a machine where+ // the real Copilot CLI isn't installed, the `copilot` that resolves on PATH+ // is often the VS Code extension shim (e.g.+ // `~/Library/Application Support/Code/User/globalStorage/github.copilot-chat/copilotCli/copilot`),+ // which exits 0 and prints `Install GitHub Copilot CLI? ['y/N']` instead of+ // a version. `probeCommandVersion`'s version-shape validation rejects that+ // output, so this reports `unhealthy` (not-installed) rather than surfacing+ // the prompt text as a bogus version. Verified on macOS.return probeCliRuntime("copilot");}diff --git a/src/daemon/src/drivers/probe.test.ts b/src/daemon/src/drivers/probe.test.tsindex fdd0eeea6..b9d76479b 100644--- a/src/daemon/src/drivers/probe.test.ts+++ b/src/daemon/src/drivers/probe.test.ts@@ -93,3 +93,67 @@ describe("probeCommandVersion — Windows shim shell parity with resolveSpawnSpeexpect(execFileSync).toHaveBeenCalledWith("/usr/local/bin/agy.cmd", ["--version"], expect.objectContaining({ shell: false }));});});++/**+ * Version-shape validation + non-interactive spawn — the fix for the GitHub+ * Copilot shim that prints `Install GitHub Copilot CLI? ['y/N']` and exits 0.+ * The shim's prompt has no version token, so it must be rejected as+ * `invalid_version_output` rather than surfacing as a bogus "version". These+ * assert on the RETURNED result (the older tests only assert call args), so the+ * validation is actually covered.+ */+describe("probeCommandVersion — version validation + non-interactive spawn", () => {+ it("rejects the Copilot install prompt (exit 0, no version token)", () => {+ vi.mocked(execFileSync).mockReturnValue("Install GitHub Copilot CLI? ['y/N'] ");++ const result = probeCommandVersion("copilot", [], {}, "darwin");++ expect(result).toEqual({ ok: false, error: "invalid_version_output" });+ });++ it("rejects a non-version first line", () => {+ vi.mocked(execFileSync).mockReturnValue("Cannot find GitHub Copilot CLI\n");++ expect(probeCommandVersion("copilot", [], {}, "darwin")).toEqual({+ ok: false,+ error: "invalid_version_output",+ });+ });++ it("returns empty_version_output for blank output", () => {+ vi.mocked(execFileSync).mockReturnValue("\n");++ expect(probeCommandVersion("copilot", [], {}, "darwin")).toEqual({+ ok: false,+ error: "empty_version_output",+ });+ });++ it("accepts a plain semver", () => {+ vi.mocked(execFileSync).mockReturnValue("1.2.3\n");++ expect(probeCommandVersion("claude", [], {}, "darwin")).toEqual({ ok: true, version: "1.2.3" });+ });++ it("accepts a v-prefixed version and keeps the whole line", () => {+ vi.mocked(execFileSync).mockReturnValue("codex v0.4\n");++ expect(probeCommandVersion("codex", [], {}, "darwin")).toEqual({ ok: true, version: "codex v0.4" });+ });++ it("spawns non-interactively: empty stdin + CI env, stdout still piped", () => {+ vi.mocked(execFileSync).mockReturnValue("1.2.3\n");++ probeCommandVersion("gemini", [], {}, "darwin");++ expect(execFileSync).toHaveBeenCalledWith(+ "gemini",+ ["--version"],+ expect.objectContaining({+ input: "",+ encoding: "utf8",+ env: expect.objectContaining({ CI: "1" }),+ }),+ );+ });+});diff --git a/src/daemon/src/drivers/probe.ts b/src/daemon/src/drivers/probe.tsindex cc7a8b0f0..a702cefc5 100644--- a/src/daemon/src/drivers/probe.ts+++ b/src/daemon/src/drivers/probe.ts@@ -44,6 +44,21 @@ export type VersionProbeResult =| { ok: true; version: string }| { ok: false; error: string };+/**+ * A `--version` line must look like a version to be accepted: it has to contain+ * a digit-dotted token (e.g. `1.2.3`, `v0.4`, `2024.1`). This is the+ * load-bearing defense against a CLI whose `--version` doesn't print a version+ * but instead an interactive prompt or error. Confirmed case: the VS Code+ * GitHub Copilot shim resolves as `copilot` on PATH, exits 0, and prints+ * `Install GitHub Copilot CLI? ['y/N']` to stdout — no version token, so it's+ * rejected here rather than surfacing as a bogus "version" on the Runtimes+ * page. The non-interactive spawn options below can't catch it (the shim exits+ * 0 even with stdin closed), so this regex is what draws the line.+ */+function looksLikeVersion(line: string): boolean {+ return /\d+\.\d+/.test(line);+}+/** True when `command` needs a shell to exec on this platform — Windows* can't run a `.cmd`/`.bat` shim (which is what most npm global installs* resolve to) directly via `CreateProcess`. Shared by `resolveSpawnSpec`@@ -80,9 +95,23 @@ export function probeCommandVersion(void deps;try {const shell = needsWindowsShimShell(command, platform);- const out = execFileSync(command, [...args, "--version"], { encoding: "utf8", timeout: 5000, shell });+ // Run non-interactively: feed empty stdin (`input: ""`) so a CLI that would+ // otherwise block on a prompt can't hang, and set `CI` in the child env+ // (options object only — never mutate `process.env`, per the statelessness+ // rule) so version-aware CLIs skip interactive paths. stdout stays piped+ // (execFileSync returns it) — that's what we parse. A misbehaving shim that+ // ignores all of this and prints a prompt anyway is caught by the+ // `looksLikeVersion` validation below.+ const out = execFileSync(command, [...args, "--version"], {+ encoding: "utf8",+ timeout: 5000,+ shell,+ input: "",+ env: { ...process.env, CI: "1" },+ });const line = out.split("\n")[0]?.trim();if (!line) return { ok: false, error: "empty_version_output" };+ if (!looksLikeVersion(line)) return { ok: false, error: "invalid_version_output" };return { ok: true, version: line };} catch (err) {const code =diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 68e245736..2c2b741ec 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -102,17 +102,23 @@ export const communityChannelMember = sqliteTable();// 3c. community_thread_participant-// The NOTIFICATION set for a thread (`community_channel` row of type "thread").-// A thread is NOT an access unit — any member of its parent channel can READ-// it. This table decides only WHO gets notified (mention pings + inbox unread)-// for new thread activity. `source` records how the user joined:-// - "mention" — @-mentioned in the thread (a parent-channel member).-// - "spoke" — posted a message in the thread.-// - "added" — added by another participant via the participant picker.-// Leaving a thread deletes the row (a later mention/speak re-adds). Admins are-// NOT auto-added — a thread's notify set is exactly its rows. Muting a thread is-// the OUTER channel-header notification level (per-layer, same control a channel-// uses), NOT a column here — participation is add/leave only.+// The NOTIFICATION set for a thread OR a forum_post (`community_channel` rows of+// type "thread" or "forum_post"). Despite the table name, it serves both: both+// are the notification dimension, so a message reaches only the unit's+// participants — a thread never notifies its whole parent channel, and a forum+// post (public or private) never notifies the whole server / whole roster, only+// the people actually involved. The FK `threadChannelId` points at+// `communityChannel.id`, which is why a forum_post id fits without a schema+// change. `source` records how the user joined:+// - "mention" — @-mentioned in the thread/post (within the unit's audience).+// - "spoke" — posted a message in the thread/post (a public post enrolls any+// server member who proactively sends; a private post's roster+// is added separately, see below).+// - "added" — added by another participant (thread picker) or, for a private+// forum_post, coupled from the access roster on member-add.+// Leaving deletes the row (a later mention/speak re-adds). Admins are NOT+// auto-added — the notify set is exactly its rows. Muting is the OUTER+// channel-header notification level, NOT a column here — add/leave only.export const communityThreadParticipant = sqliteTable("community_thread_participant",{diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex c877932bc..61a42150f 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -9,7 +9,7 @@ import {import { user } from "../../schema";import type { Database } from "../../index";import { listParticipatingThreadIds } from "./thread";-import { isThread } from "../../../utils/community-roles";+import { isThread, isForumPost } from "../../../utils/community-roles";export interface UnreadChannelRow {channelId: string;@@ -120,18 +120,27 @@ export async function listUnreadChannels(}));- // Thread unreads are scoped to PARTICIPATION (notification dimension): a- // thread surfaces in the inbox only for its participants (muted=0), NOT for- // every parent-channel member who can merely read it. Posts and channels flow- // through the visibility path above unchanged. Only threads are re-filtered.- const threadIds = unread.filter((r) => isThread(r.type)).map((r) => r.channelId);- const participatingThreadIds =- threadIds.length > 0- ? new Set(await listParticipatingThreadIds(db, threadIds, userId))+ // Thread AND forum-post 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+ // not flag as unread. Both store their notify set in the same participant+ // table (keyed by channel id), so one `listParticipatingThreadIds` covers+ // both. Top-level channels flow through the visibility path above unchanged.+ const notifyScopedIds = unread+ .filter((r) => isThread(r.type) || isForumPost(r.type))+ .map((r) => r.channelId);+ const participatingIds =+ notifyScopedIds.length > 0+ ? new Set(await listParticipatingThreadIds(db, notifyScopedIds, userId)): new Set<string>();return unread- .filter((r) => !isThread(r.type) || participatingThreadIds.has(r.channelId))+ .filter(+ (r) =>+ (!isThread(r.type) && !isForumPost(r.type)) ||+ participatingIds.has(r.channelId),+ ).map((r) => ({channelId: r.channelId,channelName: r.channelName,diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex 2600efabe..ae4951ba4 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -85,6 +85,29 @@ export async function listThreadParticipants(.where(eq(communityThreadParticipant.threadChannelId, threadChannelId));}+// Batch participant hydration for many channels at once — the forum post 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 (creator's "spoke" row is earliest, so they lead). Soft-deleted users+// drop out via the inner join, matching how the members list hydrates.+export async function listParticipantsForChannels(+ db: Database,+ channelIds: string[]+) {+ if (channelIds.length === 0) return [];+ return db+ .select({+ channelId: communityThreadParticipant.threadChannelId,+ userId: communityThreadParticipant.userId,+ addedAt: communityThreadParticipant.addedAt,+ userName: user.name,+ userImage: user.image,+ })+ .from(communityThreadParticipant)+ .innerJoin(user, eq(user.id, communityThreadParticipant.userId))+ .where(inArray(communityThreadParticipant.threadChannelId, channelIds));+}+export async function isThreadParticipant(db: Database,threadChannelId: string,diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex a62cf58ff..5833fa94d 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -287,6 +287,34 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {const result = await inboxQueries.listUnreadChannels(db, "u_1", ["t_out"]);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",+ lastReadAt: "2026-07-06T00:00:00.000Z",+ archived: false,+ joinedAt: j,+ });++ 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("public forum post the viewer has NOT joined is filtered out (visible but un-notified)", async () => {+ // A public post is visible to the whole server, so it lands in the unread+ // set, but it must only surface for its participants — an un-joined viewer+ // gets no unread badge.+ const db = createTwoQueryMock([unreadPostRow("p_out")], []);+ const result = await inboxQueries.listUnreadChannels(db, "u_1", ["p_out"]);+ expect(result).toEqual([]);+ });});describe("isDmUnread — predicate", () => {diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.tsindex 89509226d..cdefff217 100644--- a/src/web/src/app/api/community/agent/send/route.ts+++ b/src/web/src/app/api/community/agent/send/route.ts@@ -77,7 +77,12 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })const channel = gate.valuetarget = channel.parentChannelId- ? { kind: "thread", channelId: channel.id, parentChannelId: channel.parentChannelId, serverId: channel.serverId }+ ? {+ kind: channel.type === "forum_post" ? "forum_post" : "thread",+ channelId: channel.id,+ parentChannelId: channel.parentChannelId,+ serverId: channel.serverId,+ }: { kind: "channel", channelId: channel.id, serverId: channel.serverId }}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 11f18aea6..cb66e6d80 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@@ -15,6 +15,7 @@ const mockResolveScopeMembers = vi.fn()const mockGetMembersByUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()const mockLogAudit = vi.fn()+const mockAddThreadParticipants = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -36,6 +37,9 @@ vi.mock("@alook/shared", async () => {communityMembersResolver: {resolveScopeMembers: (...a: unknown[]) => mockResolveScopeMembers(...a),},+ communityThread: {+ addThreadParticipants: (...a: unknown[]) => mockAddThreadParticipants(...a),+ },user: { getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a) },},}@@ -251,5 +255,10 @@ describe("POST /channels/[id]/members", () => {expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), {channelId: "p1", userId: "u2", addedBy: "u1",})+ // Access → notify coupling: an added private-post member also joins the+ // post's participant (notify) set so they receive fan-out.+ expect(mockAddThreadParticipants).toHaveBeenCalledWith(expect.anything(), "p1", [+ { userId: "u2", source: "added" },+ ])})})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 66dade219..f42ddcbcf 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@@ -118,6 +118,17 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {addedBy: ctx.userId,})+ // Couple access → notify for a private forum post: an added member also joins+ // the post's participant (notify) set, so they receive fan-out. A post's+ // participant set is thus always a subset of its access roster. Idempotent —+ // if they already spoke/were mentioned, this is a no-op. (A top-level private+ // channel notifies via its access audience, so it needs no participant row.)+ if (isForumPost(channel.type)) {+ await queries.communityThread.addThreadParticipants(db, channelId, [+ { userId: targetUserId, source: "added" },+ ])+ }+const event = {type: WS_EVENTS.CHANNEL_MEMBER_ADD,serverId: channel.serverId,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 5990fce70..8b769f525 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@@ -148,14 +148,17 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("invalid request body", 400)}- // Thread channels (child channels with a parentChannelId) need to fire- // CHILD_CHANNEL_UPDATE on the parent so its thread indicator ticks. Detect- // that server-side from the channel row — clients always POST here, never- // to a separate thread endpoint, which avoided a UI race where a fast user- // could type before the client-side channel-meta fetch resolved.+ // 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: "thread" as const,+ kind: channel.type === "forum_post" ? ("forum_post" as const) : ("thread" as const),channelId,parentChannelId: channel.parentChannelId,serverId: channel.serverId,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.tsindex d9aa1990d..1f50ab33d 100644--- 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.ts@@ -13,6 +13,7 @@ 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: {} } })),@@ -48,6 +49,10 @@ vi.mock("@alook/shared", async () => {communityMention: {createMentions: vi.fn(async () => []),},+ communityThread: {+ addThreadParticipants: vi.fn(async () => {}),+ listParticipantsForChannels: (...a: unknown[]) => mockListParticipantsForChannels(...a),+ },user: {getUserSelf: (...a: unknown[]) => mockGetUserSelf(...a),getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),@@ -188,6 +193,32 @@ describe("GET /api/community/channels/[id]/posts — authorId", () => {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", () => {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.tsindex 8443a110b..f859bb973 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts@@ -72,6 +72,21 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {: []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).@@ -88,6 +103,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {authorAvatar,tags: t.tags ?? [],preview,+ participants: participantsByPost.get(t.id) ?? [],}})@@ -108,7 +124,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("channel is not a forum", 400)}- let body: { name?: string; content?: string; tags?: string[] }+ let body: { name?: string; content?: string }try {body = await req.json()} catch {@@ -134,18 +150,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError(`content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters`, 400)}- // Validate tags against channel's tags if present- if (body.tags && body.tags.length > 0) {- const allowedTags = channel.tags ?? []- if (allowedTags.length > 0) {- const invalid = body.tags.filter((t) => !allowedTags.includes(t))- if (invalid.length > 0) {- return writeError(`invalid tags: ${invalid.join(", ")}`, 400)- }- }- }-- // Create child channel for the forum post+ // Create child channel for the forum post. Tags are NOT set at creation —+ // they're added afterward from the post card's tag dialog.const postChannel = await queries.communityChannel.createChannel(db, {serverId: channel.serverId,parentChannelId: channelId,@@ -154,12 +160,14 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {creatorId: ctx.userId,})- // Set forumTags on the post channel to store selected tags- if (body.tags?.length) {- await queries.communityChannel.updateChannel(db, postChannel.id, {- forumTags: JSON.stringify(body.tags),- })- }+ // Enroll the creator as a participant so the post's notify set (which fan-out+ // now scopes to for a forum_post, exactly like a thread) starts with its+ // author. Done via a direct addThreadParticipants call rather than by routing+ // the first message as `kind:"forum_post"` — that would fire a+ // CHILD_CHANNEL_UPDATE colliding with the CHILD_CHANNEL_CREATE emitted below.+ await queries.communityThread.addThreadParticipants(db, postChannel.id, [+ { userId: ctx.userId, source: "spoke" },+ ])// Create the first message in the post through the unified pipeline so it// gets mention extraction + private-channel audience scoping (the forum's@@ -202,9 +210,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {messageCount: 1,lastMessageAt: message.createdAt,parent: { authorName, text: body.content.slice(0, MESSAGE_PREVIEW_LENGTH) },+ authorId: ctx.userId,authorAvatar,- tags: body.tags ?? [],+ tags: [],preview: body.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]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.tsindex a6b2dcc16..8c7dc53e2 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@@ -179,6 +179,73 @@ 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.+function forumPostCtx(over: { isCreator?: boolean; type?: string } = {}) {+ const { isCreator = true, type = "forum_post" } = over+ const channel = {+ id: "c1", serverId: "s1", type, parentChannelId: "forum_1",+ parentMessageId: null, creatorId: isCreator ? "u1" : "someone_else", categoryId: null,+ }+ return {+ channel,+ anchor: { ...channel, id: "forum_1", creatorId: "forum_owner" },+ role: "member",+ isPrivate: false, // public post → canManage resolves false even for the creator+ isChannelMember: false,+ isCreator,+ }+}++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("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()diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.tsindex 7dd392ca0..eec51b4e0 100644--- a/src/web/src/app/api/community/channels/[id]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/route.ts@@ -22,9 +22,17 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)const access = await requireChannelAccess(db, channelId, ctx.userId)if (!access.ok) return writeError(access.error, access.status)- if (!access.value.canManage) return writeError("forbidden", 403)const channel = access.value.channelconst isAdmin = canManageServer(access.value.member.role)+ // A forum post's creator may edit that post's tags even without full+ // `canManage` (a PUBLIC post's creator has `canManage === false`; a private+ // post's creator already passes it via `isPrivate && isCreator`). Scoped to+ // the `forumTags` field only below — every other field still requires+ // `canManage`. `access.value.isCreator` is the vetted post-own-creator flag+ // (NOT the forum creator), so we don't re-derive it from `channel.creatorId`.+ const canEditPostTags =+ channel.type === "forum_post" && access.value.isCreator+ if (!access.value.canManage && !canEditPostTags) return writeError("forbidden", 403)let body: { name?: string; topic?: string; categoryId?: string | null; forumTags?: string | null }try {@@ -33,6 +41,15 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {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 } = {}if (body.name !== undefined) {if (typeof body.name !== "string") return writeError("name must be a string", 400)@@ -74,7 +91,31 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {}changes.categoryId = body.categoryId}- if (body.forumTags !== undefined) changes.forumTags = body.forumTags+ 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)diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex 559f6c807..4ac1787bd 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -49,6 +49,7 @@ import {useUnpinMessage,useCreateThread,useCreateForumPost,+ useUpdatePostTags,useSetMemberRole,useKickMember,useSetChannelNotif,@@ -402,6 +403,7 @@ function ChannelView() {const unpinMessageMut = useUnpinMessage()const createThreadMut = useCreateThread()const createForumPostMut = useCreateForumPost()+ const updatePostTagsMut = useUpdatePostTags()const setMemberRoleMut = useSetMemberRole()const kickMemberMut = useKickMember()const setChannelNotifMut = useSetChannelNotif()@@ -677,7 +679,7 @@ function ChannelView() {communityWsSendTyping({ channelId })}- const createForumPost = async (post: { name: string; content: string; tags: string[] }) => {+ const createForumPost = async (post: { name: string; content: string }) => {try {const data = await createForumPostMut.mutateAsync({ channelId, ...post })// A post is its own child channel — open it, same as clicking a post row.@@ -951,9 +953,6 @@ function ChannelView() {// ── Forum view ──────────────────────────────────────────────────────────if (isForum) {- const allChannels = currentServer?.categories.flatMap((c) => c.channels) ?? []- const forumChannel = allChannels.find((ch) => ch.id === channelId)- const forumTags: string[] = forumChannel?.tags ?? []const canManage = canManageServer(myRole)return (<>@@ -973,17 +972,17 @@ function ChannelView() {<main className="flex min-h-0 min-w-0 flex-1 flex-col"><ForumViewposts={forumPosts}- tags={forumTags}loading={forumPostsLoading}onOpenPost={enterThread}onCreatePost={createForumPost}- canManageTags={canManage}- onTagsChanged={canManage ? (tags) => {- apiFetch(`/api/community/channels/${channelId}`, {- method: "PATCH",- body: JSON.stringify({ forumTags: JSON.stringify(tags) }),- }).catch((e) => toastApiError(e, "Failed to save tags"))- } : undefined}+ 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") },+ )+ }}/></main>diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex 2ebcf16e2..9ebdaab21 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -42,16 +42,16 @@ export default function MeLayout({ children }: { children: ReactNode }) {useCommunityStore.getState().setCurrentServerId(null)}, [])- // Seed the presence set for the friends/DM subtree — mirrors- // `channels/layout.tsx`'s `usePresence(serverId)` → `hydratePresence(...)`- // seed for server members. Without this, a friend who shares no server- // with you never shows online until a live WS event happens to arrive- // while you're on this page. `hydratePresence` is a one-shot replacement- // that no-ops on an identical list, so a re-render with the same online- // set doesn't cause an extra store write.+ // Seed the presence set for the friends/DM subtree. This fetch carries ONLY+ // friends — a strict subset of the WS presence audience (co-members ∪+ // friends). It must MERGE, not replace: a destructive `hydratePresence` here+ // would evict a DM peer who is a co-member-but-not-friend that the WS snapshot+ // had already marked online, flipping them online→offline ~1s after load (the+ // DM presence flicker bug). `mergePresence` unions instead, so WS-delivered+ // ids survive. It no-ops when every id is already present.const { online: onlineFriendIds } = useFriendsPresence()useEffect(() => {- useCommunityWsStore.getState().hydratePresence(onlineFriendIds)+ useCommunityWsStore.getState().mergePresence(onlineFriendIds)}, [onlineFriendIds])const hasDm = !!params.dmIddiff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 7bb1f0bf7..bb9832834 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -155,6 +155,11 @@ export type ForumPost = Thread & {authorAvatar: stringtags: string[]preview: string+ // The post's participant (notify) set — creator first, then whoever+ // spoke/was mentioned/was added. Drives the card's AvatarGroup. Always+ // 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 }[]}// ── Members / friends / DMs ──────────────────────────────────────────────────diff --git a/src/web/src/components/community/avatar.tsx b/src/web/src/components/community/avatar.tsxindex 0f42bb390..36fda3651 100644--- a/src/web/src/components/community/avatar.tsx+++ b/src/web/src/components/community/avatar.tsx@@ -80,6 +80,7 @@ export function Avatar({ label, seed, src, size = 40, dim = false, presence, rin)}{presence && (<AvatarBadge+ data-presence={presence}style={{background: STATUS_COLOR[presence],// Scales with the avatar instead of a fixed 10px — on a smalldiff --git a/src/web/src/components/community/create-forum-post.tsx b/src/web/src/components/community/create-forum-post.tsxindex 1f72d8a09..f8893b755 100644--- a/src/web/src/components/community/create-forum-post.tsx+++ b/src/web/src/components/community/create-forum-post.tsx@@ -3,30 +3,26 @@import { useState } from "react"import { X, Smile } from "lucide-react"import { Button } from "@/components/ui/button"-import { Badge } from "@/components/ui/badge"import { EmojiPickerPopover } from "./emoji-picker"import { SlugHint } from "./slug-hint"import { previewSlug } from "@/lib/community/slug-preview"-export type NewForumPost = { name: string; content: string; tags: string[] }+// Tags are added AFTER creation from the post card's tag dialog, not here — the+// create form stays focused on title + body.+export type NewForumPost = { name: string; content: string }-export function CreateForumPost({ tags, onCancel, onPost }: {- tags: string[]+export function CreateForumPost({ onCancel, onPost }: {onCancel: () => voidonPost: (post: NewForumPost) => void}) {const [title, setTitle] = useState("")const [body, setBody] = useState("")- const [selected, setSelected] = useState<string[]>([])-- const toggleTag = (t: string) =>- setSelected((prev) => (prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]))const titlePreview = previewSlug(title)const submit = () => {const name = title.trim()if (!titlePreview.slug) return- onPost({ name, content: body.trim(), tags: selected })+ onPost({ name, content: body.trim() })}return (@@ -53,22 +49,6 @@ export function CreateForumPost({ tags, onCancel, onPost }: {</div></div>- {/* tag chips */}- {tags.length > 0 && (- <div className="flex flex-wrap items-center gap-2 px-3 pb-2">- {tags.map((t) => (- <Badge- key={t}- variant={selected.includes(t) ? "default" : "secondary"}- className="cursor-pointer"- render={<button onClick={() => toggleTag(t)} />}- >- #{t}- </Badge>- ))}- </div>- )}-<div className="flex items-center justify-between border-t border-border px-3 py-2"><EmojiPickerPopover side="top" align="start" onPick={(e) => setBody((b) => b + e)}><button className="grid size-7 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:text-foreground" aria-label="Emoji picker">diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsxindex 5ba9c0a3e..1d7db07de 100644--- a/src/web/src/components/community/forum-view.tsx+++ b/src/web/src/components/community/forum-view.tsx@@ -1,116 +1,82 @@"use client"-import { useEffect, useState } from "react"-import { MessagesSquare, ListChevronsUpDown, Plus, Tags, X, Check } from "lucide-react"+import { useState } from "react"+import { MessagesSquare, ListChevronsUpDown, Plus, Tag } from "lucide-react"import { Button } from "@/components/ui/button"import { formatRelativeTime } from "./format-time"import { Badge } from "@/components/ui/badge"-import { onEnterSubmit } from "@/lib/ime"-import { Input } from "@/components/ui/input"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 { PostTagDialog } from "./post-tag-dialog"+import { tid } from "@/lib/community/testids"import type { ForumPost } from "./_types"+// Max member avatars shown in a post card's AvatarGroup before collapsing to a+// "+N" bubble. Creator is always first.+const MAX_AVATARS = 4+// Forum channel body — rendered under the shared ChannelHeader. A feed of posts;-// each post opens as a thread. The forum-specific actions (New post + Manage tags)-// live here in the filter bar, keeping the header identical to other channels.-// `tags` seeds the available tag chips ("All" + tag names); tags can be added/removed-// in manage mode.+// each post opens as a thread. The filter bar's tag chips are DERIVED from the+// posts themselves (the deduped union of every post's tags) — there is no+// forum-level tag vocabulary. Per-post tags are edited from a hover icon on each+// card (creator + server managers), not a forum-wide manage mode.export function ForumView({- posts, tags, loading, onOpenPost, onCreatePost, onTagsChanged, canManageTags,+ posts, loading, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,}: {posts: ForumPost[]- tags: string[]loading?: booleanonOpenPost: (id: string) => voidonCreatePost?: (post: NewForumPost) => void- onTagsChanged?: (tags: string[]) => void- canManageTags?: boolean+ // Save handler for a single post's tags. Absent → tag editing disabled.+ onEditPostTags?: (postId: string, tags: string[]) => void+ // Whether the current user may edit a given post's tags (creator or manager).+ canEditPostTags?: (post: ForumPost) => boolean+ // The post id whose tag save is in flight, if any.+ savingTagsFor?: string | null}) {const [tag, setTag] = useState("All")const [composing, setComposing] = useState(false)- const [managing, setManaging] = useState(false)- const [tagList, setTagList] = useState<string[]>(() => tags.filter((t) => t !== "All"))- useEffect(() => { setTagList(tags.filter((t) => t !== "All")) }, [tags])- const [newTag, setNewTag] = useState("")+ const [editingTagsFor, setEditingTagsFor] = useState<ForumPost | null>(null)- const addTag = () => {- const t = newTag.trim().toLowerCase()- if (!t || tagList.includes(t)) { setNewTag(""); return }- const next = [...tagList, t]- setTagList(next)- setNewTag("")- onTagsChanged?.(next)- }- const removeTag = (t: string) => {- const next = tagList.filter((x) => x !== t)- setTagList(next)- if (tag === t) setTag("All")- onTagsChanged?.(next)- }+ // 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))return (<>{composing && (<CreateForumPost- tags={tagList}onCancel={() => setComposing(false)}onPost={(post) => { onCreatePost?.(post); setComposing(false) }}/>)}- {/* filter bar — tag chips on the left, forum actions on the right.- Manage mode swaps the chips for delete/add-tag controls. */}+ {/* filter bar — derived tag chips on the left (hidden when there are no+ tags anywhere), New Post on the right. */}<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">- {!managing && (- <Badge variant={tag === "All" ? "default" : "secondary"} className="shrink-0 cursor-pointer" render={<button onClick={() => setTag("All")} />}>All</Badge>- )}- {tagList.map((t) => (- managing ? (- <Badge key={t} variant="secondary" className="shrink-0 gap-1">- #{t}- <button onClick={() => removeTag(t)} className="grid size-3.5 place-items-center rounded-full hover:bg-foreground/10" aria-label={`Delete tag ${t}`}><X className="size-3" /></button>- </Badge>- ) : (- <Badge- key={t}- variant={tag === t ? "default" : "secondary"}- className="shrink-0 cursor-pointer"- render={<button onClick={() => setTag(t)} />}- >- {`#${t}`}- </Badge>- )- ))}- {managing && (- <div className="flex items-center gap-1">- <Input- value={newTag}- onChange={(e) => setNewTag(e.target.value)}- onKeyDown={onEnterSubmit(addTag)}- placeholder="new-tag"- className="h-6 w-28 px-2 text-xs"- />- <button onClick={addTag} disabled={!newTag.trim()} className="grid size-6 place-items-center rounded-md bg-secondary text-muted-foreground hover:text-foreground disabled:opacity-40" aria-label="Add tag"><Check className="size-3.5" /></button>- </div>+ {allTags.length > 0 && (+ <>+ <Badge variant={tag === "All" ? "default" : "secondary"} className="shrink-0 cursor-pointer" render={<button onClick={() => setTag("All")} />}>All</Badge>+ {allTags.map((t) => (+ <Badge+ key={t}+ variant={tag === t ? "default" : "secondary"}+ className="shrink-0 cursor-pointer"+ data-testid={tid.forumTagChip(t)}+ render={<button onClick={() => setTag(t)} />}+ >+ {`#${t}`}+ </Badge>+ ))}+ </>)}</div><div className="flex shrink-0 items-center gap-1">- {canManageTags && (- <Button- variant="ghost"- size="icon-sm"- onClick={() => setManaging((v) => !v)}- aria-label="Manage tags"- className={`text-muted-foreground hover:text-foreground ${managing ? "bg-accent text-foreground" : ""}`}- >- <Tags className="size-4" />- </Button>- )}<Button size="sm" onClick={() => setComposing(true)}><Plus className="size-4" /> New Post</Button></div></div>@@ -122,33 +88,74 @@ export function ForumView({<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) => (- <button- key={p.id}- onClick={() => onOpenPost(p.id)}- className="flex 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} />- <span className="text-xs text-muted-foreground" suppressHydrationWarning>- <span className="font-medium text-foreground">{p.parent.authorName}</span> · {formatRelativeTime(p.lastMessageAt)}- </span>- </div>- <h3 className="text-[15px] font-semibold leading-tight">{p.name}</h3>- <p className="line-clamp-2 text-sm text-muted-foreground">{p.preview}</p>- <div className="flex items-center gap-2">- {p.tags.map((t) => (- <Badge key={t} variant="secondary">#{t}</Badge>- ))}- <span className="ml-auto flex items-center gap-1 text-xs text-muted-foreground">- <MessagesSquare className="size-3.5" /> {p.messageCount}- </span>+ {filtered.map((p) => {+ const canEdit = !!onEditPostTags && (canEditPostTags?.(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+ return (+ <div+ key={p.id}+ role="button"+ tabIndex={0}+ data-testid={tid.forumPostCard(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"+ >+ <div className="flex items-center gap-2">+ <Avatar label={p.authorAvatar} seed={p.authorId} size={24} />+ {others.length > 0 && (+ <AvatarGroup data-testid={tid.forumPostAvatars(p.id)}>+ {shown.map((m) => (+ <Avatar key={m.id} label={m.avatar} seed={m.id} size={24} ringColor="var(--card)" />+ ))}+ {overflow > 0 && <AvatarGroupCount className="size-6 text-[11px]">+{overflow}</AvatarGroupCount>}+ </AvatarGroup>+ )}+ <span className="text-xs text-muted-foreground" suppressHydrationWarning>+ <span className="font-medium text-foreground">{p.parent.authorName}</span> · {formatRelativeTime(p.lastMessageAt)}+ </span>+ {canEdit && (+ <button+ type="button"+ data-testid={tid.forumPostTagBtn(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"+ >+ <Tag className="size-4" />+ </button>+ )}+ </div>+ <h3 className="text-[15px] font-semibold leading-tight">{p.name}</h3>+ <p className="line-clamp-2 text-sm text-muted-foreground">{p.preview}</p>+ <div className="flex items-center gap-2">+ {p.tags.length > 0 && p.tags.map((t) => (+ <Badge key={t} variant="secondary">#{t}</Badge>+ ))}+ <span className="ml-auto flex items-center gap-1 text-xs text-muted-foreground">+ <MessagesSquare className="size-3.5" /> {p.messageCount}+ </span>+ </div></div>- </button>- ))}+ )+ })}</div>)}</main>++ {editingTagsFor && (+ <PostTagDialog+ open+ onOpenChange={(v) => { if (!v) setEditingTagsFor(null) }}+ postName={editingTagsFor.name}+ current={editingTagsFor.tags}+ allTags={allTags}+ saving={savingTagsFor === editingTagsFor.id}+ onSave={(tags) => { onEditPostTags?.(editingTagsFor.id, tags); setEditingTagsFor(null) }}+ />+ )}</>)}@@ -196,7 +203,6 @@ export function ForumViewSkeleton() {<Skeleton className="h-5 w-20 rounded-full" /></div><div className="flex shrink-0 items-center gap-1">- <Skeleton className="size-7 rounded-md" /><Skeleton className="h-8 w-25 rounded-md" /></div></div>diff --git a/src/web/src/components/community/post-tag-dialog.tsx b/src/web/src/components/community/post-tag-dialog.tsxnew file mode 100644index 000000000..fe5fa2df1--- /dev/null+++ b/src/web/src/components/community/post-tag-dialog.tsx@@ -0,0 +1,104 @@+"use client"++import { useState } from "react"+import { X } from "lucide-react"+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "@/components/ui/dialog"+import { Button } from "@/components/ui/button"+import { Badge } from "@/components/ui/badge"+import { Input } from "@/components/ui/input"+import { onEnterSubmit } from "@/lib/ime"+import { tid } from "@/lib/community/testids"++// Per-post tag editor. Opened from the tag icon on a post card. Shows the+// forum's existing tags (the deduped union across posts, passed as `allTags`)+// as toggle chips, plus a free-text input to add a brand-new tag. Saving PATCHes+// the post's tag list. There is no forum-level tag vocabulary anymore — a new+// tag simply exists on this post and joins the union once it lands.+export function PostTagDialog({+ open,+ onOpenChange,+ postName,+ current,+ allTags,+ onSave,+ saving,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ postName: string+ current: string[]+ allTags: string[]+ onSave: (tags: string[]) => void+ saving?: boolean+}) {+ const [selected, setSelected] = useState<string[]>(current)+ const [draft, setDraft] = useState("")++ const toggle = (t: string) =>+ setSelected((prev) => (prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]))++ const addDraft = () => {+ const t = draft.trim().toLowerCase()+ setDraft("")+ if (!t || selected.includes(t)) return+ setSelected((prev) => [...prev, t])+ }++ // The chip set is the union of the forum's known tags and anything selected+ // (so a freshly-typed tag shows as an active chip too), stable-sorted.+ const chips = [...new Set([...allTags, ...selected])].sort()++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-sm" data-testid={tid.forumTagDialog}>+ <DialogHeader>+ <DialogTitle>Edit tags</DialogTitle>+ <DialogDescription>Tag “{postName}” to help others find it.</DialogDescription>+ </DialogHeader>++ <div className="flex flex-wrap items-center gap-2">+ {chips.length === 0 ? (+ <p className="text-sm text-muted-foreground">No tags yet. Add the first one below.</p>+ ) : (+ chips.map((t) => (+ <Badge+ key={t}+ variant={selected.includes(t) ? "default" : "secondary"}+ className="cursor-pointer"+ render={<button type="button" onClick={() => toggle(t)} />}+ >+ {`#${t}`}+ {selected.includes(t) && <X className="ml-1 size-3" />}+ </Badge>+ ))+ )}+ </div>++ <div className="flex items-center gap-2">+ <Input+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={onEnterSubmit(addDraft)}+ placeholder="new-tag"+ className="h-9"+ />+ <Button type="button" variant="secondary" size="sm" onClick={addDraft} disabled={!draft.trim()}>+ Add+ </Button>+ </div>++ <DialogFooter>+ <Button variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>+ <Button data-testid={tid.forumTagDialogSave} onClick={() => onSave(selected)} disabled={saving}>Save tags</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.tsindex 7d497548e..cd94d7e8a 100644--- a/src/web/src/hooks/community/mutations/forum.ts+++ b/src/web/src/hooks/community/mutations/forum.ts@@ -10,19 +10,18 @@ export type CreateForumPostArgs = {channelId: stringname: stringcontent: string- tags: string[]}export type CreateForumPostResult = { post: ForumPost }export function useCreateForumPost() {const queryClient = useQueryClient()return useMutation<CreateForumPostResult, Error, CreateForumPostArgs>({- mutationFn: async ({ channelId, name, content, tags }) => {+ mutationFn: async ({ channelId, name, content }) => {return apiFetch<CreateForumPostResult>(`/api/community/channels/${channelId}/posts`,{method: "POST",- body: JSON.stringify({ name, content, tags }),+ body: JSON.stringify({ name, content }),},)},@@ -39,3 +38,44 @@ 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+ tags: string[]+}++/**+ * Edit a single forum post's tags. PATCHes the post channel (creator 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.+ */+export function useUpdatePostTags() {+ const queryClient = useQueryClient()+ return useMutation<{ tags: string[] }, Error, UpdatePostTagsArgs>({+ mutationFn: async ({ postId, 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) }),+ })+ 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,+ )+ },+ })+}diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex f746a4b74..79a4649e2 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -221,6 +221,19 @@ describe("createAuth session cookie cache", () => {const opts = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: AuthOptions }).__optionsexpect(opts.session?.cookieCache?.enabled).toBe(true)})++ // Prod caps the signed-cookie cache at 5min (a revoked session stops being+ // honored within that window — a real security property). Dev/test uses a+ // longer cache so the Playwright e2e-ui suite, which drives one session per+ // user for the whole >5min run, doesn't fall through to a per-request D1+ // findSession that flakes to 401 under late-run parallel load.+ it("caps the prod cookie cache at 5min but widens it in dev", async () => {+ const createAuth = await loadCreateAuth()+ const prod = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__options+ const dev = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: AuthOptions }).__options+ expect(prod.session?.cookieCache?.maxAge).toBe(5 * 60)+ expect(dev.session?.cookieCache?.maxAge).toBeGreaterThan(5 * 60)+ })})describe("createAuth user fields", () => {diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 6cb63866f..3a0e3ee0e 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -48,12 +48,21 @@ export function createAuth(env: Env) {// Fixes first-login 401 for newly-registered users: the just-written user row// may not yet be visible on a D1 read-replica, but the signed cookie carries// the session payload set by the sign-in handler itself.+ //+ // maxAge: in prod, 5min balances freshness (a revoked session stops being+ // honored within 5min) against D1 load. In dev/test it's 1h: the Playwright+ // e2e-ui suite mints one session per user at global-setup and drives it for+ // the whole run (>5min). Once the 5min cache lapsed, every seed request fell+ // through to a D1 `findSession`, which under the suite's late-run parallel+ // load returned null intermittently → a 401 cascade that flaked specs. A+ // longer dev cache keeps the signed-cookie fast path valid across the run.+ // Never widened in prod (revocation latency is a real security property).session: {expiresIn: 30 * 24 * 60 * 60,updateAge: 24 * 60 * 60,cookieCache: {enabled: true,- maxAge: 5 * 60,+ maxAge: isProd ? 5 * 60 : 60 * 60,},},emailAndPassword: {diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 1b7a25eef..1d4b55a34 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -13,7 +13,7 @@*/import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, createLogger, WS_EVENTS, isThread } from "@alook/shared"+import { queries, createLogger, WS_EVENTS, isThread, isForumPost } from "@alook/shared"import type { CommunityWsEvent, Database } from "@alook/shared"import { getDb } from "../db"import { broadcastToUser } from "../broadcast"@@ -43,18 +43,21 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s/*** Resolves the recipient set for a channel event.*- * - THREAD (`type="thread"`) → the thread's NOTIFY set (participants with- * `muted=0`). A thread is the notification dimension: message events reach- * only its participants, NOT the whole parent channel (and NOT admins, who- * are never auto-participants). Nested-membership model.- * - channel / post / forum → the access audience via the shared resolver- * (public/private split + post-own-roster / forum-union).+ * - 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.+ * - channel / forum → the access audience via the shared resolver+ * (public/private split + forum-union).** The split lives here so fan-out and bot-wake use the same recipient set.*/async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {const rows = await queries.communityChannel.getChannelType(db, channelId)- if (isThread(rows)) {+ if (isThread(rows) || isForumPost(rows)) {return queries.communityThread.listThreadParticipantUserIds(db, channelId)}return queries.communityMembersResolver.resolveScopeMemberUserIds(db, {diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex d40720e78..3231637f0 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -570,6 +570,41 @@ 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.+ 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" },+ body: { content: "first reply" },+ })++ expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "p1", [+ { userId: "author_1", source: "spoke" },+ ])+ expect(mockCreateChannelMember).not.toHaveBeenCalled()+ })++ it("forum_post: 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" },+ body: { content: "hey @Cara#0002" },+ })++ expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "p1", [+ { userId: "author_1", source: "spoke" },+ { userId: "cara_1", source: "mention" },+ ])+ })+it("public channel: mention of any server member is kept, no roster row", async () => {mockIsChannelPrivate.mockResolvedValue(false)mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob#0001" }))diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 5fb4146ec..194e611ff 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -25,6 +25,12 @@ export type MessageTarget =parentChannelId: stringserverId: string}+ | {+ kind: "forum_post"+ channelId: string+ parentChannelId: string+ serverId: string+ }| { kind: "dm"; dmId: string; otherUserId: string }export function isDmTarget<T extends { kind: string }>(target: T): target is Extract<T, { kind: "dm" }>@@ -45,6 +51,15 @@ 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.+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@@ -530,15 +545,16 @@ export async function createCommunityMessage(params: {// Mention beats reply — never double-count the same user.for (const id of mentionTargets) replyTargets.delete(id)- // Thread participation (notification dimension). A thread's NOTIFY set is its- // participant rows — join by:+ // Thread / forum_post participation (notification dimension). Both units'+ // NOTIFY set is their participant rows — join by:// - speaking: the author becomes a participant (source "spoke").- // - @mention: an explicitly mentioned/replied parent-channel member becomes- // a participant (source "mention"). `mentionTargets`/`replyTargets` are- // already scoped to the parent-channel audience by the block above.+ // - @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.- if (isThreadTarget(target) && !skipMentions) {+ // card messages (`skipMentions`) don't add the author. A forum post is+ // enrolled exactly like a thread so it notifies only its participants.+ if (hasParentChannel(target) && !skipMentions) {const rows: { userId: string; source: "spoke" | "mention" }[] = [{ userId: authorId, source: "spoke" },]@@ -654,7 +670,7 @@ export async function createCommunityMessage(params: {{ excludeUserId: fanoutExclude, wakeMessageRow },).catch(() => { })- if (isThreadTarget(target)) {+ if (hasParentChannel(target)) {const updated = await queries.communityChannel.getChannel(db,target.channelId,diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 735e64722..96fa1078e 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -16,6 +16,9 @@ export const tid = {inviteToken: "community-invite-token",inviteCopy: "community-invite-copy",+ forumTagDialog: "community-forum-tag-dialog",+ forumTagDialogSave: "community-forum-tag-dialog-save",+message: (id: string) => `community-message-${id}`,channelRow: (id: string) => `community-channel-row-${id}`,serverIcon: (id: string) => `community-server-icon-${id}`,@@ -25,4 +28,11 @@ export const tid = {reactionAdd: (msgId: string) => `community-reaction-add-${msgId}`,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; `forumPostAvatars`+ // 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}`,+ forumPostAvatars: (id: string) => `community-forum-post-avatars-${id}`,+ forumTagChip: (tag: string) => `community-forum-tag-chip-${tag}`,} as constdiff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.tsindex d2db4a4f7..ca2e33906 100644--- a/src/web/src/stores/community/ws.test.ts+++ b/src/web/src/stores/community/ws.test.ts@@ -72,6 +72,25 @@ describe("useCommunityWsStore", () => {expect(useCommunityWsStore.getState().onlineUserIds).toBe(before)})+ it("mergePresence unions instead of replacing — regression for the DM flicker", () => {+ // A WS snapshot marked co-member A online; the friends-only re-seed carries+ // only B. A destructive replace would evict A (the reported bug); merge must+ // keep both.+ useCommunityWsStore.getState().setPresence("A", true)+ useCommunityWsStore.getState().mergePresence(["B"])+ const online = useCommunityWsStore.getState().onlineUserIds+ expect(online.has("A")).toBe(true)+ expect(online.has("B")).toBe(true)+ expect(online.size).toBe(2)+ })++ it("mergePresence bails when every incoming id is already present", () => {+ useCommunityWsStore.getState().hydratePresence(["u1", "u2"])+ const before = useCommunityWsStore.getState().onlineUserIds+ useCommunityWsStore.getState().mergePresence(["u1"])+ expect(useCommunityWsStore.getState().onlineUserIds).toBe(before)+ })+it("markSeenMessage deduplicates", () => {useCommunityWsStore.getState().markSeenMessage("m1")const first = useCommunityWsStore.getState().seenMessageIdsdiff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex dcda2a96a..dcaa00564 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -74,8 +74,25 @@ export type CommunityWsStoreState = {botAuditEvents: Map<string, BotAuditEventEntry[]>setPresence: (userId: string, online: boolean) => void- /** Atomic bulk seed — one notification for N users. Use on server switch. */+ /**+ * Atomic bulk REPLACE — one notification for N users. Use on server switch,+ * where it must PRUNE: a peer who was online in the previous server but isn't+ * in the new server's snapshot has to drop to offline. The WS presence+ * snapshot only emits `online:true`, so this destructive replace is the only+ * thing that clears a stale-online peer on a switch.+ */hydratePresence: (userIds: readonly string[]) => void+ /**+ * Additive bulk MERGE — union `userIds` into the current set, one+ * notification. Use for a re-seed that carries only a SUBSET of the audience+ * (the friends-presence fetch), where a destructive replace would evict+ * WS-delivered co-members the fetch never knew about (the DM online→offline+ * flicker bug). Accepted trade-off: because it never prunes and the WS+ * snapshot is `online:true`-only, a peer who went offline while we were+ * disconnected stays "online" until the next live `online:false` delta — the+ * far rarer, less-jarring inverse of the flicker it fixes.+ */+ mergePresence: (userIds: readonly string[]) => voidresetPresence: () => voidhasSeenMessage: (id: string) => booleanmarkSeenMessage: (id: string) => void@@ -116,6 +133,15 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (set({ onlineUserIds: new Set(userIds) })},+ mergePresence: (userIds) => {+ const current = get().onlineUserIds+ // Fast-path: every incoming id already present → no write, no notification.+ if (userIds.every((id) => current.has(id))) return+ const next = new Set(current)+ for (const id of userIds) next.add(id)+ set({ onlineUserIds: next })+ },+resetPresence: () => {if (get().onlineUserIds.size === 0) returnset({ onlineUserIds: new Set() })diff --git a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.tsindex 6aa6ec705..f70417f9a 100644--- a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts+++ b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts@@ -1,6 +1,6 @@import { test, expect } from "./_fixtures/community-fixture"import { tid } from "./_fixtures/testids"-import { sendMessage, expectMessageVisible } from "./_fixtures/actions"+import { sendMessage, expectMessageVisible, composerEditable } from "./_fixtures/actions"import { seedServer, seedChannel, seedJoinServer } from "./_fixtures/seed"// Journey 3 — multi-user realtime. Alice and Bob are both online in the same@@ -39,10 +39,30 @@ test.describe.serial("multi-user realtime", () => {await bob.page.goto(`/c/channels/${serverId}/${channelId}`)await bob.page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })- await alice.page.getByTestId(tid.composerInput).click()- await alice.page.keyboard.type("typing…")- // Bob sees the floating typing pill.- await expect(bob.page.getByTestId(tid.typingIndicator)).toBeVisible({ timeout: 15_000 })+ // Gate on Bob's WS subscription being LIVE before testing the typing+ // indicator — otherwise Alice's one-shot `typing.start` can fire into the+ // gap before Bob's channel subscription is established and be missed+ // forever (the indicator self-clears after 8s and never re-fires). Prove+ // liveness with a real message round-trip: Alice sends, Bob receives it via+ // WS. Only then is Bob guaranteed subscribed.+ const ping = `ws-ready ${Date.now()}`+ await sendMessage(alice.page, ping)+ await expectMessageVisible(bob.page, ping)++ // `typing.start` is throttled to one emit per 3s per channel, so a single+ // keystroke that races the subscription is lost. Poll: re-type in short+ // bursts (clearing the throttle each burst is unnecessary — a fresh burst+ // after 3s re-emits) until Bob sees the pill, within the 8s self-clear.+ const aliceEditable = composerEditable(alice.page)+ await expect(async () => {+ await aliceEditable.click()+ // Clear any text a prior burst left so a stray Enter can't send noise and+ // the composer stays a clean typing surface.+ await alice.page.keyboard.press("ControlOrMeta+A")+ await alice.page.keyboard.press("Backspace")+ await alice.page.keyboard.type("typing…")+ await expect(bob.page.getByTestId(tid.typingIndicator)).toBeVisible({ timeout: 4_000 })+ }).toPass({ timeout: 20_000 })// Alice sends; her typing indicator clears on Bob's side (assert// presence→absence, not an exact duration).diff --git a/src/web/src/test/e2e-ui/13-mentions.spec.ts b/src/web/src/test/e2e-ui/13-mentions.spec.tsindex c3df6c3b6..7d2f9ab86 100644--- a/src/web/src/test/e2e-ui/13-mentions.spec.ts+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts@@ -59,8 +59,14 @@ test.describe.serial("mentions — mandatory discriminator", () => {await expect(editable.locator("[data-type='mention'], .mention-highlight").first()).toBeVisible({ timeout: 10_000 })await editable.pressSequentially(` ${marker}`)await page.keyboard.press("Enter")- // Confirm the message posted (and the composer cleared) before returning.+ // Confirm the message posted before returning.await expect(page.getByText(marker, { exact: false }).first()).toBeVisible({ timeout: 15_000 })+ // AND that the composer fully cleared — otherwise the NEXT mentionAndSend+ // types `@John` into a composer with residual state, the suggestion popup+ // doesn't open, and no second pill renders (the `.nth(1)` wait then hangs to+ // a 60s timeout). Asserting the empty composer here makes the second call+ // start from a settled surface.+ await expect(editable).toHaveText("", { timeout: 10_000 })}test("same-name mentions each resolve to the exact user on pill click (spaced name, no leaked #dddd)", async ({ asUser }) => {@@ -76,24 +82,38 @@ test.describe.serial("mentions — mandatory discriminator", () => {const carolMsg = page.getByText("msgCarol", { exact: false }).first()await expect(bobMsg).toBeVisible({ timeout: 15_000 })await expect(carolMsg).toBeVisible({ timeout: 15_000 })- const bobPill = page.locator("button", { hasText: "@John Doe" }).first()+ // Wait for BOTH pills to exist before touching either — a bare `.nth(1)`+ // click would otherwise hang to the 60s test timeout if the second pill+ // hasn't rendered yet (the observed flake).+ const pills = page.locator("button", { hasText: "@John Doe" })+ await expect(pills).toHaveCount(2, { timeout: 15_000 })+ const bobPill = pills.first()await expect(bobPill).toBeVisible()await expect(bobPill).not.toContainText("#")// Click Bob's pill → the profile card shows Bob's discriminator, not Carol's.- await bobPill.click()const card = page.getByTestId(tid.profileCard)- await expect(card).toBeVisible({ timeout: 15_000 })+ await expect(async () => {+ await bobPill.click({ timeout: 5_000 })+ await expect(card).toBeVisible({ timeout: 5_000 })+ }).toPass({ timeout: 30_000 })await expect(card).toContainText(`#${bob.discriminator}`)await expect(card).not.toContainText(`#${carol.discriminator}`)- // Dismiss and wait for the card (and its popover overlay) to fully detach- // before touching the second pill — clicking while the overlay animates out- // gets the click intercepted.- await page.keyboard.press("Escape")- await expect(card).toBeHidden({ timeout: 15_000 })- const carolPill = page.locator("button", { hasText: "@John Doe" }).nth(1)- await carolPill.click()- await expect(card).toBeVisible({ timeout: 15_000 })+ // Dismiss the first card, then open the second pill's. The popover renders+ // a portalled overlay that lingers during its exit animation and intercepts+ // pointer events; under full-run load `toBeHidden` on the card doesn't+ // guarantee the overlay has detached. Retry the whole dismiss→click so a+ // transient interception (or a stray still-open card) re-presses Escape and+ // tries again, instead of hanging the bare click to the 60s test timeout.+ const carolPill = pills.nth(1)+ await expect(async () => {+ if (await card.isVisible()) {+ await page.keyboard.press("Escape")+ await expect(card).toBeHidden({ timeout: 5_000 })+ }+ await carolPill.click({ timeout: 5_000 })+ await expect(card).toBeVisible({ timeout: 5_000 })+ }).toPass({ timeout: 30_000 })await expect(card).toContainText(`#${carol.discriminator}`)})@@ -119,14 +139,19 @@ test.describe.serial("mentions — mandatory discriminator", () => {test("@everyone renders with the distinct primary styling (its flag survives sanitize)", async ({ asUser }) => {const { page } = await asUser("alice")- await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })const marker = `everyoneMsg ${Date.now()}`// Seed via API (the composer's own @everyone popup path is covered by unit// tests) — this journey is specifically about how the sent pill renders.+ // Seed BEFORE navigating so the message is in the channel's initial fetch:+ // navigating first and relying on WS delivery races the page's channel+ // subscription (if the seed lands in the gap before subscribe, the message+ // never arrives without a reload — a real flake, not the pill logic).await seedMessage("alice", channelId, `@everyone ${marker}`)+ await page.goto(`/c/channels/${serverId}/${channelId}`)+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })+await expect(page.getByText(marker, { exact: false }).first()).toBeVisible({ timeout: 15_000 })const everyonePill = page.locator("span", { hasText: "@everyone" }).first()await expect(everyonePill).toBeVisible()diff --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.tsnew file mode 100644index 000000000..1e450cc97--- /dev/null+++ b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts@@ -0,0 +1,142 @@+import { test, expect, userId } from "./_fixtures/community-fixture"+import { tid } from "./_fixtures/testids"+import {+ seedServer,+ seedChannel,+ seedJoinServer,+ seedForumPost,+ seedMessage,+ seedDm,+ seedDmMessage,+} from "./_fixtures/seed"++// Journey 14 — forum-post notify scope, per-post tags, post-card participant+// avatars, and DM presence stability. Covers the batch that made forum posts+// notify only their participants (like threads), moved tag editing onto each+// post card, showed participant AvatarGroups, and fixed the DM presence flicker+// on refresh. See plans/community-machine-fixes-2026-07.md.++test.describe.serial("forum post tags + participant avatars", () => {+ let serverId: string+ let forumId: string+ let postId: string++ test.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")+ })++ test("creator edits a post's tags from the card; the filter bar derives the union", async ({ asUser }) => {+ const { page } = await asUser("alice")+ 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))+ await expect(card).toBeVisible({ timeout: 20_000 })++ // No tags yet → no filter-bar chip for the post's future tags.+ await expect(page.getByTestId(tid.forumTagChip("alpha"))).toHaveCount(0)++ // Hover reveals the tag-edit icon; open the dialog and add two tags.+ await card.hover()+ await page.getByTestId(tid.forumPostTagBtn(postId)).click()+ await expect(page.getByTestId(tid.forumTagDialog)).toBeVisible({ timeout: 10_000 })+ for (const t of ["alpha", "beta"]) {+ await page.getByPlaceholder("new-tag").fill(t)+ await page.getByRole("button", { name: "Add", exact: true }).click()+ }+ await page.getByTestId(tid.forumTagDialogSave).click()++ // The card now shows the tags AND the filter bar derives them as the union.+ await expect(page.getByTestId(tid.forumTagChip("alpha"))).toBeVisible({ timeout: 15_000 })+ await expect(page.getByTestId(tid.forumTagChip("beta"))).toBeVisible()++ // Remove one tag → the filter bar's union drops it.+ await card.hover()+ await page.getByTestId(tid.forumPostTagBtn(postId)).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.+ await page.getByTestId(tid.forumTagDialog).getByRole("button", { name: "#beta" }).click()+ await page.getByTestId(tid.forumTagDialogSave).click()++ await expect(page.getByTestId(tid.forumTagChip("beta"))).toHaveCount(0, { timeout: 15_000 })+ await expect(page.getByTestId(tid.forumTagChip("alpha"))).toBeVisible()+ })++ test("a non-creator non-manager sees no tag-edit icon on the post", async ({ asUser }) => {+ const { page } = await asUser("bob")+ 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))+ 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)+ })++ test("post card shows a participant AvatarGroup once a second person joins", async ({ asUser }) => {+ // Bob sends a message into the post → enrolled as a participant (source+ // 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()}`)++ // 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 })+ })+})++// DM presence stability: a co-member-but-not-friend peer who is online must+// stay online after the other side refreshes — the friends-presence re-seed+// used to destructively replace the online set and evict them (online→offline+// flicker). Alice and Bob share a server (co-members) but are not friends.+test.describe.serial("DM presence stability on refresh", () => {+ let serverId: string+ let dmId: string++ test.beforeAll(async () => {+ // Server + join makes Alice and Bob co-members (they are NOT friends —+ // that's the exact shape that reproduced the flicker). The server's default+ // channel is enough; no extra channel needed.+ serverId = await seedServer("alice", `Presence ${Date.now()}`)+ await seedJoinServer("alice", "bob", serverId)+ dmId = await seedDm("alice", userId("bob"))+ // A message so the DM row is populated in Bob's sidebar.+ await seedDmMessage("alice", dmId, "hi")+ })++ test("peer stays online after the viewer refreshes the DM view", async ({ asUser }) => {+ // Alice stays connected (her page holds a live WS connection → she's online).+ const alice = await asUser("alice")+ await alice.page.goto("/c/me")+ await alice.page.waitForURL(/\/c\/me/, { timeout: 20_000, waitUntil: "commit" })++ const bob = await asUser("bob")+ await bob.page.goto(`/c/me/${dmId}`)+ await bob.page.waitForURL(new RegExp(dmId), { timeout: 20_000, waitUntil: "commit" })++ const aliceDot = bob.page.getByTestId(tid.dmRow(dmId)).locator("[data-slot='avatar-badge']")+ // Alice shows online first (WS snapshot).+ await expect(aliceDot).toHaveAttribute("data-presence", "online", { timeout: 20_000 })++ // Refresh — the friends-presence fetch resolves ~1s later. With the merge+ // fix Alice must NOT flip to offline. Assert the dot stays online across a+ // window that comfortably covers the fetch round-trip.+ await bob.page.reload({ waitUntil: "commit" })+ await expect(aliceDot).toHaveAttribute("data-presence", "online", { timeout: 20_000 })+ // Hold the assertion for ~3s so a late destructive re-seed would be caught.+ for (let i = 0; i < 3; i++) {+ await bob.page.waitForTimeout(1000)+ await expect(aliceDot).toHaveAttribute("data-presence", "online")+ }+ })+})diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex 3aa9f9a26..a06430c72 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -84,6 +84,14 @@ export async function seedDm(from: UserKey, targetUserId: string): Promise<strinreturn data.conversation.id}+// 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 data = (await res.json()) as { message: { id: string } }+ return data.message.id+}+export async function seedBlock(blocker: UserKey, targetUserId: string): Promise<void> {await post(blocker, `/api/community/users/${targetUserId}/block`)}@@ -134,6 +142,20 @@ export async function seedMessage(author: UserKey, channelId: string, content: sreturn data.message.id}+// 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(+ 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+}+export async function createInvite(owner: UserKey, serverId: string): Promise<string> {const res = await post(owner, `/api/community/servers/${serverId}/invites`, {})const data = (await res.json()) as { invite: { token: string } }