diff --git a/frontend/src/composables/useChatStreamHandler.integration.test.ts b/frontend/src/composables/useChatStreamHandler.integration.test.ts new file mode 100644 index 00000000..4b8b76c3 --- /dev/null +++ b/frontend/src/composables/useChatStreamHandler.integration.test.ts @@ -0,0 +1,193 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test, { type TestContext } from 'node:test' +import vm from 'node:vm' +import ts from 'typescript' +import * as vue from 'vue' +import * as finalContent from '../utils/finalArtifactContent.ts' +import * as history from '../utils/rag-pipeline-history.ts' +import * as timestamps from '../utils/messageTimestamp.ts' +import * as steering from '../utils/steerStreamFork.ts' +import { useProtectedImageRecovery } from './useProtectedImageRecovery.ts' +import { clearProtectedFileFailureCache, hydrateProtectedFileImages } from '../utils/security.ts' +import { setDefaultProtectedFileAccess } from '../utils/protectedFileAccess.ts' +import type { useChatStreamHandler as StreamHandler } from './useChatStreamHandler.ts' + +// Load the entire production SSE handler, not a sliced switch branch. Only +// useI18n needs a setup-context stub; every state transition/helper is real. +const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8') +const compiled = ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, +}).outputText +const modules: Record = { + vue, 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) }, + '@/utils/finalArtifactContent': finalContent, + '@/utils/rag-pipeline-history': history, + '@/utils/messageTimestamp': timestamps, + '@/utils/steerStreamFork': steering, +} +const exports: { useChatStreamHandler?: typeof StreamHandler } = {} +vm.runInNewContext(compiled, { + exports, console, + require: (id: string) => { + assert.ok(id in modules, `unexpected import ${id}`) + return modules[id] + }, +}) +const useChatStreamHandler = exports.useChatStreamHandler! + +function setup(t: TestContext, mode: 'ordinary' | 'quick-timeline' | 'agent') { + const effects = vue.effectScope() + const oldWindow = (globalThis as any).window + const oldFetch = globalThis.fetch + ;(globalThis as any).window = { location: { origin: 'http://localhost' }, addEventListener() {} } + clearProtectedFileFailureCache() + t.after(() => { + effects.stop() + globalThis.fetch = oldFetch + ;(globalThis as any).window = oldWindow + setDefaultProtectedFileAccess(null) + clearProtectedFileFailureCache() + }) + const source = `local://2/exports/${mode}-${encodeURIComponent(t.name)}.png` + const attrs: Record = { src: source } + const img = { + dataset: {} as Record, style: { display: '' }, + get src() { return attrs.src }, set src(value: string) { attrs.src = value }, + getAttribute: (key: string) => attrs[key] || '', + setAttribute: (key: string, value: string) => { attrs[key] = value }, + removeAttribute: (key: string) => { delete attrs[key] }, + } + const root = { querySelectorAll: () => [img] } as unknown as ParentNode + const message = vue.reactive>({ + id: 'assistant', assistant_message_id: 'assistant', request_id: 'request', role: 'assistant', + content: '', is_completed: false, isAgentMode: mode !== 'ordinary', + }) + const messagesList = vue.reactive([message]) + const loading = vue.ref(true), isReplying = vue.ref(true) + const currentAssistantMessageId = vue.ref('assistant'), fullContent = vue.ref('') + const replies: string[] = [], turns: unknown[] = [], errors: string[] = [] + const handler = useChatStreamHandler({ + messagesList, loading, isReplying, currentAssistantMessageId, fullContent, + isAgentStreamSession: () => mode === 'agent', scrollToBottom() {}, + onReplyComplete: content => replies.push(content), onTurnComplete: message => turns.push(message), + onError: error => errors.push(error), + }) + const access = () => ({ mode: 'message' as const, sessionId: 'session', messageId: String(message.assistant_message_id) }) + const revealed = vue.ref(Number.MAX_SAFE_INTEGER) + const ready = vue.computed(() => Boolean(message.is_completed) && !message.persistence_error + && revealed.value >= message.content.length) + effects.run(() => useProtectedImageRecovery(() => root, access, () => ready.value)) + let persisted = false + const requests: Array<{ url: string; headers: unknown }> = [] + globalThis.fetch = async (url, init) => { + requests.push({ url: String(url), headers: init?.headers }) + // Immediate body decoding makes flushing Vue/microtasks deterministic. + return { + ok: persisted, status: persisted ? 200 : 403, + headers: new Headers(), blob: async () => new Blob(['png'], { type: 'image/png' }), + } as Response + } + const answer = `![host image](${source})` + const send = (response_type: string, content = '', done = false, data: Record = {}) => { + handler.processStreamChunk({ id: 'request', response_type, content, done, data }) + } + return { + message, loading, isReplying, currentAssistantMessageId, replies, turns, errors, img, requests, answer, send, revealed, + persist: () => { persisted = true }, + render: () => hydrateProtectedFileImages(root, access()), + flush: async () => { + await vue.nextTick() + await vue.nextTick() + await new Promise(resolve => setImmediate(resolve)) + }, + } +} + +for (const mode of ['ordinary', 'quick-timeline', 'agent'] as const) { + test(`${mode}: answer.done → persistence → complete retries the image exactly once`, async t => { + const h = setup(t, mode) + h.send('answer', h.answer, false, { event_id: 'answer' }) + await h.render() // Actual streaming render before authorization evidence is saved. + assert.equal(h.requests.length, 1) + h.send('answer', '', true, { event_id: 'answer', done: true }) + await h.flush() // Arbitrarily slow checkpoint/artifact collection can run here. + assert.equal(h.message.is_completed, false) + assert.equal(h.isReplying.value, true) + assert.equal(h.currentAssistantMessageId.value, 'assistant') + assert.equal(h.replies.length, 0) + assert.equal(h.turns.length, 0) + assert.equal(h.requests.length, 1, 'answer.done must not trigger the final retry') + h.persist() + h.send('complete', '', true, { final_content: h.answer, artifacts: [{ file_name: 'chart.png' }] }) + await h.flush() + assert.match(h.img.src, /^blob:/) + assert.equal(h.requests.length, 2, 'completion bypasses the earlier 403 cooldown') + assert.equal(h.message.content, h.answer) + assert.equal(h.message.is_completed, true) + assert.equal(h.isReplying.value, false) + assert.equal(h.replies.length, 1) + assert.equal(h.turns.length, 1) + assert.equal(h.message.artifacts[0].file_name, 'chart.png') + }) + + test(`${mode}: persistence failure preserves the streamed answer and timeline`, async t => { + const h = setup(t, mode) + h.send('answer', h.answer, false, { event_id: 'answer' }) + h.send('answer', '', true, { event_id: 'answer', done: true }) + const timeline = JSON.stringify(h.message.agentEventStream) + h.send('error', 'Failed to save assistant message', true, { stage: 'message_persistence' }) + await h.flush() + assert.equal(h.message.content, h.answer) + assert.equal(JSON.stringify(h.message.agentEventStream), timeline) + assert.equal(h.message.persistence_error, 'Failed to save assistant message') + assert.equal(h.message.is_completed, true) + assert.equal(h.isReplying.value, false) + assert.deepEqual(h.errors, ['Failed to save assistant message']) + assert.equal(h.turns.length, 0, 'unsaved output must not start follow-up requests') + assert.equal(h.requests.length, 0, 'a persistence error must not trigger a completion retry') + }) +} + +test('ordinary completion waits for the buffered typewriter before recovering images', async t => { + const h = setup(t, 'ordinary') + h.revealed.value = 0 + h.send('answer', h.answer) + await h.render() + h.send('answer', '', true) + h.persist() + h.send('complete', '', true, { final_content: h.answer }) + await h.flush() + assert.equal(h.requests.length, 1) + h.revealed.value = h.answer.length + await h.flush() + assert.equal(h.requests.length, 2) + assert.match(h.img.src, /^blob:/) +}) + +test('corrected message IDs reauthorize images without requiring completion', async t => { + const h = setup(t, 'ordinary') + h.send('answer', h.answer) + await h.render() + h.persist() + h.message.assistant_message_id = 'corrected' + await h.flush() + assert.equal(h.requests.length, 2) + assert.ok(h.requests[1].url.startsWith('/api/v1/sessions/session/messages/corrected/files?')) + assert.match(h.img.src, /^blob:/) +}) + +test('completion retries preserve the embed authentication plane', async t => { + const h = setup(t, 'ordinary') + setDefaultProtectedFileAccess({ mode: 'embed', channelId: 'channel', token: 'embed-token' }) + h.send('answer', h.answer) + await h.render() + h.send('answer', '', true) + h.persist() + h.send('complete', '', true, { final_content: h.answer }) + await h.flush() + assert.equal(h.requests.length, 2) + assert.ok(h.requests.every(request => request.url.startsWith('/api/v1/embed/channel/files?'))) + assert.deepEqual(h.requests[1].headers, { Authorization: 'Embed embed-token' }) + assert.match(h.img.src, /^blob:/) +}) diff --git a/frontend/src/composables/useChatStreamHandler.test.mjs b/frontend/src/composables/useChatStreamHandler.test.mjs index 2ee0152d..dc4b1f7a 100644 --- a/frontend/src/composables/useChatStreamHandler.test.mjs +++ b/frontend/src/composables/useChatStreamHandler.test.mjs @@ -118,17 +118,13 @@ test('injected user messages fork a continuation assistant below the bubble', () assert.match(source, /expandSteerForksInHistory\(\[\.\.\.messagesList\]\)/) }) -test('agent answer.done does not mark the session idle', () => { +test('answer.done never marks the session idle before persisted completion', () => { const chunkStart = source.indexOf("case 'answer':") const chunkEnd = source.indexOf("case 'artifacts_pending'", chunkStart) assert.notEqual(chunkStart, -1) assert.notEqual(chunkEnd, -1) const chunk = source.slice(chunkStart, chunkEnd) - assert.match(chunk, /if \(!isAgentStreamSession\(\)\)/) - assert.ok( - chunk.indexOf('isAgentStreamSession') < chunk.indexOf('isReplying.value = false'), - 'agent turns must wait for complete before clearing isReplying', - ) + assert.doesNotMatch(chunk, /isReplying.value = false/) }) // continue-stream replays the event log from the start, so after a refresh diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts index e055b3d3..aa36f316 100644 --- a/frontend/src/composables/useChatStreamHandler.ts +++ b/frontend/src/composables/useChatStreamHandler.ts @@ -954,15 +954,9 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { if (data.done && !answerEvent.done) { answerEvent.done = true onAgentAnswerDone?.(message) - // Agent turns may continue after a finishing-round inject. Closing - // isReplying here lets the composer start a second AgentQA. Wait - // for `complete` (or a non-agent answer) to mark the session idle. - if (!isAgentStreamSession()) { - loading.value = false - isReplying.value = false - fullContent.value = '' - currentAssistantMessageId.value = '' - } + // This closes only the answer segment. Both Agent and quick-answer + // turns still have to collect artifacts/checkpoint/persist before + // `complete` makes their files readable and marks the session idle. } break } @@ -1095,6 +1089,28 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { assistant_message_id: data.assistant_message_id, }) + // Persistence can fail after the entire answer has streamed. Surface the + // failure separately; the generic error path replaces the answer content. + if (data.response_type === 'error' && (data.data as ChatMessage | undefined)?.stage === 'message_persistence') { + const message = resolveActiveAssistantMessage(data) + const errorMsg = String(data.content || t('chat.processError')) + if (message) { + message.persistence_error = errorMsg + message.is_completed = true + message.thinking = false + message.artifactsCollecting = false + emitMessageUpdated(message) + } + loading.value = false + isReplying.value = false + fullContent.value = '' + currentAssistantMessageId.value = '' + if (data.id) replaySegments.delete(String(data.id)) + reportError(errorMsg) + scrollToBottom() + return + } + if (data.response_type === 'agent_query') { if (data.id) replaySegments.delete(String(data.id)) const replay = resetSteerTurnForReplay(messagesList, String(data.id || '')) @@ -1234,6 +1250,26 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { if (item.request_id === data.id) return true return item.id === data.id }) + if (data.response_type === 'complete' && existingMessage) { + if (existingMessage.is_completed) return + const metadata = data.data as ChatMessage | undefined + applyFinalArtifactContent(existingMessage, metadata?.final_content) + if (Array.isArray(metadata?.artifacts)) existingMessage.artifacts = metadata.artifacts + const usage = metadata?.usage || data.usage + if (usage) existingMessage.usage = usage + existingMessage.artifactsCollecting = false + existingMessage.thinking = false + existingMessage.is_completed = true + loading.value = false + isReplying.value = false + fullContent.value = '' + currentAssistantMessageId.value = '' + emitMessageUpdated(existingMessage, { ...data, is_completed: true }) + onReplyComplete?.(String(existingMessage.content || '')) + onTurnComplete?.(existingMessage) + scrollToBottom() + return + } if (existingMessage?.is_completed && data.done && !data.content) { log('[Non-Agent] Ignoring duplicate completion event for completed message') return @@ -1268,7 +1304,11 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { if (!existingMessage) loading.value = false - if (data.done) { + // answer.done closes the token stream, not the persisted turn. In + // particular the final image retry must wait for the subsequent complete. + // Untyped legacy streams retain their original done behavior. + const turnDone = data.done && data.response_type !== 'answer' + if (turnDone) { obj.is_completed = true onReplyComplete?.(String(obj.content || '')) isReplying.value = false @@ -1276,7 +1316,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { currentAssistantMessageId.value = '' } updateAssistantSession(obj) - if (data.done) { + if (turnDone) { const completed = resolveActiveAssistantMessage(data) || obj onTurnComplete?.(completed) } diff --git a/frontend/src/composables/useProtectedImageRecovery.ts b/frontend/src/composables/useProtectedImageRecovery.ts new file mode 100644 index 00000000..3a8ff050 --- /dev/null +++ b/frontend/src/composables/useProtectedImageRecovery.ts @@ -0,0 +1,16 @@ +import { nextTick, watch } from 'vue' +import { clearProtectedFileFailureCache, hydrateProtectedFileImages } from '../utils/security.ts' +import type { ProtectedFileAccessContext } from '../utils/protectedFileAccess.ts' + +/** Retry after persisted completion/full reveal or a corrected authorization scope. */ +export function useProtectedImageRecovery( + root: () => ParentNode | null | undefined, + access: () => ProtectedFileAccessContext | undefined, + ready: () => boolean, +) { + watch([ready, () => JSON.stringify(access() ?? null)], ([done, scope], [wasDone, previousScope]) => { + if (!(done && !wasDone) && (!previousScope || scope === previousScope)) return + clearProtectedFileFailureCache() + void nextTick(() => hydrateProtectedFileImages(root(), access())) + }, { immediate: true }) +} diff --git a/frontend/src/directives/stableHtml.test.ts b/frontend/src/directives/stableHtml.test.ts new file mode 100644 index 00000000..1ce2df07 --- /dev/null +++ b/frontend/src/directives/stableHtml.test.ts @@ -0,0 +1,105 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { DOMParser } from '@xmldom/xmldom' +import { vStableHtml } from './stableHtml.ts' +import { clearProtectedFileFailureCache, hydrateProtectedFileImages } from '../utils/security.ts' + +// Use real parsed trees and the complete directive. Adapt the small browser +// surface absent from xmldom rather than extracting the morph implementation. +function parse(html: string): any { + const root = new DOMParser().parseFromString(`
${html}
`, 'text/xml').documentElement! + function adapt(el: any) { + const tag = el.tagName.toUpperCase() + Object.defineProperties(el, { + tagName: { value: tag }, + children: { get: () => Array.from(el.childNodes).filter((child: any) => child.nodeType === 1) }, + firstElementChild: { get: () => el.children[0] ?? null }, + parentElement: { get: () => el.parentNode?.nodeType === 1 ? el.parentNode : null }, + src: { get: () => el.getAttribute('src'), set: value => el.setAttribute('src', value) }, + alt: { get: () => el.getAttribute('alt') }, + }) + el.complete = true + el.naturalWidth = 1 + el.classList = { contains: (name: string) => (el.getAttribute('class') || '').split(/\s+/).includes(name) } + el.dataset = new Proxy({}, { + get: (_, key: string) => el.getAttribute(`data-${key.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`)}`), + set: (_, key: string, value) => { + el.setAttribute(`data-${key.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`)}`, value) + return true + }, + }) + el.style = { + get display() { return el.getAttribute('style')?.match(/(?:^|;)\s*display:\s*([^;]+)/)?.[1] || '' }, + set display(value: string) { + const rest = (el.getAttribute('style') || '').replace(/(?:^|;)\s*display:[^;]*;?/g, '') + el.setAttribute('style', `${rest}${value ? `;display:${value}` : ''}`) + }, + } + el.querySelectorAll = (selector: string) => Array.from(el.getElementsByTagName('img')) + .filter((img: any) => selector.includes('src^=') || img.hasAttribute('data-protected-src')) + for (const child of el.children) adapt(child) + } + adapt(root) + return root +} + +test('missing image and paragraph stay hidden across streaming morphs, then recover without new HTML', async t => { + const previous = { + Node: (globalThis as any).Node, HTMLImageElement: (globalThis as any).HTMLImageElement, + document: (globalThis as any).document, window: (globalThis as any).window, fetch: globalThis.fetch, + } + Object.assign(globalThis, { + Node: { ELEMENT_NODE: 1, TEXT_NODE: 3, COMMENT_NODE: 8 }, + HTMLImageElement: class { static [Symbol.hasInstance](el: any) { return el?.tagName === 'IMG' } }, + document: { + createElement(tag: string) { + assert.equal(tag, 'template') + return { content: null, set innerHTML(html: string) { this.content = parse(html) } } + }, + }, + window: { location: { origin: 'http://localhost' }, addEventListener() {} }, + }) + t.after(() => { Object.assign(globalThis, previous); clearProtectedFileFailureCache() }) + const source = 'local://2/exports/morph-hidden.png' + const imageHTML = `

