Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): message tech-debt pass (#350)

Gener01c98845c581
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9d9d6aad5..d6c6e724d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -402,6 +402,30 @@ importers:
lucide-react:
specifier: ^1.23.0
version: 1.23.0([email protected])
+ mdast-util-find-and-replace:
+ specifier: ^3.0.2
+ version: 3.0.2
+ mdast-util-from-markdown:
+ specifier: ^2.0.3
+ version: 2.0.3
+ mdast-util-to-hast:
+ specifier: ^13.2.1
+ version: 13.2.1
+ micromark-util-chunked:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-classify-character:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-resolve-all:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-symbol:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-types:
+ specifier: ^2.0.2
+ version: 2.0.2
nanoid:
specifier: ^5.1.16
version: 5.1.16
@@ -432,9 +456,15 @@ importers:
rehype-external-links:
specifier: ^3.0.0
version: 3.0.0
+ rehype-harden:
+ specifier: ^1.1.8
+ version: 1.1.8
rehype-pretty-code:
specifier: ^0.14.3
version: 0.14.3([email protected])
+ rehype-sanitize:
+ specifier: ^6.0.0
+ version: 6.0.0
rehype-slug:
specifier: ^6.0.0
version: 6.0.0
@@ -481,6 +511,12 @@ importers:
'@tanstack/react-query-devtools':
specifier: ^5.101.2
+ '@types/hast':
+ specifier: ^3.0.4
+ version: 3.0.4
+ '@types/mdast':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/node':
specifier: ^25
version: 25.9.4
@@ -505,6 +541,12 @@ importers:
knip:
specifier: ^6.24.0
version: 6.24.0
+ react-test-renderer:
+ specifier: 19.2.7
+ version: 19.2.7([email protected])
+ remark-parse:
+ specifier: ^11.0.0
+ version: 11.0.0
tailwindcss:
specifier: ^4
version: 4.3.1
@@ -514,6 +556,9 @@ importers:
typescript:
specifier: ^6.0.3
version: 6.0.3
+ unified:
+ specifier: ^11.0.5
+ version: 11.0.5
vitest:
specifier: ^4.1.9
@@ -7491,12 +7536,20 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
+ resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==}
+
resolution: {integrity: sha512-ElE/UpOvMLRWtAqbCgyizHXcbws8RPMyN3cBqmdY17Nxr5f01+DEwzOLqhgcy68GSnjtIUFgKWKl8aIgx5aypQ==}
peerDependencies:
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-U4TyPDJ9MsC8rFimXuJum8w40aPc9kbOZYO8Pc2/4A884i8hwJsMNA/JNyuOc/f2/37wHvk7HjpVl1V4re7Dig==}
+ peerDependencies:
+ react: ^19.2.7
+
resolution: {integrity: sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==}
engines: {node: '>=0.10.0'}
@@ -16682,11 +16735,19 @@ snapshots:
+
dependencies:
react: 19.2.7
react-dom: 19.2.7([email protected])
+ dependencies:
+ react: 19.2.7
+ react-is: 19.2.7
+ scheduler: 0.27.0
+
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 9683e6d34..94424ebaf 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -22,7 +22,11 @@ export type CommunityMessageCreate = {
authorName: string
authorAvatar?: string
content: string
- type?: "default" | "system" | "thread_created"
+ type: "chat" | "system"
+ // Only ever set alongside `type: "system"` — distinguishes a
+ // thread-creation system message from a bare/other-origin system row
+ // (`systemKind` omitted). See `mapMessageForWs`'s `splitType`.
+ systemKind?: "thread"
mentionType?: MentionType | null
replyToId?: string | null
replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }
@@ -230,6 +234,11 @@ export type CommunityMemberUpdate = {
type: "community:member.update"
serverId: string
memberId: string
+ // Present alongside `changes.nickname` on a self-rename broadcast — lets
+ // clients patch `authorId`-keyed message caches (which don't have
+ // `memberId`, a server-scoped id) by the renamed user's actual userId.
+ // Absent on a role-only change, which never touches cached message rows.
+ userId?: string
changes: {
role?: string
nickname?: string | null
diff --git a/src/shared/src/utils/community-mentions.ts b/src/shared/src/utils/community-mentions.ts
index b64efaa4f..b8a0e1b73 100644
--- a/src/shared/src/utils/community-mentions.ts
+++ b/src/shared/src/utils/community-mentions.ts
@@ -7,9 +7,14 @@
* - be preceded by start-of-string or a non-identifier character
* - be followed by end-of-string or a non-identifier character
*
- * Identifier characters are `[A-Za-z0-9_]`, so a name ending or starting in
- * those plus the next-char rule covers normal punctuation, spaces, and
- * newlines as boundaries. Names containing whitespace are supported.
+ * Identifier characters are `\p{L}\p{N}_-` (Unicode-aware — `Member.name`
+ * is a free Unicode string, so an ASCII-only class would silently fail to
+ * resolve/notify mentions of names like `李四`/`José`/`Ünal`; this must
+ * agree with the display-side regex in `chat-syntax-plugin.ts` or the pill
+ * and the notification fan-out would disagree on which text is a mention),
+ * so a name ending or starting in those plus the next-char rule covers
+ * normal punctuation, spaces, and newlines as boundaries. Names containing
+ * whitespace are supported.
*
* When a candidate carries a `discriminator`, an exact `@Name#0042` match is
* tried FIRST at each `@` site (so a channel with two "Alex"es can be
@@ -37,7 +42,7 @@ export function isMentionType(value: unknown): value is MentionType {
return value === "everyone" || value === "here";
}
-const ID_CHAR_RE = /[A-Za-z0-9_]/;
+const ID_CHAR_RE = /[\p{L}\p{N}_-]/u;
function isBoundaryChar(ch: string | undefined): boolean {
if (ch === undefined) return true;
diff --git a/src/shared/test/utils/community-mentions.test.ts b/src/shared/test/utils/community-mentions.test.ts
index 1af5b75ee..1b236badf 100644
--- a/src/shared/test/utils/community-mentions.test.ts
+++ b/src/shared/test/utils/community-mentions.test.ts
@@ -56,6 +56,22 @@ describe("extractMentionedUserIds", () => {
expect(extractMentionedUserIds("早 @李雷 好", ROSTER)).toEqual(["u5"]);
});
+ it("handles accented-Latin names — the #4 charset fix", () => {
+ const roster = [{ userId: "u_jose", name: "José" }, { userId: "u_unal", name: "Ünal" }];
+ expect(extractMentionedUserIds("hi @José", roster)).toEqual(["u_jose"]);
+ expect(extractMentionedUserIds("hi @Ünal", roster)).toEqual(["u_unal"]);
+ });
+
+ it("respects right boundary for accented-Latin names — a longer identifier run must not false-positive match a shorter name prefix", () => {
+ // Before the #4 fix, `ID_CHAR_RE` was ASCII-only (`[A-Za-z0-9_]`), which
+ // treated `é` as a non-identifier boundary character — so `@Josééx`
+ // incorrectly matched "José" as a complete token (the boundary check
+ // right after the match wrongly passed). Verified this reproduced
+ // against the pre-fix regex before writing this test.
+ const roster = [{ userId: "u_jose", name: "José" }];
+ expect(extractMentionedUserIds("hi @Josééx", roster)).toEqual([]);
+ });
+
it("does not match @everyone / @here when not in roster", () => {
expect(extractMentionedUserIds("@everyone hi", ROSTER)).toEqual([]);
});
diff --git a/src/web/package.json b/src/web/package.json
index cba0b4c16..6ad8682cf 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -67,6 +67,14 @@
"input-otp": "^1.4.2",
"katex": "^0.17.0",
"lucide-react": "^1.23.0",
+ "mdast-util-find-and-replace": "^3.0.2",
+ "mdast-util-from-markdown": "^2.0.3",
+ "mdast-util-to-hast": "^13.2.1",
+ "micromark-util-chunked": "^2.0.1",
+ "micromark-util-classify-character": "^2.0.1",
+ "micromark-util-resolve-all": "^2.0.1",
+ "micromark-util-symbol": "^2.0.1",
+ "micromark-util-types": "^2.0.2",
"nanoid": "^5.1.16",
"next": "16.2.10",
"next-themes": "^0.4.6",
@@ -77,7 +85,9 @@
"react-resizable-panels": "^4.12.1",
"rehype-autolink-headings": "^7.1.0",
"rehype-external-links": "^3.0.0",
+ "rehype-harden": "^1.1.8",
"rehype-pretty-code": "^0.14.3",
+ "rehype-sanitize": "^6.0.0",
"rehype-slug": "^6.0.0",
"remark-gfm": "^4.0.1",
"shadcn": "^4.13.0",
@@ -95,6 +105,8 @@
"@tailwindcss/node": "^4.3.2",
"@tailwindcss/postcss": "^4",
"@tanstack/react-query-devtools": "^5.101.2",
+ "@types/hast": "^3.0.4",
+ "@types/mdast": "^4.0.4",
"@types/node": "^25",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
@@ -103,9 +115,12 @@
"eslint-plugin-tailwind-canonical-classes": "^1.3.3",
"fake-indexeddb": "^6.2.5",
"knip": "^6.24.0",
+ "react-test-renderer": "19.2.7",
+ "remark-parse": "^11.0.0",
"tailwindcss": "^4",
"tsx": "^4.23.0",
"typescript": "^6.0.3",
+ "unified": "^11.0.5",
"vitest": "^4.1.9",
"wrangler": "^4.107.0"
}
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 526d5d43a..f8b7a0374 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
@@ -109,8 +109,9 @@ describe("GET /api/community/messages/[id]", () => {
expect(body.reactions).toEqual([
{ emoji: "👍", count: 1, me: true, userIds: ["u1"] },
])
- // GET convention: no `type: "default"` on the wire (undefined for default).
- expect(body.type).toBeUndefined()
+ // GET convention: ordinary messages map to type: "chat" now (#12's
+ // exhaustive discriminator) — was `undefined` before.
+ expect(body.type).toBe("chat")
})
it("hydrates reply preview when replyToId is set + target is in the same channel", async () => {
diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts b/src/web/src/app/api/community/messages/[id]/threads/route.test.ts
index 80e8a9786..d56ec354d 100644
--- a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/threads/route.test.ts
@@ -11,6 +11,7 @@ const mockListChildChannels = vi.fn()
const mockCreateChannel = vi.fn()
const mockCreateMessage = vi.fn()
const mockListMessages = vi.fn()
+const mockGetUserInternal = vi.fn()
const mockFanOutToChannel = vi.fn()
@@ -31,6 +32,9 @@ vi.mock("@alook/shared", async () => {
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
listMessages: (...a: unknown[]) => mockListMessages(...a),
},
+ user: {
+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
+ },
},
}
})
@@ -69,12 +73,6 @@ const ctx = { params: { id: "msg-p" } } as any
describe("POST /api/community/messages/[id]/threads", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockGetMessage.mockResolvedValue({
- id: "msg-p",
- authorId: "u-author",
- content: "the parent content",
- channelId: "c-parent",
- })
mockGetChannelForMember.mockResolvedValue({
id: "c-parent",
serverId: "s1",
@@ -91,6 +89,33 @@ describe("POST /api/community/messages/[id]/threads", () => {
messageCount: 0,
createdAt: "2026-07-03T00:00:00.000Z",
})
+ mockGetUserInternal.mockResolvedValue({ id: "u1", name: "Thread Creator" })
+ // The thread-creation system message (see #12/§5 — inserted into the
+ // PARENT channel, distinct from the parent-message-clone-into-the-NEW-
+ // thread-channel bug finding #6 already guards against below).
+ mockCreateMessage.mockResolvedValue({ id: "sysmsg-1" })
+ mockGetMessage.mockImplementation((_db, id) => {
+ if (id === "sysmsg-1") {
+ return Promise.resolve({
+ id: "sysmsg-1",
+ authorId: "u1",
+ authorName: "Thread Creator",
+ authorImage: null,
+ content: "Thread Creator started a thread: my thread",
+ type: "thread_created",
+ mentionType: null,
+ replyToId: null,
+ embeds: null,
+ createdAt: "2026-07-03T00:00:01.000Z",
+ })
+ }
+ return Promise.resolve({
+ id: "msg-p",
+ authorId: "u-author",
+ content: "the parent content",
+ channelId: "c-parent",
+ })
+ })
})
it("creates the child channel WITHOUT cloning the parent message into it", async () => {
@@ -98,9 +123,22 @@ describe("POST /api/community/messages/[id]/threads", () => {
expect(res.status).toBe(201)
// Regression guard: the fix in finding #6 removes the createMessage(...)
- // clone. If someone adds it back, this assertion fails and the drift
- // problem (parent edits, attachments/reactions/mentions lost) returns.
- expect(mockCreateMessage).not.toHaveBeenCalled()
+ // CLONE of the parent's content into the NEW thread channel — that call
+ // would have `channelId: "t-new"`. It's distinct from the (correct,
+ // added in #12/§5) system-message insert into the PARENT channel
+ // (`channelId: "c-parent"`) asserted below — this checks no call
+ // targets the new thread channel specifically.
+ expect(mockCreateMessage).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ channelId: "t-new" }),
+ )
+
+ // The new system-message insert targets the PARENT channel, with the
+ // `thread_created` convention type (#12/§5).
+ expect(mockCreateMessage).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ channelId: "c-parent", type: "thread_created" }),
+ )
// Structural check: listMessages on the new thread channel is empty —
// no opener clone row exists.
@@ -126,12 +164,30 @@ describe("POST /api/community/messages/[id]/threads", () => {
expect(body.id).toBe("t-new")
expect(body.parentMessageId).toBe("msg-p")
- // The CHILD_CHANNEL_CREATE fan-out fires with the new thread id.
+ // Both fan-outs to the parent channel fire: CHILD_CHANNEL_CREATE and the
+ // new system-message MESSAGE_CREATE (#12/§5).
expect(mockFanOutToChannel).toHaveBeenCalledWith(
"c-parent",
expect.objectContaining({ parentMessageId: "msg-p" }),
expect.anything(),
)
+ // The system-message broadcast is NOT given `excludeUserId` — unlike the
+ // creator's own client-side actions elsewhere, nothing inserts this row
+ // into the creator's local cache, so they need the WS broadcast too to
+ // see "started a thread" without a refresh (verification acceptance
+ // finding #6 in community-message-tech-debt-acceptance.md).
+ expect(mockFanOutToChannel).toHaveBeenCalledWith(
+ "c-parent",
+ expect.objectContaining({
+ type: "community:message.create",
+ message: expect.objectContaining({ id: "sysmsg-1", type: "system", systemKind: "thread" }),
+ }),
+ )
+ const systemMessageCall = mockFanOutToChannel.mock.calls.find(
+ (call) => (call[1] as { type?: string }).type === "community:message.create",
+ )
+ expect(systemMessageCall).toBeDefined()
+ expect(systemMessageCall).toHaveLength(2)
})
it("rejects a second thread on the same parent message", async () => {
diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.ts b/src/web/src/app/api/community/messages/[id]/threads/route.ts
index 43e58d353..e0f91229d 100644
--- a/src/web/src/app/api/community/messages/[id]/threads/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/threads/route.ts
@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"
import { queries, MAX_CHANNEL_NAME_LENGTH, WS_EVENTS } from "@alook/shared"
import { fanOutToChannel } from "@/lib/community/fanout"
import { requireChannelMember } from "@/lib/community/permissions"
+import { mapMessageForWs } from "@/lib/community/message-payload"
export const POST = withAuth(async (req: NextRequest, ctx) => {
const messageId = ctx.params?.id
@@ -70,5 +71,37 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
parentMessageId: messageId,
}, { excludeUserId: ctx.userId })
+ // Insert a real system-message row into the PARENT channel (always
+ // `MessageList`-rendered, unlike the forum-post case — see the debt
+ // record's Out of scope note on why `POST .../posts` doesn't get this
+ // same treatment) so the "a thread was created" notice persists and
+ // reaches every viewer via the same `community:message.create` broadcast
+ // regular sends use — no new WS handler needed on the client (see
+ // `use-community-ws.ts`'s existing `insertMessageIntoCache`).
+ //
+ // `type: "thread_created"` was already documented as a possible
+ // `communityMessage.type` value (see `message-payload.ts`) but never
+ // actually written anywhere until now.
+ const creator = await queries.user.getUserInternal(db, ctx.userId)
+ const systemMessage = await queries.communityMessage.createMessage(db, {
+ authorId: ctx.userId,
+ content: `${creator?.name ?? "Someone"} started a thread: ${name}`,
+ channelId: message.channelId,
+ type: "thread_created",
+ })
+ const systemRow = await queries.communityMessage.getMessage(db, systemMessage.id)
+ if (systemRow) {
+ // No `excludeUserId` here — unlike most sends, the thread creator did
+ // not author this system message client-side (no optimistic row), so
+ // they need the WS broadcast too to see it without a refresh.
+ // `insertMessageIntoCache` dedupes by id, so this is safe even if a
+ // future change adds an optimistic row for the creator.
+ fanOutToChannel(message.channelId, {
+ type: WS_EVENTS.MESSAGE_CREATE,
+ channelId: message.channelId,
+ message: mapMessageForWs(systemRow, { replyMap: new Map(), attachments: [] }),
+ })
+ }
+
return writeJSON(childChannel, 201)
})
diff --git a/src/web/src/app/api/community/users/me/profile/route.test.ts b/src/web/src/app/api/community/users/me/profile/route.test.ts
index f97b8d46d..661eacaa5 100644
--- a/src/web/src/app/api/community/users/me/profile/route.test.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.test.ts
@@ -4,7 +4,11 @@ import { NextRequest } from "next/server"
const getProfile = vi.fn()
const updateProfile = vi.fn()
const getUser = vi.fn()
-const updateUser = vi.fn()
+const listMemberServerIds = vi.fn()
+const getMemberships = vi.fn()
+const authApiUpdateUser = vi.fn()
+const fanOutToServerMembers = vi.fn()
+const fanOutStatusUpdate = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -12,6 +16,17 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/auth", () => ({
+ createAuth: vi.fn(() => ({
+ api: { updateUser: (...a: unknown[]) => authApiUpdateUser(...a) },
+ })),
+}))
+
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToServerMembers: (...a: unknown[]) => fanOutToServerMembers(...a),
+ fanOutStatusUpdate: (...a: unknown[]) => fanOutStatusUpdate(...a),
+}))
+
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
@@ -23,7 +38,10 @@ vi.mock("@alook/shared", async () => {
},
user: {
getUserSelf: (...a: unknown[]) => getUser(...a),
- updateUser: (...a: unknown[]) => updateUser(...a),
+ },
+ communityMember: {
+ listMemberServerIds: (...a: unknown[]) => listMemberServerIds(...a),
+ getMemberships: (...a: unknown[]) => getMemberships(...a),
},
},
}
@@ -44,11 +62,6 @@ vi.mock("@/lib/middleware/helpers", async () => {
}
})
-const fanOutStatusUpdate = vi.fn()
-vi.mock("@/lib/community/fanout", () => ({
- fanOutStatusUpdate: (...a: unknown[]) => fanOutStatusUpdate(...a),
-}))
-
import { GET, PATCH } from "./route"
function patchReq(body: unknown) {
@@ -107,7 +120,9 @@ describe("GET /api/community/users/me/profile", () => {
describe("PATCH /api/community/users/me/profile", () => {
beforeEach(() => {
vi.clearAllMocks()
- updateUser.mockResolvedValue(undefined)
+ authApiUpdateUser.mockResolvedValue({ headers: new Headers() })
+ listMemberServerIds.mockResolvedValue([])
+ getMemberships.mockResolvedValue([])
fanOutStatusUpdate.mockResolvedValue(undefined)
updateProfile.mockImplementation(async (_db, _u, data) => ({
aboutMe: data.aboutMe ?? null,
@@ -158,7 +173,7 @@ describe("PATCH /api/community/users/me/profile", () => {
it("400 when name exceeds MAX_PROFILE_NAME_LENGTH", async () => {
const res = await PATCH(patchReq({ name: "x".repeat(101) }), {} as never)
expect(res.status).toBe(400)
- expect(updateUser).not.toHaveBeenCalled()
+ expect(authApiUpdateUser).not.toHaveBeenCalled()
})
it("400 when aboutMe exceeds MAX_PROFILE_ABOUT_LENGTH", async () => {
@@ -171,14 +186,64 @@ describe("PATCH /api/community/users/me/profile", () => {
const res = await PATCH(patchReq({}), {} as never)
expect(res.status).toBe(400)
expect(updateProfile).not.toHaveBeenCalled()
- expect(updateUser).not.toHaveBeenCalled()
+ expect(authApiUpdateUser).not.toHaveBeenCalled()
+ })
+
+ it("rename path goes through auth.api.updateUser (not a raw DB write) so the session cookie gets re-signed", async () => {
+ const res = await PATCH(patchReq({ name: "New" }), {} as never)
+ expect(res.status).toBe(200)
+ expect(authApiUpdateUser).toHaveBeenCalledWith(
+ expect.objectContaining({ body: { name: "New" }, returnHeaders: true }),
+ )
})
- it("rename path calls updateUser with { name } only and does not read the user", async () => {
+ it("rename broadcasts MEMBER_UPDATE with userId + the new nickname to every server the user belongs to", async () => {
+ listMemberServerIds.mockResolvedValue(["srv_a", "srv_b"])
+ getMemberships.mockResolvedValue([
+ { id: "mem_a", serverId: "srv_a", userId: "u1" },
+ { id: "mem_b", serverId: "srv_b", userId: "u1" },
+ ])
+
+ const res = await PATCH(patchReq({ name: "New" }), {} as never)
+ expect(res.status).toBe(200)
+ expect(fanOutToServerMembers).toHaveBeenCalledTimes(2)
+ expect(fanOutToServerMembers).toHaveBeenCalledWith("srv_a", expect.objectContaining({
+ type: "community:member.update",
+ serverId: "srv_a",
+ memberId: "mem_a",
+ userId: "u1",
+ changes: { nickname: "New" },
+ }))
+ expect(fanOutToServerMembers).toHaveBeenCalledWith("srv_b", expect.objectContaining({
+ type: "community:member.update",
+ serverId: "srv_b",
+ memberId: "mem_b",
+ userId: "u1",
+ changes: { nickname: "New" },
+ }))
+ })
+
+ it("rename with no server memberships broadcasts nothing", async () => {
const res = await PATCH(patchReq({ name: "New" }), {} as never)
expect(res.status).toBe(200)
- expect(updateUser).toHaveBeenCalledWith({}, "u1", { name: "New" })
- expect(getUser).not.toHaveBeenCalled()
+ expect(fanOutToServerMembers).not.toHaveBeenCalled()
+ })
+
+ it("forwards the Set-Cookie headers from auth.api.updateUser on the response", async () => {
+ const headers = new Headers()
+ headers.append("Set-Cookie", "better-auth.session_data=fresh; Path=/")
+ authApiUpdateUser.mockResolvedValue({ headers })
+
+ const res = await PATCH(patchReq({ name: "New" }), {} as never)
+ expect(res.status).toBe(200)
+ expect(res.headers.getSetCookie()).toContain("better-auth.session_data=fresh; Path=/")
+ })
+
+ it("a non-rename PATCH (aboutMe only) never calls auth.api.updateUser and forwards no rename cookies", async () => {
+ const res = await PATCH(patchReq({ aboutMe: "hi" }), {} as never)
+ expect(res.status).toBe(200)
+ expect(authApiUpdateUser).not.toHaveBeenCalled()
+ expect(res.headers.getSetCookie()).toEqual([])
})
it("returns shape consistent with GET (no userId leak)", async () => {
diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.ts
index 80ea49f17..73b40548d 100644
--- a/src/web/src/app/api/community/users/me/profile/route.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.ts
@@ -1,4 +1,4 @@
-import { NextRequest } from "next/server"
+import { NextRequest, NextResponse } from "next/server"
import {
queries,
MAX_PROFILE_NAME_LENGTH,
@@ -6,11 +6,13 @@ import {
MAX_STATUS_TEXT_LENGTH,
MAX_EMOJI_BYTES,
BANNER_COLOR_REGEX,
+ WS_EVENTS,
} from "@alook/shared"
import { getDb } from "@/lib/db"
+import { createAuth } from "@/lib/auth"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { fanOutStatusUpdate } from "@/lib/community/fanout"
+import { fanOutStatusUpdate, fanOutToServerMembers } from "@/lib/community/fanout"
export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
@@ -53,6 +55,11 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
return writeError("no changes provided", 400)
}
+ // Set only when a rename actually happens — carries the Set-Cookie
+ // headers `auth.api.updateUser` mints so they can be forwarded on the
+ // final response (see the return below).
+ let renameCookieHeaders: Headers | undefined
+
if (body.name !== undefined) {
if (typeof body.name !== "string") return writeError("name must be a string", 400)
const trimmed = body.name.trim()
@@ -60,7 +67,36 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
if (trimmed.length > MAX_PROFILE_NAME_LENGTH) {
return writeError(`name must be ≤ ${MAX_PROFILE_NAME_LENGTH} characters`, 400)
}
- await queries.user.updateUser(db, ctx.userId, { name: trimmed })
+ // Goes through Better-Auth's own `/update-user` rather than a raw
+ // Drizzle write — it updates the DB row AND re-signs the
+ // `session_token`/`session_data` cookies in the same call, so a
+ // refresh right after renaming doesn't read a stale cached session
+ // (the bug this fixes: cookieCache — auth.ts's `session.cookieCache`,
+ // 5min TTL — previously never got invalidated by a raw DB write).
+ const auth = createAuth(ctx.env)
+ const result = (await auth.api.updateUser({
+ body: { name: trimmed },
+ headers: req.headers,
+ returnHeaders: true,
+ })) as { headers: Headers }
+ renameCookieHeaders = result.headers
+
+ // Broadcast the new name to every server the user belongs to, so open
+ // member lists update without a refresh (previously nothing fired
+ // MEMBER_UPDATE for a self-rename — only role changes did).
+ const serverIds = await queries.communityMember.listMemberServerIds(db, ctx.userId)
+ if (serverIds.length > 0) {
+ const memberships = await queries.communityMember.getMemberships(db, ctx.userId, serverIds)
+ for (const membership of memberships) {
+ fanOutToServerMembers(membership.serverId, {
+ type: WS_EVENTS.MEMBER_UPDATE,
+ serverId: membership.serverId,
+ memberId: membership.id,
+ userId: ctx.userId,
+ changes: { nickname: trimmed },
+ })
+ }
+ }
}
const data: {
@@ -138,10 +174,27 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
// Normalise the response shape — same as GET — so callers don't see
// `userId` leak through on PATCH.
- return writeJSON({
+ const res = writeJSON({
aboutMe: updated?.aboutMe ?? "",
bannerColor: updated?.bannerColor ?? null,
statusEmoji: updated?.statusEmoji ?? null,
statusText: updated?.statusText ?? "",
})
+
+ // Forward the re-signed session cookies from a rename so the browser
+ // picks up the new name immediately — `withAuth` also forwards its own
+ // `getSession` Set-Cookie separately; both can land on the same response
+ // (harmless — the browser applies the last Set-Cookie for a given name).
+ if (renameCookieHeaders) {
+ const setCookies = renameCookieHeaders.getSetCookie()
+ if (setCookies.length > 0) {
+ const mutableRes = new NextResponse(res.body, res)
+ for (const cookie of setCookies) {
+ mutableRes.headers.append("Set-Cookie", cookie)
+ }
+ return mutableRes
+ }
+ }
+
+ return res
})
diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
index 2beac7cc8..a346f1d8e 100644
--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
@@ -7,7 +7,7 @@ import { apiFetch } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"
import { MessageList } from "@/components/community/message-list"
-import { Composer, ComposerSkeleton } from "@/components/community/composer"
+import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"
import { ForumView, ForumViewSkeleton } from "@/components/community/forum-view"
import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"
import { NewThreadDialog } from "@/components/community/new-thread-panel"
@@ -45,7 +45,9 @@ import {
useKickMember,
useSetChannelNotif,
useUploadFile,
+ zipUploadResultsWithDimensions,
type SendMessageResult,
+ type UploadedAttachment,
} from "@/hooks/community/mutations"
import {
communityWsSubscribe,
@@ -169,27 +171,48 @@ function ChannelView() {
// `src/shared/src/db/queries/community/message.ts`) — so without this
// walk, the divider anchors above the viewer's OWN just-sent message,
// which is never "unread" from the sender's perspective.
- const newDividerBefore = useMemo(() => {
- if (!readSnapshot) return undefined
+ // `anchorFound` and `newDividerBefore` MUST be computed inside the same
+ // memo — they used to be two independently-evaluated expressions (a
+ // `.findIndex` here, a separate `.some` in `anchorInCache` below) that
+ // read the same `messages`/`readSnapshot` inputs but weren't guaranteed to
+ // agree on every commit. A real (Playwright-verified) repro showed `mount`
+ // firing on a frame where the anchor's presence check passed but this
+ // walk hadn't "caught up" yet, burning the one-shot scroll gate with
+ // `newDividerBefore: undefined` and permanently missing the divider.
+ // Deriving both from one loop makes that class of disagreement impossible.
+ const { newDividerBefore, anchorFound } = useMemo(() => {
+ if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
const lastId = readSnapshot.lastReadMessageId
// First-visit case (viewer never read this channel): anchor the
// divider on the first non-self message so users landing from
// inbox / rail see "here's what you missed" instead of the bottom.
- // Mirrors the DM view for parity.
+ // Mirrors the DM view for parity. No anchor id to find — trivially "in
+ // cache".
if (!lastId) {
for (const m of messages) {
- if (m.authorId !== currentUser.id) return m.id
+ if (m.authorId !== currentUser.id) return { newDividerBefore: m.id, anchorFound: true }
}
- return undefined
+ return { newDividerBefore: undefined, anchorFound: true }
}
const idx = messages.findIndex((m) => m.id === lastId)
- if (idx === -1) return undefined
+ if (idx === -1) return { newDividerBefore: undefined, anchorFound: false }
for (let i = idx + 1; i < messages.length; i++) {
- if (messages[i].authorId !== currentUser.id) return messages[i].id
+ if (messages[i].authorId !== currentUser.id) return { newDividerBefore: messages[i].id, anchorFound: true }
}
- return undefined
+ return { newDividerBefore: undefined, anchorFound: true }
}, [messages, readSnapshot, currentUser.id])
+ // Gates `<MessageList>`'s mount-time scroll action until the anchor
+ // (`readSnapshot.lastReadMessageId`) is actually present in the loaded
+ // `messages` — not just until the read-state fetch settles. Without this,
+ // a stale IDB-hydrated cache (or a same-session anchor drift, e.g.
+ // returning from a thread after the watermark advanced) can win the race
+ // against `useMessages`' Fix 3 re-validation: `useScrollAnchor`'s mount
+ // effect (a `useLayoutEffect`) runs before Fix 3's plain `useEffect` can
+ // reset the query, burns its one-shot gate on the wrong window, and never
+ // re-fires once the correct data arrives.
+ const anchorInCache = anchorFound
+
// Scroll root of the message list — needed so `useChannelWatermark`'s
// IntersectionObserver measures against the correct viewport instead of
// the page's default viewport. Set once by `MessageList` via
@@ -288,6 +311,7 @@ function ChannelView() {
const data = await apiFetch<{ results: Array<{ message: { id: string; content: string; authorId: string; createdAt: string }; author: { name: string; image: string | null } }> }>(`/api/community/search?${params}`)
setSearchResults(data.results.map((r) => ({
id: r.message.id,
+ type: "chat" as const,
authorName: r.author.name,
authorAvatar: r.author.image ?? r.author.name.charAt(0).toUpperCase(),
content: r.message.content,
@@ -319,8 +343,8 @@ function ChannelView() {
apiFetch(`/api/community/threads/${id}/read`, { method: "PUT" }).catch(() => {})
}
- const openProfile: OpenProfile = (name, e) => {
- uiHandlers.openProfile?.(name, e)
+ const openProfile: OpenProfile = (name, e, discriminator, userId) => {
+ uiHandlers.openProfile?.(name, e, discriminator, userId)
}
// ── Message actions ─────────────────────────────────────────────────────
@@ -333,7 +357,7 @@ function ChannelView() {
// instead lets thread-create + retry callers detect failure without a
// try/catch each.
const doSend = useCallback(
- async (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: { url: string; filename: string; contentType: string; size: number }[] }): Promise<SendMessageResult | null> => {
+ async (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: UploadedAttachment[] }): Promise<SendMessageResult | null> => {
try {
return await sendMessageMut.mutateAsync({
channelId,
@@ -415,17 +439,17 @@ function ChannelView() {
}, [members])
// ── Send messages ───────────────────────────────────────────────────────
- const sendMessage = async (markdown: string, attachments?: File[], mentionType?: MentionType) => {
+ const sendMessage = async (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => {
if (!markdown && !attachments?.length) return
- let uploadedAttachments: { url: string; filename: string; contentType: string; size: number }[] = []
+ let uploadedAttachments: UploadedAttachment[] = []
if (attachments?.length) {
const results = await Promise.all(
- attachments.map((f) =>
- uploadFileMut.mutateAsync({ target: { channelId }, file: f }).catch(() => null),
+ attachments.map((a) =>
+ uploadFileMut.mutateAsync({ target: { channelId }, file: a.file }).catch(() => null),
),
)
- uploadedAttachments = results.filter(Boolean) as typeof uploadedAttachments
+ uploadedAttachments = zipUploadResultsWithDimensions(results, attachments)
}
void doSend(markdown || "", {
@@ -525,7 +549,19 @@ function ChannelView() {
<>
<ChannelHeaderSkeleton onBack={bp === "mobile" ? goBack : undefined} />
<main className="flex min-h-0 min-w-0 flex-1 flex-col">
- <MessageList channel="" messages={[]} loading={true} onOpenThread={() => {}} />
+ {/*
+ `key={channelId}` MUST match the hydrated branches' key below —
+ verified empirically (react-test-renderer) that a mismatched key
+ (this branch had none before) is what causes React to treat this
+ and the hydrated-branch `<MessageList>` as different component
+ identities, forcing a full unmount/remount instead of a props
+ update on one instance when `channelHydrated` flips true. With
+ matching keys, this works correctly even though this early
+ `return` and the hydrated branches' `return` produce
+ structurally different JSX trees — React's reconciliation only
+ needs the position + type + key to line up.
+ */}
+ <MessageList key={channelId} channel="" messages={[]} loading={true} onOpenThread={() => {}} />
<ComposerSkeleton />
</main>
</>
@@ -706,10 +742,11 @@ function ChannelView() {
scrollToMessageId={scrollToMessageId}
onScrollRoot={setScrollRootEl}
viewerUserId={currentUser.id}
- // Delay initial scroll until the read-state snapshot resolves —
- // otherwise the effect fires with newDividerBefore still stale
- // and snaps to bottom before the anchor is known.
- initialScrollReady={!readSnapshotFetching}
+ // Delay initial scroll until the read-state snapshot resolves AND
+ // the anchor it names is actually present in `messages` — see
+ // `anchorInCache`'s doc comment above for the mount-vs-Fix-3 race
+ // this closes.
+ initialScrollReady={!readSnapshotFetching && anchorInCache}
hasMore={hasMoreMessages}
isFetchingOlder={isFetchingOlderMessages}
onLoadOlder={fetchOlderMessages}
diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsx
index 7f5fd8db9..f80a66cc0 100644
--- a/src/web/src/app/community/channels/layout.tsx
+++ b/src/web/src/app/community/channels/layout.tsx
@@ -346,9 +346,9 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
serverId, invitePopoverOpen,
])
- const openProfile = (name: string, e: React.MouseEvent) => {
+ const openProfile = (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => {
// Delegate to the shell's registered openProfile via the community store.
- useCommunityStore.getState().uiHandlers.openProfile?.(name, e)
+ useCommunityStore.getState().uiHandlers.openProfile?.(name, e, discriminator, userId)
}
const closeSettings = () => { setServerSettingsOpen(false); setSettingsSection("overview") }
diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsx
index fb9174fff..9ea5783ca 100644
--- a/src/web/src/app/community/me/[dmId]/page.tsx
+++ b/src/web/src/app/community/me/[dmId]/page.tsx
@@ -7,7 +7,7 @@ import { useBreakpoint } from "@/hooks/use-mobile"
import { DmHeader, DmHeaderSkeleton } from "@/components/community/dm-header"
import { Avatar } from "@/components/community/avatar"
import { MessageList } from "@/components/community/message-list"
-import { Composer, ComposerSkeleton } from "@/components/community/composer"
+import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"
import type { OpenProfile } from "@/components/community/_types"
import {
useCommunityStore,
@@ -25,6 +25,7 @@ import {
useSendDmMessage,
useToggleReactionApi,
useUploadFile,
+ zipUploadResultsWithDimensions,
} from "@/hooks/community/mutations"
import { useCurrentUser } from "@/contexts/community/current-user"
import {
@@ -114,28 +115,38 @@ function DmView() {
// runs of viewer-authored messages (the server advances the sender's
// own watermark on POST, so anchoring above the viewer's own row would
// never be "unread" from the sender's perspective).
- const newDividerBefore = useMemo(() => {
- if (!readSnapshot) return undefined
+ // `anchorFound` and `newDividerBefore` MUST be computed inside the same
+ // memo — mirrors the channel page's identical fix exactly (see its doc
+ // comment for the Playwright-verified repro of the mount-vs-Fix-3 race
+ // this closes: two independently-evaluated expressions reading the same
+ // inputs aren't guaranteed to agree on every commit).
+ const { newDividerBefore, anchorFound } = useMemo(() => {
+ if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
const lastId = readSnapshot.lastReadMessageId
// First-visit case: viewer never opened this DM (no read-state row
// yet). The inbox surfaces the DM as unread, so the whole loaded
// window is unread from the viewer's perspective — anchor the
// divider on the first non-self message so the user lands centered
- // on "here's what you missed" instead of the bottom.
+ // on "here's what you missed" instead of the bottom. No anchor id to
+ // find — trivially "in cache".
if (!lastId) {
for (const m of messages) {
- if (m.authorId !== currentUser.id) return m.id
+ if (m.authorId !== currentUser.id) return { newDividerBefore: m.id, anchorFound: true }
}
- return undefined
+ return { newDividerBefore: undefined, anchorFound: true }
}
const idx = messages.findIndex((m) => m.id === lastId)
- if (idx === -1) return undefined
+ if (idx === -1) return { newDividerBefore: undefined, anchorFound: false }
for (let i = idx + 1; i < messages.length; i++) {
- if (messages[i].authorId !== currentUser.id) return messages[i].id
+ if (messages[i].authorId !== currentUser.id) return { newDividerBefore: messages[i].id, anchorFound: true }
}
- return undefined
+ return { newDividerBefore: undefined, anchorFound: true }
}, [messages, readSnapshot, currentUser.id])
+ // Gates `<MessageList>`'s mount-time scroll action until the anchor is
+ // actually present in the loaded `messages`.
+ const anchorInCache = anchorFound
+
// Scroll root of the message list — needed so `useDmWatermark`'s
// IntersectionObserver measures against the correct viewport rather
// than the page viewport. Set once by `MessageList` via `onScrollRoot`.
@@ -186,8 +197,8 @@ function DmView() {
}
}, [dms, dmId, onlineUserIds])
- const openProfile: OpenProfile = (name, e) => {
- uiHandlers.openProfile?.(name, e)
+ const openProfile: OpenProfile = (name, e, discriminator, userId) => {
+ uiHandlers.openProfile?.(name, e, discriminator, userId)
}
const resolveUserName = useCallback((userId: string) => {
@@ -235,17 +246,17 @@ function DmView() {
// DM endpoint ignores mentionType. Replies are supported — the backend
// persists replyToId for DMs too.
- const sendDmMsg = async (markdown: string, attachments?: File[]) => {
+ const sendDmMsg = async (markdown: string, attachments?: SendAttachment[]) => {
if (!markdown && !attachments?.length) return
if (!dmId) return
- let uploadedAttachments: { url: string; filename: string; contentType: string; size: number }[] = []
+ let uploadedAttachments: ReturnType<typeof zipUploadResultsWithDimensions> = []
if (attachments?.length) {
const results = await Promise.all(
- attachments.map((f) =>
- uploadFile.mutateAsync({ target: { dmId }, file: f }).catch(() => null),
+ attachments.map((a) =>
+ uploadFile.mutateAsync({ target: { dmId }, file: a.file }).catch(() => null),
),
)
- uploadedAttachments = results.filter(Boolean) as typeof uploadedAttachments
+ uploadedAttachments = zipUploadResultsWithDimensions(results, attachments)
}
sendDmMessage.mutate({
dmId,
@@ -277,7 +288,11 @@ function DmView() {
<>
<DmHeaderSkeleton onBack={bp === "mobile" ? goBack : undefined} />
<main className="flex min-h-0 min-w-0 flex-1 flex-col">
- <MessageList channel="" messages={[]} loading={true} onOpenThread={() => {}} hero={<></>} />
+ {/* `key={dmId}` matches the real-content branch below — same
+ reconciliation fix as the channel page (see its equivalent
+ comment). `variant="dm"` now drives the skeleton shape
+ explicitly instead of the removed `dm={!!hero}` inference. */}
+ <MessageList key={dmId} channel="" messages={[]} loading={true} onOpenThread={() => {}} variant="dm" />
<ComposerSkeleton />
</main>
</>
@@ -300,6 +315,7 @@ function DmView() {
<main className="flex min-h-0 flex-1 flex-col">
<MessageList
key={dmId}
+ variant="dm"
channel={dm.name}
messages={messages}
loading={messagesLoading}
@@ -324,10 +340,10 @@ function DmView() {
resolveUserName={resolveUserName}
onScrollRoot={setScrollRootEl}
viewerUserId={currentUser.id}
- // Delay initial scroll until the read-state snapshot resolves —
- // otherwise the effect fires with `newDividerBefore` still
- // undefined and snaps to bottom before the anchor is known.
- initialScrollReady={!readSnapshotFetching}
+ // Delay initial scroll until the read-state snapshot resolves AND
+ // the anchor it names is actually present in `messages` — see
+ // `anchorInCache`'s doc comment above.
+ initialScrollReady={!readSnapshotFetching && anchorInCache}
hasMore={hasMoreMessages}
isFetchingOlder={isFetchingOlderMessages}
onLoadOlder={fetchOlderMessages}
diff --git a/src/web/src/app/community/preview/_mock.ts b/src/web/src/app/community/preview/_mock.ts
index 19cabcf2e..d182ae966 100644
--- a/src/web/src/app/community/preview/_mock.ts
+++ b/src/web/src/app/community/preview/_mock.ts
@@ -77,7 +77,7 @@ export const CATEGORIES: Category[] = [
export const MESSAGES: Msg[] = [
{
- id: "m1", authorName: "Gener", color: "var(--foreground)", createdAt: "2026-06-24T21:27:00Z",
+ id: "m1", type: "chat", authorName: "Gener", color: "var(--foreground)", createdAt: "2026-06-24T21:27:00Z",
authorAvatar: "G",
content: "👋 Welcome to the Alook Community!\n\nAlook lets you run your own AI-powered personal company — agents that collaborate, stay always on, and learn from every task.",
embeds: [{
@@ -91,41 +91,46 @@ export const MESSAGES: Msg[] = [
thread: { id: "thr_research", name: "Research team setup", messageCount: 3 },
},
{
- id: "m2", authorName: "Gus", createdAt: "2026-06-24T21:31:00Z", authorAvatar: "Gu",
+ id: "m2", type: "chat", authorName: "Gus", createdAt: "2026-06-24T21:31:00Z", authorAvatar: "Gu",
content: "this is exactly what I needed — the email-per-agent thing is wild",
},
{
- id: "m3", authorName: "Gus", createdAt: "2026-06-24T21:31:30Z", authorAvatar: "Gu",
+ id: "m3", type: "chat", authorName: "Gus", createdAt: "2026-06-24T21:31:30Z", authorAvatar: "Gu",
content: "is there a template for a research team?",
},
{
- id: "m4", authorName: "Lindsay", createdAt: "2026-06-24T21:42:00Z", authorAvatar: "L",
+ id: "m4", type: "chat", authorName: "Lindsay", createdAt: "2026-06-24T21:42:00Z", authorAvatar: "L",
replyTo: { id: "m3", authorName: "Gus", text: "is there a template for a research team?" },
content: "Yes — check the Templates page, there's a Research Analyst preset. Deploys in a minute.",
reactions: [{ emoji: "🔥", count: 2, me: false, userIds: ["u_gus", "u_tomy"] }, { emoji: "🙏", count: 1, me: false, userIds: ["u_gus"] }],
},
{
- id: "m5", authorName: "Gener", createdAt: "2026-06-24T21:45:00Z", authorAvatar: "G",
+ id: "m5", type: "chat", authorName: "Gener", createdAt: "2026-06-24T21:45:00Z", authorAvatar: "G",
content: "Here's the **setup** in *three* steps:\n> Clone the repo first\n`pnpm install`\n```\npnpm dev --filter web\n```\nThat's it ~~maybe~~ ||it just works||",
},
{
- id: "ms1", type: "system", systemKind: "join", createdAt: "2026-06-25T10:00:00Z",
- content: "Azzo joined the server.",
+ // Mirrors what a live thread-creation system message looks like (see
+ // `POST /api/community/messages/[id]/threads` → `mapMessageForWs`'s
+ // `splitType`) — `systemKind: "join"` was removed from `Msg`'s type
+ // entirely (#12/#5) since no path has ever produced it; this fixture
+ // now demonstrates the one kind that's actually wired up.
+ id: "ms1", type: "system", systemKind: "thread", createdAt: "2026-06-25T10:00:00Z",
+ content: "A thread was created from this message.",
},
{
- id: "m6", authorName: "Gus", createdAt: "2026-06-25T10:02:00Z", authorAvatar: "Gu",
+ id: "m6", type: "chat", authorName: "Gus", createdAt: "2026-06-25T10:02:00Z", authorAvatar: "Gu",
content: "thanks @Lindsay — can you cross-post this in #general? cc @everyone",
},
{
- id: "m7", authorName: "Lindsay", createdAt: "2026-06-25T10:05:00Z", authorAvatar: "L",
+ id: "m7", type: "chat", authorName: "Lindsay", createdAt: "2026-06-25T10:05:00Z", authorAvatar: "L",
content: "here's the preset config + a screenshot of the result",
attachments: [
- { kind: "image", name: "research-preset.png", url: "https://images.unsplash.com/photo-1555066931-4365d14bab8c?w=800&q=80" },
+ { kind: "image", name: "research-preset.png", url: "https://images.unsplash.com/photo-1555066931-4365d14bab8c?w=800&q=80", width: 800, height: 533 },
{ kind: "file", name: "research-team.json", url: "#", size: "4.2 KB" },
],
},
{
- id: "m8", authorName: "Release Notes", createdAt: "2026-06-25T10:10:00Z", authorAvatar: "RN",
+ id: "m8", type: "chat", authorName: "Release Notes", createdAt: "2026-06-25T10:10:00Z", authorAvatar: "RN",
embeds: [{
provider: "GitHub",
url: "https://github.com/alookai/alook/releases/tag/v0.1.0",
@@ -143,7 +148,7 @@ export const MESSAGES: Msg[] = [
}],
},
{
- id: "m9", authorName: "Gener", createdAt: "2026-06-25T10:15:00Z", authorAvatar: "G",
+ id: "m9", type: "chat", authorName: "Gener", createdAt: "2026-06-25T10:15:00Z", authorAvatar: "G",
content: "trying the new preset now…", failed: true,
},
]
@@ -206,29 +211,29 @@ export const FORUM_POSTS: Record<string, ForumPost[]> = {
// the same way (look up the active id → get a message list).
export const THREAD_MESSAGES: Record<string, Msg[]> = {
thr_research: [
- { id: "t1", authorName: "Gus", createdAt: "2026-06-24T21:33:00Z", authorAvatar: "Gu", content: "what roles should the research team have?" },
- { id: "t2", authorName: "Lindsay", createdAt: "2026-06-24T21:35:00Z", authorAvatar: "L", content: "Analyst, Summarizer, and a Fact-checker works well. Give each its own `@inbox`." },
- { id: "t3", authorName: "Gener", createdAt: "2026-06-24T21:36:00Z", authorAvatar: "G", content: "nice — shipping that preset 🚀" },
+ { id: "t1", type: "chat", authorName: "Gus", createdAt: "2026-06-24T21:33:00Z", authorAvatar: "Gu", content: "what roles should the research team have?" },
+ { id: "t2", type: "chat", authorName: "Lindsay", createdAt: "2026-06-24T21:35:00Z", authorAvatar: "L", content: "Analyst, Summarizer, and a Fact-checker works well. Give each its own `@inbox`." },
+ { id: "t3", type: "chat", authorName: "Gener", createdAt: "2026-06-24T21:36:00Z", authorAvatar: "G", content: "nice — shipping that preset 🚀" },
],
thr_billing: [
- { id: "b1", authorName: "jgtech", createdAt: "2026-06-24T20:05:00Z", authorAvatar: "j", content: "is there a cap on messages per agent?" },
- { id: "b2", authorName: "Gener", createdAt: "2026-06-24T20:12:00Z", authorAvatar: "G", content: "Soft limits per plan — you can raise them in **Settings → Usage**." },
+ { id: "b1", type: "chat", authorName: "jgtech", createdAt: "2026-06-24T20:05:00Z", authorAvatar: "j", content: "is there a cap on messages per agent?" },
+ { id: "b2", type: "chat", authorName: "Gener", createdAt: "2026-06-24T20:12:00Z", authorAvatar: "G", content: "Soft limits per plan — you can raise them in **Settings → Usage**." },
],
thr_selfhost: [
- { id: "s1", authorName: "lucky tomy", createdAt: "2026-06-23T15:30:00Z", authorAvatar: "t", content: "yep — `wrangler deploy` and point D1 + R2 at your own buckets." },
+ { id: "s1", type: "chat", authorName: "lucky tomy", createdAt: "2026-06-23T15:30:00Z", authorAvatar: "t", content: "yep — `wrangler deploy` and point D1 + R2 at your own buckets." },
],
fp_smtp: [
- { id: "fp_smtp_1", authorName: "jgtech", createdAt: "2026-06-25T09:02:00Z", authorAvatar: "j", content: "I set up a custom SMTP relay but sends time out after ~30s. Anyone seen this?" },
- { id: "fp_smtp_2", authorName: "Lindsay", createdAt: "2026-06-25T09:08:00Z", authorAvatar: "L", content: "Check the port — `587` with STARTTLS works, `465` sometimes hangs on Workers." },
- { id: "fp_smtp_3", authorName: "jgtech", createdAt: "2026-06-25T09:14:00Z", authorAvatar: "j", content: "587 fixed it 🙏 thank you!" },
+ { id: "fp_smtp_1", type: "chat", authorName: "jgtech", createdAt: "2026-06-25T09:02:00Z", authorAvatar: "j", content: "I set up a custom SMTP relay but sends time out after ~30s. Anyone seen this?" },
+ { id: "fp_smtp_2", type: "chat", authorName: "Lindsay", createdAt: "2026-06-25T09:08:00Z", authorAvatar: "L", content: "Check the port — `587` with STARTTLS works, `465` sometimes hangs on Workers." },
+ { id: "fp_smtp_3", type: "chat", authorName: "jgtech", createdAt: "2026-06-25T09:14:00Z", authorAvatar: "j", content: "587 fixed it 🙏 thank you!" },
],
fp_preset: [
- { id: "fp_preset_1", authorName: "Lindsay", createdAt: "2026-06-25T07:00:00Z", authorAvatar: "L", content: "Drop your favorite agent setups here — let's build a library." },
- { id: "fp_preset_2", authorName: "Gus", createdAt: "2026-06-25T07:20:00Z", authorAvatar: "Gu", content: "Research Analyst + Fact-checker combo has been 🔥 for me" },
+ { id: "fp_preset_1", type: "chat", authorName: "Lindsay", createdAt: "2026-06-25T07:00:00Z", authorAvatar: "L", content: "Drop your favorite agent setups here — let's build a library." },
+ { id: "fp_preset_2", type: "chat", authorName: "Gus", createdAt: "2026-06-25T07:20:00Z", authorAvatar: "Gu", content: "Research Analyst + Fact-checker combo has been 🔥 for me" },
],
fp_pricing: [
- { id: "fp_pricing_1", authorName: "Azzo", createdAt: "2026-06-25T06:30:00Z", authorAvatar: "A", content: "Trying to understand how message limits work across a team of agents." },
- { id: "fp_pricing_2", authorName: "Gener", createdAt: "2026-06-25T06:45:00Z", authorAvatar: "G", content: "Limits are per-workspace, pooled across agents. Raise them in **Settings → Usage**." },
+ { id: "fp_pricing_1", type: "chat", authorName: "Azzo", createdAt: "2026-06-25T06:30:00Z", authorAvatar: "A", content: "Trying to understand how message limits work across a team of agents." },
+ { id: "fp_pricing_2", type: "chat", authorName: "Gener", createdAt: "2026-06-25T06:45:00Z", authorAvatar: "G", content: "Limits are per-workspace, pooled across agents. Raise them in **Settings → Usage**." },
],
}
@@ -282,16 +287,16 @@ export const DMS: DM[] = [
export const DM_MESSAGES: Record<string, Msg[]> = {
dm_lindsay: [
- { id: "d1", authorName: "Lindsay", createdAt: "2026-06-24T21:50:00Z", authorAvatar: "L", content: "hey! saw your research preset — looks great" },
- { id: "d2", authorName: "Gener", createdAt: "2026-06-24T21:51:00Z", authorAvatar: "G", content: "thanks! still tuning the **fact-checker** role" },
- { id: "d3", authorName: "Lindsay", createdAt: "2026-06-24T21:52:00Z", authorAvatar: "L", content: "want me to test it on the Q2 report?" },
+ { id: "d1", type: "chat", authorName: "Lindsay", createdAt: "2026-06-24T21:50:00Z", authorAvatar: "L", content: "hey! saw your research preset — looks great" },
+ { id: "d2", type: "chat", authorName: "Gener", createdAt: "2026-06-24T21:51:00Z", authorAvatar: "G", content: "thanks! still tuning the **fact-checker** role" },
+ { id: "d3", type: "chat", authorName: "Lindsay", createdAt: "2026-06-24T21:52:00Z", authorAvatar: "L", content: "want me to test it on the Q2 report?" },
],
dm_gus: [
- { id: "g1", authorName: "Gus", createdAt: "2026-06-24T20:30:00Z", authorAvatar: "Gu", content: "can I forward an email straight to an agent?" },
- { id: "g2", authorName: "Gener", createdAt: "2026-06-24T20:31:00Z", authorAvatar: "G", content: "yep — each agent has its own address. just CC it." },
+ { id: "g1", type: "chat", authorName: "Gus", createdAt: "2026-06-24T20:30:00Z", authorAvatar: "Gu", content: "can I forward an email straight to an agent?" },
+ { id: "g2", type: "chat", authorName: "Gener", createdAt: "2026-06-24T20:31:00Z", authorAvatar: "G", content: "yep — each agent has its own address. just CC it." },
],
dm_tomy: [
- { id: "y1", authorName: "lucky tomy", createdAt: "2026-06-23T14:00:00Z", authorAvatar: "t", content: "self-hosting was easier than I expected" },
+ { id: "y1", type: "chat", authorName: "lucky tomy", createdAt: "2026-06-23T14:00:00Z", authorAvatar: "t", content: "self-hosting was easier than I expected" },
],
}
@@ -316,15 +321,15 @@ export const AUDIT_LOG: AuditEntry[] = [
export const MENTIONS: Mention[] = [
{
id: "mn_1", server: "Alook", channel: "general",
- m: { id: "mn_m1", authorName: "Gus", createdAt: "2026-06-25T09:48:00Z", authorAvatar: "Gu", content: "thanks @Gener — can you cross-post this in #general? cc @everyone" },
+ m: { id: "mn_m1", type: "chat", authorName: "Gus", createdAt: "2026-06-25T09:48:00Z", authorAvatar: "Gu", content: "thanks @Gener — can you cross-post this in #general? cc @everyone" },
},
{
id: "mn_2", server: "Cloudflare", channel: "flagship",
- m: { id: "mn_m2", authorName: "roerohan", createdAt: "2026-06-25T08:43:00Z", authorAvatar: "r", content: "@Gener the Workers binding you mentioned fixed it 🙏" },
+ m: { id: "mn_m2", type: "chat", authorName: "roerohan", createdAt: "2026-06-25T08:43:00Z", authorAvatar: "r", content: "@Gener the Workers binding you mentioned fixed it 🙏" },
},
{
id: "mn_3", server: "Alook", channel: "help-forum",
- m: { id: "mn_m3", authorName: "jgtech", createdAt: "2026-06-25T07:14:00Z", authorAvatar: "j", content: "@Gener 587 fixed the SMTP timeout, thank you!" },
+ m: { id: "mn_m3", type: "chat", authorName: "jgtech", createdAt: "2026-06-25T07:14:00Z", authorAvatar: "j", content: "@Gener 587 fixed the SMTP timeout, thank you!" },
},
]
diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsx
index 64694d3f1..367b4523f 100644
--- a/src/web/src/app/community/preview/page.tsx
+++ b/src/web/src/app/community/preview/page.tsx
@@ -163,7 +163,7 @@ export default function CommunityPreview() {
setDmList((prev) => prev.map((d) => d.id !== dmId ? d : { ...d, preview: text.slice(0, 40) }))
setDmMessages((prev) => ({
...prev,
- [dmId]: [...(prev[dmId] ?? []), { id: `m_local_${++msgSeq}`, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(), content: text }],
+ [dmId]: [...(prev[dmId] ?? []), { id: `m_local_${++msgSeq}`, type: "chat" as const, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(), content: text }],
}))
setView("dm")
setActiveDm(dmId)
@@ -218,7 +218,7 @@ export default function CommunityPreview() {
const seed: Msg[] = opts?.anchor
? [opts.anchor]
: opts?.firstMessage
- ? [{ id: `${id}_1`, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(), content: opts.firstMessage }]
+ ? [{ id: `${id}_1`, type: "chat" as const, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(), content: opts.firstMessage }]
: []
const t: Thread = {
id, name, messageCount: seed.length, lastMessageAt: new Date().toISOString(),
@@ -246,7 +246,7 @@ export default function CommunityPreview() {
setMessages((prev) => [
...prev,
{
- id: `m_local_${++msgSeq}`, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(),
+ id: `m_local_${++msgSeq}`, type: "chat" as const, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(),
content: markdown, ...(replyTo ? { replyTo } : {}),
},
])
@@ -260,7 +260,7 @@ export default function CommunityPreview() {
const now = new Date().toISOString()
setThreadMessages((prev) => ({
...prev,
- [tid]: [...(prev[tid] ?? []), { id: `m_local_${++msgSeq}`, authorName: "Gener", authorAvatar: "G", createdAt: now, content: markdown }],
+ [tid]: [...(prev[tid] ?? []), { id: `m_local_${++msgSeq}`, type: "chat" as const, authorName: "Gener", authorAvatar: "G", createdAt: now, content: markdown }],
}))
setThreads((prev) => prev.map((t) => t.id !== tid ? t : { ...t, messageCount: t.messageCount + 1, lastMessageAt: now }))
setForumPosts((prev) => {
@@ -278,7 +278,7 @@ export default function CommunityPreview() {
setDmList((prev) => prev.map((d) => d.id !== dmId ? d : { ...d, preview: markdown.slice(0, 40) }))
setDmMessages((prev) => ({
...prev,
- [dmId]: [...(prev[dmId] ?? []), { id: `m_local_${++msgSeq}`, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(), content: markdown }],
+ [dmId]: [...(prev[dmId] ?? []), { id: `m_local_${++msgSeq}`, type: "chat" as const, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(), content: markdown }],
}))
}
@@ -385,7 +385,7 @@ export default function CommunityPreview() {
setForumPosts((prev) => ({ ...prev, [activeChannel]: [created, ...(prev[activeChannel] ?? [])] }))
setThreadMessages((prev) => ({
...prev,
- [id]: [{ id: `${id}_1`, authorName: "Gener", authorAvatar: "G", createdAt: now, content: post.content || post.name }],
+ [id]: [{ id: `${id}_1`, type: "chat" as const, authorName: "Gener", authorAvatar: "G", createdAt: now, content: post.content || post.name }],
}))
toast(`Posted “${post.name}”`)
}
@@ -464,7 +464,8 @@ export default function CommunityPreview() {
<MessageList
channel={dm.name}
messages={dmMessages[dm.id] ?? []}
- onOpenThread={() => { }}
+ onOpenThread={() => {}}
+ variant="dm"
{...profileProps}
hero={
<>
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index f10c35b52..afb082990 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -73,7 +73,7 @@ export type Category = {
// ── Messages ───────────────────────────────────────────────────────────────
export type Attachment =
- | { kind: "image"; name: string; url: string }
+ | { kind: "image"; name: string; url: string; width?: number; height?: number }
| { kind: "file"; name: string; url: string; size: string }
type Embed = {
@@ -93,8 +93,17 @@ type Reaction = { emoji: string; count: number; me: boolean; userIds: string[] }
export type Msg = {
id: string // nanoid
- type?: "system"
- systemKind?: "join" | "thread"
+ // Exhaustive discriminator (#12 — was `type?: "system"`, an incomplete
+ // partial discriminator that let `!m.type` silently misclassify a future
+ // third kind as an ordinary chat message). `mapMessageForApi`/`mapMessageForWs`
+ // always emit one of these two values now — never `undefined`.
+ type: "chat" | "system"
+ // Only ever set alongside `type: "system"` for a thread-creation system
+ // message (see `message-payload.ts`'s `splitType`). The `"join"` value
+ // that used to be part of this type is removed — no code path has ever
+ // produced it (join notifications are pure WS events with no persisted
+ // message row, and stay that way — see the debt-record's Out of scope).
+ systemKind?: "thread"
// Author's user id — populated by `mapMessageForApi` / WS message-create,
// consumed by `useChannelWatermark` to skip self-authored messages when
// advancing the read pointer. Optional to keep optimistic rows valid
@@ -111,9 +120,15 @@ export type Msg = {
reactions?: Reaction[]
replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }
thread?: { id: string; name: string; messageCount: number; participants?: string[]; lastReplyAt?: string }
- grouped?: boolean
}
+// `grouped` is a RENDER-TIME decision (computed by `message-list.tsx`'s
+// cluster-building `useMemo`, based on adjacent messages' author/timestamp)
+// — never a fact about a message itself, so it never belonged on `Msg`
+// (#7). `<Message>` and any other consumer that needs the clustering
+// decision takes a `RenderMsg`, not a bare `Msg` with `grouped` spread on.
+export type RenderMsg = Msg & { grouped: boolean }
+
// ── Threads / forum ──────────────────────────────────────────────────────────
// Thread/forum-post summaries shown in side panels and forum lists. Actual
// message content for a thread or post is loaded into `ctx.messages` once the
@@ -268,7 +283,14 @@ export type UnreadDm = {
}
// Shared callback signature for opening a user's profile card at a click point.
-// `discriminator` is only ever passed for a mention pill that carried a
-// disambiguating `#0042` tag (see message-markdown.tsx) — it lets the lookup
-// pick the exact same-named member/friend instead of the first name match.
-export type OpenProfile = (name: string, e: React.MouseEvent, discriminator?: string) => void
+// `userId` is the exact-match disambiguator — pass it whenever the caller
+// already has the clicked person's userId (member rows, message authors,
+// thread openers) so same-named members never collide. `discriminator` is
+// the fallback disambiguator for a mention pill, which only carries a
+// `#0042` tag (see message-markdown.tsx) and no userId.
+export type OpenProfile = (
+ name: string,
+ e: React.MouseEvent,
+ discriminator?: string,
+ userId?: string,
+) => void
diff --git a/src/web/src/components/community/channel-ref-pill.tsx b/src/web/src/components/community/channel-ref-pill.tsx
index 6db08bbe8..03d1d0b0e 100644
--- a/src/web/src/components/community/channel-ref-pill.tsx
+++ b/src/web/src/components/community/channel-ref-pill.tsx
@@ -1,5 +1,6 @@
"use client"
+import { useMemo } from "react"
import type React from "react"
import { useRouter } from "next/navigation"
import { ChannelPill } from "./inline-marks"
@@ -109,7 +110,11 @@ export function ChannelRefPill({ children }: { children?: React.ReactNode }) {
const currentServerId = useCommunityStore((s) => s.currentServerId)
const { directory, isLoading: directoryLoading } = useChannelRefDirectory()
- const resolved = resolveChannelRefBase(directory, ref)
+ // The debt record's own verification (see finding #6) confirmed the
+ // network requests behind `useChannelRefDirectory`/`useThreads` already
+ // dedupe via the shared TanStack Query cache — the one verified real cost
+ // was this directory scan running unmemoized on every render.
+ const resolved = useMemo(() => resolveChannelRefBase(directory, ref), [directory, ref])
const threadChannelId = resolved?.threadRootSeq !== undefined ? resolved.channel.id : null
const { threads, isLoading: threadsLoading } = useThreads(threadChannelId)
diff --git a/src/web/src/components/community/composer.test.ts b/src/web/src/components/community/composer.test.ts
new file mode 100644
index 000000000..c5e5b4886
--- /dev/null
+++ b/src/web/src/components/community/composer.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from "vitest"
+import { pendingFilesToSendAttachments } from "./composer"
+import type { PendingFile } from "@/hooks/use-file-attachments"
+
+// `pendingFilesToSendAttachments` is the pure mapping Composer.send() uses
+// to build onSend's attachments argument — extracted so the width/height
+// threading can be unit-tested without mounting the full tiptap editor
+// (Composer itself needs a real DOM; this pure function doesn't).
+describe("pendingFilesToSendAttachments", () => {
+ it("returns undefined for an empty pendingFiles list", () => {
+ expect(pendingFilesToSendAttachments([])).toBeUndefined()
+ })
+
+ it("maps each PendingFile to {file, width, height}, preserving width/height when present", () => {
+ const file = new File(["x"], "photo.png", { type: "image/png" })
+ const pending: PendingFile[] = [
+ { file, thumbnailUrl: null, thumbnailBlob: null, width: 1920, height: 1080 },
+ ]
+ const result = pendingFilesToSendAttachments(pending)
+ expect(result).toEqual([{ file, width: 1920, height: 1080 }])
+ })
+
+ it("carries width/height through as undefined for a non-image PendingFile", () => {
+ const file = new File(["x"], "notes.txt", { type: "text/plain" })
+ const pending: PendingFile[] = [
+ { file, thumbnailUrl: null, thumbnailBlob: null },
+ ]
+ const result = pendingFilesToSendAttachments(pending)
+ expect(result).toEqual([{ file, width: undefined, height: undefined }])
+ })
+
+ it("preserves per-file order and dimensions across multiple files", () => {
+ const a = new File(["a"], "a.png", { type: "image/png" })
+ const b = new File(["b"], "b.png", { type: "image/png" })
+ const pending: PendingFile[] = [
+ { file: a, thumbnailUrl: null, thumbnailBlob: null, width: 100, height: 200 },
+ { file: b, thumbnailUrl: null, thumbnailBlob: null, width: 300, height: 400 },
+ ]
+ const result = pendingFilesToSendAttachments(pending)
+ expect(result).toEqual([
+ { file: a, width: 100, height: 200 },
+ { file: b, width: 300, height: 400 },
+ ])
+ })
+})
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index a0f94c4cc..b15aa33ee 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -8,7 +8,7 @@ import StarterKit from "@tiptap/starter-kit"
import Placeholder from "@tiptap/extension-placeholder"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
-import { useFileAttachments } from "@/hooks/use-file-attachments"
+import { useFileAttachments, type PendingFile } from "@/hooks/use-file-attachments"
import { ALLOWED_ATTACHMENT_MIME_PREFIXES, MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"
import { Avatar } from "./avatar"
import { ChannelIcon } from "./channel-icon"
@@ -33,6 +33,16 @@ import {
type ChannelRefPopupState,
} from "@/lib/community/channel-ref-extension"
+export type SendAttachment = { file: File; width?: number; height?: number }
+
+// Pure mapping from `useFileAttachments`'s pending-file state to `onSend`'s
+// attachments argument. Extracted so the width/height threading through
+// `Composer.send()` is unit-testable without mounting the tiptap editor.
+export function pendingFilesToSendAttachments(pendingFiles: PendingFile[]): SendAttachment[] | undefined {
+ if (pendingFiles.length === 0) return undefined
+ return pendingFiles.map((pf) => ({ file: pf.file, width: pf.width, height: pf.height }))
+}
+
// Composer — plain-text TipTap editor with a chat-style @-mention popover.
// Users type raw markdown which MessageBody/Streamdown renders on display.
// Enter sends, Shift+Enter adds a newline; while the mention popover is open
@@ -52,7 +62,7 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe
// for DM composers. Always provided by the caller — empty array is fine,
// the popup just shows nothing on `/`.
channelRefCandidates?: ChannelRefCandidate[]
- onSend?: (markdown: string, attachments?: File[], mentionType?: MentionType) => void
+ onSend?: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => void
onCreateThread?: () => void
onTyping?: () => void
// when set, shows a "Replying to X" bar above the input
@@ -230,8 +240,7 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe
if (!editor || (editor.isEmpty && pendingFiles.length === 0)) return
const markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n" }).trim()
const mentionType = detectMentionType(markdown)
- const files = pendingFiles.length > 0 ? pendingFiles.map((pf) => pf.file) : undefined
- onSend?.(markdown, files, mentionType)
+ onSend?.(markdown, pendingFilesToSendAttachments(pendingFiles), mentionType)
editor.commands.clearContent()
setPendingFiles([])
setMentionPopup(EMPTY_MENTION_STATE)
diff --git a/src/web/src/components/community/dividers.tsx b/src/web/src/components/community/dividers.tsx
index 5e1e36420..cf92e93c7 100644
--- a/src/web/src/components/community/dividers.tsx
+++ b/src/web/src/components/community/dividers.tsx
@@ -13,8 +13,12 @@ export function DateDivider({ label }: { label: string }) {
export function NewDivider() {
// The row's height tracks the separator line only; the "New" pill is taken
// out of flow so its taller box doesn't push messages apart.
+ // `data-new-divider` lets `useScrollAnchor`'s mount effect center on this
+ // element itself via `querySelector`, instead of the whole message row
+ // (date divider + full message content) that used to be the only
+ // `[data-msg-id]`-selectable target — see use-scroll-anchor.ts.
return (
- <div className="relative my-1 flex items-center">
+ <div data-new-divider className="relative my-1 flex items-center">
<Separator className="flex-1 bg-destructive/60" />
<span
className="pointer-events-none absolute right-0 top-1/2 -translate-y-1/2 rounded-sm bg-destructive px-1.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-white"
diff --git a/src/web/src/components/community/member-list.test.ts b/src/web/src/components/community/member-list.test.ts
new file mode 100644
index 000000000..2d2f8c004
--- /dev/null
+++ b/src/web/src/components/community/member-list.test.ts
@@ -0,0 +1,49 @@
+import { describe, it, expect } from "vitest"
+import { computeDuplicateNames } from "./member-list"
+import type { Member } from "./_types"
+
+const member = (id: string, name: string, discriminator?: string): Member => ({
+ id,
+ userId: id,
+ name,
+ discriminator,
+ avatar: name[0],
+ status: "online",
+ sub: "",
+ role: "member",
+})
+
+describe("computeDuplicateNames", () => {
+ it("flags both members when two share a name", () => {
+ const members = [member("m1", "Alex", "0001"), member("m2", "Alex", "0002")]
+ const dupes = computeDuplicateNames(members)
+ expect(dupes.has("alex")).toBe(true)
+ })
+
+ it("is case-insensitive — 'Alex' and 'alex' still collide", () => {
+ const members = [member("m1", "Alex", "0001"), member("m2", "alex", "0002")]
+ const dupes = computeDuplicateNames(members)
+ expect(dupes.has("alex")).toBe(true)
+ })
+
+ it("leaves a unique name unflagged", () => {
+ const members = [member("m1", "Alex", "0001"), member("m2", "Bob", "0002")]
+ const dupes = computeDuplicateNames(members)
+ expect(dupes.has("alex")).toBe(false)
+ expect(dupes.has("bob")).toBe(false)
+ })
+
+ it("returns an empty set for an empty roster", () => {
+ expect(computeDuplicateNames([]).size).toBe(0)
+ })
+
+ it("flags a name shared by three or more members", () => {
+ const members = [
+ member("m1", "Alex", "0001"),
+ member("m2", "Alex", "0002"),
+ member("m3", "Alex", "0003"),
+ ]
+ const dupes = computeDuplicateNames(members)
+ expect(dupes.has("alex")).toBe(true)
+ })
+})
diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsx
index 2f59b0f79..7d71ef843 100644
--- a/src/web/src/components/community/member-list.tsx
+++ b/src/web/src/components/community/member-list.tsx
@@ -45,6 +45,22 @@ function groupMembers(members: Member[]): { label: string; list: Member[] }[] {
].filter((g) => g.list.length > 0)
}
+// Same disambiguation convention as the @-mention popover (`rankMentionItems`
+// in mention-extension.ts) — a member's name is flagged only when it collides
+// (case-insensitively) with another member's name in the same list, so a
+// caller can show the `#0042` discriminator solely for ambiguous rows.
+// Exported for unit testing without rendering the virtualized list.
+export function computeDuplicateNames(members: Member[]): Set<string> {
+ const counts = new Map<string, number>()
+ for (const m of members) {
+ const key = m.name.toLowerCase()
+ counts.set(key, (counts.get(key) ?? 0) + 1)
+ }
+ const dupes = new Set<string>()
+ for (const [key, count] of counts) if (count >= 2) dupes.add(key)
+ return dupes
+}
+
// Flatten grouped members into a single (header|row) stream so the virtualizer
// measures both kinds. Preserves the existing Owner / Admin / Online / Offline
// grouping — sticky headers become one row of the virtual list.
@@ -101,6 +117,7 @@ export function MemberList({
}, [query, onSearch])
const items = useMemo(() => flattenGroups(members), [members])
+ const duplicateNames = useMemo(() => computeDuplicateNames(members), [members])
const scrollRef = useRef<HTMLDivElement>(null)
const sentinelRef = useRef<HTMLDivElement>(null)
@@ -188,6 +205,7 @@ export function MemberList({
<MemberRow
mem={item.member}
canManage={canManage}
+ showDiscriminator={duplicateNames.has(item.member.name.toLowerCase())}
onOpenProfile={onOpenProfile}
onSetRole={onSetRole}
onKick={setKickTarget}
@@ -212,12 +230,18 @@ export function MemberList({
function MemberRow({
mem,
canManage,
+ showDiscriminator,
onOpenProfile,
onSetRole,
onKick,
}: {
mem: Member
canManage: boolean
+ // True when another member currently in the list shares this name
+ // (case-insensitive) — mirrors the @-mention popover's disambiguation
+ // rule (see `rankMentionItems`) so the two surfaces agree on when a
+ // `#0042` discriminator is worth showing.
+ showDiscriminator: boolean
onOpenProfile?: OpenProfile
onSetRole?: (name: string, role: Role) => void
onKick: (name: string) => void
@@ -227,14 +251,19 @@ function MemberRow({
<ContextMenuTrigger
render={
<button
- onClick={(e) => onOpenProfile?.(mem.name, e)}
+ onClick={(e) => onOpenProfile?.(mem.name, e, undefined, mem.userId)}
className="flex w-full items-center gap-3 rounded-md px-2 py-2 hover:bg-accent"
/>
}
>
<Avatar label={mem.avatar} size={32} presence={mem.status} dim={mem.status === "offline"} />
<div className="min-w-0 flex-1 text-left">
- <div className={`truncate text-sm leading-tight ${mem.status === "offline" ? "text-muted-foreground" : ""}`}>{mem.name}</div>
+ <div className={`truncate text-sm leading-tight ${mem.status === "offline" ? "text-muted-foreground" : ""}`}>
+ {mem.name}
+ {showDiscriminator && mem.discriminator && (
+ <span className="text-muted-foreground">#{mem.discriminator}</span>
+ )}
+ </div>
{hasStatus(mem.statusEmoji, mem.statusText) && (
<div className="truncate text-xs leading-tight text-muted-foreground">{mem.statusEmoji} {mem.statusText}</div>
)}
diff --git a/src/web/src/components/community/message-body.test.ts b/src/web/src/components/community/message-body.test.ts
new file mode 100644
index 000000000..12ea16758
--- /dev/null
+++ b/src/web/src/components/community/message-body.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { MessageBody } from "./message-body"
+
+// Regression test for the bug MD_LITERAL_TAGS included "spoiler" fixed:
+// Streamdown's `literalTagContent` flattens every descendant of a listed
+// tag into one text node. `mention`/`channelref` are leaf nodes so that's
+// harmless, but a spoiler must preserve nested markdown children — this
+// drives the full Streamdown pipeline (not just the mdast layer covered by
+// spoiler-syntax.test.ts) to prove the nested `<strong>` survives.
+describe("MessageBody — spoiler nested formatting (full Streamdown pipeline)", () => {
+ it("keeps a nested <strong> intact after expanding a spoiler that wraps bold text", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageBody, { text: "||I think **this** is neat||" }),
+ )
+ })
+
+ // The spoiler renders as a clickable button (see inline-marks.tsx's
+ // `Spoiler`); expand it, then confirm the bold span Streamdown renders
+ // for `**this**` (`<span data-streamdown="strong">`) survived as a real
+ // child element — not flattened into the button's own text content.
+ const button = renderer!.root.findByType("button")
+ act(() => {
+ button.props.onClick()
+ })
+
+ const bold = renderer!.root.findAll(
+ (node) => node.props["data-streamdown"] === "strong",
+ )
+ expect(bold).toHaveLength(1)
+ expect(bold[0].children.join("")).toBe("this")
+ })
+
+ it("still hides/expands a plain spoiler with no nested formatting (regression)", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageBody, { text: "||secret||" }),
+ )
+ })
+
+ const button = renderer!.root.findByType("button")
+ expect(button.children.join("")).toBe("secret")
+ })
+})
diff --git a/src/web/src/components/community/message-body.tsx b/src/web/src/components/community/message-body.tsx
index 56286d881..52df7d33a 100644
--- a/src/web/src/components/community/message-body.tsx
+++ b/src/web/src/components/community/message-body.tsx
@@ -1,9 +1,11 @@
import { useMemo } from "react"
import { Streamdown } from "streamdown"
+import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from "rehype-sanitize"
+import { harden } from "rehype-harden"
+import type { PluggableList } from "unified"
import { mermaid, cjk, math } from "@/lib/streamdown-plugins"
+import { chatSyntaxPlugin, chatSyntaxHandlers } from "@/lib/community/chat-syntax-plugin"
import {
- escapeHtml,
- preprocessMarkdown,
extractInviteTokens,
MD_ALLOWED_TAGS,
MD_LITERAL_TAGS,
@@ -12,35 +14,101 @@ import {
import { CommunityInviteCard } from "./community-invite-card"
import type { OpenProfile } from "./_types"
+// The sanitize schema Streamdown builds internally when `allowedTags` is
+// left at its default merge path (verified against Streamdown 2.5.0's
+// compiled source): `defaultSchema` + `protocols.href` gains `"tel"` +
+// `attributes.code` gains `"metastring"` (for the shiki code-highlighting
+// metastring), THEN `MD_ALLOWED_TAGS`'s tag names/attributes are merged in.
+// Reproduced here because dropping `rehype-raw` (below) requires supplying a
+// custom `rehypePlugins` array, and Streamdown's `allowedTags`-merge-into-
+// sanitize-schema auto-fire is gated by strict reference equality against
+// Streamdown's own default `rehypePlugins` array — a gate any custom array
+// breaks on purpose, so `allowedTags`/`MD_ALLOWED_TAGS` are NOT passed as a
+// `<Streamdown>` prop below; this schema stands in for that merge instead.
+const SANITIZE_SCHEMA: SanitizeSchema = {
+ ...defaultSchema,
+ protocols: {
+ ...defaultSchema.protocols,
+ href: [...(defaultSchema.protocols?.href ?? []), "tel"],
+ },
+ attributes: {
+ ...defaultSchema.attributes,
+ code: [...(defaultSchema.attributes?.code ?? []), "metastring"],
+ },
+ tagNames: [...(defaultSchema.tagNames ?? []), ...Object.keys(MD_ALLOWED_TAGS)],
+}
+for (const [tag, attrs] of Object.entries(MD_ALLOWED_TAGS)) {
+ SANITIZE_SCHEMA.attributes = { ...SANITIZE_SCHEMA.attributes, [tag]: attrs }
+}
+
+// The exact `rehype-harden` config Streamdown ships as its own default —
+// verified against the compiled source. This is the layer that
+// unconditionally blocks `javascript:`/`data:`/`vbscript:`/`file:` links
+// regardless of any other configuration (see debt record #9's finding —
+// `linkSafety={{ enabled: false }}` below does NOT gate this; it only
+// toggles the AI-content confirm-before-navigating modal).
+const HARDEN_CONFIG = {
+ allowedImagePrefixes: ["*"],
+ allowedLinkPrefixes: ["*"],
+ allowedProtocols: ["*"],
+ defaultOrigin: undefined,
+ allowDataImages: true,
+}
+
+// Hand-rolled replacement for Streamdown's default `rehypePlugins` pipeline
+// (`[rehype-raw, [rehype-sanitize, schema], [rehype-harden, config]]`,
+// verified against the compiled source) with `rehype-raw` dropped — chat-
+// only syntax (spoiler/mention/channelRef) is now parsed as real mdast
+// nodes by `chatSyntaxPlugin` (see the `remarkPlugins`/`remarkRehypeOptions`
+// props below), never spliced into the message string as HTML tags, so
+// there is nothing left for `rehype-raw` to parse. With `rehype-raw` gone,
+// Streamdown's own remark-side fallback (any literal `html`-type mdast node
+// — i.e. raw HTML the user typed, like `<b>bold</b>` — becomes a plain-text
+// node) makes user-typed HTML render as literal text automatically.
+const REHYPE_PLUGINS: PluggableList = [
+ [rehypeSanitize, SANITIZE_SCHEMA],
+ [harden, HARDEN_CONFIG],
+]
+
// Message body renderer. Standard markdown (bold/italic/strike/code/codeblock/quote)
// is rendered natively by streamdown (GFM, matching agent-chat). The shared
// mermaid/math/cjk plugins give parity with the agent bubble (diagrams, KaTeX
// math, CJK spacing) and operate on different constructs than the chat-only
-// syntax (spoilers, @mentions, @everyone/@here, #channels) that's preprocessed
-// into custom tags and mapped to pill components — no custom markdown parser.
+// syntax (spoilers, @mentions, @everyone/@here, #channels) that `chatSyntaxPlugin`
+// parses directly into mdast nodes and maps to pill components — no custom
+// markdown parser, no HTML-string splicing.
//
// Community invite URLs (`/community/invite/<token>`) render inline: the
// URL stays as a plain auto-linked <a> in the message body, and a rich join
// card renders BELOW it. Both surfaces coexist so users can still copy/share
// the raw link even when the card is present.
export function MessageBody({ text, onOpenProfile }: { text: string; onOpenProfile?: OpenProfile }) {
- const inviteTokens = extractInviteTokens(text)
+ const inviteTokens = useMemo(() => extractInviteTokens(text), [text])
const components = useMemo(() => buildMdComponents(onOpenProfile), [onOpenProfile])
return (
<div className="markdown text-[15px] leading-snug">
<Streamdown
parseIncompleteMarkdown={false}
plugins={{ mermaid, cjk, math }}
+ remarkPlugins={[chatSyntaxPlugin]}
+ remarkRehypeOptions={{ handlers: chatSyntaxHandlers }}
+ rehypePlugins={REHYPE_PLUGINS}
+ // Deliberately skips the AI-content confirm-before-navigating modal
+ // — that feature exists for LLM-generated content where a model
+ // could be prompt-injected into emitting a malicious-looking link;
+ // community chat links are typed by the human sender, so a plain
+ // hyperlink click is the expected behavior. Protocol/XSS filtering
+ // is unconditional via `rehype-harden` above, unaffected by this
+ // flag either way.
linkSafety={{ enabled: false }}
controls={{
code: { copy: true, download: false },
table: { copy: true, download: false, fullscreen: true },
}}
- allowedTags={MD_ALLOWED_TAGS}
literalTagContent={MD_LITERAL_TAGS}
components={components}
>
- {preprocessMarkdown(escapeHtml(text))}
+ {text}
</Streamdown>
{inviteTokens.length > 0 && (
// `pb-2` is *inside* the message row so the row's hover tint
diff --git a/src/web/src/components/community/message-list-items.test.ts b/src/web/src/components/community/message-list-items.test.ts
new file mode 100644
index 000000000..c940875c8
--- /dev/null
+++ b/src/web/src/components/community/message-list-items.test.ts
@@ -0,0 +1,222 @@
+import { describe, it, expect } from "vitest"
+import { flattenMessageItems, estimateRowHeight, computeBelowCount } from "./message-list-items"
+import type { Msg } from "./_types"
+
+function msg(overrides: Partial<Msg> & { id: string }): Msg {
+ return {
+ type: "chat",
+ authorName: "Alice",
+ content: "hello",
+ createdAt: "2026-01-01T10:00:00.000Z",
+ ...overrides,
+ }
+}
+
+describe("flattenMessageItems", () => {
+ it("emits one 'message' item per message, plus a date-divider before the first message of a new day", () => {
+ const items = flattenMessageItems([msg({ id: "m1" })], undefined)
+ expect(items.map((i) => i.kind)).toEqual(["date-divider", "message"])
+ })
+
+ it("does not emit a date-divider between two messages on the same day", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", createdAt: "2026-01-01T10:01:00.000Z" }),
+ ],
+ undefined,
+ )
+ expect(items.map((i) => i.kind)).toEqual(["date-divider", "message", "message"])
+ })
+
+ it("emits a second date-divider when the day changes", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", createdAt: "2026-01-02T10:00:00.000Z" }),
+ ],
+ undefined,
+ )
+ expect(items.map((i) => i.kind)).toEqual(["date-divider", "message", "date-divider", "message"])
+ })
+
+ it("emits a new-divider item immediately before the message matching newDividerBefore", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", createdAt: "2026-01-01T10:01:00.000Z" }),
+ ],
+ "m2",
+ )
+ expect(items.map((i) => i.kind)).toEqual(["date-divider", "message", "new-divider", "message"])
+ })
+
+ it("marks a message 'grouped' when it's a same-author chat reply within the grouping window on the same day", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", authorName: "Alice", createdAt: "2026-01-01T10:01:00.000Z" }),
+ ],
+ undefined,
+ )
+ const messageItems = items.filter((i) => i.kind === "message")
+ expect(messageItems[0].m.grouped).toBe(false)
+ expect(messageItems[1].m.grouped).toBe(true)
+ })
+
+ it("does not group across a 7+ minute gap", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", authorName: "Alice", createdAt: "2026-01-01T10:08:00.000Z" }),
+ ],
+ undefined,
+ )
+ const messageItems = items.filter((i) => i.kind === "message")
+ expect(messageItems[1].m.grouped).toBe(false)
+ })
+
+ it("does not group across a different author", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", authorName: "Bob", createdAt: "2026-01-01T10:01:00.000Z" }),
+ ],
+ undefined,
+ )
+ const messageItems = items.filter((i) => i.kind === "message")
+ expect(messageItems[1].m.grouped).toBe(false)
+ })
+
+ it("does not group a reply message even from the same author within the window", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", authorName: "Alice", createdAt: "2026-01-01T10:01:00.000Z", replyTo: { id: "m1", authorName: "Alice", text: "hi" } }),
+ ],
+ undefined,
+ )
+ const messageItems = items.filter((i) => i.kind === "message")
+ expect(messageItems[1].m.grouped).toBe(false)
+ })
+
+ it("does not group a system message even from the same author within the window", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", authorName: "Alice", createdAt: "2026-01-01T10:01:00.000Z", type: "system" }),
+ ],
+ undefined,
+ )
+ const messageItems = items.filter((i) => i.kind === "message")
+ expect(messageItems[1].m.grouped).toBe(false)
+ })
+
+ it("does not group across a date-divider even if the author/window would otherwise match", () => {
+ // Noon-to-noon (rather than a near-midnight boundary) so this holds
+ // regardless of the test runner's local timezone offset — `dateKey`
+ // compares LOCAL calendar days, and a near-midnight UTC pair can land
+ // on the same local day in some timezones.
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T12:00:00.000Z" }),
+ msg({ id: "m2", authorName: "Alice", createdAt: "2026-01-02T12:00:30.000Z" }),
+ ],
+ undefined,
+ )
+ const messageItems = items.filter((i) => i.kind === "message")
+ expect(messageItems[1].m.grouped).toBe(false)
+ })
+
+ it("returns an empty array for no messages", () => {
+ expect(flattenMessageItems([], undefined)).toEqual([])
+ })
+
+ it("gives every item a unique, stable key", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", createdAt: "2026-01-01T10:01:00.000Z" }),
+ ],
+ "m2",
+ )
+ const keys = items.map((i) => i.key)
+ expect(new Set(keys).size).toBe(keys.length)
+ })
+})
+
+describe("estimateRowHeight", () => {
+ it("returns a fixed constant for a date-divider row", () => {
+ const items = flattenMessageItems([msg({ id: "m1" })], undefined)
+ const divider = items.find((i) => i.kind === "date-divider")!
+ expect(estimateRowHeight(divider)).toBeGreaterThan(0)
+ expect(estimateRowHeight(divider)).toBe(estimateRowHeight(divider))
+ })
+
+ it("returns a fixed constant for a new-divider row, distinct in value from an empty message row (dividers are shorter)", () => {
+ const items = flattenMessageItems(
+ [msg({ id: "m1" }), msg({ id: "m2" })],
+ "m2",
+ )
+ const newDivider = items.find((i) => i.kind === "new-divider")!
+ const message = items.find((i) => i.kind === "message")!
+ expect(estimateRowHeight(newDivider)).toBeLessThan(estimateRowHeight(message))
+ })
+
+ it("scales up with longer text content", () => {
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", content: "short" }),
+ msg({ id: "m2", content: "a".repeat(500) }),
+ ],
+ undefined,
+ )
+ const messages = items.filter((i) => i.kind === "message")
+ expect(estimateRowHeight(messages[1])).toBeGreaterThan(estimateRowHeight(messages[0]))
+ })
+
+ it("adds height for an image attachment using its real aspect ratio when width/height are known", () => {
+ const wide = flattenMessageItems(
+ [msg({ id: "m1", content: "", attachments: [{ kind: "image", name: "a.png", url: "/a.png", width: 1600, height: 400 }] })],
+ undefined,
+ ).find((i) => i.kind === "message")!
+ const tall = flattenMessageItems(
+ [msg({ id: "m1", content: "", attachments: [{ kind: "image", name: "a.png", url: "/a.png", width: 400, height: 1600 }] })],
+ undefined,
+ ).find((i) => i.kind === "message")!
+ // A tall (narrow, high) image renders taller within the same max-width
+ // box than a wide (short) image — the estimate must reflect that, not
+ // treat every image attachment as the same fixed addend.
+ expect(estimateRowHeight(tall)).toBeGreaterThan(estimateRowHeight(wide))
+ })
+
+ it("adds a fallback addend for an image attachment with no known dimensions (pre-feature rows)", () => {
+ const withImage = flattenMessageItems(
+ [msg({ id: "m1", content: "", attachments: [{ kind: "image", name: "a.png", url: "/a.png" }] })],
+ undefined,
+ ).find((i) => i.kind === "message")!
+ const withoutImage = flattenMessageItems(
+ [msg({ id: "m1", content: "" })],
+ undefined,
+ ).find((i) => i.kind === "message")!
+ expect(estimateRowHeight(withImage)).toBeGreaterThan(estimateRowHeight(withoutImage))
+ })
+})
+
+describe("computeBelowCount", () => {
+ it("returns 0 when the last visible index is the last item (itemCount - 1)", () => {
+ expect(computeBelowCount(10, 9)).toBe(0)
+ })
+
+ it("returns the count of items strictly after the last visible index", () => {
+ expect(computeBelowCount(10, 6)).toBe(3)
+ })
+
+ it("returns 0 for an empty list (itemCount 0, no items to be 'below')", () => {
+ expect(computeBelowCount(0, -1)).toBe(0)
+ })
+
+ it("clamps to 0 rather than going negative if lastVisibleIndex somehow exceeds the last index", () => {
+ expect(computeBelowCount(5, 10)).toBe(0)
+ })
+})
diff --git a/src/web/src/components/community/message-list-items.ts b/src/web/src/components/community/message-list-items.ts
new file mode 100644
index 000000000..b5fbed47b
--- /dev/null
+++ b/src/web/src/components/community/message-list-items.ts
@@ -0,0 +1,109 @@
+import { dateKey, formatDateLabel } from "./format-time"
+import type { Msg, RenderMsg } from "./_types"
+
+// Pure list-prep logic for the virtualized `MessageList` — split out of
+// `message-list.tsx` (a "use client" component) into its own module with no
+// React/JSX so `use-scroll-anchor.ts` can import `FlatItem`/`estimateRowHeight`
+// /`computeBelowCount` without creating a `message-list.tsx` ↔
+// `use-scroll-anchor.ts` circular import (message-list.tsx also imports
+// `useScrollAnchor` from that file).
+
+// Consecutive messages from the same author cluster (avatar+name suppressed
+// on the second+ row) when they land within this window of each other.
+const MESSAGE_GROUP_WINDOW_MS = 7 * 60 * 1000
+
+// One virtual row per divider or per message — flattened rather than
+// nested into cluster arrays (the pre-virtualization shape) so
+// `@tanstack/react-virtual` can measure/position each row independently.
+// `grouped` (avatar/name suppressed) is still computed against the
+// immediately preceding MESSAGE item, same rule the old `clusters` memo
+// used — just not re-nested into a cluster array afterward.
+export type FlatItem =
+ | { kind: "date-divider"; label: string; key: string }
+ | { kind: "new-divider"; key: string }
+ | { kind: "message"; m: RenderMsg; key: string }
+
+// Flatten a message array into one row per divider/message. Exported for
+// direct unit testing (see message-list.test.ts) — mirrors `member-list.tsx`'s
+// `flattenGroups`/`computeDuplicateNames` pattern of exporting pure list-prep
+// logic out of the component for testability without rendering.
+export function flattenMessageItems(messages: Msg[], newDividerBefore: string | undefined): FlatItem[] {
+ const items: FlatItem[] = []
+ let prev: Msg | null = null
+ for (const m of messages) {
+ const prevDate = prev ? dateKey(prev.createdAt) : ""
+ const curDate = dateKey(m.createdAt)
+ const showDateDivider = !!(curDate && curDate !== prevDate)
+ if (showDateDivider) {
+ items.push({ kind: "date-divider", label: formatDateLabel(m.createdAt!), key: `date:${m.id}` })
+ }
+ if (m.id === newDividerBefore) {
+ items.push({ kind: "new-divider", key: "new-divider" })
+ }
+ const grouped = !!(prev && m.type === "chat" && !m.replyTo && !showDateDivider && prev.authorName === m.authorName
+ && prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < MESSAGE_GROUP_WINDOW_MS)
+ items.push({ kind: "message", m: { ...m, grouped }, key: `msg:${m.id}` })
+ prev = m
+ }
+ return items
+}
+
+// ── Row height estimation ────────────────────────────────────────────────
+// Fast, allocation-light guesses for `useVirtualizer`'s `estimateSize` —
+// corrected after paint via `measureElement`, same as `member-list.tsx`
+// already relies on for its own rows. No precision beyond that is required.
+const DATE_DIVIDER_ESTIMATE_PX = 32
+const NEW_DIVIDER_ESTIMATE_PX = 24
+const MESSAGE_BASE_ESTIMATE_PX = 24
+const CHARS_PER_LINE_ESTIMATE = 55
+const LINE_HEIGHT_ESTIMATE_PX = 20
+const MAX_TEXT_ESTIMATE_PX = 400
+// Attachment images render inside a max-width box (see message.tsx's
+// `max-w-[320px]`) — an aspect-ratio estimate is clamped against that width
+// so a very tall/narrow image doesn't produce an absurd height guess.
+const ATTACHMENT_MAX_WIDTH_PX = 320
+const ATTACHMENT_FALLBACK_ESTIMATE_PX = 200
+const EMBED_ESTIMATE_PX = 120
+const REACTIONS_ESTIMATE_PX = 32
+const THREAD_PREVIEW_ESTIMATE_PX = 36
+
+function estimateTextHeight(content: string | undefined): number {
+ if (!content) return 0
+ const lines = Math.max(1, Math.ceil(content.length / CHARS_PER_LINE_ESTIMATE))
+ return Math.min(lines * LINE_HEIGHT_ESTIMATE_PX, MAX_TEXT_ESTIMATE_PX)
+}
+
+function estimateAttachmentsHeight(m: Msg): number {
+ if (!m.attachments?.length) return 0
+ let total = 0
+ for (const a of m.attachments) {
+ if (a.kind !== "image") continue
+ if (a.width && a.height) {
+ total += Math.round((ATTACHMENT_MAX_WIDTH_PX * a.height) / a.width)
+ } else {
+ total += ATTACHMENT_FALLBACK_ESTIMATE_PX
+ }
+ }
+ return total
+}
+
+// Exported for direct unit testing (see message-list.test.ts).
+export function estimateRowHeight(item: FlatItem): number {
+ if (item.kind === "date-divider") return DATE_DIVIDER_ESTIMATE_PX
+ if (item.kind === "new-divider") return NEW_DIVIDER_ESTIMATE_PX
+ const m = item.m
+ let height = MESSAGE_BASE_ESTIMATE_PX + estimateTextHeight(m.content) + estimateAttachmentsHeight(m)
+ if (m.embeds?.length) height += EMBED_ESTIMATE_PX * m.embeds.length
+ if (m.reactions?.length) height += REACTIONS_ESTIMATE_PX
+ if (m.thread) height += THREAD_PREVIEW_ESTIMATE_PX
+ return height
+}
+
+// ── "↓ N below" pill count ───────────────────────────────────────────────
+// Replaces the pre-virtualization `recomputeBelow`'s DOM-row-walk
+// (`querySelectorAll("[data-msg-id]")` + `offsetTop` comparison) with a
+// plain arithmetic derivation from data `getVirtualItems()` already
+// exposes on every render. Exported for direct unit testing.
+export function computeBelowCount(itemCount: number, lastVisibleIndex: number): number {
+ return Math.max(0, itemCount - 1 - lastVisibleIndex)
+}
diff --git a/src/web/src/components/community/message-list.mount-identity.test.ts b/src/web/src/components/community/message-list.mount-identity.test.ts
new file mode 100644
index 000000000..2c7357e3b
--- /dev/null
+++ b/src/web/src/components/community/message-list.mount-identity.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect, vi } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { MessageList } from "./message-list"
+
+// Confirms Phase 4's core claim with an automated test rather than relying
+// solely on manual DevTools inspection: a `<MessageList>` mount effect
+// fires exactly once across a `loading: true → false` prop transition on
+// the SAME rendered instance (`renderer.update`, not a fresh `.create`) —
+// i.e. the loading→loaded transition is a props change, not an
+// unmount/remount. Uses `react-test-renderer` (works under this repo's
+// `environment: "node"` vitest config, no jsdom needed) with a minimal
+// `createNodeMock` scroll-container stub, since `useScrollAnchor`'s mount
+// effect reads `scrollHeight`/`scrollTop`/`clientHeight` off the DOM ref.
+describe("MessageList — loading→loaded mount identity (Phase 4)", () => {
+ it("does not re-fire the mount-time scroll effect when transitioning loading:true → loading:false on one instance", () => {
+ let scrollToCalls = 0
+ const mockScrollEl = {
+ scrollHeight: 1000,
+ scrollTop: 0,
+ clientHeight: 500,
+ firstElementChild: null,
+ scrollTo: () => { scrollToCalls++ },
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ }
+ const globalWithObservers = globalThis as unknown as {
+ ResizeObserver: unknown
+ IntersectionObserver: unknown
+ }
+ const prevRO = globalWithObservers.ResizeObserver
+ const prevIO = globalWithObservers.IntersectionObserver
+ globalWithObservers.ResizeObserver = class {
+ observe() {}
+ disconnect() {}
+ }
+ globalWithObservers.IntersectionObserver = class {
+ observe() {}
+ disconnect() {}
+ }
+
+ try {
+ const messages = [{ id: "m1", authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }]
+
+ let renderer: TestRenderer.ReactTestRenderer
+ // `createNodeMock` is called for EVERY host node react-test-renderer
+ // renders, not just the scroll container — including the
+ // `<number-flow-react>` custom element the "↓ N" pill's `NumberTicker`
+ // renders. That element's class-component wrapper (`NumberFlowImpl`)
+ // calls `this.el?.willUpdate()`/`didUpdate()` on its ref whenever the
+ // `data` prop changes (see `@number-flow/react`'s
+ // `getSnapshotBeforeUpdate`) — the virtualized `belowCount` now
+ // computes synchronously from virtualizer state, so it can change
+ // value between the two renders below, unlike the pre-virtualization
+ // version (computed async, stayed 0 across both renders in this
+ // test). Discriminate by node type so only the real scroll `<div>`
+ // gets the full scroll-container mock; everything else gets a no-op
+ // stub with the handful of methods any wrapped custom element might
+ // call.
+ const genericMock = { willUpdate: () => {}, didUpdate: () => {}, addEventListener: () => {}, removeEventListener: () => {} }
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageList, { channel: "general", messages: [], loading: true, onOpenThread: vi.fn() }),
+ { createNodeMock: (node) => (node.type === "div" ? mockScrollEl : genericMock) },
+ )
+ })
+
+ // The mount-time initial-scroll action fires once on the initial
+ // mount (with 0 messages, `decideScrollAction` bails without firing —
+ // see the "does not fire on an empty message list" case in
+ // `use-scroll-anchor.test.ts` — so `scrollToCalls` is 0 here).
+ const callsBeforeLoaded = scrollToCalls
+
+ act(() => {
+ renderer!.update(
+ React.createElement(MessageList, { channel: "general", messages, loading: false, onOpenThread: vi.fn() }),
+ )
+ })
+
+ // The mount effect fires exactly once total, on this SAME instance,
+ // when real messages arrive — not twice (which is what a hidden
+ // remount would look like: the effect firing once per instance).
+ expect(scrollToCalls).toBe(callsBeforeLoaded + 1)
+
+ // A second update with the same messages must NOT re-fire the
+ // one-shot mount action again (confirms the gate persisted across
+ // the prop transition — a real remount would reset it, and this
+ // assertion would then fail with `scrollToCalls` incrementing again).
+ act(() => {
+ renderer!.update(
+ React.createElement(MessageList, { channel: "general", messages, loading: false, onOpenThread: vi.fn() }),
+ )
+ })
+ expect(scrollToCalls).toBe(callsBeforeLoaded + 1)
+ } finally {
+ globalWithObservers.ResizeObserver = prevRO
+ globalWithObservers.IntersectionObserver = prevIO
+ }
+ })
+})
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index 5ff97a401..fcbd56820 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -1,14 +1,15 @@
"use client"
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
+import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { ArrowDown } from "lucide-react"
import { DateDivider, NewDivider } from "./dividers"
import { Message } from "./message"
import { TypingIndicator } from "./typing-indicator"
-import { dateKey, formatDateLabel } from "./format-time"
import { ChannelIcon } from "./channel-icon"
import { Skeleton } from "@/components/ui/skeleton"
import { NumberTicker } from "@/components/ui/number-ticker"
+import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"
+import { flattenMessageItems } from "./message-list-items"
import type { Msg, OpenProfile } from "./_types"
// Channel message list — welcome hero, date dividers, messages (with the NEW divider),
@@ -17,7 +18,7 @@ export function MessageList({
channel, messages, loading, pinnedIds, newDividerBefore, typingUsers, onOpenThread, onOpenProfile,
onToggleReaction, onReact,
onReply, onPin, onCreateThread, onCopy, onRetry, onPreviewImage, onDownloadFile,
- resolveUserName, scrollToMessageId, hero, onScrollRoot, viewerUserId, initialScrollReady = true,
+ resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,
hasMore, isFetchingOlder, onLoadOlder,
hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount,
}: {
@@ -41,6 +42,12 @@ export function MessageList({
resolveUserName?: (userId: string) => string
scrollToMessageId?: string | null
hero?: React.ReactNode
+ // Explicit skeleton-shape selector — replaces the old `dm={!!hero}`
+ // inference, which silently misfired the moment a channel-context loading
+ // `hero` was introduced (the skeleton's DM/channel shape and the `hero`
+ // slot are orthogonal concerns; `hero`'s presence was never a reliable
+ // signal for which one this view is).
+ variant?: "channel" | "dm"
/**
* Called with the scroll-root element once it mounts (and `null` on
* unmount). Consumers (e.g. `useChannelWatermark`) use this to observe
@@ -61,8 +68,8 @@ export function MessageList({
// Reverse-infinite scroll. When `hasMore` is true a top sentinel is
// rendered; when it enters the viewport (via IntersectionObserver on the
// scroll root) `onLoadOlder()` fires. The prepended rows are scroll-
- // anchored below (see the useLayoutEffect on head-id changes) so the
- // user's visual position stays fixed.
+ // anchored below (see `useScrollAnchor`) so the user's visual position
+ // stays fixed.
hasMore?: boolean
isFetchingOlder?: boolean
onLoadOlder?: () => void
@@ -84,11 +91,81 @@ export function MessageList({
unreadCount?: number
}) {
const [jumped, setJumped] = useState<string | null>(null)
- const scrollRef = useRef<HTMLDivElement>(null)
- // Tracks whether the mount-time initial-scroll has fired yet. On channel
- // switch (`messages` cleared) we reset it so the new channel gets its own
- // initial scroll.
- const didInitialScrollRef = useRef(false)
+
+ // Flattened one row per divider/message — see `message-list-items.ts`.
+ // Memoized so a re-render triggered by unrelated state (typing indicator
+ // ticks, presence updates, etc.) doesn't re-walk the full message list
+ // every time.
+ const items = useMemo(() => flattenMessageItems(messages, newDividerBefore), [messages, newDividerBefore])
+
+ // The hero ("Beginning of the channel…" copy, or a caller-supplied
+ // `hero` node such as the thread-opener) renders OUTSIDE the virtualized
+ // range, directly above it in the same scroll container — its height must
+ // be measured and fed to `useScrollAnchor` so the virtualizer's
+ // `scrollMargin` accounts for it AND so hero-resize compensation can hold
+ // the viewer's visual position (see `use-scroll-anchor.ts`'s module doc
+ // comment — `scrollMargin` alone does not do this automatically).
+ const heroRef = useRef<HTMLDivElement>(null)
+ const [heroHeight, setHeroHeight] = useState(0)
+ // True once the ResizeObserver below has reported a real height at least
+ // once. Gates `useScrollAnchor`'s mount action — see its `heroMeasured`
+ // doc comment: firing mount before this is true uses `scrollMargin`'s
+ // default (0), which mis-targets the NEW-divider `scrollToIndex` case.
+ // Never reset back to `false` — once real, the hero's height stays a
+ // known quantity even if `hasMore`/`hero` change later and this effect
+ // re-observes.
+ const [heroMeasured, setHeroMeasured] = useState(false)
+ // `isLoading` drives which content renders INSIDE the tree below, rather
+ // than an early `return` producing a structurally different element tree
+ // — the same `<MessageList>` instance (and the same `scrollRef`-bearing
+ // div) stays mounted across the loading→loaded transition (the page-level
+ // fix in the 4 community pages is what stops the unwanted REMOUNT; this
+ // internal change is what keeps the two states on one DOM structure, per
+ // DESIGN.md's "Fade, don't swap" — same dimensions/position/layout flow,
+ // ready for a real crossfade later). Declared here (not further down,
+ // where it's also used) because the hero-measurement effect below needs
+ // it in its dependency array.
+ const isLoading = !!loading && messages.length === 0
+ useEffect(() => {
+ const el = heroRef.current
+ // The hero div doesn't exist in the DOM at all while `isLoading` is
+ // true (it's inside the loading/loaded ternary below) — bails without
+ // measuring, same as before. Critically, `isLoading` is now a dep: the
+ // loading→loaded transition is what makes `heroRef.current` non-null
+ // for the FIRST time, and without `isLoading` in the dep list this
+ // effect would never re-run for that transition when `hasMore`/`hero`
+ // happen to be unchanged across it (the common case — a plain channel
+ // with no thread-opener, `hasMore` staying false on first load) —
+ // `heroMeasured` would then never flip true, and `useScrollAnchor`'s
+ // mount action would wait forever. This was the actual bug behind a
+ // report of "channel refresh flashes at the tail then scrolls to the
+ // top hero, unreads never clear."
+ if (!el) return
+ const ro = new ResizeObserver((entries) => {
+ const h = entries[0]?.borderBoxSize?.[0]?.blockSize ?? el.offsetHeight
+ setHeroHeight(h)
+ setHeroMeasured(true)
+ })
+ ro.observe(el)
+ setHeroHeight(el.offsetHeight)
+ setHeroMeasured(true)
+ return () => ro.disconnect()
+ }, [isLoading, hasMore, hero])
+
+ // All automatic scroll-anchor decisions (mount / self-send / peer-follow /
+ // hero-swap) plus the `useVirtualizer` instance live in this hook — see
+ // `use-scroll-anchor.ts`. Older-message prepend compensation is NOT
+ // decided here — it's delegated to the virtualizer's own `anchorTo: "end"`
+ // config.
+ const { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo: jumpToIndex } = useScrollAnchor({
+ items,
+ newDividerBefore,
+ initialScrollReady,
+ hasMoreNewer,
+ viewerUserId,
+ heroHeight,
+ heroMeasured,
+ })
// Publish the scroll root to interested consumers (watermark observer).
// The callback identity may vary across renders; only re-invoke when the
@@ -97,223 +174,16 @@ export function MessageList({
if (!onScrollRoot) return
onScrollRoot(scrollRef.current)
return () => onScrollRoot(null)
- }, [onScrollRoot])
-
- useEffect(() => {
- if (messages.length === 0) {
- didInitialScrollRef.current = false
- }
- }, [messages.length])
-
- // Mount-time initial scroll — exactly two rules, no auto-follow after:
- // 1. NEW divider present → center it vertically in the viewport.
- // 2. No NEW divider → snap to the bottom.
- // Fires once per mount; deliberately no near-bottom heuristic. If the
- // user has scrolled up, incoming messages do NOT pull the view back —
- // the floating "↓ N" button below is how they return, and the sibling
- // "self-send" effect handles the composer path.
- //
- // Owners key `<MessageList>` on channelId/dmId, so channel switches
- // remount the component and reset this ref — no explicit reset logic
- // needed here.
- //
- // Cold-cache guard (RO watchdog): on a hard reload the browser hasn't
- // decoded any embedded images yet, so `scrollHeight` when the initial
- // scroll fires is the pre-image height. Images arrive over the next
- // few hundred ms and push the target out of view. A ResizeObserver on
- // the scroll container re-invokes the same action on every subsequent
- // layout change, until the user scrolls or 3s elapses. Later mounts
- // (channel switch within session) skip this because the browser image
- // cache is warm and layout is stable on the first frame.
- useLayoutEffect(() => {
- const el = scrollRef.current
- if (!el) return
- if (didInitialScrollRef.current) return
- if (messages.length === 0) return
- // Wait for the owner's async anchor (e.g. useChannelReadStateSnapshot)
- // — running the effect before newDividerBefore is known silently snaps
- // to the bottom and burns the one-shot gate.
- if (!initialScrollReady) return
-
- let action: () => void
- if (newDividerBefore) {
- const target = el.querySelector<HTMLElement>(
- `[data-msg-id="${cssEscape(newDividerBefore)}"]`,
- )
- if (target) {
- // Compute scrollTop manually rather than use `scrollIntoView({
- // block: "center" })`. The scroll root's content lives inside a
- // `flex justify-end min-h-full` wrapper; some engines interpret
- // `block: "center"` against that wrapper's flex flow rather than
- // the scroll root's viewport, and the row lands at the top of
- // the viewport instead of the middle. Bounding-rect delta works
- // regardless of offsetParent since it's viewport-space math.
- // Instant, not smooth — same reason as the self-send effect
- // below: smooth animations race the RO re-pins on some engines
- // and can snap back to the pre-image target.
- action = () => {
- const targetRect = target.getBoundingClientRect()
- const scrollRect = el.getBoundingClientRect()
- const targetTopInScroller = targetRect.top - scrollRect.top + el.scrollTop
- const desired = targetTopInScroller - (el.clientHeight - target.offsetHeight) / 2
- el.scrollTop = Math.max(0, desired)
- }
- } else {
- action = () => el.scrollTo({ top: el.scrollHeight })
- }
- } else {
- action = () => el.scrollTo({ top: el.scrollHeight })
- }
- action()
- didInitialScrollRef.current = true
-
- return watchAsyncGrowth(el, action)
- }, [messages, newDividerBefore, initialScrollReady])
-
- // Rule #3: when the viewer sends a message, snap to the bottom.
- // Tracks the tail message id across renders and only fires when the tail
- // moves AND the new tail is authored by the viewer. `fetchOlder` prepends
- // older rows and leaves the tail id unchanged, so paging up never triggers
- // a jump. Peer sends move the tail but with a different authorId — those
- // stay on the "↓ N" pill path.
- //
- // The tail row can keep growing after the initial scrollTo — images
- // decode, mermaid diagrams render, invite cards resolve — all shove the
- // composer off the viewport. A ResizeObserver on the tail row re-pins to
- // the bottom on every size change, regardless of the source. Bails once
- // the user scrolls away (`wheel` / `touchstart`), so an image loading in
- // the background never yanks a scrolled-up reader.
- const lastTailIdRef = useRef<string | null>(null)
- useLayoutEffect(() => {
- const el = scrollRef.current
- if (!el) return
- if (messages.length === 0) {
- lastTailIdRef.current = null
- return
- }
- const tail = messages[messages.length - 1]
- const prev = lastTailIdRef.current
- lastTailIdRef.current = tail.id
- if (prev === null) return
- if (prev === tail.id) return
- if (!viewerUserId) return
-
- // Self-send: viewer authored the new tail → always follow. Handles the
- // composer path across image/mermaid/invite-card async growth via the
- // RO re-pin below.
- const isSelfSend = tail.authorId === viewerUserId
-
- // Peer follow: someone else sent a message AND the viewer is already at
- // (or near) the bottom → snap to the new tail. If the viewer has
- // scrolled up, we leave the "↓ N" pill to prompt them back down.
- //
- // Gated on `hasMoreNewer === false` (i.e. the loaded window is
- // tail-attached to the present) so a peer message WS-inserted while
- // the viewer is browsing history doesn't yank the view to a message
- // that isn't actually "now". The pill's jump-to-present covers that
- // case.
- let isPeerFollow = false
- if (!isSelfSend) {
- if (hasMoreNewer) return
- const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight
- // 100px window matches the pill's "near bottom" intuition — noise
- // (anti-aliasing, sub-pixel layout) is well below one line height,
- // and a scrolled-up reader is typically many lines above.
- if (distanceFromBottom >= 100) return
- isPeerFollow = true
- }
-
- if (!isSelfSend && !isPeerFollow) return
-
- // Instant, not smooth. `behavior: 'smooth'` conflicts with the RO
- // re-pins below — the browser's ongoing smooth animation and our
- // subsequent instant scrollTo race, and on some engines the smooth
- // animation "wins" by continuing to its stored target after the
- // instant jump lands, snapping the view back up.
- const action = () => el.scrollTo({ top: el.scrollHeight })
- action()
- return watchAsyncGrowth(el, action)
- }, [messages, viewerUserId, hasMoreNewer])
-
- // Reverse-infinite scroll anchor. When older messages prepend (head id
- // changes but tail id stays put), the browser's default is to keep
- // `scrollTop` constant, which visually shoves the user's current row down
- // by the height of the newly-inserted content. We snapshot the pre-commit
- // `scrollHeight` before the messages array updates and, once the DOM
- // reflects the new rows, add the height delta to `scrollTop` so the
- // user's current view stays fixed.
- //
- // Also handles the `hasMore` transition true → false: when a fetchOlder
- // reaches start-of-history the ~32px top sentinel is replaced by the
- // ~120px hero card. `messages` may not have grown at all (start-of-
- // history sometimes returns 0 rows), but the top block gained ~90px and
- // every row below it visibly shifts down. Snapshotting `scrollHeight`
- // across the flip and adding the positive delta pins the viewer's row.
- //
- // Only fires after the mount-time initial scroll has landed
- // (`didInitialScrollRef.current === true`) — otherwise we'd fight the
- // one-shot snap on first mount. Skipped when the tail id changed (that's
- // a self-send or a peer send, handled elsewhere) or when `messages`
- // shrank (channel switch, handled by the length===0 reset above).
- const prevHeadIdRef = useRef<string | null>(null)
- const prevTailIdRef = useRef<string | null>(null)
- const prevScrollHeightRef = useRef<number>(0)
- const prevMessagesLenRef = useRef<number>(0)
- const prevHasMoreRef = useRef<boolean | undefined>(hasMore)
- useLayoutEffect(() => {
- const el = scrollRef.current
- if (!el) {
- prevHeadIdRef.current = messages[0]?.id ?? null
- prevTailIdRef.current = messages[messages.length - 1]?.id ?? null
- prevMessagesLenRef.current = messages.length
- prevScrollHeightRef.current = 0
- prevHasMoreRef.current = hasMore
- return
- }
- const prevHead = prevHeadIdRef.current
- const prevTail = prevTailIdRef.current
- const prevLen = prevMessagesLenRef.current
- const prevHeight = prevScrollHeightRef.current
- const prevHasMore = prevHasMoreRef.current
- const nextHead = messages[0]?.id ?? null
- const nextTail = messages[messages.length - 1]?.id ?? null
- const nextLen = messages.length
- const nextHeight = el.scrollHeight
-
- const olderPrepended =
- prevHead !== null &&
- nextHead !== null &&
- prevHead !== nextHead &&
- nextLen > prevLen
- // Hero swap: `hasMore` flipped true → false while the tail stayed put.
- // Even when 0 rows landed on the last page, the top block grew from
- // sentinel to hero and everything below shifted down.
- const heroSwap =
- prevHasMore === true &&
- hasMore === false &&
- prevTail !== null &&
- prevTail === nextTail
-
- if (
- didInitialScrollRef.current &&
- prevHeight > 0 &&
- (olderPrepended || heroSwap)
- ) {
- const delta = nextHeight - prevHeight
- if (delta > 0) el.scrollTop = el.scrollTop + delta
- }
-
- prevHeadIdRef.current = nextHead
- prevTailIdRef.current = nextTail
- prevMessagesLenRef.current = nextLen
- prevScrollHeightRef.current = nextHeight
- prevHasMoreRef.current = hasMore
- }, [messages, hasMore])
+ }, [onScrollRoot, scrollRef])
// Top sentinel — when it intersects the scroll root's viewport, request the
// next older page. Mirrors the pattern in member-list.tsx: root is the
// scroll container (NOT the page viewport), rootMargin `200px` so the
- // fetch kicks in before the user hits the true edge.
+ // fetch kicks in before the user hits the true edge. Rendered before the
+ // virtualized range (same DOM position the hero occupies when `hasMore`
+ // is false) — this needs NO virtualizer-specific rework: an
+ // IntersectionObserver on a real sentinel node works identically whether
+ // the sibling content is virtualized or not.
const topSentinelRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!onLoadOlder || !hasMore) return
@@ -330,14 +200,14 @@ export function MessageList({
)
observer.observe(el)
return () => observer.disconnect()
- }, [onLoadOlder, hasMore, isFetchingOlder])
+ }, [onLoadOlder, hasMore, isFetchingOlder, scrollRef])
// Bottom sentinel — symmetric to the top one. Only mounted when the loaded
// window is not tail-attached (`hasMoreNewer === true`). Appended rows from
// a newer-fetch prepend to `pages[0]` in cache order → after the sort in
// `mergeMessagesPages` they land at the natural tail of `messages`, which
// grows the container downward and leaves the viewer's scrollTop untouched.
- // No compensating scroll needed.
+ // No compensating scroll needed. Rendered after the virtualized range.
const bottomSentinelRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!onLoadNewer || !hasMoreNewer) return
@@ -354,88 +224,26 @@ export function MessageList({
)
observer.observe(el)
return () => observer.disconnect()
- }, [onLoadNewer, hasMoreNewer, isFetchingNewer])
-
- // Live count of messages sitting below the viewport. Recomputed on scroll,
- // on messages change, and via a ResizeObserver so appended rows update the
- // badge even without a scroll event. `0` means the user is at the bottom
- // (or the list fits entirely in the viewport) — the button hides.
- const [belowCount, setBelowCount] = useState(0)
- const recomputeBelow = useCallback(() => {
- const el = scrollRef.current
- if (!el) {
- setBelowCount(0)
- return
- }
- // Ignore near-bottom noise (a few px off from anti-aliasing / sub-pixel
- // layout counts as "at bottom"). 8px is well below one line's height.
- const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight
- if (distanceFromBottom < 8) {
- setBelowCount(0)
- return
- }
- const rows = el.querySelectorAll<HTMLElement>("[data-msg-id]")
- const viewportBottom = el.scrollTop + el.clientHeight
- let count = 0
- for (const row of rows) {
- if (row.offsetTop >= viewportBottom) count++
- }
- setBelowCount(count)
- }, [])
-
- useEffect(() => {
- const el = scrollRef.current
- if (!el) return
- recomputeBelow()
- el.addEventListener("scroll", recomputeBelow, { passive: true })
- const ro = new ResizeObserver(recomputeBelow)
- ro.observe(el)
- return () => {
- el.removeEventListener("scroll", recomputeBelow)
- ro.disconnect()
- }
- }, [recomputeBelow, messages.length])
-
- const scrollToBottom = useCallback(() => {
- const el = scrollRef.current
- if (!el) return
- el.scrollTo({ top: el.scrollHeight, behavior: "smooth" })
- }, [])
-
- const jumpTo = (id: string) => {
+ }, [onLoadNewer, hasMoreNewer, isFetchingNewer, scrollRef])
+
+ // `jumpTo` — click a reply pill, scroll to (and briefly highlight) an
+ // earlier message. Replaces the old `querySelector('[data-msg-id="..."]')`
+ // + `scrollIntoView` DOM lookup, which only worked if the target row
+ // happened to already be mounted — with virtualization, `useScrollAnchor`'s
+ // `jumpTo` looks the target up by INDEX via `virtualizer.scrollToIndex`
+ // instead. If the target isn't in the currently loaded page window at all,
+ // this is a documented no-op — same limitation the old DOM lookup had (it
+ // also required the row to be loaded, just not further required it to be
+ // within the virtualization window).
+ const jumpTo = useCallback((id: string) => {
setJumped(id)
- document.getElementById(`dpv-${id}`)?.scrollIntoView({ behavior: "smooth", block: "center" })
+ jumpToIndex(id)
window.setTimeout(() => setJumped((v) => (v === id ? null : v)), 1600)
- }
+ }, [jumpToIndex])
useEffect(() => {
if (scrollToMessageId) jumpTo(scrollToMessageId)
- }, [scrollToMessageId])
-
- // Group consecutive messages from the same author into clusters. Memoized
- // so a re-render triggered by unrelated state (typing indicator ticks,
- // presence updates, etc.) doesn't re-walk the full message list every time.
- const clusters = useMemo(() => {
- const result: { messages: { m: Msg; grouped: boolean; showDateDivider: boolean; showNewDivider: boolean }[] }[] = []
- messages.forEach((m, i) => {
- const prev = i > 0 ? messages[i - 1] : null
- const prevDate = prev ? dateKey(prev.createdAt) : ""
- const curDate = dateKey(m.createdAt)
- const showDateDivider = !!(curDate && curDate !== prevDate)
- const grouped = !!(prev && !m.type && !m.replyTo && !showDateDivider && prev.authorName === m.authorName
- && prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < 420_000)
- const entry = { m, grouped, showDateDivider, showNewDivider: m.id === newDividerBefore }
- if (grouped && result.length > 0) {
- result[result.length - 1].messages.push(entry)
- } else {
- result.push({ messages: [entry] })
- }
- })
- return result
- }, [messages, newDividerBefore])
-
- // All hooks must run before any conditional return — rule-of-hooks.
- if (loading && messages.length === 0) return <MessageListSkeleton dm={!!hero} />
+ }, [scrollToMessageId, jumpTo])
// ↓ N pill precedence:
// - When there are messages the client hasn't fetched yet
@@ -455,167 +263,114 @@ export function MessageList({
return (
<div className="relative flex min-h-0 flex-1 flex-col">
<ScrollDownButton
- count={pillCount}
+ count={isLoading ? 0 : pillCount}
mode={jumpMode ? "jump" : "scroll"}
onClick={pillOnClick}
/>
- <TypingIndicator names={typingUsers ?? []} />
+ <TypingIndicator names={isLoading ? [] : typingUsers ?? []} />
<div ref={scrollRef} className="flex-1 overflow-y-auto thin-scrollbar">
<div className="flex min-h-full flex-col justify-end px-4 py-8">
- {/*
- When `hasMore` is true the hero's "Beginning of …" copy would
- lie — there's more history above — so we swap it for the top
- sentinel + inline "Loading older messages…" indicator. Once
- the last page loads (`hasMore === false`) the hero returns
- and reads as "you've reached the top".
- */}
- {hasMore ? (
- <div
- ref={topSentinelRef}
- className="mb-6 flex h-8 items-center justify-center text-xs text-muted-foreground"
- >
- {isFetchingOlder ? "Loading older messages…" : ""}
- </div>
+ {isLoading ? (
+ <MessageListSkeletonContent variant={variant} />
) : (
- <div className="mb-6">
- {hero ?? (
- <>
- <div className="mb-2 grid size-12 place-items-center rounded-full bg-muted/60">
- <ChannelIcon className="text-xl text-muted-foreground" />
+ <>
+ {/*
+ When `hasMore` is true the hero's "Beginning of …" copy would
+ lie — there's more history above — so we swap it for the top
+ sentinel + inline "Loading older messages…" indicator. Once
+ the last page loads (`hasMore === false`) the hero returns
+ and reads as "you've reached the top". Rendered OUTSIDE the
+ virtualized range (real DOM, natural height) — its measured
+ height (`heroRef`'s ResizeObserver, see above) feeds the
+ virtualizer's `scrollMargin` and hero-swap compensation.
+ */}
+ <div ref={heroRef} className="mb-6">
+ {hasMore ? (
+ <div
+ ref={topSentinelRef}
+ className="flex h-8 items-center justify-center text-xs text-muted-foreground"
+ >
+ {isFetchingOlder ? "Loading older messages…" : ""}
</div>
- <h2 className="text-xl font-semibold leading-tight">{channel}</h2>
- <p className="mt-2 text-sm text-muted-foreground">Beginning of the channel. Say hello, share what you&apos;re working on, or drop a link.</p>
- </>
- )}
- </div>
- )}
+ ) : (
+ hero ?? (
+ <>
+ <div className="mb-2 grid size-12 place-items-center rounded-full bg-muted/60">
+ <ChannelIcon className="text-xl text-muted-foreground" />
+ </div>
+ <h2 className="text-xl font-semibold leading-tight">{channel}</h2>
+ <p className="mt-2 text-sm text-muted-foreground">Beginning of the channel. Say hello, share what you&apos;re working on, or drop a link.</p>
+ </>
+ )
+ )}
+ </div>
- {clusters.map((cluster, ci) => (
- <div key={cluster.messages[0].m.id ?? ci}>
- {cluster.messages.map(({ m, grouped, showDateDivider, showNewDivider }) => (
- // `data-msg-id` anchors the IntersectionObserver in
- // `useChannelWatermark` — every rendered row is a candidate
- // for the read pointer. Also used by the mount-time
- // "scroll to New divider" effect above.
- <div key={m.id} data-msg-id={m.id}>
- {showDateDivider && <DateDivider label={formatDateLabel(m.createdAt!)} />}
- {showNewDivider && <NewDivider />}
- <Message
- m={{ ...m, grouped }}
- pinned={pinnedIds?.has(m.id)}
- onOpenThread={onOpenThread}
- onOpenProfile={onOpenProfile}
- onJumpReply={() => m.replyTo && jumpTo(m.replyTo.id)}
- onToggleReaction={onToggleReaction ? (emoji) => onToggleReaction(m.id, emoji) : undefined}
- onReact={onReact ? (emoji) => onReact(m.id, emoji) : undefined}
- onReply={onReply ? () => onReply(m.id) : undefined}
- onPin={onPin ? () => onPin(m.id) : undefined}
- onCreateThread={onCreateThread ? () => onCreateThread(m.id) : undefined}
- onCopy={onCopy ? () => onCopy(m.id) : undefined}
- onRetry={onRetry ? () => onRetry(m.id) : undefined}
- onPreviewImage={onPreviewImage}
- onDownloadFile={onDownloadFile}
- highlighted={jumped === m.id}
- resolveUserName={resolveUserName}
- />
- </div>
- ))}
- </div>
- ))}
+ <div style={{ height: virtualizer.getTotalSize(), position: "relative", width: "100%" }}>
+ {virtualizer.getVirtualItems().map((virtualRow) => {
+ const item = items[virtualRow.index]
+ return (
+ <div
+ key={item.key}
+ data-index={virtualRow.index}
+ ref={virtualizer.measureElement}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ transform: `translateY(${virtualRow.start - virtualizer.options.scrollMargin}px)`,
+ }}
+ >
+ {item.kind === "date-divider" && <DateDivider label={item.label} />}
+ {item.kind === "new-divider" && <NewDivider />}
+ {item.kind === "message" && (
+ // `data-msg-id` anchors the IntersectionObserver in
+ // `useChannelWatermark` — every currently-rendered
+ // row is a candidate for the read pointer (the hook
+ // only ever observes rows that exist in the DOM,
+ // which virtualization doesn't change).
+ <div data-msg-id={item.m.id}>
+ <Message
+ m={item.m}
+ pinned={pinnedIds?.has(item.m.id)}
+ onOpenThread={onOpenThread}
+ onOpenProfile={onOpenProfile}
+ onJumpReply={() => item.m.replyTo && jumpTo(item.m.replyTo.id)}
+ onToggleReaction={onToggleReaction ? (emoji) => onToggleReaction(item.m.id, emoji) : undefined}
+ onReact={onReact ? (emoji) => onReact(item.m.id, emoji) : undefined}
+ onReply={onReply ? () => onReply(item.m.id) : undefined}
+ onPin={onPin ? () => onPin(item.m.id) : undefined}
+ onCreateThread={onCreateThread ? () => onCreateThread(item.m.id) : undefined}
+ onCopy={onCopy ? () => onCopy(item.m.id) : undefined}
+ onRetry={onRetry ? () => onRetry(item.m.id) : undefined}
+ onPreviewImage={onPreviewImage}
+ onDownloadFile={onDownloadFile}
+ highlighted={jumped === item.m.id}
+ resolveUserName={resolveUserName}
+ />
+ </div>
+ )}
+ </div>
+ )
+ })}
+ </div>
- {hasMoreNewer && (
- <div
- ref={bottomSentinelRef}
- className="mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground"
- >
- {isFetchingNewer ? "Loading newer messages…" : ""}
- </div>
+ {hasMoreNewer && (
+ <div
+ ref={bottomSentinelRef}
+ className="mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground"
+ >
+ {isFetchingNewer ? "Loading newer messages…" : ""}
+ </div>
+ )}
+ </>
)}
-
</div>
</div>
</div>
)
}
-// Re-invoke `action` whenever the scroll container's own size changes.
-// Serves both initial scroll (images decoding on a cold browser cache
-// arrive after the first scrollTo — target row was still short at that
-// moment) and self-send (composer stays in view when an image the user
-// just attached finishes decoding).
-//
-// Bails when:
-// - the user scrolls (wheel / touchstart — the only reliable "user
-// intent" signal during async growth; programmatic scroll fires its
-// own `scroll` events, so scrollTop comparisons can't distinguish).
-// - the watchdog window elapses (3s — long enough for large images and
-// mermaid renders, short enough that the effect doesn't linger).
-//
-// rAF coalescing: multiple ResizeObserver fires in the same frame
-// dispatch one `action` call. Without this, several images finishing
-// decode in one layout tick would each call `action` on an intermediate
-// scrollHeight before the browser settles on the final value.
-//
-// Returns a cleanup that owners MUST return from their effect.
-const ASYNC_GROWTH_WINDOW_MS = 3000
-function watchAsyncGrowth(el: HTMLElement, action: () => void): () => void {
- // Observe the scroll container's FIRST child — the content wrapper.
- // The scroll container itself has a fixed (`flex-1`) box; its size
- // doesn't change when children grow. The wrapper does grow, and its
- // border-box growth is what pushes `scrollHeight` up.
- const content = el.firstElementChild as HTMLElement | null
- if (!content) return () => {}
-
- let userIntervened = false
- const markIntervened = () => { userIntervened = true }
- el.addEventListener("wheel", markIntervened, { passive: true })
- el.addEventListener("touchstart", markIntervened, { passive: true })
-
- // Skip the RO's synchronous initial callback (fired once with the
- // current size at observe() time) — otherwise we'd re-run `action`
- // against the pre-growth height and waste a frame.
- let firstCallback = true
- let rafId: number | null = null
- const scheduleAction = () => {
- if (rafId !== null) return
- rafId = requestAnimationFrame(() => {
- rafId = null
- if (userIntervened) return
- action()
- })
- }
- const ro = new ResizeObserver(() => {
- if (firstCallback) { firstCallback = false; return }
- scheduleAction()
- })
- ro.observe(content)
-
- const timeoutId = window.setTimeout(() => {
- ro.disconnect()
- }, ASYNC_GROWTH_WINDOW_MS)
-
- return () => {
- el.removeEventListener("wheel", markIntervened)
- el.removeEventListener("touchstart", markIntervened)
- if (rafId !== null) cancelAnimationFrame(rafId)
- window.clearTimeout(timeoutId)
- ro.disconnect()
- }
-}
-
-// Escape a message id for safe use inside an attribute selector. Message ids
-// are nanoids in production (URL-safe alphabet), but the temp-id path
-// (`temp_<Date.now()>_<rand>`) contains underscores that CSS accepts unescaped
-// too. This is defensive against a future format change — CSS.escape is native
-// in every runtime we ship to, but SSR and older test envs may lack it, so we
-// fall back to a conservative replacer for non-identifier characters.
-function cssEscape(id: string): string {
- if (typeof CSS !== "undefined" && typeof CSS.escape === "function") {
- return CSS.escape(id)
- }
- return id.replace(/[^a-zA-Z0-9_-]/g, "\\$&")
-}
-
// Floating "↓ N" pill that appears when the user has scrolled up and there
// are still messages below the viewport. `count === 0` hides the button
// entirely (fade + slide-down, matches the shared scroll-to-bottom pill's
@@ -658,13 +413,17 @@ function ScrollDownButton({
)
}
-// Loading placeholder for the message list. Mirrors the cluster layout used
-// above (avatar + author line + 1–2 content lines) and sits inside the same
-// flex-justify-end scroll container so the composer and header stay anchored.
-// `dm` swaps the channel-style hero (small round icon + title + caption) for
-// the DM hero shape (larger avatar + bigger title + caption). Kept colocated
-// so changes to hero / row density don't drift between the two.
-function MessageListSkeleton({ dm = false }: { dm?: boolean }) {
+// Loading placeholder content — rendered INSIDE `<MessageList>`'s own
+// scroll-container tree (see `isLoading` above), not as a separately-
+// returned component with its own wrapper divs. This is what makes the
+// loading→loaded transition a props change on one mounted instance rather
+// than a swap between two structurally different trees. `variant` swaps the
+// channel-style hero (small round icon + title + caption) for the DM hero
+// shape (larger avatar + bigger title + caption) — an explicit prop now
+// (previously inferred from `!!hero`, which silently misfired whenever a
+// caller passed a channel-context loading `hero`; `hero` and the skeleton's
+// DM/channel shape are orthogonal concerns).
+function MessageListSkeletonContent({ variant }: { variant: "channel" | "dm" }) {
const clusters: number[][] = [
[220, 140],
[180],
@@ -673,42 +432,38 @@ function MessageListSkeleton({ dm = false }: { dm?: boolean }) {
[200],
]
return (
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="flex-1 overflow-hidden">
- <div className="flex min-h-full flex-col justify-end px-4 py-8">
- <div className="mb-6">
- {dm ? (
- <>
- <Skeleton className="mb-3 size-16 rounded-full" />
- <Skeleton className="h-7 w-48 rounded" />
- <Skeleton className="mt-2 h-3.5 w-72 rounded" />
- </>
- ) : (
- <>
- <Skeleton className="mb-2 size-12 rounded-full" />
- <Skeleton className="h-5 w-40 rounded" />
- <Skeleton className="mt-2 h-3.5 w-80 max-w-full rounded" />
- </>
- )}
- </div>
- <div className="flex flex-col gap-3">
- {clusters.map((lines, i) => (
- <div key={i} className="flex gap-3 pt-1.5">
- <Skeleton className="size-10 shrink-0 rounded-full" />
- <div className="flex min-w-0 flex-1 flex-col gap-2">
- <div className="flex items-center gap-2">
- <Skeleton className="h-4 w-24 rounded" />
- <Skeleton className="h-3 w-14 rounded" />
- </div>
- {lines.map((w, j) => (
- <Skeleton key={j} className="h-3.5 rounded" style={{ width: w }} />
- ))}
- </div>
+ <>
+ <div className="mb-6">
+ {variant === "dm" ? (
+ <>
+ <Skeleton className="mb-3 size-16 rounded-full" />
+ <Skeleton className="h-7 w-48 rounded" />
+ <Skeleton className="mt-2 h-3.5 w-72 rounded" />
+ </>
+ ) : (
+ <>
+ <Skeleton className="mb-2 size-12 rounded-full" />
+ <Skeleton className="h-5 w-40 rounded" />
+ <Skeleton className="mt-2 h-3.5 w-80 max-w-full rounded" />
+ </>
+ )}
+ </div>
+ <div className="flex flex-col gap-3">
+ {clusters.map((lines, i) => (
+ <div key={i} className="flex gap-3 pt-1.5">
+ <Skeleton className="size-10 shrink-0 rounded-full" />
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-4 w-24 rounded" />
+ <Skeleton className="h-3 w-14 rounded" />
</div>
- ))}
+ {lines.map((w, j) => (
+ <Skeleton key={j} className="h-3.5 rounded" style={{ width: w }} />
+ ))}
+ </div>
</div>
- </div>
+ ))}
</div>
- </div>
+ </>
)
}
diff --git a/src/web/src/components/community/message-markdown.test.ts b/src/web/src/components/community/message-markdown.test.ts
index 8c96e304a..ee7c8eaaa 100644
--- a/src/web/src/components/community/message-markdown.test.ts
+++ b/src/web/src/components/community/message-markdown.test.ts
@@ -1,7 +1,5 @@
import { describe, it, expect, vi } from "vitest"
import {
- escapeHtml,
- preprocessMarkdown,
extractInviteTokens,
mentionNameFromText,
buildMdComponents,
@@ -14,152 +12,6 @@ import {
// node, see the other describe blocks in this file).
type MentionElement = { props: { onClick?: (e: unknown) => void } }
-describe("escapeHtml", () => {
- it("neutralizes < and &, keeps > for blockquotes", () => {
- expect(escapeHtml("a < b && c")).toBe("a &lt; b &amp;&amp; c")
- expect(escapeHtml("> quote")).toBe("> quote")
- })
-})
-
-describe("preprocessMarkdown", () => {
- it("wraps spoilers", () => {
- expect(preprocessMarkdown("psst ||secret||")).toBe("psst <spoiler>secret</spoiler>")
- })
-
- it("wraps @user mentions", () => {
- expect(preprocessMarkdown("hi @Lindsay")).toBe("hi <mention>@Lindsay</mention>")
- })
-
- it("wraps a full @name#0042 handle as a single mention token, hiding the discriminator from display but keeping it as a data-tag", () => {
- expect(preprocessMarkdown("hi @Gus#0042")).toBe('hi <mention data-tag="0042">@Gus</mention>')
- })
-
- it("doesn't truncate a 5+ digit run into a false-positive handle", () => {
- expect(preprocessMarkdown("hi @Gus#00423")).toBe("hi <mention>@Gus</mention>#00423")
- })
-
- it("flags @everyone / @here", () => {
- expect(preprocessMarkdown("cc @everyone")).toBe('cc <mention data-everyone="1">@everyone</mention>')
- expect(preprocessMarkdown("@here ping")).toBe('<mention data-everyone="1">@here</mention> ping')
- })
-
- it("the old #channel step/tag no longer exists — #general renders as plain text", () => {
- // Regression guard for the retired legacy chip (plan community-channel-ref.md).
- expect(preprocessMarkdown("see #general")).toBe("see #general")
- expect(preprocessMarkdown("#general")).toBe("#general")
- })
-
- it("wraps /server/channel preceded by a space or at start-of-string into <channelref>, preserving the leading separator outside the tag", () => {
- expect(preprocessMarkdown("see /studio/general")).toBe("see <channelref>/studio/general</channelref>")
- expect(preprocessMarkdown("/studio/general")).toBe("<channelref>/studio/general</channelref>")
- })
-
- it("wraps a hyphenated, single-token name segment (post-slugify server/channel names)", () => {
- expect(preprocessMarkdown("see /Server-Name/general")).toBe(
- "see <channelref>/Server-Name/general</channelref>",
- )
- })
-
- it("leaves text/studio/general (no leading space) untouched", () => {
- expect(preprocessMarkdown("text/studio/general")).toBe("text/studio/general")
- })
-
- it("a 3+-segment docs-style path now wraps its first 2 segments, leaving the rest as trailing text — accepted tradeoff of the broadened single-token-segment charset, not a regression to fix", () => {
- // `CHANNEL_REF_REGEX`'s segment charset is now "anything but whitespace/
- // `/`/`#`" (see its doc comment) so server/channel names round-trip as a
- // single token. A 3-segment docs path shape-matches its first two
- // segments as a ref and leaves the leftover `/segment` as plain text
- // next to it — this degrades gracefully (an unresolvable ref falls back
- // to plain, unstyled text per `channel-ref-pill.tsx`), it doesn't crash
- // or corrupt anything.
- expect(preprocessMarkdown("look at /api/user/123")).toBe(
- "look at <channelref>/api/user</channelref>/123",
- )
- expect(preprocessMarkdown("hit /docs/api/v1 first")).toBe(
- "hit <channelref>/docs/api</channelref>/v1 first",
- )
- })
-
- it("a punctuation-heavy non-ref token now shape-matches and gets wrapped — accepted tradeoff, not a regression to fix", () => {
- // `nginx.conf` has no `/`/`#`/whitespace, so it's a valid single-token
- // channel segment under the broadened charset even though it's not a
- // real channel name; it just fails to resolve and falls back to plain
- // text at render time (`channel-ref-pill.tsx`'s existing miss-fallback).
- expect(preprocessMarkdown("see the config at /etc/nginx.conf")).toBe(
- "see the config at <channelref>/etc/nginx.conf</channelref>",
- )
- })
-
- it("a 2-segment ref followed by punctuation now absorbs the punctuation into the segment (charset no longer excludes it) — accepted tradeoff, not a regression to fix", () => {
- // The old nanoid-only charset excluded `.`/`,`/`)`, so trailing
- // punctuation stayed outside the tag. The new charset only excludes
- // whitespace/`/`/`#`, so it's absorbed into the (still single-token)
- // segment instead. Still not a crash, still degrades to plain text if
- // unresolvable — see the plan's "Known limitations & accepted risks".
- expect(preprocessMarkdown("see /studio/general.")).toBe(
- "see <channelref>/studio/general.</channelref>",
- )
- expect(preprocessMarkdown("visit /studio/general, ok?")).toBe(
- "visit <channelref>/studio/general,</channelref> ok?",
- )
- expect(preprocessMarkdown("(see /studio/general)")).toBe(
- "(see <channelref>/studio/general)</channelref>",
- )
- })
-
- it("wraps the thread form /studio/general/#42", () => {
- expect(preprocessMarkdown("see /studio/general/#42")).toBe(
- "see <channelref>/studio/general/#42</channelref>",
- )
- })
-
- it("leaves @ / # / || / channel-refs inside inline code literal", () => {
- expect(preprocessMarkdown("use `@Lindsay` here")).toBe("use `@Lindsay` here")
- expect(preprocessMarkdown("`#general`")).toBe("`#general`")
- expect(preprocessMarkdown("`||x||`")).toBe("`||x||`")
- expect(preprocessMarkdown("`/studio/general`")).toBe("`/studio/general`")
- })
-
- it("leaves content inside fenced code literal", () => {
- const fenced = "```\n@Lindsay #general /studio/general ||x||\n```"
- expect(preprocessMarkdown(fenced)).toBe(fenced)
- })
-
- it("inserts a blank line before a `> ` quote that follows text", () => {
- expect(preprocessMarkdown("steps:\n> do it")).toBe("steps:\n\n> do it")
- })
-
- it("leaves community invite URLs literal in the body (auto-link handles them) — regression guard for the invite-URL stash fix", () => {
- // Preprocess no longer rewrites invite URLs — they stay as plain text so
- // streamdown auto-links them; the card renders separately via
- // extractInviteTokens. Must round-trip COMPLETELY unchanged (literal
- // equality, not just `.toContain()`) — this confirms invite URLs are
- // stashed BEFORE `CHANNEL_REF_REGEX` runs (which would otherwise
- // shape-match `/community/invite` as a two-segment channel ref and split
- // the URL across a `<channelref>` tag boundary, breaking streamdown's
- // GFM autolink of the whole URL).
- expect(preprocessMarkdown("join /community/invite/abc123XYZ")).toBe(
- "join /community/invite/abc123XYZ",
- )
- })
-
- it("regression guard: the full-origin invite URL form also round-trips unchanged", () => {
- expect(preprocessMarkdown("join https://alook.ai/community/invite/xY9k2vW7aQ")).toBe(
- "join https://alook.ai/community/invite/xY9k2vW7aQ",
- )
- })
-
- it("handles a mix and round-trips stashed code unchanged", () => {
- const input = "Here's the **setup**:\n> Clone the repo\n`pnpm install`\nping @Gus in /studio/dev"
- const out = preprocessMarkdown(input)
- expect(out).toContain("**setup**")
- expect(out).toContain("\n\n> Clone the repo")
- expect(out).toContain("`pnpm install`")
- expect(out).toContain("<mention>@Gus</mention>")
- expect(out).toContain("<channelref>/studio/dev</channelref>")
- })
-})
-
describe("mentionNameFromText", () => {
it("strips the leading @", () => {
expect(mentionNameFromText("@Gus")).toBe("Gus")
diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsx
index 45b9d79d5..b173e98bf 100644
--- a/src/web/src/components/community/message-markdown.tsx
+++ b/src/web/src/components/community/message-markdown.tsx
@@ -2,34 +2,14 @@ import type React from "react"
import { Spoiler, MentionPill } from "./inline-marks"
import { ChannelRefPill } from "./channel-ref-pill"
-// Match a `/server/channel` or `/server/channel/#N` (thread) ref — the CLI's
-// path grammar (`parseRef`/`formatRef` in `community-cli-contract.ts`).
-// Segment charset `[^\s/#]+` (any run of non-whitespace, non-`/`, non-`#`)
-// works because server/channel `name`s are guaranteed free of whitespace/
-// `/`/`#` at creation/rename time (`slugify()`, applied by every write
-// route) — a single-token segment can never be ambiguous, so refs render by
-// display *name* now (see `channel-ref-extension.ts`'s `renderText`)
-// instead of id. The pinned-message form (`#N` directly, no slash) is
-// intentionally not matched — see plan §1 for why.
-//
-// Accepted tradeoff: this broadened charset also shape-matches punctuation-
-// heavy non-ref text that happens to look like a path (e.g. `/etc/nginx.conf`,
-// `a/b/c`) — those just fail to resolve and fall back to plain, unstyled
-// text (`channel-ref-pill.tsx`'s existing miss-fallback), no crash. This is
-// intentional, not a regression to "fix": see the channel-ref-slugification
-// plan's "Known limitations & accepted risks".
-const CHANNEL_REF_REGEX = /(^|\s)(\/[^\s/#]+\/[^\s/#]+(?:\/#\d+)?)/g
-
-// Sentinels for stashing code spans/fences (private-use chars — won't collide with
-// real text or markdown punctuation).
-const S0 = "\u{E000}"
-const S1 = "\u{E001}"
-
// Match `/community/invite/<token>` — with or without an origin.
// - token allows [A-Za-z0-9_-] (nanoid alphabet) and length 6..64 (short + old
// 32-char tokens both fit)
-// - the URL matcher is applied AFTER code fences/spans are stashed, so links
-// inside code stay literal
+// - unrelated to chat-only syntax (mention/spoiler/channelRef, now parsed as
+// real markdown AST nodes by `chat-syntax-plugin.ts`/`spoiler-syntax.ts`) —
+// this regex only extracts invite tokens for the join-card row rendered
+// below the message body; the URL text itself stays untouched and is
+// auto-linked by Streamdown/GFM.
const INVITE_URL_RE = /(https?:\/\/[^\s/]+)?\/community\/invite\/([A-Za-z0-9_-]{6,64})/g
/**
@@ -52,73 +32,24 @@ export function extractInviteTokens(text: string): string[] {
return out
}
-// Neutralize only `<` (and `&`) so user text can't inject our custom tags or raw HTML.
-// `>` is left intact so markdown blockquote syntax (`> quote`) still works — a lone `>`
-// with no matching `<` can't form a tag.
-export const escapeHtml = (s: string) =>
- s.replace(/&/g, "&amp;").replace(/</g, "&lt;")
-
-/**
- * Turn chat-only syntax (spoilers, @mentions, @everyone/@here, #channels) into
- * custom tags streamdown preserves and hands to `components`. Code spans/fences are
- * stashed first so `@`/`#`/`||` inside code stay literal. Pure — exported for tests.
- */
-export function preprocessMarkdown(text: string): string {
- const stash: string[] = []
- const protect = (m: string) => `${S0}${stash.push(m) - 1}${S1}`
- let out = text
- .replace(/```[\s\S]*?```/g, protect) // fenced code
- .replace(/`[^`\n]*`/g, protect) // inline code
- // Stash invite-link URLs BEFORE `CHANNEL_REF_REGEX` runs — `/community/invite/<token>`
- // shape-matches the channel-ref regex too (server="community", channel="invite"),
- // which would otherwise wrap `/community/invite` in a `<channelref>` tag and
- // leave the token as a disconnected trailing text node, breaking streamdown's
- // GFM autolinking of the whole URL. A fresh (non-shared) regex copy avoids
- // inheriting `lastIndex` from `INVITE_URL_RE`/other callers.
- out = out.replace(new RegExp(INVITE_URL_RE.source, "g"), protect)
- out = out
- // CommonMark needs a blank line before a blockquote; chat-style quotes are line-by-line.
- // Insert one so a `> ` that immediately follows text still renders as a quote.
- .replace(/([^\n])\n(> )/g, "$1\n\n$2")
- .replace(/\|\|([\s\S]+?)\|\|/g, (_m, c) => `<spoiler>${c}</spoiler>`)
- // single mention pass so @everyone/@here aren't re-matched inside the tag just inserted.
- // Optional `#0042` discriminator suffix (global handle format) — the
- // `(?!\d)` lookahead stops a 5+-digit run from being truncated into a
- // false-positive handle (e.g. `@Gus#00423` wraps only `@Gus`). The
- // discriminator is consumed here (so it never leaks as unstyled trailing
- // text) and stashed in a `data-tag` attribute, but dropped from the tag's
- // visible *content* — humans only ever see `@name`. Carrying it as a data
- // attribute (rather than discarding it outright) lets a click handler
- // resolve the exact same-named member instead of the first name match
- // (see `buildMdComponents`/`shell-frame.tsx`'s `openProfile`).
- .replace(/@[\w-]+(?:#\d{4}(?!\d))?/g, (m) => {
- if (m === "@everyone" || m === "@here") return `<mention data-everyone="1">${m}</mention>`
- const tagMatch = /#(\d{4})$/.exec(m)
- const bare = m.replace(/#\d{4}$/, "")
- return tagMatch ? `<mention data-tag="${tagMatch[1]}">${bare}</mention>` : `<mention>${bare}</mention>`
- })
- // `/server/channel` refs (see `CHANNEL_REF_REGEX`'s doc comment). Leading
- // boundary `(^|\s)` kept outside the tag, same convention the old
- // `#channel` step used — `" /channel-ref"` matches, `"text/channel-ref"`
- // doesn't. The tag's content is fed straight into `@alook/shared`'s
- // `parseRef` at render time (`channel-ref-pill.tsx`), reusing the exact
- // grammar the backend already uses.
- .replace(CHANNEL_REF_REGEX, (_m, pre, ref) => `${pre}<channelref>${ref}</channelref>`)
- return out.replace(new RegExp(`${S0}(\\d+)${S1}`, "g"), (_m, i) => stash[Number(i)])
-}
-
export const MD_ALLOWED_TAGS = {
spoiler: [],
mention: ["data-everyone", "data-tag"],
channelref: [],
}
-export const MD_LITERAL_TAGS = ["spoiler", "mention", "channelref"]
+// `spoiler` is deliberately excluded — unlike `mention`/`channelref` (leaf
+// nodes whose content is always plain tag text), a spoiler must keep its
+// nested markdown children (e.g. `||**bold**||`). Handing it to Streamdown's
+// `literalTagContent` flattens all descendants into one text node, stripping
+// the nested `<strong>`/`<em>` — see message-body.test.tsx's regression case.
+export const MD_LITERAL_TAGS = ["mention", "channelref"]
-// A mention pill's rendered text is always `@name` (see `preprocessMarkdown`,
-// which already drops the `#0042` discriminator) — this strips the leading
-// `@` and, defensively, any trailing `#dddd` that slips through another path,
-// so the result matches `Member.name`/`Msg.authorName` for the profile-card
-// lookup in shell-frame.tsx's `openProfile`. Exported for tests.
+// A mention pill's rendered text is always `@name` (produced by
+// `chat-syntax-plugin.ts`'s `mentionReplacer`, which already drops the
+// `#0042` discriminator) — this strips the leading `@` and, defensively, any
+// trailing `#dddd` that slips through another path, so the result matches
+// `Member.name`/`Msg.authorName` for the profile-card lookup in
+// shell-frame.tsx's `openProfile`. Exported for tests.
export function mentionNameFromText(text: string): string {
return text.replace(/^@/, "").replace(/#\d{4}$/, "")
}
diff --git a/src/web/src/components/community/message.test.ts b/src/web/src/components/community/message.test.ts
new file mode 100644
index 000000000..20bc24de0
--- /dev/null
+++ b/src/web/src/components/community/message.test.ts
@@ -0,0 +1,24 @@
+import { describe, it, expect } from "vitest"
+import { attachmentAspectRatio } from "./message"
+
+// Reserves the correct CSS aspect-ratio box for an image attachment before
+// it decodes, mirroring the pattern the embed-image `<img>` already uses.
+// Falls back to a neutral "4/3" when a dimension is missing — pre-feature
+// attachment rows (sent before width/height were tracked) have neither.
+describe("attachmentAspectRatio", () => {
+ it("returns 'width/height' when both dimensions are present", () => {
+ expect(attachmentAspectRatio(1920, 1080)).toBe("1920/1080")
+ })
+
+ it("falls back to '4/3' when width is missing", () => {
+ expect(attachmentAspectRatio(undefined, 1080)).toBe("4/3")
+ })
+
+ it("falls back to '4/3' when height is missing", () => {
+ expect(attachmentAspectRatio(1920, undefined)).toBe("4/3")
+ })
+
+ it("falls back to '4/3' when both dimensions are missing", () => {
+ expect(attachmentAspectRatio(undefined, undefined)).toBe("4/3")
+ })
+})
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index 20437b552..fa91a7aff 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -14,14 +14,24 @@ import { EmojiPickerPopover } from "./emoji-picker"
import { NumberTicker } from "@/components/ui/number-ticker"
import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"
import { formatMessageTime } from "./format-time"
-import type { Msg, OpenProfile } from "./_types"
+import type { RenderMsg, OpenProfile } from "./_types"
+
+// Fallback ratio for an attachment image with no known dimensions
+// (pre-feature rows sent before width/height were tracked). A more neutral
+// default than the embed-image branch's "40/21" wide-banner ratio — plain
+// attachments are typically screenshots/photos, not link-preview banners.
+const ATTACHMENT_FALLBACK_ASPECT_RATIO = "4/3"
+
+export function attachmentAspectRatio(width: number | undefined, height: number | undefined): string {
+ return width && height ? `${width}/${height}` : ATTACHMENT_FALLBACK_ASPECT_RATIO
+}
export function Message({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
onToggleReaction, onReact, onReply, onPin, onCreateThread, onCopy, onRetry,
onPreviewImage, onDownloadFile, highlighted, resolveUserName,
}: {
- m: Msg
+ m: RenderMsg
compact?: boolean
pinned?: boolean
onOpenThread: (id: string) => void
@@ -63,7 +73,6 @@ export function Message({
const interactive = !compact && showMenu
const row = (
<div
- id={`dpv-${m.id}`}
className={[
"group relative -mx-2 flex gap-2 rounded px-2 transition-colors",
m.grouped ? "py-0" : "mt-3 pt-1.5 pb-0",
@@ -116,7 +125,7 @@ export function Message({
{m.grouped ? (
<div className="w-10 shrink-0" />
) : (
- <button onClick={(e) => onOpenProfile?.(m.authorName ?? "", e)} className="shrink-0 self-start">
+ <button onClick={(e) => onOpenProfile?.(m.authorName ?? "", e, undefined, m.authorId)} className="shrink-0 self-start">
<Avatar label={m.authorAvatar ?? "?"} size={40} />
</button>
)}
@@ -124,7 +133,7 @@ export function Message({
{!m.grouped && (
<div className="flex items-baseline gap-2">
<button
- onClick={(e) => onOpenProfile?.(m.authorName ?? "", e)}
+ onClick={(e) => onOpenProfile?.(m.authorName ?? "", e, undefined, m.authorId)}
className="text-[15px] font-semibold hover:underline"
style={{ color: m.color ?? "var(--foreground)" }}
>
@@ -146,7 +155,7 @@ export function Message({
onClick={() => onPreviewImage?.(a.url)}
className="block w-fit max-w-[320px] overflow-hidden rounded-md border border-border transition-colors hover:border-primary/40"
>
- <img src={a.url} alt={a.name} className="max-h-50 max-w-[320px] rounded-md object-contain" />
+ <img src={a.url} alt={a.name} className="max-h-50 max-w-[320px] rounded-md object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} />
</button>
) : (
<button
diff --git a/src/web/src/components/community/profile-lookup.test.ts b/src/web/src/components/community/profile-lookup.test.ts
new file mode 100644
index 000000000..4742aadcf
--- /dev/null
+++ b/src/web/src/components/community/profile-lookup.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from "vitest"
+import { resolveProfileTarget } from "./profile-lookup"
+import type { Member, Friend } from "./_types"
+
+function member(overrides: Partial<Member>): Member {
+ return {
+ id: overrides.id ?? "mem_default",
+ userId: overrides.userId ?? "user_default",
+ name: overrides.name ?? "Default",
+ discriminator: overrides.discriminator,
+ avatar: overrides.avatar ?? "D",
+ status: overrides.status ?? "online",
+ sub: overrides.sub ?? "",
+ role: overrides.role ?? "member",
+ }
+}
+
+describe("resolveProfileTarget", () => {
+ it("resolves the exact member by userId when two members share a name — regression for the bug where profile cards collapsed to the first name match", () => {
+ const a = member({ id: "mem_a", userId: "user_a", name: "435669237", discriminator: "7892" })
+ const b = member({ id: "mem_b", userId: "user_b", name: "435669237", discriminator: "3759" })
+ const members = [a, b]
+
+ expect(resolveProfileTarget(members, undefined, { name: "435669237", userId: "user_b" })).toBe(b)
+ expect(resolveProfileTarget(members, undefined, { name: "435669237", userId: "user_a" })).toBe(a)
+ })
+
+ it("falls back to discriminator matching when no userId is available (mention pill case)", () => {
+ const a = member({ id: "mem_a", userId: "user_a", name: "Gus", discriminator: "0042" })
+ const b = member({ id: "mem_b", userId: "user_b", name: "Gus", discriminator: "0099" })
+ const members = [a, b]
+
+ expect(resolveProfileTarget(members, undefined, { name: "Gus", discriminator: "0099" })).toBe(b)
+ })
+
+ it("falls back to the first name match when neither userId nor discriminator is provided (legacy behavior)", () => {
+ const a = member({ id: "mem_a", userId: "user_a", name: "Gus" })
+ const b = member({ id: "mem_b", userId: "user_b", name: "Gus" })
+ const members = [a, b]
+
+ expect(resolveProfileTarget(members, undefined, { name: "Gus" })).toBe(a)
+ })
+
+ it("checks friends when userId doesn't match any member", () => {
+ const friend: Friend = { id: "fr_a", userId: "user_c", name: "Ren", avatar: "R", status: "online", sub: "" }
+ expect(resolveProfileTarget([], [friend], { name: "Ren", userId: "user_c" })).toBe(friend)
+ })
+})
diff --git a/src/web/src/components/community/profile-lookup.ts b/src/web/src/components/community/profile-lookup.ts
new file mode 100644
index 000000000..49243eaec
--- /dev/null
+++ b/src/web/src/components/community/profile-lookup.ts
@@ -0,0 +1,33 @@
+import type { Member, Friend } from "./_types"
+
+/**
+ * Resolves the exact member/friend a profile-card click refers to.
+ *
+ * Priority order — exact-match first, so same-named members never collide:
+ * 1. `userId` — the caller already knows the clicked person's id (member
+ * rows, message authors, thread openers all carry it).
+ * 2. `discriminator` — a mention pill's `#0042` tag; no userId available
+ * there, but the tag still disambiguates an exact same-named person.
+ * 3. Name-only fallback — legacy behavior for callers with neither.
+ *
+ * Extracted from `shell-frame.tsx`'s `openProfile` so this lookup logic can
+ * be unit-tested without spinning up the full shell component (this repo has
+ * no jsdom/testing-library setup for rendering it).
+ */
+export function resolveProfileTarget(
+ members: Member[] | undefined,
+ friends: Friend[] | undefined,
+ target: { name: string; discriminator?: string; userId?: string },
+): Member | Friend | undefined {
+ const { name, discriminator, userId } = target
+ return (userId
+ ? (members ?? []).find((m) => m.userId === userId)
+ ?? (friends ?? []).find((f) => f.userId === userId)
+ : undefined)
+ ?? (discriminator
+ ? (members ?? []).find((m) => m.name === name && m.discriminator === discriminator)
+ ?? (friends ?? []).find((f) => f.name === name && f.discriminator === discriminator)
+ : undefined)
+ ?? (members ?? []).find((m) => m.name === name)
+ ?? (friends ?? []).find((f) => f.name === name)
+}
diff --git a/src/web/src/components/community/right-panel.tsx b/src/web/src/components/community/right-panel.tsx
index 3f4169c38..155556637 100644
--- a/src/web/src/components/community/right-panel.tsx
+++ b/src/web/src/components/community/right-panel.tsx
@@ -8,7 +8,7 @@ import { PanelShell } from "./panel-shell"
import { MemberList } from "./member-list"
import { Message } from "./message"
import { formatRelativeTime } from "./format-time"
-import type { RightPanel, Member, Role, Msg, Thread, OpenProfile } from "./_types"
+import type { RightPanel, Member, Role, Msg, RenderMsg, Thread, OpenProfile } from "./_types"
// Right-panel content router — members / pinned / search / threads. Data via props.
// Always wraps the active section in PanelShell — the surrounding Sheet provides the
@@ -178,7 +178,10 @@ function SearchPanel({ searchResults, initialQuery, showSearchInput, onOpenProfi
</div>
)}
<div className="mb-2 text-xs text-muted-foreground">{searchResults.length} results</div>
- {searchResults.map((m) => <Message key={m.id} m={{ ...m, grouped: false }} compact onOpenThread={() => {}} onOpenProfile={onOpenProfile} />)}
+ {searchResults.map((m) => {
+ const renderMsg: RenderMsg = { ...m, grouped: false }
+ return <Message key={m.id} m={renderMsg} compact onOpenThread={() => {}} onOpenProfile={onOpenProfile} />
+ })}
</PanelShell>
)
}
diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsx
index b10ff9acc..18ecea85b 100644
--- a/src/web/src/components/community/server-settings.tsx
+++ b/src/web/src/components/community/server-settings.tsx
@@ -254,7 +254,7 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad
}}
>
<div className="flex items-center gap-3 rounded-md border border-border bg-card px-4 py-2">
- <button onClick={(e) => onOpenProfile?.(m.name, e)} className="shrink-0">
+ <button onClick={(e) => onOpenProfile?.(m.name, e, undefined, m.userId)} className="shrink-0">
<Avatar label={m.avatar} size={32} presence={m.status} ringColor="var(--card)" />
</button>
<div className="min-w-0 flex-1">
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index 871d5a236..d63665d88 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -21,6 +21,7 @@ import { ImageLightbox } from "./image-lightbox"
import { ImageCropDialog } from "./image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { MobileZone, Presence, Profile, View } from "./_types"
+import { resolveProfileTarget } from "./profile-lookup"
import { signOut } from "@/lib/auth-client"
import { clearPersistedCache } from "@/lib/query-persister"
import { useCommunityStore } from "@/stores/community"
@@ -309,8 +310,8 @@ export function ShellFrame({
// enriches with the profile API. Registered with the community store so
// pages can trigger this from anywhere via `useCommunityStore.uiHandlers`.
const openProfile = useCallback(
- (name: string, e: React.MouseEvent, discriminator?: string) => {
- const isSelf = name === currentUser.name
+ (name: string, e: React.MouseEvent, discriminator?: string, targetUserId?: string) => {
+ const isSelf = targetUserId ? targetUserId === currentUser.id : name === currentUser.name
if (isSelf) {
const data: Profile = {
name: currentUser.name,
@@ -326,15 +327,7 @@ export function ShellFrame({
setProfile({ data, x: e.clientX, y: e.clientY })
return
}
- // A `#0042`-tagged mention pill disambiguates an exact same-named
- // member/friend; without a tag (author-name/avatar clicks, plain
- // `@name` mentions), fall back to the first name match as before.
- const member = (discriminator
- ? (members ?? []).find((m) => m.name === name && m.discriminator === discriminator)
- ?? (friends ?? []).find((f) => f.name === name && f.discriminator === discriminator)
- : undefined)
- ?? (members ?? []).find((m) => m.name === name)
- ?? (friends ?? []).find((f) => f.name === name)
+ const member = resolveProfileTarget(members, friends, { name, discriminator, userId: targetUserId })
const role: string = member && "role" in member ? (member as { role: string }).role : "member"
const about: string = member && "sub" in member && (member as { sub: string }).sub ? (member as { sub: string }).sub : ""
const displayRole = role.charAt(0).toUpperCase() + role.slice(1)
diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsx
index 007b5f10b..9b6f3288f 100644
--- a/src/web/src/components/community/thread-opener.tsx
+++ b/src/web/src/components/community/thread-opener.tsx
@@ -3,6 +3,7 @@
import { MessagesSquare, FileText, Download } from "lucide-react"
import { Avatar } from "./avatar"
import { MessageBody } from "./message-body"
+import { attachmentAspectRatio } from "./message"
import { formatMessageTime } from "./format-time"
import { Skeleton } from "@/components/ui/skeleton"
import { NumberTicker } from "@/components/ui/number-ticker"
@@ -62,7 +63,7 @@ export function ThreadOpener({
<div className="flex gap-3">
<button
- onClick={(e) => onOpenProfile?.(msg.authorName, e)}
+ onClick={(e) => onOpenProfile?.(msg.authorName, e, undefined, msg.authorId)}
className="shrink-0 self-start"
>
<Avatar label={avatarLabel} size={32} />
@@ -70,7 +71,7 @@ export function ThreadOpener({
<div className="min-w-0 flex-1">
<div className="flex items-baseline gap-2">
<button
- onClick={(e) => onOpenProfile?.(msg.authorName, e)}
+ onClick={(e) => onOpenProfile?.(msg.authorName, e, undefined, msg.authorId)}
className="text-sm font-semibold hover:underline"
>
{msg.authorName}
@@ -91,7 +92,7 @@ export function ThreadOpener({
onClick={() => onPreviewImage?.(a.url)}
className="block w-fit max-w-70 overflow-hidden rounded-md border border-border transition-colors hover:border-primary/40"
>
- <img src={a.url} alt={a.name} className="max-h-40 max-w-70 rounded-md object-contain" />
+ <img src={a.url} alt={a.name} className="max-h-40 max-w-70 rounded-md object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} />
</button>
) : (
<button
diff --git a/src/web/src/hooks/community/insert-message-into-cache.test.ts b/src/web/src/hooks/community/insert-message-into-cache.test.ts
new file mode 100644
index 000000000..b11e6f20f
--- /dev/null
+++ b/src/web/src/hooks/community/insert-message-into-cache.test.ts
@@ -0,0 +1,63 @@
+import { describe, it, expect } from "vitest"
+import { insertMessageIntoCache } from "./use-community-ws"
+import type { CommunityMessageCreate } from "@alook/shared"
+
+// `insertMessageIntoCache` is a pure cache-patch function (no React), so it
+// can be imported and tested directly — no need for the file's heavy React
+// shim. The image-attachment branch is one of the silent-drop sites flagged
+// in plans/attachment-image-dimensions.md's plan review.
+describe("insertMessageIntoCache — attachment width/height", () => {
+ const emptyCache = { pages: [{ messages: [] }], pageParams: [null] }
+
+ function baseMessage(overrides: Partial<CommunityMessageCreate["message"]> = {}): CommunityMessageCreate["message"] {
+ return {
+ id: "msg_1",
+ type: "chat",
+ authorId: "author_1",
+ authorName: "Author",
+ authorAvatar: "A",
+ content: "hello",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ ...overrides,
+ }
+ }
+
+ it("carries width/height through onto an image attachment", () => {
+ const msg = baseMessage({
+ attachments: [
+ { id: "a1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
+ ],
+ })
+ const result = insertMessageIntoCache(emptyCache as never, msg)
+ const inserted = result?.pages[0].messages[0]
+ expect(inserted?.attachments).toEqual([
+ { kind: "image", name: "a.png", url: "/a.png", width: 1920, height: 1080 },
+ ])
+ })
+
+ it("leaves width/height undefined for an image attachment with no dimensions on the payload", () => {
+ const msg = baseMessage({
+ attachments: [
+ { id: "a1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000 },
+ ],
+ })
+ const result = insertMessageIntoCache(emptyCache as never, msg)
+ const inserted = result?.pages[0].messages[0]
+ expect(inserted?.attachments).toEqual([
+ { kind: "image", name: "a.png", url: "/a.png", width: undefined, height: undefined },
+ ])
+ })
+
+ it("never adds width/height to a file-kind attachment", () => {
+ const msg = baseMessage({
+ attachments: [
+ { id: "a1", filename: "a.pdf", url: "/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },
+ ],
+ })
+ const result = insertMessageIntoCache(emptyCache as never, msg)
+ const inserted = result?.pages[0].messages[0]
+ expect(inserted?.attachments).toEqual([
+ { kind: "file", name: "a.pdf", url: "/a.pdf", size: "2 KB" },
+ ])
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index a8d0e11f5..4a870f4c8 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -121,12 +121,13 @@ function markFailedById(
/**
* Materialize the attachment view-model from the API attachment shape.
* Mirrors the old context's conversion at `postWithOptimisticInsert`.
+ * Exported for direct unit testing — see `to-attachment-vm.test.ts`.
*/
-function toAttachmentVm(
- a: { url: string; filename: string; contentType: string; size: number },
+export function toAttachmentVm(
+ a: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number },
): Attachment {
const isImage = a.contentType.startsWith("image/")
- if (isImage) return { kind: "image", name: a.filename, url: a.url }
+ if (isImage) return { kind: "image", name: a.filename, url: a.url, width: a.width, height: a.height }
return {
kind: "file",
name: a.filename,
@@ -148,7 +149,7 @@ export type SendMessageArgs = {
content: string
replyToId?: string
mentionType?: MentionType
- attachments?: { url: string; filename: string; contentType: string; size: number }[]
+ attachments?: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]
author: { id: string; name: string; avatar: string }
}
@@ -201,6 +202,7 @@ export function useSendMessage() {
const optimisticAttachments = args.attachments?.map(toAttachmentVm)
const msg: Msg = {
id: tempId,
+ type: "chat",
// #3: stamp the sender's userId onto optimistic rows so
// `useChannelWatermark` recognizes them as self-authored (skip
// client PUT — server-side write path already writes the sender's
@@ -244,7 +246,7 @@ export type SendDmMessageArgs = {
dmId: string
content: string
replyToId?: string
- attachments?: { url: string; filename: string; contentType: string; size: number }[]
+ attachments?: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]
author: { id: string; name: string; avatar: string }
}
@@ -272,6 +274,7 @@ export function useSendDmMessage() {
const optimisticAttachments = args.attachments?.map(toAttachmentVm)
const msg: Msg = {
id: tempId,
+ type: "chat",
// Mirror the channel path: stamp the sender's userId so the
// self-send auto-scroll effect in <MessageList> (gated on
// `tail.authorId === viewerUserId`) recognizes the optimistic row
diff --git a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
new file mode 100644
index 000000000..c983ea5ad
--- /dev/null
+++ b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from "vitest"
+import { toAttachmentVm } from "./messages"
+
+// `toAttachmentVm` materializes the optimistic-send attachment view model
+// from the uploaded-attachment shape. Its image branch must carry
+// width/height through — this is one of the silent-drop sites flagged in
+// plans/attachment-image-dimensions.md's plan review (an object literal
+// omitting an optional field produces no typecheck error).
+describe("toAttachmentVm", () => {
+ it("carries width/height through on an image attachment", () => {
+ const result = toAttachmentVm({
+ url: "/media/a.png",
+ filename: "a.png",
+ contentType: "image/png",
+ size: 1000,
+ width: 1920,
+ height: 1080,
+ })
+ expect(result).toEqual({ kind: "image", name: "a.png", url: "/media/a.png", width: 1920, height: 1080 })
+ })
+
+ it("leaves width/height undefined for an image attachment with no dimensions on file", () => {
+ const result = toAttachmentVm({
+ url: "/media/a.png",
+ filename: "a.png",
+ contentType: "image/png",
+ size: 1000,
+ })
+ expect(result).toEqual({ kind: "image", name: "a.png", url: "/media/a.png", width: undefined, height: undefined })
+ })
+
+ it("never adds width/height to a file-kind attachment", () => {
+ const result = toAttachmentVm({
+ url: "/media/a.pdf",
+ filename: "a.pdf",
+ contentType: "application/pdf",
+ size: 2048,
+ })
+ expect(result).toEqual({ kind: "file", name: "a.pdf", url: "/media/a.pdf", size: "2 KB" })
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/uploads.test.ts b/src/web/src/hooks/community/mutations/uploads.test.ts
new file mode 100644
index 000000000..81e6e1a72
--- /dev/null
+++ b/src/web/src/hooks/community/mutations/uploads.test.ts
@@ -0,0 +1,58 @@
+import { describe, it, expect } from "vitest"
+import { zipUploadResultsWithDimensions } from "./uploads"
+import type { UploadFileResult } from "./uploads"
+
+// The zip must happen BEFORE filtering out failed uploads (`null` results),
+// or indices between `results` and the original `attachments` input array
+// misalign once a failed upload is dropped — see the design note in
+// plans/attachment-image-dimensions.md ("Exact zip transform").
+describe("zipUploadResultsWithDimensions", () => {
+ const upload = (name: string): UploadFileResult => ({
+ url: `/media/${name}`,
+ filename: name,
+ contentType: "image/png",
+ size: 100,
+ })
+
+ it("zips each successful result with its input's width/height, in order", () => {
+ const attachments = [
+ { file: new File(["a"], "a.png"), width: 100, height: 200 },
+ { file: new File(["b"], "b.png"), width: 300, height: 400 },
+ ]
+ const results = [upload("a.png"), upload("b.png")]
+
+ expect(zipUploadResultsWithDimensions(results, attachments)).toEqual([
+ { ...upload("a.png"), width: 100, height: 200 },
+ { ...upload("b.png"), width: 300, height: 400 },
+ ])
+ })
+
+ it("drops a failed upload (null result) without misaligning the remaining zips", () => {
+ const attachments = [
+ { file: new File(["a"], "a.png"), width: 100, height: 200 },
+ { file: new File(["b"], "b.png"), width: 300, height: 400 },
+ { file: new File(["c"], "c.png"), width: 500, height: 600 },
+ ]
+ // Middle upload failed — results[1] is null, but results[0]/[2] must
+ // still zip with attachments[0]/[2], not shift down by one.
+ const results = [upload("a.png"), null, upload("c.png")]
+
+ expect(zipUploadResultsWithDimensions(results, attachments)).toEqual([
+ { ...upload("a.png"), width: 100, height: 200 },
+ { ...upload("c.png"), width: 500, height: 600 },
+ ])
+ })
+
+ it("carries width/height through as undefined for a non-image attachment", () => {
+ const attachments = [{ file: new File(["a"], "a.txt") }]
+ const results = [upload("a.txt")]
+
+ expect(zipUploadResultsWithDimensions(results, attachments)).toEqual([
+ { ...upload("a.txt"), width: undefined, height: undefined },
+ ])
+ })
+
+ it("returns an empty array when there are no attachments", () => {
+ expect(zipUploadResultsWithDimensions([], [])).toEqual([])
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.ts
index fef755070..9dbcab04a 100644
--- a/src/web/src/hooks/community/mutations/uploads.ts
+++ b/src/web/src/hooks/community/mutations/uploads.ts
@@ -24,6 +24,32 @@ export type UploadFileResult = {
size: number
}
+export type UploadedAttachment = UploadFileResult & { width?: number; height?: number }
+
+/**
+ * Zip each upload result back to its ORIGINAL INDEX in the input attachments
+ * array (not by `File` identity — `Promise.all` already preserves input
+ * order regardless of completion order, so a plain index is enough and can't
+ * collide if two attachments happen to share a `File` reference) to pull
+ * width/height in. Dimensions never cross the network to the upload
+ * endpoint; they're only known client-side and get attached here, after the
+ * upload resolves.
+ *
+ * The zip MUST happen before dropping failed (`null`) results, or indices
+ * between `results` and `attachments` misalign once a failed upload is
+ * filtered out — see plans/attachment-image-dimensions.md's "Exact zip
+ * transform" note.
+ */
+export function zipUploadResultsWithDimensions(
+ results: (UploadFileResult | null)[],
+ attachments: { file: File; width?: number; height?: number }[],
+): UploadedAttachment[] {
+ const zipped: (UploadedAttachment | null)[] = results.map((r, i) =>
+ r ? { ...r, width: attachments[i].width, height: attachments[i].height } : null,
+ )
+ return zipped.filter((x): x is UploadedAttachment => x !== null)
+}
+
function uploadPath(target: UploadTarget): string | null {
if (target.threadId) return `/api/community/threads/${target.threadId}/upload`
if (target.dmId) return `/api/community/dm/${target.dmId}/upload`
diff --git a/src/web/src/hooks/community/use-channel-watermark.test.ts b/src/web/src/hooks/community/use-channel-watermark.test.ts
index ef555f4b2..f75386ca2 100644
--- a/src/web/src/hooks/community/use-channel-watermark.test.ts
+++ b/src/web/src/hooks/community/use-channel-watermark.test.ts
@@ -75,6 +75,50 @@ class MockIntersectionObserver {
}
}
+// ── MutationObserver polyfill ────────────────────────────────────────────
+// The virtualized message list mounts/unmounts rows as the user scrolls —
+// no `messages` array change fires, so the IntersectionObserver seed effect
+// never re-runs. The hook wires a MutationObserver on the scroll root to
+// observe rows added after the initial seed; this polyfill records the
+// callback and lets a test fire an "added node" batch.
+type MutationObserverInstance = {
+ callback: MutationCallback
+ disconnected: boolean
+}
+let mutationObservers: MutationObserverInstance[] = []
+
+class MockMutationObserver {
+ private inst: MutationObserverInstance
+ constructor(callback: MutationCallback) {
+ this.inst = { callback, disconnected: false }
+ mutationObservers.push(this.inst)
+ }
+ observe() {}
+ disconnect() {
+ this.inst.disconnected = true
+ }
+ takeRecords(): MutationRecord[] {
+ return []
+ }
+}
+
+// Simulate the virtualizer appending new row nodes to the scroll container.
+function fireAddedNodes(nodes: Element[]) {
+ for (const obs of mutationObservers) {
+ if (obs.disconnected) continue
+ obs.callback(
+ [
+ {
+ type: "childList",
+ addedNodes: nodes as unknown as NodeList,
+ removedNodes: [] as unknown as NodeList,
+ } as unknown as MutationRecord,
+ ],
+ undefined as unknown as MutationObserver,
+ )
+ }
+}
+
function fireIntersections(
entries: Array<{ target: Element; isIntersecting: boolean; intersectionRatio: number }>,
) {
@@ -116,6 +160,7 @@ function resetHarness() {
pendingEffects = []
effectCleanups = []
observers = []
+ mutationObservers = []
advanceSpy.mockClear()
flushSpy.mockClear()
}
@@ -133,9 +178,18 @@ function makeRoot(): HTMLElement {
}
// Fabricate a message-row element. `dataset.msgId` mirrors the DOM API the
-// hook reads at intersection time.
+// hook reads at intersection time. `matches`/`querySelectorAll` mirror the
+// Element API the MutationObserver-added-node scan reads: the row element
+// itself carries `data-msg-id`, so `matches("[data-msg-id]")` is true and a
+// self-scan returns itself.
function makeRow(id: string): Element {
- return { dataset: { msgId: id } } as unknown as Element
+ const el = {
+ dataset: { msgId: id },
+ nodeType: 1,
+ matches: (sel: string) => sel === "[data-msg-id]",
+ querySelectorAll: () => [] as unknown as Iterable<Element>,
+ }
+ return el as unknown as Element
}
// The hook queries `root.querySelectorAll("[data-msg-id]")` to seed the
@@ -151,6 +205,8 @@ beforeEach(() => {
// "function" inside the hook.
;(globalThis as unknown as { IntersectionObserver: unknown }).IntersectionObserver =
MockIntersectionObserver
+ ;(globalThis as unknown as { MutationObserver: unknown }).MutationObserver =
+ MockMutationObserver
})
describe("useChannelWatermark — visibility gate", () => {
@@ -271,6 +327,41 @@ describe("useChannelWatermark — monotone forward", () => {
})
})
+describe("useChannelWatermark — virtualized rows (mounted on scroll, no messages change)", () => {
+ it("observes a row the virtualizer mounts AFTER the initial seed, so scrolling clears unreads", async () => {
+ // Regression: with the virtualized message list, rows enter the DOM as
+ // the user scrolls — the `messages` array reference doesn't change, so
+ // the seed effect (deps: [channelId, messages, scrollRootEl, viewerId])
+ // never re-runs and the newly-mounted row is never observed. The read
+ // watermark then never advances past whatever was on-screen at mount,
+ // so "NEW" unreads never clear on scroll. A MutationObserver on the
+ // scroll root must pick up the added row and observe it.
+ const useHook = await loadHook()
+ const root = makeRoot()
+ // At mount only the top row is rendered by the virtualizer.
+ const topRow = makeRow("m_1")
+ attachRows(root, [topRow])
+ useHook({
+ channelId: "ch_1",
+ messages: [
+ { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
+ { id: "m_2", createdAt: "2026-07-01T00:00:05.000Z", authorId: "u_other" },
+ ],
+ scrollRootEl: root,
+ })
+ flushEffects()
+
+ // User scrolls down — the virtualizer mounts m_2's row into the DOM.
+ // No `messages` change fires; only a DOM mutation.
+ const scrolledRow = makeRow("m_2")
+ fireAddedNodes([scrolledRow])
+
+ // The newly-mounted row must now be observed and advance the watermark.
+ fireIntersections([{ target: scrolledRow, isIntersecting: true, intersectionRatio: 0.9 }])
+ expect(advanceSpy).toHaveBeenCalledWith("ch_1", "m_2")
+ })
+})
+
describe("useChannelWatermark — self-authored skip", () => {
it("does NOT advance for a message authored by the viewer", async () => {
const useHook = await loadHook()
diff --git a/src/web/src/hooks/community/use-channel-watermark.ts b/src/web/src/hooks/community/use-channel-watermark.ts
index d5ede6c95..9a1ab33ea 100644
--- a/src/web/src/hooks/community/use-channel-watermark.ts
+++ b/src/web/src/hooks/community/use-channel-watermark.ts
@@ -112,7 +112,34 @@ export function useChannelWatermark({
const nodes = scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]")
nodes.forEach((n) => observer.observe(n))
- return () => observer.disconnect()
+ // The message list is virtualized — rows mount/unmount as the user
+ // scrolls, WITHOUT any `messages` array change to re-run this effect.
+ // A one-time `querySelectorAll` seed above therefore only ever covers
+ // the rows on-screen at mount; a row scrolled into view later would
+ // never be observed, so its read watermark would never advance and the
+ // "NEW" unread badge would never clear on scroll. Watch the scroll root
+ // for added `[data-msg-id]` nodes and observe them as they appear. No-op
+ // in environments without MutationObserver (SSR / older test shims).
+ let mutationObserver: MutationObserver | null = null
+ if (typeof MutationObserver !== "undefined") {
+ mutationObserver = new MutationObserver((records) => {
+ for (const record of records) {
+ record.addedNodes.forEach((node) => {
+ // Element nodes only (skip text/comment nodes — nodeType 1).
+ if ((node as { nodeType?: number }).nodeType !== 1) return
+ const el = node as Element
+ if (el.matches?.("[data-msg-id]")) observer.observe(el)
+ el.querySelectorAll?.("[data-msg-id]").forEach((n) => observer.observe(n))
+ })
+ }
+ })
+ mutationObserver.observe(scrollRootEl, { childList: true, subtree: true })
+ }
+
+ return () => {
+ observer.disconnect()
+ mutationObserver?.disconnect()
+ }
}, [channelId, messages, scrollRootEl, viewerId])
// On unmount / channel switch, flush the debounce so the last-watched
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 6fb0c099c..ddb64f227 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -12,6 +12,7 @@ import type {
CommunityMessageCreate,
CommunityReactionAdd,
CommunityMemberJoin,
+ CommunityMemberUpdate,
CommunityMachineCreated,
CommunityMachineStatus,
CommunityPresenceUpdate,
@@ -602,6 +603,83 @@ describe("useCommunityWs — member events", () => {
expect(cache?.pages[0].members.map((m) => m.userId)).toEqual(["u_1"])
expect(cache?.pages[0].total).toBe(1)
})
+
+ it("a self-rename (member.update with userId + changes.nickname) patches authorName in every cached channel/DM message list", async () => {
+ await mountHook()
+
+ // Two message caches — one channel, one DM — each with a message
+ // authored by the renamed user and one by someone else. Both should
+ // update; the other author's row must stay untouched.
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{
+ messages: [
+ { id: "m_1", authorId: "u_renamed", authorName: "OldName", content: "hi" },
+ { id: "m_2", authorId: "u_other", authorName: "Someone Else", content: "yo" },
+ ],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+ capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {
+ pages: [{
+ messages: [
+ { id: "m_3", authorId: "u_renamed", authorName: "OldName", content: "sup" },
+ ],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+
+ const event: CommunityMemberUpdate = {
+ type: "community:member.update",
+ serverId: "srv_1",
+ memberId: "mem_1",
+ userId: "u_renamed",
+ changes: { nickname: "NewName" },
+ }
+ capturedOnMessage!(event)
+
+ const channelCache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; authorName: string }[] }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ expect(channelCache?.pages[0].messages).toEqual([
+ { id: "m_1", authorId: "u_renamed", authorName: "NewName", content: "hi" },
+ { id: "m_2", authorId: "u_other", authorName: "Someone Else", content: "yo" },
+ ])
+
+ const dmCache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; authorName: string }[] }[]
+ }>(communityKeys.dmMessages("dm_1"))
+ expect(dmCache?.pages[0].messages).toEqual([
+ { id: "m_3", authorId: "u_renamed", authorName: "NewName", content: "sup" },
+ ])
+ })
+
+ it("a role-only member.update (no userId/nickname) does not touch any message cache", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{
+ messages: [{ id: "m_1", authorId: "u_1", authorName: "Name", content: "hi" }],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+
+ const event: CommunityMemberUpdate = {
+ type: "community:member.update",
+ serverId: "srv_1",
+ memberId: "mem_1",
+ changes: { role: "admin" },
+ }
+ capturedOnMessage!(event)
+
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; authorName: string }[] }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ expect(cache?.pages[0].messages).toEqual([
+ { id: "m_1", authorId: "u_1", authorName: "Name", content: "hi" },
+ ])
+ })
})
describe("useCommunityWs — friend + mention → invalidate", () => {
@@ -1203,7 +1281,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
).toBe(true)
})
- it("invalidates the focused channel's message + read-state queries + inbox on reconnect", async () => {
+ it("invalidates the focused channel's messages + inbox on reconnect, but NOT the read-state snapshot", async () => {
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().subscribe({ channelId: "ch_focus" })
@@ -1216,7 +1294,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const invalidatedKeys = spy.mock.calls.map(
(c) => c[0]?.queryKey as unknown[] | undefined,
)
- // Focused channel messages
+ // Focused channel messages — a legitimate top-up refetch that keeps data.
expect(
invalidatedKeys.some(
(k) =>
@@ -1227,7 +1305,12 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
k[3] === "messages",
),
).toBe(true)
- // Focused channel read-state snapshot
+ // Read-state snapshot MUST NOT be invalidated: the snapshot hook latches
+ // its first value (gcTime: 0, frozen ref) so a refetch can't move the
+ // "New" divider — it only flips `isFetching` back to true, which the
+ // channel page reads as loading and flashes a second skeleton mid-mount
+ // (the "skeleton → content → skeleton → top hero" refresh bug). See
+ // `handleReconnect`'s comment in use-community-ws.ts.
expect(
invalidatedKeys.some(
(k) =>
@@ -1237,7 +1320,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
k[2] === "ch_focus" &&
k[3] === "read-state-snapshot",
),
- ).toBe(true)
+ ).toBe(false)
// Inbox
expect(
invalidatedKeys.some(
@@ -1246,7 +1329,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
).toBe(true)
})
- it("invalidates the focused DM's message + read-state queries on reconnect", async () => {
+ it("invalidates the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })
@@ -1269,6 +1352,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
k[3] === "messages",
),
).toBe(true)
+ // Read-state snapshot MUST NOT be invalidated — same rationale as the
+ // channel case (mirrors `useChannelReadStateSnapshot`'s freeze contract).
expect(
invalidatedKeys.some(
(k) =>
@@ -1278,7 +1363,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
k[2] === "dm_focus" &&
k[3] === "read-state-snapshot",
),
- ).toBe(true)
+ ).toBe(false)
})
it("only invalidates the focused scope — no channel invalidation when only a DM is focused", async () => {
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 696a98b69..989153362 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -139,7 +139,7 @@ type PageCache = InfiniteData<MessagesPage>
* or DM stream — the same slot `useSendMessage` writes optimistic rows into,
* so the two paths converge. Deduplicates by id.
*/
-function insertMessageIntoCache(
+export function insertMessageIntoCache(
cache: PageCache | undefined,
msg: CommunityMessageCreate["message"] | CommunityDmNewMessage["message"],
): PageCache | undefined {
@@ -150,7 +150,7 @@ function insertMessageIntoCache(
const attachments: Attachment[] | undefined = msg.attachments?.map((a) => {
const isImage = a.contentType?.startsWith("image/")
return isImage
- ? { kind: "image", name: a.filename, url: a.url }
+ ? { kind: "image", name: a.filename, url: a.url, width: a.width ?? undefined, height: a.height ?? undefined }
: {
kind: "file",
name: a.filename,
@@ -159,6 +159,7 @@ function insertMessageIntoCache(
}
})
const isSystem = "type" in msg && (msg as { type?: string }).type === "system"
+ const systemKind = "systemKind" in msg ? (msg as { systemKind?: "thread" }).systemKind : undefined
const authorName = "authorName" in msg ? msg.authorName : "Unknown"
const authorAvatar = "authorAvatar" in msg ? msg.authorAvatar : undefined
const authorId = "authorId" in msg ? msg.authorId : undefined
@@ -169,7 +170,11 @@ function insertMessageIntoCache(
authorAvatar: authorAvatar || avatarInitial(authorName ?? ""),
content: msg.content,
createdAt: msg.createdAt,
- ...(isSystem ? { type: "system" as const } : {}),
+ // Non-system branch is explicit ("chat", not omitted) — `Msg.type` is a
+ // required, exhaustive discriminator (#12); a DM message (the other
+ // union member here) never carries `type` at all, and also renders as
+ // an ordinary chat row, so it gets the same explicit fallback.
+ ...(isSystem ? { type: "system" as const, ...(systemKind ? { systemKind } : {}) } : { type: "chat" as const }),
...(replyTo ? { replyTo } : {}),
...(attachments?.length ? { attachments } : {}),
// #3: preserve authorId so `useChannelWatermark` can skip self-authored
@@ -207,6 +212,31 @@ function insertMessageIntoCache(
}
}
+/**
+ * Patch every cached message authored by `userId` to the renamed
+ * `authorName` — `authorName` is a snapshot field written at send time
+ * (`communityMessage` doesn't store it; the live JOIN is `message.ts`'s
+ * `authorName: user.name`), so nothing else updates already-loaded message
+ * rows after a self-rename. Only touches rows that are actually cached in
+ * this client (open/previously-open channels & DMs) — a channel never
+ * loaded this session picks up the new name for free on its first real
+ * fetch, since that IS the live JOIN.
+ */
+function patchAuthorNameInCache(cache: PageCache | undefined, userId: string, newName: string): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ if (!p.messages.some((m) => m.authorId === userId)) return p
+ touched = true
+ return {
+ ...p,
+ messages: p.messages.map((m) => (m.authorId === userId ? { ...m, authorName: newName } : m)),
+ }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+}
+
function applyReactionToCache(
cache: PageCache | undefined,
event: CommunityReactionAdd | CommunityReactionRemove,
@@ -695,6 +725,25 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
key,
(cache) => patchCacheUpdate(cache, event),
)
+ // A self-rename carries `userId` + `changes.nickname` — patch
+ // every cached message list's `authorName` snapshot for that
+ // author. A role-only change has no `userId`/`nickname`, so
+ // this is a no-op for that case.
+ if (event.userId && event.changes.nickname) {
+ const userId = event.userId
+ const newName = event.changes.nickname
+ for (const cacheEntry of queryClient.getQueryCache().findAll({
+ predicate: (q) =>
+ q.queryKey[0] === "community"
+ && (q.queryKey[1] === "channel" || q.queryKey[1] === "dm")
+ && q.queryKey[3] === "messages",
+ })) {
+ queryClient.setQueryData<PageCache | undefined>(
+ cacheEntry.queryKey,
+ (cache) => patchAuthorNameInCache(cache, userId, newName),
+ )
+ }
+ }
}
// Membership just changed → the invite dialog's "friends who aren't
// in this server" list is stale. Cheap invalidation because the
@@ -853,9 +902,27 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// (or the tab was suspended). Invalidating the focused scope's message
// query on reconnect fires a top-up refetch — TanStack re-runs every
// page's `pageParam`, so anchor windows and newest-tail windows both
- // catch up without any client-side `?since` bookkeeping. Read-state
- // snapshots (also persisted) are invalidated too so the NEW divider
- // matches the fresh server watermark on reconnect.
+ // catch up without any client-side `?since` bookkeeping.
+ //
+ // Do NOT invalidate the read-state SNAPSHOT here. The snapshot hook
+ // (`useChannelReadStateSnapshot`, `gcTime: 0`) latches its first resolved
+ // value in a ref and deliberately never updates it during a mount — that
+ // freeze is what keeps the "New" divider pinned while the watermark
+ // advances. Re-fetching it can't move the divider (the ref ignores the new
+ // value), but it DOES flip the hook's `isFetching` back to true, which the
+ // channel/DM pages read as `lastReadMessageId: undefined` →
+ // `useMessages.isLoading: true` → the whole view drops back to the loading
+ // skeleton. Because `onReconnect` fires once even on a fresh page load (a
+ // StrictMode / refresh double-connect makes the socket's second open run
+ // it ~1.5s in), that surfaced as a SECOND skeleton flash mid-mount —
+ // "skeleton → content → skeleton → scroll to the top hero" (the empty
+ // round-trip also burned the message list's one-shot mount-scroll gate;
+ // see `use-scroll-anchor.ts`'s re-arm-on-empty branch). Verified via live
+ // Playwright page-level trace: the second skeleton window lines up exactly
+ // with `readSnapshotFetching` going true at t≈1.75s. The message-query
+ // invalidation below is the legitimate top-up and keeps its data on
+ // screen; the divider is already correct from the first (frozen) snapshot,
+ // so nothing here needs the snapshot refetched.
const handleReconnect = useCallback(() => {
queryClient.invalidateQueries({ queryKey: communityKeys.machines() })
const sub = useCommunityStore.getState().subscription
@@ -863,17 +930,11 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
void queryClient.invalidateQueries({
queryKey: communityKeys.channelMessages(sub.channelId),
})
- void queryClient.invalidateQueries({
- queryKey: communityKeys.channelReadStateSnapshot(sub.channelId),
- })
}
if (sub.dmConversationId) {
void queryClient.invalidateQueries({
queryKey: communityKeys.dmMessages(sub.dmConversationId),
})
- void queryClient.invalidateQueries({
- queryKey: communityKeys.dmReadStateSnapshot(sub.dmConversationId),
- })
}
// Inbox counts also need a refetch — unreads and mentions could have
// grown while offline and the live invalidator only fires on incoming
diff --git a/src/web/src/hooks/community/use-dm-watermark.test.ts b/src/web/src/hooks/community/use-dm-watermark.test.ts
index a2b59e4d2..d2b17ae72 100644
--- a/src/web/src/hooks/community/use-dm-watermark.test.ts
+++ b/src/web/src/hooks/community/use-dm-watermark.test.ts
@@ -75,6 +75,47 @@ class MockIntersectionObserver {
}
}
+// ── MutationObserver polyfill ────────────────────────────────────────────
+// Mirrors the channel-side harness — the virtualized list mounts rows on
+// scroll with no `messages` change, so the hook watches the scroll root via
+// MutationObserver to observe rows added after the initial seed.
+type MutationObserverInstance = {
+ callback: MutationCallback
+ disconnected: boolean
+}
+let mutationObservers: MutationObserverInstance[] = []
+
+class MockMutationObserver {
+ private inst: MutationObserverInstance
+ constructor(callback: MutationCallback) {
+ this.inst = { callback, disconnected: false }
+ mutationObservers.push(this.inst)
+ }
+ observe() {}
+ disconnect() {
+ this.inst.disconnected = true
+ }
+ takeRecords(): MutationRecord[] {
+ return []
+ }
+}
+
+function fireAddedNodes(nodes: Element[]) {
+ for (const obs of mutationObservers) {
+ if (obs.disconnected) continue
+ obs.callback(
+ [
+ {
+ type: "childList",
+ addedNodes: nodes as unknown as NodeList,
+ removedNodes: [] as unknown as NodeList,
+ } as unknown as MutationRecord,
+ ],
+ undefined as unknown as MutationObserver,
+ )
+ }
+}
+
function fireIntersections(
entries: Array<{ target: Element; isIntersecting: boolean; intersectionRatio: number }>,
) {
@@ -114,6 +155,7 @@ function resetHarness() {
pendingEffects = []
effectCleanups = []
observers = []
+ mutationObservers = []
advanceSpy.mockClear()
flushSpy.mockClear()
}
@@ -128,7 +170,13 @@ function makeRoot(): HTMLElement {
}
function makeRow(id: string): Element {
- return { dataset: { msgId: id } } as unknown as Element
+ const el = {
+ dataset: { msgId: id },
+ nodeType: 1,
+ matches: (sel: string) => sel === "[data-msg-id]",
+ querySelectorAll: () => [] as unknown as Iterable<Element>,
+ }
+ return el as unknown as Element
}
function attachRows(root: HTMLElement, rows: Element[]) {
@@ -140,6 +188,35 @@ beforeEach(() => {
resetHarness()
;(globalThis as unknown as { IntersectionObserver: unknown }).IntersectionObserver =
MockIntersectionObserver
+ ;(globalThis as unknown as { MutationObserver: unknown }).MutationObserver =
+ MockMutationObserver
+})
+
+describe("useDmWatermark — virtualized rows (mounted on scroll, no messages change)", () => {
+ it("observes a row the virtualizer mounts AFTER the initial seed, so scrolling clears unreads", async () => {
+ // Parity with the channel hook — see its equivalent test. Rows enter the
+ // DOM on scroll with no `messages` change; a MutationObserver on the
+ // scroll root must observe them so the read watermark advances.
+ const useHook = await loadHook()
+ const root = makeRoot()
+ const topRow = makeRow("m_1")
+ attachRows(root, [topRow])
+ useHook({
+ dmId: "dm_1",
+ messages: [
+ { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
+ { id: "m_2", createdAt: "2026-07-01T00:00:05.000Z", authorId: "u_other" },
+ ],
+ scrollRootEl: root,
+ })
+ flushEffects()
+
+ const scrolledRow = makeRow("m_2")
+ fireAddedNodes([scrolledRow])
+
+ fireIntersections([{ target: scrolledRow, isIntersecting: true, intersectionRatio: 0.9 }])
+ expect(advanceSpy).toHaveBeenCalledWith("dm_1", "m_2")
+ })
})
describe("useDmWatermark — visibility gate", () => {
diff --git a/src/web/src/hooks/community/use-dm-watermark.ts b/src/web/src/hooks/community/use-dm-watermark.ts
index 17e0559ae..64fcd573e 100644
--- a/src/web/src/hooks/community/use-dm-watermark.ts
+++ b/src/web/src/hooks/community/use-dm-watermark.ts
@@ -99,7 +99,33 @@ export function useDmWatermark({
const nodes = scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]")
nodes.forEach((n) => observer.observe(n))
- return () => observer.disconnect()
+ // The message list is virtualized — rows mount/unmount as the user
+ // scrolls, WITHOUT any `messages` array change to re-run this effect.
+ // Mirrors the channel hook: watch the scroll root for added
+ // `[data-msg-id]` nodes and observe them so a row scrolled into view
+ // after mount still advances the read watermark. See
+ // `useChannelWatermark` for the full rationale — kept identical for
+ // divider/read-pointer parity.
+ let mutationObserver: MutationObserver | null = null
+ if (typeof MutationObserver !== "undefined") {
+ mutationObserver = new MutationObserver((records) => {
+ for (const record of records) {
+ record.addedNodes.forEach((node) => {
+ // Element nodes only (skip text/comment nodes — nodeType 1).
+ if ((node as { nodeType?: number }).nodeType !== 1) return
+ const el = node as Element
+ if (el.matches?.("[data-msg-id]")) observer.observe(el)
+ el.querySelectorAll?.("[data-msg-id]").forEach((n) => observer.observe(n))
+ })
+ }
+ })
+ mutationObserver.observe(scrollRootEl, { childList: true, subtree: true })
+ }
+
+ return () => {
+ observer.disconnect()
+ mutationObserver?.disconnect()
+ }
}, [dmId, messages, scrollRootEl, viewerId])
// On unmount / DM switch, flush the debounce so the last-watched message
diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.ts
index bbcb947ce..babd50f3c 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -24,7 +24,9 @@ export type OpenerPayload = {
authorName: string
authorAvatar: string
content: string
- type?: "system"
+ // Required, exhaustive (#12) — matches `mapMessageForApi`'s new output
+ // shape (this payload is fed by that same endpoint, `GET /api/community/messages/:id`).
+ type: "chat" | "system"
createdAt: string
attachments?: Msg["attachments"]
embeds?: Msg["embeds"]
diff --git a/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts
new file mode 100644
index 000000000..e0426cb66
--- /dev/null
+++ b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts
@@ -0,0 +1,274 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { useMessages } from "./use-messages"
+import { communityKeys } from "@/lib/query-keys"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+})
+
+function Capture({ onRender, channelId, lastReadMessageId }: {
+ onRender: (messageIds: string[]) => void
+ channelId: string | null
+ lastReadMessageId?: string | null
+}) {
+ const result = useMessages(channelId, { lastReadMessageId })
+ onRender(result.messages.map((m) => m.id))
+ return null
+}
+
+async function flush(ms = 50) {
+ // Let queued microtasks (the mocked fetch's resolved promise, TanStack's
+ // internal state updates, the `.then()` in Fix 3's out-of-band merge)
+ // settle between renders.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, ms))
+ })
+}
+
+// Poll until `predicate` holds (or we give up), advancing timers each round.
+// The out-of-band merge chain (mocked fetch `setTimeout(20)` → `.then()` →
+// `setQueryData` → re-render) can take longer than a single fixed `flush(50)`
+// on a slow/coarse-timer CI runner (this test was Windows-flaky under a bare
+// `flush()`); polling makes the wait environment-independent instead of
+// betting on a fixed sleep.
+async function waitForSettled(predicate: () => boolean, tries = 40) {
+ for (let i = 0; i < tries; i++) {
+ if (predicate()) return
+ await flush(10)
+ }
+}
+
+describe("useMessages — Fix 3 anchor re-validation", () => {
+ it("fresh cache with a drifted anchor: merges the new anchor page into the already-loaded history instead of discarding it", async () => {
+ // `staleTime: Infinity` — without this, mounting a new observer over
+ // already-cached data triggers TanStack's own implicit refetch-on-mount
+ // (default staleTime is 0), which would race with and consume the
+ // mocked fetch response meant for Fix 3's own decision path. That
+ // implicit refetch is real production behavior but orthogonal to what
+ // this test isolates: Fix 3's stale-vs-fresh branch choice.
+ const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
+ const key = communityKeys.channelMessages("ch_1")
+
+ // Pre-seed the cache as if the channel had already loaded a window not
+ // containing "m_new_anchor" — and mark it as freshly fetched (`dataUpdatedAt`
+ // well within STALE_HYDRATED_CACHE_MS), simulating "returned from a
+ // Thread after the watermark advanced" rather than a stale IDB hydration.
+ // Explicit timestamps OLDER than the new anchor page's — these rows must
+ // survive the merge and sort BEFORE the new page's rows.
+ queryClient.setQueryData(key, {
+ pages: [{
+ messages: [
+ { id: "m_old_1", createdAt: "2026-06-30T23:59:58.000Z" },
+ { id: "m_old_2", createdAt: "2026-06-30T23:59:59.000Z" },
+ ],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ }],
+ pageParams: [{ mode: "anchor", anchor: "m_old_anchor" }],
+ })
+
+ // `mergeMessagesPages` sorts by (createdAt, id) — stamp explicit
+ // timestamps so the resulting order isn't an accident of id string
+ // comparison. Resolves on a real delay (not immediately) so React
+ // commits the pre-fetch render as its own frame — a synchronously
+ // resolving mock lets React batch the "cleared to empty" and "refetch
+ // landed" updates into a single commit, hiding the very regression
+ // this test exists to catch (see the intermediate-blank-frame
+ // assertion below).
+ apiFetchMock.mockImplementation(
+ () => new Promise((resolve) => setTimeout(() => resolve({
+ messages: [
+ { id: "m_new_1", createdAt: "2026-07-01T00:00:01.000Z" },
+ { id: "m_new_anchor", createdAt: "2026-07-01T00:00:02.000Z" },
+ { id: "m_new_2", createdAt: "2026-07-01T00:00:03.000Z" },
+ ],
+ hasMoreOlder: true,
+ hasMoreNewer: true,
+ }), 20)),
+ )
+
+ const renderedMessageIds: string[][] = []
+ act(() => {
+ TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: (ids) => { renderedMessageIds.push(ids) },
+ channelId: "ch_1",
+ lastReadMessageId: "m_new_anchor",
+ }),
+ ),
+ )
+ })
+
+ // Wait until the out-of-band merge has landed (5 rows) rather than a fixed
+ // sleep — see `waitForSettled`.
+ await waitForSettled(() => (renderedMessageIds.at(-1)?.length ?? 0) === 5)
+
+ // The old (valid) window must never be cleared to empty at any point in
+ // between — every render either shows the old window or the merged one,
+ // never a 0-length list. `resetQueries` would fail this: it clears
+ // `pages` to `undefined` synchronously (one render with 0 messages)
+ // before the refetch resolves.
+ for (const ids of renderedMessageIds) {
+ expect(ids.length).toBeGreaterThan(0)
+ }
+ // The final, settled render shows the OLD history merged with the NEW
+ // anchor window — proving the previously-loaded pages survive the
+ // re-anchor instead of being discarded wholesale.
+ expect(renderedMessageIds.at(-1)).toEqual([
+ "m_old_1", "m_old_2", "m_new_1", "m_new_anchor", "m_new_2",
+ ])
+ // Exactly one out-of-band fetch — no `resetQueries`-triggered refetch
+ // through the normal queryFn path.
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/ch_1/messages?anchor=m_new_anchor",
+ )
+ })
+
+ it("fresh cache with THREE pages (anchor + two fetchOlder pages): merge keeps every page's messages, not just the newest fetch", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
+ const key = communityKeys.channelMessages("ch_multi")
+
+ // Simulate a user who scrolled up and loaded two older pages via
+ // `fetchOlder`, in addition to the original anchor-window page. Pages
+ // are stored oldest-last per this hook's `getNextPageParam` convention
+ // (`pages[0]` = anchor/newest, later pages = progressively older).
+ queryClient.setQueryData(key, {
+ pages: [
+ { messages: [{ id: "m_anchor_old", createdAt: "2026-07-01T00:00:05.000Z" }], hasMoreOlder: true, hasMoreNewer: false },
+ { messages: [{ id: "m_older_1", createdAt: "2026-07-01T00:00:03.000Z" }], hasMoreOlder: true, hasMoreNewer: false },
+ { messages: [{ id: "m_older_2", createdAt: "2026-07-01T00:00:01.000Z" }], hasMoreOlder: false, hasMoreNewer: false },
+ ],
+ pageParams: [
+ { mode: "anchor", anchor: "m_anchor_old" },
+ { mode: "older", cursor: "x" },
+ { mode: "older", cursor: "y" },
+ ],
+ })
+
+ apiFetchMock.mockImplementation(
+ () => new Promise((resolve) => setTimeout(() => resolve({
+ messages: [{ id: "m_new_anchor", createdAt: "2026-07-01T00:00:10.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: true,
+ }), 20)),
+ )
+
+ const renderedMessageIds: string[][] = []
+ act(() => {
+ TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: (ids) => { renderedMessageIds.push(ids) },
+ channelId: "ch_multi",
+ lastReadMessageId: "m_new_anchor",
+ }),
+ ),
+ )
+ })
+
+ // Wait until the merge has folded in the new anchor (4 rows total).
+ await waitForSettled(() => (renderedMessageIds.at(-1)?.length ?? 0) === 4)
+
+ // All three pre-existing pages' messages must survive the merge — this
+ // is the exact regression the user hit: scrolling up loads history via
+ // `fetchOlder`, then a later Fix 3 re-anchor must not silently drop it.
+ const finalIds = renderedMessageIds.at(-1)
+ expect(finalIds).toContain("m_older_1")
+ expect(finalIds).toContain("m_older_2")
+ expect(finalIds).toContain("m_anchor_old")
+ expect(finalIds).toContain("m_new_anchor")
+ expect(finalIds).toEqual([
+ "m_older_2", "m_older_1", "m_anchor_old", "m_new_anchor",
+ ])
+ // Merge collapses to a single page.
+ const cache = queryClient.getQueryData(key) as { pages: unknown[] } | undefined
+ expect(cache?.pages.length).toBe(1)
+ })
+
+ it("stale cache with a drifted anchor: swaps in the fresh anchor window WITHOUT ever clearing to an empty list", async () => {
+ // `staleTime: Infinity` — without this, mounting a new observer over
+ // already-cached data triggers TanStack's own implicit refetch-on-mount
+ // (default staleTime is 0), which would race with and consume the
+ // mocked fetch response meant for Fix 3's own decision path. That
+ // implicit refetch is real production behavior but orthogonal to what
+ // this test isolates: Fix 3's stale-vs-fresh branch choice.
+ const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
+ const key = communityKeys.channelMessages("ch_2")
+
+ queryClient.setQueryData(key, {
+ pages: [{ messages: [{ id: "m_old_1", createdAt: "2026-06-30T00:00:00.000Z" }], hasMoreOlder: false, hasMoreNewer: false }],
+ pageParams: [{ mode: "anchor", anchor: "m_old_anchor" }],
+ })
+ // Force `dataUpdatedAt` far in the past — well beyond STALE_HYDRATED_CACHE_MS
+ // (30s) — simulating a cross-session IDB-hydrated cache.
+ const state = queryClient.getQueryState(key)
+ if (state) state.dataUpdatedAt = Date.now() - 60_000
+
+ // Resolve on a real delay (not synchronously) so React commits the
+ // pre-swap render as its own frame — otherwise React batches the "old
+ // window" and "fresh window" updates into one commit and hides the very
+ // empty-frame regression this test guards against. See the fresh-cache
+ // test above for the same rationale.
+ apiFetchMock.mockImplementation(
+ () => new Promise((resolve) => setTimeout(() => resolve({
+ messages: [{ id: "m_fresh_anchor", createdAt: "2026-07-01T00:00:00.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ }), 20)),
+ )
+
+ const renderedMessageIds: string[][] = []
+ act(() => {
+ TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: (ids) => { renderedMessageIds.push(ids) },
+ channelId: "ch_2",
+ lastReadMessageId: "m_fresh_anchor",
+ }),
+ ),
+ )
+ })
+
+ // Wait until the fresh anchor window has replaced the stale one.
+ await waitForSettled(() => renderedMessageIds.at(-1)?.[0] === "m_fresh_anchor")
+
+ // The stale window must never clear to empty mid-mount — that empty
+ // frame is what surfaced as the "second skeleton flash then jump to the
+ // top hero" bug. `resetQueries` (the old behavior) clears `pages` to
+ // `undefined` synchronously (one 0-length render) before the refetch
+ // lands; this assertion fails under that path.
+ for (const ids of renderedMessageIds) {
+ expect(ids.length).toBeGreaterThan(0)
+ }
+ // The stale cross-session window is untrustworthy, so the fresh anchor
+ // page REPLACES it (unlike the fresh-drift case, which merges) — the
+ // final render shows only the refetched window.
+ expect(renderedMessageIds.at(-1)).toEqual(["m_fresh_anchor"])
+ // Fix 3 fetched the fresh anchor window out of band via the queryFn.
+ // (A second `?anchor=m_old_anchor` fetch may also fire — that's Fix 4's
+ // independent mount-time `invalidateQueries` re-running the persisted
+ // stale pageParam. Both keep the previous data on screen during the
+ // refetch; neither is a `resetQueries` empty-clear, which is what this
+ // test's per-render `length > 0` assertion above guards against.)
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/ch_2/messages?anchor=m_fresh_anchor",
+ )
+ })
+})
diff --git a/src/web/src/hooks/community/use-messages.loading-state.test.ts b/src/web/src/hooks/community/use-messages.loading-state.test.ts
new file mode 100644
index 000000000..746614666
--- /dev/null
+++ b/src/web/src/hooks/community/use-messages.loading-state.test.ts
@@ -0,0 +1,71 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { useMessages } from "./use-messages"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+})
+
+// Regression test for the "brand-new channel flashes a frame of fake-empty
+// content instead of the skeleton" bug: while the anchor snapshot is still
+// resolving, `useMessages` disables its underlying query — TanStack forces
+// `isFetching` to `false` when `enabled: false`, so the native
+// `isLoading = isPending && isFetching` computes to `false` even though
+// nothing has loaded. Renders a tiny consumer via `react-test-renderer`
+// (this repo's existing pattern — see message-list.mount-identity.test.ts)
+// and captures the hook's return value.
+function Capture({ onResult, channelId, lastReadMessageId }: {
+ onResult: (r: { isLoading: boolean; messages: unknown[] }) => void
+ channelId: string | null
+ lastReadMessageId?: string | null
+}) {
+ const result = useMessages(channelId, { lastReadMessageId })
+ onResult({ isLoading: result.isLoading, messages: result.messages })
+ return null
+}
+
+function renderCapture(
+ onResult: (r: { isLoading: boolean; messages: unknown[] }) => void,
+ lastReadMessageId: string | null | undefined,
+) {
+ const queryClient = new QueryClient()
+ act(() => {
+ TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { onResult, channelId: "ch_new", lastReadMessageId }),
+ ),
+ )
+ })
+}
+
+describe("useMessages — isLoading while the anchor snapshot is unresolved", () => {
+ it("reports isLoading: true even though the underlying query is disabled (enabled: false forces isFetching: false)", () => {
+ let latest: { isLoading: boolean; messages: unknown[] } | undefined
+ // `lastReadMessageId: undefined` — the anchor snapshot resolving case
+ // (see MessagesOpts' doc comment in use-messages.ts): `enabled` is false.
+ renderCapture((r) => { latest = r }, undefined)
+
+ expect(latest?.isLoading).toBe(true)
+ expect(latest?.messages).toEqual([])
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+
+ it("reports isLoading: true while the now-enabled query's first fetch is in flight", () => {
+ apiFetchMock.mockImplementation(() => new Promise(() => {})) // never resolves
+ let latest: { isLoading: boolean; messages: unknown[] } | undefined
+ // `lastReadMessageId: null` — anchor resolved (no anchor), query enabled
+ // and genuinely fetching.
+ renderCapture((r) => { latest = r }, null)
+
+ expect(latest?.isLoading).toBe(true)
+ })
+})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index c3d545494..63c1c093f 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -134,7 +134,7 @@ const STALE_HYDRATED_CACHE_MS = 30_000
type PageCache = InfiniteData<MessagesPage, MessagesPageParam>
-type MessagesReturn = UseInfiniteQueryResult<PageCache, Error> & {
+type MessagesReturn = Omit<UseInfiniteQueryResult<PageCache, Error>, "isLoading"> & {
messages: Msg[]
latestSeq: number
hasMoreOlder: boolean
@@ -147,6 +147,11 @@ type MessagesReturn = UseInfiniteQueryResult<PageCache, Error> & {
// Legacy alias — mirrors `hasMoreOlder`. Kept so consumers not yet migrated
// off the older-only API still compile until every call site is updated.
hasMore: boolean
+ // Widened from the query's own status-discriminated literal (`true`/
+ // `false` narrowed by `status`) to a plain boolean — see the override
+ // below, which also folds in `!anchorResolved` so a disabled query (still
+ // waiting on the anchor snapshot) reports loading too.
+ isLoading: boolean
}
type MessagesOpts = {
@@ -261,10 +266,22 @@ function useMessagesInner(
// to `undefined` and the list snaps to bottom — no NEW divider, wrong
// position.
//
- // Detect that shape and reset the query so it refetches under the correct
- // anchor pageParam. Fire exactly once per (scopeId, anchorId) pair via a
- // ref — a subsequent watermark tick that advances lastReadMessageId is a
- // different pair and gets its own single reset opportunity.
+ // Detect that shape and re-anchor. Fire exactly once per (scopeId,
+ // anchorId) pair via a ref — a subsequent watermark tick that advances
+ // lastReadMessageId is a different pair and gets its own single
+ // re-anchor opportunity.
+ //
+ // Two different causes need two different repairs:
+ // - Genuinely stale cache (cross-session IDB hydration, e.g. the Inbox-
+ // to-unread-channel case) — `resetQueries` is correct: the whole
+ // window is untrustworthy anyway.
+ // - Same-session anchor drift with a still-fresh cache (e.g. returning
+ // from a Thread after the watermark advanced past the window) — the
+ // already-loaded history is still valid. `resetQueries` would clear
+ // `pages` to empty and flash a blank list while it refetches. Instead,
+ // fetch a fresh anchor-centered page out of band and swap the query
+ // data directly once it lands — the view jumps straight from the old
+ // (valid) window to the new one, never passing through an empty state.
const anchorResetKeyRef = useRef<string | null>(null)
useEffect(() => {
if (!enabled) return
@@ -291,16 +308,80 @@ function useMessagesInner(
const resetKey = `${scopeId ?? ""}::${anchorId}`
if (anchorResetKeyRef.current === resetKey) return
anchorResetKeyRef.current = resetKey
- void queryClient.resetQueries({ queryKey })
+
+ const updatedAt = query.dataUpdatedAt
+ const isFresh = !!updatedAt && Date.now() - updatedAt < STALE_HYDRATED_CACHE_MS
+
+ // Both branches fetch a fresh anchor-centered page out of band and swap
+ // it in via `setQueryData` — NEITHER uses `resetQueries`. `resetQueries`
+ // clears `pages` to empty synchronously, which flashes a second loading
+ // skeleton mid-mount and, worse, wipes the virtualizer's measurement
+ // cache so the one-shot mount scroll (fired once the refetch lands)
+ // mis-targets and settles at the top hero instead of the NEW divider —
+ // and the unread rows near the tail then never enter the viewport, so
+ // the read watermark never advances. Keeping the old (renderable) window
+ // on screen until the fresh page lands makes the transition a direct
+ // swap with no empty frame (DESIGN.md "Fade, don't swap").
+ //
+ // The branches differ only in what they keep:
+ // - FRESH cache (same-session drift, e.g. returning from a Thread after
+ // the watermark advanced): the already-loaded history is still valid,
+ // so MERGE the new anchor page into it — dropping it would lose rows
+ // the user paged in via `fetchOlder`.
+ // - STALE cache (cross-session IDB hydration): the loaded window is
+ // untrustworthy, so REPLACE it with just the fresh anchor page.
+ const anchorPageParam: MessagesPageParam = { mode: "anchor", anchor: anchorId }
+ queryFn({ pageParam: anchorPageParam })
+ .then((page) => {
+ // Re-check right before the swap — a concurrent send/WS update or a
+ // second re-anchor attempt in the interim shouldn't be clobbered by
+ // a now-outdated fetch result landing late.
+ if (anchorResetKeyRef.current !== resetKey) return
+ queryClient.setQueryData<PageCache>(queryKey, (current) => {
+ // Stale replace-path: use the fresh page even if `current` is
+ // somehow absent — never fall back to leaving an un-anchored
+ // window in place.
+ if (!isFresh) {
+ return { pages: [page], pageParams: [anchorPageParam] }
+ }
+ if (!current) return current
+ // Fresh merge-path: fold the freshly-fetched anchor page into the
+ // ALREADY-LOADED history rather than replacing `pages` outright —
+ // discarding it would drop every page the user loaded via
+ // `fetchOlder` (scroll-up pagination), which surfaced as history
+ // vanishing on channel switch. `mergeMessagesPages` sorts +
+ // dedupes by id, so overlapping rows between the old window and
+ // the new anchor page collapse cleanly. The merged set collapses
+ // into a single page — `hasMoreOlder`/`hasMoreNewer` come from the
+ // new anchor page since it alone knows the true state of both
+ // edges relative to the (possibly wider) merged window.
+ const merged = mergeMessagesPages([...current.pages, page])
+ const mergedPage: MessagesPage = {
+ ...page,
+ messages: merged,
+ }
+ return { pages: [mergedPage], pageParams: [anchorPageParam] }
+ })
+ })
+ .catch(() => {
+ // Out-of-band fetch failed — fall back to the reset path so the
+ // scope isn't stuck showing a stale, un-anchored window forever.
+ // This is the ONLY `resetQueries` path left: an outright fetch
+ // failure has no fresh page to swap in, so the empty-then-refetch
+ // flash is the acceptable last resort rather than the common case.
+ void queryClient.resetQueries({ queryKey })
+ })
}, [
enabled,
anchorId,
scopeId,
query.data,
+ query.dataUpdatedAt,
query.isFetching,
query.isPending,
queryClient,
queryKey,
+ queryFn,
])
// Fix 4 — staleness invalidate on mount / scope switch ONLY.
@@ -388,6 +469,13 @@ function useMessagesInner(
return {
...query,
+ // While the anchor snapshot is still resolving, the query is `enabled:
+ // false` — TanStack forces `isFetching` to `false` in that state, which
+ // makes the native `isLoading = isPending && isFetching` compute to
+ // `false` even though nothing has loaded yet. Left uncorrected, callers
+ // see one frame of "ready but empty" (no skeleton) on a brand-new scope
+ // before the query flips `enabled` and `isLoading` jumps back to `true`.
+ isLoading: query.isLoading || !anchorResolved,
messages,
latestSeq,
hasMoreOlder,
diff --git a/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.test.ts b/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.test.ts
new file mode 100644
index 000000000..c3c9ab298
--- /dev/null
+++ b/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.test.ts
@@ -0,0 +1,145 @@
+import { describe, it, expect } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { useScrollAnchor } from "./use-scroll-anchor"
+import type { FlatItem } from "@/components/community/message-list-items"
+
+// Render-level coverage for something `computeHeroScrollCompensation`'s
+// pure-function tests can't reach — it lives in `useScrollAnchor`'s effect
+// body, not the pure delta function: the hero-swap compensation effect
+// must actually adjust the real scroll container's `scrollTop`, and must
+// NOT rely on `scrollMargin` doing this automatically (verified against the
+// installed virtual-core source that it doesn't — see use-scroll-anchor.ts's
+// module doc comment). Uses `react-test-renderer` (this repo's existing
+// pattern for scroll-effect tests — see message-list.mount-identity.test.ts).
+
+function makeMockScrollEl() {
+ const el = {
+ scrollTop: 0,
+ scrollHeight: 1000,
+ clientHeight: 500,
+ firstElementChild: null,
+ scrollTo: (opts: { top: number }) => { el.scrollTop = opts.top },
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ ownerDocument: { defaultView: {} },
+ }
+ return el
+}
+
+const items: FlatItem[] = [
+ { kind: "message", m: { id: "m1", type: "chat", grouped: false }, key: "msg:m1" },
+ { kind: "message", m: { id: "m2", type: "chat", grouped: false }, key: "msg:m2" },
+]
+
+function Harness({ heroHeight }: { heroHeight: number }) {
+ const { scrollRef } = useScrollAnchor({
+ items,
+ initialScrollReady: true,
+ heroHeight,
+ })
+ return React.createElement("div", { ref: scrollRef })
+}
+
+describe("useScrollAnchor — hero-swap compensation adjusts scrollTop directly (does not rely on scrollMargin alone)", () => {
+ it("shoves scrollTop down by the delta when the hero grows between renders", () => {
+ const g = globalThis as unknown as { ResizeObserver: unknown; IntersectionObserver: unknown }
+ const prevRO = g.ResizeObserver
+ const prevIO = g.IntersectionObserver
+ g.ResizeObserver = class { observe() {} disconnect() {} }
+ g.IntersectionObserver = class { observe() {} disconnect() {} }
+
+ const el = makeMockScrollEl()
+ try {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(Harness, { heroHeight: 0 }),
+ { createNodeMock: () => el },
+ )
+ })
+
+ // Mount consumes the one-shot gate and calls scrollToEnd — reset the
+ // baseline scrollTop it left behind before asserting the hero-swap
+ // delta in isolation.
+ el.scrollTop = 200
+
+ act(() => {
+ renderer!.update(React.createElement(Harness, { heroHeight: 96 }))
+ })
+
+ // The hero grew by 96px — the viewer's visual position must be held
+ // by shoving scrollTop down by the same amount, not left alone
+ // (which is what would happen if this hook relied on `scrollMargin`
+ // to do this automatically, per the verified-false original plan
+ // draft claim).
+ expect(el.scrollTop).toBe(200 + 96)
+ } finally {
+ g.ResizeObserver = prevRO
+ g.IntersectionObserver = prevIO
+ }
+ })
+
+ it("pulls scrollTop back up by the delta when the hero shrinks between renders", () => {
+ const g = globalThis as unknown as { ResizeObserver: unknown; IntersectionObserver: unknown }
+ const prevRO = g.ResizeObserver
+ const prevIO = g.IntersectionObserver
+ g.ResizeObserver = class { observe() {} disconnect() {} }
+ g.IntersectionObserver = class { observe() {} disconnect() {} }
+
+ const el = makeMockScrollEl()
+ try {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(Harness, { heroHeight: 96 }),
+ { createNodeMock: () => el },
+ )
+ })
+
+ el.scrollTop = 300
+
+ act(() => {
+ renderer!.update(React.createElement(Harness, { heroHeight: 40 }))
+ })
+
+ expect(el.scrollTop).toBe(300 - 56)
+ } finally {
+ g.ResizeObserver = prevRO
+ g.IntersectionObserver = prevIO
+ }
+ })
+
+ it("does not touch scrollTop when heroHeight is unchanged across a re-render", () => {
+ const g = globalThis as unknown as { ResizeObserver: unknown; IntersectionObserver: unknown }
+ const prevRO = g.ResizeObserver
+ const prevIO = g.IntersectionObserver
+ g.ResizeObserver = class { observe() {} disconnect() {} }
+ g.IntersectionObserver = class { observe() {} disconnect() {} }
+
+ const el = makeMockScrollEl()
+ try {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(Harness, { heroHeight: 60 }),
+ { createNodeMock: () => el },
+ )
+ })
+
+ el.scrollTop = 150
+
+ act(() => {
+ renderer!.update(React.createElement(Harness, { heroHeight: 60 }))
+ })
+
+ expect(el.scrollTop).toBe(150)
+ } finally {
+ g.ResizeObserver = prevRO
+ g.IntersectionObserver = prevIO
+ }
+ })
+})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.ts
new file mode 100644
index 000000000..f16a835f4
--- /dev/null
+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts
@@ -0,0 +1,253 @@
+import { describe, it, expect } from "vitest"
+import {
+ decideScrollAction,
+ createScrollAnchorState,
+ computeHeroScrollCompensation,
+ findMessageIndex,
+ findMountScrollTargetIndex,
+ extractScrollAnchorMessages,
+ NEAR_BOTTOM_PX,
+ type ScrollAnchorState,
+ type ScrollAnchorMessage,
+} from "./use-scroll-anchor"
+import type { FlatItem } from "@/components/community/message-list-items"
+
+const msgs = (...ids: string[]): ScrollAnchorMessage[] => ids.map((id) => ({ id }))
+
+function baseInput(overrides: Partial<Parameters<typeof decideScrollAction>[0]> = {}) {
+ return {
+ state: createScrollAnchorState(),
+ messages: msgs("m1", "m2", "m3"),
+ initialScrollReady: true,
+ heroMeasured: true,
+ isAtEnd: true,
+ ...overrides,
+ }
+}
+
+describe("decideScrollAction — mount (rewritten — neither case is free with the virtualizer, both must be explicit)", () => {
+ it("centers on the NEW divider when present", () => {
+ const { action, nextState } = decideScrollAction(baseInput({ newDividerBefore: "m2" }))
+ expect(action).toEqual({ type: "mount", newDividerBefore: "m2" })
+ expect(nextState.didInitialScroll).toBe(true)
+ })
+
+ it("scrolls to end when no NEW divider is present — NOT free, must be an explicit action", () => {
+ const { action } = decideScrollAction(baseInput())
+ expect(action).toEqual({ type: "mount", newDividerBefore: undefined })
+ })
+
+ it("does not fire (and does not consume the one-shot gate) until initialScrollReady", () => {
+ const { action, nextState } = decideScrollAction(baseInput({ initialScrollReady: false }))
+ expect(action).toEqual({ type: "none" })
+ expect(nextState.didInitialScroll).toBe(false)
+ })
+
+ it("does not fire (and does not consume the one-shot gate) until the hero has been measured at least once", () => {
+ // Regression: the hero's real height is only known after its own
+ // ResizeObserver effect runs (a later commit than the one that first
+ // renders real messages). scrollMargin defaults to 0 until then — if
+ // mount fired on that stale scrollMargin, scrollToIndex's offset math
+ // (align: "center") would target the wrong scrollTop, and the
+ // virtualizer's own reconcile loop stabilizes on that wrong value
+ // within a frame, well before heroHeight's real value lands. Observed
+ // as: page loads, view flashes at the tail then snaps to the top hero,
+ // and unread messages near the true tail never enter the viewport so
+ // useChannelWatermark never advances the read pointer.
+ const { action, nextState } = decideScrollAction(baseInput({ heroMeasured: false }))
+ expect(action).toEqual({ type: "none" })
+ expect(nextState.didInitialScroll).toBe(false)
+ })
+
+ it("fires once both initialScrollReady and heroMeasured become true, even if one lagged behind the other", () => {
+ const notReady = decideScrollAction(baseInput({ initialScrollReady: false, heroMeasured: false }))
+ expect(notReady.action).toEqual({ type: "none" })
+ const heroOnly = decideScrollAction(baseInput({ state: notReady.nextState, initialScrollReady: false, heroMeasured: true }))
+ expect(heroOnly.action).toEqual({ type: "none" })
+ const bothReady = decideScrollAction(baseInput({ state: heroOnly.nextState, initialScrollReady: true, heroMeasured: true }))
+ expect(bothReady.action.type).toBe("mount")
+ })
+
+ it("fires exactly once — a second commit with didInitialScroll already true does not re-mount-scroll", () => {
+ const first = decideScrollAction(baseInput())
+ expect(first.action.type).toBe("mount")
+ const second = decideScrollAction(baseInput({ state: first.nextState }))
+ expect(second.action.type).not.toBe("mount")
+ })
+
+ it("does not fire on an empty message list, and does not consume the gate", () => {
+ const { action, nextState } = decideScrollAction(baseInput({ messages: [] }))
+ expect(action).toEqual({ type: "none" })
+ expect(nextState.didInitialScroll).toBe(false)
+ })
+
+ it("re-arms and re-fires the mount scroll after a transient empty following the initial scroll", () => {
+ // Regression (live-Playwright-verified): the message list can round-trip
+ // through `[]` AFTER the initial scroll already fired, when a live path
+ // invalidates the message query mid-mount — the observed trigger is
+ // `useCommunityWs`'s `handleReconnect` firing ~1.5s into a fresh load and
+ // invalidating both `channelMessages` and the `gcTime: 0` read-state
+ // snapshot. Before the fix, the consumed one-shot gate stayed consumed,
+ // so when rows returned the view was stuck at the top hero with the NEW
+ // divider off-screen. The empty commit must RE-ARM the gate.
+ const first = decideScrollAction(baseInput({ newDividerBefore: "m2" }))
+ expect(first.action.type).toBe("mount")
+ expect(first.nextState.didInitialScroll).toBe(true)
+
+ // Mid-mount invalidation empties the list — gate must re-arm to false.
+ const emptied = decideScrollAction(baseInput({ state: first.nextState, messages: [] }))
+ expect(emptied.action).toEqual({ type: "none" })
+ expect(emptied.nextState.didInitialScroll).toBe(false)
+
+ // Rows return — mount must fire again to re-anchor on the NEW divider.
+ const returned = decideScrollAction(baseInput({ state: emptied.nextState, newDividerBefore: "m2" }))
+ expect(returned.action).toEqual({ type: "mount", newDividerBefore: "m2" })
+ expect(returned.nextState.didInitialScroll).toBe(true)
+ })
+})
+
+// Helper: state as-if mount already happened, tail = "m3".
+function mountedState(overrides: Partial<ScrollAnchorState> = {}): ScrollAnchorState {
+ return {
+ didInitialScroll: true,
+ lastTailId: "m3",
+ ...overrides,
+ }
+}
+
+describe("decideScrollAction — self-send / peer-follow (both hand-rolled — followOnAppend is deliberately off)", () => {
+ it("self-send (tail author === viewer) snaps to bottom regardless of isAtEnd", () => {
+ const state = mountedState()
+ const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "viewer" }]
+ const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer", isAtEnd: false }))
+ expect(action).toEqual({ type: "scrollToEnd" })
+ })
+
+ it("peer send while isAtEnd is true snaps to bottom", () => {
+ const state = mountedState()
+ const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
+ const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer", isAtEnd: true }))
+ expect(action).toEqual({ type: "scrollToEnd" })
+ })
+
+ it("peer send while isAtEnd is false does not scroll — leaves the pill to prompt the user back down", () => {
+ const state = mountedState()
+ const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
+ const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer", isAtEnd: false }))
+ expect(action).toEqual({ type: "none" })
+ })
+
+ it("peer send is ignored (no auto-follow) when hasMoreNewer is true — loaded window isn't tail-attached, even if isAtEnd is true", () => {
+ const state = mountedState()
+ const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
+ const { action } = decideScrollAction(
+ baseInput({ state, messages, viewerUserId: "viewer", hasMoreNewer: true, isAtEnd: true }),
+ )
+ expect(action).toEqual({ type: "none" })
+ })
+
+ it("no action when the tail id is unchanged", () => {
+ const state = mountedState()
+ const { action } = decideScrollAction(baseInput({ state, viewerUserId: "viewer" }))
+ expect(action).toEqual({ type: "none" })
+ })
+
+ it("temp-id → server-id reconcile: tail id changes via reconcileServerId but author/content/position are otherwise unchanged — resolves as an idempotent self-send, not a misclassified no-op", () => {
+ // Simulates: viewer sent a message (tempId "temp_123"), it's already the
+ // tail, then the server responds and `reconcileServerId` swaps the id to
+ // the real server id ("srv_abc") — same author, same position, nothing
+ // about scroll position should change, but the tail id STRING changed.
+ // With getItemKey keyed on message id, this is a bigger structural event
+ // for the virtualizer than it was for raw DOM (the item's key changes) —
+ // still must resolve as self-send, not fall through to "none".
+ const state = mountedState({ lastTailId: "temp_123" })
+ const messages = [{ id: "m1" }, { id: "m2" }, { id: "srv_abc", authorId: "viewer" }]
+ const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer" }))
+ expect(action).toEqual({ type: "scrollToEnd" })
+ })
+})
+
+describe("NEAR_BOTTOM_PX", () => {
+ it("is the single shared threshold, reused for both isAtEnd checks and the virtualizer's own scrollEndThreshold config", () => {
+ expect(NEAR_BOTTOM_PX).toBe(100)
+ })
+})
+
+describe("computeHeroScrollCompensation", () => {
+ it("returns 0 when the hero's height is unchanged", () => {
+ expect(computeHeroScrollCompensation(80, 80)).toBe(0)
+ })
+
+ it("returns a positive delta when the hero grows (e.g. sentinel swaps for the full 'Beginning of channel' block)", () => {
+ expect(computeHeroScrollCompensation(0, 96)).toBe(96)
+ })
+
+ it("returns a negative delta when the hero shrinks", () => {
+ expect(computeHeroScrollCompensation(96, 40)).toBe(-56)
+ })
+})
+
+describe("findMountScrollTargetIndex", () => {
+ const items: FlatItem[] = [
+ { kind: "date-divider", label: "Today", key: "d1" },
+ { kind: "message", m: { id: "m1", type: "chat", grouped: false }, key: "msg:m1" },
+ { kind: "new-divider", key: "new-divider" },
+ { kind: "message", m: { id: "m2", type: "chat", grouped: false }, key: "msg:m2" },
+ ]
+
+ it("prefers the new-divider ROW itself over the message row it precedes — it's now its own flattened item, thin, not the whole message box", () => {
+ expect(findMountScrollTargetIndex(items, "m2")).toBe(2)
+ })
+
+ it("falls back to the message's own index when no new-divider item exists (e.g. first-visit anchoring on a non-self message with no divider rendered)", () => {
+ const noDivider: FlatItem[] = [
+ { kind: "message", m: { id: "m1", type: "chat", grouped: false }, key: "msg:m1" },
+ { kind: "message", m: { id: "m2", type: "chat", grouped: false }, key: "msg:m2" },
+ ]
+ expect(findMountScrollTargetIndex(noDivider, "m2")).toBe(1)
+ })
+
+ it("returns null when the target message isn't loaded", () => {
+ expect(findMountScrollTargetIndex(items, "unloaded")).toBeNull()
+ })
+})
+
+describe("findMessageIndex", () => {
+ const items: FlatItem[] = [
+ { kind: "date-divider", label: "Today", key: "d1" },
+ { kind: "message", m: { id: "m1", type: "chat", grouped: false }, key: "msg:m1" },
+ { kind: "message", m: { id: "m2", type: "chat", grouped: true }, key: "msg:m2" },
+ ]
+
+ it("returns the item-array index of the message with the given id", () => {
+ expect(findMessageIndex(items, "m2")).toBe(2)
+ })
+
+ it("returns null when the id isn't present (message not loaded)", () => {
+ expect(findMessageIndex(items, "unloaded")).toBeNull()
+ })
+
+ it("never matches a divider row even if some future divider carried an overlapping id-like key", () => {
+ expect(findMessageIndex(items, "d1")).toBeNull()
+ })
+})
+
+describe("extractScrollAnchorMessages", () => {
+ it("extracts only 'message' items' id/authorId, in order, skipping dividers", () => {
+ const items: FlatItem[] = [
+ { kind: "date-divider", label: "Today", key: "d1" },
+ { kind: "message", m: { id: "m1", type: "chat", grouped: false, authorId: "u1" }, key: "msg:m1" },
+ { kind: "new-divider", key: "new-divider" },
+ { kind: "message", m: { id: "m2", type: "chat", grouped: false }, key: "msg:m2" },
+ ]
+ expect(extractScrollAnchorMessages(items)).toEqual([
+ { id: "m1", authorId: "u1" },
+ { id: "m2", authorId: undefined },
+ ])
+ })
+
+ it("returns an empty array when there are no message items", () => {
+ const items: FlatItem[] = [{ kind: "date-divider", label: "Today", key: "d1" }]
+ expect(extractScrollAnchorMessages(items)).toEqual([])
+ })
+})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
new file mode 100644
index 000000000..73ad1fa30
--- /dev/null
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -0,0 +1,389 @@
+import { useCallback, useLayoutEffect, useRef } from "react"
+import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual"
+import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/components/community/message-list-items"
+
+// Virtualized rewrite of message-list's scroll-anchoring logic. The
+// pre-virtualization version (see git history) hand-rolled 4 branches —
+// mount / self-send-peer-follow / older-prepend-compensation / hero-swap-
+// compensation — verified against `record-debt-community-messages.md`
+// findings #2/#10 (two disagreeing "near bottom" thresholds, a same-commit
+// double-write race, a silently-unhandled compound case).
+//
+// This version delegates OLDER-PREPEND compensation entirely to
+// `@tanstack/react-virtual`'s `anchorTo: "end"` (verified against the
+// installed `[email protected]` source: its `setOptions` anchor-preserving
+// branch fires on any edge-key/count change on a non-initial commit — exactly
+// what `fetchOlder` prepending rows produces). `decideScrollAction` below
+// therefore only covers the 2 behaviors the library does NOT provide:
+// mount-time positioning and self-send/peer-follow. Hero-swap compensation
+// is also NOT delegated to the library (`scrollMargin` shifts the
+// measurement coordinate system only — verified it never triggers a
+// `scrollOffset` write) and is handled by the separate, narrower
+// `computeHeroScrollCompensation` below plus a dedicated `ResizeObserver`
+// on the hero wrapper (see `useScrollAnchor`'s hero-tracking effect) — NOT
+// the old catch-all `watchAsyncGrowth`, which is deleted along with its
+// row-level image-decode case (native `resizeItem`/`applyScrollAdjustment`
+// in the installed library replaces that one).
+//
+// `followOnAppend` is deliberately left OFF in the virtualizer config (see
+// `useScrollAnchor`) — turning it on would let the library ALSO call
+// `scrollToEnd()` on any append where `isAtEnd()` was already true, racing
+// with this hook's own explicit self-send/peer-follow `scrollToEnd()` call
+// in the same commit (same class of same-commit double-write the debt
+// record already flagged once). `isAtEnd()` is still reused here as a cheap
+// boolean read — only the ACT of scrolling stays single-sourced.
+
+// Shared "near bottom" threshold. Also passed as the virtualizer's own
+// `scrollEndThreshold` config value (see `useScrollAnchor`) — NOT purely
+// cosmetic: `scrollEndThreshold` independently gates the library's native
+// `resizeItem` above-viewport compensation (defaults to 1px otherwise).
+export const NEAR_BOTTOM_PX = 100
+
+export interface ScrollAnchorMessage {
+ id: string
+ authorId?: string
+}
+
+export interface ScrollAnchorState {
+ didInitialScroll: boolean
+ lastTailId: string | null
+}
+
+export function createScrollAnchorState(): ScrollAnchorState {
+ return {
+ didInitialScroll: false,
+ lastTailId: null,
+ }
+}
+
+export interface DecideScrollActionInput {
+ state: ScrollAnchorState
+ messages: ScrollAnchorMessage[]
+ newDividerBefore?: string
+ initialScrollReady: boolean
+ // Whether the hero block's real height has been measured at least once
+ // (the caller's `ResizeObserver` effect has fired). Gates mount the same
+ // way `initialScrollReady` does: firing mount while this is still false
+ // means `scrollMargin` is still its default 0, so `scrollToIndex`'s
+ // offset math (align: "center", for the NEW-divider case) targets the
+ // wrong scrollTop — and the virtualizer's own scroll-reconcile loop
+ // stabilizes on that wrong value within a frame, well before the hero's
+ // real height (a separate React state update) lands. Observed as: page
+ // loads, view flashes at the tail then snaps to the top hero, and unread
+ // messages near the true tail never enter the viewport so
+ // useChannelWatermark never advances the read pointer.
+ heroMeasured: boolean
+ hasMoreNewer?: boolean
+ viewerUserId?: string
+ // Whether the viewport was within NEAR_BOTTOM_PX of the end BEFORE this
+ // commit's append — the caller reads this off `virtualizer.isAtEnd(NEAR_BOTTOM_PX)`.
+ isAtEnd: boolean
+}
+
+type ScrollAction =
+ | { type: "none" }
+ | { type: "mount"; newDividerBefore: string | undefined }
+ | { type: "scrollToEnd" }
+
+export interface DecideScrollActionResult {
+ action: ScrollAction
+ nextState: ScrollAnchorState
+}
+
+/**
+ * Pure decision function — given the previous anchor state and this
+ * commit's inputs, decides AT MOST ONE scroll action, in priority order:
+ * 1. Mount-time initial scroll (fires exactly once — covers BOTH the
+ * divider-center case and the plain "start at the end" case; neither
+ * is free with `anchorTo: "end"`, which only engages its
+ * anchor-preserving logic on options DIFFS, not the constructor's
+ * initial `setOptions` call).
+ * 2. Self-send / peer-follow snap to end.
+ * Older-prepend compensation and hero-swap compensation are NOT decided
+ * here — see this file's module doc comment for where they moved. No DOM
+ * access — the caller (the hook) executes the chosen action against the
+ * real virtualizer. Exported for unit testing without DOM/hooks.
+ */
+export function decideScrollAction(input: DecideScrollActionInput): DecideScrollActionResult {
+ const { state, messages, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, isAtEnd } = input
+
+ const nextTail = messages[messages.length - 1]?.id ?? null
+ const nextLen = messages.length
+
+ const baseNextState: ScrollAnchorState = {
+ didInitialScroll: state.didInitialScroll,
+ lastTailId: nextTail,
+ }
+
+ // Channel/DM cleared (or genuinely empty) — nothing to anchor, and RE-ARM
+ // the mount one-shot gate. The list can transiently empty AFTER a
+ // successful initial scroll when a live path invalidates the message query
+ // mid-mount — the observed trigger is `useCommunityWs`'s `handleReconnect`,
+ // which fires ~1.5s into a fresh load (a StrictMode / refresh double-
+ // connect makes the socket's `onReconnect` run once even on first paint)
+ // and invalidates BOTH `channelMessages` and the `gcTime: 0`
+ // `channelReadStateSnapshot`. That round-trips `messages` through `[]`
+ // (itemCount 48 → 0 → 48, verified via live Playwright trace). Without
+ // re-arming, the one-shot `didInitialScroll` gate stays consumed, so when
+ // the rows return the mount scroll never re-fires and the view is left
+ // parked at the top hero with the NEW divider off-screen — exactly the
+ // "content → skeleton → content → stuck at hero" refresh bug. Re-arming
+ // makes the next non-empty commit re-run the mount positioning.
+ //
+ // Safe for a genuine channel switch too: that path already gets a fresh
+ // hook instance (keyed by channelId/dmId — see this hook's doc comment),
+ // so this branch only ever matters for a same-scope transient empty.
+ if (nextLen === 0) {
+ return { action: { type: "none" }, nextState: { ...baseNextState, didInitialScroll: false } }
+ }
+
+ // 1. Mount-time initial scroll — fires exactly once. Bails (without
+ // consuming the gate) until `initialScrollReady` — running before the
+ // owner's async anchor (e.g. `useChannelReadStateSnapshot`) resolves
+ // would silently snap to the bottom and burn the one-shot gate. Also
+ // bails until `heroMeasured` — see this field's doc comment above for why
+ // firing on a stale (default-0) scrollMargin silently mis-targets the
+ // NEW-divider case.
+ if (!state.didInitialScroll) {
+ if (!initialScrollReady || !heroMeasured) {
+ return { action: { type: "none" }, nextState: { ...baseNextState, didInitialScroll: false } }
+ }
+ return { action: { type: "mount", newDividerBefore }, nextState: { ...baseNextState, didInitialScroll: true } }
+ }
+
+ // 2. Self-send / peer-follow — only relevant when the tail actually moved.
+ const tailChanged = state.lastTailId !== null && state.lastTailId !== nextTail
+ if (tailChanged) {
+ const tail = messages[messages.length - 1]
+ const isSelfSend = !!viewerUserId && tail?.authorId === viewerUserId
+ if (isSelfSend) {
+ // Always follow — handles the composer path and, incidentally, the
+ // optimistic temp-id → server-id reconcile (the tail id string
+ // changes via `reconcileServerId` on send success, but the author is
+ // still the viewer, so this branch still catches it as an idempotent
+ // self-send snap, not a misclassified no-op).
+ return { action: { type: "scrollToEnd" }, nextState: baseNextState }
+ }
+ // Peer send: only follow if the loaded window is tail-attached to the
+ // present (`hasMoreNewer` false) AND the viewer was already at/near the
+ // bottom just BEFORE this append — otherwise leave the "↓ N" pill to
+ // prompt them back down.
+ if (!hasMoreNewer && isAtEnd) {
+ return { action: { type: "scrollToEnd" }, nextState: baseNextState }
+ }
+ }
+
+ return { action: { type: "none" }, nextState: baseNextState }
+}
+
+/**
+ * Hero-swap scroll compensation. Unlike the deleted `olderPrepended`/
+ * `heroSwap` delta-compensation branch this replaces, this is a plain
+ * arithmetic delta between two known heights — not a `scrollHeight`-diff
+ * read off the DOM — since the caller already tracks the hero wrapper's
+ * measured height via `ResizeObserver` (see `useScrollAnchor`). Exported
+ * for direct unit testing.
+ */
+export function computeHeroScrollCompensation(prevHeroHeight: number, nextHeroHeight: number): number {
+ return nextHeroHeight - prevHeroHeight
+}
+
+/**
+ * Look up a message's position in the flattened item array by id — the
+ * virtualized replacement for `jumpTo`'s old
+ * `querySelector('[data-msg-id="..."]')` DOM lookup, which only worked if
+ * the target row happened to already be mounted. `virtualizer.scrollToIndex`
+ * needs an INDEX, not a DOM node, so this walks `items` instead. Returns
+ * `null` when the target isn't in the currently loaded page window — same
+ * limitation the old DOM lookup had (it also required the row to be
+ * loaded), just surfaced earlier/more explicitly. Never matches a divider
+ * row. Exported for direct unit testing.
+ */
+export function findMessageIndex(items: FlatItem[], messageId: string): number | null {
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i]
+ if (item.kind === "message" && item.m.id === messageId) return i
+ }
+ return null
+}
+
+/**
+ * Mount-time scroll target: the NEW divider's own row when present (it's a
+ * thin line, not the whole message box — centering on the row instead
+ * visibly biases the divider toward the top of that taller box once the
+ * anchor message has an attachment/long text/thread preview), falling back
+ * to the target message's own index when no divider item was flattened
+ * (e.g. first-visit anchoring with no unread pointer to render a divider
+ * for). Returns `null` if the target message isn't loaded.
+ */
+export function findMountScrollTargetIndex(items: FlatItem[], newDividerBefore: string): number | null {
+ const msgIdx = findMessageIndex(items, newDividerBefore)
+ if (msgIdx === null) return null
+ const dividerIdx = items.findIndex((i) => i.kind === "new-divider")
+ return dividerIdx !== -1 ? dividerIdx : msgIdx
+}
+
+/**
+ * Projects the flattened item array down to just the id/authorId pairs
+ * `decideScrollAction` needs (it only cares about the tail message's id
+ * and author, not divider rows). Exported for direct unit testing.
+ */
+export function extractScrollAnchorMessages(items: FlatItem[]): ScrollAnchorMessage[] {
+ const out: ScrollAnchorMessage[] = []
+ for (const item of items) {
+ if (item.kind === "message") out.push({ id: item.m.id, authorId: item.m.authorId })
+ }
+ return out
+}
+
+/**
+ * Owns the message-list scroll container ref, the `useVirtualizer` instance,
+ * and every automatic scroll-anchor decision (mount / self-send /
+ * peer-follow / hero-swap) plus the "↓ N below" pill's `belowCount`. Older-
+ * message prepend compensation is NOT decided here — it's delegated to the
+ * virtualizer's own `anchorTo: "end"` config (see this file's module doc
+ * comment for the source-verified rationale).
+ *
+ * `jumpTo` (scrolling to an arbitrary earlier message on reply-pill click)
+ * DOES live here now, unlike the pre-virtualization hook — it needs direct
+ * `virtualizer.scrollToIndex` access, which `message-list.tsx` has no other
+ * reason to reach into the virtualizer instance for.
+ *
+ * No `channelId`/`dmId` reset param: `<MessageList>` is still keyed by
+ * `channelId`/`dmId` at the page level, which gives this hook a fresh
+ * instance — and therefore fresh internal state — on every genuine channel
+ * switch for free.
+ */
+export function useScrollAnchor({
+ items,
+ newDividerBefore,
+ initialScrollReady,
+ hasMoreNewer,
+ viewerUserId,
+ heroHeight,
+ heroMeasured,
+}: {
+ items: FlatItem[]
+ newDividerBefore?: string
+ initialScrollReady: boolean
+ hasMoreNewer?: boolean
+ viewerUserId?: string
+ // Current measured height (px) of the non-virtualized hero block that
+ // renders above the virtualized range (the "Beginning of the channel…"
+ // copy or the thread-opener). Feeds the virtualizer's `scrollMargin` AND
+ // the hand-rolled hero-swap compensation (see `computeHeroScrollCompensation`)
+ // — `scrollMargin` alone does NOT preserve scroll position on its own,
+ // verified against the installed virtual-core source.
+ heroHeight: number
+ // True once the caller's hero-height ResizeObserver has fired at least
+ // once. Gates mount the same way `initialScrollReady` does — see
+ // `DecideScrollActionInput.heroMeasured`'s doc comment for the bug this
+ // prevents (mount firing on a stale, default-0 `scrollMargin`).
+ heroMeasured: boolean
+}): {
+ scrollRef: React.RefObject<HTMLDivElement | null>
+ virtualizer: Virtualizer<HTMLDivElement, Element>
+ belowCount: number
+ scrollToBottom: () => void
+ jumpTo: (messageId: string) => void
+} {
+ const scrollRef = useRef<HTMLDivElement>(null)
+ const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())
+ const messages = extractScrollAnchorMessages(items)
+
+ // eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
+ const virtualizer = useVirtualizer({
+ count: items.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: (index) => estimateRowHeight(items[index]),
+ getItemKey: (index) => items[index].key,
+ anchorTo: "end",
+ // Deliberately OFF — see this file's module doc comment for the
+ // same-commit double-`scrollToEnd()` race this avoids.
+ followOnAppend: false,
+ // NOT purely cosmetic even with followOnAppend off — independently
+ // gates the library's native `resizeItem` above-viewport compensation
+ // (the mechanism replacing the deleted `watchAsyncGrowth`'s row-level
+ // image-decode case). Left at the library default (1px), that native
+ // compensation would only fire when the user is within 1px of the
+ // literal bottom.
+ scrollEndThreshold: NEAR_BOTTOM_PX,
+ scrollMargin: heroHeight,
+ overscan: 8,
+ })
+
+ useLayoutEffect(() => {
+ const { action, nextState } = decideScrollAction({
+ state: stateRef.current,
+ messages,
+ newDividerBefore,
+ initialScrollReady,
+ heroMeasured,
+ hasMoreNewer,
+ viewerUserId,
+ isAtEnd: virtualizer.isAtEnd(NEAR_BOTTOM_PX),
+ })
+ stateRef.current = nextState
+
+ switch (action.type) {
+ case "mount": {
+ const idx = action.newDividerBefore ? findMountScrollTargetIndex(items, action.newDividerBefore) : null
+ if (idx !== null) {
+ virtualizer.scrollToIndex(idx, { align: "center" })
+ } else {
+ virtualizer.scrollToEnd()
+ }
+ return
+ }
+ case "scrollToEnd":
+ virtualizer.scrollToEnd()
+ return
+ case "none":
+ return
+ }
+ // messages/items share identity per render (extractScrollAnchorMessages
+ // derives from items) — `items` alone is the correct dep, not a
+ // secondary `messages` dep, avoiding a re-derivation-triggered re-fire.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [items, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, virtualizer])
+
+ // Hero-swap compensation — NOT delegated to `scrollMargin` (verified it
+ // never triggers a `scrollOffset` write on its own). Tracks the hero's
+ // height across renders and adjusts `el.scrollTop` by the delta whenever
+ // it changes, holding the visually-anchored row in place. Narrower than
+ // the deleted `watchAsyncGrowth`: only one input (a single number this
+ // hook already receives as a prop), no ResizeObserver of its own needed
+ // here — the caller (`message-list.tsx`) owns the hero's own
+ // ResizeObserver and passes the resulting height in as `heroHeight`.
+ const prevHeroHeightRef = useRef(heroHeight)
+ useLayoutEffect(() => {
+ const el = scrollRef.current
+ if (!el) return
+ const delta = computeHeroScrollCompensation(prevHeroHeightRef.current, heroHeight)
+ prevHeroHeightRef.current = heroHeight
+ if (delta !== 0) el.scrollTop += delta
+ }, [heroHeight])
+
+ // "↓ N below" pill count — a plain arithmetic derivation from data
+ // `getVirtualItems()` already exposes on every render, replacing the
+ // pre-virtualization `recomputeBelow`'s DOM-row-walk
+ // (`querySelectorAll("[data-msg-id]")` + `offsetTop` comparison).
+ const virtualItems = virtualizer.getVirtualItems()
+ const lastVisibleIndex = virtualItems.length > 0 ? virtualItems[virtualItems.length - 1].index : -1
+ const belowCount = virtualizer.isAtEnd(NEAR_BOTTOM_PX) ? 0 : computeBelowCount(items.length, lastVisibleIndex)
+
+ const scrollToBottom = useCallback(() => {
+ virtualizer.scrollToEnd({ behavior: "smooth" })
+ }, [virtualizer])
+
+ const jumpTo = useCallback((messageId: string) => {
+ const idx = findMessageIndex(items, messageId)
+ // Target not in the currently loaded page window — same limitation the
+ // pre-virtualization `querySelector` lookup had (it also required the
+ // row to be loaded); documented no-op, not a new failure mode.
+ if (idx === null) return
+ virtualizer.scrollToIndex(idx, { align: "center", behavior: "smooth" })
+ }, [items, virtualizer])
+
+ return { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo }
+}
diff --git a/src/web/src/hooks/use-file-attachments.test.ts b/src/web/src/hooks/use-file-attachments.test.ts
index 31d66f9be..b28472f1b 100644
--- a/src/web/src/hooks/use-file-attachments.test.ts
+++ b/src/web/src/hooks/use-file-attachments.test.ts
@@ -1,5 +1,7 @@
-import { describe, it, expect } from "vitest"
-import { isMimeAllowed } from "./use-file-attachments"
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { isMimeAllowed, useFileAttachments, type PendingFile } from "./use-file-attachments"
// Pin the MIME allowlist logic against the server-side `mimeAllowed` in
// `src/web/src/lib/community/upload.ts`. Both must agree — if this fires the
@@ -46,3 +48,78 @@ describe("isMimeAllowed", () => {
expect(isMimeAllowed("video/mp4", ICONS_ONLY)).toBe(false)
})
})
+
+// `generateThumbnail` runs entirely against browser APIs unavailable under
+// this repo's `environment: "node"` vitest config — mocked at the module
+// boundary (this file only exercises `useFileAttachments`'s handling of the
+// hook's result, not `generateThumbnail` itself, which has its own direct
+// unit tests in `lib/image-thumbnail.test.ts`).
+const generateThumbnailMock = vi.fn()
+vi.mock("../lib/image-thumbnail", () => ({
+ generateThumbnail: (...args: unknown[]) => generateThumbnailMock(...args),
+}))
+
+beforeEach(() => {
+ generateThumbnailMock.mockReset()
+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:fake"), revokeObjectURL: vi.fn() })
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+// Renders the hook via a tiny consumer component — this repo's existing
+// pattern for testing hooks without @testing-library (see
+// use-messages.loading-state.test.ts).
+function Capture({ onResult }: { onResult: (r: ReturnType<typeof useFileAttachments>) => void }) {
+ const result = useFileAttachments()
+ onResult(result)
+ return null
+}
+
+async function renderCapture() {
+ let latest!: ReturnType<typeof useFileAttachments>
+ await act(async () => {
+ TestRenderer.create(
+ React.createElement(Capture, { onResult: (r) => { latest = r } }),
+ )
+ })
+ return {
+ get current() {
+ return latest
+ },
+ async addFiles(files: File[]) {
+ await act(async () => {
+ await latest.addPendingFiles(files)
+ })
+ },
+ }
+}
+
+describe("useFileAttachments — PendingFile width/height", () => {
+ it("carries the image's natural width/height from generateThumbnail onto the PendingFile", async () => {
+ generateThumbnailMock.mockResolvedValue({ blob: { size: 1 } as Blob, width: 1920, height: 1080 })
+
+ const hook = await renderCapture()
+ const file = new File([new Uint8Array([1, 2, 3])], "photo.png", { type: "image/png" })
+ await hook.addFiles([file])
+
+ const pending: PendingFile[] = hook.current.pendingFiles
+ expect(pending).toHaveLength(1)
+ expect(pending[0].width).toBe(1920)
+ expect(pending[0].height).toBe(1080)
+ })
+
+ it("leaves width/height undefined when generateThumbnail returns null (non-image file, or a failed decode)", async () => {
+ generateThumbnailMock.mockResolvedValue(null)
+
+ const hook = await renderCapture()
+ const file = new File(["hello"], "notes.txt", { type: "text/plain" })
+ await hook.addFiles([file])
+
+ const pending: PendingFile[] = hook.current.pendingFiles
+ expect(pending).toHaveLength(1)
+ expect(pending[0].width).toBeUndefined()
+ expect(pending[0].height).toBeUndefined()
+ })
+})
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
index 48ce32917..e7a32888f 100644
--- a/src/web/src/hooks/use-file-attachments.ts
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -8,6 +8,8 @@ export type PendingFile = {
file: File;
thumbnailUrl: string | null;
thumbnailBlob: Blob | null;
+ width?: number;
+ height?: number;
};
export type UseFileAttachmentsOptions = {
@@ -96,9 +98,15 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const pending: PendingFile[] = await Promise.all(
valid.map(async (file) => {
- const blob = await generateThumbnail(file);
- const thumbnailUrl = blob ? URL.createObjectURL(blob) : null;
- return { file, thumbnailUrl, thumbnailBlob: blob };
+ const thumbnail = await generateThumbnail(file);
+ const thumbnailUrl = thumbnail ? URL.createObjectURL(thumbnail.blob) : null;
+ return {
+ file,
+ thumbnailUrl,
+ thumbnailBlob: thumbnail?.blob ?? null,
+ width: thumbnail?.width,
+ height: thumbnail?.height,
+ };
}),
);
diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.ts
index 121fa5437..54651267c 100644
--- a/src/web/src/lib/community/channel-ref-extension.ts
+++ b/src/web/src/lib/community/channel-ref-extension.ts
@@ -107,10 +107,10 @@ const ChannelRefNode = Mention.extend({
*
* `renderText` inserts by display name, not id — server/channel names are
* now guaranteed ref-safe at creation/rename time (`slugify()`, applied by
- * every write route), so `serverName`/`label` always round-trip through
- * `CHANNEL_REF_REGEX` and `resolveChannelRefBase` (exact-string match) just
- * as cleanly as ids used to, but render as something a human can actually
- * read. Falls back to `serverId`/`id` if either name is ever missing
+ * every write route), so `serverName`/`label` round-trip through
+ * `chat-syntax-plugin.ts`'s `CHANNEL_REF_RE` and `resolveChannelRefBase`
+ * (exact-string match) and render as something a human can actually read.
+ * Falls back to `serverId`/`id` if either name is ever missing
* (paste-from-HTML, drag-drop, etc.) — defensive, not the primary
* mechanism. `renderHTML` shows a compact in-editor chip — channel name
* only, not the full path — keeping the compose box readable.
diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.ts
new file mode 100644
index 000000000..eaf73c01b
--- /dev/null
+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts
@@ -0,0 +1,121 @@
+import { describe, it, expect } from "vitest"
+import { unified } from "unified"
+import remarkParse from "remark-parse"
+import type { Root, PhrasingContent } from "mdast"
+import { chatSyntaxPlugin } from "./chat-syntax-plugin"
+import type { MentionNode, ChannelRefNode } from "./chat-syntax-plugin"
+
+function parse(md: string): Root {
+ const processor = unified().use(remarkParse).use(chatSyntaxPlugin)
+ return processor.runSync(processor.parse(md)) as Root
+}
+
+function paragraphChildren(tree: Root): PhrasingContent[] {
+ const para = tree.children[0]
+ if (para?.type !== "paragraph") throw new Error("expected a paragraph")
+ return para.children
+}
+
+describe("chatSyntaxPlugin — mention", () => {
+ it("wraps a bare @name mention", () => {
+ const children = paragraphChildren(parse("hi @Lindsay"))
+ expect(children.map((c) => c.type)).toEqual(["text", "mention"])
+ expect(children[1]).toMatchObject({ value: "@Lindsay", everyone: false })
+ expect((children[1] as MentionNode).discriminator).toBeUndefined()
+ })
+
+ it("splits a @name#0042 handle into a bare mention + discriminator", () => {
+ const children = paragraphChildren(parse("hi @Gus#0042"))
+ expect(children[1]).toMatchObject({ type: "mention", value: "@Gus", everyone: false, discriminator: "0042" })
+ })
+
+ it("does not truncate a 5+ digit run into a false-positive discriminator", () => {
+ const children = paragraphChildren(parse("hi @Gus#00423"))
+ expect(children.map((c) => c.type)).toEqual(["text", "mention", "text"])
+ expect(children[1]).toMatchObject({ value: "@Gus", everyone: false })
+ expect(children[2]).toMatchObject({ type: "text", value: "#00423" })
+ })
+
+ it("flags @everyone", () => {
+ const children = paragraphChildren(parse("cc @everyone"))
+ expect(children[1]).toMatchObject({ type: "mention", value: "@everyone", everyone: true })
+ })
+
+ it("flags @here", () => {
+ const children = paragraphChildren(parse("@here ping"))
+ expect(children[0]).toMatchObject({ type: "mention", value: "@here", everyone: true })
+ })
+
+ it("supports Unicode names (李四, José, Ünal) — the #4 charset fix", () => {
+ expect(paragraphChildren(parse("hi @李四"))[1]).toMatchObject({ value: "@李四", everyone: false })
+ expect(paragraphChildren(parse("hi @José"))[1]).toMatchObject({ value: "@José", everyone: false })
+ expect(paragraphChildren(parse("hi @Ünal"))[1]).toMatchObject({ value: "@Ünal", everyone: false })
+ })
+
+ it("leaves an @mention inside inline code literal", () => {
+ const children = paragraphChildren(parse("use `@Lindsay` here"))
+ expect(children.map((c) => c.type)).toEqual(["text", "inlineCode", "text"])
+ })
+
+ it("leaves an @mention inside a fenced code block literal", () => {
+ const tree = parse("```\n@Lindsay\n```")
+ expect(tree.children.map((c) => c.type)).toEqual(["code"])
+ })
+})
+
+describe("chatSyntaxPlugin — channelRef", () => {
+ it("wraps /server/channel preceded by a space or at start-of-string", () => {
+ expect(paragraphChildren(parse("see /studio/general"))[1]).toMatchObject({ type: "channelRef", value: "/studio/general" })
+ expect(paragraphChildren(parse("/studio/general"))[0]).toMatchObject({ type: "channelRef", value: "/studio/general" })
+ })
+
+ it("leaves text/studio/general (no leading space) untouched", () => {
+ const children = paragraphChildren(parse("text/studio/general"))
+ expect(children).toHaveLength(1)
+ expect(children[0]).toMatchObject({ type: "text", value: "text/studio/general" })
+ })
+
+ it("does NOT wrap a 3+-segment docs-style path — trailing /segment fails the terminator boundary", () => {
+ expect(paragraphChildren(parse("look at /api/user/123"))).toHaveLength(1)
+ expect(paragraphChildren(parse("hit /docs/api/v1 first"))).toHaveLength(1)
+ })
+
+ it("still wraps a 2-segment ref followed by punctuation (period, comma, close-paren)", () => {
+ const children = paragraphChildren(parse("see /studio/general."))
+ expect(children.map((c) => c.type)).toEqual(["text", "channelRef", "text"])
+ expect(children[1]).toMatchObject({ value: "/studio/general" })
+ expect(children[2]).toMatchObject({ type: "text", value: "." })
+ })
+
+ it("wraps the thread form /studio/general/#42", () => {
+ const children = paragraphChildren(parse("see /studio/general/#42"))
+ expect(children[1]).toMatchObject({ type: "channelRef", value: "/studio/general/#42" })
+ })
+
+ it("leaves a channel-ref-shaped path inside inline code literal", () => {
+ const children = paragraphChildren(parse("`/studio/general`"))
+ expect(children.map((c) => c.type)).toEqual(["inlineCode"])
+ })
+
+ it("does not double-match a community invite URL — the 3-segment /community/invite/<token> path never satisfies the 2-segment terminator boundary", () => {
+ const bare = paragraphChildren(parse("join /community/invite/abc123XYZ"))
+ expect(bare).toHaveLength(1)
+ expect(bare[0]).toMatchObject({ type: "text", value: "join /community/invite/abc123XYZ" })
+
+ const full = paragraphChildren(parse("join https://alook.ai/community/invite/xY9k2vW7aQ"))
+ expect(full.some((c) => c.type === "channelRef")).toBe(false)
+ })
+})
+
+describe("chatSyntaxPlugin — mixed", () => {
+ it("handles a mix of mention, channelRef, and unrelated formatting in one message", () => {
+ const children = paragraphChildren(parse("Here's the **setup**: `pnpm install` ping @Gus in /studio/dev"))
+ const types = children.map((c) => c.type)
+ expect(types).toContain("strong")
+ expect(types).toContain("inlineCode")
+ const mention = children.find((c): c is MentionNode => c.type === "mention")
+ expect(mention).toMatchObject({ value: "@Gus" })
+ const channelRef = children.find((c): c is ChannelRefNode => c.type === "channelRef")
+ expect(channelRef).toMatchObject({ value: "/studio/dev" })
+ })
+})
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
new file mode 100644
index 000000000..a1ead4608
--- /dev/null
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -0,0 +1,149 @@
+import type { Root, PhrasingContent } from "mdast"
+import { findAndReplace } from "mdast-util-find-and-replace"
+import type { Handler, Handlers } from "mdast-util-to-hast"
+import type { Element } from "hast"
+import type { Plugin } from "unified"
+import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"
+import type { SpoilerNode } from "./spoiler-syntax"
+
+// Chat-only syntax (`||spoiler||`, `@mention`, `/server/channel` refs),
+// parsed as real markdown AST nodes rather than string-spliced HTML tags fed
+// through `rehype-raw`. `mention`/`channelRef` content is always an
+// identifier charset (`\p{L}\p{N}_-` for names, `[A-Za-z0-9_-]` for
+// nanoid-based refs) — `remark-parse` never splits an identifier across
+// sibling text nodes (no markdown metacharacters inside one), so a
+// `mdast-util-find-and-replace` pass is safe for these two. `spoiler` is
+// handled separately by the micromark tokenizer extension in
+// `spoiler-syntax.ts` — see that file's comment for why find-and-replace
+// cannot handle spoilers containing nested formatting.
+
+// Mirrors `CHANNEL_REF_REGEX`'s old doc comment: matches a `/server/channel`
+// or `/server/channel/#N` (thread) ref — the CLI's path grammar
+// (`parseRef`/`formatRef` in `community-cli-contract.ts`). Segment charset
+// `[A-Za-z0-9_-]+` is the nanoid alphabet every `communityServer.id`/
+// `communityChannel.id` is generated with. Trailing
+// `(?=\s|$|[.,;:!?)\]])` boundary lookahead: a 2-segment path followed by
+// ANOTHER `/segment` (e.g. `/api/user/123` in a docs URL) must NOT match —
+// otherwise this regex would greedily take `/api/user` and orphan `/123` as
+// trailing text next to a broken pill. Leading `(?<=^|\s)` lookbehind
+// (verified empirically — a bare leading `\/` with no lookbehind would let
+// this match START mid-path, e.g. matching `/user/123` inside
+// `/api/user/123`): `" /channel-ref"` matches, `"text/channel-ref"` doesn't.
+// Both boundaries are zero-width lookaround (not capture groups) so
+// `findAndReplace` doesn't need to redistribute a leading/trailing text
+// node around the match the way the old string-splice regex's `(^|\s)`
+// capture group did.
+const CHANNEL_REF_RE = /(?<=^|\s)\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+)?(?=\s|$|[.,;:!?)\]])/g
+
+// `@name`, `@name#0042` (disambiguating discriminator), or the literal
+// `@everyone`/`@here` tokens. `\p{L}\p{N}_-` (Unicode-aware, `u` flag) in
+// place of the old `\w` — `Member.name` is a free Unicode string (no
+// charset constraint), so an ASCII-only `\w` silently dropped mentions for
+// names like `李四`/`José`/`Ünal`. The `(?!\d)` lookahead after the
+// discriminator group stops a 5+-digit run from being truncated into a
+// false-positive handle (e.g. `@Gus#00423` must not become `@Gus` + a
+// dangling `#0042` handle).
+const MENTION_RE = /@[\p{L}\p{N}_-]+(?:#\d{4}(?!\d))?/gu
+
+/** mdast node produced by `@name`/`@name#0042`/`@everyone`/`@here`. */
+export interface MentionNode {
+ type: "mention"
+ /** Display name — `#dddd` discriminator, if present, is stripped from here (matches the old `<mention>` tag's content). */
+ value: string
+ everyone: boolean
+ /** The 4-digit discriminator, if the mention carried one (never set for `@everyone`/`@here`). */
+ discriminator?: string
+}
+
+/** mdast node produced by a `/server/channel` or `/server/channel/#N` ref. */
+export interface ChannelRefNode {
+ type: "channelRef"
+ value: string
+}
+
+declare module "mdast" {
+ interface RootContentMap {
+ mention: MentionNode
+ channelRef: ChannelRefNode
+ }
+ interface PhrasingContentMap {
+ mention: MentionNode
+ channelRef: ChannelRefNode
+ }
+}
+
+// `ignore` list mirrors mdast-util-find-and-replace's own default protection
+// for GFM autolinks/definitions, plus `code`/`inlineCode` so `@fake-mention`,
+// `#0042`, `/server/channel`, and `||spoiler||` all stay literal inside a
+// code span or fenced code block — replacing the old `preprocessMarkdown`'s
+// manual stash/unstash sentinel dance, which existed only because that
+// implementation operated on a raw string before markdown parsing.
+const IGNORE_NODE_TYPES = ["code", "inlineCode", "link", "linkReference"]
+
+function mentionReplacer(value: string): MentionNode {
+ const everyone = value === "@everyone" || value === "@here"
+ if (everyone) return { type: "mention", value, everyone: true }
+ const tag = /#(\d{4})$/.exec(value)
+ const bare = value.replace(/#\d{4}$/, "")
+ return tag ? { type: "mention", value: bare, everyone: false, discriminator: tag[1] } : { type: "mention", value: bare, everyone: false }
+}
+
+function channelRefReplacer(value: string): ChannelRefNode {
+ return { type: "channelRef", value }
+}
+
+/**
+ * remark plugin: combines the spoiler micromark extension (`spoiler-syntax.ts`)
+ * with a `mdast-util-find-and-replace` pass for `mention`/`channelRef`.
+ * Registers `spoilerSyntax`'s micromark/from-markdown extensions on the
+ * processor (the `remark-gfm`-style `this.data(...)` convention) and returns
+ * a tree transform running the find-and-replace pass after parsing.
+ */
+export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this: import("unified").Processor) {
+ type ProcessorData = { micromarkExtensions?: unknown[]; fromMarkdownExtensions?: unknown[] }
+ const settings = this.data() as ProcessorData
+ const micromarkExtensions = (settings.micromarkExtensions ??= [])
+ const fromMarkdownExtensions = (settings.fromMarkdownExtensions ??= [])
+ micromarkExtensions.push(spoilerSyntax())
+ fromMarkdownExtensions.push(spoilerFromMarkdown())
+
+ return function transform(tree: Root): void {
+ findAndReplace(
+ tree,
+ [
+ [MENTION_RE, mentionReplacer as unknown as (value: string, ...rest: unknown[]) => PhrasingContent | string | false],
+ [CHANNEL_REF_RE, channelRefReplacer as unknown as (value: string) => PhrasingContent],
+ ],
+ { ignore: IGNORE_NODE_TYPES },
+ )
+ }
+}
+
+// `remarkRehypeOptions.handlers` — converts each custom mdast node directly
+// into a hast element, skipping the HTML-string round-trip entirely. Tag
+// names/attributes match the old string-spliced tags exactly
+// (`<spoiler>`/`<mention data-everyone/data-tag>`/`<channelref>`) so
+// `MD_ALLOWED_TAGS`/`MD_COMPONENTS` in `message-markdown.tsx` need no change.
+export const chatSyntaxHandlers: Handlers = {
+ spoiler: ((state, node: SpoilerNode): Element => ({
+ type: "element",
+ tagName: "spoiler",
+ properties: {},
+ children: state.all(node),
+ })) as Handler,
+ mention: ((_state, node: MentionNode): Element => ({
+ type: "element",
+ tagName: "mention",
+ properties: {
+ ...(node.everyone ? { dataEveryone: "1" } : {}),
+ ...(node.discriminator ? { dataTag: node.discriminator } : {}),
+ },
+ children: [{ type: "text", value: node.value }],
+ })) as Handler,
+ channelRef: ((_state, node: ChannelRefNode): Element => ({
+ type: "element",
+ tagName: "channelref",
+ properties: {},
+ children: [{ type: "text", value: node.value }],
+ })) as Handler,
+}
diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.ts
index 3b42831f8..c34bfc3cf 100644
--- a/src/web/src/lib/community/mention-extension.test.ts
+++ b/src/web/src/lib/community/mention-extension.test.ts
@@ -333,4 +333,11 @@ describe("detectMentionType", () => {
expect(detectMentionType("(@everyone)")).toBe("everyone")
expect(detectMentionType("@everyone,")).toBe("everyone")
})
+
+ it("does not treat a Unicode letter immediately after the token as a boundary — the #4 charset fix", () => {
+ // Before the fix, `ID` was ASCII-only (`[A-Za-z0-9_]`), so `ä` in
+ // `@hereäx` was wrongly treated as a non-identifier boundary character,
+ // making `@hereäx` look like a genuine standalone `@here` token.
+ expect(detectMentionType("cc @hereäx")).toBe(undefined)
+ })
})
diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.ts
index c022ca9d3..74451cfcc 100644
--- a/src/web/src/lib/community/mention-extension.ts
+++ b/src/web/src/lib/community/mention-extension.ts
@@ -216,7 +216,12 @@ export function buildCommunityMentionExtension(opts: {
*/
export function detectMentionType(text: string): MentionType | undefined {
if (!text) return undefined
- const ID = /[A-Za-z0-9_]/
+ // Unicode-aware (`\p{L}\p{N}_-`) — must agree with the display-side regex
+ // in `chat-syntax-plugin.ts` and the server-side boundary check in
+ // `community-mentions.ts`'s `ID_CHAR_RE`, or a name like `@hereäx` would
+ // disagree across surfaces on whether the literal `@here` token is a
+ // genuine standalone mention vs. part of a longer word.
+ const ID = /[\p{L}\p{N}_-]/u
for (const name of MENTION_TYPES) {
let i = 0
while (i < text.length) {
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index cacb310f4..5442e660a 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -247,6 +247,49 @@ describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-conditi
})
})
+describe("createCommunityMessage — attachment width/height reach the live WS broadcast", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
+ mockFanOutToChannel.mockResolvedValue(undefined)
+ mockFanOutToDM.mockResolvedValue(undefined)
+ mockBroadcastToUser.mockResolvedValue(undefined)
+ })
+
+ it("includes width/height on an image attachment in the MESSAGE_CREATE broadcast payload", async () => {
+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })
+ mockCreateAttachment.mockResolvedValue({
+ id: "att_1",
+ filename: "photo.png",
+ url: "/media/photo.png",
+ contentType: "image/png",
+ size: 1000,
+ width: 1920,
+ height: 1080,
+ })
+ mockGetMessage.mockResolvedValue(messageRow())
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: {
+ content: "hello",
+ attachments: [
+ { url: "/media/photo.png", filename: "photo.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
+ ],
+ },
+ })
+
+ expect(mockCreateAttachment).toHaveBeenCalledWith({}, expect.objectContaining({ width: 1920, height: 1080 }))
+ expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)
+ const [, event] = mockFanOutToChannel.mock.calls[0]!
+ expect(event.message.attachments).toEqual([
+ expect.objectContaining({ width: 1920, height: 1080 }),
+ ])
+ })
+})
+
describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index e98cf5d7b..31ec517db 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -28,6 +28,8 @@ type IncomingAttachment = {
filename: string
contentType: string
size: number
+ width?: number
+ height?: number
}
export type IncomingMessageBody = {
@@ -43,6 +45,8 @@ type CreatedAttachment = {
url: string
contentType: string | null
size: number | null
+ width?: number | null
+ height?: number | null
}
type FullMessageRow = NonNullable<
@@ -161,6 +165,8 @@ export async function createCommunityMessage(params: {
url: att.url,
contentType: att.contentType,
size: att.size,
+ width: att.width,
+ height: att.height,
}),
),
)
@@ -297,6 +303,8 @@ export async function createCommunityMessage(params: {
url: a.url,
contentType: a.contentType ?? undefined,
size: a.size ?? undefined,
+ width: a.width ?? undefined,
+ height: a.height ?? undefined,
})),
})
diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.ts
index 8d77f31df..8a4f9578a 100644
--- a/src/web/src/lib/community/message-payload.test.ts
+++ b/src/web/src/lib/community/message-payload.test.ts
@@ -42,12 +42,23 @@ describe("mapMessageForApi", () => {
expect(out.authorAvatar).toBe("A")
})
- it("hides `type: default` (undefined) and surfaces `system` verbatim", () => {
- expect(mapMessageForApi({ ...baseRow, type: null }, emptyApiCtx).type).toBeUndefined()
- expect(mapMessageForApi({ ...baseRow, type: "default" }, emptyApiCtx).type).toBeUndefined()
+ it("maps ordinary rows to type: \"chat\" (never undefined — #12's exhaustive discriminator) and surfaces `system` verbatim", () => {
+ expect(mapMessageForApi({ ...baseRow, type: null }, emptyApiCtx).type).toBe("chat")
+ expect(mapMessageForApi({ ...baseRow, type: "default" }, emptyApiCtx).type).toBe("chat")
expect(mapMessageForApi({ ...baseRow, type: "system" }, emptyApiCtx).type).toBe("system")
})
+ it("splits `type: \"thread_created\"` into { type: \"system\", systemKind: \"thread\" }", () => {
+ const out = mapMessageForApi({ ...baseRow, type: "thread_created" }, emptyApiCtx)
+ expect(out.type).toBe("system")
+ expect(out.systemKind).toBe("thread")
+ })
+
+ it("a bare `type: \"system\"` row (no known kind) omits systemKind", () => {
+ const out = mapMessageForApi({ ...baseRow, type: "system" }, emptyApiCtx)
+ expect(out.systemKind).toBeUndefined()
+ })
+
it("resolves replyTo from an in-scope replyMap entry", () => {
const replyMap = new Map([["m0", { id: "m0", authorName: "Bob", content: "hey there" }]])
const out = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap })
@@ -97,12 +108,28 @@ describe("mapMessageForApi", () => {
})
describe("mapMessageForWs", () => {
- it("returns type: default explicitly (WS convention differs from API)", () => {
- expect(mapMessageForWs({ ...baseRow, type: null }, emptyWsCtx).type).toBe("default")
- expect(mapMessageForWs({ ...baseRow, type: "default" }, emptyWsCtx).type).toBe("default")
+ it("maps ordinary rows to type: \"chat\" (was \"default\" before #12's exhaustive discriminator)", () => {
+ expect(mapMessageForWs({ ...baseRow, type: null }, emptyWsCtx).type).toBe("chat")
+ expect(mapMessageForWs({ ...baseRow, type: "default" }, emptyWsCtx).type).toBe("chat")
expect(mapMessageForWs({ ...baseRow, type: "system" }, emptyWsCtx).type).toBe("system")
})
+ it("splits `type: \"thread_created\"` into { type: \"system\", systemKind: \"thread\" } for both mappers", () => {
+ const wsOut = mapMessageForWs({ ...baseRow, type: "thread_created" }, emptyWsCtx)
+ expect(wsOut.type).toBe("system")
+ expect(wsOut.systemKind).toBe("thread")
+
+ const apiOut = mapMessageForApi({ ...baseRow, type: "thread_created" }, emptyApiCtx)
+ expect(apiOut.type).toBe("system")
+ expect(apiOut.systemKind).toBe("thread")
+ })
+
+ it("a bare `type: \"system\"` row (no known kind) round-trips to { type: \"system\" } with systemKind omitted", () => {
+ const out = mapMessageForWs({ ...baseRow, type: "system" }, emptyWsCtx)
+ expect(out.type).toBe("system")
+ expect(out.systemKind).toBeUndefined()
+ })
+
it("carries replyTo and mentionType — regression for the thread-payload skip bug", () => {
const replyMap = new Map([["m0", { id: "m0", authorName: "Bob", content: "hey there" }]])
const out = mapMessageForWs(
@@ -135,6 +162,18 @@ describe("mapMessageForWs", () => {
expect(mapMessageForWs(baseRow, emptyWsCtx).attachments).toBeUndefined()
})
+ it("includes width/height on an image attachment when present on the input", () => {
+ const out = mapMessageForWs(baseRow, {
+ ...emptyWsCtx,
+ attachments: [
+ { id: "a1", filename: "x.png", url: "/x.png", contentType: "image/png", size: 4096, width: 1920, height: 1080 },
+ ],
+ })
+ expect(out.attachments).toEqual([
+ { id: "a1", filename: "x.png", url: "/x.png", contentType: "image/png", size: 4096, width: 1920, height: 1080 },
+ ])
+ })
+
it("coerces null content to empty string (attachments-only message)", () => {
expect(mapMessageForWs({ ...baseRow, content: null }, emptyWsCtx).content).toBe("")
})
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index e70b04a25..0d0ee8e80 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -39,8 +39,8 @@ export type MessageRow = {
type ReplyTargetRow = { id: string; authorName: string; content: string | null }
-type UiAttachment = { kind: "image" | "file"; name: string; url: string; size?: string }
-type WsAttachment = { id: string; filename: string; url: string; contentType?: string; size?: number }
+type UiAttachment = { kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }
+type WsAttachment = { id: string; filename: string; url: string; contentType?: string; size?: number; width?: number; height?: number }
type UiReaction = { emoji: string; count: number; me: boolean; userIds: string[] }
type ReplyPreview = { id: string; authorName: string; text: string; deleted?: boolean }
@@ -91,14 +91,29 @@ export type ApiMessageContext = {
threadByMessageId?: Map<string, ThreadPreview>
}
+// Splits the DB's `type` column value into the wire's `{ type, systemKind }`
+// pair. `"thread_created"` was already documented above (and in the shared
+// WS type, `CommunityMessageCreate.message.type`) as a possible column
+// value — verified it was never actually written by any insert anywhere in
+// this codebase, purely a placeholder for exactly this feature. Reused
+// here (rather than inventing a new convention value) since it maps to
+// `{ type: "system", systemKind: "thread" }` so `message.tsx`'s icon branch
+// can distinguish it from a bare `type: "system"` row with no known kind
+// (which stays `systemKind: undefined`, falling back to the generic icon).
+// Ordinary messages map to `type: "chat"` (never `undefined`) now that
+// `Msg.type` is a required, exhaustive discriminator (#12).
+function splitType(type: string | null): { type: "chat" | "system"; systemKind?: "thread" } {
+ if (type === "thread_created") return { type: "system", systemKind: "thread" }
+ if (type === "system") return { type: "system" }
+ return { type: "chat" }
+}
+
export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {
const core = coreFields(row)
const thread = ctx.threadByMessageId?.get(row.id)
return {
...core,
- // GET convention: hide "default" (undefined = default). Preserved from
- // the pre-refactor per-route behaviour.
- type: row.type === "system" ? ("system" as const) : undefined,
+ ...splitType(row.type),
replyTo: resolveReply(row, ctx.replyMap),
embeds: row.embeds,
attachments: ctx.attachmentsByMessage[row.id]?.length ? ctx.attachmentsByMessage[row.id] : undefined,
@@ -116,9 +131,7 @@ export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext) {
const core = coreFields(row)
return {
...core,
- // WS convention: return "default" explicitly. Matches CommunityMessageCreate
- // in @alook/shared where `type?: "default" | "system" | "thread_created"`.
- type: (row.type as "default" | "system" | "thread_created") ?? "default",
+ ...splitType(row.type),
replyTo: resolveReply(row, ctx.replyMap),
// The shared CommunityMessageCreate.embeds is `unknown[]` — narrow here
// rather than widening the wire type.
@@ -131,6 +144,8 @@ export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext) {
url: a.url,
contentType: a.contentType,
size: a.size,
+ width: a.width,
+ height: a.height,
}))
: undefined,
}
diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.ts
new file mode 100644
index 000000000..3f82b27dd
--- /dev/null
+++ b/src/web/src/lib/community/messages.test.ts
@@ -0,0 +1,38 @@
+import { describe, it, expect } from "vitest"
+import { groupAttachments } from "./messages"
+
+// No test file covered `groupAttachments` before this — it was only
+// exercised indirectly through route tests. `width`/`height` are optional
+// fields on the output shape, which per a plan review of
+// plans/attachment-image-dimensions.md means an implementation could omit
+// them from the `entry` object literal (and its `as {...}` cast) with zero
+// typecheck error — assert on the actual returned value, not just the
+// declared type, to catch that.
+describe("groupAttachments", () => {
+ it("projects width/height onto an image-kind entry when present on the row", () => {
+ const result = groupAttachments([
+ { messageId: "m1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
+ ])
+ expect(result.m1).toEqual([
+ { kind: "image", name: "a.png", url: "/a.png", width: 1920, height: 1080 },
+ ])
+ })
+
+ it("leaves width/height undefined on an image-kind entry when the row has none", () => {
+ const result = groupAttachments([
+ { messageId: "m1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000, width: null, height: null },
+ ])
+ expect(result.m1).toEqual([
+ { kind: "image", name: "a.png", url: "/a.png", width: undefined, height: undefined },
+ ])
+ })
+
+ it("never adds width/height to a file-kind entry, even if present on the row", () => {
+ const result = groupAttachments([
+ { messageId: "m1", filename: "a.pdf", url: "/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },
+ ])
+ expect(result.m1).toEqual([
+ { kind: "file", name: "a.pdf", url: "/a.pdf", size: "2.0 KB" },
+ ])
+ })
+})
diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.ts
index 2ae7eb35c..14165f223 100644
--- a/src/web/src/lib/community/messages.ts
+++ b/src/web/src/lib/community/messages.ts
@@ -122,12 +122,18 @@ export function buildMemberPaginatedResponse<T extends { joinedAt: string; id: s
// Group raw attachment rows by messageId into display format
export function groupAttachments(
- attachments: Array<{ messageId: string; filename: string; url: string; contentType: string | null; size: number | null }>
-): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string }>> {
- const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string }>> = {}
+ attachments: Array<{ messageId: string; filename: string; url: string; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>
+): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> {
+ const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> = {}
for (const a of attachments) {
const kind = a.contentType?.startsWith("image/") ? "image" : "file"
- const entry = { kind, name: a.filename, url: a.url, ...(kind === "file" && a.size ? { size: formatBytes(a.size) } : {}) } as { kind: "image" | "file"; name: string; url: string; size?: string }
+ const entry = {
+ kind,
+ name: a.filename,
+ url: a.url,
+ ...(kind === "file" && a.size ? { size: formatBytes(a.size) } : {}),
+ ...(kind === "image" ? { width: a.width ?? undefined, height: a.height ?? undefined } : {}),
+ } as { kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }
;(map[a.messageId] ??= []).push(entry)
}
return map
diff --git a/src/web/src/lib/community/spoiler-syntax.test.ts b/src/web/src/lib/community/spoiler-syntax.test.ts
new file mode 100644
index 000000000..8d8422819
--- /dev/null
+++ b/src/web/src/lib/community/spoiler-syntax.test.ts
@@ -0,0 +1,67 @@
+import { describe, it, expect } from "vitest"
+import { fromMarkdown } from "mdast-util-from-markdown"
+import type { Root, PhrasingContent } from "mdast"
+import { spoilerSyntax, spoilerFromMarkdown, type SpoilerNode } from "./spoiler-syntax"
+
+function parse(md: string): Root {
+ return fromMarkdown(md, {
+ extensions: [spoilerSyntax()],
+ mdastExtensions: [spoilerFromMarkdown()],
+ })
+}
+
+function paragraphChildren(tree: Root): PhrasingContent[] {
+ const para = tree.children[0]
+ if (para?.type !== "paragraph") throw new Error("expected a paragraph")
+ return para.children
+}
+
+describe("spoilerSyntax", () => {
+ it("produces a spoiler node for a bare ||secret||", () => {
+ const children = paragraphChildren(parse("psst ||secret||"))
+ expect(children.map((c) => c.type)).toEqual(["text", "spoiler"])
+ const spoiler = children[1] as SpoilerNode
+ expect(spoiler.children).toHaveLength(1)
+ expect(spoiler.children[0]).toMatchObject({ type: "text", value: "secret" })
+ })
+
+ it("produces a spoiler node CONTAINING a nested strong node for nested formatting — the verified regression case", () => {
+ // A text-node find-and-replace pass (mdast-util-find-and-replace) cannot
+ // handle this: remark-parse splits this input into 3 sibling nodes
+ // (text, strong, text) before any post-processing plugin runs, so the
+ // two `|` markers never co-occur in one text node to match against.
+ // The micromark tokenizer extension recognizes the `||` boundary during
+ // tokenization instead — the same phase that recognizes `**` — so this
+ // must NOT silently fail to match.
+ const children = paragraphChildren(parse("hello ||I think **this** is neat|| world"))
+ expect(children.map((c) => c.type)).toEqual(["text", "spoiler", "text"])
+ const spoiler = children[1] as SpoilerNode
+ expect(spoiler.children.map((c) => c.type)).toEqual(["text", "strong", "text"])
+ const strong = spoiler.children[1]
+ expect(strong).toMatchObject({ type: "strong" })
+ })
+
+ it("does not convert spoiler markers inside an inline code span", () => {
+ const children = paragraphChildren(parse("use `||x||` here"))
+ expect(children.map((c) => c.type)).toEqual(["text", "inlineCode", "text"])
+ expect(children[1]).toMatchObject({ type: "inlineCode", value: "||x||" })
+ })
+
+ it("does not convert spoiler markers inside a fenced code block", () => {
+ const tree = parse("```\n||x||\n```")
+ expect(tree.children.map((c) => c.type)).toEqual(["code"])
+ expect(tree.children[0]).toMatchObject({ value: "||x||" })
+ })
+
+ it("leaves an unterminated ||text (no closing pair) as literal text", () => {
+ const children = paragraphChildren(parse("||text with no close"))
+ expect(children).toHaveLength(1)
+ expect(children[0]).toMatchObject({ type: "text", value: "||text with no close" })
+ })
+
+ it("does not convert a lone single | (e.g. inside a table row) into a spoiler boundary", () => {
+ const children = paragraphChildren(parse("a | b"))
+ expect(children).toHaveLength(1)
+ expect(children[0]).toMatchObject({ type: "text", value: "a | b" })
+ })
+})
diff --git a/src/web/src/lib/community/spoiler-syntax.ts b/src/web/src/lib/community/spoiler-syntax.ts
new file mode 100644
index 000000000..4f3e479bf
--- /dev/null
+++ b/src/web/src/lib/community/spoiler-syntax.ts
@@ -0,0 +1,170 @@
+import { splice } from "micromark-util-chunked"
+import { classifyCharacter } from "micromark-util-classify-character"
+import { resolveAll } from "micromark-util-resolve-all"
+import { codes } from "micromark-util-symbol"
+import type { Construct, Effects, Event, Extension, State, Token, TokenizeContext } from "micromark-util-types"
+import type { CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle } from "mdast-util-from-markdown"
+
+// Discord-style `||spoiler||` — a micromark inline tokenizer extension +
+// mdast-util-from-markdown extension, structurally mirroring
+// micromark-extension-gfm-strikethrough/mdast-util-gfm-strikethrough (`~~text~~`)
+// with `|` (code 124) in place of `~` (code 126). Recognizing the `||`
+// boundary during TOKENIZATION (the same phase that recognizes `**`/`*`/`` ` ``)
+// — rather than as a text-node find-and-replace pass after parsing — is what
+// lets `||I think **this** is neat||` correctly produce a `spoiler` node
+// containing a nested `strong` node. A text-node find-and-replace can't do
+// this: remark-parse would already have split that input into 3 sibling
+// nodes (text, strong, text) before any post-processing plugin runs, so the
+// two `|` markers never co-occur in one text node to match against.
+
+declare module "micromark-util-types" {
+ interface TokenTypeMap {
+ spoilerSequence: "spoilerSequence"
+ spoilerSequenceTemporary: "spoilerSequenceTemporary"
+ spoiler: "spoiler"
+ spoilerText: "spoilerText"
+ }
+}
+
+declare module "mdast" {
+ interface RootContentMap {
+ spoiler: SpoilerNode
+ }
+ interface PhrasingContentMap {
+ spoiler: SpoilerNode
+ }
+}
+
+/** mdast node produced by `||...||` — a phrasing-content parent, like `emphasis`/`strong`. */
+export interface SpoilerNode {
+ type: "spoiler"
+ children: import("mdast").PhrasingContent[]
+}
+
+/** Micromark extension enabling `||...||` spoiler syntax during tokenization. */
+export function spoilerSyntax(): Extension {
+ const tokenizer: Construct = {
+ name: "spoiler",
+ tokenize: tokenizeSpoiler,
+ resolveAll: resolveAllSpoiler,
+ }
+ return {
+ text: { [codes.verticalBar]: tokenizer },
+ insideSpan: { null: [tokenizer] },
+ attentionMarkers: { null: [codes.verticalBar] },
+ }
+
+ function resolveAllSpoiler(events: Event[], context: TokenizeContext): Event[] {
+ let index = -1
+ while (++index < events.length) {
+ if (
+ events[index][0] === "enter" &&
+ events[index][1].type === "spoilerSequenceTemporary" &&
+ events[index][1]._close
+ ) {
+ let open = index
+ while (open--) {
+ if (
+ events[open][0] === "exit" &&
+ events[open][1].type === "spoilerSequenceTemporary" &&
+ events[open][1]._open &&
+ events[index][1].end.offset - events[index][1].start.offset ===
+ events[open][1].end.offset - events[open][1].start.offset
+ ) {
+ events[index][1].type = "spoilerSequence"
+ events[open][1].type = "spoilerSequence"
+
+ const spoiler: Token = {
+ type: "spoiler",
+ start: Object.assign({}, events[open][1].start),
+ end: Object.assign({}, events[index][1].end),
+ }
+ const text: Token = {
+ type: "spoilerText",
+ start: Object.assign({}, events[open][1].end),
+ end: Object.assign({}, events[index][1].start),
+ }
+
+ const nextEvents: Event[] = [
+ ["enter", spoiler, context],
+ ["enter", events[open][1], context],
+ ["exit", events[open][1], context],
+ ["enter", text, context],
+ ]
+ const insideSpan = context.parser.constructs.insideSpan.null
+ if (insideSpan) {
+ splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context))
+ }
+ splice(nextEvents, nextEvents.length, 0, [
+ ["exit", text, context],
+ ["enter", events[index][1], context],
+ ["exit", events[index][1], context],
+ ["exit", spoiler, context],
+ ])
+ splice(events, open - 1, index - open + 3, nextEvents)
+ index = open + nextEvents.length - 2
+ break
+ }
+ }
+ }
+ }
+ index = -1
+ while (++index < events.length) {
+ if (events[index][1].type === "spoilerSequenceTemporary") {
+ events[index][1].type = "data"
+ }
+ }
+ return events
+ }
+
+ function tokenizeSpoiler(this: TokenizeContext, effects: Effects, ok: State, nok: State): State {
+ const previous = this.previous
+ const events = this.events
+ let size = 0
+ return start
+
+ function start(code: Parameters<State>[0]): State | undefined {
+ if (previous === codes.verticalBar && events[events.length - 1][1].type !== "characterEscape") {
+ return nok(code)
+ }
+ effects.enter("spoilerSequenceTemporary")
+ return more(code)
+ }
+
+ function more(code: Parameters<State>[0]): State | undefined {
+ const before = classifyCharacter(previous)
+ if (code === codes.verticalBar) {
+ if (size > 1) return nok(code)
+ effects.consume(code)
+ size++
+ return more
+ }
+ // Only the doubled `||` marker forms a spoiler boundary — a lone `|`
+ // (e.g. inside a table row, which this codebase's Streamdown/GFM
+ // pipeline also parses) must fall through untouched.
+ if (size < 2) return nok(code)
+ const token = effects.exit("spoilerSequenceTemporary")
+ const after = classifyCharacter(code)
+ token._open = !after || (after === 2 && Boolean(before))
+ token._close = !before || (before === 2 && Boolean(after))
+ return ok(code)
+ }
+ }
+}
+
+/** mdast-util-from-markdown extension: turns the `spoiler` token into a `spoiler` mdast node. */
+export function spoilerFromMarkdown(): FromMarkdownExtension {
+ return {
+ canContainEols: ["spoiler"],
+ enter: { spoiler: enterSpoiler },
+ exit: { spoiler: exitSpoiler },
+ }
+}
+
+const enterSpoiler: FromMarkdownHandle = function (this: CompileContext, token) {
+ this.enter({ type: "spoiler", children: [] }, token)
+}
+
+const exitSpoiler: FromMarkdownHandle = function (this: CompileContext, token) {
+ this.exit(token)
+}
diff --git a/src/web/src/lib/image-thumbnail.test.ts b/src/web/src/lib/image-thumbnail.test.ts
new file mode 100644
index 000000000..e0b29995f
--- /dev/null
+++ b/src/web/src/lib/image-thumbnail.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { generateThumbnail } from "./image-thumbnail"
+
+// `generateThumbnail` runs entirely against browser APIs (Image decode,
+// canvas draw, URL.createObjectURL) that don't exist under this repo's
+// `environment: "node"` vitest config. Stub the minimal surface it touches —
+// mirrors the existing `vi.stubGlobal("window", ...)` pattern used elsewhere
+// in this repo (see `inbox-filter.test.ts`) rather than pulling in jsdom.
+class FakeImage {
+ onload: (() => void) | null = null
+ onerror: (() => void) | null = null
+ naturalWidth = 0
+ naturalHeight = 0
+ private _src = ""
+ get src() {
+ return this._src
+ }
+ set src(value: string) {
+ this._src = value
+ queueMicrotask(() => {
+ if (FakeImage.nextShouldError) {
+ this.onerror?.()
+ } else {
+ this.naturalWidth = FakeImage.nextWidth
+ this.naturalHeight = FakeImage.nextHeight
+ this.onload?.()
+ }
+ })
+ }
+ static nextWidth = 0
+ static nextHeight = 0
+ static nextShouldError = false
+}
+
+function stubBrowserImageApis() {
+ vi.stubGlobal("Image", FakeImage)
+ vi.stubGlobal("URL", {
+ createObjectURL: vi.fn(() => "blob:fake"),
+ revokeObjectURL: vi.fn(),
+ })
+ vi.stubGlobal("document", {
+ createElement: (tag: string) => {
+ if (tag !== "canvas") throw new Error(`unexpected createElement(${tag})`)
+ return {
+ width: 0,
+ height: 0,
+ getContext: () => ({ drawImage: vi.fn() }),
+ toBlob: (cb: (b: Blob | null) => void) => cb({ size: 1 } as Blob),
+ }
+ },
+ })
+}
+
+describe("generateThumbnail", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ FakeImage.nextShouldError = false
+ })
+
+ it("returns the source image's natural width/height alongside the thumbnail blob", async () => {
+ stubBrowserImageApis()
+ FakeImage.nextWidth = 1920
+ FakeImage.nextHeight = 1080
+
+ const file = new File([new Uint8Array([1, 2, 3])], "photo.png", { type: "image/png" })
+ const result = await generateThumbnail(file)
+
+ expect(result).not.toBeNull()
+ expect(result?.width).toBe(1920)
+ expect(result?.height).toBe(1080)
+ expect(result?.blob).toBeTruthy()
+ })
+
+ it("returns null for a non-image file, without touching any browser API", async () => {
+ // Deliberately no stubBrowserImageApis() call — if generateThumbnail's
+ // early-return guard were removed, this would throw on `document` being
+ // undefined rather than returning null, so this test doubles as a guard
+ // against that regression.
+ const file = new File(["hello"], "notes.txt", { type: "text/plain" })
+ const result = await generateThumbnail(file)
+ expect(result).toBeNull()
+ })
+
+ it("returns null when the image fails to decode (e.g. a corrupt file with a spoofed image MIME type)", async () => {
+ stubBrowserImageApis()
+ FakeImage.nextShouldError = true
+
+ const file = new File([new Uint8Array([0, 0, 0])], "fake.png", { type: "image/png" })
+ const result = await generateThumbnail(file)
+
+ expect(result).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/image-thumbnail.ts b/src/web/src/lib/image-thumbnail.ts
index 7b2e15296..8a37453e2 100644
--- a/src/web/src/lib/image-thumbnail.ts
+++ b/src/web/src/lib/image-thumbnail.ts
@@ -1,6 +1,8 @@
const MAX_SIZE = 200;
-export async function generateThumbnail(file: File): Promise<Blob | null> {
+export type ThumbnailResult = { blob: Blob; width: number; height: number };
+
+export async function generateThumbnail(file: File): Promise<ThumbnailResult | null> {
if (!file.type.startsWith("image/") || file.type === "image/svg+xml") return null;
let objectUrl: string | undefined;
@@ -16,7 +18,9 @@ export async function generateThumbnail(file: File): Promise<Blob | null> {
if (!ctx) return null;
ctx.drawImage(img, 0, 0, w, h);
- return await canvasToBlob(canvas, "image/jpeg", 0.7);
+ const blob = await canvasToBlob(canvas, "image/jpeg", 0.7);
+ if (!blob) return null;
+ return { blob, width: img.naturalWidth, height: img.naturalHeight };
} catch {
return null;
} finally {
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index cd52eba6c..f7f5f5ccf 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -68,7 +68,7 @@ type CommunitySubscription = {
type CommunityUiHandlers = {
previewImage?: (url: string) => void
- openProfile?: (name: string, e: React.MouseEvent, discriminator?: string) => void
+ openProfile?: (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => void
goBackMobile?: () => void
}
@@ -218,8 +218,8 @@ export const useCurrentChannelMeta = () =>
*/
const stableUiHandlers: CommunityUiHandlers = {
previewImage: (url) => useCommunityStore.getState().uiHandlers.previewImage?.(url),
- openProfile: (name, e, discriminator) =>
- useCommunityStore.getState().uiHandlers.openProfile?.(name, e, discriminator),
+ openProfile: (name, e, discriminator, userId) =>
+ useCommunityStore.getState().uiHandlers.openProfile?.(name, e, discriminator, userId),
goBackMobile: () => useCommunityStore.getState().uiHandlers.goBackMobile?.(),
}
export const useUiHandlers = () => stableUiHandlers
diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.ts
index da4d04a65..d6c38d42b 100644
--- a/src/web/src/stores/community/ws.ts
+++ b/src/web/src/stores/community/ws.ts
@@ -27,7 +27,7 @@ import { create } from "zustand"
export const SEEN_MESSAGE_MAX = 500
export const SEEN_MESSAGE_TRIM_TO = 400
-export type UserStatus = { emoji: string | null; text: string | null }
+type UserStatus = { emoji: string | null; text: string | null }
export type CommunityWsStoreState = {
/**