diff --git a/.agents/skills/webjs/references/components.md b/.agents/skills/webjs/references/components.md
index 7df1f4453..d91b4b04e 100644
--- a/.agents/skills/webjs/references/components.md
+++ b/.agents/skills/webjs/references/components.md
@@ -181,7 +181,7 @@ Errors are isolated per component by default (no user code): a thrown `await` re
The boundary also covers `watch(signal)` (its notify microtask) and `until()` (its promise resolution), which commit outside the update cycle. A throw from either used to surface at the window instead of the owning component. It routes to the component whose TEMPLATE holds the binding, which is not always the element the binding sits inside: `html`${watch(sig)}`` belongs to the parent that wrote it, not to `child-el`. The `asyncAppend` / `asyncReplace` path is NOT covered, in two distinct ways: its own iteration throw is swallowed to `console.error` on purpose (an author's iterable should handle it), and a `watch` / `until` nested inside a chunk it commits is installed with no owner in scope, so that one still reaches the window.
-**A commit that throws leaves the directive's own state consistent, so the NEXT valid render is correct.** (One reconciler is still exempt: a plain `.map()` array whose item TEMPLATE SHAPE changes in the same render that throws can strand a row. `repeat()` is the keyed path and is repaired.) This matters because the corruption is otherwise silent: the renders that expose it are fully valid and log nothing after the first throw. The hole whose commit threw is marked so the next render re-applies it rather than skipping it as unchanged (its recorded value is never advanced past a throw, and would otherwise match exactly what the recovering render supplies, leaving a child region blank for good). `repeat()` additionally repairs its key map so the map describes the DOM again, and the next render is an ordinary reconcile that repositions every row (the failure was a permanently duplicated row); it is deliberately NOT a rebuild of the region, which would discard the node identity keyed reconciliation exists to preserve. `guard()` records its new deps only once the commit succeeds, so a later render with those same deps re-renders the region instead of short-circuiting past a region the throw had blanked; `until()` advances its resolved priority only after the commit succeeds, so a failed high-priority resolution does not refuse the lower-priority one behind it.
+**A commit that throws leaves the directive's own state consistent, so the NEXT valid render is correct.** This matters because the corruption is otherwise silent: the renders that expose it are fully valid and log nothing after the first throw. The hole whose commit threw is marked so the next render re-applies it rather than skipping it as unchanged (its recorded value is never advanced past a throw, and would otherwise match exactly what the recovering render supplies, leaving a child region blank for good). Both list reconcilers additionally repair their own bookkeeping so it describes the DOM again, and the next render is an ordinary reconcile rather than a rebuild of the region, which would discard the node identity the reconcilers exist to preserve. `repeat()` re-unites its key map and repositions every row (the failure was a permanently duplicated row). A plain `.map()` array splices the part of its slot list the failed pass never reached back on, which matters whenever a slot is REPLACED rather than updated in place (its template shape changed, its kind changed between text, template and empty, or the array grew past its old length), since that is the branch that inserts the replacement before removing what it replaced (the failure was a stranded row that outlived even a render of an empty array). `guard()` records its new deps only once the commit succeeds, so a later render with those same deps re-renders the region instead of short-circuiting past a region the throw had blanked; `until()` advances its resolved priority only after the commit succeeds, so a failed high-priority resolution does not refuse the lower-priority one behind it.
**Teardown is total as well.** Removing a row is not a commit and has no retry, so a throw while tearing one down cannot be allowed to abandon the rest. Unbinding a `ref` during teardown can never abort the removal of the remaining rows, and `repeat()` drops each leftover key from its map before touching that row, so the map never describes a row that has already been removed (which used to leave the row the app DELETED on screen, reorder the survivors, and let a later render that re-added that key reinsert the disposed instance). To make that hold, a `ref` whose object `value` setter throws is now SWALLOWED on teardown, matching the ref CALLBACK, which was already swallowed everywhere. That is a deliberate divergence from lit, which guards neither and propagates from both. It applies to teardown only: on the COMMIT path a throwing object-ref setter still reaches `renderError()`, because there the boundary can report it and the next render can repair it.
diff --git a/packages/core/src/render-client.js b/packages/core/src/render-client.js
index 7b54427ac..b70f284e0 100644
--- a/packages/core/src/render-client.js
+++ b/packages/core/src/render-client.js
@@ -2055,42 +2055,107 @@ function reconcileArray(part, value) {
const old = state.items;
/** @type {ArrayItem[]} */
const next = [];
+ // How many slots of `old` are fully processed. Tracked rather than inferred
+ // from `next.length`, because the shrink loop below advances through `old`
+ // while `next` stops growing, so the two part company there. The catch is
+ // the only reader.
+ let consumed = 0;
- for (let i = 0; i < value.length; i++) {
- const v = value[i];
- const o = old[i];
- if (isTemplate(v)) {
- const tr = /** @type any */ (v);
- if (o && o.type === 'tpl' && o.inst.strings === tr.strings) {
- updateInstance(o.inst, tr.values);
- next.push(o);
- continue;
- }
- } else if (v != null && v !== false && v !== true) {
- if (o && o.type === 'text') {
- const str = String(v);
- if (o.node.data !== str) o.node.data = str;
- next.push(o);
+ try {
+ for (let i = 0; i < value.length; i++) {
+ const v = value[i];
+ const o = old[i];
+ if (isTemplate(v)) {
+ const tr = /** @type any */ (v);
+ if (o && o.type === 'tpl' && o.inst.strings === tr.strings) {
+ updateInstance(o.inst, tr.values);
+ next.push(o);
+ consumed = i + 1;
+ continue;
+ }
+ } else if (v != null && v !== false && v !== true) {
+ if (o && o.type === 'text') {
+ const str = String(v);
+ if (o.node.data !== str) o.node.data = str;
+ next.push(o);
+ consumed = i + 1;
+ continue;
+ }
+ } else {
+ // Empty slot: drop any prior nodes that occupied this position.
+ // Deliberately NOT reordered like the branch below. That reorder
+ // exists to keep a slot that was already BUILT and INSERTED tracked,
+ // and this branch builds and inserts nothing, so pushing first would
+ // only mean a throw from the removal leaves a phantom empty slot at
+ // this index AND `old[i]` spliced in at the next one, shifting every
+ // later slot by one in a POSITIONAL reconciler. Removing first, a
+ // throw here leaves `old[i]` describing its own position, which is
+ // still exactly where its nodes are.
+ if (o) removeArrayItem(o);
+ next.push({ type: 'empty' });
+ consumed = i + 1;
continue;
}
- } else {
- // Empty slot: drop any prior nodes that occupied this position.
+ // Shape changed, or the array grew past the old length. Build fresh,
+ // insert at this position (before the current / next still-attached
+ // old node, else the marker), then drop the old slot it replaced.
+ // The push sits BEFORE the removal, which is a pure reordering on the
+ // success path and means a slot that has already been built and
+ // inserted is never untracked at any throw point.
+ const { item, frag } = buildArrayItem(v);
+ if (frag) parent.insertBefore(frag, nextArrayAnchor(old, i, marker));
+ next.push(item);
if (o) removeArrayItem(o);
- next.push({ type: 'empty' });
- continue;
+ consumed = i + 1;
}
- // Shape changed, or the array grew past the old length. Build fresh,
- // insert at this position (before the current / next still-attached
- // old node, else the marker), then drop the old slot it replaced.
- const { item, frag } = buildArrayItem(v);
- if (frag) parent.insertBefore(frag, nextArrayAnchor(old, i, marker));
- if (o) removeArrayItem(o);
- next.push(item);
- }
- // Shrink: remove slots beyond the new length.
- for (let i = value.length; i < old.length; i++) removeArrayItem(old[i]);
- state.items = next;
+ // Shrink: remove slots beyond the new length.
+ for (let i = value.length; i < old.length; i++) {
+ removeArrayItem(old[i]);
+ consumed = i + 1;
+ }
+ state.items = next;
+ } catch (err) {
+ // `state.items` is committed only after the whole walk, so a throw part
+ // way through discards `next` entirely: the map of slots keeps describing
+ // positions whose nodes were already removed, while the freshly built and
+ // inserted ones are in the document tracked by nothing. Nothing is logged
+ // after the first throw, and the orphan outlives even a render of an EMPTY
+ // array, because the only code that could remove it walks `state.items`.
+ //
+ // Splice the untouched tail of `old` onto what `next` accumulated, so the
+ // bookkeeping describes the DOM again. The invariant that holds at any
+ // throw point: every live node is described by exactly one slot, the
+ // slots below `next.length` being the rebuilt or reused ones and the rest
+ // the part of `old` this pass never reached. Index alignment survives
+ // because this reconciler is POSITIONAL, so a slot's index IS its
+ // identity, which is also why the boundary has to come from `consumed`
+ // rather than `next.length`: during the shrink loop those differ, and
+ // splicing from `next.length` would re-describe slots already removed.
+ // A later render that grew the array would then match a live value
+ // against a DETACHED slot with the same `strings`, update it in place,
+ // and that row would silently never appear.
+ //
+ // Deliberately NOT a teardown-and-rebuild of the region, for the reason
+ // recorded on `reconcileRepeat`'s catch above: it discards node identity
+ // for every row, which cancels an in-progress native drag and drops focus
+ // and scroll.
+ //
+ // The residual is a throw from the removal step itself, which takes a
+ // throwing DOM to reach (the teardown it calls is total, so only
+ // `removeBetween` is left, and that calls `removeChild` solely on nodes
+ // the renderer owns). State it rather than deny it: `removeBetween`
+ // takes the start marker first and then early-returns for good once that
+ // marker is gone, so a row whose removal refused part-way can never be
+ // removed afterwards. Its remaining nodes stay in the document, and an
+ // EMPTY render will not clear them. Tracked or not, they are there for
+ // the life of the region, the same residual `reconcileRepeat`'s catch
+ // names. What this repair buys is that there is only ONE such row and
+ // every other slot still reconciles, where before the whole pass was
+ // discarded.
+ state.items = next.concat(old.slice(consumed));
+ throw err;
+ }
}
/**
diff --git a/packages/core/test/rendering/browser/directive-commit-throw.test.js b/packages/core/test/rendering/browser/directive-commit-throw.test.js
index 6f553a3d9..ea27437f3 100644
--- a/packages/core/test/rendering/browser/directive-commit-throw.test.js
+++ b/packages/core/test/rendering/browser/directive-commit-throw.test.js
@@ -286,6 +286,37 @@ suite('directive commit throws (browser)', () => {
);
});
+ test('a plain .map() array recovers a shape-changed row without losing identity', () => {
+ // The non-keyed reconciler updates in place, so the rows that were NOT
+ // rebuilt must survive the recovery as the same elements. linkedom can
+ // show the markup is right; only a real DOM can show it was repaired
+ // rather than rebuilt.
+ const view = (items) => html`
${items.map((it) => (
+ it.kind === 'a' ? html`
${it.v}
` : html`
${it.v}`
+ ))}
`;
+
+ render(view([{ kind: 'a', v: '1' }, { kind: 'a', v: '2' }]), container);
+ const before = [...container.querySelectorAll('p')];
+
+ throwsMatching(() => {
+ render(view([{ kind: 'b', v: '1' }, { kind: 'a', v: poison }]), container);
+ }, /boom/);
+
+ render(view([{ kind: 'b', v: '1' }, { kind: 'a', v: '2' }]), container);
+ const region = container.querySelector('div');
+ assert.deepEqual(
+ [...region.children].map((el) => `${el.tagName.toLowerCase()}:${el.textContent}`),
+ ['b:1', 'p:2'],
+ );
+ // Row 1 changed shape and was legitimately rebuilt; row 2 did not, and
+ // holding its identity is what proves this is a reconcile against
+ // repaired bookkeeping rather than a teardown of the region.
+ assert.strictEqual(region.querySelector('p'), before[1]);
+
+ render(view([]), container);
+ assert.equal(container.querySelector('div').children.length, 0);
+ });
+
test('removing rows after recovery leaves nothing behind', () => {
render(rows(good), container);
throwsMatching(() => {
diff --git a/packages/core/test/rendering/directive-commit-throw.test.js b/packages/core/test/rendering/directive-commit-throw.test.js
index 409c34df9..138bc815b 100644
--- a/packages/core/test/rendering/directive-commit-throw.test.js
+++ b/packages/core/test/rendering/directive-commit-throw.test.js
@@ -316,6 +316,111 @@ test('a plain template child hole recovers too (not just repeat)', () => {
assert.equal(container.querySelector('span').textContent, 'ok');
});
+// --- plain .map() arrays (the non-keyed child reconciler) ---
+
+/** Rendered markup of the array region, with the renderer's markers stripped. */
+function regionHTML(container) {
+ return container.querySelector('div').innerHTML.replace(//g, '');
+}
+
+// The REPLACE branch is the destructive one: it inserts the replacement and
+// removes the old slot BEFORE the walk can finish. An in-place update touches
+// only values and cannot reach it. Three different things route there, and
+// the cases below cover more than one, because narrowing this to "the
+// template shape changed" would leave the others untested: the item's
+// template shape changed, its slot KIND changed (text, template, empty), or
+// the array GREW past the old length, where there is no old slot to compare
+// against at all.
+
+test('array: a mid-walk throw does not strand a row on the next valid render', () => {
+ const container = document.createElement('div');
+ const view = (items) => html`${items.map((it) => (
+ it.kind === 'a' ? html`
${it.v}
` : html`
${it.v}`
+ ))}
`;
+
+ render(view([{ kind: 'a', v: '1' }, { kind: 'a', v: '2' }]), container);
+ assert.equal(regionHTML(container), '1
2
');
+
+ // Item 0 changes shape (destructive) and item 1's child hole then throws.
+ assert.throws(() => {
+ render(view([{ kind: 'b', v: '1' }, { kind: 'a', v: poison }]), container);
+ }, /boom/);
+
+ // The freshly built used to be tracked by nothing, so it survived
+ // alongside a rebuilt copy of itself: 112
.
+ render(view([{ kind: 'b', v: '1' }, { kind: 'a', v: '2' }]), container);
+ assert.equal(regionHTML(container), '12
');
+
+ // Not merely delayed by one render.
+ render(view([{ kind: 'b', v: '1' }, { kind: 'a', v: '2' }]), container);
+ assert.equal(regionHTML(container), '12
');
+});
+
+test('array: a GROWN array reaches the same branch, with no shape change at all', () => {
+ // Every item here is the same template shape, so nothing about this render
+ // is a "shape change". The new tail index simply has no old slot to reuse,
+ // which routes it to the same build-insert-remove branch.
+ const container = document.createElement('div');
+ const view = (items) => html`${items.map((v) => html`
${v}
`)}
`;
+
+ render(view(['1']), container);
+ assert.throws(() => { render(view(['1', '2', poison]), container); }, /boom/);
+
+ render(view(['1', '2', '3']), container);
+ assert.equal(regionHTML(container), '1
2
3
');
+ render(view([]), container);
+ assert.equal(regionHTML(container), '');
+});
+
+test('array: an EMPTY render after a throw leaves nothing behind', () => {
+ const container = document.createElement('div');
+ const view = (items) => html`${items.map((it) => (
+ it.kind === 'a' ? html`
${it.v}
` : html`
${it.v}`
+ ))}
`;
+
+ render(view([{ kind: 'a', v: '1' }, { kind: 'a', v: '2' }]), container);
+ assert.throws(() => {
+ render(view([{ kind: 'b', v: '1' }, { kind: 'a', v: poison }]), container);
+ }, /boom/);
+
+ // The sharpest probe there is: the only code that could remove a slot walks
+ // the tracked list, so anything tracked by nothing outlives even a render
+ // that asks for no rows at all.
+ render(view([]), container);
+ assert.equal(regionHTML(container), '');
+});
+
+test('array: a throw in the SHRINK loop leaves no slot describing a detached row', () => {
+ // The shrink loop advances through the old slots while the replacement list
+ // stops growing, so this is the case that separates the processed-slot
+ // cursor from the replacement list's length. Splicing from the latter would
+ // re-describe an already-removed slot, and the bug only surfaces later, on a
+ // render that GROWS the array back.
+ const container = document.createElement('div');
+ const view = (items) => html`${items.map((v) => html`
${v}
`)}
`;
+
+ render(view(['1', '2', '3', '4']), container);
+ const region = container.querySelector('div');
+ const fourth = [...region.querySelectorAll('p')][3];
+
+ const origRemove = region.removeChild.bind(region);
+ region.removeChild = (node) => {
+ if (node === fourth) throw new Error('rm-boom');
+ return origRemove(node);
+ };
+
+ // Drop the last two. Slot 2 is removed cleanly, slot 3 refuses part-way.
+ assert.throws(() => { render(view(['1', '2']), container); }, /rm-boom/);
+ region.removeChild = origRemove;
+
+ // Grow back. The already-removed slot must not still be described, or its
+ // detached instance matches by shape, is updated in place, and that row
+ // silently never appears.
+ render(view(['1', '2', '3', '4']), container);
+ assert.equal([...region.querySelectorAll('p')].length, 4, 'every row must render');
+ assert.deepEqual([...region.querySelectorAll('p')].map((p) => p.textContent), ['1', '2', '3', '4']);
+});
+
// --- guard() ---
test('guard: a throw during the commit does not blank the region forever', () => {
diff --git a/website/app/docs/error-handling/page.ts b/website/app/docs/error-handling/page.ts
index d678389a9..a6f2eab3b 100644
--- a/website/app/docs/error-handling/page.ts
+++ b/website/app/docs/error-handling/page.ts
@@ -127,7 +127,7 @@ export default function GlobalError({ error }: { error: Error }) {
A directive that throws mid-commit stays consistent
The component boundary above also covers watch(signal) and until(), which commit outside the update cycle, so a throw from either reaches renderError() rather than the window. It reaches the component whose template holds the binding, which is not always the element the binding sits inside: a watch() written between a child component's tags belongs to the parent that wrote it. asyncAppend / asyncReplace are not covered, in two ways: that path logs its own iteration throw and continues on purpose, and a watch() or until() nested inside a chunk it commits still reaches the window.
- Beyond reporting the error, the directive's own state is left describing the DOM that actually exists, which is what makes the NEXT render correct. That matters because the failure is otherwise silent: the renders that expose it are fully valid and log nothing. The hole whose commit threw is marked so the next render re-applies it instead of skipping it as unchanged, which is what used to leave a region blank for good. repeat() additionally repairs its key map so it describes the DOM again, and the next render is an ordinary reconcile that repositions every row (the symptom was a permanently duplicated row); it deliberately does not rebuild the region, which would throw away the node identity keyed reconciliation exists to preserve. guard() records its new deps only once the commit succeeds, so a later render with those deps re-renders the region instead of skipping past one the throw had blanked; until() advances its resolved priority only after its commit succeeds, so a failed high-priority resolution does not refuse the lower-priority one behind it.
+ Beyond reporting the error, the directive's own state is left describing the DOM that actually exists, which is what makes the NEXT render correct. That matters because the failure is otherwise silent: the renders that expose it are fully valid and log nothing. The hole whose commit threw is marked so the next render re-applies it instead of skipping it as unchanged, which is what used to leave a region blank for good. Both list reconcilers additionally repair their own bookkeeping so it describes the DOM again, and the next render is an ordinary reconcile rather than a rebuild of the region, which would throw away the node identity they exist to preserve. repeat() re-unites its key map and repositions every row (the symptom was a permanently duplicated row). A plain .map() array splices back the part of its slot list the failed pass never reached, which is what a slot REPLACED rather than updated in place needs (its template shape changed, its kind changed between text, template and empty, or the array grew past its old length), since that is the branch that inserts the replacement before removing what it replaced (the symptom was a stranded row that outlived even a render of an empty array). guard() records its new deps only once the commit succeeds, so a later render with those deps re-renders the region instead of skipping past one the throw had blanked; until() advances its resolved priority only after its commit succeeds, so a failed high-priority resolution does not refuse the lower-priority one behind it.
Tearing content back out is covered too, and it has to be, because a teardown has no next render to repair it. Unbinding a ref while a row is removed can never abort the removal of the rest of the list, and repeat() drops each leftover key from its map before touching that row, so the map never describes a row that has already been removed. Without that, a throw part-way through left the row you had DELETED on screen, reordered the survivors, and let a later render that re-added the key reinsert the disposed instance. The cost is that a ref whose object value setter throws is swallowed on teardown, matching the ref callback, which was already swallowed everywhere (lit guards neither and propagates from both, so this is a deliberate divergence). It applies to teardown only: on the COMMIT path a throwing object-ref setter still reaches renderError().
Server action errors