Skip to content

fix(web): recover from stale content-hashed chunks after deploys - #434

Closed
RXWatcher wants to merge 3 commits into
Silo-Server:mainfrom
RXWatcher:fix/spa-stale-chunk-recovery
Closed

RXWatcher wants to merge 3 commits into
Silo-Server:mainfrom
RXWatcher:fix/spa-stale-chunk-recovery

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Every deploy changes the content-hashed /assets/ chunk names. An open tab from before the deploy fails its next lazy navigation with "Failed to fetch dynamically imported module" — made worse by the SPA fallback answering the missing chunk URL with 200 + index.html, so the browser rejects an HTML document as a JS module instead of seeing a clean miss.

Two fixes, observed and verified on a production install today:

  • Server: /assets/ paths that don't resolve to a bundled file now return 404 instead of falling through to the SPA shell. Fingerprinted assets are immutable; an unknown one is a stale reference, not an app route.
  • Web: handle Vite's vite:preloadError by reloading once onto the current build, guarded to at most one reload per minute so a genuinely broken deploy cannot reload-loop.

Tests

  • go test ./internal/server (new: TestFrontendHandlerReturns404ForMissingAssets)
  • pnpm exec vitest run src/lib/reloadOnPreloadError.test.ts (3 cases: reload, loop guard, guard expiry)
  • Live-verified: stale chunk URL now 404s; SPA routes still serve the shell with CSP intact

AI-use disclosure

Implemented with Claude Code (TDD).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Missing frontend asset files now return a clear 404 response instead of incorrectly serving the application shell.
    • Added automatic page recovery when a dynamically loaded application component fails after an update.
    • Recovery is limited to once per minute to prevent repeated reload loops.
    • Normal application routes continue to load as expected.

RXWatcher and others added 2 commits July 20, 2026 13:57
A /assets/ chunk from a previous build no longer exists after a deploy;
serving the SPA shell at that URL makes the browser fail dynamic imports
on a text/html module. Exclude /assets/ from the SPA fallback so the
miss surfaces as a 404 the client can react to.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
After a deploy, an open tab still references the previous build's
content-hashed chunks and the first lazy navigation dies with "Failed to
fetch dynamically imported module". Handle Vite's vite:preloadError by
reloading onto the current build, guarded to at most one reload per
minute so a persistently missing chunk cannot reload-loop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@RXWatcher, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 47 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a84d1b0d-dec0-49fe-b99a-389730eb7ac4

📥 Commits

Reviewing files that changed from the base of the PR and between b2a0367 and 43249aa.

📒 Files selected for processing (2)
  • web/src/lib/reloadOnPreloadError.test.ts
  • web/src/lib/reloadOnPreloadError.ts
📝 Walkthrough

Walkthrough

Missing /assets/ requests now return 404 instead of the SPA shell. A frontend preload-error handler reloads the page once per 60-second session-storage window and is installed before React mounts.

Changes

Asset failure recovery

Layer / File(s) Summary
Missing asset response
internal/server/frontend.go, internal/server/frontend_test.go
Missing /assets/ requests return 404 responses, while non-asset SPA routes continue serving HTML.
Guarded preload reload
web/src/lib/reloadOnPreloadError.ts, web/src/lib/reloadOnPreloadError.test.ts
Vite preload errors trigger a reload with a 60-second session-storage guard, tested for initial reload, suppression, and expiry.
Startup handler installation
web/src/main.tsx
The preload-error listener is installed before the React root is resolved and rendered.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant frontendHandler.ServeHTTP
  participant installPreloadErrorReload
  participant sessionStorage
  participant window.location.reload
  Browser->>frontendHandler.ServeHTTP: Request missing /assets/ chunk
  frontendHandler.ServeHTTP-->>Browser: Return HTTP 404
  Browser->>installPreloadErrorReload: Dispatch vite:preloadError
  installPreloadErrorReload->>sessionStorage: Read reload guard timestamp
  installPreloadErrorReload->>sessionStorage: Store eligible reload timestamp
  installPreloadErrorReload->>window.location.reload: Reload page
Loading

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: recovering from stale hashed chunks after deploys.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
web/src/lib/reloadOnPreloadError.test.ts (1)

18-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prevent event listener leaks across tests.

Since window is shared across tests in Vitest, calling installPreloadErrorReload multiple times accumulates event listeners. While the mocked clocks and isolated storage happen to prevent the tests from interfering with each other right now, this state leakage makes the test suite brittle to future changes.

Consider updating installPreloadErrorReload to return a cleanup function, and invoking it in an afterEach block.

