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/misc offline fixes (#5318)

Sean Aye1761c49ecd9a
diff --git a/Cargo.lock b/Cargo.lock
index a67c1b90a3..70cc9e2c71 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2443,7 +2443,7 @@ dependencies = [
[[package]]
name = "cache-wasm"
-version = "0.3.0"
+version = "0.3.1"
dependencies = [
"async-lock",
"cache-core",
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index 91d33a601f..5c0c788f55 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
@@ -662,8 +662,8 @@ describe('normalizedCacheExchange', () => {
ops.next(makeOp(1));
await tick();
- expect(host.reads).toHaveLength(1);
- expect(host.reads[0]?.opKey).toBe(1);
+ expect(host.reads).toHaveLength(2);
+ expect(host.reads.map((read) => read.opKey)).toEqual([1, 1]);
expect(forwarded.map((op) => op.key)).toEqual([1]);
expect(results).toHaveLength(1);
expect(results[0]?.data).toEqual({ from: 'network' });
@@ -696,14 +696,16 @@ describe('normalizedCacheExchange', () => {
]);
expect(forwarded.map((op) => op.key)).toEqual([1]);
expect(host.writes).toHaveLength(1);
+ expect(host.reads).toHaveLength(1);
});
- it('network-only skips the read but writes the response', async () => {
+ it('network-only skips the initial read and refreshes dependencies after writing', async () => {
const { ops, results } = harness(host);
ops.next(makeOp(1, 'network-only'));
await tick();
- expect(host.reads).toHaveLength(0);
+ expect(host.reads).toHaveLength(1);
+ expect(host.reads[0]?.opKey).toBe(1);
expect(results[0]?.data).toEqual({ from: 'network' });
expect(host.writes).toHaveLength(1);
});
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index 52c6b8fbcc..c7b225654b 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
@@ -302,6 +302,12 @@ export function normalizedCacheExchange(
return ({ forward, client }) => {
/** Operations registered with the host, for push-driven re-execution. */
const activeOps = new Map<number, Operation>();
+ /**
+ * Network-bound queries whose initial cache read could not register their
+ * complete normalized dependencies. Refresh these after write-through so
+ * later optimistic entity writes can affect the active operation.
+ */
+ const dependencyRefreshOps = new Set<number>();
const unsubscribePush = host.onOpsAffected((opKeys) => {
for (const key of opKeys) {
@@ -473,6 +479,7 @@ export function normalizedCacheExchange(
): Promise<OperationResult | undefined> {
const policy = op.context.requestPolicy;
if (policy === 'network-only') {
+ dependencyRefreshOps.add(op.key);
enqueueForward(op);
return undefined;
}
@@ -491,6 +498,7 @@ export function normalizedCacheExchange(
if (policy === 'cache-only') {
return cacheResult(op, undefined, false);
}
+ dependencyRefreshOps.add(op.key);
} catch (error) {
options.onCacheError?.(error, op);
// `cache-only` must never touch the network, even when the cache
@@ -616,14 +624,23 @@ export function normalizedCacheExchange(
}
} else if (op.kind === 'query' && result.data != null) {
try {
- await host.writeQuery({
+ const args = {
opKey: op.key,
query: queryText(op),
operationName: operationName(op),
variables: op.variables as Record<string, unknown> | undefined,
+ };
+ await host.writeQuery({
+ ...args,
data: result.data,
identity: options.extractIdentity?.(result.data),
});
+ if (dependencyRefreshOps.delete(op.key) && activeOps.has(op.key)) {
+ // A miss only records dependencies reached before the missing
+ // record. Re-read the now-populated query to register its full
+ // entity graph for push-driven optimistic updates.
+ await host.readQuery(args);
+ }
} catch (error) {
options.onCacheError?.(error, op);
}
@@ -763,6 +780,7 @@ export function normalizedCacheExchange(
tap((op) => {
if (op.kind === 'teardown') {
activeOps.delete(op.key);
+ dependencyRefreshOps.delete(op.key);
host.teardown(op.key).catch(() => undefined);
}
})
diff --git a/apps/web/src/lib/queries/properties/entity.test.tsx b/apps/web/src/lib/queries/properties/entity.test.tsx
index ee1359def3..20a45ea249 100644
--- a/apps/web/src/lib/queries/properties/entity.test.tsx
+++ b/apps/web/src/lib/queries/properties/entity.test.tsx
@@ -1,5 +1,9 @@
import type { Property } from '@property/types';
-import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import {
+ onlineManager,
+ QueryClient,
+ QueryClientProvider,
+} from '@tanstack/solid-query';
import type { JSX } from 'solid-js';
import { render } from 'solid-js/web';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -152,6 +156,7 @@ function renderMutation(): void {
describe('useBulkSaveEntityPropertiesMutation dispositions', () => {
beforeEach(() => {
+ onlineManager.setOnline(true);
vi.clearAllMocks();
optimisticUpdateSoupEntityMock.mockReturnValue({ rollback: rollbackMock });
graphqlSoupEnabledMock.mockReturnValue(true);
@@ -168,11 +173,31 @@ describe('useBulkSaveEntityPropertiesMutation dispositions', () => {
});
afterEach(() => {
+ onlineManager.setOnline(true);
dispose?.();
document.body.replaceChildren();
vi.restoreAllMocks();
});
+ it('submits GraphQL optimism while offline for the durable cache queue', async () => {
+ onlineManager.setOnline(false);
+ setEntityPropertyMock.mockResolvedValue({
+ kind: 'queued',
+ transactionId: 'txn-offline',
+ });
+
+ await expect(mutation.mutateAsync(variables)).resolves.toBeUndefined();
+
+ expect(setEntityPropertyMock).toHaveBeenCalledOnce();
+ expect(setEntityPropertyMock).toHaveBeenCalledWith(
+ expect.objectContaining({ optimisticProperty: { id: 'assignment-1' } })
+ );
+
+ for (const callback of settlementCallbacks) {
+ callback({ transactionId: 'txn-offline', status: 'committed' });
+ }
+ });
+
it('mirrors queued GraphQL optimism and defers reconciliation', async () => {
setEntityPropertyMock
.mockResolvedValueOnce({ kind: 'queued', transactionId: 'txn-1' })
diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.ts
index 661644b5dd..784d8f8327 100644
--- a/apps/web/src/lib/queries/properties/entity.ts
+++ b/apps/web/src/lib/queries/properties/entity.ts
@@ -861,6 +861,10 @@ export function useBulkSaveEntityPropertiesMutation(
>
) {
return useMutation(() => ({
+ // The normalized GraphQL cache owns its durable offline queue. TanStack's
+ // default `online` mode would pause before `mutationFn`, preventing the
+ // optimistic layer from ever reaching the SharedWorker.
+ networkMode: ENABLE_GRAPHQL_SOUP() ? 'always' : 'online',
mutationFn: async (vars: BulkSaveEntityPropertiesParams): Promise<void> => {
const usesGraphqlSoup = ENABLE_GRAPHQL_SOUP();
const save = async (
diff --git a/apps/web/src/lib/queries/soup/reactive-items.test.ts b/apps/web/src/lib/queries/soup/reactive-items.test.ts
new file mode 100644
index 0000000000..3ef847993f
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/reactive-items.test.ts
@@ -0,0 +1,81 @@
+import { createRoot, createSignal } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const createQuerySignalMock = vi.hoisted(() => vi.fn());
+const mapGraphqlSoupPageMock = vi.hoisted(() => vi.fn((data) => data));
+const mapSoupPageToEntityListMock = vi.hoisted(() =>
+ vi.fn((page) => page.items)
+);
+
+vi.mock('@graphql-cache/solid/create-query-signal', () => ({
+ createQuerySignal: createQuerySignalMock,
+}));
+
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: { error: vi.fn() },
+}));
+
+vi.mock('@queries/storage/instructions-md', () => ({
+ useInstructionsMdIdQuery: vi.fn(() => ({})),
+}));
+
+vi.mock('@service-storage/graphql/generated/graphql', () => ({
+ SoupDocument: {},
+}));
+
+vi.mock('@service-storage/graphql-soup', () => ({
+ getGraphqlSoupClient: vi.fn(() => ({})),
+ mapGraphqlSoupPage: mapGraphqlSoupPageMock,
+}));
+
+vi.mock('./graphql-ast', () => ({
+ makeGraphqlSoupInput: vi.fn(() => ({ initial: { limit: 50 } })),
+}));
+
+vi.mock('./transform-utils', () => ({
+ mapSoupPageToEntityList: mapSoupPageToEntityListMock,
+}));
+
+import { useReactiveSoupAstItemsQuery } from './reactive-items';
+
+describe('useReactiveSoupAstItemsQuery', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('retains identical page projections across cache re-executions', () => {
+ const firstPage = {
+ items: [{ id: 'task-1', type: 'document', name: 'Task' }],
+ next_cursor: null,
+ };
+ const [queryData, setQueryData] = createSignal<unknown>(firstPage);
+ createQuerySignalMock.mockReturnValue({
+ data: queryData,
+ error: () => undefined,
+ fetching: () => false,
+ stale: () => false,
+ });
+
+ createRoot((dispose) => {
+ const query = useReactiveSoupAstItemsQuery(
+ () => ({ params: {}, body: {} }) as never,
+ () => ({ enabled: true })
+ );
+
+ const initial = query.data();
+ expect(initial?.entities[0]).toEqual(firstPage.items[0]);
+
+ setQueryData(structuredClone(firstPage));
+ expect(query.data()).toBe(initial);
+
+ setQueryData({
+ ...firstPage,
+ items: [{ ...firstPage.items[0], name: 'Updated task' }],
+ });
+ expect(query.data()).not.toBe(initial);
+ expect(query.data()?.entities[0]?.name).toBe('Updated task');
+
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/reactive-items.ts b/apps/web/src/lib/queries/soup/reactive-items.ts
index 13d536a8f0..4caeb63ce4 100644
--- a/apps/web/src/lib/queries/soup/reactive-items.ts
+++ b/apps/web/src/lib/queries/soup/reactive-items.ts
@@ -10,9 +10,11 @@
* and fall back to the TanStack path otherwise.
*/
+import { deepEqual } from '@core/util/compareUtils';
import { createQuerySignal } from '@graphql-cache/solid/create-query-signal';
import { Telemetry } from '@macro-inc/observability';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
+import type { SoupPage } from '@service-storage/generated/schemas/soupPage';
import {
SoupDocument,
type SoupQuery,
@@ -107,10 +109,19 @@ export function useReactiveSoupAstItemsQuery(
return input === undefined ? undefined : { input };
},
});
- const page = createMemo(() => {
- const data = query.data();
- return data == null ? undefined : mapGraphqlSoupPage(data);
- });
+ const page = createMemo<SoupPage | undefined>(
+ () => {
+ const data = query.data();
+ return data == null ? undefined : mapGraphqlSoupPage(data);
+ },
+ undefined,
+ {
+ // Cache writes for unrelated backfill arguments can re-execute this
+ // operation with identical data. Retain the prior page so Solid's
+ // keyed list does not remount every row and dismiss open editors.
+ equals: deepEqual,
+ }
+ );
return { query, page };
});
diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.toml
index bde03fce07..82e501bfb2 100644
--- a/crates/client/cache-wasm/Cargo.toml
+++ b/crates/client/cache-wasm/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2024"
name = "cache-wasm"
publish = false
-version = "0.3.0"
+version = "0.3.1"
[lib]
crate-type = ["cdylib", "rlib"]