Skip to content

fix(embedded-sdk): re-authenticate the iframe after a navigation internal to the dashboard - #44470

Merged
rusackas merged 4 commits into
apache:masterfrom
chadek:fix/embedded-sdk-internal-navigation
Sep 29, 2026
Merged

rusackas merged 4 commits into
apache:masterfrom
chadek:fix/embedded-sdk-internal-navigation

Conversation

@chadek

@chadek chadek commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Fixes #44468.

The iframe's load listener is registered before iframe.src, so it fires on every load, reloads included, and opens a fresh MessageChannel each time — but it only returns that channel through resolve() of a promise that is already settled from the second load onwards. Nobody keeps the new port1, so a dashboard that navigates itself (tab link, link in a Markdown chart, drill-down) leaves a blank frame: the new document waits for a guest token on a channel whose other end is gone, while ourPort keeps talking to the document that disappeared. #39860 already made the embedded page tolerate a second port transfer handshake; this completes the host half.

A Connection bundles a port with everything scoped to the document behind it — its switchboard, the get calls still awaiting a reply, and whether it has been handed a token. The SDK holds exactly one, and a load replaces it.

  • connect(iframe) is extracted from the listener: it opens the channel, transfers the port, constructs and starts the Switchboard, and replays the host-defined methods — a reloaded document has never heard of them. MessagePort queues what arrives before start(), so emitting the token right after the handshake is safe; that is already the property the first load relies on.
  • The accessors go through portGet, which scopes a call to the connection it was issued on. A get still in flight when the document leaves is rejected with PortClosedError instead of hanging forever on a reply that can no longer come, and the retired port is closed. Same for unmount().
  • A reload re-fetches a token rather than replaying the cached one: refresh happens 5s before expiry, so a reload landing just before it would hand the new page a token with seconds to live, and its GET /api/v1/me/roles/ would 401 into the "session interrupted" banner.
  • Not every navigation lands on the embedded page. A link in a Markdown chart can point at a plain Superset URL, or off site, and re-authenticating on any load minted guest tokens for documents that can never use one. The SDK probes the new document with a method the page deliberately does not implement: the Method "..." is not defined error every version replies with is itself the acknowledgement, and silence times out (5s) without a fetch, so the host's endpoint is not billed for a stray navigation.
  • refreshGuestToken carries a generation number and bails out if a reload superseded it, so a refresh left in flight cannot emit a stale token or arm a second timer. A token from a superseded cycle is still handed straight to the current document when that document has none — any valid token gets the page rendering, and holding it back would leave the frame blank for a full retry interval.
  • The initial fetch failing tears the iframe down only when no reload has taken over. Once a reload owns the token chain, that chain decides whether the embed lives; a rejection from a fetch nobody awaits any more must not take a dashboard that is already rendering away from the host.
  • Host-defined methods and host-pushed state survive a reload. resolvePermalinkUrl and observeDataMask are registered through defineHostMethod; the theme set with setThemeConfig/setThemeMode is replayed to the new document after its token, in the order a host applies it on a first load. A new realm holds none of it.
  • A load arriving after unmount() is ignored. On master it still opens a channel.

No API change beyond the new exported PortClosedError, no change to the host's token endpoint, to the Superset instance, or to how the iframe is mounted.

The two commits are split so the first is exactly what was reviewed and the second is the follow-up work plus the review responses.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A — no UI change in Superset itself. Before: clicking a link internal to an embedded dashboard leaves an empty frame until the host remounts the iframe. After: the target page renders with its data, in the theme the host had applied.

TESTING INSTRUCTIONS

Unit: cd superset-embedded-sdk && npm test — 27 tests pass. Ten cover this change:

test what it pins down
reload hands the reloaded document a new port and a fresh guest token the bug itself
reload replays the host's methods on the new port resolvePermalinkUrl, observeDataMask
reload re-applies the theme the host set, after the new token state replay, and its ordering
reload rejects the calls left unanswered on the abandoned port PortClosedError
unmount rejects the calls left unanswered, and closes the port same, on unmount
reload does not mint a token for a page that is not the embedded one the handshake probe
reload gives the new document the initial token when its own fetch fails superseded token still delivered
initial fetch failing after a reload leaves the recovered embed alone no teardown of a live embed
initial fetch failing with no reload tears the iframe down the teardown that should still happen
reload ignores a load that arrives after unmount no channel after unmount

