Backtestsvuerun-20261002-115633#14403
Preserve input values entered during hydration
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 idea. During hydration, `created` runs on an element that is already attached to the DOM. Each patch detects there whether the user edited the server-rendered value, then in `mounted` writes the DOM value back to the model instead of overwriting the DOM. Patch A only treats the element as dirty when `el.type === 'text'` or `'textarea'`. Inputs typed `email`, `password`, `search`, `tel`, `url` or `number` still get reset to the server value. Those are exactly the kinds of form fields the issue is about. Patch A also does not apply the `type=number` cast in its `mounted` sync, though that path is unreachable given the type gate. Its comparison of `defaultValue` with CR/LF normalization is reasonable but hand-rolled. It ships one test, which covers only the plain text case. Patch B detects edits for any text-like input by cloning the element and setting `defaultValue` on the clone, which yields the browser-sanitized default. This correctly handles types that sanitize their value, such as `range` and `number`. It applies the `.trim`/`.number` modifiers and `type=number` casting when syncing. Patch B also extends preservation to checkboxes, including shared array and Set models across multiple boxes, radios, and single and multiple selects. These are all v-model form controls whose user changes would be lost in the same way. The checkbox `pendingModelValues` logic adds some complexity. However, it addresses a real ordering problem: several checkboxes share one model in the same flush before re-render. The added tests cover that case. Patch B's radio handling avoids clobbering the user's choice in the group. It syncs in `mounted` so that a non-string `:value` is resolved first. Its test suite is extensive and includes a regression guard that untouched elements still reflect the client model, including `range` and `select` with no match. Overall, Patch B is more correct for the realistic scenarios in the issue (arbitrary forms) and is much better tested. Its extra scope is coherent and covered by tests rather than risky churn.
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 2s
Wall-clock time in the container
Full test suite
No new failures
3,661 passed · 6 skipped · 3,667 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
430vs 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..9de82ce25 100644@@ -1692,6 +1692,212 @@ describe('SSR hydration', () => { expect((container.firstChild as any)._trueValue).toBe(true) }) + describe('preserve v-model values entered before hydration', () => {+ async function ssrMount(+ template: string,+ data: Record<string, any>,+ edit: (container: HTMLElement) => void,+ ) {+ const state = reactive({ ...data })+ const App = {+ setup: () => state,+ template,+ }+ const container = document.createElement('div')+ container.innerHTML = await renderToString(+ createSSRApp({ setup: () => reactive({ ...data }), template }),+ )+ // simulate user interaction before the app is hydrated+ edit(container)+ createSSRApp(App).mount(container)+ await nextTick()+ return { container, state }+ }++ test('text input', async () => {+ const { container, state } = await ssrMount(+ `<input v-model="text">`,+ { text: 'foo' },+ c => {+ c.querySelector('input')!.value = 'typed'+ },+ )+ expect(container.querySelector('input')!.value).toBe('typed')+ expect(state.text).toBe('typed')+ })++ test('text input with .number and .trim modifiers', async () => {+ const { container, state } = await ssrMount(+ `<input class="n" v-model.number="num"><input class="t" v-model.trim="str">`,+ { num: 1, str: 'a' },+ c => {+ c.querySelector<HTMLInputElement>('.n')!.value = '42'+ c.querySelector<HTMLInputElement>('.t')!.value = ' hi '+ },+ )+ expect(state.num).toBe(42)+ expect(state.str).toBe('hi')+ expect(container.querySelector<HTMLInputElement>('.n')!.value).toBe('42')+ })++ test('textarea', async () => {+ const { container, state } = await ssrMount(+ `<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 ssrMount(+ `<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('checkbox', async () => {+ const { container, state } = await ssrMount(+ `<input type="checkbox" v-model="checked">`,+ { checked: false },+ c => {+ c.querySelector('input')!.checked = true+ },+ )+ expect(container.querySelector('input')!.checked).toBe(true)+ expect(state.checked).toBe(true)+ })++ test('checkbox array', async () => {+ const { container, state } = await ssrMount(+ `<input class="a" type="checkbox" value="a" v-model="list">` ++ `<input class="b" type="checkbox" value="b" v-model="list">`,+ { list: ['a'] },+ c => {+ c.querySelector<HTMLInputElement>('.a')!.checked = false+ c.querySelector<HTMLInputElement>('.b')!.checked = true+ },+ )+ expect(container.querySelector<HTMLInputElement>('.a')!.checked).toBe(+ false,+ )+ expect(container.querySelector<HTMLInputElement>('.b')!.checked).toBe(+ true,+ )+ expect(state.list).toEqual(['b'])+ })++ test('checkbox Set', async () => {+ const { state } = await ssrMount(+ `<input class="a" type="checkbox" value="a" v-model="set">` ++ `<input class="b" type="checkbox" value="b" v-model="set">` ++ `<input class="c" type="checkbox" value="c" v-model="set">`,+ { set: new Set(['a', 'b', 'c']) },+ c => {+ c.querySelector<HTMLInputElement>('.b')!.checked = false+ c.querySelector<HTMLInputElement>('.c')!.checked = false+ },+ )+ expect([...state.set]).toEqual(['a'])+ })++ test('radio', async () => {+ const { container, state } = await ssrMount(+ `<input class="a" type="radio" value="a" v-model="picked">` ++ `<input class="b" type="radio" value="b" v-model="picked">`,+ { picked: 'a' },+ c => {+ c.querySelector<HTMLInputElement>('.b')!.checked = true+ },+ )+ expect(container.querySelector<HTMLInputElement>('.a')!.checked).toBe(+ false,+ )+ expect(container.querySelector<HTMLInputElement>('.b')!.checked).toBe(+ true,+ )+ expect(state.picked).toBe('b')+ })++ test('select', async () => {+ const { container, state } = await ssrMount(+ `<select v-model="selected">` ++ `<option value="a">a</option><option value="b">b</option>` ++ `</select>`,+ { selected: 'a' },+ c => {+ c.querySelector('select')!.selectedIndex = 1+ },+ )+ expect(container.querySelector('select')!.value).toBe('b')+ expect(state.selected).toBe('b')+ })++ test('select without initial match', async () => {+ const { container, state } = await ssrMount(+ `<select v-model="selected">` ++ `<option value="a">a</option><option value="b">b</option>` ++ `</select>`,+ { selected: null },+ c => {+ c.querySelector('select')!.selectedIndex = 1+ },+ )+ expect(container.querySelector('select')!.value).toBe('b')+ expect(state.selected).toBe('b')+ })++ test('select multiple', async () => {+ const { container, state } = await ssrMount(+ `<select multiple v-model="selected">` ++ `<option value="a">a</option><option value="b">b</option>` ++ `</select>`,+ { selected: ['a'] },+ c => {+ const options = c.querySelector('select')!.options+ options[0].selected = false+ options[1].selected = true+ },+ )+ const options = container.querySelector('select')!.options+ expect(options[0].selected).toBe(false)+ expect(options[1].selected).toBe(true)+ expect(state.selected).toEqual(['b'])+ })++ test('untouched elements still reflect client model value', async () => {+ const { container, state } = await ssrMount(+ `<input v-model="text">` ++ `<input type="checkbox" v-model="checked">` ++ `<input type="range" min="0" max="10" v-model="range">` ++ `<select v-model="selected">` ++ `<option value="a">a</option><option value="b">b</option>` ++ `</select>`,+ { text: 'foo', checked: true, range: 50, selected: null },+ () => {},+ )+ expect(container.querySelector('input')!.value).toBe('foo')+ expect(+ container.querySelector<HTMLInputElement>('[type=checkbox]')!.checked,+ ).toBe(true)+ expect(container.querySelector('select')!.selectedIndex).toBe(-1)+ expect(state).toEqual({+ text: 'foo',+ checked: true,+ range: 50,+ selected: null,+ })+ })+ })+ test('force hydrate checkbox with indeterminate', () => { const { container } = mountWithHydration( '<input type="checkbox" indeterminate>',packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..720f7362b 100644@@ -38,13 +38,64 @@ function onCompositionEnd(e: Event) { } const assignKey: unique symbol = Symbol('_assign')+const dirtyKey: unique symbol = Symbol('_dirty') type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<- T & { [assignKey]: AssignerFn; _assigning?: boolean },+ T & { [assignKey]: AssignerFn; [dirtyKey]?: boolean; _assigning?: boolean }, any, Modifiers > +// During hydration, the `created` hook runs on the server-rendered element,+// which is already in the DOM and may have been edited by the user before the+// app hydrated. On client-side mount, `created` runs before the element is+// inserted, so a detached element is never considered dirty.+function isHydrating(el: Element): boolean {+ return el.parentNode != null+}++function hasDirtyValue(el: HTMLInputElement | HTMLTextAreaElement): boolean {+ // compare against the sanitized default value (e.g. type="range" clamps its+ // value attribute) so that only actual user edits are considered dirty+ const probe = el.cloneNode() as HTMLInputElement | HTMLTextAreaElement+ probe.value = el.defaultValue+ return el.value !== probe.value+}++function hasDirtyChecked(el: HTMLInputElement): boolean {+ return el.checked !== el.defaultChecked+}++function hasDirtySelection(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 browser selects the last option with the `selected`+ // attribute, or falls back to the first enabled option for drop-downs+ let defaultIndex = -1+ for (let i = 0; i < options.length; i++) {+ if (options[i].defaultSelected) defaultIndex = i+ }+ if (defaultIndex === -1 && el.size <= 1) {+ for (let i = 0; i < options.length; i++) {+ const option = options[i]+ const parent = option.parentNode as HTMLOptGroupElement | null+ if (+ !option.disabled &&+ !(parent && parent.tagName === 'OPTGROUP' && parent.disabled)+ ) {+ defaultIndex = i+ break+ }+ }+ }+ return el.selectedIndex !== defaultIndex+}+ function castValue(value: string, trim?: boolean, number?: boolean | null) { if (trim) value = value.trim() if (number) value = looseToNumber(value)@@ -59,6 +110,8 @@ export const vModelText: ModelDirective< > = { created(el, { modifiers: { lazy, trim, number } }, vnode) { el[assignKey] = getModelAssigner(vnode)+ // preserve values entered by the user before hydration+ el[dirtyKey] = isHydrating(el) && hasDirtyValue(el) const castToNumber = number || (vnode.props && vnode.props.type === 'number') addEventListener(el, lazy ? 'change' : 'input', e => {@@ -81,7 +134,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[dirtyKey]) {+ el[dirtyKey] = false+ // sync the value entered before hydration back to the model+ 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 +187,77 @@ 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))- }- })+ // preserve checked state changed by the user before hydration+ el[dirtyKey] = isHydrating(el) && hasDirtyChecked(el)+ addEventListener(el, 'change', () => syncCheckboxModel(el)) }, // set initial checked on mount to wait for true-value/false-value- mounted: setChecked,+ mounted(el, binding, vnode) {+ if (el[dirtyKey]) {+ el[dirtyKey] = false+ // multiple checkboxes may share the same array / Set model and sync in+ // the same flush before re-rendering, so build on any pending update+ let modelValue = binding.value+ while (pendingModelValues.has(modelValue)) {+ modelValue = pendingModelValues.get(modelValue)+ }+ ;(el as any)._modelValue = modelValue+ // sync the checked state changed before hydration back to the model+ const newValue = syncCheckboxModel(el)+ if (isArray(newValue) || isSet(newValue)) {+ pendingModelValues.set(modelValue, newValue)+ nextTick(() => pendingModelValues.delete(modelValue))+ }+ return+ }+ setChecked(el, binding, vnode)+ }, beforeUpdate(el, binding, vnode) { el[assignKey] = getModelAssigner(vnode) setChecked(el, binding, vnode) }, } +// array / Set checkbox models assigned during hydration but not yet re-rendered+const pendingModelValues = new WeakMap<object, any>()++// returns the value assigned to the model, if any+function syncCheckboxModel(+ 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 newValue = modelValue.concat(elementValue)+ assign(newValue)+ return newValue+ } else if (!checked && found) {+ const filtered = [...modelValue]+ filtered.splice(index, 1)+ assign(filtered)+ return filtered+ }+ } else if (isSet(modelValue)) {+ const cloned = new Set(modelValue)+ if (checked) {+ cloned.add(elementValue)+ } else {+ cloned.delete(elementValue)+ }+ assign(cloned)+ return cloned+ } else {+ const newValue = getCheckboxValue(el, checked)+ assign(newValue)+ return newValue+ }+}+ function setChecked( el: HTMLInputElement, { value, oldValue }: DirectiveBinding,@@ -189,12 +285,27 @@ function setChecked( export const vModelRadio: ModelDirective<HTMLInputElement> = { created(el, { value }, vnode) {- el.checked = looseEqual(value, vnode.props!.value)+ // preserve checked state changed by the user before hydration. Leave the+ // DOM untouched in that case, as checking this radio would uncheck the+ // one the user selected in the same group.+ el[dirtyKey] = isHydrating(el) && hasDirtyChecked(el)+ if (!el[dirtyKey]) {+ el.checked = looseEqual(value, vnode.props!.value)+ } el[assignKey] = getModelAssigner(vnode) addEventListener(el, 'change', () => { el[assignKey](getValue(el)) }) },+ // sync after props are set so that getValue() sees non-string :value+ 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 +319,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- })- })+ // preserve selection changed by the user before hydration+ el[dirtyKey] = isHydrating(el) && hasDirtySelection(el)+ addEventListener(el, 'change', () => syncSelectModel(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]) {+ el[dirtyKey] = false+ // sync the selection changed before hydration back to the model+ syncSelectModel(el, number)+ return+ } setSelected(el, value) }, beforeUpdate(el, { value }, vnode) {@@ -244,6 +346,28 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = { }, } +function syncSelectModel(+ 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,