Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): message-area scroll, truncation, jump count, newlines, forum reads, DM reactions (#393)

Generd6829cf46dd9
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fe1ecc266..a7f9f6430 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -471,6 +471,9 @@ importers:
rehype-slug:
specifier: ^6.0.0
version: 6.0.0
+ remark-breaks:
+ specifier: ^4.0.0
+ version: 4.0.0
remark-gfm:
specifier: ^4.0.1
version: 4.0.1
@@ -6316,6 +6319,9 @@ packages:
resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}
+ resolution: {integrity: sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog==}
+
resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}
@@ -7237,6 +7243,9 @@ packages:
resolution: {integrity: sha512-lWyvf/jwu+oS5+hL5eClVd3hNdmwM1kAC0BUvEGD19pajQMIzcNUd/k9GsfQ+FfECvX+JE+e9/btsKH0EjJT6A==}
+ resolution: {integrity: sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==}
+
resolution: {integrity: sha512-pWKj25O2eLXIL1aBupayl1fKhco+Brw8qWUWJPVB9EBzbQNd7nGLj0nLmJpggWsGLR5j5y40PIdjxby9IEYTuA==}
engines: {node: '>=18'}
@@ -11732,7 +11741,7 @@ snapshots:
obug: 2.1.3
std-env: 4.2.0
tinyrainbow: 3.1.0
'@vitest/[email protected]':
dependencies:
@@ -13039,8 +13048,8 @@ snapshots:
'@next/eslint-plugin-next': 16.2.10
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
+ eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -13062,7 +13071,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -13073,21 +13082,21 @@ snapshots:
tinyglobby: 0.2.17
unrs-resolver: 1.12.2
optionalDependencies:
+ eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -13098,7 +13107,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.4
is-core-module: 2.16.2
is-glob: 4.0.3
@@ -14715,6 +14724,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-find-and-replace: 3.0.2
+
dependencies:
'@types/mdast': 4.0.4
@@ -16061,6 +16075,12 @@ snapshots:
hast-util-to-string: 3.0.1
unist-util-visit: 5.1.0
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-newline-to-break: 2.0.0
+ unified: 11.0.5
+
dependencies:
micromark-extension-cjk-friendly-gfm-strikethrough: 2.0.1([email protected])([email protected])
diff --git a/src/web/package.json b/src/web/package.json
index fb7c94b8c..16c2c0f77 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -92,6 +92,7 @@
"rehype-pretty-code": "^0.14.4",
"rehype-sanitize": "^6.0.0",
"rehype-slug": "^6.0.0",
+ "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
"shadcn": "^4.13.0",
"shiki": "^4.3.1",
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 99052f5c3..b47837781 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -912,6 +912,7 @@ function ChannelView() {
resolveUserName={resolveUserName}
scrollToMessageId={scrollToMessageId}
hero={opener}
+ onScrollRoot={setScrollRootEl}
viewerUserId={currentUser.id}
hasMore={hasMoreMessages}
isFetchingOlder={isFetchingOlderMessages}
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 270bbeb08..599ee0e4b 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -208,7 +208,22 @@ function DmView() {
uiHandlers.openProfile?.(name, e, discriminator, userId)
}
- const resolveUserName = useMemo(() => makeUserNameResolver(friends), [friends])
+ // A DM contains only two participants, and the friends-based resolver
+ // covers neither reliably: the viewer is never in their own friends list,
+ // and the counterpart is only there if they're actually a friend. Resolve
+ // those two ids explicitly (self → current user, counterpart → the DM's
+ // display name) before delegating to friends, so reactions (whose reactor
+ // is most often the viewer) never fall through to "Unknown member". Shared
+ // by both `typingUsers` and the `resolveUserName` prop so the two paths
+ // can't drift.
+ const resolveUserName = useMemo(() => {
+ const fromFriends = makeUserNameResolver(friends)
+ return (userId: string) => {
+ if (userId === currentUser.id) return currentUser.name
+ if (dm && userId === dm.userId) return dm.name
+ return fromFriends(userId)
+ }
+ }, [friends, currentUser.id, currentUser.name, dm])
const messageActions = useMemo(() => ({
onToggleReaction: (id: string, emoji: string) =>
@@ -327,14 +342,7 @@ function DmView() {
messages={messages}
loading={messagesLoading}
newDividerBefore={newDividerBefore}
- typingUsers={typingUsers.map((id) => {
- // In a DM there are only two participants — if the typing id
- // matches the DM's counterpart, use their DM display name.
- // Fall back to friends list (adds names for friend-typers in
- // group DMs when we add them) and finally to "Unknown member".
- if (dm && id === dm.userId) return dm.name
- return resolveUserName(id)
- })}
+ typingUsers={typingUsers.map((id) => resolveUserName(id))}
onOpenThread={() => { }}
onToggleReaction={dmBlocked ? undefined : messageActions.onToggleReaction}
onReact={dmBlocked ? undefined : messageActions.onReact}
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index 1c484bc95..cbf066faf 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -6,6 +6,8 @@ import { AtSign, FileIcon, ImageIcon, PlusCircle, Smile, Upload, Users, X } from
import { useEditor, EditorContent } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
import Placeholder from "@tiptap/extension-placeholder"
+import { DOMParser as PMDOMParser } from "@tiptap/pm/model"
+import { buildPasteDom } from "@/lib/community/paste-plain-text"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import { useFileAttachments, type PendingFile } from "@/hooks/use-file-attachments"
@@ -230,6 +232,19 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe
}
return false
},
+ // Preserve BOTH newline levels on paste: a blank line (`\n\n`) becomes a
+ // paragraph break, a single `\n` becomes a hard line break — instead of
+ // ProseMirror's default, which collapses any run of newlines to one
+ // paragraph boundary (flattening a pasted multi-paragraph message). The
+ // built DOM is handed to ProseMirror's own `DOMParser.parseSlice` so
+ // slice open depths are computed by the library, not by hand.
+ clipboardTextParser: (text, $context) => {
+ const dom = buildPasteDom(text, document)
+ return PMDOMParser.fromSchema($context.doc.type.schema).parseSlice(dom, {
+ preserveWhitespace: true,
+ context: $context,
+ })
+ },
},
onUpdate: () => {
fireTyping()
@@ -238,7 +253,12 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe
const send = () => {
if (!editor || (editor.isEmpty && pendingFiles.length === 0)) return
- const markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n" }).trim()
+ // Block separator `\n\n` — paragraph breaks serialize as a markdown blank
+ // line (a real paragraph), while in-paragraph hard breaks serialize as a
+ // single `\n` (HardBreak's `renderText`). `remark-breaks` on render turns
+ // the single `\n` into `<br>` and the blank line into a new paragraph, so
+ // the compose → send → render round-trip preserves both newline levels.
+ const markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n\n" }).trim()
const mentionType = detectMentionType(markdown)
onSend?.(markdown, pendingFilesToSendAttachments(pendingFiles), mentionType)
editor.commands.clearContent()
@@ -277,8 +297,8 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe
{/* reply context bar — attached above the input */}
{replyingTo && (
<div className="flex items-center gap-2 rounded-t-xl border border-b-0 border-border/40 bg-muted/60 px-4 py-2 text-xs text-muted-foreground">
- <span>Replying to <span className="font-medium text-foreground">{replyingTo}</span></span>
- <button onClick={onCancelReply} className="ml-auto grid size-4 place-items-center rounded-full hover:bg-foreground/10 hover:text-foreground" aria-label="Cancel reply">
+ <span className="min-w-0 truncate">Replying to <span className="font-medium text-foreground">{replyingTo}</span></span>
+ <button onClick={onCancelReply} className="ml-auto grid size-4 shrink-0 place-items-center rounded-full hover:bg-foreground/10 hover:text-foreground" aria-label="Cancel reply">
<X className="size-3.5" />
</button>
</div>
diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsx
index eff134b5a..08ca8cb5a 100644
--- a/src/web/src/components/community/forum-view.tsx
+++ b/src/web/src/components/community/forum-view.tsx
@@ -152,7 +152,7 @@ export function ForumView({
</button>
)}
</div>
- <h3 className="text-[15px] font-semibold leading-tight">{p.name}</h3>
+ <h3 className="line-clamp-1 text-[15px] font-semibold leading-tight">{p.name}</h3>
<p className="line-clamp-2 text-sm text-muted-foreground">{p.preview}</p>
<div className="flex items-center gap-2">
{p.tags.length > 0 && p.tags.map((t) => (
diff --git a/src/web/src/components/community/inline-marks.tsx b/src/web/src/components/community/inline-marks.tsx
index df916a303..fc6312ba8 100644
--- a/src/web/src/components/community/inline-marks.tsx
+++ b/src/web/src/components/community/inline-marks.tsx
@@ -29,24 +29,29 @@ export function MentionPill({
children,
everyone,
onClick,
+ label,
}: {
children?: React.ReactNode
everyone?: boolean
onClick?: (e: React.MouseEvent) => void
+ // Plain-text label for the native `title` tooltip so a long, truncated
+ // mention stays fully readable on hover. Falls back to the string children.
+ label?: string
}) {
+ const title = label ?? (typeof children === "string" ? children : undefined)
const className = [
- "rounded-[4px] px-1 font-medium",
+ "inline-block max-w-[12rem] truncate align-bottom rounded-[4px] px-1 font-medium",
everyone ? "bg-primary/15 text-primary" : "bg-accent text-foreground",
onClick ? "cursor-pointer transition-colors hover:bg-primary/15 hover:text-primary" : "",
].join(" ")
if (onClick) {
return (
- <button type="button" onClick={onClick} className={className}>
+ <button type="button" onClick={onClick} title={title} className={className}>
{children}
</button>
)
}
- return <span className={className}>{children}</span>
+ return <span title={title} className={className}>{children}</span>
}
// Channel-ref pill — leading channel icon + name. `onClick` navigates
@@ -65,28 +70,29 @@ export function ChannelPill({
serverPrefix?: string
muted?: boolean
}) {
+ const title = typeof children === "string" ? children : undefined
const className = [
- "inline-flex items-center gap-1 rounded-lg bg-accent px-1 font-medium text-foreground",
+ "inline-flex max-w-[16rem] items-center gap-1 rounded-lg bg-accent px-1 align-bottom font-medium text-foreground",
muted ? "opacity-60" : "",
onClick ? "group/pill cursor-pointer transition-colors hover:bg-primary/15 hover:text-primary" : "",
].join(" ")
const content = (
<>
- <ChannelIcon className="text-xs" />
+ <ChannelIcon className="shrink-0 text-xs" />
{serverPrefix && (
- <span className="text-muted-foreground transition-colors group-hover/pill:text-primary">{serverPrefix} /</span>
+ <span className="shrink-0 text-muted-foreground transition-colors group-hover/pill:text-primary">{serverPrefix} /</span>
)}
- {children}
+ <span className="min-w-0 truncate">{children}</span>
</>
)
if (onClick) {
return (
- <button type="button" onClick={onClick} className={className}>
+ <button type="button" onClick={onClick} title={title} className={className}>
{content}
</button>
)
}
- return <span className={className}>{content}</span>
+ return <span title={title} className={className}>{content}</span>
}
// Server-ref pill — same icon/shape/on-off pattern as `ChannelPill` (reuses
@@ -102,23 +108,24 @@ export function ServerPill({
onClick?: (e: React.MouseEvent) => void
muted?: boolean
}) {
+ const title = typeof children === "string" ? children : undefined
const className = [
- "inline-flex items-center gap-1 rounded-lg bg-accent px-1 font-medium text-foreground",
+ "inline-flex max-w-[16rem] items-center gap-1 rounded-lg bg-accent px-1 align-bottom font-medium text-foreground",
muted ? "opacity-60" : "",
onClick ? "group/pill cursor-pointer transition-colors hover:bg-primary/15 hover:text-primary" : "",
].join(" ")
const content = (
<>
- <ChannelIcon className="text-xs" />
- {children}
+ <ChannelIcon className="shrink-0 text-xs" />
+ <span className="min-w-0 truncate">{children}</span>
</>
)
if (onClick) {
return (
- <button type="button" onClick={onClick} className={className}>
+ <button type="button" onClick={onClick} title={title} className={className}>
{content}
</button>
)
}
- return <span className={className}>{content}</span>
+ return <span title={title} className={className}>{content}</span>
}
diff --git a/src/web/src/components/community/message-body.test.ts b/src/web/src/components/community/message-body.test.ts
index 77a33b3e4..d540c581a 100644
--- a/src/web/src/components/community/message-body.test.ts
+++ b/src/web/src/components/community/message-body.test.ts
@@ -94,3 +94,31 @@ describe("MessageBody — mention pill survives sanitize (full pipeline)", () =>
expect(pill.props.onClick).toBeUndefined()
})
})
+
+// The composer serializes multi-line content with single `\n` separators
+// (getText's blockSeparator). Standard markdown collapses a single `\n` to a
+// space; `remark-breaks` (added to the remark pipeline) turns it into a hard
+// line break so typed/pasted newlines survive. These drive the full pipeline.
+describe("MessageBody — single newlines render as hard breaks (remark-breaks)", () => {
+ it("renders a <br> for a single \\n between two lines", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageBody, { text: "line one\nline two" }),
+ )
+ })
+ const brs = renderer!.root.findAllByType("br")
+ expect(brs.length).toBeGreaterThanOrEqual(1)
+ })
+
+ it("still renders a blank line (\\n\\n) as separate paragraphs", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageBody, { text: "para one\n\npara two" }),
+ )
+ })
+ const paras = renderer!.root.findAllByType("p")
+ expect(paras.length).toBe(2)
+ })
+})
diff --git a/src/web/src/components/community/message-body.tsx b/src/web/src/components/community/message-body.tsx
index 17e21de3d..42c80e2e7 100644
--- a/src/web/src/components/community/message-body.tsx
+++ b/src/web/src/components/community/message-body.tsx
@@ -2,6 +2,7 @@ import { useMemo } from "react"
import { Streamdown } from "streamdown"
import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from "rehype-sanitize"
import { harden } from "rehype-harden"
+import remarkBreaks from "remark-breaks"
import type { PluggableList } from "unified"
import { mermaid, cjk, math } from "@/lib/streamdown-plugins"
import { chatSyntaxPlugin, chatSyntaxHandlers } from "@/lib/community/chat-syntax-plugin"
@@ -86,11 +87,11 @@ export function MessageBody({ text, onOpenProfile }: { text: string; onOpenProfi
const inviteTokens = useMemo(() => extractInviteTokens(text), [text])
const components = useMemo(() => buildMdComponents(onOpenProfile), [onOpenProfile])
return (
- <div className="markdown text-[15px] leading-snug">
+ <div className="markdown wrap-anywhere text-[15px] leading-snug">
<Streamdown
parseIncompleteMarkdown={false}
plugins={{ mermaid, cjk, math }}
- remarkPlugins={[chatSyntaxPlugin]}
+ remarkPlugins={[chatSyntaxPlugin, remarkBreaks]}
remarkRehypeOptions={{ handlers: chatSyntaxHandlers }}
rehypePlugins={REHYPE_PLUGINS}
// Deliberately skips the AI-content confirm-before-navigating modal
diff --git a/src/web/src/components/community/message-list-items.test.ts b/src/web/src/components/community/message-list-items.test.ts
index fbcbc5541..ac7d30d95 100644
--- a/src/web/src/components/community/message-list-items.test.ts
+++ b/src/web/src/components/community/message-list-items.test.ts
@@ -266,19 +266,45 @@ describe("estimateRowHeight", () => {
})
describe("computeBelowCount", () => {
- it("returns 0 when the last visible index is the last item (itemCount - 1)", () => {
- expect(computeBelowCount(10, 9)).toBe(0)
+ // Three messages on the same day → [date-divider, message, message, message]
+ const items = flattenMessageItems(
+ [
+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", createdAt: "2026-01-01T10:01:00.000Z" }),
+ msg({ id: "m3", createdAt: "2026-01-01T10:02:00.000Z" }),
+ ],
+ undefined,
+ )
+
+ it("returns 0 when the last visible index is the last item", () => {
+ expect(computeBelowCount(items, items.length - 1)).toBe(0)
+ })
+
+ it("counts only message rows strictly after the last visible index", () => {
+ // lastVisibleIndex 1 (first message) → m2, m3 remain below = 2
+ expect(computeBelowCount(items, 1)).toBe(2)
})
- it("returns the count of items strictly after the last visible index", () => {
- expect(computeBelowCount(10, 6)).toBe(3)
+ it("excludes divider rows below the fold from the count", () => {
+ // Two days → [date-divider, m1, date-divider, m2]. With only the first
+ // message visible (index 1), a naive itemCount-based count would report 2
+ // (the trailing divider + m2); the message-only count is 1.
+ const twoDay = flattenMessageItems(
+ [
+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),
+ msg({ id: "m2", createdAt: "2026-01-02T10:00:00.000Z" }),
+ ],
+ undefined,
+ )
+ expect(twoDay.map((i) => i.kind)).toEqual(["date-divider", "message", "date-divider", "message"])
+ expect(computeBelowCount(twoDay, 1)).toBe(1)
})
- it("returns 0 for an empty list (itemCount 0, no items to be 'below')", () => {
- expect(computeBelowCount(0, -1)).toBe(0)
+ it("returns 0 for an empty list", () => {
+ expect(computeBelowCount([], -1)).toBe(0)
})
- it("clamps to 0 rather than going negative if lastVisibleIndex somehow exceeds the last index", () => {
- expect(computeBelowCount(5, 10)).toBe(0)
+ it("returns 0 when lastVisibleIndex is at or beyond the last index", () => {
+ expect(computeBelowCount(items, 99)).toBe(0)
})
})
diff --git a/src/web/src/components/community/message-list-items.ts b/src/web/src/components/community/message-list-items.ts
index 882fdc8e2..faa64f0f3 100644
--- a/src/web/src/components/community/message-list-items.ts
+++ b/src/web/src/components/community/message-list-items.ts
@@ -108,7 +108,14 @@ export function estimateRowHeight(item: FlatItem): number {
// 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)
+// exposes on every render. Counts only MESSAGE rows below the last visible
+// index — date/NEW dividers are structural, not messages, so a bare
+// `itemCount - 1 - lastVisibleIndex` would inflate the badge by one per
+// divider below the fold. Exported for direct unit testing.
+export function computeBelowCount(items: FlatItem[], lastVisibleIndex: number): number {
+ let count = 0
+ for (let i = lastVisibleIndex + 1; i < items.length; i++) {
+ if (items[i].kind === "message") count++
+ }
+ return count
}
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index 926667abd..7594d578a 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -158,7 +158,7 @@ export function MessageList({
// `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({
+ const { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo: jumpToIndex, onImageLoad } = useScrollAnchor({
items,
newDividerBefore,
initialScrollReady,
@@ -307,7 +307,7 @@ export function MessageList({
onClick={pillOnClick}
/>
<TypingIndicator names={isLoading ? [] : typingUsers ?? []} />
- <div ref={scrollRef} className="flex-1 overflow-y-auto thin-scrollbar">
+ <div ref={scrollRef} className="flex-1 overflow-x-clip overflow-y-auto thin-scrollbar">
<div className="flex min-h-full flex-col justify-end px-4 py-8">
{isLoading ? (
<MessageListSkeletonContent variant={variant} />
@@ -386,6 +386,7 @@ export function MessageList({
onDownloadFile={onDownloadFile}
highlighted={jumped === item.m.id}
resolveUserName={resolveUserName}
+ onImageLoad={onImageLoad}
/>
</div>
)}
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index 85c7d3cfc..1b802cb53 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
export function Message({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
onToggleReaction, onReact, onReply, onPin, onCreateThread, onCopy, onRetry,
- onPreviewImage, onDownloadFile, highlighted, resolveUserName,
+ onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad,
}: {
m: RenderMsg
compact?: boolean
@@ -53,6 +53,11 @@ export function Message({
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
}) {
// keep the hover toolbar pinned open while its ⋯ dropdown is open
const [toolbarOpen, setToolbarOpen] = useState(false)
@@ -62,8 +67,8 @@ export function Message({
return (
<div className="flex items-center gap-2 px-2 py-1 text-sm text-muted-foreground">
<Icon className="size-4 shrink-0" />
- <span>{m.content}</span>
- <span className="text-xs" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span>
+ <span className="min-w-0 wrap-break-word">{m.content}</span>
+ <span className="shrink-0 text-xs" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span>
</div>
)
}
@@ -113,14 +118,14 @@ export function Message({
)}
{m.replyTo && (
- <button onClick={onJumpReply} className="mb-1 ml-13 flex items-center gap-2 text-[13px] text-muted-foreground hover:text-foreground">
- <div className="h-2 w-4 rounded-tl-md border-l-2 border-t-2 border-border" />
+ <button onClick={onJumpReply} className="mb-1 ml-13 flex min-w-0 max-w-[calc(100%-3.25rem)] items-center gap-2 text-[13px] text-muted-foreground hover:text-foreground">
+ <div className="h-2 w-4 shrink-0 rounded-tl-md border-l-2 border-t-2 border-border" />
{m.replyTo.deleted ? (
<span className="italic text-muted-foreground">Original message was deleted</span>
) : (
<>
- <span className="font-medium text-foreground/80">@{m.replyTo.authorName}</span>
- <span className="truncate">{stripInlineMarkup(m.replyTo.text)}</span>
+ <span className="shrink-0 font-medium text-foreground/80">@{m.replyTo.authorName}</span>
+ <span className="min-w-0 truncate">{stripInlineMarkup(m.replyTo.text)}</span>
</>
)}
</button>
@@ -139,12 +144,12 @@ export function Message({
<div className="flex items-baseline gap-2">
<button
onClick={(e) => onOpenProfile?.(m.authorName ?? "", e, undefined, m.authorId)}
- className="text-[15px] font-semibold hover:underline"
+ className="min-w-0 max-w-full truncate text-[15px] font-semibold hover:underline"
style={{ color: m.color ?? "var(--foreground)" }}
>
{m.authorName}
</button>
- <span className="text-xs text-muted-foreground" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span>
+ <span className="shrink-0 text-xs text-muted-foreground" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span>
</div>
)}
{m.content && (
@@ -160,7 +165,7 @@ export function Message({
onClick={() => onPreviewImage?.(a.url)}
className="block w-fit max-w-[320px] overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"
>
- <img src={a.url} alt={a.name} className="max-h-50 max-w-[320px] rounded-lg object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} />
+ <img src={a.url} alt={a.name} width={a.width} height={a.height} className="max-h-50 max-w-[320px] rounded-lg object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} onLoad={onImageLoad} />
</button>
) : (
<button
@@ -228,7 +233,7 @@ export function Message({
)}
{embed.image && (
- <img src={embed.image.url} alt="" className="mt-2 w-full max-w-100 rounded-sm object-cover" style={{ aspectRatio: embed.image.width && embed.image.height ? `${embed.image.width}/${embed.image.height}` : "40/21" }} />
+ <img src={embed.image.url} alt="" width={embed.image.width} height={embed.image.height} className="mt-2 w-full max-w-100 rounded-sm object-cover" style={{ aspectRatio: embed.image.width && embed.image.height ? `${embed.image.width}/${embed.image.height}` : "40/21" }} onLoad={onImageLoad} />
)}
{embed.footer && (
diff --git a/src/web/src/components/community/profile-card.tsx b/src/web/src/components/community/profile-card.tsx
index 506e52eb0..261ade0e9 100644
--- a/src/web/src/components/community/profile-card.tsx
+++ b/src/web/src/components/community/profile-card.tsx
@@ -149,10 +149,10 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
</div>
</div>
<div className="rounded-lg bg-card p-4">
- <div className="text-xl font-semibold leading-tight tracking-[-0.015em]">
- {data.name}
+ <div className="flex min-w-0 items-baseline text-xl font-semibold leading-tight tracking-[-0.015em]">
+ <span className="min-w-0 truncate">{data.name}</span>
{data.discriminator && (
- <span className="ml-1.5 text-sm font-normal tracking-wide text-muted-foreground">
+ <span className="ml-1.5 shrink-0 text-sm font-normal tracking-wide text-muted-foreground">
#{data.discriminator}
</span>
)}
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 73ad1fa30..7dec3f97a 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -286,6 +286,7 @@ export function useScrollAnchor({
belowCount: number
scrollToBottom: () => void
jumpTo: (messageId: string) => void
+ onImageLoad: () => void
} {
const scrollRef = useRef<HTMLDivElement>(null)
const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())
@@ -364,18 +365,71 @@ export function useScrollAnchor({
if (delta !== 0) el.scrollTop += delta
}, [heroHeight])
+ // Composer/viewport resize compensation — the composer is a flex sibling
+ // of this scroll viewport with no `shrink-0`, so when it grows/shrinks
+ // (auto-grow while typing, clearing on send, opening/closing the reply
+ // banner, adding/removing attachment chips) the viewport's `clientHeight`
+ // changes and the bottom-pinned content (`min-h-full … justify-end`) would
+ // otherwise appear to jump. A `ResizeObserver` on the viewport itself
+ // catches every such resize regardless of cause without coupling to the
+ // composer component: if the list was at the bottom, re-pin instantly (NOT
+ // the smooth `scrollToBottom` — a smooth animation firing on every
+ // keystroke resize is janky and fights rapid successive resizes); otherwise
+ // compensate `scrollTop` by the height delta so the visible top-of-content
+ // stays put. Keyed on `clientHeight`, orthogonal to the hero compensation
+ // below (keyed on `heroHeight`) — separate effects, no double-apply.
+ const prevClientHeightRef = useRef(0)
+ useLayoutEffect(() => {
+ const el = scrollRef.current
+ if (!el) return
+ // First-fire guard: ResizeObserver fires immediately on observe() with
+ // the current size. Seed the previous height first so that initial
+ // callback computes a zero delta instead of a spurious jump at mount.
+ prevClientHeightRef.current = el.clientHeight
+ const ro = new ResizeObserver(() => {
+ const prev = prevClientHeightRef.current
+ const next = el.clientHeight
+ if (next === prev) return
+ const wasAtEnd = virtualizer.isAtEnd(NEAR_BOTTOM_PX)
+ prevClientHeightRef.current = next
+ if (wasAtEnd) {
+ virtualizer.scrollToEnd()
+ } else {
+ el.scrollTop += prev - next
+ }
+ })
+ ro.observe(el)
+ return () => ro.disconnect()
+ }, [virtualizer])
+
// "↓ 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)
+ // `virtualizer.range?.endIndex` is the last VISIBLE index BEFORE overscan
+ // is applied (overscan is added only in `defaultRangeExtractor`, not in
+ // `range`), so counting below it doesn't treat the 8 overscanned off-screen
+ // rows as visible and deflate the badge. `null` before the first
+ // measurement → `-1` → `computeBelowCount` returns 0 (nothing measured
+ // yet), which is correct.
+ const lastVisibleIndex = virtualizer.range?.endIndex ?? -1
+ const belowCount = virtualizer.isAtEnd(NEAR_BOTTOM_PX) ? 0 : computeBelowCount(items, lastVisibleIndex)
const scrollToBottom = useCallback(() => {
virtualizer.scrollToEnd({ behavior: "smooth" })
}, [virtualizer])
+ // Re-pin after an attachment image finishes loading, but only if the
+ // viewer is still at/near the bottom — restores the deleted
+ // `watchAsyncGrowth` image-decode re-scroll narrowly, per-image and gated,
+ // so a dimensionless image that grows after `scrollToEnd` already fired
+ // still lands the message's bottom at the viewport bottom, while never
+ // yanking a reader who has scrolled away. Instant (no smooth) so it doesn't
+ // animate on every image load.
+ const onImageLoad = useCallback(() => {
+ if (virtualizer.isAtEnd(NEAR_BOTTOM_PX)) virtualizer.scrollToEnd()
+ }, [virtualizer])
+
const jumpTo = useCallback((messageId: string) => {
const idx = findMessageIndex(items, messageId)
// Target not in the currently loaded page window — same limitation the
@@ -385,5 +439,5 @@ export function useScrollAnchor({
virtualizer.scrollToIndex(idx, { align: "center", behavior: "smooth" })
}, [items, virtualizer])
- return { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo }
+ return { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo, onImageLoad }
}
diff --git a/src/web/src/lib/community/paste-plain-text.test.ts b/src/web/src/lib/community/paste-plain-text.test.ts
new file mode 100644
index 000000000..97825247f
--- /dev/null
+++ b/src/web/src/lib/community/paste-plain-text.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect } from "vitest"
+import { splitPlainTextToBlocks, planPastedBlocks } from "./paste-plain-text"
+
+describe("splitPlainTextToBlocks", () => {
+ it("splits on a blank line into separate blocks", () => {
+ expect(splitPlainTextToBlocks("para one\n\npara two")).toEqual(["para one", "para two"])
+ })
+
+ it("keeps a single newline inside one block (not a paragraph break)", () => {
+ expect(splitPlainTextToBlocks("line one\nline two")).toEqual(["line one\nline two"])
+ })
+
+ it("treats 3+ newlines as one paragraph break, not empty blocks", () => {
+ expect(splitPlainTextToBlocks("a\n\n\nb")).toEqual(["a", "b"])
+ })
+
+ it("trims leading/trailing blank lines so there are no empty edge blocks", () => {
+ expect(splitPlainTextToBlocks("\n\nmiddle\n\n")).toEqual(["middle"])
+ })
+
+ it("normalizes CRLF", () => {
+ expect(splitPlainTextToBlocks("a\r\n\r\nb")).toEqual(["a", "b"])
+ })
+
+ it("returns an empty array for whitespace-only text", () => {
+ expect(splitPlainTextToBlocks("\n\n\n")).toEqual([])
+ })
+})
+
+describe("planPastedBlocks", () => {
+ it("returns one block per blank-line-separated paragraph", () => {
+ expect(planPastedBlocks("para one\n\npara two")).toEqual([["para one"], ["para two"]])
+ })
+
+ it("splits single newlines into hard-break lines within one block", () => {
+ expect(planPastedBlocks("line one\nline two\nline three")).toEqual([
+ ["line one", "line two", "line three"],
+ ])
+ })
+
+ it("preserves both levels together (paragraphs with internal line breaks)", () => {
+ // A title line + body line in one paragraph, then a separate paragraph —
+ // mirrors the reported agent-answer paste (blank line between sections,
+ // single newline between a heading and its text).
+ expect(planPastedBlocks("**title**\nbody line\n\nnext para")).toEqual([
+ ["**title**", "body line"],
+ ["next para"],
+ ])
+ })
+
+ it("returns an empty plan for whitespace-only text", () => {
+ expect(planPastedBlocks("\n\n")).toEqual([])
+ })
+})
diff --git a/src/web/src/lib/community/paste-plain-text.ts b/src/web/src/lib/community/paste-plain-text.ts
new file mode 100644
index 000000000..9746aea4f
--- /dev/null
+++ b/src/web/src/lib/community/paste-plain-text.ts
@@ -0,0 +1,59 @@
+// Plain-text paste → ProseMirror DOM, preserving BOTH structure levels.
+//
+// ProseMirror's default clipboard text parser splits on `/(?:\r\n?|\n)+/` —
+// one-OR-MORE newlines collapse to a single paragraph boundary, so a blank
+// line (`\n\n`, a real paragraph break) and a single `\n` (an in-paragraph
+// line break) become indistinguishable the moment text is pasted. Pasting an
+// agent's multi-paragraph answer therefore flattens every paragraph gap.
+//
+// This builds the DOM the parser needs from the two levels the source text
+// actually encodes, matching markdown's block model exactly:
+// - `\n\n+` (one blank line or more) → a new <p> (paragraph break)
+// - single `\n` inside a block → a <br> (hard line break)
+// Paired with `getText({ blockSeparator: "\n\n" })` on send and `remark-breaks`
+// on render, the round-trip is lossless: paste → serialize → render all agree.
+//
+// Extracted as a pure DOM builder (no ProseMirror imports) so it can be unit
+// tested with jsdom's `document`; the composer wraps it in a
+// `clipboardTextParser` that hands the DOM to ProseMirror's own
+// `DOMParser.parseSlice` (which computes slice open depths correctly — never
+// hand-rolled here).
+
+// Split on 2+ newlines (allowing \r\n / \r), trimming a single leading/trailing
+// blank-line run so a copied block with surrounding whitespace doesn't yield
+// empty leading/trailing paragraphs.
+const PARAGRAPH_SPLIT = /(?:\r\n?|\n){2,}/
+
+export function splitPlainTextToBlocks(text: string): string[] {
+ const normalized = text.replace(/\r\n?/g, "\n").replace(/^\n+|\n+$/g, "")
+ if (normalized === "") return []
+ return normalized.split(PARAGRAPH_SPLIT)
+}
+
+/**
+ * Pure structural view of pasted text: an array of blocks (paragraphs), each
+ * block an array of lines (hard breaks between them). No DOM — the unit-
+ * testable core of the paste transform.
+ * "a\nb\n\nc" → [["a", "b"], ["c"]]
+ */
+export function planPastedBlocks(text: string): string[][] {
+ return splitPlainTextToBlocks(text).map((block) => block.split("\n"))
+}
+
+/**
+ * Build a `<div>` of `<p>` blocks (single `\n` → `<br>`) from pasted plain
+ * text, using the provided `doc`. Returns a DIV whose children ProseMirror's
+ * `DOMParser.parseSlice` can consume.
+ */
+export function buildPasteDom(text: string, doc: Document): HTMLDivElement {
+ const wrap = doc.createElement("div")
+ for (const lines of planPastedBlocks(text)) {
+ const p = doc.createElement("p")
+ lines.forEach((line, i) => {
+ if (i > 0) p.appendChild(doc.createElement("br"))
+ if (line) p.appendChild(doc.createTextNode(line))
+ })
+ wrap.appendChild(p)
+ }
+ return wrap
+}