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.

feat(notifications-inbox): filter the Unread tab on the server (#9933)

teo0d9845ed6ac5
diff --git a/apps/web/src/features/notifications-inbox/context/notifications-inbox-context.ts b/apps/web/src/features/notifications-inbox/context/notifications-inbox-context.ts
index d30f298edb..d32a730824 100644
--- a/apps/web/src/features/notifications-inbox/context/notifications-inbox-context.ts
+++ b/apps/web/src/features/notifications-inbox/context/notifications-inbox-context.ts
@@ -20,6 +20,11 @@ export type NotificationInboxRow = InboxRow<InboxRowContent>;
/** Which rows a feed shows; with no row types it shows and reads nothing. */
export type InboxScope = {
rowTypes: readonly InboxRowType[];
+ /**
+ * Only unread rows. The server filters, so pages and live changes cover
+ * unread rows alone.
+ */
+ unreadOnly?: boolean;
};
/** A completed done, which the caller can reverse once. */
diff --git a/apps/web/src/features/notifications-inbox/core/inbox-filters.test.ts b/apps/web/src/features/notifications-inbox/core/inbox-filters.test.ts
index 21bf1347f2..e9326486fe 100644
--- a/apps/web/src/features/notifications-inbox/core/inbox-filters.test.ts
+++ b/apps/web/src/features/notifications-inbox/core/inbox-filters.test.ts
@@ -6,7 +6,6 @@ import {
clearIncludes,
parseInboxFilters,
rowTypesFor,
- statusIncludes,
} from './inbox-filters';
describe('rowTypesFor', () => {
@@ -29,17 +28,6 @@ describe('rowTypesFor', () => {
});
});
-describe('statusIncludes', () => {
- it('narrows to unread rows', () => {
- expect(
- [true, false].filter((unseen) => statusIncludes('unread', unseen))
- ).toEqual([true]);
- expect(
- [true, false].filter((unseen) => statusIncludes('all', unseen))
- ).toEqual([true, false]);
- });
-});
-
describe('saved filters', () => {
it('counts hidden categories, not the toggle that shows its own state', () => {
expect(
diff --git a/apps/web/src/features/notifications-inbox/core/inbox-filters.ts b/apps/web/src/features/notifications-inbox/core/inbox-filters.ts
index a1f0b0e37e..ef1b42a607 100644
--- a/apps/web/src/features/notifications-inbox/core/inbox-filters.ts
+++ b/apps/web/src/features/notifications-inbox/core/inbox-filters.ts
@@ -143,14 +143,6 @@ export function clearIncludes(
);
}
-/** Whether a row's read state passes the status filter. */
-export function statusIncludes(status: InboxStatus, unseen: boolean): boolean {
- return match(status)
- .with('all', () => true)
- .with('unread', () => unseen)
- .exhaustive();
-}
-
/**
* How many kinds of notification are hidden, for the filter trigger's badge.
* The All and Unread toggle shows its own state.
diff --git a/apps/web/src/features/notifications-inbox/primitives/inbox-filters.test.ts b/apps/web/src/features/notifications-inbox/primitives/inbox-filters.test.ts
index b6a02eed68..5cdf186dfc 100644
--- a/apps/web/src/features/notifications-inbox/primitives/inbox-filters.test.ts
+++ b/apps/web/src/features/notifications-inbox/primitives/inbox-filters.test.ts
@@ -12,9 +12,6 @@ const memoryStorage = () => {
};
};
-const unread = { id: 'a', unseen: true };
-const read = { id: 'a', unseen: false };
-
describe('createInboxFilters', () => {
it('opens at the choice saved on the last visit', () => {
createRoot((dispose) => {
@@ -30,30 +27,18 @@ describe('createInboxFilters', () => {
});
});
- it('shows only unread rows under Unread, and every row under All', () => {
- createRoot((dispose) => {
- const filters = createInboxFilters(memoryStorage());
- expect(filters.includesRow(read)).toBe(true);
-
- filters.setStatus('unread');
- expect(filters.includesRow(unread)).toBe(true);
- expect(filters.includesRow(read)).toBe(false);
- dispose();
- });
- });
-
- it('keeps a row read under Unread until the reader next switches', () => {
+ it('asks the feed for unread rows only under Unread', () => {
createRoot((dispose) => {
const filters = createInboxFilters(memoryStorage());
- filters.setStatus('unread');
-
- filters.keepRead('a');
- expect(filters.includesRow(read)).toBe(true);
- expect(filters.includesRow({ id: 'b', unseen: false })).toBe(false);
+ expect(filters.scope().unreadOnly).toBe(false);
- filters.setStatus('all');
filters.setStatus('unread');
- expect(filters.includesRow(read)).toBe(false);
+ expect(filters.scope().unreadOnly).toBe(true);
+ filters.setShown('email', false);
+ expect(filters.scope()).toEqual({
+ rowTypes: filters.rowTypes(),
+ unreadOnly: true,
+ });
dispose();
});
});
diff --git a/apps/web/src/features/notifications-inbox/primitives/inbox-filters.ts b/apps/web/src/features/notifications-inbox/primitives/inbox-filters.ts
index 575c7c7a72..6f3a03c4b1 100644
--- a/apps/web/src/features/notifications-inbox/primitives/inbox-filters.ts
+++ b/apps/web/src/features/notifications-inbox/primitives/inbox-filters.ts
@@ -7,7 +7,6 @@ import {
type InboxStatus,
parseInboxFilters,
rowTypesFor,
- statusIncludes,
} from '../core/inbox-filters';
/** The reader's inbox filters, kept in `storage` between visits. */
@@ -22,9 +21,6 @@ export function createInboxFilters(storage: {
setFilters(next);
storage.write(JSON.stringify(next));
};
- // Opening a row reads it, and it shouldn't vanish from Unread while the reader
- // is on it or its stack. It leaves when they next choose All or Unread.
- const [readHere, setReadHere] = createSignal<ReadonlySet<string>>(new Set());
return {
filters,
@@ -34,16 +30,12 @@ export function createInboxFilters(storage: {
!filters().hiddenCategories.includes(category),
/** Every category is hidden, so nothing can show. */
showsNothing: () => rowTypesFor(filters()).length === 0,
- /** Whether a row shows under the chosen read state. */
- includesRow: (row: { id: string; unseen: boolean }) =>
- statusIncludes(filters().status, row.unseen) || readHere().has(row.id),
- /** Keep a row the reader just read showing until they next switch. */
- keepRead: (rowId: string) =>
- setReadHere((kept) => new Set(kept).add(rowId)),
- setStatus: (status: InboxStatus) => {
- setReadHere(new Set<string>());
- save({ ...filters(), status });
- },
+ /** The rows the feed reads: these kinds, and only unread ones under Unread. */
+ scope: () => ({
+ rowTypes: rowTypesFor(filters()),
+ unreadOnly: filters().status === 'unread',
+ }),
+ setStatus: (status: InboxStatus) => save({ ...filters(), status }),
setShown: (category: InboxCategory, shown: boolean) => {
const hidden = filters().hiddenCategories.filter(
(hiddenCategory) => hiddenCategory !== category
diff --git a/apps/web/src/features/notifications-inbox/primitives/inbox-list.test.ts b/apps/web/src/features/notifications-inbox/primitives/inbox-list.test.ts
index 11bc2752a5..0f11d6becf 100644
--- a/apps/web/src/features/notifications-inbox/primitives/inbox-list.test.ts
+++ b/apps/web/src/features/notifications-inbox/primitives/inbox-list.test.ts
@@ -92,27 +92,7 @@ describe('createInboxList', () => {
expect(list.view()).toMatchObject({ t: 'ready', rows: [] });
setHasMore(false);
- expect(list.view()).toEqual({ t: 'empty', filtered: false });
- dispose();
- });
- });
-
- it('shows only the rows the filter admits, and says when it hid them all', () => {
- createRoot((dispose) => {
- const { feed, setRows } = fakeFeed();
- const [unreadOnly, setUnreadOnly] = createSignal(false);
- const read = { ...row('b#task'), unseen: false };
- const list = createInboxList(
- feed,
- notices().value,
- (candidate) => !unreadOnly() || candidate.unseen
- );
- setRows([row('a#task'), read]);
- setUnreadOnly(true);
- expect(list.view()).toMatchObject({ t: 'ready', rows: [row('a#task')] });
-
- setRows([read]);
- expect(list.view()).toEqual({ t: 'empty', filtered: true });
+ expect(list.view()).toEqual({ t: 'empty' });
dispose();
});
});
diff --git a/apps/web/src/features/notifications-inbox/primitives/inbox-list.ts b/apps/web/src/features/notifications-inbox/primitives/inbox-list.ts
index df3f7d35c9..d0c782e404 100644
--- a/apps/web/src/features/notifications-inbox/primitives/inbox-list.ts
+++ b/apps/web/src/features/notifications-inbox/primitives/inbox-list.ts
@@ -12,8 +12,7 @@ import { traceInboxClear, traceInboxRows } from './inbox-telemetry';
export type InboxListView =
| { t: 'loading' }
| { t: 'error' }
- /** `filtered` when rows exist but the status filter hides them all. */
- | { t: 'empty'; filtered: boolean }
+ | { t: 'empty' }
| {
t: 'ready';
rows: readonly NotificationInboxRow[];
@@ -52,8 +51,7 @@ export type InboxDoneNotices = {
*/
export function createInboxList(
feed: InboxFeedSource,
- notices: InboxDoneNotices,
- include: (row: NotificationInboxRow) => boolean = () => true
+ notices: InboxDoneNotices
) {
const view = (): InboxListView => {
const loaded = feed.rows();
@@ -61,11 +59,9 @@ export function createInboxList(
if (loaded === undefined) {
return error ? { t: 'error' } : { t: 'loading' };
}
- const rows = loaded.filter(include);
+ const rows = loaded;
if (rows.length === 0 && !feed.hasMore()) {
- return error
- ? { t: 'error' }
- : { t: 'empty', filtered: loaded.length > 0 };
+ return error ? { t: 'error' } : { t: 'empty' };
}
return {
t: 'ready',
diff --git a/apps/web/src/features/notifications-inbox/queries/decode.test.ts b/apps/web/src/features/notifications-inbox/queries/decode.test.ts
index f06df9a0f1..c03c589ded 100644
--- a/apps/web/src/features/notifications-inbox/queries/decode.test.ts
+++ b/apps/web/src/features/notifications-inbox/queries/decode.test.ts
@@ -299,4 +299,10 @@ describe('encodeInboxScope', () => {
{ rowTypes: ['EMAIL', 'CHANNEL_THREAD'] }
);
});
+
+ it('asks the server for unread rows only when the scope is unread', () => {
+ expect(
+ encodeInboxScope({ rowTypes: ALL_INBOX_ROW_TYPES, unreadOnly: true })
+ ).toEqual({ rowTypes: [], unreadOnly: true });
+ });
});
diff --git a/apps/web/src/features/notifications-inbox/queries/decode.ts b/apps/web/src/features/notifications-inbox/queries/decode.ts
index 67ddffa40f..1abb505f90 100644
--- a/apps/web/src/features/notifications-inbox/queries/decode.ts
+++ b/apps/web/src/features/notifications-inbox/queries/decode.ts
@@ -105,7 +105,8 @@ export function encodeInboxScope(
const everyType = ALL_INBOX_ROW_TYPES.every((type) =>
scope.rowTypes.includes(type)
);
- return { rowTypes: everyType ? [] : scope.rowTypes.map(toGraphqlRowType) };
+ const rowTypes = everyType ? [] : scope.rowTypes.map(toGraphqlRowType);
+ return scope.unreadOnly ? { rowTypes, unreadOnly: true } : { rowTypes };
}
/**
diff --git a/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.test.ts b/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.test.ts
index e6c5958803..df07a98561 100644
--- a/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.test.ts
+++ b/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.test.ts
@@ -326,7 +326,6 @@ describe('createNotificationInboxSource', () => {
{
input: {
scope: { rowTypes: ['TASK'] },
- unreadOnly: false,
since: null,
cursor: null,
},
@@ -518,6 +517,79 @@ describe('createNotificationInboxSource', () => {
expect(row('document:doc-a#top_level').unseen).toBe(false);
});
+ it('reads unread rows from the server under Unread, live changes too', async () => {
+ vi.useFakeTimers();
+ const { fake } = setup({}, () => ({
+ rowTypes: ALL_INBOX_ROW_TYPES,
+ unreadOnly: true,
+ }));
+ await flush();
+
+ const unreadScope = { rowTypes: [], unreadOnly: true };
+ expect(fake.queries[0].variables).toEqual({
+ input: { scope: unreadScope, limit: 50, cursor: null },
+ });
+ expect(fake.subscriptions[0].variables).toEqual({ scope: unreadScope });
+ });
+
+ it('keeps a row read here under Unread until the scope changes', async () => {
+ vi.useFakeTimers();
+ const [scope, setScope] = createSignal<InboxScope>({
+ rowTypes: ALL_INBOX_ROW_TYPES,
+ unreadOnly: true,
+ });
+ const { fake, feed, row, rowIds } = setup(
+ {
+ // Read, doc-b leaves the server's unread inbox.
+ MarkNotificationInboxRowsSeen: {
+ markNotificationInboxRowsSeen: {
+ patches: [removedPatch(docB.groupId)],
+ },
+ },
+ },
+ scope
+ );
+ await flush();
+ fake.queries[0].resolve(inboxPage([docA, docB]));
+ await flush();
+
+ await feed.markSeen([row('document:doc-b#top_level')]);
+ await flush();
+ expect(rowIds()).toContain('document:doc-b#top_level');
+ expect(row('document:doc-b#top_level').unseen).toBe(false);
+
+ setScope({ rowTypes: ALL_INBOX_ROW_TYPES });
+ await flush();
+ setScope({ rowTypes: ALL_INBOX_ROW_TYPES, unreadOnly: true });
+ await flush();
+ fake.queries.at(-1)?.resolve(inboxPage([docA]));
+ await flush();
+ expect(rowIds()).not.toContain('document:doc-b#top_level');
+ });
+
+ it('clears unread rows by the scope it sends', async () => {
+ vi.useFakeTimers();
+ const { fake, feed } = await loaded({
+ ClearNotificationInbox: {
+ clearNotificationInbox: {
+ rowCount: 1,
+ undoToken: 'undo-1',
+ nextCursor: null,
+ },
+ },
+ });
+
+ await feed.clear({ rowTypes: ALL_INBOX_ROW_TYPES, unreadOnly: true });
+
+ expect(fake.mutations[0].variables).toEqual({
+ input: {
+ scope: { rowTypes: [], unreadOnly: true },
+ since: null,
+ cursor: null,
+ },
+ });
+ });
+
it('reads the row as unseen again when marking it seen fails', async () => {
vi.useFakeTimers();
const { feed, row } = await loaded();
diff --git a/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.ts b/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.ts
index f483c2988f..af545883e5 100644
--- a/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.ts
+++ b/apps/web/src/features/notifications-inbox/queries/notification-inbox-source.ts
@@ -16,6 +16,7 @@ import {
createComputed,
createMemo,
createSignal,
+ on,
} from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import type {
@@ -25,6 +26,7 @@ import type {
} from '../context/notifications-inbox-context';
import { clearIncludes, type InboxClear } from '../core/inbox-filters';
import {
+ compareInboxRows,
markRows,
type RowMarks,
settleRowMarks,
@@ -197,12 +199,25 @@ export function createNotificationInboxSource(
surface: 'notifications-inbox',
});
+ // Under Unread the server drops a row once it is read. One the reader read
+ // here stays listed, read, until the scope changes, so it doesn't vanish
+ // while they are on it; a newer copy from the server replaces it.
+ const [kept, setKept] = createSignal<readonly NotificationInboxRow[]>([]);
+ createComputed(on(scopeInput, () => setKept([])));
+ const listed = () => {
+ const present = new Set(ordered.map((row) => row.id));
+ const extra = kept().filter((row) => !present.has(row.id));
+ return extra.length === 0
+ ? ordered
+ : [...ordered, ...extra].sort(compareInboxRows);
+ };
+
const rows = createMemo(() =>
query.data === undefined
? undefined
: withSeenRows(
withoutDoneNotifications(
- withoutDoneRows(ordered, done()),
+ withoutDoneRows(listed(), done()),
doneNotifications()
),
seen()
@@ -303,8 +318,10 @@ export function createNotificationInboxSource(
const hiddenIds = hidden.map((row) => row.id);
setDone((current) => markRows(current, hidden));
const input = {
- scope: encodeInboxScope({ rowTypes: request.rowTypes }),
- unreadOnly: request.unreadOnly,
+ scope: encodeInboxScope({
+ rowTypes: request.rowTypes,
+ unreadOnly: request.unreadOnly,
+ }),
since:
request.since === undefined
? null
@@ -352,12 +369,19 @@ export function createNotificationInboxSource(
const client = options.client();
const ids = unseen.map((row) => row.id);
setSeen((current) => markRows(current, unseen));
+ if (options.scope().unreadOnly) {
+ setKept((current) => [
+ ...current.filter((row) => !ids.includes(row.id)),
+ ...unseen.map((row) => ({ ...row, unseen: false })),
+ ]);
+ }
try {
const scope = scopeInput();
const patches = await markInboxRowsSeen(client, ids, scope);
applyIfCurrent(scope, patches);
} catch (error) {
setSeen((current) => unmarkRows(current, ids));
+ setKept((current) => current.filter((row) => !ids.includes(row.id)));
throw error;
}
revalidate(client);
diff --git a/apps/web/src/features/notifications-inbox/views/notifications-view.tsx b/apps/web/src/features/notifications-inbox/views/notifications-view.tsx
index 708043c3bd..6dc04fe9c7 100644
--- a/apps/web/src/features/notifications-inbox/views/notifications-view.tsx
+++ b/apps/web/src/features/notifications-inbox/views/notifications-view.tsx
@@ -254,54 +254,47 @@ export function NotificationsView(props: NotificationsViewProps) {
const context = useNotificationsInboxContext();
const { pushUndo } = useMutationUndoContext();
const filters = createInboxFilters(context.filterStorage);
- const feed = context.createFeed(() => ({ rowTypes: filters.rowTypes() }));
- const inbox = createInboxList(
- feed,
- {
- pushUndo: (entry) => pushUndo(entry),
- announceDone: (count, undo) => {
- const id = toast.success(
- t('notificationsInbox.markedDone', { count }),
+ const feed = context.createFeed(filters.scope);
+ const inbox = createInboxList(feed, {
+ pushUndo: (entry) => pushUndo(entry),
+ announceDone: (count, undo) => {
+ const id = toast.success(t('notificationsInbox.markedDone', { count }), {
+ actions: [
{
- actions: [
- {
- label: t('notificationsInbox.undo'),
- icon: ArrowCounterClockwise,
- onClick: () => fireAndForget(undo(), 'notifications-inbox'),
- },
- ],
- duration: 3_000,
- stack: true,
- hideOnMobile: true,
- }
- );
- return () => {
- if (id !== undefined) toast.dismiss(id);
- };
- },
- announceCleared: (count, undo) => {
- const id =
- count === 0
- ? toast.success(t('notificationsInbox.clearedNothing'))
- : toast.success(t('notificationsInbox.cleared', { count }), {
- actions: [
- {
- label: t('notificationsInbox.undo'),
- icon: ArrowCounterClockwise,
- onClick: () => fireAndForget(undo(), 'notifications-inbox'),
- },
- ],
- duration: 8_000,
- stack: true,
- });
- return () => {
- if (id !== undefined) toast.dismiss(id);
- };
- },
- announceFailure: (message) => toast.failure(message),
+ label: t('notificationsInbox.undo'),
+ icon: ArrowCounterClockwise,
+ onClick: () => fireAndForget(undo(), 'notifications-inbox'),
+ },
+ ],
+ duration: 3_000,
+ stack: true,
+ hideOnMobile: true,
+ });
+ return () => {
+ if (id !== undefined) toast.dismiss(id);
+ };
},
- filters.includesRow
- );
+ announceCleared: (count, undo) => {
+ const id =
+ count === 0
+ ? toast.success(t('notificationsInbox.clearedNothing'))
+ : toast.success(t('notificationsInbox.cleared', { count }), {
+ actions: [
+ {
+ label: t('notificationsInbox.undo'),
+ icon: ArrowCounterClockwise,
+ onClick: () => fireAndForget(undo(), 'notifications-inbox'),
+ },
+ ],
+ duration: 8_000,
+ stack: true,
+ });
+ return () => {
+ if (id !== undefined) toast.dismiss(id);
+ };
+ },
+ announceFailure: (message) => toast.failure(message),
+ });
onMount(() => panel.handle.setDisplayName(t('nav.notifications')));
@@ -369,7 +362,6 @@ export function NotificationsView(props: NotificationsViewProps) {
const markSeen = (row: NotificationInboxRow) => {
if (!row.unseen) return;
- filters.keepRead(row.id);
fireAndForget(feed.markSeen([row]), 'notifications-inbox');
};
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index 6838281de5..230f5dfdc1 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -174,7 +174,10 @@ export type ClearNotificationInboxInput = {
* after it.
*/
since?: string | null | undefined;
- /** Clear only unread rows. */
+ /**
+ * Clear only unread rows.
+ * @deprecated Set scope.unreadOnly. Remove after 2026-12-06.
+ */
unreadOnly?: boolean | null | undefined;
};
@@ -2394,6 +2397,11 @@ export type NotificationInboxRowType =
export type NotificationInboxScopeInput = {
/** Row kinds to include; omitted or empty means every kind. */
rowTypes?: Array<NotificationInboxRowType> | null | undefined;
+ /**
+ * Only unread rows; pages, cursors and updates then cover unread rows
+ * alone. Defaults to false.
+ */
+ unreadOnly?: boolean | null | undefined;
};
/** The notification state as represented by GraphQL variables and responses. */
diff --git a/crates/complete_graph/src/schema/test/notification_inbox.rs b/crates/complete_graph/src/schema/test/notification_inbox.rs
index fea84de64f..b4d6d88581 100644
--- a/crates/complete_graph/src/schema/test/notification_inbox.rs
+++ b/crates/complete_graph/src/schema/test/notification_inbox.rs
@@ -303,7 +303,7 @@ async fn notification_inbox_pages_groups_with_their_rows() {
harness
.request(
r#"{ user { notificationInbox(input: {
- scope: { rowTypes: [DISCUSSION_THREAD, AGENT] },
+ scope: { rowTypes: [DISCUSSION_THREAD, AGENT], unreadOnly: true },
limit: 10
}) {
nextCursor
@@ -360,6 +360,7 @@ async fn notification_inbox_pages_groups_with_their_rows() {
pages[0].scope.row_types,
vec![InboxRowType::DiscussionThread, InboxRowType::Agent]
);
+ assert!(pages[0].scope.unread_only);
assert_eq!(pages[0].limit, 10);
}
@@ -512,7 +513,7 @@ async fn the_inbox_is_cleared_one_batch_at_a_time() {
harness
.request(
r#"mutation { clearNotificationInbox(input: {
- scope: { rowTypes: [EMAIL] }, unreadOnly: true,
+ scope: { rowTypes: [EMAIL], unreadOnly: true },
since: "2024-06-01T00:00:00+02:00", limit: 150
}) { rowCount undoToken nextCursor } }"#,
authenticated_parts(),
@@ -538,7 +539,7 @@ async fn the_inbox_is_cleared_one_batch_at_a_time() {
assert_eq!(FeedPosition::decode(cursor).unwrap().sort_at, at(7));
let clears = service.clears.lock().unwrap();
assert_eq!(clears[0].scope.row_types, vec![InboxRowType::Email]);
- assert!(clears[0].unread_only);
+ assert!(clears[0].scope.unread_only);
assert_eq!(
clears[0].since,
Some(
@@ -583,7 +584,7 @@ async fn notification_inbox_updates_batch_recomputed_patches() {
FeedKey::new(ModelEntityType::Chat.with_entity_string(Uuid::from_u128(0xC4A7).to_string()));
let request = async_graphql::Request::new(
- r#"subscription { notificationInboxUpdates(scope: { rowTypes: [DISCUSSION_THREAD] }) {
+ r#"subscription { notificationInboxUpdates(scope: { rowTypes: [DISCUSSION_THREAD], unreadOnly: true }) {
__typename
... on NotificationInboxEntryUpserted { entry { groupId rows { id } } }
... on NotificationInboxEntryRemoved { groupId }
@@ -631,6 +632,7 @@ async fn notification_inbox_updates_batch_recomputed_patches() {
{
let recomputes = service.recomputes.lock().unwrap();
assert_eq!(recomputes.len(), 1);
+ assert!(recomputes[0].0.unread_only);
assert_eq!(recomputes[0].1, vec![doc_group(), other.clone()]);
}
assert_eq!(
diff --git a/crates/graphql_notification_inbox/src/inputs.rs b/crates/graphql_notification_inbox/src/inputs.rs
index a5576bc815..ec8b1e4f3e 100644
--- a/crates/graphql_notification_inbox/src/inputs.rs
+++ b/crates/graphql_notification_inbox/src/inputs.rs
@@ -102,6 +102,9 @@ impl From<InboxRowType> for GraphqlNotificationInboxRowType {
pub struct NotificationInboxScopeInput {
/// Row kinds to include; omitted or empty means every kind.
pub row_types: Option<Vec<GraphqlNotificationInboxRowType>>,
+ /// Only unread rows; pages, cursors and updates then cover unread rows
+ /// alone. Defaults to false.
+ pub unread_only: Option<bool>,
}
impl NotificationInboxScopeInput {
@@ -114,6 +117,7 @@ impl NotificationInboxScopeInput {
.into_iter()
.map(Into::into)
.collect(),
+ unread_only: self.unread_only.unwrap_or(false),
}
}
}
@@ -158,6 +162,7 @@ pub struct ClearNotificationInboxInput {
/// Which rows are cleared; the inbox the caller shows.
pub scope: Option<NotificationInboxScopeInput>,
/// Clear only unread rows.
+ #[graphql(deprecation = "Set scope.unreadOnly. Remove after 2026-12-06.")]
pub unread_only: Option<bool>,
/// RFC 3339 time; clear only rows whose newest notification arrived at or
/// after it.
@@ -184,9 +189,10 @@ impl ClearNotificationInboxInput {
.transpose()
.map_err(|_| async_graphql::Error::new("invalid notification inbox clear time"))?
.map(|since| since.with_timezone(&Utc));
+ let mut scope = self.scope.unwrap_or_default().into_scope();
+ scope.unread_only |= self.unread_only.unwrap_or(false);
Ok(InboxClearRequest {
- scope: self.scope.unwrap_or_default().into_scope(),
- unread_only: self.unread_only.unwrap_or(false),
+ scope,
since,
limit: u16::try_from(limit).expect("limit is capped below u16::MAX"),
after,
diff --git a/crates/graphql_notification_inbox/src/inputs/test.rs b/crates/graphql_notification_inbox/src/inputs/test.rs
index db6fd04517..8f7d5a217e 100644
--- a/crates/graphql_notification_inbox/src/inputs/test.rs
+++ b/crates/graphql_notification_inbox/src/inputs/test.rs
@@ -30,12 +30,46 @@ fn scope_input_maps_row_types() {
GraphqlNotificationInboxRowType::Agent,
GraphqlNotificationInboxRowType::ChannelThread,
]),
+ unread_only: None,
}
.into_scope();
assert_eq!(
scope.row_types,
vec![InboxRowType::Agent, InboxRowType::ChannelThread]
);
+ assert!(!scope.unread_only);
+}
+
+#[test]
+fn scope_input_carries_unread_only_into_pages_and_clears() {
+ let unread = || NotificationInboxScopeInput {
+ row_types: None,
+ unread_only: Some(true),
+ };
+ let query = NotificationInboxInput {
+ scope: Some(unread()),
+ ..Default::default()
+ }
+ .into_query()
+ .unwrap();
+ assert!(query.scope.unread_only);
+
+ let clear = ClearNotificationInboxInput {
+ scope: Some(unread()),
+ ..Default::default()
+ }
+ .into_request()
+ .unwrap();
+ assert!(clear.scope.unread_only);
+
+ // Older clients name it beside the scope.
+ let legacy = ClearNotificationInboxInput {
+ unread_only: Some(true),
+ ..Default::default()
+ }
+ .into_request()
+ .unwrap();
+ assert!(legacy.scope.unread_only);
}
const ROW: &str = "channel:11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa#top_level";
diff --git a/crates/notification_inbox/AGENTS.md b/crates/notification_inbox/AGENTS.md
index d0a1d0226c..728c02b2c5 100644
--- a/crates/notification_inbox/AGENTS.md
+++ b/crates/notification_inbox/AGENTS.md
@@ -56,6 +56,9 @@ or agent session). Built on the shared feed layer, `crates/attention_feed`.
(`groupId`, `principalId`, `targetId`).
- Row contents must not depend on the scope; scopes only filter rows, so the
web cache can normalize rows by id across inboxes.
+- An unread scope filters on each row's `unseen`, which follows the row's own
+ rule (mail by its unread messages), so a row leaves or returns through the
+ same recompute as any other change.
## Related
diff --git a/crates/notification_inbox/src/domain/models.rs b/crates/notification_inbox/src/domain/models.rs
index 130c11e2cb..0836071c19 100644
--- a/crates/notification_inbox/src/domain/models.rs
+++ b/crates/notification_inbox/src/domain/models.rs
@@ -203,12 +203,18 @@ pub struct InboxEntry<E> {
pub struct InboxScope {
/// The row kinds to include; empty means every kind.
pub row_types: Vec<InboxRowType>,
+ /// Only unread rows, by each row's own unread rule (mail by its unread
+ /// messages). Pages, cursors and live changes are then over unread rows
+ /// alone, so a row read elsewhere leaves and one with new activity
+ /// returns.
+ pub unread_only: bool,
}
impl InboxScope {
- /// Whether the scope lists rows of `row_type`.
- pub fn admits(&self, row_type: InboxRowType) -> bool {
- self.row_types.is_empty() || self.row_types.contains(&row_type)
+ /// Whether the scope lists `row`.
+ pub fn admits(&self, row: &InboxRow) -> bool {
+ (self.row_types.is_empty() || self.row_types.contains(&row.row_type))
+ && (!self.unread_only || row.unseen)
}
}
@@ -256,10 +262,8 @@ pub struct InboxRowTarget {
/// marked done.
#[derive(Debug, Clone)]
pub struct InboxClearRequest {
- /// Which rows are cleared.
+ /// Which rows are cleared; an unread scope clears unread rows only.
pub scope: InboxScope,
- /// Clear only unread rows.
- pub unread_only: bool,
/// Clear only rows whose newest notification arrived at or after this
/// time; older groups end the clear.
pub since: Option<DateTime<Utc>>,
diff --git a/crates/notification_inbox/src/domain/models/test.rs b/crates/notification_inbox/src/domain/models/test.rs
index 54360a63a8..3a298850c3 100644
--- a/crates/notification_inbox/src/domain/models/test.rs
+++ b/crates/notification_inbox/src/domain/models/test.rs
@@ -27,12 +27,39 @@ fn malformed_row_ids_are_rejected() {
}
}
+fn bare_row(row_type: InboxRowType, unseen: bool) -> InboxRow {
+ InboxRow {
+ id: InboxRowId {
+ group: FeedKey::new(EntityType::Channel.with_entity_string(uuid(1).to_string())),
+ slot: "top_level".to_string(),
+ },
+ row_type,
+ thread_id: None,
+ actor: None,
+ actions: Vec::new(),
+ notifications: Vec::new(),
+ hidden: Vec::new(),
+ unseen,
+ }
+}
+
#[test]
fn an_empty_scope_admits_every_row_type() {
- assert!(InboxScope::default().admits(InboxRowType::Email));
+ assert!(InboxScope::default().admits(&bare_row(InboxRowType::Email, false)));
let scope = InboxScope {
row_types: vec![InboxRowType::Task],
+ ..Default::default()
+ };
+ assert!(scope.admits(&bare_row(InboxRowType::Task, false)));
+ assert!(!scope.admits(&bare_row(InboxRowType::Email, true)));
+}
+
+#[test]
+fn an_unread_scope_admits_unread_rows_only() {
+ let scope = InboxScope {
+ unread_only: true,
+ ..Default::default()
};
- assert!(scope.admits(InboxRowType::Task));
- assert!(!scope.admits(InboxRowType::Email));
+ assert!(scope.admits(&bare_row(InboxRowType::Email, true)));
+ assert!(!scope.admits(&bare_row(InboxRowType::Email, false)));
}
diff --git a/crates/notification_inbox/src/domain/service.rs b/crates/notification_inbox/src/domain/service.rs
index 4a86f17335..87c5c12a6f 100644
--- a/crates/notification_inbox/src/domain/service.rs
+++ b/crates/notification_inbox/src/domain/service.rs
@@ -178,7 +178,7 @@ impl<E> Group<E> {
let rows: Vec<InboxRow> = self
.rows
.into_iter()
- .filter(|row| scope.admits(row.row_type))
+ .filter(|row| scope.admits(row))
.collect();
(!rows.is_empty()).then_some(InboxEntry {
group: self.key,
@@ -221,8 +221,7 @@ struct ClearedGroup {
impl InboxClearRequest {
/// Whether the request clears `row`.
fn clears(&self, row: &InboxRow) -> bool {
- self.scope.admits(row.row_type)
- && (!self.unread_only || row.unseen)
+ self.scope.admits(row)
&& self
.since
.is_none_or(|since| row.latest().created_at >= since)
@@ -307,6 +306,7 @@ where
user = %viewer.user,
limit = query.limit,
row_types = query.scope.row_types.len(),
+ unread_only = query.scope.unread_only,
groups = tracing::field::Empty,
rows = tracing::field::Empty,
),
@@ -477,7 +477,7 @@ where
fields(
user = %viewer.user,
row_types = request.scope.row_types.len(),
- unread_only = request.unread_only,
+ unread_only = request.scope.unread_only,
since = request.since.is_some(),
rows = tracing::field::Empty,
notifications = tracing::field::Empty,
diff --git a/crates/notification_inbox/src/domain/service/test.rs b/crates/notification_inbox/src/domain/service/test.rs
index e202beb0fd..488471f42b 100644
--- a/crates/notification_inbox/src/domain/service/test.rs
+++ b/crates/notification_inbox/src/domain/service/test.rs
@@ -1,6 +1,6 @@
use attention_feed::{
domain::{
- models::{Candidate, FeedNotification, FeedRevision},
+ models::{Candidate, FeedNotification, FeedPosition, FeedRevision},
ports::NotificationTransition,
},
test_support::*,
@@ -73,7 +73,10 @@ fn thread_slot() -> String {
fn query(row_types: Vec<InboxRowType>) -> InboxQuery {
InboxQuery {
- scope: InboxScope { row_types },
+ scope: InboxScope {
+ row_types,
+ ..Default::default()
+ },
limit: 50,
after: None,
}
@@ -488,7 +491,6 @@ async fn done_on_a_notification_the_row_no_longer_shows_acknowledges_nothing() {
fn clear_request(scope: InboxScope) -> InboxClearRequest {
InboxClearRequest {
scope,
- unread_only: false,
since: None,
limit: 50,
after: None,
@@ -526,6 +528,7 @@ async fn clear_takes_only_the_rows_the_request_names() {
since: Some(at(8)),
..clear_request(InboxScope {
row_types: vec![InboxRowType::ChannelMention, InboxRowType::ChannelMessages],
+ ..Default::default()
})
},
)
@@ -571,10 +574,10 @@ async fn clear_of_unread_rows_leaves_read_ones() {
.service
.clear(
viewer(),
- InboxClearRequest {
+ clear_request(InboxScope {
unread_only: true,
- ..clear_request(InboxScope::default())
- },
+ ..Default::default()
+ }),
)
.await
.unwrap();
@@ -705,3 +708,190 @@ async fn recompute_removes_groups_with_no_matching_row() {
assert!(matches!(&changes[0], InboxChange::Upserted(entry) if entry.group == channel()));
assert!(matches!(&changes[1], InboxChange::Removed(removed) if *removed == doc));
}
+
+fn unread() -> InboxScope {
+ InboxScope {
+ unread_only: true,
+ ..Default::default()
+ }
+}
+
+fn unread_query(limit: u16, after: Option<FeedPosition>) -> InboxQuery {
+ InboxQuery {
+ scope: unread(),
+ limit,
+ after,
+ }
+}
+
+/// Mail read by its own state: one thread with an unread message whose
+/// notification was seen, one read thread whose notification wasn't; a
+/// channel whose thread is read and top level unread; a read document task.
+fn mostly_read() -> Harness {
+ let unread_mail = MailFacts {
+ inbox_visible: true,
+ is_read: false,
+ };
+ let read_mail = MailFacts {
+ inbox_visible: true,
+ is_read: true,
+ };
+ let mut seen_reply = channel_reply(4, CHANNEL, ROOT, 0x101, 9);
+ std::sync::Arc::make_mut(&mut seen_reply).state = NotificationState::Seen;
+ harness(
+ vec![
+ candidate("doc", entity(EntityType::Document, DOC), Some(10), None),
+ candidate("channel", channel().into_entity(), Some(9), None),
+ mail_candidate("unread mail", MAIL, Some(7), None, unread_mail),
+ mail_candidate("read mail", ARCHIVED, Some(6), None, read_mail),
+ ],
+ vec![
+ notification(
+ 1,
+ entity(EntityType::Document, DOC),
+ "task_assigned",
+ json!({ "taskId": "task-1", "assignedBy": "macro|[email protected]", "taskName": "Plan" }),
+ 10,
+ NotificationState::Seen,
+ ),
+ channel_send(2, CHANNEL, 0x100, 2),
+ seen_reply,
+ new_email(5, MAIL, 7, NotificationState::Seen),
+ new_email(6, ARCHIVED, 6, NotificationState::Unseen),
+ ],
+ )
+}
+
+#[tokio::test]
+async fn an_unread_page_lists_only_unread_rows_by_each_rows_rule() {
+ let harness = mostly_read();
+ let page = harness
+ .service
+ .page(viewer(), unread_query(50, None))
+ .await
+ .unwrap();
+
+ let listed: Vec<_> = page
+ .entries
+ .iter()
+ .map(|entry| {
+ let slots: Vec<_> = entry.rows.iter().map(|row| row.id.slot.clone()).collect();
+ (entry.entity, slots)
+ })
+ .collect();
+ // The read task and the read thread are left out; mail follows its own
+ // read state, not whether its notification was seen.
+ assert_eq!(
+ listed,
+ vec![
+ ("channel", vec!["top_level".to_string()]),
+ ("unread mail", vec!["email".to_string()]),
+ ]
+ );
+ assert!(
+ page.entries
+ .iter()
+ .flat_map(|entry| &entry.rows)
+ .all(|row| row.unseen)
+ );
+}
+
+#[tokio::test]
+async fn unread_pages_and_cursors_cover_unread_groups_only() {
+ let harness = mostly_read();
+ let first = harness
+ .service
+ .page(viewer(), unread_query(1, None))
+ .await
+ .unwrap();
+ assert_eq!(
+ first
+ .entries
+ .iter()
+ .map(|entry| entry.entity)
+ .collect::<Vec<_>>(),
+ vec!["channel"],
+ "the read document before it doesn't take the page's one place"
+ );
+ let second = harness
+ .service
+ .page(viewer(), unread_query(1, first.next))
+ .await
+ .unwrap();
+ assert_eq!(
+ second
+ .entries
+ .iter()
+ .map(|entry| entry.entity)
+ .collect::<Vec<_>>(),
+ vec!["unread mail"]
+ );
+ if let Some(after) = second.next {
+ let third = harness
+ .service
+ .page(viewer(), unread_query(1, Some(after)))
+ .await
+ .unwrap();
+ assert!(third.entries.is_empty(), "the read mail never lists");
+ assert!(third.next.is_none());
+ }
+}
+
+#[tokio::test]
+async fn reading_a_row_takes_it_out_of_an_unread_inbox() {
+ let harness = inbox();
+ let changes = harness
+ .service
+ .mark_seen(viewer(), unread(), vec![row(&channel(), &thread_slot())])
+ .await
+ .unwrap();
+ let InboxChange::Upserted(entry) = &changes[0] else {
+ panic!("the channel's top level is still unread");
+ };
+ let slots: Vec<_> = entry.rows.iter().map(|row| row.id.slot.clone()).collect();
+ assert_eq!(slots, vec!["top_level".to_string()]);
+
+ let changes = harness
+ .service
+ .mark_seen(viewer(), unread(), vec![row(&channel(), "top_level")])
+ .await
+ .unwrap();
+ assert!(matches!(&changes[0], InboxChange::Removed(removed) if *removed == channel()));
+}
+
+#[tokio::test]
+async fn new_activity_brings_a_read_row_back_into_an_unread_inbox() {
+ let harness = mostly_read();
+ let doc = key(entity(EntityType::Document, DOC));
+ let changes = harness
+ .service
+ .recompute(viewer(), unread(), vec![doc.clone()])
+ .await
+ .unwrap();
+ assert!(matches!(&changes[0], InboxChange::Removed(removed) if *removed == doc));
+
+ harness
+ .notifications
+ .by_entity
+ .lock()
+ .unwrap()
+ .get_mut(doc.entity())
+ .unwrap()
+ .push(notification(
+ 8,
+ entity(EntityType::Document, DOC),
+ "task_assigned",
+ json!({ "taskId": "task-1", "assignedBy": "macro|[email protected]", "taskName": "Plan" }),
+ 11,
+ NotificationState::Unseen,
+ ));
+ let changes = harness
+ .service
+ .recompute(viewer(), unread(), vec![doc.clone()])
+ .await
+ .unwrap();
+ let InboxChange::Upserted(entry) = &changes[0] else {
+ panic!("the task is unread again");
+ };
+ assert!(entry.rows.iter().all(|row| row.unseen));
+}
diff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.md
index b77e9712aa..aabd82a5c5 100644
--- a/docs/agent-guide/notifications.md
+++ b/docs/agent-guide/notifications.md
@@ -80,8 +80,10 @@ whose review was requested offers **Review**, which opens the pull request on
GitHub and marks the row seen.
**All** and **Unread** under the header switch the list (`1` and `2`, or Tab, also
-switch), and the choice is kept per user across reloads. A row you read under
-Unread, or a stack you're going through, stays until you next switch or reload.
+switch), and the choice is kept per user across reloads. Unread reads only unread
+rows from the server, so it pages through unread rows alone; a row read elsewhere
+leaves it and new activity brings one back. A row you read under Unread, or a
+stack you're going through, stays until you next switch or reload.
With nothing unread, Unread shows **You're all caught up**.
**Clear notifications** (double check, beside the filter; a sheet beside the
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index f615917025..f00c1d88a4 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -261,7 +261,7 @@ input ClearNotificationInboxInput {
"""
Clear only unread rows.
"""
- unreadOnly: Boolean
+ unreadOnly: Boolean @deprecated(reason: "Set scope.unreadOnly. Remove after 2026-12-06.")
"""
RFC 3339 time; clear only rows whose newest notification arrived at or
after it.
@@ -11316,6 +11316,11 @@ input NotificationInboxScopeInput {
Row kinds to include; omitted or empty means every kind.
"""
rowTypes: [NotificationInboxRowType!]
+ """
+ Only unread rows; pages, cursors and updates then cover unread rows
+ alone. Defaults to false.
+ """
+ unreadOnly: Boolean
}
"""