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: clicking channel goes to most recent unread notification (#6947)

Peter Chinmanbb623862f4b0
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
index 55f180f637..430e9faabd 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
@@ -9,10 +9,18 @@ import {
useViewTabHotkeys,
} from '@app/components/view-shell';
import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';
-import type { ChannelPreviewSelection } from '@app/features/next-soup/utils';
+import {
+ type ChannelPreviewSelection,
+ getChannelEntityTarget,
+ navigateChannelEntityToTarget,
+} from '@app/features/next-soup/utils';
+import { withEntityNotifications } from '@app/features/soup/entity-notifications';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { favoriteSplitContent } from '@app/util/favorites';
-import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
+import {
+ useGlobalBlockOrchestrator,
+ useGlobalNotificationSource,
+} from '@components/app/GlobalAppState';
import { useSplitLayout } from '@components/app/split-layout/layout';
import {
useSplitPanelOrThrow,
@@ -23,9 +31,15 @@ import { enableChannelTags } from '@core/constant/featureFlags';
import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { debouncedDependent } from '@core/util/debounce';
import { thrownResultErrorHasCode } from '@core/util/result';
-import { type ChannelEntity, isChannelEntity, type WithSearch } from '@entity';
+import {
+ type ChannelEntity,
+ isChannelEntity,
+ type WithNotification,
+ type WithSearch,
+} from '@entity';
import { notificationIsRead } from '@entity/utils/notification';
import { ensureNotificationSourceLoaded } from '@notifications/notification-helpers';
+import { hydrateChannelNotificationSelection } from '@queries/channel/notification-selection';
import {
useChannelLabelsQuery,
useCreateChannelLabelMutation,
@@ -47,6 +61,7 @@ import {
createUniqueId,
getOwner,
onCleanup,
+ startTransition,
} from 'solid-js';
import type { VirtualizerHandle } from 'virtua/solid';
import { useChannelsView } from '../../channels-view-context';
@@ -134,6 +149,68 @@ export function ChannelsRail(props: ChannelsRailProps) {
const panel = useSplitPanelOrThrow();
const layout = useSplitLayout();
const notificationSource = useGlobalNotificationSource();
+ const orchestrator = useGlobalBlockOrchestrator();
+ let activation = 0;
+ onCleanup(() => activation++);
+
+ const reportActivationError = (error: unknown) => {
+ console.error('Failed to open conversation', error);
+ toast.failure('Unable to open conversation. Please try again.');
+ };
+
+ const selectChannel = async (channel: WithNotification<ChannelEntity>) => {
+ try {
+ const entity = withEntityNotifications(channel, notificationSource);
+ const target = getChannelEntityTarget(entity, {
+ scopeChannelThreads: false,
+ });
+ const selection = {
+ ...entity,
+ target: target?.kind === 'message' ? target : undefined,
+ };
+ const previous = selectedChannel();
+ if (!setSelectedChannel(selection)) return;
+ // Repeated clicks must navigate even when the route stays the same.
+ if (
+ previous?.id === selection.id &&
+ previous.target?.messageId === selection.target?.messageId &&
+ previous.target?.threadId === selection.target?.threadId
+ ) {
+ await navigateChannelEntityToTarget(selection, orchestrator);
+ }
+ } catch (error) {
+ reportActivationError(error);
+ }
+ };
+
+ const selectHydratedChannel = async (
+ pending: Promise<WithNotification<ChannelEntity>>,
+ request: number
+ ) => {
+ 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);
+ });
+ } catch (error) {
+ if (request === activation) reportActivationError(error);
+ }
+ };
+
+ const activateChannel = (channel: ChannelEntity) => {
+ const request = ++activation;
+ const selection = hydrateChannelNotificationSelection(
+ channel,
+ notificationSource.withLocalOverrides
+ );
+ if (selection instanceof Promise) {
+ void selectHydratedChannel(selection, request);
+ } else {
+ void selectChannel(selection);
+ }
+ };
const favoritesData = useFavoritesData({ entityType: ['channel'] });
@@ -378,6 +455,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
row.channel.id === initialSelectedChannelId
)?.id,
onActivate: ({ item, metadata }) => {
+ activation++;
previewAfterNavigation.clear();
const openInNewSplit =
metadata?.newSplit === true || metadata?.event?.shiftKey === true;
@@ -414,11 +492,12 @@ export function ChannelsRail(props: ChannelsRailProps) {
return;
}
- setSelectedChannel(
+ const channel =
item.kind === 'conversation'
? item.channel
- : { type: 'channel', id: channelId }
- );
+ : channelsById().get(channelId);
+ if (channel) activateChannel(channel);
+ else setSelectedChannel({ type: 'channel', id: channelId });
},
})
);
@@ -629,6 +708,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
return false;
},
onNavigate: (event) => {
+ activation++;
listRoot()?.focus({ preventScroll: true });
previewAfterNavigation.clear();
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index 393bad743f..93f5f08122 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -125,6 +125,7 @@ import { type ChannelEntityTarget, type EntityData, queryKeys } from '@entity';
import type { NotificationSource, UnifiedNotification } from '@notifications';
import {
type CalendarPreviewSelection,
+ type ChannelPreviewSelection,
executeMarkEntitiesDone,
executeMarkEntitiesUndone,
getChannelEntityTarget,
@@ -320,6 +321,101 @@ const channelThreadRow = (opts?: {
...(opts?.notifications ? { notifications: () => opts.notifications } : {}),
}) as unknown as EntityData;
+describe('channel unread clicks', () => {
+ const newer = {
+ ...replyNotification('reply', 'newer', 'thread'),
+ created_at: '2026-09-24T12:00:00Z',
+ };
+ const older = {
+ ...sendNotification('send', 'older'),
+ created_at: '2026-09-23T12:00:00Z',
+ };
+
+ it('reads current unread state on every click without revisiting read targets', () => {
+ let notifications = [older, newer, { ...newer, id: 'mention' }];
+ const row: ChannelPreviewSelection = {
+ type: 'channel',
+ id: 'channel-1',
+ notifications: () => notifications,
+ };
+ const click = () =>
+ getChannelEntityTarget(row, { scopeChannelThreads: false });
+ expect(click()).toEqual({
+ kind: 'message',
+ messageId: 'newer',
+ threadId: 'thread',
+ });
+
+ notifications = [older, asRead(newer), asRead({ ...newer, id: 'mention' })];
+ expect(click()).toEqual({
+ kind: 'message',
+ messageId: 'older',
+ threadId: undefined,
+ });
+
+ notifications = notifications.map(asRead);
+ expect(click()).toEqual({ kind: 'latest' });
+ expect(click()).toEqual({ kind: 'latest' });
+
+ notifications.push({
+ ...older,
+ id: 'incoming',
+ created_at: '2026-09-25T12:00:00Z',
+ notification_metadata: {
+ ...older.notification_metadata,
+ content: {
+ ...older.notification_metadata.content,
+ messageId: 'incoming',
+ },
+ },
+ } as UnifiedNotification);
+ expect(click()).toMatchObject({ kind: 'message', messageId: 'incoming' });
+ });
+
+ it('uses new arrivals immediately while older notifications remain unread', () => {
+ let notifications = [older];
+ const row: ChannelPreviewSelection = {
+ type: 'channel',
+ id: 'channel-1',
+ notifications: () => notifications,
+ };
+ expect(
+ getChannelEntityTarget(row, { scopeChannelThreads: false })
+ ).toMatchObject({ messageId: 'older' });
+ notifications = [older, newer];
+ expect(
+ getChannelEntityTarget(row, { scopeChannelThreads: false })
+ ).toMatchObject({ messageId: 'newer' });
+ });
+
+ it('preserves Home row targets, including an already-read thread reply', () => {
+ const notifications = [
+ asRead({
+ ...replyNotification('read-reply', 'read-newest', 'thread'),
+ created_at: '2026-09-25T12:00:00Z',
+ }),
+ newer,
+ older,
+ ];
+ expect(getChannelEntityTarget(channelRow({ notifications }))).toMatchObject(
+ { messageId: 'older' }
+ );
+ const thread: ChannelPreviewSelection = {
+ type: 'channel_thread',
+ id: 'thread',
+ channelId: 'channel-1',
+ messageId: 'thread',
+ threadId: 'thread',
+ notifications: () => notifications,
+ };
+ expect(getChannelEntityTarget(thread)).toEqual({
+ kind: 'message',
+ messageId: 'read-newest',
+ threadId: 'thread',
+ });
+ });
+});
+
describe('resolveMarkEntitiesDoneVariables', () => {
it('uses notifications attached to a GraphQL Soup entity', () => {
const notification = sendNotification('notification-1', 'message-1');
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index e2dc261eb1..e5b03b6444 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -55,7 +55,7 @@ import {
} from '@core/dom-selectors';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import type { BlockOrchestrator } from '@core/orchestrator';
-import type { DateValue } from '@core/util/date';
+import { compareDateDesc, type DateValue } from '@core/util/date';
import { throwOnErr } from '@core/util/result';
import { waitForFrames } from '@core/util/sleep';
import { openExternalUrl } from '@core/util/url';
@@ -473,7 +473,8 @@ export type ChannelPreviewSelection = WithNotification<
>;
export function getChannelEntityTarget(
- entity: EntityData | ChannelPreviewSelection
+ entity: EntityData | ChannelPreviewSelection,
+ options: { scopeChannelThreads?: boolean } = {}
): ChannelClickTarget | undefined {
if (
entity.type !== 'channel' &&
@@ -502,10 +503,13 @@ export function getChannelEntityTarget(
if (!isWithNotification(entity)) return fallback;
- const scoped = scopeChannelNotificationsForEntity(
- entity,
- entity.notifications?.() ?? []
- );
+ const notifications = entity.notifications?.() ?? [];
+ const scoped =
+ options.scopeChannelThreads === false
+ ? [...notifications].sort((a, b) =>
+ compareDateDesc(a.created_at, b.created_at)
+ )
+ : scopeChannelNotificationsForEntity(entity, notifications);
for (const notification of scoped) {
// For a whole-`channel` row, ignore notifications you have already read:
// the row stands for the entire channel, so once read it should open at
diff --git a/apps/web/src/lib/queries/channel/notification-selection.test.ts b/apps/web/src/lib/queries/channel/notification-selection.test.ts
index 8d2e4f57ea..626c1e660d 100644
--- a/apps/web/src/lib/queries/channel/notification-selection.test.ts
+++ b/apps/web/src/lib/queries/channel/notification-selection.test.ts
@@ -22,12 +22,14 @@ const channel = (
describe('channel selection hydration', () => {
beforeEach(() => vi.clearAllMocks());
- it('does not load history for a read channel or a legacy row', async () => {
+ it('returns synchronously for a read channel or a legacy row', () => {
const legacy = channel(undefined);
- expect(await hydrateChannelNotificationSelection(legacy)).toBe(legacy);
- expect(
- (await hydrateChannelNotificationSelection(channel([]))).notifications?.()
- ).toEqual([]);
+ expect(hydrateChannelNotificationSelection(legacy)).toBe(legacy);
+ const read = hydrateChannelNotificationSelection(channel([]));
+ expect(read).not.toBeInstanceOf(Promise);
+ if (read instanceof Promise)
+ throw new Error('Unexpected notification fetch');
+ expect(read.notifications?.()).toEqual([]);
expect(fetchNotifications).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/lib/queries/channel/notification-selection.ts b/apps/web/src/lib/queries/channel/notification-selection.ts
index eb66daf425..4324a1164b 100644
--- a/apps/web/src/lib/queries/channel/notification-selection.ts
+++ b/apps/web/src/lib/queries/channel/notification-selection.ts
@@ -6,15 +6,25 @@ import type {
import { fetchGraphqlEntityNotifications } from '@service-storage/graphql-notifications';
import { buildGraphqlEntitySoupInput } from '../soup/graphql/entity-input';
-/** A limit-one edge cannot determine all mark-read IDs or thread membership. */
-export async function hydrateChannelNotificationSelection(
+/**
+ * Return immediately when no fetch is needed. A limit-one unread edge needs
+ * hydration to determine message targets, mark-read IDs, and thread membership.
+ */
+export function hydrateChannelNotificationSelection(
channel: ChannelEntity,
applyLocalOverrides?: (notification: Notification) => Notification
-): Promise<WithNotification<ChannelEntity>> {
+): WithNotification<ChannelEntity> | Promise<WithNotification<ChannelEntity>> {
if (channel.unreadNotifications === undefined) return channel;
if (channel.unreadNotifications.length === 0) {
return { ...channel, notifications: () => [] };
}
+ return fetchChannelNotificationSelection(channel, applyLocalOverrides);
+}
+
+async function fetchChannelNotificationSelection(
+ channel: ChannelEntity,
+ applyLocalOverrides?: (notification: Notification) => Notification
+): Promise<WithNotification<ChannelEntity>> {
const input = buildGraphqlEntitySoupInput('CHANNEL', channel.id);
if (!input) throw new Error('Invalid channel notification selection');
const notifications = await fetchGraphqlEntityNotifications(
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 9a08af02ab..d02277e4ba 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -493,6 +493,13 @@ 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.
+On desktop, each click on a conversation in the Chat rail opens its most recent
+currently unread notification, including replies in threads. Read notifications
+are not retained as click targets: once a channel has no unread
+notifications, 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.
+
With GraphQL enabled, the app-shell Chat badge uses `ChannelUnreadPresence`: only
channel IDs and at most one unread notification ID/state per channel, with a
500-channel candidate bound and no history, message previews, or metadata. It