Skip to content

Strong migration needs native ref state across ancestor Suspense #2452

Closed

Description

@domgan-oai

A React callback ref can publish the current native element with const [node, setNode] = useState(null) and ref={setNode}. Strong rejects this pattern. Replacing it with an object ref and useLayoutSnapshot(() => ref.current, { initial: null }) works when the owning component commits the attachment, but misses the detach under an ancestor Suspense boundary.

Observed

A sibling suspends and the ancestor boundary shows its fallback without receiving an update from the ref owner. Resolving it reveals the identical original DOM node. A descendant layout effect records the following values on reveal.

Version Observed node values
Compatibility with ref={setNode} [null, original]
Strong with an object ref and layout snapshot [original]

Both versions compile cleanly in their respective modes, mount the original node, show the fallback, and reveal the same node. The result reproduces with default snapshot timing in Chromium 149.0.7827.55 on Octane 0.16.7 and upstream eb1abbbd8f7dce8f3be7f91564e2af3e609b9f6b.

Expected

A Strong migration that turns a native callback ref into a renderable value needs to observe its attach and detach lifecycle when an ancestor owns the commit. The same requirement applies to synchronous commits under the public frame timing setting, where layout snapshots deliberately publish later.

Reproduction

Save the script below as repro.mjs in an empty directory. With Node 26.12.1, install the pinned packages and run it. Set CHROME_BIN to use an existing compatible Chromium binary.

npm init -y
npm install --save-exact [email protected] [email protected] [email protected]
npx playwright install chromium
node repro.mjs

The final parity assertion fails.

repro.mjs
import assert from 'node:assert/strict';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { build } from 'esbuild';
import { collectDiagnostics, compile } from 'octane/compiler';
import { chromium } from 'playwright';

const cwd = path.dirname(fileURLToPath(import.meta.url));
const reference = 'const [node, attach] = useState(null);';
const candidate = `const attach = useRef<HTMLDivElement | null>(null);
  const node = useLayoutSnapshot(() => attach.current, { initial: null });`;
const main = (hook) => `${hook === candidate ? '"use strong";' : ''}
import { use, useState, useRef, useLayoutEffect, useLayoutSnapshot } from 'octane';

function Reader({node, report}) @{
  useLayoutEffect(() => { report(node); });
  <em/>
}
function Owner({report}) @{
  ${hook}
  <div><div ref={attach} data-host=""/><Reader {node} {report}/></div>
}
function Loader({register, pending}) @{
  const [blocked, setBlocked] = useState(false);
  useLayoutEffect(() => { register(setBlocked); });
  if (blocked) use(pending);
  <i/>
}
export function App({report, register, pending}) @{
  <section>
    @try { <div><Owner {report}/><Loader {register} {pending}/></div> }
    @pending { <p data-fallback="">Loading</p> }
  </section>
}`;
const imports = [];
const modules = {};
for (const [name, hook] of [['State', reference], ['Snapshot', candidate]]) {
  const file = name + '.tsrx';
  const source = main(hook);
  const diagnostics = collectDiagnostics(source, file, {strong: name === 'Snapshot'});
  assert.equal(diagnostics.error, null);
  assert.deepEqual(diagnostics.diagnostics.filter(d => d.severity === 'error'), []);
  modules[name] = compile(source, file, {mode:'client'}).code;
  imports.push(`import {App as ${name}} from 'example:${name}';`);
}
const runner = imports.join('\n') + `
import {act, createRoot} from 'octane';

window.probe = async function(ComponentName) {
  const host = document.getElementById('root');
  const root = createRoot(host);
  let suspend, resolve, observed = [];
  const pending = new Promise(r => { resolve = r; });
  const props = {pending, register(fn) { suspend = fn; }, report(node) { observed.push(node); }};
  await act(async () => root.render(ComponentName === 'State' ? State : Snapshot, props));
  const original = host.querySelector('[data-host]');
  const mounted = observed.at(-1) === original && original !== null;
  await act(async () => suspend(true)); // Only Loader updates. Owner receives no new props.
  const showedFallback = !!host.querySelector('[data-fallback]');
  observed = [];
  await act(async () => { resolve('ready'); await pending; });
  const observations = observed.map(node => node === null ? null : node === original ? 'original' : 'other');
  const revealedOriginal = host.querySelector('[data-host]') === original && !host.querySelector('[data-fallback]');
  await act(async () => root.unmount());
  return {mounted, showedFallback, revealedOriginal, observations};
};`;
const out = await mkdtemp(path.join(tmpdir(), 'octane-snapshot-ref-'));
const html = path.join(out, 'index.html');
await build({
  stdin:{contents:runner, resolveDir:cwd},
  platform:'browser', format:'iife', bundle:true, outfile:path.join(out,'probe.js'),
  plugins:[{name:'compiled-tsrx', setup(b) {
    b.onResolve({filter:/^example:/}, args => ({path:args.path.slice(8),namespace:'example'}));
    b.onLoad({filter:/.*/,namespace:'example'}, args => ({contents:modules[args.path],resolveDir:cwd}));
  }}],
});
await writeFile(html, '<div id="root"></div><script src="probe.js"></script>');
if (process.argv.includes('--html')) {
  console.log(pathToFileURL(html).href);
} else {
  const browser = await chromium.launch({
    headless:true,
    ...(process.env.CHROME_BIN ? {executablePath:process.env.CHROME_BIN} : {}),
  });
  try {
    const page = await browser.newPage();
    await page.goto(pathToFileURL(html).href);
    const state = await page.evaluate(() => window.probe('State'));
    const snapshot = await page.evaluate(() => window.probe('Snapshot'));
    console.log(JSON.stringify({chromium:browser.version(), state, snapshot}, null, 2));
    assert.deepEqual(state, {mounted:true, showedFallback:true, revealedOriginal:true, observations:[null,'original']});
    assert.deepEqual(snapshot, state); // Fails: the snapshot only reports 'original'.
  } finally {
    await browser.close();
  }
}

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions