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/perf/gql UI perf (#6483)
Sean Aye3f722340406a
diff --git a/apps/web/src/features/entity/composed/ListEntity.tsx b/apps/web/src/features/entity/composed/ListEntity.tsxindex 1500db1f28..553f057d76 100644--- a/apps/web/src/features/entity/composed/ListEntity.tsx+++ b/apps/web/src/features/entity/composed/ListEntity.tsx@@ -117,7 +117,11 @@ export function ListEntity(props: ListEntityProps) {const [snippetContainerRef, setSnippetContainerRef] = createSignal<HTMLElement | undefined>();- const chars = useCharacterCount(snippetContainerRef);+ const chars = useCharacterCount(() =>+ props.deferInteractions && !hasSearchContentHits(props.entity)+ ? undefined+ : snippetContainerRef()+ );// For singleton hits on a SnippetEntity, expanding "show more" only adds// value when windowSearchMatch trimmed text — otherwise the inline@@ -156,6 +160,7 @@ export function ListEntity(props: ListEntityProps) {const draggable = createEntityDraggable({entity: props.entity,splitId: useSplitPanel()?.handle?.id,+ deferUntilInteraction: () => props.deferInteractions === true,});const listLayout = useListLayout();diff --git a/apps/web/src/features/entity/composed/list-entity/shared.tsx b/apps/web/src/features/entity/composed/list-entity/shared.tsxindex d585587707..8086e00bc2 100644--- a/apps/web/src/features/entity/composed/list-entity/shared.tsx+++ b/apps/web/src/features/entity/composed/list-entity/shared.tsx@@ -29,6 +29,8 @@ export interface BaseListEntityProps<E extends EntityData = EntityData> {highlighted?: boolean;hovered?: boolean;hideContentHits?: boolean;+ /** Opt-in by the data-owning view; keep nonessential setup off initial render. */+ deferInteractions?: boolean;/** Hide the multi-select checkbox (e.g. read-only embeds outside soup). */hideCheckbox?: boolean;onChecked?: (checked: boolean, shiftKey: boolean) => void;diff --git a/apps/web/src/features/entity/utils/draggable.test.tsx b/apps/web/src/features/entity/utils/draggable.test.tsxnew file mode 100644index 0000000000..2600a56e5c--- /dev/null+++ b/apps/web/src/features/entity/utils/draggable.test.tsx@@ -0,0 +1,142 @@+import { cleanup, fireEvent, render } from '@solidjs/testing-library';+import {+ DragDropProvider,+ DragDropSensors,+ useDragDropContext,+} from '@thisbeyond/solid-dnd';+import { type Accessor, createSignal, Show } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { ChannelEntity } from '../types/entity';+import { createEntityDraggable } from './draggable';++vi.mock('@components/app/ItemDragAndDrop', () => ({+ useDragOperation: () => ({ isAltKey: () => false }),+}));++const entity: ChannelEntity = {+ id: 'row',+ type: 'channel',+ channelType: 'private',+ name: 'A channel',+ ownerId: 'owner',+};++function setup(deferUntilInteraction?: Accessor<boolean>) {+ let state!: NonNullable<ReturnType<typeof useDragDropContext>>[0];+ let removeRow!: () => void;+ function Row() {+ const draggable = createEntityDraggable({+ entity,+ splitId: 'split',+ deferUntilInteraction,+ });+ return (+ <div ref={draggable} data-testid="row">+ <span data-testid="child">A channel</span>+ </div>+ );+ }+ function Content() {+ const context = useDragDropContext();+ if (!context) throw new Error('Missing drag provider');+ state = context[0];+ const [mounted, setMounted] = createSignal(true);+ removeRow = () => setMounted(false);+ return (+ <>+ <DragDropSensors />+ <Show when={mounted()}>+ <Row />+ </Show>+ </>+ );+ }+ const view = render(() => (+ <DragDropProvider>+ <Content />+ </DragDropProvider>+ ));+ return { ...view, state, removeRow };+}++afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('createEntityDraggable', () => {+ it.each([undefined, () => false])(+ 'preserves eager legacy registration without opting in (%s)',+ (deferred) => {+ const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');+ const { state } = setup(deferred);+ expect(state.draggables['row-split']).toBeDefined();+ expect(rect).toHaveBeenCalled();+ }+ );++ it('does not register or measure opted-in rows until a primary press', () => {+ const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');+ const { state, getByTestId } = setup(() => true);+ expect(state.draggables['row-split']).toBeUndefined();+ expect(rect).not.toHaveBeenCalled();++ fireEvent.mouseEnter(getByTestId('row'));+ fireEvent.mouseDown(getByTestId('child'), { button: 2 });+ expect(state.draggables['row-split']).toBeUndefined();+ expect(rect).not.toHaveBeenCalled();++ getByTestId('child').dispatchEvent(+ new MouseEvent('pointerdown', { bubbles: true, button: 0 })+ );+ expect(state.draggables['row-split']?.data.name).toBe('A channel');+ expect(rect).toHaveBeenCalledTimes(1);+ getByTestId('child').dispatchEvent(+ new MouseEvent('pointerdown', { bubbles: true, button: 0 })+ );+ expect(rect).toHaveBeenCalledTimes(1);+ });++ it('starts the first drag without a prior hover or pointerdown', () => {+ vi.useFakeTimers();+ const { state, getByTestId } = setup(() => true);+ fireEvent.mouseDown(getByTestId('child'), {+ button: 0,+ clientX: 10,+ clientY: 10,+ });+ fireEvent.mouseMove(document, { clientX: 40, clientY: 10 });+ expect(state.active.draggableId).toBe('row-split');+ expect(state.active.draggable?.data.dragType).toBe('entity');+ fireEvent.mouseUp(document, { button: 0 });+ expect(state.active.draggableId).toBeNull();+ });++ it('initializes eagerly if a mounted row falls back to the legacy path', () => {+ const [deferred, setDeferred] = createSignal(true);+ const { state } = setup(deferred);+ expect(state.draggables['row-split']).toBeUndefined();+ setDeferred(false);+ expect(state.draggables['row-split']).toBeDefined();+ });++ it('removes handlers when a row is disposed before its first interaction', () => {+ const { state, getByTestId, removeRow } = setup(() => true);+ const row = getByTestId('row');+ removeRow();+ fireEvent.mouseDown(row, { button: 0 });+ expect(state.draggables['row-split']).toBeUndefined();+ });++ it('unregisters an initialized row when its owner is disposed', async () => {+ const { state, getByTestId, removeRow } = setup(() => true);+ getByTestId('row').dispatchEvent(+ new MouseEvent('pointerdown', { bubbles: true, button: 0 })+ );+ expect(state.draggables['row-split']).toBeDefined();+ removeRow();+ await Promise.resolve();+ expect(state.draggables['row-split']).toBeUndefined();+ });+});diff --git a/apps/web/src/features/entity/utils/draggable.ts b/apps/web/src/features/entity/utils/draggable.tsindex 8f3974cc02..a817b86dc7 100644--- a/apps/web/src/features/entity/utils/draggable.ts+++ b/apps/web/src/features/entity/utils/draggable.ts@@ -1,22 +1,67 @@import { useDragOperation } from '@components/app/ItemDragAndDrop';+import { createSubRoot } from '@solid-primitives/rootless';import { createDraggable } from '@thisbeyond/solid-dnd';-import { createUniqueId } from 'solid-js';+import {+ type Accessor,+ createEffect,+ createUniqueId,+ getOwner,+ onCleanup,+ untrack,+} from 'solid-js';import type { EntityDragData } from '../types/drag';import type { EntityData } from '../types/entity';export function createEntityDraggable(options: {entity: EntityData;splitId?: string;-}): ReturnType<typeof createDraggable> {+ /** Opt-in by the owning view; legacy rows register eagerly. */+ deferUntilInteraction?: Accessor<boolean>;+}): (element: HTMLElement) => void {const { isAltKey } = useDragOperation();const draggableId = `${options.entity.id}-${options.splitId ?? createUniqueId()}`;- const dragData: EntityDragData = {- dragType: 'entity',- splitId: options.splitId,- ...options.entity,- operation: () => (isAltKey() ? 'copy' : 'move'),+ const create = () => {+ const dragData: EntityDragData = {+ dragType: 'entity',+ splitId: options.splitId,+ ...options.entity,+ operation: () => (isAltKey() ? 'copy' : 'move'),+ };+ return createDraggable(draggableId, dragData);};- return createDraggable(draggableId, dragData);+ if (+ !options.deferUntilInteraction ||+ !untrack(options.deferUntilInteraction)+ ) {+ return create();+ }++ const owner = getOwner();+ return (element) => {+ let initialized = false;+ let disposed = false;+ const initialize = () => {+ if (initialized || disposed) return;+ initialized = true;+ createSubRoot(() => create()(element), owner);+ };+ // Register before the sensor's bubbling mousedown listener. pointerdown+ // prepares real mouse input; mousedown also handles synthesized input.+ const onPress = (event: MouseEvent) => {+ if (event.button === 0) initialize();+ };+ element.addEventListener('pointerdown', onPress, true);+ element.addEventListener('mousedown', onPress, true);+ createEffect(() => {+ // A live transport fallback must restore eager legacy behavior.+ if (!options.deferUntilInteraction?.()) untrack(initialize);+ });+ onCleanup(() => {+ disposed = true;+ element.removeEventListener('pointerdown', onPress, true);+ element.removeEventListener('mousedown', onPress, true);+ });+ };}diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex 7ac8c25459..584386e658 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -115,6 +115,8 @@ type DataSource<T> = {data: Accessor<T[]>;/** Results are limited to synchronized email metadata. */cachedMail?: Accessor<boolean>;+ /** Only the active GraphQL source opts rows into deferred interaction setup. */+ deferRowInteractions?: Accessor<boolean>;error: Accessor<Error | null>;/** True when the active request has local or network data, including an* intentionally empty result. */@@ -1538,6 +1540,8 @@ export const SoupViewContextProvider: FlowComponent<initialize,source: {data: entities,+ deferRowInteractions: () =>+ !search.isSearching() && itemsQuery.transport === 'graphql',cachedMail: () =>!search.isSearching() && itemsQueryData()?.cachedMail === true,error: () =>diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsxindex 0df2248d1a..635725c09b 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx@@ -1615,6 +1615,9 @@ const SoupViewListContent = (props: SoupViewListProps) => {><Dynamiccomponent={rowEntry().component}+ deferInteractions={+ source.deferRowInteractions?.() === true+ }entity={row.original}timestamp={timestamp()}highlighted={row.isFocused()}diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListEntity.tsx b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListEntity.tsxindex 5c94d9fc00..b11ce317d3 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListEntity.tsx+++ b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListEntity.tsx@@ -67,6 +67,7 @@ export function CompanyListEntity(props: BaseListEntityProps) {const draggable = createEntityDraggable({entity: props.entity,splitId: useSplitPanel()?.handle?.id,+ deferUntilInteraction: () => props.deferInteractions === true,});const isWide = useListLayout()?.isWide ?? (() => true);diff --git a/apps/web/src/features/next-soup/soup-view/views/tasks/TaskListEntity.tsx b/apps/web/src/features/next-soup/soup-view/views/tasks/TaskListEntity.tsxindex 117758daf1..07b226a97d 100644--- a/apps/web/src/features/next-soup/soup-view/views/tasks/TaskListEntity.tsx+++ b/apps/web/src/features/next-soup/soup-view/views/tasks/TaskListEntity.tsx@@ -105,7 +105,11 @@ export function TaskListEntity(props: TaskListEntityProps) {const [snippetContainerRef, setSnippetContainerRef] = createSignal<HTMLElement | undefined>();- const chars = useCharacterCount(snippetContainerRef);+ const chars = useCharacterCount(() =>+ props.deferInteractions && !hasSearchContentHits(props.entity)+ ? undefined+ : snippetContainerRef()+ );const showHitSnippet = () =>!props.hideContentHits && hasSearchContentHits(props.entity);@@ -130,6 +134,7 @@ export function TaskListEntity(props: TaskListEntityProps) {const draggable = createEntityDraggable({entity: props.entity,splitId: useSplitPanel()?.handle?.id,+ deferUntilInteraction: () => props.deferInteractions === true,});const isWide = useListLayout()?.isWide ?? (() => true);diff --git a/apps/web/src/features/notifications/tests/notification-stacking.test.ts b/apps/web/src/features/notifications/tests/notification-stacking.test.tsindex f5898cb40b..1fac42765f 100644--- a/apps/web/src/features/notifications/tests/notification-stacking.test.ts+++ b/apps/web/src/features/notifications/tests/notification-stacking.test.ts@@ -1,5 +1,6 @@import type { NotifEvent } from '@service-notification/generated/schemas';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import { scopeChannelNotificationsForEntity } from '../../soup/entity-notifications';import {getAllNotificationsFromGroup,getMostRecentNotification,@@ -136,6 +137,122 @@ function createDocMentionNotification(});}+describe('channel notification scoping', () => {+ function expectStackMembership(notifications: UnifiedNotification[]) {+ const threadIds = new Set(+ stackNotifications(notifications)+ .filter(+ (stack) =>+ stack.type === 'channel_message_reply' ||+ stack.type === 'channel_mention'+ )+ .flatMap((stack) => stack.notifications.map((n) => n.id))+ );+ expect(+ scopeChannelNotificationsForEntity({ type: 'channel' }, notifications)+ ).toEqual(notifications.filter((n) => !threadIds.has(n.id)));+ }++ it('matches display-stack membership for every combination of channel events', () => {+ const candidates = [+ createNewMessageNotification('root-send', 'root', 2000),+ createNewMessageNotification('standalone-send', 'standalone', 1000),+ createReplyNotification('reply', 'reply-message', 'root', 5000),+ createMentionNotification('reply-mention', 'reply-message', 4000, 'root'),+ createMentionNotification('root-mention', 'root', 6000),+ createMentionNotification('orphan-mention', 'orphan', 3000),+ createMentionNotification(+ 'thread-mention',+ 'other-message',+ 8000,+ 'other'+ ),+ createDocCommentNotification('document-comment', 1, 2, 7000),+ ];+ for (let mask = 0; mask < 2 ** candidates.length; mask++) {+ const notifications = candidates.filter((_, i) => mask & (1 << i));+ expectStackMembership(notifications);+ expectStackMembership([...notifications].reverse());+ }+ });++ it('matches stack membership for empty thread and message keys', () => {+ const candidates = [+ createNewMessageNotification('empty-send', '', 1000),+ createReplyNotification('empty-thread-reply', 'reply', '', 2000),+ createMentionNotification('empty-root-mention', '', 3000),+ createMentionNotification('empty-thread-mention', 'mention', 4000, ''),+ ];+ for (let mask = 0; mask < 2 ** candidates.length; mask++) {+ expectStackMembership(candidates.filter((_, i) => mask & (1 << i)));+ }+ });++ it('does not read timestamps or sort stacks to scope channel notifications', () => {+ const readTimestamp = vi.fn(() => new Date(1000).toISOString());+ const notifications = [+ createNewMessageNotification('root', 'root', 1000),+ createReplyNotification('reply', 'reply-message', 'root', 2000),+ createNewMessageNotification('standalone', 'standalone', 3000),+ ].map((notification) => ({+ ...notification,+ get created_at() {+ return readTimestamp();+ },+ }));++ const scoped = scopeChannelNotificationsForEntity(+ { type: 'channel' },+ notifications+ );++ expect(scoped.map((n) => n.id)).toEqual(['standalone']);+ expect(scoped[0]).toBe(notifications[2]);+ expect(readTimestamp).not.toHaveBeenCalled();+ });++ it('keeps root sends and mentions in their explicit thread row', () => {+ const notifications = [+ createNewMessageNotification('root-send', 'root', 1000),+ createMentionNotification('root-mention', 'root', 2000),+ createReplyNotification('reply', 'reply-message', 'root', 3000),+ createMentionNotification('reply-mention', 'reply-message', 4000, 'root'),+ createReplyNotification('other-reply', 'other-message', 'other', 5000),+ ];++ expect(+ scopeChannelNotificationsForEntity(+ { type: 'channel_thread', messageId: 'root' },+ notifications+ )+ ).toEqual(notifications.slice(0, 4));+ expect(+ scopeChannelNotificationsForEntity(+ { type: 'channel_message' },+ notifications+ )+ ).toBe(notifications);+ });++ it('recomputes membership when an existing notification array changes', () => {+ const notifications = [createNewMessageNotification('root', 'root', 1000)];+ const entity = { type: 'channel' } as const;+ expect(scopeChannelNotificationsForEntity(entity, notifications)).toEqual(+ notifications+ );+ notifications.push(+ createReplyNotification('reply', 'message', 'root', 2000)+ );+ expect(scopeChannelNotificationsForEntity(entity, notifications)).toEqual(+ []+ );+ notifications.pop();+ expect(scopeChannelNotificationsForEntity(entity, notifications)).toEqual(+ notifications+ );+ });+});+describe('stackNotifications', () => {describe('basic stacking', () => {it('stacks multiple new messages into a single group', () => {diff --git a/apps/web/src/features/soup/entity-notifications.ts b/apps/web/src/features/soup/entity-notifications.tsindex d29c244aaa..b67894c7f2 100644--- a/apps/web/src/features/soup/entity-notifications.ts+++ b/apps/web/src/features/soup/entity-notifications.ts@@ -8,45 +8,56 @@ import type { WithNotification } from '@entity/types/notification';import { toNotificationEntity } from '@entity/utils/notification';import { channelThreadRootId } from '@notifications/channel-thread-root';import type { NotificationSource } from '@notifications/notification-source';-import {- getAllNotificationsFromGroup,- stackNotifications,-} from '@notifications/notification-stacking';import {compositeEntity,type UnifiedNotification,} from '@notifications/types';import type { Accessor } from 'solid-js';-import { match } from 'ts-pattern';function channelThreadNotificationIds(- notifications: UnifiedNotification[],- threadId?: string+ notifications: UnifiedNotification[]): Set<string> {const ids = new Set<string>();- if (threadId !== undefined) {- for (const notification of notifications) {- const belongsToThread = match(notification.notification_metadata)- .with(- { tag: 'channel_message_send' },- (metadata) => metadata.content.messageId === threadId- )- .otherwise(() => channelThreadRootId(notification) === threadId);- if (belongsToThread) ids.add(notification.id);+ // Match channel stacking's membership rules without constructing or sorting+ // display stacks. Inbox predicates call this for every channel in the list.+ const mentionedMessageIds = new Set<string>();+ const activeThreadIds = new Set<string>();+ for (const notification of notifications) {+ const metadata = notification.notification_metadata;+ if (metadata.tag === 'channel_mention') {+ mentionedMessageIds.add(metadata.content.messageId);+ if (metadata.content.threadId != null) {+ activeThreadIds.add(metadata.content.threadId);+ }+ } else if (metadata.tag === 'channel_message_reply') {+ activeThreadIds.add(metadata.content.threadId);}- return ids;}- for (const stack of stackNotifications(notifications)) {- if (- stack.type !== 'channel_message_reply' &&- stack.type !== 'channel_mention'+ for (const notification of notifications) {+ const metadata = notification.notification_metadata;+ if (metadata.tag === 'channel_mention') {+ const { messageId, threadId } = metadata.content;+ // Empty thread keys are discarded by the stacker. An orphan root+ // mention is still a standalone mention stack, even with an empty id.+ const key = threadId ?? messageId;+ if (key !== '' || (threadId == null && !activeThreadIds.has(key))) {+ ids.add(notification.id);+ }+ } else if (+ metadata.tag === 'channel_message_send' ||+ metadata.tag === 'channel_message_reply') {- continue;- }- for (const notification of getAllNotificationsFromGroup(stack)) {- ids.add(notification.id);+ const { messageId } = metadata.content;+ if (mentionedMessageIds.has(messageId)) continue;+ const key =+ metadata.tag === 'channel_message_reply'+ ? metadata.content.threadId+ : activeThreadIds.has(messageId)+ ? messageId+ : undefined;+ if (key) ids.add(notification.id);}}return ids;@@ -72,10 +83,15 @@ export function scopeChannelNotificationsForEntity();}if (entity.type === 'channel_thread') {- const threadIds = channelThreadNotificationIds(- notifications,- entity.messageId- );+ const threadIds = new Set<string>();+ for (const notification of notifications) {+ const metadata = notification.notification_metadata;+ const belongsToThread =+ metadata.tag === 'channel_message_send'+ ? metadata.content.messageId === entity.messageId+ : channelThreadRootId(notification) === entity.messageId;+ if (belongsToThread) threadIds.add(notification.id);+ }return notifications.filter((notification) =>threadIds.has(notification.id));diff --git a/apps/web/src/lib/queries/soup/graphql/items.test.ts b/apps/web/src/lib/queries/soup/graphql/items.test.tsindex e2ffe2c22e..497dc6b858 100644--- a/apps/web/src/lib/queries/soup/graphql/items.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.test.ts@@ -14,6 +14,7 @@ const getGraphqlSoupClientMock = vi.hoisted(() => vi.fn());const getGraphqlSoupCacheHostMock = vi.hoisted(() => vi.fn());const entityFilterMock = vi.hoisted(() => vi.fn());const readRecordsByKeysMock = vi.hoisted(() => vi.fn());+const useInstructionsMdIdQueryMock = vi.hoisted(() => vi.fn());const REVISION_0 = '0';const REVISION_1 = '1';const REVISION_2 = '2';@@ -40,7 +41,7 @@ vi.mock('@macro-inc/observability', () => ({}));vi.mock('@queries/storage/instructions-md', () => ({- useInstructionsMdIdQuery: vi.fn(() => ({})),+ useInstructionsMdIdQuery: useInstructionsMdIdQueryMock,}));vi.mock('@app/lib/graphql-cache', () => ({@@ -147,6 +148,7 @@ function makeFakeClient(): {describe('createGraphqlSoupAstItemsQuery', () => {beforeEach(() => {vi.clearAllMocks();+ useInstructionsMdIdQueryMock.mockReturnValue({ isSuccess: false });mapSoupPageToEntityListMock.mockImplementation((page) => page.items);getGraphqlSoupCacheHostMock.mockReturnValue(undefined);makeGraphqlSoupInputMock.mockReturnValue({@@ -211,6 +213,231 @@ describe('createGraphqlSoupAstItemsQuery', () => {});+ it('retains the page projection when only query activity changes', () => {+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ const [enabled, setEnabled] = createSignal(true);+ const { query, dispose } = createRoot((dispose) => ({+ dispose,+ query: createGraphqlSoupAstItemsQuery(+ () => ({ params: { sort_method: 'updated_at' }, body: {} }),+ () => ({ enabled: enabled() })+ ),+ }));+ try {+ fake.executions[0].next(+ graphqlSoupPage({ items: [{ id: 'retained' }], next_cursor: null })+ );+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(1);+ const entities = query.data()?.entities;++ setEnabled(false);+ expect(query.isEnabled()).toBe(false);+ setEnabled(true);+ expect(query.isEnabled()).toBe(true);+ query.resetToInitialPage();++ expect(query.data()?.entities).toBe(entities);+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(1);+ expect(mapSoupPageToEntityListMock).toHaveBeenCalledTimes(1);+ } finally {+ dispose();+ }+ });++ it('reprojects cached pages when the instructions document resolves without reading pending data', () => {+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ const [instructions, setInstructions] = createSignal<+ { isSuccess: false } | { isSuccess: true; data: string | null }+ >({ isSuccess: false });+ const [enabled, setEnabled] = createSignal(true);+ const readInstructionsData = vi.fn(() => {+ const result = instructions();+ if (!result.isSuccess) throw new Error('Pending data read');+ return result.data;+ });+ const instructionsQuery = {+ get isSuccess() {+ return instructions().isSuccess;+ },+ get data() {+ return readInstructionsData();+ },+ };+ useInstructionsMdIdQueryMock.mockReturnValue(instructionsQuery);+ mapSoupPageToEntityListMock.mockImplementation((page) =>+ page.items.filter(+ (item: { id: string }) =>+ !instructionsQuery.isSuccess || item.id !== instructionsQuery.data+ )+ );+ const { query, dispose } = createRoot((dispose) => ({+ dispose,+ query: createGraphqlSoupAstItemsQuery(+ () => ({ params: { sort_method: 'updated_at' }, body: {} }),+ () => ({ enabled: enabled() })+ ),+ }));+ const ids = () => query.data()?.entities.map((entity) => entity.id);+ try {+ fake.executions[0].next(+ graphqlSoupPage({+ items: [+ { id: 'visible', updatedAt: '2026-09-10T00:00:00Z' },+ { id: 'instructions', updatedAt: '2026-09-08T00:00:00Z' },+ ],+ next_cursor: 'next-page',+ })+ );+ expect(ids()).toEqual(['visible', 'instructions']);+ expect(readInstructionsData).not.toHaveBeenCalled();+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(1);++ setInstructions({ isSuccess: true, data: 'instructions' });+ expect(ids()).toEqual(['visible']);+ expect(query.data()?.oldestFetchedTimestamp).toBe(+ Date.parse('2026-09-08T00:00:00Z')+ );+ expect(query.hasNextPage()).toBe(true);+ expect(fake.executions).toHaveLength(1);+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(2);++ // An identical id and activity-only changes must keep the cached selector.+ setInstructions({ isSuccess: true, data: 'instructions' });+ setEnabled(false);+ setEnabled(true);+ query.resetToInitialPage();+ expect(ids()).toEqual(['visible']);+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(2);++ setInstructions({ isSuccess: true, data: 'visible' });+ expect(ids()).toEqual(['instructions']);+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(3);++ setInstructions({ isSuccess: true, data: null });+ expect(ids()).toEqual(['visible', 'instructions']);+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(4);+ } finally {+ dispose();+ }+ });++ it('keeps raw wire payloads outside deep store reconciliation', () => {+ mapSoupPageToEntityListMock.mockImplementation((page) =>+ page.items.map((item: { id: string }) => ({ id: item.id }))+ );+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ const { query, dispose } = createRoot((dispose) => ({+ dispose,+ query: createGraphqlSoupAstItemsQuery(+ () => ({ params: { sort_method: 'updated_at' }, body: {} }),+ () => ({ enabled: true })+ ),+ }));+ const metadata = { content: { message: 'large immutable payload' } };+ const descriptors = vi.spyOn(Object, 'getOwnPropertyDescriptors');+ try {+ fake.executions[0].next(+ graphqlSoupPage({+ items: [{ id: 'document', metadata }],+ next_cursor: null,+ })+ );++ expect(query.data()?.entities[0]?.id).toBe('document');+ expect(descriptors).not.toHaveBeenCalledWith(metadata);+ expect(descriptors).not.toHaveBeenCalledWith(metadata.content);+ } finally {+ descriptors.mockRestore();+ dispose();+ }+ });++ it('updates mapped entities reactively without mutating raw wire records', () => {+ mapSoupPageToEntityListMock.mockImplementation((page) =>+ page.items.map((item: object) => ({ ...item }))+ );+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ const names: Array<string | undefined> = [];+ const { query, dispose } = createRoot((dispose) => {+ const query = createGraphqlSoupAstItemsQuery(+ () => ({ params: { sort_method: 'updated_at' }, body: {} }),+ () => ({ enabled: true })+ );+ createComputed(() => names.push(query.data()?.entities[0]?.name));+ return { query, dispose };+ });+ try {+ const firstPage = graphqlSoupPage({+ items: [{ id: 'document', name: 'before' }],+ next_cursor: null,+ });+ fake.executions[0].next(firstPage);+ const previousEntity = query.data()?.entities[0];+ fake.executions[0].next(+ graphqlSoupPage({+ items: [{ id: 'document', name: 'after' }],+ next_cursor: null,+ })+ );++ expect(query.data()?.entities[0]?.name).toBe('after');+ expect(names).toContain('before');+ expect(names.at(-1)).toBe('after');+ expect(query.data()?.entities[0]).toBe(previousEntity);+ expect(firstPage.user.soup.items[0]).toMatchObject({ name: 'before' });+ expect(fake.executions).toHaveLength(1);+ } finally {+ dispose();+ }+ });++ it('reprojects retained pages when projection inputs change', () => {+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ const [sort, setSort] = createSignal<'notified_at' | 'updated_at'>(+ 'updated_at'+ );+ const [showForeign, setShowForeign] = createSignal(false);+ const { query, dispose } = createRoot((dispose) => ({+ dispose,+ query: createGraphqlSoupAstItemsQuery(+ () => ({ params: { sort_method: sort() }, body: {} }),+ () => ({ enabled: true, showSupportedForeignEntities: showForeign() })+ ),+ }));+ try {+ fake.executions[0].next(+ graphqlSoupPage({+ items: [{ id: 'retained', notifiedAt: '2025-01-01T00:00:00Z' }],+ next_cursor: null,+ })+ );+ expect(query.data()?.oldestFetchedTimestamp).toBe(+ Date.parse('2026-01-01T00:00:00Z')+ );+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(1);++ setSort('notified_at');+ expect(query.data()?.oldestFetchedTimestamp).toBe(+ Date.parse('2025-01-01T00:00:00Z')+ );+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(2);++ setShowForeign(true);+ expect(mapGraphqlSoupPageMock).toHaveBeenCalledTimes(3);+ expect(mapSoupPageToEntityListMock).toHaveBeenLastCalledWith(+ expect.anything(),+ expect.objectContaining({ showSupportedForeignEntities: true })+ );+ } finally {+ dispose();+ }+ });+it('retains fetched coverage when display filtering hides every row', () => {const fake = makeFakeClient();getGraphqlSoupClientMock.mockReturnValue(fake.client);diff --git a/apps/web/src/lib/queries/soup/graphql/items.ts b/apps/web/src/lib/queries/soup/graphql/items.tsindex 0af9921d8a..6bb6787d66 100644--- a/apps/web/src/lib/queries/soup/graphql/items.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.ts@@ -11,7 +11,10 @@ import {readRecordsByKeys,selectRecords,} from '@app/lib/graphql-cache';-import { createUrqlInfiniteQuery } from '@app/lib/urql-solid';+import {+ createUrqlInfiniteQuery,+ type UrqlInfiniteData,+} from '@app/lib/urql-solid';import { Telemetry } from '@macro-inc/observability';import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';import {@@ -125,7 +128,7 @@ export function createGraphqlSoupAstItemsQuery(const isSupported = () => firstPageInput() !== undefined;type ServerProjection = {data: SoupAstItemsData;- records: GraphqlSoupItem[];+ records: Accessor<GraphqlSoupItem[]>;};type LocalProjection = {input: GraphqlSoupInput;@@ -439,6 +442,47 @@ export function createGraphqlSoupAstItemsQuery(})();});+ // Keep the selector stable across activity/filter changes. The observer+ // caches projections by selector and page identity; rebuilding the closure+ // would remap and reconcile every notification when merely disabling a view.+ const projectionSortMethod = createMemo(() => args().params.sort_method);+ const projectionForeignEntities = createMemo(+ () => options().showSupportedForeignEntities+ );+ const projectionInstructionsId = createMemo(() =>+ instructionsIdQuery.isSuccess ? instructionsIdQuery.data : undefined+ );+ const selectPages = createMemo(() => {+ // The mapper reads this query inside the untracked observer callback.+ // Track its resolved id here so cached pages reselect when it changes.+ projectionInstructionsId();+ const sortMethod = projectionSortMethod();+ const showSupportedForeignEntities = projectionForeignEntities();+ return ({+ pages,+ }: UrqlInfiniteData<SoupQuery, string | null>): ServerProjection => {+ const mappedPages = pages.map(mapGraphqlSoupPage);+ const oldestFetchedTimestamp = soupPageTimestamp(+ mappedPages.flatMap((page) => page.items.map(mapApiSoupItemToEntity)),+ sortMethod+ );+ const entities = mappedPages.flatMap((page) =>+ mapSoupPageToEntityList(page, {+ instructionsIdQuery,+ showSupportedForeignEntities,+ })+ );+ const records = pages.flatMap((page) => page.user.soup.items);+ return {+ // Raw wire records are reconciliation evidence, not reactive UI state.+ // Publish them atomically without walking their entire notification+ // payload again. Mapped entities retain deep reactivity and identity.+ records: () => records,+ data: { entities, groups: undefined, oldestFetchedTimestamp },+ };+ };+ });+const query = createUrqlInfiniteQuery<SoupQuery,SoupQueryVariables,@@ -446,10 +490,7 @@ export function createGraphqlSoupAstItemsQuery(ServerProjection>(() => {const firstInput = firstPageInput();- const sortMethod = args().params.sort_method;const queryOptions = options();- const showSupportedForeignEntities =- queryOptions.showSupportedForeignEntities;return {query: SoupDocument,@@ -481,36 +522,15 @@ export function createGraphqlSoupAstItemsQuery(recordAuthority('network');finishStaleFallback('network');},- select: ({ pages }) => {- const mappedPages = pages.map(mapGraphqlSoupPage);- const oldestFetchedTimestamp = soupPageTimestamp(- mappedPages.flatMap((page) => page.items.map(mapApiSoupItemToEntity)),- sortMethod- );- const entities = mappedPages.flatMap((page) =>- mapSoupPageToEntityList(page, {- instructionsIdQuery,- showSupportedForeignEntities,- })- );- return {- records: pages.flatMap((page) => page.user.soup.items),- data: {- entities,- groups: undefined,- oldestFetchedTimestamp,- },- };- },+ select: selectPages(),};});- // Snapshot the reactive normalized rows: their object identities may remain- // stable across writes, but baseline membership/sort evidence must not mutate- // beneath an in-flight reconciliation.+ // Capture membership/sort evidence for each published projection, so a later+ // cache revision cannot change the baseline of an in-flight reconciliation.const serverRecords = createMemo(() =>baselineGeneration() === cacheGeneration- ? (query.data?.records ?? []).map((record) => ({ ...record }))+ ? (query.data?.records() ?? []).map((record) => ({ ...record })): []);diff --git a/apps/web/src/lib/urql-solid/create-base-query.test.ts b/apps/web/src/lib/urql-solid/create-base-query.test.tsnew file mode 100644index 0000000000..419d92b25f--- /dev/null+++ b/apps/web/src/lib/urql-solid/create-base-query.test.ts@@ -0,0 +1,41 @@+import type { Client } from '@urql/core';+import { createRoot } from 'solid-js';+import { describe, expect, it } from 'vitest';+import { createBaseQuery } from './create-base-query';++describe('createBaseQuery', () => {+ it('keeps the observer snapshot separate from the mutable result store', () => {+ createRoot((dispose) => {+ try {+ const initial = {+ data: undefined as string | undefined,+ fetching: true,+ };+ let notify: ((result: typeof initial) => void) | undefined;+ const query = createBaseQuery(+ () => ({ client: {} as Client }),+ () => ({+ getCurrentResult: () => initial,+ setOptions: () => {},+ subscribe: (listener) => {+ notify = listener;+ return () => {};+ },+ destroy: () => {},+ }),+ 'testQuery'+ );++ notify?.({ data: 'loaded', fetching: false });+ expect(query.data).toBe('loaded');+ expect(initial).toEqual({ data: undefined, fetching: true });++ notify?.(initial);+ expect(query.data).toBeUndefined();+ expect(query.fetching).toBe(true);+ } finally {+ dispose();+ }+ });+ });+});diff --git a/apps/web/src/lib/urql-solid/create-base-query.ts b/apps/web/src/lib/urql-solid/create-base-query.tsindex 728b00bca7..351fae911c 100644--- a/apps/web/src/lib/urql-solid/create-base-query.ts+++ b/apps/web/src/lib/urql-solid/create-base-query.ts@@ -42,9 +42,9 @@ export function createBaseQuery<equals: false,});- const [state, setState] = createStore<Result>(- untrack(() => initialObserver.getCurrentResult())- );+ let previous = untrack(() => initialObserver.getCurrentResult());+ // The store mutates its root; observer snapshots must remain independent.+ const [state, setState] = createStore<Result>({ ...previous });const result = new Proxy(state, {get(target, property) {@@ -55,7 +55,18 @@ export function createBaseQuery<initialObserver.setReference?.(result);const update = (next: Result): void => {- setState(reconcile(next));+ untrack(() => {+ const reconciled = { ...next };+ for (const key in reconciled) {+ if (Object.is(previous[key], next[key])) {+ // reconcile unwraps its entire input before comparing it. Existing+ // store proxies let unwrap skip unchanged branches in constant time.+ reconciled[key] = state[key];+ }+ }+ previous = next;+ setState(reconcile(reconciled));+ });};createComputed(() => {diff --git a/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsx b/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsxindex 2f54c40294..b421b93c8f 100644--- a/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsx+++ b/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsx@@ -7,7 +7,7 @@ import {type OperationResult,} from '@urql/core';import { createRoot, createSignal } from 'solid-js';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { fromValue, makeSubject, onEnd, pipe } from 'wonka';import { createUrqlInfiniteQuery } from './create-urql-infinite-query';import { InfiniteQueryObserver } from './infinite-query-observer';@@ -72,6 +72,7 @@ const DOCUMENT = gql`const disposals: Array<() => void> = [];afterEach(() => {for (const dispose of disposals.splice(0)) dispose();+ vi.restoreAllMocks();});describe('createUrqlInfiniteQuery', () => {@@ -241,6 +242,38 @@ describe('createUrqlInfiniteQuery', () => {expect(fake.executions[0]?.unsubscribed).toBe(false);});+ it('does not traverse retained page data on resets and option changes', () => {+ const fake = makeFakeClient();+ const [enabled, setEnabled] = createSignal(true);+ let query!: ReturnType<+ typeof createUrqlInfiniteQuery<Page, Variables, string | null>+ >;+ const dispose = createRoot((rootDispose) => {+ query = createUrqlInfiniteQuery<Page, Variables, string | null>(() => ({+ query: DOCUMENT,+ client: fake.client,+ enabled: enabled(),+ initialPageParam: null,+ variables: (cursor) => ({ cursor }),+ getNextPageParam: (lastPage) => lastPage.nextCursor,+ }));+ return rootDispose;+ });+ disposals.push(dispose);+ const page = { values: ['first'], nextCursor: null };+ fake.executions[0]?.next(page);+ const firstData = query.data;+ const descriptors = vi.spyOn(Object, 'getOwnPropertyDescriptors');++ query.resetToInitialPage();+ setEnabled(false);++ expect(query.isEnabled).toBe(false);+ expect(query.data).toBe(firstData);+ expect(fake.executions[0]?.unsubscribed).toBe(true);+ expect(descriptors).not.toHaveBeenCalledWith(page);+ });+it('resets to the live initial page before refetching', async () => {const fake = makeFakeClient();let query!: ReturnType<diff --git a/apps/web/src/lib/urql-solid/create-urql-query.test.tsx b/apps/web/src/lib/urql-solid/create-urql-query.test.tsxindex a9208e7fa4..d3087a384a 100644--- a/apps/web/src/lib/urql-solid/create-urql-query.test.tsx+++ b/apps/web/src/lib/urql-solid/create-urql-query.test.tsx@@ -419,6 +419,81 @@ describe('createUrqlQuery reactive state', () => {expect(observed.at(-1)).toEqual([2, undefined]);});+ it('does not traverse unchanged data for status-only emissions', () => {+ const fake = makeFakeClient();+ const query = setup(() => activeOptions(fake.client));+ const data = { value: 'cached', nested: { count: 1 } };+ fake.executions[0]?.next({ data, stale: true, hasNext: true });+ const firstData = query.data;+ const firstNested = query.data?.nested;+ const descriptors = vi.spyOn(Object, 'getOwnPropertyDescriptors');++ fake.executions[0]?.next({ data, stale: false, hasNext: true });+ fake.executions[0]?.complete();++ expect(query.stale).toBe(false);+ expect(query.hasNext).toBe(false);+ expect(query.isFetching).toBe(false);+ expect(query.data).toBe(firstData);+ expect(query.data?.nested).toBe(firstNested);+ expect(descriptors).not.toHaveBeenCalledWith(data);+ expect(descriptors).not.toHaveBeenCalledWith(data.nested);+ });++ it('reconciles changed data after skipping an unchanged emission', () => {+ const fake = makeFakeClient();+ const query = setup(() => activeOptions(fake.client));+ const first = { value: 'first', nested: { count: 1, removed: 'old' } };+ const second = { value: 'second', nested: { count: 2 } };+ fake.executions[0]?.next({ data: first, stale: true });+ const firstData = query.data;+ const firstNested = query.data?.nested;++ fake.executions[0]?.next({ data: first });+ fake.executions[0]?.next({ data: second });++ expect(query.data).toBe(firstData);+ expect(query.data?.nested).toBe(firstNested);+ expect(query.data).toEqual(second);+ expect(query.data?.nested?.removed).toBeUndefined();++ const descriptors = vi.spyOn(Object, 'getOwnPropertyDescriptors');+ fake.executions[0]?.next({ data: second, stale: true });+ expect(query.stale).toBe(true);+ expect(descriptors).not.toHaveBeenCalledWith(second);+ expect(descriptors).not.toHaveBeenCalledWith(second.nested);+ });++ it('publishes data and status together without notifying unchanged data consumers', () => {+ const fake = makeFakeClient();+ const snapshots: Array<[string | undefined, boolean]> = [];+ const values: Array<string | undefined> = [];+ const data = { value: 'cached' };+ const dispose = createRoot((rootDispose) => {+ const query = createUrqlQuery(() => activeOptions(fake.client));+ createRenderEffect(() => {+ snapshots.push([query.data?.value, query.isFetching]);+ });+ createRenderEffect(() => {+ values.push(query.data?.value);+ });+ return rootDispose;+ });+ disposals.push(dispose);++ fake.executions[0]?.next({ data, stale: true });+ fake.executions[0]?.next({ data });+ fake.executions[0]?.next({ data: { value: 'fresh' } });++ expect(snapshots).toEqual([+ [undefined, true],+ ['cached', true],+ ['cached', false],+ ['fresh', false],+ ]);+ expect(values).toEqual([undefined, 'cached', 'fresh']);+ });+it('normalizes stale and incremental state when a source completes', () => {const fake = makeFakeClient();const query = setup(() => activeOptions(fake.client));diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex b4745f914e..77d03149ed 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -79,6 +79,14 @@ Email, Tasks, and Agents use the same sidebar rows, including favorites, tags,inboxes, and recent agent chats: 32px high on desktop and 44px on touch devices,with regular-weight labels and consistent icon spacing.+## List-row dragging++GraphQL-backed Soup rows initialize dragging on the first primary-button press;+a preparatory hover is not required. REST-backed rows retain eager registration.+Verify first-press dragging after navigation as well as ordinary row clicks and+right-click menus. A completed drop can move or copy real data; use a disposable+test item when verifying drop actions.+## FavoritesUse an entity's command/context menu to add or remove it from Favorites; drag rows