Repository navigation
[2500 by Claude Opus 5] Cache downsampled canvas preview images locally with 1-week expiration and Cache downsampled canvas preview images locally with 1-week expiration - #2502
Conversation
What I built
New `propr-ui/src/components/previewCache.ts` — a two-layer cache for downsampled thumbnails:
- `CachedPreviewRecord` (`key`, `dataUrl`, `cssWidth`, `cssHeight`, `width`, `height`, `timestamp`) and the specified constants, including `PREVIEW_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000`.
- `getPreviewCacheKey(url, w, h, ratio)` rounds dimensions and the ratio, so a 24×24 micro thumbnail, an 80×56 compact one and a retina render each get their own entry while subpixel layout jitter doesn't fragment the cache.
- `openPreviewDatabase()` opens IndexedDB with a `timestamp` index and resolves `null` rather than rejecting when storage is missing, blocked or private-mode restricted — so jsdom, private browsing and blocked storage all silently degrade to the L1 `Map`.
- `getCachedPreview` reads L1 then L2, treats anything past a week as a miss and deletes it; `setCachedPreview` / `deleteCachedPreview` / `clearPreviewCache` keep both layers in step.
- `cacheCanvasPreview` captures `toDataURL('image/png')` inside try/catch, so a `SecurityError` from a cross-origin-tainted canvas is a no-op.
- `renderCachedPreview` restores backing store, CSS box and pixels; `pruneExpiredPreviews` deletes by `IDBKeyRange.upperBound(now - TTL)` via the index, scheduled once per session on idle.
`PreviewMedia.tsx` — `renderFromCache` runs before any downsampling, so a reload paints from cache without waiting on the 4K source; on a miss, `draw` downsamples as before and stores the result. `renderedSizeRef` tracks the rendered url/width/height so the lazy `<img>`'s later `onLoad` doesn't redo work the cache already covered, and the mount effect now calls `draw()` as soon as `clientWidth`/`clientHeight` are known instead of waiting for `image.complete`.
`previewDownsampling.ts` — extracted the device-pixel-ratio clamp as `previewPixelRatio()` so the cache key records the exact density the thumbnail was rendered at (behaviour unchanged).
Verification
- `npx vitest run src/components/PreviewMedia.test.tsx` → 23/23 pass, including new tests for key differentiation, the 1-week cutoff, canvas capture, tainted-canvas fallback, cached re-render and undecodable-thumbnail fallback.
- Full `src/components` + `src/pages` suite: 85 files, 609 tests pass. `tsc --noEmit` and `eslint` clean.
One deliberate deviation worth flagging: I added a `showsPreview` src guard around the async cache read, so a read that resolves after the `preview.url` prop changed on a reused element can't write the new image's pixels under the old key. That case isn't in the spec but is reachable, since the async path didn't exist before.
I did not generate visual previews: this is a caching change whose rendered thumbnails are pixel-identical to the current behaviour. The only perceptible difference is paint timing on reload, which a static screenshot would show as unchanged — capturing one would be misleading rather than evidential.
|
/ultrafix |
|
🔄 Ultrafix loop started (goal: 8/10, max cycles: 10) First action:
|
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — claude:claude-opus-5Overall EvaluationThis PR adds a two-tier (in-memory + IndexedDB) persistent cache for the downsampled compact thumbnails produced by The problem is that the write side of the cache can never succeed for the media this component actually renders. ✅ Never-throwing storage layer — ✅ Key correctly models what was rendered — extracting ✅ Async-read staleness guards — Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F1: 🔴 Cache can never be populated — the preview canvas is always cross-origin tainted
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 IndexedDB tier is entirely untestedjsdom provides no S2: 🟢 A cache hit still downloads and decodes the full-resolution sourceEven when S3: 🟢 Unbounded growth and a prune that only runs after a successful write
S4: 🟢 Concurrent
|
|
✅ Applied the requested follow-up changes in commit 64671b9
Summary of ChangesF1 is addressed, plus one finding you should know about before merge. What changed
Why the memo exists — and the limitation you need to decide on I probed the real endpoint. So the capture path is now correct and reachable for any origin-clean source, but F1's underlying symptom persists for today's only preview host. Without the memo my change would have been a straight regression — a doomed extra request per thumbnail on every page load. With it, the cost is one failed probe per browser per origin, and a client automatically starts caching if GitHub ever adds the header. The finding's second branch ("decode bytes the app itself fetched") can't be done client-side — Tests
Full No preview files: the change is deliberately not visually perceptible — the rendered thumbnail is byte-identical on both paths. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
…ore merge. F1 is addressed, plus one finding you should know about before merge. **What changed** `propr-ui/src/components/PreviewMedia.tsx` - Compact previews now request `crossOrigin="anonymous"`, so a successful load leaves the canvas origin-clean and `cacheCanvasPreview` can actually export it. - If that fetch is refused, the `<img>` is remounted (via a `key` flip) without the attribute, so the visible thumbnail never regresses — it just stops being cacheable. - `cacheCanvasPreview` is now gated on the live CORS state via a ref, not a captured closure value. This mattered: a cache read started before the fallback can still resolve afterwards, and the stale closure would have attempted a write from a tainted canvas (caught by my test, which failed until I fixed it). `propr-ui/src/components/previewCors.ts` (new) — remembers, per origin and persisted in `localStorage`, that a host refused CORS, so later thumbnails skip straight to the no-cors load. The refusal is only recorded once the no-cors retry *succeeds*, so a 404 or an offline load isn't mistaken for a CORS refusal. **Why the memo exists — and the limitation you need to decide on** I probed the real endpoint. `https://github.com/user-attachments/assets/<id>` serves a 302 to `github-production-user-asset-6210df.s3.amazonaws.com`, and **neither the redirect nor the S3 response carries `Access-Control-Allow-Origin`**, even with `Origin`/`Sec-Fetch-*` set. A CORS-mode image load fails the check at the redirect, so for GitHub attachments specifically the fallback will always engage and the cache will stay empty. So the capture path is now correct and reachable for any origin-clean source, but F1's underlying symptom persists for today's only preview host. Without the memo my change would have been a straight regression — a doomed extra request per thumbnail on every page load. With it, the cost is one failed probe per browser per origin, and a client automatically starts caching if GitHub ever adds the header. The finding's second branch ("decode bytes the app itself fetched") can't be done client-side — `fetch` is blocked by the same CORS policy, and `createImageBitmap` on a tainted image throws by spec. It needs a same-origin/CORS-enabled proxy in the ProPR API, which is a new endpoint with an auth problem (`<img>` can't send an `Authorization` header, so it'd need signed URLs or cookie auth). That's a server-side feature well outside this PR, so I did not build it — flagging it as the real unblock for issue #2500's caching goal. **Tests** - New: a `cacheCanvasPreview` → `getCachedPreview` → `renderCachedPreview` round trip, covering the populated path rather than only the failure path. - New component tests: the CORS attribute is requested; a first mount writes to storage and the next mount repaints from it in a single draw with no halving passes; the refusal path retries without CORS, renders, and writes nothing; the memo suppresses re-probing and persists; an unavailable image does not poison the memo. - Updated the existing "handles unavailable images" test — availability is now decided by the retry, not the first error. Full `propr-ui` suite: 159 files, 1264 tests passing. `tsc --noEmit` and `eslint` clean. No preview files: the change is deliberately not visually perceptible — the rendered thumbnail is byte-identical on both paths. PR: #2502 Comment by: @propr-ultrafix (ID: 0) Model: claude-opus-5
|
CI failed: Full Test Suite Shard 4/4 Please investigate and fix this CI failure.
Failure evidence
|
|
✅ Applied the requested follow-up changes in commit c844606 Summary of ChangesCI is green-able again. Here's what was wrong. Root cause
await waitFor(() => expect(screen.queryByText(goal.title)).not.toBeInTheDocument());
expect(screen.getByTestId('location-search')).toHaveTextContent('search=billing+api');
I confirmed the ordering with an instrumented copy of the test: immediately after the list filtered, the probe read This is not caused by the preview-cache work on this branch; FixOne assertion in // The debounce commits the filter and the URL together, but React Router applies the
// navigation in a transition, so the probe catches up a render after the filtered list.
await waitFor(() => expect(screen.getByTestId('location-search')).toHaveTextContent('search=billing+api'));The later Verification
No preview files: the change is test-only and produces no visually perceptible difference. 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
|
CI failed: Run Full Test Suite Please investigate and fix this CI failure.
Failure evidence
|
Full Test Suite ResultsValidation failed during: Test shard (shard 4).
View shard 4/4 outputDetails truncated; see the uploaded artifacts for complete failure rows and logs. |
CI is green-able again. Here's what was wrong.
## Root cause
`GoalsPage.test.tsx:660` asserted the URL synchronously right after the search debounce fired:
```js
await waitFor(() => expect(screen.queryByText(goal.title)).not.toBeInTheDocument());
expect(screen.getByTestId('location-search')).toHaveTextContent('search=billing+api');
```
`commitSearch` (`GoalsPage.tsx:692`) does two things in one call: `setDebouncedSearch(value)` (a plain state update, which re-filters the list) and `updateFilterParams(...)` → `setSearchParams` (a React Router navigation, which React Router applies inside a transition). Because the debounce fires from a `setTimeout` that isn't wrapped in `act`, the plain update commits first and the transition lands a render later. `waitFor` unblocked on the filtered list, and the location probe was still empty at that instant.
I confirmed the ordering with an instrumented copy of the test: immediately after the list filtered, the probe read `""`; 100 ms later it read `"?search=billing+api"`. So the app behaves correctly — the assertion was racing the transition.
This is not caused by the preview-cache work on this branch; `GoalsPage.tsx` and `GoalsPage.test.tsx` are unchanged against the merge base. The race arrived with the goals search/filter feature (PR #2474) and reproduces 100% of the time on this machine, which is why shard 4 caught it.
## Fix
One assertion in `propr-ui/src/pages/GoalsPage.test.tsx` now waits for the navigation, matching the convention already used for the same probe in `PlanStudioPage.notificationIntent.test.tsx:55`:
```js
// The debounce commits the filter and the URL together, but React Router applies the
// navigation in a transition, so the probe catches up a render after the filtered list.
await waitFor(() => expect(screen.getByTestId('location-search')).toHaveTextContent('search=billing+api'));
```
The later `not.toHaveTextContent('search=')` assertion in the same test is driven by a `fireEvent.click`, whose `act` wrapper flushes the transition before the assertion runs, so it doesn't have this hazard.
## Verification
- `GoalsPage.test.tsx`: 40/40 pass (failed before the change).
- Full `propr-ui` suite: 159 files, 1264 tests pass.
- `tsc --noEmit` and `eslint` clean.
No preview files: the change is test-only and produces no visually perceptible difference.
PR: #2502
Comment by: @propr-dev[bot] (ID: 5800047297)
Model: claude-opus-5
|
ℹ️ Analyzed the follow-up request by @propr-dev[bot], @github-actions[bot] Analysis SummaryNo changes were needed — the failure was already fixed on this branch, in a commit that landed after CI ran. I verified that rather than assuming it. What CI hitShard 4/4 failed on one
Why nothing needed changingCI tested commit Verification on the current head
Shards 1–3 passed at Two things worth knowingThe race is not from this PR's work. The other three probe assertions in that file are safe, for a specific reason. Lines 633, 639, and 668 read the same The No preview files: this request produced no implementation changes and nothing visually perceptible. No code changes were necessary based on the current state of the branch. 🤖 Analysis Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — claude:claude-opus-5Overall EvaluationThis PR adds a two-tier (in-memory + IndexedDB) cache for downsampled compact preview thumbnails with a one-week TTL, extracts The engineering craft in the individual modules is high — failure handling is thorough and the visible image never regresses. The problem is at the seam between the two new modules: ✅ Defensive failure handling throughout — ✅ Cache key is correctly scoped and normalized — ✅ Async staleness guards are genuinely careful — Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F2: 🔴 Cache can never be populated for the only preview origin the app permits
F3: 🔴 CORS remount leaves the ResizeObserver bound to the detached
|
|
✅ Applied the requested follow-up changes in commit 77980ec
Summary of ChangesBoth findings are addressed. Here's what I did and why. F2 — verified the premise first, then replaced the mechanismI probed a real attachment URL from this repo's PRs (
So an origin-clean load is not achievable, The probe also exposed why this matters more than the issue assumed: the 302 is Replacement (the reviewer's first-listed option): Because an opaque entry could equally be a GitHub error page, Two things this does not do, which you should weigh before merge:
F3 — resolved structurallyThe stale-observer bug came from the Verification
No preview images: the rendered output is pixel-identical — the change is caching and request behaviour, not appearance. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
Both findings are addressed. Here's what I did and why. ## F2 — verified the premise first, then replaced the mechanism I probed a real attachment URL from this repo's PRs (`https://github.com/user-attachments/assets/a8cc3c1e-…`) with an `Origin` header and browser-like `Sec-Fetch-*` headers: - Hop 1 (`github.com`, 302): **no `Access-Control-Allow-Origin`** - Hop 2 (the signed `…s3.amazonaws.com` asset, 200): **no `Access-Control-Allow-Origin`** So an origin-clean load is not achievable, `toDataURL` can never succeed, and `previewCors.ts` was right. The canvas-export/IndexedDB tier could not populate for any URL `trustedGitHubAttachmentUrl` admits — it was deleted along with the CORS probe and the extra refused request per thumbnail. The probe also exposed *why* this matters more than the issue assumed: the 302 is `no-store` and points at a single-use signed URL that changes per request, so the browser's HTTP cache never reuses a capture — the full-resolution source is re-downloaded on every page load. Replacement (the reviewer's first-listed option): `propr-ui/public/preview-media-cache.js`, imported by the service worker with `importScripts` and fully self-contained (own cache, own `fetch`/`activate`/`message` listeners, no shared state). It keys the **opaque** response on the stable attachment URL, so a reload paints from disk with no network. It carries the one-week expiry the issue asked for via a companion stamp entry (opaque responses expose no headers), caps the cache at 60 captures, prunes on activate, writes off the response path via `waitUntil`, and serves an expired capture rather than failing when the network is down. Because an opaque entry could equally be a GitHub error page, `PreviewImage`'s `onError` posts the URL back for eviction (`previewMediaCache.ts`) instead of replaying a transient failure for a week. Two things this does **not** do, which you should weigh before merge: - It caches the source bytes, not the thumbnail — decode and downsample still run per load. Storing a thumbnail requires readable pixels, which is impossible without a same-origin proxy or server-side thumbnailing; I did not expand into backend auth/SSRF territory for that. - Service workers are registered only for secure production builds, so there is no caching in dev or in the Electron runtime. ## F3 — resolved structurally The stale-observer bug came from the `key={corsRequested ? 'cors' : 'no-cors'}` remount. With the CORS fallback gone there is no remount, the `<img>` identity is stable, and the observer stays bound to the element in the DOM. Deps are now `[compact, draw, failed]`, with `preview.url` covered through `draw`. ## Verification - `propr-ui`: 1266 tests pass (160 files), `tsc --noEmit` clean, `eslint . --max-warnings 0` clean, `vite build` succeeds and emits `preview-media-cache.js`. - New coverage: `previewMediaCacheWorker.test.ts` (10 tests — never answers a CORS/non-preview/query/POST request, holds-then-serves-without-network, TTL refetch, offline fallback, activate purge, eviction message including an untrusted-URL rejection) and three page-side tests. - Both worker files were within ~10 lines of the 400-line `max-lines` gate, so the test harness moved to `src/test/serviceWorkerHarness.ts` (now dispatching to *all* listeners per event, since two modules register `fetch`/`activate`, and throwing on a double `respondWith`). - `serve.json` and the reverse-proxy contract in `pwa-web-push.md` / `deployment.md` list the new worker file so a proxy does not SPA-rewrite it. No preview images: the rendered output is pixel-identical — the change is caching and request behaviour, not appearance. PR: #2502 Comment by: @propr-ultrafix (ID: 0) Model: claude-opus-5
|
CI failed: Full Test Suite Shard 2/4 Please investigate and fix this CI failure.
Failure evidence
|
|
✅ Applied the requested follow-up changes in commit cc9a0f0 Summary of ChangesFixed. The failure was a pre-existing timing flake, unrelated to this PR's preview-cache work. What failedI pulled the shard's uploaded artifact rather than guessing. Of 131 units, 130 passed and one failed:
Root causeThe test inserted a retry attempt with That rejection hinged entirely on the trigger condition The test file is untouched by this branch ( VerificationI didn't just assert the diagnosis — I reproduced it. Injecting a 300 ms stall before the UPDATE on the original code produced the identical The fix pins Then re-ran with that same stall applied to the fixed code:
I also audited the rest of that test for the same fragility. The other timing constructs are "sleep 250 ms, then act on a 200 ms window" — those only get more valid as a machine slows, so they don't fail in the same direction. The one I fixed was the only assertion requiring a timestamp to still be in the future. Two notes worth flagging: this fix is confined to one assertion, so if the suite is genuinely CPU-starved other latent timing tests could surface — the 4.3s duration suggests real runner contention. Separately, shard 1/4 and 4/4 were still in progress when I checked, and an earlier comment records a 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
|
CI failed: Run Full Test Suite Please investigate and fix this CI failure.
Failure evidence
|
Full Test Suite ResultsValidation failed during: Test shard (shard 2).
View shard 2/4 outputDetails truncated; see the uploaded artifacts for complete failure rows and logs. |
…ed to this PR's preview-cache work.
Fixed. The failure was a pre-existing timing flake, unrelated to this PR's preview-cache work.
## What failed
I pulled the shard's uploaded artifact rather than guessing. Of 131 units, 130 passed and one failed:
- `test/notificationSchema.test.ts` → *"uses one database-timed claim statement for pending, retryable, and expired processing jobs"*
- `AssertionError: Missing expected rejection` at line 2921, in a test that took **4.3s** — the tell-tale sign of a loaded runner.
## Root cause
The test inserted a retry attempt with `next_retry_at = now + 0.200 seconds`, read that value back off the job row, and used it as `claimed_at` in an update it expected the `push_delivery_jobs_valid_transition` trigger to reject.
That rejection hinged entirely on the trigger condition `NEW.claimed_at <= strftime('now')` being **false** — i.e. on the timestamp still being in the future. The margin was 200 ms of wall clock covering an INSERT, a SELECT and an UPDATE. On a busy CI runner that window elapses, `claimed_at` becomes the past, the transition becomes genuinely legal, and no rejection is raised.
The test file is untouched by this branch (`git diff main...HEAD` shows nothing; it was last modified in #1731), so this was latent flakiness that this run happened to trip.
## Verification
I didn't just assert the diagnosis — I reproduced it. Injecting a 300 ms stall before the UPDATE on the **original** code produced the identical `Missing expected rejection.` error from CI.
The fix pins `claimed_at` to a fixed far-future constant (`futureClaimedAt = '2099-08-02T08:05:00.000Z'`, kept below `leaseExpiresAt` so the row stays coherent) instead of deriving it from the 200 ms window. Rejection now comes from the future-`claimed_at` condition deterministically, which is what the `future-time-worker` claim token shows the test always meant to check.
Then re-ran with that same stall applied to the fixed code:
- 300 ms stall → passes; 3000 ms stall → passes (timing-independent)
- Full file: **32/32 pass**; three repeat runs of the target test all green
- Full file again under 12 busy-loops on 12 cores (saturated CPU, closest analogue to the loaded runner): **32/32 pass**
- `tsc --noEmit` clean
I also audited the rest of that test for the same fragility. The other timing constructs are "sleep 250 ms, then act on a 200 ms window" — those only get *more* valid as a machine slows, so they don't fail in the same direction. The one I fixed was the only assertion requiring a timestamp to still be in the future.
Two notes worth flagging: this fix is confined to one assertion, so if the suite is genuinely CPU-starved other latent timing tests could surface — the 4.3s duration suggests real runner contention. Separately, shard 1/4 and 4/4 were still in progress when I checked, and an earlier comment records a `propr-ui` shard 4 failure; that's outside this request's scope, so I left it alone. No preview files were generated — a test-only timing fix has no user-visible surface.
PR: #2502
Comment by: @propr-dev[bot] (ID: 5800966925)
Model: claude-opus-5
|
✅ Applied the requested follow-up changes in commit c241237 Processed 2 comments:
Summary of ChangesWhat the CI failure actually wasI pulled the real job log rather than working from the truncated comment. Shard 2's only failure was subtest 22 of That assertion expected the This was already fixed on the branch. The CI run was queued against What I did changeWhile confirming the diagnosis I checked the rest of the file for the same failure class and found a second, still-live instance in subtest 25, This one is the mirror image of the flake CI just hit, in the same file, and would have been one slow runner away from breaking the next run, so I fixed it:
The two other short windows in the file (lines ~3233, ~2940) only ever wait past a deadline, so slowness makes them more true, not less — I left them alone. Verification
The change is test-only and produces no visible UI difference, so I did not generate preview files. One caveat worth stating plainly: the 2 s window is a widened margin, not a proof. It cannot be made unconditional while 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
## What the CI failure actually was
I pulled the real job log rather than working from the truncated comment. Shard 2's only failure was subtest 22 of `test/notificationSchema.test.ts`:
```
not ok 22 - uses one database-timed claim statement for pending, retryable, and expired processing jobs
error: 'Missing expected rejection.'
location: test/notificationSchema.test.ts:2921:53424
```
That assertion expected the `push_delivery_jobs_valid_transition` trigger to reject a claim whose `claimed_at` came from the row's `next_retry_at` — a value only **200 ms** in the future. The rejection hinged entirely on `NEW.claimed_at <= strftime('now')` still being false. On a loaded runner that 200 ms elapses across the intervening INSERT/SELECT/UPDATE, the transition becomes genuinely legal, and nothing is raised.
**This was already fixed on the branch.** The CI run was queued against `77980ec7a`; the fix landed in `cc9a0f07d` immediately after. I verified it independently rather than taking the commit message's word for it — injecting a 400 ms stall before the update reproduces CI's exact `Missing expected rejection.` on the pre-fix file (3/3 runs), and the same stall against the current file passes (3/3). So no change was needed for the reported failure.
## What I did change
While confirming the diagnosis I checked the rest of the file for the same failure class and found a second, still-live instance in subtest 25, `versions subscription refreshes and cleans up natural expiration`. It inserts a subscription expiring in 200 ms, then claims a job through `push_delivery_claimable_jobs` — a view that requires `subscription.expires_at > now`. If the runner drifts past 200 ms before the claim, the claim matches nothing and the test fails with `0 !== 1`. I reproduced exactly that with an injected stall.
This one is the mirror image of the flake CI just hit, in the same file, and would have been one slow runner away from breaking the next run, so I fixed it:
- The expiry window widened from 200 ms to 2 s, so the claim isn't racing the statements in between. `expires_at` is immutable by trigger (`push_subscriptions_version_identity_immutable`) and rows can't be deleted, so natural expiration can only come from the clock passing it — the window can be widened but not eliminated.
- The fixed `setTimeout(250)` is replaced by `waitForDatabaseDeadlines`, which polls SQLite's own `now` until it passes the later of the stored `expires_at` and `lease_expires_at`. Triggers and views compare against the database clock, so the test now waits on the actual deadlines: it returns immediately on a runner that already drifted past them, and keeps waiting on one that hasn't. It's bounded at 30 s with an explicit error.
The two other short windows in the file (lines ~3233, ~2940) only ever wait *past* a deadline, so slowness makes them more true, not less — I left them alone.
## Verification
- Full file: **32/32 pass**, `# fail 0`
- Full file **4/4 green under 24-way CPU saturation on 12 cores** — the closest analogue to the loaded runner
- The repaired subtest passes with a 1.5 s stall injected at the claim (7.5× the old margin); the old version fails that same stall
- `tsc --noEmit` clean
The change is test-only and produces no visible UI difference, so I did not generate preview files.
One caveat worth stating plainly: the 2 s window is a widened margin, not a proof. It cannot be made unconditional while `expires_at` stays immutable, so a pathological >2 s stall between two adjacent SQLite statements would still trip it — but it now fails with a clear `0 !== 1` on the claim rather than an ambiguous missing rejection.
PR: #2502
Comment by: @propr-dev[bot] (ID: 5801068329)
Comment by: @github-actions[bot] (ID: 5801069273)
Model: claude-opus-5
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — claude:claude-opus-5Overall EvaluationThis PR adds a durable local cache for published capture previews. Rather than the IndexedDB-of-downsampled-bitmaps approach named in the issue, it ships a separate service-worker module ( The reasoning behind the deviation is sound and is documented in-code: the attachment host sends no ✅ Well-isolated worker module — ✅ Substantive worker test coverage — ✅ Redraw memoization is correct — Needs one targeted change before merge (F1). Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F4: 🔴 Preview worker intercepts and caches video attachment requests, including range requests
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Surface the IndexedDB/downsampled-thumbnail deviation to the issue ownerThe issue asks for the downsampled previews to be cached in IndexedDB so that the multi-pass halving in S2: 🟢 Mirror the
|
|
✅ Applied the requested follow-up changes in commit fca98bf
Summary of ChangesF4 is addressed. Two guards in 1. Interception narrowed to still images ( The fetch listener now returns early unless 2. Ranged requests are never stored (
I left Tests — Both new tests were confirmed to fail against the pre-fix worker and pass after. Full suite: 1268 tests across 160 files pass, plus No preview files: the change is a service-worker interception gate, and video previews now load over the network exactly as they did before this PR, so there is nothing visually perceptible to capture. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
…ia-cache.js`:
F4 is addressed. Two guards in `propr-ui/public/preview-media-cache.js`:
**1. Interception narrowed to still images** (`preview-media-cache.js:139`)
The fetch listener now returns early unless `request.destination === 'image'`. `isPreviewMediaUrl` matches any `github.com/user-attachments/assets/<id>` URL, and `PublishedVisualPreview` includes `type: 'video'` — `TaskVisualPreviews.tsx` renders `<video src={preview.url} preload="metadata" controls>` against exactly that shape, which is a no-cors GET and was being intercepted. Verified the intended path is unaffected: `PreviewMedia.tsx:58` loads captures through `<img>`, whose destination is `image`.
**2. Ranged requests are never stored** (`preview-media-cache.js:80`)
`storePreviewMedia` bails when `request.headers.get('range')` is set. An opaque filtered response reports `status` 0, so `Cache.put`'s 206 rejection never fires and a partial body could land under the full-resource key, to be replayed later as the whole resource.
I left `servePreviewMedia`'s `cache.match` as is — with interception limited to `destination: 'image'` and partials never written, there is no entry a range request could be wrongly answered from.
**Tests** — `previewMediaCacheWorker.test.ts` gains a `'a published video'` case in the existing "never answers" table and a new test asserting a `Range: bytes=128-` request still reaches the network but writes nothing to the cache. The harness's `dispatchFetch` now defaults `destination: ''` and `headers: new Headers()` on fetch fixtures, which name only what they exercise; the preview fixture sets `destination: 'image'`.
Both new tests were confirmed to fail against the pre-fix worker and pass after. Full suite: 1268 tests across 160 files pass, plus `tsc --noEmit` and eslint clean on the changed files.
No preview files: the change is a service-worker interception gate, and video previews now load over the network exactly as they did before this PR, so there is nothing visually perceptible to capture.
PR: #2502
Comment by: @propr-ultrafix (ID: 0)
Model: claude-opus-5
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — claude:claude-opus-5Overall EvaluationThis PR implements durable, one-week local caching for published capture previews. Rather than the literal approach named in the issue (IndexedDB storage of the downsampled bitmaps), it introduces a separate service-worker module ( The deviation from the issue's wording is technically justified and documented in code: a no-CORS cross-origin image taints the canvas, so ✅ Conservative interception surface — The fetch handler only claims ✅ Fail-open composition with the shell worker — ✅ Opaque-response age tracking and self-healing — Because opaque entries expose no headers, the module stores a sibling stamp entry and treats a missing/unparseable stamp as expired, and the page reports undecodable bytes back via Merge blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Downsampling CPU cost still repeats per loadThe issue asked for cached downsampled images so that neither the high-resolution decode nor the multi-pass halving runs again on reload. The PR's documented constraint (tainted canvas ⇒ no export) is accurate, so the delivered cache removes the network round-trip but each page load still decodes the 4K source and re-runs S2: 🟢 Eviction can race the deferred cache write
S3: 🟢 Preview cache survives sign-outThis is the first place in the app that persists attachment bytes to disk: GitHub marks both hops S4: 🟢 Duplicated trust predicate and message contract
S5: 🟢 Harness cache-key semantics changed for pre-existing testsThe extracted harness replaces the old S6: 🟢 Trim cost and opaque quota paddingEvery successful store re-reads the stamp of every surviving entry with a sequential S7: 🟢 Redraw memo ignores device-pixel-ratio changes
ScoreThe implementation is careful, narrowly scoped, well documented about a genuine platform constraint, and covered by focused worker and component tests with the deployment contract kept in sync; I found no PR-introduced correctness or safety regression. It loses points only for delivering the network half of the stated objective while leaving the repeated downsampling CPU cost in place, and for bundling unrelated test-timing changes. Score: 8/10 🤖 Review Details
🤖 Review by ProPR |
|
/review astra fable |
|
✅ AI Code Review Complete requested by @integry Posted 2 reviews: |
🔍 AI Code Review — astraOverall EvaluationThe PR adds a bounded, week-long service-worker cache for original capture responses and avoids repeated downsampling within a mounted component. It needs significant rework because it does not persist downsampled previews, and cache-read failures can prevent otherwise available images from loading. ✅ Narrow interception — The worker restricts caching to trusted attachment URLs requested as no-CORS images and excludes videos. ✅ Worker integration coverage — The shared harness dispatches multiple listeners and rejects duplicate Current-head checks show three skipped checks and no failures or passes. This review uses static tracing only; no commands or tests were run. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F5: 🔴 Persist the downsampled previews
F6: 🔴 Fall back when cache reads fail
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Exercise real opaque responsesThe harness constructs ordinary ScoreThe implementation provides useful network caching and focused tests, but misses the central resized-preview persistence requirement and introduces a storage-failure loading regression. Current checks provide no passing validation evidence. Score: 5/10 🤖 Review Details
🤖 Review by ProPR |
🔍 AI Code Review — fableOverall EvaluationPR #2502 targets issue #2500 ("Cache downsampled canvas preview images locally with 1-week expiration … using IndexedDB"). The current head, however, delivers a different design: a service-worker module ( The worker code itself is careful and well tested; the harness refactor is a solid improvement; the unrelated test-flake fixes ( ✅ Correct request gating in the worker — ✅ Range/partial-response guard — ✅ Draw dedupe is sound — Verdict: needs significant rework or explicit re-scoping before merge. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F7: 🔴 Deliverable does not implement the specified downsampled-thumbnail cache
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Forget-message can lose a race with the pending cache write
S2: 🟢 Unrelated test-flake fixes bundled in this PR
S3: 🟢 Opaque-entry quota footprint is largeChromium pads each opaque response to roughly 7 MB of quota accounting; S4: 🟢 Trim performs O(n) stamp reads on every store
S5: 🟢 Cache is inert outside production secure contexts
ScoreThe worker implementation is clean, defensively gated, and well covered, but the PR does not deliver the objective it is anchored to (IndexedDB-persisted downsampled thumbnails), the description misrepresents the shipped code, and no full test run is recorded on the current head. Score: 5/10 🤖 Review Details
🤖 Review by ProPR |
AI Implementation Summary
Closes #2500
Branch:
2500/claude-opus-5-cache-downsampled-canvas--20260923-1611-2mhCommits: ✅ Changes committed (56405f7)
AI Processing Completed
Execution Details:
Summary:
Implementation complete.
What I built
New
propr-ui/src/components/previewCache.ts— a two-layer cache for downsampled thumbnails:CachedPreviewRecord(key,dataUrl,cssWidth,cssHeight,width,height,timestamp) and the specified constants, includingPREVIEW_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000.getPreviewCacheKey(url, w, h, ratio)rounds dimensions and the ratio, so a 24×24 micro thumbnail, an 80×56 compact one and a retina render each get their own entry while subpixel layout jitter doesn't fragment the cache.openPreviewDatabase()opens IndexedDB with atimestampindex and resolvesnullrather than rejecting when storage is missing, blocked or private-mode restricted — so jsdom, private browsing and blocked storage all silently degrade to the L1Map.getCachedPreviewreads L1 then L2, treats anything past a week as a miss and deletes it;setCachedPreview/deleteCachedPreview/clearPreviewCachekeep both layers in step.cacheCanvasPreviewcapturestoDataURL('image/png')inside try/catch, so aSecurityErrorfrom a cross-origin-tainted canvas is a no-op.renderCachedPreviewrestores backing store, CSS box and pixels;pruneExpiredPreviewsdeletes byIDBKeyRange.upperBound(now - TTL)via the index, scheduled once per session on idle.PreviewMedia.tsx—renderFromCacheruns before any downsampling, so a reload paints from cache without waiting on the 4K source; on a miss,drawdownsamples as before and stores the result.renderedSizeReftracks the rendered url/width/height so the lazy<img>'s lateronLoaddoesn't redo work the cache already covered, and the mount effect now callsdraw()as soon asclientWidth/clientHeightare known instead of waiting forimage.complete.previewDownsampling.ts— extracted the device-pixel-ratio clamp aspreviewPixelRatio()so the cache key records the exact density the thumbnail was rendered at (behaviour unchanged).Verification
npx vitest run src/components/PreviewMedia.test.tsx→ 23/23 pass, including new tests for key differentiation, the 1-week cutoff, canvas capture, tainted-canvas fallback, cached re-render and undecodable-thumbnail fallback.src/components+src/pagessuite: 85 files, 609 tests pass.tsc --noEmitandeslintclean.One deliberate deviation worth flagging: I added a
showsPreviewsrc guard around the async cache read, so a read that resolves after thepreview.urlprop changed on a reused element can't write the new image's pixels under the old key. That case isn't in the spec but is reachable, since the async path didn't exist before.I did not generate visual previews: this is a caching change whose rendered thumbnails are pixel-identical to the current behaviour. The only perceptible difference is paint timing on reload, which a static screenshot would show as unchanged — capturing one would be misleading rather than evidential.
Detailed Logs:
d56766f9-ac7e-41df-be5e-0435d2d572b8Log files stored at:
/tmp/claude-logs/issue-2500-2026-09-23T16-20-01-146Z-conversation.json/tmp/claude-logs/issue-2500-2026-09-23T16-20-01-146Z-output.txtLatest Conversation Messages
This PR was created automatically by ProPR after processing issue #2500.
💡 Need changes?
Comment on this PR to request refinements — the AI agent monitors comments and will update the implementation based on your feedback. Keep iterating until you're satisfied!