@snowcone-app/ui 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowcone-app/ui",
3
- "version": "0.9.6",
3
+ "version": "0.9.8",
4
4
  "description": "React components for merchandise visualization and customization",
5
5
  "keywords": [
6
6
  "react",
@@ -103,7 +103,7 @@
103
103
  "react-instantsearch": "^7.15.5",
104
104
  "react-zoom-pan-pinch": "^3.6.4",
105
105
  "tailwind-merge": "^3.0.0",
106
- "@snowcone-app/sdk": "0.25.0"
106
+ "@snowcone-app/sdk": "0.26.0"
107
107
  },
108
108
  "devDependencies": {
109
109
  "@chromatic-com/storybook": "^4.1.2",
@@ -555,6 +555,28 @@ export const HeroProductImage = memo(function HeroProductImage({
555
555
  // picture stuck on `stale` is the "editor updates, pictures don't" defect
556
556
  // (snowcone.app phone case, 2026-11-11). Absent until the first edit.
557
557
  const renderVersionRef = useRef(0);
558
+ // What arrived vs what is on screen: url -> the version it was rendered from; the url the <img> has loaded.
559
+ const arrivedVersionRef = useRef(0);
560
+ const versionByUrlRef = useRef<Map<string, { v: number; versions: Record<string, number> | null }>>(new Map());
561
+ const loadedUrlRef = useRef<string | null>(null);
562
+ // This element's identity for frame release (a picture can have several elements showing different frames).
563
+ const blobConsumerRef = useRef(`el-${Math.random().toString(36).slice(2, 10)}`);
564
+ const releaseBlobConsumer = realtimeContext?.releaseBlobConsumer;
565
+ useEffect(() => {
566
+ const id = actualMockupId;
567
+ const consumer = blobConsumerRef.current;
568
+ return () => {
569
+ if (id) releaseBlobConsumer?.(id, consumer);
570
+ };
571
+ }, [actualMockupId, releaseBlobConsumer]);
572
+ const frameErrorRef = useRef<string | null>(null);
573
+ const showVersionOf = useCallback((url: string) => {
574
+ const e = versionByUrlRef.current.get(url);
575
+ if (!e || e.v < renderVersionRef.current) return;
576
+ renderVersionRef.current = e.v;
577
+ renderVersionsRef.current = e.versions;
578
+ frameErrorRef.current = null;
579
+ }, []);
558
580
  // Per-placement versions of the shown frame (servers that stamp them).
559
581
  const renderVersionsRef = useRef<Record<string, number> | null>(null);
560
582
  const getLatestSentVersions = realtimeContext?.getLatestSentVersions;
@@ -584,10 +606,15 @@ export const HeroProductImage = memo(function HeroProductImage({
584
606
  : rendered < canvas;
585
607
  node.dataset.canvasVersion = String(canvas);
586
608
  node.dataset.renderVersion = String(rendered);
609
+ node.dataset.arrivedVersion = String(arrivedVersionRef.current);
610
+ if (frameErrorRef.current) node.dataset.frameError = frameErrorRef.current;
611
+ else delete node.dataset.frameError;
587
612
  node.dataset.renderState = refusalCodeRef.current || (behind && sessionErrorCodeRef.current)
588
613
  ? "refused"
589
614
  : behind ? "stale" : "current";
590
615
  }, [getCanvasVersion, getLatestSentVersions]);
616
+ const applyRenderStampRef = useRef(applyRenderStamp);
617
+ applyRenderStampRef.current = applyRenderStamp;
591
618
  // Re-apply after every render (the root node can change; refusals are state).
592
619
  useEffect(() => {
593
620
  applyRenderStamp();
@@ -598,9 +625,15 @@ export const HeroProductImage = memo(function HeroProductImage({
598
625
  if (!actualMockupId || !subscribeSent || !subscribeResult) return;
599
626
  const offSent = subscribeSent(() => applyRenderStamp());
600
627
  const offResult = subscribeResult(actualMockupId, (result) => {
601
- if (typeof result?.requestVersion === "number" && result.requestVersion >= renderVersionRef.current) {
602
- renderVersionRef.current = result.requestVersion;
603
- renderVersionsRef.current = result.versions ?? null;
628
+ // A frame ARRIVED; data-render-version moves only when it is ON SCREEN (the <img> loaded it): a frame
629
+ // revoked or failed before it painted must never be stamped current (prod 2026-11-11).
630
+ if (typeof result?.requestVersion === "number") {
631
+ arrivedVersionRef.current = Math.max(arrivedVersionRef.current, result.requestVersion);
632
+ const url = realtimeContext?.getMockupUrl?.(result.mockupId) ?? result.imageUrl;
633
+ if (url) {
634
+ versionByUrlRef.current.set(url, { v: result.requestVersion, versions: result.versions ?? null });
635
+ if (url === loadedUrlRef.current) showVersionOf(url); // already on screen (an identical re-delivery)
636
+ }
604
637
  }
605
638
  applyRenderStamp();
606
639
  });
@@ -1043,8 +1076,14 @@ export const HeroProductImage = memo(function HeroProductImage({
1043
1076
  };
1044
1077
  if (preload.complete) startCrossfade();
1045
1078
  else preload.onload = startCrossfade;
1079
+ // The new frame could not load (e.g. its blob: URL was already revoked): keep the old image on screen, marked —
1080
+ // its data-render-version stays behind, so the picture reads stale, never current over an old image.
1081
+ preload.onerror = () => {
1082
+ frameErrorRef.current = "E_FRAME_UNAVAILABLE";
1083
+ applyRenderStampRef.current?.();
1084
+ };
1046
1085
 
1047
- return () => { preload.onload = null; };
1086
+ return () => { preload.onload = null; preload.onerror = null; };
1048
1087
  }, [displayUrl]);
1049
1088
 
1050
1089
  // Clean up old layer after crossfade completes
@@ -1145,6 +1184,12 @@ export const HeroProductImage = memo(function HeroProductImage({
1145
1184
  onLoad={() => {
1146
1185
  setImgFailed(false);
1147
1186
  setFirstImageLoaded(true);
1187
+ if (renderedUrl) {
1188
+ loadedUrlRef.current = renderedUrl;
1189
+ showVersionOf(renderedUrl);
1190
+ if (actualMockupId) realtimeContext?.markBlobShown?.(actualMockupId, renderedUrl, blobConsumerRef.current);
1191
+ applyRenderStampRef.current?.();
1192
+ }
1148
1193
  if (!onLoadCalledRef.current && onLoad) {
1149
1194
  onLoadCalledRef.current = true;
1150
1195
  onLoad();
@@ -62,6 +62,12 @@ const DEFAULT_ARTBOARD_SIZE = 2000;
62
62
  // Enforce a conservative cap to prevent memory crashes
63
63
  const MAX_CONCURRENT_BLOBS = 5;
64
64
 
65
+ /**
66
+ * Live composited frames per picture: the one on screen, the newest, one in flight. Measured bound (2026-11-11):
67
+ * phone case, 31 pictures: at 1200 px ~38 KB a frame -> <= 3.5 MB held on a phone; at 3000 px ~115 KB -> <= 10.7 MB.
68
+ */
69
+ const MAX_FRAMES_PER_PICTURE = 3;
70
+
65
71
  /** How long a frame whose blob: URL was revoked waits for its newer frame before counting as a real failure. */
66
72
  const FRAME_SUPERSEDE_GRACE_MS = 2000;
67
73
  /** The box accepts one `rerender` per this many ms (rc#840; more are refused with E_RERENDER_RATE_LIMITED). */
@@ -301,6 +307,12 @@ export interface RealtimeContextValue {
301
307
  * @returns The blob URL (created or passed through)
302
308
  */
303
309
  registerBlobUrl: (blobOrUrl: Blob | string, placementName?: string) => string;
310
+
311
+ /** A picture's <img> loaded `url` (from getMockupUrl): its older composited frames are released. */
312
+ markBlobShown: (mockupId: string, url: string, consumer?: string) => void;
313
+
314
+ /** An element that called markBlobShown unmounted: it no longer holds its frame. */
315
+ releaseBlobConsumer: (mockupId: string, consumer: string) => void;
304
316
  }
305
317
 
306
318
  const RealtimeContext = createContext<RealtimeContextValue | undefined>(
@@ -504,7 +516,11 @@ export function RealtimeProvider({
504
516
  getLastSentVersion,
505
517
  getLatestSentVersions,
506
518
  rerender: rerenderRaw,
519
+ isFrameSuperseded,
507
520
  } = realtimeMockup;
521
+ // Read through a ref: the composite pump's callbacks stay stable across renders.
522
+ const isFrameSupersededRef = useRef(isFrameSuperseded);
523
+ isFrameSupersededRef.current = isFrameSuperseded;
508
524
 
509
525
  // PERFORMANCE: Store mockup results in ref only - NO STATE UPDATES
510
526
  // This eliminates re-render cascades entirely. Components that need mockup results
@@ -570,6 +586,10 @@ export function RealtimeProvider({
570
586
  // Track all registered blob URLs for memory management
571
587
  // Uses insertion order to determine oldest URL for eviction
572
588
  const registeredBlobUrlsRef = useRef<Set<string>>(new Set());
589
+ // Composited frames per picture (newest first), and the one its <img> shows: revoked only when that picture moves on.
590
+ const blobsByOwnerRef = useRef<Map<string, string[]>>(new Map());
591
+ // Per picture: what EACH of its elements shows (a gallery can render one picture twice: the phone carousel does).
592
+ const shownBlobByOwnerRef = useRef<Map<string, Map<string, string>>>(new Map());
573
593
 
574
594
  // Track which placements have pending exports (for shimmer state)
575
595
  const pendingPlacementsRef = useRef<Set<string>>(new Set());
@@ -637,39 +657,88 @@ export function RealtimeProvider({
637
657
  /**
638
658
  * Register a blob URL with lifecycle management
639
659
  */
640
- const registerBlobUrl = useCallback((blobOrUrl: Blob | string, placementName?: string): string => {
641
- let url: string;
642
-
643
- if (blobOrUrl instanceof Blob) {
644
- // Enforce blob URL limit before creating new one
645
- if (registeredBlobUrlsRef.current.size >= MAX_CONCURRENT_BLOBS) {
646
- // Revoke oldest blob URL (first entry in Set maintains insertion order)
647
- const oldest = registeredBlobUrlsRef.current.values().next().value;
648
- if (oldest) {
649
- URL.revokeObjectURL(oldest);
650
- registeredBlobUrlsRef.current.delete(oldest);
651
-
652
- // Also remove from URL cache and the results snapshot if present, so
653
- // late subscribers are never replayed a revoked blob URL.
654
- mockupUrlCacheRef.current.forEach((value, key) => {
655
- if (value.url === oldest) {
656
- mockupUrlCacheRef.current.delete(key);
657
- }
658
- });
659
- mockupResultsRef.current = mockupResultsRef.current.filter(
660
- (r) => r.imageUrl !== oldest
661
- );
662
- }
663
- }
660
+ /** Revoke one blob URL and forget it everywhere a late subscriber could be replayed it. */
661
+ const revokeBlobUrl = useCallback((url: string) => {
662
+ URL.revokeObjectURL(url);
663
+ registeredBlobUrlsRef.current.delete(url);
664
+ mockupUrlCacheRef.current.forEach((value, key) => {
665
+ if (value.url === url) mockupUrlCacheRef.current.delete(key);
666
+ });
667
+ mockupResultsRef.current = mockupResultsRef.current.filter((r) => r.imageUrl !== url);
668
+ }, []);
664
669
 
665
- url = URL.createObjectURL(blobOrUrl);
666
- registeredBlobUrlsRef.current.add(url);
667
- } else {
668
- url = blobOrUrl;
670
+ /**
671
+ * Register a blob URL with lifecycle management.
672
+ *
673
+ * With an `owner` (a mockup id: the composited frames), a picture's frames are
674
+ * revoked only when that SAME picture has shown a newer one (`markBlobShown`,
675
+ * from its <img> load). A global "keep the newest 5" revoked other pictures'
676
+ * fresh frames before their <img> loaded them (31 composites per edit on the
677
+ * phone case): the picture kept its old image while its stamp said current
678
+ * (prod desktop, 2026-11-11: 15 ERR_FILE_NOT_FOUND per edit). Bound: at most
679
+ * MAX_FRAMES_PER_PICTURE live frames per picture (shown + newest + one in
680
+ * flight); a picture that exceeds it is a typed error and loses its OLDEST,
681
+ * never-shown frame — never the one on screen. Unowned blobs keep the old cap.
682
+ */
683
+ const registerBlobUrl = useCallback((blobOrUrl: Blob | string, _placementName?: string, owner?: string): string => {
684
+ if (!(blobOrUrl instanceof Blob)) return blobOrUrl;
685
+ const url = URL.createObjectURL(blobOrUrl);
686
+ if (owner) {
687
+ const list = [url, ...(blobsByOwnerRef.current.get(owner) ?? [])]; // newest first
688
+ const shown = new Set(shownBlobByOwnerRef.current.get(owner)?.values() ?? []);
689
+ while (list.length > MAX_FRAMES_PER_PICTURE) {
690
+ const victimIdx = [...list.keys()].reverse().find((i) => i > 0 && !shown.has(list[i]));
691
+ if (victimIdx === undefined) break;
692
+ const [victim] = list.splice(victimIdx, 1);
693
+ console.error(
694
+ `[RealtimeProvider] E_BLOB_PICTURE_BOUND: ${owner} has more than ${MAX_FRAMES_PER_PICTURE} frames waiting to be shown; dropping its oldest unshown frame (the picture on screen is kept).`
695
+ );
696
+ revokeBlobUrl(victim);
697
+ }
698
+ blobsByOwnerRef.current.set(owner, list);
699
+ return url;
669
700
  }
670
-
701
+ if (registeredBlobUrlsRef.current.size >= MAX_CONCURRENT_BLOBS) {
702
+ const oldest = registeredBlobUrlsRef.current.values().next().value;
703
+ if (oldest) revokeBlobUrl(oldest);
704
+ }
705
+ registeredBlobUrlsRef.current.add(url);
671
706
  return url;
672
- }, []);
707
+ }, [revokeBlobUrl]);
708
+
709
+ /** Release a picture's frames that are older than what EVERY one of its elements shows. */
710
+ const releaseOlderFrames = useCallback((owner: string) => {
711
+ const list = blobsByOwnerRef.current.get(owner);
712
+ const shown = shownBlobByOwnerRef.current.get(owner);
713
+ if (!list || !shown || shown.size === 0) return;
714
+ // The oldest frame any element still shows: everything older is unreachable.
715
+ const oldestShownIdx = Math.max(...[...shown.values()].map((u) => list.indexOf(u)));
716
+ if (oldestShownIdx < 0) return;
717
+ list.slice(oldestShownIdx + 1).forEach(revokeBlobUrl);
718
+ blobsByOwnerRef.current.set(owner, list.slice(0, oldestShownIdx + 1));
719
+ }, [revokeBlobUrl]);
720
+
721
+ /**
722
+ * An element of a picture (`consumer`: one per <img>) has loaded `url`. A picture can be rendered by more than one
723
+ * element (the phone carousel renders each twice): releasing on the FIRST element's load revoked the frame its twin
724
+ * was still loading, so the twin kept its old image for good (prod phone, 2026-11-11, after #4390). Frames go only
725
+ * when they are older than what every element shows.
726
+ */
727
+ const markBlobShown = useCallback((owner: string, url: string, consumer = "default") => {
728
+ const list = blobsByOwnerRef.current.get(owner);
729
+ if (!list || list.indexOf(url) < 0) return;
730
+ const shown = shownBlobByOwnerRef.current.get(owner) ?? new Map<string, string>();
731
+ shown.set(consumer, url);
732
+ shownBlobByOwnerRef.current.set(owner, shown);
733
+ releaseOlderFrames(owner);
734
+ }, [releaseOlderFrames]);
735
+
736
+ /** An element of a picture is gone (unmount): it no longer holds a frame. */
737
+ const releaseBlobConsumer = useCallback((owner: string, consumer: string) => {
738
+ const shown = shownBlobByOwnerRef.current.get(owner);
739
+ if (!shown?.delete(consumer)) return;
740
+ releaseOlderFrames(owner);
741
+ }, [releaseOlderFrames]);
673
742
 
674
743
  const croppedDeliveryEnabled = delivery !== "full-frame";
675
744
 
@@ -964,7 +1033,7 @@ export function RealtimeProvider({
964
1033
  });
965
1034
  // Scene changed while compositing (variant/bg flip) — stale, drop.
966
1035
  if (gen !== sceneGenRef.current) return;
967
- deliverResults([{ ...result, imageUrl: registerBlobUrl(blob) }]);
1036
+ deliverResults([{ ...result, imageUrl: registerBlobUrl(blob, undefined, result.mockupId) }]);
968
1037
  } catch (err) {
969
1038
  // A newer frame for this mockup already arrived: the SDK revokes a
970
1039
  // mockup's previous blob: frame the moment the next one lands, so a
@@ -980,6 +1049,13 @@ export function RealtimeProvider({
980
1049
  ) {
981
1050
  return;
982
1051
  }
1052
+ // The SDK revoked this frame because the mockup's NEXT frame has
1053
+ // arrived. React only learns of it with that batch's
1054
+ // all_mockups_rendered, which on a 31-picture product can come well
1055
+ // after the 2 s grace below (prod phone case, 2026-11-11, rendercenter
1056
+ // 20d5eaf: v3 batch 2.3 s, the grace fired first, cropped delivery went
1057
+ // off and a visible picture stayed at v2). The SDK knows at once.
1058
+ if (isFrameSupersededRef.current?.(result.imageUrl)) return;
983
1059
  // The FRAME (not the background) failed to load from a revoked blob:
984
1060
  // URL. The SDK revokes a mockup's frame only when that mockup's next
985
1061
  // frame arrives, so the newer frame exists even if React state hasn't
@@ -1789,6 +1865,8 @@ export function RealtimeProvider({
1789
1865
  getLatestSentVersions: getLatestSentVersionsStable,
1790
1866
  isMockupLoading,
1791
1867
  registerBlobUrl,
1868
+ markBlobShown,
1869
+ releaseBlobConsumer,
1792
1870
  // WebRTC streaming
1793
1871
  subscribeRTCTiming,
1794
1872
  }),
@@ -1822,6 +1900,8 @@ export function RealtimeProvider({
1822
1900
  getLatestSentVersionsStable,
1823
1901
  isMockupLoading,
1824
1902
  registerBlobUrl,
1903
+ markBlobShown,
1904
+ releaseBlobConsumer,
1825
1905
  ]
1826
1906
  );
1827
1907
 
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Cropped-frame delivery state machine (RealtimeProvider internals).
3
+ *
4
+ * The sdk hook and the composite engine are mocked; these tests pin the
5
+ * provider's money-path invariants:
6
+ * - the session flips to overlayCrop:'auto' only after EVERY configured
7
+ * mockup has a frozen full-frame background
8
+ * - cropped frames are composited and consumers only ever see full-frame
9
+ * URLs (blob: URLs from the composite)
10
+ * - any composite failure falls back to full-frame delivery for the session
11
+ * and re-renders the affected mockup so the edit isn't lost
12
+ * - priority requests for never-rendered mockups drop the session back to
13
+ * full-frame before rendering
14
+ */
15
+ import { describe, expect, it, beforeEach, vi } from "vitest";
16
+ import React from "react";
17
+ import { render, waitFor, act } from "@testing-library/react";
18
+ import {
19
+ RealtimeProvider,
20
+ useRealtime,
21
+ type RealtimeContextValue,
22
+ } from "../RealtimeProvider";
23
+
24
+ const h = vi.hoisted(() => {
25
+ return {
26
+ state: {
27
+ results: [] as Array<Record<string, unknown>>,
28
+ },
29
+ sendConfig: vi.fn(),
30
+ updateMockupIds: vi.fn(),
31
+ compositeCroppedFrame: vi.fn(),
32
+ loadImageElement: vi.fn(),
33
+ // Stable identities across renders — the real hook returns stable
34
+ // callbacks; fresh fns per render would churn the provider's effects.
35
+ sendCanvasBlob: vi.fn(),
36
+ sendCanvasState: vi.fn(),
37
+ sendColorBlob: vi.fn(),
38
+ updatePlacementSettings: vi.fn(),
39
+ connect: vi.fn(),
40
+ disconnect: vi.fn(),
41
+ flushPendingBlobs: vi.fn(),
42
+ hasPendingBlobs: vi.fn(() => false),
43
+ getLastSentVersion: vi.fn(() => 0),
44
+ getLatestSentVersions: vi.fn(() => ({})),
45
+ rerender: vi.fn((_ids: string[]) => true),
46
+ opts: null as null | { onError?: (msg: string, detail: Record<string, unknown>) => void },
47
+ };
48
+ });
49
+
50
+ vi.mock("@snowcone-app/sdk/react", () => ({
51
+ useRealtimeMockup: (opts: unknown) => {
52
+ h.opts = opts as typeof h.opts;
53
+ return {
54
+ isConnected: true,
55
+ isConfigured: true,
56
+ renderError: null,
57
+ mockupResults: h.state.results,
58
+ sendCanvasBlob: h.sendCanvasBlob,
59
+ sendCanvasState: h.sendCanvasState,
60
+ sendColorBlob: h.sendColorBlob,
61
+ sendConfig: h.sendConfig,
62
+ updateMockupIds: h.updateMockupIds,
63
+ updatePlacementSettings: h.updatePlacementSettings,
64
+ connect: h.connect,
65
+ disconnect: h.disconnect,
66
+ flushPendingBlobs: h.flushPendingBlobs,
67
+ hasPendingBlobs: h.hasPendingBlobs,
68
+ getLastSentVersion: h.getLastSentVersion,
69
+ getLatestSentVersions: h.getLatestSentVersions,
70
+ rerender: h.rerender,
71
+ };
72
+ },
73
+ }));
74
+
75
+ vi.mock("@snowcone-app/sdk", () => ({
76
+ resolveVariantId: () => "gv1",
77
+ resolvePreviewVariantId: (_context: unknown, variantId: string) => variantId,
78
+ }));
79
+
80
+ vi.mock("../Product", () => {
81
+ const product = {
82
+ id: "prod1",
83
+ placements: [{ label: "Front", type: "image" }],
84
+ mockups: Array.from({ length: 31 }, (_, i) => ({ id: `m${i}` })),
85
+ };
86
+ return {
87
+ useProductOptional: () => ({ product, selection: {} }),
88
+ };
89
+ });
90
+
91
+ vi.mock("../MockupBackground", () => ({
92
+ useMockupBackgroundOptional: () => undefined,
93
+ }));
94
+
95
+ vi.mock("../croppedFrameComposite", async (importOriginal) => {
96
+ const actual = await importOriginal<typeof import("../croppedFrameComposite")>();
97
+ return {
98
+ ...actual,
99
+ compositeCroppedFrame: h.compositeCroppedFrame,
100
+ loadImageElement: h.loadImageElement,
101
+ };
102
+ });
103
+
104
+ let capturedCtx: RealtimeContextValue;
105
+ function Capture() {
106
+ capturedCtx = useRealtime();
107
+ return null;
108
+ }
109
+
110
+ function Harness({ version }: { version: number }) {
111
+ void version; // re-render trigger — the mocked hook returns h.state.results
112
+ return (
113
+ <RealtimeProvider autoEnable>
114
+ <Capture />
115
+ </RealtimeProvider>
116
+ );
117
+ }
118
+
119
+ function fullResult(mockupId: string, url: string) {
120
+ return { mockupId, imageUrl: url, renderUrl: url, imageSize: 1000, placement: "Front" };
121
+ }
122
+
123
+ function croppedResult(mockupId: string, url: string) {
124
+ return {
125
+ ...fullResult(mockupId, url),
126
+ cropRect: { x: 0.2, y: 0.1, w: 0.5, h: 0.6 },
127
+ };
128
+ }
129
+
130
+ /** sendConfig payloads observed since the last mock reset. */
131
+ function sentConfigs(): Array<Record<string, unknown>> {
132
+ return h.sendConfig.mock.calls.map((c) => c[0] as Record<string, unknown>);
133
+ }
134
+
135
+ let blobCounter = 0;
136
+
137
+ /**
138
+ * The box's rule (rendercenter realtime.ts renderFingerprint): a config
139
+ * re-renders only when its render fingerprint changes — overlayCrop is NOT in
140
+ * it and mockupIds are SORTED. Returns the mockup sets the box re-renders for
141
+ * `configs`, given the set in force before them.
142
+ */
143
+ function boxRerenders(before: string[], configs: Array<Record<string, unknown>>): string[][] {
144
+ const fp = (ids: unknown) => [...(ids as string[])].sort().join(",");
145
+ let prev = fp(before);
146
+ const out: string[][] = [];
147
+ for (const c of configs) {
148
+ if (fp(c.mockupIds) !== prev) out.push(c.mockupIds as string[]);
149
+ prev = fp(c.mockupIds);
150
+ }
151
+ return out;
152
+ }
153
+
154
+ beforeEach(() => {
155
+ vi.clearAllMocks();
156
+ h.state.results = [];
157
+ blobCounter = 0;
158
+ h.loadImageElement.mockResolvedValue({ naturalWidth: 1400, naturalHeight: 782 });
159
+ h.compositeCroppedFrame.mockResolvedValue(new Blob(["x"], { type: "image/webp" }));
160
+ // jsdom has no createObjectURL
161
+ globalThis.URL.createObjectURL = vi.fn(() => `blob:composite-${++blobCounter}`);
162
+ globalThis.URL.revokeObjectURL = vi.fn();
163
+ });
164
+
165
+ async function seedAndFlip(rerender: (ui: React.ReactElement) => void) {
166
+ h.state.results = [fullResult("m1", "https://r/m1-full")];
167
+ await act(async () => rerender(<Harness version={2} />));
168
+ expect(sentConfigs().some((c) => c.overlayCrop)).toBe(false);
169
+
170
+ h.state.results = [
171
+ fullResult("m1", "https://r/m1-full"),
172
+ fullResult("m2", "https://r/m2-full"),
173
+ ];
174
+ await act(async () => rerender(<Harness version={3} />));
175
+ await waitFor(() => {
176
+ expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true);
177
+ });
178
+ }
179
+
180
+
181
+ const IDS = Array.from({ length: 31 }, (_, i) => `m${i}`);
182
+
183
+ describe("composited frames per picture (prod desktop 2026-11-11: 15 ERR_FILE_NOT_FOUND per edit)", () => {
184
+ it("31 pictures, one edit: no picture's NEW frame is revoked before that picture shows it; showing it releases its older frame", async () => {
185
+ const revoked: string[] = [];
186
+ globalThis.URL.revokeObjectURL = vi.fn((u: string) => { revoked.push(u); });
187
+ const { rerender } = render(<Harness version={1} />);
188
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
189
+ h.state.results = IDS.map((id) => fullResult(id, `https://r/${id}-full`));
190
+ await act(async () => rerender(<Harness version={2} />));
191
+ await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
192
+
193
+ // Edit 1: a cropped frame for every picture, composited into a blob each.
194
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-1`));
195
+ await act(async () => rerender(<Harness version={3} />));
196
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(31));
197
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
198
+ const firstUrls = IDS.map((id) => capturedCtx.getMockupUrl(id));
199
+ expect(firstUrls.every((u) => u?.startsWith("blob:composite-"))).toBe(true);
200
+ // The bug: a global "keep 5" revoked 26 of these fresh frames before any <img> loaded them.
201
+ expect(revoked.filter((u) => firstUrls.includes(u))).toEqual([]);
202
+
203
+ // m0's <img> shows its frame; edit 2 arrives; m0 shows the new one -> its edit-1 frame goes, nobody else's.
204
+ capturedCtx.markBlobShown("m0", firstUrls[0]!);
205
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-2`));
206
+ await act(async () => rerender(<Harness version={4} />));
207
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(62));
208
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
209
+ const second = capturedCtx.getMockupUrl("m0")!;
210
+ expect(revoked).toEqual([]);
211
+ capturedCtx.markBlobShown("m0", second);
212
+ expect(revoked).toEqual([firstUrls[0]]);
213
+ });
214
+
215
+ it("a picture rendered by N elements (the phone page renders each twice): a frame goes only when EVERY element has moved past it", async () => {
216
+ const revoked: string[] = [];
217
+ globalThis.URL.revokeObjectURL = vi.fn((u: string) => { revoked.push(u); });
218
+ const { rerender } = render(<Harness version={1} />);
219
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
220
+ h.state.results = IDS.map((id) => fullResult(id, `https://r/${id}-full`));
221
+ await act(async () => rerender(<Harness version={2} />));
222
+ await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
223
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-1`));
224
+ await act(async () => rerender(<Harness version={3} />));
225
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(31));
226
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
227
+ const f1 = capturedCtx.getMockupUrl("m0")!;
228
+ // N elements of m0 (the phone page mounts the carousel twice; a third surface for the general case) show frame 1.
229
+ for (const el of ["hero", "twin", "third"]) capturedCtx.markBlobShown("m0", f1, el);
230
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-2`));
231
+ await act(async () => rerender(<Harness version={4} />));
232
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(62));
233
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
234
+ const f2 = capturedCtx.getMockupUrl("m0")!;
235
+ // The hero shows frame 2 first; the twin still shows (and may be reloading) frame 1: it must stay alive.
236
+ capturedCtx.markBlobShown("m0", f2, "hero");
237
+ expect(revoked).toEqual([]);
238
+ // A second element catches up: the third still shows frame 1, so it stays.
239
+ capturedCtx.markBlobShown("m0", f2, "twin");
240
+ expect(revoked).toEqual([]);
241
+ // The last element catches up: now frame 1 is unreachable and goes.
242
+ capturedCtx.markBlobShown("m0", f2, "third");
243
+ expect(revoked).toEqual([f1]);
244
+ });
245
+
246
+ it("an element that unmounts stops holding its frame", async () => {
247
+ const revoked: string[] = [];
248
+ globalThis.URL.revokeObjectURL = vi.fn((u: string) => { revoked.push(u); });
249
+ const { rerender } = render(<Harness version={1} />);
250
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
251
+ h.state.results = IDS.map((id) => fullResult(id, `https://r/${id}-full`));
252
+ await act(async () => rerender(<Harness version={2} />));
253
+ await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
254
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-1`));
255
+ await act(async () => rerender(<Harness version={3} />));
256
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(31));
257
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
258
+ const f1 = capturedCtx.getMockupUrl("m0")!;
259
+ capturedCtx.markBlobShown("m0", f1, "hero");
260
+ capturedCtx.markBlobShown("m0", f1, "twin");
261
+ h.state.results = IDS.map((id) => croppedResult(id, `https://r/${id}-crop-2`));
262
+ await act(async () => rerender(<Harness version={4} />));
263
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(62));
264
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
265
+ capturedCtx.markBlobShown("m0", capturedCtx.getMockupUrl("m0")!, "hero");
266
+ expect(revoked).toEqual([]);
267
+ capturedCtx.releaseBlobConsumer("m0", "twin");
268
+ expect(revoked).toEqual([f1]);
269
+ });
270
+ });
271
+
@@ -43,6 +43,7 @@ const h = vi.hoisted(() => {
43
43
  getLastSentVersion: vi.fn(() => 0),
44
44
  getLatestSentVersions: vi.fn(() => ({})),
45
45
  rerender: vi.fn((_ids: string[]) => true),
46
+ isFrameSuperseded: vi.fn((_url: string) => false),
46
47
  opts: null as null | { onError?: (msg: string, detail: Record<string, unknown>) => void },
47
48
  };
48
49
  });
@@ -68,6 +69,7 @@ vi.mock("@snowcone-app/sdk/react", () => ({
68
69
  getLastSentVersion: h.getLastSentVersion,
69
70
  getLatestSentVersions: h.getLatestSentVersions,
70
71
  rerender: h.rerender,
72
+ isFrameSuperseded: h.isFrameSuperseded,
71
73
  };
72
74
  },
73
75
  }));
@@ -435,6 +437,31 @@ describe("RealtimeProvider cropped delivery", () => {
435
437
  errSpy.mockRestore();
436
438
  });
437
439
 
440
+ it("a frame the SDK superseded is dropped at once, even when the newer batch reaches React after the grace (prod phone case, 20d5eaf, 2026-11-11)", async () => {
441
+ const { rerender } = render(<Harness version={1} />);
442
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
443
+ await seedAndFlip(rerender);
444
+ h.sendConfig.mockClear();
445
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
446
+ // v3's frame arrived in the SDK (v2 revoked) at the START of a 31-picture batch; the batch's
447
+ // all_mockups_rendered — the only thing that updates React — came 2.3 s later.
448
+ h.isFrameSuperseded.mockImplementation((url: string) => url === "blob:v2-m1");
449
+ h.compositeCroppedFrame.mockImplementationOnce(() =>
450
+ Promise.reject(new Error("E_OVERLAY_FRAME_LOAD: image failed to load: blob:v2-m1"))
451
+ );
452
+ h.state.results = [croppedResult("m1", "blob:v2-m1"), fullResult("m2", "https://r/m2-full")];
453
+ await act(async () => rerender(<Harness version={4} />));
454
+ await act(async () => { await new Promise((r) => setTimeout(r, 2300)); });
455
+ expect(h.sendConfig).not.toHaveBeenCalled(); // cropped delivery stays on: no fallback config
456
+ expect(h.rerender).not.toHaveBeenCalled();
457
+ expect(errSpy.mock.calls.some((c) => String(c[0]).includes("E_OVERLAY_COMPOSITE_FAILED"))).toBe(false);
458
+ // The late batch composites normally.
459
+ h.state.results = [croppedResult("m1", "blob:v3-m1"), fullResult("m2", "https://r/m2-full")];
460
+ await act(async () => rerender(<Harness version={5} />));
461
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenLastCalledWith(expect.objectContaining({ frameUrl: "blob:v3-m1" })));
462
+ errSpy.mockRestore();
463
+ });
464
+
438
465
  it("a revoked frame with no newer frame within the grace window is a real failure: full-frame re-render", async () => {
439
466
  const { rerender } = render(<Harness version={1} />);
440
467
  await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());