Repository navigation
fix(hydration): discard the server elements and text a shorter @if/@switch arm leaves unclaimed - #1600
Merged
Conversation
…witch arm leaves unclaimed When the server rendered a longer @if or @switch arm, the client arm adopts the start of the server's range. discardArmTail removes what follows a range the arm claimed, but a template leaves the cursor on the elements and text it adopts, so elements or text after the client arm's own roots stayed on screen with no report. A component that adopted its root in place left the same tail. renderAdoptedArm now opens a claim on the arm's range, so the arm's own template records where its roots end (claimRoots), and steps the cursor past them as a range claim parks it. discardArmTail then removes the server content from there, stops at client-built nodes, and reports code 51 once with a dev diagnostic at the directive. A component that adopts its root in place at the arm's top level parks the cursor past that root the same way (parkPast), so the last such root records the arm's end too. Production adoption never parses a template, so the compiler now ships every multi-root template raw with its root count, as resolved-HTML and foreign ones already did. A branch in a helper passed as a render prop, whose template was pre-wrapped in <octane-frag> with no count, no longer parses it in production. The compiler change and adopted-branch-tail.test.ts come from the closed #1565. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contributor
Benchmark report
Compares js-framework: 1k/10k row operations (ms, lower is better)All 20 timed operations (20 within noise)
Application bundle size (bytes)
30 other measured values are unchanged. Public-import reachability bundles (bytes)
70 other measured values are unchanged. |
trueadm
marked this pull request as ready for review
October 2, 2026 19:35
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Fragment in-place arms keep tails
- Added inPlace clearing in the fragment match path of adopt(), a parkHere() method for cursor-based arm tracking, and inPlacePark for multi-root fragment cursor advancement so renderInPlace returns true and the arm tail is correctly tracked and discarded.
Or push these changes by commenting:
@cursor push d3f10b4443
Preview (d3f10b4443)
diff --git a/.changeset/branch-arm-host-tails.md b/.changeset/branch-arm-host-tails.md
new file mode 100644
--- /dev/null
+++ b/.changeset/branch-arm-host-tails.md
@@ -1,0 +1,5 @@
+---
+'octane': patch
+---
+
+Discard the server elements and text that an `@if` or `@switch` arm leaves unclaimed during hydration. When the server rendered a longer arm, the client arm adopts the start of the server's range. Elements or text after the roots of the client arm's own template, or after a component the arm adopts in place, stayed on screen with no report. Hydration now steps past those roots, removes the server content after them, and reports one structural `onRecoverableError`, with a development diagnostic at the directive. Every compiled multi-root template now carries its root count, so production hydration finds that end without parsing the template, including for a branch in a helper passed as a render prop.
diff --git a/packages/octane/src/compiler/compile.js b/packages/octane/src/compiler/compile.js
--- a/packages/octane/src/compiler/compile.js
+++ b/packages/octane/src/compiler/compile.js
@@ -26160,8 +26160,8 @@
};
}
- // Emit ONE template containing all top-level JSX (wrapping multiple roots in
- // a synthetic <octane-frag>).
+ // Emit ONE template containing all top-level JSX (the runtime parses
+ // multiple roots inside a synthetic <octane-frag>).
// We walk the tree, building HTML and a list of bindings.
const elementBindings = []; // ordered list of bindings (per dynamic site)
const forCalls = []; // forBlock calls — emitted after the mount/append
@@ -26339,18 +26339,19 @@
ctx.runtimeNeeded.add('clone');
// Template namespace strategy:
// - HTML single-root: parse the element directly, no flag.
- // - HTML multi-root: wrap in <octane-frag> so template() returns the wrap.
+ // - HTML multi-root: raw markup + its root count; the runtime parses it
+ // inside an <octane-frag> wrapper and drains the wrapper's children.
// - SVG/MathML single-root: pass ns flag; runtime wraps with <svg>/<math>
// so the HTML5 parser places children in foreign content, then returns
// the inner root.
- // - SVG/MathML multi-root: pass ns + frag=1; runtime wraps and returns
- // the wrap itself (caller drains its children — no <octane-frag>).
+ // - SVG/MathML multi-root: pass ns + the root count; runtime wraps and
+ // returns the wrap itself (caller drains its children — no <octane-frag>).
// - Opaque component bodies/children whose root tags pin the namespace
// statically (every root exists in exactly one namespace — see
// staticNsForOpaqueRoot) compile like fixed HTML/SVG/MathML templates:
// the parse is identical at every destination, so pay nothing per
// clone. Only genuinely ambiguous roots (`a`, `title`, custom/unknown
- // tags, mixed fragments) pass flag 3 (+ frag=1 for multiple roots);
+ // tags, mixed fragments) pass flag 3 (+ the root count for several);
// clone() resolves and caches the concrete namespace from the render
// block's actual parent.
// Multi-root fragments at an HTML parent imply SVG only when EVERY element
@@ -26373,11 +26374,6 @@
: (parentNs === 'html' || parentNs === 'opaque') && fragImpliesSvg
? 'svg'
: parentNs;
- // A resolved-HTML multi-root ships raw markup + frag=1 (parseTemplate adds
- // the <octane-frag> wrapper) instead of the fixed-HTML path's pre-wrapped
- // string: same parsed DOM, but the template literal stays as small as the
- // opaque form it replaces.
- let resolvedFrag = false;
if (tplNs === 'opaque') {
// Component-destination template whose root tags didn't imply SVG:
// resolve the namespace statically when every root pins the same one.
@@ -26394,7 +26390,6 @@
resolved = ns;
}
tplNs = resolved === null ? 'html' : resolved;
- resolvedFrag = tplNs !== 'opaque';
}
}
// Binding planning precedes the final template namespace. An inherited
@@ -26407,23 +26402,11 @@
}
}
const flag = nsFlag(tplNs);
- // A raw multi-root template passes its root count, which hydration reads
- // without parsing the template to find where the roots it adopted end.
- const fragArg = !single && (flag !== 0 || resolvedFrag) ? htmlIdx : 0;
- let template = rootTemplate;
- if (!single && flag === 0 && !resolvedFrag) {
- template = templateElement(
- 'octane-frag',
- 'html',
- false,
- createTemplateIr(),
- rootTemplate,
- null,
- null,
- true,
- );
- }
- const tpl = allocTemplate(ctx, template, flag, fragArg);
+ // A multi-root template ships raw markup and its root count; parseTemplate
+ // adds the wrapper the HTML parser needs. Hydration reads the count without
+ // parsing the template to find where the roots it adopted end.
+ const fragArg = single ? 0 : htmlIdx;
+ const tpl = allocTemplate(ctx, rootTemplate, flag, fragArg);
// DEV: pass the root element's source location so a STRUCTURAL hydration mismatch
// (swapped @if/@switch branch, changed tag) warns with `file:line:col`. Single-root
// only (a multi-root <octane-frag> wrapper has no source position); prod omits it.
diff --git a/packages/octane/src/runtime.ts b/packages/octane/src/runtime.ts
--- a/packages/octane/src/runtime.ts
+++ b/packages/octane/src/runtime.ts
@@ -11881,11 +11881,14 @@
anchor: Node | undefined,
root: Node,
): void {
- hydration.renderInPlace(
- () => componentSlotLite(parentScope, slotKey, host, comp, props, invocationSite, anchor),
- undefined,
- root,
- );
+ if (
+ hydration.renderInPlace(
+ () => componentSlotLite(parentScope, slotKey, host, comp, props, invocationSite, anchor),
+ undefined,
+ root,
+ )
+ )
+ hydration.parkHere(parentScope);
}
// Keep the fresh-subtree callback's extra captures out of ordinary lite dispatch.
@@ -18434,7 +18437,8 @@
ns: 0 | 1 | 2 | 3;
/**
* Raw multi-root markup: the number of roots, as the compiler counts them.
- * 0 = one root, or HTML roots pre-wrapped in `<octane-frag>`.
+ * 0 = one root, or HTML roots already wrapped in `<octane-frag>`, which the
+ * compiler no longer emits.
*/
frag: number;
parsed: Array<Node | null>;
@@ -18477,9 +18481,9 @@
initDomOperations();
const t = (STAGED_DOM?.view(document) ?? document).createElement('template');
if (ns === 0) {
- // Fixed HTML multi-root templates arrive pre-wrapped by the compiler. Opaque
- // multi-root templates carry raw markup because their eventual namespace is
- // unknown, so add the equivalent wrapper only after HTML wins at clone time.
+ // Multi-root templates carry raw markup: an opaque one because its eventual
+ // namespace is unknown until clone time. Add the wrapper the HTML parser
+ // needs here. Markup that arrives already wrapped parses the same way.
(STAGED_DOM?.view(t) ?? t).innerHTML = frag ? `<octane-frag>${html}</octane-frag>` : html;
const root = getFirstChild(t.content) as Element;
// Multi-root HTML templates arrive wrapped in a synthetic <octane-frag>. The
@@ -18545,10 +18549,10 @@
}
/**
- * Is this lazy template a multi-root fragment? SVG/MathML/opaque fragments carry
- * `frag`; HTML multi-root templates arrive from the compiler pre-wrapped in
- * `<octane-frag>` with frag=0, so the wrapper tag is the discriminant there
- * (mirrors parseTemplate's `__oct_frag` stamping of the parsed root).
+ * Is this lazy template a multi-root fragment? Compiled fragments carry `frag`;
+ * HTML roots already wrapped in `<octane-frag>` with frag=0 are discriminated
+ * by the wrapper tag (mirrors parseTemplate's `__oct_frag` stamping of the
+ * parsed root).
*/
function isLazyFragment(lazy: LazyTemplateRecord): boolean {
return lazy.frag !== 0 || lazyRootDescriptor(lazy) === 'octane-frag';
@@ -18556,8 +18560,8 @@
/**
* How many roots a multi-root template has. The compiler passes the count as
- * a raw fragment's `frag`; a parsed or pre-wrapped template counts its
- * children.
+ * `frag`; a parsed template, or markup already wrapped in `<octane-frag>`,
+ * counts its children.
*/
function templateRootCount(template: Node | LazyTemplateRecord): number {
let parsed: Node;
@@ -18593,8 +18597,8 @@
/**
* lazyRootMatches for a nested fragment's FIRST logical root, read from the
- * template source. A raw fragment's cached descriptor is that root; a
- * fixed-HTML fragment's starts after its synthetic `<octane-frag>` wrapper. A
+ * template source. A raw fragment's cached descriptor is that root; markup
+ * already wrapped in `<octane-frag>` has it after the wrapper. A
* leading `<!>` is a dynamic hole whose server form (text, a marker range, or
* nothing) cannot decide a mismatch, so the first static element root after
* the leading holes decides, as in fragmentRootMatches.
@@ -18827,6 +18831,12 @@
private readonly unframedRootRanges = new WeakMap<Node, Node>();
/** The server node renderInPlace's body may adopt, until a template does. */
private inPlace: Node | null = null;
+ /**
+ * When a fragment body clears `inPlace`, the close of its last root's range
+ * (or the last root itself when it is not a range). renderInPlace steps past
+ * it so the cursor lands after all fragment roots, not just the first.
+ */
+ private inPlacePark: Node | null = null;
/** Pairs discovered while matching an outer range; released with this hydration pass. */
private matchingCloses: WeakMap<Node, Comment> | null = null;
/** First unclaimed root sibling after a compiled root clone; undefined until known. */
@@ -19206,6 +19216,7 @@
renderInPlace<T>(render: (target: T) => void, target: T, root: Node): boolean {
const outer = this.inPlace;
this.inPlace = root;
+ this.inPlacePark = null;
let adopted = false;
try {
render(target);
@@ -19213,7 +19224,11 @@
} finally {
this.inPlace = outer;
}
- if (adopted) this.node = getNextSibling(root);
+ if (adopted) {
+ const last = this.inPlacePark;
+ this.inPlacePark = null;
+ this.node = last !== null ? getNextSibling(last) : getNextSibling(root);
+ }
return adopted;
}
@@ -19660,8 +19675,9 @@
}
/**
- * A slot of `parent` claimed the server range that `close` ends. Step the
- * cursor past it to the next sibling's server content.
+ * A slot of `parent` claimed the server range that `close` ends, or adopted
+ * `close` in place as its root. Step the cursor past it to the next
+ * sibling's server content.
*/
parkPast(close: Node, parent: Scope): void {
const next = (this.node = getNextSibling(close));
@@ -19672,28 +19688,49 @@
}
/**
+ * Record the arm tracking at the current cursor, which renderInPlace already
+ * parked past the adopted content. Unlike parkPast this does not move the
+ * cursor: renderInPlace already advanced it past all roots (including the
+ * extra roots of a fragment body).
+ */
+ parkHere(parent: Scope): void {
+ if (parent === this.arm) {
+ this.armTail = this.node;
+ this.armSlots = parent.slots.length;
+ }
+ }
+
+ /**
* First render of an @if or @switch arm into the server range it adopted,
- * `block`'s own. When the arm's content is its own slots and the last of
- * them claimed a server range, returns the node that claim parked the
- * cursor on: whatever the server rendered from there belongs to no client
- * node (discardArmTail). Null when the arm cloned a template of its own, or
- * a later slot adopted without claiming a range, since the cursor then
- * rests on the roots they adopted.
+ * `block`'s own. Returns the node from which whatever the server rendered
+ * belongs to no client node (discardArmTail), with the cursor parked on it:
+ * the first node after the roots of the arm's own template, which records
+ * them as the range's content (claimRoots), or else where the arm's last
+ * slot parked the cursor after the range it claimed, or after the root it
+ * adopted in place. Null when a later slot adopted without either, since
+ * the cursor then rests on the roots it adopted.
*/
renderAdoptedArm(block: Block): Node | null {
const outerArm = this.arm;
const outerTail = this.armTail;
const outerSlots = this.armSlots;
+ const outerClaim = this.beginClaim(getNextSibling(block.startMarker!));
this.arm = block;
this.armTail = null;
+ let parked: Node | null = null;
+ let claimed: Node | null | undefined;
try {
renderBlock(block);
- return this.arm === block && this.armSlots === block.slots.length ? this.armTail : null;
+ if (this.arm === block && this.armSlots === block.slots.length) parked = this.armTail;
} finally {
+ claimed = this.endClaim(outerClaim);
this.arm = outerArm;
this.armTail = outerTail;
this.armSlots = outerSlots;
}
+ // The cursor rests on the roots the arm's own template adopted, or inside
+ // them: step it past them, as a range claim parks it.
+ return claimed == null ? parked : (this.node = claimed);
}
/**
@@ -19704,7 +19741,8 @@
* something, a server range at the cursor or just after that marker is one
* that nothing in the arm claimed: the server rendered another arm here,
* longer than this one. So is any server content at `parked`, where the
- * arm's last slot parked the cursor after its range (renderAdoptedArm).
+ * arm parked the cursor after its own template's roots, or after its last
+ * slot's range or in-place root (renderAdoptedArm).
* Discard the server content from there up to `end`, stopping at any
* client nodes that mismatch recovery built there, and report it once.
*
@@ -19713,7 +19751,7 @@
* empty client branch, as an arm with no body is. The cursor does not move
* past the elements and text that a template adopts, so at an element or
* text node it cannot otherwise tell what the arm adopted from what the
- * server rendered for another arm. Both stay.
+ * server rendered for another arm: `parked` does, and anything else stays.
*/
discardArmTail(scope: Scope, slotKey: number, first: Node, end: Node, parked: Node | null): void {
let from = this.node;
@@ -20284,6 +20322,19 @@
: lazyFragmentRootMatches(cursor, lazy!, this))
) {
if (cursor === this.claimFrom) this.claimRoots(cursor, template ?? lazy!);
+ if (cursor === this.inPlace) {
+ this.inPlace = null;
+ const count = templateRootCount(template ?? lazy!);
+ if (count > 1) {
+ let node: Node | null = cursor;
+ for (let i = count; i > 1; i--) {
+ node = this.sibling(node!, 1);
+ if (node === null || isBlockClose(node)) break;
+ }
+ if (node !== null && !isBlockClose(node))
+ this.inPlacePark = this.isOpen(node) ? this.close(node) : node;
+ }
+ }
return { __oct_vfrag: true, firstChild: cursor } as unknown as Node;
}
return this.rebuildFragment(template ?? resolveLazyTemplate(lazy!), cursor, loc);
@@ -32398,6 +32449,8 @@
b.endMarker = last;
}
}
+ // An arm that ends with this root cannot read its end off the cursor.
+ if (adopted) hydration!.parkHere(parentScope);
} else {
const b = createBlock(
'dynamic',
diff --git a/packages/octane/tests/compiler/compiler-template-origins.test.ts b/packages/octane/tests/compiler/compiler-template-origins.test.ts
--- a/packages/octane/tests/compiler/compiler-template-origins.test.ts
+++ b/packages/octane/tests/compiler/compiler-template-origins.test.ts
@@ -230,15 +230,17 @@
expect(kinds.has(kind)).toBe(true);
}
- const nested = compileInspect().find((template) =>
- template.html.startsWith('<octane-frag><i>'),
- )!;
- const wrapper = nested.ast.parts[0];
- expect(wrapper.type).toBe('TemplateElement');
- if (wrapper.type !== 'TemplateElement') throw new Error('expected a template element');
- expect(wrapper.tag).toBe('octane-frag');
- expect(wrapper.synthetic).toBe(true);
- expect(wrapper.children.filter((node) => node.type === 'TemplateElement')).toHaveLength(2);
+ // A multi-root template's roots are its own top-level parts, with no
+ // synthetic wrapper: the runtime adds the one the HTML parser needs.
+ const nested = compileInspect().find((template) => template.html.startsWith('<i>'))!;
+ expect(
+ nested.ast.parts.map((node) =>
+ node.type === 'TemplateElement' ? [node.tag, node.synthetic] : node.type,
+ ),
+ ).toEqual([
+ ['i', false],
+ ['b', false],
+ ]);
});
it('every origin entry slices cleanly out of both the template HTML and the source', () => {
diff --git a/packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx b/packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx
new file mode 100644
--- /dev/null
+++ b/packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx
@@ -1,0 +1,189 @@
+import type { ComponentBody } from 'octane';
+
+function label(): string {
+ return 'ok';
+}
+
+function Leaf() @{
+ <i>{label() as string}</i>
+}
+
+function Bold() @{
+ <b>{'b'}</b>
+}
+
+function Strike() @{
+ <s>{'s'}</s>
+}
+
+// Each branch renders its `@else` arm on the client. The server renders the
+// `@if` arm, whose content starts with what the `@else` arm renders and ends
+// with a stale tail, so the client adopts the arm's range and leaves the tail.
+export function SoleComponent(props: { server?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <Leaf />
+ <s class="foreign">{'f'}</s>
+ </>
+ } @else {
+ <Leaf />
+ }
+ </div>
+}
+
+export function SingleRoot(props: { server?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <i>{label() as string}</i>
+ <s class="foreign">{'f'}</s>
+ </>
+ } @else {
+ <i>{label() as string}</i>
+ }
+ </div>
+}
+
+// The stale tail ends with the same tag as the client's last root.
+export function StaticFragment(props: { server?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <i>{label() as string}</i>
+ <b>{'b'}</b>
+ <s class="foreign">{'f'}</s>
+ <b class="foreign">{'b'}</b>
+ </>
+ } @else {
+ <>
+ <i>{label() as string}</i>
+ <b>{'b'}</b>
+ </>
+ }
+ </div>
+}
+
+export function HoleFragment(props: { server?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <i>{label() as string}</i>
+ <Bold />
+ <s class="foreign">{'f'}</s>
+ </>
+ } @else {
+ <>
+ <i>{label() as string}</i>
+ <Bold />
+ </>
+ }
+ </div>
+}
+
+export function SwitchBranch(props: { server?: boolean }) @{
+ <div>
+ @switch (props.server ? 'server' : 'client') {
+ @case 'server': {
+ <>
+ <i>{label() as string}</i>
+ <s class="foreign">{'f'}</s>
+ </>
+ }
+ @default: {
+ <i>{label() as string}</i>
+ }
+ }
+ </div>
+}
+
+// Both sides render the outer `@if` arm; only the inner arm leaves a tail.
+export function NestedBranch(props: { server?: boolean }) @{
+ <div>
+ @if (true) {
+ <>
+ <Leaf />
+ @if (props.server) {
+ <>
+ <b>{'b'}</b>
+ <s class="foreign">{'f'}</s>
+ </>
+ } @else {
+ <b>{'b'}</b>
+ }
+ <u>{'u'}</u>
+ </>
+ }
+ </div>
+}
+
+// Only the outer arm leaves a tail, after an inner branch both sides render.
+export function OuterBranch(props: { server?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <Leaf />
+ @if (true) {
+ <b>{'b'}</b>
+ }
+ <u>{'u'}</u>
+ <s class="foreign">{'f'}</s>
+ </>
+ } @else {
+ <>
+ <Leaf />
+ @if (true) {
+ <b>{'b'}</b>
+ }
+ <u>{'u'}</u>
+ </>
+ }
+ </div>
+}
+
+// The client's last component finds the server's `<s>` where it expects its
+// range and adopts it without one. That `<s>` is client content now.
+export function UnframedComponent(props: { server?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <Bold />
+ <s>{'s'}</s>
+ <u class="foreign">{'tail'}</u>
+ </>
+ } @else {
+ <>
+ <Bold />
+ <Strike />
+ </>
+ }
+ </div>
+}
+
+function Slot(props: { render: ComponentBody }) @{
+ const Render = props.render;
+ <section>
+ <Render />
+ </section>
+}
+
+// The branch sits in a template that a helper passed as a render prop returns.
+export function HelperFragment(props: { server?: boolean }) @{
+ const render = () => @{
+ <div>
+ @if (props.server) {
+ <>
+ <i>{label() as string}</i>
+ <b>{'b'}</b>
+ <s class="foreign">{'f'}</s>
+ </>
+ } @else {
+ <>
+ <i>{label() as string}</i>
+ <b>{'b'}</b>
+ </>
+ }
+ </div>
+ };
+ <Slot render={render} />
+}
diff --git a/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx b/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
--- a/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
+++ b/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
@@ -116,6 +116,193 @@
</div>
}
+// The client's arm is one element, which adopts the first of the server's.
+export function IfHosts(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <em>{'x' as string}</em>
+ } @else {
+ <>
+ <em>{'x' as string}</em>
+ <b>{'z' as string}</b>
+ </>
+ }
+ </div>
+}
+
+// The two cases share their first elements, so the server's last one is the
+// only difference.
+export function SwitchHosts(props: { k: string }) @{
+ <div id="r">
+ @switch (props.k) {
+ @case 'one': {
+ <>
+ <em>{'x' as string}</em>
+ <b>{'z' as string}</b>
+ </>
+ }
+ @default: {
+ <>
+ <em>{'x' as string}</em>
+ <b>{'z' as string}</b>
+ <i>{'i' as string}</i>
+ </>
+ }
+ }
+ </div>
+}
+
+// The server's arm ends with static text after the element both arms share.
+export function IfTextTail(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <em>{'x' as string}</em>
+ } @else {
+ <>
+ <em>{'x' as string}</em>
+ tail
+ </>
+ }
+ </div>
+}
+
+// The client's root holds a component, whose range moves the cursor inside it.
+export function IfNestedRoot(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <p>
+ <Leaf v="x" />
+ </p>
+ } @else {
+ <>
+ <p>
+ <Leaf v="x" />
+ </p>
+ <b>{'z' as string}</b>
+ </>
+ }
+ </div>
+}
+
+// The client's arm ends with an element after a component range, and the
+// server's arm has another component after it.
+export function IfRangeAfterHost(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <>
+ <Leaf v="x" />
+ <b>{'b' as string}</b>
+ </>
+ } @else {
+ <>
+ <Leaf v="x" />
+ <b>{'b' as string}</b>
+ <Leaf v="z" />
+ </>
+ }
+ </div>
+}
+
+// The client's arm is a component that borrows the arm's range, so its
+// template adopts the first of the server's elements.
+export function IfInheritedHost(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <Leaf v="x" />
+ } @else {
+ <>
+ <em>{'x' as string}</em>
+ <b>{'z' as string}</b>
+ </>
+ }
+ </div>
+}
+
+// The arm's second component finds no server range, so it adopts the element
+// there in place, and the server's arm has another element after it.
+export function IfLaterHost(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <>
+ <Leaf v="x" />
+ <Leaf v="y" />
+ </>
+ } @else {
+ <>
+ <Leaf v="x" />
+ <em>{'y' as string}</em>
+ <b>{'z' as string}</b>
+ </>
+ }
+ </div>
+}
+
+// A hookless component whose body is a fragment (not a single host element).
+function FragLeaf(props: { v: string }) @{
+ <>
+ {props.v as string}
+ </>
+}
+
+// The arm's second component returns a fragment body, which finds no server
+// range and adopts the text node there in place. The server's arm has another
+// element after it that must be discarded.
+export function IfLaterFragment(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <>
+ <Leaf v="x" />
+ <FragLeaf v="y" />
+ </>
+ } @else {
+ <>
+ <Leaf v="x" />
+ y
+ <b>{'z' as string}</b>
+ </>
+ }
+ </div>
+}
+
+// A component in a hole of the arm's own template finds no server range and
+// adopts the element there in place. The template already recorded where the
+// arm ends, after its last root.
+export function HoleWithoutRange(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <>
+ <Leaf v="x" />
+ <b>{'b' as string}</b>
+ </>
+ } @else {
+ <>
+ <em>{'x' as string}</em>
+ <b>{'b' as string}</b>
+ </>
+ }
+ </div>
+}
+
+// A branch inside the arm's template, at its start and inside an element,
+// records where its own template ends without disturbing the arm's.
+export function NestedArms(props: { on: boolean; inner: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <>
+ @if (props.inner) {
+ <em>{'x' as string}</em>
+ }
+ <p>
+ @if (props.inner) {
+ <i>{'i' as string}</i>
+ }
+ </p>
+ <b>{'b' as string}</b>
+ </>
+ }
+ </div>
+}
+
export function Tail() @{
<u>{'tail' as string}</u>
}
diff --git a/packages/octane/tests/hydration/adopted-branch-tail.test.ts b/packages/octane/tests/hydration/adopted-branch-tail.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/octane/tests/hydration/adopted-branch-tail.test.ts
@@ -1,0 +1,210 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { act, flushSync, hydrateRoot } from '../../src/index.js';
+import * as ServerRT from 'octane/server';
+import { loadCompiledFixtureSource, loadServerFixture } from '../_server-fixture';
+
+// An @if or @switch slot adopts the server's range for its arm even when the
+// server rendered a different arm, as long as that range starts with what the
+// client arm renders. Whatever the server left after the client arm's content
+// is stale: hydration removes it and reports the mismatch once, while the
+// nodes the arm adopted keep their identity.
+
+const FIXTURE = join(
+ process.cwd(),
+ 'packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx',
+);
+const FILE = 'adopted-branch-tail.tsrx';
+const SOURCE = readFileSync(FIXTURE, 'utf8');
+const LINES = SOURCE.split('\n');
+
+/** The `file:line:col` of the first `directive` after the line containing `after`. */
+function siteOf(after: string, directive: string): string {
+ const start = LINES.findIndex((line) => line.includes(after));
+ if (start < 0) throw new Error(`fixture has no line containing ${after}`);
+ const index = LINES.findIndex((line, i) => i > start && line.includes(directive));
+ if (index < 0) throw new Error(`fixture has no ${directive} after ${after}`);
+ return `${FILE}:${index + 1}:${LINES[index].indexOf(directive)}`;
+}
+
+/** Element and text markup, ignoring hydration comments. */
+function markup(node: Element): string {
+ const copy = node.cloneNode(true) as Element;
+ const walker = document.createTreeWalker(copy, NodeFilter.SHOW_COMMENT);
+ const comments: Node[] = [];
+ while (walker.nextNode()) comments.push(walker.currentNode);
+ for (const comment of comments) comment.parentNode!.removeChild(comment);
... diff truncated: showing 800 of 1229 linesYou can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 2828027. Configure here.
A component that adopts a fragment or text in place reports no adoption from renderInPlace, so an arm that ends with one records no end and keeps the server content after it, as before. Say so in renderAdoptedArm and the changeset rather than claiming every in-place component. Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm
added a commit
that referenced
this pull request
Oct 2, 2026
… in place With #1600 merged, an @if/@switch arm reads its end from where its last in-place component parked the cursor. renderInPlace now parks it past every root a fragment template adopted (it previously stepped past the first root only, and only for a single root), so a server arm that continues after those roots is discarded and reported once at the directive. Pin that, and say so in the changeset. Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 of 5 tasks
trueadm
added a commit
that referenced
this pull request
Oct 2, 2026
… the changeset Main's #1602 and #1600 now handle the single-root and lite calls at a component hole in an adopted arm, so this branch's runtime change is reduced to the unframed (keyed or dynamic) path. A keyed call after the adopted static root pins that its stale node comes from its anchor rather than the lagging cursor, which would delete the adopted root. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
This is the element/text follow-up to #1564 that was agreed across the overlapping sessions. It supersedes the closed #1565.
When the server rendered a longer
@if/@switcharm, the client arm adopts the start of the server's arm range.discardArmTail(#1564, #1587) removes what follows a range the arm claimed. A template, though, leaves the cursor on the elements and text it adopts, so elements or text after the client arm's own roots stayed on screen, and nothing was reported. For example, with server<em>x</em><b>z</b>and client<em>x</em>, the<b>z</b>stayed. A component that adopted its root in place left the same kind of tail.renderAdoptedArmnow opens a claim on the arm's range (beginClaim/endClaim, from fix(hydration): discard the server tail of an adopted component range #1576).claimRoots). The cursor is then parked past them, the way a range claim parks it, anddiscardArmTailremoves the server content from there. It stops at client-built nodes and reports code 51 once, with a dev diagnostic at the directive.renderInPlace, singleRoot and lite) now parks the cursor throughparkPast. So the last such root records the arm's end, as a range claim does.template()'sfrag. Fixed-HTML ones were still pre-wrapped in<octane-frag>withfrag0, sotemplateRootCountparsed them in production. A branch inside a helper passed as a render prop compiles that way.parseTemplateadds the same wrapper when it parses one, so the parsed DOM is unchanged.Validation
Per Dominic's rule while the machine is overloaded, I ran no local test suites on this head. CI does the testing.
pnpm sync: no changes.pnpm format:files:checkon every changed file.pnpm typecheck:fileson the changed runtime, compiler, test and.tsrxfixture files.compiler-template-origins.test.tshas a pre-existing TS2769 on main at lines 149 and 151 (hmr: 'vite'), which this PR does not touch.pnpm format:check,pnpm typecheckandpnpm testwere not run locally; CI runs them.tests/hydration/branch-arm-tail.test.ts, in dev and prod compile plus a production-runtime block that stubsNODE_ENVand asserts no template is parsed. It covers element and text tails after a single root (IfHosts), a fragment (SwitchHosts), static text (IfTextTail), a root whose component moves the cursor into it (IfNestedRoot), and a range after a host (IfRangeAfterHost). It also covers a sole component (IfInheritedHost) and a later component (IfLaterHost) that adopt in place, with matching-arm guardsTrailingHosts,NestedArmsandHoleWithoutRange.tests/hydration/adopted-branch-tail.test.ts, from fix(hydration): discard the server content an adopted @if/@switch arm leaves unclaimed #1565, with code 337 replaced by 51. It runs in dev compile, prod compile, and prod compile with a prod runtime, and coversHelperFragment(the render-prop helper),OuterBranch,StaticFragment(a tail that repeats the last root's tag) andUnframedComponent(an in-place root stays and the tail after it goes).adoptArmrecord instead ofclaimRoots, passed the full octane plus octane-prod run (36,674 tests). A whole-suite probe on that version found discards only in the target tests.Performance
claimRootswalk the template already pays for in component claims), and oneparkPastafter an in-place adoption. No hot path gains a branch outside hydration.<octane-frag></octane-frag>and gain, 0, N.Risk / follow-ups
The compiler and runtime must match. An older compiler's
fragfor a multi-root template would make this runtime miscount roots. Both ship inoctane, and apps compile with their own copy.Parking the cursor past the arm template's roots means
sweepRebuiltTailno longer runs for an arm whose own template claimed its range. The template's record decides that tail instead.Not covered: a component in a no-template arm that adopts a fragment or text in place, without a server range.
renderInPlacereports no adoption for it, so the arm records no end and the server content after it stays, as on main. Tracking that extent meansrenderInPlacestepping past every adopted root, which changes fix(hydration): continue after a component adopted in place without a range #1567's sibling stepping, so it is left to a follow-up.Provenance
agent-authored)🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
Medium Risk
Changes core hydration cursor/claim logic for control-flow arms and requires compiler/runtime agreement on multi-root
fragcounts; mismatched versions could miscount roots, though both ship together inoctane.Overview
Fixes hydration when the client’s
@if/@switcharm is shorter than what the server rendered but still adopts the start of that arm’s DOM range. Extra server elements/text after the client arm’s real content used to remain visible with no error; they are now removed and surfaced as a single structural recoverable error (dev diagnostic at the directive, error #51 in production).Runtime:
renderAdoptedArmwraps the arm render in a claim so an arm-owned template can record where its roots end; the hydration cursor is parked past those roots (same idea as after a range claim). Top-level components that adopt a root in place callparkPastafterrenderInPlace.discardArmTailthen trims leftover server nodes from that point and reports once.Compiler: Multi-root templates are emitted as raw markup plus a root count (
frag) instead of baking in a synthetic<octane-frag>wrapper, so production hydration can find the arm boundary without parsing the template (including branches inside render-prop helpers).parseTemplatestill adds the wrapper when parsing when needed.Reviewed by Cursor Bugbot for commit ac9b42b. Bugbot is set up for automated code reviews on this repo. Configure here.