Backtestsvuerun-20261009-161443#14403
Preserve input values entered during hydration
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 approach: during hydration the element is already attached in `created`, so each compares the live DOM value against the server-rendered default and, if they differ, writes the DOM value into the model instead of overwriting it in `mounted`. They differ in coverage. Patch B only handles `type === 'text'` inputs and textareas. Password, email, search, tel, url and number inputs still get reset, as do checkboxes, radios and selects. The issue is about forms in general, so many common fields stay broken. Patch A handles text-like inputs of every type, including a sanitization-aware comparison for range and color inputs and support for the .trim and .number modifiers. It also handles textarea, checkbox (including true-value/false-value and array/Set models, with a pending-model map so several boxes sharing a collection combine correctly), radio, and select (single and multiple, including correct default-index logic for selects with no `selected` attribute). It deliberately skips custom elements. Patch A's tests are thorough: each element type, the modifiers, the unchanged-by-user case, and false-positive guards for browser-sanitized values and selects with no matching option. Patch B adds a single text-input test. Patch A is more complex, notably the `pendingCheckboxModels` mechanism, but the complexity is targeted and tested, and the refactors (`assignChecked`, `assignSelected`) keep existing behavior. On correctness breadth and tests, Patch A is clearly better.
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 12s
Wall-clock time in the container
Full test suite
No new failures
1,772 passed · 1 skipped · 1,773 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
485vs 50 merged
Changed lines, ours vs merged
The issue
View on GitHubVue 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
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..3142fdadf 100644@@ -1692,6 +1692,240 @@ describe('SSR hydration', () => { expect((container.firstChild as any)._trueValue).toBe(true) }) + describe('preserve form values changed before hydration', () => {+ async function hydrateAfterUserInput(+ component: any,+ interact: (container: HTMLElement) => void,+ ) {+ const container = document.createElement('div')+ container.innerHTML = await renderToString(createSSRApp(component))+ // simulate user interaction before the app is hydrated+ interact(container)+ createSSRApp(component).mount(container)+ await nextTick()+ return container+ }++ test('input text', async () => {+ const text = ref('foo')+ const container = await hydrateAfterUserInput(+ { setup: () => ({ text }), template: `<input v-model="text">` },+ c => ((c.querySelector('input') as HTMLInputElement).value = 'bar'),+ )+ expect(container.querySelector('input')!.value).toBe('bar')+ expect(text.value).toBe('bar')+ expect(`Hydration`).not.toHaveBeenWarned()+ })++ test('input text unchanged by user is set from the model', async () => {+ const text = ref('foo')+ const container = await hydrateAfterUserInput(+ { setup: () => ({ text }), template: `<input v-model="text">` },+ () => {},+ )+ expect(container.querySelector('input')!.value).toBe('foo')+ expect(text.value).toBe('foo')+ })++ test('input sanitized by the browser is not treated as changed', async () => {+ const vol = ref(150)+ const color = ref('red')+ await hydrateAfterUserInput(+ {+ setup: () => ({ vol, color }),+ template: `<div><input type="range" max="100" v-model="vol"><input type="color" v-model="color"></div>`,+ },+ () => {},+ )+ expect(vol.value).toBe(150)+ expect(color.value).toBe('red')+ })++ test('input with .number and .trim modifiers', async () => {+ const num = ref(1)+ const str = ref('a')+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ num, str }),+ template: `<div><input v-model.number="num"><input v-model.trim="str"></div>`,+ },+ c => {+ const [numInput, strInput] = c.querySelectorAll('input')+ numInput.value = '42'+ strInput.value = ' hello '+ },+ )+ expect(num.value).toBe(42)+ expect(str.value).toBe('hello')+ expect(container.querySelectorAll('input')[0].value).toBe('42')+ })++ test('textarea', async () => {+ const text = ref('foo')+ const container = await hydrateAfterUserInput(+ { setup: () => ({ text }), template: `<textarea v-model="text"/>` },+ c =>+ ((c.querySelector('textarea') as HTMLTextAreaElement).value = 'bar'),+ )+ expect(container.querySelector('textarea')!.value).toBe('bar')+ expect(text.value).toBe('bar')+ })++ test('dynamic type input', async () => {+ const text = ref('foo')+ const type = ref('text')+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ text, type }),+ template: `<input :type="type" v-model="text">`,+ },+ c => ((c.querySelector('input') as HTMLInputElement).value = 'bar'),+ )+ expect(container.querySelector('input')!.value).toBe('bar')+ expect(text.value).toBe('bar')+ })++ test('checkbox', async () => {+ const checked = ref(false)+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ checked }),+ template: `<input type="checkbox" v-model="checked">`,+ },+ c => ((c.querySelector('input') as HTMLInputElement).checked = true),+ )+ expect(container.querySelector('input')!.checked).toBe(true)+ expect(checked.value).toBe(true)+ })++ test('checkbox with true-value / false-value', async () => {+ const value = ref('yes')+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ value }),+ template: `<input type="checkbox" v-model="value" true-value="yes" false-value="no">`,+ },+ c => ((c.querySelector('input') as HTMLInputElement).checked = false),+ )+ expect(container.querySelector('input')!.checked).toBe(false)+ expect(value.value).toBe('no')+ })++ test('multiple checkboxes bound to an array', async () => {+ const list = ref(['a'])+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ list }),+ template: `<div>+ <input type="checkbox" value="a" v-model="list">+ <input type="checkbox" value="b" v-model="list">+ <input type="checkbox" value="c" v-model="list">+ </div>`,+ },+ c => {+ const [a, b, c2] = c.querySelectorAll('input')+ a.checked = false+ b.checked = true+ c2.checked = true+ },+ )+ expect(list.value).toEqual(['b', 'c'])+ const inputs = container.querySelectorAll('input')+ expect([...inputs].map(i => i.checked)).toEqual([false, true, true])+ })++ test('multiple checkboxes bound to a Set', async () => {+ const set = ref(new Set(['a', 'b']))+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ set }),+ template: `<div>+ <input type="checkbox" value="a" v-model="set">+ <input type="checkbox" value="b" v-model="set">+ </div>`,+ },+ c => {+ c.querySelectorAll('input').forEach(i => (i.checked = false))+ },+ )+ expect([...set.value]).toEqual([])+ const inputs = container.querySelectorAll('input')+ expect([...inputs].map(i => i.checked)).toEqual([false, false])+ })++ test('radio', async () => {+ const picked = ref('a')+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ picked }),+ template: `<div>+ <input type="radio" name="r" value="a" v-model="picked">+ <input type="radio" name="r" value="b" v-model="picked">+ </div>`,+ },+ c => {+ c.querySelectorAll('input')[1].checked = true+ },+ )+ expect(picked.value).toBe('b')+ const inputs = container.querySelectorAll('input')+ expect([...inputs].map(i => i.checked)).toEqual([false, true])+ })++ test('select', async () => {+ const selected = ref('a')+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ selected }),+ template: `<select v-model="selected">+ <option value="a">a</option>+ <option value="b">b</option>+ </select>`,+ },+ c => {+ ;(c.querySelector('select') as HTMLSelectElement).selectedIndex = 1+ },+ )+ expect(selected.value).toBe('b')+ expect(container.querySelector('select')!.value).toBe('b')+ })++ test('select without a matching option is not treated as changed', async () => {+ const selected = ref('x')+ await hydrateAfterUserInput(+ {+ setup: () => ({ selected }),+ template: `<select v-model="selected">+ <option value="a">a</option>+ <option value="b">b</option>+ </select>`,+ },+ () => {},+ )+ expect(selected.value).toBe('x')+ })++ test('select multiple with .number', async () => {+ const selected = ref([1])+ const container = await hydrateAfterUserInput(+ {+ setup: () => ({ selected }),+ template: `<select multiple v-model.number="selected">+ <option value="1">1</option>+ <option value="2">2</option>+ </select>`,+ },+ c => {+ c.querySelectorAll('option')[1].selected = true+ },+ )+ expect(selected.value).toEqual([1, 2])+ expect(+ [...container.querySelectorAll('option')].map(o => o.selected),+ ).toEqual([true, true])+ })+ })+ test('force hydrate checkbox with indeterminate', () => { const { container } = mountWithHydration( '<input type="checkbox" indeterminate>',packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..3f88f9f7d 100644@@ -40,11 +40,90 @@ 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 the element already lives in the DOM when the `created`+// hook is called, while freshly created elements are only inserted after+// `beforeMount`.+function isHydrating(el: Element): boolean {+ return el.parentNode != null+}++// Whether the user has changed the value of a server-rendered form element+// before it got hydrated (e.g. typed into an input while the app was loading).+// Must be called in `created`, before any props are patched onto the element.+function isModifiedBeforeHydration(+ el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,+): boolean {+ if (!isHydrating(el)) return false+ if (el.tagName === 'SELECT') {+ return isSelectModified(el as HTMLSelectElement)+ }+ if (el.tagName === 'TEXTAREA') {+ return el.value !== (el as HTMLTextAreaElement).defaultValue+ }+ // v-model on custom elements also uses vModelText, but they don't expose a+ // server-rendered default to compare against+ if (el.tagName !== 'INPUT') return false+ const input = el as HTMLInputElement+ const type = input.type+ if (type === 'checkbox' || type === 'radio') {+ return input.checked !== input.defaultChecked+ }+ if (input.value === input.defaultValue) return false+ // the browser sanitizes the value attribute (e.g. clamps a range input to+ // min/max), so compare against the sanitized default of an untouched copy+ const pristine = input.ownerDocument.createElement('input')+ const attrs = input.attributes+ for (let i = 0; i < attrs.length; i++) {+ pristine.setAttribute(attrs[i].name, attrs[i].value)+ }+ return input.value !== pristine.value+}++function isSelectModified(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+ }+ // the last option with the `selected` attribute wins+ let defaultIndex = -1+ for (let i = 0; i < options.length; i++) {+ if (options[i].defaultSelected) defaultIndex = i+ }+ // without any `selected` attribute, a drop-down select displays its first+ // non-disabled option+ if (defaultIndex === -1 && el.size <= 1) {+ for (let i = 0; i < options.length; i++) {+ if (!isOptionDisabled(options[i])) {+ defaultIndex = i+ break+ }+ }+ }+ return el.selectedIndex !== defaultIndex+}++function isOptionDisabled(option: HTMLOptionElement): boolean {+ const parent = option.parentNode as HTMLElement | null+ return (+ option.disabled ||+ (!!parent &&+ parent.tagName === 'OPTGROUP' &&+ (parent as HTMLOptGroupElement).disabled)+ )+}+ function castValue(value: string, trim?: boolean, number?: boolean | null) { if (trim) value = value.trim() if (number) value = looseToNumber(value)@@ -59,6 +138,7 @@ export const vModelText: ModelDirective< > = { created(el, { modifiers: { lazy, trim, number } }, vnode) { el[assignKey] = getModelAssigner(vnode)+ el._userModified = isModifiedBeforeHydration(el) const castToNumber = number || (vnode.props && vnode.props.type === 'number') addEventListener(el, lazy ? 'change' : 'input', e => {@@ -81,7 +161,15 @@ 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._userModified) {+ // preserve the value entered before hydration and sync it to the model+ 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 +214,78 @@ 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)- }- assign(cloned)- } else {- assign(getCheckboxValue(el, checked))- }- })+ el._userModified = isModifiedBeforeHydration(el)+ addEventListener(el, 'change', () => assignChecked(el)) }, // set initial checked on mount to wait for true-value/false-value- mounted: setChecked,+ mounted(el, binding, vnode) {+ if (el._userModified) {+ // preserve the checked state changed before hydration and sync it to+ // the model+ el._userModified = false+ const { value } = binding+ const isCollection = isArray(value) || isSet(value)+ // multiple checkboxes sharing an array / Set model sync in the same+ // flush, before the model is re-rendered, so build on top of the value+ // assigned by the previous ones+ ;(el as any)._modelValue =+ isCollection && pendingCheckboxModels.has(value)+ ? pendingCheckboxModels.get(value)+ : value+ const assigned = assignChecked(el)+ if (isCollection && assigned !== undefined) {+ pendingCheckboxModels.set(value, assigned)+ nextTick(() => pendingCheckboxModels.delete(value))+ }+ return+ }+ setChecked(el, binding, vnode)+ }, beforeUpdate(el, binding, vnode) { el[assignKey] = getModelAssigner(vnode) setChecked(el, binding, vnode) }, } +const pendingCheckboxModels = new WeakMap<object, any>()++// assigns the model value derived from the checkbox state and returns it, or+// returns undefined if the model does not need to change+function assignChecked(+ el: HTMLInputElement & { [assignKey]: AssignerFn },+): unknown {+ const modelValue = (el as any)._modelValue+ const elementValue = getValue(el)+ const checked = el.checked+ const assign = el[assignKey]+ let newValue: unknown+ if (isArray(modelValue)) {+ const index = looseIndexOf(modelValue, elementValue)+ const found = index !== -1+ if (checked && !found) {+ newValue = modelValue.concat(elementValue)+ } else if (!checked && found) {+ const filtered = [...modelValue]+ filtered.splice(index, 1)+ newValue = filtered+ } else {+ return+ }+ } else if (isSet(modelValue)) {+ const cloned = new Set(modelValue)+ if (checked) {+ cloned.add(elementValue)+ } else {+ cloned.delete(elementValue)+ }+ newValue = cloned+ } else {+ newValue = getCheckboxValue(el, checked)+ }+ assign(newValue)+ return newValue+}+ function setChecked( el: HTMLInputElement, { value, oldValue }: DirectiveBinding,@@ -189,12 +313,26 @@ function setChecked( export const vModelRadio: ModelDirective<HTMLInputElement> = { created(el, { value }, vnode) {- el.checked = looseEqual(value, vnode.props!.value)+ el._userModified = isModifiedBeforeHydration(el)+ // keep the checked state changed by the user before hydration+ if (!el._userModified) {+ el.checked = looseEqual(value, vnode.props!.value)+ } el[assignKey] = getModelAssigner(vnode) addEventListener(el, 'change', () => { el[assignKey](getValue(el)) }) },+ // sync the radio checked by the user before hydration to the model. done on+ // mount so that the raw `:value` binding is available.+ mounted(el) {+ if (el._userModified) {+ el._userModified = false+ if (el.checked) {+ el[assignKey](getValue(el))+ }+ }+ }, beforeUpdate(el, { value, oldValue }, vnode) { el[assignKey] = getModelAssigner(vnode) if (value !== oldValue) {@@ -208,29 +346,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- })- })+ el._userModified = isModifiedBeforeHydration(el)+ addEventListener(el, 'change', () => assignSelected(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._userModified) {+ // preserve the selection changed before hydration and sync it to the+ // model. done on mount so that the options' raw values are available.+ el._userModified = false+ assignSelected(el, number)+ return+ } setSelected(el, value) }, beforeUpdate(el, { value }, vnode) {@@ -244,6 +373,28 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = { }, } +function assignSelected(+ 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+ })+}+ function setSelected(el: HTMLSelectElement, value: any) { const isMultiple = el.multiple const isArrayValue = isArray(value)
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,