Backtestsvuerun-20261007-145226#14403

Issue #14403 Merged fix PR #14411 Run 7 Oct 2026 · run-20261007-145226 vuejs/core

Preserve input values entered during hydration

Better

Our patch was judged better than the merged fix.

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

Both patches use the same core approach. In `created`, they detect that the element is being hydrated (`el.parentNode` is set). In `mounted`, if the live DOM value differs from the server-rendered default, they keep that value and push it into the model instead of overwriting it.

Patch A only handles `el.type === 'text'` and textarea. Inputs typed `email`, `password`, `number`, `tel`, `search` and so on, plus checkboxes, radios and selects, would all still be reset on hydration. Those are common in the forms the issue describes. A also normalizes newlines with hand-written regexes to approximate browser sanitization, which only works because it is limited to text and textarea.

Patch B fixes the root cause across every v-model directive:
- **Text-like inputs:** it handles any type. It compares against a clone that has the default value applied, so browser sanitization for range, color and stripped line breaks is respected generically.
- **`.number` and `type=number`:** these are cast correctly when syncing to the model.
- **Checkboxes:** it handles single checkboxes and groups bound to arrays or Sets. Several checkboxes toggled before hydration have their updates chained through a WeakMap, because `binding.value` is stale until the next render.
- **Radios:** it keeps the user's checked state and assigns the model only from the checked radio.
- **Selects:** it handles single and multiple selects. It works out the browser-default selection, including the fallback to the first non-disabled option.

B refactors the listener bodies into `assignCheckboxValue` and `assignSelectValue` so the hydration path can reuse them. That adds some complexity, most notably the pending-checkbox map. However, the logic is coherent, and the refactor keeps the existing listener behavior the same.

On tests, A adds a single text-input test. B adds a thorough suite that would fail before its change: text, trim/number modifiers, textarea, dynamic type, checkbox, Set-bound checkbox group, radio, single and multiple select. It also adds regression tests confirming that untouched elements, including sanitized range, color and text values, are not falsely treated as user-edited.

B is clearly the more correct and better-tested fix for the reported UX problem. Its extra complexity is justified by the breadth of the bug.

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

11m 18s

Wall-clock time in the container

Full test suite

No new failures

3,659 passed · 6 skipped · 3,665 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

