Skip to content

refactor(webapp): simplify ResumeRefreshService — delegate visibilitychange to Supabase + replace 12s watchdog with instant reload - #415

Merged
neogenz merged 5 commits into
previewfrom
refactor/simplify-resume-refresh-via-supabase-2-71
May 4, 2026
Merged

neogenz merged 5 commits into
previewfrom
refactor/simplify-resume-refresh-via-supabase-2-71

Conversation

@neogenz

@neogenz neogenz commented Apr 30, 2026

Copy link
Copy Markdown
Owner

Summary

Two-step simplification of ResumeRefreshService, the iOS Safari bfcache failsafe added in #414.

Step 1 — Delegate visibilitychange to Supabase auth-js (>= 2.71)

The Supabase JS SDK ships a native visibilitychange listener (auth-js@2.71.1 via @supabase/supabase-js@^2.56.0) that calls the session recovery path on tab foreground. Removed the duplicated visibility + pagehide tracking + 15-min long-background heuristic — Pulpe now only owns the surfaces the SDK does NOT cover: pageshow.persisted (bfcache) and document.wasDiscarded (low-memory tab discard).

Bumped declared @supabase/supabase-js floor from ^2.49.10 to ^2.56.0 to make the auth-js >= 2.71 requirement explicit (lockfile already at 2.56.0).

Step 2 — Replace 12s watchdog with instant reload on hung-fetch

WebKit silently aborts in-flight fetch() calls when a tab enters bfcache (webkit.org/b/282506). If the user backgrounds the app DURING the initial getSession(), the Promise never resolves and AuthStore.isLoading() stays true forever.

Previous code queued the resume reason and waited 12 seconds before reloading. That wait was theater — the Promise was already dead at bfcache enter, no amount of patience would unblock it. Detect isLoading=true at pageshow and reload immediately. Cooldown (60s sessionStorage) still protects against reload loops.

