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(web): preserve cached tasks offline and unblock startup (#7499)
Sean Aye231630ba8b9d
diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-items-offline.test.ts b/apps/web/src/lib/queries/soup/graphql/grouped-items-offline.test.tsnew file mode 100644index 0000000000..2c19ab524d--- /dev/null+++ b/apps/web/src/lib/queries/soup/graphql/grouped-items-offline.test.ts@@ -0,0 +1,204 @@+import {+ type Client,+ CombinedError,+ type GraphQLRequest,+ makeOperation,+ type OperationContext,+ type OperationResult,+} from '@urql/core';+import { createRoot, createSignal } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { makeSubject } from 'wonka';++const mocks = vi.hoisted(() => ({ client: vi.fn(), local: vi.fn() }));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: { error: vi.fn() },+}));+vi.mock('@app/lib/graphql-cache', () => ({+ normalizedCacheResultMetadata: () => undefined,+}));+vi.mock('@queries/storage/instructions-md', () => ({+ useInstructionsMdIdQuery: () => ({}),+}));+vi.mock('@queries/client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return { queryClient: new QueryClient() };+});+vi.mock('@service-storage/graphql-soup', () => ({+ getGraphqlSoupClient: mocks.client,+ mapGraphqlGroupedSoupPage: (data: {+ user: {+ groupSoup: { items: Record<string, unknown>; groups: unknown[] };+ };+ }) => data.user.groupSoup,+}));+vi.mock('./items', () => ({ createGraphqlSoupAstItemsQuery: mocks.local }));+vi.mock('./active-queries', () => ({+ registerGraphqlSoupRevalidations: () => () => {},+}));+vi.mock('../transform-utils', () => ({+ mapSoupPageToEntityList: (page: { items: unknown[] }) => page.items,+}));+vi.mock('../grouped/api', () => ({+ makeGroupComparator: () => () => 0,+ resolveGroupMetaForKey: () => undefined,+}));+vi.mock('../grouped/mail-date-groups', () => ({+ groupCachedMailByDate: (data: unknown) => data,+}));++import { authKeys } from '@queries/auth/keys';+import { queryClient } from '@queries/client';+import {+ createGraphqlGroupedSoupAstItemsQuery,+ type GraphqlGroupedSoupAstItemsQueryArgs,+} from './grouped-items';++beforeEach(() => {+ queryClient.clear();+ queryClient.setQueryData(authKeys.userInfo.queryKey, {+ userId: 'viewer',+ authenticated: true,+ });+});++function fixture() {+ const executions: Array<(result: Partial<OperationResult>) => void> = [];+ mocks.client.mockReturnValue({+ executeQuery(request: GraphQLRequest, context: Partial<OperationContext>) {+ const subject = makeSubject<OperationResult>();+ const operation = makeOperation('query', request, {+ url: 'https://test.invalid/graphql',+ requestPolicy: 'cache-and-network',+ ...context,+ });+ executions.push((result) =>+ subject.next({ operation, stale: false, hasNext: false, ...result })+ );+ return subject.source;+ },+ } as unknown as Client);+ mocks.local.mockReturnValue({ data: () => undefined });+ const [args, setArgs] = createSignal<GraphqlGroupedSoupAstItemsQueryArgs>({+ params: { limit: 100 },+ body: {},+ groupBy: { type: 'property', propertyDefinitionId: 'priority' },+ });+ const root = createRoot((dispose) => ({+ dispose,+ query: createGraphqlGroupedSoupAstItemsQuery(args, () => ({+ enabled: true,+ // Retained data must not be mistaken for a hit for changed filters.+ keepPreviousData: true,+ })),+ }));+ const publish = (result: Partial<OperationResult>) =>+ executions[executions.length - 1](result);+ return {+ ...root,+ setArgs,+ fail: (error: CombinedError) => publish({ error }),+ cache(empty = false, error?: CombinedError) {+ publish({+ stale: true,+ error,+ data: {+ user: {+ id: 'viewer',+ groupSoup: {+ items: empty ? {} : { task: { id: 'task', type: 'document' } },+ groups: empty+ ? []+ : [+ {+ key: 'high',+ totalCount: 1,+ nextCursor: null,+ itemIds: ['task'],+ },+ ],+ },+ },+ },+ });+ },+ };+}++const disconnected = () =>+ new CombinedError({ networkError: new TypeError('Failed to fetch') });++describe('grouped Soup transport failures', () => {+ it.each([false, true])(+ 'retains a usable cached page (empty=%s) after a failed refresh',+ async (empty) => {+ const f = fixture();+ try {+ await vi.waitFor(() => f.cache(empty));+ const cached = f.query.data();+ expect(cached?.entities.length).toBe(empty ? 0 : 1);+ f.fail(disconnected());+ expect(f.query.data()).toBe(cached);+ expect(f.query.error()).toBeUndefined();+ expect(f.query.isLoading()).toBe(false);+ } finally {+ f.dispose();+ }+ }+ );++ it('surfaces an initial failure until a delayed cache hit arrives', async () => {+ const f = fixture();+ try {+ const error = disconnected();+ await vi.waitFor(() => f.fail(error));+ expect(f.query.error()).toBe(error);+ expect(f.query.data()).toBeUndefined();+ f.cache(false, error);+ expect(f.query.data()?.entities).toHaveLength(1);+ expect(f.query.error()).toBeUndefined();+ } finally {+ f.dispose();+ }+ });++ it('does not hide a new filter failure using previous-query data', async () => {+ const f = fixture();+ try {+ await vi.waitFor(() => f.cache());+ const error = disconnected();+ f.setArgs((args) => ({ ...args, params: { limit: 50 } }));+ await vi.waitFor(() => f.fail(error));+ expect(f.query.error()).toBe(error);+ f.cache();+ f.fail(error);+ expect(f.query.error()).toBeUndefined();+ } finally {+ f.dispose();+ }+ });++ it.each([+ new CombinedError({ graphQLErrors: ['Access denied'] }),+ new CombinedError({+ graphQLErrors: ['Resolver failed'],+ networkError: new TypeError('Failed to fetch'),+ }),+ ...[401, 403, 500].map(+ (status) =>+ new CombinedError({+ networkError: new Error('HTTP error'),+ response: new Response(null, { status }),+ })+ ),+ ])('preserves server errors even with cached data: %s', async (error) => {+ const f = fixture();+ try {+ await vi.waitFor(() => f.cache());+ f.fail(error);+ expect(f.query.error()).toBe(error);+ } finally {+ f.dispose();+ }+ });+});diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts b/apps/web/src/lib/queries/soup/graphql/grouped-items.tsindex 345c7a3921..3b640b17ba 100644--- a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts+++ b/apps/web/src/lib/queries/soup/graphql/grouped-items.ts@@ -10,6 +10,7 @@ import {} from '@app/lib/graphql-cache';import { createUrqlQuery } from '@app/lib/urql-solid';import { createBrowserOfflineSignal } from '@core/util/connectivity';+import { isTransientRequestError } from '@core/util/request-error';import { Telemetry } from '@macro-inc/observability';import {makeGroupComparator,@@ -163,11 +164,16 @@ export function createGraphqlGroupedSoupAstItemsQuery(}});const isSupported = () => input() !== undefined;+ const inputKey = createMemo(() => JSON.stringify(input()));const query = createUrqlQuery<GroupSoupQuery,GroupSoupQueryVariables,- { viewerId: string; data: SoupAstItemsData }+ {+ inputKey: string;+ viewerId: string;+ data: SoupAstItemsData;+ }>(() => {const queryOptions = options();const groupBy = args().groupBy;@@ -198,6 +204,7 @@ export function createGraphqlGroupedSoupAstItemsQuery();},select: (data: GroupSoupQuery) => ({+ inputKey: JSON.stringify(queryInput),viewerId: data.user.id,data: mapGraphqlGroupedSoupData(data, groupBy!, {instructionsIdQuery,@@ -234,7 +241,6 @@ export function createGraphqlGroupedSoupAstItemsQuery(}));- const error = (): CombinedError | undefined => query.error ?? undefined;const cachedMail = createMemo(() => {const data = local.data();if (@@ -253,6 +259,24 @@ export function createGraphqlGroupedSoupAstItemsQuery(return;return groupCachedMailByDate(data, now());});+ const error = (): CombinedError | undefined => {+ const error = query.error;+ // A failed refresh must not hide usable current-query data, including an+ // empty page. Retained data from other filters is not an offline fallback.+ // Server/GraphQL errors and failures without cached data still surface.+ if (+ error &&+ isTransientRequestError(error) &&+ !error.response &&+ options().enabled &&+ isSupported() &&+ (cachedMail() !== undefined ||+ (query.data?.inputKey === inputKey() && query.data?.data !== undefined))+ ) {+ return undefined;+ }+ return error ?? undefined;+ };createComputed(on(error, (queryError) => {if (queryError) {diff --git a/apps/web/src/lib/queries/soup/quick-access-pending.test.tsx b/apps/web/src/lib/queries/soup/quick-access-pending.test.tsxindex 59965d676c..14418ba1f2 100644--- a/apps/web/src/lib/queries/soup/quick-access-pending.test.tsx+++ b/apps/web/src/lib/queries/soup/quick-access-pending.test.tsx@@ -1,4 +1,10 @@-import { createRoot, createSignal } from 'solid-js';+import { render, screen, waitFor } from '@solidjs/testing-library';+import {+ createQuery,+ QueryClient,+ QueryClientProvider,+} from '@tanstack/solid-query';+import { createRoot, createSignal, Suspense } from 'solid-js';import { describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({ query: undefined as unknown }));@@ -8,19 +14,30 @@ vi.mock('@app/lib/analytics/posthog', () => ({}));vi.mock('@entity', () => ({isSnippetEntity: (entity: { type: string }) => entity.type === 'snippet',+ isSkillEntity: (entity: { type: string }) => entity.type === 'skill',}));vi.mock('@queries/soup/items', () => ({useSoupItemsQuery: () => mocks.query,}));+import { useQuickAccessSkillsQuery } from './quick-access-skills';import { useQuickAccessSnippetsQuery } from './quick-access-snippets';-describe('Quick Access snippets', () => {- it('does not read pending query data', () => {+const feeds = [+ {+ type: 'snippet',+ useEntities: () => useQuickAccessSnippetsQuery().snippets,+ },+ { type: 'skill', useEntities: () => useQuickAccessSkillsQuery().skills },+];++describe.each(feeds)('Quick Access $type', ({ type, useEntities }) => {+ it('does not read pending query data, including disabled or paused queries', () => {createRoot((dispose) => {const [pending, setPending] = createSignal(true);- const entity = { id: 'one', type: 'snippet' };+ const entity = { id: 'one', type };mocks.query = {+ isLoading: false,get isPending() {return pending();},@@ -30,12 +47,51 @@ describe('Quick Access snippets', () => {},};- const { snippets } = useQuickAccessSnippetsQuery();- expect(snippets()).toEqual([]);+ try {+ const entities = useEntities();+ expect(entities()).toEqual([]);- setPending(false);- expect(snippets()).toEqual([entity]);- dispose();+ setPending(false);+ expect(entities()).toEqual([entity]);+ } finally {+ dispose();+ }});});++ it('does not suspend the app shell while the discovery request is pending', async () => {+ const response =+ Promise.withResolvers<Array<{ id: string; type: string }>>();+ const client = new QueryClient();+ function Shell() {+ mocks.query = createQuery(() => ({+ queryKey: ['quick-access', type],+ queryFn: () => response.promise,+ retry: false,+ }));+ const entities = useEntities();+ return <button>Navigation: {entities().length}</button>;+ }+ const view = render(() => (+ <QueryClientProvider client={client}>+ <Suspense fallback={<p>Loading app shell</p>}>+ <Shell />+ </Suspense>+ </QueryClientProvider>+ ));+ try {+ await waitFor(() => {+ expect(screen.getByRole('button').textContent).toBe('Navigation: 0');+ expect(screen.queryByText('Loading app shell')).toBeNull();+ });+ response.resolve([{ id: 'one', type }]);+ await waitFor(() =>+ expect(screen.getByRole('button').textContent).toBe('Navigation: 1')+ );+ } finally {+ response.resolve([]);+ view.unmount();+ client.clear();+ }+ });});diff --git a/apps/web/src/lib/queries/soup/quick-access-skills.ts b/apps/web/src/lib/queries/soup/quick-access-skills.tsindex 5191fe1212..c1287d18db 100644--- a/apps/web/src/lib/queries/soup/quick-access-skills.ts+++ b/apps/web/src/lib/queries/soup/quick-access-skills.ts@@ -1,5 +1,6 @@import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';import { isSkillEntity, type SkillEntity } from '@entity';+import { queryReadyGate } from '@queries/gate';import { useSoupItemsQuery } from '@queries/soup/items';import { createMemo } from 'solid-js';@@ -33,8 +34,8 @@ export function useQuickAccessSkillsQuery() {() => ({ staleTime: STALE_TIME }));- const skills = createMemo<SkillEntity[]>(- () => query.data?.filter(isSkillEntity) ?? []+ const skills = createMemo<SkillEntity[]>(() =>+ queryReadyGate(query) ? query.data.filter(isSkillEntity) : []);return { query, skills };diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex b06ab84f1c..9c6743a6c6 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -649,9 +649,12 @@ time; equal timestamps have a stable entity-type and ID order. Searching retainsrelevance/recency ranking and DM boost with GraphQL enabled. Verify that refreshingthe cache or reopening the menu with unchanged data does not reorder the results.-Pending or failed Quick Access history, recently-viewed, and cached-channel lookups-must not hide the app shell. Verify a cold lookup with Cmd/Ctrl+K: navigation stays-mounted and usable while the optional source loads or fails. The menu shows no+Pending or failed Quick Access history, recently-viewed, skills, and cached-channel+lookups must not hide the app shell. Verify a cold lookup with Cmd/Ctrl+K: navigation+stays mounted and usable while the optional source loads or fails. Also hold the+skills discovery request (`/items/soup`, skill subtype) during startup: even a+paused or disabled discovery query must not suspend navigation or Home. Releasing+the request should populate skills without remounting the shell. The menu shows noloading text: while entity rows are still loading, an empty list stays blank andcommands remain usable; a settled empty category shows **No results found**.Background history or channel refetches alone must not blank a settled emptydiff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.mdindex 54fec92bcf..d7b20d3002 100644--- a/docs/AGENT_GUIDE/tasks.md+++ b/docs/AGENT_GUIDE/tasks.md@@ -67,6 +67,17 @@ the originating tab breadcrumb, a task tab, or a tag to return to the list.Shift-click a row or favorite to open it in a new splitinstead. Keyboard list navigation only moves focus; press Enter to open the focused task.+## Cached grouped lists++With GraphQL caching enabled, previously loaded grouped task lists remain usable+when their background refresh fails without an HTTP response. Load a Priority-grouped+view online, navigate away, then reopen it offline. Repeat by holding its GroupSoup+request: cached rows should appear before the response, and rejecting that request+must not replace them with **Tasks couldn’t be loaded**. A cached empty result is+also usable. An initial cache miss still shows failure; HTTP and GraphQL errors+remain visible even with cached rows. Change filters while retaining prior rows:+those older results must not hide a failure for the new, uncached query.+## Reviews viewWith `enable-tasks-reviews` enabled (on by default in development), a