437vs 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+388 −49
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..dc3b8e705 100644@@ -1717,6 +1717,208 @@ describe('SSR hydration', () => {     )     expect((container.firstChild!.firstChild as any)._value).toBe(true)   })+  describe('preserve v-model values entered before hydration', () => {+    // render on the server, let the user interact with the SSR markup via+    // `interact`, then hydrate and return the container + component state+    async function hydrateAfterInteraction(+      template: string,+      data: Record<string, any>,+      interact: (container: Element) => void,+    ) {+      const Comp = {+        template,+        setup() {+          return reactive({ ...data })+        },+      }+      const container = document.createElement('div')+      container.innerHTML = await renderToString(createSSRApp(Comp))+      interact(container)+      const app = createSSRApp(Comp)+      const state = app.mount(container) as any+      await nextTick()+      return { container, state }+    }++    test('text input', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input v-model="text">`,+        { text: 'foo' },+        c => (c.querySelector('input')!.value = 'typed'),+      )+      expect(container.querySelector('input')!.value).toBe('typed')+      expect(state.text).toBe('typed')+      expect(`Hydration`).not.toHaveBeenWarned()+    })++    test('text input with .trim / .number modifiers', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input v-model.trim="text"><input type="number" v-model="num">`,+        { text: '', num: 1 },+        c => {+          const [text, num] = c.querySelectorAll('input')+          text.value = '  typed  '+          num.value = '42'+        },+      )+      expect(state.text).toBe('typed')+      expect(state.num).toBe(42)+      expect(container.querySelectorAll('input')[1].value).toBe('42')+    })++    test('textarea', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<textarea v-model="text"></textarea>`,+        { text: 'foo' },+        c => (c.querySelector('textarea')!.value = 'typed'),+      )+      expect(container.querySelector('textarea')!.value).toBe('typed')+      expect(state.text).toBe('typed')+    })++    test('dynamic type input', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input :type="type" v-model="text">`,+        { type: 'text', text: 'foo' },+        c => (c.querySelector('input')!.value = 'typed'),+      )+      expect(container.querySelector('input')!.value).toBe('typed')+      expect(state.text).toBe('typed')+    })++    test('untouched inputs with browser-sanitized values', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input type="range" v-model="range">` ++          `<input type="range" min="0" max="10" v-model="clamped">` ++          `<input type="color" v-model="color">` ++          `<input v-model="text">`,+        { range: null, clamped: 20, color: '', text: 'a\nb' },+        () => {},+      )+      expect(state).toMatchObject({+        range: null,+        clamped: 20,+        color: '',+        text: 'a\nb',+      })+      const [, clamped] = container.querySelectorAll('input')+      expect(clamped.value).toBe('10')+    })++    test('checkbox', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input type="checkbox" v-model="checked">` ++          `<input type="checkbox" value="a" v-model="list">` ++          `<input type="checkbox" value="b" v-model="list">`,+        { checked: false, list: ['a'] },+        c => {+          const [single, a, b] = c.querySelectorAll('input')+          single.checked = true+          a.checked = false+          b.checked = true+        },+      )+      const [single, a, b] = container.querySelectorAll('input')+      expect(single.checked).toBe(true)+      expect(a.checked).toBe(false)+      expect(b.checked).toBe(true)+      expect(state.checked).toBe(true)+      expect(state.list).toEqual(['b'])+    })++    test('checkbox group bound to a Set', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input type="checkbox" value="a" v-model="set">` ++          `<input type="checkbox" value="b" v-model="set">` ++          `<input type="checkbox" value="c" v-model="set">`,+        { set: new Set(['a', 'b', 'c']) },+        c => {+          const [a, , cb] = c.querySelectorAll('input')+          a.checked = false+          cb.checked = false+        },+      )+      const [a, b, c] = container.querySelectorAll('input')+      expect([a.checked, b.checked, c.checked]).toEqual([false, true, false])+      expect([...state.set]).toEqual(['b'])+    })++    test('radio', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input type="radio" value="a" v-model="picked">` ++          `<input type="radio" value="b" v-model="picked">`,+        { picked: 'a' },+        c => (c.querySelectorAll('input')[1].checked = true),+      )+      const [a, b] = container.querySelectorAll('input')+      expect(a.checked).toBe(false)+      expect(b.checked).toBe(true)+      expect(state.picked).toBe('b')+    })++    test('select', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<select v-model="selected">` ++          `<option value="a">a</option><option value="b">b</option>` ++          `</select>` ++          `<select v-model="multi" multiple>` ++          `<option value="a">a</option><option value="b">b</option>` ++          `</select>`,+        { selected: 'a', multi: ['a'] },+        c => {+          const [single, multi] = c.querySelectorAll('select')+          single.value = 'b'+          multi.options[0].selected = false+          multi.options[1].selected = true+        },+      )+      const [single, multi] = container.querySelectorAll('select')+      expect(single.value).toBe('b')+      expect(state.selected).toBe('b')+      expect(multi.options[0].selected).toBe(false)+      expect(multi.options[1].selected).toBe(true)+      expect(state.multi).toEqual(['b'])+    })++    test('untouched elements are synced to the model', async () => {+      const { container, state } = await hydrateAfterInteraction(+        `<input v-model="text">` ++          `<input type="checkbox" v-model="checked">` ++          `<input type="radio" value="a" v-model="picked">` ++          `<input type="radio" value="b" v-model="picked">` ++          `<select v-model="selected">` ++          `<option value="a">a</option><option value="b">b</option>` ++          `</select>` ++          `<select v-model="none">` ++          `<option value="a">a</option><option value="b">b</option>` ++          `</select>`,+        {+          text: 'foo',+          checked: true,+          picked: 'b',+          selected: 'b',+          none: null,+        },+        () => {},+      )+      const [text, checkbox, a, b] = container.querySelectorAll('input')+      const [select, none] = container.querySelectorAll('select')+      expect(text.value).toBe('foo')+      expect(checkbox.checked).toBe(true)+      expect(a.checked).toBe(false)+      expect(b.checked).toBe(true)+      expect(select.value).toBe('b')+      expect(none.selectedIndex).toBe(-1)+      expect(state).toMatchObject({+        text: 'foo',+        checked: true,+        picked: 'b',+        selected: 'b',+        none: null,+      })+    })+  })+    // #7203   test('force hydrate custom element with dynamic props', () => {packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..eea200173 100644@@ -38,9 +38,30 @@ function onCompositionEnd(e: Event) { }  const assignKey: unique symbol = Symbol('_assign')+// marks an element whose state was changed by the user before hydration+const dirtyKey: unique symbol = Symbol('_dirty')++// `created` hooks run either on a freshly created element (not inserted into+// the DOM until after its props are set) or on an existing SSR-rendered+// element being hydrated. Only the latter may have been interacted with by the+// user already, before the app became interactive.+function isHydratingElement(el: Element): boolean {+  return el.parentNode != null+}++// whether the value differs from the server-rendered one. The browser may+// sanitize the `value` attribute (e.g. type="range" clamps it, type="color"+// defaults to #000000, line breaks are stripped), so compare against the+// sanitized default rather than the raw attribute.+function isValueChanged(el: HTMLInputElement | HTMLTextAreaElement): boolean {+  if (el.value === el.defaultValue) return false+  const clone = el.cloneNode() as HTMLInputElement | HTMLTextAreaElement+  clone.value = el.defaultValue+  return el.value !== clone.value+}  type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<-  T & { [assignKey]: AssignerFn; _assigning?: boolean },+  T & { [assignKey]: AssignerFn; [dirtyKey]?: boolean; _assigning?: boolean },   any,   Modifiers >@@ -59,6 +80,8 @@ export const vModelText: ModelDirective< > = {   created(el, { modifiers: { lazy, trim, number } }, vnode) {     el[assignKey] = getModelAssigner(vnode)+    // detect a value entered by the user before hydration+    el[dirtyKey] = isHydratingElement(el) && isValueChanged(el)     const castToNumber =       number || (vnode.props && vnode.props.type === 'number')     addEventListener(el, lazy ? 'change' : 'input', e => {@@ -81,7 +104,19 @@ export const vModelText: ModelDirective<     }   },   // 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[dirtyKey]) {+      // preserve the value entered before hydration and sync it to the model+      el[dirtyKey] = false+      el[assignKey](+        castValue(+          el.value,+          trim,+          number || (vnode.props && vnode.props.type === 'number'),+        ),+      )+      return+    }     el.value = value == null ? '' : value   },   beforeUpdate(@@ -126,42 +161,81 @@ 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)+    // detect a checkbox toggled by the user before hydration+    el[dirtyKey] = isHydratingElement(el) && el.checked !== el.defaultChecked+    addEventListener(el, 'change', () => assignCheckboxValue(el))+  },+  // set initial checked on mount to wait for true-value/false-value+  mounted(el, binding, vnode) {+    if (el[dirtyKey]) {+      // preserve the state toggled before hydration and sync it to the model+      el[dirtyKey] = false+      const { value } = binding+      // several checkboxes bound to the same array / Set may have been+      // toggled; chain their updates since `binding.value` is stale until+      // the next render.+      const pending = isArray(value) || isSet(value)+      ;(el as any)._modelValue =+        pending && pendingCheckboxValues.has(value)+          ? pendingCheckboxValues.get(value)+          : value+      const assigned = assignCheckboxValue(el)+      if (pending) {+        if (!pendingCheckboxValues.has(value)) {+          nextTick(() => pendingCheckboxValues.delete(value))         }-        assign(cloned)-      } else {-        assign(getCheckboxValue(el, checked))+        pendingCheckboxValues.set(value, 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 model values assigned by checkboxes during hydration, keyed by+// the (stale) model value they were derived from+const pendingCheckboxValues = new WeakMap<object, any>()++// assigns the model value derived from the checkbox state and returns the new+// model value (or the current one if unchanged)+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]+  let newValue: any+  if (isArray(modelValue)) {+    const index = looseIndexOf(modelValue, elementValue)+    const found = index !== -1+    if (checked && !found) {+      assign((newValue = modelValue.concat(elementValue)))+    } else if (!checked && found) {+      newValue = [...modelValue]+      newValue.splice(index, 1)+      assign(newValue)+    } else {+      newValue = modelValue+    }+  } else if (isSet(modelValue)) {+    newValue = new Set(modelValue)+    if (checked) {+      newValue.add(elementValue)+    } else {+      newValue.delete(elementValue)+    }+    assign(newValue)+  } else {+    assign((newValue = getCheckboxValue(el, checked)))+  }+  return newValue+}+ function setChecked(   el: HTMLInputElement,   { value, oldValue }: DirectiveBinding,@@ -189,12 +263,26 @@ function setChecked(  export const vModelRadio: ModelDirective<HTMLInputElement> = {   created(el, { value }, vnode) {-    el.checked = looseEqual(value, vnode.props!.value)+    // a radio whose checked state was changed by the user before hydration+    // keeps that state; the model is synced in mounted (after :value is set)+    if (isHydratingElement(el) && el.checked !== el.defaultChecked) {+      el[dirtyKey] = true+    } else {+      el.checked = looseEqual(value, vnode.props!.value)+    }     el[assignKey] = getModelAssigner(vnode)     addEventListener(el, 'change', () => {       el[assignKey](getValue(el))     })   },+  mounted(el) {+    if (el[dirtyKey]) {+      el[dirtyKey] = false+      if (el.checked) {+        el[assignKey](getValue(el))+      }+    }+  },   beforeUpdate(el, { value, oldValue }, vnode) {     el[assignKey] = getModelAssigner(vnode)     if (value !== oldValue) {@@ -208,29 +296,20 @@ 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-      })-    })+    // detect a selection changed by the user before hydration+    el[dirtyKey] = isHydratingElement(el) && isSelectionChanged(el)+    addEventListener(el, 'change', () => assignSelectValue(el, number))     el[assignKey] = getModelAssigner(vnode)   },   // set value in mounted & updated because <select> relies on its children   // <option>s.-  mounted(el, { value }) {+  mounted(el, { value, modifiers: { number } }) {+    if (el[dirtyKey]) {+      // preserve the selection made before hydration and sync it to the model+      el[dirtyKey] = false+      assignSelectValue(el, number)+      return+    }     setSelected(el, value)   },   beforeUpdate(el, { value }, vnode) {@@ -244,6 +323,64 @@ 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 the browser derives+// from the `selected` attributes, i.e. it was changed by the user.+function isSelectionChanged(el: HTMLSelectElement): boolean {+  const options = el.options+  if (el.multiple) {+    for (let i = 0; i < options.length; i++) {+      if (options[i].selected !== options[i].defaultSelected) return true+    }+    return false+  }+  // single select: the last option with `selected` wins, otherwise the+  // browser selects the first non-disabled option (when displayed as a+  // drop-down)+  let expected = -1+  for (let i = 0; i < options.length; i++) {+    if (options[i].defaultSelected) expected = i+  }+  if (expected === -1 && el.size <= 1) {+    for (let i = 0; i < options.length; i++) {+      if (!isOptionDisabled(options[i])) {+        expected = i+        break+      }+    }+  }+  return el.selectedIndex !== expected+}++function isOptionDisabled(option: HTMLOptionElement): boolean {+  const parent = option.parentNode as HTMLOptGroupElement | null+  return (+    option.disabled ||+    (!!parent && parent.tagName === '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,