Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): reconcile forum opener titles

Gener31f1cf90dd72
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index e4e401044..cc3b1f5b8 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -78,16 +78,27 @@ export type CommunityMessageUpdated = {
approval: FriendApprovalPayload
}
-export type CommunityMessageEdited = {
+type CommunityMessageEditedBase = {
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 CommunityMessageEdited = CommunityMessageEditedBase & (
+ | {
+ // Forum opener address: the edited message lives in the parent forum,
+ // while channelId names the child post whose title must reconcile.
+ parentChannelId: string
+ serverId: string
+ }
+ | {
+ parentChannelId?: never
+ // Ordinary server edits may carry their server identity. DM edits omit it.
+ serverId?: string
+ }
+)
+
export type CommunityReactionAdd = {
type: "community:reaction.add"
channelId: string
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index 6e1445038..4199f79a6 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -297,6 +297,79 @@ export async function listUnreadForumOpeners(
}));
}
+/**
+ * Resolve canonical forum opener metadata for an already-authorized set of
+ * unread child channels. The caller owns visibility, participation, and mute
+ * filtering; this query only validates the child → forum → opener structure.
+ */
+export async function listForumOpenersByChildIds(
+ db: Database,
+ childIds: string[]
+): Promise<UnreadForumOpenerRow[]> {
+ if (childIds.length === 0) return [];
+
+ const childChannel = aliasedTable(communityChannel, "forum_inbox_child_lookup");
+ const parentForum = aliasedTable(communityChannel, "forum_inbox_parent_lookup");
+ const rows = (
+ await Promise.all(
+ chunk(childIds, D1_MAX_IN_PARAMS).map((ids) =>
+ db
+ .select({
+ forumChannelId: parentForum.id,
+ openerMessageId: communityMessage.id,
+ openerContent: communityMessage.content,
+ openerSeq: communityMessage.seq,
+ childChannelId: childChannel.id,
+ childName: childChannel.name,
+ createdAt: communityMessage.createdAt,
+ })
+ .from(childChannel)
+ .innerJoin(
+ parentForum,
+ and(
+ eq(parentForum.id, childChannel.parentChannelId),
+ eq(parentForum.type, "forum")
+ )
+ )
+ .innerJoin(
+ communityMessage,
+ and(
+ eq(communityMessage.id, childChannel.parentMessageId),
+ eq(communityMessage.channelId, parentForum.id)
+ )
+ )
+ .where(
+ and(
+ inArray(childChannel.id, ids),
+ eq(childChannel.type, "thread"),
+ eq(childChannel.archived, 0),
+ eq(parentForum.archived, 0)
+ )
+ )
+ )
+ )
+ ).flat();
+
+ 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,
+ 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/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index 18615ad86..f2cca5e8e 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -1,11 +1,23 @@
import { describe, it, expect } from "vitest";
import { isCommunityEvent, WS_EVENTS } from "../src/community-ws-events";
import type {
+ CommunityMessageEdited,
CommunityMachineCreated,
CommunityMachineUpdated,
CommunityMachineSummary,
} from "../src/community-ws-events";
+describe("CommunityMessageEdited address contract", () => {
+ it("supports forum opener, ordinary server, and DM edits", () => {
+ const events: CommunityMessageEdited[] = [
+ { type: "community:message.edited", channelId: "post", parentChannelId: "forum", serverId: "server", messageId: "opener", content: "new" },
+ { type: "community:message.edited", channelId: "text", serverId: "server", messageId: "message", content: "new" },
+ { type: "community:message.edited", channelId: "dm", messageId: "message", content: "new" },
+ ];
+ expect(events).toHaveLength(3);
+ });
+});
+
describe("isCommunityEvent", () => {
it("accepts every exact event declared by WS_EVENTS", () => {
expect(Object.values(WS_EVENTS)).toHaveLength(41);
diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.ts
index 5b2700e8e..6b2a17e61 100644
--- a/src/shared/test/queries/community-inbox.test.ts
+++ b/src/shared/test/queries/community-inbox.test.ts
@@ -29,6 +29,10 @@ describe("community/inbox exports", () => {
it("exports listUnreadForumOpeners", () => {
expect(typeof inboxQueries.listUnreadForumOpeners).toBe("function");
});
+
+ it("exports listForumOpenersByChildIds", () => {
+ expect(typeof inboxQueries.listForumOpenersByChildIds).toBe("function");
+ });
});
describe("isChannelUnread — two-branch predicate (seq)", () => {
@@ -299,6 +303,60 @@ describe("listUnreadForumOpeners — scoped forum projection", () => {
});
});
+describe("listForumOpenersByChildIds — structurally validated child projection", () => {
+ function createChildOpenerMock(responseSets: any[][]) {
+ let call = 0;
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.innerJoin = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(responseSets[call++] ?? []));
+ return chain;
+ }
+
+ const raw = (overrides: Record<string, unknown> = {}) => ({
+ forumChannelId: "forum_1",
+ openerMessageId: "opener_1",
+ openerContent: "Canonical title",
+ openerSeq: 7,
+ childChannelId: "post_1",
+ childName: "derived",
+ createdAt: "2026-07-07T10:00:00.000Z",
+ ...overrides,
+ });
+
+ it("does not query for an empty authorized child scope", async () => {
+ const db = createChildOpenerMock([]);
+ await expect(inboxQueries.listForumOpenersByChildIds(db, [])).resolves.toEqual([]);
+ expect(db.select).not.toHaveBeenCalled();
+ });
+
+ it("returns full canonical content and falls back only for blank content", async () => {
+ const db = createChildOpenerMock([[
+ raw(),
+ raw({ openerMessageId: "blank", childChannelId: "post_2", openerContent: " ", childName: "Fallback" }),
+ ]]);
+ const rows = await inboxQueries.listForumOpenersByChildIds(db, ["post_1", "post_2"]);
+ expect(rows.map((row) => [row.childChannelId, row.title])).toEqual([
+ ["post_1", "Canonical title"],
+ ["post_2", "Fallback"],
+ ]);
+ expect(db.innerJoin).toHaveBeenCalledTimes(2);
+ });
+
+ it("chunks the bounded child id set and globally sorts results", async () => {
+ const db = createChildOpenerMock([[
+ raw({ openerMessageId: "older", childChannelId: "post_old", createdAt: "2026-07-07T09:00:00.000Z" }),
+ ], [
+ raw({ openerMessageId: "newer", childChannelId: "post_new", createdAt: "2026-07-07T11:00:00.000Z" }),
+ ]]);
+ const ids = Array.from({ length: 91 }, (_, index) => `post_${index}`);
+ const rows = await inboxQueries.listForumOpenersByChildIds(db, ids);
+ expect(db.select).toHaveBeenCalledTimes(2);
+ expect(rows.map((row) => row.openerMessageId)).toEqual(["newer", "older"]);
+ });
+});
+
describe("isDmUnread — predicate (seq)", () => {
it("no lastMessageAt → false (empty conversation)", () => {
expect(isDmUnread({ lastMessageAt: null, hasReadState: false, hasUnreadBeyondSeq: false })).toBe(false);
diff --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.ts
index b405d2539..3255f7cbb 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
@@ -137,6 +137,9 @@ describe("GET /api/community/channels/[id]/threads", () => {
expect(res.status).toBe(200)
const body = await res.json() as { threads: Array<{ id: string; parentMessageId: string | null }> }
+ expect((body as typeof body & { parentType: string }).parentType).toBe("forum")
+ expect((body as typeof body & { serverId: string }).serverId).toBe("s1")
+
expect(body.threads).toEqual([
{ 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" },
@@ -191,6 +194,8 @@ describe("GET /api/community/channels/[id]/threads", () => {
const body = await res.json()
expect(body.threads.map((thread: { id: string }) => thread.id)).toEqual(["t3", "t2"])
expect(body).toMatchObject({
+ parentType: "forum",
+ serverId: "s1",
hasMore: true,
included: {
parentMessages: [{ id: "m3" }, { id: "m2" }],
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.ts
index 885fab6b6..d584d4e85 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
@@ -85,6 +85,8 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
])
return writeJSON({
+ serverId: access.value.channel.serverId,
+ parentType: access.value.channel.type,
threads,
included: { parentMessages, firstMessages, tags, participants },
hasMore,
@@ -106,5 +108,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
// 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 })
+ return writeJSON({
+ serverId: access.value.channel.serverId,
+ parentType: access.value.channel.type,
+ threads: childChannels,
+ })
})
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.ts
index 409cd2144..e910a6ba8 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
@@ -10,6 +10,7 @@ const mockUpdateOwnMessageContent = vi.fn()
const mockGetMessagesByIdsInScope = vi.fn()
const mockGetChannelForMember = vi.fn()
const mockGetChannelType = vi.fn()
+const mockGetChannel = vi.fn()
const mockGetThreadChannelByParentMessage = vi.fn()
const mockGetDM = vi.fn()
const mockGetDMPeer = vi.fn()
@@ -38,6 +39,7 @@ vi.mock("@alook/shared", async () => {
communityChannel: {
getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
getChannelType: (...a: unknown[]) => mockGetChannelType(...a),
+ getChannel: (...a: unknown[]) => mockGetChannel(...a),
getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),
},
communityMessage: {
@@ -101,6 +103,7 @@ describe("GET /api/community/messages/[id]", () => {
mockGetMessagesByIdsInScope.mockResolvedValue([])
// Default: a normal (non-DM) channel → server-scoped member gate.
mockGetChannelType.mockResolvedValue("text")
+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" })
})
it("returns the hydrated payload for a channel message when caller is a server member", async () => {
@@ -384,7 +387,7 @@ describe("PATCH /api/community/messages/[id]", () => {
messageId: "m1", authorId: "u1", content: "new",
})
expect(mockFanOutToChannel).toHaveBeenCalledWith("c1", {
- type: "community:message.edited", channelId: "c1", messageId: "m1", content: "new",
+ type: "community:message.edited", channelId: "c1", messageId: "m1", content: "new", serverId: "s1",
})
})
@@ -398,16 +401,23 @@ describe("PATCH /api/community/messages/[id]", () => {
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")
+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" })
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
- mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "post_1", type: "thread", parentChannelId: "c1", parentMessageId: "m1" })
+ mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "post_1", serverId: "s1", 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" }))
+ expect(mockFanOutToChannel).toHaveBeenCalledWith("c1", {
+ type: "community:message.edited",
+ channelId: "post_1",
+ parentChannelId: "c1",
+ serverId: "s1",
+ messageId: "m1",
+ content: "new",
+ })
mockFanOutToChannel.mockClear()
- mockGetChannelType.mockResolvedValue("thread")
+ mockGetChannel.mockResolvedValue({ id: "post_1", serverId: "s1", type: "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" })
@@ -418,6 +428,24 @@ describe("PATCH /api/community/messages/[id]", () => {
{ params: { id: "reply_1" } } as any,
)
expect(mockFanOutToChannel.mock.calls[0]?.[1]).not.toHaveProperty("parentChannelId")
+ expect(mockFanOutToChannel.mock.calls[0]?.[1]).toMatchObject({ serverId: "s1" })
+ })
+
+ it("keeps DM edit events free of server identity", async () => {
+ mockGetChannel.mockResolvedValue({ id: "dm_1", serverId: "dm-server", type: "dm" })
+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "dm_1", authorId: "u1", content: "old" })
+ mockUpdateOwnMessageContent.mockResolvedValue({ id: "m1", channelId: "dm_1", content: "new" })
+ mockGetDM.mockResolvedValue({ id: "dm_1", channelId: "dm_1" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })
+
+ const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)
+ expect(res.status).toBe(200)
+ expect(mockFanOutToChannel).toHaveBeenCalledWith("dm_1", {
+ type: "community:message.edited",
+ channelId: "dm_1",
+ messageId: "m1",
+ content: "new",
+ })
})
it("rejects bot credentials and empty content", async () => {
diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.ts
index 36a2c9ef8..55a2000ba 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -74,7 +74,8 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
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 channel = await queries.communityChannel.getChannel(db, message.channelId)
+ const channelType = channel?.type ?? null
const access = channelType === "dm"
? await requireDMAccess(db, message.channelId, ctx.actor.userId)
: await requireChannelMember(db, message.channelId, ctx.actor.userId)
@@ -93,13 +94,17 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
const openerThread = channelType === "forum"
? await queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId, messageId)
: null
- const parentChannelId = openerThread?.type === "thread" ? message.channelId : undefined
+ const isForumOpener = openerThread?.type === "thread"
await fanOutToChannel(message.channelId, {
type: WS_EVENTS.MESSAGE_EDITED,
- channelId: message.channelId,
+ channelId: isForumOpener ? openerThread.id : message.channelId,
messageId,
content,
- ...(parentChannelId ? { parentChannelId } : {}),
+ ...(isForumOpener
+ ? { parentChannelId: message.channelId, serverId: openerThread.serverId }
+ : channelType !== "dm" && channel?.serverId
+ ? { serverId: channel.serverId }
+ : {}),
})
return writeJSON({ message: updated })
})
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
index fface1bb4..398999490 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
@@ -3,6 +3,7 @@ import { NextRequest } from "next/server"
const mockListUnreadChannels = vi.fn()
const mockListUnreadForumOpeners = vi.fn()
+const mockListForumOpenersByChildIds = vi.fn()
const mockGetSettings = vi.fn()
const mockListUnreadMentions = vi.fn()
const mockListUnreadDms = vi.fn()
@@ -23,6 +24,7 @@ vi.mock("@alook/shared", async () => {
communityInbox: {
listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),
listUnreadForumOpeners: (...args: unknown[]) => mockListUnreadForumOpeners(...args),
+ listForumOpenersByChildIds: (...args: unknown[]) => mockListForumOpenersByChildIds(...args),
listUnreadDms: (...args: unknown[]) => mockListUnreadDms(...args),
},
communityNotificationSetting: {
@@ -96,6 +98,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {
mockListUnreadMentions.mockResolvedValue([])
mockListUnreadDms.mockResolvedValue([])
mockListUnreadForumOpeners.mockResolvedValue([])
+ mockListForumOpenersByChildIds.mockResolvedValue([])
mockListVisibleChannelIds.mockResolvedValue([])
mockGetChannelsByIds.mockResolvedValue([])
})
@@ -407,6 +410,52 @@ describe("GET /api/community/users/me/inbox/unreads", () => {
})
})
+ it("uses canonical opener metadata when only a child reply is unread", async () => {
+ mockListUnreadChannels.mockResolvedValue([
+ row({
+ channelId: "post_1",
+ channelName: "stale derived title",
+ type: "thread",
+ parentChannelId: "forum_1",
+ lastMessageAt: "2026-06-25T12:00:00Z",
+ }),
+ ])
+ mockGetChannelsByIds.mockResolvedValue([
+ { id: "forum_1", name: "Forum", type: "forum", serverId: "s1" },
+ ])
+ mockListForumOpenersByChildIds.mockResolvedValue([
+ opener({ forumChannelId: "forum_1", childChannelId: "post_1", title: "Full canonical opener" }),
+ ])
+
+ const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))
+ const body = await res.json()
+
+ expect(mockListForumOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), ["post_1"])
+ expect(body.servers[0].channels[0].children).toEqual([
+ expect.objectContaining({
+ channelId: "post_1",
+ channelName: "Full canonical opener",
+ openerMessageId: "m1",
+ }),
+ ])
+ })
+
+ it("prefilters muted server, parent, and child ids before canonical child lookup", async () => {
+ mockListUnreadChannels.mockResolvedValue([
+ row({ channelId: "post_server", serverId: "muted_server", parentChannelId: "forum_a", type: "thread" }),
+ row({ channelId: "post_parent", parentChannelId: "forum_muted", type: "thread" }),
+ row({ channelId: "post_child", parentChannelId: "forum_ok", type: "thread" }),
+ row({ channelId: "post_ok", parentChannelId: "forum_ok", type: "thread" }),
+ ])
+ mockGetSettings.mockResolvedValue([
+ { serverId: "muted_server", channelId: null, level: "nothing" },
+ { serverId: "s1", channelId: "forum_muted", level: "nothing" },
+ { serverId: "s1", channelId: "post_child", level: "nothing" },
+ ])
+ await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))
+ expect(mockListForumOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), ["post_ok"])
+ })
+
it("drops opener rows whose child channel is individually muted", async () => {
mockListUnreadChannels.mockResolvedValue([
row({ channelId: "f1", channelName: "Forum", type: "forum" }),
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
index 9fdaf5711..735f22528 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
@@ -71,11 +71,24 @@ export const GET = withAuth(async (req, ctx) => {
)
.map((row) => row.channelId),
)]
- const forumOpeners = await queries.communityInbox.listUnreadForumOpeners(
- db,
- ctx.userId,
- forumParentIds,
- )
+ const unreadForumChildIds = [...new Set(
+ unread
+ .filter(
+ (row) =>
+ !!row.parentChannelId &&
+ !mutedServers.has(row.serverId) &&
+ !mutedChannels.has(row.parentChannelId) &&
+ !mutedChannels.has(row.channelId),
+ )
+ .map((row) => row.channelId),
+ )]
+ const [directForumOpeners, childForumOpeners] = await Promise.all([
+ queries.communityInbox.listUnreadForumOpeners(db, ctx.userId, forumParentIds),
+ queries.communityInbox.listForumOpenersByChildIds(db, unreadForumChildIds),
+ ])
+ const forumOpeners = [...new Map(
+ [...directForumOpeners, ...childForumOpeners].map((row) => [row.childChannelId, row]),
+ ).values()]
return { unread, settings, mentions, unreadDms, forumOpeners }
},
{ unread: [], settings: [], mentions: [], unreadDms: [], forumOpeners: [] },
@@ -123,6 +136,7 @@ export const GET = withAuth(async (req, ctx) => {
const parents = new Map<string, ParentNode>()
const childrenByParent = new Map<string, Map<string, UnreadChild>>()
+ const unreadByChannelId = new Map(unread.map((row) => [row.channelId, row]))
for (const row of unread) {
if (!row.serverId || !row.channelId || !row.serverName || !row.channelName) continue
@@ -167,7 +181,10 @@ export const GET = withAuth(async (req, ctx) => {
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 unreadChild = unreadByChannelId.get(opener.childChannelId)
+ if (!parent && unreadChild?.parentChannelId !== opener.forumChannelId) continue
+ const serverId = parent?.serverId ?? unreadChild?.serverId
+ if (!serverId || mutedServers.has(serverId) || mutedChannels.has(opener.forumChannelId)) continue
const children = childrenByParent.get(opener.forumChannelId) ?? new Map<string, UnreadChild>()
const existing = children.get(opener.childChannelId)
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 311764b2e..326ef7048 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -167,6 +167,9 @@ export type Thread = {
// parent message (omitted only for legacy rootless threads).
// Used by `channel-ref-pill.tsx` to match a `/server/channel/#N` ref.
parentSeq?: number
+ // Stable opener identity used to reconcile forum-title edits without
+ // accidentally patching a same-named or re-rooted child.
+ openerMessageId?: string
}
export type ForumThread = Thread & {
diff --git a/src/web/src/components/community/channel-ref-pill.tsx b/src/web/src/components/community/channel-ref-pill.tsx
index cf0258670..1695a3524 100644
--- a/src/web/src/components/community/channel-ref-pill.tsx
+++ b/src/web/src/components/community/channel-ref-pill.tsx
@@ -7,6 +7,7 @@ import { resolveChannelRefBase, type ResolvedChannelRef } from "@/lib/community/
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import { useThreads } from "@/hooks/community/use-channel-panels"
import { useCommunityStore, useUiHandlers } from "@/stores/community"
+import { tid } from "@/lib/community/testids"
export type ChannelRefPillView =
| { kind: "plain"; text: string }
@@ -175,7 +176,12 @@ export function ChannelRefPill({ children }: { children?: React.ReactNode }) {
return (
<>
- <ChannelPill serverPrefix={view.serverPrefix} onClick={onClick} seqSuffix={view.messageSuffix}>
+ <ChannelPill
+ serverPrefix={view.serverPrefix}
+ onClick={onClick}
+ seqSuffix={view.messageSuffix}
+ testId={tid.channelRefPill(view.href.channelId)}
+ >
{view.label}
</ChannelPill>
{/* The `/#N` thread-root suffix stays a detached plain span — it names the
diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsx
index bf52c1ded..544399d19 100644
--- a/src/web/src/components/community/community-inbox-popover.tsx
+++ b/src/web/src/components/community/community-inbox-popover.tsx
@@ -9,6 +9,7 @@ import { ChannelIcon } from "./channel-icon"
import { EmptyState } from "./empty-state"
import { formatRelativeTime } from "./format-time"
import type { Marked, Mention, UnreadDm, UnreadServer } from "./_types"
+import { tid } from "@/lib/community/testids"
function MentionBadge({ count }: { count: number }) {
if (count <= 0) return null
@@ -66,6 +67,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, o
{c.children.map((child) => (
<button
key={child.channelId}
+ data-testid={tid.inboxUnreadChild(child.channelId)}
onClick={() => {
if (child.openerMessageId) {
onOpenForumThread(s.serverId, c.channelId, child.channelId, child.openerMessageId)
diff --git a/src/web/src/components/community/inline-marks.tsx b/src/web/src/components/community/inline-marks.tsx
index 82446c1bf..774191a75 100644
--- a/src/web/src/components/community/inline-marks.tsx
+++ b/src/web/src/components/community/inline-marks.tsx
@@ -65,11 +65,13 @@ export function ChannelPill({
serverPrefix,
muted,
seqSuffix,
+ testId,
}: {
children?: React.ReactNode
onClick?: (e: React.MouseEvent) => void
serverPrefix?: string
muted?: boolean
+ testId?: string
// A message ref (`/server/channel#N`): render the whole thing as ONE pill —
// channel name + `#N` inside — with a leading `#` glyph (instead of the `/`
// channel glyph) so it reads as "a message in general", one clickable unit.
@@ -99,12 +101,12 @@ export function ChannelPill({
)
if (onClick) {
return (
- <button type="button" onClick={onClick} title={title} className={className}>
+ <button type="button" onClick={onClick} title={title} className={className} data-testid={testId}>
{content}
</button>
)
}
- return <span title={title} className={className}>{content}</span>
+ return <span title={title} className={className} data-testid={testId}>{content}</span>
}
// Server-ref pill — same icon/shape/on-off pattern as `ChannelPill` (reuses
diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.ts
index d23e7cc90..3575951ca 100644
--- a/src/web/src/hooks/community/community-ws/message-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts
@@ -667,28 +667,37 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>
const opener: CommunityMessageEdited = {
type: "community:message.edited",
channelId: "post_1",
- messageId: "opener_1",
+ messageId: "opener-post_1",
content: "new title",
parentChannelId: "forum_1",
+ serverId: "s1",
}
- capturedQueryClient.setQueryData(communityKeys.message("opener_1"), {
- id: "opener_1",
+ capturedQueryClient.setQueryData(communityKeys.message("opener-post_1"), {
+ id: "opener-post_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] }
+ const forumPage = { pages: [{ messages: [{ id: "opener-post_1", content: "old title" }] }], pageParams: [null] }
capturedQueryClient.setQueryData(allKey, forumPage)
capturedQueryClient.setQueryData(bugKey, forumPage)
const sidebarKey = communityKeys.forumSidebarThreads("s1")
capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
+ capturedQueryClient.setQueryData(communityKeys.threads("forum_1"), {
+ parentType: "forum",
+ serverId: "s1",
+ parentChannelId: "forum_1",
+ threads: [{ id: "post_1", name: "old title", openerMessageId: "opener-post_1" }],
+ })
capturedOnMessage!(opener)
- expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMessages("forum_1") })
- expect(capturedQueryClient.getQueryState(allKey)?.isInvalidated).toBe(true)
- expect(capturedQueryClient.getQueryState(bugKey)?.isInvalidated).toBe(true)
+ await vi.waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({
+ queryKey: communityKeys.threads("forum_1"), exact: true,
+ }))
+ expect(capturedQueryClient.getQueryState(allKey)?.isInvalidated).toBe(false)
+ expect(capturedQueryClient.getQueryState(bugKey)?.isInvalidated).toBe(false)
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")
+ expect(capturedQueryClient.getQueryData<{ content: string }>(communityKeys.message("opener-post_1"))?.content).toBe("new title")
expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].title)
.toBe("new title")
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index fbbfbb29d..ca4891e68 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -18,8 +18,8 @@ import {
isForumSidebarParent,
invalidateForumSidebarBaseExact,
patchForumSidebarActivityExact,
- patchForumSidebarTitleExact,
} from "@/hooks/community/use-forum-sidebar-threads"
+import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"
import {
applyReactionToCache,
applyReactionToMessage,
@@ -255,6 +255,16 @@ export function handleMessageEdited(
event: CommunityMessageEdited,
{ queryClient }: MessageEventContext,
) {
+ if (event.parentChannelId) {
+ void reconcileForumOpenerTitle(queryClient, {
+ serverId: event.serverId,
+ forumChannelId: event.parentChannelId,
+ childChannelId: event.channelId,
+ openerMessageId: event.messageId,
+ content: event.content,
+ })
+ return
+ }
queryClient.setQueryData<{ content: string }>(
communityKeys.message(event.messageId),
(message) => message ? { ...message, content: event.content } : message,
@@ -276,17 +286,4 @@ export function handleMessageEdited(
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),
- })
- const serverId = useCommunityStore.getState().currentServerId
- if (serverId && isForumSidebarParent(queryClient, serverId, event.parentChannelId)) {
- patchForumSidebarTitleExact(queryClient, serverId, event.channelId, event.content)
- }
- }
}
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
new file mode 100644
index 000000000..32bf3746d
--- /dev/null
+++ b/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
@@ -0,0 +1,148 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { reconcileForumOpenerTitle } from "./forum-opener-title-reconciliation"
+
+const identity = {
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ childChannelId: "post_1",
+ openerMessageId: "opener_1",
+ content: "Full new title",
+}
+
+let queryClient: QueryClient
+
+beforeEach(() => {
+ queryClient = new QueryClient()
+})
+
+function seedCanonicalCaches() {
+ queryClient.setQueryData(communityKeys.message("opener_1"), {
+ id: "opener_1", type: "chat", content: "Old title",
+ })
+ const messagePage = {
+ pages: [{ messages: [{ id: "opener_1", type: "chat", content: "Old title" }], hasMore: false }],
+ pageParams: [null],
+ }
+ queryClient.setQueryData(communityKeys.channelMessages("forum_1"), messagePage)
+ queryClient.setQueryData(communityKeys.channelMessages("post_1"), messagePage)
+ queryClient.setQueryData(communityKeys.inboxUnreads(), {
+ servers: [{
+ serverId: "server_1",
+ serverName: "Server",
+ channels: [{
+ channelId: "forum_1",
+ channelName: "Forum",
+ lastMessageAt: "now",
+ mentionCount: 0,
+ children: [{
+ channelId: "post_1",
+ channelName: "Old title",
+ lastMessageAt: "now",
+ mentionCount: 0,
+ openerMessageId: "opener_1",
+ }],
+ }],
+ }],
+ dms: [],
+ })
+ queryClient.setQueryData(communityKeys.threads("forum_1"), {
+ parentType: "forum",
+ serverId: "server_1",
+ parentChannelId: "forum_1",
+ threads: [{
+ id: "post_1",
+ name: "Old title",
+ openerMessageId: "opener_1",
+ messageCount: 1,
+ lastMessageAt: "now",
+ parent: { authorName: "A", text: "Old title" },
+ }],
+ })
+ queryClient.setQueryData(communityKeys.forumActivityFeed("forum_1", null), {
+ pages: [{
+ parentType: "forum",
+ serverId: "server_1",
+ threads: [{ id: "post_1", parentMessageId: "opener_1" }],
+ included: {
+ parentMessages: [{ id: "opener_1", channelId: "forum_1", content: "Old title" }],
+ firstMessages: [], tags: [], participants: [],
+ },
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+ queryClient.setQueryData(communityKeys.forumSidebarThreads("server_1"), {
+ threads: [{
+ id: "post_1",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ title: "Old title",
+ activityAt: "now",
+ expiresAt: "later",
+ unread: false,
+ }],
+ verifiedEpoch: 0,
+ serverNow: "now",
+ serverClockOffsetMs: 0,
+ })
+ queryClient.setQueryData(communityKeys.forumOpenerHint("server_1", "opener_1"), {
+ id: "opener_1", content: "Old title",
+ })
+}
+
+describe("reconcileForumOpenerTitle", () => {
+ it("patches every exact forum title read model and repairs only exact network reads", async () => {
+ seedCanonicalCaches()
+ const activityKey = communityKeys.forumActivityFeed("forum_1", null)
+ const cancel = vi.spyOn(queryClient, "cancelQueries")
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")
+
+ await reconcileForumOpenerTitle(queryClient, identity)
+
+ expect(cancel).toHaveBeenCalledWith({ queryKey: communityKeys.inboxUnreads(), exact: true })
+ expect(cancel).toHaveBeenCalledWith({ queryKey: communityKeys.threads("forum_1"), exact: true })
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inboxUnreads(), exact: true })
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.threads("forum_1"), exact: true })
+ expect(queryClient.getQueryState(activityKey)?.isInvalidated).toBe(false)
+
+ expect(queryClient.getQueryData<any>(communityKeys.message("opener_1")).content).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(communityKeys.channelMessages("forum_1")).pages[0].messages[0].content).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(communityKeys.channelMessages("post_1")).pages[0].messages[0].content).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(communityKeys.inboxUnreads()).servers[0].channels[0].children[0].channelName).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(communityKeys.threads("forum_1")).threads[0].name).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(activityKey).pages[0].included.parentMessages[0].content).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(communityKeys.forumSidebarThreads("server_1")).threads[0].title).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(communityKeys.forumOpenerHint("server_1", "opener_1")).content).toBe("Full new title")
+ })
+
+ it("is idempotent and leaves title caches unchanged for every mismatched identity", async () => {
+ seedCanonicalCaches()
+ const mismatches = [
+ { ...identity, serverId: "wrong" },
+ { ...identity, forumChannelId: "wrong" },
+ { ...identity, childChannelId: "wrong" },
+ { ...identity, openerMessageId: "wrong" },
+ ]
+ for (const mismatch of mismatches) {
+ await reconcileForumOpenerTitle(queryClient, mismatch)
+ await reconcileForumOpenerTitle(queryClient, mismatch)
+ }
+
+ expect(queryClient.getQueryData<any>(communityKeys.inboxUnreads()).servers[0].channels[0].children[0].channelName).toBe("Old title")
+ expect(queryClient.getQueryData<any>(communityKeys.threads("forum_1")).threads[0].name).toBe("Old title")
+ expect(queryClient.getQueryData<any>(communityKeys.forumSidebarThreads("server_1")).threads[0].title).toBe("Old title")
+ })
+
+ it("never rewrites a text-thread name", async () => {
+ queryClient.setQueryData(communityKeys.threads("forum_1"), {
+ parentType: "text",
+ serverId: "server_1",
+ parentChannelId: "forum_1",
+ threads: [{ id: "post_1", name: "Custom thread", openerMessageId: "opener_1" }],
+ })
+ await reconcileForumOpenerTitle(queryClient, identity)
+ expect(queryClient.getQueryData<any>(communityKeys.threads("forum_1")).threads[0].name).toBe("Custom thread")
+ })
+})
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
new file mode 100644
index 000000000..70b69817c
--- /dev/null
+++ b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
@@ -0,0 +1,219 @@
+"use client"
+
+import type { InfiniteData, QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import type { Msg, UnreadServer } from "@/components/community/_types"
+import type { MessagesPage } from "@/hooks/community/use-messages"
+import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"
+import type { ForumActivityPage } from "@/hooks/community/use-forum-feed"
+import {
+ getForumSidebarBase,
+ patchForumSidebarTitleExact,
+ type ChildChannelMeta,
+ type ForumOpenerHint,
+ type ForumSidebarThread,
+} from "@/hooks/community/use-forum-sidebar-threads"
+import { patchMessageContentInCache } from "@/hooks/community/community-ws/cache"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+
+type PageCache = InfiniteData<MessagesPage>
+
+export type ForumOpenerTitleIdentity = {
+ serverId: string
+ forumChannelId: string
+ childChannelId: string
+ openerMessageId: string
+ content: string
+}
+
+function patchInbox(
+ data: { servers: UnreadServer[]; dms: unknown[] } | undefined,
+ identity: ForumOpenerTitleIdentity,
+) {
+ if (!data) return data
+ let touched = false
+ const servers = data.servers.map((server) => {
+ if (server.serverId !== identity.serverId) return server
+ return {
+ ...server,
+ channels: server.channels.map((channel) => {
+ if (channel.channelId !== identity.forumChannelId) return channel
+ return {
+ ...channel,
+ children: channel.children.map((child) => {
+ if (
+ child.channelId !== identity.childChannelId ||
+ child.openerMessageId !== identity.openerMessageId
+ ) return child
+ touched = true
+ return { ...child, channelName: identity.content }
+ }),
+ }
+ }),
+ }
+ })
+ return touched ? { ...data, servers } : data
+}
+
+function patchActivity(
+ data: InfiniteData<ForumActivityPage> | undefined,
+ identity: ForumOpenerTitleIdentity,
+) {
+ if (!data) return data
+ let touched = false
+ const pages = data.pages.map((page) => ({
+ ...page,
+ included: {
+ ...page.included,
+ parentMessages: page.included.parentMessages.map((message) => {
+ if (
+ page.serverId !== identity.serverId ||
+ message.id !== identity.openerMessageId ||
+ message.channelId !== identity.forumChannelId
+ ) return message
+ touched = true
+ return { ...message, content: identity.content }
+ }),
+ },
+ }))
+ return touched ? { ...data, pages } : data
+}
+
+function sidebarIdentityMatches(queryClient: QueryClient, identity: ForumOpenerTitleIdentity) {
+ const meta = queryClient.getQueryData<ChildChannelMeta>(
+ communityKeys.channelMeta(identity.serverId, identity.childChannelId),
+ )
+ if (meta) {
+ return meta.parentChannelId === identity.forumChannelId &&
+ meta.parentMessageId === identity.openerMessageId
+ }
+ const base = getForumSidebarBase(queryClient, identity.serverId)?.threads
+ .find((thread) => thread.id === identity.childChannelId)
+ if (base) {
+ return base.parentChannelId === identity.forumChannelId &&
+ base.parentMessageId === identity.openerMessageId
+ }
+ const retained = queryClient.getQueryData<ForumSidebarThread | null>(
+ communityKeys.forumSidebarRetained(identity.serverId, identity.childChannelId),
+ )
+ return !!retained && retained.parentChannelId === identity.forumChannelId &&
+ retained.parentMessageId === identity.openerMessageId
+}
+
+export async function reconcileForumOpenerTitle(
+ queryClient: QueryClient,
+ identity: ForumOpenerTitleIdentity,
+) {
+ const inboxKey = communityKeys.inboxUnreads()
+ const threadsKey = communityKeys.threads(identity.forumChannelId)
+
+ await Promise.all([
+ queryClient.cancelQueries({ queryKey: inboxKey, exact: true }),
+ queryClient.cancelQueries({ queryKey: threadsKey, exact: true }),
+ ])
+
+ // A loaded base-threads response is server-authorized and carries the full
+ // forum/child/opener identity. Treat any mismatch as an untrusted/stale
+ // event and stop before touching even the message-shaped title caches.
+ const loadedThreads = queryClient.getQueryData<ThreadsResponse>(threadsKey)
+ if (loadedThreads) {
+ const loadedChild = loadedThreads.threads.find(
+ (thread) => thread.id === identity.childChannelId,
+ )
+ if (
+ loadedThreads.serverId !== identity.serverId ||
+ loadedThreads.parentType !== "forum" ||
+ loadedThreads.parentChannelId !== identity.forumChannelId ||
+ (loadedChild !== undefined && loadedChild.openerMessageId !== identity.openerMessageId)
+ ) return
+ }
+ const loadedInbox = queryClient.getQueryData<{ servers: UnreadServer[] }>(inboxKey)
+ const knownInboxIdentity = loadedInbox?.servers.flatMap((server) =>
+ server.channels.flatMap((channel) => channel.children.map((child) => ({
+ serverId: server.serverId,
+ forumChannelId: channel.channelId,
+ childChannelId: child.channelId,
+ openerMessageId: child.openerMessageId,
+ }))),
+ ).find((row) =>
+ row.childChannelId === identity.childChannelId ||
+ row.openerMessageId === identity.openerMessageId,
+ )
+ if (knownInboxIdentity && (
+ knownInboxIdentity.serverId !== identity.serverId ||
+ knownInboxIdentity.forumChannelId !== identity.forumChannelId ||
+ knownInboxIdentity.childChannelId !== identity.childChannelId ||
+ knownInboxIdentity.openerMessageId !== identity.openerMessageId
+ )) return
+
+ queryClient.setQueryData<Msg | undefined>(
+ communityKeys.message(identity.openerMessageId),
+ (message) => message ? { ...message, content: identity.content } : message,
+ )
+ for (const channelId of [identity.forumChannelId, identity.childChannelId]) {
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: communityKeys.channelMessages(channelId) },
+ (cache) => patchMessageContentInCache(cache, identity.openerMessageId, identity.content),
+ )
+ }
+ queryClient.setQueriesData<InfiniteData<ForumActivityPage>>(
+ { queryKey: [...communityKeys.threads(identity.forumChannelId), "activity"] },
+ (data) => patchActivity(data, identity),
+ )
+ queryClient.setQueryData<{ servers: UnreadServer[]; dms: unknown[] }>(
+ inboxKey,
+ (data) => patchInbox(data, identity),
+ )
+ queryClient.setQueryData<ThreadsResponse>(threadsKey, (data) => {
+ if (
+ !data ||
+ data.serverId !== identity.serverId ||
+ data.parentType !== "forum" ||
+ data.parentChannelId !== identity.forumChannelId
+ ) return data
+ let touched = false
+ const threads = data.threads.map((thread) => {
+ if (
+ thread.id !== identity.childChannelId ||
+ thread.openerMessageId !== identity.openerMessageId
+ ) return thread
+ touched = true
+ return { ...thread, name: identity.content }
+ })
+ return touched ? { ...data, threads } : data
+ })
+
+ if (sidebarIdentityMatches(queryClient, identity)) {
+ patchForumSidebarTitleExact(
+ queryClient,
+ identity.serverId,
+ identity.childChannelId,
+ identity.content,
+ )
+ }
+ queryClient.setQueryData<ForumOpenerHint | undefined>(
+ communityKeys.forumOpenerHint(identity.serverId, identity.openerMessageId),
+ (hint) => hint?.id === identity.openerMessageId
+ ? { ...hint, content: identity.content }
+ : hint,
+ )
+
+ const streamStore = useMessageStreamStore.getState()
+ for (const entry of streamStore.entries.values()) {
+ if (
+ entry.scope.kind !== "channel" ||
+ entry.scope.serverId !== identity.serverId ||
+ (entry.scope.id !== identity.forumChannelId && entry.scope.id !== identity.childChannelId)
+ ) continue
+ streamStore.dispatch(entry.scope, {
+ type: "messageEdited",
+ messageId: identity.openerMessageId,
+ content: identity.content,
+ })
+ }
+
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: inboxKey, exact: true }),
+ queryClient.invalidateQueries({ queryKey: threadsKey, exact: true }),
+ ])
+}
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index 4a5c5f9ca..9213e7041 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -85,7 +85,7 @@ async function runMutation<Args>(args: Args) {
const ctx = cfg.onMutate ? await cfg.onMutate(args) : undefined
try {
const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
- cfg.onSuccess?.(data, args, ctx)
+ await cfg.onSuccess?.(data, args, ctx)
return { data, ctx }
} catch (err) {
cfg.onError?.(err, args, ctx)
@@ -191,21 +191,25 @@ describe("useEditMessage", () => {
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: [] })
+ it("invalidates only the exact Inbox and base threads reads after an opener edit", async () => {
+ const threads = communityKeys.threads("forum_1")
+ const activity = communityKeys.forumActivityFeed("forum_1", "bug")
+ const inbox = communityKeys.inboxUnreads()
+ capturedQc.setQueryData(threads, { serverId: "s1", parentType: "forum", parentChannelId: "forum_1", threads: [] })
+ capturedQc.setQueryData(activity, { pages: [], pageParams: [] })
+ capturedQc.setQueryData(inbox, { servers: [], dms: [] })
apiFetchMock.mockResolvedValueOnce(undefined)
const mod = await loadMod()
mod.useEditMessage()
await runMutation({
- serverId: "s1", channelId: "forum_1", messageId: "opener_1", content: "new", forumChannelId: "forum_1",
+ serverId: "s1", channelId: "forum_1", messageId: "opener_1", content: "new",
+ forumChannelId: "forum_1", forumThreadId: "post_1",
})
- expect(capturedQc.getQueryState(root)?.isInvalidated).toBe(true)
- expect(capturedQc.getQueryState(bug)?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(threads)?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(inbox)?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(activity)?.isInvalidated).toBe(false)
})
it("patches a loaded forum-sidebar title after the opener edit succeeds", async () => {
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index f2789d05a..7e2e07342 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -33,8 +33,8 @@ import {
invalidateForumSidebarBaseExact,
isForumSidebarParent,
patchForumSidebarActivityExact,
- patchForumSidebarTitleExact,
} from "@/hooks/community/use-forum-sidebar-threads"
+import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"
import { isBlocked, type MentionType } from "@alook/shared"
/**
@@ -132,16 +132,15 @@ export function useEditMessage() {
}
queryClient.setQueryData(context.messageKey, context.previousMessage)
},
- onSuccess: (_data, variables) => {
- if (variables.forumChannelId) void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(variables.forumChannelId) })
- if (variables.forumThreadId) {
- patchForumSidebarTitleExact(
- queryClient,
- variables.serverId,
- variables.forumThreadId,
- variables.content,
- )
- }
+ onSuccess: async (_data, variables) => {
+ if (!variables.forumChannelId || !variables.forumThreadId) return
+ await reconcileForumOpenerTitle(queryClient, {
+ serverId: variables.serverId,
+ forumChannelId: variables.forumChannelId,
+ childChannelId: variables.forumThreadId,
+ openerMessageId: variables.messageId,
+ content: variables.content,
+ })
},
})
}
diff --git a/src/web/src/hooks/community/use-channel-panels.test.ts b/src/web/src/hooks/community/use-channel-panels.test.ts
index 6e448bb18..8429f970d 100644
--- a/src/web/src/hooks/community/use-channel-panels.test.ts
+++ b/src/web/src/hooks/community/use-channel-panels.test.ts
@@ -14,19 +14,19 @@ beforeEach(() => {
describe("useThreads / threadsQueryFn", () => {
it("fetches from /channels/:id/threads and returns { threads }", async () => {
apiFetchMock
- .mockResolvedValueOnce({ threads: [{ id: "t_1", name: "t", type: "thread", creatorId: "u1", parentMessageId: "m1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
+ .mockResolvedValueOnce({ serverId: "s1", parentType: "forum", 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).toHaveBeenCalledWith("/api/community/channels/ch_1/threads", { signal: undefined })
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: [] })
+ apiFetchMock.mockResolvedValueOnce({ serverId: "s1", parentType: "text", threads: [] })
.mockResolvedValueOnce({ messages: [], firstMessages: [] })
.mockResolvedValueOnce({ tags: [] })
.mockResolvedValueOnce({ participants: [] })
@@ -34,7 +34,54 @@ describe("useThreads / threadsQueryFn", () => {
const qc = new QueryClient()
const key = communityKeys.threads("ch_1")
await qc.fetchQuery({ queryKey: key, queryFn: threadsQueryFn("ch_1") })
- expect(qc.getQueryData(key)).toEqual({ threads: [] })
+ expect(qc.getQueryData(key)).toEqual({ threads: [], serverId: "s1", parentType: "text", parentChannelId: "ch_1" })
+ })
+
+ it("uses full opener content only for forum parents and shares one AbortSignal", async () => {
+ const signal = new AbortController().signal
+ apiFetchMock
+ .mockResolvedValueOnce({ serverId: "s1", parentType: "forum", threads: [{ id: "post_1", name: "derived", type: "thread", creatorId: "u1", parentMessageId: "opener_1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
+ .mockResolvedValueOnce({ messages: [{ id: "opener_1", channelId: "forum_1", content: " Full opener content ", seq: 4, authorId: "u1", authorName: "A", authorImage: null }], firstMessages: [] })
+ .mockResolvedValueOnce({ tags: [] })
+ .mockResolvedValueOnce({ participants: [] })
+ const { threadsQueryFn } = await import("./use-channel-panels")
+ const forum = await threadsQueryFn("forum_1")({ signal })
+ expect(forum.threads[0]).toMatchObject({
+ name: " Full opener content ",
+ openerMessageId: "opener_1",
+ })
+ expect(apiFetchMock.mock.calls).toHaveLength(4)
+ for (const call of apiFetchMock.mock.calls) expect(call[1]).toEqual(expect.objectContaining({ signal }))
+
+ apiFetchMock.mockReset()
+ apiFetchMock
+ .mockResolvedValueOnce({ serverId: "s1", parentType: "text", threads: [{ id: "thread_1", name: "Custom thread name", type: "thread", creatorId: "u1", parentMessageId: "root_1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
+ .mockResolvedValueOnce({ messages: [{ id: "root_1", channelId: "text_1", content: "Root message", seq: 1, authorId: "u1", authorName: "A", authorImage: null }], firstMessages: [] })
+ .mockResolvedValueOnce({ tags: [] })
+ .mockResolvedValueOnce({ participants: [] })
+ const text = await threadsQueryFn("text_1")()
+ expect(text.threads[0]?.name).toBe("Custom thread name")
+ })
+
+ it("aborts all four loader requests when the exact base query is cancelled", async () => {
+ const signals: AbortSignal[] = []
+ apiFetchMock.mockImplementation((url: string, init: RequestInit = {}) => {
+ const requestSignal = init.signal as AbortSignal
+ signals.push(requestSignal)
+ if (url.endsWith("/threads")) return Promise.resolve({ serverId: "s1", parentType: "forum", threads: [] })
+ return new Promise((_resolve, reject) => {
+ requestSignal.addEventListener("abort", () => reject(new Error("aborted")))
+ })
+ })
+ const { threadsQueryFn } = await import("./use-channel-panels")
+ const qc = new QueryClient()
+ const key = communityKeys.threads("forum_1")
+ const pending = qc.fetchQuery({ queryKey: key, queryFn: threadsQueryFn("forum_1") }).catch(() => undefined)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(4))
+ await qc.cancelQueries({ queryKey: key, exact: true })
+ expect(new Set(signals).size).toBe(1)
+ expect(signals[0]?.aborted).toBe(true)
+ await pending
})
})
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index 8bd4340de..8556cfba4 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -18,7 +18,12 @@ const EMPTY_PINS: readonly Msg[] = Object.freeze([])
* WS (`community:channel.child_create`) can invalidate the thread list only
* — without touching messages.
*/
-export type ThreadsResponse = { threads: Thread[] }
+export type ThreadsResponse = {
+ threads: Thread[]
+ serverId: string
+ parentType: string
+ parentChannelId: string
+}
type RawThread = {
id: string
@@ -41,30 +46,40 @@ type BatchMessage = {
}
type ParticipantRow = { channelId: string; userId: string; userName: string | null; userImage: string | null; addedAt: string; participantCount?: number }
-async function loadThreadResources(channelId: string, tag?: string | null) {
+async function loadThreadResources(channelId: string, tag?: string | null, signal?: AbortSignal) {
const query = tag ? `?tag=${encodeURIComponent(tag)}` : ""
- const { threads } = await apiFetch<{ threads: RawThread[] }>(`/api/community/channels/${channelId}/threads${query}`)
+ const { threads, parentType, serverId } = await apiFetch<{
+ threads: RawThread[]
+ parentType: string
+ serverId: string
+ }>(
+ `/api/community/channels/${channelId}/threads${query}`,
+ { signal },
+ )
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 }),
+ signal,
}),
apiFetch<{ tags: { messageId: string; tag: string }[] }>("/api/community/messages/tags/batch", {
method: "POST",
body: JSON.stringify({ channelId, messageIds: openerIds }),
+ signal,
}),
apiFetch<{ participants: ParticipantRow[] }>("/api/community/channels/participants/batch", {
method: "POST",
body: JSON.stringify({ parentChannelId: channelId, channelIds: threadIds }),
+ signal,
}),
])
- return { threads, openerIds, ...messageBatch, ...tagBatch, ...participantBatch }
+ return { threads, parentType, serverId, openerIds, ...messageBatch, ...tagBatch, ...participantBatch }
}
-export const threadsQueryFn = (channelId: string) => async () => {
- const data = await loadThreadResources(channelId)
+export const threadsQueryFn = (channelId: string) => async ({ signal }: { signal?: AbortSignal } = {}) => {
+ const data = await loadThreadResources(channelId, null, signal)
const openerMap = new Map(data.messages.map((message) => [message.id, message]))
const firstMap = new Map(data.firstMessages.map((message) => [message.channelId, message]))
return {
@@ -73,13 +88,21 @@ export const threadsQueryFn = (channelId: string) => async () => {
const first = firstMap.get(thread.id)
return {
id: thread.id,
- name: thread.name,
+ name: data.parentType === "forum"
+ ? opener?.content.trim()
+ ? opener.content
+ : thread.name.trim() || "Post"
+ : 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 } : {}),
+ ...(thread.parentMessageId ? { openerMessageId: thread.parentMessageId } : {}),
}
}),
+ parentType: data.parentType,
+ serverId: data.serverId,
+ parentChannelId: channelId,
}
}
diff --git a/src/web/src/hooks/community/use-forum-feed.test.ts b/src/web/src/hooks/community/use-forum-feed.test.ts
index c0880eb23..785c873d9 100644
--- a/src/web/src/hooks/community/use-forum-feed.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.test.ts
@@ -39,6 +39,8 @@ describe("mapForumActivityPages", () => {
it("joins included resources, deduplicates pages, and keeps latest activity first", () => {
const pages: ForumActivityPage[] = [
{
+ serverId: "server_1",
+ parentType: "forum",
threads: [
{
id: "t2",
@@ -63,7 +65,7 @@ describe("mapForumActivityPages", () => {
],
included: {
parentMessages: [
- { id: "m2", channelId: "forum_1", content: "Opener title", authorId: "u2", authorName: "Alice", authorImage: null },
+ { id: "m2", channelId: "forum_1", content: " Opener title ", authorId: "u2", authorName: "Alice", authorImage: null },
],
firstMessages: [{ channelId: "t2", content: "First reply preview" }],
tags: [{ messageId: "m2", tag: "bug" }, { messageId: "m2", tag: "help" }],
@@ -76,6 +78,8 @@ describe("mapForumActivityPages", () => {
nextCursor: "next",
},
{
+ serverId: "server_1",
+ parentType: "forum",
threads: [
{
id: "t2",
@@ -96,7 +100,7 @@ describe("mapForumActivityPages", () => {
const result = mapForumActivityPages(pages)
expect(result.map((thread) => thread.id)).toEqual(["t2", "t1"])
expect(result[0]).toMatchObject({
- name: "Opener title",
+ name: " Opener title ",
authorId: "u2",
authorAvatar: "A",
preview: "First reply preview",
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index afa7f5e08..5218938fb 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -41,6 +41,8 @@ type IncludedParticipant = {
}
export type ForumActivityPage = {
+ serverId: string
+ parentType: string
threads: ActivityThread[]
included: {
parentMessages: IncludedMessage[]
@@ -96,7 +98,7 @@ export function mapForumActivityPages(pages: ForumActivityPage[]): ForumThread[]
const first = firstByChannel.get(thread.id)
byId.set(thread.id, {
id: thread.id,
- name: opener?.content.trim() || thread.name?.trim() || "Post",
+ name: opener?.content.trim() ? opener.content : thread.name?.trim() || "Post",
messageCount: thread.messageCount ?? 0,
lastMessageAt: thread.activityAt,
parent: {
diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.ts
index cdc71e604..d0e904d96 100644
--- a/src/web/src/hooks/community/use-inbox.test.ts
+++ b/src/web/src/hooks/community/use-inbox.test.ts
@@ -18,9 +18,28 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
const qc = new QueryClient()
const key = communityKeys.inboxUnreads()
await qc.fetchQuery({ queryKey: key, queryFn: inboxUnreadsQueryFn })
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/inbox/unreads")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/inbox/unreads",
+ { signal: expect.any(AbortSignal) },
+ )
expect(qc.getQueryData(key)).toEqual({ servers: [], dms: [] })
})
+
+ it("aborts an in-flight unread read when the exact query is cancelled", async () => {
+ let signal: AbortSignal | undefined
+ apiFetchMock.mockImplementationOnce((_url: string, init: RequestInit) => new Promise((_resolve, reject) => {
+ signal = init.signal as AbortSignal
+ signal.addEventListener("abort", () => reject(new Error("aborted")))
+ }))
+ const { inboxUnreadsQueryFn } = await import("./use-inbox")
+ const qc = new QueryClient()
+ const key = communityKeys.inboxUnreads()
+ const pending = qc.fetchQuery({ queryKey: key, queryFn: inboxUnreadsQueryFn }).catch(() => undefined)
+ await vi.waitFor(() => expect(signal).toBeDefined())
+ await qc.cancelQueries({ queryKey: key, exact: true })
+ expect(signal?.aborted).toBe(true)
+ await pending
+ })
})
describe("useInboxMentions / inboxMentionsQueryFn", () => {
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index 98980703d..921665453 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -34,8 +34,11 @@ const EMPTY_MARKED: readonly Marked[] = Object.freeze([])
export type UnreadsResponse = { servers: UnreadServer[]; dms: UnreadDm[] }
-export const inboxUnreadsQueryFn = () =>
- apiFetch<UnreadsResponse & { stale?: boolean }>("/api/community/users/me/inbox/unreads").then(throwIfStale)
+export const inboxUnreadsQueryFn = ({ signal }: { signal?: AbortSignal } = {}) =>
+ apiFetch<UnreadsResponse & { stale?: boolean }>(
+ "/api/community/users/me/inbox/unreads",
+ { signal },
+ ).then(throwIfStale)
export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
servers: UnreadServer[]
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
new file mode 100644
index 000000000..8f2409e4d
--- /dev/null
+++ b/src/web/src/lib/community/testids.test.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from "vitest"
+import { tid } from "./testids"
+
+describe("community QA selectors", () => {
+ it("keys forum-title read models by their stable child identity", () => {
+ expect(tid.inboxUnreadChild("post_1")).toBe("community-inbox-unread-child-post_1")
+ expect(tid.channelRefPill("post_1")).toBe("community-channel-ref-pill-post_1")
+ })
+})
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index dc3791841..b02b8bd26 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -40,4 +40,6 @@ export const tid = {
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}`,
+ inboxUnreadChild: (id: string) => `community-inbox-unread-child-${id}`,
+ channelRefPill: (id: string) => `community-channel-ref-pill-${id}`,
} as const