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
Seanaye/fix/thread unreads (#7128)
Sean Aye440ea62a8869
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsxindex 82fd482aa9..d49d60f8d7 100644--- a/apps/web/src/features/channels-view/channels-view.test.tsx+++ b/apps/web/src/features/channels-view/channels-view.test.tsx@@ -214,7 +214,11 @@ describe('channel selection loading and recovery', () => {setQuery('isFetching', false);});expect(screen.getByTestId('channel-detail').textContent).toBe('one');- expect(mocks.markRead).toHaveBeenCalledOnce();+ expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ id: 'one' }),+ expect.anything(),+ { scopeChannelThreads: false }+ );});it('never marks cached data while a reopened selection is refreshing', async () => {diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsxindex 4d6d49d819..45d1a3dd96 100644--- a/apps/web/src/features/channels-view/channels-view.tsx+++ b/apps/web/src/features/channels-view/channels-view.tsx@@ -215,7 +215,9 @@ function ChannelDetailRouteContent() {on(readyId, () => {const channel = hydrated();if (channel && channel.isParticipant !== false)- markChannelNotificationsSeenOnOpen(channel, notificationSource);+ markChannelNotificationsSeenOnOpen(channel, notificationSource, {+ scopeChannelThreads: false,+ });}));diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsxnew file mode 100644index 0000000000..355e64c4a2--- /dev/null+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx@@ -0,0 +1,92 @@+import type { ChannelTargetRequest } from '@channel/Channel/ChannelSurface';+import type { ChannelEntity } from '@entity/types/entity';+import { cleanup, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getTarget:+ vi.fn<+ typeof import('@app/features/next-soup/utils').getChannelEntityTarget+ >(),+}));+vi.mock('@app/features/next-soup/actions', () => ({+ useBlockEntityCommands: vi.fn(),+}));+vi.mock('@app/features/next-soup/utils', () => ({+ getChannelEntityTarget: mocks.getTarget,+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({ splitHotkeyScope: 'test' }),+}));+vi.mock('@channel/Channel/ChannelDetail', () => ({+ ChannelDetail: (props: { target?: ChannelTargetRequest }) => (+ <output data-testid="target">{JSON.stringify(props.target)}</output>+ ),+ ChannelDetailTopBar: () => null,+}));++import { ChannelDetailView } from './ChannelDetailView';++const channel: ChannelEntity = {+ id: 'channel',+ type: 'channel',+ name: 'Channel',+ ownerId: 'owner',+ channelType: 'private',+};+const replyTarget = {+ kind: 'message' as const,+ messageId: 'reply',+ threadId: 'root',+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.getTarget.mockReturnValue(replyTarget);+});+afterEach(cleanup);++describe('Chat detail navigation', () => {+ it('requests a channel-wide target for unstamped route and favorite selections', () => {+ render(() => <ChannelDetailView channel={channel} />);++ expect(mocks.getTarget).toHaveBeenCalledExactlyOnceWith(channel, {+ scopeChannelThreads: false,+ });+ expect(screen.getByTestId('target').textContent).toBe(+ JSON.stringify(replyTarget)+ );+ });++ it('keeps the initial target when notification reads replace the channel', () => {+ const [selected, setSelected] = createSignal(channel);+ render(() => <ChannelDetailView channel={selected()} />);++ mocks.getTarget.mockReturnValue({ kind: 'latest' });+ setSelected({ ...channel, notifications: () => [] });++ expect(mocks.getTarget).toHaveBeenCalledOnce();+ expect(screen.getByTestId('target').textContent).toBe(+ JSON.stringify(replyTarget)+ );+ });++ it('resolves a new explicit target rather than retaining the initial unread target', () => {+ const [selected, setSelected] = createSignal(channel);+ render(() => <ChannelDetailView channel={selected()} />);+ const explicit = { messageId: 'search-hit', threadId: 'search-thread' };+ const target = { kind: 'message' as const, ...explicit };+ mocks.getTarget.mockReturnValue(target);++ setSelected({ ...channel, target: explicit });++ expect(mocks.getTarget).toHaveBeenLastCalledWith(+ expect.objectContaining({ target: explicit }),+ { scopeChannelThreads: false }+ );+ expect(screen.getByTestId('target').textContent).toBe(+ JSON.stringify(target)+ );+ });+});diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.tsxindex 0f6f68d7fe..c9199ccab6 100644--- a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx@@ -31,7 +31,9 @@ export function ChannelDetailView(props: { channel: ChannelEntity }) {}`;if (lastTargetKey !== undefined && key === lastTargetKey) return previous;lastTargetKey = key;- const clickTarget = getChannelEntityTarget(props.channel);+ const clickTarget = getChannelEntityTarget(props.channel, {+ scopeChannelThreads: false,+ });if (!clickTarget) return undefined;return clickTarget.kind === 'latest'? { kind: 'latest' }diff --git a/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx b/apps/web/src/features/channels-view/components/ChannelsMobileView.tsxindex d9f4cea4e5..26a6c15391 100644--- a/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx+++ b/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx@@ -124,6 +124,7 @@ export function ChannelsMobileView(props: {splitHandle: panel.handle,referredFrom: 'channels',notificationSource,+ scopeChannelThreads: false,});} catch (error) {if (request !== opening) return;diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsxnew file mode 100644index 0000000000..6497237a51--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx@@ -0,0 +1,319 @@+import type { ChannelPreviewSelection } from '@app/features/next-soup/utils';+import type { ChannelEntity } from '@entity/types/entity';+import type { WithNotification } from '@entity/types/notification';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ChannelsSources } from '../../queries';+import type { ChannelRailRow } from './ChannelsRailContext';++const mocks = vi.hoisted(() => ({+ hydrate:+ vi.fn<+ (+ channel: ChannelEntity+ ) =>+ | WithNotification<ChannelEntity>+ | Promise<WithNotification<ChannelEntity>>+ >(),+ markRead: vi.fn(),+ navigate: vi.fn(async () => {}),+ openSplit: vi.fn(async () => {}),+ select: vi.fn((_channel: ChannelPreviewSelection) => true),+ selected: undefined as ChannelPreviewSelection | undefined,+ source: {},+ activate: (_event: MouseEvent) => {},+ row: undefined as ChannelEntity | undefined,+ failure: vi.fn(),+}));+vi.mock('@app/components/list', () => ({+ createListController: (options: {+ onActivate: (event: {+ item: ChannelRailRow;+ metadata: { event: MouseEvent };+ }) => void;+ }) => {+ mocks.activate = (event) =>+ options.onActivate({+ item: {+ kind: 'conversation',+ id: 'channel:one',+ scope: 'channels',+ localIndex: 0,+ channel: mocks.row!,+ },+ metadata: { event },+ });+ return {};+ },+ listOwnedSlotName: (name: string) => name,+ useListInteractions: vi.fn(),+}));+vi.mock('@app/components/view-shell', () => ({+ useViewControlHotkeys: vi.fn(),+ useViewTabHotkeys: vi.fn(),+}));+vi.mock('@app/features/next-soup/utils', () => ({+ channelPreviewSelection: (id: string) => ({ type: 'channel', id }),+ getChannelEntityTarget: () => ({ kind: 'latest' }),+ markChannelNotificationsSeenOnOpen: mocks.markRead,+ navigateChannelEntityToTarget: mocks.navigate,+ openEntityInSplitFromUnifiedList: mocks.openSplit,+}));+vi.mock('@app/features/soup/entity-notifications', () => ({+ withEntityNotifications: (channel: ChannelEntity) => channel,+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: false }),+}));+vi.mock('@app/util/favorites', () => ({ favoriteSplitContent: vi.fn() }));+vi.mock('@components/app/GlobalAppState', () => ({+ useGlobalNotificationSource: () => mocks.source,+ useGlobalBlockOrchestrator: () => ({}),+}));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: mocks.openSplit }),+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({ isPanelActive: () => true }),+ withSplitPanelOwner: (_name: string, run: () => unknown) => run(),+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: mocks.failure },+}));+vi.mock('@core/constant/featureFlags', () => ({ enableChannelTags: {} }));+vi.mock('@core/hotkey/hotkeys', () => ({+ createHotkeyGroup: () => ({ dispose: vi.fn() }),+ registerHotkey: () => ({ withGroup: vi.fn() }),+}));+vi.mock('@entity', () => ({+ isChannelEntity: (entity: { type: string }) => entity.type === 'channel',+}));+vi.mock('@entity/utils/notification', () => ({+ notificationIsRead: (notification: { state: string }) =>+ notification.state !== 'unseen',+}));+vi.mock('@notifications/notification-helpers', () => ({+ ensureNotificationSourceLoaded: vi.fn(),+}));+vi.mock('@queries/channel/notification-selection', () => ({+ hydrateChannelNotificationSelection: mocks.hydrate,+}));+vi.mock('@queries/channel-labels/channel-labels', () => ({+ useChannelLabelsQuery: () => ({ isSuccess: false }),+ useCreateChannelLabelMutation: () => ({}),+ useDeleteChannelLabelMutation: () => ({}),+ useRenameChannelLabelMutation: () => ({}),+ useSetChannelLabelMutation: () => ({}),+}));+vi.mock('@queries/favorites/favorites', () => ({+ useFavoritesData: () => () => ({ favorites: [] }),+}));+vi.mock('@queries/soup/search', () => ({+ useSearchSoupQuery: () => ({ isSuccess: false }),+}));+vi.mock('@thisbeyond/solid-dnd', () => ({+ useDragDropContext: () => undefined,+}));+vi.mock('@ui', () => ({ confirmDialog: vi.fn() }));+vi.mock('../../channels-view-context', () => ({+ useChannelsView: () => ({+ state: {+ tab: 'browse',+ expandedGroups: { channels: true, direct_messages: true },+ collapsedLabels: [],+ },+ selectedChannel: () => mocks.selected,+ setSelectedChannel: mocks.select,+ }),+}));+vi.mock('../../queries', () => ({+ deduplicateChannels: (collections: ChannelEntity[][]) => [+ ...new Map(+ collections.flat().map((channel) => [channel.id, channel])+ ).values(),+ ],+ useChannelsByIdsQuery: () => ({ isEnabled: false }),+}));+vi.mock('./ChannelLabelNameDialog', () => ({ promptLabelName: vi.fn() }));+vi.mock('./SmartTagDialog', () => ({ promptSmartTag: vi.fn() }));+vi.mock('./hooks/useChannelCalls', () => ({ useChannelCalls: () => ({}) }));+vi.mock('./hooks/useChannelRailActivity', () => ({+ useChannelRailActivity: () => ({}),+}));+vi.mock('./ExpandedChannelsRail', () => ({+ ExpandedChannelsRail: () => (+ <button onClick={(event) => mocks.activate(event)}>+ Open conversation+ </button>+ ),+}));++import { ChannelsRail } from './ChannelsRail';++const channel: ChannelEntity = {+ id: 'one',+ type: 'channel',+ name: 'One',+ ownerId: 'owner',+ channelType: 'private',+ isParticipant: true,+ unreadNotifications: [+ { id: 'witness', state: 'unseen', createdAt: '2026-01-01' },+ ],+};+const hydrated: WithNotification<ChannelEntity> = {+ ...channel,+ unreadNotifications: undefined,+ notifications: () => [],+};+const source = {+ items: () => [channel],+ isLoading: () => false,+ isFetching: () => false,+ error: () => undefined,+ hasMore: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ refresh: async () => {},+};+const sources: ChannelsSources = {+ channels: source,+ direct_messages: source,+ recents: source,+ search: source,+};+const mount = () =>+ render(() => (+ <ChannelsRail+ sources={sources}+ searchOpen={false}+ onSearchOpenChange={() => {}}+ />+ ));++beforeEach(() => {+ vi.clearAllMocks();+ mocks.row = channel;+ mocks.selected = undefined;+ mocks.select.mockReturnValue(true);+ mocks.hydrate.mockReturnValue(hydrated);+});+afterEach(cleanup);++describe('explicit channel activation read marking', () => {+ it('marks the full channel on every accepted click, including the already-selected route', async () => {+ mocks.selected = { type: 'channel', id: channel.id };+ mount();+ fireEvent.click(screen.getByRole('button'));+ await waitFor(() =>+ expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(+ hydrated,+ mocks.source,+ { scopeChannelThreads: false }+ )+ );+ expect(mocks.navigate).toHaveBeenCalledOnce();+ const refreshed = { ...hydrated, notifications: () => [] };+ mocks.hydrate.mockReturnValue(refreshed);+ fireEvent.click(screen.getByRole('button'));+ await waitFor(() => expect(mocks.markRead).toHaveBeenCalledTimes(2));+ expect(mocks.markRead).toHaveBeenLastCalledWith(refreshed, mocks.source, {+ scopeChannelThreads: false,+ });+ expect(mocks.navigate).toHaveBeenCalledTimes(2);+ });++ it('awaits native async hydration when telemetry replaces the global Promise constructor', async () => {+ const NativePromise = globalThis.Promise;+ let resolve!: (channel: WithNotification<ChannelEntity>) => void;+ const pending = (async () =>+ await new NativePromise<WithNotification<ChannelEntity>>((done) => {+ resolve = done;+ }))();+ class InstrumentedPromise<T> extends NativePromise<T> {}+ vi.stubGlobal('Promise', InstrumentedPromise);+ mocks.hydrate.mockReturnValue(pending);+ try {+ expect(pending instanceof Promise).toBe(false);+ mount();+ fireEvent.click(screen.getByRole('button'));+ expect(mocks.select).not.toHaveBeenCalled();+ expect(mocks.markRead).not.toHaveBeenCalled();+ resolve(hydrated);+ await waitFor(() =>+ expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(+ hydrated,+ mocks.source,+ { scopeChannelThreads: false }+ )+ );+ } finally {+ resolve(hydrated);+ await pending;+ vi.unstubAllGlobals();+ }+ });++ it('does not mark a rejected selection or a non-participant channel', () => {+ mount();+ mocks.select.mockReturnValue(false);+ fireEvent.click(screen.getByRole('button'));+ expect(mocks.markRead).not.toHaveBeenCalled();+ mocks.select.mockReturnValue(true);+ mocks.hydrate.mockReturnValue({ ...hydrated, isParticipant: false });+ fireEvent.click(screen.getByRole('button'));+ expect(mocks.markRead).not.toHaveBeenCalled();+ });++ it('does not mark a superseded hydration; only the latest click is accepted', async () => {+ let resolve!: (channel: WithNotification<ChannelEntity>) => void;+ mocks.hydrate.mockReturnValueOnce(+ new Promise((value) => {+ resolve = value;+ })+ );+ mount();+ fireEvent.click(screen.getByRole('button'));+ expect(mocks.markRead).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button'));+ await waitFor(() => expect(mocks.markRead).toHaveBeenCalledOnce());+ resolve(hydrated);+ await Promise.resolve();+ expect(mocks.select).toHaveBeenCalledOnce();+ expect(mocks.markRead).toHaveBeenCalledOnce();+ });++ it('hydrates shift-clicks and requests channel-wide marking in the split-open path', async () => {+ mount();+ fireEvent.click(screen.getByRole('button'), { shiftKey: true });+ await waitFor(() =>+ expect(mocks.openSplit).toHaveBeenCalledExactlyOnceWith(hydrated, {+ openInNewSplit: true,+ referredFrom: 'channels',+ notificationSource: mocks.source,+ scopeChannelThreads: false,+ })+ );+ expect(mocks.select).not.toHaveBeenCalled();+ });++ it('reports hydration failures without marking or selecting a partial edge', async () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.hydrate.mockRejectedValueOnce(new Error('failed'));+ try {+ mount();+ fireEvent.click(screen.getByRole('button'));+ await waitFor(() => expect(mocks.failure).toHaveBeenCalledOnce());+ expect(mocks.markRead).not.toHaveBeenCalled();+ expect(mocks.select).not.toHaveBeenCalled();+ } finally {+ log.mockRestore();+ }+ });+});diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsxindex 26bf885684..bd1ecd130c 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx@@ -13,7 +13,9 @@ import {type ChannelPreviewSelection,channelPreviewSelection,getChannelEntityTarget,+ markChannelNotificationsSeenOnOpen,navigateChannelEntityToTarget,+ openEntityInSplitFromUnifiedList,} from '@app/features/next-soup/utils';import { withEntityNotifications } from '@app/features/soup/entity-notifications';import { useFeatureFlag } from '@app/lib/analytics/posthog';@@ -161,10 +163,20 @@ export function ChannelsRail(props: ChannelsRailProps) {const selectChannel = async (channel: WithNotification<ChannelEntity>,- channelId: string+ channelId: string,+ openInNewSplit: boolean) => {try {const entity = withEntityNotifications(channel, notificationSource);+ if (openInNewSplit) {+ await openEntityInSplitFromUnifiedList(entity, {+ openInNewSplit: true,+ referredFrom: 'channels',+ notificationSource,+ scopeChannelThreads: false,+ });+ return;+ }const selection = channelPreviewSelection(channelId, {target: getChannelEntityTarget(entity, {scopeChannelThreads: false,@@ -173,6 +185,13 @@ export function ChannelsRail(props: ChannelsRailProps) {});const previous = selectedChannel();if (!setSelectedChannel(selection)) return;+ // Mark on every accepted activation, including re-clicks of the same+ // route. The detail's ready-id effect only handles initial/route opens.+ if (channel.isParticipant !== false) {+ markChannelNotificationsSeenOnOpen(entity, notificationSource, {+ scopeChannelThreads: false,+ });+ }// Repeated clicks must navigate even when the route stays the same.if (previous?.id === selection.id &&@@ -189,21 +208,23 @@ export function ChannelsRail(props: ChannelsRailProps) {const selectHydratedChannel = async (pending: Promise<WithNotification<ChannelEntity>>,request: number,- channelId: string+ channelId: string,+ openInNewSplit: boolean) => {try {const channel = await pending;if (request !== activation) return;// Only fetched selections need to join the browser router's transition.await startTransition(() => {- if (request === activation) void selectChannel(channel, channelId);+ if (request === activation)+ void selectChannel(channel, channelId, openInNewSplit);});} catch (error) {if (request === activation) reportActivationError(error);}};- const activateChannel = (channel: ChannelEntity) => {+ const activateChannel = (channel: ChannelEntity, openInNewSplit: boolean) => {const request = ++activation;// Capture before hydrate/await — store proxies from the list can lose// fields if the query refreshes while notifications are fetched.@@ -216,10 +237,12 @@ export function ChannelsRail(props: ChannelsRailProps) {channel,notificationSource.withLocalOverrides);- if (selection instanceof Promise) {- void selectHydratedChannel(selection, request, channelId);+ // Telemetry installs ZoneAwarePromise; native async results are not+ // instances of that constructor. Detect the pending edge structurally.+ if ('then' in selection) {+ void selectHydratedChannel(selection, request, channelId, openInNewSplit);} else {- void selectChannel(selection, channelId);+ void selectChannel(selection, channelId, openInNewSplit);}};@@ -495,20 +518,17 @@ export function ChannelsRail(props: ChannelsRailProps) {const channelId =item.kind === 'favorite' ? item.favorite.entityId : item.channel.id;- if (openInNewSplit) {- layout.openWithSplit(- { type: 'channel', id: channelId },- { preferNewSplit: true, referredFrom: 'channels' }- );- return;- }-const channel =item.kind === 'conversation'? item.channel: channelsById().get(channelId);- if (channel) activateChannel(channel);- else setSelectedChannel({ type: 'channel', id: channelId });+ if (channel) activateChannel(channel, openInNewSplit);+ else if (openInNewSplit) {+ layout.openWithSplit(+ { type: 'channel', id: channelId },+ { preferNewSplit: true, referredFrom: 'channels' }+ );+ } else setSelectedChannel({ type: 'channel', id: channelId });},}));diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.tsindex a1c70128ce..323859d082 100644--- a/apps/web/src/features/next-soup/utils.test.ts+++ b/apps/web/src/features/next-soup/utils.test.ts@@ -281,7 +281,7 @@ const asRead = (notification: UnifiedNotification): UnifiedNotification =>}) as unknown as UnifiedNotification;const notificationSourceWithBulkMarkAsRead = (- bulkMarkAsRead = vi.fn(async () => {})+ bulkMarkAsRead: NotificationSource['bulkMarkAsRead'] = vi.fn(async () => {})) => ({ bulkMarkAsRead }) as unknown as NotificationSource;const channelMessageRow = (opts?: {@@ -947,9 +947,83 @@ describe('getChannelEntityTarget', () => {]);});+ it.each(['channel_mention', 'channel_message_reply'] as const)(+ 'marks %s when Chat opens the whole channel without reading the global feed',+ (tag) => {+ const notification = {+ ...sendNotification('thread-notification', 'message'),+ notification_event_type: tag,+ notification_metadata: {+ tag,+ content: { messageId: 'message', threadId: 'root' },+ },+ } as UnifiedNotification;+ const bulkMarkAsRead = vi.fn(async () => {});+ const notificationsByEntity = vi.fn(() => ({}));+ markChannelNotificationsSeenOnOpen(+ channelRow({ notifications: [notification] }),+ {+ ...notificationSourceWithBulkMarkAsRead(bulkMarkAsRead),+ notificationsByEntity,+ },+ { scopeChannelThreads: false }+ );+ expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([notification]);+ expect(notificationsByEntity).not.toHaveBeenCalled();+ }+ );++ it('marks mixed channel notifications on repeated Chat opens, skipping local reads', () => {+ const send = sendNotification('send', 'root');+ const reply = replyNotification('reply', 'reply-message', 'root');+ const mention = {+ ...sendNotification('mention', 'mentioned-message'),+ notification_event_type: 'channel_mention',+ notification_metadata: {+ tag: 'channel_mention',+ content: { messageId: 'mentioned-message' },+ },+ } as UnifiedNotification;+ const read = asRead(sendNotification('seen', 'seen-message'));+ const done = {+ ...sendNotification('done', 'done-message'),+ state: 'done' as const,+ };+ const readIds = new Set<string>();+ const bulkMarkAsRead = vi.fn(+ async (notifications: UnifiedNotification[]) => {+ for (const notification of notifications) readIds.add(notification.id);+ }+ );+ const source: NotificationSource = {+ ...notificationSourceWithBulkMarkAsRead(bulkMarkAsRead),+ withLocalOverrides: (notification) =>+ readIds.has(notification.id) ? asRead(notification) : notification,+ };+ const notifications = [send, reply, mention, read, done];+ const channel = channelRow({ notifications });+ const open = () =>+ markChannelNotificationsSeenOnOpen(channel, source, {+ scopeChannelThreads: false,+ });+ open();+ expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([+ send,+ reply,+ mention,+ ]);+ open();+ expect(bulkMarkAsRead).toHaveBeenCalledTimes(1);+ const incoming = replyNotification('incoming', 'new-reply', 'root');+ notifications.push(incoming);+ open();+ expect(bulkMarkAsRead).toHaveBeenCalledTimes(2);+ expect(bulkMarkAsRead).toHaveBeenLastCalledWith([incoming]);+ });+it('marks attached channel notifications through the shared split-open path', async () => {const notification = sendNotification('shared-open', 'message');- const openWithSplit = vi.fn(() => ({ status: 'unavailable' }));+ const openWithSplit = vi.fn(() => ({ status: 'opened' }));setGlobalSplitManager({activeSplit: vi.fn(),getOrchestrator: vi.fn(() => ({@@ -978,11 +1052,60 @@ describe('getChannelEntityTarget', () => {expect(bulkMarkAsRead).toHaveBeenCalledWith([notification]);});- it('marks raw GraphQL notifications when opening a mobile channel', async () => {- const unread = sendNotification('mobile-unread', 'message');- const read = asRead(sendNotification('mobile-read', 'read-message'));- const reply = replyNotification('mobile-reply', 'reply', 'thread-root');- const openWithSplit = vi.fn(() => ({ status: 'unavailable' }));+ it.each(+ [false, true].flatMap((openInNewSplit) =>+ ['opened', 'reused', 'unavailable'].map((status) => ({+ openInNewSplit,+ status,+ }))+ )+ )(+ 'only marks the whole GraphQL channel after a successful Chat open (new split=$openInNewSplit, status=$status)',+ async ({ openInNewSplit, status }) => {+ const unread = sendNotification('mobile-unread', 'message');+ const read = asRead(sendNotification('mobile-read', 'read-message'));+ const reply = replyNotification('mobile-reply', 'reply', 'thread-root');+ const bulkMarkAsRead = vi.fn(async () => {});+ const openWithSplit = vi.fn(() => {+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ return { status };+ });+ setGlobalSplitManager({+ activeSplit: vi.fn(),+ getOrchestrator: vi.fn(() => ({+ getBlockHandle: vi.fn(async () => undefined),+ })),+ getSplitByContent: vi.fn(),+ openWithSplit,+ } as unknown as SplitManager);++ const channel = { ...channelRow(), notifications: [unread, read, reply] };+ await openEntityInSplitFromUnifiedList(channel, {+ referredFrom: 'channels',+ openInNewSplit,+ notificationSource:+ notificationSourceWithBulkMarkAsRead(bulkMarkAsRead),+ scopeChannelThreads: false,+ });++ expect(openWithSplit).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'channel', id: 'channel-1' }),+ expect.objectContaining({+ referredFrom: 'channels',+ preferNewSplit: openInNewSplit,+ })+ );+ if (status === 'unavailable') {+ expect(bulkMarkAsRead).not.toHaveBeenCalled();+ } else {+ expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([unread, reply]);+ }+ }+ );++ it('chooses the unread reply target before marking a Chat conversation read', async () => {+ const reply = replyNotification('reply-target', 'reply-message', 'root');+ const openWithSplit = vi.fn(() => ({ status: 'opened' }));setGlobalSplitManager({activeSplit: vi.fn(),getOrchestrator: vi.fn(() => ({@@ -991,19 +1114,27 @@ describe('getChannelEntityTarget', () => {getSplitByContent: vi.fn(),openWithSplit,} as unknown as SplitManager);-- const bulkMarkAsRead = vi.fn(async () => {});- const channel = { ...channelRow(), notifications: [unread, read, reply] };- await openEntityInSplitFromUnifiedList(channel, {- referredFrom: 'channels',- notificationSource: notificationSourceWithBulkMarkAsRead(bulkMarkAsRead),+ const bulkMarkAsRead = vi.fn(async () => {+ reply.state = 'seen';});-+ await openEntityInSplitFromUnifiedList(+ channelRow({ notifications: [reply] }),+ {+ notificationSource:+ notificationSourceWithBulkMarkAsRead(bulkMarkAsRead),+ scopeChannelThreads: false,+ }+ );expect(openWithSplit).toHaveBeenCalledWith(- expect.objectContaining({ type: 'channel', id: 'channel-1' }),- expect.objectContaining({ referredFrom: 'channels' })+ expect.objectContaining({+ params: expect.objectContaining({+ channel_message_id: 'reply-message',+ channel_thread_id: 'root',+ }),+ }),+ expect.any(Object));- expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([unread]);+ expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([reply]);});it('uses the global source for channels without an attached notification edge', () => {@@ -1064,7 +1195,7 @@ describe('getChannelEntityTarget', () => {})),getSplitByContent: vi.fn(),findOpenView: vi.fn(),- openWithSplit: vi.fn(() => ({ status: 'unavailable' })),+ openWithSplit: vi.fn(() => ({ status: 'opened' })),} as unknown as SplitManager);const bulkMarkAsRead = vi.fn(async () => {});diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.tsindex eacd70b237..d92a1bb981 100644--- a/apps/web/src/features/next-soup/utils.ts+++ b/apps/web/src/features/next-soup/utils.ts@@ -432,6 +432,8 @@ interface OpenEntityOptions {* opening a channel row. Callers that can open channels must provide it.*/notificationSource?: NotificationSource;+ /** False for Chat conversations; Inbox rows keep their thread-scoped reads. */+ scopeChannelThreads?: boolean;}/**@@ -766,15 +768,13 @@ export const openEntityInSplitFromUnifiedList = async (const content = getEntitySplitContent(entity);- const channelTarget = getChannelEntityTarget(entity);+ const channelTarget = getChannelEntityTarget(entity, {+ scopeChannelThreads: options.scopeChannelThreads,+ });const channelMessageTarget =channelTarget?.kind === 'message' ? channelTarget : undefined;const openChannelAtLatest = channelTarget?.kind === 'latest';- if (options.notificationSource) {- markChannelNotificationsSeenOnOpen(entity, options.notificationSource);- }-let params: Record<string, string> | undefined;if (entity.type === 'agent_session' && location?.type === 'agent') {params = agentMessageParams(location);@@ -852,6 +852,12 @@ export const openEntityInSplitFromUnifiedList = async (toast.alert('Content already open');}+ if (result.status !== 'unavailable' && options.notificationSource) {+ markChannelNotificationsSeenOnOpen(entity, options.notificationSource, {+ scopeChannelThreads: options.scopeChannelThreads,+ });+ }+// Routed calls have no block handle. Update a reused split's route search// instead of waiting for a legacy block method that will never register.if (location?.type === 'call_record') {@@ -897,11 +903,13 @@ export const openEntityInSplitFromUnifiedList = async (* array (mobile Channels) or a list accessor. Only rows without an edge fall* back to the separately paginated global source. Passing these notifications* through the source keeps its REST cache and durable seen overrides in sync- * while the configured mutation updates GraphQL edges.+ * while the configured mutation updates GraphQL edges. Chat opens the whole+ * conversation (scopeChannelThreads: false); Inbox opens only the row's stack.*/export function markChannelNotificationsSeenOnOpen(entity: EntityWithRawNotifications<EntityData>,- notificationSource: NotificationSource+ notificationSource: NotificationSource,+ options: { scopeChannelThreads?: boolean } = {}) {if (entity.type !== 'channel' &&@@ -912,7 +920,7 @@ export function markChannelNotificationsSeenOnOpen(}const notifications = getEntityNotifications(entity, notificationSource, {- scopeChannelThreads: true,+ scopeChannelThreads: options.scopeChannelThreads !== false,}).filter((notification) => !notificationIsRead(notification));if (notifications.length === 0) return;diff --git a/apps/web/src/lib/queries/channel/notification-selection.test.ts b/apps/web/src/lib/queries/channel/notification-selection.test.tsindex c84b5fa3fd..db45369cb7 100644--- a/apps/web/src/lib/queries/channel/notification-selection.test.ts+++ b/apps/web/src/lib/queries/channel/notification-selection.test.ts@@ -61,6 +61,25 @@ describe('channel selection hydration', () => {expect(full.notifications?.()).toEqual([{ id: 'one' }]);});+ it.each([true, false, undefined])(+ 'preserves participant status (%s) when the source changes during hydration',+ async (isParticipant) => {+ const row = {+ ...channel([{ id: 'one', state: 'unseen', createdAt: '2026-01-01' }]),+ isParticipant,+ };+ fetchNotifications.mockImplementation(async () => {+ row.isParticipant = undefined;+ return [{ id: 'one' }];+ });++ const full = await hydrateChannelNotificationSelection(row);++ expect(full.isParticipant).toBe(isParticipant);+ expect(full.notifications?.()).toEqual([{ id: 'one' }]);+ }+ );+it('does not silently mark a partial selection on a failed full read', async () => {fetchNotifications.mockRejectedValue(new Error('offline and uncached'));await expect(diff --git a/apps/web/src/lib/queries/channel/notification-selection.ts b/apps/web/src/lib/queries/channel/notification-selection.tsindex a9206910d8..301def914f 100644--- a/apps/web/src/lib/queries/channel/notification-selection.ts+++ b/apps/web/src/lib/queries/channel/notification-selection.ts@@ -31,6 +31,7 @@ async function fetchChannelNotificationSelection(const name = channel.name;const ownerId = channel.ownerId;const channelType = channel.channelType;+ const isParticipant = channel.isParticipant;const target = channel.target;const input = buildGraphqlEntitySoupInput('CHANNEL', channelId);if (!input) throw new Error('Invalid channel notification selection');@@ -41,6 +42,7 @@ async function fetchChannelNotificationSelection(name,ownerId,channelType,+ isParticipant,...(target ? { target } : {}),unreadNotifications: undefined,notifications: () =>diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex a790b08e26..7d4900035a 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -515,16 +515,25 @@ Channels, and DMs section headers.On touch layouts, the `Recent`, `Channels`, and `DMs` pill tabs each retaintheir own loaded pages and load more as their active list approaches the end.With `enable-graphql-soup` enabled, open an unread conversation from each tab-and return to the list: its top-level notifications should be read, including-ones older than the global notification feed's loaded page. Notifications for-separate thread stacks remain unread until that thread is opened.+and return to the list: all its message notifications should be read, including+mentions, replies, and ones older than the global notification feed's loaded page.+Chat opens the whole conversation; opening a parent channel row in Inbox still+leaves separate thread-stack notifications unread.On desktop, each click on a conversation in the Chat rail opens its most recentcurrently unread notification, including replies in threads. Read notificationsare not retained as click targets: once a channel has no unreadnotifications, clicking it opens the latest message. Explicit search hits still-open their matched message. Verify repeated clicks after read-state updates and-after a new notification arrives; previously read targets must not loop around.+open their matched message. Each accepted click marks the complete loaded channel+edge read, even when the same conversation is already selected. Shift-clicks use+the same channel-wide read behavior, but mark notifications only after the split+opens or reuses an existing conversation. Route opens, reloads, and uncached+favorites also target the newest unread notification across the channel,+including thread replies; an explicit message target still wins. Verify repeated+clicks after read-state updates, a failed read, and a new notification; previously+read targets must not loop around. A rejected selection or unavailable split must+not mark the conversation read. Hydrating an unread non-participant row must+preserve its membership status and must not mark its notifications read.With GraphQL enabled, the app-shell Chat badge uses `ChannelUnreadPresence`: onlychannel IDs and at most one unread notification ID/state per channel, with a@@ -546,7 +555,8 @@ per channel through an aliased, filtered `notifications` edge. An empty edge meano unread messages; invites and call notifications do not light the dot. Recentcards still use the latest-message preview. Full notification edges load only foran opened unread conversation, so mark-read and message targeting retain their-complete thread-scoped inputs. Reopening a conversation must refresh that full+complete channel-wide inputs in Chat and thread-scoped inputs in Inbox. Reopening+a conversation must refresh that fulledge even within 30 seconds; mark-read waits for the refresh rather than usingolder cached notifications. Failed lookups and successful lookups with no matchingchannel show **Conversation unavailable** with **Retry**, never permanent loading.