` + const root = parse(`${imageHTML}

first

`) + const img = root.children[0].firstElementChild + const paragraph = img.parentElement + const access = { mode: 'message', sessionId: 'session', messageId: 'assistant' } as const + let persisted = false + globalThis.fetch = async () => persisted + ? new Response(new Blob(['png'], { type: 'image/png' })) : new Response(null, { status: 404 }) + await hydrateProtectedFileImages(root, access) + assert.equal(img.style.display, 'none') + assert.equal(paragraph.style.display, 'none') + let previousHTML = `${imageHTML}

first

` + for (const text of ['first second', 'first second third']) { + const html = `${imageHTML}

${text}

` + ;(vStableHtml.updated as Function)(root, { value: html, oldValue: previousHTML }) + // Assert BEFORE another onUpdated/hydrate pass can mask a flicker. + assert.equal(root.children[0].firstElementChild, img) + assert.equal(img.style.display, 'none') + assert.equal(paragraph.style.display, 'none') + previousHTML = html + } + persisted = true + clearProtectedFileFailureCache() + await hydrateProtectedFileImages(root, access) + assert.match(img.src, /^blob:/) + assert.equal(img.style.display, '') + assert.equal(paragraph.style.display, '') + assert.equal(img.hasAttribute('data-protected-hidden'), false) + assert.equal(paragraph.hasAttribute('data-protected-hidden'), false) + + // A new source occupying the same paragraph must not inherit hidden state. + persisted = false + const other = 'local://2/exports/morph-other.png' + const otherHTML = imageHTML.replaceAll(source, other) + ;(vStableHtml.updated as Function)(root, { value: `${otherHTML}

