authoravatarclover caruso<git@paperclover.net>2026-11-11 09:56:11-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-11 11:13:55-08:00
logfe2445675b26022550a41a0f80dc6f3cc32b1aef
tree6854f9a104b3e05c17be9ae57b7eab9168eba760
parentcf0988729b9a3695215b40bc5090ed5cebde810e
signature Signed by SSH key SHA256:cOKiuRFOeSRxne6EWgHtdQQSlBxjOXm2hOCFnCdLQbQ

fix: attribute helper restores and refetches to their call

Optimistic helpers were created once per channel and registered their restores straight onto the channel's rollback list, uncounted. A call retired its rollbacks by splicing its count from the front of that list, so a succeeded call left its helper restores behind (or retired another call's entry in their place), and a later failure on the same key replayed them, putting back the value from before the confirmed write. The throw, no-op snapshot and debounced paths spliced by count from the end with the same blind spot. Refetches were shared the same way. The shared helpers' refetch dedupe was never cleared, so while a listener kept the channel alive only the first call refetched a query, and a settling call ran every queued call's refetches before their writes landed, leaving the cache stale after the later write succeeded. Each call now creates its own helpers and owns its restores and refetches. Success drops them with the call; failure runs the restores of the failed, queued and pending debounced calls newest first, then the refetches of the failed and cancelled calls; a throw, a no-op snapshot and a superseded debounced call run only their own restores. The public API is unchanged. Assisted-by: claude-opus-5.5

4 files changed, 323 insertions(+), 108 deletions(-)

