Skip to content

fix(core): register the router hooks before the router installs - #19434

Merged
elevatebart merged 2 commits into
developfrom
elevate-bot/unsaved-changes-guard-registration
Sep 14, 2026
Merged

elevatebart merged 2 commits into
developfrom
elevate-bot/unsaved-changes-guard-registration

Conversation

@elevatebart

@elevatebart elevatebart commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🔗 Related Issue

None filed. Follow-up to a note @MilosPaunovic left reviewing #19424.

✨ Description

createUnsavedChanged and createEventsRouter both ran in initApp after app.use(router) and after the i18n and moment awaits, so neither was seen by the router's first navigation, for the reason #19424 fixed for the tenant guard: vue-router reads its hook lists once a navigation reaches the relevant phase, and by then those awaits have not resolved.

Both calls move above app.use(router), keeping their position after the other hooks so relative order is unchanged on every later navigation.

  • createUnsavedChanged (beforeEach) is a no-op on a cold start, since nothing is unsaved yet. It is the same footgun sitting one line over, and nothing in the file flagged it. Its confirmation message is now read when beforeunload fires rather than at setup, because app.use(i18n) has not run at the new call site and $t would be undefined.
  • createEventsRouter (afterEach) is not a no-op. It branches on from.matched.length === 0, which only ever holds for the first navigation, to attribute the landing page to document.referrer. Missing that hop drops the landing-page PAGE event and makes the branch unreachable. It takes useApiStore() at setup and nothing else, and pinia is installed well before the new call site, so it needs no deferral of the kind unsavedChange.ts needed.

An earlier version of this PR claimed afterEach sat outside the window, since afterGuards.list() is read when a navigation finishes. @MilosPaunovic showed the conclusion does not follow: the first navigation finishes during initApp's awaits, not after them.

📝 Additional Notes

Also writes the class of bug down in ui/AGENTS.md, since four separate things about initApp's hook wiring are non-obvious and none of them were recorded anywhere:

  • registration has to happen before the router installs, and why a synchronous registration after app.use(router) still works while one after an await does not;
  • afterEach is in the same window, because the first navigation can finish inside those awaits;
  • guards.beforeEach.bind(null, router) leaves a (router, to, from) guard at bound length 2 and so in return-value mode. A fourth parameter takes it to 3, which flips vue-router into next()-callback mode: the returned redirect is ignored and the navigation hangs, with no error;
  • there is a single beforeEach slot, which OSS can spend on tenantGuard only because its auth guard is a beforeResolve, and EE already spends on authGuard.

No test. The same argument as on #19424 applies: a timing test would pin vue-router's behaviour rather than this app's wiring, and would stay green if a call moved back down. The initApp contract test @MilosPaunovic proposed there would cover all of these at once, and is the one worth writing.

🎨 Frontend Checklist

  • Type checking passes (npm run check:types)
  • Code builds without errors (npm run build)
  • Unit tests pass (npm run test:unit, 2332 passed)
  • Translations are complete if en.json changed (not touched)
  • Screenshots or video recordings attached showing the UI changes

No screenshot: nothing visible changes. The user-visible difference is a landing-page analytics event that now gets emitted, which a screenshot cannot show.

Related PRs

Nine lives, but only one first navigation.

🤖 Generated with Claude Code

https://claude.ai/code/session_018uaa7WdWh538GESjnntTL6

createUnsavedChanged ran in initApp after app.use(router) and after the i18n and
moment awaits, so its beforeEach was missed by the router's first navigation, the
same way the tenant guard was in #19424. Nothing is unsaved on a cold start, so
this never bit, but the guard was silently absent for the one navigation it could
not cover.

The call moves above app.use(router). Its confirmation message is now read when
beforeunload fires rather than at setup, since app.use(i18n) has not run yet at
that point and $t would be undefined.

Also writes down what this class of bug costs, in ui/AGENTS.md: registration
before install, the bound-arity trap that flips vue-router into next() mode, and
initApp's single beforeEach slot.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018uaa7WdWh538GESjnntTL6
@github-actions

Copy link
Copy Markdown
Contributor

🐋 Docker image

ghcr.io/kestra-io/kestra-pr:19434
docker run --pull=always --rm -it -p 8080:8080 --user=root -v /var/run/docker.sock:/var/run/docker.sock -v /tmp:/tmp ghcr.io/kestra-io/kestra-pr:19434 server local

@MilosPaunovic MilosPaunovic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The change itself is correct and I verified it. Commenting rather than approving because of the guard it leaves behind, which I think belongs in this PR.

What I verified

