Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channels): keep offscreen reply notifications unread (#9172)
gbirmancae24fbf4b9a
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex b83300d9fd..43334a4826 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -239,6 +239,15 @@ on desktop and mobile. Tool results render through`lib/core/component/AI/component/tool/Canvas.tsx`; edits arrive through live sync.The shared plain-text Lexical codec is `packages/lexical-core/canvas-text.ts`.+## Message notification reads++Gate automatic message notification reads on the actual message element+intersecting the visible scroll area, excluding floating chrome and background+tabs. Share visibility observers per thread list, including standalone threads;+never treat virtualized overscan or a visible thread parent as seeing its replies.+The backend-free desktop/phone/tablet regression is+`bunx playwright test --config src/features/notifications/browser-test/playwright.config.ts`.+## Development PatternsRoute database row rename and delete through `renameDatabase` anddiff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsxindex 3a9b610b95..a39ce31e10 100644--- a/apps/web/src/features/channel/Channel/ThreadList.tsx+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx@@ -3,6 +3,7 @@ import {createScrollIntentTracker,type ScrollDirection,} from '@core/util/scroll-intent';+import { MessageReadVisibilityProvider } from '@notifications/components/MessageReadVisibility';import { Key } from '@solid-primitives/keyed';import { isIOS, isSafari } from '@solid-primitives/platform';import {@@ -619,7 +620,7 @@ export function ThreadList(props: ThreadListProps) {});return (- <>+ <MessageReadVisibilityProvider root={scrollEl} insets={insets}><divref={scrollRef}data-channel-scroll@@ -681,6 +682,6 @@ export function ThreadList(props: ThreadListProps) {scrollIntent.markUserIntent(delta > 0 ? 'down' : 'up');}}/>- </>+ </MessageReadVisibilityProvider>);}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.tsxindex 2330cd3922..aebad53d4d 100644--- 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@@ -1,12 +1,20 @@+import { MessageNotificationIndexContext } from '@notifications/components/MarkMessageNotifications';import {- MarkMessageNotifications,- MessageNotificationIndexContext,-} from '@notifications/components/MarkMessageNotifications';+ installMessageIntersectionObserver,+ ObservedMessage as MarkMessageNotifications,+} from '@notifications/tests/message-read-visibility';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 { afterEach, beforeEach, expect, it, vi } from 'vitest';++let intersect: ReturnType<typeof installMessageIntersectionObserver>;+beforeEach(() => {+ intersect = installMessageIntersectionObserver();+});+afterEach(() => vi.unstubAllGlobals());+import { notifyElementOnMount } from '../../Thread/message-element-lifecycle';import { ThreadCollapsedIndicator } from '../../Thread/ThreadCollapsedIndicator';import { createChannelUnreadNavigation } from '../create-channel-unread-navigation';@@ -121,11 +129,13 @@ it('shares unread lookups across mounted messages without rescanning history perexpect(bulkMarkAsRead).not.toHaveBeenCalled();setMessageIds(Array.from({ length: 50 }, (_, index) => `other-${index}`));- expect(view.container.querySelectorAll('span')).toHaveLength(50);+ expect(view.container.children).toHaveLength(50);expect(readMetadata).toHaveBeenCalledTimes(initialReads);expect(bulkMarkAsRead).not.toHaveBeenCalled();setMessageIds([...messageIds(), 'reply-12']);+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ intersect();await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());expect(bulkMarkAsRead).toHaveBeenCalledWith([reply]);expect(globalRead).not.toHaveBeenCalled();@@ -219,7 +229,7 @@ it('updates one chip live without suspending the channel or loading the global fexpect(globalRead).not.toHaveBeenCalled();});-it('hands off to the inline unread indicator, keeps other offscreen threads reachable, and only marks rendered replies seen', async () => {+it('hands off to the inline unread indicator, keeps other offscreen threads reachable, and only marks visible replies seen', async () => {const [records, setRecords] = createSignal<UnifiedNotification[]>([]);const [container, setContainer] = createSignal<HTMLDivElement>();const [expanded, setExpanded] = createSignal(false);@@ -365,6 +375,8 @@ it('hands off to the inline unread indicator, keeps other offscreen threads reac).toBe(true);expect(bulkMarkAsRead).not.toHaveBeenCalled();view.getByTitle('Expand thread').click();+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ intersect();await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());expect(bulkMarkAsRead).toHaveBeenCalledWith([notification('root-3', 14)]);expect(view.getByText('Unread reply content')).toBeTruthy();diff --git a/apps/web/src/features/channel/Thread/ChannelThread.tsx b/apps/web/src/features/channel/Thread/ChannelThread.tsxindex ad66800696..2e10c6dc5a 100644--- a/apps/web/src/features/channel/Thread/ChannelThread.tsx+++ b/apps/web/src/features/channel/Thread/ChannelThread.tsx@@ -4,6 +4,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { getDisplayName, tryMacroId } from '@core/user';import { thrownResultErrorHasCode } from '@core/util/result';import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';+import { MessageReadVisibilityProvider } from '@notifications/components/MessageReadVisibility';import { queryReadyGate } from '@queries/gate';import { useThreadRepliesQuery } from '@queries/messages/thread-replies';import type { Message as EntityMessage } from '@service-storage/messages';@@ -36,6 +37,7 @@ import {} from './utils/thread-reply-indicator-helpers';export function ChannelThread(props: ThreadProps) {+ const [messageElement, setMessageElement] = createSignal<HTMLDivElement>();const userId = useUserId();const replyUserId = () => userId() ?? props.data().sender_id;const macroId = () => tryMacroId(replyUserId());@@ -316,19 +318,21 @@ export function ChannelThread(props: ThreadProps) {messages carry no rail. */}<divclass="relative"- ref={(element) =>+ ref={(element) => {+ setMessageElement(element);notifyElementOnMount(props.onMessageMount,props.data().id,element- )- }+ );+ }}><Thread.RootRailvisible={rootRailVisible()}grouped={props.listMeta?.isGroupedWithPrevious}/><MarkMessageNotifications+ element={messageElement()}messageId={props.data().id}parent={props.parent()}>@@ -509,8 +513,10 @@ export function ChannelThread(props: ThreadProps) {function ThreadReadBoundary(props: ParentProps<{ available: boolean }>) {return (- <DebugSuspense name="ChannelThread.root">- <Show when={props.available}>{props.children}</Show>- </DebugSuspense>+ <MessageReadVisibilityProvider>+ <DebugSuspense name="ChannelThread.root">+ <Show when={props.available}>{props.children}</Show>+ </DebugSuspense>+ </MessageReadVisibilityProvider>);}diff --git a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx b/apps/web/src/features/channel/Thread/ThreadReplyList.tsxindex db39a49abd..062da197f6 100644--- a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx+++ b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx@@ -6,6 +6,7 @@ import type {import {type Accessor,createMemo,+ createSignal,For,onCleanup,onMount,@@ -88,6 +89,7 @@ export function ThreadReplyList(props: {return (<For each={[...repliesById().keys()]}>{(id) => {+ const [element, setElement] = createSignal<HTMLDivElement>();onCleanup(() => replyElements.delete(id));const replyMessage = () => ({...repliesById().get(id)!,@@ -100,6 +102,7 @@ export function ThreadReplyList(props: {return (<divref={(element) => {+ setElement(element);replyElements.set(id, element);notifyElementOnMount(props.onMessageMount, id, element);}}@@ -128,7 +131,11 @@ export function ThreadReplyList(props: {</Show></Show></Show>- <MarkMessageNotifications messageId={id} parent={props.parent}>+ <MarkMessageNotifications+ messageId={id}+ parent={props.parent}+ element={element()}+ ><ChannelMessageparent={props.parent}inputMode={props.inputMode}diff --git a/apps/web/src/features/notifications/browser-test/fixture.tsx b/apps/web/src/features/notifications/browser-test/fixture.tsxnew file mode 100644index 0000000000..caf3e4d01b--- /dev/null+++ b/apps/web/src/features/notifications/browser-test/fixture.tsx@@ -0,0 +1,158 @@+import { ThreadList } from '@channel/Channel/ThreadList';+import { createMemo, createSignal, For } from 'solid-js';+import { render } from 'solid-js/web';+import {+ MarkMessageNotifications,+ MessageNotificationIndexContext,+} from '../components/MarkMessageNotifications';+import { MessageReadVisibilityProvider } from '../components/MessageReadVisibility';+import { indexUnreadMessageNotifications } from '../unread-message-notifications';+import { addNotification, notifications } from './source';++function Message(props: { id: string }) {+ const [element, setElement] = createSignal<HTMLDivElement>();+ return (+ <div+ ref={setElement}+ data-message={props.id}+ style={{+ height: '96px',+ 'box-sizing': 'border-box',+ padding: '24px',+ 'border-bottom': '1px solid #ccc',+ }}+ >+ <MarkMessageNotifications+ messageId={props.id}+ parent={{ type: 'channel', id: 'channel-fixture' }}+ element={element()}+ >+ Reply {props.id}+ </MarkMessageNotifications>+ </div>+ );+}++function Fixture() {+ const mode = new URLSearchParams(location.search).get('mode');+ const [insets, setInsets] = createSignal({ start: 64, end: 96 });+ const [hidden, setHidden] = createSignal(false);+ const keys = Array.from({ length: 30 }, (_, index) => String(index));+ const index = createMemo(() =>+ indexUnreadMessageNotifications(notifications())+ );+ const notify = (id: string) => addNotification(id);+ return (+ <main+ style={{+ 'font-family': 'sans-serif',+ 'max-width': '700px',+ margin: '0 auto',+ }}+ >+ <h1>Reply notifications</h1>+ <div style={{ display: 'flex', gap: '8px', 'flex-wrap': 'wrap' }}>+ <button onClick={() => notify(mode === 'panel' ? '0' : '23')}>+ Notify offscreen reply+ </button>+ <button onClick={() => notify(mode === 'panel' ? '5' : '29')}>+ Notify covered reply+ </button>+ <button onClick={() => setInsets({ start: 0, end: 0 })}>+ Remove overlays+ </button>+ <button onClick={() => setHidden(!hidden())}>Toggle pane</button>+ <button+ onClick={() => {+ const scroller = document.querySelector('[data-channel-scroll]');+ if (scroller) scroller.scrollTop = scroller.scrollHeight;+ notify('23');+ }}+ >+ Scroll away and notify+ </button>+ </div>+ <ul aria-label="Notification states">+ <For each={notifications()}>+ {(n) => (+ <li+ data-notification={+ n.notification_metadata.tag === 'channel_message_reply'+ ? n.notification_metadata.content.messageId+ : ''+ }+ >+ {n.state === 'unseen' ? 'Unread' : 'Read'}+ </li>+ )}+ </For>+ </ul>+ <MessageNotificationIndexContext.Provider value={index}>+ <section+ style={{+ position: 'relative',+ height: '384px',+ display: hidden() ? 'none' : 'block',+ border: '1px solid #999',+ }}+ >+ {mode === 'panel' ? (+ <MessageReadVisibilityProvider>+ <div+ ref={(el) => {+ queueMicrotask(() => {+ el.scrollTop = 384;+ });+ }}+ data-channel-scroll+ style={{ height: '384px', overflow: 'auto' }}+ >+ <For each={keys}>{(id) => <Message id={id} />}</For>+ </div>+ </MessageReadVisibilityProvider>+ ) : (+ <ThreadList keys={() => keys} insets={insets()}>+ {({ id }) => <Message id={id} />}+ </ThreadList>+ )}+ {mode !== 'panel' && (+ <>+ <div+ aria-label="Header overlay"+ style={{+ position: 'absolute',+ top: 0,+ height: `${insets().start}px`,+ left: 0,+ right: 0,+ background: '#eee',+ 'pointer-events': 'none',+ }}+ >+ Header+ </div>+ <div+ aria-label="Composer overlay"+ style={{+ position: 'absolute',+ bottom: 0,+ height: `${insets().end}px`,+ left: 0,+ right: 0,+ background: '#eee',+ 'pointer-events': 'none',+ }}+ >+ Composer+ </div>+ </>+ )}+ </section>+ </MessageNotificationIndexContext.Provider>+ </main>+ );+}++const root = document.getElementById('root');+if (!root) throw new Error('Missing fixture root');+render(() => <Fixture />, root);diff --git a/apps/web/src/features/notifications/browser-test/index.html b/apps/web/src/features/notifications/browser-test/index.htmlnew file mode 100644index 0000000000..2579c5fbce--- /dev/null+++ b/apps/web/src/features/notifications/browser-test/index.html@@ -0,0 +1,2 @@+<!doctype html>+<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Message read visibility</title></head><body><div id="root"></div><script type="module" src="/fixture.tsx"></script></body></html>diff --git a/apps/web/src/features/notifications/browser-test/message-read.browser.e2e.ts b/apps/web/src/features/notifications/browser-test/message-read.browser.e2e.tsnew file mode 100644index 0000000000..93b2252c1f--- /dev/null+++ b/apps/web/src/features/notifications/browser-test/message-read.browser.e2e.ts@@ -0,0 +1,100 @@+import { expect, type Page, test } from '@playwright/test';++// Wait for the browser's observer delivery after layout, rather than a timer.+async function afterLayout(page: Page) {+ await page.evaluate(+ () =>+ new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))+ )+ );+}++test('overscanned replies stay unread until scrolled into the channel viewport', async ({+ page,+}, testInfo) => {+ await page.goto('/');+ const reply = page.locator('[data-message="23"]');+ await expect(reply).toBeAttached();+ await page.getByRole('button', { name: 'Notify offscreen reply' }).click();+ await afterLayout(page);+ await page.screenshot({ path: testInfo.outputPath('offscreen.png') });+ await expect(page.locator('[data-notification="23"]')).toHaveText('Unread');+ await reply.evaluate((el) => el.scrollIntoView({ block: 'center' }));+ await expect(page.locator('[data-notification="23"]')).toHaveText('Read');+ await page.screenshot({ path: testInfo.outputPath('visible.png') });+});++test('composer-covered replies and hidden panes do not clear notifications', async ({+ page,+}) => {+ await page.goto('/');+ await expect(page.locator('[data-message="29"]')).toBeAttached();+ // Put the last reply entirely behind the composer while keeping it mounted.+ await page.locator('[data-channel-scroll]').evaluate((el) => {+ el.scrollTop = el.scrollHeight - el.clientHeight - 96;+ });+ await afterLayout(page);+ await page.getByRole('button', { name: 'Notify covered reply' }).click();+ await afterLayout(page);+ await expect(page.locator('[data-notification="29"]')).toHaveText('Unread');+ await page.getByRole('button', { name: 'Toggle pane' }).click();+ await page.getByRole('button', { name: 'Remove overlays' }).click();+ await afterLayout(page);+ await expect(page.locator('[data-notification="29"]')).toHaveText('Unread');+ await page.getByRole('button', { name: 'Toggle pane' }).click();+ await page+ .locator('[data-message="29"]')+ .evaluate((el) => el.scrollIntoView({ block: 'center' }));+ await expect(page.locator('[data-notification="29"]')).toHaveText('Read');+});++test('standalone expanded threads keep offscreen replies unread', async ({+ page,+}) => {+ await page.goto('/?mode=panel');+ await page.getByRole('button', { name: 'Notify offscreen reply' }).click();+ await afterLayout(page);+ await expect(page.locator('[data-notification="0"]')).toHaveText('Unread');+ await page+ .locator('[data-message="0"]')+ .evaluate((el) => el.scrollIntoView({ block: 'center' }));+ await expect(page.locator('[data-notification="0"]')).toHaveText('Read');+});++test('a reply scrolled out from behind the composer becomes read', async ({+ page,+}) => {+ await page.goto('/');+ const scroller = page.locator('[data-channel-scroll]');+ await scroller.evaluate((el) => {+ el.scrollTop = el.scrollHeight - el.clientHeight - 96;+ });+ await afterLayout(page);+ await page.getByRole('button', { name: 'Notify covered reply' }).click();+ await afterLayout(page);+ await expect(page.locator('[data-notification="29"]')).toHaveText('Unread');+ await scroller.evaluate((el) => {+ el.scrollTop += 96;+ });+ await expect(page.locator('[data-notification="29"]')).toHaveText('Read');+});++test('a notification arriving in the same task as a scroll waits for fresh visibility', async ({+ page,+}) => {+ await page.goto('/');+ const reply = page.locator('[data-message="23"]');+ await reply.evaluate((el) => el.scrollIntoView({ block: 'center' }));+ await page.getByRole('button', { name: 'Notify offscreen reply' }).click();+ await expect(page.locator('[data-notification="23"]')).toHaveText('Read');+ await page.getByRole('button', { name: 'Scroll away and notify' }).click();+ await afterLayout(page);+ await expect(page.locator('[data-notification="23"]').last()).toHaveText(+ 'Unread'+ );+ await reply.evaluate((el) => el.scrollIntoView({ block: 'center' }));+ await expect(page.locator('[data-notification="23"]').last()).toHaveText(+ 'Read'+ );+});diff --git a/apps/web/src/features/notifications/browser-test/playwright.config.ts b/apps/web/src/features/notifications/browser-test/playwright.config.tsnew file mode 100644index 0000000000..3797a397c4--- /dev/null+++ b/apps/web/src/features/notifications/browser-test/playwright.config.ts@@ -0,0 +1,37 @@+import { fileURLToPath } from 'node:url';+import { defineConfig, devices } from '@playwright/test';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));+const port = Number(process.env.MESSAGE_READ_BROWSER_PORT ?? 3138);+export default defineConfig({+ testDir: directory,+ testMatch: '*.browser.e2e.ts',+ outputDir: `${directory}/test-results`,+ workers: 1,+ reporter: 'line',+ use: {+ baseURL: `http://127.0.0.1:${port}`,+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ trace: 'retain-on-failure',+ screenshot: 'only-on-failure',+ },+ webServer: {+ command: `bunx vite --config src/features/notifications/browser-test/vite.config.ts --port ${port}`,+ cwd: webDirectory,+ url: `http://127.0.0.1:${port}`,+ },+ projects: [+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },+ {+ name: 'phone',+ use: { ...devices['iPhone 13'], browserName: 'chromium' },+ },+ {+ name: 'tablet',+ use: { ...devices['iPad Mini'], browserName: 'chromium' },+ },+ ],+});diff --git a/apps/web/src/features/notifications/browser-test/scrollbar.tsx b/apps/web/src/features/notifications/browser-test/scrollbar.tsxnew file mode 100644index 0000000000..056828bbe4--- /dev/null+++ b/apps/web/src/features/notifications/browser-test/scrollbar.tsx@@ -0,0 +1,4 @@+// The scrollbar's app-wide UI dependencies are unrelated to read visibility.+export function CustomScrollbar() {+ return null;+}diff --git a/apps/web/src/features/notifications/browser-test/source.ts b/apps/web/src/features/notifications/browser-test/source.tsnew file mode 100644index 0000000000..7991f5c2ae--- /dev/null+++ b/apps/web/src/features/notifications/browser-test/source.ts@@ -0,0 +1,52 @@+import { createSignal } from 'solid-js';+import type { UnifiedNotification } from '../types';++const [notifications, setNotifications] = createSignal<UnifiedNotification[]>(+ []+);++export { notifications };+export function addNotification(messageId: string) {+ setNotifications((previous) => [+ ...previous,+ {+ id: `notification-${previous.length}`,+ entity_id: 'channel-fixture',+ entity_type: 'channel',+ state: 'unseen',+ sent: true,+ viewed_at: null,+ created_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+ notification_event_type: 'channel_message_reply',+ notification_metadata: {+ tag: 'channel_message_reply',+ content: {+ channelType: 'private',+ messageId,+ threadId: 'thread-fixture',+ messageContent: 'Reply fixture',+ },+ },+ },+ ]);+}++// Only the app data boundary is replaced. Read marking and observers are real.+export function useGlobalNotificationSource() {+ return {+ notificationsByEntity: () => ({+ 'channel@channel-fixture': notifications(),+ }),+ bulkMarkAsRead: async (seen: UnifiedNotification[]) => {+ const ids = new Set(seen.map((n) => n.id));+ setNotifications((previous) =>+ previous.map((n) => (ids.has(n.id) ? { ...n, state: 'seen' } : n))+ );+ },+ };+}++export function useNotificationsForEntity() {+ return notifications;+}diff --git a/apps/web/src/features/notifications/browser-test/vite.config.ts b/apps/web/src/features/notifications/browser-test/vite.config.tsnew file mode 100644index 0000000000..acd6f4c590--- /dev/null+++ b/apps/web/src/features/notifications/browser-test/vite.config.ts@@ -0,0 +1,23 @@+import { fileURLToPath } from 'node:url';+import { defineConfig } from 'vite';+import solid from 'vite-plugin-solid';+import tsconfigPaths from 'vite-tsconfig-paths';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));+export default defineConfig({+ root: directory,+ plugins: [+ solid(),+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),+ ],+ resolve: {+ dedupe: ['solid-js'],+ alias: {+ '@components/app/GlobalAppState': `${directory}/source.ts`,+ '@notifications/notification-helpers': `${directory}/source.ts`,+ '@core/component/CustomScrollbar': `${directory}/scrollbar.tsx`,+ },+ },+ server: { host: '127.0.0.1', strictPort: true },+});diff --git a/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx b/apps/web/src/features/notifications/components/MarkMessageNotifications.tsxindex a6fbf3de7f..84cb9822f9 100644--- a/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx+++ b/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx@@ -1,4 +1,7 @@import { useGlobalNotificationSource } from '@components/app/GlobalAppState';+import { fireAndForget } from '@core/util/fireAndForget';+import { catchToResult } from '@core/util/result';+import { Telemetry } from '@macro-inc/observability';import { useNotificationsForEntity } from '@notifications/notification-helpers';import type { UnifiedNotification } from '@notifications/types';import type { MessageParent } from '@service-storage/messages';@@ -7,9 +10,12 @@ import {type Accessor,createContext,createEffect,+ createMemo,createSignal,+ on,useContext,} from 'solid-js';+import { useMessageReadVisibility } from './MessageReadVisibility';/** Share exact unread matches so each message avoids scanning the channel history. */export const MessageNotificationIndexContext =@@ -20,6 +26,7 @@ const MAX_MARK_ATTEMPTS = 3;export function MarkMessageNotifications(props: {messageId: string;parent: MessageParent;+ element: HTMLElement | undefined;children: JSXElement;}) {// TODO(dev-rb/notifications): Stop discovering message notifications through the@@ -38,6 +45,22 @@ export function MarkMessageNotifications(props: {('commentId' in content && String(content.commentId) === props.messageId));};+ const unreadNotifications = () =>+ notifications().filter(+ (notification) =>+ notification.state === 'unseen' &&+ (scopedIndex !== undefined || isMessageNotification(notification))+ );+ const batchKey = createMemo(() =>+ unreadNotifications().length+ ? JSON.stringify(+ unreadNotifications()+ .map((notification) => notification.id)+ .sort()+ )+ : ''+ );+ const visible = useMessageReadVisibility(() => props.element, batchKey);// A message can generate several notifications — notably one// `document_mention` per mentioned document. Mark every notification for@@ -53,32 +76,42 @@ export function MarkMessageNotifications(props: {let attempts = 0;let attemptedIds = '';- createEffect(() => {- const unread = notifications().filter(- (notification) =>- notification.state === 'unseen' &&- (scopedIndex !== undefined || isMessageNotification(notification))- );- if (unread.length === 0 || inFlight()) return;- const ids = JSON.stringify(- unread.map((notification) => notification.id).sort()- );- if (ids !== attemptedIds) {- attemptedIds = ids;- attempts = 0;- }- if (attempts >= MAX_MARK_ATTEMPTS) return;- attempts += 1;- setInFlight(true);- void notificationSource- .bulkMarkAsRead(unread)- .catch((error) => {- console.error('Failed to mark message notifications as read', error);+ const markRead = async (unread: UnifiedNotification[]) => {+ const result = await catchToResult(() =>+ Telemetry.span('notification.message_seen', async (span) => {+ span.setAttr('message.id', props.messageId);+ span.setAttr('notification.count', unread.length);+ span.setAttr('notification.read_trigger', 'visible');+ await notificationSource.bulkMarkAsRead(unread);})- .finally(() => {- setInFlight(false);- });- });+ );+ if (result.isErr())+ console.error(+ 'Failed to mark message notifications as read',+ result.error+ );+ setInFlight(false);+ };++ createEffect(+ on(+ [unreadNotifications, inFlight, visible],+ ([unread, pending, isVisible]) => {+ if (unread.length === 0 || pending || !isVisible) return;+ const ids = JSON.stringify(+ unread.map((notification) => notification.id).sort()+ );+ if (ids !== attemptedIds) {+ attemptedIds = ids;+ attempts = 0;+ }+ if (attempts >= MAX_MARK_ATTEMPTS) return;+ attempts += 1;+ setInFlight(true);+ fireAndForget(markRead(unread), 'message-notification-read');+ }+ )+ );return props.children;}diff --git a/apps/web/src/features/notifications/components/MessageReadVisibility.tsx b/apps/web/src/features/notifications/components/MessageReadVisibility.tsxnew file mode 100644index 0000000000..5be8b41fb7--- /dev/null+++ b/apps/web/src/features/notifications/components/MessageReadVisibility.tsx@@ -0,0 +1,58 @@+import {+ type Accessor,+ createContext,+ createEffect,+ createSignal,+ on,+ onCleanup,+ type ParentProps,+ useContext,+} from 'solid-js';+import { createMessageReadVisibility } from '../primitives/create-message-read-visibility';++const MessageReadVisibilityContext =+ createContext<ReturnType<typeof createMessageReadVisibility>>();++/** Thread lists supply their floating chrome insets; standalone threads use the window. */+export function MessageReadVisibilityProvider(+ props: ParentProps<{+ root?: Accessor<Element | null | undefined>;+ insets?: Accessor<{ start: number; end: number }>;+ }>+) {+ const inherited = useContext(MessageReadVisibilityContext);+ const visibility =+ !props.root && inherited+ ? inherited+ : createMessageReadVisibility({+ root: props.root ?? (() => null),+ insets: props.insets ?? (() => ({ start: 0, end: 0 })),+ });+ return (+ <MessageReadVisibilityContext.Provider value={visibility}>+ {props.children}+ </MessageReadVisibilityContext.Provider>+ );+}++export function useMessageReadVisibility(+ element: Accessor<Element | undefined>,+ batch: Accessor<string>+) {+ const visibility = useContext(MessageReadVisibilityContext);+ if (!visibility) throw new Error('MessageReadVisibilityProvider is required');+ const [visibleBatch, setVisibleBatch] = createSignal<string>();+ createEffect(+ on([element, batch], ([target, key]) => {+ // Every newly unread batch needs a fresh browser observation. A live+ // notification may arrive in the same task that scrolls the row away.+ if (target && key)+ onCleanup(+ visibility.observe(target, (visible) =>+ setVisibleBatch(visible ? key : undefined)+ )+ );+ })+ );+ return () => !!batch() && visibleBatch() === batch();+}diff --git a/apps/web/src/features/notifications/primitives/create-message-read-visibility.ts b/apps/web/src/features/notifications/primitives/create-message-read-visibility.tsnew file mode 100644index 0000000000..2eedd16e62--- /dev/null+++ b/apps/web/src/features/notifications/primitives/create-message-read-visibility.ts@@ -0,0 +1,169 @@+import {+ type Accessor,+ createEffect,+ createSignal,+ on,+ onCleanup,+} from 'solid-js';++type Observation = { time: number; rect?: DOMRectReadOnly };++type Target = {+ publish: (visible: boolean) => void;+ registeredAt: number;+ viewport?: Observation;+ scroller?: Observation;+ refreshing?: boolean;+};++// Avoid counting edge contact as seeing a message, including very tall replies.+const INTERSECTION_THRESHOLD = 0.001;++/** Share observers across a message list; never infer visibility from mounting. */+export function createMessageReadVisibility(options: {+ root: Accessor<Element | null | undefined>;+ insets: Accessor<{ start: number; end: number }>;+}) {+ const targets = new Map<Element, Target>();+ const [foreground, setForeground] = createSignal(!document.hidden);+ const onVisibilityChange = () => setForeground(!document.hidden);+ document.addEventListener('visibilitychange', onVisibilityChange);+ onCleanup(() =>+ document.removeEventListener('visibilitychange', onVisibilityChange)+ );++ let viewportObserver: IntersectionObserver | undefined;+ let scrollerObserver: IntersectionObserver | undefined;+ createEffect(+ on(+ [+ options.root,+ () => options.insets().start,+ () => options.insets().end,+ foreground,+ ],+ ([root, start, end, visible]) => {+ if (+ !visible ||+ root === undefined ||+ typeof IntersectionObserver === 'undefined'+ )+ return;+ let active = true;+ const update = (+ entries: IntersectionObserverEntry[],+ kind: 'viewport' | 'scroller'+ ) => {+ if (!active) return;+ for (const entry of entries) {+ const target = targets.get(entry.target);+ if (!target) continue;+ if (entry.time <= target.registeredAt) {+ // unobserve() does not discard queued entries from an old batch.+ // Reobserve also handles a new registration in the current frame.+ const observer =+ kind === 'viewport' ? viewportObserver : scrollerObserver;+ observer?.unobserve(entry.target);+ observer?.observe(entry.target);+ continue;+ }+ target[kind] = {+ time: entry.time,+ rect:+ entry.isIntersecting &&+ entry.intersectionRatio >= INTERSECTION_THRESHOLD+ ? entry.intersectionRect+ : undefined,+ };+ const viewportObservation = target.viewport;+ const scrollerObservation = root+ ? target.scroller+ : viewportObservation;+ if (!viewportObservation || !scrollerObservation) {+ target.publish(false);+ continue;+ }+ if (viewportObservation.time !== scrollerObservation.time) {+ target.publish(false);+ // Only one observer may cross a threshold during a scroll. Get+ // both rectangles from the same rendering update before clipping+ // them, rather than combining new and old screen coordinates.+ if (!target.refreshing) {+ target.refreshing = true;+ target.viewport = undefined;+ target.scroller = undefined;+ viewportObserver?.unobserve(entry.target);+ scrollerObserver?.unobserve(entry.target);+ viewportObserver?.observe(entry.target);+ scrollerObserver?.observe(entry.target);+ }+ continue;+ }+ target.refreshing = false;+ const viewport = viewportObservation.rect;+ const scroller = scrollerObservation.rect;+ target.publish(+ !!viewport &&+ !!scroller &&+ Math.min(viewport.bottom, scroller.bottom) >+ Math.max(viewport.top, scroller.top) &&+ Math.min(viewport.right, scroller.right) >+ Math.max(viewport.left, scroller.left)+ );+ }+ };+ // The implicit root also clips against the window and every ancestor.+ // An explicit scroll root alone can intersect while its pane is offscreen.+ viewportObserver = new IntersectionObserver(+ (entries) => update(entries, 'viewport'),+ {+ threshold: INTERSECTION_THRESHOLD,+ }+ );+ if (root) {+ scrollerObserver = new IntersectionObserver(+ (entries) => update(entries, 'scroller'),+ {+ root,+ rootMargin: `${-Math.max(0, start)}px 0px ${-Math.max(0, end)}px 0px`,+ threshold: INTERSECTION_THRESHOLD,+ }+ );+ }+ for (const element of targets.keys()) {+ viewportObserver.observe(element);+ scrollerObserver?.observe(element);+ }+ onCleanup(() => {+ active = false;+ viewportObserver?.disconnect();+ scrollerObserver?.disconnect();+ viewportObserver = undefined;+ scrollerObserver = undefined;+ for (const target of targets.values()) {+ target.viewport = undefined;+ target.scroller = undefined;+ target.refreshing = false;+ target.publish(false);+ }+ });+ }+ )+ );++ return {+ observe(element: Element, publish: Target['publish']) {+ const target: Target = { publish, registeredAt: performance.now() };+ targets.set(element, target);+ viewportObserver?.observe(element);+ scrollerObserver?.observe(element);+ return () => {+ if (targets.get(element) !== target) return;+ viewportObserver?.unobserve(element);+ scrollerObserver?.unobserve(element);+ targets.delete(element);+ publish(false);+ };+ },+ };+}diff --git a/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsx b/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsxindex 23bcaf1e15..e5e20c2331 100644--- a/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsx+++ b/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsx@@ -4,11 +4,12 @@ import { render, waitFor } from '@solidjs/testing-library';import { createMemo, createSignal } from 'solid-js';import { createStore } from 'solid-js/store';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import {- MarkMessageNotifications,- MessageNotificationIndexContext,-} from '../components/MarkMessageNotifications';+import { MessageNotificationIndexContext } from '../components/MarkMessageNotifications';import { indexUnreadMessageNotifications } from '../unread-message-notifications';+import {+ installMessageIntersectionObserver,+ ObservedMessage as MarkMessageNotifications,+} from './message-read-visibility';const mocks = vi.hoisted(() => ({notificationSource: undefined as NotificationSource | undefined,@@ -42,9 +43,11 @@ function documentMentionNotification(describe('MarkMessageNotifications', () => {const bulkMarkAsRead = vi.fn<NotificationSource['bulkMarkAsRead']>();let matchingNotifications: UnifiedNotification[];+ let intersect: ReturnType<typeof installMessageIntersectionObserver>;beforeEach(() => {vi.clearAllMocks();+ intersect = installMessageIntersectionObserver();matchingNotifications = [documentMentionNotification('notification-1'),documentMentionNotification('notification-2'),@@ -66,7 +69,7 @@ describe('MarkMessageNotifications', () => {} as unknown as NotificationSource;});- it('marks every document mention from the mounted channel message as read', async () => {+ it('keeps mounted notifications unread until their message becomes visible', async () => {render(() => (<MarkMessageNotificationsmessageId="message-1"@@ -76,20 +79,24 @@ describe('MarkMessageNotifications', () => {</MarkMessageNotifications>));+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ intersect(false);+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ intersect();await waitFor(() => {expect(matchingNotifications.every((n) => n.viewed_at)).toBe(true);});- await new Promise((resolve) => setTimeout(resolve, 0));expect(bulkMarkAsRead).toHaveBeenCalledOnce();expect(bulkMarkAsRead).toHaveBeenCalledWith(matchingNotifications);});- afterEach(() => vi.unstubAllGlobals());+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });- it('marks scoped notifications on mount and live updates without reading the global feed', async () => {- const observer = vi.fn();- vi.stubGlobal('IntersectionObserver', observer);+ it('marks scoped notifications and live updates only while visible without reading the global feed', async () => {const globalRead = vi.spyOn(mocks.notificationSource!,'notificationsByEntity'@@ -113,16 +120,23 @@ describe('MarkMessageNotifications', () => {);});expect(globalRead).not.toHaveBeenCalled();+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ intersect();await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());expect(bulkMarkAsRead).toHaveBeenCalledWith(matchingNotifications);+ intersect(false);+ setNotifications([documentMentionNotification('offscreen-live')]);+ expect(bulkMarkAsRead).toHaveBeenCalledOnce();+ intersect();+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledTimes(2));for (let i = 0; i < 4; i++) {const liveNotifications = [documentMentionNotification(`live-${i}`)];setNotifications(liveNotifications);- await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledTimes(i + 2));+ intersect();+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledTimes(i + 3));expect(bulkMarkAsRead).toHaveBeenLastCalledWith(liveNotifications);}expect(globalRead).not.toHaveBeenCalled();- expect(observer).not.toHaveBeenCalled();expect(view.container.firstElementChild?.tagName).toBe('SPAN');});@@ -153,11 +167,14 @@ describe('MarkMessageNotifications', () => {);});expect(bulkMarkAsRead).not.toHaveBeenCalled();+ intersect();setNotifications(0, 'state', 'unseen');+ intersect();await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());setNotifications(0, 'state', 'seen');setNotifications(1, documentMentionNotification('second'));+ intersect();expect(bulkMarkAsRead).toHaveBeenCalledOnce();finishMark!();await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledTimes(2));@@ -168,6 +185,64 @@ describe('MarkMessageNotifications', () => {finishMark!();});+ it('ignores queued visibility from an earlier notification batch', async () => {+ const clock = vi.spyOn(performance, 'now').mockReturnValue(100);+ const [notifications, setNotifications] = createSignal(+ matchingNotifications+ );+ render(() => {+ const index = createMemo(() =>+ indexUnreadMessageNotifications(notifications())+ );+ return (+ <MessageNotificationIndexContext.Provider value={index}>+ <MarkMessageNotifications+ messageId="message-1"+ parent={{ type: 'channel', id: 'channel-1' }}+ >+ <span>Message</span>+ </MarkMessageNotifications>+ </MessageNotificationIndexContext.Provider>+ );+ });+ clock.mockReturnValue(200);+ const deliverOldVisibility = intersect.queue();+ clock.mockReturnValue(300);+ const incoming = [documentMentionNotification('new-offscreen-batch')];+ setNotifications(incoming);+ deliverOldVisibility();+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ clock.mockReturnValue(400);+ intersect(false);+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ clock.mockReturnValue(500);+ intersect();+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());+ expect(bulkMarkAsRead).toHaveBeenCalledWith(incoming);+ });++ it('waits for foreground and a fresh observation before reading a background notification', async () => {+ const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(true);+ const view = render(() => (+ <MarkMessageNotifications+ messageId="message-1"+ parent={{ type: 'channel', id: 'channel-1' }}+ >+ <span>Message</span>+ </MarkMessageNotifications>+ ));+ intersect();+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ hidden.mockReturnValue(false);+ document.dispatchEvent(new Event('visibilitychange'));+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ intersect();+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());+ view.unmount();+ intersect();+ expect(bulkMarkAsRead).toHaveBeenCalledOnce();+ });+it('bounds retries for the same notifications and retries a new batch after exhaustion', async () => {const error = new Error('mark failed');bulkMarkAsRead.mockRejectedValue(error);@@ -195,6 +270,7 @@ describe('MarkMessageNotifications', () => {);});+ intersect();await waitFor(() => {expect(bulkMarkAsRead).toHaveBeenCalledTimes(3);expect(consoleError).toHaveBeenCalledTimes(3);@@ -203,7 +279,6 @@ describe('MarkMessageNotifications', () => {setNotifications([...matchingNotifications].reverse().map((n) => ({ ...n })));- await new Promise((resolve) => setTimeout(resolve, 0));expect(bulkMarkAsRead).toHaveBeenCalledTimes(3);const incoming = [documentMentionNotification('new-after-failure')];@@ -211,6 +286,7 @@ describe('MarkMessageNotifications', () => {for (const notification of notifications) notification.state = 'seen';});setNotifications(incoming);+ intersect();await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledTimes(4));expect(bulkMarkAsRead).toHaveBeenLastCalledWith(incoming);} finally {diff --git a/apps/web/src/features/notifications/tests/message-read-visibility.tsx b/apps/web/src/features/notifications/tests/message-read-visibility.tsxnew file mode 100644index 0000000000..ec6a005d71--- /dev/null+++ b/apps/web/src/features/notifications/tests/message-read-visibility.tsx@@ -0,0 +1,73 @@+import { type ComponentProps, createSignal } from 'solid-js';+import { vi } from 'vitest';+import { MarkMessageNotifications } from '../components/MarkMessageNotifications';+import { MessageReadVisibilityProvider } from '../components/MessageReadVisibility';++/** jsdom has no layout; tests deliver browser intersection events explicitly. */+export function installMessageIntersectionObserver() {+ const observers = new Set<TestObserver>();+ class TestObserver implements IntersectionObserver {+ readonly root: Element | Document | null;+ readonly rootMargin: string;+ readonly scrollMargin = '0px';+ readonly thresholds = [0.001];+ readonly targets = new Set<Element>();+ constructor(+ private callback: IntersectionObserverCallback,+ options?: IntersectionObserverInit+ ) {+ this.root = options?.root ?? null;+ this.rootMargin = options?.rootMargin ?? '0px';+ observers.add(this);+ }+ observe(element: Element) {+ this.targets.add(element);+ }+ unobserve(element: Element) {+ this.targets.delete(element);+ }+ disconnect() {+ this.targets.clear();+ observers.delete(this);+ }+ takeRecords() {+ return [];+ }+ queue(visible: boolean, time: number) {+ const entries = [...this.targets].map((target) => ({+ target,+ isIntersecting: visible,+ intersectionRatio: visible ? 1 : 0,+ intersectionRect: new DOMRect(0, 0, 200, visible ? 50 : 0),+ boundingClientRect: new DOMRect(0, 0, 200, 50),+ rootBounds: null,+ time,+ }));+ return () => this.callback(entries, this);+ }+ }+ vi.stubGlobal('IntersectionObserver', TestObserver);+ const queue = (visible = true) => {+ const time = performance.now();+ const deliveries = [...observers].map((observer) =>+ observer.queue(visible, time)+ );+ return () => {+ for (const deliver of deliveries) deliver();+ };+ };+ return Object.assign((visible = true) => queue(visible)(), { queue });+}++export function ObservedMessage(+ props: Omit<ComponentProps<typeof MarkMessageNotifications>, 'element'>+) {+ const [element, setElement] = createSignal<HTMLSpanElement>();+ return (+ <MessageReadVisibilityProvider>+ <MarkMessageNotifications {...props} element={element()}>+ <span ref={setElement}>{props.children}</span>+ </MarkMessageNotifications>+ </MessageReadVisibilityProvider>+ );+}diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex c27bad3758..6b62a683cf 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -708,9 +708,21 @@ 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.+hidden replies seen. Automatic read marking waits until the actual message intersects+the visible scroll area, excluding floating header/composer insets. Offscreen+overscan, collapsed replies, hidden panes, and background tabs remain unread.+Expanded standalone threads and the thread side panel use the same visibility+rule. New notifications on an already-mounted offscreen reply remain unread until+that reply comes into view. Explicit notification clicks and mark-read actions+retain their existing behavior.++Visibility is conservative: moving a partly off-window pane without crossing+either observer's visibility threshold can leave a now-visible reply unread+until the next intersection update or an explicit mark-read action.++The backend-free regression uses the real message read marker and channel+virtualizer on desktop, phone, and tablet:+`bunx playwright test --config src/features/notifications/browser-test/playwright.config.ts`.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. Withanother unread thread above, an upward chip should remain and count only that offscreen thread.