Skip to content

Admin form: a rejected save shows no toast and no field errors when a field's value changes while the save's request is in flight #19887

In progress

Description

@sam9191

Describe the Bug

On main after #17455, an explicit save that the server rejects shows nothing when a field's value changes while the save's request is in flight: no error toast and no field errors. The form is enabled again, Save stays enabled, and the document is not saved.

Fields are disabled during a save, so the change comes from something other than typing. Three ways, all reproduced with the steps below at b0d2f50 (form code as merged in 7c766ec):

What changes the field while the save is out Rejected saves that showed nothing Control: the change lands before the save
The built-in slug field: click Generate, then Save before the slug comes back 3/3 Toast and field error, 3/3
A rich text field: type, then press the save hotkey at once 8/10 Toast and field error, 3/3
A component that sets another field's value, as useField().setValue does 3/3

Cause (packages/ui/src, at 7c766ec):

Possible fix: when an explicit save fails, report it even if the form has changed since it was sent: show the toast, set submitted, and apply the field errors to the fields whose value is still the one that was sent, the comparison the rejectedFields branch already makes.

The review of #17455 raised the successful-save side of this (item 4: a successful save that is no longer current loses its feedback). Found while re-running the probes from #18425 against main.

Link to the code that reproduces this issue

if (res.status >= 400 && !requestContext.isCurrent()) {
return
}

(A test/silent-save suite for the monorepo and a Playwright script are below.)

Reproduction Steps

  1. In the monorepo at main, add the three files below as test/silent-save/config.ts, test/silent-save/SetNote.tsx and test/silent-save/silent.mjs.
  2. PAYLOAD_DATABASE=sqlite PORT=3100 pnpm dev silent-save
  3. BASE=http://localhost:3100 RUNS=3 node test/silent-save/silent.mjs. Every save is rejected, because Title must start with "ok". The script hands each save's answer to the page 1 s after the server gave it, so there is time for a field to change while it is out; in slug it also holds the slug field's answer until 300 ms after the click on Save.
test/silent-save/config.ts
import type { CollectionConfig, Field } from 'payload'

import { fileURLToPath } from 'node:url'
import path from 'path'

import { buildConfigWithDefaults } from '../buildConfigWithDefaults.js'
import { devUser } from '../credentials.js'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

// Only checked on the server, so a save with any other title is rejected with a field error.
const title: Field = {
  name: 'title',
  type: 'text',
  validate: (value: null | string | undefined) =>
    value?.startsWith('ok') ? true : 'Must start with "ok".',
}

// Built-in slug field: its Generate button asks the server for the slug, and the answer
// sets the field's value.
const SlugProbes: CollectionConfig = {
  slug: 'slug-probes',
  fields: [title, { name: 'slug', type: 'slug', required: false, useAsSlug: 'title' }],
}

// Rich text field: the editor hands its value to the form in an idle callback, up to
// 500 ms after the last keystroke.
const RichProbes: CollectionConfig = {
  slug: 'rich-probes',
  fields: [title, { name: 'body', type: 'richText' }],
}

// A button that sets `note` from a component.
const ComponentProbes: CollectionConfig = {
  slug: 'component-probes',
  fields: [
    title,
    { name: 'note', type: 'text' },
    {
      name: 'setNote',
      type: 'ui',
      admin: {
        components: {
          Field: './SetNote.js#SetNote',
        },
      },
    },
  ],
}

export default buildConfigWithDefaults({
  suite: 'silent-save',
  config: {
    admin: {
      importMap: {
        baseDir: path.resolve(dirname),
      },
    },
    collections: [SlugProbes, RichProbes, ComponentProbes],
    typescript: {
      outputFile: path.resolve(dirname, 'payload-types.ts'),
    },
  },
  seed: async (payload) => {
    await payload.create({
      collection: 'users',
      data: {
        email: devUser.email,
        password: devUser.password,
      },
      overrideAccess: true,
    })
  },
})
test/silent-save/SetNote.tsx
'use client'