Check Result
Diff scope 3 files, +17/-4, matches the description
npm run check:types passes
eslint on init.ts + unsavedChange.ts clean
Ordering claim holds: docId (init.ts:68), then guards.beforeEach (:85), then createUnsavedChanged (:106)
useUnsavedChangesStore() still binds yes, app.use(piniaStore) is at :63, well before the new call site
The $t deferral was needed yes, app.use(i18n) is at :143, the new call site is :106
"unsaved changed ?" resolves yes, ui/src/translations/en.json:686

1. createEventsRouter is affected by the same window

It registers an afterEach, which is read when the navigation finishes rather than when it starts, so it is not affected by the same window.

The first half is true, the conclusion does not follow. afterGuards.list() is read when the navigation finishes, but the first navigation finishes during initApp's awaits rather than after them. Registering an afterEach after one await Promise.resolve() plus one setTimeout(0) following app.use(router), the first navigation never reaches it: the handler recorded nothing while the router sat on the target route. Before the install, or synchronously after it, it fires. Same three-way result as the beforeEach case in #19424.

This matters more than the guard that did move. You are right that the unsaved-changes guard is a no-op on a cold start. createEventsRouter is not:

const isInitialNavigation = (from.matched?.length ?? 0) === 0
const referrerUrl = isInitialNavigation ? (document.referrer || undefined) : `${currentOrigin}${from.fullPath}`

from.matched.length === 0 only ever holds for the first navigation, START_LOCATION being the only route with no matched records. That branch exists specifically to attribute the landing page to document.referrer. If the afterEach misses navigation one, the landing-page PAGE event is never emitted and the branch is unreachable, silently.

I did not settle which side wins in a real browser, and that is rather the point: it is a race the code does not control, on a path with an explicit first-navigation branch. For calibration on direction, initApp awaits registerDesignSystemI18n, which loops over 11 *.locale.ts modules with the await inside the loop, so 11 sequential dynamic imports, plus the moment locale. Against that the first navigation needs one lazy route chunk plus beforeResolve's loadLoginConfig() call.

The fix looks like one line, hoisting createEventsRouter(app, router) next to createUnsavedChanged. I checked its dependencies so this is not a blind suggestion: it takes useApiStore() at setup and nothing else, pinia is installed at :63, and there is no i18n reference in stores/api.ts, utils/analytics/activation.ts or utils/posthog.ts, so it should need no deferral of the kind unsavedChange.ts needed.

2. The new AGENTS.md section omits the afterEach case

The "Register before the router installs" bullet explains beforeGuards.list() and stops. A reader following it would conclude what this description concluded, that afterEach sits outside the window. Since the section exists to stop this class of bug recurring, it is worth a sentence saying afterGuards.list() has the same window because the first navigation can finish inside it.

The arity and single-slot bullets are accurate as written.

3. Minor: the beforeunload message is dead text

Moving the read to fire time is correct, and it has a bonus you do not claim: it now picks up a locale changed after setup. But no browser has shown a custom beforeunload string since Chrome 51 and Firefox 44, so the value only matters for being non-empty so the generic dialog appears. Nothing is broken and the key resolves. If that string were a literal, the i18n coupling and this whole timing question would leave the file.

Backport

releases/v2.0.x (init.ts:164-165) and releases/v1.3.x (init.js:152-153) both have the two calls in the same late position, so both carry the same latent bug. As this stands the change is invisible at runtime, so a backport is optional. If createEventsRouter gets hoisted, the analytics loss becomes real and the backport is worth doing.

…s too

Review caught the description's claim wrong: afterGuards.list() is read when a
navigation finishes, but the first navigation can finish while initApp is still
awaiting, so an afterEach registered afterwards misses it exactly as a beforeEach
does.

This one is not a no-op. eventsRouter branches on from.matched.length === 0, true
only for the first navigation, to attribute the landing page to document.referrer;
missing that hop drops the landing-page event and makes the branch unreachable.

createEventsRouter moves up next to createUnsavedChanged. It takes useApiStore at
setup and nothing else, and pinia is installed well before the new call site, so
it needs no deferral. AGENTS.md now covers the afterEach case as well.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018uaa7WdWh538GESjnntTL6
@elevatebart elevatebart changed the title fix(core): register the unsaved-changes guard before the router installs fix(core): register the router hooks before the router installs Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

You are right, and the correction is in 85db87592. My "so it is not affected by the same window" was reasoning from where afterGuards.list() is read without checking when the first navigation finishes relative to the awaits, which is the only thing that matters.

1. createEventsRouter hoisted. I checked your dependency analysis rather than taking it on trust: no $t/useI18n/i18n reference anywhere in eventsRouter.ts, stores/api.ts, utils/analytics/activation.ts or utils/posthog.ts (the one document.title hit in api.ts is unrelated), and useApiStore() binds fine at the new call site with pinia installed at :63. No deferral needed, so the move is the whole change. The isInitialNavigation branch at eventsRouter.ts:41 is exactly as you describe, which is what makes this the half worth fixing: a no-op guard moving is housekeeping, a landing-page event that never fires is a real hole.

