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/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/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/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.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..2fee4a6be06 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() @@ -2086,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' @@ -2433,7 +2445,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.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 ccfdd12897e..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[] @@ -551,6 +577,46 @@ 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() + } + + 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, @@ -588,6 +654,8 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { startSubmission, settleSubmission, takeFailedSubmission, - invalidateSubmission + invalidateSubmission, + clearDraft, + trackDraftThread } })