changed

`, oldValue: previousHTML }) + await hydrateProtectedFileImages(root, access) + assert.equal(img.style.display, 'none') + ;(vStableHtml.updated as Function)(root, { value: `${imageHTML}

restored

`, oldValue: `${otherHTML}

changed

` }) + assert.notEqual(img.style.display, 'none') + assert.notEqual(paragraph.style.display, 'none') + assert.equal(img.hasAttribute('data-protected-hidden'), false) +}) diff --git a/frontend/src/directives/stableHtml.ts b/frontend/src/directives/stableHtml.ts index 723854bf..9ac9322d 100644 --- a/frontend/src/directives/stableHtml.ts +++ b/frontend/src/directives/stableHtml.ts @@ -37,6 +37,13 @@ function morphImage(current: HTMLImageElement, next: HTMLImageElement): void { && current.naturalWidth > 1 && (sameProtectedSource || sameIdentity || sameProtectedAlt); + if (sameProtectedSource && current.hasAttribute('data-protected-hidden')) { + // The authenticated loader keeps missing images addressable for the final + // retry. Do not reveal their 1px placeholder between streaming patches. + syncAttributes(current, next, new Set(['style', 'data-protected-hidden'])); + return; + } + if (keepDecodedImage) { // Never write the placeholder src (or loading flags) over an image Chrome // has already decoded. More importantly, leave this exact DOM node attached @@ -91,7 +98,18 @@ function morphNode(current: Node, next: Node): void { return; } - syncAttributes(currentElement, nextElement); + // Standalone missing images hide their empty paragraph as well. Preserve it + // only while the next paragraph still contains that exact image and no text. + const currentImage = currentElement.firstElementChild; + const nextImage = nextElement.firstElementChild; + const keepHiddenParagraph = currentElement.tagName === 'P' + && currentElement.hasAttribute('data-protected-hidden') + && nextElement.children.length === 1 && !nextElement.textContent?.trim() + && nextImage?.tagName === 'IMG' + && Boolean(currentImage?.getAttribute('data-protected-src')) + && currentImage?.getAttribute('data-protected-src') === nextImage?.getAttribute('data-protected-src'); + syncAttributes(currentElement, nextElement, + keepHiddenParagraph ? new Set(['style', 'data-protected-hidden']) : undefined); morphChildren(currentElement, nextElement); } diff --git a/frontend/src/utils/protectedResource.test.ts b/frontend/src/utils/protectedResource.test.ts index d2e53214..e171417a 100644 --- a/frontend/src/utils/protectedResource.test.ts +++ b/frontend/src/utils/protectedResource.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' -import { hydrateProtectedFileImages, protectProviderImageSrcInHTML } from './security.ts' +import test, { type TestContext } from 'node:test' +import { clearProtectedFileFailureCache, hydrateProtectedFileImages, protectProviderImageSrcInHTML } from './security.ts' import { responseFileName } from './protectedResource.ts' import { applyFinalArtifactContent } from './finalArtifactContent.ts' @@ -30,14 +30,17 @@ test('download filenames preserve Unicode and remove path components', () => { // Minimal DOM adapter exercises the actual hydration/fetch pipeline without // adding a browser-emulation dependency to the application. function imageRoot(source: string) { - const root: any = { replacement: null, querySelectorAll: () => root.replacement ? [] : [img] } + const root: any = { replacement: null, removed: false, querySelectorAll: () => root.replacement || root.removed ? [] : [img] } const attrs: Record = { src: source } const img: any = { - alt: '比赛 PPT', dataset: {}, src: '', + alt: '比赛 PPT', dataset: {}, style: { display: '' }, + get src() { return attrs.src }, + set src(value: string) { attrs.src = value }, getAttribute: (key: string) => attrs[key] || '', setAttribute: (key: string, value: string) => { attrs[key] = value }, removeAttribute: (key: string) => { delete attrs[key] }, replaceWith: (link: any) => { root.replacement = link }, + remove: () => { root.removed = true }, ownerDocument: { createElement: (tag: string) => ({ tag, dataset: {}, addEventListener() {} }) }, } return { root, img } @@ -90,3 +93,138 @@ test('cross-turn files hydrate as downloadable preview cards; images remain imag ;(globalThis as any).window = originalWindow } }) + +function hydrationEnvironment(t: TestContext) { + const originalWindow = (globalThis as any).window + const originalFetch = globalThis.fetch + ;(globalThis as any).window = { location: { origin: 'http://localhost' }, addEventListener() {} } + clearProtectedFileFailureCache() + t.after(() => { + globalThis.fetch = originalFetch + ;(globalThis as any).window = originalWindow + clearProtectedFileFailureCache() + }) +} + +const messageAccess = { mode: 'message', sessionId: 'shared-session', messageId: 'assistant' } as const +const pngResponse = () => new Response(new Blob(['png bytes'], { type: 'image/png' })) + +for (const status of [403, 404]) { + test(`completion retries an in-flight ${status} and hydrates all waiting image elements`, async (t) => { + hydrationEnvironment(t) + const source = `local://2/exports/pending-${status}.png` + const first = imageRoot(source) + const second = imageRoot(source) + let finishOld!: (response: Response) => void + let calls = 0 + globalThis.fetch = async () => { + calls++ + if (calls === 1) return new Promise(resolve => { finishOld = resolve }) + return pngResponse() + } + const streaming = hydrateProtectedFileImages(first.root, messageAccess) + // Completion can run while the same DOM node is marked authHydrated=1. + clearProtectedFileFailureCache() + const completion = hydrateProtectedFileImages(first.root, messageAccess) + const otherOccurrence = hydrateProtectedFileImages(second.root, messageAccess) + finishOld(new Response(null, { status })) + await Promise.all([streaming, completion, otherOccurrence]) + assert.equal(calls, 2, 'exactly one shared retry after persistence') + assert.match(first.img.src, /^blob:/) + assert.equal(second.img.src, first.img.src) + assert.equal(first.root.removed, false) + await hydrateProtectedFileImages(first.root, messageAccess) + assert.equal(calls, 2, 'decoded image stays cached') + }) +} + +test('completion clears a settled failure cooldown without waiting for another render', async (t) => { + hydrationEnvironment(t) + const image = imageRoot('local://2/exports/settled.png') + let calls = 0 + globalThis.fetch = async () => ++calls === 1 ? new Response(null, { status: 403 }) : pngResponse() + await hydrateProtectedFileImages(image.root, messageAccess) + await hydrateProtectedFileImages(image.root, messageAccess) + assert.equal(calls, 1) + clearProtectedFileFailureCache() + await hydrateProtectedFileImages(image.root, messageAccess) + assert.equal(calls, 2) + assert.match(image.img.src, /^blob:/) +}) + +test('a settled 404 recovers on the same DOM node without a Markdown change', async (t) => { + hydrationEnvironment(t) + const image = imageRoot('local://2/exports/settled-404.png') + const paragraph = { + tagName: 'P', textContent: '', children: [image.img], style: { display: '' }, + setAttribute() {}, removeAttribute() {}, + } + image.img.parentElement = paragraph + let calls = 0 + globalThis.fetch = async () => ++calls === 1 ? new Response(null, { status: 404 }) : pngResponse() + await hydrateProtectedFileImages(image.root, messageAccess) + assert.equal(image.root.removed, false) + assert.equal(image.img.style.display, 'none') + assert.equal(paragraph.style.display, 'none', 'no empty image paragraph is left visible') + await hydrateProtectedFileImages(image.root, messageAccess) + assert.equal(calls, 1, 'known-missing requests remain cached') + clearProtectedFileFailureCache() + await hydrateProtectedFileImages(image.root, messageAccess) + assert.equal(calls, 2) + assert.match(image.img.src, /^blob:/) + assert.equal(image.img.style.display, '') + assert.equal(paragraph.style.display, '') +}) + +test('a stale message 404 cannot remove an image loaded with the corrected message ID', async (t) => { + hydrationEnvironment(t) + const image = imageRoot('local://2/exports/corrected-id.png') + let finishOld!: (response: Response) => void + globalThis.fetch = async url => String(url).includes('/temporary/') + ? new Promise(resolve => { finishOld = resolve }) : pngResponse() + const old = hydrateProtectedFileImages(image.root, { ...messageAccess, messageId: 'temporary' }) + await hydrateProtectedFileImages(image.root, messageAccess) + const loaded = image.img.src + finishOld(new Response(null, { status: 404 })) + await old + assert.equal(image.root.removed, false) + assert.match(loaded, /^blob:/) + assert.equal(image.img.src, loaded) +}) + +test('a missing request does not suppress the same source under another message', async (t) => { + hydrationEnvironment(t) + const source = 'local://2/exports/scoped-missing.png' + const old = imageRoot(source) + globalThis.fetch = async url => String(url).includes('/temporary/') + ? new Response(null, { status: 404 }) : pngResponse() + await hydrateProtectedFileImages(old.root, { ...messageAccess, messageId: 'temporary' }) + assert.equal(old.img.style.display, 'none') + assert.match(protectProviderImageSrcInHTML(``), /data-protected-src/) + const corrected = imageRoot(source) + await hydrateProtectedFileImages(corrected.root, messageAccess) + assert.match(corrected.img.src, /^blob:/) +}) + +test('revoked sharing remains denied and completion retries are bounded', async (t) => { + hydrationEnvironment(t) + const image = imageRoot('local://2/exports/revoked-share.png') + let finishOld!: (response: Response) => void + let calls = 0 + globalThis.fetch = async () => { + calls++ + if (calls === 1) return new Promise(resolve => { finishOld = resolve }) + // Even another completion signal while retrying cannot create a loop. + clearProtectedFileFailureCache() + return new Response(null, { status: 403 }) + } + const pending = hydrateProtectedFileImages(image.root, messageAccess) + clearProtectedFileFailureCache() + finishOld(new Response(null, { status: 403 })) + await pending + assert.equal(calls, 2) + assert.match(image.img.src, /^data:image\/gif/) + assert.equal(image.img.dataset.authHydrated, '0') + await hydrateProtectedFileImages(image.root, messageAccess) + assert.equal(calls, 2, 'denial cooldown is retained') +}) diff --git a/frontend/src/utils/security.ts b/frontend/src/utils/security.ts index 800355dc..de42c6ef 100644 --- a/frontend/src/utils/security.ts +++ b/frontend/src/utils/security.ts @@ -209,12 +209,6 @@ function buildProtectedImageTag( protectedSrc: string, after: string, ): string { - // A definitive 404 should not leave a skeleton behind. Streaming - // re-renders call this function repeatedly, so remember the missing - // source until the explicit end-of-stream retry clears the cache. - if (protectedFileMissingSources.has(protectedSrc)) { - return ''; - } // Reuse the already-hydrated file if we have one, so repeated re-renders // (typewriter streaming) keep the same stable image or download card // instead of flashing back to the placeholder every frame. @@ -436,12 +430,21 @@ type ProtectedFileLoadResult = | { status: 'missing' } | { status: 'failed' }; +type HiddenProtectedImage = { + display: string; + parent: HTMLElement | null; + parentDisplay: string; +}; + type ProtectedFileCacheState = { blobByRequest: Map; fileBySource: Map; - missingSources: Set; + missingRequests: Set; failures: Map; inflight: Map>; + retryGeneration: number; + imageRequests: WeakMap; + hiddenImages: WeakMap; }; // Keep object URLs alive across Vite hot updates. A hot update replaces this @@ -451,16 +454,19 @@ const protectedFileCacheState = (() => { const fresh = (): ProtectedFileCacheState => ({ blobByRequest: new Map(), fileBySource: new Map(), - missingSources: new Set(), + missingRequests: new Set(), failures: new Map(), inflight: new Map(), + retryGeneration: 0, + imageRequests: new WeakMap(), + hiddenImages: new WeakMap(), }); if (typeof window === 'undefined') return fresh(); const scope = window as typeof window & { - __weknoraProtectedFileCacheV3__?: ProtectedFileCacheState; + __weknoraProtectedFileCacheV4__?: ProtectedFileCacheState; }; - scope.__weknoraProtectedFileCacheV3__ ||= fresh(); - return scope.__weknoraProtectedFileCacheV3__; + scope.__weknoraProtectedFileCacheV4__ ||= fresh(); + return scope.__weknoraProtectedFileCacheV4__; })(); const protectedFileBlobCache = protectedFileCacheState.blobByRequest; @@ -468,7 +474,9 @@ const protectedFileBlobCache = protectedFileCacheState.blobByRequest; // image or download card has been hydrated, re-renders of the same markdown // can emit the blob src / card HTML directly instead of the placeholder. const protectedFileBySource = protectedFileCacheState.fileBySource; -const protectedFileMissingSources = protectedFileCacheState.missingSources; +// A 404 may mean a temporary message ID was not found, not that the resource +// is missing in every message/workspace. Cache it only under that request. +const protectedFileMissingRequests = protectedFileCacheState.missingRequests; // Throttle retries of failed file fetches. During streaming the same markdown // is re-rendered on every chunk, producing brand-new elements (so the // per-element `authHydrated` flag is reset each time). Without throttling a @@ -478,6 +486,8 @@ const protectedFileMissingSources = protectedFileCacheState.missingSources; const protectedFileFailureCache = protectedFileCacheState.failures; const protectedFileInflight = protectedFileCacheState.inflight; const PROTECTED_FILE_RETRY_COOLDOWN_MS = 5000; +const protectedImageRequests = protectedFileCacheState.imageRequests; +const hiddenProtectedImages = protectedFileCacheState.hiddenImages; /** * 将 Markdown 里通过 /files 代理的图片,改为用带鉴权 Header 的 fetch 拉取后再显示。 @@ -488,8 +498,11 @@ const PROTECTED_FILE_RETRY_COOLDOWN_MS = 5000; * 的图片可以立即重新尝试加载,而无需等待冷却窗口结束。 */ export function clearProtectedFileFailureCache(): void { + // An earlier request can still be in flight when completion arrives. Its + // failure must get one fresh attempt against the newly persisted message. + protectedFileCacheState.retryGeneration++; protectedFileFailureCache.clear(); - protectedFileMissingSources.clear(); + protectedFileMissingRequests.clear(); } function protectedImageSource(img: HTMLImageElement): string { @@ -501,27 +514,50 @@ function protectedImageSource(img: HTMLImageElement): string { function forEachProtectedImageWithSource( root: ParentNode, sourceURL: string, + requestKey: string, callback: (img: HTMLImageElement) => void, ): void { root.querySelectorAll('img[data-protected-src]').forEach((candidate) => { - if (protectedImageSource(candidate) === sourceURL) callback(candidate); + if (protectedImageRequests.get(candidate) === requestKey && protectedImageSource(candidate) === sourceURL) callback(candidate); }); } -function removeMissingProtectedImages(root: ParentNode, sourceURL: string): void { - forEachProtectedImageWithSource(root, sourceURL, (img) => { - const parent = img.parentElement; - img.remove(); - // Markdown emits a dedicated paragraph for a standalone image. Remove that - // wrapper too so a missing image leaves no vertical placeholder/gap. - if (parent?.tagName === 'P' && !parent.textContent?.trim() && parent.children.length === 0) { - parent.remove(); +function hideMissingProtectedImages(root: ParentNode, sourceURL: string, requestKey: string): void { + forEachProtectedImageWithSource(root, sourceURL, requestKey, (img) => { + // Keep the node addressable for completion/scope retries. v-stable-html + // skips unchanged HTML, so removing it would make a settled 404 permanent + // even after failure state is cleared and the resource becomes readable. + if (!hiddenProtectedImages.has(img)) { + const parent = img.parentElement; + const standalone = parent?.tagName === 'P' && !parent.textContent?.trim() && parent.children.length === 1 + ? parent : null; + hiddenProtectedImages.set(img, { + display: img.style.display, parent: standalone, parentDisplay: standalone?.style.display || '', + }); } + img.style.display = 'none'; + img.setAttribute('data-protected-hidden', '1'); + const parent = hiddenProtectedImages.get(img)?.parent; + if (parent) { + parent.style.display = 'none'; + parent.setAttribute('data-protected-hidden', '1'); + } + img.dataset.authHydrated = '0'; }); } -function applyHydratedProtectedImage(root: ParentNode, sourceURL: string, file: LoadedProtectedFile): void { - forEachProtectedImageWithSource(root, sourceURL, (img) => { +function applyHydratedProtectedImage(root: ParentNode, sourceURL: string, file: LoadedProtectedFile, requestKey: string): void { + forEachProtectedImageWithSource(root, sourceURL, requestKey, (img) => { + const hidden = hiddenProtectedImages.get(img); + if (hidden) { + img.style.display = hidden.display; + img.removeAttribute('data-protected-hidden'); + if (hidden.parent) { + hidden.parent.style.display = hidden.parentDisplay; + hidden.parent.removeAttribute('data-protected-hidden'); + } + hiddenProtectedImages.delete(img); + } if (!isRasterProtectedImage(file)) { applyProtectedFile(img, file, sourceURL); return; @@ -589,15 +625,6 @@ export async function hydrateProtectedFileImages( if (!sourceURL) { return; } - if (img.dataset.authHydrated === '1') { - return; - } - if (protectedFileMissingSources.has(sourceURL)) { - removeMissingProtectedImages(root, sourceURL); - return; - } - img.dataset.authHydrated = '1'; - // A null request means this source cannot be fetched under the current // access context (not a storage path, or the embed token has not arrived // yet). Leave the placeholder so a later pass can retry. @@ -608,10 +635,19 @@ export async function hydrateProtectedFileImages( } const { url: requestURL, headers } = request; const requestKey = JSON.stringify([requestURL, headers]); + if (img.dataset.authHydrated === '1' && src.startsWith('blob:') && protectedImageRequests.get(img) === requestKey) { + return; + } + protectedImageRequests.set(img, requestKey); + if (protectedFileMissingRequests.has(requestKey)) { + hideMissingProtectedImages(root, sourceURL, requestKey); + return; + } + img.dataset.authHydrated = '1'; const cachedBlobURL = protectedFileBlobCache.get(requestKey); if (cachedBlobURL) { - applyHydratedProtectedImage(root, sourceURL, cachedBlobURL); + applyHydratedProtectedImage(root, sourceURL, cachedBlobURL, requestKey); return; } @@ -628,46 +664,52 @@ export async function hydrateProtectedFileImages( let loadTask = protectedFileInflight.get(requestKey); if (!loadTask) { loadTask = (async (): Promise => { - try { - const resp = await fetch(requestURL, { - method: 'GET', - headers, - credentials: 'include', - }); - if (!resp.ok) { - if (resp.status === 404) { - protectedFileFailureCache.set(requestKey, Date.now()); - return { status: 'missing' }; + for (let attempt = 0; ; attempt++) { + const generation = protectedFileCacheState.retryGeneration; + try { + const resp = await fetch(requestURL, { + method: 'GET', + headers, + credentials: 'include', + }); + if (!resp.ok) { + if (attempt === 0 && generation !== protectedFileCacheState.retryGeneration) continue; + if (resp.status === 404) { + protectedFileFailureCache.set(requestKey, Date.now()); + return { status: 'missing' }; + } + throw new Error(`HTTP ${resp.status}`); } - throw new Error(`HTTP ${resp.status}`); + const blob = await resp.blob(); + const blobURL = URL.createObjectURL(blob); + const file = { blobURL, blob, fileName: responseFileName(resp.headers.get("Content-Disposition"), sourceURL) }; + protectedFileBlobCache.set(requestKey, file); + protectedFileFailureCache.delete(requestKey); + return { status: 'loaded', ...file }; + } catch (error) { + if (attempt === 0 && generation !== protectedFileCacheState.retryGeneration) continue; + console.warn('[security] hydrateProtectedFileImages failed:', error); + protectedFileFailureCache.set(requestKey, Date.now()); + return { status: 'failed' }; } - const blob = await resp.blob(); - const blobURL = URL.createObjectURL(blob); - const file = { blobURL, blob, fileName: responseFileName(resp.headers.get("Content-Disposition"), sourceURL) }; - protectedFileBlobCache.set(requestKey, file); - protectedFileFailureCache.delete(requestKey); - return { status: 'loaded', ...file }; - } catch (error) { - console.warn('[security] hydrateProtectedFileImages failed:', error); - protectedFileFailureCache.set(requestKey, Date.now()); - return { status: 'failed' }; - } finally { - protectedFileInflight.delete(requestKey); } - })(); + })().finally(() => protectedFileInflight.delete(requestKey)); protectedFileInflight.set(requestKey, loadTask); } const result = await loadTask; + // A late response for an old message ID must not remove or overwrite an + // image that has since been reauthorized under its persisted message ID. + if (protectedImageRequests.get(img) !== requestKey) return; if (result.status === 'loaded') { protectedFileBySource.set(sourceURL, result); - protectedFileMissingSources.delete(sourceURL); - applyHydratedProtectedImage(root, sourceURL, result); + protectedFileMissingRequests.delete(requestKey); + applyHydratedProtectedImage(root, sourceURL, result, requestKey); return; } if (result.status === 'missing') { - protectedFileMissingSources.add(sourceURL); - removeMissingProtectedImages(root, sourceURL); + protectedFileMissingRequests.add(requestKey); + hideMissingProtectedImages(root, sourceURL, requestKey); return; } if (result.status === 'failed') { diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 1e247719..f93198a3 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -661,7 +661,8 @@ import { useSettingsStore } from '@/stores/settings'; import { useAuthStore } from '@/stores/auth'; import { useI18n } from 'vue-i18n'; import i18n from '@/i18n'; -import { hydrateProtectedFileImages, clearProtectedFileFailureCache, sanitizeMarkdownHTML } from '@/utils/security'; +import { hydrateProtectedFileImages, sanitizeMarkdownHTML } from '@/utils/security'; +import { useProtectedImageRecovery } from '@/composables/useProtectedImageRecovery'; import { artifactIndexFromEventTarget, hydrateArtifactImages, @@ -1053,25 +1054,6 @@ const protectedFileAccess = computed(() return undefined; }); -// Re-hydrate when the message authorization anchor becomes available or is -// corrected (e.g. request_id → persisted assistant_message_id after agent_query). -watch( - () => { - const access = protectedFileAccess.value; - if (access?.mode === 'message') { - return `${access.sessionId}\0${access.messageId}`; - } - return ''; - }, - (scopeKey, previousScopeKey) => { - if (!scopeKey || scopeKey === previousScopeKey) return; - clearProtectedFileFailureCache(); - nextTick(async () => { - await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value); - }); - }, -); - // ----------------------------------------------------------------------------- // Skill artifact download drawer (Agent path) // ----------------------------------------------------------------------------- @@ -1710,15 +1692,12 @@ const answerFullyRendered = computed( isSegmentDone.value && typedAnswer.value.length >= activeAnswerMarkdown.value.length, ); +useProtectedImageRecovery(() => rootElement.value, () => protectedFileAccess.value, + () => !props.session?.persistence_error && answerFullyRendered.value); watch(answerFullyRendered, (ready) => { emit('render-complete-change', ready); if (!ready) return; - // Clear before this reactive update renders, so a source that returned 404 - // mid-stream gets one real final-attempt node instead of remaining - // suppressed by the missing-source cache. - clearProtectedFileFailureCache(); nextTick(async () => { - await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value); await enhanceMarkdownContainer(rootElement.value); }); }, { immediate: true }); diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index 8718fbed..02042df3 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -154,6 +154,7 @@ import { useArtifactArriveMotion } from '@/composables/useArtifactArriveMotion'; import { useChatSandboxPanel } from '@/composables/useChatSandboxPanel'; import { persistedAssistantId } from '@/utils/steerStreamFork'; import { sanitizeMarkdownHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security'; +import { useProtectedImageRecovery } from '@/composables/useProtectedImageRecovery'; import { artifactIndexFromEventTarget, hydrateArtifactImages, @@ -327,6 +328,14 @@ const artifactRefContext = computed(() => { return { sessionId: props.sessionId, messageId }; }); +// Shared replies must authorize files through the persisted message, just as +// AgentStreamDisplay does. The default embed plane still takes precedence. +const protectedFileAccess = computed(() => { + const messageId = persistedAssistantId(props.session); + if (!props.sessionId || !messageId) return undefined; + return { mode: 'message', sessionId: props.sessionId, messageId }; +}); + const artifactRefLabels = computed(() => ({ previewHint: t('agent.artifactDrawer.inlinePreviewHint'), missingHint: t('agent.artifactDrawer.inlineMissing'), @@ -389,6 +398,8 @@ const { displayed: typedAnswer } = useTypewriter( const answerFullyRendered = computed(() => Boolean(props.session?.is_completed) && typedAnswer.value.length >= answerText.value.length ); +useProtectedImageRecovery(() => parentMd.value, () => protectedFileAccess.value, + () => !props.session?.isAgentMode && !props.session?.persistence_error && answerFullyRendered.value); watch( answerFullyRendered, @@ -484,7 +495,7 @@ watch(renderedHTML, () => { // 渲染 Mermaid 图表的函数 onUpdated(() => { nextTick(async () => { - await hydrateProtectedFileImages(parentMd.value); + await hydrateProtectedFileImages(parentMd.value, protectedFileAccess.value); await hydrateArtifactImages(parentMd.value, artifactRefContext.value); refreshMarkdownEnhancements(parentMd.value); if (props.session?.is_completed) { @@ -500,7 +511,7 @@ onMounted(async () => { parentMd.value.addEventListener('click', handleMarkdownImageClick, true); } rebindCitations(); - await hydrateProtectedFileImages(parentMd.value); + await hydrateProtectedFileImages(parentMd.value, protectedFileAccess.value); await hydrateArtifactImages(parentMd.value, artifactRefContext.value); await enhanceMarkdownContainer(parentMd.value); }); diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go index 3d6c3f96..8968a0d1 100644 --- a/internal/handler/session/agent_stream_handler.go +++ b/internal/handler/session/agent_stream_handler.go @@ -42,6 +42,7 @@ type AgentStreamHandler struct { ttfbLogged bool // Guards one-shot TTFB log on first answer chunk assistantMessage *types.Message streamManager interfaces.StreamManager + completionEvent *interfaces.StreamEvent // Published only after the final message is persisted. eventBus *event.EventBus @@ -876,7 +877,9 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event } } - // Send completion event to stream manager so SSE can detect completion + // Prepare completion metadata. Publishing must wait for the caller to save + // Content/AgentSteps/Artifacts: message-scoped file requests authorize against + // that persisted output as soon as the client receives this event. completeData := map[string]interface{}{ "total_steps": data.TotalSteps, "total_duration_ms": data.TotalDurationMs, @@ -897,7 +900,7 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event if turnUsage != nil { completeData["usage"] = turnUsage } - if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{ + h.completionEvent = &interfaces.StreamEvent{ ID: evt.ID, Type: types.ResponseTypeComplete, Content: "", @@ -905,13 +908,27 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event Timestamp: time.Now(), Data: completeData, Usage: turnUsage, - }); err != nil { - logger.GetLogger(h.ctx).Errorf("Append complete event to stream failed: %v", err) } return nil } +// publishCompletion is called only after UpdateMessage succeeds. Keep it +// separate from handleComplete so steering handoff and final persistence retain +// their existing order, including on cancellation and quick-answer turns. +func (h *AgentStreamHandler) publishCompletion(ctx context.Context) error { + h.mu.Lock() + defer h.mu.Unlock() + if h.completionEvent == nil { + return nil + } + if err := h.streamManager.AppendEvent(ctx, h.sessionID, h.assistantMessageID, *h.completionEvent); err != nil { + return err + } + h.completionEvent = nil + return nil +} + // emitArtifactsPending tells the live UI that sandbox files exist and are // being uploaded. It must not take h.mu — Collect calls it while // handleComplete already holds the lock. diff --git a/internal/handler/session/artifact_completion_test.go b/internal/handler/session/artifact_completion_test.go index ddb5efa2..580386d2 100644 --- a/internal/handler/session/artifact_completion_test.go +++ b/internal/handler/session/artifact_completion_test.go @@ -49,6 +49,7 @@ func TestCompletionPublishesReconciledArtifactContent(t *testing.T) { ) err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}}) require.NoError(t, err) + require.NoError(t, handler.publishCompletion(context.Background())) last := stream.events[len(stream.events)-1] require.Equal(t, types.ResponseTypeComplete, last.Type) require.Equal(t, message.Content, last.Data["final_content"]) @@ -81,6 +82,7 @@ func TestCompletionResolvesReferencesWhenNothingWasPersisted(t *testing.T) { err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}}) require.NoError(t, err) + require.NoError(t, handler.publishCompletion(context.Background())) require.Len(t, message.Artifacts, 1, "the referenced file must be attached to this message") require.Equal(t, existing.URL, message.Artifacts[0].URL) diff --git a/internal/handler/session/image_completion_test.go b/internal/handler/session/image_completion_test.go new file mode 100644 index 00000000..4f4bc6be --- /dev/null +++ b/internal/handler/session/image_completion_test.go @@ -0,0 +1,144 @@ +package session + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/application/access" + "github.com/Tencent/WeKnora/internal/event" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/require" +) + +type imageCompletionMessages struct { + interfaces.MessageService + saved *types.Message + tenant uint64 + err error + beforeSave func() +} + +func (s *imageCompletionMessages) UpdateMessage(ctx context.Context, message *types.Message) error { + if err := ctx.Err(); err != nil { + return err + } + if s.beforeSave != nil { + s.beforeSave() + } + if s.err != nil { + return s.err + } + s.tenant = types.MustTenantIDFromContext(ctx) + snapshot := *message + s.saved = &snapshot + return nil +} + +func TestQuickAnswerCompletionPersistsAfterGenerationCancellation(t *testing.T) { + messages := &imageCompletionMessages{} + stream := &imageCompletionStream{} + h := &Handler{messageService: messages, streamManager: stream} + bus := event.NewEventBus() + message := &types.Message{ + ID: "m", SessionID: "s", Role: "assistant", Content: "already streamed answer", AgentTenantID: 2, + } + ctx, cancel := context.WithCancel(types.WithExecutionTenant(context.Background(), 1)) + streamHandler := h.setupStreamHandler(ctx, "s", "m", "req", 1, time.Now(), message, bus) + cancel() + released := false + h.completeQuickAnswerTurn(ctx, &sseStreamContext{ + eventBus: bus, streamHandler: streamHandler, assistantMessage: message, + releaseTurn: func() { released = true }, + }, "", "") + require.NotNil(t, messages.saved) + require.Equal(t, "already streamed answer", messages.saved.Content) + require.Equal(t, uint64(1), messages.tenant) + require.True(t, released) + require.Equal(t, types.ResponseTypeComplete, stream.events[len(stream.events)-1].Type) +} + +type imageCompletionStream struct { + completionEventRecorder + onComplete func() +} + +func (s *imageCompletionStream) AppendEvent( + ctx context.Context, session, message string, e interfaces.StreamEvent, +) error { + if e.Type == types.ResponseTypeComplete && s.onComplete != nil { + s.onComplete() + } + return s.completionEventRecorder.AppendEvent(ctx, session, message, e) +} + +func TestSharedImageCompletionWaitsForPersistedReferences(t *testing.T) { + const image = "resource://AbCdEfGhIjKlMnOpQrStUv" + for _, quick := range []bool{false, true} { + name := "agent" + if quick { + name = "quick answer" + } + t.Run(name, func(t *testing.T) { + for _, fail := range []bool{false, true} { + t.Run(map[bool]string{false: "saved", true: "save failed"}[fail], func(t *testing.T) { + messages := &imageCompletionMessages{} + if fail { + messages.err = errors.New("database unavailable") + } + stream := &imageCompletionStream{} + h := &Handler{messageService: messages, streamManager: stream} + bus := event.NewEventBus() + message := &types.Message{ + ID: "m", SessionID: "s", Role: "assistant", AgentTenantID: 2, + } + // Execution uses the host workspace; the conversation belongs to + // the visitor's workspace and must be saved there before notifying it. + runCtx := types.WithExecutionTenant(context.Background(), 2) + saveCtx := types.WithExecutionTenant(runCtx, 1) + streamHandler := h.setupStreamHandler(runCtx, "s", "m", "req", 1, time.Now(), message, bus) + streamCtx := &sseStreamContext{ + eventBus: bus, streamHandler: streamHandler, assistantMessage: message, + } + completed := 0 + stream.onComplete = func() { + completed++ + require.NotNil(t, messages.saved, "a completion-triggered image GET must see persisted output") + require.True(t, access.MessageReferencesFile(messages.saved, image)) + require.True(t, messages.saved.IsCompleted) + require.Equal(t, uint64(1), messages.tenant) + } + messages.beforeSave = func() { + require.Zero(t, completed, "completion must not escape while the database write is pending") + } + answer := "![host image](" + image + ")" + if quick { + message.Content = answer + h.completeQuickAnswerTurn(saveCtx, streamCtx, "", "") + } else { + require.NoError(t, bus.Emit(runCtx, event.Event{ + Type: event.EventAgentComplete, + Data: event.AgentCompleteData{MessageID: "m", FinalAnswer: answer}, + })) + require.Zero(t, completed) + h.completeStreamAssistantMessage(saveCtx, streamCtx, "", "") + } + last := stream.events[len(stream.events)-1] + if fail { + require.Zero(t, completed) + require.Equal(t, types.ResponseTypeError, last.Type) + require.Equal(t, "message_persistence", last.Data["stage"]) + } else { + require.Equal(t, 1, completed) + require.Equal(t, types.ResponseTypeComplete, last.Type) + require.Equal(t, answer, last.Data["final_content"]) + require.NoError(t, streamHandler.publishCompletion(saveCtx)) + require.Equal(t, 1, completed, "completion must only be published once") + } + }) + } + }) + } +} diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index f816475a..51cdcde0 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -656,6 +656,7 @@ func mergeKnowledgeTargets(requestKBIDs []string, requestKnowledgeIDs []string, // sseStreamContext holds the context for SSE streaming type sseStreamContext struct { eventBus *event.EventBus + streamHandler *AgentStreamHandler asyncCtx context.Context cancel context.CancelFunc assistantMessage *types.Message @@ -775,7 +776,7 @@ func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool, m h.startStopWatcher(logger.CloneContext(baseCtx), reqCtx.sessionID, reqCtx.assistantMessage.ID, eventBus) // Setup stream handler - h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID, + streamCtx.streamHandler = h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID, reqCtx.requestID, reqCtx.session.TenantID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus) // Generate title if needed @@ -1341,13 +1342,13 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle injected = streamCtx.steerSink.InjectedIDs() } h.discardSteerBacklog(updateCtx, sessionID, streamCtx.assistantMessage.ID, injected) - h.completeAssistantMessage( - updateCtx, streamCtx.assistantMessage, reqCtx.query, reqCtx.userMessageID, + h.completeStreamAssistantMessage( + updateCtx, streamCtx, reqCtx.query, reqCtx.userMessageID, ) } else { kicked := h.kickNextRunFromSteerBacklog(updateCtx, reqCtx, streamCtx) - h.completeAssistantMessage( - updateCtx, streamCtx.assistantMessage, reqCtx.query, reqCtx.userMessageID, + h.completeStreamAssistantMessage( + updateCtx, streamCtx, reqCtx.query, reqCtx.userMessageID, ) // A /steer that landed while we were completing still sits // on this run. Claim it before ClearLiveRun so it is not @@ -1788,6 +1789,9 @@ func (h *Handler) completeQuickAnswerTurn( if streamCtx == nil || streamCtx.assistantMessage == nil { return } + // A stop can cancel the generation context after the final answer event + // was queued. Preserve the streamed answer just as the Agent defer does. + ctx = context.WithoutCancel(ctx) if streamCtx.eventBus != nil { // MessageID is what handleComplete keys on. Leave FinalAnswer empty: // KnowledgeQA already accumulated the answer on the message, and @@ -1800,7 +1804,7 @@ func (h *Handler) completeQuickAnswerTurn( }, }) } - h.completeAssistantMessage(ctx, streamCtx.assistantMessage, query, userMessageID) + h.completeStreamAssistantMessage(ctx, streamCtx, query, userMessageID) if streamCtx.releaseTurn != nil { streamCtx.releaseTurn() } @@ -1827,14 +1831,39 @@ func (h *Handler) sessionTenantInfoContext(ctx context.Context) (context.Context return context.WithValue(ctx, types.TenantInfoContextKey, tenant), true } +// completeStreamAssistantMessage makes output readable before notifying clients +// to perform their final image/artifact fetch. A failed write must not announce +// a successful completion whose file authorization evidence is still missing. +func (h *Handler) completeStreamAssistantMessage( + ctx context.Context, streamCtx *sseStreamContext, query, userMessageID string, +) { + if err := h.completeAssistantMessage(ctx, streamCtx.assistantMessage, query, userMessageID); err != nil { + if streamCtx.streamHandler != nil { + _ = streamCtx.streamHandler.handleError(ctx, event.Event{ + ID: uuid.New().String(), Type: event.EventError, SessionID: streamCtx.assistantMessage.SessionID, + Data: event.ErrorData{Stage: "message_persistence", Error: "Failed to save assistant message"}, + }) + } + return + } + if streamCtx.streamHandler != nil { + if err := streamCtx.streamHandler.publishCompletion(ctx); err != nil { + logger.Errorf(ctx, "Append persisted message completion failed: %v", err) + } + } +} + // completeAssistantMessage marks an assistant message as complete, updates it, // and asynchronously indexes the Q&A pair into the chat history knowledge base. func (h *Handler) completeAssistantMessage( ctx context.Context, assistantMessage *types.Message, userQuery, userMessageID string, -) { +) error { assistantMessage.UpdatedAt = time.Now() assistantMessage.IsCompleted = true - _ = h.messageService.UpdateMessage(ctx, assistantMessage) + if err := h.messageService.UpdateMessage(ctx, assistantMessage); err != nil { + logger.Errorf(ctx, "Failed to persist assistant message %s: %v", assistantMessage.ID, err) + return err + } // Asynchronously index the Q&A pair into the chat history knowledge base for vector search. // Use WithoutCancel so the goroutine survives after the HTTP request context is done. @@ -1855,6 +1884,7 @@ func (h *Handler) completeAssistantMessage( if userQuery != "" { go h.recordTurnMemory(bgCtx, assistantMessage, userQuery, userMessageID) } + return nil } // recordTurnMemory runs the long-term memory write path for a finished turn. diff --git a/internal/handler/session/workspace_checkpoint_completion_test.go b/internal/handler/session/workspace_checkpoint_completion_test.go index c6759ec7..65bb6c26 100644 --- a/internal/handler/session/workspace_checkpoint_completion_test.go +++ b/internal/handler/session/workspace_checkpoint_completion_test.go @@ -140,6 +140,7 @@ func TestQuickAnswerCompletionPersistsSandboxCheckpoint(t *testing.T) { h := &Handler{messageService: stub} h.completeQuickAnswerTurn(context.Background(), &sseStreamContext{ eventBus: bus, + streamHandler: streamHandler, assistantMessage: message, }, "", "")