From 73262a0cfc99ff7ef24a0e62572c788c99506512 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Tue, 3 Nov 2026 09:24:45 +0000 Subject: [PATCH 1/2] fix(agent): start a new chat with an empty composer (#21588) New Chat now starts with an empty composer. Before, it retargeted to the tab on screen (PM-1321) but kept the unsent draft, so text written about workflow A followed the user into a new chat on workflow B. **Design call for review:** this reverses one part of #18693, which deliberately carried the draft (and its node references, with their original target) through New Chat. PM-2251 and the original PM-1321 acceptance both ask for an empty composer, so the two cannot both hold. Needs a yes/no from the agent UI owner before merge. Fixes PM-2251
Full context - `agentComposerStore.clearDraft()` resets text, references (workflow, node, asset, skill), attachments, insertion point and prompt origin. - `AgentPanelRoot.onNewChat()` calls it instead of only clearing workflow references, and always resumes following the visible workflow. The old `retainWorkflowTarget()` branch existed only for node references carried by the draft; none survive now. | Case | Before | After | | --- | --- | --- | | Unsent text, switch tab, New Chat | text kept, now aimed at the new tab | empty composer, follows the new tab | | Unsent text with node references, New Chat | draft and chips kept, target stays on the original workflow | empty composer, follows the visible tab | | Fresh chat, switch tabs (no New Chat) | draft kept while following | unchanged | | Switch chats via history | draft kept | unchanged (not in PM-2251's acceptance; flagged there as worth a separate look) | Three `AgentPanelRoot.test.ts` cases asserted the carry-through; they now assert the empty composer. The node-reference case now asserts the chip is dropped and the target follows the tab on screen. - Browser harness, `agentNewChatTargetWorkflow.spec.ts` PM-1322 case extended to leave an unsent draft before switching tabs: - parent `606fbc634c`: fails at `expect(composer).toHaveText('')`, received `Only edit workflow A`; PM-1415 control passes - this branch: 2/2 pass. The spec attaches before/after New Chat screenshots to the CI report; after shows the placeholder and target `Unsaved Workflow (2)`. - Adjacent agent specs that press New Chat (10 files, 21 tests): all pass locally on cloud distribution. - `vitest run src/workbench/extensions/agent/`: 178 files, 4037 passed. - `pnpm typecheck`, eslint, oxfmt, pre-push knip/fallow: clean. - PM-1321 / PM-1322: same QA case; target half fixed in #18196. - PM-2002 (draft lost on refresh) pulls the other way on the same state. This PR does not add draft persistence.
(cherry picked from commit 5d8e08b8d0ffc56a3751eddef9d9f1319d399a56) --- .../tests/agent/agentAttachmentUpload.spec.ts | 60 ++++++++++ .../agent/agentNewChatTargetWorkflow.spec.ts | 4 +- ...rkflow-target-on-send-or-node-reference.md | 11 +- .../extensions/agent/AgentPanelRoot.test.ts | 108 ++++++++++++++---- .../extensions/agent/AgentPanelRoot.vue | 20 +++- .../agent/components/agent/AgentPanel.test.ts | 4 +- .../agent/components/agent/AgentPanel.vue | 10 +- .../agent/stores/agent/agentComposerStore.ts | 13 ++- 8 files changed, 192 insertions(+), 38 deletions(-) diff --git a/browser_tests/tests/agent/agentAttachmentUpload.spec.ts b/browser_tests/tests/agent/agentAttachmentUpload.spec.ts index 30aee056b48..b144b595986 100644 --- a/browser_tests/tests/agent/agentAttachmentUpload.spec.ts +++ b/browser_tests/tests/agent/agentAttachmentUpload.spec.ts @@ -8,6 +8,66 @@ import { assetPath } from '@e2e/fixtures/utils/paths' import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' test.describe('Agent attachment cancellation', { tag: '@cloud' }, () => { + test( + 'starting a new chat releases upload capacity for the next draft', + { + annotation: { + type: 'regression', + description: + 'https://github.com/Comfy-Org/ComfyUI_frontend/pull/21588#discussion_r4378869451' + } + }, + async ({ comfyPage, agentPanel }) => { + const page = comfyPage.page + let releaseUploads = () => {} + const uploadsHeld = new Promise((resolve) => { + releaseUploads = resolve + }) + const uploadsSettled = new Set>() + let uploadCount = 0 + function holdUpload(route: Route) { + uploadCount += 1 + const uploadSettled = uploadsHeld.then(() => route.abort()) + uploadsSettled.add(uploadSettled) + return uploadSettled + } + await page.route('**/api/upload/image', holdUpload) + + try { + await agentPanel.open() + await agentPanel.fileInput.setInputFiles( + Array.from({ length: 3 }, (_, index) => ({ + name: `old-draft-${index}.png`, + mimeType: 'image/png', + buffer: Buffer.from(`old draft ${index}`) + })) + ) + await expect.poll(() => uploadCount).toBe(3) + await expect(agentPanel.attachmentChips).toHaveCount(3) + + await agentPanel.root + .getByRole('button', { + name: enMessages.agent.newChat, + exact: true + }) + .click() + await expect(agentPanel.attachmentChips).toHaveCount(0) + await agentPanel.fileInput.setInputFiles({ + name: 'new-draft.png', + mimeType: 'image/png', + buffer: Buffer.from('new draft') + }) + + await expect(agentPanel.attachmentChip('new-draft.png')).toBeVisible() + await expect.poll(() => uploadCount).toBe(4) + } finally { + releaseUploads() + await Promise.all(uploadsSettled) + await page.unroute('**/api/upload/image', holdUpload) + } + } + ) + test('closing the panel removes a pending upload and preserves a sendable draft', async ({ comfyPage, agentPanel diff --git a/browser_tests/tests/agent/agentNewChatTargetWorkflow.spec.ts b/browser_tests/tests/agent/agentNewChatTargetWorkflow.spec.ts index 0ae12bc3848..aa76481d445 100644 --- a/browser_tests/tests/agent/agentNewChatTargetWorkflow.spec.ts +++ b/browser_tests/tests/agent/agentNewChatTargetWorkflow.spec.ts @@ -22,7 +22,7 @@ test.describe( 'New chat targets the workflow tab on screen', { tag: ['@cloud', '@agent'] }, () => { - test('PM-1322: retargets to a tab the user switched to', async ({ + test('PM-1322 / PM-2251: retargets to a tab the user switched to and starts with an empty composer', async ({ page, workflowSelection }, testInfo) => { @@ -48,7 +48,7 @@ test.describe( await initialComposer.press('Enter') await expect.poll(() => workflowSelection.postedMessages.length).toBe(1) await expect(initialComposer).toHaveText('Start in this workflow') - await initialComposer.fill('') + await initialComposer.fill('Only edit workflow A') // Open a second workflow tab (B), then switch back to A so B is just // another open tab rather than the newest/active one. diff --git a/docs/adr/AGENT-TARGET-0037-commit-workflow-target-on-send-or-node-reference.md b/docs/adr/AGENT-TARGET-0037-commit-workflow-target-on-send-or-node-reference.md index 9af4b4b10bd..17cd03df836 100644 --- a/docs/adr/AGENT-TARGET-0037-commit-workflow-target-on-send-or-node-reference.md +++ b/docs/adr/AGENT-TARGET-0037-commit-workflow-target-on-send-or-node-reference.md @@ -25,8 +25,11 @@ retain the target before further tab navigation, including a picker choice of the already-visible workflow. Send retains before asynchronous preparation; a picker retains only after successful selection. Failed, cancelled or superseded picker operations do not commit. Success, failure, retry and removing -references do not resume following. Explicit target selection remains available; New Chat starts -following again unless its retained draft still contains node references. +references do not resume following. Explicit target selection remains available. New Chat +clears the unsent draft (text, attachments and staged node references), cancels pending uploads +and starts following again, so a new chat never carries input aimed at another workflow +(amended 2026-11-01 for PM-2251). Leaving a failed history selection with Back keeps the unsent +text and follows the visible workflow. The panel store owns a single target-state union so it survives component remounts. In `following`, the target derives directly from the editor's active @@ -55,6 +58,8 @@ workflow is already known. Ordinary draft text does not commit a target. ### Positive - Fresh chat entry and New Chat use the same default without an extra save. +- New Chat always starts empty; references staged for the previous chat are dropped rather + than carried to a workflow the user may have left. - Explicit choices, failed sends and node references preserve the target. - Mismatch feedback can reveal a different target without changing it. @@ -64,6 +69,8 @@ workflow is already known. Ordinary draft text does not commit a target. length and thread ID cannot replace the explicit policy. - Existing tests that treat manual first selection as mandatory must instead distinguish fresh following from a target committed by user input. +- A user who wanted to reuse staged references or text in a new chat must restage them; + the unchanged canvas selection can be restaged immediately. - Explicit retargeting keeps the existing node-scope cleanup behavior; this decision only changes passive tab following. diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 03518af2619..40c2e0710fc 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -9414,7 +9414,7 @@ describe('AgentPanelRoot workflow binding', () => { } ) - it('resumes following on New Chat after an explicit pick while preserving draft text', async () => { + it('resumes following on New Chat after an explicit pick and starts with an empty composer', async () => { const { target, references: [other] @@ -9444,7 +9444,7 @@ describe('AgentPanelRoot workflow binding', () => { workflowStore.activeWorkflow = other await nextTick() expect(useAgentPanelStore().selectedWorkflow?.path).toBe(other.path) - expect(screen.getByRole('textbox')).toHaveTextContent('keep this draft') + expect(screen.getByRole('textbox')).toHaveTextContent('') }) it('retains the first Send target through failure, reopen and retry until New Chat', async () => { @@ -10049,6 +10049,46 @@ describe('AgentPanelRoot workflow binding', () => { expect(workflowStore.activeWorkflow.path).toBe(other.path) }) + it('preserves a new unsent draft when Back leaves a failed history selection', async () => { + makeTab('wf-42') + mockMessagesEndpoint( + 'wf-42', + [{ id: 'wf-42', name: 'current' }], + [ + agentThread({ + id: 'th-1', + title: 'Previous chat', + last_message_at: '2026-09-25T00:00:00Z' + }) + ] + ) + const request = vi.mocked(fetch).getMockImplementation() + assert.exists(request) + vi.mocked(fetch).mockImplementation((input, init) => + String(input).includes('/messages') && init?.method !== 'POST' + ? Promise.resolve(json(500, {})) + : request(input, init) + ) + renderWithSelectedTarget() + await userEvent.click(screen.getByRole('textbox')) + await userEvent.paste('Keep my new draft') + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click( + await screen.findByRole('button', { name: 'Previous chat' }) + ) + await screen.findByRole('alert') + + await userEvent.click( + screen.getByRole('button', { name: 'Back to previous chat' }) + ) + + expect(screen.getByRole('textbox')).toHaveTextContent('Keep my new draft') + }) + it('restores Current after remounting an interrupted return instead of reusing stale messages', async () => { makeTab('wf-42') mockMessagesEndpoint( @@ -15491,33 +15531,35 @@ describe('AgentPanelRoot workflow binding', () => { name: i18n.global.t('agent.switchWorkflow') }) ).toHaveTextContent('other') - expect(screen.getByRole('textbox')).toHaveTextContent('Keep this draft') + expect(screen.getByRole('textbox')).toHaveTextContent('') workflowStore.activeWorkflow = target await nextTick() expect(useAgentPanelStore().selectedWorkflow?.path).toBe(target.path) + await userEvent.click(screen.getByRole('textbox')) + await userEvent.paste('Fresh prompt') await userEvent.click(screen.getByRole('button', { name: 'Send' })) await vi.waitFor(() => expect(bodies).toHaveLength(1)) expect(bodies[0]).toMatchObject({ - content: 'Keep this draft', + content: 'Fresh prompt', workflow_id: 'wf-42' }) expect(bodies[0]).not.toHaveProperty('selection') }) it.for(['current', 'other'] as const)( - 'preserves carried node references through New Chat while viewing $0', + 'drops staged node references on New Chat while viewing $0', async (visibleTab) => { const tabs = { current: makeTab('wf-42'), other: addTab('workflows/other.json') } - const bodies = mockMessagesEndpoint('wf-42') + mockMessagesEndpoint('wf-42') setupNodeSelectionCanvas() render(AgentPanelRoot, { global: { plugins: [i18n] } }) useAgentPanelStore().isOpen = true await openMentionPicker() await userEvent.click(await screen.findByText('KSampler')) - await userEvent.paste('Keep these nodes') + await userEvent.paste('Edit these nodes') workflowStore.activeWorkflow = tabs[visibleTab] await nextTick() @@ -15527,24 +15569,48 @@ describe('AgentPanelRoot workflow binding', () => { screen.getByRole('button', { name: i18n.global.t('agent.switchWorkflow') }) - ).toHaveTextContent('current') - expect(screen.getByRole('textbox')).toHaveTextContent('Keep these nodes') + ).toHaveTextContent(visibleTab) + expect(screen.getByRole('textbox')).toHaveTextContent('') expect( - screen.getByRole('button', { name: 'Remove KSampler #12 reference' }) - ).toBeVisible() - - workflowStore.activeWorkflow = addTab('workflows/third.json') - await nextTick() - await userEvent.click(screen.getByRole('button', { name: 'Send' })) - await vi.waitFor(() => expect(bodies).toHaveLength(1)) - expect(bodies[0]).toMatchObject({ - content: '@[Node: KSampler #12] Keep these nodes', - workflow_id: 'wf-42', - selection: { node_ids: ['12'], workflow_id: 'wf-42' } - }) + screen.queryByRole('button', { name: 'Remove KSampler #12 reference' }) + ).toBeNull() } ) + it('restages the unchanged canvas selection in a new chat', async () => { + makeTab('wf-42') + mockMessagesEndpoint('wf-42') + const state = setupNodeSelectionCanvas() + renderWithSelectedTarget() + useAgentPanelStore().isOpen = true + + await enterNodeSelectionMode() + state.selectedItems.add(state.nodes[0]) + syncFakeSelection() + await nextTick() + expect( + screen.getByRole('button', { + name: /Remove VAE Decode #\d+ reference/ + }) + ).toBeVisible() + + await userEvent.click(screen.getByRole('button', { name: 'New chat' })) + expect( + screen.queryByRole('button', { + name: /Remove VAE Decode #\d+ reference/ + }) + ).toBeNull() + + state.selectedItems.add(state.nodes[0]) + syncFakeSelection() + await enterNodeSelectionMode() + expect( + screen.getByRole('button', { + name: /Remove VAE Decode #\d+ reference/ + }) + ).toBeVisible() + }) + it('clears old node references when selecting another workflow with the same node id', async () => { const { references: [other] diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index a3ca938cfaa..e0e484f4c8d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -2042,17 +2042,25 @@ function onDeleteHistory(id: string): void { if (isCurrent) onNewChat('history_delete') } -function onNewChat(source?: 'new_chat_button' | 'history_delete'): void { +function onNewChat( + source: 'new_chat_button' | 'history_back' | 'history_delete' +): void { retireFollow() + if (source === 'history_back') { + newChat() + agentPanelStore.startFollowingVisibleWorkflow() + return + } provisionalTitle.value = undefined composerStore.invalidateSubmission() cancelWorkflowSelection() canvasStore.stopNodePicking() - composerStore.setWorkflowReferences([]) - composerStore.resetPromptHistory() + attachment.cancelAllUploads() + replaceSelectionTags([]) + dismissedSelectionSignature.value = null + composerStore.clearDraft() newChat(source) - if (selectionTags.value.length) agentPanelStore.retainWorkflowTarget() - else agentPanelStore.startFollowingVisibleWorkflow() + agentPanelStore.startFollowingVisibleWorkflow() } const fileInput = ref() @@ -2433,7 +2441,7 @@ onMounted(() => agentPanelRenderStore.reach('drawn')) @paywall-action="onPaywallAction" @standing-paywall-shown="onStandingPaywallShown" @retry-sync="retrySubscription" - @new-chat="onNewChat('new_chat_button')" + @new-chat="onNewChat" @start-tour="restartCoach" @toggle-size="agentPanelStore.toggleMaximize()" @close="onClosePanel" diff --git a/src/workbench/extensions/agent/components/agent/AgentPanel.test.ts b/src/workbench/extensions/agent/components/agent/AgentPanel.test.ts index bc0f2af0917..1058662bd61 100644 --- a/src/workbench/extensions/agent/components/agent/AgentPanel.test.ts +++ b/src/workbench/extensions/agent/components/agent/AgentPanel.test.ts @@ -491,7 +491,7 @@ describe('AgentPanel', () => { await pending await nextTick() - expect(emitted().newChat).toEqual([[]]) + expect(emitted().newChat).toEqual([['new_chat_button']]) expect(screen.queryByRole('heading', { name: 'Chat history' })).toBeNull() expect(screen.queryByRole('alert')).toBeNull() expect( @@ -559,7 +559,7 @@ describe('AgentPanel', () => { await nextTick() expect(select.mock.calls.map(([id]) => id)).toEqual(['first']) - expect(emitted().newChat).toEqual([[]]) + expect(emitted().newChat).toEqual([['history_back']]) expect( screen.getByRole('button', { name: 'Show chat history' }) ).toBeVisible() diff --git a/src/workbench/extensions/agent/components/agent/AgentPanel.vue b/src/workbench/extensions/agent/components/agent/AgentPanel.vue index c337d7b4034..c9889626c28 100644 --- a/src/workbench/extensions/agent/components/agent/AgentPanel.vue +++ b/src/workbench/extensions/agent/components/agent/AgentPanel.vue @@ -147,7 +147,7 @@ const emit = defineEmits<{ feedback: [turnId: string, vote: 'up' | 'down' | null] paywallAction: [action: AgentPaywallAction, surface: AgentPaywallSurface] standingPaywallShown: [] - newChat: [] + newChat: [source: 'new_chat_button' | 'history_back'] startTour: [] toggleSize: [] close: [] @@ -216,9 +216,11 @@ watch( { immediate: true } ) -function onNewChat(): void { +function onNewChat( + source: 'new_chat_button' | 'history_back' = 'new_chat_button' +): void { view.value = { screen: 'chat' } - emit('newChat') + emit('newChat', source) } function onOpenHistory(): void { view.value = { @@ -262,7 +264,7 @@ function onBackFromHistory(): void { (view.value.selection.status === 'idle' || currentChatReady) ) view.value = { screen: 'chat' } - else if (view.value.previousThreadId === null) onNewChat() + else if (view.value.previousThreadId === null) onNewChat('history_back') else void openHistoryChat(view.value.previousThreadId, 'leave') } diff --git a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts index ccfdd12897e..da5dd04a1b2 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts @@ -551,6 +551,16 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { releaseUnusedAssets() } + function clearDraft(): void { + resetPromptHistory() + promptOrigin.value = 'typed' + starterPrompt.value = null + attachmentIds.value = [] + updateDraft({ text: '', references: [] }) + insertionPoint.value = { textOffset: 0, referenceIndex: 0 } + releaseUnusedAssets() + } + return { draftState, draft, @@ -588,6 +598,7 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { startSubmission, settleSubmission, takeFailedSubmission, - invalidateSubmission + invalidateSubmission, + clearDraft } }) From 27a91219a454a76e0310ea462e1f385b13f029b6 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Tue, 3 Nov 2026 18:00:12 +0000 Subject: [PATCH 2/2] fix(agent): keep an unsent chat draft across a page refresh (#22821) Refreshing the page no longer wipes an unsent Agent chat draft. The draft comes back in the same chat after a reload; New Chat and a successful send still clear it. - Restored: typed text and workflow `@` mentions. - Not restored: attachments (in-memory blobs, they would come back as broken thumbnails), node mentions (tied to a tab instance), and skill mentions (tied to the skill-pack scope loaded at runtime). They are dropped; the text stays. - Keeps #21588: `clearDraft()` on New Chat clears the saved draft, so it does not come back after a reload. Fixes PM-2002 - New black-box spec `browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts`: type a draft, reload, the composer shows it; New Chat, reload, the composer is empty with its placeholder. **Red on `main`** (`Expected: "Make the background a sunset over the ocean"`, `Received: ""`), **green on this branch**. - A version that kept the draft after New Chat fails the spec's second step. - Unit tests in `agentComposerStore.test.ts` cover what the browser case cannot reach: no restore into a different chat, node mentions and attachments dropped, the saved draft forgotten after send and after `clearDraft()`, and a malformed saved draft discarded without breaking the composer. Each one fails against a specific wrong implementation. - Also ran `agentNewChatTargetWorkflow.spec.ts` and `agentChatRefreshPersistence.spec.ts`: green. `pnpm typecheck`, `typecheck:browser` and lint are clean.
Full context for agent readers - `agentComposerStore` keeps the draft in `localStorage` under `StorageKeys.agentComposerDraft(workspaceId)` as `{ threadId, text, workflowReferences }`. It writes `null` once the draft is empty, so a send (`startSubmission`) or New Chat (`clearDraft`) removes it. - Nothing is written until `AgentPanelRoot` reports the open chat through `trackDraftThread(threadId)`. That call is registered right after `useAgentSession.start()`, which has already moved `threadId` to the chat being restored (`Comfy.Agent.ThreadId:*`). This prevents the empty composer on a fresh page load from overwriting the draft before it is restored. - The first `trackDraftThread` call restores the saved draft only if its `threadId` matches the open chat (a new chat with no thread matches `null`) and the composer is empty. Later calls retag the saved draft to whichever chat the composer is in, so it matches what the user sees in memory. - The restore goes through the existing `replaceDraft()` / `snapshotReferences()` path with `attachments: []`. - The saved value is parsed with a zod schema before restoring. A wrong shape (for example `null` text) is removed from localStorage and nothing is restored, so a bad entry cannot throw on every panel start. - `clearAllWorkspaceStorage()` now also clears `Comfy.Agent.ComposerDraft:*`, matching the other per-workspace Agent keys. `src/platform/workflow/persistence/base/storageKeys.ts` and `storageIO.ts` are owned only by `@Comfy-Org/comfy_frontend_devs`, so the program-owned route does not apply. Assigned to @dante01yoon. - A draft that is mid-send when the page reloads is not restored. The send already cleared it, and a failed send restores it in memory only. - If the restored thread fails to hydrate and the session falls back to a new chat, the draft stays in the composer (retagged to the new chat). This matches how the in-memory draft already behaves when you switch chats.
(cherry picked from commit 70046f12e23c6f0a07de7af2327e00d8581c5510) --- .../agentComposerDraftSurvivesReload.spec.ts | 59 ++++++++++++ .../workflow/persistence/base/storageIO.ts | 3 +- .../workflow/persistence/base/storageKeys.ts | 7 +- .../extensions/agent/AgentPanelRoot.vue | 4 + .../stores/agent/agentComposerStore.test.ts | 95 +++++++++++++++++++ .../agent/stores/agent/agentComposerStore.ts | 63 +++++++++++- 6 files changed, 226 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..5b19d26f906 --- /dev/null +++ b/browser_tests/tests/agent/agentComposerDraftSurvivesReload.spec.ts @@ -0,0 +1,59 @@ +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' + +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 8c4ca4d49bf..4df1b2ca9c4 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -592,7 +592,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 e0e484f4c8d..2fee4a6be06 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -2094,6 +2094,10 @@ start({ (agentPanelStore.view.selection.status === 'idle' && threadId.value === agentPanelStore.view.previousThreadId) }) +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..ebc1b5993b8 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts @@ -1,5 +1,11 @@ +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' @@ -380,6 +386,95 @@ describe('composer draft presence', () => { }) }) +describe('composer draft persistence (PM-2002)', () => { + 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.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) + 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 da5dd04a1b2..cfd649a7f8a 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts @@ -1,6 +1,19 @@ +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 { z } from 'zod' + +import { + getWorkspaceId, + StorageKeys +} from '@/platform/workflow/persistence/base/storageKeys' import { getMediaTypeFromFilename } from '@/utils/formatUtil' import type { AgentInputMethod } from '@/platform/telemetry/types' @@ -41,6 +54,19 @@ function resetTextWhenReferencesCleared( return references.length === 0 && text.trim() === '' ? '' : text } +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[] nodes: SelectedNode[] @@ -561,6 +587,36 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { releaseUnusedAssets() } + 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 + }) + + function trackDraftThread(threadId: string | null): void { + 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 + } + return { draftState, draft, @@ -599,6 +655,7 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { settleSubmission, takeFailedSubmission, invalidateSubmission, - clearDraft + clearDraft, + trackDraftThread } })