From c6731fdfcbc990fe6a8f6c08a1b925eb6445ed8d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Tue, 3 Nov 2026 08:28:12 -0800 Subject: [PATCH 1/2] fix(agent): keep an unsent chat draft across a page refresh The Agent composer now saves its draft text and workflow references to localStorage, tagged with the chat it was written in, and restores it after a reload only into that same chat. A successful send and New Chat (clearDraft) clear the saved draft. Node references, skill references and attachments are not restored: they are scoped to a tab instance, the loaded skill-pack scope, and in-memory blobs respectively. Fixes PM-2002 --- .../agentComposerDraftSurvivesReload.spec.ts | 63 ++++++++++++++++ .../workflow/persistence/base/storageIO.ts | 3 +- .../workflow/persistence/base/storageKeys.ts | 7 +- .../extensions/agent/AgentPanelRoot.vue | 5 ++ .../stores/agent/agentComposerStore.test.ts | 71 +++++++++++++++++++ .../agent/stores/agent/agentComposerStore.ts | 71 ++++++++++++++++++- 6 files changed, 215 insertions(+), 5 deletions(-) create mode 100644 browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts diff --git a/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts b/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts new file mode 100644 index 00000000000..65d74f4becd --- /dev/null +++ b/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts @@ -0,0 +1,63 @@ +import { expect } from '@playwright/test' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } + +import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' +import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' + +// PM-2002 (https://linear.app/comfyorg/issue/PM-2002): refreshing the page +// wiped an unsent Agent chat draft with no warning. The draft now survives a +// reload in the chat it was written in, and New Chat (PM-2251) still starts +// empty after a reload rather than bringing the discarded draft back. +test.describe( + 'Agent composer draft survives a page refresh', + { tag: ['@cloud', '@ui'] }, + () => { + test('restores an unsent draft after a reload, but not one discarded by New Chat', async ({ + agentPanel, + page + }, testInfo) => { + await agentPanel.open() + const draft = 'Make the background a sunset over the ocean' + + await test.step('an unsent draft is still in the composer after a reload', async () => { + await agentPanel.composer.fill(draft) + await expect(agentPanel.composer).toHaveText(draft) + + await page.reload() + await waitForCloudApp(page) + await agentPanel.open() + await expect(agentPanel.composer).toHaveText(draft) + await testInfo.attach('draft-restored-after-reload', { + body: await agentPanel.root.screenshot({ + path: testInfo.outputPath('draft-restored-after-reload.png') + }), + contentType: 'image/png' + }) + }) + + await test.step('New Chat leaves the composer empty after a reload', async () => { + await agentPanel.root + .getByRole('button', { name: enMessages.agent.newChat }) + .click() + await expect(agentPanel.composer).toHaveText('') + + await page.reload() + await waitForCloudApp(page) + await agentPanel.open() + await expect( + agentPanel.root.getByText(enMessages.agent.placeholder, { + exact: true + }) + ).toBeVisible() + await expect(agentPanel.composer).toHaveText('') + await testInfo.attach('new-chat-empty-after-reload', { + body: await agentPanel.root.screenshot({ + path: testInfo.outputPath('new-chat-empty-after-reload.png') + }), + contentType: 'image/png' + }) + }) + }) + } +) diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index 0d66fd5953c..0c17ae405ec 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -664,7 +664,8 @@ export function clearAllWorkspaceStorage(): void { StorageKeys.prefixes.agentThread, StorageKeys.prefixes.agentWorkflowTabBindings, StorageKeys.prefixes.agentChatTitles, - StorageKeys.prefixes.agentDeletedThreads + StorageKeys.prefixes.agentDeletedThreads, + StorageKeys.prefixes.agentComposerDraft ] ) } diff --git a/src/platform/workflow/persistence/base/storageKeys.ts b/src/platform/workflow/persistence/base/storageKeys.ts index 607bab5c1f5..2170594479c 100644 --- a/src/platform/workflow/persistence/base/storageKeys.ts +++ b/src/platform/workflow/persistence/base/storageKeys.ts @@ -91,6 +91,10 @@ export const StorageKeys = { return `Comfy.Agent.DeletedThreads:${workspaceId}` }, + agentComposerDraft(workspaceId: string): string { + return `Comfy.Agent.ComposerDraft:${workspaceId}` + }, + /** * localStorage copies of tab pointers for cross-session restore. * sessionStorage is per-tab (correct for in-session use) but lost @@ -117,6 +121,7 @@ export const StorageKeys = { agentThread: 'Comfy.Agent.ThreadId:', agentWorkflowTabBindings: 'Comfy.Agent.WorkflowTabBindings:', agentChatTitles: 'Comfy.Agent.ChatTitles:', - agentDeletedThreads: 'Comfy.Agent.DeletedThreads:' + agentDeletedThreads: 'Comfy.Agent.DeletedThreads:', + agentComposerDraft: 'Comfy.Agent.ComposerDraft:' } } as const diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index d3a1fcab999..b04b40da32f 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -2282,6 +2282,11 @@ start({ (agentPanelStore.view.selection.status === 'idle' && threadId.value === agentPanelStore.view.previousThreadId) }) +// After start(): on a page load, threadId is now the chat being restored. +watch(threadId, composerStore.trackDraftThread, { + immediate: true, + flush: 'sync' +}) watch(() => canvasStore.currentGraph, canvasStore.stopNodePicking, { flush: 'sync' diff --git a/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts b/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts index c844e9022b0..92c2177673e 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts @@ -1,4 +1,6 @@ +import { getActivePinia } from 'pinia' import { assert, describe, expect, it, vi } from 'vitest' +import { nextTick } from 'vue' import { createMockLoadedWorkflow } from '@/utils/__tests__/litegraphTestUtils' @@ -380,6 +382,75 @@ describe('composer draft presence', () => { }) }) +describe('composer draft persistence (PM-2002)', () => { + // A page load is a fresh store, with no in-memory state, over the same + // localStorage. + async function reloadPage() { + await nextTick() + const store = useAgentComposerStore() + store.$dispose() + delete getActivePinia()?.state.value[store.$id] + return useAgentComposerStore() + } + + it('does not restore a draft into a different chat', async () => { + const store = useAgentComposerStore() + store.trackDraftThread('thread-a') + store.setText('Only for thread A') + + const otherChat = await reloadPage() + otherChat.trackDraftThread('thread-b') + expect(otherChat.hasDraft).toBe(false) + }) + + it('restores text and workflow references, dropping node references and attachments', async () => { + const store = useAgentComposerStore() + store.trackDraftThread('thread-a') + store.setText('Use as the style') + store.setWorkflowReferences([ + { id: 'wf-portrait', name: 'portrait', textOffset: 4 } + ]) + store.setNodeScope('tab-1') + store.setNodes([{ id: '7', title: 'KSampler' }]) + store.addAttachment({ id: 'a-1', name: 'cat.png', ref: 'cat.png' }) + const text = store.draft + + const restored = await reloadPage() + restored.trackDraftThread('thread-a') + expect(restored.prompt).toEqual({ + text, + references: [ + { kind: 'workflow', id: 'wf-portrait', name: 'portrait', textOffset: 4 } + ] + }) + expect(restored.attachments).toEqual([]) + }) + + it('forgets the draft once it is sent or cleared', async () => { + const sent = useAgentComposerStore() + sent.trackDraftThread(null) + sent.setText('Make it blue') + await nextTick() + const id = sent.startSubmission({ + prompt: sent.prompt, + attachments: [], + nodes: [], + target: createMockLoadedWorkflow({ path: 'workflows/target.json' }) + }) + sent.settleSubmission(id, true) + const afterSend = await reloadPage() + afterSend.trackDraftThread(null) + expect(afterSend.hasDraft).toBe(false) + + afterSend.setText('Make it red') + await nextTick() + afterSend.clearDraft() + const afterClear = await reloadPage() + afterClear.trackDraftThread(null) + expect(afterClear.hasDraft).toBe(false) + }) +}) + describe('composer prompt origin (PM-1474 F11)', () => { it('starts out typed and stays typed while the user writes', () => { const store = useAgentComposerStore() diff --git a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts index c546ef1d18a..89512618540 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts @@ -1,6 +1,18 @@ +import { StorageSerializers, useLocalStorage } from '@vueuse/core' import { defineStore } from 'pinia' -import { computed, onScopeDispose, ref, shallowReactive, shallowRef } from 'vue' - +import { + computed, + onScopeDispose, + ref, + shallowReactive, + shallowRef, + watch +} from 'vue' + +import { + getWorkspaceId, + StorageKeys +} from '@/platform/workflow/persistence/base/storageKeys' import { getMediaTypeFromFilename } from '@/utils/formatUtil' import type { AgentInputMethod } from '@comfyorg/telemetry/types' @@ -45,6 +57,19 @@ function composerReferencePosition(reference: ComposerReference): string { return `${composerReferenceKey(reference)}@${reference.textOffset}` } +/** + * The unsent draft as written to localStorage, tagged with the chat it + * belongs to (`null` for a chat with no thread yet). Only text and workflow + * references are kept: node references are scoped to a tab instance, skill + * references to the loaded skill-pack scope, and attachments to in-memory + * blobs, none of which survive a page load. + */ +interface SavedDraft { + threadId: string | null + text: string + workflowReferences: WorkflowReference[] +} + interface SubmittedDraft { attachments: ComposerAttachment[] nodes: SelectedNode[] @@ -606,6 +631,45 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { releaseUnusedAssets() } + // PM-2002: the unsent draft survives a page refresh. Nothing is written + // until the panel reports which chat is open, so the empty composer of a + // freshly loaded page cannot overwrite the draft before it is restored. + const savedDraft = useLocalStorage( + StorageKeys.agentComposerDraft(getWorkspaceId()), + null, + { serializer: StorageSerializers.object } + ) + const draftThreadId = ref() + + watch([draftState, draftThreadId], ([state, threadId]) => { + if (threadId === undefined) return + const references = workflowReferences.value + savedDraft.value = + state.text.trim() !== '' || references.length > 0 + ? { threadId, text: state.text, workflowReferences: references } + : null + }) + + /** + * Tells the composer which chat is open. The first call after a page load + * restores the saved draft when it was written in that same chat; later + * calls only retag what is saved. + */ + function trackDraftThread(threadId: string | null): void { + const saved = savedDraft.value + if ( + draftThreadId.value === undefined && + saved?.threadId === threadId && + !hasDraft.value + ) + replaceDraft({ + text: saved.text, + workflowReferences: saved.workflowReferences, + attachments: [] + }) + draftThreadId.value = threadId + } + return { draftState, draft, @@ -648,6 +712,7 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { settleSubmission, takeFailedSubmission, invalidateSubmission, - clearDraft + clearDraft, + trackDraftThread } }) From c590da8e7d5512a27aee3e5fea6fb573d49c034c Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Tue, 3 Nov 2026 09:20:35 -0800 Subject: [PATCH 2/2] fix(agent): discard a malformed saved composer draft instead of throwing Validate the persisted draft with a zod schema before restoring it. An entry with the wrong shape (for example null text or non-array references) is cleared from localStorage and the composer starts empty and usable, instead of throwing from promptReferenceParts on every panel start. Remove the comments the PR added; the rationale lives in the PR description. Amp-Thread-ID: https://ampcode.com/threads/T-01a1a265-7ae1-7473-b0dd-23573f0fa73e --- .../agentComposerDraftSurvivesReload.spec.ts | 4 -- .../extensions/agent/AgentPanelRoot.vue | 1 - .../stores/agent/agentComposerStore.test.ts | 28 +++++++++- .../agent/stores/agent/agentComposerStore.ts | 56 ++++++++----------- 4 files changed, 50 insertions(+), 39 deletions(-) diff --git a/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts b/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts index 65d74f4becd..5b19d26f906 100644 --- a/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts +++ b/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts @@ -5,10 +5,6 @@ import enMessages from '@/locales/en/main.json' with { type: 'json' } import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' -// PM-2002 (https://linear.app/comfyorg/issue/PM-2002): refreshing the page -// wiped an unsent Agent chat draft with no warning. The draft now survives a -// reload in the chat it was written in, and New Chat (PM-2251) still starts -// empty after a reload rather than bringing the discarded draft back. test.describe( 'Agent composer draft survives a page refresh', { tag: ['@cloud', '@ui'] }, diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index b04b40da32f..68d29c2b4e2 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -2282,7 +2282,6 @@ start({ (agentPanelStore.view.selection.status === 'idle' && threadId.value === agentPanelStore.view.previousThreadId) }) -// After start(): on a page load, threadId is now the chat being restored. watch(threadId, composerStore.trackDraftThread, { immediate: true, flush: 'sync' diff --git a/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts b/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts index 92c2177673e..ebc1b5993b8 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts @@ -2,6 +2,10 @@ import { getActivePinia } from 'pinia' import { assert, describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' +import { + getWorkspaceId, + StorageKeys +} from '@/platform/workflow/persistence/base/storageKeys' import { createMockLoadedWorkflow } from '@/utils/__tests__/litegraphTestUtils' import { useAgentComposerStore } from './agentComposerStore' @@ -383,8 +387,6 @@ describe('composer draft presence', () => { }) describe('composer draft persistence (PM-2002)', () => { - // A page load is a fresh store, with no in-memory state, over the same - // localStorage. async function reloadPage() { await nextTick() const store = useAgentComposerStore() @@ -426,6 +428,28 @@ describe('composer draft persistence (PM-2002)', () => { expect(restored.attachments).toEqual([]) }) + it.for([ + { threadId: null, text: null, workflowReferences: [] }, + { threadId: null, text: 'Hi', workflowReferences: null }, + { threadId: null, text: 'Hi', workflowReferences: [{ id: 'wf' }] }, + { threadId: null, text: 'Hi', workflowReferences: ['wf'] } + ])( + 'discards a malformed saved draft %j and keeps the composer usable', + async (saved) => { + const key = StorageKeys.agentComposerDraft(getWorkspaceId()) + localStorage.setItem(key, JSON.stringify(saved)) + + const store = useAgentComposerStore() + expect(() => store.trackDraftThread(null)).not.toThrow() + expect(store.hasDraft).toBe(false) + await nextTick() + expect(localStorage.getItem(key)).toBeNull() + + store.setText('Make it blue') + expect(store.prompt).toEqual({ text: 'Make it blue', references: [] }) + } + ) + it('forgets the draft once it is sent or cleared', async () => { const sent = useAgentComposerStore() sent.trackDraftThread(null) diff --git a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts index 89512618540..57cb409912f 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts @@ -8,6 +8,7 @@ import { shallowRef, watch } from 'vue' +import { z } from 'zod' import { getWorkspaceId, @@ -57,18 +58,18 @@ function composerReferencePosition(reference: ComposerReference): string { return `${composerReferenceKey(reference)}@${reference.textOffset}` } -/** - * The unsent draft as written to localStorage, tagged with the chat it - * belongs to (`null` for a chat with no thread yet). Only text and workflow - * references are kept: node references are scoped to a tab instance, skill - * references to the loaded skill-pack scope, and attachments to in-memory - * blobs, none of which survive a page load. - */ -interface SavedDraft { - threadId: string | null - text: string - workflowReferences: WorkflowReference[] -} +const zSavedDraft = z.object({ + threadId: z.string().nullable(), + text: z.string(), + workflowReferences: z.array( + z.object({ + id: z.string(), + name: z.string(), + unavailable: z.boolean().optional(), + textOffset: z.number() + }) + ) +}) interface SubmittedDraft { attachments: ComposerAttachment[] @@ -631,10 +632,7 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { releaseUnusedAssets() } - // PM-2002: the unsent draft survives a page refresh. Nothing is written - // until the panel reports which chat is open, so the empty composer of a - // freshly loaded page cannot overwrite the draft before it is restored. - const savedDraft = useLocalStorage( + const savedDraft = useLocalStorage( StorageKeys.agentComposerDraft(getWorkspaceId()), null, { serializer: StorageSerializers.object } @@ -650,23 +648,17 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { : null }) - /** - * Tells the composer which chat is open. The first call after a page load - * restores the saved draft when it was written in that same chat; later - * calls only retag what is saved. - */ function trackDraftThread(threadId: string | null): void { - const saved = savedDraft.value - if ( - draftThreadId.value === undefined && - saved?.threadId === threadId && - !hasDraft.value - ) - replaceDraft({ - text: saved.text, - workflowReferences: saved.workflowReferences, - attachments: [] - }) + if (draftThreadId.value === undefined) { + const saved = zSavedDraft.nullable().safeParse(savedDraft.value) + if (!saved.success) savedDraft.value = null + else if (saved.data?.threadId === threadId && !hasDraft.value) + replaceDraft({ + text: saved.data.text, + workflowReferences: saved.data.workflowReferences, + attachments: [] + }) + } draftThreadId.value = threadId }