Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): restore conversation UI regressions (#837)

Generd990f077bf66
diff --git a/src/shared/src/db/queries/community/dm.ts b/src/shared/src/db/queries/community/dm.ts
index 77084569f..8800502cd 100644
--- a/src/shared/src/db/queries/community/dm.ts
+++ b/src/shared/src/db/queries/community/dm.ts
@@ -4,6 +4,7 @@ import { alias } from "drizzle-orm/sqlite-core";
import { communityChannel, communityChannelMember, communityFriendship } from "../../community-schema";
import { user } from "../../schema";
import { PARTICIPANT_SOURCE } from "../../../constants/community";
+import { compareAsciiSqliteBinary } from "../../../lib/sqlite-binary";
import type { Database } from "../../index";
function dmChannelQuery(
@@ -282,7 +283,7 @@ export async function listDMs(db: Database, userId: string) {
return result.sort((a, b) => {
const aTime = a.lastMessageAt ?? a.createdAt;
const bTime = b.lastMessageAt ?? b.createdAt;
- return bTime.localeCompare(aTime);
+ return bTime.localeCompare(aTime) || compareAsciiSqliteBinary(a.id, b.id);
});
}
diff --git a/src/shared/test/queries/community-dm-order.test.ts b/src/shared/test/queries/community-dm-order.test.ts
new file mode 100644
index 000000000..6bde47b4c
--- /dev/null
+++ b/src/shared/test/queries/community-dm-order.test.ts
@@ -0,0 +1,80 @@
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import type { Database } from "../../src/db"
+import { listDMs } from "../../src/db/queries/community/dm"
+
+describe("listDMs ordering", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE community_channel (
+ id TEXT PRIMARY KEY,
+ type TEXT NOT NULL,
+ last_message_at TEXT,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE community_channel_member (
+ channel_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ relation TEXT NOT NULL
+ );
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL,
+ image TEXT,
+ avatarVersion INTEGER NOT NULL DEFAULT 0,
+ discriminator TEXT NOT NULL DEFAULT '0000',
+ deletedAt TEXT
+ );
+ `)
+ db = drizzle(sqlite) as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("preserves SQLite BINARY ordering for equal-activity mixed-case nanoids", async () => {
+ const channelIds = [
+ "kMRip4KDm4Ki2HU8vQ2qd",
+ "bc02tEwQaazjdPwrMuNih",
+ "XzKeKetmiRMJ16hwOrhSl",
+ "3kY1MAppCm6RYM4IvnXPN",
+ ]
+ const activityAt = "2026-09-27T03:00:00.000Z"
+ sqlite.prepare(
+ "INSERT INTO user (id, name, email) VALUES (?, ?, ?)",
+ ).run("viewer", "Viewer", "[email protected]")
+ const insertChannel = sqlite.prepare(`
+ INSERT INTO community_channel (id, type, last_message_at, created_at)
+ VALUES (?, 'dm', ?, ?)
+ `)
+ const insertUser = sqlite.prepare(
+ "INSERT INTO user (id, name, email) VALUES (?, ?, ?)",
+ )
+ const insertMember = sqlite.prepare(`
+ INSERT INTO community_channel_member (channel_id, user_id, relation)
+ VALUES (?, ?, 'access')
+ `)
+
+ channelIds.forEach((channelId, index) => {
+ const peerId = `peer-${index}`
+ insertChannel.run(channelId, activityAt, activityAt)
+ insertUser.run(peerId, peerId, `${peerId}@example.com`)
+ insertMember.run(channelId, "viewer")
+ insertMember.run(channelId, peerId)
+ })
+
+ const rows = await listDMs(db, "viewer")
+
+ expect(rows.map((row) => row.id)).toEqual([
+ "3kY1MAppCm6RYM4IvnXPN",
+ "XzKeKetmiRMJ16hwOrhSl",
+ "bc02tEwQaazjdPwrMuNih",
+ "kMRip4KDm4Ki2HU8vQ2qd",
+ ])
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/dms/route.test.ts b/src/web/src/app/api/community/users/me/dms/route.test.ts
index fbd90e592..9a9678665 100644
--- a/src/web/src/app/api/community/users/me/dms/route.test.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.test.ts
@@ -86,6 +86,9 @@ describe("GET /api/community/users/me/dms — name projection", () => {
expect(body.conversations[0]?.name).toBe("Alice")
expect(body.conversations[0]?.name).not.toContain("@")
expect(body.conversations[0]?.avatar).toBe("A")
+ expect(body.conversations[0]).toMatchObject({
+ activityAt: "2026-06-30T00:00:00.000Z",
+ })
})
it("projects canonical unread state and its sequence evidence", async () => {
@@ -108,6 +111,7 @@ describe("GET /api/community/users/me/dms — name projection", () => {
const res = await GET(getReq(), {} as any)
expect((await res.json()).conversations[0]).toMatchObject({
id: "d1",
+ activityAt: "2026-06-30T00:00:00.000Z",
unread: true,
lastUnreadSeq: 9,
})
diff --git a/src/web/src/app/api/community/users/me/dms/route.ts b/src/web/src/app/api/community/users/me/dms/route.ts
index 442ba1d2a..34c31d376 100644
--- a/src/web/src/app/api/community/users/me/dms/route.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.ts
@@ -38,6 +38,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
avatarVersion: r.otherUserAvatarVersion,
status: "offline" as const,
preview: "",
+ activityAt: r.lastMessageAt ?? r.createdAt,
unread: unreadByChannelId.has(r.id),
...(unreadByChannelId.has(r.id)
? { lastUnreadSeq: unreadByChannelId.get(r.id) }
diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.ts
index 9d54c7814..45570f030 100644
--- a/src/web/src/app/c/me/[dmId]/page.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.test.ts
@@ -21,8 +21,10 @@ describe("DM page loading ownership", () => {
expect(source).not.toContain("composerOverlap")
expect(source).not.toContain("onOverlapChange")
expect(source).toContain("typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}")
- const messageListProps = source.split(" <MessageList\n")[1]?.split(" />")[0]
- expect(messageListProps).not.toContain("typingUsers")
+ const dmHeaderProps = source.split("<DmHeader\n")[1]?.split("/>")[0]
+ expect(dmHeaderProps).not.toContain("typingUsers")
+ const messageListProps = source.split("<MessageList\n")[1]?.split("/>")[0]
+ expect(messageListProps).toContain("typingUsers")
expect(source).not.toContain('data-onboarding-name={dm.name} className="shrink-0"')
expect(source).toContain("loading={loadingOwnership.messageBodyLoading}")
expect(source).not.toContain("<ComposerSkeleton")
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 5e47f6372..ba02eb4a6 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -445,7 +445,6 @@ function DmView() {
<DmHeader
dm={dm}
onBack={bp === "mobile" ? goBack : undefined}
- typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}
notifLevel={(notifications.channel[dmId] ?? notifLevelDisplay("all")) as NotifLevel}
onSetNotifLevel={(level) => setNotification.mutate({ channelId: dmId, level }, {
onError: (error) => toastApiError(error, "Failed to update notification level"),
@@ -491,6 +490,7 @@ function DmView() {
onJumpToPresent={jumpToPresent}
presentVersion={presentVersion}
unreadCount={unreadCount}
+ typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}
hero={
<>
<div className="relative mb-3 w-fit"><Avatar label={dm.avatar} seed={dm.userId} size={64} /></div>
diff --git a/src/web/src/components/community/channels/channel-header.navigation.dom.test.ts b/src/web/src/components/community/channels/channel-header.navigation.dom.test.ts
index cc958c019..dfad583aa 100644
--- a/src/web/src/components/community/channels/channel-header.navigation.dom.test.ts
+++ b/src/web/src/components/community/channels/channel-header.navigation.dom.test.ts
@@ -74,9 +74,9 @@ describe("ChannelHeader hierarchy navigation", () => {
expect(screen.getByRole("button", { name: "Open thread full screen" })).toBeInTheDocument()
})
- it("owns typing presence without changing the header footprint", () => {
- const renderer = renderHeader({ typingUsers: ["Alice"] })
- expect(renderer.getByTestId(tid.typingIndicator)).toHaveTextContent("Alice is typing…")
+ it("keeps transient typing presence out of the header footprint", () => {
+ const renderer = renderHeader()
+ expect(renderer.queryByTestId(tid.typingIndicator)).not.toBeInTheDocument()
expect(renderer.getByRole("banner")).toHaveClass("h-12", "shrink-0")
})
})
diff --git a/src/web/src/components/community/channels/channel-header.tsx b/src/web/src/components/community/channels/channel-header.tsx
index b38a24250..d1359f86d 100644
--- a/src/web/src/components/community/channels/channel-header.tsx
+++ b/src/web/src/components/community/channels/channel-header.tsx
@@ -19,7 +19,6 @@ import type { RightPanel } from "@/components/community/shell/panel-types"
import type { EntityKind } from "@/lib/community/models/navigation"
import { CreateDialogShell } from "../settings/create-dialog-shell"
import { tid } from "@/lib/community/testids"
-import { TypingIndicator } from "../messages/typing-indicator"
import { MessageHeader, MessageHeaderMobileBack } from "./message-header"
// Skeleton header for the loading frame between route change and channel
@@ -75,7 +74,7 @@ export type ChannelNotifLevel = typeof USE_SERVER_DEFAULT | NotifLevel
export function ChannelHeader({
channel, rightPanel, onToggle, notifLevel, onSetNotifLevel,
kind = "text", server, mobileBack, mobileBackDisplay = "viewport", onBack, tools,
- onRename, titleRename, endActions, compactActions, typingUsers = [],
+ onRename, titleRename, endActions, compactActions,
}: {
channel: string
kind?: EntityKind
@@ -92,7 +91,6 @@ export function ChannelHeader({
tools?: { threads?: boolean; pinned?: boolean; members?: boolean }
endActions?: ReactNode
compactActions?: boolean
- typingUsers?: string[]
}) {
const tool = (k: Exclude<RightPanel, null>, Icon: LucideIcon, label: string) => (
@@ -121,7 +119,6 @@ export function ChannelHeader({
<EntityIcon kind={kind} className="size-4" />
</div>
<span className="min-w-0 truncate text-base font-semibold" title={channel}>{channel}</span>
- <TypingIndicator names={typingUsers} variant="header" />
{onRename && (
<HeaderRename
label={channel}
diff --git a/src/web/src/components/community/channels/dm-header.test.ts b/src/web/src/components/community/channels/dm-header.test.ts
index 2161154da..8e9d04794 100644
--- a/src/web/src/components/community/channels/dm-header.test.ts
+++ b/src/web/src/components/community/channels/dm-header.test.ts
@@ -34,15 +34,9 @@ describe("DmHeader", () => {
expect(markup).toContain(`data-testid="${tid.dmHeaderTitle}"`)
})
- it("owns typing presence inside the fixed-height header", () => {
- const markup = renderToStaticMarkup(createElement(DmHeader, {
- dm,
- typingUsers: ["Alice"],
- }))
- expect(markup).toContain(`data-testid="${tid.typingIndicator}"`)
- expect(markup).toContain("Alice")
- expect(markup).toContain("is typing…")
- expect(markup).toContain("hidden sm:inline")
+ it("keeps transient typing presence out of the fixed-height header", () => {
+ const markup = renderToStaticMarkup(createElement(DmHeader, { dm }))
+ expect(markup).not.toContain(`data-testid="${tid.typingIndicator}"`)
})
})
diff --git a/src/web/src/components/community/channels/dm-header.tsx b/src/web/src/components/community/channels/dm-header.tsx
index 2a347c9b9..fe2264eb5 100644
--- a/src/web/src/components/community/channels/dm-header.tsx
+++ b/src/web/src/components/community/channels/dm-header.tsx
@@ -6,23 +6,14 @@ import { Skeleton } from "@/components/ui/skeleton"
import { Avatar } from "../avatar"
import type { DM } from "@/lib/community/models/people"
import { tid } from "@/lib/community/testids"
-import { TypingIndicator } from "../messages/typing-indicator"
import { MessageHeader, MessageHeaderMobileBack } from "./message-header"
-export function DmHeader({
- dm,
- onBack,
- titleAs: Title = "h1",
- notifLevel,
- onSetNotifLevel,
- typingUsers = [],
-}: {
+export function DmHeader({ dm, onBack, titleAs: Title = "h1", notifLevel, onSetNotifLevel }: {
dm: DM
onBack?: () => void
titleAs?: "h1" | "div"
notifLevel?: NotifLevel
onSetNotifLevel?: (level: NotifLevel) => void
- typingUsers?: string[]
}) {
return (
<MessageHeader
@@ -40,7 +31,6 @@ export function DmHeader({
</span>
)}
</Title>
- <TypingIndicator names={typingUsers} variant="header" />
</>
)}
actions={notifLevel && <DmNotifDropdown level={notifLevel} onSetLevel={onSetNotifLevel} />}
diff --git a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
index dd7ca8b33..b56f08a2f 100644
--- a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
@@ -463,7 +463,7 @@ describe("TextChannelSurface header hierarchy", () => {
expect(renderer.container.querySelector('[data-slot="community-conversation-surface"]'))
.toHaveAttribute("data-channel-id", "channel_1")
expect(mockedMessageList.mock.calls.at(-1)?.[0]).not.toHaveProperty("composerOverlap")
- expect(mockedMessageList.mock.calls.at(-1)?.[0]).not.toHaveProperty("typingUsers")
- expect(mockedChannelHeader.mock.calls.at(-1)?.[0].typingUsers).toEqual([])
+ expect(mockedMessageList.mock.calls.at(-1)?.[0].typingUsers).toEqual([])
+ expect(mockedChannelHeader.mock.calls.at(-1)?.[0]).not.toHaveProperty("typingUsers")
})
})
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index e97adeced..952cf3794 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -125,7 +125,6 @@ export function TextChannelSurface({
notifLevel={notificationLevel}
onSetNotifLevel={onSetNotificationLevel}
mobileBack={onNavigateParent}
- typingUsers={controller.typingUsers}
/>
)}
body={(
@@ -163,6 +162,7 @@ export function TextChannelSurface({
onJumpToPresent={feed.jumpToPresent}
presentVersion={feed.presentVersion}
unreadCount={feed.unreadCount}
+ typingUsers={controller.typingUsers}
/>
<ConversationFooterShell
data-onboarding-target="channel-composer"
diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
index 39ce1504f..c013ca283 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
@@ -360,13 +360,13 @@ describe("ThreadChannelSurface ownership", () => {
channel: "Thread name",
kind: "thread",
mobileBack: props.onNavigateParent,
- typingUsers: ["Alice"],
}), undefined)
+ expect(mockedChannelHeader.mock.calls.at(-1)?.[0]).not.toHaveProperty("typingUsers")
expect(mockedMessageList).toHaveBeenCalledWith(expect.objectContaining({
channel: "Thread name",
loading: true,
}), undefined)
- expect(mockedMessageList.mock.calls.at(-1)?.[0]).not.toHaveProperty("typingUsers")
+ expect(mockedMessageList.mock.calls.at(-1)?.[0].typingUsers).toEqual(["Alice"])
expect(mockedComposer).toHaveBeenCalled()
mockedUseChannelMessageFeed.mockReturnValue(feed({ isLoading: false, isError: true }))
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index b61fdf631..ee1954cf8 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -221,7 +221,6 @@ export function ThreadChannelSurface({
titleRename={parentIsForum}
onRename={parentChannelId && !splitActions ? rename : undefined}
compactActions={!!splitActions}
- typingUsers={controller.typingUsers}
endActions={splitActions ? (
<ThreadPanelActions
onFullscreen={splitActions.onFullscreen}
@@ -266,6 +265,7 @@ export function ThreadChannelSurface({
onJumpToPresent={controller.feed.jumpToPresent}
presentVersion={controller.feed.presentVersion}
unreadCount={controller.feed.unreadCount}
+ typingUsers={controller.typingUsers}
/>
<ConversationFooterShell
data-onboarding-target="channel-composer"
diff --git a/src/web/src/components/community/messages/composer-accessory-rail-layout.test.ts b/src/web/src/components/community/messages/composer-accessory-rail-layout.test.ts
new file mode 100644
index 000000000..ce8ad594d
--- /dev/null
+++ b/src/web/src/components/community/messages/composer-accessory-rail-layout.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest"
+import {
+ allocateComposerAccessoryRail,
+ type ComposerAccessoryRailLayout,
+} from "./composer-accessory-rail-layout"
+
+describe("allocateComposerAccessoryRail", () => {
+ it.each([
+ [false, false, "empty"],
+ [true, false, "left-only"],
+ [false, true, "centered"],
+ [true, true, "centered"],
+ ] satisfies Array<[boolean, boolean, ComposerAccessoryRailLayout]>) (
+ "maps normal left=%s center=%s to %s",
+ (left, center, expected) => {
+ expect(allocateComposerAccessoryRail({ mode: "normal", left, center })).toBe(expected)
+ },
+ )
+})
diff --git a/src/web/src/components/community/messages/composer-accessory-rail-layout.ts b/src/web/src/components/community/messages/composer-accessory-rail-layout.ts
new file mode 100644
index 000000000..71a259001
--- /dev/null
+++ b/src/web/src/components/community/messages/composer-accessory-rail-layout.ts
@@ -0,0 +1,18 @@
+export type ComposerAccessoryRailOccupancy = {
+ mode: "normal"
+ left: boolean
+ center: boolean
+}
+
+export type ComposerAccessoryRailLayout =
+ | "empty"
+ | "centered"
+ | "left-only"
+
+export function allocateComposerAccessoryRail(
+ occupancy: ComposerAccessoryRailOccupancy,
+): ComposerAccessoryRailLayout {
+ if (occupancy.center) return "centered"
+ if (occupancy.left) return "left-only"
+ return "empty"
+}
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts
index ac442f3ce..e6fe135b0 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts
+++ b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts
@@ -1,10 +1,9 @@
import React from "react"
import { readFileSync } from "node:fs"
import { resolve } from "node:path"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { beforeEach, describe, expect, it, vi } from "vitest"
import { tid } from "@/lib/community/testids"
-import { useCommunityWsStore } from "@/stores/community/ws"
-import { fireEvent, render } from "@/test/react-dom-harness"
+import { fireEvent, render, type RenderResult } from "@/test/react-dom-harness"
import { ComposerAccessoryRail, MessageSelectionFooter } from "./composer-accessory-rail"
vi.mock("@/components/ui/number-ticker", () => ({
@@ -23,57 +22,71 @@ vi.mock("@/components/ui/tooltip", () => ({
TooltipContent: ({ children }: { children: React.ReactNode }) => React.createElement("tooltip-content", null, children),
}))
-const railProps = {
+const baseProps = {
+ typingNames: [] as string[],
scrollCount: 4,
scrollMode: "jump" as const,
onScroll: vi.fn(),
}
describe("ComposerAccessoryRail", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- useCommunityWsStore.getState().reset()
- })
+ beforeEach(() => vi.clearAllMocks())
- afterEach(() => {
- useCommunityWsStore.getState().reset()
- })
+ function renderRail(overrides: Partial<typeof baseProps> = {}) {
+ return render(React.createElement(ComposerAccessoryRail, {
+ ...baseProps,
+ ...overrides,
+ }))
+ }
+
+ function slotClassName(renderer: RenderResult, testId: string): string {
+ const node = renderer.getByTestId(testId).closest('div[class*="col-start-"]')
+ expect(node, `${testId} must have a bounded grid slot`).not.toBeNull()
+ return node!.className
+ }
+
+ it.each([
+ [false, false, "empty"],
+ [true, false, "left-only"],
+ [false, true, "centered"],
+ [true, true, "centered"],
+ ] as const)(
+ "renders typing=%s scroll=%s as %s",
+ (typing, center, layout) => {
+ const renderer = renderRail({
+ typingNames: typing ? ["Alice"] : [],
+ scrollCount: center ? 2 : 0,
+ })
+ const rails = renderer.queryAllByTestId(tid.composerAccessoryRail)
+ expect(rails).toHaveLength(layout === "empty" ? 0 : 1)
+ expect(renderer.queryAllByTestId(tid.scrollToPresent)).toHaveLength(center ? 1 : 0)
+ expect(renderer.queryAllByTestId(tid.typingIndicator)).toHaveLength(typing ? 1 : 0)
+ if (layout === "empty") return
- it("renders only the away scroll control and preserves its floating boundary", () => {
- const renderer = render(React.createElement(ComposerAccessoryRail, railProps))
+ expect(rails[0]).toHaveAttribute("data-layout", layout)
+ if (center) expect(slotClassName(renderer, tid.scrollToPresent)).toContain("col-start-2")
+ if (typing) expect(slotClassName(renderer, tid.typingIndicator)).toContain("col-start-1")
+ },
+ )
+
+ it("centers the scroll control without owning composer geometry", () => {
+ const renderer = renderRail()
const rail = renderer.getByTestId(tid.composerAccessoryRail)
- expect(rail).toHaveAttribute("data-layout", "centered")
expect(rail).toHaveClass("absolute", "bottom-2", "sm:bottom-4")
expect(rail).not.toHaveAttribute("style")
const scroll = renderer.getByTestId(tid.scrollToPresent)
expect(scroll).toHaveAttribute("aria-label", "Jump to present, 4 unread below")
- expect(scroll.closest('div[class*="col-start-"]')).toHaveClass("col-start-2")
fireEvent.click(scroll)
- expect(railProps.onScroll).toHaveBeenCalledOnce()
- })
-
- it("stays absent at the tail regardless of WebSocket state", () => {
- const renderEmpty = () => render(React.createElement(ComposerAccessoryRail, {
- ...railProps,
- scrollCount: 0,
- }))
- useCommunityWsStore.getState().setConnectionStatus("reconnecting")
- expect(renderEmpty().queryAllByTestId(tid.composerAccessoryRail)).toHaveLength(0)
- useCommunityWsStore.getState().setConnectionStatus("failed")
- const failed = renderEmpty()
- expect(failed.queryAllByTestId(tid.composerAccessoryRail)).toHaveLength(0)
- expect(failed.queryAllByTestId(tid.wsRetry)).toHaveLength(0)
+ expect(baseProps.onScroll).toHaveBeenCalledOnce()
})
- it("keeps typing and selection ownership out of the viewport rail", () => {
+ it("does not reintroduce WS or viewport-derived width ownership", () => {
const source = readFileSync(resolve(
process.cwd(),
process.cwd().endsWith("/src/web") ? "" : "src/web",
"src/components/community/messages/composer-accessory-rail.tsx",
), "utf8")
expect(source).not.toContain("@/stores/community/ws")
- expect(source).not.toContain("TypingIndicator")
- expect(source).not.toContain("selectionTypingFits")
expect(source).not.toMatch(/max-w-\[calc\([^\]]*vw/)
})
})
@@ -96,7 +109,6 @@ describe("MessageSelectionFooter", () => {
name: "Share 12 selected messages as image",
})
expect(cancel).toHaveClass("w-11", "text-foreground")
- expect(cancel.querySelector("svg")).toHaveClass("text-foreground")
expect(share).toHaveClass("after:-inset-y-1.5")
fireEvent.click(cancel)
fireEvent.click(share)
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.tsx b/src/web/src/components/community/messages/composer-accessory-rail.tsx
index 39cfb5a96..dd4142b60 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail.tsx
+++ b/src/web/src/components/community/messages/composer-accessory-rail.tsx
@@ -5,28 +5,54 @@ import { Button } from "@/components/ui/button"
import { NumberTicker } from "@/components/ui/number-ticker"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
+import { allocateComposerAccessoryRail } from "./composer-accessory-rail-layout"
+import { TypingIndicator } from "./typing-indicator"
export function ComposerAccessoryRail({
+ typingNames,
scrollCount,
scrollMode,
onScroll,
}: {
+ typingNames: string[]
scrollCount: number
scrollMode: "scroll" | "jump"
onScroll: () => void
}) {
- if (scrollCount <= 0) return null
+ const hasTyping = typingNames.length > 0
+ const hasScroll = scrollCount > 0
+ const layout = allocateComposerAccessoryRail({
+ mode: "normal",
+ left: hasTyping,
+ center: hasScroll,
+ })
+
+ if (layout === "empty") return null
return (
<div
data-testid={tid.composerAccessoryRail}
- data-layout="centered"
+ data-layout={layout}
className="pointer-events-none absolute inset-x-0 bottom-2 z-20 px-2 sm:bottom-4 sm:px-4"
>
- <div className="grid w-full grid-cols-[minmax(0,1fr)_minmax(0,max-content)_minmax(0,1fr)] items-end">
- <div className="col-start-2 min-w-0 max-w-full justify-self-center">
- <ScrollControl count={scrollCount} mode={scrollMode} onClick={onScroll} />
- </div>
+ <div
+ className={cn(
+ "grid w-full items-end gap-1 sm:gap-2",
+ layout === "centered" && "grid-cols-[minmax(0,1fr)_minmax(0,max-content)_minmax(0,1fr)]",
+ layout === "left-only" && "grid-cols-[minmax(0,1fr)]",
+ )}
+ >
+ {hasTyping && (
+ <div className="col-start-1 min-w-0 max-w-full">
+ <TypingIndicator names={typingNames} className="w-fit max-w-full" />
+ </div>
+ )}
+ {hasScroll && (
+ <div className="col-start-2 min-w-0 max-w-full justify-self-center">
+ <ScrollControl count={scrollCount} mode={scrollMode} onClick={onScroll} />
+ </div>
+ )}
</div>
</div>
)
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index 4624db101..e274b77da 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -8,6 +8,7 @@ export type MessageListProps = {
loading?: boolean
pinnedIds?: Set<string>
newDividerBefore?: string
+ typingUsers?: string[]
onOpenThread: (id: string) => void
onOpenProfile?: OpenProfile
onToggleReaction?: (id: string, emoji: string) => void
diff --git a/src/web/src/components/community/messages/message-list-view.dom.test.ts b/src/web/src/components/community/messages/message-list-view.dom.test.ts
index 151b27e6f..ddb41ff5e 100644
--- a/src/web/src/components/community/messages/message-list-view.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-view.dom.test.ts
@@ -57,6 +57,7 @@ function props(overrides: Partial<ResolvedMessageListProps> = {}): ResolvedMessa
createdAt: new Date(0).toISOString(),
}],
loading: true,
+ typingUsers: ["Alice"],
onOpenThread: vi.fn(),
variant: "channel",
initialScrollReady: true,
@@ -96,12 +97,13 @@ function controller(overrides: Partial<MessageListController> = {}): MessageList
describe("renderMessageListView", () => {
beforeEach(() => vi.clearAllMocks())
- it("keeps warm non-empty loading data on the loaded DOM with the away pill", () => {
+ it("keeps warm non-empty loading data on the loaded DOM with typing and the away pill", () => {
const listProps = props()
const state = controller()
const renderRows = vi.fn(() => React.createElement("virtual-rows"))
const renderer = render(renderMessageListView(listProps, state, renderRows))
expect(mockedRail).toHaveBeenCalledWith(expect.objectContaining({
+ typingNames: ["Alice"],
scrollCount: 3,
}), undefined)
expect(mockedRail.mock.calls.at(-1)?.[0]).not.toHaveProperty("composerOverlap")
@@ -218,15 +220,25 @@ describe("renderMessageListView", () => {
expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toHaveClass("opacity-0")
})
- it("keeps typing ownership out of the message list", () => {
+ it("routes typing through the rail without adding a dynamic flex sibling", () => {
const renderer = render(renderMessageListView(
- props({ loading: false }),
+ props({ loading: false, typingUsers: [] }),
controller({ isLoading: false, pillCount: 0 }),
() => React.createElement("virtual-rows"),
))
- expect(mockedRail).toHaveBeenLastCalledWith(expect.objectContaining({ scrollCount: 0 }), undefined)
+ expect(mockedRail).toHaveBeenLastCalledWith(expect.objectContaining({
+ typingNames: [],
+ scrollCount: 0,
+ }), undefined)
expect(renderer.container.querySelectorAll("[data-message-typing-space]")).toHaveLength(0)
- expect(JSON.stringify(mockedRail.mock.calls.at(-1)?.[0])).not.toContain("typing")
+ renderer.rerender(renderMessageListView(
+ props({ loading: false, typingUsers: ["Alice"] }),
+ controller({ isLoading: false, pillCount: 0 }),
+ () => React.createElement("virtual-rows"),
+ ))
+ expect(mockedRail).toHaveBeenLastCalledWith(expect.objectContaining({
+ typingNames: ["Alice"],
+ }), undefined)
})
it("keeps only the normal tail inset across scroll and selection state", () => {
@@ -252,7 +264,7 @@ describe("renderMessageListView", () => {
expect(content()).toHaveClass("pb-4", "sm:pb-6")
})
- it("wires selection actions and dialog close without changing overlay order", () => {
+ it("wires selection actions through the footer slot and closes the share dialog", () => {
const exitSelect = vi.fn()
const setShareOpen = vi.fn()
const closeShare = vi.fn()
diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsx
index d775f02d8..4d3f53694 100644
--- a/src/web/src/components/community/messages/message-list-view.tsx
+++ b/src/web/src/components/community/messages/message-list-view.tsx
@@ -34,6 +34,7 @@ export function renderMessageListView(
<div data-message-scroller-boundary className="relative isolate min-h-0 flex-1">
{controller.initialPosition.contentInteractive && !controller.selectMode && (
<ComposerAccessoryRail
+ typingNames={props.typingUsers ?? []}
scrollCount={controller.pillCount}
scrollMode={controller.pillMode}
onScroll={controller.pillOnClick}
diff --git a/src/web/src/components/community/messages/message.render.dom.test.ts b/src/web/src/components/community/messages/message.render.dom.test.ts
index d68728207..f430729ca 100644
--- a/src/web/src/components/community/messages/message.render.dom.test.ts
+++ b/src/web/src/components/community/messages/message.render.dom.test.ts
@@ -371,13 +371,17 @@ describe("Message memo comparator", () => {
&& node.props.className.includes("group relative -mx-2")
))
const checkbox = renderer!.root.find((node) => (
- typeof node.props.className === "string"
- && node.props.className.includes("absolute left-5 top-1/2")
+ node.props["data-message-selection-checkbox"] === true
))
+ const nameRow = checkbox.parent!
expect(row.props.className).toContain("cursor-pointer")
expect(row.props.className).not.toContain("pl-9")
- expect(checkbox.parent?.element).toBe(row.element)
+ expect(checkbox.props.className).toContain("absolute right-0 top-1/2")
+ expect(nameRow.props.className).toContain("relative")
+ expect(nameRow.props.className).toContain("pr-6")
+ expect(nameRow.parent?.props.className).toContain("min-w-0 flex-1")
+ expect(nameRow.parent?.props.className).not.toContain("pr-6")
act(() => renderer!.unmount())
})
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index 051fdd5d4..43e8da1f4 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -364,7 +364,7 @@ function MessageImpl({
}
: undefined
// In select mode (multi-share), the whole row is a big toggle target and gets
- // a leading checkbox overlay + a tint when picked. `canShare` rows only —
+ // a name-row checkbox overlay + a tint when picked. `canShare` rows only —
// approval/attachment-only rows aren't selectable (nothing to put on the card).
const selectable = selectMode && canShare
const reactionAddButton = (
@@ -585,23 +585,6 @@ function MessageImpl({
}
: undefined}
>
- {selectMode && (
- // Checkbox overlay (absolute → no layout shift / no virtualizer
- // remeasure storm on enter/exit, per the list's dynamic measurement).
- // Selectable rows show an interactive box; non-selectable (approval/
- // system) rows show nothing so they read as "can't pick this".
- selectable && (
- <span
- aria-hidden
- className={[
- "absolute left-5 top-1/2 z-20 grid size-4 -translate-y-1/2 place-items-center rounded-[5px] border transition-colors",
- selected ? "border-primary bg-primary text-primary-foreground" : "border-muted-foreground/50 bg-card",
- ].join(" ")}
- >
- {selected && <Check className="size-3" strokeWidth={3} />}
- </span>
- )
- )}
<div className="min-w-0 flex-1">
{interactive && activated && !selectMode && (
<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"}`}>
@@ -668,9 +651,21 @@ function MessageImpl({
<Avatar label={authorAvatar} seed={m.authorId} size={40} />
</button>
)}
- <div className="min-w-0 flex-1">
+ <div className="relative min-w-0 flex-1">
+ {m.grouped && selectable && (
+ <span
+ aria-hidden
+ data-message-selection-checkbox
+ className={[
+ "absolute right-0 top-0 z-20 grid size-4 place-items-center rounded-[5px] border transition-colors",
+ selected ? "border-primary bg-primary text-primary-foreground" : "border-muted-foreground/50 bg-card",
+ ].join(" ")}
+ >
+ {selected && <Check className="size-3" strokeWidth={3} />}
+ </span>
+ )}
{!m.grouped && (
- <div className="flex items-baseline gap-2">
+ <div className={`relative flex items-baseline gap-2${selectable ? " pr-6" : ""}`}>
<button
onClick={(e) => onOpenProfile?.(authorName, e, undefined, m.authorId)}
className="min-w-0 max-w-full truncate text-[15px] font-semibold hover:underline"
@@ -679,6 +674,18 @@ function MessageImpl({
{authorName}
</button>
<span className="shrink-0 text-xs text-muted-foreground" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span>
+ {selectable && (
+ <span
+ aria-hidden
+ data-message-selection-checkbox
+ className={[
+ "absolute right-0 top-1/2 z-20 grid size-4 -translate-y-1/2 place-items-center rounded-[5px] border transition-colors",
+ selected ? "border-primary bg-primary text-primary-foreground" : "border-muted-foreground/50 bg-card",
+ ].join(" ")}
+ >
+ {selected && <Check className="size-3" strokeWidth={3} />}
+ </span>
+ )}
</div>
)}
{m.approval ? (
diff --git a/src/web/src/components/community/messages/typing-indicator.dom.test.ts b/src/web/src/components/community/messages/typing-indicator.dom.test.ts
index 8d81a56db..dfcd183d6 100644
--- a/src/web/src/components/community/messages/typing-indicator.dom.test.ts
+++ b/src/web/src/components/community/messages/typing-indicator.dom.test.ts
@@ -29,15 +29,11 @@ describe("TypingIndicator", () => {
expect(status).not.toHaveTextContent("Dorothy")
})
- it("uses a compact header status without a floating pill footprint", () => {
- render(createElement(TypingIndicator, {
- names: ["Alice"],
- variant: "header",
- }))
+ it("uses the floating bottom-rail pill footprint", () => {
+ render(createElement(TypingIndicator, { names: ["Alice"] }))
const status = screen.getByTestId(tid.typingIndicator)
- expect(status).toHaveClass("h-7", "max-w-[min(16rem,40vw)]")
- expect(status).not.toHaveClass("h-8", "rounded-full", "shadow-(--e1)")
- expect(status.querySelector(".min-w-0.truncate")).toHaveClass("hidden", "sm:inline")
+ expect(status).toHaveClass("h-8", "rounded-full", "shadow-(--e1)")
+ expect(status.querySelector(".min-w-0.truncate")).not.toHaveClass("hidden")
})
})
diff --git a/src/web/src/components/community/messages/typing-indicator.tsx b/src/web/src/components/community/messages/typing-indicator.tsx
index 43005e318..69e3049c3 100644
--- a/src/web/src/components/community/messages/typing-indicator.tsx
+++ b/src/web/src/components/community/messages/typing-indicator.tsx
@@ -4,11 +4,9 @@ import { cn } from "@/lib/utils"
export function TypingIndicator({
names,
className,
- variant = "pill",
}: {
names: string[]
className?: string
- variant?: "pill" | "header"
}) {
if (names.length === 0) return null
const label = names.length === 0
@@ -25,10 +23,7 @@ export function TypingIndicator({
aria-live="polite"
aria-atomic="true"
className={cn(
- "pointer-events-none flex min-w-0 max-w-full items-center gap-2 text-xs text-muted-foreground",
- variant === "pill"
- ? "h-8 rounded-full border border-border bg-background/90 px-3 shadow-(--e1) backdrop-blur-sm"
- : "h-7 max-w-[min(16rem,40vw)] shrink px-1.5",
+ "pointer-events-none flex h-8 min-w-0 max-w-full items-center gap-2 rounded-full border border-border bg-background/90 px-3 text-xs text-muted-foreground shadow-(--e1) backdrop-blur-sm",
className,
)}
>
@@ -37,9 +32,7 @@ export function TypingIndicator({
<span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-[typing-dot_1.4s_ease-in-out_160ms_infinite]" />
<span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-[typing-dot_1.4s_ease-in-out_320ms_infinite]" />
</span>
- <span className={cn("min-w-0 truncate", variant === "header" && "hidden sm:inline")}>
- {label}
- </span>
+ <span className="min-w-0 truncate">{label}</span>
</div>
)
}
diff --git a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
index 28b77e00e..49dca8a94 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
+++ b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
@@ -199,9 +199,12 @@ describe("InboxPopover thread opener rows", () => {
isProjected: (target) => target?.kind === "channel-direct",
}))
const parentRows = renderer.queryAllByTestId(tid.inboxUnreadChannel("f1"))
+ const openerRows = renderer.queryAllByTestId(tid.inboxUnreadChild("p1"))
expect(parentRows).toHaveLength(1)
- expect(renderer.queryAllByTestId(tid.inboxUnreadChild("p1"))).toHaveLength(1)
+ expect(openerRows).toHaveLength(1)
expect(renderer.queryAllByTestId(tid.inboxUnreadChild("t1"))).toHaveLength(1)
+ expect(textOf(parentRows[0]!)).toContain("Forum")
+ expect(textOf(openerRows[0]!)).toContain("Full authoritative opener content")
expect(textOf(parentRows[0]!)).not.toContain("2")
fireEvent.click(parentRows[0]!)
expect(onOpenChannel).toHaveBeenCalledWith(
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
index b3f6ccaa8..a5b93b0cf 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
@@ -84,8 +84,14 @@ vi.mock("@/hooks/community/use-inbox", () => ({
hasProjectedUnread: false,
hasOutstandingFriendRequest: true,
exactAttentionCount: 7,
+ pendingChannelIds: [],
+ }),
+ useInboxMentions: () => ({
+ mentions: [mention],
+ isLoading: false,
+ hasProjectedMention: false,
+ pendingChannelIds: [],
}),
- useInboxMentions: () => ({ mentions: [mention], isLoading: false, hasProjectedMention: false }),
useInboxMarked: (enabled: boolean) => {
mocks.markedEnabled.push(enabled)
return { marked: [], isLoading: false }
@@ -242,7 +248,7 @@ describe("useShellInboxController", () => {
it("includes friend requests in the global dot while keeping navigation and actions read-neutral", async () => {
const hook = await renderController()
expect(hook.current.hasUnread).toBe(true)
- expect(hook.current.unreadCount).toBe(8)
+ expect(hook.current.unreadCount).toBe(4)
expect(hook.current.popoverProps.hasProjectedUnreads).toBe(false)
expect(hook.current.popoverProps.friendRequests).toHaveLength(1)
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index f6345f391..ec4f8d1b0 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
@@ -36,6 +36,7 @@ import { startConversationNavigationWarmup } from "@/lib/community/conversation-
import type { ConversationNavigationTarget } from "@/lib/community/conversation-navigation-proof"
import { cancelConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"
import { publishCommunityDmSummary } from "@/lib/community-db/sync"
+import { inboxUnreadCount } from "@/lib/community/inbox-unread-count"
type UnreadChannel = UnreadServer["channels"][number]
type UnreadChild = UnreadChannel["children"][number]
@@ -323,15 +324,22 @@ export function useShellInboxController({
onUnmark: (messageId) => unmarkMessageMutate({ messageId }),
isProjected: inbox.isProjected,
}
+ const unreadCount = inboxUnreadCount({
+ servers: unreadFeed,
+ dms: unreadDms,
+ mentions,
+ pendingChannelIds: [
+ ...inboxUnreads.pendingChannelIds,
+ ...inboxMentions.pendingChannelIds,
+ ],
+ friendRequestCount: inboxUnreads.friendRequests.length,
+ })
return {
popoverProps,
- unreadCount: (inboxUnreads.exactAttentionCount ?? 0) + inboxUnreads.friendRequests.length,
+ unreadCount,
unreadCountPartial: false,
- hasUnread:
- inboxUnreads.hasProjectedUnread
- || inboxMentions.hasProjectedMention
- || inboxUnreads.friendRequests.length > 0,
+ hasUnread: unreadCount > 0,
open: inbox.open,
onOpenChange: inbox.onOpenChange,
}
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index f0c678baa..4adcb33e9 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -31,6 +31,7 @@ import {
captureCommunityLiveSnapshotToken,
publishCommunityLiveSnapshot,
} from "@/lib/community-db/sync"
+import { sortDmsByActivity } from "@/lib/community/dm-order"
/**
* Fetches the DM conversation sidebar list.
@@ -139,7 +140,7 @@ export function useDms(enabled = true): UseQueryResult<DmsResponse> & { dms: DM[
? dbDms ?? EMPTY_DMS
: query.data?.conversations ?? EMPTY_DMS
if (source.length === 0) return EMPTY_DMS as DM[]
- return source.map((dm) => {
+ return sortDmsByActivity(source.map((dm) => {
const liveProfile = profilesByUserId.get(dm.userId)
const profile = readCommunityProfile(liveProfile, dm.userId)
const unread = attentionScopes.some((scope) => (
@@ -154,7 +155,7 @@ export function useDms(enabled = true): UseQueryResult<DmsResponse> & { dms: DM[
status: liveProfile ? profile.presence : "offline",
unread,
}
- })
+ }))
}, [attentionScopes, dbDms, profilesByUserId, query.data?.conversations, registry, unreadVersion])
return {
...query,
diff --git a/src/web/src/hooks/community/use-forum-feed.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
index 9de066fc5..a79f585e0 100644
--- a/src/web/src/hooks/community/use-forum-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
@@ -290,8 +290,8 @@ describe("mapForumFeedPages", () => {
name: "canonical content",
authorId: "transport-author",
authorAvatarVersion: 0,
- preview: "",
- parent: { authorName: "Canonical", text: "" },
+ preview: "transport preview",
+ parent: { authorName: "Canonical", text: "transport preview" },
}),
])
expect(mapForumFeedPages(pages, canonical)[0]).not.toHaveProperty("openerCreatedAt")
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 4ff0205a5..55fe714da 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -153,13 +153,10 @@ export function mapForumFeedPages(
}
: undefined
: canonicalOpener
- // The forum transport exposes firstMessages only as a channel/content
- // preview with no stable message identity. It is a providerless read
- // projection only; a canonical-backed surface must never treat it as a
- // second message entity source because edits/deletes cannot reconcile it.
- const first = canonicalMessages === undefined
- ? firstByChannel.get(thread.id)
- : undefined
+ // firstMessages is transport-owned view metadata, not a canonical
+ // message entity. Keep rendering the preview on canonical-backed
+ // surfaces without publishing it into the canonical message collection.
+ const first = firstByChannel.get(thread.id)
byId.set(thread.id, {
id: thread.id,
name: opener?.content?.trim() ? opener.content : thread.name?.trim() || "Post",
diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
index c022afd23..1353c91b3 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
@@ -12,6 +12,7 @@ let refs: Array<{ current: unknown }> = []
let refIndex = 0
let layoutEffects: Array<() => void | (() => void)> = []
let resizeCallbacks: ResizeObserverCallback[] = []
+let mutationCallbacks: MutationCallback[] = []
const PAGINATION_ANCHOR_FRAME_REF_INDEX = 14
const PAGINATION_UNMOUNT_EFFECT_INDEX = 2
@@ -50,6 +51,7 @@ function resetHarness() {
refIndex = 0
layoutEffects = []
resizeCallbacks = []
+ mutationCallbacks = []
virtualizerOptions = undefined
virtualizer.options.anchorTo = "end"
virtualizer.isAtEnd.mockReturnValue(true)
@@ -68,6 +70,15 @@ function resetHarness() {
unobserve() {}
disconnect() {}
})
+ vi.stubGlobal("MutationObserver", class {
+ constructor(callback: MutationCallback) {
+ mutationCallbacks.push(callback)
+ }
+
+ observe() {}
+ disconnect() {}
+ takeRecords() { return [] }
+ })
}
async function mountHook({
@@ -120,6 +131,7 @@ async function mountHook({
const scroller = {
addEventListener: (type: string, listener: EventListener) => listeners.set(type, listener),
removeEventListener: vi.fn(),
+ closest: () => ({ querySelector: () => ({}) }),
get clientHeight() {
return clientHeight
},
@@ -169,6 +181,7 @@ async function mountHook({
}
const dispatchScroll = () => listeners.get("scroll")?.(new Event("scroll"))
const dispatchResize = () => resizeCallbacks.at(-1)?.([], {} as ResizeObserver)
+ const dispatchMutation = () => mutationCallbacks.at(-1)?.([], {} as MutationObserver)
const resizeViewport = (
nextClientHeight: number,
order: "scroll-ro" | "ro-scroll" = "ro-scroll",
@@ -190,8 +203,10 @@ async function mountHook({
scroller,
result,
dispatchScroll,
+ dispatchMutation,
resizeViewport,
setBrowserScrollTop,
+ setClientHeight,
setScrollHeight,
geometry,
rerender,
@@ -475,6 +490,21 @@ describe("useScrollAnchor semantic viewport resize anchoring", () => {
}
})
+ it("repairs browser shrink clamping in the footer-mutation microtask before ResizeObserver", async () => {
+ const mounted = await mountHook({ distanceToEnd: 100 })
+
+ mounted.setClientHeight(920)
+ expect(mounted.geometry().scrollHeight - mounted.geometry().clientHeight - mounted.geometry().scrollTop)
+ .toBe(0)
+ mounted.dispatchMutation()
+
+ expect(mounted.geometry().scrollHeight - mounted.geometry().clientHeight - mounted.geometry().scrollTop)
+ .toBe(100)
+ mounted.resizeViewport(920)
+ expect(mounted.geometry().scrollHeight - mounted.geometry().clientHeight - mounted.geometry().scrollTop)
+ .toBe(100)
+ })
+
it.each([
{ name: "grow→grow", heights: [780, 760] },
{ name: "shrink→shrink", heights: [801, 802] },
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 2957f96ef..ad43e2e1d 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -973,10 +973,16 @@ export function useScrollAnchor({
// changes both alter this viewport's real `clientHeight`. Preserve the
// conversation's semantic anchor from the last accepted geometry: exact
// distance-to-tail through the shared 100px tail context, otherwise the
- // reading scrollTop. This is the sole writer for footer-driven viewport
- // changes; the footer itself does not measure or mutate the message list.
- // Keyed on `clientHeight`, orthogonal to hero compensation above (keyed on
- // `heroHeight`) — separate effects, no double-apply.
+ // reading scrollTop. This hook remains the sole writer for footer-driven
+ // viewport changes; the footer itself does not measure or mutate the list.
+ //
+ // A footer DOM mutation is observed in the microtask that created it so the
+ // correction lands before the next animation frame. Waiting only for the
+ // scroller ResizeObserver leaves one frame where the browser has already
+ // clamped scrollTop to its new maximum (a visible 100px flash at the tail
+ // boundary). ResizeObserver remains the fallback for pure layout changes
+ // such as the mobile keyboard. Both paths share and immediately accept the
+ // same geometry, so a later delivery is a no-op rather than a double-write.
useLayoutEffect(() => {
const el = scrollRef.current
if (!el) return
@@ -986,7 +992,7 @@ export function useScrollAnchor({
acceptedClientHeightRef.current = el.clientHeight
acceptedScrollTopRef.current = el.scrollTop
acceptedScrollHeightRef.current = el.scrollHeight
- const ro = new ResizeObserver(() => {
+ const reconcileViewportResize = () => {
const previousClientHeight = acceptedClientHeightRef.current
const nextClientHeight = el.clientHeight
if (nextClientHeight === previousClientHeight) return
@@ -1008,9 +1014,25 @@ export function useScrollAnchor({
virtualizer.options.anchorTo = wasExactlyPinnedRef.current && !userScrolledAwayRef.current
? "end"
: "start"
- })
+ }
+ const ro = new ResizeObserver(reconcileViewportResize)
ro.observe(el)
- return () => ro.disconnect()
+ const footer = el
+ .closest<HTMLElement>('[data-slot="community-conversation-surface"]')
+ ?.querySelector<HTMLElement>('[data-slot="community-conversation-footer"]')
+ const mo = footer && typeof MutationObserver !== "undefined"
+ ? new MutationObserver(reconcileViewportResize)
+ : null
+ mo?.observe(footer!, {
+ attributes: true,
+ characterData: true,
+ childList: true,
+ subtree: true,
+ })
+ return () => {
+ ro.disconnect()
+ mo?.disconnect()
+ }
}, [virtualizer])
// "↓ N below" pill count — a plain arithmetic derivation from data
diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.ts
index 7622f0d4a..41004e756 100644
--- a/src/web/src/lib/community-db/projections.dom.test.ts
+++ b/src/web/src/lib/community-db/projections.dom.test.ts
@@ -236,8 +236,8 @@ describe("community DB projections", () => {
{ ...channelBase, id: "forum2", serverId: "s1", categoryId: null, name: "later forum", type: "forum", position: 2 },
{ ...channelBase, id: "forum1", serverId: "s1", categoryId: null, name: "forum", type: "forum", position: 1 },
{ ...channelBase, id: "thread1", serverId: "s1", categoryId: null, name: "thread", type: "thread", parentChannelId: "forum1" },
- { ...channelBase, id: "dm1", serverId: null, categoryId: null, name: "Peer", type: "dm", preview: "hello", lastUnreadSeq: 8 },
- { ...channelBase, id: "dm-no-read-state", serverId: null, categoryId: null, name: "Quiet", type: "dm" },
+ { ...channelBase, id: "dm1", serverId: null, categoryId: null, name: "Peer", type: "dm", preview: "hello", lastUnreadSeq: 8, lastMessageAt: "2026-09-25T00:00:00.000Z" },
+ { ...channelBase, id: "dm-no-read-state", serverId: null, categoryId: null, name: "Quiet", type: "dm", lastMessageAt: "2026-09-25T00:00:01.000Z" },
{ ...channelBase, id: "dm-no-member", serverId: null, categoryId: null, name: "Missing", type: "dm" },
{ ...channelBase, id: "dm-no-profile", serverId: null, categoryId: null, name: "Missing profile", type: "dm" },
])
@@ -316,10 +316,19 @@ describe("community DB projections", () => {
expect.objectContaining({ id: "cat1", channels: expect.arrayContaining([expect.objectContaining({ id: "c1" })]) }),
expect.objectContaining({ id: "__uncategorized__", channels: expect.arrayContaining([expect.objectContaining({ id: "forum1" })]) }),
]))
- expect(rendered.result.current.dms).toEqual(expect.arrayContaining([
- expect.objectContaining({ id: "dm1", userId: "peer", lastUnreadSeq: 8 }),
- expect.objectContaining({ id: "dm-no-read-state", userId: "quiet" }),
- ]))
+ expect(rendered.result.current.dms).toEqual([
+ expect.objectContaining({
+ id: "dm-no-read-state",
+ userId: "quiet",
+ activityAt: "2026-09-25T00:00:01.000Z",
+ }),
+ expect.objectContaining({
+ id: "dm1",
+ userId: "peer",
+ activityAt: "2026-09-25T00:00:00.000Z",
+ lastUnreadSeq: 8,
+ }),
+ ])
expect(rendered.result.current.dms?.find((dm) => dm.id === "dm-no-read-state"))
.not.toHaveProperty("lastUnreadSeq")
expect(rendered.result.current.route?.id).toBe("c1")
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 0f58547f2..97f47f945 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -13,6 +13,7 @@ import { DbProvider, useLiveQuery } from "@tanstack/react-db"
import { notifLevelDisplay } from "@alook/shared"
import { avatarInitial } from "@/lib/community/avatar"
import type { DM } from "@/lib/community/models/people"
+import { sortDmsByActivity } from "@/lib/community/dm-order"
import type { CommunityProfile } from "@/lib/community/models/people"
import type { Category, CommunityFolder, Server } from "@/lib/community/models/navigation"
import type { Msg } from "@/lib/community/models/message"
@@ -282,7 +283,7 @@ export function useDmProjection() {
const channelMemberships = rows.channelMemberships
const profileById = new Map(rows.profiles.map((profile) => [profile.userId, profile]))
const readStateByChannel = new Map((rows.readStates ?? []).map((state) => [state.channelId, state]))
- return rows.channels
+ return sortDmsByActivity(rows.channels
.filter((channel) => channel.type === "dm")
.flatMap((channel): DM[] => {
const peerMembership = channelMemberships.find((membership) => (
@@ -303,12 +304,13 @@ export function useDmProjection() {
avatarVersion: profile.avatarVersion,
status: "offline",
preview: channel.preview ?? "",
+ ...(channel.lastMessageAt ? { activityAt: channel.lastMessageAt } : {}),
unread: channel.unread,
...(channel.lastUnreadSeq === undefined && !readState
? {}
: { lastUnreadSeq: channel.lastUnreadSeq ?? readState?.lastReadSeq }),
}]
- })
+ }))
}, [rows])
}
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 7014d3aa5..642c9ec61 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -901,7 +901,7 @@ export function ingestDms(
const channels: ChannelRow[] = []
const memberships: ChannelMembershipRow[] = []
const profilePatches: CommunityProfilePatch[] = []
- for (const dm of response.conversations) {
+ for (const [position, dm] of response.conversations.entries()) {
channels.push({
id: dm.id,
serverId: null,
@@ -911,13 +911,13 @@ export function ingestDms(
parentChannelId: null,
parentMessageId: null,
creatorId: null,
- position: 0,
+ position,
archived: false,
muted: false,
unread: dm.unread === true,
tags: [],
pending: false,
- lastMessageAt: null,
+ lastMessageAt: dm.activityAt ?? null,
preview: dm.preview,
...(dm.lastUnreadSeq === undefined ? {} : { lastUnreadSeq: dm.lastUnreadSeq }),
})
diff --git a/src/web/src/lib/community/dm-cache.test.ts b/src/web/src/lib/community/dm-cache.test.ts
index 501ead04e..c0eccf49f 100644
--- a/src/web/src/lib/community/dm-cache.test.ts
+++ b/src/web/src/lib/community/dm-cache.test.ts
@@ -30,6 +30,7 @@ describe("DM cache projector", () => {
avatar: "N",
status: "offline",
preview: "",
+ activityAt: "2026-08-24T05:00:00.000Z",
unread: false,
})
})
@@ -64,4 +65,15 @@ describe("DM cache projector", () => {
})
expect(result.conversations[1]).toBe(unrelated)
})
+
+ it("promotes newer activity while a read-state-only update leaves order stable", () => {
+ const first = { ...cached, id: "dm-a", activityAt: "2026-09-27T02:00:00.000Z" }
+ const second = { ...cached, id: "dm-b", activityAt: "2026-09-27T01:00:00.000Z" }
+ const promoted = { ...second, activityAt: "2026-09-27T03:00:00.000Z" }
+ const afterActivity = upsertDmSummary({ conversations: [first, second] }, promoted)
+ expect(afterActivity.conversations.map((dm) => dm.id)).toEqual(["dm-b", "dm-a"])
+
+ const afterRead = upsertDmSummary(afterActivity, { ...promoted, unread: false })
+ expect(afterRead.conversations.map((dm) => dm.id)).toEqual(["dm-b", "dm-a"])
+ })
})
diff --git a/src/web/src/lib/community/dm-cache.ts b/src/web/src/lib/community/dm-cache.ts
index 3e8eb3757..05fda3e43 100644
--- a/src/web/src/lib/community/dm-cache.ts
+++ b/src/web/src/lib/community/dm-cache.ts
@@ -1,5 +1,6 @@
import type { UnreadDm } from "./models/inbox"
import type { DM } from "./models/people"
+import { sortDmsByActivity } from "./dm-order"
export type DmCache = { conversations: DM[] }
@@ -13,6 +14,7 @@ export function dmSummaryFromInbox(unread: UnreadDm): DM {
avatarVersion: unread.otherUserAvatarVersion,
status: "offline",
preview: "",
+ activityAt: unread.lastMessageAt,
unread: false,
}
}
@@ -24,11 +26,11 @@ export function upsertDmSummary(
if (!previous) return { conversations: [incoming] }
const existingIndex = previous.conversations.findIndex((dm) => dm.id === incoming.id)
if (existingIndex < 0) {
- return { ...previous, conversations: [incoming, ...previous.conversations] }
+ return { ...previous, conversations: sortDmsByActivity([incoming, ...previous.conversations]) }
}
return {
...previous,
- conversations: previous.conversations.map((dm, index) =>
+ conversations: sortDmsByActivity(previous.conversations.map((dm, index) =>
index === existingIndex
? {
...dm,
@@ -37,6 +39,6 @@ export function upsertDmSummary(
preview: dm.preview,
}
: dm
- ),
+ )),
}
}
diff --git a/src/web/src/lib/community/dm-order.test.ts b/src/web/src/lib/community/dm-order.test.ts
new file mode 100644
index 000000000..c3a4a42d6
--- /dev/null
+++ b/src/web/src/lib/community/dm-order.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest"
+import { sortDmsByActivity } from "./dm-order"
+
+describe("DM sidebar order", () => {
+ it("sorts recent activity first and uses channel id as the stable tie-break", () => {
+ expect(sortDmsByActivity([
+ { id: "dm-z", activityAt: "2026-09-27T02:00:00.000Z" },
+ { id: "dm-b", activityAt: "2026-09-27T03:00:00.000Z" },
+ { id: "dm-a", activityAt: "2026-09-27T03:00:00.000Z" },
+ ]).map((dm) => dm.id)).toEqual(["dm-a", "dm-b", "dm-z"])
+ })
+
+ it("does not let unread presentation reorder equal-activity conversations", () => {
+ expect(sortDmsByActivity([
+ { id: "dm-b", activityAt: "2026-09-27T03:00:00.000Z", unread: true },
+ { id: "dm-a", activityAt: "2026-09-27T03:00:00.000Z", unread: false },
+ ]).map((dm) => dm.id)).toEqual(["dm-a", "dm-b"])
+ })
+
+ it("matches SQLite BINARY ordering for equal-activity mixed-case nanoids", () => {
+ const activityAt = "2026-09-27T03:00:00.000Z"
+
+ expect(sortDmsByActivity([
+ { id: "kMRip4KDm4Ki2HU8vQ2qd", activityAt },
+ { id: "bc02tEwQaazjdPwrMuNih", activityAt },
+ { id: "XzKeKetmiRMJ16hwOrhSl", activityAt },
+ { id: "3kY1MAppCm6RYM4IvnXPN", activityAt },
+ ]).map((dm) => dm.id)).toEqual([
+ "3kY1MAppCm6RYM4IvnXPN",
+ "XzKeKetmiRMJ16hwOrhSl",
+ "bc02tEwQaazjdPwrMuNih",
+ "kMRip4KDm4Ki2HU8vQ2qd",
+ ])
+ })
+})
diff --git a/src/web/src/lib/community/dm-order.ts b/src/web/src/lib/community/dm-order.ts
new file mode 100644
index 000000000..a3da97b99
--- /dev/null
+++ b/src/web/src/lib/community/dm-order.ts
@@ -0,0 +1,21 @@
+import { compareAsciiSqliteBinary } from "@alook/shared"
+
+export type DmOrderKey = {
+ id: string
+ activityAt?: string
+}
+
+/**
+ * Preserve the original DM-list contract from the server query:
+ * newest conversation activity first, then channel id ascending. Read state
+ * is deliberately absent — marking a conversation read changes presentation,
+ * not its position.
+ */
+function compareDmOrder(left: DmOrderKey, right: DmOrderKey): number {
+ const activity = (right.activityAt ?? "").localeCompare(left.activityAt ?? "")
+ return activity || compareAsciiSqliteBinary(left.id, right.id)
+}
+
+export function sortDmsByActivity<T extends DmOrderKey>(dms: readonly T[]): T[] {
+ return [...dms].sort(compareDmOrder)
+}
diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.ts
index 3f0b93988..b85e7e086 100644
--- a/src/web/src/lib/community/models/people.ts
+++ b/src/web/src/lib/community/models/people.ts
@@ -102,6 +102,8 @@ export type DM = CommunityUserCore & {
userId: string
status: Presence
preview: string
+ /** Server-authoritative `lastMessageAt ?? createdAt`, used only for list order. */
+ activityAt?: string
unread?: boolean
lastUnreadSeq?: number
}
diff --git a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts
index 4b95c1652..6e3bafc85 100644
--- a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts
+++ b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts
@@ -195,8 +195,9 @@ function expectCheckpoint(
expect(metrics.contentPaddingBottom, evidence).toBe(width < 640 ? 16 : 24)
expect(metrics.scroller.bottom, evidence).toBeLessThanOrEqual(metrics.composer.top + 1)
if (metrics.typing?.width) {
- expect(metrics.typing.height, `typing ${evidence}`).toBe(28)
- expect(metrics.typing.bottom, evidence).toBeLessThanOrEqual(metrics.scroller.top + 1)
+ expect(metrics.typing.height, `typing ${evidence}`).toBe(32)
+ expect(Math.abs(metrics.scroller.bottom - metrics.typing.bottom - expectedGap), evidence)
+ .toBeLessThanOrEqual(1)
}
if (metrics.center?.width) {
if (!selection) {
@@ -259,10 +260,10 @@ async function captureState(args: {
: rect.left > 1 && Math.abs(rect.right - viewportWidth) <= 1
}, width)).toBe(true)
const rail = page.getByTestId(tid.composerAccessoryRail)
- await expect(rail).toHaveCount(center && !selection ? 1 : 0)
- if (center && !selection) await expect(rail).toHaveAttribute("data-layout", layout!)
- await expect(page.getByTestId(tid.typingIndicator)).toHaveCount(typing ? 1 : 0)
- if (typing) await expect(page.getByTestId(tid.typingIndicator)).toBeVisible()
+ await expect(rail).toHaveCount((center || typing) && !selection ? 1 : 0)
+ if ((center || typing) && !selection) await expect(rail).toHaveAttribute("data-layout", layout!)
+ await expect(page.getByTestId(tid.typingIndicator)).toHaveCount(typing && !selection ? 1 : 0)
+ if (typing && !selection) await expect(page.getByTestId(tid.typingIndicator)).toBeVisible()
await expect(page.getByTestId(tid.messageSelectionToolbar)).toHaveCount(selection ? 1 : 0)
if (selection) {
await expect.poll(() => page.getByTestId(tid.messageSelectionToolbar).evaluate(
@@ -479,13 +480,13 @@ test("composer accessory rail reallocates every occupied slot without overflow",
page: alice.page,
testInfo,
state: "l-only",
- layout: null,
+ layout: "left-only",
center: false,
typing: true,
finalMessageId,
})
for (const width of VIEWPORT_WIDTHS) {
- expect(leftOnly[width].rail).toBeNull()
+ expect(leftOnly[width].rail).not.toBeNull()
expect(leftOnly[width].typing).not.toBeNull()
}
@@ -513,30 +514,26 @@ test("composer accessory rail reallocates every occupied slot without overflow",
state: "selection-short",
layout: "centered",
center: true,
- typing: true,
+ typing: false,
selection: true,
finalMessageId,
})
for (const width of VIEWPORT_WIDTHS) {
expect(selectionShort[width].center!.center).toBe(selectionNone[width].center!.center)
- expect(selectionShort[width].typing).not.toBeNull()
+ expect(selectionShort[width].typing).toBeNull()
}
await bobEditor.click()
await bob.page.keyboard.press("ControlOrMeta+A")
await bob.page.keyboard.press("Backspace")
await bob.page.keyboard.type("multiple selection typing")
- await expect(alice.page.getByTestId(tid.typingIndicator))
- .toContainText(LONG_TYPING_NAME, { timeout: 20_000 })
- await expect(alice.page.getByTestId(tid.typingIndicator)).toContainText("Cy")
- await expect(alice.page.getByTestId(tid.typingIndicator)).toContainText(" and ")
const selectionMultiple = await captureState({
page: alice.page,
testInfo,
state: "selection-multiple",
layout: "centered",
center: true,
- typing: true,
+ typing: false,
selection: true,
widths: [390, 639, 1280],
finalMessageId,
@@ -560,22 +557,19 @@ test("composer accessory rail reallocates every occupied slot without overflow",
await bob.page.keyboard.press("ControlOrMeta+A")
await bob.page.keyboard.press("Backspace")
await bob.page.keyboard.type("long selection typing")
- await expect(alice.page.getByTestId(tid.typingIndicator))
- .toContainText(LONG_TYPING_NAME, { timeout: 20_000 })
- await expect(alice.page.getByTestId(tid.typingIndicator)).not.toContainText("Cy")
const selectionLong = await captureState({
page: alice.page,
testInfo,
state: "selection-long",
layout: "centered",
center: true,
- typing: true,
+ typing: false,
selection: true,
widths: [390, 639, 640, 1280],
finalMessageId,
})
for (const width of [390, 639, 640, 1280] as const) {
- expect(selectionLong[width].typing).not.toBeNull()
+ expect(selectionLong[width].typing).toBeNull()
}
await sendExactMessage(
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 8f58a2c96..599f7b174 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -648,8 +648,9 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
})
expect(geometry.contentPaddingBottom).toBe(16)
expect(geometry.scroller!.bottom).toBeLessThanOrEqual(geometry.composer!.top + 1)
- expect(geometry.rail).toBeNull()
- expect(geometry.indicator!.bottom).toBeLessThanOrEqual(geometry.scroller!.top + 1)
+ expect(geometry.rail!.bottom).toBeLessThanOrEqual(geometry.scroller!.bottom + 1)
+ expect(geometry.indicator!.height).toBe(32)
+ expect(Math.abs(geometry.scroller!.bottom - geometry.indicator!.bottom - 8)).toBeLessThanOrEqual(1)
expect(geometry.scroller!.bottom - geometry.finalMessage!.bottom).toBeGreaterThanOrEqual(15)
expect(geometry.finalMessage!.bottom).toBeLessThanOrEqual(geometry.scroller!.bottom + 1)
expect(geometry.horizontalOverflow).toBeLessThanOrEqual(0)
@@ -676,7 +677,8 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
})
expect(scrollTypingGeometry.rail!.bottom).toBeLessThanOrEqual(scrollTypingGeometry.scroller!.bottom + 1)
expect(scrollTypingGeometry.scroll!.bottom).toBeLessThanOrEqual(scrollTypingGeometry.scroller!.bottom + 1)
- expect(scrollTypingGeometry.indicator!.bottom).toBeLessThanOrEqual(scrollTypingGeometry.scroller!.top + 1)
+ expect(Math.abs(scrollTypingGeometry.scroller!.bottom - scrollTypingGeometry.indicator!.bottom - 8))
+ .toBeLessThanOrEqual(1)
await alice.page.getByTestId(tid.scrollToPresent).click()
await expect(alice.page.getByTestId(tid.scrollToPresent)).toHaveCount(0)
@@ -718,8 +720,7 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
expect(selectionTypingGeometry.selection!.bottom).toBeLessThanOrEqual(selectionTypingGeometry.composer!.bottom + 1)
expect(selectionTypingGeometry.scroller!.bottom).toBeLessThanOrEqual(selectionTypingGeometry.composer!.top + 1)
expect(selectionTypingGeometry.finalMessage!.bottom).toBeLessThanOrEqual(selectionTypingGeometry.scroller!.bottom + 1)
- expect(selectionTypingGeometry.indicator!.bottom)
- .toBeLessThanOrEqual(selectionTypingGeometry.scroller!.top + 1)
+ expect(selectionTypingGeometry.indicator).toBeNull()
await alice.page.getByRole("button", { name: "Cancel message selection" }).click()
const channelScrollerAfterSelection = await settledScrollerGeometry(alice.page)
expectStableScroller(channelScrollerBeforeSelection, channelScrollerAfterSelection)
@@ -820,8 +821,9 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
})
expect(dmGeometry.contentPaddingBottom).toBe(16)
expect(dmGeometry.scroller!.bottom).toBeLessThanOrEqual(dmGeometry.composer!.top + 1)
- expect(dmGeometry.rail).toBeNull()
- expect(dmGeometry.indicator!.bottom).toBeLessThanOrEqual(dmGeometry.scroller!.top + 1)
+ expect(dmGeometry.rail!.bottom).toBeLessThanOrEqual(dmGeometry.scroller!.bottom + 1)
+ expect(dmGeometry.indicator!.height).toBe(32)
+ expect(Math.abs(dmGeometry.scroller!.bottom - dmGeometry.indicator!.bottom - 8)).toBeLessThanOrEqual(1)
expect(dmGeometry.horizontalOverflow).toBeLessThanOrEqual(0)
await bobDmEditable.fill("")
await expect(alice.page.getByTestId(tid.typingIndicator)).toBeHidden({ timeout: 15_000 })
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
index 11a9dfaa3..417468676 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -396,7 +396,7 @@ test.describe.serial("account unread projection", () => {
await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
- await expect(page.getByTestId(tid.inboxTrigger).locator('[data-slot="inbox-unread-indicator"]')).toHaveAttribute("data-count", "0")
+ await expect(page.getByTestId(tid.inboxTrigger).locator('[data-slot="inbox-unread-indicator"]')).toHaveAttribute("data-count", "2")
await page.getByTestId(tid.inboxTrigger).click()
expect(targetPuts).toEqual([])
diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
index ac7128b82..ab247fbf7 100644
--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
@@ -423,6 +423,41 @@ function expectResizeAnchorPreserved(
expectViewportAnchorPreserved(before, after, label)
}
+function expectContinuousResizeAnchorPreserved(
+ trace: ScrollTraceResult,
+ segmentName: string,
+ distance: number,
+): void {
+ const start = trace.marks.find((mark) => mark.name === `analysis-start:${segmentName}`)
+ const end = trace.marks.find((mark) => mark.name === `analysis-end:${segmentName}`)
+ expect(start, `${segmentName}: start mark`).toBeDefined()
+ expect(end, `${segmentName}: end mark`).toBeDefined()
+ const frames = trace.frames.filter((frame) => (
+ frame.frame >= start!.frame && frame.frame <= end!.frame
+ ))
+ expect(frames.length, `${segmentName}: continuous frames`).toBeGreaterThan(1)
+
+ const baseline = frames[0]!
+ if (distance <= 100) {
+ for (const frame of frames) {
+ expect(
+ Math.abs(frame.distanceToEnd - baseline.distanceToEnd),
+ `${segmentName}: frame ${frame.frame} tail-distance drift`,
+ ).toBeLessThanOrEqual(1)
+ }
+ return
+ }
+
+ for (const frame of frames) {
+ expect(frame.firstVisibleId, `${segmentName}: frame ${frame.frame} visible row`)
+ .toBe(baseline.firstVisibleId)
+ expect(
+ Math.abs((frame.firstVisibleOffset ?? 0) - (baseline.firstVisibleOffset ?? 0)),
+ `${segmentName}: frame ${frame.frame} visible-anchor drift`,
+ ).toBeLessThanOrEqual(1)
+ }
+}
+
function expectInFlowMessageGeometry(geometry: MessageViewportGeometry, label: string): void {
expect(geometry.contentPaddingBottom, `${label}: desktop normal tail inset`).toBe(24)
expect(geometry.composerRect, `${label}: scoped composer`).not.toBeNull()
@@ -962,7 +997,9 @@ test.describe.serial("message scroll characterization", () => {
summarizeScrollTrace(trace).analysisSegments.map((segment) => [segment.name, segment]),
)
for (const distance of [0, 2, 100, 300]) {
- expect(segments.get(`dm-composer-shrink-${distance}`)).toBeDefined()
+ const segmentName = `dm-composer-shrink-${distance}`
+ expect(segments.get(segmentName)).toBeDefined()
+ expectContinuousResizeAnchorPreserved(trace, segmentName, distance)
}
expect(messagePosts).toBe(0)
expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>
@@ -1096,6 +1133,9 @@ test.describe.serial("message scroll characterization", () => {
await expect(selectionAction).toBeVisible()
await selectionAction.evaluate((button) => (button as HTMLButtonElement).click())
await expect(alice.page.getByTestId(tid.messageSelectionToolbar)).toBeVisible()
+ const conversationFooter = alice.page.locator('[data-slot="community-conversation-footer"]')
+ await expect(conversationFooter).toHaveAttribute("data-selection-active", "true")
+ await expect(editable).toBeHidden()
const selectionOpen = await waitForCommittedGeometry(scroller)
expect(selectionOpen.clientHeight).toBeGreaterThan(selectionBase.clientHeight)
expect(selectionOpen.scrollHeight).toBe(selectionBase.scrollHeight)
@@ -1103,6 +1143,8 @@ test.describe.serial("message scroll characterization", () => {
await expect(editable).toContainText("selection-draft line 0")
await alice.page.getByRole("button", { name: "Cancel message selection" }).click()
await expect(alice.page.getByTestId(tid.messageSelectionToolbar)).toHaveCount(0)
+ await expect(conversationFooter).toHaveAttribute("data-selection-active", "false")
+ await expect(editable).toBeVisible()
const selectionClosed = await waitForCommittedGeometry(scroller)
expect(selectionClosed.clientHeight).toBe(selectionBase.clientHeight)
expect(selectionClosed.scrollHeight).toBe(selectionBase.scrollHeight)
@@ -1189,8 +1231,11 @@ test.describe.serial("message scroll characterization", () => {
const shrink = resizeSegments.get(`composer-shrink-${distance}`)
expect(grow, `missing composer-grow-${distance}`).toBeDefined()
expect(shrink, `missing composer-shrink-${distance}`).toBeDefined()
+ expectContinuousResizeAnchorPreserved(trace, `composer-grow-${distance}`, distance)
+ expectContinuousResizeAnchorPreserved(trace, `composer-shrink-${distance}`, distance)
}
expect(resizeSegments.get("typing-rail-away")?.writerCount).toBe(0)
+ expectContinuousResizeAnchorPreserved(trace, "selection-footer-away", 300)
expect(mutationPosts).toBe(0)
expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>
event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)