Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): #NUMBER message-ref pills with out-of-window context sheet

Gusd393a015a222
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index bd6a7ec00..ce3f3422d 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -375,6 +375,7 @@ const listedMessageProjection = {
replyToId: communityMessage.replyToId,
embeds: communityMessage.embeds,
flags: communityMessage.flags,
+ seq: communityMessage.seq,
createdAt: communityMessage.createdAt,
channelId: communityMessage.channelId,
dmConversationId: communityMessage.dmConversationId,
@@ -392,6 +393,7 @@ export type ListedMessageRow = {
replyToId: string | null;
embeds: unknown | undefined;
flags: number | null;
+ seq: number;
createdAt: string;
channelId: string | null;
dmConversationId: string | null;
diff --git a/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts
new file mode 100644
index 000000000..f874acc40
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/messages/seq/[seq]/route.ts
@@ -0,0 +1,41 @@
+import { NextRequest } from "next/server"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import { queries } from "@alook/shared"
+import { requireChannelMember } from "@/lib/community/permissions"
+
+/**
+ * GET /api/community/channels/:id/messages/seq/:seq
+ *
+ * Resolve a seq number to its message ID within a channel. Used for message
+ * ref jumping: when the user clicks #123 and that message isn't loaded, we
+ * need its ID to trigger an anchor fetch.
+ *
+ * Returns: { id: string } | { error: "not_found" }
+ */
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const channelId = ctx.params?.id
+ const seqStr = ctx.params?.seq
+ if (typeof channelId !== "string" || typeof seqStr !== "string") {
+ return writeJSON({ error: "invalid_params" }, 400)
+ }
+
+ const seq = parseInt(seqStr, 10)
+ if (isNaN(seq) || seq <= 0) {
+ return writeJSON({ error: "invalid_seq" }, 400)
+ }
+
+ const db = getDb(ctx.env.DB)
+
+ // Permission check: user must have access to this channel
+ const auth = await requireChannelMember(db, channelId, ctx.userId)
+ if (!auth.ok) return writeError(auth.error, auth.status)
+
+ const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { channelId }, seq)
+ if (!message) {
+ return writeJSON({ error: "not_found" }, 404)
+ }
+
+ return writeJSON({ id: message.id })
+})
diff --git a/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts b/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts
new file mode 100644
index 000000000..214277fda
--- /dev/null
+++ b/src/web/src/app/api/community/dm/[id]/messages/seq/[seq]/route.ts
@@ -0,0 +1,41 @@
+import { NextRequest } from "next/server"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import { queries } from "@alook/shared"
+import { requireDMParticipant } from "@/lib/community/permissions"
+
+/**
+ * GET /api/community/dm/:id/messages/seq/:seq
+ *
+ * Resolve a seq number to its message ID within a DM. Used for message
+ * ref jumping: when the user clicks #123 and that message isn't loaded, we
+ * need its ID to trigger an anchor fetch.
+ *
+ * Returns: { id: string } | { error: "not_found" }
+ */
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const dmId = ctx.params?.id
+ const seqStr = ctx.params?.seq
+ if (typeof dmId !== "string" || typeof seqStr !== "string") {
+ return writeJSON({ error: "invalid_params" }, 400)
+ }
+
+ const seq = parseInt(seqStr, 10)
+ if (isNaN(seq) || seq <= 0) {
+ return writeJSON({ error: "invalid_seq" }, 400)
+ }
+
+ const db = getDb(ctx.env.DB)
+
+ // Permission check: user must be a participant in this DM
+ const auth = await requireDMParticipant(db, dmId, ctx.userId)
+ if (!auth.ok) return writeError(auth.error, auth.status)
+
+ const message = await queries.communityMessage.getMessageByChannelAndSeq(db, { dmConversationId: dmId }, seq)
+ if (!message) {
+ return writeJSON({ error: "not_found" }, 404)
+ }
+
+ return writeJSON({ id: message.id })
+})
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
index 22851d229..88174848a 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -12,6 +12,7 @@ import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/co
import { ForumView, ForumViewSkeleton } from "@/components/community/forum-view"
import type { NewForumPost } from "@/components/community/create-forum-post"
import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"
+import { MessageContextSheet } from "@/components/community/message-context-sheet"
import { ThreadOpener } from "@/components/community/thread-opener"
import { AddMembersDialog } from "@/components/community/add-members-dialog"
import type { RightPanel, Msg, OpenProfile, Role } from "@/components/community/_types"
@@ -581,6 +582,9 @@ function ChannelView() {
router.push(`/c/channels/${params.serverId}/${id}`)
}, [router, params.serverId])
+ // Message context sheet for unloaded message refs
+ const [contextSheetSeq, setContextSheetSeq] = useState<number | null>(null)
+
// Stable so it doesn't bust the memoized message rows; reads uiHandlers
// lazily through the actions ref (assigned just below).
const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {
@@ -984,6 +988,7 @@ function ChannelView() {
onLoadNewer={fetchNewerMessages}
onJumpToPresent={jumpToPresent}
unreadCount={unreadCount}
+ onOpenContextSheet={setContextSheetSeq}
/>
<Composer
channel={channelName}
@@ -1009,6 +1014,20 @@ function ChannelView() {
/>
)}
{manageMembersDialog}
+ <MessageContextSheet
+ open={contextSheetSeq !== null}
+ onOpenChange={(v) => { if (!v) setContextSheetSeq(null) }}
+ channelId={channelId}
+ targetSeq={contextSheetSeq}
+ pinnedIds={pinnedIds}
+ onOpenContextSheet={setContextSheetSeq}
+ onOpenProfile={openProfile}
+ resolveUserName={resolveUserName}
+ onReply={(target) => {
+ setReplyTo(target)
+ setContextSheetSeq(null)
+ }}
+ />
</>
)
}
@@ -1118,6 +1137,7 @@ function ChannelView() {
onLoadNewer={fetchNewerMessages}
onJumpToPresent={jumpToPresent}
unreadCount={unreadCount}
+ onOpenContextSheet={setContextSheetSeq}
/>
<Composer
channel={channelName}
@@ -1143,6 +1163,20 @@ function ChannelView() {
/>
)}
{manageMembersDialog}
+ <MessageContextSheet
+ open={contextSheetSeq !== null}
+ onOpenChange={(v) => { if (!v) setContextSheetSeq(null) }}
+ channelId={channelId}
+ targetSeq={contextSheetSeq}
+ pinnedIds={pinnedIds}
+ onOpenContextSheet={setContextSheetSeq}
+ onOpenProfile={openProfile}
+ resolveUserName={resolveUserName}
+ onReply={(target) => {
+ setReplyTo(target)
+ setContextSheetSeq(null)
+ }}
+ />
</>
)
}
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 599ee0e4b..3eaf0e631 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -8,6 +8,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 { MessageContextSheet } from "@/components/community/message-context-sheet"
import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"
import type { OpenProfile } from "@/components/community/_types"
import {
@@ -102,6 +103,8 @@ function DmView() {
? undefined
: (readSnapshot?.lastReadMessageId ?? null),
})
+
+ const [contextSheetSeq, setContextSheetSeq] = useState<number | null>(null)
// DM composer has no "current server" — flatten every member server's
// channels into one cross-server candidate list so a `/`-ref can be
// dropped into a DM (see plan community-channel-ref.md §6).
@@ -367,6 +370,7 @@ function DmView() {
onLoadNewer={fetchNewerMessages}
onJumpToPresent={jumpToPresent}
unreadCount={unreadCount}
+ onOpenContextSheet={setContextSheetSeq}
hero={
<>
<div className="relative mb-3 w-fit"><Avatar label={dm.avatar} seed={dm.userId} size={64} /></div>
@@ -396,6 +400,20 @@ function DmView() {
/>
)}
</main>
+ <MessageContextSheet
+ open={contextSheetSeq !== null}
+ onOpenChange={(v) => { if (!v) setContextSheetSeq(null) }}
+ channelId={dmId}
+ targetSeq={contextSheetSeq}
+ onOpenContextSheet={setContextSheetSeq}
+ type="dm"
+ onOpenProfile={openProfile}
+ resolveUserName={resolveUserName}
+ onReply={dmBlocked ? undefined : (target) => {
+ setReplyTo(target)
+ setContextSheetSeq(null)
+ }}
+ />
</>
)
}
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 4b4863f57..92b12ba5f 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -94,7 +94,7 @@ type Embed = {
author?: { name: string; url?: string; iconUrl?: string }
}
-type Reaction = { emoji: string; count: number; me: boolean; userIds: string[] }
+export type Reaction = { emoji: string; count: number; me: boolean; userIds: string[] }
export type Msg = {
id: string // nanoid
@@ -116,6 +116,7 @@ export type Msg = {
authorId?: string
authorName?: string
color?: string
+ seq?: number // Per-scope (channel/DM) monotonic sequence number
createdAt?: string // ISO 8601 timestamp — the UI formats for display
authorAvatar?: string
failed?: boolean
diff --git a/src/web/src/components/community/message-body.tsx b/src/web/src/components/community/message-body.tsx
index 1c72b3511..0e440387c 100644
--- a/src/web/src/components/community/message-body.tsx
+++ b/src/web/src/components/community/message-body.tsx
@@ -83,9 +83,20 @@ const REHYPE_PLUGINS: PluggableList = [
// 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.
-function MessageBodyImpl({ text, onOpenProfile }: { text: string; onOpenProfile?: OpenProfile }) {
+function MessageBodyImpl({
+ text,
+ onOpenProfile,
+ messageRefContext,
+}: {
+ text: string
+ onOpenProfile?: OpenProfile
+ messageRefContext?: { onJumpToSeq?: (seq: number) => void }
+}) {
const inviteTokens = useMemo(() => extractInviteTokens(text), [text])
- const components = useMemo(() => buildMdComponents(onOpenProfile), [onOpenProfile])
+ const components = useMemo(
+ () => buildMdComponents(onOpenProfile, messageRefContext),
+ [onOpenProfile, messageRefContext],
+ )
return (
<div className="markdown wrap-anywhere text-[15px] leading-snug">
<Streamdown
diff --git a/src/web/src/components/community/message-context-sheet.tsx b/src/web/src/components/community/message-context-sheet.tsx
new file mode 100644
index 000000000..1b79ef889
--- /dev/null
+++ b/src/web/src/components/community/message-context-sheet.tsx
@@ -0,0 +1,509 @@
+"use client"
+
+import { useCallback, useEffect, useMemo, useRef } from "react"
+import { useRouter, useParams } from "next/navigation"
+import { toast } from "sonner"
+import { useQuery, useQueryClient } from "@tanstack/react-query"
+import { deriveThreadName } from "@alook/shared"
+import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet"
+import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle"
+import { MessageRow } from "./message-row"
+import { Skeleton } from "@/components/ui/skeleton"
+import { apiFetch, toastApiError } from "@/lib/api/client"
+import { ApiError } from "@/lib/errors"
+import { formatDateLabel } from "./format-time"
+import { DateDivider } from "./dividers"
+import { useCurrentUser } from "@/contexts/community/current-user"
+import { useUiHandlers } from "@/stores/community"
+import { usePinMessage, useUnpinMessage, useCreateThread } from "@/hooks/community/mutations"
+import type { Msg, OpenProfile, Reaction, RenderMsg } from "./_types"
+import type { MessagesPage } from "@/hooks/community/use-messages"
+
+export type ReplyTarget = { id: string; authorName: string; text: string }
+
+// Preview window sizing — small on purpose. The sheet is a read-only
+// excerpt with just enough surrounding context to make the target message
+// legible; deeper browsing happens in the underlying channel view.
+const CONTEXT_LIMIT = 11
+
+type ScopeType = "channel" | "dm"
+
+function seqLookupUrl(type: ScopeType, id: string, seq: number): string {
+ return type === "dm"
+ ? `/api/community/dm/${id}/messages/seq/${seq}`
+ : `/api/community/channels/${id}/messages/seq/${seq}`
+}
+
+function anchorFetchUrl(type: ScopeType, id: string, anchor: string, limit: number): string {
+ const base = type === "dm"
+ ? `/api/community/dm/${id}/messages`
+ : `/api/community/channels/${id}/messages`
+ return `${base}?anchor=${encodeURIComponent(anchor)}&limit=${limit}`
+}
+
+type SheetCache = {
+ notFound?: boolean
+ anchorId?: string
+ messages?: Msg[]
+}
+
+// Apply a reaction toggle to the sheet's own cache — mirrors the reducer
+// `togglePageCacheReaction` in mutations/messages.ts but on this hook's flat
+// `messages[]` shape instead of the main list's PageCache-of-pages shape.
+function toggleSheetReaction(
+ cache: SheetCache | undefined,
+ messageId: string,
+ emoji: string,
+ userId: string,
+ add: boolean,
+): SheetCache | undefined {
+ if (!cache?.messages) return cache
+ let touched = false
+ const messages = cache.messages.map((m) => {
+ if (m.id !== messageId) return m
+ touched = true
+ const reactions: Reaction[] = (m.reactions ?? []).map((r) => ({ ...r, userIds: [...(r.userIds ?? [])] }))
+ const existing = reactions.find((r) => r.emoji === emoji)
+ if (add) {
+ if (existing) {
+ if (!existing.userIds.includes(userId)) {
+ existing.userIds.push(userId)
+ existing.count = existing.userIds.length
+ }
+ existing.me = true
+ } else {
+ reactions.push({ emoji, count: 1, me: true, userIds: [userId] })
+ }
+ } else if (existing) {
+ existing.userIds = existing.userIds.filter((id) => id !== userId)
+ existing.count = existing.userIds.length
+ existing.me = false
+ if (existing.count <= 0) reactions.splice(reactions.indexOf(existing), 1)
+ }
+ return { ...m, reactions }
+ })
+ if (!touched) return cache
+ return { ...cache, messages }
+}
+
+/**
+ * Sidecar preview shown when the user clicks a `#NUMBER` ref pointing at a
+ * message that isn't in the currently loaded window. Fetches ~5 above / target
+ * / ~5 below via the anchor endpoint, renders them as a plain vertical stack
+ * of `<MessageRow>` rows (no MessageList, no virtualization), centers the
+ * target row on open.
+ *
+ * **Self-contained by design** — reactions, pin, copy, thread, image preview,
+ * file download all live INSIDE the sheet and operate on the sheet's own
+ * TanStack cache (a separate query key from the main channel). The main
+ * channel's cache is deliberately untouched to avoid re-render storms in the
+ * underlying `<MessageList>` and to avoid injecting mid-history rows into the
+ * main window that the user would then have to scroll past. The trade-off is
+ * that a reaction added here won't show in the main list until the WS event
+ * patches it (which already happens on the main cache) — a moment's
+ * inconsistency, but the sheet is transient, so it's the right cost.
+ *
+ * Reply is the ONE action that intentionally crosses back into the main
+ * surface: since the sheet has no composer, clicking Reply on a preview row
+ * closes the sheet and seeds the main channel's composer with that target,
+ * via the `onReply` prop.
+ *
+ * Retry is disabled — the sheet only shows server-persisted messages, never
+ * failed optimistic rows.
+ */
+export function MessageContextSheet({
+ open,
+ onOpenChange,
+ channelId,
+ targetSeq,
+ pinnedIds,
+ onOpenContextSheet,
+ onOpenProfile,
+ resolveUserName,
+ onReply,
+ type = "channel",
+}: {
+ open: boolean
+ onOpenChange: (v: boolean) => void
+ channelId: string
+ targetSeq: number | null
+ pinnedIds?: Set<string>
+ onOpenContextSheet?: (seq: number) => void
+ onOpenProfile?: OpenProfile
+ resolveUserName?: (userId: string) => string
+ // Fired when Reply is clicked in the sheet. Parent should seed its
+ // composer's replyTo state AND close the sheet — the sheet is a
+ // read-only preview, replying belongs on the main surface.
+ onReply?: (target: ReplyTarget) => void
+ type?: ScopeType
+}) {
+ const { width, onPointerDown, onPointerMove, onPointerUp } = useSheetResize({
+ defaultWidth: 420,
+ minWidth: 320,
+ maxWidthRatio: 0.6,
+ })
+
+ const currentUser = useCurrentUser()
+ const uiHandlers = useUiHandlers()
+ const queryClient = useQueryClient()
+ const router = useRouter()
+ const routeParams = useParams<{ serverId?: string }>()
+ const pinMessageMut = usePinMessage()
+ const unpinMessageMut = useUnpinMessage()
+ const createThreadMut = useCreateThread()
+
+ const queryKey = useMemo(
+ () => ["messageContext", type, channelId, targetSeq] as const,
+ [type, channelId, targetSeq],
+ )
+
+ // Two-step fetch: seq → id, then anchor-fetch around the id.
+ const query = useQuery({
+ queryKey,
+ enabled: open && !!channelId && !!targetSeq,
+ queryFn: async ({ signal }): Promise<SheetCache> => {
+ let lookup: { id: string }
+ try {
+ lookup = await apiFetch<{ id: string }>(
+ seqLookupUrl(type, channelId, targetSeq!),
+ { signal },
+ )
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 404) return { notFound: true }
+ throw e
+ }
+ const page = await apiFetch<MessagesPage>(
+ anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),
+ { signal },
+ )
+ const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
+ return { notFound: false, anchorId: lookup.id, messages }
+ },
+ staleTime: 30_000,
+ })
+
+ const renderRows = useMemo<RenderMsg[]>(() => {
+ if (!query.data || query.data.notFound || !query.data.messages) return []
+ const src = query.data.messages
+ // Same grouping heuristic the main list uses (adjacent same-author within
+ // ~5 min → collapse header). Inlined here rather than sharing the util
+ // because the excerpt is small enough that the extra dep isn't worth the
+ // module coupling.
+ return src.map((m, i) => {
+ const prev = i > 0 ? src[i - 1] : null
+ const grouped =
+ !!prev &&
+ prev.authorId != null &&
+ prev.authorId === m.authorId &&
+ prev.type === m.type &&
+ !!prev.createdAt &&
+ !!m.createdAt &&
+ new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime() < 5 * 60_000
+ return { ...m, grouped }
+ })
+ }, [query.data])
+
+ const anchorId = query.data && !query.data.notFound ? (query.data.anchorId ?? null) : null
+
+ // ── Sheet-local actions ──────────────────────────────────────────────────
+ const findMessage = useCallback(
+ (id: string): Msg | undefined => query.data?.messages?.find((m) => m.id === id),
+ [query.data],
+ )
+
+ const toggleReaction = useCallback((messageId: string, emoji: string) => {
+ const msg = findMessage(messageId)
+ if (!msg) return
+ const wasMe = msg.reactions?.find((r) => r.emoji === emoji)?.me ?? false
+ const nextMe = !wasMe
+ // Optimistic — flip immediately on the sheet's own cache.
+ queryClient.setQueryData<SheetCache>(queryKey, (c) =>
+ toggleSheetReaction(c, messageId, emoji, currentUser.id, nextMe),
+ )
+ const method = wasMe ? "DELETE" : "PUT"
+ const url = `/api/community/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`
+ apiFetch(url, { method }).catch((e) => {
+ queryClient.setQueryData<SheetCache>(queryKey, (c) =>
+ toggleSheetReaction(c, messageId, emoji, currentUser.id, wasMe),
+ )
+ toastApiError(e, "Failed to update reaction")
+ })
+ }, [queryKey, queryClient, currentUser.id, findMessage])
+
+ const onCopyId = useCallback((id: string) => {
+ const m = findMessage(id)
+ if (m?.content) {
+ navigator.clipboard?.writeText(m.content)
+ toast("Copied to clipboard")
+ }
+ }, [findMessage])
+
+ const onReplyId = useCallback((id: string) => {
+ if (!onReply) return
+ const m = findMessage(id)
+ if (!m) return
+ onReply({ id: m.id, authorName: m.authorName ?? "", text: m.content ?? "" })
+ }, [findMessage, onReply])
+
+ const onPinId = useCallback((id: string) => {
+ if (type === "dm") return
+ const isPinned = pinnedIds?.has(id)
+ if (isPinned) {
+ unpinMessageMut.mutate({ channelId, messageId: id }, {
+ onSuccess: () => toast("Message unpinned"),
+ onError: (e) => toastApiError(e, "Failed to unpin message"),
+ })
+ } else {
+ pinMessageMut.mutate({ channelId, messageId: id }, {
+ onSuccess: () => toast("Message pinned"),
+ onError: (e) => toastApiError(e, "Failed to pin message"),
+ })
+ }
+ }, [type, channelId, pinnedIds, pinMessageMut, unpinMessageMut])
+
+ const onCreateThreadId = useCallback(async (id: string) => {
+ if (type === "dm") return
+ const m = findMessage(id)
+ const name = deriveThreadName(m?.content, "channel")
+ try {
+ const data = await createThreadMut.mutateAsync({ channelId, messageId: id, name })
+ // Match the main-channel UX: after creating a thread the row shows
+ // the thread indicator, click it to enter. Don't auto-navigate — we're
+ // inside a sidecar preview, silently teleporting the user to the thread
+ // route surprises them.
+ // Patch the sheet's own cache so the indicator appears immediately (the
+ // main list's WS handler patches the main cache, but the sheet uses its
+ // own query key). Server-authoritative fields land on the actual thread
+ // page's fetch; here we only need the shape the row's indicator reads.
+ queryClient.setQueryData<SheetCache>(queryKey, (c) => {
+ if (!c?.messages) return c
+ return {
+ ...c,
+ messages: c.messages.map((msg) =>
+ msg.id === id
+ ? { ...msg, thread: { id: data.id, name, messageCount: 0 } }
+ : msg,
+ ),
+ }
+ })
+ } catch (e) {
+ toastApiError(e, "Failed to create thread")
+ }
+ }, [type, channelId, findMessage, createThreadMut, queryClient, queryKey])
+
+ const onOpenThreadId = useCallback((threadId: string) => {
+ // Sheet's Reply-style handoff: navigate the main window to the thread and
+ // close the sheet in the same gesture. Falls back to a no-op in the DM
+ // case (threads live inside channels, not DMs).
+ if (type === "dm") return
+ const serverId = routeParams?.serverId
+ if (!serverId) return
+ router.push(`/c/channels/${serverId}/${threadId}`)
+ onOpenChange(false)
+ }, [type, router, routeParams, onOpenChange])
+
+ const onPreviewImage = useCallback((url: string) => {
+ uiHandlers.previewImage?.(url)
+ }, [uiHandlers])
+
+ const onDownloadFile = useCallback((url: string) => {
+ const a = document.createElement("a")
+ a.href = url
+ a.download = url.split("/").pop() ?? "file"
+ a.click()
+ }, [])
+
+ // The sheet's scrollable body — we scroll INSIDE this container, not via
+ // `element.scrollIntoView({block:'center'})`. `scrollIntoView` walks up to
+ // the nearest scrollable ancestor and, on a first-open where the sheet is
+ // still animating in, that ancestor's layout box is mid-translate — the
+ // browser then computes a wrong scrollTop. Doing the math ourselves against
+ // the body's `getBoundingClientRect()` sidesteps that entirely and works
+ // identically on first-open and cache-hit reopen.
+ const bodyRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (!open || !anchorId) return
+ // `targetSeq` in the effect key so re-clicking the SAME pill (open→close→
+ // open→same seq) still fires — closing keeps `anchorId` unchanged, so a
+ // deps=[open, anchorId] effect would skip the reopen.
+ let cancelled = false
+ let r2 = 0
+ // Two rAFs: first waits for React commit + Base UI popup layout, second
+ // waits one paint after that so the popup's translate transition has been
+ // ticked at least once and the scroll math resolves against the settled
+ // box. Cheap (~32ms) and deterministic across first-open vs reopen.
+ const r1 = requestAnimationFrame(() => {
+ r2 = requestAnimationFrame(() => {
+ if (cancelled) return
+ const body = bodyRef.current
+ const row = body?.querySelector<HTMLElement>(`[data-anchor-row="1"]`)
+ if (!body || !row) return
+ const bodyRect = body.getBoundingClientRect()
+ const rowRect = row.getBoundingClientRect()
+ const targetTop =
+ body.scrollTop + (rowRect.top - bodyRect.top) - (bodyRect.height - rowRect.height) / 2
+ body.scrollTop = Math.max(0, targetTop)
+ })
+ })
+ return () => {
+ cancelled = true
+ cancelAnimationFrame(r1)
+ if (r2) cancelAnimationFrame(r2)
+ }
+ }, [open, anchorId, targetSeq])
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange} modal={false} disablePointerDismissal>
+ <SheetContent
+ side="right"
+ showOverlay={false}
+ style={{ width: `min(${width}px, 100vw)`, maxWidth: "none" }}
+ className="flex flex-col p-0 data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border data-[side=right]:sm:overflow-hidden"
+ >
+ <SheetResizeHandle onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />
+ <SheetHeader className="gap-0 border-b-0 py-3">
+ <SheetTitle className="flex items-baseline gap-0.5 font-mono text-2xl font-semibold tracking-tight">
+ <span className="text-muted-foreground">#</span>
+ <span>{targetSeq ?? ""}</span>
+ </SheetTitle>
+ </SheetHeader>
+
+ <div ref={bodyRef} className="flex-1 overflow-y-auto thin-scrollbar px-4 py-3">
+ {query.isLoading && <ContextSkeleton />}
+
+ {query.isError && (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ Couldn&rsquo;t load the message. Check your connection and retry.
+ </p>
+ )}
+
+ {query.data?.notFound && (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ Message not found — it may have been deleted.
+ </p>
+ )}
+
+ {!query.isLoading && !query.isError && query.data && !query.data.notFound && (
+ <ContextRows
+ rows={renderRows}
+ anchorId={anchorId}
+ pinnedIds={pinnedIds}
+ onOpenProfile={onOpenProfile}
+ onOpenThread={type === "channel" ? onOpenThreadId : undefined}
+ resolveUserName={resolveUserName}
+ onToggleReaction={toggleReaction}
+ onReact={toggleReaction}
+ onReply={onReply ? onReplyId : undefined}
+ onCopy={onCopyId}
+ onPin={type === "channel" ? onPinId : undefined}
+ onCreateThread={type === "channel" ? onCreateThreadId : undefined}
+ onPreviewImage={onPreviewImage}
+ onDownloadFile={onDownloadFile}
+ onOpenContextSheet={onOpenContextSheet}
+ />
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function ContextRows({
+ rows,
+ anchorId,
+ pinnedIds,
+ onOpenProfile,
+ onOpenThread,
+ resolveUserName,
+ onToggleReaction,
+ onReact,
+ onReply,
+ onCopy,
+ onPin,
+ onCreateThread,
+ onPreviewImage,
+ onDownloadFile,
+ onOpenContextSheet,
+}: {
+ rows: RenderMsg[]
+ anchorId: string | null
+ pinnedIds?: Set<string>
+ onOpenProfile?: OpenProfile
+ onOpenThread?: (threadId: string) => void
+ resolveUserName?: (userId: string) => string
+ onToggleReaction: (id: string, emoji: string) => void
+ onReact: (id: string, emoji: string) => void
+ onReply?: (id: string) => void
+ onCopy: (id: string) => void
+ onPin?: (id: string) => void
+ onCreateThread?: (id: string) => void
+ onPreviewImage: (url: string) => void
+ onDownloadFile: (url: string) => void
+ onOpenContextSheet?: (seq: number) => void
+}) {
+ // Chained `#NUMBER` refs inside the sheet reopen the sheet on the new seq,
+ // via the same setter the parent already owns.
+ const messageRefContext = useMemo(
+ () => ({
+ onJumpToSeq: onOpenContextSheet ? (s: number) => onOpenContextSheet(s) : undefined,
+ }),
+ [onOpenContextSheet],
+ )
+ return (
+ <div className="flex flex-col">
+ {rows.map((m, i) => {
+ const isTarget = m.id === anchorId
+ const prev = i > 0 ? rows[i - 1] : null
+ const showDate =
+ !prev ||
+ (m.createdAt &&
+ prev.createdAt &&
+ new Date(m.createdAt).toDateString() !== new Date(prev.createdAt).toDateString())
+ return (
+ <div key={m.id}>
+ {showDate && m.createdAt && <DateDivider label={formatDateLabel(m.createdAt)} />}
+ <div data-anchor-row={isTarget ? "1" : undefined}>
+ <MessageRow
+ m={m}
+ pinned={pinnedIds?.has(m.id)}
+ highlighted={isTarget}
+ onOpenThread={onOpenThread ?? (() => {})}
+ onOpenProfile={onOpenProfile}
+ onToggleReactionId={onToggleReaction}
+ onReactId={onReact}
+ onReplyId={onReply}
+ onPinId={onPin}
+ onCreateThreadId={onCreateThread}
+ onCopyId={onCopy}
+ onPreviewImage={onPreviewImage}
+ onDownloadFile={onDownloadFile}
+ resolveUserName={resolveUserName}
+ messageRefContext={messageRefContext}
+ />
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+function ContextSkeleton() {
+ return (
+ <div className="flex flex-col gap-3">
+ {[0, 1, 2, 3].map((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>
+ <Skeleton className="h-3.5 w-full max-w-[240px] rounded" />
+ </div>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/src/web/src/components/community/message-list-items.ts b/src/web/src/components/community/message-list-items.ts
index faa64f0f3..36f97b09b 100644
--- a/src/web/src/components/community/message-list-items.ts
+++ b/src/web/src/components/community/message-list-items.ts
@@ -39,7 +39,18 @@ export function flattenMessageItems(messages: Msg[], newDividerBefore: string |
items.push({ kind: "new-divider", key: "new-divider", dateLabel: formatDateLabel(m.createdAt!) })
} else {
if (showDateDivider) {
- items.push({ kind: "date-divider", label: formatDateLabel(m.createdAt!), key: `date:${m.id}` })
+ // Keyed by the DATE (not the first-of-day message id) so an older-page
+ // prepend that pushes new same-day messages in front of the current
+ // first-of-day row keeps the divider's key stable. Without this,
+ // `@tanstack/react-virtual`'s anchor path (see use-scroll-anchor.ts) —
+ // which captures the anchor row's key before prepend and finds it in
+ // the new items after — falls off when the anchor sits on `items[0]`
+ // (the top-of-window divider), the divider gets re-emitted with a
+ // different `date:${id}` key, and `anchorTo: "end"` silently no-ops.
+ // Symptom: viewport jumps to the top of the loaded window on every
+ // top-sentinel load. `curDate` is `YYYY-MM-DD`, one row per day, so
+ // it's a stable identity.
+ items.push({ kind: "date-divider", label: formatDateLabel(m.createdAt!), key: `date:${curDate}` })
}
if (isNewDivider) {
items.push({ kind: "new-divider", key: "new-divider" })
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index 5b78a9035..0267cb722 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -21,7 +21,7 @@ export function MessageList({
onReply, onPin, onCreateThread, onCopy, onRetry, onPreviewImage, onDownloadFile,
resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,
hasMore, isFetchingOlder, onLoadOlder,
- hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount,
+ hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount, onOpenContextSheet,
}: {
channel: string
messages: Msg[]
@@ -90,6 +90,10 @@ export function MessageList({
// the `↓ N` badge when `hasMoreNewer` is true — DOM math can't see rows
// that haven't been fetched yet.
unreadCount?: number
+ // Fired when a message ref pill (`#NUMBER`) is clicked and the target
+ // isn't in the currently loaded window — the owner opens the context
+ // sheet (see `MessageContextSheet`). If omitted, the click is a no-op.
+ onOpenContextSheet?: (seq: number) => void
}) {
const [jumped, setJumped] = useState<string | null>(null)
@@ -280,6 +284,31 @@ export function MessageList({
window.setTimeout(() => setJumped((v) => (v === id ? null : v)), 1600)
}, [jumpToIndex])
+ // Message-ref jump handler + the context object handed to each message row.
+ //
+ // Both MUST stay reference-stable across renders — otherwise `MessageRow`'s
+ // memo tears down every row on every WS tick, which is exactly the storm
+ // 3fc84fa2 ("perf(web): kill community switch re-render storm") set out to
+ // fix. We reach the target by:
+ // - reading `messages` / `jumpTo` / `onOpenContextSheet` lazily through a
+ // ref that's written on each commit (latest-ref pattern, same as
+ // `page.tsx`'s `messageActions`);
+ // - `useCallback([])` on the handler and `useMemo([onJumpToSeq])` on the
+ // context — both are stable for the mount's lifetime.
+ const jumpCtxRef = useRef({ messages, jumpTo, onOpenContextSheet })
+ /* eslint-disable-next-line react-hooks/immutability -- latest-ref for lazy click reads */
+ jumpCtxRef.current = { messages, jumpTo, onOpenContextSheet }
+ const onJumpToSeq = useCallback((seq: number) => {
+ const { messages, jumpTo, onOpenContextSheet } = jumpCtxRef.current
+ const msg = messages.find((m) => m.seq === seq)
+ if (msg) {
+ jumpTo(msg.id)
+ } else if (onOpenContextSheet) {
+ onOpenContextSheet(seq)
+ }
+ }, [])
+ const messageRefContext = useMemo(() => ({ onJumpToSeq }), [onJumpToSeq])
+
useEffect(() => {
if (scrollToMessageId) jumpTo(scrollToMessageId)
}, [scrollToMessageId, jumpTo])
@@ -387,6 +416,7 @@ export function MessageList({
onDownloadFile={onDownloadFile}
resolveUserName={resolveUserName}
onImageLoad={onImageLoad}
+ messageRefContext={messageRefContext}
/>
</div>
)}
diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsx
index 036a1f551..e28228512 100644
--- a/src/web/src/components/community/message-markdown.tsx
+++ b/src/web/src/components/community/message-markdown.tsx
@@ -2,6 +2,7 @@ import type React from "react"
import { Spoiler, MentionPill } from "./inline-marks"
import { ChannelRefPill } from "./channel-ref-pill"
import { ServerRefPill } from "./server-ref-pill"
+import { MessageRefPill } from "./message-ref-pill"
// Match `/c/invite/<token>` — with or without an origin.
// - token allows [A-Za-z0-9_-] (nanoid alphabet) and length 6..64 (short + old
@@ -44,13 +45,14 @@ export const MD_ALLOWED_TAGS = {
mention: ["dataEveryone", "dataTag"],
channelref: [],
serverref: [],
+ messageref: [],
}
-// `spoiler` is deliberately excluded — unlike `mention`/`channelref`/`serverref`
+// `spoiler` is deliberately excluded — unlike `mention`/`channelref`/`serverref`/`messageref`
// (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", "serverref"]
+export const MD_LITERAL_TAGS = ["mention", "channelref", "serverref", "messageref"]
// A mention pill's rendered text is always `@name` (produced by
// `chat-syntax-plugin.ts`'s `mentionReplacer`, which already drops the
@@ -67,20 +69,24 @@ export const MD_COMPONENTS = {
mention: ({ children, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => (
<MentionPill everyone={rest["data-everyone"] === "1"}>{children}</MentionPill>
),
- // `channelref`/`serverref` are fully self-sufficient via hooks (resolve via
- // `useChannelRefDirectory`, navigate via `useRouter`) — unlike `mention`,
- // they need no closure injected by `buildMdComponents`, so the same static
- // entries are reused there too (see the spread below).
+ // `channelref`/`serverref`/`messageref` are fully self-sufficient via hooks
+ // (resolve via `useChannelRefDirectory`/`useMessages`, navigate via
+ // `useRouter`) — unlike `mention`, they need no closure injected by
+ // `buildMdComponents`, so the same static entries are reused there too (see
+ // the spread below).
channelref: ChannelRefPill,
serverref: ServerRefPill,
+ messageref: MessageRefPill,
} as Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>>
// Same as `MD_COMPONENTS`, but the `mention` pill opens the profile card on
-// click (skipped for @everyone/@here — there's no user behind those). Built
-// per-render (memoized by the caller) rather than statically, since it
-// closes over `onOpenProfile`.
+// click (skipped for @everyone/@here — there's no user behind those), and
+// `messageref` receives `onJumpToSeq` for click-time navigation. Built
+// per-render (memoized by the caller) rather than statically, since it closes
+// over callbacks.
export function buildMdComponents(
onOpenProfile?: (name: string, e: React.MouseEvent, discriminator?: string) => void,
+ messageRefContext?: { onJumpToSeq?: (seq: number) => void },
): Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>> {
return {
...MD_COMPONENTS,
@@ -98,5 +104,10 @@ export function buildMdComponents(
</MentionPill>
)
},
+ messageref: ({ children }: { children?: React.ReactNode }) => (
+ <MessageRefPill onJumpToSeq={messageRefContext?.onJumpToSeq}>
+ {children}
+ </MessageRefPill>
+ ),
}
}
diff --git a/src/web/src/components/community/message-ref-pill.tsx b/src/web/src/components/community/message-ref-pill.tsx
new file mode 100644
index 000000000..6c04b86c6
--- /dev/null
+++ b/src/web/src/components/community/message-ref-pill.tsx
@@ -0,0 +1,39 @@
+"use client"
+
+import type React from "react"
+
+// `#NUMBER` — channel-scoped message ref. Lazy: always renders as a pill,
+// validates on click. The click handler decides:
+// - loaded in the current window → scroll to it
+// - not loaded → open the context sheet (which resolves seq → id server-side)
+//
+// Range-based rendering was removed on purpose. `seqRange` (min/max) advanced
+// on every WS message tick, which busted the `messageRefContext` identity and
+// re-rendered every memoized message row on incoming traffic. `onJumpToSeq` is
+// built with a latest-ref in `message-list.tsx` and stays reference-stable,
+// which keeps `MessageRow`'s memo intact.
+export function MessageRefPill({
+ children,
+ onJumpToSeq,
+}: {
+ children?: React.ReactNode
+ onJumpToSeq?: (seq: number) => void
+}) {
+ const text = String(children ?? "")
+ const seq = parseInt(text.replace(/^#/, ""), 10)
+
+ if (!seq || isNaN(seq) || seq <= 0 || !onJumpToSeq) {
+ return <>{text}</>
+ }
+
+ return (
+ <button
+ type="button"
+ onClick={() => onJumpToSeq(seq)}
+ title={text}
+ className="inline-flex items-baseline rounded-[4px] bg-accent px-1 font-medium text-foreground transition-colors hover:bg-primary/15 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {text}
+ </button>
+ )
+}
diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/message-row.tsx
index bc46a2da6..76a246d64 100644
--- a/src/web/src/components/community/message-row.tsx
+++ b/src/web/src/components/community/message-row.tsx
@@ -33,6 +33,7 @@ export interface MessageRowProps {
onDownloadFile?: (name: string) => void
resolveUserName?: (userId: string) => string
onImageLoad?: () => void
+ messageRefContext?: { onJumpToSeq?: (seq: number) => void }
}
function MessageRowImpl(props: MessageRowProps) {
@@ -40,7 +41,7 @@ function MessageRowImpl(props: MessageRowProps) {
m, pinned, highlighted, onOpenThread, onOpenProfile,
onToggleReactionId, onReactId, onReplyId, onPinId, onCreateThreadId,
onCopyId, onRetryId, onJumpToId, onPreviewImage, onDownloadFile,
- resolveUserName, onImageLoad,
+ resolveUserName, onImageLoad, messageRefContext,
} = props
const id = m.id
const replyToId = m.replyTo?.id
@@ -84,6 +85,7 @@ function MessageRowImpl(props: MessageRowProps) {
onDownloadFile={onDownloadFile}
resolveUserName={resolveUserName}
onImageLoad={onImageLoad}
+ messageRefContext={messageRefContext}
/>
)
}
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index d42b73d63..3f83dbb1d 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -34,7 +34,7 @@ export function attachmentAspectRatio(width: number | undefined, height: number
function MessageImpl({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
onToggleReaction, onReact, onReply, onPin, onCreateThread, onCopy, onRetry,
- onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad,
+ onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad, messageRefContext,
}: {
m: RenderMsg
compact?: boolean
@@ -53,11 +53,8 @@ function MessageImpl({
onDownloadFile?: (name: string) => void
highlighted?: boolean
resolveUserName?: (userId: string) => string
- // Fired when an attachment/embed image finishes loading — the scroll
- // anchor re-pins to the bottom if the viewer is still there, so a tall
- // image that grows after the initial auto-scroll doesn't leave the
- // message's bottom cut off.
onImageLoad?: () => void
+ messageRefContext?: { onJumpToSeq?: (seq: number) => void }
}) {
// keep the hover toolbar pinned open while its ⋯ dropdown is open
const [toolbarOpen, setToolbarOpen] = useState(false)
@@ -103,6 +100,11 @@ function MessageImpl({
<div className="min-w-0 flex-1">
{interactive && activated && (
<div className={`absolute right-2 z-20 flex items-center gap-1 rounded-lg border border-border/60 bg-card px-2 py-1 shadow-(--e1) transition-opacity duration-150 ${m.grouped ? "-top-2" : "-top-3"} ${toolbarOpen ? "opacity-100" : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100"}`}>
+ {m.seq != null && m.seq > 0 && (
+ <span className="mr-0.5 select-none font-mono text-xs text-muted-foreground" aria-label={`Message ${m.seq}`}>
+ <span className="opacity-60">#</span>{m.seq}
+ </span>
+ )}
{onReact && (
<EmojiPickerPopover side="bottom" align="end" onPick={(e) => onReact(e)} onOpenChange={setToolbarOpen}>
<button data-testid={tid.reactionAdd(m.id)} className="grid size-7 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none aria-expanded:text-foreground" aria-label="Add reaction">
@@ -164,7 +166,7 @@ function MessageImpl({
</div>
)}
{m.content && (
- <MessageBody text={m.content} onOpenProfile={onOpenProfile} />
+ <MessageBody text={m.content} onOpenProfile={onOpenProfile} messageRefContext={messageRefContext} />
)}
{m.attachments && (
@@ -383,7 +385,8 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
a.attachments !== b.attachments ||
a.embeds !== b.embeds ||
a.replyTo !== b.replyTo ||
- a.thread !== b.thread
+ a.thread !== b.thread ||
+ a.seq !== b.seq
) {
return false
}
@@ -405,7 +408,8 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
prev.onPreviewImage === next.onPreviewImage &&
prev.onDownloadFile === next.onDownloadFile &&
prev.resolveUserName === next.resolveUserName &&
- prev.onImageLoad === next.onImageLoad
+ prev.onImageLoad === next.onImageLoad &&
+ prev.messageRefContext === next.messageRefContext
)
}
diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.ts
index 9ca8b2621..8e51eb978 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts
@@ -3,7 +3,7 @@ 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, ServerRefNode } from "./chat-syntax-plugin"
+import type { MentionNode, ChannelRefNode, ServerRefNode, MessageRefNode } from "./chat-syntax-plugin"
function parse(md: string): Root {
const processor = unified().use(remarkParse).use(chatSyntaxPlugin)
@@ -37,9 +37,11 @@ describe("chatSyntaxPlugin — mention", () => {
it("does not swallow ordinary prose ending in #dddd — the name-run must end in a non-space", () => {
// No earlier `#`, so a naive non-greedy run would span "bob check issue "
// and terminate at #0042. The non-space-before-# guard prevents this.
+ // With message ref support, `#0042` is now parsed as a message ref (which
+ // will render as a muted pill when the seq doesn't exist in the channel).
const children = paragraphChildren(parse("@bob check issue #0042"))
expect(children.some((c) => c.type === "mention")).toBe(false)
- expect(children.map((c) => c.type)).toEqual(["text"])
+ expect(children.map((c) => c.type)).toEqual(["text", "messageRef"])
})
it("keeps two adjacent handles as two distinct mentions", () => {
@@ -185,6 +187,48 @@ describe("chatSyntaxPlugin — serverRef", () => {
})
})
+describe("chatSyntaxPlugin — message ref", () => {
+ it("parses space + #NUMBER as messageRef", () => {
+ const children = paragraphChildren(parse("see #123"))
+ const messageRef = children.find((c): c is MessageRefNode => c.type === "messageRef")
+ expect(messageRef).toMatchObject({ type: "messageRef", value: "#123" })
+ })
+
+ it("parses #NUMBER at line start as messageRef", () => {
+ const children = paragraphChildren(parse("#42 was fixed"))
+ const messageRef = children.find((c): c is MessageRefNode => c.type === "messageRef")
+ expect(messageRef).toMatchObject({ type: "messageRef", value: "#42" })
+ })
+
+ it("does NOT parse text#NUMBER (no leading space) as messageRef", () => {
+ const children = paragraphChildren(parse("issue#42 in GitHub"))
+ expect(children.some((c) => c.type === "messageRef")).toBe(false)
+ expect(children.map((c) => c.type)).toEqual(["text"])
+ })
+
+ it("parses multiple message refs in one message", () => {
+ const children = paragraphChildren(parse("See #10 and #20"))
+ const messageRefs = children.filter((c): c is MessageRefNode => c.type === "messageRef")
+ expect(messageRefs.map((m) => m.value)).toEqual(["#10", "#20"])
+ })
+
+ it("does NOT parse inside code blocks", () => {
+ const children = paragraphChildren(parse("`#42`"))
+ expect(children.some((c) => c.type === "messageRef")).toBe(false)
+ })
+
+ it("parses #NUMBER with trailing punctuation", () => {
+ const children = paragraphChildren(parse("Fixed in #123."))
+ const messageRef = children.find((c): c is MessageRefNode => c.type === "messageRef")
+ expect(messageRef).toMatchObject({ value: "#123" })
+ })
+
+ it("does NOT parse 7+ digit numbers", () => {
+ const children = paragraphChildren(parse("ref #9999999"))
+ expect(children.some((c) => c.type === "messageRef")).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#0042 in /studio/dev"))
@@ -204,4 +248,14 @@ describe("chatSyntaxPlugin — mixed", () => {
const serverRef = children.find((c): c is ServerRefNode => c.type === "serverRef")
expect(serverRef).toMatchObject({ value: "/studio" })
})
+
+ it("handles mention, message ref, and channel ref together", () => {
+ const children = paragraphChildren(parse("@Alice#0001 check #42 in /studio/general"))
+ const mention = children.find((c): c is MentionNode => c.type === "mention")
+ expect(mention).toMatchObject({ value: "@Alice", discriminator: "0001" })
+ const messageRef = children.find((c): c is MessageRefNode => c.type === "messageRef")
+ expect(messageRef).toMatchObject({ value: "#42" })
+ const channelRef = children.find((c): c is ChannelRefNode => c.type === "channelRef")
+ expect(channelRef).toMatchObject({ value: "/studio/general" })
+ })
})
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
index 032b9c4c9..dad6404ac 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -50,6 +50,16 @@ const CHANNEL_REF_RE = /(?<=^|\s)\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+(?:#\d
// makes the ordering non-load-bearing for correctness.
const SERVER_REF_RE = /(?<=^|\s)\/[A-Za-z0-9_-]+(?=\s|$|[.,;:!?)\]])/g
+// Message ref: `#NUMBER` where NUMBER is 1-6 digits (seq range 1-999999).
+// Same boundary pattern as channel/server refs: leading `(?<=^|\s)` so
+// `text#123` doesn't match (avoids GitHub issue refs, URL fragments),
+// trailing `(?=\s|$|[.,;:!?)\]])` so it works inline and at EOL.
+// Channel-scoped: `#123` refers to message seq 123 in the current channel,
+// not a global identifier. Registered AFTER mention regex so `@Alice#0042`
+// is parsed as mention first (4-digit discriminator), not broken into text
+// `@Alice` + message ref `#0042`.
+const MESSAGE_REF_RE = /(?<=^|\s)#\d{1,6}(?=\s|$|[.,;:!?)\]])/g
+
// Two-branch mention grammar (see plans/mandatory-mention-discriminator.md):
//
// 1. The literal `@everyone`/`@here` tokens, with a trailing
@@ -91,16 +101,25 @@ export interface ServerRefNode {
value: string
}
+/** mdast node produced by `#NUMBER` (message seq ref in current channel). */
+export interface MessageRefNode {
+ type: "messageRef"
+ /** The full matched string including `#` (e.g., `"#123"`). */
+ value: string
+}
+
declare module "mdast" {
interface RootContentMap {
mention: MentionNode
channelRef: ChannelRefNode
serverRef: ServerRefNode
+ messageRef: MessageRefNode
}
interface PhrasingContentMap {
mention: MentionNode
channelRef: ChannelRefNode
serverRef: ServerRefNode
+ messageRef: MessageRefNode
}
}
@@ -128,9 +147,13 @@ function serverRefReplacer(value: string): ServerRefNode {
return { type: "serverRef", value }
}
+function messageRefReplacer(value: string): MessageRefNode {
+ return { type: "messageRef", value }
+}
+
/**
* remark plugin: combines the spoiler micromark extension (`spoiler-syntax.ts`)
- * with a `mdast-util-find-and-replace` pass for `mention`/`channelRef`.
+ * with a `mdast-util-find-and-replace` pass for `mention`/`channelRef`/`messageRef`.
* 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.
@@ -148,6 +171,7 @@ export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this
tree,
[
[MENTION_RE, mentionReplacer as unknown as (value: string, ...rest: unknown[]) => PhrasingContent | string | false],
+ [MESSAGE_REF_RE, messageRefReplacer as unknown as (value: string) => PhrasingContent],
[CHANNEL_REF_RE, channelRefReplacer as unknown as (value: string) => PhrasingContent],
// Runs as its own pass AFTER the channelRef pass above — by then every
// `/server/channel` span is already a `channelRef` element (no longer
@@ -193,4 +217,10 @@ export const chatSyntaxHandlers: Handlers = {
properties: {},
children: [{ type: "text", value: node.value }],
})) as Handler,
+ messageRef: ((_state, node: MessageRefNode): Element => ({
+ type: "element",
+ tagName: "messageref",
+ properties: {},
+ children: [{ type: "text", value: node.value }],
+ })) as Handler,
}
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 0d0ee8e80..2974986ad 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -34,6 +34,7 @@ export type MessageRow = {
mentionType: string | null
replyToId: string | null
embeds: unknown
+ seq: number
createdAt: string
}
@@ -61,6 +62,7 @@ function coreFields(row: MessageRow) {
// The `type` column can hold "default" / "system" / "thread_created".
// GET hides "default" (undefined = default), WS returns it explicitly —
// both are correct; we keep the difference at the variant boundary below.
+ seq: row.seq,
createdAt: row.createdAt,
mentionType: (row.mentionType ?? null) as MentionType | null,
}