Manual: embed a dashboard containing a link internal to the dashboard, click it, and check that the target page renders and that the network tab shows one call to the host's guest-token endpoint per reload, followed by the page's chart/data calls. Leave the page open longer than the guest token's lifetime and navigate again: the refresh follows the current port. Apply a theme from the host before navigating, and check it is still applied afterwards. Follow a link that leaves the embedded page and confirm no token is minted for it.

Cross-document: the unit tests mock MessageChannel and Switchboard, which is the layer these bugs live in. I also have a local test rig — a host app and a stand-in for the embedded page on two origins, driven in headless Chromium against the built UMD bundle over the real @superset-ui/switchboard — with 39 checks covering the above end to end, including both directions of the race between the initial fetch and a navigation during it. Split out into its own PR, #44608, so this one stays just the fix.

ADDITIONAL INFORMATION

  • Has associated issue: Embedded dashboard goes blank after a navigation internal to the dashboard #44468
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API — exports PortClosedError, which host calls interrupted by a navigation or an unmount now reject with instead of hanging
  • Removes existing feature or API

@bito-code-review

bito-code-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #42e7a3

Actionable Suggestions - 0
Additional Suggestions - 4
  • superset-embedded-sdk/src/index.test.ts - 3
    • New as any casts in mocks · Line 36-43
      The new `makeMockSwitchboard` factory ends in `as any` (line 42), and the new assertions at lines 259-260 add two more `as any` casts — AGENTS.md and `.cursor/rules/dev-standard.mdc` both mandate no `any` types. `as unknown as Switchboard` satisfies the mock's partial shape without `any`.
    • Dead unused setTimeout spy · Line 73-73
      This spy is created but never used: no `vi.mocked(setTimeout)` or assertion on it exists anywhere in the file (verified by grep), and without `mockImplementation` it just passes through to the real timer. Dead setup code that suggests timer control that isn't there — remove it.
    • Nested describe violates test rule · Line 225-225
      AGENTS.md mandates `test()` instead of `describe()` (avoid-nesting principle), but this adds a nested `describe("reauthentication after a navigation internal to the dashboard")` block. The grouping is already expressible in test names; hoisting the three tests keeps the suite consistent with the documented standard.
  • superset-embedded-sdk/src/index.ts - 1
    • Object injection sink via dynamic method names · Line 237-237
      The `hostMethods` object is used to store and replay host-defined methods. Using a plain object for dynamic method names can be an object injection sink (CWE-1321). Consider using a `Map` to avoid prototype pollution.
Review Details
  • Files reviewed - 2 · Commit Range: 07e30b5..07e30b5
    • superset-embedded-sdk/src/index.test.ts
    • superset-embedded-sdk/src/index.ts
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • Eslint (Linter) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@rusackas rusackas 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.

Heya @chadek, thanks for chasing this down, the generation counter is the right shape for keeping a reload from racing a refresh that's already in flight.

One thing I want to raise before this lands, though. If the internal navigation happens before the very first fetchGuestTokenWithTimeout() in the initial Promise.all settles, the reload's own refreshGuestToken() cycle can already authenticate the new document on its own, and then the stale initial fetch rejecting later still tears the whole thing down through the catch block (mountPoint.replaceChildren() plus rethrow). A dashboard that's already working gets wiped by a promise nobody cares about anymore. Related: if that same race goes the other way (the reload's attempt fails first and schedules a retry), the perfectly valid initial token gets thrown away by if (generation === 0) and we wait out the 10s retry for no reason. Neither felt like a one-line fix to me since that catch currently doubles as "build vs bail" for the whole function's return value, so wanted your take on the right shape for it rather than guessing at one myself.

Separately and non-blocking: the load listener now re-authenticates on any load, not just an internal one, so an iframe navigating away to something unrelated still fires off a guest token fetch. Probably fine, but flagging in case it's worth a guard.

Left a suggestion on the new tests too, we usually keep this file flat rather than nesting a describe().

Comment thread superset-embedded-sdk/src/index.test.ts Outdated
Comment on lines +225 to +314
describe("reauthentication after a navigation internal to the dashboard", () => {
const fakeToken = () => makeFakeJWT({ exp: Date.now() / 1000 + 300 });

// A link internal to the dashboard (side menu, tab, drill-down) navigates
// the iframe: same element, brand new document, which knows nothing of the
// channel the previous one was given.
function reload() {
mountPoint.querySelector("iframe")!.dispatchEvent(new Event("load"));
}

test("hands the reloaded document a new port and a fresh guest token", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
});
expect(mockFetchGuestToken).toHaveBeenCalledTimes(1);

reload();
// The token is fetched again rather than replayed from memory: the one in
// hand may be seconds from expiring, and the new page would take it
// straight into a 401.
await vi.waitFor(() =>
expect(switchboards[1].emit).toHaveBeenCalledWith("guestToken", {
guestToken: expect.any(String),
}),
);
expect(mockFetchGuestToken).toHaveBeenCalledTimes(2);

// A channel of its own, not the one the first document holds.
const constructions = vi.mocked(Switchboard).mock.calls;
expect(constructions).toHaveLength(2);
expect((constructions[1][0] as any).port).not.toBe(
(constructions[0][0] as any).port,
);
// Nothing is sent to the document that is gone.
expect(switchboards[0].emit).toHaveBeenCalledTimes(1);

dashboard.unmount();
});

