From b2c882c8de221af6c3eaa424ca150711309701ff Mon Sep 17 00:00:00 2001 From: DarkSky <25152247+darkskygit@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:46:48 +0800 Subject: [PATCH] fix(core): retain chat drafts until runtime accepts the send (#15796) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix #15708 #### PR Dependency Tree * **PR #15796** 👈 This tree was auto-generated by [Charcoal](https://github.com/danerwilliams/charcoal) ## Summary by CodeRabbit * **Bug Fixes** * Draft text and attachments are preserved when a message cannot be sent, including when preparation fails or another send is in progress. * After a send is accepted, submitted text and context are cleared while edits and attachments made during preparation are retained. * Draft updates are saved in order, and later edits continue to be saved even if an earlier save is delayed or fails. * Sending now waits for the chat to be ready, helping prevent input from being lost when a send cannot proceed. --- .../ai-chat-input/ai-chat-input.spec.ts | 343 ++++++++++++++++++ .../components/ai-chat-input/ai-chat-input.ts | 86 +++-- .../src/blocksuite/ai/runtime/chat/actions.ts | 2 +- .../ai/runtime/chat/runtime.spec.ts | 45 ++- .../src/blocksuite/ai/runtime/chat/runtime.ts | 13 +- .../modules/ai-button/services/ai-draft.ts | 33 +- 6 files changed, 476 insertions(+), 46 deletions(-) create mode 100644 packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.spec.ts diff --git a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.spec.ts b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.spec.ts new file mode 100644 index 0000000000..4c9e8fa295 --- /dev/null +++ b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.spec.ts @@ -0,0 +1,343 @@ +/** + * @vitest-environment happy-dom + */ +import { signal } from '@preact/signals-core'; +import { Framework, MemoryMemento } from '@toeverything/infra'; +import { afterEach, expect, test, vi } from 'vitest'; + +import { + type AIDraftGlobal, + AIDraftService, +} from '../../../../modules/ai-button/services/ai-draft'; +import { + CacheStorage, + GlobalState, +} from '../../../../modules/storage/providers/global'; +import { GlobalStateService } from '../../../../modules/storage/services/global'; +import { AIChatRuntime, DocAIChatSessionStrategy } from '../../runtime/chat'; +import type { AIRequestService } from '../../runtime/request'; +import { AIChatContent } from '../ai-chat-content/ai-chat-content'; +import { AIChatInput } from './ai-chat-input'; + +vi.unstubAllGlobals(); +customElements.define('ai-chat-input', AIChatInput); +customElements.define('ai-chat-content', AIChatContent); + +function createInput() { + const input = new AIChatInput(); + const textarea = document.createElement('textarea'); + textarea.value = 'pending question'; + input.isInputEmpty = false; + Object.defineProperty(input, 'textarea', { value: textarea }); + input.chatContextValue = { + images: [new File(['image'], 'image.png', { type: 'image/png' })], + quote: 'selected quote', + markdown: 'selected markdown', + } as AIChatInput['chatContextValue']; + const globalState = new MemoryMemento(); + const files = new MemoryMemento(); + const cache: CacheStorage = { + get: async (key: string) => files.get(key), + set: async (key, value) => { + files.set(key, value); + }, + del: async key => { + files.del(key); + }, + clear: async () => { + files.clear(); + }, + keys: async () => files.keys(), + watch: (key: string) => files.watch(key), + }; + const image = input.chatContextValue.images[0]; + const cacheKey = 'AIDraftFile:' + image.name + image.size; + files.set(cacheKey, new TextEncoder().encode('image').buffer); + globalState.set('AIDrafts', { + input: textarea.value, + quote: 'selected quote', + markdown: 'selected markdown', + images: [ + { name: image.name, size: image.size, type: image.type, cacheKey }, + ], + }); + const framework = new Framework(); + framework + .impl(GlobalState, globalState) + .impl(CacheStorage, cache) + .service(GlobalStateService, [GlobalState]) + .service(AIDraftService, [GlobalStateService, CacheStorage]); + input.aiDraftService = framework.provider().get(AIDraftService); + const setDraft = vi.spyOn(input.aiDraftService, 'setDraft'); + const content = new AIChatContent(); + content.aiDraftService = input.aiDraftService; + content.chatContextValue = { + ...content.chatContextValue, + ...input.chatContextValue, + }; + input.updateContext = change => { + content['updateContext'](change); + input.chatContextValue = content.chatContextValue; + }; + const settleDrafts = async () => { + for (const result of setDraft.mock.results) { + if (result.type === 'return') await result.value; + } + }; + input.chips = []; + input.reasoningConfig = { enabled: signal(false), setEnabled: vi.fn() }; + input.aiToolsConfigService = { + config: { value: {} }, + } as AIChatInput['aiToolsConfigService']; + input.aiModelService = { + modelId: { value: 'test-model' }, + } as AIChatInput['aiModelService']; + + let finish!: () => void; + const finished = new Promise(resolve => { + finish = resolve; + }); + const request = { + createSessionWithHistory: vi.fn().mockResolvedValue({ + sessionId: 'session-1', + docId: 'doc-1', + messages: [], + }), + executeAction: vi.fn().mockResolvedValue({ + async *[Symbol.asyncIterator]() { + await finished; + yield 'answer'; + }, + }), + getActiveEditorContext: vi.fn(), + histories: { ids: vi.fn().mockResolvedValue([]) }, + } as unknown as AIRequestService; + input.runtime = new AIChatRuntime({ + scope: { kind: 'doc', workspaceId: 'workspace-1', docId: 'doc-1' }, + request, + strategy: new DocAIChatSessionStrategy(), + }); + const dispatch = vi.spyOn(input.runtime, 'dispatch'); + return { + input, + textarea, + setDraft, + dispatch, + finish, + globalState, + cache, + settleDrafts, + }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +test('keeps input and attachments on preparation failure and clears them on accepted retry before streaming finishes', async () => { + const { + input, + textarea, + setDraft, + dispatch, + finish, + globalState, + settleDrafts, + } = createInput(); + const originalImages = input.chatContextValue.images; + vi.spyOn(FileReader.prototype, 'readAsDataURL').mockImplementationOnce( + function (this: FileReader) { + this.dispatchEvent(new ProgressEvent('error')); + } + ); + + await expect( + input['_onTextareaSend'](new MouseEvent('click')) + ).rejects.toBeDefined(); + expect(textarea.value).toBe('pending question'); + expect(input.isInputEmpty).toBe(false); + expect(setDraft).not.toHaveBeenCalled(); + expect(input.chatContextValue.images).toEqual(originalImages); + expect(input.chatContextValue.quote).toBe('selected quote'); + expect(dispatch).not.toHaveBeenCalled(); + + const completion = input['_onTextareaSend'](new MouseEvent('click')); + await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce()); + expect(textarea.value).toBe(''); + expect(input.isInputEmpty).toBe(true); + expect(setDraft).toHaveBeenCalledWith({ input: '' }); + expect(input.chatContextValue.images).toEqual([]); + expect(input.chatContextValue.quote).toBe(''); + expect(input.runtime?.getSnapshot().status).toBe('loading'); + await settleDrafts(); + expect(globalState.get('AIDrafts')).toMatchObject({ + input: '', + images: [], + quote: '', + markdown: '', + }); + finish(); + await completion; + expect(input.runtime?.getSnapshot().status).toBe('success'); +}); + +test('preserves edits and newly attached images while preparing and ignores duplicate submission', async () => { + const { + input, + textarea, + setDraft, + dispatch, + finish, + globalState, + settleDrafts, + } = createInput(); + const readers: FileReader[] = []; + vi.spyOn(FileReader.prototype, 'readAsDataURL').mockImplementationOnce( + function (this: FileReader) { + readers.push(this); + } + ); + const sentImage = input.chatContextValue.images[0]; + const completion = input['_onTextareaSend'](new MouseEvent('click')); + await input['_onTextareaSend'](new MouseEvent('click')); + expect(dispatch).not.toHaveBeenCalled(); + + textarea.value = 'next question'; + await input['_handleInput'](); + const nextImage = new File(['new image'], 'next.png', { type: 'image/png' }); + input.updateContext({ + images: [sentImage, nextImage], + quote: 'new quote', + markdown: 'new markdown', + }); + const reader = readers[0]; + Object.defineProperty(reader, 'result', { + value: 'data:image/png;base64,aW1hZ2U=', + }); + reader.dispatchEvent(new ProgressEvent('load')); + await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce()); + + expect(textarea.value).toBe('next question'); + expect(setDraft).not.toHaveBeenCalledWith({ input: '' }); + expect(input.chatContextValue.images).toEqual([nextImage]); + expect(input.chatContextValue.quote).toBe('new quote'); + expect(input.chatContextValue.markdown).toBe('new markdown'); + await settleDrafts(); + expect(globalState.get('AIDrafts')).toMatchObject({ + input: 'next question', + images: [{ name: 'next.png' }], + quote: 'new quote', + markdown: 'new markdown', + }); + expect(dispatch.mock.calls[0][0]).toMatchObject({ + input: 'pending question', + attachments: [sentImage], + }); + finish(); + await completion; +}); + +test.each(['unavailable', 'busy'] as const)( + 'keeps the draft when the runtime is %s', + async mode => { + const { input, textarea, setDraft, finish, settleDrafts } = createInput(); + let competingSend: Promise | undefined; + input.updateContext({ images: [] }); + await settleDrafts(); + setDraft.mockClear(); + if (mode === 'unavailable') input.runtime = null; + if (mode === 'busy') { + competingSend = input.runtime!.dispatch({ + type: 'send', + input: 'another sender', + }); + } + await input['_onTextareaSend'](new MouseEvent('click')); + expect(textarea.value).toBe('pending question'); + expect(setDraft).not.toHaveBeenCalled(); + finish(); + await competingSend; + } +); + +test('keeps the draft when another sender occupies the runtime during preparation', async () => { + const { input, textarea, setDraft, finish } = createInput(); + const readers: FileReader[] = []; + vi.spyOn(FileReader.prototype, 'readAsDataURL').mockImplementationOnce( + function (this: FileReader) { + readers.push(this); + } + ); + const originalImages = input.chatContextValue.images; + const completion = input['_onTextareaSend'](new MouseEvent('click')); + const competingSend = input.runtime!.dispatch({ + type: 'send', + input: 'another sender', + }); + const reader = readers[0]; + Object.defineProperty(reader, 'result', { + value: 'data:image/png;base64,aW1hZ2U=', + }); + reader.dispatchEvent(new ProgressEvent('load')); + await completion; + expect(textarea.value).toBe('pending question'); + expect(input.chatContextValue.images).toEqual(originalImages); + expect(setDraft).not.toHaveBeenCalled(); + finish(); + await competingSend; +}); + +test.each(['deferred', 'failed'] as const)( + 'persists accepted cleanup and later edits in order with a %s file cache write', + async mode => { + const { + input, + textarea, + dispatch, + finish, + globalState, + cache, + settleDrafts, + } = createInput(); + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined); + let release!: () => void; + const held = new Promise(resolve => { + release = resolve; + }); + const del = cache.del.bind(cache); + vi.spyOn(cache, 'del').mockImplementationOnce(async key => { + if (mode === 'failed') throw new Error('cache unavailable'); + await held; + await del(key); + }); + const completion = input['_onTextareaSend'](new MouseEvent('click')); + await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce()); + expect(textarea.value).toBe(''); + textarea.value = 'next persisted question'; + const edit = input['_handleInput'](); + release(); + await edit; + if (mode === 'failed') { + await expect(settleDrafts()).rejects.toThrow('cache unavailable'); + expect(consoleError).toHaveBeenCalled(); + } else { + await settleDrafts(); + } + expect(await input.aiDraftService!.getDraft()).toMatchObject({ + input: 'next persisted question', + images: [], + quote: '', + markdown: '', + }); + expect(globalState.get('AIDrafts')).toMatchObject({ + input: 'next persisted question', + images: [], + quote: '', + markdown: '', + }); + finish(); + await completion; + } +); diff --git a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts index 2af3ed8667..e55b8e292b 100644 --- a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts +++ b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts @@ -25,7 +25,11 @@ import { styleMap } from 'lit/directives/style-map.js'; import { ChatAbortIcon } from '../../_common/icons'; import { AIAppEvents, type AISendParams } from '../../provider'; -import type { AIChatRuntime, AIChatSnapshot } from '../../runtime/chat'; +import type { + AIChatRuntime, + AIChatSendOptions, + AIChatSnapshot, +} from '../../runtime/chat'; import { reportResponse } from '../../utils/action-reporter'; import { readBlobAsURL } from '../../utils/image'; import type { SearchMenuConfig } from '../ai-chat-add-context'; @@ -363,6 +367,11 @@ export class AIChatInput extends SignalWatcher( @query('.chat-panel-input') accessor chatPanelInput!: HTMLDivElement; + @state() + private accessor isPreparing = false; + + private _inputVersion = 0; + private _dragEnterCounter = 0; private _internalDropCleanup: (() => void) | null = null; @@ -465,6 +474,7 @@ export class AIChatInput extends SignalWatcher( if (this.host !== host) return; if (input) { + this._inputVersion++; this.textarea.value = input; this.isInputEmpty = !this.textarea.value.trim(); } @@ -677,7 +687,7 @@ export class AIChatInput extends SignalWatcher( } private get isSendDisabled() { - if (this.isInputEmpty) { + if (this.isPreparing || this.isInputEmpty) { return true; } @@ -697,6 +707,7 @@ export class AIChatInput extends SignalWatcher( }; private readonly _handleInput = async () => { + this._inputVersion++; const { textarea } = this; const value = textarea.value.trim(); this.isInputEmpty = !value; @@ -823,34 +834,55 @@ export class AIChatInput extends SignalWatcher( const value = this.textarea.value.trim(); if (value.length === 0) return; - this.textarea.value = ''; - this.isInputEmpty = true; - this.textarea.style.height = 'unset'; - - if (this.aiDraftService) { - await this.aiDraftService.setDraft({ - input: '', - }); - } - await this.send(value); + const inputVersion = this._inputVersion; + await this.send(value, () => { + if (this._inputVersion !== inputVersion) return; + this.textarea.value = ''; + this.isInputEmpty = true; + this.textarea.style.height = 'unset'; + this.aiDraftService?.setDraft({ input: '' }).catch(console.error); + }); }; - send = async (text: string) => { - if (!this.runtime) return; - const { images } = this.chatContextValue; - const imageAttachments = await Promise.all( - images?.map(image => readBlobAsURL(image)) - ); - const contexts = await this._getMatchedContexts(); - const userInfo = AIAppEvents.userInfo.value; + send = async (text: string, onAccepted?: () => void) => { + const runtime = this.runtime; + if (!runtime || this.isPreparing || !runtime.getSnapshot().uiPolicy.canSend) + return; - this.updateContext({ - images: [], - quote: '', - markdown: '', - }); - await this.runtime.dispatch({ + const { quote, markdown } = this.chatContextValue; + const images = [...this.chatContextValue.images]; + this.isPreparing = true; + let imageAttachments: string[]; + let contexts: AIChatSendOptions['contexts']; + try { + imageAttachments = await Promise.all( + images.map(image => readBlobAsURL(image)) + ); + contexts = await this._getMatchedContexts(); + } finally { + this.isPreparing = false; + } + const userInfo = AIAppEvents.userInfo.value; + let accepted = false; + await runtime.dispatch({ type: 'send', + onAccepted: () => { + accepted = true; + this.updateContext({ + images: this.chatContextValue.images.filter( + image => !images.includes(image) + ), + quote: + this.chatContextValue.quote === quote + ? '' + : this.chatContextValue.quote, + markdown: + this.chatContextValue.markdown === markdown + ? '' + : this.chatContextValue.markdown, + }); + onAccepted?.(); + }, input: text, contexts, attachments: images, @@ -867,7 +899,7 @@ export class AIChatInput extends SignalWatcher( avatarUrl: userInfo?.avatarUrl ?? undefined, }, }); - this.onChatSuccess?.(); + if (accepted) this.onChatSuccess?.(); }; private async _getMatchedContexts() { diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts index 3ecdc842ae..8d34891dc9 100644 --- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts +++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts @@ -49,6 +49,6 @@ export type AIChatAction = | { type: 'removeScopeSelector'; item: AIChatScopeSelector } | { type: 'addFocusSelector'; item: AIChatScopeSelector } | { type: 'removeFocusSelector'; item: AIChatScopeSelector } - | ({ type: 'send' } & AIChatSendOptions) + | ({ type: 'send'; onAccepted?: () => void } & AIChatSendOptions) | { type: 'retry'; messageId: string } | { type: 'stop' }; diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.spec.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.spec.ts index 8663277e19..1ab5e5e20b 100644 --- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.spec.ts +++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.spec.ts @@ -148,11 +148,27 @@ describe('AIChatRuntime', () => { const runtime = createRuntime(request); await runtime.dispatch({ type: 'initialize' }); - const firstSend = runtime.dispatch({ type: 'send', input: 'hello' }); + const onAccepted = vi.fn(() => runtime.getSnapshot()); + const firstSend = runtime.dispatch({ + type: 'send', + input: 'hello', + onAccepted, + }); + expect(onAccepted).toHaveBeenCalledOnce(); + const acceptedSnapshot = onAccepted.mock.results[0]?.value; + expect(acceptedSnapshot?.messages[0]?.content).toBe('hello'); + expect(acceptedSnapshot?.status).toBe('loading'); await waitUntil(() => { expect(request.executeAction).toHaveBeenCalled(); }); - await runtime.dispatch({ type: 'send', input: 'again' }); + const rejected = vi.fn(); + await runtime.dispatch({ + type: 'send', + input: 'again', + onAccepted: rejected, + }); + expect(rejected).not.toHaveBeenCalled(); + expect(onAccepted).toHaveBeenCalledOnce(); release(); await firstSend; @@ -191,6 +207,31 @@ describe('AIChatRuntime', () => { consoleError.mockRestore(); }); + test('send completes when the acceptance callback throws', async () => { + const error = new Error('Draft cleanup failed'); + using consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}); + const request = createRequest(); + const runtime = createRuntime(request); + await runtime.dispatch({ type: 'initialize' }); + + await runtime.dispatch({ + type: 'send', + input: 'question', + onAccepted: () => { + throw error; + }, + }); + + expect(consoleError).toHaveBeenCalledWith(error); + expect(request.executeAction).toHaveBeenCalledOnce(); + expect(runtime.getSnapshot()).toMatchObject({ + status: 'success', + uiPolicy: { canSend: true }, + }); + }); + test('send binds an unbound session to the active doc after success', async () => { const unboundSession = session({ docId: null }); const boundSession = session({ docId: 'doc-1' }); diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts index 2329d29e43..ee474ec1cd 100644 --- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts +++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts @@ -99,7 +99,7 @@ export class AIChatRuntime { await this.togglePinActiveSession(); return; case 'send': - await this.send(action); + await this.send(action, false, action.onAccepted); return; case 'retry': await this.retry(); @@ -327,7 +327,11 @@ export class AIChatRuntime { } } - private async send(options: AIChatSendOptions, retryExisting = false) { + private async send( + options: AIChatSendOptions, + retryExisting = false, + onAccepted?: () => void + ) { const content = options.input || this.snapshot.composer.text; if (!content.trim() || !this.snapshot.uiPolicy.canSend) return; const seq = ++this.requestSeq; @@ -347,6 +351,11 @@ export class AIChatRuntime { this.createMessage('assistant', ''), ], }); + try { + onAccepted?.(); + } catch (error) { + console.error(error); + } try { const session = await this.ensureSession(); if (seq !== this.requestSeq) return; diff --git a/packages/frontend/core/src/modules/ai-button/services/ai-draft.ts b/packages/frontend/core/src/modules/ai-button/services/ai-draft.ts index 12a4a07eeb..ffc0a5b1cd 100644 --- a/packages/frontend/core/src/modules/ai-button/services/ai-draft.ts +++ b/packages/frontend/core/src/modules/ai-button/services/ai-draft.ts @@ -35,6 +35,8 @@ const DEFAULT_VALUE = { export class AIDraftService extends Service { private state: AIDraftState | null = null; + private loadingState: Promise | null = null; + private writes = Promise.resolve(); constructor( private readonly globalStateService: GlobalStateService, @@ -43,19 +45,20 @@ export class AIDraftService extends Service { super(); } - setDraft = async (data: Partial) => { - const state = await this.getState(); - const newState = { - ...state, - ...data, - }; - this.state = newState; - await this.saveDraft(newState); + setDraft = (data: Partial) => { + const write = this.writes.then(async () => { + const state = await this.getState(); + const newState = { ...state, ...data }; + this.state = newState; + await this.saveDraft(newState); + }); + this.writes = write.catch(() => undefined); + return write; }; getDraft = async () => { - const state = await this.getState(); - return state; + await this.writes; + return await this.getState(); }; private readonly saveDraft = async (state: AIDraftState) => { @@ -94,9 +97,6 @@ export class AIDraftService extends Service { }; private readonly initState = async () => { - if (this.state) { - return; - } const draft = this.globalStateService.globalState.get(AI_DRAFTS_KEY); if (draft) { @@ -113,7 +113,12 @@ export class AIDraftService extends Service { }; private readonly getState = async () => { - await this.initState(); + if (!this.state) { + this.loadingState ??= this.initState().finally(() => { + this.loadingState = null; + }); + await this.loadingState; + } return this.state as AIDraftState; };