jsr.json+1-1
......@@ -1,6 +1,6 @@
11{
22 "name": "@clo/react-mutation",
3 "version": "3.0.3",
3 "version": "3.0.4",
44 "exports": {
55 ".": "./src/mod.ts",
66 "./tanstack-query": "./src/tanstack-query.ts",
readme.changes.md+16
......@@ -1,5 +1,21 @@
11# notable changes in React Mutation
22
3## v3.0.4
4
5### bugfixes
6
7- resolve a failed call replaying the optimistic helper restores of an earlier
8 call on the same key that had succeeded, putting back the value from before
9 the confirmed write
10- resolve a successful call that also used optimistic helpers retiring another
11 call's `onRestore` callbacks instead of its own
12- resolve helper updates not being rolled back when `optimistic` throws, when
13 `snapshot` skips a no-op call, or when a debounced call is superseded
14- resolve helpers refetching a query only for the first call on a key while a
15 `useMutate` stays subscribed to it
16- resolve a queued call's refetches running when the call ahead of it settled,
17 before its own write, which left the cache stale after both succeeded
18
319## v3.0.3
420
521### bugfixes
src/mutation.ts+73-105
......@@ -124,8 +124,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> {
124124 args: Args;
125125 /** Context captured when the most recent call was allowed */
126126 context: Context;
127 /** Number of rollbacks the most recent call added */
128 rollbackCount: number;
127 /** Restores registered by the most recent call */
128 rollbacks: Array<() => void>;
129129 /** All pending promises from all superseded calls */
130130 pending: Array<{
131131 resolve: (result: Result) => void;
......@@ -133,6 +133,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> {
133133 }>;
134134 /** Success callbacks from the most recent call */
135135 onSuccess: Array<(result: Result) => void>;
136 /** Refetch callbacks from the most recent call */
137 refetches: Array<() => Promise<void>>;
136138 /** Initial snapshot before any debounced calls (for no-op detection) */
137139 initialSnapshot?: unknown;
138140 /** Whether the last call wanted global handlers to be called */
......@@ -157,14 +159,10 @@ function unwrapMutationError(caught: unknown) {
157159 return { error: caught, description: null };
158160}
159161
160interface Channel<Args extends unknown[], Result, OptimisticHelpers, Context> {
162interface Channel<Args extends unknown[], Result, Context> {
161163 listeners: Set<(update: MutationEvent<Result>) => void>;
162164 status: "idle" | "waiting" | "mutating" | "refetching" | "skipped";
163 rollbacks: Array<() => void>;
164 refetches: Array<() => Promise<void>>;
165165 queue: Array<Item<Args, Result, Context>>;
166 // Shared optimistic helpers instance for the channel
167 helpers: OptimisticHelpers | null;
168166 // Debounce state (only used if debounce option is set)
169167 debounceTimer: ReturnType<typeof setTimeout> | null;
170168 pendingDebounced: PendingDebouncedState<Args, Result, Context> | null;
......@@ -175,7 +173,8 @@ interface Channel<Args extends unknown[], Result, OptimisticHelpers, Context> {
175173interface Item<Args extends unknown[], Result, Context> {
176174 args: Args;
177175 context: Context;
178 rollbacks: number;
176 rollbacks: Array<() => void>;
177 refetches: Array<() => Promise<void>>;
179178 onSuccess: Array<(result: Result) => void>;
180179 resolve: (result: Result) => void;
181180 reject: (error: unknown) => void;
......@@ -191,7 +190,7 @@ export class BlockingMutation<
191190 #client: MutationClientFromConfig<Config>;
192191 #channels: Map<
193192 string,
194 Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>
193 Channel<Args, Result, Context<Config, Auth>>
195194 > = new Map();
196195 client: MutationClientFromConfig<Config>;
197196
......@@ -255,14 +254,10 @@ export class BlockingMutation<
255254 #getOrPutChannel(key: string) {
256255 let channel = this.#channels.get(key);
257256 if (!channel) {
258 const rollbacks: Array<() => []> = [];
259257 channel = {
260258 listeners: new Set(),
261259 status: "idle",
262 rollbacks,
263 refetches: [],
264260 queue: [],
265 helpers: null,
266261 debounceTimer: null,
267262 pendingDebounced: null,
268263 lastDebouncedExecutionTime: null,
......@@ -282,7 +277,7 @@ export class BlockingMutation<
282277 }
283278
284279 #notify(
285 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,
280 channel: Channel<Args, Result, Context<Config, Auth>>,
286281 status: MutationEvent<Result>["status"],
287282 result: Result | null = null,
288283 error: unknown = null,
......@@ -293,7 +288,7 @@ export class BlockingMutation<
293288
294289 #setIdle(
295290 key: string,
296 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,
291 channel: Channel<Args, Result, Context<Config, Auth>>,
297292 ) {
298293 // Check if there are pending debounced calls waiting
299294 if (channel.pendingDebounced !== null) {
......@@ -303,8 +298,6 @@ export class BlockingMutation<
303298 } else {
304299 // Normal idle transition
305300 channel.status = "idle";
306 // Discard any unconsumed refetch callbacks
307 channel.refetches = [];
308301 this.#notify(channel, "idle", null, null);
309302 // Clean up the channel if there are no listeners
310303 if (channel.listeners.size === 0) {
......@@ -477,44 +470,39 @@ export class BlockingMutation<
477470 ? this.#options.snapshot.call(context, { ...context, args })
478471 : undefined;
479472
480 // Create shared optimistic helpers instance for the channel if it doesn't exist
481 if (channel.helpers === null) {
482 const onRefetch = (cb: () => Promise<void>) => {
483 channel.refetches.push(cb);
484 };
485
486 channel.helpers = this.#client.getOptimisticHelpers({
487 onRestore: (cb: () => void) => {
488 channel.rollbacks.push(cb);
489 },
490 onRefetch,
491 });
492 }
493
494473 const onSuccess: Array<(result: Result) => void> = [];
495474 let expired = false;
496 let rollbacks = 0;
475 const rollbacks: Array<() => void> = [];
476 const refetches: Array<() => Promise<void>> = [];
497477 const onRestore = (cb: () => void) => {
498478 if (expired) {
499479 throw new Error(
500480 "Can only call onRestore from within the optimistic update function.",
501481 );
502482 }
503 channel.rollbacks.push(cb);
504 rollbacks += 1;
483 rollbacks.push(cb);
505484 };
506485
507486 // Register user's onRestore callback if provided
508487 if (userOnRestore) {
509 channel.rollbacks.push(userOnRestore);
510 rollbacks += 1;
488 rollbacks.push(userOnRestore);
511489 }
512490
491 // Per call, so restores, refetches and refetch dedupe belong to this call
492 const helpers = this.#client.getOptimisticHelpers({
493 onRestore: (cb) => {
494 rollbacks.push(cb);
495 },
496 onRefetch: (cb) => {
497 refetches.push(cb);
498 },
499 });
500
513501 try {
514502 this.#options.optimistic({
515503 ...context,
516504 args,
517 helpers: channel.helpers,
505 helpers,
518506 onRestore,
519507 onSuccess(cb) {
520508 if (expired) {
......@@ -530,17 +518,13 @@ export class BlockingMutation<
530518 "Can only call onRefetch from within the optimistic update function.",
531519 );
532520 }
533 channel.refetches.push(cb);
521 refetches.push(cb);
534522 },
535523 });
536524 } catch (error) {
537525 expired = true;
538526 let next;
539 while (
540 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
541 ) {
542 next();
543 }
527 while (next = rollbacks.pop()) next();
544528 return Promise.reject(error);
545529 }
546530 expired = true;
......@@ -555,11 +539,7 @@ export class BlockingMutation<
555539
556540 if (isNoOp) {
557541 let next;
558 while (
559 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
560 ) {
561 next();
562 }
542 while (next = rollbacks.pop()) next();
563543
564544 // Notify listeners of skipped status
565545 this.#notify(channel, "skipped");
......@@ -573,6 +553,7 @@ export class BlockingMutation<
573553 args,
574554 context,
575555 rollbacks,
556 refetches,
576557 onSuccess,
577558 resolve,
578559 reject,
......@@ -587,7 +568,7 @@ export class BlockingMutation<
587568
588569 #executeNext(
589570 key: string,
590 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,
571 channel: Channel<Args, Result, Context<Config, Auth>>,
591572 ) {
592573 const item = channel.queue.shift();
593574 if (!item) {
......@@ -595,21 +576,19 @@ export class BlockingMutation<
595576 return;
596577 }
597578
598 const { args, context, onSuccess, resolve, reject } = item;
579 const { args, context, refetches, onSuccess, resolve, reject } = item;
599580 channel.status = "mutating";
600581 this.#notify(channel, "mutating");
601582
602583 new Promise<Result>((resolve) => resolve(this.#options.mutate.call(context, ...args))).then((result) => {
603 // remove rollbacks and apply optimistic success handlers
604 channel.rollbacks.splice(0, item.rollbacks);
584 // the call's rollbacks retire with it; apply optimistic success handlers
605585 onSuccess.forEach((cb) => cb(result));
606586
607587 if (this.#options.refetchOnSuccess !== false) {
608588 channel.status = "refetching";
609589 this.#notify(channel, "refetching", result);
610590 // Call refetch and all refetch callbacks in parallel
611 const refetchCallbacks = channel.refetches.splice(0);
612 Promise.allSettled(refetchCallbacks.map((cb) => cb())).then(
591 Promise.allSettled(refetches.map((cb) => cb())).then(
613592 (results) => {
614593 // Report any errors from refetch or callbacks
615594 results.forEach((result) => {
......@@ -623,8 +602,6 @@ export class BlockingMutation<
623602 this.#executeNext(key, channel);
624603 });
625604 } else {
626 // Discard refetch callbacks if refetchOnSuccess is false
627 channel.refetches = [];
628605 // Notify listeners with success status and result before moving to next
629606 this.#notify(channel, "mutating", result);
630607 this.#executeNext(key, channel);
......@@ -635,12 +612,14 @@ export class BlockingMutation<
635612 const description = this.describe(...args);
636613 const wrappedError = new MutationError(error, description);
637614
638 // if an error happens, then every rollback is called in reverse order
639 let next;
640 while (next = channel.rollbacks.pop()) next();
615 // if an error happens, then every pending call's rollbacks are called in reverse order
616 const remainingItems = channel.queue.splice(0);
617 for (const call of [item, ...remainingItems, channel.pendingDebounced].reverse()) {
618 let next;
619 while (next = call?.rollbacks.pop()) next();
620 }
641621
642622 // Cancel all remaining items in the channel
643 const remainingItems = channel.queue.splice(0);
644623 remainingItems.forEach((queuedItem) => {
645624 queuedItem.reject(wrappedError);
646625 });
......@@ -651,8 +630,8 @@ export class BlockingMutation<
651630 // Refetch to restore correct state
652631 channel.status = "refetching";
653632 this.#notify(channel, "refetching", null, error);
654 // Call refetch and all refetch callbacks in parallel
655 const refetchCallbacks = channel.refetches.splice(0);
633 // Refetch for the failed and cancelled calls in parallel
634 const refetchCallbacks = [item, ...remainingItems].flatMap((call) => call.refetches);
656635 Promise.allSettled(refetchCallbacks.map((cb) => cb())).then((results) => {
657636 // Report any errors from refetch or callbacks
658637 results.forEach((result) => {
......@@ -672,7 +651,7 @@ export class BlockingMutation<
672651 #runDebouncedAndReturn(
673652 args: Args,
674653 key: string,
675 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,
654 channel: Channel<Args, Result, Context<Config, Auth>>,
676655 context: Context<Config, Auth>,
677656 userOnRestore: (() => void) | undefined,
678657 shouldExecuteImmediate: boolean,
......@@ -693,44 +672,40 @@ export class BlockingMutation<
693672 this.#rollbackPendingDebounced(channel);
694673 }
695674
696 // Create shared helpers if needed (same as current implementation)
697 if (channel.helpers === null) {
698 const onRefetch = (cb: () => Promise<void>) => {
699 channel.refetches.push(cb);
700 };
701 channel.helpers = this.#client.getOptimisticHelpers({
702 onRestore: (cb: () => void) => {
703 channel.rollbacks.push(cb);
704 },
705 onRefetch,
706 });
707 }
708
709675 // Apply optimistic update (same logic as current runAndReturn)
710676 const onSuccess: Array<(result: Result) => void> = [];
711677 let expired = false;
712 let rollbacks = 0;
678 const rollbacks: Array<() => void> = [];
679 const refetches: Array<() => Promise<void>> = [];
713680 const onRestore = (cb: () => void) => {
714681 if (expired) {
715682 throw new Error(
716683 "Can only call onRestore from within the optimistic update function.",
717684 );
718685 }
719 channel.rollbacks.push(cb);
720 rollbacks += 1;
686 rollbacks.push(cb);
721687 };
722688
723689 // Register user's onRestore callback if provided
724690 if (userOnRestore) {
725 channel.rollbacks.push(userOnRestore);
726 rollbacks += 1;
691 rollbacks.push(userOnRestore);
727692 }
728693
694 // Per call, so restores, refetches and refetch dedupe belong to this call
695 const helpers = this.#client.getOptimisticHelpers({
696 onRestore: (cb) => {
697 rollbacks.push(cb);
698 },
699 onRefetch: (cb) => {
700 refetches.push(cb);
701 },
702 });
703
729704 try {
730705 this.#options.optimistic({
731706 ...context,
732707 args,
733 helpers: channel.helpers,
708 helpers,
734709 onRestore,
735710 onSuccess(cb) {
736711 if (expired) {
......@@ -746,18 +721,14 @@ export class BlockingMutation<
746721 "Can only call onRefetch from within the optimistic update function.",
747722 );
748723 }
749 channel.refetches.push(cb);
724 refetches.push(cb);
750725 },
751726 });
752727 } catch (error) {
753728 expired = true;
754729 // Roll back the rollbacks we just added
755730 let next;
756 while (
757 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
758 ) {
759 next();
760 }
731 while (next = rollbacks.pop()) next();
761732 return Promise.reject(error);
762733 }
763734 expired = true;
......@@ -778,11 +749,7 @@ export class BlockingMutation<
778749 ) {
779750 // No-op detected - rollback optimistic update
780751 let next;
781 while (
782 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
783 ) {
784 next();
785 }
752 while (next = rollbacks.pop()) next();
786753
787754 // Clear debounce timer
788755 if (channel.debounceTimer !== null) {
......@@ -810,9 +777,10 @@ export class BlockingMutation<
810777 channel.pendingDebounced = {
811778 args,
812779 context,
813 rollbackCount: rollbacks,
780 rollbacks,
814781 pending: [{ resolve, reject }],
815782 onSuccess,
783 refetches,
816784 initialSnapshot: isFirstDebouncedCall ? initialSnapshot : undefined,
817785 shouldCallGlobalHandler,
818786 };
......@@ -826,9 +794,10 @@ export class BlockingMutation<
826794 // Subsequent debounced call - update state
827795 channel.pendingDebounced.args = args;
828796 channel.pendingDebounced.context = context;
829 channel.pendingDebounced.rollbackCount = rollbacks;
797 channel.pendingDebounced.rollbacks = rollbacks;
830798 channel.pendingDebounced.pending.push({ resolve, reject });
831799 channel.pendingDebounced.onSuccess = onSuccess;
800 channel.pendingDebounced.refetches = refetches;
832801 channel.pendingDebounced.shouldCallGlobalHandler = shouldCallGlobalHandler;
833802 // Keep the initial snapshot from the first call
834803 // Status stays "waiting"
......@@ -849,18 +818,15 @@ export class BlockingMutation<
849818 }
850819
851820 #rollbackPendingDebounced(
852 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,
821 channel: Channel<Args, Result, Context<Config, Auth>>,
853822 ) {
854823 if (!channel.pendingDebounced) return;
855824
856 const { rollbackCount } = channel.pendingDebounced;
825 const { rollbacks } = channel.pendingDebounced;
857826
858827 // Roll back this call's optimistic updates (in reverse order)
859 // Remove from the end of the rollbacks array
860 for (let i = 0; i < rollbackCount; i++) {
861 const rollback = channel.rollbacks.pop();
862 if (rollback) rollback();
863 }
828 let next;
829 while (next = rollbacks.pop()) next();
864830
865831 // Note: We do NOT reject the promises here
866832 // They will all resolve when the final call completes
......@@ -868,7 +834,7 @@ export class BlockingMutation<
868834
869835 #enqueueDebouncedCall(
870836 key: string,
871 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,
837 channel: Channel<Args, Result, Context<Config, Auth>>,
872838 ) {
873839 // Clear timer
874840 channel.debounceTimer = null;
......@@ -879,7 +845,8 @@ export class BlockingMutation<
879845 return;
880846 }
881847
882 const { args, context, rollbackCount, pending, onSuccess, shouldCallGlobalHandler } = channel.pendingDebounced;
848 const { args, context, rollbacks, pending, onSuccess, refetches, shouldCallGlobalHandler } =
849 channel.pendingDebounced;
883850 channel.pendingDebounced = null;
884851
885852 // Track execution time for debounceImmediate
......@@ -928,7 +895,8 @@ export class BlockingMutation<
928895 channel.queue.push({
929896 args,
930897 context,
931 rollbacks: rollbackCount,
898 rollbacks,
899 refetches,
932900 onSuccess,
933901 resolve: wrapperResolve,
934902 reject: wrapperReject,
test/tanstack-query-helpers.test.ts+233-2
......@@ -1,6 +1,8 @@
1import { delay } from "@clo/lib/async.ts";
12import { assertEquals } from "@std/assert";
2import { QueryClient, queryOptions } from "@tanstack/react-query";
3import { test } from "vitest";
3import { QueryClient, QueryObserver, queryOptions } from "@tanstack/react-query";
4import { test, vi } from "vitest";
5import { MutationClient } from "../src/client.ts";
46import { queryClientOptimisticHelpers, reactiveFromQueryCache } from "../src/tanstack-query.ts";
57
68interface TestData {
......@@ -1114,3 +1116,232 @@ test("integration - multiple operations work together", () => {
11141116 assertEquals(restored?.active, true);
11151117 assertEquals(restored?.items.length, 3);
11161118});
1119
1120// ============================================================================
1121// Mutation integration: each call owns the restores and refetches its helpers register
1122// ============================================================================
1123
1124function createToggleClient() {
1125 const queryClient = new QueryClient({
1126 defaultOptions: { queries: { retry: false } },
1127 });
1128 const server = { enabled: true, online: true, fetches: 0 };
1129
1130 const queryToggle = queryOptions({
1131 queryKey: ["toggle"],
1132 queryFn: async () => {
1133 server.fetches += 1;
1134 if (!server.online) throw new Error("offline");
1135 return { enabled: server.enabled };
1136 },
1137 });
1138 queryClient.setQueryData(queryToggle.queryKey, { enabled: true });
1139 // Observed, so invalidation refetches it; the refetch fails while offline.
1140 new QueryObserver(queryClient, queryToggle).subscribe(() => {});
1141
1142 const mutations = new MutationClient({
1143 context: {},
1144 getOptimisticHelpers: queryClientOptimisticHelpers(queryClient),
1145 reportError: () => {},
1146 });
1147
1148 const save = async (enabled: boolean) => {
1149 await delay(10);
1150 if (!server.online) throw new Error("offline");
1151 server.enabled = enabled;
1152 return enabled;
1153 };
1154 const read = () => queryClient.getQueryData(queryToggle.queryKey)?.enabled;
1155
1156 return { queryClient, queryToggle, server, mutations, save, read };
1157}
1158
1159test("a failure does not replay the helper restores of a call that succeeded", async () => {
1160 vi.useFakeTimers();
1161 const { queryToggle, server, mutations, save, read } = createToggleClient();
1162 const mutToggle = mutations.define({
1163 id: "toggle",
1164 mutate: save,
1165 optimistic: ({ helpers, args: [enabled] }) => {
1166 helpers.updateExisting(queryToggle, { enabled });
1167 },
1168 describe: "toggle",
1169 describeResult: null,
1170 });
1171 // `useMutate` keeps the channel alive between calls
1172 mutToggle.subscribe(mutToggle.key([true]), () => {});
1173
1174 mutToggle.run(false);
1175 await vi.advanceTimersByTimeAsync(100);
1176 assertEquals([server.enabled, read()], [false, false]);
1177
1178 server.online = false;
1179 mutToggle.run(true);
1180 assertEquals(read(), true);
1181 await vi.advanceTimersByTimeAsync(100);
1182 assertEquals(read(), false);
1183});
1184
1185test("a queued failure does not replay the helper restores of the call ahead of it", async () => {
1186 vi.useFakeTimers();
1187 const { queryToggle, server, mutations, save, read } = createToggleClient();
1188 const mutToggle = mutations.define({
1189 id: "toggle",
1190 mutate: save,
1191 optimistic: ({ helpers, args: [enabled] }) => {
1192 helpers.updateExisting(queryToggle, { enabled });
1193 },
1194 describe: "toggle",
1195 describeResult: null,
1196 });
1197
1198 mutToggle.run(false);
1199 mutToggle.run(true);
1200 await vi.advanceTimersByTimeAsync(10);
1201 assertEquals(server.enabled, false);
1202
1203 server.online = false;
1204 await vi.advanceTimersByTimeAsync(100);
1205 assertEquals(read(), false);
1206});
1207
1208test("a success retires its own onRestore callbacks, not the channel's oldest restores", async () => {
1209 vi.useFakeTimers();
1210 const { queryToggle, server, mutations, save, read } = createToggleClient();
1211 let lastChoice: boolean | null = null;
1212 const mutToggle = mutations.define({
1213 id: "toggle",
1214 mutate: save,
1215 optimistic: ({ helpers, args: [enabled], onRestore }) => {
1216 helpers.updateExisting(queryToggle, { enabled });
1217 const prev = lastChoice;
1218 lastChoice = enabled;
1219 onRestore(() => {
1220 lastChoice = prev;
1221 });
1222 },
1223 describe: "toggle",
1224 describeResult: null,
1225 });
1226 mutToggle.subscribe(mutToggle.key([true]), () => {});
1227
1228 mutToggle.run(false);
1229 await vi.advanceTimersByTimeAsync(100);
1230
1231 server.online = false;
1232 mutToggle.run(true);
1233 await vi.advanceTimersByTimeAsync(100);
1234 assertEquals([lastChoice, read()], [false, false]);
1235});
1236
1237test("an optimistic update that throws restores its helper updates", () => {
1238 const { queryToggle, mutations, save, read } = createToggleClient();
1239 const mutToggle = mutations.define({
1240 id: "toggle",
1241 mutate: save,
1242 optimistic: ({ helpers, args: [enabled] }) => {
1243 helpers.updateExisting(queryToggle, { enabled });
1244 throw new Error("optimistic update failed");
1245 },
1246 describe: "toggle",
1247 describeResult: null,
1248 });
1249
1250 mutToggle.run(false);
1251 assertEquals(read(), true);
1252});
1253
1254test("a skipped no-op call's helper restores are not replayed by a later failure", async () => {
1255 vi.useFakeTimers();
1256 const { queryClient, queryToggle, server, mutations, save, read } = createToggleClient();
1257 const mutToggle = mutations.define({
1258 id: "toggle",
1259 mutate: save,
1260 optimistic: ({ helpers, args: [enabled] }) => {
1261 helpers.updateExisting(queryToggle, { enabled });
1262 },
1263 snapshot: () => read(),
1264 describe: "toggle",
1265 describeResult: null,
1266 });
1267
1268 mutToggle.run(true);
1269 // Another client turns it off.
1270 server.enabled = false;
1271 queryClient.setQueryData(queryToggle.queryKey, { enabled: false });
1272
1273 server.online = false;
1274 mutToggle.run(true);
1275 await vi.advanceTimersByTimeAsync(100);
1276 assertEquals(read(), false);
1277});
1278
1279test("a debounced success retires the helper restores of every call it covers", async () => {
1280 vi.useFakeTimers();
1281 const { queryToggle, server, mutations, save, read } = createToggleClient();
1282 const mutToggle = mutations.define({
1283 id: "toggle",
1284 mutate: save,
1285 optimistic: ({ helpers, args: [enabled] }) => {
1286 helpers.updateExisting(queryToggle, { enabled });
1287 },
1288 describe: "toggle",
1289 describeResult: null,
1290 debounceMs: 50,
1291 });
1292 mutToggle.subscribe(mutToggle.key([true]), () => {});
1293
1294 mutToggle.run(false);
1295 mutToggle.run(false);
1296 await vi.advanceTimersByTimeAsync(200);
1297 assertEquals([server.enabled, read()], [false, false]);
1298
1299 server.online = false;
1300 mutToggle.run(true);
1301 await vi.advanceTimersByTimeAsync(200);
1302 assertEquals(read(), false);
1303});
1304
1305test("every call refetches the queries its helpers touched", async () => {
1306 vi.useFakeTimers();
1307 const { queryToggle, server, mutations, save } = createToggleClient();
1308 const mutToggle = mutations.define({
1309 id: "toggle",
1310 mutate: save,
1311 optimistic: ({ helpers, args: [enabled] }) => {
1312 helpers.updateExisting(queryToggle, { enabled });
1313 },
1314 describe: "toggle",
1315 describeResult: null,
1316 });
1317 mutToggle.subscribe(mutToggle.key([true]), () => {});
1318 await vi.advanceTimersByTimeAsync(0);
1319 const fetchesBefore = server.fetches;
1320
1321 mutToggle.run(false);
1322 await vi.advanceTimersByTimeAsync(100);
1323 assertEquals(server.fetches, fetchesBefore + 1);
1324
1325 mutToggle.run(true);
1326 await vi.advanceTimersByTimeAsync(100);
1327 assertEquals(server.fetches, fetchesBefore + 2);
1328});
1329
1330test("a queued call refetches after its own write, not with the call ahead of it", async () => {
1331 vi.useFakeTimers();
1332 const { queryToggle, server, mutations, save, read } = createToggleClient();
1333 const mutToggle = mutations.define({
1334 id: "toggle",
1335 mutate: save,
1336 optimistic: ({ helpers, args: [enabled] }) => {
1337 helpers.updateExisting(queryToggle, { enabled });
1338 },
1339 describe: "toggle",
1340 describeResult: null,
1341 });
1342
1343 mutToggle.run(false);
1344 mutToggle.run(true);
1345 await vi.advanceTimersByTimeAsync(100);
1346 assertEquals([server.enabled, read()], [true, true]);
1347});