Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(drive): seed folder contents from cached non-email membership (#6879)
Sean Aye70b15708695f
diff --git a/apps/web/src/features/drive-view/queries/drive-data-source.ts b/apps/web/src/features/drive-view/queries/drive-data-source.tsindex 8e79feeb79..23fd8d51ea 100644--- a/apps/web/src/features/drive-view/queries/drive-data-source.ts+++ b/apps/web/src/features/drive-view/queries/drive-data-source.ts@@ -65,6 +65,12 @@ export function createDriveDataSource(options: {return {enabled: Boolean(viewer) && facetsReady() && !current.search.trim(),+ // Folder contents mix email with indexed project members. Seed the+ // latter locally without narrowing the authoritative server request.+ graphqlLocalReconciliation:+ current.location.kind === 'folder' && current.location.id+ ? 'without-email'+ : undefined,meta: {// REST inserts omit attachment status. Let a scoped server refetch// admit them rather than inserting an unverifiable document.diff --git a/apps/web/src/lib/queries/soup/graphql/items.test.ts b/apps/web/src/lib/queries/soup/graphql/items.test.tsindex 06b8cb6539..c42176f6f2 100644--- a/apps/web/src/lib/queries/soup/graphql/items.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.test.ts@@ -182,6 +182,304 @@ describe('createGraphqlSoupAstItemsQuery', () => {});});+ describe('mixed folder contents', () => {+ const excludedId = '00000000-0000-0000-0000-000000000000';+ const item = (id: string, __typename = 'GraphqlSoupDocument') => ({+ id,+ __typename,+ projectId: 'folder-a',+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-02T00:00:00Z',+ });++ function fixture(localItems = [item('cached-document')]) {+ const fake = makeFakeClient();+ getGraphqlSoupClientMock.mockReturnValue(fake.client);+ let revision = REVISION_0;+ let notify: (revision: string) => void = () => {};+ const [folder, setFolder] = createSignal('folder-a');+ const filters = () => ({+ documentFilter: { literal: { projectId: folder() } },+ chatFilter: { literal: { projectId: folder() } },+ projectFilter: { literal: { projectId: folder() } },+ emailFilter: { tree: { literal: { projectId: folder() } } },+ });+ makeGraphqlSoupInputMock.mockImplementation(({ cursor }) =>+ cursor+ ? { continuation: { cursor } }+ : {+ initial: {+ filters: filters(),+ emailView: 'ALL',+ sortMethod: 'UPDATED_AT',+ limit: 100,+ },+ }+ );+ getGraphqlSoupCacheHostMock.mockReturnValue({+ currentRevision: async () => revision,+ entityFilter: entityFilterMock,+ onCacheChanged: (callback: typeof notify) => {+ notify = callback;+ return () => {};+ },+ onCacheGenerationChanged: () => () => {},+ });+ entityFilterMock.mockImplementation(async () => ({+ kind: 'reconciled',+ revision,+ keys: localItems.map((record) => `${record.__typename}:${record.id}`),+ retainedKeys: [],+ optimistic: false,+ }));+ readRecordsByKeysMock.mockImplementation(async () => ({+ revision,+ records: localItems.map((record) => ({+ recordKey: `${record.__typename}:${record.id}`,+ record,+ })),+ }));+ const { query, dispose } = createRoot((dispose) => ({+ dispose,+ query: createGraphqlSoupAstItemsQuery(+ () => ({ params: {}, body: {} }),+ () => ({ enabled: true, localReconciliation: 'without-email' })+ ),+ }));+ return {+ fake,+ query,+ dispose,+ filters,+ setFolder,+ ids: () => query.data()?.entities.map((entity) => entity.id),+ push: () => {+ revision = String(Number(revision) + 1);+ notify(revision);+ },+ };+ }++ it('hydrates a never-visited folder without waiting for its mixed GraphQL response', async () => {+ const f = fixture([+ item('document'),+ item('chat', 'GraphqlSoupChat'),+ item('subfolder', 'GraphqlSoupProject'),+ ]);+ try {+ await vi.waitFor(() =>+ expect(f.ids()).toEqual(['document', 'chat', 'subfolder'])+ );+ expect(f.query.isLoading()).toBe(false);+ expect(f.query.isFetching()).toBe(true);+ expect(f.query.hasNextPage()).toBe(false);+ expect(f.fake.executions).toHaveLength(1);+ expect(f.fake.executions[0].variables).toMatchObject({+ input: { initial: { filters: f.filters(), emailView: 'ALL' } },+ });+ expect(entityFilterMock).toHaveBeenCalledWith({+ filters: {+ ...f.filters(),+ emailFilter: { tree: { literal: { threadId: excludedId } } },+ },+ sortMethod: 'UPDATED_AT',+ sortDirection: 'DESC',+ limit: 100,+ baseline: [],+ });+ } finally {+ f.dispose();+ }+ });++ it('retains server email and cursors across local reconciliation and later pages', async () => {+ const f = fixture();+ const email = item('email', 'GraphqlSoupEmailThread');+ const olderEmail = item('older-email', 'GraphqlSoupEmailThread');+ try {+ await vi.waitFor(() => expect(f.ids()).toEqual(['cached-document']));+ f.fake.executions[0].next(+ graphqlSoupPage({+ items: [item('server-document'), email],+ next_cursor: 'page-2',+ }),+ { source: 'normalized-cache-hit' }+ );+ f.push();+ await vi.waitFor(() =>+ expect(f.ids()).toEqual(['cached-document', 'email'])+ );+ expect(entityFilterMock.mock.lastCall?.[0].baseline).toEqual([+ {+ key: 'GraphqlSoupDocument:server-document',+ sortTimestamp: '2026-01-02T00:00:00Z',+ },+ ]);+ expect(f.query.hasNextPage()).toBe(true);+ const next = f.query.fetchNextPage();+ expect(f.fake.executions[1].variables).toEqual({+ input: { continuation: { cursor: 'page-2' } },+ });+ f.fake.executions[1].next(+ graphqlSoupPage({ items: [olderEmail], next_cursor: null }),+ { source: 'normalized-cache-hit' }+ );+ await next;+ await vi.waitFor(() =>+ expect(f.ids()).toEqual(['cached-document', 'email', 'older-email'])+ );+ expect(f.query.hasNextPage()).toBe(false);+ const refresh = f.query.refresh();+ f.fake.executions[2].next(+ graphqlSoupPage({ items: [email], next_cursor: null })+ );+ await refresh;+ expect(f.ids()).toEqual(['email']);+ } finally {+ f.dispose();+ }+ });++ it.each(['email-only', 'network-error'] as const)(+ 'does not mistake an empty partial projection for an empty folder: %s',+ async (outcome) => {+ const f = fixture([]);+ try {+ await vi.waitFor(() =>+ expect(readRecordsByKeysMock).toHaveBeenCalled()+ );+ expect(f.query.data()).toBeUndefined();+ expect(f.query.isLoading()).toBe(true);+ if (outcome === 'network-error') {+ const error = new CombinedError({+ networkError: new Error('offline'),+ });+ f.fake.executions[0].fail(error);+ expect(f.query.error()).toBe(error);+ expect(f.query.data()).toBeUndefined();+ } else {+ f.fake.executions[0].next(+ graphqlSoupPage({+ items: [item('email', 'GraphqlSoupEmailThread')],+ next_cursor: null,+ })+ );+ expect(f.ids()).toEqual(['email']);+ }+ } finally {+ f.dispose();+ }+ }+ );++ it.each([false, true])(+ 'requires visible local rows before suppressing loading/errors unless server data exists: %s',+ async (hasServerData) => {+ const f = fixture();+ const deletion = createGraphqlSoupDeletion(['cached-document']);+ const pending = deferred<void>();+ const mutation = queryClient.getMutationCache().build(queryClient, {+ mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,+ onMutate: () => ({ graphqlDeletion: deletion }),+ mutationFn: () => pending.promise,+ onSettled: () => deletion.release(),+ });+ let completion: Promise<void> | undefined;+ try {+ await vi.waitFor(() => expect(f.ids()).toEqual(['cached-document']));+ if (hasServerData) {+ f.fake.executions[0].next(+ graphqlSoupPage({+ items: [item('cached-document')],+ next_cursor: null,+ }),+ { source: 'normalized-cache-hit' }+ );+ }+ completion = mutation.execute(undefined);+ await vi.waitFor(() =>+ expect(mutation.state.context?.graphqlDeletion).toBe(deletion)+ );+ await vi.waitFor(() =>+ expect(f.ids()).toEqual(hasServerData ? [] : undefined)+ );+ expect(f.query.isLoading()).toBe(!hasServerData);++ const error = new CombinedError({+ networkError: new Error('offline'),+ });+ f.fake.executions[0].fail(error);+ expect(f.query.error()).toBe(hasServerData ? undefined : error);+ expect(f.ids()).toEqual(hasServerData ? [] : undefined);++ // Releasing the deletion makes the cached projection usable again.+ deletion.release();+ await vi.waitFor(() => expect(f.ids()).toEqual(['cached-document']));+ expect(f.query.error()).toBeUndefined();+ expect(f.query.isLoading()).toBe(false);+ } finally {+ pending.resolve();+ await completion;+ deletion.release();+ f.dispose();+ }+ }+ );++ it('keeps a partial projection usable when only some cached rows are pending deletion', async () => {+ const f = fixture([item('deleted'), item('visible')]);+ const deletion = createGraphqlSoupDeletion(['deleted']);+ const pending = deferred<void>();+ const mutation = queryClient.getMutationCache().build(queryClient, {+ mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,+ onMutate: () => ({ graphqlDeletion: deletion }),+ mutationFn: () => pending.promise,+ onSettled: () => deletion.release(),+ });+ let completion: Promise<void> | undefined;+ try {+ await vi.waitFor(() => expect(f.ids()).toEqual(['deleted', 'visible']));+ completion = mutation.execute(undefined);+ await vi.waitFor(() => expect(f.ids()).toEqual(['visible']));+ expect(f.query.isLoading()).toBe(false);+ f.fake.executions[0].fail(+ new CombinedError({ networkError: new Error('offline') })+ );+ expect(f.query.error()).toBeUndefined();+ expect(f.ids()).toEqual(['visible']);+ } finally {+ pending.resolve();+ await completion;+ deletion.release();+ f.dispose();+ }+ });++ it('does not leak local members across folders while a new projection is pending', async () => {+ const f = fixture();+ const pending = deferred<unknown>();+ try {+ await vi.waitFor(() => expect(f.ids()).toEqual(['cached-document']));+ entityFilterMock.mockImplementation(() => pending.promise);+ f.setFolder('folder-b');+ expect(f.query.data()).toBeUndefined();+ expect(f.query.isLoading()).toBe(true);+ await vi.waitFor(() =>+ expect(entityFilterMock.mock.lastCall?.[0].filters).toMatchObject({+ documentFilter: { literal: { projectId: 'folder-b' } },+ })+ );+ f.fake.executions[0].next(+ graphqlSoupPage({ items: [item('late-folder-a')], next_cursor: null })+ );+ expect(f.query.data()).toBeUndefined();+ } finally {+ f.dispose();+ pending.resolve({ kind: 'unsupported' });+ }+ });+ });+it('uses the channel list projection for initial pages, pagination, refresh and reconciliation', async () => {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 b01229c32c..40af9d175c 100644--- a/apps/web/src/lib/queries/soup/graphql/items.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.ts@@ -51,6 +51,7 @@ import {onCleanup,untrack,} from 'solid-js';+import { NIL as NIL_UUID } from 'uuid';import type { SoupAstBody, SoupAstItemsData, SoupAstParams } from '../items';import { soupPageTimestamp } from '../page-timestamp';import {@@ -79,6 +80,8 @@ export type GraphqlSoupAstItemsQueryArgs = {export type GraphqlSoupAstItemsQueryOptions = {enabled: boolean;projection?: 'channel-list';+ /** Reconcile indexed members while retaining server-only email rows. */+ localReconciliation?: 'without-email';showSupportedForeignEntities?: boolean;};@@ -146,6 +149,7 @@ export function createGraphqlSoupAstItemsQuery(generation: number;baselineKeys: ReadonlySet<string>;displayedKeys: ReadonlySet<string>;+ withoutEmail: boolean;data: SoupAstItemsData;mail?: {nextCursor: string | null;@@ -311,7 +315,14 @@ export function createGraphqlSoupAstItemsQuery(const input = firstPageInput();const queryOptions = options();const host = getGraphqlSoupCacheHost();- const records = serverRecords();+ const withoutEmail = queryOptions.localReconciliation === 'without-email';+ // Email membership remains server-owned. Leaving it out of the overlay's+ // baseline makes displayData retain those rows, including later pages.+ const records = withoutEmail+ ? serverRecords().filter(+ (record) => record.__typename !== 'GraphqlSoupEmailThread'+ )+ : serverRecords();const requestId = ++localRequest;const requestGeneration = cacheGeneration;if (input !== previousInitialInput) {@@ -347,14 +358,23 @@ export function createGraphqlSoupAstItemsQuery(localEvaluationPending = false;return;}- const filters = initial.filters ?? {};+ const filters = withoutEmail+ ? {+ ...initial.filters,+ emailFilter: { tree: { literal: { threadId: NIL_UUID } } },+ }+ : (initial.filters ?? {});+ const mailView =+ !withoutEmail && isCachedMailView(initial.emailView)+ ? initial.emailView+ : undefined;const sortMethod = initial.sortMethod;if (sortMethod !== 'CREATED_AT' && sortMethod !== 'UPDATED_AT') {localEvaluationPending = false;return;}const baseline = soupReconciliationBaseline(records, sortMethod);- if (!baseline && !isCachedMailView(initial.emailView)) {+ if (!baseline && !mailView) {setLocalProjection(undefined);localEvaluationPending = false;return;@@ -377,9 +397,6 @@ export function createGraphqlSoupAstItemsQuery(let outcome: 'success' | 'incomplete' | 'error' = 'incomplete';try {for (let attempt = 0; attempt < 3; attempt += 1) {- const mailView = isCachedMailView(initial.emailView)- ? initial.emailView- : undefined;let result = await host.entityFilter({filters,sortMethod,@@ -474,6 +491,7 @@ export function createGraphqlSoupAstItemsQuery(result.kind === 'mail-page' ? [] : records.map(soupItemKey)),displayedKeys: new Set(reconciledRecords.map(soupItemKey)),+ withoutEmail,...(result.kind === 'mail-page'? {mail: {@@ -683,7 +701,17 @@ export function createGraphqlSoupAstItemsQuery(if (!local ||local.input !== firstPageInput() ||- local.generation !== cacheGeneration+ local.generation !== cacheGeneration ||+ local.withoutEmail !== (options().localReconciliation === 'without-email')+ )+ return undefined;+ // A partial projection with no visible rows after pending deletes cannot+ // prove that a folder is empty (it could contain only email). Keep initial+ // loading/errors until the server establishes membership.+ if (+ local.withoutEmail &&+ !query.data &&+ local.data.entities.every((entity) => pendingDeleteIds().has(entity.id)))return undefined;const keys = serverRecordKeys();diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.tsindex c8a781b092..66a60a5026 100644--- a/apps/web/src/lib/queries/soup/items.ts+++ b/apps/web/src/lib/queries/soup/items.ts@@ -70,6 +70,8 @@ interface SoupItemsQueryOptions {staleTime?: StaleTime;/** Channel navigation reads bounded unread evidence, not notification history. */graphqlProjection?: 'channel-list';+ /** Seed mixed lists from indexed non-email members; keep the full server query. */+ graphqlLocalReconciliation?: 'without-email';meta?: {groupBy?: GroupByField;groupKey?: string;@@ -383,6 +385,7 @@ export function useSoupAstItemsQuery(enabled:graphqlRequested() && queryEnabled() && args().groupBy === undefined,projection: options?.().graphqlProjection,+ localReconciliation: options?.().graphqlLocalReconciliation,showSupportedForeignEntities: options?.().showSupportedForeignEntities,}));diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 3dab80ab34..7c23cedd19 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -536,7 +536,18 @@ label's font weight matches the file title. The linkrestores the originating Drive view.The `Drive` folder row opens the folder overview. Click a folder name to browseits contents in the main pane; its separate expand/collapse button reveals child-folders without navigating. The top bar keeps the full folder and file detail+folders without navigating. With GraphQL caching enabled and membership metadata+hydrated, a never-visited folder can immediately show cached documents, chats,+and subfolders for supported created/modified sorts and filters. Email remains+server-owned: the full mixed GraphQL query still refreshes in the background,+keeps loaded email rows, and owns pagination. A non-email projection with no visible+rows, including when pending deletions hide every cached row, must not show+`This folder is empty` while that initial request is pending or failed. Verify that+loading and transport errors remain visible in this case; releasing a failed deletion+restores cached rows without a refetch.+Verify with a folder-specific GraphQL response delayed, then navigate to another+folder before it completes; neither cached rows nor late results may leak across+folders. The top bar keeps the full folder and file detailpath in one breadcrumb trail. Folder containment uses `/` separators, while thetransition to a file detail and nested detail navigation use the default `>`separator. Choosing a folder breadcrumb returns to that folder and clears newer