import { useForm } from '@payloadcms/ui'
import React from 'react'

// Sets `note` the way useField().setValue does: an UPDATE dispatch plus setModified(true).
// A plain button stays clickable while a save has the form disabled.
export const SetNote: React.FC = () => {
  const { dispatchFields, setModified } = useForm()

  return (
    <button
      id="set-note"
      onClick={() => {
        dispatchFields({ type: 'UPDATE', path: 'note', value: 'set by a component' })
        setModified(true)
      }}
      type="button"
    >
      Set note
    </button>
  )
}
test/silent-save/silent.mjs
// A rejected save shows nothing when a field's value changes while the save's request is
// in flight. Put this file, config.ts and SetNote.tsx in test/silent-save, run
// `PAYLOAD_DATABASE=sqlite PORT=3100 pnpm dev silent-save`, then
// BASE=http://localhost:3100 RUNS=3 node test/silent-save/silent.mjs [scenario ...]
// Optional: CHROMIUM_PATH=/path/to/chromium for a different browser build.
//
// Every save is rejected (Title must start with "ok") and is answered after 1 s, so there
// is time for a field to change while it is out.
//
// slug-control      click Generate on the slug field, let its answer land, then save
// slug              click Generate, save while the slugify answer is out; it lands 300 ms later
// richtext-control  type in the rich text field, wait 1.5 s, press the save hotkey
// richtext          type in the rich text field and press the save hotkey at once
// component         save, and 300 ms later a component sets another field's value
//
// Every line of output is a timeline in ms since the create view was ready: requests from
// the network, and the Title field's error state and toasts from a MutationObserver.
import { chromium } from '@playwright/test'

const BASE = process.env.BASE ?? 'http://localhost:3100'
const user = { email: '[email protected]', password: 'test' }
const RUNS = Number(process.env.RUNS ?? 1)

const collections = {
  'slug-control': 'slug-probes',
  slug: 'slug-probes',
  'richtext-control': 'rich-probes',
  richtext: 'rich-probes',
  component: 'component-probes',
}

const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH })
const context = await browser.newContext({ baseURL: BASE })
const login = await context.request.post('/api/users/login', { data: user })
if (!login.ok()) throw new Error(`login failed: ${login.status()}`)

// Records, with Date.now(), each time the Title field gains or loses its error state, and
// each toast the first time it shows a given text.
await context.addInitScript(() => {
  let error = false
  const toasts = new Set()
  window.__events = []
  const check = () => {
    // The field wrapper gets `error` exactly when FieldError shows its message.
    const hasError = Boolean(document.querySelector('.field-type.error:has(input[name="title"])'))
    if (hasError !== error) {
      error = hasError
      window.__events.push([Date.now(), `title error ${hasError ? 'SHOWN' : 'hidden'}`])
    }
    for (const toast of document.querySelectorAll('[data-sonner-toast]')) {
      const text = `${toast.getAttribute('data-type')} toast "${(toast.textContent ?? '').trim()}"`
      if (!toasts.has(text)) {
        toasts.add(text)
        window.__events.push([Date.now(), text])
      }
    }
  }
  new MutationObserver(check).observe(document, {
    attributes: true,
    characterData: true,
    childList: true,
    subtree: true,
  })
})

const isServerAction = (req, name) =>
  req.method() === 'POST' && 'next-action' in req.headers() && (req.postData() ?? '').includes(name)