test("replays the host's methods on the new port", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const observer = vi.fn();
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
resolvePermalinkUrl: ({ key }) => `https://host.example.com/p/${key}`,
});
dashboard.observeDataMask(observer);

reload();
await vi.waitFor(() =>
expect(mockFetchGuestToken).toHaveBeenCalledTimes(2),
);

// The new document has never heard of either method.
const defined = vi
.mocked(switchboards[1].defineMethod)
.mock.calls.map(([name]) => name);
expect(defined).toContain("resolvePermalinkUrl");
expect(defined).toContain("observeDataMask");

dashboard.unmount();
});

test("ignores a load that arrives after unmount", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
});
const iframe = mountPoint.querySelector("iframe")!;

dashboard.unmount();
iframe.dispatchEvent(new Event("load"));
await new Promise((resolve) => {
setTimeout(resolve, 0);
});

expect(vi.mocked(Switchboard).mock.calls).toHaveLength(1);
expect(mockFetchGuestToken).toHaveBeenCalledTimes(1);
});
});

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.

We usually keep this file flat (test() per case, no nesting) rather than wrapping related tests in a describe(). Same coverage, just flattened and renamed to match the setDataMask ...-style convention already used above.

Suggested change
describe("reauthentication after a navigation internal to the dashboard", () => {
const fakeToken = () => makeFakeJWT({ exp: Date.now() / 1000 + 300 });
// A link internal to the dashboard (side menu, tab, drill-down) navigates
// the iframe: same element, brand new document, which knows nothing of the
// channel the previous one was given.
function reload() {
mountPoint.querySelector("iframe")!.dispatchEvent(new Event("load"));
}
test("hands the reloaded document a new port and a fresh guest token", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
});
expect(mockFetchGuestToken).toHaveBeenCalledTimes(1);
reload();
// The token is fetched again rather than replayed from memory: the one in
// hand may be seconds from expiring, and the new page would take it
// straight into a 401.
await vi.waitFor(() =>
expect(switchboards[1].emit).toHaveBeenCalledWith("guestToken", {
guestToken: expect.any(String),
}),
);
expect(mockFetchGuestToken).toHaveBeenCalledTimes(2);
// A channel of its own, not the one the first document holds.
const constructions = vi.mocked(Switchboard).mock.calls;
expect(constructions).toHaveLength(2);
expect((constructions[1][0] as any).port).not.toBe(
(constructions[0][0] as any).port,
);
// Nothing is sent to the document that is gone.
expect(switchboards[0].emit).toHaveBeenCalledTimes(1);
dashboard.unmount();
});
test("replays the host's methods on the new port", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const observer = vi.fn();
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
resolvePermalinkUrl: ({ key }) => `https://host.example.com/p/${key}`,
});
dashboard.observeDataMask(observer);
reload();
await vi.waitFor(() =>
expect(mockFetchGuestToken).toHaveBeenCalledTimes(2),
);
// The new document has never heard of either method.
const defined = vi
.mocked(switchboards[1].defineMethod)
.mock.calls.map(([name]) => name);
expect(defined).toContain("resolvePermalinkUrl");
expect(defined).toContain("observeDataMask");
dashboard.unmount();
});
test("ignores a load that arrives after unmount", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
});
const iframe = mountPoint.querySelector("iframe")!;
dashboard.unmount();
iframe.dispatchEvent(new Event("load"));
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
expect(vi.mocked(Switchboard).mock.calls).toHaveLength(1);
expect(mockFetchGuestToken).toHaveBeenCalledTimes(1);
});
});
const fakeToken = () => makeFakeJWT({ exp: Date.now() / 1000 + 300 });
// A link internal to the dashboard (side menu, tab, drill-down) navigates
// the iframe: same element, brand new document, which knows nothing of the
// channel the previous one was given.
function reload() {
mountPoint.querySelector("iframe")!.dispatchEvent(new Event("load"));
}
test("reload hands the reloaded document a new port and a fresh guest token", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
});
expect(mockFetchGuestToken).toHaveBeenCalledTimes(1);
reload();
// The token is fetched again rather than replayed from memory: the one in
// hand may be seconds from expiring, and the new page would take it
// straight into a 401.
await vi.waitFor(() =>
expect(switchboards[1].emit).toHaveBeenCalledWith("guestToken", {
guestToken: expect.any(String),
}),
);
expect(mockFetchGuestToken).toHaveBeenCalledTimes(2);
// A channel of its own, not the one the first document holds.
const constructions = vi.mocked(Switchboard).mock.calls;
expect(constructions).toHaveLength(2);
expect((constructions[1][0] as any).port).not.toBe(
(constructions[0][0] as any).port,
);
// Nothing is sent to the document that is gone.
expect(switchboards[0].emit).toHaveBeenCalledTimes(1);
dashboard.unmount();
});
test("reload replays the host's methods on the new port", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const observer = vi.fn();
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
resolvePermalinkUrl: ({ key }) => `https://host.example.com/p/${key}`,
});
dashboard.observeDataMask(observer);
reload();
await vi.waitFor(() =>
expect(mockFetchGuestToken).toHaveBeenCalledTimes(2),
);
// The new document has never heard of either method.
const defined = vi
.mocked(switchboards[1].defineMethod)
.mock.calls.map(([name]) => name);
expect(defined).toContain("resolvePermalinkUrl");
expect(defined).toContain("observeDataMask");
dashboard.unmount();
});
test("reload ignores a load that arrives after unmount", async () => {
const mockFetchGuestToken = vi.fn().mockResolvedValue(fakeToken());
const dashboard = await embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
});
const iframe = mountPoint.querySelector("iframe")!;
dashboard.unmount();
iframe.dispatchEvent(new Event("load"));
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
expect(vi.mocked(Switchboard).mock.calls).toHaveLength(1);
expect(mockFetchGuestToken).toHaveBeenCalledTimes(1);
});

