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.

perf(web): cut redundant work when opening cached content (#8027)

teo2ece3ac6d0d6
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx
index 5b924c0071..a145ff9538 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.test.tsx
@@ -2,6 +2,7 @@ import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMe
import { render, waitFor } from '@solidjs/testing-library';
import { createSignal, type JSX } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
+import { replaceCitations } from '../../citationsUtils';
import { StaticMarkdown, StaticMarkdownContext } from './StaticMarkdown';
const agentPreview = vi.hoisted(() => ({
@@ -9,6 +10,11 @@ const agentPreview = vi.hoisted(() => ({
mounted: vi.fn(),
}));
+vi.mock('../../citationsUtils', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../citationsUtils')>();
+ return { ...actual, replaceCitations: vi.fn(actual.replaceCitations) };
+});
+
vi.mock('../decorator/AgentSessionMention', () => ({
AgentSessionMention: () => {
// Query setup can synchronously read its current reactive snapshot.
@@ -196,3 +202,50 @@ describe('static pull request mentions', () => {
rendered.unmount();
});
});
+
+describe('static markdown citations', () => {
+ it('keeps the rendered DOM for markdown without citations', async () => {
+ vi.mocked(replaceCitations).mockClear();
+ const rendered = render(() => (
+ <StaticMarkdownContext>
+ <StaticMarkdown markdown="plain **reply**" lazy={false} />
+ </StaticMarkdownContext>
+ ));
+ const paragraph = rendered.container.querySelector('p');
+ expect(paragraph?.textContent).toBe('plain reply');
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(rendered.container.querySelector('p')).toBe(paragraph);
+ expect(replaceCitations).not.toHaveBeenCalled();
+ rendered.unmount();
+ });
+
+ it('ignores a citation lookup that finishes after newer markdown', async () => {
+ const lookups = new Map<string, (content: string) => void>();
+ vi.mocked(replaceCitations).mockImplementation(
+ (input) =>
+ new Promise((resolve) => {
+ lookups.set(input, resolve);
+ })
+ );
+ const [markdown, setMarkdown] = createSignal('first [[old]]');
+ const rendered = render(() => (
+ <StaticMarkdownContext>
+ <StaticMarkdown markdown={markdown()} lazy={false} />
+ </StaticMarkdownContext>
+ ));
+ setMarkdown('second [[new]]');
+
+ lookups.get('second [[new]]')?.('second resolved');
+ await waitFor(() => {
+ expect(rendered.container.textContent).toBe('second resolved');
+ });
+ lookups.get('first [[old]]')?.('first resolved');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(rendered.container.textContent).toBe('second resolved');
+ vi.mocked(replaceCitations).mockReset();
+ rendered.unmount();
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index bde32609e4..09a8537324 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -1201,15 +1201,34 @@ export function StaticMarkdown(props: {
// TODO: Move citations to bulk query when built in backend
createEffect(() => {
const editor = currentEditor();
+ const markdown = props.markdown;
+ const target = props.target;
+ const singleLine = props.singleLine;
+ // Without citations the replacement is identical; re-rendering it would
+ // parse the markdown again and rebuild the same DOM.
+ if (!markdown.includes('[[')) return;
+
+ // A newer render owns the editor state; drop this lookup's late result.
+ let current = true;
+ onCleanup(() => {
+ current = false;
+ });
// Handle citations without affecting mentions
- replaceCitations(props.markdown).then((content: string) => {
- setEditorStateFromMarkdown(editor, content, props.target);
- if (props.singleLine) {
- forceSingleLine(editor);
+ const renderCitations = async () => {
+ try {
+ const content = await replaceCitations(markdown);
+ if (!current || content === markdown) return;
+ setEditorStateFromMarkdown(editor, content, target);
+ if (singleLine) {
+ forceSingleLine(editor);
+ }
+ setEditorState(editor.getEditorState());
+ } catch (error) {
+ console.error('Failed to resolve markdown citations', error);
}
- setEditorState(editor.getEditorState());
- });
+ };
+ void renderCitations();
});
const domTree = createMemo(() => {
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.cancellation.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.cancellation.test.ts
index 4d7b701d39..0e3861106b 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.cancellation.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.cancellation.test.ts
@@ -10,7 +10,7 @@
*/
import type { QueryKey } from '@tanstack/solid-query';
-import { QueryClient, QueryObserver } from '@tanstack/solid-query';
+import { hashKey, QueryClient, QueryObserver } from '@tanstack/solid-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
let testQueryClient: QueryClient;
@@ -295,3 +295,27 @@ describe('destination-folder refetch vs optimistic soup updates', () => {
expect(source.state().status).toBe('success');
});
});
+
+describe('optimistic update cancellation cost', () => {
+ it('does not re-hash dependent keys against every cached query', async () => {
+ const queryKeyHashFn = vi.fn(hashKey);
+ testQueryClient = new QueryClient({
+ defaultOptions: { queries: { queryKeyHashFn, retry: false } },
+ });
+ for (let index = 0; index < 500; index += 1) {
+ testQueryClient.setQueryData(['unrelated', index], index);
+ }
+ testQueryClient.setQueryData(sourceListKey, ['thread-1']);
+ queryKeyHashFn.mockClear();
+
+ mockNormalizer.getDependentQueriesByIds.mockReturnValue([sourceListKey]);
+ optimisticUpdateSoupEntity({
+ tag: 'emailThread',
+ data: { id: 'thread-1', isRead: true },
+ frecency_score: 0,
+ } as unknown as Parameters<typeof optimisticUpdateSoupEntity>[0]);
+
+ // An exact-key cancel hashed the key once per cached query (501+).
+ expect(queryKeyHashFn.mock.calls.length).toBeLessThan(10);
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
index 8b64f3991e..afbb6a0601 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -102,17 +102,24 @@ function updateSoupEntity<T extends SoupEntityTag>(
// list refetching on mount): the fetch dies and nothing retries it.
// Skip cold initial fetches (data === undefined); cancelling those can leave
// the query stuck pending, which is why cancelSoupQueries has the same guard.
- for (const queryKey of cancelRefetches ? dependentKeys : []) {
- if (
- partialMatchKey(queryKey, soupKeys.items._def) ||
- partialMatchKey(queryKey, soupKeys.astItems._def)
- ) {
- queryClient.cancelQueries({
- queryKey,
- exact: true,
- predicate: (query) => query.state.data !== undefined,
- });
- }
+ // Hash the keys once and cancel in a single cache pass: an `exact` cancel
+ // per key re-hashes that key against every cached query.
+ const cancelHashes = new Set(
+ (cancelRefetches ? dependentKeys : [])
+ .filter(
+ (queryKey) =>
+ partialMatchKey(queryKey, soupKeys.items._def) ||
+ partialMatchKey(queryKey, soupKeys.astItems._def)
+ )
+ .map(
+ (queryKey) => queryClient.defaultQueryOptions({ queryKey }).queryHash
+ )
+ );
+ if (cancelHashes.size > 0) {
+ queryClient.cancelQueries({
+ predicate: (query) =>
+ query.state.data !== undefined && cancelHashes.has(query.queryHash),
+ });
}
const previousDependents = dependentKeys.map(
(key: QueryKey) =>
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
index f52acfd5d6..b819081f52 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
@@ -710,6 +710,36 @@ describe('GraphQL Soup browser cache session gate', () => {
}
);
+ it('inspects a successful projection response without parsing it', async () => {
+ const body = JSON.stringify({
+ data: {
+ user: {
+ soup: { items: [{ id: 'item-1', cacheProjection: { v: 2 } }] },
+ },
+ },
+ });
+ mocks.platformFetch.mockResolvedValueOnce(
+ new Response(body, {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ );
+ const json = vi.spyOn(Response.prototype, 'json');
+ const soup = await import('./graphql-soup');
+ const response = await soup.dssGraphqlFetch('http://dss.test/graphql', {
+ method: 'POST',
+ body: JSON.stringify({
+ query: 'query Soup { user { soup { items { id cacheProjection } } } }',
+ }),
+ });
+
+ expect(json).not.toHaveBeenCalled();
+ expect(mocks.platformFetch).toHaveBeenCalledOnce();
+ expect(await response.text()).toBe(body);
+ expect(soup.graphqlSoupProjectionSupported()).toBe(true);
+ json.mockRestore();
+ });
+
it('keeps GraphQL notification subscriptions active when the cache is disabled', async () => {
mocks.enabled = false;
const soup = await import('./graphql-soup');
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index 3900f33201..8c0b993df4 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -224,11 +224,19 @@ function legacyProjectionRequest(
}
}
+// Matches the JSON-encoded body, where the field's quotes are escaped.
+const LEGACY_PROJECTION_ERROR_TEXT =
+ /(?:Cannot query|Unknown) field \\?["']cacheProjection/;
+
async function isLegacyProjectionValidationError(
response: Response
): Promise<boolean> {
try {
- const payload: unknown = await response.clone().json();
+ // Every projection response passes through here and urql parses the body
+ // again, so only parse one whose text names the rejected field.
+ const text = await response.clone().text();
+ if (!LEGACY_PROJECTION_ERROR_TEXT.test(text)) return false;
+ const payload: unknown = JSON.parse(text);
if (
payload === null ||
typeof payload !== 'object' ||
@@ -293,10 +301,14 @@ export async function dssGraphqlFetch(
span.setAttr('graphql.response_headers_ms', performance.now() - started);
span.setAttr('http.response.status_code', response.status);
span.event('response_headers');
- const legacyInit = legacyProjectionRequest(transportInit);
- if (legacyInit === undefined) return response;
+ if (
+ typeof transportInit?.body !== 'string' ||
+ !transportInit.body.includes('cacheProjection')
+ ) {
+ return response;
+ }
- // This includes body delivery and JSON parsing, not just validation CPU.
+ // This includes body delivery and the text scan, not just validation CPU.
const inspectStarted = performance.now();
const legacy = await isLegacyProjectionValidationError(response);
span.setAttr(
@@ -304,8 +316,11 @@ export async function dssGraphqlFetch(
performance.now() - inspectStarted
);
span.event('response_inspected');
- span.setAttr('graphql.legacy_retry', legacy);
- if (!legacy) return response;
+ const legacyInit = legacy
+ ? legacyProjectionRequest(transportInit)
+ : undefined;
+ span.setAttr('graphql.legacy_retry', legacyInit !== undefined);
+ if (legacyInit === undefined) return response;
// A mixed deployment remains network-correct: retry without the additive
// metadata field and suppress v2 local authority for this session. Backfill