♻️ Proposed refactor for cleanup

Update the source in web/src/lib/reloadOnPreloadError.ts:

-export function installPreloadErrorReload(deps?: Partial<PreloadErrorReloadDeps>): void {
+export function installPreloadErrorReload(deps?: Partial<PreloadErrorReloadDeps>): () => void {
   const reload = deps?.reload ?? (() => window.location.reload());
   const now = deps?.now ?? Date.now;
   const getItem = deps?.getItem ?? ((k: string) => sessionStorage.getItem(k));
   const setItem = deps?.setItem ?? ((k: string, v: string) => sessionStorage.setItem(k, v));

-  window.addEventListener("vite:preloadError", (event) => {
+  const handler = (event: Event) => {
     const lastReloadAt = Number(getItem(GUARD_KEY) ?? 0);
     if (now() - lastReloadAt < GUARD_WINDOW_MS) {
       // We already reloaded moments ago and the chunk is still missing;
       // let the failure surface instead of reload-looping.
       return;
     }
     event.preventDefault();
     setItem(GUARD_KEY, String(now()));
     reload();
-  });
+  };
+
+  window.addEventListener("vite:preloadError", handler);
+  return () => window.removeEventListener("vite:preloadError", handler);
 }

Then, in the test file, capture and call the cleanups:

+import { afterEach } from "vitest";

 describe("installPreloadErrorReload", () => {
+  let cleanups: Array<() => void> = [];
+
+  afterEach(() => {
+    cleanups.forEach((cleanup) => cleanup());
+    cleanups = [];
+  });

   it("reloads when a dynamically imported chunk fails to load", () => {
     const { reload, deps } = harness(() => 1_000_000);
-    installPreloadErrorReload(deps);
+    cleanups.push(installPreloadErrorReload(deps));

     window.dispatchEvent(new Event("vite:preloadError"));
     expect(reload).toHaveBeenCalledTimes(1);
   });

   it("does not reload again within the loop-guard window", () => {
     let clock = 1_000_000;
     const { reload, deps } = harness(() => clock);

-    installPreloadErrorReload(deps);
+    cleanups.push(installPreloadErrorReload(deps));
     window.dispatchEvent(new Event("vite:preloadError"));
     expect(reload).toHaveBeenCalledTimes(1);

     // Post-reload page still hits the error seconds later: give up instead
     // of reload-looping.
     clock += 5_000;
-    installPreloadErrorReload(deps);
+    cleanups.push(installPreloadErrorReload(deps));
     window.dispatchEvent(new Event("vite:preloadError"));
     expect(reload).toHaveBeenCalledTimes(1);
   });

   it("reloads again once the guard window has passed (a later deploy)", () => {
     let clock = 1_000_000;
     const { reload, deps } = harness(() => clock);

-    installPreloadErrorReload(deps);
+    cleanups.push(installPreloadErrorReload(deps));
     window.dispatchEvent(new Event("vite:preloadError"));
     expect(reload).toHaveBeenCalledTimes(1);

     clock += 10 * 60_000;
-    installPreloadErrorReload(deps);
+    cleanups.push(installPreloadErrorReload(deps));
     window.dispatchEvent(new Event("vite:preloadError"));
     expect(reload).toHaveBeenCalledTimes(2);
   });
 });
🤖 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 `@web/src/lib/reloadOnPreloadError.test.ts` around lines 18 - 56, Update
installPreloadErrorReload in reloadOnPreloadError.ts to return a cleanup
function that removes its registered window event listener. In the
installPreloadErrorReload tests, capture each returned cleanup and invoke it
from afterEach so listeners do not accumulate across tests.
🤖 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.

Nitpick comments:
In `@web/src/lib/reloadOnPreloadError.test.ts`:
- Around line 18-56: Update installPreloadErrorReload in reloadOnPreloadError.ts
to return a cleanup function that removes its registered window event listener.
In the installPreloadErrorReload tests, capture each returned cleanup and invoke
it from afterEach so listeners do not accumulate across tests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cfbce971-a6c2-4eba-9c6c-d82a307d7600

📥 Commits

Reviewing files that changed from the base of the PR and between 8044eb8 and b2a0367.

📒 Files selected for processing (5)
  • internal/server/frontend.go
  • internal/server/frontend_test.go
  • web/src/lib/reloadOnPreloadError.test.ts
  • web/src/lib/reloadOnPreloadError.ts
  • web/src/main.tsx

Review feedback: window is shared across vitest tests, so repeated
installs accumulated listeners. The installer now returns a remover and
the tests detach in afterEach.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants