fix(agent): hide trailing thinking event when it duplicates final answer

The natural-stop path on the backend (observe.go Case 1) emits the same
content twice: once as streaming thinking chunks (from
streamThinkingToEventBus's per-chunk callback) which the frontend merges
into a single thinking event, and once as one big EventAgentFinalAnswer.
The result is that the intermediate-steps tree contains a thinking card
whose content is identical to the answer card rendered below it.

Detect this duplication and hide the offending thinking event from the
tree:

- New utils `normaliseForComparison` and `thinkingEqualsAnswer` perform
  a tolerant comparison: strip <think>…</think> blocks (which leak into
  raw thinking chunks but not into the post-StripThinkBlocks answer),
  strip final-answer wrappers, collapse whitespace, then exact-equal or
  ±2% length with matching head/tail.
- `hiddenThinkingEventIds` (replacing the previous single-id
  `promotedThinkingEventId`) now collects two cases of duplicate
  thinking: the legacy promotion fallback (no answer event present) and
  the natural-stop content-match case.

The final_answer-tool path is unaffected because reasoning thinking
events ("我找到了…让我整理…") and the answer payload have different
content and don't match the equivalence check.
This commit is contained in:
wizardchen
2026-05-07 17:14:32 +08:00
committed by lyingbug
parent 4677caba01
commit 921e4c015a
2 changed files with 90 additions and 17 deletions
+42
View File
@@ -69,3 +69,45 @@ export function unwrapFinalAnswerWrappers(content: string): string {
return changed ? result.trim() : result;
}
const THINK_BLOCK_RE = /<think\b[^>]*>[\s\S]*?<\/think>/gi;
/**
* Normalise content for cross-event comparison. Strips <think>…</think>
* blocks (which appear in raw thinking chunks but not in the final answer
* event), strips final-answer wrappers, and collapses whitespace. Used to
* detect when the natural-stop path emits the same content twice (once as
* streaming thinking chunks and once as a final answer event).
*/
export function normaliseForComparison(content: string): string {
if (!content || typeof content !== 'string') return '';
const stripped = content.replace(THINK_BLOCK_RE, '');
const unwrapped = unwrapFinalAnswerWrappers(stripped);
return unwrapped.replace(/\s+/g, ' ').trim();
}
/**
* Returns true when `thinking` and `answer` represent the same final answer
* after normalisation. Tolerates small differences (≤2% length delta with
* matching head/tail) to absorb chunk-boundary whitespace noise.
*/
export function thinkingEqualsAnswer(thinking: string, answer: string): boolean {
const a = normaliseForComparison(thinking);
const b = normaliseForComparison(answer);
if (!a || !b) return false;
if (a === b) return true;
const maxLen = Math.max(a.length, b.length);
// Require at least ~80 chars of signal to avoid matching trivial prefixes.
if (maxLen < 80) return false;
const lenDelta = Math.abs(a.length - b.length);
if (lenDelta > maxLen * 0.02) return false;
const head = 50;
const tail = 50;
return (
a.slice(0, head) === b.slice(0, head) &&
a.slice(-tail) === b.slice(-tail)
);
}
@@ -385,7 +385,7 @@ import { useAuthStore } from '@/stores/auth';
import { useI18n } from 'vue-i18n';
import i18n from '@/i18n';
import { hydrateProtectedFileImages } from '@/utils/security';
import { unwrapFinalAnswerWrappers } from '@/utils/finalAnswer';
import { unwrapFinalAnswerWrappers, thinkingEqualsAnswer } from '@/utils/finalAnswer';
import {
buildManualMarkdown,
copyTextToClipboard,
@@ -1060,21 +1060,52 @@ const buildFullEventList = (stream: any[]) => {
return result;
};
// When the agent loop ended via natural-stop (no final_answer tool call) and
// we promote the trailing thinking event into a virtual answer card below
// the tree, we must hide that same thinking event from the tree to avoid
// rendering its content twice.
const promotedThinkingEventId = computed<string | null>(() => {
const final = finalContent.value;
if (!final || final.type !== 'thinking') return null;
// Only promote when there's no real answer event content already.
// IDs of thinking events that should NOT be rendered in the intermediate-
// steps tree because their content is already shown as the final answer.
// Two cases produce duplicates:
// 1. `promotedThinkingEventId` — agent loop ended via natural-stop with
// no answer event at all; we promote the trailing thinking into a
// virtual answer card (see displayEvents) and must hide the source
// thinking from the tree.
// 2. Natural-stop path on the backend streams answer chunks as thought
// events first, then re-emits the *same* content as one big answer
// event. The merged thinking event in the tree would duplicate the
// answer card, so detect content-equivalence and hide it.
const hiddenThinkingEventIds = computed<Set<string>>(() => {
const hidden = new Set<string>();
const stream = eventStream.value;
if (!stream || !Array.isArray(stream)) return null;
const hasRealAnswer = stream.some(
(e: any) => e.type === 'answer' && e.content && e.content.trim()
);
if (hasRealAnswer) return null;
return final.event_id || null;
if (!stream || !Array.isArray(stream)) return hidden;
// Case 1: trailing thinking promoted to answer (no answer events present).
const final = finalContent.value;
if (final && final.type === 'thinking') {
const hasRealAnswer = stream.some(
(e: any) => e.type === 'answer' && e.content && e.content.trim()
);
if (!hasRealAnswer && final.event_id) {
hidden.add(final.event_id);
}
}
// Case 2: natural-stop duplicates — answer events carry the same content
// already streamed as thinking chunks. Compare merged thinking events
// against the concatenated answer content and hide on match.
const answerContent = stream
.filter((e: any) => e.type === 'answer' && e.content)
.map((e: any) => e.content)
.join('');
if (answerContent.trim()) {
const merged = buildFullEventList(stream);
for (const e of merged) {
if (e.type !== 'thinking' || !e.event_id || !e.content) continue;
if (hidden.has(e.event_id)) continue;
if (thinkingEqualsAnswer(e.content, answerContent)) {
hidden.add(e.event_id);
}
}
}
return hidden;
});
// Intermediate events (tree children: everything except answer)
@@ -1082,10 +1113,10 @@ const intermediateEvents = computed(() => {
const stream = eventStream.value;
if (!stream || !Array.isArray(stream)) return [];
const result = buildFullEventList(stream);
const promotedId = promotedThinkingEventId.value;
const hidden = hiddenThinkingEventIds.value;
return result.filter((e: any) => {
if (e.type === 'answer' || e.type === 'agent_complete') return false;
if (promotedId && e.type === 'thinking' && e.event_id === promotedId) return false;
if (e.type === 'thinking' && e.event_id && hidden.has(e.event_id)) return false;
return true;
});
});