2. AGENTS.md. Added a paragraph to the same bullet: afterGuards.list() is read at navigation end, the first navigation can end inside initApp's awaits, so an afterEach registered afterwards misses it too, with eventsRouter's referrer attribution named as what it costs.

3. The beforeunload string. Agreed it is dead text on every current browser, and that a literal would take the i18n coupling and this timing question out of the file entirely. Leaving it alone here since it is a behaviour change to a user-facing string in a PR about registration order; happy to do it separately if you want it gone.

Backport: noted that both 2.0.x and 1.3.x carry the same late calls. Now that createEventsRouter moved, I agree it is worth doing rather than optional. Not doing it unasked, since 1.3.x needs the same re-implementation you flagged on #19424.

PR title and description updated; it is no longer only about the unsaved-changes guard. Re-requesting your review.


Generated by Claude Code

@MilosPaunovic MilosPaunovic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving. Two things still open, neither blocking this PR.

Verified on 85db8759: npm run check:types passes, eslint clean on init.ts, unsavedChange.ts and eventsRouter.ts, and the relative order is preserved (guards.afterEach at :97, the KestraRouterAfterEach dispatch at :100, then createEventsRouter at :107). The new AGENTS.md paragraph is accurate. CI was still mid-run when I looked.

1. The hoist does not finish the job on EE

initApp is shared, so this makes the first-navigation PAGE event fire on EE too. On EE it then lands in a buffer nothing drains.

apiStore.events() enqueues into PendingEventsBuffer when miscStore.configs is undefined. OSS closes that loop at ui/src/override/stores/misc.ts:51, where loadConfigs calls flushQueuedEvents(). EE replaces that store wholesale with ui-ee/src/override/stores/misc.ts, whose loadConfigs at :43 sets configs.value and returns, with no flush. There is no flushQueuedEvents reference anywhere in ui-ee/src.

And configs really is undefined at that point on EE: it is loaded in App.vue:169, which runs after app.mount(), which runs after router.isReady(), so after the first navigation has finished. authGuard:64 only loads it when requiredRouteFeature(...) returns something, which is not the general case.

The event then survives only if another events() call arrives while configs are ready, since sendEventNow is the only other flush trigger, and PendingEventsBuffer.prune() drops entries older than the maxAgeMs: 2 * 60 * 1000. A user who lands on a page and stays put for two minutes loses exactly the event this PR exists to recover.

One line in EE, mirroring OSS. I did not find a companion PR open for it.

2. The beforeunload message is still dead text

Unchanged from the last round and entirely your call. No browser has shown a custom beforeunload string since Chrome 51 and Firefox 44, so the $t round trip only exists to make returnValue non-empty. A literal would take the i18n coupling, and the timing question, out of the file.

Backport

Worth revisiting now that this is not invisible. Last round I said a backport was optional while the change had no runtime effect; with createEventsRouter hoisted the lost landing-page event is real, so releases/v2.0.x (init.ts:164-165) and releases/v1.3.x (init.js:152-153) are both worth doing. Each carries the two calls in the same late position.

@elevatebart
elevatebart merged commit a430c3b into develop Sep 14, 2026
17 checks passed
@elevatebart
elevatebart deleted the elevate-bot/unsaved-changes-guard-registration branch September 14, 2026 14:01
@github-project-automation github-project-automation Bot moved this from To review to Done in Pull Requests Sep 14, 2026
elevatebart added a commit that referenced this pull request Nov 18, 2026
…port #19434) (#22867)

createUnsavedChanged and createEventsRouter both ran in initApp after
app.use(router) and after the i18n and moment awaits, so neither was seen by the
router's first navigation: vue-router reads its hook lists once a navigation
reaches the relevant phase, and by then those awaits have not resolved.

The unsaved-changes beforeEach is a no-op on a cold start; the analytics
afterEach is not. eventsRouter branches on from.matched.length === 0, true only
for the first navigation, to attribute the landing page to document.referrer, so
missing that hop dropped the landing-page event and made the branch unreachable.

Both calls move above app.use(router). The beforeunload message is now read when
the event fires, since app.use(i18n) has not run at the new call site.

ui/AGENTS.md records the class of bug: registration before install, afterEach
being in the same window, the bound-arity trap that flips vue-router into next()
mode, and initApp's single beforeEach slot.

(cherry picked from commit a430c3b)


Claude-Session: https://claude.ai/code/session_01HaCc1WQPzWtUceWN7H857T

Co-authored-by: Claude Opus 5.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

Archived in project

Development

Successfully merging this pull request may close these issues.

3 participants