@rusackas rusackas 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.

Really solid state machine for the reload/generation handling, and the tests cover the scenarios in the description well. One thing before this merges, though: the initial fetchGuestTokenWithTimeout() catch block tears down the iframe and rethrows unconditionally, even if a reload already recovered the embed and is rendering fine. The comment above it names that exact scenario but only guards the emit, not the teardown, so a slow initial fetch finally timing out would wipe out a dashboard that's already working.

Also, a reload firing before that initial fetch settles triggers a second, concurrent fetchGuestToken() call to the host, and if the reload's own fetch fails, a valid token from the original call gets discarded in favor of a 10s retry.

Smaller ones: hostMethods/defineHostMethod type callback args as any, which the repo's CLAUDE.md asks to avoid, and the new tests are wrapped in a describe() block where the convention here is flat test()s.

@chadek
chadek force-pushed the fix/embedded-sdk-internal-navigation branch from c43a119 to cc3e9cb Compare September 22, 2026 00:20
@chadek
chadek force-pushed the fix/embedded-sdk-internal-navigation branch from cc3e9cb to 5adc262 Compare September 22, 2026 00:40
@chadek

chadek commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @rusackas — both directions of that race were real, and you were right that it isn't a one-line fix while the catch doubles as "build vs bail" for the whole function's return value. Rebased onto current master and pushed; here's where each point landed.

The stale initial fetch tearing down an embed a reload already recovered. The teardown is now gated on whether anything has taken over the token chain:

if (generation === 0) {
  teardown("the initial guest token fetch failed");
  throw err;
}
log("the initial guest token fetch failed, a reload has taken over:", err);