const open = async (slug) => {
  const create = `/admin/collections/${slug}/create`
  const isSave = (req) => req.method() === 'POST' && new URL(req.url()).pathname === `/api/${slug}`
  const page = await context.newPage()
  const log = []
  const at = (msg) => log.push([Date.now(), msg])
  // The slug field's "slugify" request, held until deliverSlug().
  const slugify = { armed: false, route: null, response: null }
  page.on('request', (req) => {
    if (isServerAction(req, 'form-state')) at('form-state sent')
    if (isServerAction(req, 'slugify')) at('slugify sent')
    if (isSave(req)) at('save sent')
  })
  await page.route(`**${create}`, async (route) => {
    if (!slugify.armed || !isServerAction(route.request(), 'slugify')) return route.continue()
    slugify.armed = false
    slugify.response = await route.fetch()
    slugify.route = route
  })
  // Every save is answered by the server at once and reaches the page 1 s later.
  await page.route(`**/api/${slug}**`, async (route) => {
    if (!isSave(route.request())) return route.continue()
    const response = await route.fetch()
    await page.waitForTimeout(1_000)
    await route.fulfill({ response })
    at(`save answered ${response.status()}`)
  })
  await page.goto(create, { timeout: 180_000 })
  await page.locator('form[data-form-ready="true"]').first().waitFor({ timeout: 180_000 })
  const t0 = Date.now()
  log.length = 0
  return {
    page,
    at,
    holdSlug: () => (slugify.armed = true),
    slugCaptured: async () => {
      while (!slugify.route) await page.waitForTimeout(25)
    },
    deliverSlug: async () => {
      at('HELD slugify answer delivered')
      await slugify.route.fulfill({ response: slugify.response })
    },
    result: async () => {
      const events = (await page.evaluate(() => window.__events)).filter(([time]) => time >= t0)
      const timeline = [...log, ...events]
        .sort((a, b) => a[0] - b[0])
        .map(([time, msg]) => `${time - t0}: ${msg}`)
        .join(' | ')
      const end =
        `titleError=${(await page.locator('.field-type.error:has(input[name="title"])').count()) > 0 ? 'SHOWN' : 'hidden'} ` +
        `errorToast=${events.some(([, msg]) => msg.startsWith('error toast')) ? 'SHOWN' : 'none'} ` +
        `saveEnabled=${await page.locator('#action-save').isEnabled()}`
      return { end, timeline }
    },
  }
}

const typeTitle = async (f) => {
  await f.page.locator('input[name="title"]').fill('not ok')
  await f.page.waitForTimeout(1_500) // let the form-state request for the typing settle
}

const scenarios = {
  async 'slug-control'(f) {
    await typeTitle(f)
    await f.page.locator('#field-slug-lock').click()
    await f.page.waitForTimeout(1_000)
    await f.page.locator('#field-slug-generate').click()
    f.at('Generate clicked')
    await f.page.waitForTimeout(1_500)
    f.at(`slug is "${await f.page.locator('#field-slug').inputValue()}"`)
    await f.page.locator('#action-save').click()
    f.at('save clicked')
  },
  async slug(f) {
    await typeTitle(f)
    await f.page.locator('#field-slug-lock').click()
    await f.page.waitForTimeout(1_000)
    f.holdSlug()
    await f.page.locator('#field-slug-generate').click()
    f.at('Generate clicked')
    await f.slugCaptured()
    await f.page.locator('#action-save').click()
    f.at('save clicked')
    await f.page.waitForTimeout(300)
    await f.deliverSlug()
    await f.page.waitForTimeout(1_500)
    f.at(`slug is "${await f.page.locator('#field-slug').inputValue()}"`)
  },
  async 'richtext-control'(f) {
    await typeTitle(f)
    await f.page.locator('[data-lexical-editor="true"]').first().click()
    await f.page.waitForTimeout(500)
    await f.page.keyboard.type('hello')
    f.at('typed in the rich text field')
    await f.page.waitForTimeout(1_500)
    await f.page.keyboard.press('ControlOrMeta+s')
    f.at('save hotkey pressed')
  },
  async richtext(f) {
    await typeTitle(f)
    await f.page.locator('[data-lexical-editor="true"]').first().click()
    await f.page.waitForTimeout(500)
    await f.page.keyboard.type('hello')
    await f.page.keyboard.press('ControlOrMeta+s')
    f.at('typed in the rich text field, save hotkey pressed')
  },
  async component(f) {
    await typeTitle(f)
    await f.page.locator('#action-save').click()
    f.at('save clicked')
    await f.page.waitForTimeout(300)
    await f.page.locator('#set-note').click()
    f.at('note set by the component')
  },
}

