Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(channel): unread notification pill (#7827)

Peter Chinman723c9fe131ef
diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsx
index 6317239284..ce8d6a16eb 100644
--- a/apps/web/src/features/channel/Channel/Channel.tsx
+++ b/apps/web/src/features/channel/Channel/Channel.tsx
@@ -45,6 +45,7 @@ import {
buildMentionMarkdownString,
markdownToPlainText,
} from '@macro-inc/lexical-core';
+import { MessageNotificationIndexContext } from '@notifications/components/MarkMessageNotifications';
import {
invalidateChannelsActivity,
useUpdateChannelsActivityMutation,
@@ -102,12 +103,12 @@ import { CHANNEL_TOUR } from '../tour';
import { isUnifiedInputMode } from '../unified-input-mode';
import { ActiveCallMessage } from './ActiveCallMessage';
import { ChannelDropZone } from './ChannelDropZone';
-import { ChannelUnreadNotifications } from './ChannelUnreadNotifications';
import { createChannelDragState } from './create-channel-drag-state';
import { createChannelFindBar } from './create-channel-find-bar';
import { createChannelHotkeys } from './create-channel-hotkeys';
import { createChannelKeyboardHandler } from './create-channel-keyboard-handler';
import { createChannelMessageActions } from './create-channel-message-actions';
+import { createChannelUnreadNavigation } from './create-channel-unread-navigation';
import { createDeleteMessageConfirmation } from './create-delete-message-confirmation';
import { createMessageEditor } from './create-message-editor';
import { createMessageSelection } from './create-message-selection';
@@ -260,6 +261,15 @@ export function Channel(props: ChannelProps) {
const messageById = () => messageIndex.byId;
// Loaded messages, oldest first; activity rows are not unread targets.
const messages = createMemo(() => [...messageIndex.byId.values()]);
+ const unread = createChannelUnreadNavigation({
+ channelId: props.channelId,
+ messages,
+ activities: () => messageIndex.activityByKey,
+ scrollState: threadListScrollState,
+ container: threadListContainerEl,
+ insets: threadListScrollInsets,
+ onDestinationsChanged: () => threadListNavigation()?.requestLayoutUpdate(),
+ });
const participants = useChannelParticipants(() => props.channelId);
const channelBotMentionUsers = useMessageBotMentionUsers(() => ({
type: 'channel',
@@ -725,223 +735,209 @@ export function Channel(props: ChannelProps) {
class="relative flex-1 min-h-0"
ref={setThreadListContainerEl}
>
- <ChannelUnreadNotifications
- channelId={props.channelId}
- messages={messages}
- activities={() => messageIndex.activityByKey}
- scrollState={threadListScrollState}
- container={threadListContainerEl}
- insets={threadListScrollInsets}
+ <MessageNotificationIndexContext.Provider
+ value={unread.unreadByMessage}
>
- {(unreadChip) => (
- <>
- <SwipableRowProvider
- container={threadListContainerEl}
- triggerBehavior="spring-back"
- >
- <ThreadList
- keys={() => messageIndex.entryKeys}
- targetId={
- targetMessageController.hasPendingElementScroll()
- ? targetMessageController.activeTargetMessageId()
- : undefined
- }
- insets={threadListScrollInsets()}
- followOnAppend={!messagesQuery.hasPreviousPage}
- onScrollNearTop={threadPaginator.shiftPaginate}
- onScrollNearBottom={
- threadPaginator.prependPaginate
- }
- onReady={onThreadListReady}
- onScroll={onThreadListScroll}
- onUserNavigation={cancelLatestNavigation}
- initialPosition={
- targetMessageController.activeTargetMessageId()
- ? {
- type: 'element',
- id: targetMessageController.activeTargetMessageId()!,
- }
- : props.initialMessagesStateSnapshot?.scroll
- ? {
- type: 'restore',
- snapshot:
- props.initialMessagesStateSnapshot
- .scroll,
- }
- : { type: 'latest' }
- }
- >
- {(item) => {
- const isNewestRow = () =>
- item.id === messageIndex.entryKeys.at(-1);
- const activity = () =>
- messageIndex.activityByKey.get(item.id);
- const message = () =>
- messageById().get(item.id);
+ <SwipableRowProvider
+ container={threadListContainerEl}
+ triggerBehavior="spring-back"
+ >
+ <ThreadList
+ keys={() => messageIndex.entryKeys}
+ targetId={
+ targetMessageController.hasPendingElementScroll()
+ ? targetMessageController.activeTargetMessageId()
+ : undefined
+ }
+ insets={threadListScrollInsets()}
+ followOnAppend={!messagesQuery.hasPreviousPage}
+ onScrollNearTop={threadPaginator.shiftPaginate}
+ onScrollNearBottom={threadPaginator.prependPaginate}
+ onReady={onThreadListReady}
+ onScroll={onThreadListScroll}
+ onUserNavigation={cancelLatestNavigation}
+ initialPosition={
+ targetMessageController.activeTargetMessageId()
+ ? {
+ type: 'element',
+ id: targetMessageController.activeTargetMessageId()!,
+ }
+ : props.initialMessagesStateSnapshot?.scroll
+ ? {
+ type: 'restore',
+ snapshot:
+ props.initialMessagesStateSnapshot
+ .scroll,
+ }
+ : { type: 'latest' }
+ }
+ >
+ {(item) => {
+ const isNewestRow = () =>
+ item.id === messageIndex.entryKeys.at(-1);
+ const activity = () =>
+ messageIndex.activityByKey.get(item.id);
+ const message = () => messageById().get(item.id);
- return (
- <Switch>
- <Match when={activity()}>
- {(activity) => (
- <ThreadRow
- channelId={props.channelId}
- message={{
- created_at:
- activity().occurred_at,
- }}
- listMeta={listMetaByKey()[item.id]}
- >
- <SystemActivity
- event={decodeSystemActivity(
- activity()
- )}
- />
- <Show when={isNewestRow()}>
- <ThreadTypingIndicator
- parent={{
- type: 'channel',
- id: props.channelId,
- }}
- threadId={null}
- />
- </Show>
- </ThreadRow>
- )}
- </Match>
- <Match when={message()}>
- {(m) => {
- const state =
- threadManager.getOrCreateThreadState(
- item.id
- );
- return (
- <ChannelThread
- data={m}
- parent={() => ({
- type: 'channel',
- id: (() => props.channelId)(),
- })}
- isNewestThread={isNewestRow()}
- getMessageActions={
- getMessageActions
- }
- isFindBarOpen={findBar.isOpen}
- targetNavigation={{
- targetThreadId:
- targetMessageController.activeTargetMessageId,
- targetMessageId: () =>
- !targetMessageController.pendingTargetReplyId()
- ? targetMessageController.pendingScrollTargetId()
- : undefined,
- targetReplyId: () =>
- targetMessageController.pendingScrollTargetId()
- ? undefined
- : targetMessageController.pendingTargetReplyId(),
- activeTargetReplyId:
- targetMessageController.activeTargetMessageReplyId,
- positionTarget: (
- _,
- targetElement
- ) =>
- threadListNavigation()?.scrollToElement(
- targetElement
- ) ?? false,
- onTargetMessageScrolled:
- targetMessageController.completePendingScroll,
- onTargetReplyScrolled: (
- replyId
- ) => {
- targetMessageController.completePendingReplyScroll(
- item.id,
- replyId
- );
- },
- onClearTarget:
- releaseSelectionAndTarget,
- }}
- inputMode={
- isUnifiedInputMode()
- ? 'unified'
- : 'inline'
- }
- unifiedReplyTarget={unifiedInput.replyTarget()}
- isExpanded={state.isExpanded}
- setIsExpanded={
- state.setIsExpanded
- }
- isReplying={state.isReplying}
- setIsReplying={
- state.setIsReplying
- }
- replyInputState={
- state.replyInputState
- }
- setReplyInputState={
- state.setReplyInputState
- }
- setReplyInputEl={
- state.setReplyInputEl
- }
- replyInputHandle={
- state.replyInputHandle
- }
- setReplyInputHandle={
- state.setReplyInputHandle
- }
- replyInputFocusRequest={
- state.replyInputFocusRequest
- }
- listMeta={
- listMetaByKey()[item.id]
- }
- messageEditor={messageEditor}
- threadActions={{
- onDismissNewMessages:
- activityTracker.dismissNewMessages,
- }}
- isNewMessage={
- activityTracker.isNewMessage
- }
- selectedMessageId={
- selection.selectedId
- }
- onSelectMessage={selectMessage}
- onClearSelection={clearSelection}
- messageListScopeId={
- messageListScopeId
- }
- />
- );
+ return (
+ <Switch>
+ <Match when={activity()}>
+ {(activity) => (
+ <ThreadRow
+ channelId={props.channelId}
+ message={{
+ created_at: activity().occurred_at,
}}
- </Match>
- </Switch>
- );
- }}
- </ThreadList>
- </SwipableRowProvider>
+ listMeta={listMetaByKey()[item.id]}
+ >
+ <SystemActivity
+ event={decodeSystemActivity(
+ activity()
+ )}
+ />
+ <Show when={isNewestRow()}>
+ <ThreadTypingIndicator
+ parent={{
+ type: 'channel',
+ id: props.channelId,
+ }}
+ threadId={null}
+ />
+ </Show>
+ </ThreadRow>
+ )}
+ </Match>
+ <Match when={message()}>
+ {(m) => {
+ const state =
+ threadManager.getOrCreateThreadState(
+ item.id
+ );
+ return (
+ <ChannelThread
+ data={m}
+ parent={() => ({
+ type: 'channel',
+ id: (() => props.channelId)(),
+ })}
+ isNewestThread={isNewestRow()}
+ getMessageActions={getMessageActions}
+ isFindBarOpen={findBar.isOpen}
+ targetNavigation={{
+ targetThreadId:
+ targetMessageController.activeTargetMessageId,
+ targetMessageId: () =>
+ !targetMessageController.pendingTargetReplyId()
+ ? targetMessageController.pendingScrollTargetId()
+ : undefined,
+ targetReplyId: () =>
+ targetMessageController.pendingScrollTargetId()
+ ? undefined
+ : targetMessageController.pendingTargetReplyId(),
+ activeTargetReplyId:
+ targetMessageController.activeTargetMessageReplyId,
+ positionTarget: (
+ _,
+ targetElement
+ ) =>
+ threadListNavigation()?.scrollToElement(
+ targetElement
+ ) ?? false,
+ onTargetMessageScrolled:
+ targetMessageController.completePendingScroll,
+ onTargetReplyScrolled: (
+ replyId
+ ) => {
+ targetMessageController.completePendingReplyScroll(
+ item.id,
+ replyId
+ );
+ },
+ onClearTarget:
+ releaseSelectionAndTarget,
+ }}
+ inputMode={
+ isUnifiedInputMode()
+ ? 'unified'
+ : 'inline'
+ }
+ unifiedReplyTarget={unifiedInput.replyTarget()}
+ onMessageMount={unread.onMessageMount}
+ onDisclosureMount={
+ unread.onDisclosureMount
+ }
+ unreadMessageIds={unread
+ .unreadByThread()
+ .get(item.id)}
+ isExpanded={state.isExpanded}
+ setIsExpanded={state.setIsExpanded}
+ isReplying={state.isReplying}
+ setIsReplying={state.setIsReplying}
+ replyInputState={
+ state.replyInputState
+ }
+ setReplyInputState={
+ state.setReplyInputState
+ }
+ setReplyInputEl={
+ state.setReplyInputEl
+ }
+ replyInputHandle={
+ state.replyInputHandle
+ }
+ setReplyInputHandle={
+ state.setReplyInputHandle
+ }
+ replyInputFocusRequest={
+ state.replyInputFocusRequest
+ }
+ listMeta={listMetaByKey()[item.id]}
+ messageEditor={messageEditor}
+ threadActions={{
+ onDismissNewMessages:
+ activityTracker.dismissNewMessages,
+ }}
+ isNewMessage={
+ activityTracker.isNewMessage
+ }
+ selectedMessageId={
+ selection.selectedId
+ }
+ onSelectMessage={selectMessage}
+ onClearSelection={clearSelection}
+ messageListScopeId={
+ messageListScopeId
+ }
+ />
+ );
+ }}
+ </Match>
+ </Switch>
+ );
+ }}
+ </ThreadList>
+ </SwipableRowProvider>
- <Show when={!findBar.isOpen()}>
- <Show when={unreadChip()}>
- {(chip) => (
- <UnreadNotificationsOverlay
- direction={chip().direction}
- count={chip().count}
- onClick={() => goToUnread(chip().thread)}
- bottomInset={threadListScrollInsets().end}
- />
- )}
- </Show>
- <Show when={unreadChip()?.direction !== 'above'}>
- <ScrollToBottomOverlay
- scrollState={threadListScrollState}
- onScrollToBottom={goToLatest}
- class="touch:top-[calc(var(--mobile-content-inset-top,0)+1rem)]"
- />
- </Show>
- </Show>
- </>
- )}
- </ChannelUnreadNotifications>
+ <Show when={!findBar.isOpen()}>
+ <Show when={unread.chip()}>
+ {(chip) => (
+ <UnreadNotificationsOverlay
+ direction={chip().direction}
+ count={chip().count}
+ onClick={() => goToUnread(chip().thread)}
+ bottomInset={threadListScrollInsets().end}
+ />
+ )}
+ </Show>
+ <Show when={unread.chip()?.direction !== 'above'}>
+ <ScrollToBottomOverlay
+ scrollState={threadListScrollState}
+ onScrollToBottom={goToLatest}
+ class="touch:top-[calc(var(--mobile-content-inset-top,0)+1rem)]"
+ />
+ </Show>
+ </Show>
+ </MessageNotificationIndexContext.Provider>
</div>
</Show>
<DebugSuspense name="Channel.active-call">
diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsx
index 57e5640b29..81b6ae7e44 100644
--- a/apps/web/src/features/channel/Channel/ThreadList.tsx
+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx
@@ -41,6 +41,8 @@ export type ThreadListInitialPosition =
| { type: 'restore'; snapshot: ThreadListScrollSnapshot };
export type ThreadListNavigation = {
+ /** Publish geometry after registered destinations finish mounting/unmounting. */
+ requestLayoutUpdate: () => void;
scrollToLatest: () => boolean;
scrollToMessage: (
id: string,
@@ -407,6 +409,7 @@ export function ThreadList(props: ThreadListProps) {
(scrollEl()?.clientHeight ?? 0) > 0;
const navigation: ThreadListNavigation = {
+ requestLayoutUpdate: scheduleScrollState,
scrollToLatest: () => {
if (!canNavigate() || !props.keys().length) return false;
lifecycle.send('navigate');
diff --git a/apps/web/src/features/channel/Channel/ChannelUnreadNotifications.tsx b/apps/web/src/features/channel/Channel/create-channel-unread-navigation.ts
similarity index 63%
rename from apps/web/src/features/channel/Channel/ChannelUnreadNotifications.tsx
rename to apps/web/src/features/channel/Channel/create-channel-unread-navigation.ts
index c06b24529d..c199eb0dea 100644
--- a/apps/web/src/features/channel/Channel/ChannelUnreadNotifications.tsx
+++ b/apps/web/src/features/channel/Channel/create-channel-unread-navigation.ts
@@ -2,7 +2,6 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { enableGraphqlSoup } from '@core/constant/featureFlags';
import { isTransientRequestError } from '@core/util/request-error';
-import { MessageNotificationIndexContext } from '@notifications/components/MarkMessageNotifications';
import { compositeEntity } from '@notifications/types';
import { indexUnreadMessageNotifications } from '@notifications/unread-message-notifications';
import { createChannelNotificationsQuery } from '@queries/channel/notifications';
@@ -12,17 +11,18 @@ import type {
MessageListItem,
TimelineActivity,
} from '@service-storage/messages';
-import { type Accessor, createMemo, type JSX } from 'solid-js';
+import { type Accessor, createMemo } from 'solid-js';
+import { createUnreadDestinationRegistry } from './create-unread-destination-registry';
import type { ThreadListScrollState } from './ThreadList';
import {
type ThreadPosition,
- type UnreadNotificationChip,
+ unreadDestinationPositions,
unreadNotificationChip,
unreadThreads,
} from './unread-thread-navigation';
/** Data and viewport wiring for the channel's unread navigation affordance. */
-export function ChannelUnreadNotifications(props: {
+export function createChannelUnreadNavigation(options: {
channelId: string;
messages: Accessor<MessageListItem[]>;
/** Activity rows can be the first visible row, so they need positions too. */
@@ -30,19 +30,19 @@ export function ChannelUnreadNotifications(props: {
scrollState: Accessor<ThreadListScrollState | undefined>;
container: Accessor<HTMLElement | undefined>;
insets: Accessor<{ start: number; end: number }>;
- children: (chip: Accessor<UnreadNotificationChip | undefined>) => JSX.Element;
+ onDestinationsChanged: () => void;
}) {
const notificationSource = useGlobalNotificationSource();
const graphqlNotifications = useFeatureFlag(enableGraphqlSoup);
const channelNotifications = createChannelNotificationsQuery(
- props.channelId,
+ options.channelId,
() => graphqlNotifications().enabled
);
const notifications = createMemo(() => {
if (!graphqlNotifications().enabled) {
return (
notificationSource.notificationsByEntity()[
- compositeEntity({ type: 'channel', id: props.channelId })
+ compositeEntity({ type: 'channel', id: options.channelId })
] ?? []
);
}
@@ -62,15 +62,22 @@ export function ChannelUnreadNotifications(props: {
indexUnreadMessageNotifications(notifications())
);
const unread = createMemo(() => unreadThreads(notifications()));
+ const unreadByThread = createMemo(
+ () =>
+ new Map(unread().map((thread) => [thread.threadId, thread.messageIds]))
+ );
+ const destinationRegistry = createUnreadDestinationRegistry(() =>
+ options.onDestinationsChanged()
+ );
// A reply's timestamp says nothing about where its parent sits in history.
- // Resolve only the target parent without loading the timeline around it.
+ // Only the first unloaded unread parent can become the next target.
+ // Resolve it without loading entire timelines or every offscreen thread.
const unreadRoots = useMessageTimelineByIdsQuery(
- () => ({ type: 'channel', id: props.channelId }),
+ () => ({ type: 'channel', id: options.channelId }),
() => {
- const id = unread()[0]?.threadId;
- return id && !props.messages().some((message) => message.id === id)
- ? [id]
- : [];
+ const loaded = new Set(options.messages().map((message) => message.id));
+ const target = unread().find((thread) => !loaded.has(thread.threadId));
+ return target ? [target.threadId] : [];
}
);
const unreadChip = createMemo(() => {
@@ -80,41 +87,35 @@ export function ChannelUnreadNotifications(props: {
message,
])
);
- for (const message of props.messages()) positions.set(message.id, message);
- for (const [key, activity] of props.activities?.() ?? [])
+ for (const message of options.messages())
+ positions.set(message.id, message);
+ for (const [key, activity] of options.activities?.() ?? [])
positions.set(key, { id: activity.id, created_at: activity.occurred_at });
- const scroll = props.scrollState();
- const target = unread()[0];
- const container = props.container();
+ const scroll = options.scrollState();
+ const container = options.container();
const viewport = container?.querySelector('[data-channel-scroll]');
- const element =
- target &&
- container?.querySelector(
- `[data-message-id="${CSS.escape(target.messageId)}"]`
- );
- let targetPosition: 'above' | 'below' | 'visible' | undefined;
- if (viewport && element) {
- const bounds = viewport.getBoundingClientRect();
- const message = element.getBoundingClientRect();
- const insets = props.insets();
- targetPosition =
- message.bottom <= bounds.top + insets.start
- ? 'above'
- : message.top >= bounds.bottom - insets.end
- ? 'below'
- : 'visible';
- }
+ const destinations =
+ container && viewport
+ ? unreadDestinationPositions(
+ unread(),
+ destinationRegistry.elements,
+ viewport,
+ options.insets()
+ )
+ : undefined;
return unreadNotificationChip(
unread(),
positions,
scroll?.didInitialScroll ? scroll.visibleRange : undefined,
- targetPosition
+ destinations
);
});
- return (
- <MessageNotificationIndexContext.Provider value={unreadByMessage}>
- {props.children(unreadChip)}
- </MessageNotificationIndexContext.Provider>
- );
+ return {
+ chip: unreadChip,
+ unreadByThread,
+ unreadByMessage,
+ onMessageMount: destinationRegistry.registerMessage,
+ onDisclosureMount: destinationRegistry.registerDisclosure,
+ };
}
diff --git a/apps/web/src/features/channel/Channel/create-unread-destination-registry.ts b/apps/web/src/features/channel/Channel/create-unread-destination-registry.ts
new file mode 100644
index 0000000000..0481e57e87
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/create-unread-destination-registry.ts
@@ -0,0 +1,28 @@
+export type UnreadDestinationElements = {
+ messages: ReadonlyMap<string, HTMLElement>;
+ disclosures: ReadonlyMap<string, HTMLElement>;
+};
+
+/** Mounted destinations are explicit; ThreadList owns when layout is measured. */
+export function createUnreadDestinationRegistry(onChange: () => void) {
+ const messages = new Map<string, HTMLElement>();
+ const disclosures = new Map<string, HTMLElement>();
+ const register =
+ (elements: Map<string, HTMLElement>) =>
+ (id: string, element: HTMLElement) => {
+ elements.set(id, element);
+ onChange();
+ return () => {
+ // A replacement may mount before the previous row's cleanup runs.
+ if (elements.get(id) !== element) return;
+ elements.delete(id);
+ onChange();
+ };
+ };
+
+ return {
+ elements: { messages, disclosures } satisfies UnreadDestinationElements,
+ registerMessage: register(messages),
+ registerDisclosure: register(disclosures),
+ };
+}
diff --git a/apps/web/src/features/channel/Channel/tests/ChannelUnreadNotifications.test.tsx b/apps/web/src/features/channel/Channel/tests/ChannelUnreadNotifications.test.tsx
deleted file mode 100644
index 8170909d1f..0000000000
--- a/apps/web/src/features/channel/Channel/tests/ChannelUnreadNotifications.test.tsx
+++ /dev/null
@@ -1,271 +0,0 @@
-import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';
-import type { UnifiedNotification } from '@notifications/types';
-import type { MessageListItem } from '@service-storage/messages';
-import { render, waitFor } from '@solidjs/testing-library';
-import { createSignal, For, Show } from 'solid-js';
-import { expect, it, vi } from 'vitest';
-import { ChannelUnreadNotifications } from '../ChannelUnreadNotifications';
-import { UnreadNotificationsOverlay } from '../UnreadNotificationsOverlay';
-
-const mocks = vi.hoisted(() => ({ query: vi.fn(), source: vi.fn() }));
-vi.mock('@app/lib/analytics/posthog', () => ({
- useFeatureFlag: () => () => ({ enabled: true }),
-}));
-vi.mock('@components/app/GlobalAppState', () => ({
- useGlobalNotificationSource: mocks.source,
-}));
-vi.mock('@queries/channel/notifications', () => ({
- createChannelNotificationsQuery: mocks.query,
-}));
-vi.mock('@queries/messages/timeline', () => ({
- useMessageTimelineByIdsQuery: () => ({
- isPending: true,
- get data() {
- throw new Error('Read pending parent query');
- },
- }),
-}));
-
-function notification(threadId: string, time: number): UnifiedNotification {
- return {
- id: `n-${time}`,
- entity_id: 'channel',
- entity_type: 'channel',
- state: 'unseen',
- sent: true,
- viewed_at: null,
- created_at: `2026-09-01T${time}:00:00Z`,
- updated_at: '2026-09-01T00:00:00Z',
- notification_event_type: 'channel_message_reply',
- notification_metadata: {
- tag: 'channel_message_reply',
- content: {
- channelType: 'private',
- messageId: `reply-${time}`,
- threadId,
- messageContent: 'Hello',
- },
- },
- };
-}
-
-it('shares unread lookups across mounted messages without rescanning history per row', async () => {
- const reply = notification('root-1', 12);
- const metadata = reply.notification_metadata;
- const readMetadata = vi.fn(() => metadata);
- Object.defineProperty(reply, 'notification_metadata', { get: readMetadata });
- const history = Array.from({ length: 200 }, (_, index) => ({
- ...notification('root-1', 12),
- id: `done-${index}`,
- state: 'done' as const,
- get notification_metadata(): UnifiedNotification['notification_metadata'] {
- throw new Error('Read historical notification metadata');
- },
- }));
- const [records, setRecords] = createSignal<UnifiedNotification[]>([
- ...history,
- reply,
- ]);
- const [messageIds, setMessageIds] = createSignal(['root-1']);
- const globalRead = vi.fn(() => {
- throw new Error('Read global notifications');
- });
- const bulkMarkAsRead = vi.fn(async () => {
- setRecords([...history, { ...reply, state: 'seen' }]);
- });
- mocks.source.mockReturnValue({
- notificationsByEntity: globalRead,
- withLocalOverrides: (n: UnifiedNotification) => n,
- bulkMarkAsRead,
- });
- mocks.query.mockReturnValue({
- isEnabled: true,
- isPending: false,
- get data() {
- return records();
- },
- });
- const view = render(() => (
- <ChannelUnreadNotifications
- channelId="channel"
- messages={() => []}
- scrollState={() => undefined}
- container={() => undefined}
- insets={() => ({ start: 0, end: 0 })}
- >
- {() => (
- <For each={messageIds()}>
- {(messageId) => (
- <MarkMessageNotifications
- messageId={messageId}
- parent={{ type: 'channel', id: 'channel' }}
- >
- <span>{messageId}</span>
- </MarkMessageNotifications>
- )}
- </For>
- )}
- </ChannelUnreadNotifications>
- ));
- const initialReads = readMetadata.mock.calls.length;
- expect(initialReads).toBeGreaterThan(0);
- expect(bulkMarkAsRead).not.toHaveBeenCalled();
-
- setMessageIds(Array.from({ length: 50 }, (_, index) => `other-${index}`));
- expect(view.container.querySelectorAll('span')).toHaveLength(50);
- expect(readMetadata).toHaveBeenCalledTimes(initialReads);
- expect(bulkMarkAsRead).not.toHaveBeenCalled();
-
- setMessageIds([...messageIds(), 'reply-12']);
- await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());
- expect(bulkMarkAsRead).toHaveBeenCalledWith([reply]);
- expect(globalRead).not.toHaveBeenCalled();
-});
-
-it('updates one chip live without suspending the channel or loading the global feed', () => {
- const [pending, setPending] = createSignal(true);
- const [notifications, setNotifications] = createSignal<UnifiedNotification[]>(
- []
- );
- const [seen, setSeen] = createSignal(false);
- const globalRead = vi.fn(() => {
- throw new Error('Read global notifications');
- });
- mocks.source.mockReturnValue({
- notificationsByEntity: globalRead,
- withLocalOverrides: (n: UnifiedNotification) =>
- seen() ? { ...n, state: 'seen' } : n,
- });
- mocks.query.mockReturnValue({
- isEnabled: true,
- get isPending() {
- return pending();
- },
- get data() {
- if (pending()) throw new Error('Read pending notifications');
- return notifications();
- },
- });
- const messages = [1, 2, 3].map(
- (i) =>
- ({
- id: `root-${i}`,
- created_at: `2026-08-0${i}T00:00:00Z`,
- }) as MessageListItem
- );
- const navigate = vi.fn();
- const view = render(() => (
- <ChannelUnreadNotifications
- channelId="channel"
- messages={() => messages}
- scrollState={() => ({
- didInitialScroll: true,
- visibleRange: { first: 'root-2', last: 'root-2' },
- isNearBottom: false,
- isScrollingDown: false,
- distanceFromBottom: 500,
- distanceFromTop: 500,
- viewportSize: 500,
- })}
- container={() => undefined}
- insets={() => ({ start: 0, end: 0 })}
- >
- {(chip) => (
- <>
- <p>Channel messages</p>
- <Show when={chip()}>
- {(value) => (
- <UnreadNotificationsOverlay
- direction={value().direction}
- count={value().count}
- onClick={() => navigate(value().thread)}
- />
- )}
- </Show>
- </>
- )}
- </ChannelUnreadNotifications>
- ));
- expect(view.getByText('Channel messages')).toBeTruthy();
- expect(view.queryByRole('button')).toBeNull();
- setNotifications([notification('root-1', 12), notification('root-1', 13)]);
- setPending(false);
- expect(
- view.getByRole('button', { name: '1 unread notification stack above' })
- ).toBeTruthy();
- setNotifications([...notifications(), notification('root-3', 14)]);
- expect(view.getAllByRole('button')).toHaveLength(1);
- view
- .getByRole('button', { name: '2 unread notification stacks below' })
- .click();
- expect(navigate).toHaveBeenCalledWith(
- expect.objectContaining({ threadId: 'root-3', messageId: 'reply-14' })
- );
- setSeen(true);
- expect(view.queryByRole('button')).toBeNull();
- expect(globalRead).not.toHaveBeenCalled();
-});
-
-it('places the chip when an activity row is the first visible row', () => {
- mocks.source.mockReturnValue({
- notificationsByEntity: vi.fn(),
- withLocalOverrides: (n: UnifiedNotification) => n,
- });
- mocks.query.mockReturnValue({
- isEnabled: true,
- isPending: false,
- data: [notification('root-1', 12)],
- });
- const messages = [1, 3].map(
- (i) =>
- ({
- id: `root-${i}`,
- created_at: `2026-08-0${i}T00:00:00Z`,
- }) as MessageListItem
- );
- const activities = new Map([
- [
- 'activity:joined',
- {
- id: 'joined',
- actor_id: 'macro|[email protected]',
- occurred_at: '2026-08-02T00:00:00Z',
- action: 'participant_added',
- payload: null,
- },
- ],
- ]);
- const view = render(() => (
- <ChannelUnreadNotifications
- channelId="channel"
- messages={() => messages}
- activities={() => activities}
- scrollState={() => ({
- didInitialScroll: true,
- visibleRange: { first: 'activity:joined', last: 'root-3' },
- isNearBottom: false,
- isScrollingDown: false,
- distanceFromBottom: 500,
- distanceFromTop: 500,
- viewportSize: 500,
- })}
- container={() => undefined}
- insets={() => ({ start: 0, end: 0 })}
- >
- {(chip) => (
- <Show when={chip()}>
- {(value) => (
- <UnreadNotificationsOverlay
- direction={value().direction}
- count={value().count}
- onClick={() => {}}
- />
- )}
- </Show>
- )}
- </ChannelUnreadNotifications>
- ));
- expect(
- view.getByRole('button', { name: '1 unread notification stack above' })
- ).toBeTruthy();
-});
diff --git a/apps/web/src/features/channel/Channel/tests/create-channel-unread-navigation.test.tsx b/apps/web/src/features/channel/Channel/tests/create-channel-unread-navigation.test.tsx
new file mode 100644
index 0000000000..2330cd3922
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/create-channel-unread-navigation.test.tsx
@@ -0,0 +1,444 @@
+import {
+ MarkMessageNotifications,
+ MessageNotificationIndexContext,
+} from '@notifications/components/MarkMessageNotifications';
+import type { UnifiedNotification } from '@notifications/types';
+import type { MessageListItem } from '@service-storage/messages';
+import { render, waitFor } from '@solidjs/testing-library';
+import { createSignal, For, Show } from 'solid-js';
+import { expect, it, vi } from 'vitest';
+import { notifyElementOnMount } from '../../Thread/message-element-lifecycle';
+import { ThreadCollapsedIndicator } from '../../Thread/ThreadCollapsedIndicator';
+import { createChannelUnreadNavigation } from '../create-channel-unread-navigation';
+import { UnreadNotificationsOverlay } from '../UnreadNotificationsOverlay';
+
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => <span /> }));
+
+const mocks = vi.hoisted(() => ({ query: vi.fn(), source: vi.fn() }));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: true }),
+}));
+vi.mock('@components/app/GlobalAppState', () => ({
+ useGlobalNotificationSource: mocks.source,
+}));
+vi.mock('@queries/channel/notifications', () => ({
+ createChannelNotificationsQuery: mocks.query,
+}));
+vi.mock('@queries/messages/timeline', () => ({
+ useMessageTimelineByIdsQuery: () => ({
+ isPending: true,
+ get data() {
+ throw new Error('Read pending parent query');
+ },
+ }),
+}));
+
+function notification(threadId: string, time: number): UnifiedNotification {
+ return {
+ id: `n-${time}`,
+ entity_id: 'channel',
+ entity_type: 'channel',
+ state: 'unseen',
+ sent: true,
+ viewed_at: null,
+ created_at: `2026-09-01T${time}:00:00Z`,
+ updated_at: '2026-09-01T00:00:00Z',
+ notification_event_type: 'channel_message_reply',
+ notification_metadata: {
+ tag: 'channel_message_reply',
+ content: {
+ channelType: 'private',
+ messageId: `reply-${time}`,
+ threadId,
+ messageContent: 'Hello',
+ },
+ },
+ };
+}
+
+it('shares unread lookups across mounted messages without rescanning history per row', async () => {
+ const reply = notification('root-1', 12);
+ const metadata = reply.notification_metadata;
+ const readMetadata = vi.fn(() => metadata);
+ Object.defineProperty(reply, 'notification_metadata', { get: readMetadata });
+ const history = Array.from({ length: 200 }, (_, index) => ({
+ ...notification('root-1', 12),
+ id: `done-${index}`,
+ state: 'done' as const,
+ get notification_metadata(): UnifiedNotification['notification_metadata'] {
+ throw new Error('Read historical notification metadata');
+ },
+ }));
+ const [records, setRecords] = createSignal<UnifiedNotification[]>([
+ ...history,
+ reply,
+ ]);
+ const [messageIds, setMessageIds] = createSignal(['root-1']);
+ const globalRead = vi.fn(() => {
+ throw new Error('Read global notifications');
+ });
+ const bulkMarkAsRead = vi.fn(async () => {
+ setRecords([...history, { ...reply, state: 'seen' }]);
+ });
+ mocks.source.mockReturnValue({
+ notificationsByEntity: globalRead,
+ withLocalOverrides: (n: UnifiedNotification) => n,
+ bulkMarkAsRead,
+ });
+ mocks.query.mockReturnValue({
+ isEnabled: true,
+ isPending: false,
+ get data() {
+ return records();
+ },
+ });
+ const view = render(() => {
+ const unread = createChannelUnreadNavigation({
+ channelId: 'channel',
+ messages: () => [],
+ scrollState: () => undefined,
+ onDestinationsChanged: () => {},
+ container: () => undefined,
+ insets: () => ({ start: 0, end: 0 }),
+ });
+ return (
+ <MessageNotificationIndexContext.Provider value={unread.unreadByMessage}>
+ <For each={messageIds()}>
+ {(messageId) => (
+ <MarkMessageNotifications
+ messageId={messageId}
+ parent={{ type: 'channel', id: 'channel' }}
+ >
+ <span>{messageId}</span>
+ </MarkMessageNotifications>
+ )}
+ </For>
+ </MessageNotificationIndexContext.Provider>
+ );
+ });
+ const initialReads = readMetadata.mock.calls.length;
+ expect(initialReads).toBeGreaterThan(0);
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+
+ setMessageIds(Array.from({ length: 50 }, (_, index) => `other-${index}`));
+ expect(view.container.querySelectorAll('span')).toHaveLength(50);
+ expect(readMetadata).toHaveBeenCalledTimes(initialReads);
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+
+ setMessageIds([...messageIds(), 'reply-12']);
+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());
+ expect(bulkMarkAsRead).toHaveBeenCalledWith([reply]);
+ expect(globalRead).not.toHaveBeenCalled();
+});
+
+it('updates one chip live without suspending the channel or loading the global feed', () => {
+ const [pending, setPending] = createSignal(true);
+ const [notifications, setNotifications] = createSignal<UnifiedNotification[]>(
+ []
+ );
+ const [seen, setSeen] = createSignal(false);
+ const globalRead = vi.fn(() => {
+ throw new Error('Read global notifications');
+ });
+ mocks.source.mockReturnValue({
+ notificationsByEntity: globalRead,
+ withLocalOverrides: (n: UnifiedNotification) =>
+ seen() ? { ...n, state: 'seen' } : n,
+ });
+ mocks.query.mockReturnValue({
+ isEnabled: true,
+ get isPending() {
+ return pending();
+ },
+ get data() {
+ if (pending()) throw new Error('Read pending notifications');
+ return notifications();
+ },
+ });
+ const messages = [1, 2, 3].map(
+ (i) =>
+ ({
+ id: `root-${i}`,
+ created_at: `2026-08-0${i}T00:00:00Z`,
+ }) as MessageListItem
+ );
+ const navigate = vi.fn();
+ const view = render(() => {
+ const unread = createChannelUnreadNavigation({
+ channelId: 'channel',
+ messages: () => messages,
+ scrollState: () => ({
+ didInitialScroll: true,
+ visibleRange: { first: 'root-2', last: 'root-2' },
+ isNearBottom: false,
+ isScrollingDown: false,
+ distanceFromBottom: 500,
+ distanceFromTop: 500,
+ viewportSize: 500,
+ }),
+ onDestinationsChanged: () => {},
+ container: () => undefined,
+ insets: () => ({ start: 0, end: 0 }),
+ });
+ return (
+ <>
+ <p>Channel messages</p>
+ <Show when={unread.chip()}>
+ {(value) => (
+ <UnreadNotificationsOverlay
+ direction={value().direction}
+ count={value().count}
+ onClick={() => navigate(value().thread)}
+ />
+ )}
+ </Show>
+ </>
+ );
+ });
+ expect(view.getByText('Channel messages')).toBeTruthy();
+ expect(view.queryByRole('button')).toBeNull();
+ setNotifications([notification('root-1', 12), notification('root-1', 13)]);
+ setPending(false);
+ expect(
+ view.getByRole('button', {
+ name: '1 unread notification stack above',
+ })
+ ).toBeTruthy();
+ setNotifications([...notifications(), notification('root-3', 14)]);
+ expect(view.getAllByRole('button')).toHaveLength(1);
+ view
+ .getByRole('button', {
+ name: '2 unread notification stacks below',
+ })
+ .click();
+ expect(navigate).toHaveBeenCalledWith(
+ expect.objectContaining({ threadId: 'root-3', messageId: 'reply-14' })
+ );
+ setSeen(true);
+ expect(view.queryByRole('button')).toBeNull();
+ expect(globalRead).not.toHaveBeenCalled();
+});
+
+it('hands off to the inline unread indicator, keeps other offscreen threads reachable, and only marks rendered replies seen', async () => {
+ const [records, setRecords] = createSignal<UnifiedNotification[]>([]);
+ const [container, setContainer] = createSignal<HTMLDivElement>();
+ const [expanded, setExpanded] = createSignal(false);
+ const [scrollTick, setScrollTick] = createSignal(0);
+ let disclosureTop = 350;
+ const bulkMarkAsRead = vi.fn(async (seen: UnifiedNotification[]) => {
+ const ids = new Set(seen.map((n) => n.id));
+ setRecords((current) =>
+ current.map((n) => (ids.has(n.id) ? { ...n, state: 'seen' } : n))
+ );
+ });
+ mocks.source.mockReturnValue({
+ withLocalOverrides: (n: UnifiedNotification) => n,
+ bulkMarkAsRead,
+ });
+ mocks.query.mockReturnValue({
+ isEnabled: true,
+ isPending: false,
+ get data() {
+ return records();
+ },
+ });
+ const messages = [1, 2, 3].map(
+ (i) =>
+ ({
+ id: `root-${i}`,
+ created_at: `2026-08-0${i}T00:00:00Z`,
+ }) as MessageListItem
+ );
+ const view = render(() => {
+ const unread = createChannelUnreadNavigation({
+ channelId: 'channel',
+ messages: () => messages,
+ container,
+ onDestinationsChanged: () =>
+ queueMicrotask(() => setScrollTick((tick) => tick + 1)),
+ insets: () => ({ start: 20, end: 80 }),
+ scrollState: () => ({
+ didInitialScroll: true,
+ visibleRange: { first: 'root-2', last: 'root-3' },
+ isNearBottom: true,
+ isScrollingDown: false,
+ distanceFromBottom: 0,
+ distanceFromTop: scrollTick(),
+ viewportSize: 400,
+ }),
+ });
+ return (
+ <div ref={setContainer}>
+ <MessageNotificationIndexContext.Provider
+ value={unread.unreadByMessage}
+ >
+ <div
+ data-channel-scroll
+ ref={(el) => {
+ el.getBoundingClientRect = () => new DOMRect(0, 100, 500, 400);
+ }}
+ >
+ <Show
+ when={!expanded()}
+ fallback={
+ <MarkMessageNotifications
+ messageId="reply-14"
+ parent={{ type: 'channel', id: 'channel' }}
+ >
+ <div
+ ref={(element) =>
+ notifyElementOnMount(
+ unread.onMessageMount,
+ 'reply-14',
+ element
+ )
+ }
+ >
+ Unread reply content
+ </div>
+ </MarkMessageNotifications>
+ }
+ >
+ <ThreadCollapsedIndicator
+ ref={(el) => {
+ el.getBoundingClientRect = () =>
+ new DOMRect(0, disclosureTop, 200, 32);
+ notifyElementOnMount(unread.onDisclosureMount, 'root-3', el);
+ }}
+ hasUnreadNotifications={unread.unreadByThread().has('root-3')}
+ collapsedRepliesCount={24}
+ participants={[]}
+ onClick={() => setExpanded(true)}
+ />
+ </Show>
+ </div>
+ <Show when={unread.chip()}>
+ {(value) => (
+ <UnreadNotificationsOverlay
+ direction={value().direction}
+ count={value().count}
+ onClick={() => setExpanded(true)}
+ />
+ )}
+ </Show>
+ </MessageNotificationIndexContext.Provider>
+ </div>
+ );
+ });
+ setRecords([notification('root-1', 12), notification('root-3', 14)]);
+ await waitFor(() =>
+ expect(view.getByText('Unread').classList.contains('sr-only')).toBe(true)
+ );
+ await waitFor(() =>
+ expect(
+ view.getByRole('button', {
+ name: '1 unread notification stack above',
+ })
+ ).toBeTruthy()
+ );
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+
+ disclosureTop = 450; // Hidden behind the composer inset.
+ setScrollTick((tick) => tick + 1);
+ expect(
+ view.getByRole('button', {
+ name: '2 unread notification stacks below',
+ })
+ ).toBeTruthy();
+ disclosureTop = 350;
+ setScrollTick((tick) => tick + 1);
+ expect(
+ view.getByRole('button', {
+ name: '1 unread notification stack above',
+ })
+ ).toBeTruthy();
+
+ setRecords([notification('root-3', 14)]);
+ await waitFor(() =>
+ expect(view.queryByText('Unread notification')).toBeNull()
+ );
+ expect(
+ view.getByTitle('Expand thread').querySelector('.bg-accent')
+ ).not.toBeNull();
+ expect(
+ view.getByTitle('Expand thread').classList.contains('border-accent/40')
+ ).toBe(true);
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+ view.getByTitle('Expand thread').click();
+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());
+ expect(bulkMarkAsRead).toHaveBeenCalledWith([notification('root-3', 14)]);
+ expect(view.getByText('Unread reply content')).toBeTruthy();
+
+ // A new notification after manual collapse restores the inline affordance.
+ setExpanded(false);
+ setRecords([notification('root-3', 15)]);
+ await waitFor(() =>
+ expect(view.getByText('Unread').classList.contains('sr-only')).toBe(true)
+ );
+ expect(view.queryByText('Unread notification')).toBeNull();
+ expect(bulkMarkAsRead).toHaveBeenCalledOnce();
+});
+
+it('places the chip when an activity row is the first visible row', () => {
+ mocks.source.mockReturnValue({
+ notificationsByEntity: vi.fn(),
+ withLocalOverrides: (n: UnifiedNotification) => n,
+ });
+ mocks.query.mockReturnValue({
+ isEnabled: true,
+ isPending: false,
+ data: [notification('root-1', 12)],
+ });
+ const messages = [1, 3].map(
+ (i) =>
+ ({
+ id: `root-${i}`,
+ created_at: `2026-08-0${i}T00:00:00Z`,
+ }) as MessageListItem
+ );
+ const activities = new Map([
+ [
+ 'activity:joined',
+ {
+ id: 'joined',
+ actor_id: 'macro|[email protected]',
+ occurred_at: '2026-08-02T00:00:00Z',
+ action: 'participant_added',
+ payload: null,
+ },
+ ],
+ ]);
+ const view = render(() => {
+ const unread = createChannelUnreadNavigation({
+ channelId: 'channel',
+ messages: () => messages,
+ activities: () => activities,
+ scrollState: () => ({
+ didInitialScroll: true,
+ visibleRange: { first: 'activity:joined', last: 'root-3' },
+ isNearBottom: false,
+ isScrollingDown: false,
+ distanceFromBottom: 500,
+ distanceFromTop: 500,
+ viewportSize: 500,
+ }),
+ container: () => undefined,
+ insets: () => ({ start: 0, end: 0 }),
+ onDestinationsChanged: () => {},
+ });
+ return (
+ <Show when={unread.chip()}>
+ {(value) => (
+ <UnreadNotificationsOverlay
+ direction={value().direction}
+ count={value().count}
+ onClick={() => {}}
+ />
+ )}
+ </Show>
+ );
+ });
+ expect(
+ view.getByRole('button', { name: '1 unread notification stack above' })
+ ).toBeTruthy();
+});
diff --git a/apps/web/src/features/channel/Channel/tests/create-unread-destination-registry.test.tsx b/apps/web/src/features/channel/Channel/tests/create-unread-destination-registry.test.tsx
new file mode 100644
index 0000000000..61c3315b93
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/create-unread-destination-registry.test.tsx
@@ -0,0 +1,72 @@
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal, Show } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { notifyElementOnMount } from '../../Thread/message-element-lifecycle';
+import { createUnreadDestinationRegistry } from '../create-unread-destination-registry';
+
+afterEach(cleanup);
+
+it('registers connected destinations and publishes mount/unmount changes even without resizing', () => {
+ const onChange = vi.fn();
+ const registry = createUnreadDestinationRegistry(onChange);
+ const [expanded, setExpanded] = createSignal(false);
+ const mounted = vi.fn((id: string, element: HTMLElement) => {
+ expect(element.isConnected).toBe(true);
+ return registry.registerDisclosure(id, element);
+ });
+ const view = render(() => (
+ <Show
+ when={!expanded()}
+ fallback={
+ <div
+ style={{ height: '32px' }}
+ ref={(element) =>
+ notifyElementOnMount(registry.registerMessage, 'reply', element)
+ }
+ >
+ Reply
+ </div>
+ }
+ >
+ <button
+ style={{ height: '32px' }}
+ ref={(element) => notifyElementOnMount(mounted, 'thread', element)}
+ >
+ Expand
+ </button>
+ </Show>
+ ));
+ expect(mounted).toHaveBeenCalledOnce();
+ expect(registry.elements.disclosures.get('thread')).toBe(
+ view.getByText('Expand')
+ );
+ expect(onChange).toHaveBeenCalledTimes(1);
+ setExpanded(true);
+ expect(registry.elements.disclosures.has('thread')).toBe(false);
+ expect(registry.elements.messages.get('reply')).toBe(view.getByText('Reply'));
+ expect(onChange).toHaveBeenCalledTimes(3);
+ setExpanded(false);
+ expect(registry.elements.messages.has('reply')).toBe(false);
+ expect(registry.elements.disclosures.get('thread')).toBe(
+ view.getByText('Expand')
+ );
+ view.unmount();
+ expect(registry.elements.messages.size).toBe(0);
+ expect(registry.elements.disclosures.size).toBe(0);
+});
+
+it('does not let a stale row cleanup unregister its replacement', () => {
+ const onChange = vi.fn();
+ const registry = createUnreadDestinationRegistry(onChange);
+ const first = document.createElement('div');
+ const replacement = document.createElement('div');
+ const removeFirst = registry.registerMessage('reply', first);
+ const removeReplacement = registry.registerMessage('reply', replacement);
+ onChange.mockClear();
+ removeFirst();
+ expect(registry.elements.messages.get('reply')).toBe(replacement);
+ expect(onChange).not.toHaveBeenCalled();
+ removeReplacement();
+ expect(registry.elements.messages.has('reply')).toBe(false);
+ expect(onChange).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx b/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
index db9f2d82d5..f933e96e37 100644
--- a/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
+++ b/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
@@ -74,6 +74,7 @@ function setup(followOnAppend = true) {
Array.from({ length: 20 }, (_, index) => String(index))
);
const paginate = vi.fn();
+ const onScroll = vi.fn();
let navigation: ThreadListNavigation | undefined;
const { container } = render(() => (
<ThreadList
@@ -83,6 +84,7 @@ function setup(followOnAppend = true) {
navigation = value;
}}
onScrollNearTop={paginate}
+ onScroll={onScroll}
>
{({ id }) => <div>{id}</div>}
</ThreadList>
@@ -99,7 +101,14 @@ function setup(followOnAppend = true) {
...previous,
]);
};
- return { element, paginate, prepend, setKeys, navigation: () => navigation };
+ return {
+ element,
+ paginate,
+ prepend,
+ setKeys,
+ onScroll,
+ navigation: () => navigation,
+ };
}
describe('history loading ahead of scrolling', () => {
@@ -237,3 +246,22 @@ describe('server acknowledgement scroll anchoring', () => {
expect(f.element.scrollTop).toBe(before);
});
});
+
+it('coalesces explicit destination changes into a post-render layout notification', async () => {
+ const f = setup();
+ await waitFor(() => expect(f.navigation()).toBeDefined());
+ await new Promise((resolve) => queueMicrotask(() => resolve(undefined)));
+ f.onScroll.mockClear();
+ const before = f.element.scrollTop;
+ f.navigation()?.requestLayoutUpdate();
+ f.navigation()?.requestLayoutUpdate();
+ expect(f.onScroll).not.toHaveBeenCalled();
+ await new Promise((resolve) => queueMicrotask(() => resolve(undefined)));
+ expect(f.onScroll).toHaveBeenCalledOnce();
+ expect(f.element.scrollTop).toBe(before);
+ cleanup();
+ f.onScroll.mockClear();
+ f.navigation()?.requestLayoutUpdate();
+ await new Promise((resolve) => queueMicrotask(() => resolve(undefined)));
+ expect(f.onScroll).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/channel/Channel/tests/unread-thread-navigation.test.ts b/apps/web/src/features/channel/Channel/tests/unread-thread-navigation.test.ts
index 690413a2c0..f9e60f7607 100644
--- a/apps/web/src/features/channel/Channel/tests/unread-thread-navigation.test.ts
+++ b/apps/web/src/features/channel/Channel/tests/unread-thread-navigation.test.ts
@@ -1,6 +1,8 @@
import type { UnifiedNotification } from '@notifications/types';
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createUnreadDestinationRegistry } from '../create-unread-destination-registry';
import {
+ unreadDestinationPositions,
unreadNotificationChip,
unreadThreads,
} from '../unread-thread-navigation';
@@ -57,6 +59,7 @@ describe('channel unread notification navigation', () => {
{
threadId: 'old',
messageId: 'third',
+ messageIds: ['third', 'second', 'first'],
createdAt: '2026-09-01T14:00:00Z',
},
]);
@@ -144,17 +147,49 @@ describe('channel unread notification navigation', () => {
it('uses measured reply position within a tall thread and hides for a visible message', () => {
const threads = unreadThreads([reply('a', 'middle')]);
expect(
- unreadNotificationChip(threads, positions, visible, 'above')?.direction
+ unreadNotificationChip(
+ threads,
+ positions,
+ visible,
+ new Map([['a', 'above']])
+ )?.direction
).toBe('above');
expect(
- unreadNotificationChip(threads, positions, visible, 'below')?.direction
+ unreadNotificationChip(
+ threads,
+ positions,
+ visible,
+ new Map([['a', 'below']])
+ )?.direction
).toBe('below');
expect(
- unreadNotificationChip(threads, positions, visible, 'visible')
+ unreadNotificationChip(
+ threads,
+ positions,
+ visible,
+ new Map([['a', 'visible']])
+ )
+ ).toBeUndefined();
+ expect(unreadNotificationChip(threads, positions, visible)).toBeUndefined();
+ });
+
+ it('counts unloaded offscreen threads without resolving every parent', () => {
+ const threads = unreadThreads([
+ reply('a', 'old', 14),
+ reply('b', 'unloaded', 12),
+ ]);
+ expect(unreadNotificationChip(threads, positions, visible)).toMatchObject({
+ count: 2,
+ direction: 'above',
+ thread: { messageId: 'a' },
+ });
+ expect(
+ unreadNotificationChip(
+ unreadThreads([reply('a', 'old', 12), reply('b', 'unloaded', 14)]),
+ positions,
+ visible
+ )
).toBeUndefined();
- expect(unreadNotificationChip(threads, positions, visible)?.direction).toBe(
- 'below'
- );
});
it('waits for layout and an unloaded parent position instead of guessing from reply time', () => {
@@ -164,4 +199,123 @@ describe('channel unread notification navigation', () => {
).toBeUndefined();
expect(unreadNotificationChip(threads, new Map(), visible)).toBeUndefined();
});
+ it('hands off a visible collapsed thread to its badge and targets another offscreen thread', () => {
+ const threads = unreadThreads([
+ reply('a', 'middle', 14),
+ reply('b', 'old', 13),
+ reply('c', 'new', 12),
+ ]);
+ const destinations = new Map([['a', 'visible' as const]]);
+ expect(
+ unreadNotificationChip(threads, positions, visible, destinations)
+ ).toMatchObject({
+ count: 2,
+ direction: 'above',
+ thread: { messageId: 'b' },
+ });
+ expect(
+ unreadNotificationChip(
+ threads.slice(0, 1),
+ positions,
+ visible,
+ destinations
+ )
+ ).toBeUndefined();
+ // Visibility changes the navigation affordance, never the underlying unread records.
+ expect(threads).toHaveLength(3);
+ });
+
+ it('keeps a thread reachable when its newest unread reply is visible but an older one is above', () => {
+ const threads = unreadThreads([
+ reply('newest', 'middle', 14),
+ reply('older', 'middle', 13),
+ reply('oldest', 'middle', 12),
+ ]);
+ expect(
+ unreadNotificationChip(
+ threads,
+ positions,
+ visible,
+ new Map([
+ ['newest', 'visible'],
+ ['older', 'above'],
+ ['oldest', 'above'],
+ ])
+ )
+ ).toMatchObject({
+ count: 1,
+ direction: 'above',
+ thread: { messageId: 'older' },
+ });
+ });
+
+ it('does not guess a direction for an unmeasured destination anywhere within the visible range', () => {
+ const threads = unreadThreads([reply('a', 'middle')]);
+ expect(
+ unreadNotificationChip(threads, positions, { first: 'old', last: 'new' })
+ ).toBeUndefined();
+ });
+});
+
+describe('unread destination geometry', () => {
+ afterEach(() => document.body.replaceChildren());
+ function fixture() {
+ const registry = createUnreadDestinationRegistry(() => {});
+ const viewport = document.createElement('div');
+ document.body.append(viewport);
+ viewport.getBoundingClientRect = () => new DOMRect(0, 100, 500, 400);
+ const add = (
+ kind: 'message' | 'disclosure',
+ id: string,
+ top: number,
+ height = 32
+ ) => {
+ const element = document.createElement('button');
+ element.getBoundingClientRect = () => new DOMRect(0, top, 100, height);
+ viewport.append(element);
+ if (kind === 'message') registry.registerMessage(id, element);
+ else registry.registerDisclosure(id, element);
+ return element;
+ };
+ const threads = unreadThreads([reply('a', 'middle')]);
+ const measure = () =>
+ unreadDestinationPositions(threads, registry.elements, viewport, {
+ start: 20,
+ end: 80,
+ });
+ return { add, measure };
+ }
+
+ it('uses the visible show-replies control for a hidden unread reply at the channel bottom', () => {
+ const { add, measure } = fixture();
+ add('message', 'middle', 50);
+ const disclosure = add('disclosure', 'middle', 350);
+ expect(measure().get('a')).toBe('visible');
+ disclosure.getBoundingClientRect = () => new DOMRect(0, 80, 100, 32);
+ expect(measure().get('a')).toBe('above');
+ disclosure.getBoundingClientRect = () => new DOMRect(0, 110, 100, 32);
+ expect(measure().get('a')).toBe('above');
+ disclosure.getBoundingClientRect = () => new DOMRect(0, 410, 100, 32);
+ expect(measure().get('a')).toBe('below');
+ disclosure.getBoundingClientRect = () => new DOMRect(0, 430, 100, 32);
+ expect(measure().get('a')).toBe('below');
+ });
+
+ it('uses a rendered reply rather than its thread disclosure, including after expansion', () => {
+ const { add, measure } = fixture();
+ const disclosure = add('disclosure', 'middle', 350);
+ const message = add('message', 'a', 50);
+ expect(measure().get('a')).toBe('above');
+ disclosure.remove();
+ expect(measure().get('a')).toBe('above');
+ message.getBoundingClientRect = () => new DOMRect(0, 200, 100, 32);
+ expect(measure().get('a')).toBe('visible');
+ });
+
+ it('waits for a destination to mount or obtain layout', () => {
+ const { add, measure } = fixture();
+ expect(measure().has('a')).toBe(false);
+ add('message', 'a', 0, 0);
+ expect(measure().has('a')).toBe(false);
+ });
});
diff --git a/apps/web/src/features/channel/Channel/unread-thread-navigation.ts b/apps/web/src/features/channel/Channel/unread-thread-navigation.ts
index 98c6b60df2..8bc6ffec4e 100644
--- a/apps/web/src/features/channel/Channel/unread-thread-navigation.ts
+++ b/apps/web/src/features/channel/Channel/unread-thread-navigation.ts
@@ -1,4 +1,5 @@
import type { UnifiedNotification } from '@notifications/types';
+import type { UnreadDestinationElements } from './create-unread-destination-registry';
export type UnreadThread = {
threadId: string;
@@ -7,17 +8,24 @@ export type UnreadThread = {
createdAt: string;
};
+export type UnreadThreadGroup = UnreadThread & { messageIds: string[] };
+
/** Unlike Inbox display stacks, every parent message is its own stack here. */
export function unreadThreads(
notifications: readonly UnifiedNotification[]
-): UnreadThread[] {
- const threads = new Map<string, UnreadThread>();
- for (const notification of notifications) {
- if (
- notification.state !== 'unseen' ||
- notification.entity_type !== 'channel'
+): UnreadThreadGroup[] {
+ const threads = new Map<string, UnreadThreadGroup>();
+ for (const notification of notifications
+ .filter(
+ (notification) =>
+ notification.state === 'unseen' &&
+ notification.entity_type === 'channel'
)
- continue;
+ .sort(
+ (a, b) =>
+ Date.parse(b.created_at) - Date.parse(a.created_at) ||
+ b.id.localeCompare(a.id)
+ )) {
const metadata = notification.notification_metadata;
if (
metadata.tag !== 'channel_message_send' &&
@@ -32,13 +40,14 @@ export function unreadThreads(
('threadId' in metadata.content && metadata.content.threadId) ||
messageId;
const previous = threads.get(threadId);
- if (
- !previous ||
- Date.parse(notification.created_at) > Date.parse(previous.createdAt)
- ) {
+ if (previous) {
+ if (!previous.messageIds.includes(messageId))
+ previous.messageIds.push(messageId);
+ } else {
threads.set(threadId, {
threadId,
messageId,
+ messageIds: [messageId],
createdAt: notification.created_at,
});
}
@@ -59,28 +68,84 @@ export type UnreadNotificationChip = {
direction: 'above' | 'below';
};
-/** Target recency and placement are separate: a new reply can be far above. */
+export type UnreadDestinationPosition = 'above' | 'below' | 'visible';
+
+function compareThreads(a: ThreadPosition, b: ThreadPosition) {
+ return (
+ Date.parse(a.created_at) - Date.parse(b.created_at) ||
+ a.id.localeCompare(b.id)
+ );
+}
+
+/** Count only offscreen threads; keep newest-first navigation among those left. */
export function unreadNotificationChip(
- threads: readonly UnreadThread[],
+ threads: readonly UnreadThreadGroup[],
positions: ReadonlyMap<string, ThreadPosition>,
visible: VisibleThreadRange | undefined,
- targetPosition?: 'above' | 'below' | 'visible'
+ destinations: ReadonlyMap<string, UnreadDestinationPosition> = new Map()
): UnreadNotificationChip | undefined {
- const thread = threads[0];
- if (!thread || !visible || targetPosition === 'visible') return;
- if (targetPosition)
- return { thread, count: threads.length, direction: targetPosition };
- const root = positions.get(thread.threadId);
- const first = positions.get(visible.first);
- if (!root || !first) return;
- const order =
- Date.parse(root.created_at) - Date.parse(first.created_at) ||
- root.id.localeCompare(first.id);
- // A collapsed reply in a visible thread lies below its parent. Clicking opens
- // it; merely seeing the parent must not clear that thread's unread count.
- return {
- thread,
- count: threads.length,
- direction: order < 0 ? 'above' : 'below',
- };
+ if (!visible) return;
+ let target: UnreadThread | undefined;
+ let targetDirection: 'above' | 'below' | undefined;
+ let count = 0;
+ for (const thread of threads) {
+ const root = positions.get(thread.threadId);
+ const first = positions.get(visible.first);
+ const last = positions.get(visible.last);
+ const fallback =
+ root && first && last
+ ? compareThreads(root, first) < 0
+ ? 'above'
+ : compareThreads(root, last) > 0
+ ? 'below'
+ : undefined
+ : undefined;
+ for (const messageId of thread.messageIds) {
+ const direction = destinations.get(messageId) ?? fallback;
+ // A mounted thread with no destination yet is waiting for layout/data.
+ // Never guess that a hidden reply in a visible row is below the viewport.
+ if (direction === 'visible' || (!direction && root)) continue;
+ // An unloaded root is offscreen, but its position must resolve before
+ // showing an arrow. It still contributes to the offscreen thread count.
+ count += 1;
+ if (!target) {
+ target = { ...thread, messageId };
+ targetDirection = direction;
+ }
+ break;
+ }
+ }
+ if (target && targetDirection)
+ return { thread: target, count, direction: targetDirection };
+}
+
+/** A hidden reply is reached through its collapsed thread's disclosure control. */
+export function unreadDestinationPositions(
+ threads: readonly UnreadThreadGroup[],
+ elements: UnreadDestinationElements,
+ viewport: Element,
+ insets: { start: number; end: number }
+): ReadonlyMap<string, UnreadDestinationPosition> {
+ const positions = new Map<string, UnreadDestinationPosition>();
+ const bounds = viewport.getBoundingClientRect();
+ const { messages, disclosures } = elements;
+ for (const thread of threads) {
+ const disclosure = disclosures.get(thread.threadId);
+ for (const messageId of thread.messageIds) {
+ const message = messages.get(messageId);
+ const destination =
+ message ?? (messageId !== thread.threadId ? disclosure : null);
+ if (!destination?.isConnected) continue;
+ const rect = destination.getBoundingClientRect();
+ if (rect.height === 0) continue;
+ const top = bounds.top + insets.start;
+ const bottom = bounds.bottom - insets.end;
+ // Keep the reminder until the whole disclosure (including its badge)
+ // clears sticky headers/composers. Messages retain overlap visibility.
+ const above = message ? rect.bottom <= top : rect.top < top;
+ const below = message ? rect.top >= bottom : rect.bottom > bottom;
+ positions.set(messageId, above ? 'above' : below ? 'below' : 'visible');
+ }
+ }
+ return positions;
}
diff --git a/apps/web/src/features/channel/Thread/ChannelThread.tsx b/apps/web/src/features/channel/Thread/ChannelThread.tsx
index ccf84930f6..ad09193dc2 100644
--- a/apps/web/src/features/channel/Thread/ChannelThread.tsx
+++ b/apps/web/src/features/channel/Thread/ChannelThread.tsx
@@ -23,6 +23,7 @@ import { createTargetReplyScroller } from './create-target-reply-scroller';
import { createThreadHotkeys } from './create-thread-hotkeys';
import { createThreadRepliesFetchGate } from './create-thread-replies-fetch-gate';
import { createThreadReplyView } from './create-thread-reply-view';
+import { notifyElementOnMount } from './message-element-lifecycle';
import { Thread } from './Thread';
import type { ThreadReplyListHandle } from './ThreadReplyList';
import { ThreadTypingIndicator } from './ThreadTypingIndicator';
@@ -180,6 +181,12 @@ export function ChannelThread(props: ThreadProps) {
activeReplies()
.slice(visibleReplyCount())
.some((reply: EntityMessage) => props.isNewMessage?.(reply));
+ const collapsedRepliesHaveUnreadNotifications = () =>
+ props.unreadMessageIds?.some(
+ (id) =>
+ id !== props.data().id &&
+ !displayReplies().some((reply) => reply.id === id)
+ ) ?? false;
const collapsedReplyUsers = () =>
getUniqueReplyUserIds(activeReplies().slice(visibleReplyCount()));
const collapsedLatestReplyAt = () =>
@@ -306,7 +313,16 @@ export function ChannelThread(props: ThreadProps) {
top (fed by the run's pass-through rails) and a fork node on
the spine marks which message the thread replies to. Plain
messages carry no rail. */}
- <div class="relative">
+ <div
+ class="relative"
+ ref={(element) =>
+ notifyElementOnMount(
+ props.onMessageMount,
+ props.data().id,
+ element
+ )
+ }
+ >
<Thread.RootRail
visible={rootRailVisible()}
grouped={props.listMeta?.isGroupedWithPrevious}
@@ -358,6 +374,7 @@ export function ChannelThread(props: ThreadProps) {
parent={props.parent()}
threadId={props.data().id}
replies={displayReplies()}
+ onMessageMount={props.onMessageMount}
getMessageActions={props.getMessageActions}
inputMode={props.inputMode}
messageEditor={props.messageEditor}
@@ -439,6 +456,14 @@ export function ChannelThread(props: ThreadProps) {
<Thread.ActionsFooter>
<Show when={shouldShowCollapsedIndicator()}>
<Thread.CollapsedIndicator
+ ref={(element) =>
+ notifyElementOnMount(
+ props.onDisclosureMount,
+ props.data().id,
+ element
+ )
+ }
+ hasUnreadNotifications={collapsedRepliesHaveUnreadNotifications()}
collapsedRepliesCount={collapsedRepliesCount()}
participants={collapsedReplyUsers()}
latestReplyAt={collapsedLatestReplyAt()}
diff --git a/apps/web/src/features/channel/Thread/ThreadCollapsedIndicator.tsx b/apps/web/src/features/channel/Thread/ThreadCollapsedIndicator.tsx
index 33cc85e9d5..05c4c45afb 100644
--- a/apps/web/src/features/channel/Thread/ThreadCollapsedIndicator.tsx
+++ b/apps/web/src/features/channel/Thread/ThreadCollapsedIndicator.tsx
@@ -11,6 +11,7 @@ type ThreadCollapsedIndicatorProps =
participants: string[];
latestReplyAt?: string;
hasNewMessages?: boolean;
+ hasUnreadNotifications?: boolean;
};
const MAX_VISIBLE_PARTICIPANTS = 4;
@@ -22,6 +23,7 @@ export function ThreadCollapsedIndicator(props: ThreadCollapsedIndicatorProps) {
'participants',
'latestReplyAt',
'hasNewMessages',
+ 'hasUnreadNotifications',
]);
const visibleParticipants = () =>
local.participants.slice(0, MAX_VISIBLE_PARTICIPANTS);
@@ -34,7 +36,9 @@ export function ThreadCollapsedIndicator(props: ThreadCollapsedIndicatorProps) {
title="Expand thread"
class={cn(
'flex items-center gap-2 text-xs w-fit h-8 touch:min-h-(--user-icon-width) border hover:bg-hover py-1 pr-2 pl-1.5 mb-2 select-none outline-none focus-visible:bg-active rounded-full',
- local.hasNewMessages ? 'border-accent/40' : 'border-thread-rail',
+ local.hasNewMessages || local.hasUnreadNotifications
+ ? 'border-accent/40'
+ : 'border-thread-rail',
local.class
)}
{...rest}
@@ -65,12 +69,18 @@ export function ThreadCollapsedIndicator(props: ThreadCollapsedIndicatorProps) {
</Show>
</div>
</Show>
- <Show when={local.hasNewMessages}>
- <span class="size-1.5 shrink-0 rounded-full bg-accent" />
+ <Show when={local.hasNewMessages || local.hasUnreadNotifications}>
+ <span
+ class="size-1.5 shrink-0 rounded-full bg-accent"
+ aria-hidden="true"
+ />
</Show>
<span class="text-accent font-medium whitespace-nowrap">
{getThreadReplyCountLabel(local.collapsedRepliesCount)}
</span>
+ <Show when={local.hasUnreadNotifications}>
+ <span class="sr-only">Unread</span>
+ </Show>
<Show when={local.latestReplyAt}>
{(latestReplyAt) => (
<span class="text-ink-muted whitespace-nowrap @max-[40rem]:hidden">
diff --git a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
index cef40ae43d..db39a49abd 100644
--- a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
+++ b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
@@ -19,6 +19,10 @@ import {
type MessageData,
} from '../Message';
import { createTargetReplyScroller } from './create-target-reply-scroller';
+import {
+ type MessageElementMount,
+ notifyElementOnMount,
+} from './message-element-lifecycle';
import { buildThreadReplyListMeta } from './reply-list-meta';
import { ThreadReplyMonorail } from './ThreadReplyMonorail';
import { ThreadReplyRail } from './ThreadReplyRail';
@@ -36,6 +40,7 @@ export function ThreadReplyList(props: {
getMessageActions?: (message: MessageData) => MessageActions | undefined;
messageEditor?: MessageEditor;
isNewMessage?: (message: NewMessageCheckable) => boolean;
+ onMessageMount?: MessageElementMount;
onReady?: (handle: ThreadReplyListHandle) => void;
positionTarget?: (
threadRow: HTMLElement,
@@ -96,6 +101,7 @@ export function ThreadReplyList(props: {
<div
ref={(element) => {
replyElements.set(id, element);
+ notifyElementOnMount(props.onMessageMount, id, element);
}}
class="relative"
>
diff --git a/apps/web/src/features/channel/Thread/create-thread-reply-view.ts b/apps/web/src/features/channel/Thread/create-thread-reply-view.ts
index 993d3fa282..ca3b4a5b2a 100644
--- a/apps/web/src/features/channel/Thread/create-thread-reply-view.ts
+++ b/apps/web/src/features/channel/Thread/create-thread-reply-view.ts
@@ -1,16 +1,17 @@
import { type Accessor, createMemo } from 'solid-js';
-import type { GroupableMessage } from '../Channel/message-grouping-meta';
-import { getVisibleReplyCount } from './utils/thread-reply-indicator-helpers';
+
+// Match the timeline's three-reply preview. Live updates append to that cache
+// even when older replies are missing, so it is not a complete set of groups.
+const COLLAPSED_REPLY_PREVIEW_LIMIT = 3;
/** Full reply data may arrive independently of the user's expansion choice. */
-export function createThreadReplyView<T extends GroupableMessage>(options: {
+export function createThreadReplyView<T>(options: {
preview: Accessor<T[]>;
loaded: Accessor<T[] | undefined>;
isExpanded: Accessor<boolean>;
}) {
- const previewCount = createMemo(() =>
- getVisibleReplyCount(options.preview())
- );
+ const previewCount = () =>
+ Math.min(options.preview().length, COLLAPSED_REPLY_PREVIEW_LIMIT);
const activeReplies = () => options.loaded() ?? options.preview();
const displayReplies = createMemo(() =>
options.isExpanded()
diff --git a/apps/web/src/features/channel/Thread/message-element-lifecycle.ts b/apps/web/src/features/channel/Thread/message-element-lifecycle.ts
new file mode 100644
index 0000000000..12c853e701
--- /dev/null
+++ b/apps/web/src/features/channel/Thread/message-element-lifecycle.ts
@@ -0,0 +1,21 @@
+import { onCleanup, onMount } from 'solid-js';
+
+/** Called once connected; the returned cleanup runs when the row is disposed. */
+export type MessageElementMount = (
+ id: string,
+ element: HTMLElement
+) => (() => void) | void;
+
+/** Attach from a row's ref, which can run before the element is connected. */
+export function notifyElementOnMount(
+ onElementMount: MessageElementMount | undefined,
+ id: string,
+ element: HTMLElement
+) {
+ if (!onElementMount) return;
+ let cleanup: (() => void) | void;
+ onMount(() => {
+ cleanup = onElementMount(id, element);
+ });
+ onCleanup(() => cleanup?.());
+}
diff --git a/apps/web/src/features/channel/Thread/tests/create-thread-reply-view.test.ts b/apps/web/src/features/channel/Thread/tests/create-thread-reply-view.test.ts
index e4f38e1216..8670128916 100644
--- a/apps/web/src/features/channel/Thread/tests/create-thread-reply-view.test.ts
+++ b/apps/web/src/features/channel/Thread/tests/create-thread-reply-view.test.ts
@@ -1,3 +1,5 @@
+import { insertReplyIntoThreadPreview } from '@queries/messages/thread-preview';
+import type { Message } from '@service-storage/messages';
import { createRoot, createSignal } from 'solid-js';
import { describe, expect, it } from 'vitest';
import type { GroupableMessage } from '../../Channel/message-grouping-meta';
@@ -64,3 +66,99 @@ describe('thread preview and explicit expansion', () => {
}
});
});
+
+describe('collapse after live thread replies', () => {
+ const liveReplies: Message[] = Array.from({ length: 12 }, (_, index) => ({
+ id: `live-reply-${index}`,
+ parent: { type: 'channel', id: 'channel' },
+ thread_id: 'root',
+ sender_id: 'sender',
+ content: `Reply ${index + 1}`,
+ created_at: new Date(Date.UTC(2026, 8, 24, 9, index)).toISOString(),
+ updated_at: new Date(Date.UTC(2026, 8, 24, 9, index)).toISOString(),
+ mentions: [],
+ attachments: [],
+ reactions: [],
+ }));
+
+ function liveFixture(loadedInitially: boolean) {
+ return createRoot((dispose) => {
+ const [thread, setThread] = createSignal({
+ preview: liveReplies.slice(0, 3),
+ reply_count: 10,
+ });
+ const [loaded, setLoaded] = createSignal<Message[] | undefined>(
+ loadedInitially ? liveReplies.slice(0, 10) : undefined
+ );
+ const [isExpanded, setExpanded] = createSignal(false);
+ const view = createThreadReplyView({
+ preview: () => thread().preview,
+ loaded,
+ isExpanded,
+ });
+ const receive = (reply: Message) => {
+ setThread((current) => insertReplyIntoThreadPreview(current, reply));
+ setLoaded((current) => (current ? [...current, reply] : current));
+ };
+ return { ...view, dispose, receive, setExpanded, setLoaded, thread };
+ });
+ }
+
+ it('returns to the original preview after replies arrive while expanded', () => {
+ const view = liveFixture(true);
+ try {
+ view.setExpanded(true);
+ view.receive(liveReplies[10]);
+ view.receive(liveReplies[11]);
+ expect(view.displayReplies()).toHaveLength(12);
+ view.setExpanded(false);
+ expect(view.displayReplies().map((reply) => reply.id)).toEqual(
+ liveReplies.slice(0, 3).map((reply) => reply.id)
+ );
+ expect(view.visibleReplyCount()).toBe(3);
+ expect(view.thread().reply_count - view.visibleReplyCount()).toBe(9);
+ view.setExpanded(true);
+ expect(view.displayReplies()).toEqual(liveReplies);
+ } finally {
+ view.dispose();
+ }
+ });
+
+ it('keeps incoming replies hidden while collapsed, including before the full thread loads', () => {
+ const view = liveFixture(false);
+ try {
+ view.receive(liveReplies[10]);
+ expect(view.displayReplies()).toEqual(liveReplies.slice(0, 3));
+ // The live cache must retain the reply for a fetch racing its arrival.
+ expect(view.thread().preview.at(-1)).toEqual(liveReplies[10]);
+ view.setLoaded(liveReplies.slice(0, 11));
+ expect(view.displayReplies()).toEqual(liveReplies.slice(0, 3));
+ view.setExpanded(true);
+ expect(view.displayReplies()).toEqual(liveReplies.slice(0, 11));
+ } finally {
+ view.dispose();
+ }
+ });
+
+ it('does not reveal live replies after the row remounts from the updated preview cache', () => {
+ const updated = insertReplyIntoThreadPreview(
+ {
+ preview: liveReplies.slice(0, 3),
+ reply_count: 10,
+ },
+ liveReplies[10]
+ );
+ createRoot((dispose) => {
+ try {
+ const view = createThreadReplyView({
+ preview: () => updated.preview,
+ loaded: () => liveReplies.slice(0, 11),
+ isExpanded: () => false,
+ });
+ expect(view.displayReplies()).toEqual(liveReplies.slice(0, 3));
+ } finally {
+ dispose();
+ }
+ });
+ });
+});
diff --git a/apps/web/src/features/channel/Thread/types.ts b/apps/web/src/features/channel/Thread/types.ts
index 416317aeb2..7e4812f3c6 100644
--- a/apps/web/src/features/channel/Thread/types.ts
+++ b/apps/web/src/features/channel/Thread/types.ts
@@ -9,6 +9,7 @@ import type {
MessageData,
} from '../Message';
import type { FocusRequest } from './focus-request';
+import type { MessageElementMount } from './message-element-lifecycle';
export type ThreadActions = {
onDismissNewMessages?: () => void;
@@ -66,6 +67,10 @@ export type ThreadProps = {
isFindBarOpen: Accessor<boolean>;
/** The unified input's reply binding */
unifiedReplyTarget?: { threadId: string; replyId?: string };
+ /** Exact unread notification targets, including replies not yet loaded. */
+ unreadMessageIds?: readonly string[];
+ onMessageMount?: MessageElementMount;
+ onDisclosureMount?: MessageElementMount;
isNewMessage?: (reply: NewMessageCheckable) => boolean;
selectedMessageId?: Accessor<string | undefined>;
onSelectMessage?: (messageId: string) => void;
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 234fa93ffa..85ec31258c 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -43,17 +43,21 @@ See the [rollout/recovery gates](../SLACK_ARCHIVE_IMPORT_RUNBOOK.md).
## Collapsed reply chains
-Collapsed threads show the first three complete message groups. Consecutive
-replies from the same sender within the five-minute avatar-grouping window count
-as one group, so a run of short messages stays together. A different sender or a
-longer gap starts another group; returning to an earlier sender also starts a new
-group. Deleted replies and agent replies triggered by different users keep the
-same group boundaries as their avatar display.
-
-The `N more replies` control counts individual hidden replies and expands the
-whole thread. Check a thread with more than three consecutive replies from one
-sender (all remain visible), then one with four groups (the first three groups
-remain visible in full). Standalone thread previews follow the same rule.
+Collapsed channel threads show up to the first three replies from the timeline
+preview. New replies arriving while the channel is open must not enlarge that
+collapsed preview, even when they share a sender with earlier replies. Expanding
+shows the full thread; collapsing returns to the three-reply preview. The
+`N more replies` control counts individual hidden replies.
+
+Check a long thread that receives replies while expanded, then collapse it:
+new replies must be hidden and included in the hidden count. Repeat while it is
+already collapsed, while its full replies are loading, and after scrolling the
+row out of view and back. Expanding again must retain every incoming reply.
+
+Standalone thread previews show the first three complete message groups instead.
+Consecutive replies from the same sender within the five-minute avatar-grouping
+window count as one group. Different senders, longer gaps, deleted replies, and
+agent replies triggered by different users preserve their avatar group boundaries.
Channel timelines show system updates alongside messages: participant additions
and removals, renames, profile picture changes, and completed calls with their
@@ -409,20 +413,28 @@ A newer message navigation cancels a pending jump to latest. Scrolling manually
or choosing another destination also cancels the initial target's delayed fallback.
A touch tap leaves pending navigation intact; a vertical finger drag cancels it.
-The **Unread notification** chip points to the most recent unread notification.
-There is only one chip: above the list for a target above the viewport, or below
-for a target below it. The number counts distinct parent-message threads across
-the channel, not individual notifications. Three replies and a mention in the
-same thread count as one; reactions do not count. Clicking jumps to the target
-and expands its thread. A collapsed unread reply in a visible thread is reachable
-with the bottom chip. A visible target has no chip. Notifications are marked seen
-when their message mounts, including virtualized overscan. Collapsed replies that
-are not rendered remain unread.
-The count and target update as notifications arrive or become seen. Check an old
-thread receiving a new reply while a newer thread is also unread: the chip must
-point upward to the old thread, still show two stacks, and preserve the scroll
-position until clicked. Check a target below the viewport, loading an unloaded
-parent, and switching channels while notifications are loading. Loading this
+The **Unread notification** chip navigates unread threads whose destinations are
+outside the viewport. A collapsed thread with hidden unread replies shows a
+dot and accent border on its show-replies control. While that control is visible,
+those hidden replies do not contribute to the floating chip; scrolling it out of
+view restores the chip, pointing toward the control. Expanded threads use actual
+unread message positions. A visible unread reply does not hide other offscreen
+unread replies in the same thread.
+There is one chip, targeting the most recently active eligible unread thread.
+Its count includes only distinct offscreen unread threads, not notifications.
+Three replies and a mention in one thread count as one; reactions do not count.
+Clicking the chip expands the target thread and reveals an unread message.
+Scrolling an inline indicator into view does not expand the thread or mark its
+hidden replies seen. Notifications are still marked seen when their message mounts,
+including virtualized overscan. Collapsed replies that are not rendered remain
+unread.
+Check the last channel message with a long collapsed unread thread: at the bottom,
+the inline dot and accent border should be visible without a downward chip. With
+another unread thread above, an upward chip should remain and count only that offscreen thread.
+Scroll the disclosure out of view and back, expand and manually collapse the
+thread, and check composer/mobile insets. The indicator must appear even before
+full reply data loads. Check a target below the viewport, an unloaded parent, live
+notifications, and switching channels while notifications load. Loading this
channel's notification edge must not delay its messages or activate the global
GraphQL notification feed.