Repository navigation
feat(web): live gallery — Eden Treaty + TanStack Query - #10
Conversation
Wire the frontend to the live API so uploads actually render (Model A topology). - api: GET /api/v1/assets/:id (single metadata for deep links); export AssetDto. - web: Eden Treaty client (`lib/api.ts`, same-origin, `unwrap` helper for the error-envelope), QueryClient, `useAssetsPage`/`useAsset` hooks. The grid and detail page render live data (real thumbnails via /:id/file, real pagination, loading/empty/error states); the static post-fixtures are removed. The web dev server reverse-proxies /api/* to the API (no CORS), with a 502 on upstream failure and credential-redacted startup logging. - scripts/seed.ts (`bun run seed [n]`): generates varied colour PNGs through the real upload service to populate the gallery for local demos. - a11y: aria-pressed on layout toggles, aria-current on the active page. Tests: API routes for /:id (200/404/422). typecheck 0, 105 tests, boundaries 0. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds a single-asset API endpoint, updates API/package resolution and storage defaults, wires live querying into the web app, rewrites the posts views to use asset data, and adds a Bun seed script for generating and uploading PNGs. ChangesAsset API and live asset UI
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@coderabbitai full review |
✅ Action performedFull review finished. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.gitignore:
- Around line 45-46: The .gitignore rule only ignores repo-root storage, so
package-local storage under apps/api can still be tracked after STORAGE_ROOT
resolves from process.cwd() in env-config. Update the storage ignore entry in
.gitignore so it also covers nested package storage paths like the one produced
by apps/api, using the existing storage ignore rule as the anchor point.
In `@apps/api/src/server.ts`:
- Around line 182-188: The `/assets/:id` and file route numeric path validators
in `server.ts` allow values beyond JavaScript’s safe integer range, which can be
rounded before `getById()` is called. Update both `t.Numeric` schemas used in
the asset lookup handlers to include a `maximum: Number.MAX_SAFE_INTEGER`
constraint, alongside the existing minimum and integer checks, so oversized IDs
are rejected before routing into `core.assetService.getById` and the related
file lookup logic.
In `@apps/web/src/lib/assets.ts`:
- Around line 27-32: useAsset currently lets Eden 404s bubble out of the
queryFn, which makes PostDetailPage hit isError instead of the missing-asset
path. Update the queryFn in useAsset to catch the assets().get() error, detect
404s, and return null/undefined for that case before calling unwrap; keep
non-404 failures unchanged so only deleted/missing assets are treated as absent.
In `@apps/web/src/routes/post-detail.tsx`:
- Around line 23-26: The post-detail route is converting the raw id with
Number(id), which allows non-decimal forms like 1e2 or 0x10 to pass and fetch
the wrong asset. Update the validation in post-detail.tsx to check the original
route segment as decimal digits only and require a safe integer before calling
useAsset, using the existing postId/validId logic in the route component to gate
the fetch.
- Around line 72-77: The post detail error handling currently treats a 404 from
unwrap() as a generic query failure, so missing posts never reach the NotFound
state. Update useAsset and/or the post-detail route logic to detect a 404
separately from other errors, then render NotFound for absent posts while
keeping the existing retry message for non-404 failures; use the existing
isError, asset, and NotFound branches in post-detail.tsx to wire this
distinction in.
In `@apps/web/src/routes/posts.tsx`:
- Around line 131-148: The posts page can end up on an out-of-range page when
server data shrinks, causing the “No posts yet” empty state and no active
pagination item. Update the state handling in posts.tsx around the page/data
loading logic so that when `pageCount` from the server is less than the current
page, the page is clamped back to the last valid page before rendering. Use the
existing `posts` route component and its pagination/data-fetch flow to detect
this in the same place that computes `pageCount` and `data.assets`.
In `@scripts/seed.ts`:
- Around line 106-125: The asset generator in seed.ts can only produce 1,800
distinct images because SHAPES and the HSL color cycle repeat, causing
core.assetService.create() to dedupe repeated bytes on larger runs. Update the
generation logic in the loop that builds bytes so each image includes a per-item
nonce (for example, embed i into the PNG payload via a metadata chunk) while
keeping the existing solidPng and hslToRgb flow, ensuring every iteration
produces unique bytes for any count.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 2d2c6cf4-402e-4b1f-aaab-a6344a7bf9c1
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (19)
.gitignoreapps/api/package.jsonapps/api/src/env-config.tsapps/api/src/index.tsapps/api/src/server.tsapps/api/test/env-config.test.tsapps/api/test/server.test.tsapps/web/package.jsonapps/web/src/index.tsapps/web/src/index.tsxapps/web/src/lib/api.tsapps/web/src/lib/assets.tsapps/web/src/lib/post-fixtures.tsapps/web/src/lib/query.tsapps/web/src/routes/post-detail.tsxapps/web/src/routes/posts.tsxpackage.jsonscripts/seed.tstsconfig.json
💤 Files with no reviewable changes (1)
- apps/web/src/lib/post-fixtures.ts
Apply the 7 findings from the full review of the live-gallery PR:
- web: `useAsset` maps an API 404 to `null` instead of throwing, so the
detail page shows its "not found" state for missing/deleted posts rather
than the generic error/retry UI (Major).
- web: validate the detail route id as plain decimal digits + a safe integer
(`Number("1e2")`/`"0x10"` would otherwise fetch a different asset).
- web: clamp the posts page back into range when the server's `pageCount`
shrinks (deletions), avoiding a stuck "No posts yet" with no active page.
- api: cap `/assets/:id` and `/assets/:id/file` ids at `Number.MAX_SAFE_INTEGER`
so oversized path values can't round before lookup.
- chore: also gitignore `/apps/api/storage/` (STORAGE_ROOT resolves from cwd);
kept anchored so it never shadows the `packages/storage` source package.
- seed: embed a per-image `tEXt` nonce so byte streams stay unique beyond the
1,800-image shape/hue cycle, letting large `count` runs create real assets
instead of deduping.
Commit 89dcc0a (bot-reviewed) is left untouched; these land on top.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/api/test/server.test.ts (1)
240-243: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd a regression test for the safe-integer ceiling.
This suite checks non-numeric ids, but not the
Number.MAX_SAFE_INTEGERguard added inserver.ts. A9007199254740993case would lock in the overflow protection that motivated the validator change.Suggested test
it("rejects a non-numeric id with 422", async () => { const res = await request("/api/v1/assets/abc"); expect(res.status).toBe(422); }); + + it("rejects an id above Number.MAX_SAFE_INTEGER with 422", async () => { + const res = await request("/api/v1/assets/9007199254740993"); + expect(res.status).toBe(422); + }); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/api/test/server.test.ts` around lines 240 - 243, Add a regression test in server.test.ts for the Number.MAX_SAFE_INTEGER validator path covered by server.ts. Extend the existing asset id validation suite with a request to /api/v1/assets/9007199254740993 and assert it returns 422, mirroring the non-numeric id test so the safe-integer ceiling behavior stays locked in.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/web/src/index.ts`:
- Around line 29-35: The proxied `/api/*` handler currently relies on Bun’s
default fetch timeout, so a stalled upstream can keep the request open too long.
Update the route in `apps/web/src/index.ts` to use `AbortSignal.timeout(...)`
when calling `fetch` through the existing `Request` construction, and handle the
abort case by returning a 504 instead of waiting for the default network
timeout. Keep the change localized to the `/api/*` proxy logic so the fast-fail
behavior applies only to this upstream API path.
In `@apps/web/src/routes/posts.tsx`:
- Around line 146-163: The asset rendering flow in posts.tsx assumes metadata
means the file is present, but /assets/:id/file can still 404 and currently
shows broken media. Update the shared asset file-loading path used by the
thumbnail Link/img rendering and the detail-page image/download flow so missing
bytes are handled gracefully, either by surfacing file availability in the asset
DTO or by adding a reusable fallback around assetFileUrl. Make sure the relevant
asset rendering logic in the posts route and the matching detail view both gate
on file availability instead of treating every metadata row as renderable.
In `@scripts/seed.ts`:
- Around line 9-10: The seed script’s default storage path is inconsistent with
the API-served root, so default seeding can write to a location the API won’t
read. Update the fallback used in the seed setup around createCore so it
defaults to the same data/storage root documented for the API, and keep the
filesystem provider pointed at that shared storage path.
---
Nitpick comments:
In `@apps/api/test/server.test.ts`:
- Around line 240-243: Add a regression test in server.test.ts for the
Number.MAX_SAFE_INTEGER validator path covered by server.ts. Extend the existing
asset id validation suite with a request to /api/v1/assets/9007199254740993 and
assert it returns 422, mirroring the non-numeric id test so the safe-integer
ceiling behavior stays locked in.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 5860620a-5e7b-4d21-b88f-a5c130c3c2b3
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (19)
.gitignoreapps/api/package.jsonapps/api/src/env-config.tsapps/api/src/index.tsapps/api/src/server.tsapps/api/test/env-config.test.tsapps/api/test/server.test.tsapps/web/package.jsonapps/web/src/index.tsapps/web/src/index.tsxapps/web/src/lib/api.tsapps/web/src/lib/assets.tsapps/web/src/lib/post-fixtures.tsapps/web/src/lib/query.tsapps/web/src/routes/post-detail.tsxapps/web/src/routes/posts.tsxpackage.jsonscripts/seed.tstsconfig.json
💤 Files with no reviewable changes (1)
- apps/web/src/lib/post-fixtures.ts
Three findings from the full re-review: - web: cap the dev `/api/*` proxy with `AbortSignal.timeout` (2 min) so a stalled upstream fails fast with a 504 instead of riding Bun's ~5-min default; connect/transport failures stay 502. Dev-only proxy (prod serves the SPA from the API directly), so the timeout is generous enough not to abort legitimate dev uploads. - web: add a shared `AssetImage` that falls back to an "unavailable" placeholder when `/assets/:id/file` 404s (a row can outlive its bytes), used by both the gallery grid and the detail view instead of a raw <img> that renders the broken-image glyph (Major). - seed: correct the stale docstring to `storage/` (the API's STORAGE_ROOT default). The code already defaulted to "storage"; CodeRabbit's suggested change to "data/storage" is declined — that's the root-owned Docker bind-mount path (EACCES) the API does not use. Doc was wrong, not the code. Lands on top of bot-reviewed 6016207 (left untouched). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/api/test/server.test.ts (1)
240-245: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a regression test for ids above
Number.MAX_SAFE_INTEGER.The new schema cap in
apps/api/src/server.tsLines 189-190 and 204-205 is the actual overflow fix, but this block only covers non-numeric input. A422case for something like/api/v1/assets/9007199254740992would keep that boundary from regressing silently.Suggested test
it("rejects a non-numeric id with 422", async () => { const res = await request("/api/v1/assets/abc"); expect(res.status).toBe(422); }); + + it("rejects an id above MAX_SAFE_INTEGER with 422", async () => { + const res = await request("/api/v1/assets/9007199254740992"); + expect(res.status).toBe(422); + }); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/api/test/server.test.ts` around lines 240 - 245, Add a regression test in server.test.ts alongside the existing non-numeric id case to cover an asset id above Number.MAX_SAFE_INTEGER, using request("/api/v1/assets/9007199254740992") and asserting a 422 response. This should exercise the same API route behavior as the current "rejects a non-numeric id with 422" test and protect the server.ts schema cap from regressing.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/web/src/components/asset-image.tsx`:
- Line 1: The AssetImage component is keeping its error state across different
src values, so a failed image never retries when the same instance is reused for
another asset. Update AssetImage to clear the load-failure state whenever the
src prop changes, likely by resetting the state in an effect tied to src or by
keying the rendered image/placeholder logic off src. Make sure the
retry/placeholder behavior in the AssetImage render path reflects the current
src instead of a previous failure.
In `@apps/web/src/index.ts`:
- Line 12: Normalize the upstream base URL used by the request proxy so a
trailing slash in API_TARGET cannot produce a double-slash path. Update the
apiTarget initialization in index.ts, and make the request-forwarding logic that
builds the /api/... URL use the normalized value (or URL composition) so the
route is always joined cleanly regardless of environment configuration.
In `@apps/web/src/routes/posts.tsx`:
- Around line 158-163: The grid in the posts route is using the full-size asset
endpoint via AssetImage with assetFileUrl(asset.id), which can load original
bytes for every tile. Update the gallery thumbnail rendering to use a
preview/resized image source instead of the original file endpoint, and keep
assetFileUrl(asset.id) only for the detail/download flow. Use the existing
AssetImage usage in the posts grid to switch the src to a dedicated preview URL
or helper so thumbnails are lightweight.
---
Nitpick comments:
In `@apps/api/test/server.test.ts`:
- Around line 240-245: Add a regression test in server.test.ts alongside the
existing non-numeric id case to cover an asset id above Number.MAX_SAFE_INTEGER,
using request("/api/v1/assets/9007199254740992") and asserting a 422 response.
This should exercise the same API route behavior as the current "rejects a
non-numeric id with 422" test and protect the server.ts schema cap from
regressing.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 92136aff-ce13-44f7-ab26-afee2b4c5e60
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (20)
.gitignoreapps/api/package.jsonapps/api/src/env-config.tsapps/api/src/index.tsapps/api/src/server.tsapps/api/test/env-config.test.tsapps/api/test/server.test.tsapps/web/package.jsonapps/web/src/components/asset-image.tsxapps/web/src/index.tsapps/web/src/index.tsxapps/web/src/lib/api.tsapps/web/src/lib/assets.tsapps/web/src/lib/post-fixtures.tsapps/web/src/lib/query.tsapps/web/src/routes/post-detail.tsxapps/web/src/routes/posts.tsxpackage.jsonscripts/seed.tstsconfig.json
💤 Files with no reviewable changes (1)
- apps/web/src/lib/post-fixtures.ts
…lash
- web: AssetImage resets its `failed` state when `src` changes, so a reused
instance retries the new asset instead of staying on the placeholder.
- web: strip a trailing slash from `API_TARGET` so the dev proxy can't build
`//api/...` (some upstreams route that differently).
The grid full-resolution-thumbnail finding (preview-sized source) is deferred
to a dedicated thumbnail thrust — it needs an async resize/preview pipeline,
which CLAUDE.md scopes as future work ("Generate thumbnails asynchronously").
Lands on top of bot-reviewed 296fabb (left untouched).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
@coderabbitai review |
✅ Action performedReview finished.
|
Live gallery — frontend ↔ API (thrust #2)
Uploads now render on screen. The grid + detail page are backed entirely by the live API via Eden Treaty + TanStack Query (Model A: one origin, no CORS).
API
GET /api/v1/assets/:id— single-asset metadata (deep links / detail page); exportsAssetDto.Web
lib/api.ts):treaty<App>(window.location.origin)— the only way the frontend talks to the API (neverfetch).unwraphelper narrows the global error-envelope out ofdata.lib/query.ts,lib/assets.ts):useAssetsPage/useAssethooks; Eden is the transport, TanStack owns cache + loading/error./:id/file, real pagination, loading/empty/error states. Staticpost-fixtures.tsdeleted./api/*→ API (502 on upstream down; startup log redacts any credentials).aria-pressedon layout toggles,aria-currenton the active page.Seed
scripts/seed.ts(bun run seed [n]) generates varied colour PNGs through the real upload service — verified locally: 18 assets, 18 content-addressed files.Try it
Validation
typecheck 0 · 105 tests · boundaries 0 · CLI-pre-reviewed (8 findings fixed: split error vs not-found, redacted proxy log, proxy 502, a11y, page guard, seed arg validation, simplified
unwrap). One CLI "critical" (duplicateconst) was a false positive — verified single declaration per block; compiles + tests pass.🤖 Generated with Claude Code
Summary by CodeRabbit
GET /api/v1/assets/:idfor single-asset metadata./api/*reverse proxy to a configurable backend target with clear timeout/unavailable responses and sanitized logging.:idvalidation for safer routing and consistent not-found behavior./storage.