diff --git a/frontend/src/utils/sessionArtifacts.test.ts b/frontend/src/utils/sessionArtifacts.test.ts index 6eb98c76..03b6fd09 100644 --- a/frontend/src/utils/sessionArtifacts.test.ts +++ b/frontend/src/utils/sessionArtifacts.test.ts @@ -1,5 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' +import { expandSteerForksInHistory, forkAfterInjectedUser } from './steerStreamFork.ts' +import { readFileSync } from 'node:fs' import { collectSessionArtifacts, formatArtifactDateTime, @@ -64,3 +66,34 @@ test('formatArtifactDateTime renders a stable local timestamp', () => { assert.equal(formatArtifactDateTime('not-a-date'), 'not-a-date') assert.match(formatArtifactDateTime('2026-09-08T04:05:00Z'), /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/) }) + +test('artifacts after a live inject use the persisted assistant ID regardless of filename', () => { + const assistant = { id: 'assistant', request_id: 'request', role: 'assistant' } + const list = [assistant] + const continuation = forkAfterInjectedUser(list, assistant, { id: 'user', role: 'user' }, 'steer') + continuation.artifacts = [{ file_name: 'WeKnora-示例文档.docx', index: 3 }] + const items = collectSessionArtifacts(list) + assert.equal(items[0]?.messageId, 'assistant') + assert.equal(items[0]?.index, 3) + assert.equal(items[0]?.file_name, 'WeKnora-示例文档.docx') +}) + +test('history-split artifacts keep their persisted download address after refresh', () => { + const list = expandSteerForksInHistory([ + { id: 'assistant', role: 'assistant', request_id: 'request', is_completed: true, + artifacts: [{ file_name: '示例.docx' }, { file_name: 'example.docx' }] }, + { id: 'user', role: 'user', request_id: 'request', created_at: '2026-09-09T12:00:00Z' }, + ]) + const items = collectSessionArtifacts(list) + assert.deepEqual(items.map(item => [item.messageId, item.index]), [['assistant', 0], ['assistant', 1]]) +}) + +test('both answer renderers resolve the persisted artifact owner for inline previews and folder entry', () => { + for (const file of ['botmsg.vue', 'AgentStreamDisplay.vue']) { + const source = readFileSync(new URL(`../views/chat/components/${file}`, import.meta.url), 'utf8') + const start = source.indexOf('const messageIdForArtifacts = computed(') + const end = source.indexOf('// Set when the drawer', start) + assert.ok(start >= 0 && end > start) + assert.match(source.slice(start, end), /persistedAssistantId\(props\.session\)/) + } +}) diff --git a/frontend/src/utils/sessionArtifacts.ts b/frontend/src/utils/sessionArtifacts.ts index fbc24cfe..f7423cb9 100644 --- a/frontend/src/utils/sessionArtifacts.ts +++ b/frontend/src/utils/sessionArtifacts.ts @@ -1,4 +1,5 @@ import type { ArtifactMeta } from '@/api/chat' +import { persistedAssistantId } from './steerStreamFork' /** Artifact metadata plus the assistant message that owns the download index. */ export type SessionArtifactItem = ArtifactMeta & { @@ -11,7 +12,7 @@ function asRecord(value: unknown): Record | null { } function readMessageId(message: Record): string { - return String(message.id || message.request_id || '') + return persistedAssistantId(message) || String(message.request_id || '') } /** diff --git a/frontend/src/utils/steerStreamFork.ts b/frontend/src/utils/steerStreamFork.ts index 23c39678..31ce2027 100644 --- a/frontend/src/utils/steerStreamFork.ts +++ b/frontend/src/utils/steerStreamFork.ts @@ -20,6 +20,23 @@ export function discardSteerPreview(list: ChatMessage[], steerId: string): void if (index >= 0) list.splice(index, 1) } +/** Reconcile older servers that assign their own ID instead of echoing the client UUID. */ +export function reconcileSteerMessageId(list: ChatMessage[], clientId: string, serverId: string): ChatMessage | undefined { + const preview = list.find(m => m.role === 'user' && m.steer_id === clientId) + const received = list.find(m => m.role === 'user' && m.steer_id === serverId) + if (preview && received && preview !== received && preview._steerPending) { + // SSE may have already inserted the persisted row. Keep its position and + // server metadata while preserving mentions from the optimistic message. + if (Array.isArray(preview.mentioned_items) && preview.mentioned_items.length) { + received.mentioned_items = preview.mentioned_items + } + list.splice(list.indexOf(preview), 1) + return received + } + if (preview) preview.steer_id = serverId + return received || preview +} + /** * The row id the server knows this assistant message by. * diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 079c3ff8..7ef19d8f 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -603,6 +603,7 @@ import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue'; import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts'; import { useArtifactArriveMotion } from '@/composables/useArtifactArriveMotion'; import { useChatSandboxPanel } from '@/composables/useChatSandboxPanel'; +import { persistedAssistantId } from '@/utils/steerStreamFork'; import ChatMemoryStep from './ChatMemoryStep.vue'; import { useChatMemoryRow, type UsedMemory } from '@/composables/useChatMemoryRow'; import { countGrepDocuments, groupGrepChunkResults } from '@/utils/grepResultsGroup'; @@ -1025,7 +1026,7 @@ const artifactsCollecting = computed(() => isCollectingSkillArtifacts(props.sess const artifactButtonCollecting = computed(() => artifactsCollecting.value && !hasArtifacts.value); const sessionIdForArtifacts = computed(() => props.sessionId ?? ''); const messageIdForArtifacts = computed(() => - String(props.session?.id || props.session?.request_id || ''), + persistedAssistantId(props.session) || String(props.session?.request_id || ''), ); // Set when the drawer is opened from an inline artifact card in the answer, so // it lands on that file's preview instead of the list. diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index 245263a4..0c6b8458 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -115,6 +115,7 @@ import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue'; import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts'; 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 { artifactIndexFromEventTarget, @@ -233,9 +234,9 @@ const { artifactArrived, onArtifactArriveEnd } = useArtifactArriveMotion(artifac const artifactsCollecting = computed(() => isCollectingSkillArtifacts(props.session)); const artifactButtonCollecting = computed(() => artifactsCollecting.value && !hasArtifacts.value); const messageIdForArtifacts = computed(() => { - // Prefer the persistent message ID; fall back to request_id for the - // in-flight path where the SSE stream still identifies rows by request. - return String((props.session && (props.session.id || props.session.request_id)) || ''); + // Steered segments have synthetic row IDs; artifact APIs address the + // persisted assistant. Keep request_id as the in-flight fallback. + return persistedAssistantId(props.session) || String(props.session?.request_id || ''); }); // Set when the drawer is opened by clicking an inline artifact card, so it // lands directly on that file's preview instead of the list. @@ -535,6 +536,8 @@ onBeforeUnmount(() => { font-size: 16px; // padding: 10px 12px; margin-right: auto; + width: 100%; + min-width: 0; max-width: 100%; box-sizing: border-box; } diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 44b2c435..03aae628 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -183,7 +183,7 @@ import { getSuggestedQuestions } from "@/api/agent/index"; import { deleteTemporaryAttachment, uploadTemporaryAttachment } from '@/api/chat/temporary-attachments'; import { useStream } from '../../api/chat/streame' import { listSteerSession, promoteSteerSession, removeSteerSession, steerSession } from '@/api/chat/steer'; -import { persistedAssistantId, previewSteerMessage, discardSteerPreview } from '@/utils/steerStreamFork'; +import { persistedAssistantId, previewSteerMessage, discardSteerPreview, reconcileSteerMessageId } from '@/utils/steerStreamFork'; import { useMenuStore } from '@/stores/menu'; import { useSettingsStore } from '@/stores/settings'; import { MessagePlugin } from 'tdesign-vue-next'; @@ -873,15 +873,25 @@ const handleSteerMsg = async (value, mentionedItems = [], delivery = 'after', re try { const res = await steerSession(requestSessionId, value, mentionedItems, delivery, expectedId, clientId); if (session_id.value !== requestSessionId) return; - if (res?.status === 'already_injected') { + const serverId = res?.steer_id || clientId; + const received = reconcileSteerMessageId(messagesList, clientId, serverId); + const queued = findSteerQueueItem(clientId); + if (received && !received._steerPending) { + // The SSE receipt can arrive before the HTTP response, including + // when an older backend generated a different steer ID. dropSteerQueueItem(clientId); - const preview = messagesList.find(m => m.steer_id === clientId); + } else if (queued) { + queued.steer_id = serverId; + } + if (res?.status === 'already_injected') { + dropSteerQueueItem(serverId); + const preview = messagesList.find(m => m.steer_id === serverId); if (preview) delete preview._steerPending; MessagePlugin.info(t('input.messages.steerAlreadyInjected')); return; } if (res?.status === 'new_run') { - const item = findSteerQueueItem(clientId); + const item = findSteerQueueItem(serverId); // Still attached to a stream: aborting it to POST AgentQA races the // finishing turn and can start a second engine. Keep the message and // send once the current SSE completes. @@ -892,15 +902,13 @@ const handleSteerMsg = async (value, mentionedItems = [], delivery = 'after', re } return; } - dropSteerQueueItem(clientId); - discardSteerPreview(messagesList, clientId); + dropSteerQueueItem(serverId); + discardSteerPreview(messagesList, serverId); await sendMsg(value, '', mentionedItems); return; } - const item = findSteerQueueItem(clientId); + const item = findSteerQueueItem(serverId); if (item) { - // The server echoes the stable client UUID used by SSE receipts. - if (res?.steer_id) item.steer_id = res.steer_id; item.pending = false; } } catch (e) { diff --git a/frontend/src/views/chat/steerInteraction.test.mjs b/frontend/src/views/chat/steerInteraction.test.mjs index fedea335..d5244810 100644 --- a/frontend/src/views/chat/steerInteraction.test.mjs +++ b/frontend/src/views/chat/steerInteraction.test.mjs @@ -3,7 +3,9 @@ import { readFileSync } from 'node:fs' import { webcrypto } from 'node:crypto' import vm from 'node:vm' import test from 'node:test' -import { previewSteerMessage, discardSteerPreview, forkAfterInjectedUser } from '../../utils/steerStreamFork.ts' +import ts from 'typescript' +import { reactive } from 'vue' +import { previewSteerMessage, discardSteerPreview, forkAfterInjectedUser, reconcileSteerMessageId } from '../../utils/steerStreamFork.ts' const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8') const handlers = source.slice(source.indexOf('const dropSteerQueueItem ='), source.indexOf('let attachingSteerFollowUp =')) @@ -16,8 +18,8 @@ function harness(overrides = {}) { const state = { session_id: { value: 'session' }, currentAssistantMessageId: { value: 'assistant' }, isReplying: { value: true }, isStreaming: { value: true }, - steerQueue: { value: [] }, messagesList: [], crypto: webcrypto, - previewSteerMessage, discardSteerPreview, + steerQueue: { value: [] }, messagesList: reactive([]), crypto: webcrypto, + previewSteerMessage, discardSteerPreview, reconcileSteerMessageId, scrollToBottom() {}, sendMsg() { throw new Error('must not start a second run') }, MessagePlugin: { info() {}, error() {} }, t: key => key, console: { error() {} }, ...overrides, @@ -91,3 +93,63 @@ test('failed promotion restores the after queue and removes only its optimistic assert.equal(h.state.steerQueue.value[0].delivery, 'after') assert.equal(h.state.messagesList.length, 0) }) + +const streamSource = readFileSync(new URL('../../composables/useChatStreamHandler.ts', import.meta.url), 'utf8') +const receiptStart = streamSource.indexOf("case 'user_message_injected': {") +const receiptEnd = streamSource.indexOf("case 'complete':", receiptStart) +assert.ok(receiptStart >= 0 && receiptEnd > receiptStart) +const receipt = ts.transpile(`() => { switch ('user_message_injected') { + ${streamSource.slice(receiptStart, receiptEnd)} +} }`) + +function receiveInjection(h, steerId, userId) { + vm.runInNewContext(receipt, { + messagesList: h.state.messagesList, + message: h.state.messagesList.findLast(m => m.role === 'assistant'), + dataPayload: { steer_id: steerId, user_message_id: userId, content: '写到Docx' }, + data: {}, dataId: 'request', replaySegments: new Map(), + forkAfterInjectedUser, log() {}, emitMessageCreated() {}, onAgentChunkBound() {}, + onUserMessageInjected(id) { + const index = h.state.steerQueue.value.findIndex(item => item.steer_id === id) + if (index >= 0) h.state.steerQueue.value.splice(index, 1) + }, + })() +} + +for (const receiptFirst of [false, true]) { + test(`server-assigned steer ID reconciles the optimistic bubble when SSE arrives ${receiptFirst ? 'before' : 'after'} HTTP`, async () => { + const request = deferred() + const h = harness({ steerSession: () => request.promise }) + h.state.messagesList.push({ id: 'assistant', role: 'assistant', request_id: 'request', is_completed: false }) + const sending = h.handleSteerMsg('写到Docx', [{ id: 'mention' }], 'inject') + if (receiptFirst) receiveInjection(h, 'server-steer', 'persisted-user') + request.resolve({ status: 'queued', steer_id: 'server-steer' }) + await sending + if (!receiptFirst) receiveInjection(h, 'server-steer', 'persisted-user') + const users = h.state.messagesList.filter(m => m.role === 'user') + assert.equal(users.length, 1) + assert.equal(users[0].id, 'persisted-user') + assert.equal(users[0]._steerPending, undefined) + assert.equal(users[0].mentioned_items[0].id, 'mention') + assert.equal(h.state.steerQueue.value.length, 0) + assert.deepEqual(h.state.messagesList.map(m => m.role), ['assistant', 'user', 'assistant']) + }) +} + +test('concurrent identical injects reconcile by their HTTP receipts without merging distinct messages', async () => { + const first = deferred(), second = deferred() + let calls = 0 + const h = harness({ steerSession: () => (++calls === 1 ? first.promise : second.promise) }) + h.state.messagesList.push({ id: 'assistant', role: 'assistant', request_id: 'request', is_completed: false }) + const sendingFirst = h.handleSteerMsg('写到Docx', [{ id: 'first' }], 'inject') + const sendingSecond = h.handleSteerMsg('写到Docx', [{ id: 'second' }], 'inject') + receiveInjection(h, 'server-first', 'user-first') + receiveInjection(h, 'server-second', 'user-second') + second.resolve({ status: 'queued', steer_id: 'server-second' }) + await sendingSecond + first.resolve({ status: 'queued', steer_id: 'server-first' }) + await sendingFirst + const users = h.state.messagesList.filter(m => m.role === 'user') + assert.deepEqual(users.map(m => [m.id, m.mentioned_items[0].id]), [['user-first', 'first'], ['user-second', 'second']]) + assert.equal(h.state.steerQueue.value.length, 0) +})