From 093c16cbb36725baf2388bcb4fd719c9f929a6c8 Mon Sep 17 00:00:00 2001 From: lyingbug Date: Sun, 20 Sep 2026 13:17:50 +0800 Subject: [PATCH] fix(agent): end the turn when the completion cap truncates an answer (#3449) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(agent): end the turn when the completion cap truncates an answer A round that came back with finish_reason=length and no tool calls used to fall through analyzeResponse as non-terminal. With no tool calls to run, appendToolResults pushed the half-written answer back into the history as a plain assistant message with nothing telling the model to continue, so the next round rewrote the answer from the top, hit the same cap, and repeated until the round budget ran out or the user cancelled. Three guards, each independently load-bearing: - analyzeResponse gains a truncation case: deliver the partial text and end the turn. A cap hit that produced no text at all has nothing to hand over and defers to the existing bounded empty-content retry. No continuation nudge is sent — it only grows the prompt with the discarded fragment, and assistant prefill, the reliable form, is unavailable on most OpenAI-compatible endpoints. - A consecutive-length breaker stops the loop when truncation keeps landing inside tool-call arguments, the one shape that still legitimately loops. - The stuck-loop detector now counts an identical lack of content. A model burning its whole budget on reasoning returns empty every round, which used to land in the else branch and reset the counter, so the guard could never fire on the case that needed it most. The answer event and its Done marker carry a truncated flag through the SSE metadata, and the chat UI shows the same style of notice it already uses for fallback answers. Fixes #3446 * fix(agent): treat unterminated reasoning as no answer and keep the truncation marker Review follow-up on three ways the truncation path could still mislead. An inline block that the cap cut off never gets its closing tag, so the pair regex left it whole and the round looked like it had produced an answer. The truncation case then skipped the empty-content retry it exists for and emitted the chain of thought as the final answer. StripThinkBlocks now drops a dangling through end of input, which is what the streaming splitter already does with the same text, so the two agree on what counts as an answer. The truncation marker only rode on the SSE metadata, and a finished conversation is rebuilt from agent_steps rather than replayed from stream events. A reloaded, shared or re-opened turn therefore lost the notice and its half-written answer looked complete. AgentStep carries the flag now — it is a jsonb column, so no migration — and the frontend marks the rebuilt answer event and message from it. The consecutive-length guard ran before the round was recorded, so a final round of "let me look that up" plus a truncated tool call handed that preamble over as the final answer, with its tool calls never refused and the preamble never retracted from the answer area. The guard now records the round and fails its tool calls the way every other truncated round does, and a response carrying tool calls never donates its text as the answer. --- .../composables/useChatStreamHandler.test.mjs | 62 +++ .../src/composables/useChatStreamHandler.ts | 17 + frontend/src/i18n/locales/en-US.ts | 1 + frontend/src/i18n/locales/ja-JP.ts | 1 + frontend/src/i18n/locales/ko-KR.ts | 1 + frontend/src/i18n/locales/ru-RU.ts | 1 + frontend/src/i18n/locales/zh-CN.ts | 1 + .../chat/components/AgentStreamDisplay.vue | 5 + frontend/src/views/chat/components/botmsg.vue | 6 + internal/agent/const.go | 22 + internal/agent/engine.go | 189 ++++++-- internal/agent/length_truncation_test.go | 419 ++++++++++++++++++ internal/agent/observe.go | 78 +++- internal/agent/tools/strip_think.go | 12 + internal/event/event_data.go | 6 + .../handler/session/agent_stream_handler.go | 7 + internal/types/agent.go | 6 + 17 files changed, 795 insertions(+), 39 deletions(-) create mode 100644 internal/agent/length_truncation_test.go diff --git a/frontend/src/composables/useChatStreamHandler.test.mjs b/frontend/src/composables/useChatStreamHandler.test.mjs index 3b7ecca8..2ee0152d 100644 --- a/frontend/src/composables/useChatStreamHandler.test.mjs +++ b/frontend/src/composables/useChatStreamHandler.test.mjs @@ -236,3 +236,65 @@ test('a superseded prior round does not block or re-seed the new round', () => { assert.equal(message._eventMap.get('r2').content, '正式答案') assert.equal(message.content, '正式答案') }) + +// A round the completion cap cut off marks its agent step. History is rebuilt +// from agent_steps and never replays the live answer events, so the rebuilt +// answer event has to carry the flag forward or a reloaded half-written answer +// looks finished. +const buildReconstruct = () => { + const helperStart = source.indexOf('const agentStepsAreTruncated =') + const start = source.indexOf('const reconstructEventStreamFromSteps = (') + const end = source.indexOf('const handleMsgList = async (', start) + const block = source.slice(helperStart, end) + return vm.runInNewContext( + ts.transpile(`(() => { ${block}; return reconstructEventStreamFromSteps })()`), + { markRaw: (v) => v, steerStepEvents: () => [] }, + ) +} + +test('a truncated agent step marks the rebuilt answer event', () => { + const reconstruct = buildReconstruct() + const steps = [ + { iteration: 0, thought: 'looking it up', tool_calls: [{ id: 'c1', name: 'wiki_read_page' }] }, + { iteration: 1, thought: '', tool_calls: [], truncated: true }, + ] + const events = reconstruct(steps, '1. First point. 2. Second po', true, false, 0, undefined) + const answer = events.filter((e) => e.type === 'answer').at(-1) + assert.equal(answer.content, '1. First point. 2. Second po') + assert.equal(answer.truncated, true) +}) + +test('an ordinary finished turn is not marked truncated', () => { + const reconstruct = buildReconstruct() + const steps = [{ iteration: 0, thought: '', tool_calls: [] }] + const events = reconstruct(steps, 'a complete answer', true, false, 0, undefined) + const answer = events.filter((e) => e.type === 'answer').at(-1) + assert.equal(answer.content, 'a complete answer') + assert.equal(answer.truncated, undefined) +}) + +test('the live answer path carries truncated onto the event and the message', () => { + const chunkStart = source.indexOf("case 'answer':") + const chunk = source.slice(chunkStart, source.indexOf("case 'artifacts_pending'", chunkStart)) + const state = { fullContent: { value: '' } } + const process = vm.runInNewContext( + ts.transpile(`(message, data, dataPayload) => { switch ('answer') { ${chunk} } }`), + { + ...state, + recomposeAgentAnswer: (m) => + (m.agentEventStream || []).filter((e) => e.type === 'answer' && !e.superseded).map((e) => e.content || '').join(''), + log() {}, + onAgentAnswerDone() {}, + isAgentStreamSession: () => true, + loading: { value: true }, + isReplying: { value: true }, + }, + ) + const message = { agentEventStream: [], _eventMap: new Map(), content: '' } + process(message, { content: 'half an answer' }, { event_id: 'r1' }) + assert.equal(message.truncated, undefined) + // The cap is only known at the close, so the Done marker carries it too. + process(message, { content: '' }, { event_id: 'r1', done: true, truncated: true }) + assert.equal(message._eventMap.get('r1').truncated, true) + assert.equal(message.truncated, true) +}) diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts index 3268dada..e055b3d3 100644 --- a/frontend/src/composables/useChatStreamHandler.ts +++ b/frontend/src/composables/useChatStreamHandler.ts @@ -317,6 +317,10 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { return out } + const agentStepsAreTruncated = (agentSteps: unknown[] | undefined) => + Array.isArray(agentSteps) && + agentSteps.some((step) => (step as ChatMessage | undefined)?.truncated === true) + const reconstructEventStreamFromSteps = ( agentSteps: unknown[], messageContent: string, @@ -407,6 +411,11 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { done: true, } if (isFallback) answerEvent.is_fallback = true + // A round the completion cap cut off marks its step. Live streaming + // carries the same fact on the answer event, but history is rebuilt from + // agent_steps and never sees those events, so without this a reloaded + // half-written answer looks finished. + if (agentStepsAreTruncated(agentSteps)) answerEvent.truncated = true events.push(answerEvent) } else if (isCompleted) { events.push({ @@ -459,6 +468,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { ), ) item.hideContent = true + if (agentStepsAreTruncated(item.agent_steps as unknown[])) item.truncated = true } restoreQuickAnswerFlags(item) @@ -934,6 +944,13 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { answerEvent.is_fallback = true message.is_fallback = true } + // The completion cap cut this answer off. The backend sends it on the + // content chunks and again on the Done marker, because an answer that + // streamed live only learns of the cap at the close. + if (dataPayload?.truncated) { + answerEvent.truncated = true + message.truncated = true + } if (data.done && !answerEvent.done) { answerEvent.done = true onAgentAnswerDone?.(message) diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index afa3cd03..cae7aed5 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3701,6 +3701,7 @@ export default { questionMinimapAttachmentPlaceholder: '(Attachment)', referenceChunkCount: '{count} chunk(s)', fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.', + truncatedHint: 'This answer was cut off at the per-response output limit. Above is what the model produced before the cut.', requestInfoTitle: 'Request info', requestInfoRequestId: 'Request ID', requestInfoMessageId: 'Message ID', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 932faed3..6d4cb9c5 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -3701,6 +3701,7 @@ export default { questionMinimapAttachmentPlaceholder: '(添付ファイル)', referenceChunkCount: '{count}件のチャンク', fallbackHint: 'ナレッジベースから関連する内容が見つかりませんでした。上記はモデルの直接回答です。', + truncatedHint: 'モデルの1回あたりの出力上限で回答が途中で打ち切られました。上記は打ち切り前に生成された内容です。', requestInfoTitle: 'リクエスト情報', requestInfoRequestId: 'Request ID', requestInfoMessageId: 'メッセージID', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 7a05c85f..ceb4b230 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3827,6 +3827,7 @@ export default { questionMinimapAttachmentPlaceholder: '(첨부)', referenceChunkCount: '{count}개 청크', fallbackHint: '지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.', + truncatedHint: '모델의 응답당 출력 한도에서 답변이 잘렸습니다. 위 내용은 잘리기 전까지 생성된 부분입니다.', requestInfoTitle: 'Request info', requestInfoRequestId: 'Request ID', requestInfoMessageId: 'Message ID', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 3321ee93..8c77cae7 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3827,6 +3827,7 @@ export default { questionMinimapAttachmentPlaceholder: '(Вложение)', referenceChunkCount: '{count} фрагмент(ов)', fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.', + truncatedHint: 'Ответ обрезан на лимите вывода модели за один ответ. Выше — то, что было создано до обрыва.', requestInfoTitle: 'Request info', requestInfoRequestId: 'Request ID', requestInfoMessageId: 'Message ID', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 8d7eed33..1939eccd 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3829,6 +3829,7 @@ export default { questionMinimapAttachmentPlaceholder: '(附件)', referenceChunkCount: '{count}个片段', fallbackHint: '未从知识库中检索到相关内容,以上为模型直接回答', + truncatedHint: '回答在模型单次输出上限处被截断,以上为截断前已生成的内容', requestInfoTitle: '请求信息', requestInfoRequestId: 'Request ID', requestInfoMessageId: '消息 ID', diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 8f246422..fcdeb7f3 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -418,6 +418,11 @@ + + + + + diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index d92a941a..b8c392bc 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -85,6 +85,12 @@ + + + + + +