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/feat/separate tan stack optimistic (#5020)

Sean Aye1869f71304af
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 98c858dc7f..5e1fbb69e2 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
@@ -22,6 +22,7 @@ import {
type NormalizedCacheExchangeOptions,
normalizedCacheExchange,
} from './normalized-cache-exchange';
+import { optimisticMutationDispositionOf } from './optimistic';
const QUERY = gql`
query Soup($input: SoupInput!) {
@@ -66,6 +67,7 @@ function makeFakeHost(): FakeHost {
args: Parameters<CacheHost['beginOptimisticWrite']>[0];
attemptCount: number;
leased: boolean;
+ nextAttemptAtMs?: number;
}> = [];
const host: FakeHost = {
clientId: 'test-client',
@@ -128,10 +130,20 @@ function makeFakeHost(): FakeHost {
async inspectQuery() {
return [];
},
- async claimNextMutation(_owner): Promise<ClaimedMutation | undefined> {
+ async claimNextMutation(
+ _owner,
+ nowMs
+ ): Promise<ClaimedMutation | undefined> {
const head = queue[0];
- if (!head || head.leased) return undefined;
+ if (
+ !head ||
+ head.leased ||
+ (head.nextAttemptAtMs !== undefined && head.nextAttemptAtMs > nowMs)
+ ) {
+ return undefined;
+ }
head.leased = true;
+ head.nextAttemptAtMs = undefined;
head.attemptCount += 1;
host.claims.push(head.transactionId);
return {
@@ -146,12 +158,15 @@ function makeFakeHost(): FakeHost {
async deferOptimisticWrite(
transactionId,
_claim: MutationClaim,
- _nextAttemptAtMs,
+ nextAttemptAtMs,
error
) {
host.defers.push({ transactionId, error });
const head = queue[0];
- if (head?.transactionId === transactionId) head.leased = false;
+ if (head?.transactionId === transactionId) {
+ head.leased = false;
+ head.nextAttemptAtMs = nextAttemptAtMs;
+ }
},
async commitOptimisticWrite(
transactionId,
@@ -181,6 +196,9 @@ function makeFakeHost(): FakeHost {
onCacheChanged() {
return () => undefined;
},
+ onMutationSettled() {
+ return () => undefined;
+ },
dispose() {},
};
return host;
@@ -662,6 +680,10 @@ describe('normalizedCacheExchange', () => {
// Only the real network result reaches the caller.
expect(results).toHaveLength(1);
expect(results[0]?.data).toEqual({ from: 'network' });
+ expect(optimisticMutationDispositionOf(results[0])).toEqual({
+ kind: 'committed',
+ data: { from: 'network' },
+ });
// The optimistic path never uses the plain write-through.
expect(host.writes).toHaveLength(0);
});
@@ -699,6 +721,27 @@ describe('normalizedCacheExchange', () => {
expect(host.rollbacks).toEqual(['txn-1']);
expect(host.commits).toHaveLength(0);
expect(results[0]?.error).toBe(error);
+ expect(optimisticMutationDispositionOf(results[0])).toEqual({
+ kind: 'permanently-failed',
+ error,
+ });
+ });
+
+ it('keeps the disposition queued when permanent settlement is uncertain', async () => {
+ const error = new CombinedError({ graphQLErrors: ['nope'] });
+ host.rollbackOptimisticWrite = async () => {
+ throw new Error('lost rollback response');
+ };
+ const { ops, results } = harness(host, (op) =>
+ op.kind === 'mutation' ? { error, data: undefined } : {}
+ );
+ ops.next(makeMutationOp(1, optimistic));
+ await tick();
+
+ expect(optimisticMutationDispositionOf(results[0])).toEqual({
+ kind: 'queued',
+ transactionId: 'txn-1',
+ });
});
it('rolls back on a network error result', async () => {
@@ -734,6 +777,34 @@ describe('normalizedCacheExchange', () => {
]);
expect(host.rollbacks).toHaveLength(0);
expect(results[0]?.error).toBe(error);
+ expect(optimisticMutationDispositionOf(results[0])).toEqual({
+ kind: 'queued',
+ transactionId: 'txn-1',
+ });
+ });
+
+ it('reports a later mutation as queued while a deferred head blocks it', async () => {
+ const error = new CombinedError({
+ networkError: new Error('offline'),
+ });
+ const { ops, results, forwarded } = harness(
+ host,
+ (op) => (op.kind === 'mutation' ? { error, data: undefined } : {}),
+ { shouldRetryMutation: () => true }
+ );
+
+ ops.next(makeMutationOp(1, optimistic));
+ await tick();
+ ops.next(makeMutationOp(2, optimistic));
+ await tick();
+
+ expect(host.claims).toEqual(['txn-1']);
+ expect(forwarded.map((op) => op.key)).toEqual([1]);
+ expect(results).toHaveLength(2);
+ expect(optimisticMutationDispositionOf(results[1])).toEqual({
+ kind: 'queued',
+ transactionId: 'txn-2',
+ });
});
it('forwards queued optimistic mutations strictly in enqueue order', async () => {
@@ -743,7 +814,11 @@ describe('normalizedCacheExchange', () => {
await tick();
expect(host.claims).toEqual(['txn-1', 'txn-2']);
- expect(forwarded.map((op) => op.key)).toEqual([1, 2]);
+ // The second caller was released as queued while the first attempt was
+ // in flight, so its eventual send is reconstructed from durable data.
+ expect(forwarded).toHaveLength(2);
+ expect(forwarded[0]?.key).toBe(1);
+ expect(forwarded[1]?.kind).toBe('mutation');
expect(host.commits.map((entry) => entry.transactionId)).toEqual([
'txn-1',
'txn-2',
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 4f8588776f..c01fbd52c4 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
@@ -21,7 +21,8 @@
* - With an optimistic response (see `executeOptimisticMutation`): the
* mutation and layer are durably queued before the ordered runner forwards
* it. Retryable failures retain optimism for background replay; permanent
- * failures roll back. The caller still receives only its network result.
+ * failures roll back. A caller whose operation is blocked behind the queue
+ * head receives a synthetic `queued` disposition instead of waiting.
* - Without one: forwarded normally; successful responses are normalized
* through the standard write path so dependent cached queries update.
*
@@ -57,7 +58,10 @@ import {
} from 'wonka';
import type { CacheHost } from '../host/types';
import type { OptimisticWriteResult, QueryRevalidationWire } from '../protocol';
-import { optimisticContextOf } from './optimistic';
+import {
+ optimisticContextOf,
+ withOptimisticMutationDisposition,
+} from './optimistic';
/**
* Private operation-context field carrying the optimistic transaction id
@@ -166,6 +170,23 @@ function cacheResult(
};
}
+function queuedMutationResult(
+ op: Operation,
+ transactionId: string
+): OperationResult {
+ return withOptimisticMutationDisposition(
+ {
+ operation: op,
+ data: optimisticContextOf(op)?.optimisticResponse,
+ error: undefined,
+ extensions: undefined,
+ stale: false,
+ hasNext: false,
+ },
+ { kind: 'queued', transactionId }
+ );
+}
+
export interface NormalizedCacheExchangeOptions {
/** Called when a cache read/write fails (diagnostics; flow already degraded to network). */
onCacheError?: (error: unknown, op: Operation) => void;
@@ -180,8 +201,8 @@ export interface NormalizedCacheExchangeOptions {
extractIdentity?: (data: unknown) => string | undefined;
/**
* Decides whether a failed optimistic mutation remains queued. The caller
- * still receives the current network error; `true` retains the optimistic
- * layer for a later background attempt. Defaults to `false`.
+ * receives a `queued` disposition; `true` retains the optimistic layer for
+ * a later background attempt. Defaults to `false`.
*/
shouldRetryMutation?: (error: CombinedError) => boolean | Promise<boolean>;
}
@@ -216,7 +237,13 @@ export function normalizedCacheExchange(
const { source: forwardQueue$, next: enqueueForward } =
makeSubject<Operation>();
const queueOwner = `exchange:${host.clientId}`;
- const liveQueuedOps = new Map<string, Operation>();
+ const liveQueuedOps = new Map<
+ string,
+ {
+ operation: Operation;
+ resolveRoute: (result: OperationResult | undefined) => void;
+ }
+ >();
let attemptInFlight = false;
let drainRunning = false;
let deferredUntil: number | undefined;
@@ -230,8 +257,23 @@ export function normalizedCacheExchange(
}, delayMs);
}
+ function resolveLiveOperationsAsQueued(): void {
+ for (const [transactionId, live] of liveQueuedOps) {
+ liveQueuedOps.delete(transactionId);
+ live.resolveRoute(
+ queuedMutationResult(live.operation, transactionId)
+ );
+ }
+ }
+
async function drainQueue(): Promise<void> {
- if (attemptInFlight || drainRunning) return;
+ if (attemptInFlight) {
+ // Every newly enqueued operation is behind the claimed head. Its
+ // caller can stop waiting; durable replay now owns the mutation.
+ resolveLiveOperationsAsQueued();
+ return;
+ }
+ if (drainRunning) return;
drainRunning = true;
try {
const now = Date.now();
@@ -241,6 +283,7 @@ export function normalizedCacheExchange(
now + QUEUE_LEASE_MS
);
if (!claimed) {
+ resolveLiveOperationsAsQueued();
scheduleDrain(
deferredUntil === undefined
? EMPTY_QUEUE_POLL_MS
@@ -259,10 +302,12 @@ export function normalizedCacheExchange(
};
const live = liveQueuedOps.get(claimed.transactionId);
if (live) {
+ liveQueuedOps.delete(claimed.transactionId);
+ live.resolveRoute(undefined);
enqueueForward(
withQueueRequestTimeout(
- makeOperation(live.kind, live, {
- ...live.context,
+ makeOperation(live.operation.kind, live.operation, {
+ ...live.operation.context,
[QUEUE_ATTEMPT_CONTEXT_KEY]: attempt,
})
)
@@ -278,16 +323,25 @@ export function normalizedCacheExchange(
}
);
void replay.toPromise();
- } catch {
- await host.rollbackOptimisticWrite(claimed.transactionId, {
- owner: queueOwner,
- generation: claimed.leaseGeneration,
- });
+ } catch (error) {
+ await host.rollbackOptimisticWrite(
+ claimed.transactionId,
+ {
+ owner: queueOwner,
+ generation: claimed.leaseGeneration,
+ },
+ error instanceof Error ? error.message : String(error)
+ );
attemptInFlight = false;
scheduleDrain();
}
}
+ // Any other live operation is ordered behind the claimed head.
+ resolveLiveOperationsAsQueued();
} catch {
+ // Enqueue already succeeded, so callers must observe these as
+ // queued even if the runner cannot currently inspect the head.
+ resolveLiveOperationsAsQueued();
scheduleDrain(EMPTY_QUEUE_POLL_MS);
} finally {
drainRunning = false;
@@ -361,20 +415,22 @@ export function normalizedCacheExchange(
}
/** Durably queues optimism before allowing the ordered runner to send. */
- async function prepareMutation(op: Operation): Promise<void> {
+ async function prepareMutation(
+ op: Operation
+ ): Promise<OperationResult | undefined> {
if (host.disabled) {
enqueueForward(op);
- return;
+ return undefined;
}
// Reconstructed startup retries already have a durable transaction.
if (queueAttemptOf(op)) {
enqueueForward(withQueueRequestTimeout(op));
- return;
+ return undefined;
}
const optimistic = optimisticContextOf(op);
if (!optimistic) {
enqueueForward(op);
- return;
+ return undefined;
}
try {
const args = {
@@ -407,11 +463,18 @@ export function normalizedCacheExchange(
],
});
}
- liveQueuedOps.set(begin.transactionId, op);
+ const routed = new Promise<OperationResult | undefined>((resolve) => {
+ liveQueuedOps.set(begin.transactionId, {
+ operation: op,
+ resolveRoute: resolve,
+ });
+ });
scheduleDrain();
+ return await routed;
} catch (error) {
options.onCacheError?.(error, op);
enqueueForward(op);
+ return undefined;
}
}
@@ -440,6 +503,8 @@ export function normalizedCacheExchange(
generation: attempt.leaseGeneration,
};
let retryAt: number | undefined;
+ let disposition: 'committed' | 'queued' | 'permanently-failed' =
+ 'queued';
try {
if (result.error || result.data == null) {
let retry = false;
@@ -458,11 +523,14 @@ export function normalizedCacheExchange(
retryAt,
result.error?.message ?? 'mutation returned no data'
);
+ disposition = 'queued';
} else {
await host.rollbackOptimisticWrite(
attempt.transactionId,
- claim
+ claim,
+ result.error?.message ?? 'mutation returned no data'
);
+ disposition = 'permanently-failed';
}
} else {
const committed = await host.commitOptimisticWrite(
@@ -478,10 +546,15 @@ export function normalizedCacheExchange(
}
);
revalidateAfterCommit(committed.revalidations ?? [], op);
+ disposition = 'committed';
}
} catch (error) {
options.onCacheError?.(error, op);
retryAt = Date.now() + QUEUE_LEASE_MS;
+ // The durable transaction may still exist (or the settlement
+ // may have completed despite a lost response). Never tell the
+ // caller to roll back while settlement is uncertain.
+ disposition = 'queued';
} finally {
liveQueuedOps.delete(attempt.transactionId);
attemptInFlight = false;
@@ -490,7 +563,14 @@ export function normalizedCacheExchange(
retryAt === undefined ? 0 : Math.max(0, retryAt - Date.now())
);
}
- } else if (result.data != null && !result.error) {
+ return withOptimisticMutationDisposition(result, {
+ kind: disposition,
+ transactionId: attempt.transactionId,
+ });
+ }
+
+ const optimistic = optimisticContextOf(op);
+ if (result.data != null && !result.error) {
try {
// Plain mutation write-through: normalized entities update
// dependent cached queries.
@@ -504,6 +584,14 @@ export function normalizedCacheExchange(
options.onCacheError?.(error, op);
}
}
+ if (optimistic) {
+ return withOptimisticMutationDisposition(result, {
+ kind:
+ result.data != null && !result.error
+ ? 'committed'
+ : 'permanently-failed',
+ });
+ }
}
return result;
}
@@ -523,15 +611,17 @@ export function normalizedCacheExchange(
);
// Optimistic mutations are held after durable enqueue until the strict
- // queue runner claims them. The network result remains the only
- // mutation emission.
+ // queue runner claims them. Operations behind the head emit a queued
+ // disposition immediately; the head emits its network disposition.
const mutationPrep$ = pipe(
shared,
filter((op) => op.kind === 'mutation'),
mergeMap((op) =>
pipe(
fromPromise(prepareMutation(op)),
- mergeMap(() => empty as Source<OperationResult>)
+ mergeMap((result) =>
+ result ? fromValue(result) : (empty as Source<OperationResult>)
+ )
)
)
);
diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
index a7d1a2230c..ecd578894d 100644
--- a/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
@@ -10,6 +10,7 @@ import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
import {
type AnyVariables,
type Client,
+ CombinedError,
type Operation,
type OperationResult,
type OperationResultSource,
@@ -28,6 +29,9 @@ import {
/** Private operation-context field carrying serializable optimistic data. */
const OPTIMISTIC_MUTATION_CONTEXT_KEY = 'normalizedCacheOptimistic';
+/** Private result-extension field carrying the queue disposition. */
+const OPTIMISTIC_MUTATION_DISPOSITION_KEY =
+ 'normalizedCacheMutationDisposition';
declare const selectionType: unique symbol;
declare const optimisticUpdateType: unique symbol;
@@ -92,6 +96,65 @@ export type OptimisticMutationContext<TData = unknown> = {
revalidations: QueryRevalidationWire[];
};
+/** Caller-facing disposition of one durable optimistic mutation submission. */
+export type OptimisticMutationDisposition<TData> =
+ | { kind: 'committed'; data: TData }
+ | { kind: 'queued'; transactionId: string }
+ | { kind: 'permanently-failed'; error: CombinedError };
+
+/** Exchange-private metadata attached after queue routing or settlement. */
+export type OptimisticMutationDispositionMetadata =
+ | { kind: 'committed'; transactionId?: string }
+ | { kind: 'queued'; transactionId: string }
+ | { kind: 'permanently-failed'; transactionId?: string };
+
+/** Returns a copy of an operation result carrying its queue disposition. */
+export function withOptimisticMutationDisposition(
+ result: OperationResult,
+ disposition: OptimisticMutationDispositionMetadata
+): OperationResult {
+ return {
+ ...result,
+ extensions: {
+ ...result.extensions,
+ [OPTIMISTIC_MUTATION_DISPOSITION_KEY]: disposition,
+ },
+ };
+}
+
+/** Reads the typed caller-facing disposition attached by the cache exchange. */
+export function optimisticMutationDispositionOf<
+ TData,
+ TVariables extends AnyVariables,
+>(
+ result: OperationResult<TData, TVariables>
+): OptimisticMutationDisposition<TData> | undefined {
+ const value: unknown =
+ result.extensions?.[OPTIMISTIC_MUTATION_DISPOSITION_KEY];
+ if (value === null || typeof value !== 'object' || !('kind' in value)) {
+ return undefined;
+ }
+
+ const metadata = value as OptimisticMutationDispositionMetadata;
+ if (metadata.kind === 'queued' && metadata.transactionId) {
+ return { kind: 'queued', transactionId: metadata.transactionId };
+ }
+ if (metadata.kind === 'committed' && result.data != null) {
+ return { kind: 'committed', data: result.data };
+ }
+ if (metadata.kind === 'permanently-failed') {
+ return {
+ kind: 'permanently-failed',
+ error:
+ result.error ??
+ new CombinedError({
+ graphQLErrors: [new Error('mutation returned no data')],
+ }),
+ };
+ }
+ return undefined;
+}
+
function serializeRevalidation(
revalidation: QueryRevalidation
): QueryRevalidationWire {
@@ -163,7 +226,8 @@ export function update<TItem extends object>(
/**
* Executes `document` with one durable optimistic entity/link transaction.
- * The source resolves only with the real network result.
+ * The source resolves with the head's network result or a synthetic queued
+ * disposition when an older mutation currently blocks the operation.
*/
export function executeOptimisticMutation<
TData,
diff --git a/apps/web/src/lib/graphql-cache/host/noop-host.ts b/apps/web/src/lib/graphql-cache/host/noop-host.ts
index c39d8a90f5..9c985ae06b 100644
--- a/apps/web/src/lib/graphql-cache/host/noop-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/noop-host.ts
@@ -61,6 +61,9 @@ export function createNoopCacheHost(reason: string): CacheHost {
onCacheChanged() {
return () => undefined;
},
+ onMutationSettled() {
+ return () => undefined;
+ },
dispose() {},
};
}
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index 44c1085931..197e66ad4e 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -175,13 +175,14 @@ describe('createTauriCacheHost', () => {
})
);
- await host.rollbackOptimisticWrite('1', claim);
+ await host.rollbackOptimisticWrite('1', claim, 'invalid property');
expect(invokeMock).toHaveBeenCalledWith(
'graphql_cache_rollback_optimistic_write',
{
transactionId: '1',
leaseOwner: 'runner',
leaseGeneration: '2',
+ error: 'invalid property',
}
);
});
@@ -249,6 +250,24 @@ describe('createTauriCacheHost', () => {
expect(calls).toBe(1);
});
+ it('delivers queued mutation settlements from the broadcast event', async () => {
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ const seen: unknown[] = [];
+ host.onMutationSettled((settlement) => seen.push(settlement));
+ await Promise.resolve();
+
+ const settlement = {
+ transactionId: '12',
+ status: 'permanently-failed' as const,
+ error: 'invalid property',
+ };
+ eventCallbacks.get('graphql-cache://mutation-settled')?.({
+ payload: settlement,
+ });
+
+ expect(seen).toEqual([settlement]);
+ });
+
it('normalizes string command errors to Error rejections', async () => {
const host = createTauriCacheHost({ scope: 'scope-1' });
invokeMock.mockImplementation((command: string) =>
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index c655b3f135..935ecbf684 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -13,6 +13,7 @@ import {
type CachedQueryInstanceWire,
type ClaimedMutation,
type MutationClaim,
+ type MutationSettlement,
type OptimisticWriteResult,
type ReadRecordsArgs,
type ReadResult,
@@ -32,6 +33,8 @@ import type {
const OPS_AFFECTED_EVENT = 'graphql-cache://ops-affected';
/** Keep in sync with `CACHE_CHANGED_EVENT` in the native plugin. */
const CACHE_CHANGED_EVENT = 'graphql-cache://cache-changed';
+/** Keep in sync with `MUTATION_SETTLED_EVENT` in graphql_cache_plugin. */
+const MUTATION_SETTLED_EVENT = 'graphql-cache://mutation-settled';
/** Payload of the ops-affected event (graphql_cache_plugin `OpsAffectedEvent`). */
type OpsAffectedPayload = {
@@ -59,6 +62,9 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
const clientId = crypto.randomUUID();
const affectedSubscribers = new Set<(opKeys: number[]) => void>();
const cacheChangeSubscribers = new Set<() => void>();
+ const settlementSubscribers = new Set<
+ (settlement: MutationSettlement) => void
+ >();
const requestTimeoutMs =
options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
@@ -87,9 +93,8 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
// Failure tolerated: reads/writes still work, only push-driven
// re-execution is lost — same degradation as a broken worker port.
- const unlisten: Promise<UnlistenFn | undefined> = listen<OpsAffectedPayload>(
- OPS_AFFECTED_EVENT,
- (event) => {
+ const unlistenOps: Promise<UnlistenFn | undefined> =
+ listen<OpsAffectedPayload>(OPS_AFFECTED_EVENT, (event) => {
const prefix = `${clientId}:`;
const opKeys = event.payload.opIds
.filter((id) => id.startsWith(prefix))
@@ -98,11 +103,17 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
if (opKeys.length > 0) {
for (const cb of affectedSubscribers) cb(opKeys);
}
- }
- ).catch((error) => {
- console.warn('graphql cache ops-affected listener failed', error);
- return undefined;
- });
+ }).catch((error) => {
+ console.warn('graphql cache ops-affected listener failed', error);
+ return undefined;
+ });
+ const unlistenSettlements: Promise<UnlistenFn | undefined> =
+ listen<MutationSettlement>(MUTATION_SETTLED_EVENT, (event) => {
+ for (const cb of settlementSubscribers) cb(event.payload);
+ }).catch((error) => {
+ console.warn('graphql cache mutation-settled listener failed', error);
+ return undefined;
+ });
const unlistenCacheChanges: Promise<UnlistenFn | undefined> =
listen<CacheChangedPayload>(CACHE_CHANGED_EVENT, () => {
@@ -250,7 +261,8 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
async rollbackOptimisticWrite(
transactionId: string,
- claim: MutationClaim
+ claim: MutationClaim,
+ error: string
): Promise<WriteResult> {
await ready;
return await request<WriteResult>(
@@ -259,6 +271,7 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
transactionId,
leaseOwner: claim.owner,
leaseGeneration: claim.generation,
+ error,
}
);
},
@@ -288,11 +301,20 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
return () => cacheChangeSubscribers.delete(cb);
},
+ onMutationSettled(
+ cb: (settlement: MutationSettlement) => void
+ ): () => void {
+ settlementSubscribers.add(cb);
+ return () => settlementSubscribers.delete(cb);
+ },
+
dispose() {
affectedSubscribers.clear();
cacheChangeSubscribers.clear();
- void unlisten.then((fn) => fn?.());
+ settlementSubscribers.clear();
+ void unlistenOps.then((fn) => fn?.());
void unlistenCacheChanges.then((fn) => fn?.());
+ void unlistenSettlements.then((fn) => fn?.());
},
};
}
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index 9bfb80f1bf..7bf3fd3207 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -9,6 +9,7 @@ import type {
CachedQueryInstanceWire,
ClaimedMutation,
MutationClaim,
+ MutationSettlement,
OptimisticLinkPatchWire,
OptimisticWriteResult,
QueryRevalidationWire,
@@ -83,7 +84,8 @@ export interface CacheHost {
/** Permanently fails a claimed mutation and drops its optimistic layer. */
rollbackOptimisticWrite(
transactionId: string,
- claim: MutationClaim
+ claim: MutationClaim,
+ error: string
): Promise<WriteResult>;
/** Evict records by entity key (external/push updates); returns affected local op ids. */
invalidate(keys: string[]): Promise<string[]>;
@@ -102,5 +104,8 @@ export interface CacheHost {
/** Subscribes whenever the effective normalized-cache view changes. */
onCacheChanged(cb: () => void): () => void;
+ /** Subscribes to final commit/rollback events for queued mutations. */
+ onMutationSettled(cb: (settlement: MutationSettlement) => void): () => void;
+
dispose(): void;
}
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
index 5cfbb66545..23e20cb97d 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
@@ -77,6 +77,45 @@ describe('createWorkerCacheHost', () => {
host.dispose();
});
+ it('delivers queued mutation settlements pushed by the worker', async () => {
+ let push: (message: unknown) => void = () => {
+ throw new Error('worker not initialized');
+ };
+ class FakeSharedWorker {
+ port = {
+ onmessage: null as ((event: MessageEvent) => void) | null,
+ start() {},
+ close() {},
+ postMessage: (request: { id?: number }) => {
+ if (request.id === undefined) return;
+ queueMicrotask(() => {
+ this.port.onmessage?.({
+ data: { id: request.id, ok: true, result: null },
+ } as MessageEvent);
+ });
+ },
+ };
+
+ constructor() {
+ push = (message) =>
+ this.port.onmessage?.({ data: message } as MessageEvent);
+ }
+ }
+ vi.stubGlobal('SharedWorker', FakeSharedWorker);
+ const host = createWorkerCacheHost({ scope: 'scope-1' });
+ const seen: unknown[] = [];
+ host.onMutationSettled((settlement) => seen.push(settlement));
+ const settlement = {
+ transactionId: '12',
+ status: 'committed' as const,
+ };
+
+ push({ kind: 'mutation-settled', settlement });
+
+ expect(seen).toEqual([settlement]);
+ host.dispose();
+ });
+
it('times out reads without timing out durable mutations', async () => {
vi.useFakeTimers();
const requests: Array<{ id?: number; kind: string }> = [];
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.ts
index 98b556fe78..b5c7ee86de 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -10,6 +10,7 @@ import {
type ClaimedMutation,
isCachePush,
type MutationClaim,
+ type MutationSettlement,
type OptimisticWriteResult,
type ReadRecordsArgs,
type ReadResult,
@@ -62,6 +63,9 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
const pending = new Map<number, Pending>();
const affectedSubscribers = new Set<(opKeys: number[]) => void>();
const cacheChangeSubscribers = new Set<() => void>();
+ const settlementSubscribers = new Set<
+ (settlement: MutationSettlement) => void
+ >();
const requestTimeoutMs =
options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
let nextRequestId = 1;
@@ -76,6 +80,10 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
for (const cb of cacheChangeSubscribers) cb();
return;
}
+ if (msg.kind === 'mutation-settled') {
+ for (const cb of settlementSubscribers) cb(msg.settlement);
+ return;
+ }
const prefix = `${clientId}:`;
const opKeys = msg.opIds
.filter((id) => id.startsWith(prefix))
@@ -281,7 +289,8 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
async rollbackOptimisticWrite(
transactionId: string,
- claim: MutationClaim
+ claim: MutationClaim,
+ error: string
): Promise<WriteResult> {
await ready;
return (await request({
@@ -289,6 +298,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
transactionId,
leaseOwner: claim.owner,
leaseGeneration: claim.generation,
+ error,
})) as WriteResult;
},
@@ -317,9 +327,17 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
return () => cacheChangeSubscribers.delete(cb);
},
+ onMutationSettled(
+ cb: (settlement: MutationSettlement) => void
+ ): () => void {
+ settlementSubscribers.add(cb);
+ return () => settlementSubscribers.delete(cb);
+ },
+
dispose() {
affectedSubscribers.clear();
cacheChangeSubscribers.clear();
+ settlementSubscribers.clear();
dispose();
},
};
diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.ts
index 370e28ad7b..27bbd83668 100644
--- a/apps/web/src/lib/graphql-cache/index.ts
+++ b/apps/web/src/lib/graphql-cache/index.ts
@@ -13,8 +13,10 @@ export {
executeOptimisticMutation,
type LinkDiff,
type ListSelection,
+ type OptimisticMutationDisposition,
type OptimisticMutationOptions,
type OptimisticUpdate,
+ optimisticMutationDispositionOf,
prependUnique,
type QueryRevalidation,
remove,
@@ -41,6 +43,7 @@ export type {
CachePush,
CacheRequest,
CacheResponse,
+ MutationSettlement,
OptimisticWriteResult,
ReadRecordsArgs,
ReadResult,
diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.ts
index 4b2ff8885d..80a1e446b2 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -123,6 +123,15 @@ export type MutationClaim = {
generation: string;
};
+/** Final settlement of a previously queued optimistic mutation. */
+export type MutationSettlement =
+ | { transactionId: string; status: 'committed' }
+ | {
+ transactionId: string;
+ status: 'permanently-failed';
+ error: string;
+ };
+
export type CacheRequest = { id: number } & (
| { kind: 'init'; scope: string; hotCapacity?: number }
| {
@@ -189,6 +198,7 @@ export type CacheRequest = { id: number } & (
transactionId: string;
leaseOwner: string;
leaseGeneration: string;
+ error: string;
}
| {
kind: 'read-records';
@@ -240,15 +250,11 @@ export type CachePush =
/** Changed entity keys, for diagnostics/advanced consumers. */
keys: string[];
}
- | {
- kind: 'cache-changed';
- };
+ | { kind: 'cache-changed' }
+ | { kind: 'mutation-settled'; settlement: MutationSettlement };
export type WorkerMessage = CacheResponse | CachePush;
export function isCachePush(msg: WorkerMessage): msg is CachePush {
- return (
- 'kind' in msg &&
- (msg.kind === 'ops-affected' || msg.kind === 'cache-changed')
- );
+ return 'kind' in msg;
}
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
index 8820da2718..cdc7a1d196 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -148,6 +148,13 @@ export class CacheWorkerCore {
request.data
);
this.fanOut(result, true);
+ this.push({
+ kind: 'mutation-settled',
+ settlement: {
+ transactionId: request.transactionId,
+ status: 'committed',
+ },
+ });
return result;
})
.with({ kind: 'rollback-optimistic-write' }, async (request) => {
@@ -158,6 +165,14 @@ export class CacheWorkerCore {
request.leaseGeneration
);
this.fanOut(result, true);
+ this.push({
+ kind: 'mutation-settled',
+ settlement: {
+ transactionId: request.transactionId,
+ status: 'permanently-failed',
+ error: request.error,
+ },
+ });
return result;
})
.with({ kind: 'invalidate' }, async (request) => {
diff --git a/apps/web/src/lib/queries/properties/entity.test.tsx b/apps/web/src/lib/queries/properties/entity.test.tsx
new file mode 100644
index 0000000000..fbfd104758
--- /dev/null
+++ b/apps/web/src/lib/queries/properties/entity.test.tsx
@@ -0,0 +1,262 @@
+import type { Property } from '@property/types';
+import { 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';
+
+const setEntityPropertyMock = vi.hoisted(() => vi.fn());
+const rollbackMock = vi.hoisted(() => vi.fn());
+const optimisticUpdateSoupEntityMock = vi.hoisted(() => vi.fn());
+const invalidateSoupEntityMock = vi.hoisted(() => vi.fn());
+const graphqlSoupEnabledMock = vi.hoisted(() => vi.fn(() => true));
+const toastFailureMock = vi.hoisted(() => vi.fn());
+const trackMock = vi.hoisted(() => vi.fn());
+const settlementCallbacks = vi.hoisted(
+ () =>
+ new Set<
+ (settlement: {
+ transactionId: string;
+ status: 'committed' | 'permanently-failed';
+ error?: string;
+ }) => void
+ >()
+);
+
+vi.mock('@app/lib/analytics', () => ({
+ analytics: { track: trackMock },
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: toastFailureMock },
+}));
+
+vi.mock('@core/constant/featureFlags', () => ({
+ ENABLE_GRAPHQL_SOUP: graphqlSoupEnabledMock,
+}));
+
+vi.mock('@property/api/converters', () => ({
+ entityPropertyFromApi: vi.fn(),
+ propertyValueToApi: vi.fn(() => ({ type: 'string', value: 'doing' })),
+}));
+
+vi.mock('@property/utils', () => ({
+ isInstantiatedProperty: vi.fn(() => true),
+}));
+
+vi.mock('../../service-clients/service-properties/client', () => ({
+ propertiesServiceClient: {},
+}));
+
+vi.mock('../../service-clients/service-storage/graphql-properties', () => ({
+ setEntityProperty: setEntityPropertyMock,
+}));
+
+vi.mock('../client', () => ({
+ get queryClient() {
+ return testQueryClient;
+ },
+}));
+
+vi.mock('../../service-clients/service-storage/graphql-soup', () => ({
+ getGraphqlSoupClient: vi.fn(() => ({})),
+ getGraphqlCacheHost: vi.fn(() => ({
+ onMutationSettled: (
+ callback: (settlement: {
+ transactionId: string;
+ status: 'committed' | 'permanently-failed';
+ error?: string;
+ }) => void
+ ) => {
+ settlementCallbacks.add(callback);
+ return () => settlementCallbacks.delete(callback);
+ },
+ })),
+}));
+
+vi.mock('../soup/cache', () => ({
+ getSoupEntityById: vi.fn(() => ({
+ tag: 'document',
+ data: {
+ id: 'task-1',
+ properties: [
+ {
+ id: 'assignment-1',
+ definition: { id: 'status-def' },
+ value: { type: 'String', value: 'todo' },
+ },
+ ],
+ },
+ frecency_score: 0,
+ })),
+ invalidateSoupEntity: invalidateSoupEntityMock,
+ optimisticUpdateSoupEntity: optimisticUpdateSoupEntityMock.mockImplementation(
+ () => ({ rollback: rollbackMock })
+ ),
+}));
+
+vi.mock('../soup/grouped/graphql-optimistic', () => ({
+ buildOptimisticGroupedPropertyUpdates: vi.fn(async () => undefined),
+ groupedPropertyKeys: vi.fn(() => []),
+}));
+
+vi.mock('./graphql-optimistic', () => ({
+ buildOptimisticSetEntityProperty: vi.fn(() => ({ id: 'assignment-1' })),
+}));
+
+import {
+ useAddEntityPropertyMutation,
+ useBulkSaveEntityPropertiesMutation,
+} from './entity';
+
+let testQueryClient: QueryClient;
+let mutation: ReturnType<typeof useBulkSaveEntityPropertiesMutation>;
+let addMutation: ReturnType<typeof useAddEntityPropertyMutation>;
+let dispose: (() => void) | undefined;
+
+const property = {
+ propertyId: 'assignment-1',
+ propertyDefinitionId: 'status-def',
+ displayName: 'Status',
+ valueType: 'STRING',
+ isMultiSelect: false,
+ isSystemProperty: true,
+} as unknown as Property;
+
+const variables = {
+ properties: [
+ {
+ entityId: 'task-1',
+ entityType: 'TASK' as const,
+ property,
+ apiValues: { valueType: 'STRING' as const, value: 'doing' },
+ },
+ ],
+};
+
+function renderMutation(): void {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ dispose = render(
+ () => (
+ <QueryClientProvider client={testQueryClient}>
+ {(() => {
+ mutation = useBulkSaveEntityPropertiesMutation();
+ addMutation = useAddEntityPropertyMutation();
+ return null as unknown as JSX.Element;
+ })()}
+ </QueryClientProvider>
+ ),
+ container
+ );
+}
+
+describe('useBulkSaveEntityPropertiesMutation dispositions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ optimisticUpdateSoupEntityMock.mockReturnValue({ rollback: rollbackMock });
+ graphqlSoupEnabledMock.mockReturnValue(true);
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ settlementCallbacks.clear();
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ vi.spyOn(testQueryClient, 'invalidateQueries');
+ renderMutation();
+ });
+
+ afterEach(() => {
+ dispose?.();
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+ });
+
+ it('uses only GraphQL optimism when writes are queued', async () => {
+ setEntityPropertyMock
+ .mockResolvedValueOnce({ kind: 'queued', transactionId: 'txn-1' })
+ .mockResolvedValueOnce({ kind: 'queued', transactionId: 'txn-2' });
+
+ await expect(mutation.mutateAsync(variables)).resolves.toBeUndefined();
+ await expect(mutation.mutateAsync(variables)).resolves.toBeUndefined();
+
+ expect(optimisticUpdateSoupEntityMock).not.toHaveBeenCalled();
+ expect(rollbackMock).not.toHaveBeenCalled();
+ expect(invalidateSoupEntityMock).not.toHaveBeenCalled();
+ expect(testQueryClient.invalidateQueries).not.toHaveBeenCalled();
+ expect(toastFailureMock).not.toHaveBeenCalled();
+ expect(setEntityPropertyMock).toHaveBeenCalledWith(
+ expect.objectContaining({ optimisticProperty: { id: 'assignment-1' } })
+ );
+ });
+
+ it('reports a queued write that later permanently fails', async () => {
+ setEntityPropertyMock.mockResolvedValue({
+ kind: 'queued',
+ transactionId: 'txn-1',
+ });
+ await mutation.mutateAsync(variables);
+
+ for (const callback of settlementCallbacks) {
+ callback({
+ transactionId: 'txn-1',
+ status: 'permanently-failed',
+ error: 'invalid property',
+ });
+ }
+
+ expect(optimisticUpdateSoupEntityMock).not.toHaveBeenCalled();
+ expect(invalidateSoupEntityMock).not.toHaveBeenCalled();
+ expect(testQueryClient.invalidateQueries).not.toHaveBeenCalled();
+ expect(toastFailureMock).toHaveBeenCalledWith('Failed to save properties');
+ });
+
+ it('reports GraphQL permanent failures without touching TanStack caches', async () => {
+ setEntityPropertyMock.mockResolvedValue({
+ kind: 'permanently-failed',
+ error: new Error('invalid property'),
+ });
+
+ await expect(mutation.mutateAsync(variables)).rejects.toThrow(
+ 'One or more properties permanently failed to save'
+ );
+
+ expect(optimisticUpdateSoupEntityMock).not.toHaveBeenCalled();
+ expect(rollbackMock).not.toHaveBeenCalled();
+ expect(invalidateSoupEntityMock).not.toHaveBeenCalled();
+ expect(testQueryClient.invalidateQueries).not.toHaveBeenCalled();
+ expect(toastFailureMock).toHaveBeenCalledOnce();
+ });
+
+ it('does not invalidate TanStack property queries for GraphQL attachments', async () => {
+ setEntityPropertyMock.mockResolvedValue({ kind: 'committed' });
+
+ await addMutation.mutateAsync({
+ entityId: 'task-1',
+ entityType: 'TASK',
+ propertyDefinitionId: 'status-def',
+ });
+
+ expect(testQueryClient.invalidateQueries).not.toHaveBeenCalled();
+ expect(toastFailureMock).not.toHaveBeenCalled();
+ });
+
+ it('keeps the existing TanStack lifecycle when GraphQL Soup is disabled', async () => {
+ graphqlSoupEnabledMock.mockReturnValue(false);
+ setEntityPropertyMock.mockResolvedValue({
+ kind: 'permanently-failed',
+ error: new Error('invalid property'),
+ });
+
+ await expect(mutation.mutateAsync(variables)).rejects.toThrow(
+ 'One or more properties permanently failed to save'
+ );
+
+ expect(optimisticUpdateSoupEntityMock).toHaveBeenCalledOnce();
+ expect(rollbackMock).toHaveBeenCalledOnce();
+ expect(invalidateSoupEntityMock).toHaveBeenCalledWith('task-1');
+ expect(testQueryClient.invalidateQueries).toHaveBeenCalled();
+ expect(toastFailureMock).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.ts
index bbe1c5fbc5..f46c3d49a0 100644
--- a/apps/web/src/lib/queries/properties/entity.ts
+++ b/apps/web/src/lib/queries/properties/entity.ts
@@ -20,7 +20,10 @@ import type { EntityType } from '../../service-clients/service-properties/genera
import type { PropertyTargetEntityType } from '../../service-clients/service-properties/generated/schemas/propertyTargetEntityType';
import type { SoupProperty } from '../../service-clients/service-storage/generated/schemas/soupProperty';
import type { SoupPropertyValue } from '../../service-clients/service-storage/generated/schemas/soupPropertyValue';
-import { setEntityProperty } from '../../service-clients/service-storage/graphql-properties';
+import {
+ type SetEntityPropertyDisposition,
+ setEntityProperty,
+} from '../../service-clients/service-storage/graphql-properties';
import {
getGraphqlCacheHost,
getGraphqlSoupClient,
@@ -289,21 +292,34 @@ export function useAddEntityPropertyMutation(
return useMutation(() => ({
mutationFn: async (vars: AddEntityPropertyParams) => {
// New attachments have no assignment id until the server responds, so
- // this write is never optimistic; onSettled invalidation refetches.
- await setEntityProperty({
- entityType: toPropertyTargetEntityType(vars.entityType),
- entityId: vars.entityId,
- propertyDefinitionId: vars.propertyDefinitionId,
- value: null,
- });
+ // this write is never optimistic.
+ try {
+ const disposition = await setEntityProperty({
+ entityType: toPropertyTargetEntityType(vars.entityType),
+ entityId: vars.entityId,
+ propertyDefinitionId: vars.propertyDefinitionId,
+ value: null,
+ });
+ if (disposition.kind === 'permanently-failed') {
+ throw disposition.error;
+ }
+ } catch (error) {
+ if (ENABLE_GRAPHQL_SOUP()) {
+ console.error('Failed to add property', error);
+ toast.failure('Failed to add property');
+ }
+ throw error;
+ }
},
...withCallbacks<void, Error, AddEntityPropertyParams>(
{
onError(error) {
+ if (ENABLE_GRAPHQL_SOUP()) return;
console.error('Failed to add property', error);
toast.failure('Failed to add property');
},
onSettled: (_data, _error, variables) => {
+ if (ENABLE_GRAPHQL_SOUP()) return;
invalidatePropertiesForEntity(
variables.entityType,
variables.entityId
@@ -697,10 +713,93 @@ type BulkSaveEntityPropertiesParams = {
};
type BulkSaveEntityPropertiesContext = {
- soupTxns: SoupTransaction[];
+ usesGraphqlSoup: boolean;
+ /** Index-aligned with `variables.properties`; empty on the GraphQL path. */
+ soupTxns: Array<SoupTransaction | undefined>;
+};
+
+type BulkSaveEntityPropertiesResult = {
+ /** Index-aligned with the submitted properties. */
+ dispositions: SetEntityPropertyDisposition[];
};
-/** Saves multiple entity properties in bulk using parallel requests */
+class BulkSaveEntityPropertiesError extends Error {
+ constructor(readonly result: BulkSaveEntityPropertiesResult) {
+ super('One or more properties permanently failed to save');
+ this.name = 'BulkSaveEntityPropertiesError';
+ }
+}
+
+type QueuedPropertySave = BulkSaveEntityPropertiesParams['properties'][number];
+const queuedPropertySaves = new Map<string, QueuedPropertySave>();
+let settlementHost:
+ | NonNullable<ReturnType<typeof getGraphqlCacheHost>>
+ | undefined;
+let unsubscribeSettlements: (() => void) | undefined;
+
+function ensurePropertySettlementListener(): void {
+ const host = getGraphqlCacheHost();
+ if (!host || host === settlementHost) return;
+
+ unsubscribeSettlements?.();
+ settlementHost = host;
+ unsubscribeSettlements = host.onMutationSettled((settlement) => {
+ const item = queuedPropertySaves.get(settlement.transactionId);
+ if (!item) return;
+ queuedPropertySaves.delete(settlement.transactionId);
+
+ if (settlement.status === 'committed') {
+ trackTaskPropertySave(
+ item.entityId,
+ getPropertyDefinitionId(item.property),
+ item.apiValues
+ );
+ return;
+ }
+
+ const error = new Error(settlement.error);
+ console.error('Queued property save permanently failed', error);
+ toast.failure('Failed to save properties');
+ });
+}
+
+function handleAcceptedPropertySaves(
+ variables: BulkSaveEntityPropertiesParams,
+ result: BulkSaveEntityPropertiesResult
+): void {
+ for (const [index, disposition] of result.dispositions.entries()) {
+ const item = variables.properties[index];
+ if (!item) continue;
+ if (disposition.kind === 'committed') {
+ trackTaskPropertySave(
+ item.entityId,
+ getPropertyDefinitionId(item.property),
+ item.apiValues
+ );
+ } else if (disposition.kind === 'queued') {
+ queuedPropertySaves.set(disposition.transactionId, item);
+ ensurePropertySettlementListener();
+ }
+ }
+}
+
+function reportBulkPropertySaveFailure(error: Error): void {
+ console.error('Failed to bulk save properties', error);
+ toast.failure('Failed to save properties');
+}
+
+function rollbackBulkSoupTransactions(
+ context: BulkSaveEntityPropertiesContext | undefined
+): void {
+ if (!context?.soupTxns.length) return;
+ batch(() => {
+ for (let i = context.soupTxns.length - 1; i >= 0; i--) {
+ context.soupTxns[i]?.rollback();
+ }
+ });
+}
+
+/** Saves multiple entity properties, durably queueing GraphQL writes. */
export function useBulkSaveEntityPropertiesMutation(
callbacks?: MutationCallbacks<
void,
@@ -710,7 +809,8 @@ export function useBulkSaveEntityPropertiesMutation(
>
) {
return useMutation(() => ({
- mutationFn: async (vars: BulkSaveEntityPropertiesParams) => {
+ mutationFn: async (vars: BulkSaveEntityPropertiesParams): Promise<void> => {
+ const usesGraphqlSoup = ENABLE_GRAPHQL_SOUP();
const save = async (
item: BulkSaveEntityPropertiesParams['properties'][number]
) => {
@@ -724,7 +824,7 @@ export function useBulkSaveEntityPropertiesMutation(
);
let optimisticCache;
- if (ENABLE_GRAPHQL_SOUP() && isInstantiatedProperty(item.property)) {
+ if (usesGraphqlSoup && isInstantiatedProperty(item.property)) {
// Client construction owns host selection; force it before asking
// for the host used by inspect-driven relation discovery.
getGraphqlSoupClient();
@@ -751,24 +851,50 @@ export function useBulkSaveEntityPropertiesMutation(
}
}
- return setEntityProperty({
+ return await setEntityProperty({
entityType: toPropertyTargetEntityType(item.entityType),
entityId: item.entityId,
propertyDefinitionId: getPropertyDefinitionId(item.property),
value: propertyValue,
- // The TanStack optimistic transaction below stays as a transitional
- // render mirror until grouped Soup is a live urql subscription.
optimisticProperty,
optimisticCache,
});
};
- if (ENABLE_GRAPHQL_SOUP()) {
- // Begin each durable layer sequentially so later relation recipes see
- // the effective result of earlier property edits.
- for (const item of vars.properties) await save(item);
- } else {
- await Promise.all(vars.properties.map(save));
+ try {
+ let dispositions: SetEntityPropertyDisposition[];
+ if (usesGraphqlSoup) {
+ // Begin each durable layer sequentially so later relation recipes see
+ // the effective result of earlier property edits.
+ dispositions = [];
+ for (const item of vars.properties) {
+ dispositions.push(await save(item));
+ }
+ } else {
+ dispositions = await Promise.all(vars.properties.map(save));
+ }
+
+ const result = { dispositions };
+ handleAcceptedPropertySaves(vars, result);
+ if (
+ dispositions.some(
+ (disposition) => disposition.kind === 'permanently-failed'
+ )
+ ) {
+ const error = new BulkSaveEntityPropertiesError(result);
+ if (usesGraphqlSoup) reportBulkPropertySaveFailure(error);
+ throw error;
+ }
+ } catch (error) {
+ if (
+ usesGraphqlSoup &&
+ !(error instanceof BulkSaveEntityPropertiesError)
+ ) {
+ reportBulkPropertySaveFailure(
+ error instanceof Error ? error : new Error(String(error))
+ );
+ }
+ throw error;
}
},
...withCallbacks<
@@ -781,57 +907,39 @@ export function useBulkSaveEntityPropertiesMutation(
onMutate: (
vars: BulkSaveEntityPropertiesParams
): BulkSaveEntityPropertiesContext => {
- const soupTxns = batch<SoupTransaction[]>(() => {
- const txns: SoupTransaction[] = [];
- for (const item of vars.properties) {
- const txn = optimisticUpdateSoupEntityProperty(
- item.entityId,
- item.property,
- apiValuesToSoupPropertyValue(item.apiValues)
- );
- if (txn) txns.push(txn);
- }
- return txns;
- });
- return { soupTxns };
+ const usesGraphqlSoup = ENABLE_GRAPHQL_SOUP();
+ return {
+ usesGraphqlSoup,
+ soupTxns: usesGraphqlSoup
+ ? []
+ : batch(() =>
+ vars.properties.map((item) =>
+ optimisticUpdateSoupEntityProperty(
+ item.entityId,
+ item.property,
+ apiValuesToSoupPropertyValue(item.apiValues)
+ )
+ )
+ ),
+ };
},
onError(
error: Error,
- _vars: BulkSaveEntityPropertiesParams,
+ _variables: BulkSaveEntityPropertiesParams,
context: BulkSaveEntityPropertiesContext | undefined
) {
- // Reverse order: later transactions snapshotted state that already
- // included earlier updates, so they must unwind first.
- if (context?.soupTxns.length) {
- batch(() => {
- for (let i = context.soupTxns.length - 1; i >= 0; i--) {
- context.soupTxns[i].rollback();
- }
- });
- }
- console.error('Failed to bulk save properties', error);
- toast.failure('Failed to save properties');
+ if (context?.usesGraphqlSoup) return;
+ rollbackBulkSoupTransactions(context);
+ reportBulkPropertySaveFailure(error);
},
- onSettled: (_data, error, variables) => {
- if (error) {
- console.error('Failed bulk save properties', variables, error);
- toast.failure('Failed to save properties');
- }
+ onSettled: (_data, _error, variables, context) => {
+ if (context?.usesGraphqlSoup) return;
batch(() => {
for (const p of variables.properties) {
invalidatePropertiesForEntity(p.entityType, p.entityId);
invalidateSoupEntity(p.entityId);
}
});
- if (!error) {
- for (const p of variables.properties) {
- trackTaskPropertySave(
- p.entityId,
- getPropertyDefinitionId(p.property),
- p.apiValues
- );
- }
- }
},
},
callbacks
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts
index d73cbffa17..3ff658b9a3 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts
@@ -30,7 +30,11 @@ const restSetEntityProperty = vi.mocked(
);
const flag = vi.mocked(ENABLE_GRAPHQL_SOUP);
-type MutationResult = { data?: unknown; error?: unknown };
+type MutationResult = {
+ data?: unknown;
+ error?: unknown;
+ extensions?: Record<string, unknown>;
+};
function mockGraphqlClient(result: MutationResult) {
const mutation = vi.fn(() => ({
@@ -129,7 +133,9 @@ describe('setEntityProperty', () => {
restSetEntityProperty.mockResolvedValue(okRestResult);
const mutation = mockGraphqlClient({ data: undefined });
- await setEntityProperty(args);
+ await expect(setEntityProperty(args)).resolves.toEqual({
+ kind: 'committed',
+ });
expect(restSetEntityProperty).toHaveBeenCalledWith({
entity_type: 'DOCUMENT',
@@ -140,13 +146,18 @@ describe('setEntityProperty', () => {
expect(mutation).not.toHaveBeenCalled();
});
- it('propagates REST errors as throws', async () => {
+ it('returns permanently-failed for REST errors', async () => {
restSetEntityProperty.mockResolvedValue({
isErr: () => true,
error: [{ code: 'boom', message: 'boom' }],
} as never);
- await expect(setEntityProperty(args)).rejects.toThrow();
+ const result = await setEntityProperty(args);
+
+ expect(result.kind).toBe('permanently-failed');
+ if (result.kind === 'permanently-failed') {
+ expect(result.error).toBeInstanceOf(Error);
+ }
});
it('executes the GraphQL mutation when the flag is enabled', async () => {
@@ -154,6 +165,9 @@ describe('setEntityProperty', () => {
const property = { id: 'prop-1' } as SoupPropertyFieldsFragment;
const mutation = mockGraphqlClient({
data: { setEntityProperty: property },
+ extensions: {
+ normalizedCacheMutationDisposition: { kind: 'committed' },
+ },
});
const result = await setEntityProperty(args);
@@ -174,7 +188,7 @@ describe('setEntityProperty', () => {
},
});
expect(context).toBeUndefined();
- expect(result).toBe(property);
+ expect(result).toEqual({ kind: 'committed', property });
});
it('attaches the optimistic response to the mutation context', async () => {
@@ -200,10 +214,52 @@ describe('setEntityProperty', () => {
});
});
- it('throws on GraphQL errors', async () => {
+ it('returns queued when the durable exchange retains the mutation', async () => {
flag.mockReturnValue(true);
- mockGraphqlClient({ error: new Error('mutation failed') });
+ const optimistic = { id: 'prop-1' } as SoupPropertyFieldsFragment;
+ mockGraphqlClient({
+ data: { setEntityProperty: optimistic },
+ error: new Error('offline'),
+ extensions: {
+ normalizedCacheMutationDisposition: {
+ kind: 'queued',
+ transactionId: 'txn-1',
+ },
+ },
+ });
+
+ await expect(
+ setEntityProperty({ ...args, optimisticProperty: optimistic })
+ ).resolves.toEqual({ kind: 'queued', transactionId: 'txn-1' });
+ });
- await expect(setEntityProperty(args)).rejects.toThrow('mutation failed');
+ it('returns permanently-failed after the durable exchange rolls back', async () => {
+ flag.mockReturnValue(true);
+ const error = new Error('mutation failed');
+ mockGraphqlClient({
+ error,
+ extensions: {
+ normalizedCacheMutationDisposition: {
+ kind: 'permanently-failed',
+ transactionId: 'txn-1',
+ },
+ },
+ });
+
+ await expect(setEntityProperty(args)).resolves.toEqual({
+ kind: 'permanently-failed',
+ error,
+ });
+ });
+
+ it('returns permanently-failed for non-durable GraphQL errors', async () => {
+ flag.mockReturnValue(true);
+ const error = new Error('mutation failed');
+ mockGraphqlClient({ error });
+
+ await expect(setEntityProperty(args)).resolves.toEqual({
+ kind: 'permanently-failed',
+ error,
+ });
});
});
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts
index 087bfcedbf..ee46f84e09 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts
@@ -15,6 +15,7 @@ import { throwOnErr } from '@core/util/result';
import {
executeOptimisticMutation,
type OptimisticMutationOptions,
+ optimisticMutationDispositionOf,
} from '@graphql-cache/index';
import { match } from 'ts-pattern';
import { propertiesServiceClient } from '../service-properties/client';
@@ -163,25 +164,35 @@ export type SetEntityPropertyArgs = {
optimisticCache?: OptimisticMutationOptions;
};
-/**
- * Sets or attaches one property on an entity. Rejects on transport or
- * GraphQL errors, matching the REST path's throw-on-error behavior
- * expected by the TanStack mutation hooks.
- */
+/** Outcome of submitting one property mutation to its configured transport. */
+export type SetEntityPropertyDisposition =
+ | { kind: 'committed'; property?: SoupPropertyFieldsFragment }
+ | { kind: 'queued'; transactionId: string }
+ | { kind: 'permanently-failed'; error: Error };
+
+function asError(error: unknown): Error {
+ return error instanceof Error ? error : new Error(String(error));
+}
+
+/** Sets or durably queues one property assignment. */
export async function setEntityProperty(
args: SetEntityPropertyArgs
-): Promise<SoupPropertyFieldsFragment | void> {
+): Promise<SetEntityPropertyDisposition> {
if (!ENABLE_GRAPHQL_SOUP()) {
- await throwOnErr(
- async () =>
- await propertiesServiceClient.setEntityProperty({
- entity_type: args.entityType,
- entity_id: args.entityId,
- property_id: args.propertyDefinitionId,
- body: { value: args.value },
- })
- );
- return;
+ try {
+ await throwOnErr(
+ async () =>
+ await propertiesServiceClient.setEntityProperty({
+ entity_type: args.entityType,
+ entity_id: args.entityId,
+ property_id: args.propertyDefinitionId,
+ body: { value: args.value },
+ })
+ );
+ return { kind: 'committed' };
+ } catch (error) {
+ return { kind: 'permanently-failed', error: asError(error) };
+ }
}
const client = getGraphqlSoupClient();
@@ -204,8 +215,24 @@ export async function setEntityProperty(
args.optimisticCache
).toPromise()
: await client.mutation(SetEntityPropertyDocument, variables).toPromise();
+ const disposition = optimisticMutationDispositionOf(result);
+ if (disposition?.kind === 'queued') return disposition;
+ if (disposition?.kind === 'permanently-failed') return disposition;
+ if (disposition?.kind === 'committed') {
+ return {
+ kind: 'committed',
+ property: disposition.data.setEntityProperty,
+ };
+ }
+
if (result.error) {
- throw result.error;
+ return { kind: 'permanently-failed', error: result.error };
+ }
+ if (!result.data) {
+ return {
+ kind: 'permanently-failed',
+ error: new Error('setEntityProperty mutation returned no data'),
+ };
}
- return result.data?.setEntityProperty;
+ return { kind: 'committed', property: result.data.setEntityProperty };
}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index b3207f7ee9..a307a4bf63 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -12,7 +12,9 @@
use crate::engine::{
ClaimedMutationWire, EngineHandle, OptimisticWriteResultWire, ReadResultWire, WriteResultWire,
};
-use crate::{CacheState, InitializedCache, emit_cache_changed, emit_ops_affected};
+use crate::{
+ CacheState, InitializedCache, emit_cache_changed, emit_mutation_settled, emit_ops_affected,
+};
use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
use cache_core::query_inspection::CachedQueryInstance;
use cache_core::record_selection::{RecordCursor, SelectedRecordPage};
@@ -236,6 +238,7 @@ pub async fn graphql_cache_commit_optimistic_write<R: Runtime>(
variables: Option<Variables>,
data: serde_json::Value,
) -> Result<WriteResultWire, String> {
+ let settlement_transaction_id = transaction_id.clone();
let result = engine_handle(&state)?
.commit_optimistic_write(
transaction_id,
@@ -249,6 +252,7 @@ pub async fn graphql_cache_commit_optimistic_write<R: Runtime>(
.await?;
emit_ops_affected(&app, &result.affected_ops, &result.changed);
emit_cache_changed(&app);
+ emit_mutation_settled(&app, settlement_transaction_id, "committed", None);
Ok(result)
}
@@ -260,12 +264,20 @@ pub async fn graphql_cache_rollback_optimistic_write<R: Runtime>(
transaction_id: String,
lease_owner: String,
lease_generation: String,
+ error: String,
) -> Result<WriteResultWire, String> {
+ let settlement_transaction_id = transaction_id.clone();
let result = engine_handle(&state)?
.rollback_optimistic_write(transaction_id, lease_owner, lease_generation)
.await?;
emit_ops_affected(&app, &result.affected_ops, &result.changed);
emit_cache_changed(&app);
+ emit_mutation_settled(
+ &app,
+ settlement_transaction_id,
+ "permanently-failed",
+ Some(error),
+ );
Ok(result)
}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/lib.rs b/apps/web/tauri/graphql_cache_plugin/src/lib.rs
index dbc23d0b17..36aff9f68c 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/lib.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/lib.rs
@@ -7,9 +7,9 @@
//! instance across all webviews/windows, never webview storage.
//! Webviews talk to it through the commands in [`commands`] (registered
//! app-level in `src-tauri`, like the bundle updater plugin) and receive
-//! operation and cache change notifications via broadcast events.
-//! These mirror worker pushes; each webview's `CacheHost` filters operation
-//! ids by its own client prefix.
+//! operation, cache-change, and queued-mutation settlement notifications via
+//! broadcast events. These mirror browser worker pushes; each webview's
+//! `CacheHost` filters operation ids by its own client prefix.
//!
//! Design doc: `apps/web/docs/graphql-normalized-cache-plan.md`.
@@ -35,6 +35,9 @@ pub const OPS_AFFECTED_EVENT: &str = "graphql-cache://ops-affected";
/// Broadcast event emitted whenever the effective cache view changes.
pub const CACHE_CHANGED_EVENT: &str = "graphql-cache://cache-changed";
+/// Broadcast event carrying the final outcome of a queued mutation.
+pub const MUTATION_SETTLED_EVENT: &str = "graphql-cache://mutation-settled";
+
/// Payload of [`OPS_AFFECTED_EVENT`] — mirrors the worker `CachePush`
/// message in `apps/web/src/lib/graphql-cache/protocol.ts`.
#[derive(Clone, Debug, Serialize)]
@@ -51,6 +54,15 @@ pub struct OpsAffectedEvent {
#[serde(rename_all = "camelCase")]
pub struct CacheChangedEvent {}
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct MutationSettledEvent {
+ transaction_id: String,
+ status: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ error: Option<String>,
+}
+
struct InitializedCache {
scope: String,
handle: EngineHandle,
@@ -81,3 +93,21 @@ fn emit_cache_changed<R: Runtime>(app: &AppHandle<R>) {
.inspect_err(|e| tracing::error!(error=?e, "failed to emit graphql cache change event"))
.ok();
}
+
+fn emit_mutation_settled<R: Runtime>(
+ app: &AppHandle<R>,
+ transaction_id: String,
+ status: &'static str,
+ error: Option<String>,
+) {
+ app.emit(
+ MUTATION_SETTLED_EVENT,
+ MutationSettledEvent {
+ transaction_id,
+ status,
+ error,
+ },
+ )
+ .inspect_err(|e| tracing::error!(error=?e, "failed to emit graphql mutation settlement"))
+ .ok();
+}