Backtestsvuerun-20261003-231210#14403

Issue #14403 Merged fix PR #14411 Run 3 Oct 2026 · run-20261003-231210 vuejs/core

Preserve input values entered during hydration

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches use the same root-cause fix. During hydration, the v-model `created` hook runs on an element that is already attached to the DOM. Each patch detects that via `parentNode` and then, in `mounted`, syncs the user-entered DOM value back into the model instead of overwriting it.

Patch B only handles `vModelText` for `el.type === 'text'` and textarea. Common inputs such as email, password, search, number and tel are still reset, so the issue as reported (forms in general) is only partly fixed. It does not cover checkbox, radio or select at all. Its CR/LF normalization is a reasonable detail. Its single test covers just the basic text case.

Patch A covers text-like inputs of any type. It avoids false positives from browser value sanitization (range clamping, email trimming) by cloning the input and assigning `defaultValue` to the clone. It also applies `.number`/`.trim` casting, including the implicit cast for `type=number`. Beyond text, it handles:
- checkboxes, including several checkboxes bound to the same array/Set model, using a pending-model map so each assignment builds on the previous one;
- radios, where only the newly checked radio assigns;
- single and multiple selects, with careful default-selection detection that accounts for disabled options and optgroups;
- dynamic type through the existing delegation.

The event-handler logic is refactored into shared `assignCheckboxValue`/`assignSelectValue` helpers rather than duplicated.

Patch A's test suite is extensive and meaningful. It includes negative cases: an unmodified input, sanitized values that should not count as user input, and a select with no matching option. These tests would fail before the change.

The pendingCheckboxModels mechanism adds some complexity and risk. Even so, Patch A is far more complete against the issue's ask (preserving form input during hydration) and better tested. Patch B leaves most form controls broken.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

15m 20s

Wall-clock time in the container

Full test suite

No new failures

3,662 passed · 6 skipped · 3,668 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

429vs 50 merged

Changed lines, ours vs merged

Vue version

3.5.27

Link to minimal reproduction

https://github.com/nuxt/nuxt/issues/29206

Steps to reproduce

user loads a page with a slow internet connection
starts entering some values ​​into the input with v-model
after all browser resources loaded - input v-model reset to default value

What is expected?

entered input value is preserved once hydration completes

What is actually happening?

input value is reset to its default value

System Info

Any additional comments?

This is affecting UX when interacting with inputs/forms in slowly loading apps, where values entered during hydration phase are erased and the progress is lost. I have been blocking all forms myself until mounted hook fires to workaround this issue - it would be great to not have to!

The two patches