A reload opens a token cycle of its own, and that cycle — not this one — decides whether the embed lives: it either hands the document in front of the user a token, or retries until it can. Guarding on generation rather than on "has a token actually arrived" also covers the narrower window where the reload's own fetch is still in flight when the initial one rejects; tearing down there would kill the embed microseconds before it recovers. embedDashboard then resolves normally rather than rethrowing.

The other direction — a valid initial token thrown away for a 10s retry. deliverGuestToken hands a superseded token over when the current document has none:

const ownsChain = gen === generation;
if (ownsChain || !connection.tokenSent) { /* emit */ }
if (ownsChain) { armRefresh(/* … */); }

Any valid token gets that document rendering, and only the cycle that owns the chain arms a timer, so two cycles overlapping across a reload still can't leave two timers running.

The load listener re-authenticating on any load — not as harmless as it looked, so thanks for flagging it. It was minting tokens for documents that can never use one. The SDK now confirms the handshake before asking the host for anything: it calls a method the embedded page deliberately does not implement, and the Method "..." is not defined error every version of the page replies with is itself the acknowledgement. Silence times out at 5s and no token is fetched. A link in a Markdown chart pointing at a plain Superset URL, or off site, now costs the host's endpoint nothing, and coming back to the dashboard re-authenticates as usual.

The smaller two. hostMethods/defineHostMethod no longer use any — the registry is HostMethod = (args: never) => unknown with a generic defineHostMethod<A extends object>, so each method keeps its own signature at the call site and no cast is needed. Tests are flattened to top-level test()s named in the reload … / unmount … style already used in the file; ten of them now.

Heads-up on what else grew here since you reviewed. Your comments were against the version that still kept a bare ourPort. A Connection now bundles a port with everything scoped to the document behind it, which brought in two things worth a look: a get still in flight when the document leaves is rejected with PortClosedError instead of hanging forever on a reply that can no longer come (same for unmount()), and the theme pushed with setThemeConfig/setThemeMode is replayed to the new document after its token — methods were being replayed but state wasn't, so the dashboard came back in the default theme.

On verification. The unit tests mock MessageChannel and Switchboard, which is precisely the layer these bugs live in, so I also built a local test rig to check the parts that only exist between two documents: a host app and a stand-in for the embedded page on two origins, driven in headless Chromium against the built UMD bundle over the real @superset-ui/switchboard, no npm dependencies beyond a chromium binary. 39 checks, including both directions of this race — it reaches them by holding the first fetchGuestToken() open while the dashboard navigates, which is not otherwise reachable with an endpoint that answers promptly.

I confirmed each fix by reverting it and watching the matching check go red:

  • dropping the generation === 0 guard → "the working dashboard is not torn down" and "embedDashboard resolves rather than rejecting" fail
  • dropping || !connection.tokenSent → "the superseded token is handed straight to the current document" fails, bounded to 3s on purpose: a token that only turns up on the 10s retry is exactly the blank page this is about

It also covers the theme replay, the PortClosedError paths, and that a navigation away from the embedded page mints nothing. I've kept it out of this diff to hold the review surface to the fix itself, but I'm glad to push it as a follow-up commit here or as its own PR if you think it earns its place — it's the only thing I have that exercises the cross-document behaviour for real.

Happy to refresh the PR description too, since it predates the handshake probe and the PortClosedError work.

chadek added a commit to chadek/superset that referenced this pull request Sep 22, 2026
…e embed

Review feedback on apache#44470.

The initial `fetchGuestToken()` and a navigation the dashboard makes while that
fetch is still in flight race each other, and both outcomes were wrong.

If the fetch rejects after the navigation has already re-authenticated the new
document, the `catch` tore the iframe down and rethrew, wiping a dashboard that
was rendering fine on the word of a promise nobody was waiting for any more. The
teardown is now gated on `generation`: once a reload has opened a token cycle of
its own, that cycle — not this one — decides whether the embed lives, either by
handing the current document a token or by retrying until it can, and
`embedDashboard` resolves instead of rethrowing. Gating on the generation rather
than on whether a token has actually arrived also covers the narrower window
where the reload's own fetch is still in flight when the initial one rejects.

