Skip to content

Beautiful Open-Source Form Builder

Fix agent draft editor autosave loops and version conflicts (#1332)

Julien Nahumb2b1fc9bb328
diff --git a/api/tests/Feature/Forms/VersionTest.php b/api/tests/Feature/Forms/VersionTest.php
index 921dff1b4..b4eb90f47 100644
--- a/api/tests/Feature/Forms/VersionTest.php
+++ b/api/tests/Feature/Forms/VersionTest.php
@@ -114,17 +114,18 @@ describe('Submission Versions', function () {
describe('Form Version Preview', function () {
it('can preview a form version as pro user', function () {
+ $this->freezeTime();
+
$user = $this->actingAsBusinessUser();
$workspace = $this->createUserWorkspace($user);
$form = $this->createForm($user, $workspace);
$originalTitle = $form->title;
+ // Capture the initial snapshot before creating a second version.
+ // latest() is ambiguous when both versions share a created_at timestamp.
+ $version = $form->versions()->sole();
- // Update form to create a version
$form->update(['title' => 'Changed Title']);
- // Get the version (should have the original title)
- $version = $form->versions()->latest()->first();
-
// Preview the versioned form via API (form restore is frontend-only)
$response = $this->getJson(route('open.forms.show', $form->slug) . "?version_id={$version->version_id}")
->assertSuccessful();
diff --git a/client/lib/forms/agent-draft-errors.js b/client/lib/forms/agent-draft-errors.js
index 1f87afc86..2b7837dc0 100644
--- a/client/lib/forms/agent-draft-errors.js
+++ b/client/lib/forms/agent-draft-errors.js
@@ -1,6 +1,8 @@
export function isAgentDraftVersionConflict(exception) {
const status = exception?.statusCode ?? exception?.status ?? exception?.response?.status
- const errors = exception?.data?.errors ?? exception?.response?._data?.errors
+ // Nitro wraps the Laravel response in its own `data` field.
+ const payload = exception?.data ?? exception?.response?._data
+ const errors = payload?.errors ?? payload?.data?.errors
return status === 422
&& errors !== null
diff --git a/client/pages/agent-drafts/edit.vue b/client/pages/agent-drafts/edit.vue
index 6231b5644..b58395480 100644
--- a/client/pages/agent-drafts/edit.vue
+++ b/client/pages/agent-drafts/edit.vue
@@ -14,7 +14,7 @@
<FormEditor
v-else
class="w-full grow"
- :loading="saving"
+ :loading="claiming"
:save-handler="syncDraft"
:back-button="false"
>
@@ -77,7 +77,6 @@ const { isAuthenticated } = useIsAuthenticated()
provide('disableCustomCodeExecution', true)
const loading = ref(true)
-const saving = ref(false)
const claiming = ref(false)
const fatalError = ref(null)
const version = ref(null)
@@ -89,6 +88,8 @@ const workspaceModalOpen = ref(false)
const claimAfterLogin = ref(false)
const hydratingEditor = ref(true)
let syncPromise = null
+let editorForm = null
+let editorActive = true
const syncLabel = computed(() => ({
saving: 'Saving draft…',
@@ -117,47 +118,44 @@ const applyDraft = (draft) => {
version.value = draft.version
const definition = cleanDefinition(draft.definition)
lastSavedFingerprint.value = JSON.stringify(definition)
- workingFormStore.set(useForm(definition))
+ editorForm = useForm(definition)
+ if (editorActive) workingFormStore.set(editorForm)
syncState.value = 'saved'
}
const refreshDraft = () => $fetch('/api/agent-drafts/current').then((response) => {
+ hydratingEditor.value = true
applyDraft(response.draft)
- return response.draft
+ return nextTick().then(() => {
+ lastSavedFingerprint.value = JSON.stringify(cleanDefinition(editorForm?.data()))
+ hydratingEditor.value = false
+ return response.draft
+ })
})
const performSync = (rawData, keepalive = false) => {
- const definition = cleanDefinition(rawData || workingFormStore.content?.data())
+ if (syncPromise) {
+ // Read the latest editor state after the previous save (or conflict refresh).
+ return syncPromise.then(() => performSync(undefined, keepalive))
+ }
+ const definition = cleanDefinition(rawData || editorForm?.data())
const fingerprint = JSON.stringify(definition)
if (!definition || fingerprint === lastSavedFingerprint.value) {
return Promise.resolve()
}
- if (syncPromise) {
- return syncPromise.then(() => performSync(definition, keepalive))
- }
- saving.value = true
syncState.value = 'saving'
syncPromise = $fetch('/api/agent-drafts/current', {
method: 'PUT',
body: { expected_version: version.value, definition },
keepalive,
}).then((response) => {
- const serverDefinition = cleanDefinition(response.draft.definition)
- const serverFingerprint = JSON.stringify(serverDefinition)
- const currentData = workingFormStore.content?.data?.()
- const currentFingerprint = currentData
- ? JSON.stringify(cleanDefinition(currentData))
- : null
-
version.value = response.draft.version
- lastSavedFingerprint.value = serverFingerprint
-
- // Reflect deterministic server cleanups without overwriting edits made
- // while this request was in flight.
- if (currentFingerprint === fingerprint && serverFingerprint !== fingerprint) {
- workingFormStore.set(useForm(serverDefinition))
- }
+ // Acknowledge the submitted snapshot, not the server's normalized shape.
+ // Replacing the form here makes editor defaults (e.g. settings {} vs [])
+ // look like new edits and can start an endless autosave/rehydration loop.
+ // Later edits remain dirty and will be saved by the next queued sync.
+ lastSavedFingerprint.value = fingerprint
syncState.value = 'saved'
}).catch((exception) => {
@@ -170,7 +168,6 @@ const performSync = (rawData, keepalive = false) => {
useAlert().error(exception?.data?.message || 'Unable to save this draft right now.')
throw exception
}).finally(() => {
- saving.value = false
syncPromise = null
})
@@ -184,12 +181,22 @@ const syncDraft = (data) => performSync(data).then(() => {
const draftAutosave = createAgentDraftAutosave(({ keepalive }) => performSync(undefined, keepalive))
const scheduleSync = () => {
- if (loading.value || claiming.value || hydratingEditor.value) return
+ if (!editorActive || loading.value || claiming.value || hydratingEditor.value) return
draftAutosave.schedule()
}
const flushPendingSync = () => draftAutosave.flush().catch(() => {})
+const warnBeforeUnload = (event) => {
+ if (loading.value || !editorForm) return
+ const fingerprint = JSON.stringify(cleanDefinition(editorForm.data()))
+ if (!syncPromise && fingerprint === lastSavedFingerprint.value) return
+
+ // A pagehide flush queued behind an ordinary PUT may never run on teardown.
+ event.preventDefault()
+ event.returnValue = ''
+}
+
watch(() => workingFormStore.content?.data?.(), scheduleSync, { deep: true })
const prepareClaim = () => {
@@ -249,6 +256,7 @@ const claimDraft = () => {
onMounted(() => {
window.addEventListener('pagehide', flushPendingSync)
+ window.addEventListener('beforeunload', warnBeforeUnload)
const sessionRequest = getAgentDraftSessionRequest(window.location.hash)
if (sessionRequest.consumesHandoff) {
@@ -262,7 +270,7 @@ onMounted(() => {
loading.value = false
if (!fatalError.value) {
nextTick().then(() => {
- lastSavedFingerprint.value = JSON.stringify(cleanDefinition(workingFormStore.content?.data()))
+ lastSavedFingerprint.value = JSON.stringify(cleanDefinition(editorForm?.data()))
hydratingEditor.value = false
})
}
@@ -277,7 +285,9 @@ onMounted(() => {
})
onBeforeUnmount(() => {
+ editorActive = false
window.removeEventListener('pagehide', flushPendingSync)
+ window.removeEventListener('beforeunload', warnBeforeUnload)
flushPendingSync()
})
</script>
diff --git a/client/test/nuxt/agent-draft-editor.spec.ts b/client/test/nuxt/agent-draft-editor.spec.ts
new file mode 100644
index 000000000..4acee741c
--- /dev/null
+++ b/client/test/nuxt/agent-draft-editor.spec.ts
@@ -0,0 +1,256 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { flushPromises, mount } from '@vue/test-utils'
+import { computed, defineComponent, nextTick, reactive, watch } from 'vue'
+import { mockNuxtImport } from '@nuxt/test-utils/runtime'
+import DraftEditor from '~/pages/agent-drafts/edit.vue'
+
+const mocks = vi.hoisted(() => ({
+ store: null as any,
+ authenticated: false,
+ alert: { success: vi.fn(), warning: vi.fn(), error: vi.fn() },
+}))
+
+vi.mock('~/composables/useIsAuthenticated', () => ({
+ useIsAuthenticated: () => ({ isAuthenticated: computed(() => mocks.authenticated) }),
+}))
+mockNuxtImport('useOpnSeoMeta', () => () => {})
+vi.mock('~/composables/useAlert', () => ({ useAlert: () => mocks.alert }))
+mockNuxtImport('useWindowMessage', () => () => ({ listen: vi.fn() }))
+mockNuxtImport('useForm', () => (definition: any) => reactive({
+ ...definition,
+ data() {
+ const { data: _data, ...values } = this
+ return values
+ },
+}))
+
+// Exercise the same settings hydration as FormEditor, without the full builder.
+vi.mock('~/components/open/forms/components/FormEditor.vue', () => ({
+ default: defineComponent({
+ name: 'AgentFormEditorStub',
+ props: ['saveHandler', 'loading'],
+ setup() {
+ watch(() => mocks.store.content, (form) => {
+ if (Array.isArray(form.settings)) form.settings = {}
+ }, { immediate: true, flush: 'sync' })
+ },
+ template: '<div><slot name="before-save" /></div>',
+ }),
+}))
+vi.mock('~/api', () => ({ workspaceApi: { list: vi.fn().mockResolvedValue([{ id: 1, name: 'Test workspace' }]) } }))
+
+const draft = (version = 1, title = 'Agent form') => ({
+ version,
+ definition: { title, settings: [], properties: [{ id: 'name', type: 'text', name: 'Name' }] },
+})
+
+let wrapper: ReturnType<typeof mount> | undefined
+let fetchMock: ReturnType<typeof vi.fn>
+
+async function openEditor() {
+ wrapper = mount(DraftEditor, {
+ global: { stubs: { UModal: true, UButton: true, UAlert: true, Loader: true, SelectInput: true } },
+ })
+ await flushPromises()
+ await nextTick()
+}
+
+async function debounceSave() {
+ await nextTick()
+ await vi.advanceTimersByTimeAsync(900)
+ await flushPromises()
+}
+
+function writes() {
+ return fetchMock.mock.calls.filter(([, options]) => options?.method === 'PUT')
+}
+
+describe('agent draft editor autosave', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.clearAllMocks()
+ mocks.authenticated = false
+ mocks.store = reactive({ content: null, set(form: any) { this.content = form } })
+ fetchMock = vi.fn().mockResolvedValue({ draft: draft() })
+ vi.stubGlobal('$fetch', fetchMock)
+ vi.stubGlobal('useWorkingFormStore', () => mocks.store)
+ vi.stubGlobal('useAppStore', () => ({}))
+ })
+
+ afterEach(() => {
+ wrapper?.unmount()
+ wrapper = undefined
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it('does not save an untouched draft after editor hydration', async () => {
+ await openEditor()
+ await vi.advanceTimersByTimeAsync(9000)
+ expect(writes()).toHaveLength(0)
+ })
+
+ it('saves one edit once even when the server normalizes settings back to an array', async () => {
+ await openEditor()
+ fetchMock.mockResolvedValue({ draft: draft(2, 'Changed') })
+ const form = mocks.store.content
+ form.title = 'Changed'
+ await debounceSave()
+ await vi.advanceTimersByTimeAsync(9000)
+
+ expect(writes()).toHaveLength(1)
+ expect(writes()[0][1].body).toMatchObject({ expected_version: 1, definition: { title: 'Changed', settings: {} } })
+ expect(mocks.store.content).toBe(form)
+ })
+
+ it('keeps edits made during a save and serializes the next save with the new version', async () => {
+ await openEditor()
+ let resolveSave: (value: any) => void = () => {}
+ fetchMock.mockImplementationOnce(() => new Promise(resolve => { resolveSave = resolve }))
+ mocks.store.content.title = 'First'
+ await debounceSave()
+ mocks.store.content.title = 'Second'
+ await debounceSave()
+ expect(writes()).toHaveLength(1)
+
+ fetchMock.mockResolvedValue({ draft: draft(3, 'Second') })
+ resolveSave({ draft: draft(2, 'First') })
+ await flushPromises()
+
+ expect(writes()).toHaveLength(2)
+ expect(writes()[1][1].body).toMatchObject({ expected_version: 2, definition: { title: 'Second' } })
+ expect(mocks.store.content.title).toBe('Second')
+ await vi.advanceTimersByTimeAsync(9000)
+ expect(writes()).toHaveLength(2)
+ })
+
+ it.each([false, true])('guards closing during an in-flight save with a second edit (debounce elapsed: %s)', async (debounceElapsed) => {
+ await openEditor()
+ let resolveSave: (value: any) => void = () => {}
+ fetchMock.mockImplementationOnce(() => new Promise(resolve => { resolveSave = resolve }))
+ mocks.store.content.title = 'First'
+ await debounceSave()
+ mocks.store.content.title = 'Latest edit'
+ await nextTick()
+ if (debounceElapsed) await debounceSave()
+
+ const beforeUnload = new Event('beforeunload', { cancelable: true })
+ window.dispatchEvent(beforeUnload)
+ expect(beforeUnload.defaultPrevented).toBe(true)
+ window.dispatchEvent(new Event('pagehide'))
+
+ fetchMock.mockResolvedValue({ draft: draft(3, 'Latest edit') })
+ resolveSave({ draft: draft(2, 'First') })
+ await flushPromises()
+ expect(writes()).toHaveLength(2)
+ expect(writes()[1][1].body.definition.title).toBe('Latest edit')
+
+ const savedUnload = new Event('beforeunload', { cancelable: true })
+ window.dispatchEvent(savedUnload)
+ expect(savedUnload.defaultPrevented).toBe(false)
+ })
+
+ it('does not guard an unchanged draft and removes the guard on navigation', async () => {
+ await openEditor()
+ const unchangedUnload = new Event('beforeunload', { cancelable: true })
+ window.dispatchEvent(unchangedUnload)
+ expect(unchangedUnload.defaultPrevented).toBe(false)
+ mocks.store.content.title = 'Unsaved edit'
+ await nextTick()
+ const dirtyUnload = new Event('beforeunload', { cancelable: true })
+ window.dispatchEvent(dirtyUnload)
+ expect(dirtyUnload.defaultPrevented).toBe(true)
+ wrapper?.unmount()
+ wrapper = undefined
+ const navigatedUnload = new Event('beforeunload', { cancelable: true })
+ window.dispatchEvent(navigatedUnload)
+ expect(navigatedUnload.defaultPrevented).toBe(false)
+ await flushPromises()
+ })
+
+ it('blocks the editor while the final save and account claim are in progress', async () => {
+ mocks.authenticated = true
+ await openEditor()
+ mocks.store.content.title = 'Final account draft'
+ await nextTick()
+ let resolveSave: (value: any) => void = () => {}
+ fetchMock.mockImplementationOnce(() => new Promise(resolve => { resolveSave = resolve }))
+ wrapper?.findComponent({ name: 'UButton' }).vm.$emit('click', new MouseEvent('click'))
+ await nextTick()
+
+ expect(writes()).toHaveLength(1)
+ expect(wrapper?.findComponent({ name: 'AgentFormEditorStub' }).props('loading')).toBe(true)
+ fetchMock.mockImplementationOnce(() => new Promise(() => {}))
+ resolveSave({ draft: draft(2, 'Final account draft') })
+ await flushPromises()
+ expect(fetchMock.mock.calls.some(([url]) => url === '/api/agent-drafts/claim')).toBe(true)
+ expect(wrapper?.findComponent({ name: 'AgentFormEditorStub' }).props('loading')).toBe(true)
+ })
+
+ it('flushes the original editor when navigation replaces the shared form during a save', async () => {
+ await openEditor()
+ let resolveSave: (value: any) => void = () => {}
+ fetchMock.mockImplementationOnce(() => new Promise(resolve => { resolveSave = resolve }))
+ mocks.store.content.title = 'First'
+ await debounceSave()
+ mocks.store.content.title = 'Last edit before navigation'
+ await nextTick()
+ wrapper?.unmount()
+ wrapper = undefined
+ const destinationForm = { title: 'Unrelated destination form', data() { return { title: this.title } } }
+ mocks.store.set(destinationForm)
+
+ fetchMock.mockResolvedValue({ draft: draft(3, 'Last edit before navigation') })
+ resolveSave({ draft: draft(2, 'First') })
+ await flushPromises()
+
+ expect(writes()).toHaveLength(2)
+ expect(writes()[1][1]).toMatchObject({
+ keepalive: true,
+ body: { expected_version: 2, definition: { title: 'Last edit before navigation' } },
+ })
+ expect(mocks.store.content.title).toBe('Unrelated destination form')
+ })
+
+ it('does not replace the destination form when a conflict refresh finishes after navigation', async () => {
+ await openEditor()
+ let rejectSave: (error: any) => void = () => {}
+ fetchMock.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectSave = reject }))
+ mocks.store.content.title = 'Local edit'
+ await debounceSave()
+ wrapper?.unmount()
+ wrapper = undefined
+ mocks.store.set({ title: 'Destination form' })
+ fetchMock.mockResolvedValue({ draft: draft(37, 'Agent revision') })
+ rejectSave({ statusCode: 422, data: { data: { errors: { expected_version: ['Conflict'] } } } })
+ await flushPromises()
+
+ expect(mocks.store.content.title).toBe('Destination form')
+ expect(writes()).toHaveLength(1)
+ })
+
+ it('refreshes a wrapped version conflict without replaying a queued stale edit', async () => {
+ await openEditor()
+ let rejectSave: (error: any) => void = () => {}
+ fetchMock.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectSave = reject }))
+ mocks.store.content.title = 'Local'
+ await debounceSave()
+ mocks.store.content.title = 'Queued local edit'
+ await debounceSave()
+
+ fetchMock.mockResolvedValue({ draft: draft(37, 'Agent revision') })
+ rejectSave({ statusCode: 422, data: { data: { errors: { expected_version: ['Conflict'] } } } })
+ await flushPromises()
+ await vi.advanceTimersByTimeAsync(9000)
+
+ expect(mocks.store.content.title).toBe('Agent revision')
+ expect(writes()).toHaveLength(1)
+ await flushPromises()
+ mocks.store.content.title = 'New edit after refresh'
+ await debounceSave()
+ expect(writes()).toHaveLength(2)
+ expect(writes()[1][1].body.expected_version).toBe(37)
+ expect(mocks.alert.warning).toHaveBeenCalledOnce()
+ expect(mocks.alert.error).not.toHaveBeenCalled()
+ })
+})
diff --git a/client/test/unit/agent-draft-errors.test.ts b/client/test/unit/agent-draft-errors.test.ts
index 0633e265b..269449df7 100644
--- a/client/test/unit/agent-draft-errors.test.ts
+++ b/client/test/unit/agent-draft-errors.test.ts
@@ -13,6 +13,18 @@ describe('isAgentDraftVersionConflict', () => {
})).toBe(true)
})
+ it('recognizes Laravel errors wrapped by the Nuxt proxy', () => {
+ expect(isAgentDraftVersionConflict({
+ response: {
+ status: 422,
+ _data: {
+ statusCode: 422,
+ data: { errors: { expected_version: ['Draft version conflict.'] } },
+ },
+ },
+ })).toBe(true)
+ })
+
it('does not treat definition validation errors as version conflicts', () => {
expect(isAgentDraftVersionConflict({
statusCode: 422,
diff --git a/docs/integrations/mcp.mdx b/docs/integrations/mcp.mdx
index f0974f703..732ec798f 100644
--- a/docs/integrations/mcp.mdx
+++ b/docs/integrations/mcp.mdx
@@ -49,7 +49,7 @@ The preview is private and does not publish the form.
</Step>
<Step title="Open the draft in OpnForm">
-Select **Open in OpnForm** when you want to continue in the visual editor. You can customize the design before creating an account or signing in to save the form.
+Select **Open in OpnForm** when you want to continue in the visual editor. You can customize the design before creating an account or signing in to save the form. Changes are saved automatically to the private draft without publishing it. Keep the editor open until it shows **Draft saved**; closing or reloading with unsaved changes triggers a browser warning. If the assistant updates the same draft while you are editing, the editor reloads the latest version and displays a warning.
</Step>
<Step title="Connect your account when needed">