Our patch+380 −49
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..1338903a4 100644@@ -921,6 +921,193 @@ describe('SSR hydration', () => {     expect(text.textContent).toBe('bye')   }) +  describe('preserve user input made before hydration', () => {+    // server render, simulate user interaction on the static markup, then+    // hydrate and return the reactive state + rendered output+    async function hydrateAfterInput<T extends Record<string, any>>(+      template: string,+      data: () => T,+      interact: (container: HTMLElement) => void,+    ) {+      const App = defineComponent({+        data,+        template: `<div>${template}<span class="out">{{ $data }}</span></div>`,+      })+      const container = document.createElement('div')+      container.innerHTML = await renderToString(h(App))+      interact(container)+      const vm = createSSRApp(App).mount(container) as any+      await nextTick()+      return { vm, container }+    }++    test('text input', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<input v-model="text">`,+        () => ({ text: 'foo' }),+        c => (c.querySelector('input')!.value = 'typed'),+      )+      expect(container.querySelector('input')!.value).toBe('typed')+      expect(vm.text).toBe('typed')+      expect(container.querySelector('.out')!.textContent).toContain('typed')+    })++    test('text input with modifiers', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<input v-model.number="num"><input v-model.trim.lazy="text">`,+        () => ({ num: 1, text: '' }),+        c => {+          const [a, b] = c.querySelectorAll('input')+          a.value = '42'+          b.value = '  hi  '+        },+      )+      expect(vm.num).toBe(42)+      expect(vm.text).toBe('hi')+      expect(container.querySelectorAll('input')[0].value).toBe('42')+    })++    test('textarea', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<textarea v-model="text"></textarea>`,+        () => ({ text: 'foo' }),+        c => (c.querySelector('textarea')!.value = 'typed'),+      )+      expect(container.querySelector('textarea')!.value).toBe('typed')+      expect(vm.text).toBe('typed')+    })++    test('text input not modified by user', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<input v-model="text">`,+        () => ({ text: 'foo' }),+        () => {},+      )+      expect(container.querySelector('input')!.value).toBe('foo')+      expect(vm.text).toBe('foo')+    })++    test('value sanitized by the browser is not treated as user input', async () => {+      const { vm } = await hydrateAfterInput(+        `<input type="range" v-model="empty">` ++          `<input type="range" max="100" v-model="clamped">` ++          `<input type="email" v-model="email">`,+        () => ({ empty: null, clamped: 150, email: ' a@b.c ' }),+        () => {},+      )+      expect(vm.empty).toBe(null)+      expect(vm.clamped).toBe(150)+      expect(vm.email).toBe(' a@b.c ')+    })++    test('range input modified by user', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<input type="range" v-model="num">`,+        () => ({ num: null }),+        c => (c.querySelector('input')!.value = '20'),+      )+      expect(container.querySelector('input')!.value).toBe('20')+      expect(vm.num).toBe('20')+    })++    test('checkbox', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<input type="checkbox" v-model="ok">` ++          `<input type="checkbox" value="a" v-model="list">` ++          `<input type="checkbox" value="b" v-model="list">`,+        () => ({ ok: false, list: ['a'] }),+        c => {+          const [ok, a, b] = c.querySelectorAll('input')+          ok.checked = true+          a.checked = false+          b.checked = true+        },+      )+      const [ok, a, b] = container.querySelectorAll('input')+      expect(vm.ok).toBe(true)+      expect(vm.list).toEqual(['b'])+      expect(ok.checked).toBe(true)+      expect(a.checked).toBe(false)+      expect(b.checked).toBe(true)+    })++    test('multiple checkboxes checked on the same array model', async () => {+      const { vm } = await hydrateAfterInput(+        `<input type="checkbox" value="a" v-model="list">` ++          `<input type="checkbox" value="b" v-model="list">` ++          `<input type="checkbox" value="c" v-model="list">`,+        () => ({ list: ['a'] }),+        c => {+          const [, b, cc] = c.querySelectorAll('input')+          b.checked = true+          cc.checked = true+        },+      )+      expect(vm.list).toEqual(['a', 'b', 'c'])+    })++    test('radio', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<input type="radio" name="r" value="a" v-model="picked">` ++          `<input type="radio" name="r" value="b" v-model="picked">`,+        () => ({ picked: 'a' }),+        c => (c.querySelectorAll('input')[1].checked = true),+      )+      const [a, b] = container.querySelectorAll('input')+      expect(vm.picked).toBe('b')+      expect(a.checked).toBe(false)+      expect(b.checked).toBe(true)+    })++    test('dynamic type (vModelDynamic)', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<input :type="type" v-model="ok">`,+        () => ({ type: 'checkbox', ok: false }),+        c => (c.querySelector('input')!.checked = true),+      )+      expect(vm.ok).toBe(true)+      expect(container.querySelector('input')!.checked).toBe(true)+    })++    test('select', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<select v-model="selected">` ++          `<option value="a">a</option><option value="b">b</option>` ++          `</select>`,+        () => ({ selected: 'a' }),+        c => (c.querySelector('select')!.value = 'b'),+      )+      expect(vm.selected).toBe('b')+      expect(container.querySelector('select')!.value).toBe('b')+    })++    test('select multiple', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<select multiple v-model="selected">` ++          `<option value="a">a</option><option value="b">b</option>` ++          `</select>`,+        () => ({ selected: ['a'] }),+        c => (c.querySelectorAll('option')[1].selected = true),+      )+      expect(vm.selected).toEqual(['a', 'b'])+      const options = container.querySelectorAll('option')+      expect(options[0].selected).toBe(true)+      expect(options[1].selected).toBe(true)+    })++    test('select with no matching option is left untouched', async () => {+      const { vm, container } = await hydrateAfterInput(+        `<select v-model="selected">` ++          `<option value="a">a</option><option value="b">b</option>` ++          `</select>`,+        () => ({ selected: null as string | null }),+        () => {},+      )+      expect(vm.selected).toBe(null)+      expect(container.querySelector('select')!.selectedIndex).toBe(-1)+    })+  })+   test('handle click error in ssr mode', async () => {     const App = {       setup() {packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..51f7d2598 100644@@ -40,11 +40,35 @@ function onCompositionEnd(e: Event) { const assignKey: unique symbol = Symbol('_assign')  type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<-  T & { [assignKey]: AssignerFn; _assigning?: boolean },+  T & {+    [assignKey]: AssignerFn+    _assigning?: boolean+    _userModified?: boolean+  },   any,   Modifiers > +// During hydration, directive `created` hooks run on the existing+// server-rendered element, which is already attached to its parent. Freshly+// created elements are only inserted after `beforeMount`, so they never have+// a parent at this point.+function isHydratingElement(el: Element): boolean {+  return el.parentNode != null+}++// whether the value of a server-rendered element was changed by the user.+// The browser sanitizes an input's value based on its type (e.g. range inputs+// clamp to min/max, email inputs trim whitespace), so compare against the+// sanitized server value rather than the raw `value` attribute.+function isValueModified(el: HTMLInputElement | HTMLTextAreaElement): boolean {+  if (el.value === el.defaultValue) return false+  if (el.tagName !== 'INPUT') return true+  const probe = el.cloneNode() as HTMLInputElement+  probe.value = el.defaultValue+  return el.value !== probe.value+}+ function castValue(value: string, trim?: boolean, number?: boolean | null) {   if (trim) value = value.trim()   if (number) value = looseToNumber(value)@@ -79,9 +103,21 @@ export const vModelText: ModelDirective<       // fires "change" instead of "input" on autocomplete.       addEventListener(el, 'change', onCompositionEnd)     }+    // the user may have typed into the server-rendered element before+    // hydration completed - preserve that input instead of resetting it.+    if (isHydratingElement(el) && isValueModified(el)) {+      el._userModified = true+    }   },   // set value on mounted so it's after min/max for type="range"-  mounted(el, { value }) {+  mounted(el, { value, modifiers: { trim, number } }, vnode) {+    if (el._userModified) {+      el._userModified = false+      const castToNumber =+        number || (vnode.props && vnode.props.type === 'number')+      el[assignKey](castValue(el.value, trim, castToNumber))+      return+    }     el.value = value == null ? '' : value   },   beforeUpdate(@@ -126,42 +162,83 @@ export const vModelCheckbox: ModelDirective<HTMLInputElement> = {   deep: true,   created(el, _, vnode) {     el[assignKey] = getModelAssigner(vnode)-    addEventListener(el, 'change', () => {-      const modelValue = (el as any)._modelValue-      const elementValue = getValue(el)-      const checked = el.checked-      const assign = el[assignKey]-      if (isArray(modelValue)) {-        const index = looseIndexOf(modelValue, elementValue)-        const found = index !== -1-        if (checked && !found) {-          assign(modelValue.concat(elementValue))-        } else if (!checked && found) {-          const filtered = [...modelValue]-          filtered.splice(index, 1)-          assign(filtered)-        }-      } else if (isSet(modelValue)) {-        const cloned = new Set(modelValue)-        if (checked) {-          cloned.add(elementValue)-        } else {-          cloned.delete(elementValue)+    addEventListener(el, 'change', () => assignCheckboxValue(el))+    // preserve a checked state toggled by the user before hydration completed+    if (isHydratingElement(el) && el.checked !== el.defaultChecked) {+      el._userModified = true+    }+  },+  // set initial checked on mount to wait for true-value/false-value+  mounted(el, binding, vnode) {+    if (el._userModified) {+      el._userModified = false+      const original = binding.value+      const isCollection = isArray(original) || isSet(original)+      ;(el as any)._modelValue =+        isCollection && pendingCheckboxModels.has(original)+          ? pendingCheckboxModels.get(original)+          : original+      const assigned = assignCheckboxValue(el)+      if (isCollection) {+        if (!pendingCheckboxModels.size) {+          nextTick(() => pendingCheckboxModels.clear())         }-        assign(cloned)-      } else {-        assign(getCheckboxValue(el, checked))+        pendingCheckboxModels.set(original, assigned)       }-    })+      return+    }+    setChecked(el, binding, vnode)   },-  // set initial checked on mount to wait for true-value/false-value-  mounted: setChecked,   beforeUpdate(el, binding, vnode) {     el[assignKey] = getModelAssigner(vnode)     setChecked(el, binding, vnode)   }, } +// Array / Set models assigned by checkboxes synced on hydration, keyed by the+// model value they were rendered with. Checkboxes sharing the same model are+// all mounted before the assignment re-renders, so each one must build upon+// the value assigned by the previous one instead of the stale binding value.+const pendingCheckboxModels = new Map<any, any>()++// assigns the checkbox state to the model, returns the resulting model value+function assignCheckboxValue(+  el: HTMLInputElement & { [assignKey]: AssignerFn },+): any {+  const modelValue = (el as any)._modelValue+  const elementValue = getValue(el)+  const checked = el.checked+  const assign = el[assignKey]+  if (isArray(modelValue)) {+    const index = looseIndexOf(modelValue, elementValue)+    const found = index !== -1+    if (checked && !found) {+      const added = modelValue.concat(elementValue)+      assign(added)+      return added+    } else if (!checked && found) {+      const filtered = [...modelValue]+      filtered.splice(index, 1)+      assign(filtered)+      return filtered+    }+    return modelValue+  } else if (isSet(modelValue)) {+    const cloned = new Set(modelValue)+    if (checked) {+      cloned.add(elementValue)+    } else {+      cloned.delete(elementValue)+    }+    assign(cloned)+    return cloned+  } else {+    const value = getCheckboxValue(el, checked)+    assign(value)+    return value+  }+}+ function setChecked(   el: HTMLInputElement,   { value, oldValue }: DirectiveBinding,@@ -189,12 +266,28 @@ function setChecked(  export const vModelRadio: ModelDirective<HTMLInputElement> = {   created(el, { value }, vnode) {-    el.checked = looseEqual(value, vnode.props!.value)+    if (isHydratingElement(el) && el.checked !== el.defaultChecked) {+      // the user changed the selection before hydration completed - keep the+      // current DOM state and sync it back to the model on mount.+      el._userModified = true+    } else {+      el.checked = looseEqual(value, vnode.props!.value)+    }     el[assignKey] = getModelAssigner(vnode)     addEventListener(el, 'change', () => {       el[assignKey](getValue(el))     })   },+  mounted(el) {+    if (el._userModified) {+      el._userModified = false+      // only the radio the user selected updates the model; the previously+      // selected radio of the same group was unchecked as a side effect.+      if (el.checked) {+        el[assignKey](getValue(el))+      }+    }+  },   beforeUpdate(el, { value, oldValue }, vnode) {     el[assignKey] = getModelAssigner(vnode)     if (value !== oldValue) {@@ -208,29 +301,21 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = {   deep: true,   created(el, { value, modifiers: { number } }, vnode) {     ;(el as any)._modelValue = value-    addEventListener(el, 'change', () => {-      const selectedVal = Array.prototype.filter-        .call(el.options, (o: HTMLOptionElement) => o.selected)-        .map((o: HTMLOptionElement) =>-          number ? looseToNumber(getValue(o)) : getValue(o),-        )-      el[assignKey](-        el.multiple-          ? isSet((el as any)._modelValue)-            ? new Set(selectedVal)-            : selectedVal-          : selectedVal[0],-      )-      el._assigning = true-      nextTick(() => {-        el._assigning = false-      })-    })+    addEventListener(el, 'change', () => assignSelectValue(el, number))     el[assignKey] = getModelAssigner(vnode)+    // preserve a selection made by the user before hydration completed+    if (isHydratingElement(el) && isSelectionModified(el)) {+      el._userModified = true+    }   },   // set value in mounted & updated because <select> relies on its children   // <option>s.-  mounted(el, { value }) {+  mounted(el, { value, modifiers: { number } }) {+    if (el._userModified) {+      el._userModified = false+      assignSelectValue(el, number)+      return+    }     setSelected(el, value)   },   beforeUpdate(el, { value }, vnode) {@@ -244,6 +329,65 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = {   }, } +function assignSelectValue(+  el: HTMLSelectElement & { [assignKey]: AssignerFn; _assigning?: boolean },+  number: boolean | undefined,+) {+  const selectedVal = Array.prototype.filter+    .call(el.options, (o: HTMLOptionElement) => o.selected)+    .map((o: HTMLOptionElement) =>+      number ? looseToNumber(getValue(o)) : getValue(o),+    )+  el[assignKey](+    el.multiple+      ? isSet((el as any)._modelValue)+        ? new Set(selectedVal)+        : selectedVal+      : selectedVal[0],+  )+  el._assigning = true+  nextTick(() => {+    el._assigning = false+  })+}++// whether the current selection differs from the one defined by the+// server-rendered `selected` attributes.+function isSelectionModified(el: HTMLSelectElement): boolean {+  const options = el.options+  if (el.multiple) {+    return Array.prototype.some.call(+      options,+      (o: HTMLOptionElement) => o.selected !== o.defaultSelected,+    )+  }+  // single select: the last option with a `selected` attribute wins, or the+  // browser selects the first non-disabled option when the select is+  // rendered as a drop-down and no option has the attribute.+  let defaultIndex = -1+  for (let i = options.length - 1; i >= 0; i--) {+    if (options[i].defaultSelected) {+      defaultIndex = i+      break+    }+  }+  if (defaultIndex === -1 && el.size <= 1) {+    defaultIndex = Array.prototype.findIndex.call(+      options,+      (o: HTMLOptionElement) => !isOptionDisabled(o),+    )+  }+  return el.selectedIndex !== defaultIndex+}++function isOptionDisabled(option: HTMLOptionElement): boolean {+  const parent = option.parentNode as HTMLOptGroupElement | null+  return (+    option.disabled ||+    (parent != null && parent.nodeName === 'OPTGROUP' && parent.disabled)+  )+}+ function setSelected(el: HTMLSelectElement, value: any) {   const isMultiple = el.multiple   const isArrayValue = isArray(value) 
Merged fix · PR #14411+47 −3
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..49c39bdd6 100644@@ -1692,6 +1692,24 @@ describe('SSR hydration', () => {     expect((container.firstChild as any)._trueValue).toBe(true)   }) +  test('preserves text entered before v-model hydration', async () => {+    const state = reactive({ text: 'server value' })+    const App = {+      setup: () => state,+      template: `<input v-model="text">`,+    }+    const container = document.createElement('div')+    container.innerHTML = await renderToString(h(App))+    const input = container.firstChild as HTMLInputElement+    input.value = 'user value'++    createSSRApp(App).mount(container)+    await nextTick()++    expect(input.value).toBe('user value')+    expect(state.text).toBe('user value')+  })+   test('force hydrate checkbox with indeterminate', () => {     const { container } = mountWithHydration(       '<input type="checkbox" indeterminate>',packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..eeb248f28 100644@@ -38,9 +38,14 @@ function onCompositionEnd(e: Event) { }  const assignKey: unique symbol = Symbol('_assign')+const initialValueKey: unique symbol = Symbol('_initialValue')  type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<-  T & { [assignKey]: AssignerFn; _assigning?: boolean },+  T & {+    [assignKey]: AssignerFn+    [initialValueKey]?: string+    _assigning?: boolean+  },   any,   Modifiers >@@ -58,6 +63,16 @@ export const vModelText: ModelDirective<   'trim' | 'number' | 'lazy' > = {   created(el, { modifiers: { lazy, trim, number } }, vnode) {+    // During hydration, created runs on an element already in the DOM.+    if (el.parentNode) {+      if (el.type === 'text') {+        // Text inputs strip CR/LF from value, while defaultValue retains them.+        el[initialValueKey] = el.defaultValue.replace(/[\r\n]/g, '')+      } else if (el.type === 'textarea') {+        // Textareas normalize CRLF/CR to LF in value.+        el[initialValueKey] = el.defaultValue.replace(/\r\n?/g, '\n')+      }+    }     el[assignKey] = getModelAssigner(vnode)     const castToNumber =       number || (vnode.props && vnode.props.type === 'number')@@ -81,8 +96,19 @@ export const vModelText: ModelDirective<     }   },   // set value on mounted so it's after min/max for type="range"-  mounted(el, { value }) {-    el.value = value == null ? '' : value+  mounted(el, { value, modifiers: { trim, number } }) {+    const newValue = value == null ? '' : value+    const initialValue = el[initialValueKey]+    delete el[initialValueKey]+    if (+      initialValue !== undefined &&+      (el.type === 'text' || el.type === 'textarea') &&+      el.value !== initialValue+    ) {+      el[assignKey](castValue(el.value, trim, number))+    } else {+      el.value = newValue+    }   },   beforeUpdate(     el,