`hostMethods` and `defineHostMethod` no longer type their callback arguments as
`any`, which CLAUDE.md asks new code to avoid. The registry holds
`HostMethod = (args: never) => unknown` and `defineHostMethod<A extends object>`
keeps each method's own signature at the call site, so no cast is needed.

The new tests move out of the nested `describe()` into top-level `test()`s named
the way the rest of the file names them, and two more cover the two directions of
the race.

Signed-off-by: Fabrice Meyer <[email protected]>
@chadek
chadek force-pushed the fix/embedded-sdk-internal-navigation branch from 5adc262 to 95e6c43 Compare September 22, 2026 00:54
…ation

The iframe's `load` listener is registered before `iframe.src`, so it fires on
every load, reloads included, and opens a fresh `MessageChannel` each time. But
it only returns that channel through `resolve()` of a promise that is already
settled from the second load onwards. Nobody keeps the new `port1`, so a
dashboard that navigates itself — a tab link, a link in a Markdown chart, a
drill-down — leaves a blank frame: the new document waits for a guest token on a
channel whose other end is gone, while `ourPort` keeps talking to the document
that disappeared. apache#39860 already made the embedded page tolerate a second
'port transfer' handshake; this completes the host half.

- `connect(iframe)` is extracted from the listener: it opens the channel,
  transfers the port, constructs and starts the `Switchboard`, and replays the
  host-defined methods — a reloaded document has never heard of them.
- `ourPort`, `refreshTimer` and `unmounted` move above `mountIframe`, which now
  resolves `void`; the listener reassigns `ourPort` on every load. The existing
  accessors read that variable, so they follow the current port unchanged.
- A reload cancels the pending timer and re-fetches a token rather than
  replaying the cached one: refresh happens 5s before expiry, so a reload
  landing just before it would hand the new page a token with seconds to live,
  and its `GET /api/v1/me/roles/` would 401 into the "session interrupted"
  banner.
- `refreshGuestToken` takes a generation number and bails out if a reload
  superseded it, so a refresh left in flight cannot emit a stale token or arm a
  second timer.
- `resolvePermalinkUrl` and `observeDataMask` are registered through
  `defineHostMethod`, so they survive a reload.
- A `load` arriving after `unmount()` is now ignored; it used to open a channel.

`MessagePort` queues what arrives before `start()`, so emitting the token right
after the handshake is safe — that is already the property the first load relies
on.

Three tests cover re-authentication on the new port, the replay of host-defined
methods, and a load after unmount. All three fail without this change.

Signed-off-by: Fabrice Meyer <[email protected]>
…eded token

Follow-up work and review feedback on apache#44470.

Reloading the port left three things unaccounted for, so a `Connection` now
bundles a port with everything scoped to the document behind it: its switchboard,
the `get` calls still awaiting a reply, and whether it has been handed a token.
The SDK holds exactly one, and a load replaces it.

- The accessors go through `portGet`, which scopes a call to the connection it
  was issued on. A `get` still in flight when the document leaves is rejected
  with `PortClosedError` instead of hanging forever on a reply that can no
  longer come, and the retired port is closed. Same for `unmount()`.
- Not every navigation lands on the embedded page — a link in a Markdown chart
  can point at a plain Superset URL, or off site — and re-authenticating on any
  load minted guest tokens for documents that can never use one. The SDK now
  probes the new document with a method the page deliberately does not
  implement: the `Method "..." is not defined` error every version replies with
  is itself the acknowledgement, and silence times out without a fetch.
- Methods were replayed to the new document but state was not, so the dashboard
  came back in the default theme. What the host pushed with `setThemeConfig` and
  `setThemeMode` is replayed too, after the token, in the order a host applies it
  on a first load.

The rest answers the review. The initial `fetchGuestToken()` and a navigation the
dashboard makes while that fetch is still in flight race each other, and both
outcomes were wrong. If the fetch rejected after the navigation had already
re-authenticated the new document, the `catch` tore the iframe down and rethrew,
wiping a dashboard that was rendering fine on the word of a promise nobody was
waiting for any more. The teardown is now gated on `generation`: once a reload
has opened a token cycle of its own, that cycle — not this one — decides whether
the embed lives, either by handing the current document a token or by retrying
until it can, and `embedDashboard` resolves instead of rethrowing. Gating on the
generation rather than on whether a token has actually arrived also covers the
narrower window where the reload's own fetch is still in flight when the initial
one rejects. In the other direction, a token from a superseded cycle is handed
straight to the current document when it has none, rather than leaving the page
blank for a full retry interval.