Why now

  • Supabase shipped the visibility listener fix (supabase-js#2228, April 2025) — large parts of the original service became redundant.
  • Recent research (April 2026) confirms iOS Safari app-switch restore still fires only pageshow.persisted, not visibilitychange (Flarum#4588) — so we still need our own bfcache surface.
  • The 12s wait could not actually rescue the hung Promise — only a reload can. Removing the delay improves perceived recovery time without weakening the failsafe.

Diff

~225 net lines removed across 2 commits:

  • d560bfba7 refactor(webapp): replace 12s resume watchdog with instant reload on hung-fetch
  • 7d385f7e1 refactor(webapp): delegate visibilitychange to Supabase auth-js + collapse pending state

Files touched:

  • frontend/projects/webapp/src/app/core/lifecycle/resume-refresh.service.ts
  • frontend/projects/webapp/src/app/core/lifecycle/resume-refresh.service.spec.ts
  • frontend/package.json
  • pnpm-lock.yaml

Behavior changes

Scenario Before After
Cold load OK + bfcache resume + auth ready Soft refresh (cache invalidate + userSettings reload) Soft refresh (unchanged)
Cold load interrupted + bfcache + isLoading=true Wait 12s → reload Instant reload
User on /welcome (unauthenticated route) No-op No-op
Long background ≥ 15min Custom visibility listener fired refresh Supabase SDK handles natively
Cooldown active Block reload, splash hide fallback Block reload (unchanged)

Safety nets surviving

  1. pageshow.persisted listener (bfcache) — Pulpe-owned.
  2. document.wasDiscarded (low-memory) — Pulpe-owned.
  3. Splash 15s watchdog (cold-load) — unchanged, still calls forceReloadOnSplashTimeout().
  4. Cooldown 60s (sessionStorage) — protects all reload paths.
  5. Soft-refresh failure → hard reload — unchanged.

Test plan

  • pnpm quality (typecheck + lint + format) — clean
  • pnpm test — 1874/1874 green (the 12s timer test was removed; 2 new instant-reload tests added)
  • Manual iOS Safari: background app 30+ min, lock phone, reopen — app should soft-refresh or single forced reload if isLoading=true at pageshow
  • Manual iOS Safari: app-switch out then immediately back — should soft-refresh (no reload)
  • Throttle network, cold load: splash auto-reloads at 15s if auth still loading

neogenz added 2 commits April 30, 2026 20:41
…lapse pending state

Supabase auth-js >= 2.71 ships a native visibilitychange listener that calls
the session recovery path on resume. Removes the duplicated visibility +
pagehide tracking from ResumeRefreshService. Service now owns only the
surfaces the SDK does not cover: pageshow.persisted (bfcache) and
document.wasDiscarded (low-memory tab discard), plus Pulpe-specific cache
invalidation and userSettings reload.

Also collapses #pendingReason + #loadingTimeoutId into a single #pending
struct so the watchdog state is set/cleared atomically, and bumps the
declared @supabase/supabase-js floor to ^2.56.0 to make the auth-js >= 2.71
requirement explicit (lockfile already at 2.56.0).

~100 lines removed. All 1875 frontend tests still green.
…hung-fetch

WebKit silently aborts in-flight fetch on bfcache enter (webkit.org/b/282506).
If the user backgrounds the app DURING the initial getSession() call, the
Promise never resolves: AuthStore.isLoading stays true forever. Previous
implementation queued the resume reason and waited 12s before reloading.

That wait was theater — the Promise was already dead, no amount of patience
would unblock it. Detect isLoading=true at pageshow and reload immediately.
Cooldown (60s sessionStorage) still protects against reload loops.

Removes:
- effect()-based queue-and-drain
- RESUME_LOADING_TIMEOUT_MS (12s) + setTimeout watchdog
- #pending struct + #armPending + #drainPendingReasonOnAuthReady
- redundant #shouldRefreshOnResume() re-check in #runSoftRefresh
- duplicated logger.warn on hung-fetch path (single warn via #triggerHardReload)

Adds:
- 'pageshow_hung_fetch' to ResumeTriggerReason enum (single source of cause)
- two new tests: instant reload on isLoading=true, no-op on non-protected route
@vercel

vercel Bot commented Apr 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
pulpe-frontend Ready Ready Preview, Comment May 4, 2026 8:06pm
pulpe-landing Ready Ready Preview, Comment May 4, 2026 8:06pm

@supabase

supabase Bot commented Apr 30, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project qhhlloqisgzwcsrbdppn because there are no changes detected in backend-nest/supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

if (this.#authStore.isLoading()) {
this.#triggerHardReload('pageshow_hung_fetch');
return;
}

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.

[IMPORTANT] Fausse positive sur wasDiscarded : le check isLoading() s'applique aux deux cas alors que le bug WebKit est bfcache-exclusif (confiance: 82%)

Le hung-fetch est causé par WebKit qui annule silencieusement les fetch() en-vol lors de l'entrée en bfcache (webkit.org/b/282506). Ce bug ne s'applique qu'à event.persisted === true.

Pour un tab discardé (wasDiscarded=true, persisted=false), la page est reconstruite à zéro : isLoading()=true est l'état initial normal, pas un fetch suspendu. Angular bootstrap généralement avant le pageshow (le listener est donc déjà enregistré quand pageshow fire), ce qui signifie que ce chemin est atteignable en production.

Impact : sur un tab discardé sur une route protégée, l'auth démarre normalement (isLoading=true) → le service déclenche un hard reload inutile → la page se recharge une fois (limitée par le cooldown à 60s).

Suggested change
}
if (event.persisted && this.#authStore.isLoading()) {
this.#triggerHardReload('pageshow_hung_fetch');
return;
}

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d560bfba7c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +154 to +156
if (this.#authStore.isLoading()) {
this.#triggerHardReload('pageshow_hung_fetch');
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Gate hung-fetch reload to bfcache restores only

This hard-reload path now runs whenever isLoading() is true for both pageshow.persisted and document.wasDiscarded resumes, but wasDiscarded restores are cold reloads where auth booting is expected (not the WebKit hung-fetch condition). In that case this causes an unnecessary full reload, and if cooldown blocks it, the resume trigger is dropped entirely. Restricting this branch to the bfcache case (event.persisted) avoids false-positive reloads on discarded-tab restores.

Useful? React with 👍 / 👎.

Comment on lines 150 to 151
if (!event.persisted && !wasDiscarded) {
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve app-level refresh on non-bfcache foreground resumes

By removing the visibility/pagehide path, resume refresh now only runs on pageshow persisted/discarded signals. Regular foregrounding (tab/app switch without bfcache/discard) no longer triggers this service, so its app-level recovery work (budget/templates cache invalidation and userSettings reload) is skipped even after long background periods. Supabase’s visibility handler can refresh auth tokens, but it does not execute these Pulpe-specific refresh steps.

Useful? React with 👍 / 👎.

@@ -130,38 +119,6 @@ describe('ResumeRefreshService', () => {
expect(reloadSpy).not.toHaveBeenCalled();
});

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.

[SUGGESTION] Test manquant pour wasDiscarded=true + isLoading=true (confiance: 90%)

Le test existant à la ligne 107 couvre wasDiscarded=true avec isLoading=false (comportement happy path). Mais il n'y a pas de test pour le cas où auth est encore en cours de chargement au moment du pageshow discardé — c'est exactement le scénario de la fausse positive décrite sur le service.

Ajouter ce test permettrait de documenter et verrouiller le comportement attendu (soft refresh vs hard reload) :

it('should perform soft refresh when document was discarded even if auth is still initializing', async () => {
  Object.defineProperty(document, 'wasDiscarded', {
    configurable: true,
    value: true,
  });
  isLoadingSignal.set(true);

  dispatchPageShow(false);
  await Promise.resolve();

  // wasDiscarded + isLoading=true is NOT a hung-fetch: auth is just starting fresh
  expect(reloadSpy).not.toHaveBeenCalled();
  expect(mockAuthSession.refreshSession).not.toHaveBeenCalled();
});

@claude

claude Bot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

Review PR #415

Résumé : 0 bloquant - 1 important - 1 suggestion

Importants

  • resume-refresh.service.ts:154 — Fausse positive hung-fetch sur wasDiscarded : le check isLoading() s'applique aux deux branches (bfcache + tab discard) alors que le bug WebKit est bfcache-exclusif. Pour un tab discardé, isLoading=true est l'état initial normal — déclenche un hard reload inutile (confiance: 82%)

Suggestions

  • resume-refresh.service.spec.ts:120 — Test manquant pour wasDiscarded=true + isLoading=true qui documenterait le comportement attendu et verrouillerait la correction (confiance: 90%)

Points positifs

  • auth-js 2.71.1 confirmé dans le lockfile : la délégation de visibilitychange au SDK Supabase est valide — le refactoring repose sur une base solide
  • Suppression du state complexe (#pendingReason, #loadingTimeoutId, #lastHiddenAt, effect()) : le service est significativement plus simple et plus lisible
  • JSDoc très précis sur la séparation des responsabilités vs Supabase SDK — pageshow.persisted + wasDiscarded vs visibilitychange
  • La logique hung-fetch pour event.persisted=true est correcte et bien couverte par les tests
  • Nouvelle architecture synchrone (reload immédiat vs queue asynchrone) élimine toute la complexité de drain + watchdog timer

Verdict : CHANGES REQUESTED

@github-actions

github-actions Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright E2E Tests

12 tests  ±0   12 ✅ ±0   41s ⏱️ -1s
 3 suites ±0    0 💤 ±0 
 1 files   ±0    0 ❌ ±0 

Results for commit 8282ada. ± Comparison against base commit 489ba09.

♻️ This comment has been updated with latest results.

WebKit silently aborts in-flight fetch on bfcache enter
(webkit.org/b/282506) — this affects event.persisted=true only.
On document.wasDiscarded=true the page is rebuilt from scratch
(cold restart, fresh JS state), so AuthStore.isLoading()=true is
the normal initial bootstrap state, not a hung Promise.

Split #onPageShow so the hung-fetch failsafe only fires on
bfcache. Discarded tabs fall through to the soft refresh path,
which self-gates via #hasLiveSession() during bootstrap.
@neogenz
neogenz merged commit a4b2cd4 into preview May 4, 2026
16 of 17 checks passed
@neogenz
neogenz deleted the refactor/simplify-resume-refresh-via-supabase-2-71 branch May 4, 2026 20:15

This branch was successfully deployed

2 active deployments
Preview – pulpe-landing — 8282ada8 Deployed May 4, 2026 by vercel[bot]
Preview – pulpe-frontend — 8282ada8 Deployed May 4, 2026 by vercel[bot]
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.

1 participant