Backtestsvuerun-20261001-022054#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 approach. In `created`, they detect hydration via `el.parentNode` and compare the live `el.value` against what the server rendered. In `mounted`, if the user changed the value, they push it into the model instead of overwriting the DOM. Correctness: Patch A only records an initial value when `el.type` is 'text' or 'textarea'. That leaves out common form input types such as email, password, search, tel, url and number, where the issue's data loss would still happen. Patch B applies to all text-like types and excludes only types whose values the browser normalizes on parse (range, color, date/time), avoiding false positives there. Patch B also handles `type="number"` casting correctly via `vnode.props.type`, matching the existing `created` logic. Patch A's `castValue` call ignores that, although A never reaches number inputs anyway. Patch A's CR/LF normalization of `defaultValue` is a careful touch for a rare edge case (newlines in a value attribute). It does not outweigh A failing the issue for most non-'text' input types. Tests: Patch B adds three focused tests covering an input, a textarea, and a no-op case that asserts the model is not updated when the value is unchanged. These use explicit `withDirectives`/`vModelText` render functions that work in the runtime-core test environment. Patch A adds a single test that relies on `template` compilation and `renderToString` inside runtime-core's hydration spec, which is less clearly runnable there. It also covers only the text-input happy path. Scope and craft: both are tightly scoped to vModel.ts. Patch B's comment explains the `isConnected` versus `parentNode` choice and why some types are excluded. Overall, B fixes the issue more completely and tests it 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
5m 39s13 turns
Wall-clock time in the container
Full test suite
No new failures
3,652 passed · 6 skipped · 3,658 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
99vs 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..e9c6ab7a0 100644@@ -30,6 +30,7 @@ import { renderSlot, useCssVars, vModelCheckbox,+ vModelText, vShow, withCtx, withDirectives,@@ -1692,6 +1693,73 @@ describe('SSR hydration', () => { expect((container.firstChild as any)._trueValue).toBe(true) }) + test('preserve input value entered before hydration', async () => {+ const container = document.createElement('div')+ container.innerHTML = '<input value="foo">'+ // simulate user typing before hydration completes+ ;(container.firstChild as HTMLInputElement).value = 'bar'+ const text = ref('foo')+ const app = createSSRApp({+ render() {+ return withDirectives(+ h('input', {+ 'onUpdate:modelValue': (v: string) => (text.value = v),+ }),+ [[vModelText, text.value]],+ )+ },+ })+ app.mount(container)+ await nextTick()+ await nextTick()+ expect((container.firstChild as HTMLInputElement).value).toBe('bar')+ expect(text.value).toBe('bar')+ })++ test('preserve textarea value entered before hydration', async () => {+ const container = document.createElement('div')+ container.innerHTML = '<textarea>foo</textarea>'+ // simulate user typing before hydration completes+ ;(container.firstChild as HTMLTextAreaElement).value = 'bar'+ const text = ref('foo')+ const app = createSSRApp({+ render() {+ return withDirectives(+ h('textarea', {+ 'onUpdate:modelValue': (v: string) => (text.value = v),+ }),+ [[vModelText, text.value]],+ )+ },+ })+ app.mount(container)+ await nextTick()+ await nextTick()+ expect((container.firstChild as HTMLTextAreaElement).value).toBe('bar')+ expect(text.value).toBe('bar')+ })++ test('do not update model when input value is unchanged before hydration', async () => {+ const container = document.createElement('div')+ container.innerHTML = '<input value="foo">'+ const text = ref('foo')+ const onUpdate = vi.fn((v: string) => (text.value = v))+ const app = createSSRApp({+ render() {+ return withDirectives(+ h('input', { 'onUpdate:modelValue': onUpdate }),+ [[vModelText, text.value]],+ )+ },+ })+ app.mount(container)+ await nextTick()+ await nextTick()+ expect((container.firstChild as HTMLInputElement).value).toBe('foo')+ expect(text.value).toBe('foo')+ expect(onUpdate).not.toHaveBeenCalled()+ })+ test('force hydrate checkbox with indeterminate', () => { const { container } = mountWithHydration( '<input type="checkbox" indeterminate>',packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..6f7558020 100644@@ -40,7 +40,11 @@ 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+ _hydratedUserValue?: boolean+ }, any, Modifiers >@@ -65,6 +69,18 @@ export const vModelText: ModelDirective< if ((e.target as any).composing) return el[assignKey](castValue(el.value, trim, castToNumber)) })+ // preserve value entered before hydration (nuxt/nuxt#29206)+ // during client mount the el is not yet inserted; during hydration it is+ // already attached (possibly to a detached container, so not isConnected).+ // skip types whose values the browser normalizes on parse (e.g. clamping,+ // lowercasing), which would otherwise be mistaken for user input.+ if (+ el.parentNode &&+ el.value !== el.defaultValue &&+ !/^(?:range|color|date|datetime-local|month|week|time)$/.test(el.type)+ ) {+ el._hydratedUserValue = true+ } if (trim || castToNumber) { addEventListener(el, 'change', () => { el.value = castValue(el.value, trim, castToNumber)@@ -81,7 +97,18 @@ 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._hydratedUserValue) {+ el._hydratedUserValue = false+ el[assignKey](+ castValue(+ el.value,+ trim,+ number || (vnode.props && vnode.props.type === 'number'),+ ),+ )+ return+ } el.value = value == null ? '' : value }, beforeUpdate(
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,
What the agent reported
I fixed the bug: text you type into a server-rendered <input v-model> or <textarea v-model> before hydration finishes is now kept, and the bound model is updated to match. The new regression tests failed before the change and pass now. The full runtime-core, runtime-dom, server-renderer and vue suites pass (1756 passed, 1 skipped), and tsc --noEmit is clean.
What was wrong: During hydration, the mounted hook of vModelText (packages/runtime-dom/src/directives/vModel.ts) always ran el.value = value. That replaced whatever the user had typed into the server-rendered element with the model's starting value.
What I changed (only in vModel.ts):
- Spotting hydration (
created): in a normal client-side mount the element isn't attached yet whencreatedruns, but during hydration it is already in the page (I checkedel.parentNode, notisConnected, so it also works when the container isn't attached to the document). - Spotting typed text: if the element is already attached and
el.value !== el.defaultValue(the live value differs from the server-renderedvalue), I mark the element. - Using the typed text (
mounted): for a marked element, I sendel.valueto the model (applying thetrim/numbermodifiers the same way the input listener does) instead of overwriting it. - Excluded input types: range, color, date, datetime-local, month, week and time are left out. The final review pointed out that browsers already adjust these values while loading the page (clamping range, lowercasing colours, clearing invalid dates). Without the exclusion, hydration would have changed the model even though nobody typed anything.
Tests: three new tests in packages/runtime-core/__tests__/hydration.spec.ts. Each puts server-rendered HTML in a container, changes the value to mimic a user typing, then hydrates:
- A text input typed from
footobarkeepsbar, and the model becomesbar. This failed before the fix with "expected 'foo' to be 'bar'". - The same check for a
<textarea>, which also failed before the fix. - An input nobody touched keeps
fooand the model update handler is never called. This passes both before and after; it guards against updating the model without user input.
Requirements:
- Typed value preserved after hydration: done; tests 1 and 2.
- Model reflects the typed value: done; the
text.value === 'bar'assertions in tests 1 and 2. - No change when nothing was typed: done; test 3, and all existing client-side mount and v-model tests pass.
Remaining gaps:
- Checkboxes, radios and selects are not covered. A box ticked or option picked before hydration finishes can still be reset. The report only described text entry.
- Some types still lose typed text: for the excluded date/time, range and colour inputs, anything entered before hydration is still reset, as before.
- Rare unprompted model changes: in a few unusual cases the browser still adjusts the value while loading the page, and the model would then be updated without any typing. Examples are leading or trailing spaces in an email or URL field, a line break in a single-line field, or an invalid string in a number field.
- Untested paths: the
trim/number/lazymodifiers and dynamic:typeinputs follow the same code but have no dedicated tests. I also didn't add a test for the excluded types, because jsdom may not adjust values the way real browsers do.
Changes are uncommitted in the working tree.