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.

Seanaye/fix/cyclical preview (#6263)

Sean Ayec4b6772dbd17
diff --git a/apps/web/src/lib/queries/preview/graphql.ts b/apps/web/src/lib/queries/preview/graphql.ts
index a135033e91..dffb08f906 100644
--- a/apps/web/src/lib/queries/preview/graphql.ts
+++ b/apps/web/src/lib/queries/preview/graphql.ts
@@ -582,10 +582,29 @@ function previewBatcher(client: Client, includeProperties: boolean) {
/** Joins a shared live preview batch; rich document edges load in the first request. */
export function createGraphqlItemPreviewQuery(
- item: Accessor<ItemEntity>,
+ getItem: Accessor<ItemEntity>,
enabled: Accessor<boolean>,
includeProperties = true
): GraphqlItemPreviewQuery {
+ // Hover popup props derive from another live preview. Snapshot only the
+ // entity identity so cache/fetch updates cannot release and reacquire the
+ // same batch, clear its data, or feed another update back upstream.
+ const item = createMemo<ItemEntity, undefined>(
+ () => {
+ const current = getItem();
+ return current.type === 'channel'
+ ? { id: current.id, type: current.type, messageId: current.messageId }
+ : { id: current.id, type: current.type };
+ },
+ undefined,
+ {
+ equals: (previous, next) =>
+ previous.id === next.id &&
+ normalizedItemType(previous) === normalizedItemType(next) &&
+ (previous.type === 'channel' ? previous.messageId : undefined) ===
+ (next.type === 'channel' ? next.messageId : undefined),
+ }
+ );
const [group, setGroup] = createSignal<PreviewBatch>();
let ready: Promise<PreviewBatch | undefined> = Promise.resolve(undefined);
const isEnabled = () => enabled() && isGraphqlPreviewItem(item());
diff --git a/apps/web/src/lib/queries/preview/tests/graphql-reactivity.test.ts b/apps/web/src/lib/queries/preview/tests/graphql-reactivity.test.ts
new file mode 100644
index 0000000000..c6c3b5cde5
--- /dev/null
+++ b/apps/web/src/lib/queries/preview/tests/graphql-reactivity.test.ts
@@ -0,0 +1,186 @@
+import { normalizedCacheExchange } from '@graphql-cache/exchange/normalized-cache-exchange';
+import type { CacheHost } from '@graphql-cache/host/types';
+import { INITIAL_CACHE_REVISION } from '@graphql-cache/protocol';
+import type { ItemPreviewsQuery } from '@service-storage/graphql/generated/graphql';
+import { type Client, createClient, fetchExchange } from '@urql/core';
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const fixture = vi.hoisted(() => ({ client: undefined as Client | undefined }));
+
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: true }),
+}));
+vi.mock('@core/constant/featureFlags', () => ({
+ enableGraphqlSoup: {},
+ isFeatureEnabled: () => true,
+ LOCAL_ONLY: false,
+}));
+vi.mock('@service-storage/client', () => ({ DEFAULT_ITEM_TYPE: 'document' }));
+vi.mock('@service-storage/graphql-soup', () => ({
+ getGraphqlSoupClient: () => fixture.client,
+ getGraphqlSoupCacheHost: () => undefined,
+ mapGraphqlProperties: (properties: unknown[]) => properties,
+}));
+vi.mock('@app/lib/graphql-cache', () => ({
+ selectRecords: () => ({}),
+ readRecordsByKeys: vi.fn(),
+}));
+vi.mock('@tanstack/solid-query', () => ({
+ useQuery: () => ({ isPending: false, isSuccess: false }),
+}));
+vi.mock('@queries/client', () => ({ queryClient: {} }));
+vi.mock('../dataloader', () => ({ previewDataLoader: {} }));
+vi.mock('../fetchers', () => ({
+ // The real transform returns a new object, even when the name is unchanged.
+ defaultNameTransform: (item: PreviewItem) => ({ ...item }),
+ fetchMessageContext: vi.fn(),
+ fetchRestPreviewBatch: vi.fn(),
+}));
+
+import { refreshActiveGraphqlPreviewQueries } from '../active-queries';
+import { useItemPreview } from '../preview';
+import type { PreviewItem } from '../types';
+
+const disposals: Array<() => void> = [];
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ for (const dispose of disposals.splice(0)) dispose();
+ vi.clearAllTimers();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+// Bound the flush so a regressing feedback loop fails instead of starving a timer.
+async function flushResults() {
+ for (let i = 0; i < 100; i++) await Promise.resolve();
+}
+
+describe('GraphQL preview hover reactivity', () => {
+ it('shares a rich batch with the popup and stays settled across live updates', async () => {
+ const id = '01a081e3-3982-70e8-8d67-4c28ed21129e';
+ const document: Extract<
+ ItemPreviewsQuery['user']['soup']['items'][number],
+ { __typename: 'GraphqlSoupDocument' }
+ > = {
+ __typename: 'GraphqlSoupDocument',
+ id,
+ displayName: 'Roadmap',
+ documentName: 'Roadmap',
+ fileType: 'md',
+ subType: { __typename: 'GraphqlTaskSubType', isCompleted: false },
+ properties: [],
+ viewerPermission: {
+ __typename: 'GraphqlAccessLevelPermission',
+ accessLevel: 'EDIT',
+ },
+ };
+ const data: ItemPreviewsQuery = {
+ user: { id: 'user-1', soup: { items: [document] } },
+ };
+ const fetch = vi.fn<typeof globalThis.fetch>(
+ async () =>
+ new Response(JSON.stringify({ data }), {
+ headers: { 'Content-Type': 'application/json' },
+ })
+ );
+ let cachedData: unknown;
+ // Only the host's storage boundary is faked; retain the real async cache
+ // exchange, urql client, Solid query bridge, and preview facade.
+ const host = {
+ clientId: 'preview-test',
+ onOpsAffected: () => () => {},
+ claimNextMutation: async () => undefined,
+ readQuery: async () =>
+ cachedData
+ ? { kind: 'hit', data: structuredClone(cachedData) }
+ : { kind: 'miss' },
+ writeQuery: async (args) => {
+ cachedData = structuredClone(args.data);
+ return {
+ revision: INITIAL_CACHE_REVISION,
+ revisionAdvanced: false,
+ affectedOps: [],
+ changed: [],
+ reset: false,
+ };
+ },
+ teardown: async () => {},
+ } satisfies Pick<
+ CacheHost,
+ | 'clientId'
+ | 'onOpsAffected'
+ | 'claimNextMutation'
+ | 'readQuery'
+ | 'writeQuery'
+ | 'teardown'
+ >;
+ fixture.client = createClient({
+ url: 'http://preview.test/graphql',
+ exchanges: [
+ normalizedCacheExchange(host as unknown as CacheHost),
+ fetchExchange,
+ ],
+ fetch,
+ preferGetMethod: false,
+ });
+ const executeQuery = vi.spyOn(fixture.client, 'executeQuery');
+ const [parent, parentControls] = createRoot((dispose) => {
+ disposals.push(dispose);
+ return useItemPreview(() => ({ id, type: 'document' }));
+ });
+ vi.advanceTimersByTime(30);
+ await flushResults();
+ expect(parent()).toMatchObject({ id, name: 'Roadmap', loading: false });
+ expect(parentControls.documentProperties()).toMatchObject({
+ properties: [],
+ canEdit: true,
+ });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(fetch.mock.calls[0][1]?.body as string)).toMatchObject({
+ operationName: 'ItemPreviews',
+ });
+
+ const [popup, popupControls] = createRoot((dispose) => {
+ disposals.push(dispose);
+ // ItemPreview's inline documentInfo depends on the parent's preview
+ // object; DocumentPreviewContent derives another ItemEntity from it.
+ const documentInfo = () => ({ id: parent().id, type: 'md' });
+ return useItemPreview(() => ({
+ id: documentInfo().id,
+ type: 'document',
+ }));
+ });
+ await flushResults();
+ expect(popup()).toMatchObject({ id, name: 'Roadmap', loading: false });
+ expect(popupControls.documentProperties()).toMatchObject({
+ properties: [],
+ canEdit: true,
+ });
+ vi.advanceTimersByTime(90);
+ await flushResults();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(executeQuery).toHaveBeenCalledTimes(1);
+
+ // Both consumers must see refreshed task metadata without releasing and
+ // reacquiring their batch when the parent passes down a new preview object.
+ document.displayName = 'Renamed';
+ document.viewerPermission = {
+ __typename: 'GraphqlAccessLevelPermission',
+ accessLevel: 'VIEW',
+ };
+ await refreshActiveGraphqlPreviewQueries(id);
+ expect(parent()).toMatchObject({ name: 'Renamed', loading: false });
+ expect(popup()).toMatchObject({ name: 'Renamed', loading: false });
+ expect(parentControls.documentProperties()).toMatchObject({
+ canEdit: false,
+ });
+ expect(popupControls.documentProperties()).toMatchObject({
+ canEdit: false,
+ });
+ vi.advanceTimersByTime(90);
+ await flushResults();
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(executeQuery).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/web/src/lib/queries/preview/tests/graphql.test.ts b/apps/web/src/lib/queries/preview/tests/graphql.test.ts
index 709f1fed95..29aad90820 100644
--- a/apps/web/src/lib/queries/preview/tests/graphql.test.ts
+++ b/apps/web/src/lib/queries/preview/tests/graphql.test.ts
@@ -1,11 +1,14 @@
+import type { UrqlQueryOptions } from '@app/lib/urql-solid';
import type { CacheHost, ReadRecordsByKeysArgs } from '@graphql-cache/index';
import { INITIAL_CACHE_REVISION } from '@graphql-cache/index';
import type {
ItemPreviewDetailsFieldsFragment,
ItemPreviewFieldsFragment,
ItemPreviewQuery,
+ ItemPreviewQueryVariables,
+ ItemPreviewsQuery,
} from '@service-storage/graphql/generated/graphql';
-import { createRoot } from 'solid-js';
+import { type Accessor, createRoot, createSignal } from 'solid-js';
import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -33,6 +36,33 @@ import {
setGraphqlPreviewName,
setGraphqlPreviewOnCreate,
} from '../graphql';
+import type { ItemEntity } from '../types';
+
+type PreviewQueryOptions = UrqlQueryOptions<
+ ItemPreviewQuery | ItemPreviewsQuery,
+ ItemPreviewQueryVariables
+>;
+
+function trackPreviewBatches() {
+ const options: PreviewQueryOptions[] = [];
+ createUrqlQueryMock.mockImplementation(
+ (getOptions: Accessor<PreviewQueryOptions>) => {
+ options.push(getOptions());
+ return {
+ data: undefined,
+ error: null,
+ isError: false,
+ isFetched: false,
+ isFetching: false,
+ isLoading: false,
+ isEnabled: true,
+ stale: false,
+ refetch: vi.fn(async () => undefined),
+ };
+ }
+ );
+ return options;
+}
beforeEach(() => {
vi.useFakeTimers();
@@ -293,6 +323,96 @@ describe('GraphQL item previews', () => {
);
});
+ it('only rejoins a batch when entity identity or enabled state changes', async () => {
+ const options = trackPreviewBatches();
+ const { setItem, setEnabled, query, dispose } = createRoot((dispose) => {
+ const [item, setItem] = createSignal<ItemEntity>({ id: 'doc-1' });
+ const [enabled, setEnabled] = createSignal(true);
+ const query = createGraphqlItemPreviewQuery(item, enabled);
+ return { setItem, setEnabled, query, dispose };
+ });
+ try {
+ expect(options).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(1);
+
+ setItem({ id: 'doc-1' });
+ setItem({ id: 'doc-1', type: 'document' });
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(1);
+
+ setItem({ id: 'doc-2', type: 'document' });
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(2);
+ expect(
+ options.at(-1)?.variables?.input.initial?.filters?.documentFilter
+ ).toEqual({ literal: { id: 'doc-2' } });
+
+ setItem({ id: 'doc-2', type: 'chat' });
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(3);
+ expect(
+ options.at(-1)?.variables?.input.initial?.filters?.chatFilter
+ ).toEqual({ literal: { chatId: 'doc-2' } });
+
+ setEnabled(false);
+ expect(query.isEnabled()).toBe(false);
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(3);
+ setEnabled(true);
+ expect(query.isEnabled()).toBe(true);
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(4);
+ expect(options.at(-1)?.requestPolicy).toBe('cache-and-network');
+ } finally {
+ dispose();
+ }
+ });
+
+ it('snapshots reactive props and preserves channel-message REST exceptions', async () => {
+ const options = trackPreviewBatches();
+ const { setItem, query, dispose } = createRoot((dispose) => {
+ const [item, setItem] = createStore({
+ id: 'channel-1',
+ type: 'channel' as const,
+ messageId: undefined as string | undefined,
+ });
+ const query = createGraphqlItemPreviewQuery(
+ () => item,
+ () => true
+ );
+ return { setItem, query, dispose };
+ });
+ try {
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(1);
+ expect(query.isEnabled()).toBe(true);
+
+ setItem('id', 'channel-2');
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(2);
+ expect(
+ options.at(-1)?.variables?.input.initial?.filters?.channelFilter
+ ).toEqual({ literal: { channelId: 'channel-2' } });
+
+ setItem('messageId', 'message-1');
+ expect(query.isEnabled()).toBe(false);
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(2);
+ setItem('messageId', 'message-2');
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(2);
+ expect(query.isEnabled()).toBe(false);
+
+ setItem('messageId', undefined);
+ expect(query.isEnabled()).toBe(true);
+ await vi.advanceTimersByTimeAsync(30);
+ expect(options).toHaveLength(3);
+ } finally {
+ dispose();
+ }
+ });
+
it('holds creation grace before the asynchronous cache seed is readable', async () => {
vi.useFakeTimers();
let finishWrite!: () => void;
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 0affade53d..8c13d39b6f 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -17,6 +17,15 @@ nodes — use the snapshot itself to verify content. For formatting checks, run
Body placeholder advertises: `/` for block commands, `@` to reference files, `;` for snippets.
Markdown auto-format works while typing (`#` heading, `[]` checklist, `>` quote).
+## Reference hover previews
+
+Hover a document reference chip to open its preview without navigating. With
+`ENABLE_GRAPHQL_SOUP` enabled, the popup reuses the reference's live `ItemPreviews`
+batch, including task properties and viewer permission, without another fetch.
+Explicit refreshes may revalidate that batch, but requests must settle while the
+pointer stays over the same reference; cache updates must not cause a continuous
+fetch cascade.
+
## AI edit
1. Click `Edit with AI` (button directly under the editor body).