const names = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(scenarios)
for (const name of names) {
  for (let run = 1; run <= RUNS; run++) {
    const f = await open(collections[name])
    await scenarios[name](f)
    await f.page.waitForTimeout(5_000)
    const { end, timeline } = await f.result()
    console.log(`${name.padEnd(16)} #${run} END: ${end}`)
    console.log(`      ${timeline}`)
    await f.page.close()
  }
}

await browser.close()

Output (ms since the create view was ready; END = state 5 s after the last step). Runs of one scenario agree, except richtext: of 10 runs (the 3 from the command above and 7 more of richtext alone), 8 showed nothing, like run 2 below, and 2 showed the toast and the error, like run 1.

slug-control     #1 END: titleError=SHOWN errorToast=SHOWN saveEnabled=true
      345: form-state sent | 2665: slugify sent | 2666: Generate clicked | 2959: form-state sent | 4173: slug is "not-ok" | 4204: save sent | 4207: save clicked | 5243: save answered 400 | 5248: form-state sent | 5297: title error SHOWN | 5312: error toast "The following field is invalid: Title"
slug             #1 END: titleError=hidden errorToast=none saveEnabled=true
      313: form-state sent | 2627: slugify sent | 2629: Generate clicked | 2713: save sent | 2714: save clicked | 3016: HELD slugify answer delivered | 3737: save answered 400 | 3747: form-state sent | 4522: slug is "not-ok"
richtext-control #1 END: titleError=SHOWN errorToast=SHOWN saveEnabled=true
      416: form-state sent | 2368: typed in the rich text field | 2645: form-state sent | 3892: save sent | 3895: save hotkey pressed | 4927: save answered 400 | 4932: form-state sent | 4992: title error SHOWN | 5008: error toast "The following field is invalid: Title"
richtext         #1 END: titleError=SHOWN errorToast=SHOWN saveEnabled=true
      394: form-state sent | 2405: save sent | 2408: typed in the rich text field, save hotkey pressed | 3431: save answered 400 | 3435: form-state sent | 3491: title error SHOWN | 3492: form-state sent | 3514: error toast "The following field is invalid: Title"
richtext         #2 END: titleError=hidden errorToast=none saveEnabled=true
      401: form-state sent | 2408: save sent | 2410: typed in the rich text field, save hotkey pressed | 3432: save answered 400 | 3448: form-state sent
component        #1 END: titleError=hidden errorToast=none saveEnabled=true
      313: form-state sent | 1602: save sent | 1651: save clicked | 1978: note set by the component | 2626: save answered 400 | 2634: form-state sent

Expected: a rejected save says so: the toast shows, and the fields whose values are still the ones that were sent are marked.

Which area(s) are affected?

area: ui

Environment Info

Payload monorepo, main at b0d2f5003b8171ff6f683e070334e4a06373dc4d (4.0.0-beta.11 + 13 commits)
Dev server: PAYLOAD_DATABASE=sqlite pnpm dev (Next.js 16.4.6, Turbopack)

Binaries:
  Node: 24.22.3
  pnpm: 11.28.6
Relevant Packages:
  payload, @payloadcms/ui, @payloadcms/next, @payloadcms/richtext-lexical, @payloadcms/db-sqlite: workspace (4.0.0-beta.11)
  next: 16.4.6
  react: 19.3.1
  react-dom: 19.3.1
  lexical: 0.53.0
  @playwright/test: 1.63.0, headless Chromium (Playwright build 1208, via CHROMIUM_PATH)
Operating System:
  Platform: darwin
  Arch: x64
  Version: Darwin Kernel Version 24.6.0

Activity

  1. added
    area: ui
    on Nov 24, 2026
  2. self-assigned this
    on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

BugPayload OSSarea: ui

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions