Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions e2e/guest-app/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {HashRouter, Route, Routes} from "react-router-dom";
import Extention from './Extention';
import ExtentionPartial from './ExtentionPartial';
import Counter from './MainApp';
import UiFrameProbe from './UiFrameProbe';

function App() {

Expand All @@ -12,6 +13,7 @@ function App() {
<Route index element={<Counter/>}/>
<Route path="register" element={<Extention/>}/>
<Route path="register-partial" element={<ExtentionPartial/>}/>
<Route path="ui-frame" element={<UiFrameProbe/>}/>
</Routes>
</HashRouter>
);
Expand Down
53 changes: 53 additions & 0 deletions e2e/guest-app/src/UiFrameProbe.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React, { useEffect, useRef, useState } from 'react';
import { attach } from '@adobe/uix-guest';

// Computed once when this module is evaluated. It only changes if the iframe's
// browsing context is actually torn down and reloaded (a real navigation) - a
// hash-only route change or a parent re-render does NOT re-run this line.
// This is how the test detects whether moving this frame in the host's DOM
// silently reloaded it, as opposed to React simply relocating the same node.
const bootId = Math.random().toString(36).slice(2, 10);

function log(message) {
// eslint-disable-next-line no-console
console.log(`[uix-e2e-reorder] ${bootId} ${message}`);
}

export default function UiFrameProbe() {
const [status, setStatus] = useState('connecting');
const [error, setError] = useState('');
const attempted = useRef(false);

useEffect(() => {
if (attempted.current) return;
attempted.current = true;

const hashSearch = window.location.hash.split('?')[1] || '';
const params = new URLSearchParams(hashSearch);
const extensionId = params.get('id') || 'extensionId';
const timeout = Number(params.get('timeout')) || 5000;

log(`booted, attaching as "${extensionId}" (timeout ${timeout}ms)`);

attach({ id: extensionId, timeout })
.then(() => {
log('attach resolved: connected');
setStatus('connected');
})
.catch((e) => {
const message = (e && e.message) || String(e);
log(`attach rejected: ${message}`);
setStatus('error');
setError(message);
});
}, []);

return (
<div>
<p>UI frame probe</p>
<p id="boot-id">{bootId}</p>
<p id="attach-status">{status}</p>
<p id="attach-error">{error}</p>
</div>
);
}
6 changes: 6 additions & 0 deletions e2e/host-app/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import HostAppRequires from './HostAppRequires';
import HostAppDynamic from './HostAppDynamic';
import HostAppCallbackAdd from './HostAppCallbackAdd';
import HostAppRenderTest from './HostAppRenderTest';
import HostAppReorder from './HostAppReorder';

function getScenario() {
const hash = window.location.hash;
Expand All @@ -15,6 +16,7 @@ function getScenario() {
if (hash.startsWith('#/dynamic')) return 'dynamic';
if (hash.startsWith('#/callback-add')) return 'callback-add';
if (hash.startsWith('#/render-test')) return 'render-test';
if (hash.startsWith('#/reorder')) return 'reorder';
return 'default';
}

Expand Down Expand Up @@ -62,6 +64,10 @@ function App() {
return <HostAppRenderTest />;
}

if (scenario === 'reorder') {
return <HostAppReorder />;
}

const Component = components[scenario];
const provider = providers[scenario];

Expand Down
91 changes: 91 additions & 0 deletions e2e/host-app/src/HostAppReorder.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { useState } from 'react';
import { Extensible, GuestUIFrame, useExtensions } from '@adobe/uix-host-react';

// Same extension registered once (control frame via #/register); every row
// attaches its OWN UI frame (#/ui-frame) to that single registered guest -
// this mirrors a multifield where every item is rendered by the same
// extension, one live iframe per item, all sharing one Port/guest registration.
const provider = async () => ({
extensionId: { id: 'extensionId', url: 'http://localhost:3002#/register?id=extensionId' },
});

const UI_FRAME_URL = 'http://localhost:3002#/ui-frame?id=extensionId&timeout=5000';

const ROWS_INITIAL = [
{ id: 'row-a', label: 'Row A' },
{ id: 'row-b', label: 'Row B' },
];

function Row({ rowId, label }) {
return (
<div id={`row-${rowId}`} data-row-id={rowId} style={{ border: '1px solid #999', margin: 8, padding: 8 }}>
<p>{label}</p>
<GuestUIFrame id={`iframe-${rowId}`} guestId="extensionId" src={UI_FRAME_URL} />
</div>
);
}

function ReorderableList() {
const [rows, setRows] = useState(ROWS_INITIAL);
// Positive control: gives Row A a brand new identity/key, forcing React to
// unmount + remount it for real, so the test can confirm a genuine remount
// still reconnects cleanly (proving the harness itself works).
const [rowAInstance, setRowAInstance] = useState(0);

const swap = () => {
// Pure position swap, same object identities/keys - mirrors
// canvasValuesStore.ts's swapMultiValues (array.splice in / splice out,
// no re-keying).
setRows((prev) => [prev[1], prev[0]]);
};

const remountRowA = () => setRowAInstance((n) => n + 1);

return (
<div>
<button id="swap-rows-button" onClick={swap}>
Swap rows
</button>
<button id="remount-row-a-button" onClick={remountRowA}>
Force remount row A
</button>
<div id="rows-container">
{rows.map((row) => (
<Row
key={row.id === 'row-a' ? `row-a-${rowAInstance}` : row.id}
rowId={row.id}
label={row.label}
/>
))}
</div>
</div>
);
}

// Only render the rows (and therefore GuestUIFrame) once the extension is
// actually loaded - matching production, where CustomField is only chosen
// as a field's renderer after its extension is known. Mounting GuestUIFrame
// before `useHost()` resolves is a separate, pre-existing bug in
// GuestUIFrame itself (host starts null, then becomes truthy on the same
// instance, which skips its useEffect calls on the first render and trips
// React's "Rendered more hooks than during the previous render" - masked
// in every other e2e scenario by their use of key={Math.random()}, which
// forces a fresh instance every render). That's out of scope here.
function ReadyGate() {
const { extensions = [], loading } = useExtensions(() => ({}));
if (loading || extensions.length === 0) {
return <p id="extensions-loading">Loading extension...</p>;
}
return <ReorderableList />;
}

export default function HostAppReorder() {
return (
<div>
<h2>Multifield Reorder Scenario</h2>
<Extensible debug={true} extensionsProvider={provider}>
<ReadyGate />
</Extensible>
</div>
);
}
123 changes: 123 additions & 0 deletions e2e/tests/tests/multifield-reorder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { fixture, test, Selector } from "testcafe";

// Reproduces SITES-42495: a host renders one GuestUIFrame per "row" (e.g. a
// multifield item), keyed by stable per-row identity rather than array
// position - the same pattern @aem-sites/headless-components' Multifield
// uses (a birth-assigned `multiIdx` that a pure position-swap never
// re-keys). A stable key means React relocates the existing iframe DOM node
// on reorder instead of unmounting/remounting it.
//
// If the browser silently reloads a live cross-origin iframe when it's moved
// in the DOM (a documented risk - see @adobe/uix-host's HostConfig.runtimeContainer
// comment), GuestUIFrame's connect effect (deps: [guest.id], which never
// changes here) never re-runs, so the host never re-attaches - the reloaded
// guest's fresh attach() call then times out.
//
// This test asserts the CORRECT behavior - both rows should still be
// connected after the swap - and currently FAILS because of the bug. It
// should start passing once SITES-42495 is fixed; no changes to the test
// should be needed at that point.

const rowASelector = "#iframe-row-a";
const rowBSelector = "#iframe-row-b";

fixture("Multifield reorder - stable-keyed GuestUIFrame across a position swap")
.page("http://localhost:3000/#/reorder");

async function waitConnected(t, iframeSelector, label) {
await t.switchToIframe(iframeSelector);
await t
.expect(Selector("#attach-status").innerText)
.eql("connected", `${label} should connect on initial load`, { timeout: 10000 });
await t.switchToMainWindow();
}

async function readProbe(t, iframeSelector) {
await t.switchToIframe(iframeSelector);
const bootId = await Selector("#boot-id").innerText;
const status = await Selector("#attach-status").innerText;
const error = await Selector("#attach-error").innerText;
await t.switchToMainWindow();
return { bootId, status, error };
}

test("swapping two stable-keyed rows should not break either iframe's connection (SITES-42495)", async (t) => {
await t.expect(Selector(rowASelector).exists).ok("Row A iframe should exist", { timeout: 15000 });
await t.expect(Selector(rowBSelector).exists).ok("Row B iframe should exist", { timeout: 15000 });

await waitConnected(t, rowASelector, "Row A");
await waitConnected(t, rowBSelector, "Row B");

const before = {
a: await readProbe(t, rowASelector),
b: await readProbe(t, rowBSelector),
};

await t.click("#swap-rows-button");

// Give a silently-reloaded guest time to either reconnect or hit its
// (short, test-configured) attach() timeout.
await t.wait(6000);

const after = {
a: await readProbe(t, rowASelector),
b: await readProbe(t, rowBSelector),
};

// eslint-disable-next-line no-console
console.log("[multifield-reorder] probe result:", JSON.stringify({ before, after }, null, 2));

// The DOM nodes themselves must survive the swap (identified by their
// stable ids, regardless of which now sits in which visual position).
await t.expect(Selector(rowASelector).exists).ok("Row A iframe element should still exist after swap");
await t.expect(Selector(rowBSelector).exists).ok("Row B iframe element should still exist after swap");

// Precondition check, expected to keep passing either way: at least one
// row's iframe silently reloaded (new bootId) purely from being moved in
// the DOM - proving React relocated the live node rather than
// remounting it, and that the browser discarded its browsing context
// anyway. This is just context for the real assertions below; a reload
// happening is not itself the bug.
const aReloaded = after.a.bootId !== before.a.bootId;
const bReloaded = after.b.bootId !== before.b.bootId;
await t
.expect(aReloaded || bReloaded)
.ok(
`Expected at least one row's iframe to silently reload after the swap (this is a browser quirk, not the bug under test). before=${JSON.stringify(before)} after=${JSON.stringify(after)}`
);

// The actual bug: a silent reload should not be fatal. The host/SDK
// should notice the guest reconnecting and re-establish the tunnel, so
// both rows should read "connected" here. Today they don't - whichever
// row got moved is left permanently unreachable instead.
await t
.expect(after.a.status)
.eql(
"connected",
`Row A should still be connected after the swap. bootId ${before.a.bootId} -> ${after.a.bootId}, error="${after.a.error}"`
);
await t
.expect(after.b.status)
.eql(
"connected",
`Row B should still be connected after the swap. bootId ${before.b.bootId} -> ${after.b.bootId}, error="${after.b.error}"`
);
});

test("a genuine remount (new key) reconnects cleanly - positive control", async (t) => {
await t.expect(Selector(rowASelector).exists).ok("Row A iframe should exist", { timeout: 15000 });
await waitConnected(t, rowASelector, "Row A");

const before = await readProbe(t, rowASelector);

await t.click("#remount-row-a-button");
await t.wait(1000);

await waitConnected(t, rowASelector, "Row A (after remount)");
const after = await readProbe(t, rowASelector);

await t
.expect(after.bootId)
.notEql(before.bootId, "A real remount should produce a fresh boot id");
await t.expect(after.status).eql("connected", "A real remount should reconnect cleanly");
});
17 changes: 16 additions & 1 deletion packages/uix-core/src/tunnel/tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,24 @@ export class Tunnel extends EventEmitter {
let frameStatusCheck: number;
let timeout: number;

/**
* Deliberately does not gate on `!tunnel.isConnected`: a host can
* legitimately receive a fresh handshake offer from this same iframe
* after it's already connected once, if the iframe's browsing context
* was silently reloaded (e.g. the DOM node was relocated by the host's
* own re-render, which some browsers treat as a reload even though the
* element was never removed from the document - see the reload note in
* HostConfig.runtimeContainer). `target.contentWindow` still identifies
* the current window inside that same iframe element, so accepting the
* offer and calling `tunnel.connect()` again re-establishes the tunnel
* with a fresh MessagePort, matching the "may reconnect if the iframe
* reloads" behavior already documented on this method. A still-alive,
* non-reloaded guest never re-sends an offer once its own tunnel is
* connected (see Tunnel.toParent's sendOffer), so this can't fire
* spuriously for a healthy connection.
*/
const offerListener = (event: MessageEvent) => {
if (
!tunnel.isConnected &&
isFromOrigin(event, target.contentWindow, config.targetOrigin) &&
messenger.isHandshakeOffer(event.data)
) {
Expand Down
Loading