`hostMethods` and `defineHostMethod` no longer type their callback arguments as
`any`, which CLAUDE.md asks new code to avoid. The registry holds
`HostMethod = (args: never) => unknown` and `defineHostMethod<A extends object>`
keeps each method's own signature at the call site, so no cast is needed.

The tests move out of the nested `describe()` into top-level `test()`s named the
way the rest of the file names them, and cover the rejection of stranded calls,
the theme replay, a navigation that is not the embedded page, and both directions
of the race.

Signed-off-by: Fabrice Meyer <[email protected]>
@chadek
chadek force-pushed the fix/embedded-sdk-internal-navigation branch from 95e6c43 to 3945e36 Compare September 22, 2026 00:56
@chadek

chadek commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Sorry for the force-push mess up, I actually first rebased my branch on latest upstream bundling up everything in one single commit. I then split it up in 2 commits so you can review what was added afterwards. We just discovered this bug before going to production and had to quickly find out a patch. Hopefully it will be packed into next release!

@bito-code-review

bito-code-review Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #ddb05d

Actionable Suggestions - 0
Additional Suggestions - 3
  • superset-embedded-sdk/src/index.ts - 2
    • Handshake timeout leaves no retry · Line 68-68
      HANDSHAKE_PROBE_TIMEOUT_MS gives a reloaded document 5s to answer the probe, and `reauthenticate` then returns without arming any retry — `refreshGuestToken` only runs from `armRefresh` timers or a successful handshake. A valid embedded page whose switchboard boots slower than 5s is silently and permanently stranded without a token, with no error surfaced to the host. Consider retrying the probe before giving up.
    • Stale takeover check · Line 431-436
      The takeover signal fires only when `refreshGuestToken` runs `++generation`, but `reauthenticate` first awaits `handshakeAcknowledged` (up to 5s). An initial fetch failing inside that window still sees `generation === 0` at line 472 and tears down the just-reconnected embed — the exact outcome the comment above says a reload prevents. Bump `generation` in the reload branch so the takeover is visible immediately.
  • superset-embedded-sdk/src/index.test.ts - 1
    • Guideline: no `any` types · Line 87-87
      The new mock plumbing leans on `as any` (here, plus `neverAnswered as any` at lines 386/406 and `any` in the `getImpls` element type at line 69), which `.cursor/rules/dev-standard.mdc` prohibits for TypeScript files. Typing `makeMockSwitchboard` as `Mocked` and the `getImpls` entries as `Switchboard["get"]`-compatible removes the casts and lets the compiler check the handshake stubs these reload tests rely on.
Review Details
  • Files reviewed - 2 · Commit Range: 42c06eb..3945e36
    • superset-embedded-sdk/src/index.test.ts
    • superset-embedded-sdk/src/index.ts
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • Eslint (Linter) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@rusackas

Copy link
Copy Markdown
Member

Thanks @chadek, this all checks out. The generation === 0 gate plus handing a superseded token to a document that has none covers both directions of that race, and the handshake probe keeps stray navigations from minting tokens. Tests are flat now too. LGTM!

On the test rig, I'd keep it as its own PR so this one stays just the fix. And yes, a refreshed description would be appreciated since the probe and PortClosedError bits aren't in it yet.

@netlify

netlify Bot commented Sep 24, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit f72bc9e
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ab528a6e67ec20008fb8cc8
😎 Deploy Preview https://deploy-preview-44470--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@chadek

chadek commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Description's refreshed, the probe and PortClosedError bits are in there now. Test rig is split out into its own PR: #44608. It needs this fix to actually pass (I ran it against this branch: 39/39), so I've flagged in there that it should land after this one merges. Thanks for digging into the race conditions, that second commit wouldn't exist without your review.

@chadek
chadek requested a review from rusackas September 24, 2026 15:05

@rusackas rusackas 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.

LGTM, thanks!

@rusackas
rusackas merged commit 7cb19e2 into apache:master Sep 29, 2026
68 of 69 checks passed
@chadek

chadek commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Hi @rusackas I have seen the recent RC for 7.0.0 but it seams not to contain this fix. Any idea on when it would land in a release?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Embedded dashboard goes blank after a navigation internal to the dashboard

2 participants