Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions packages/core/src/core/geminiChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2583,6 +2583,109 @@ describe('GeminiChat', async () => {
);
});

it('should coalesce overlapping recovery continuation text', async () => {
const streams = [
makeStream([makeChunk([{ text: 'discarded initial' }], 'MAX_TOKENS')]),
makeStream([
makeChunk([{ text: 'Alpha shared recovery suffix' }], 'MAX_TOKENS'),
]),
makeStream([
makeChunk(
[{ text: 'shared recovery suffix and continuation' }],
'STOP',
),
]),
];
let callIndex = 0;
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
async () => streams[callIndex++]!,
);

const stream = await chat.sendMessageStream(
'gemini-3-pro',
{ message: 'write a long essay' },
'prompt-recovery-overlap',
);

for await (const _event of stream) {
// consume
}

const history = chat.getHistory();
const lastEntry = history[history.length - 1]!;
const text = lastEntry.parts
?.map((part) => ('text' in part ? part.text : ''))
.join('');

expect(lastEntry.role).toBe('model');
expect(text).toBe('Alpha shared recovery suffix and continuation');
});

it('should coalesce recovery text that replays a previous tail anchor', async () => {
const streams = [
makeStream([makeChunk([{ text: 'discarded initial' }], 'MAX_TOKENS')]),
makeStream([
makeChunk(
[
{
text: [
'Intro',
'### 常用语法速查',
'| 语法 | 说明 |',
'tail that was truncated',
].join('\n'),
},
],
'MAX_TOKENS',
),
]),
makeStream([
makeChunk(
[
{
text: [
'### 常用语法速查',
'| 语法 | 说明 |',
'new suffix',
].join('\n'),
},
],
'STOP',
),
]),
];
let callIndex = 0;
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
async () => streams[callIndex++]!,
);

const stream = await chat.sendMessageStream(
'gemini-3-pro',
{ message: 'write a long mermaid answer' },
'prompt-recovery-contained-replay',
);

for await (const _event of stream) {
// consume
}

const history = chat.getHistory();
const lastEntry = history[history.length - 1]!;
const text = lastEntry.parts
?.map((part) => ('text' in part ? part.text : ''))
.join('');

expect(text).toBe(
[
'Intro',
'### 常用语法速查',
'| 语法 | 说明 |',
'tail that was truncated',
'new suffix',
].join('\n'),
);
});

it('should skip recovery when truncated turn has a functionCall', async () => {
// Initial stream returns a functionCall + MAX_TOKENS. Escalated stream
// returns the same (functionCall + MAX_TOKENS). Recovery must NOT run
Expand Down
182 changes: 177 additions & 5 deletions packages/core/src/core/geminiChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,176 @@ const OUTPUT_RECOVERY_MESSAGE =
'you were doing. Pick up mid-thought if that is where the cut happened. ' +
'Break remaining work into smaller pieces.';

const OUTPUT_RECOVERY_TAIL_CHARS = 1200;
const RECOVERY_OVERLAP_MAX_SCAN_CHARS = 4000;
const RECOVERY_OVERLAP_MIN_BYTES = 6;
const RECOVERY_STRUCTURAL_OVERLAP_MIN_BYTES = 4;
Comment on lines +124 to +168

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: these magic numbers deserve a sentence of rationale each, the way RECOVERY_CONTAINED_TAIL_LOOKBACK_CHARS and RECOVERY_CONTAINED_PREFIX_MIN_BYTES already get below. Specifically:

  • OUTPUT_RECOVERY_TAIL_CHARS = 1200 — why 1200? (token budget consideration? empirically enough context?)
  • RECOVERY_OVERLAP_MAX_SCAN_CHARS = 4000 — caps the inner loop; worth saying so.
  • RECOVERY_OVERLAP_MIN_BYTES = 6 — minimum length before a plain-text overlap is treated as significant (presumably to avoid coincidental short shared suffixes like ". " or "the ").
  • RECOVERY_STRUCTURAL_OVERLAP_MIN_BYTES = 4 — lower floor when the overlap contains Markdown structure chars; explain why structural overlaps get a lower bar.

Future readers will need to adjust these and the reasoning shouldn't have to be reverse-engineered from the tests.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call — done in 3663e8b. Each of the four constants now has a JSDoc block explaining the rationale:

  • OUTPUT_RECOVERY_TAIL_CHARS = 1200 — pragmatic balance: large enough for ~200–400 tokens of trailing prose or a multi-row Markdown table to give the model coherent resume context, small enough to stay well under provider input budgets even combined with the rest of history.
  • RECOVERY_OVERLAP_MAX_SCAN_CHARS = 4000 — hard cap on both the suffix-anchored overlap scan and the contained-prefix scan, so recovery dedup stays O(min(prev, cont, 4000)) in iteration count.
  • RECOVERY_OVERLAP_MIN_BYTES = 6 — minimum bytes for a plain-text overlap to count as significant; explicitly calls out the ". "/"the "/", and " false-positive class your comment named.
  • RECOVERY_STRUCTURAL_OVERLAP_MIN_BYTES = 4 — lower floor when the overlap contains #/|/backtick/\n, since those don't collide coincidentally the way short prose does.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — added a JSDoc block per constant in 3663e8ba. Each rationale captures the angle you flagged:

  • OUTPUT_RECOVERY_TAIL_CHARS = 1200 — large enough for ~200–400 tokens of trailing context (or a multi-row table), small enough to stay under any provider's input budget alongside the rest of history.
  • RECOVERY_OVERLAP_MAX_SCAN_CHARS = 4000 — explicit hard cap on the inner loops so dedup stays O(min(previous, continuation, 4000)).
  • RECOVERY_OVERLAP_MIN_BYTES = 6 — exactly the ". "/"the " false-positive floor you suggested.
  • RECOVERY_STRUCTURAL_OVERLAP_MIN_BYTES = 4 — explains why structural overlaps get a lower bar ("| a ", "## " are almost certainly replayed block markers).

See geminiChat.ts L116-L153.


function byteLength(text: string): number {
return Buffer.byteLength(text, 'utf8');
}

function isSignificantRecoveryOverlap(overlap: string): boolean {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] isSignificantRecoveryOverlap character class [#|\\n]matches#, `` ``, |, or `\n` anywhere in the overlap string. This means prose fragments like `"C# programming"` (15 bytes), `"tag #xyz"` (9 bytes), or `"see `backtick`"` (21 bytes) qualify for the lowered 4-byte structural floor instead of the 6-byte prose floor.

Impact: Minimal — the gap is only 2 bytes and coincidence at truncation boundaries is rare. This is primarily a classification-accuracy concern: the implementation is looser than the JSDoc's "structural anchors" implies.

Suggested fix: Scope to Markdown contexts (e.g., /(^|\n)#{1,6}\s/ for headings) or add a comment acknowledging the intentional over-classification and its negligible risk.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented in 25ea94e (no behavior change).

Taking your "add a comment acknowledging the intentional over-classification" path rather than scoping to Markdown contexts. Reasoning: the 4-byte structural floor vs the 6-byte prose floor only differs by a 2-byte window. Realistic prose at 4–5 bytes containing #/|/`/\n (e.g. "C#dev", "a|b|c") qualifying structurally requires that exact fragment to be identical at the truncation boundary on both sides — extraordinarily rare in practice, and the prose floor (6 bytes + 4 chars) catches anything longer. Tightening the char-class would add code complexity without changing real-world recovery outcomes.

The new inline comment makes the trade-off explicit so future readers don't have to reverse-engineer the intent.

const overlapBytes = byteLength(overlap);
const hasMarkdownStructure = /[#|`\n]/.test(overlap);
return (
overlapBytes >= RECOVERY_OVERLAP_MIN_BYTES ||
(hasMarkdownStructure &&
overlapBytes >= RECOVERY_STRUCTURAL_OVERLAP_MIN_BYTES)
);
}

function findContainedRecoveryPrefixReplayLength(
previousText: string,
continuationText: string,
): number {
const previousTail =
previousText.length > RECOVERY_OVERLAP_MAX_SCAN_CHARS
? previousText.slice(-RECOVERY_OVERLAP_MAX_SCAN_CHARS)
: previousText;
const maxPrefix = Math.min(
previousTail.length,
continuationText.length,
RECOVERY_OVERLAP_MAX_SCAN_CHARS,
);

for (let length = maxPrefix; length > 0; length -= 1) {
const prefix = continuationText.slice(0, length);
if (isSignificantRecoveryOverlap(prefix) && previousTail.includes(prefix)) {
return length;
}
}

return 0;
}

function getRecoveryContinuationSuffix(
previousText: string,
continuationText: string,
): string {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] getRecoveryContinuationSuffix 的空输入守卫分支 (previousText.length === 0 || continuationText.length === 0) 未被测试覆盖。若该分支损坏,空字符串场景下的合并行为可能异常。

Suggested change
): string {
// 建议添加测试:previousText='' 或 continuationText='',断言返回 continuationText 原样

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 549f27a — prompt-recovery-thought-only exercises the empty-text guard end-to-end (previous turn has only a thought part, so getPlainTextFromParts returns ''). The continuation is asserted to pass through verbatim, and the same test verifies that buildOutputRecoveryMessage does NOT append a <previous_response_suffix> block when there's no plain text to anchor on.

if (previousText.length === 0 || continuationText.length === 0) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The continuationText.length === 0 sub-path of the empty-input guard in getRecoveryContinuationSuffix is untested. The previousText.length === 0 path is covered (via prompt-recovery-thought-only), but a scenario where the continuation text part is empty (e.g., thought-only continuation) would exercise the || short-circuit. If this guard regresses, empty continuation text would flow into the endsWith and scan logic.

Consider adding a test where the continuation turn has only thought parts (no text parts), asserting continuationText passes through verbatim.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

@chiga0 chiga0 May 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looked at this carefully — the continuationText.length === 0 sub-path is defensive-only and unreachable from the production caller, so a "thought-only continuation" test would actually skip the call entirely rather than exercise the guard. Tracing the flow:

appendRecoveryContinuationParts only invokes getRecoveryContinuationSuffix when both findLastPlainTextPartIndex(mergedParts) >= 0 and nextParts.findIndex(isPlainTextPart) >= 0. A thought-only continuation would have continuationTextIndex < 0, the if (… && continuationTextIndex >= 0) block would be skipped, and getRecoveryContinuationSuffix would never run — the empty-input guard inside it is never hit from production. The same applies to previousText.length === 0 (the round-6 reply pointing at prompt-recovery-thought-only was technically imprecise: that test covers buildOutputRecoveryMessage's previousText.trim().length === 0 branch, not the guard inside getRecoveryContinuationSuffix).

Rather than add a synthetic test that exports an internal helper just to hit defensive-only code, I documented the intent in 556b015. The new JSDoc on getRecoveryContinuationSuffix explicitly calls out that the empty-input guard is defensive only — kept in place so a future refactor or direct unit-test caller bypassing the production filter cannot crash, but not reachable from the live recovery pipeline. If you'd still prefer an export + direct unit test for paranoia, happy to add it — but the JSDoc makes the contract explicit either way.

return continuationText;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] getRecoveryContinuationSuffix 的完全重叠守卫分支 (previousText.endsWith(continuationText) && isSignificantRecoveryOverlap) 未被测试。当续写与上一轮末尾完全相同时应返回 '',但该路径未被直接验证。

Suggested change
}
// 建议添加测试:previousText='Hello world', continuationText='world'(≥6字节),断言返回 ''

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 549f27a — prompt-recovery-full-overlap covers exactly this branch: previous text ends with tail-fragment, continuation is tail-fragment (≥ RECOVERY_OVERLAP_MIN_BYTES), and the test asserts the merged history is just the previous text with no duplication appended (i.e. getRecoveryContinuationSuffix returned '').


if (
previousText.endsWith(continuationText) &&
isSignificantRecoveryOverlap(continuationText)
) {
return '';
}

const maxOverlap = Math.min(
previousText.length,
continuationText.length,
RECOVERY_OVERLAP_MAX_SCAN_CHARS,
);

for (let length = maxOverlap; length > 0; length -= 1) {
const overlap = continuationText.slice(0, length);
if (
isSignificantRecoveryOverlap(overlap) &&
previousText.endsWith(overlap)
) {
return continuationText.slice(length);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] previousLastPart.text += suffix 原地修改 history 中 part 对象的 text 属性。虽然创建了新数组,但元素是共享引用。若未来有代码缓存 part 引用,将产生难以调试的不一致。建议创建新对象:mergedParts[mergedParts.length - 1] = { ...previousLastPart, text: previousLastPart.text + suffix }

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 08f2abd. Replaced the in-place previousLastPart.text += suffix with a fresh-allocated part:

mergedParts[previousTextIndex] = {
  ...previousTextPart,
  text: previousTextPart.text + suffix,
};

Currently no downstream caller appears to cache part references across the recovery merge, but the mutation invariant was fragile and the allocation is essentially free, so worth fixing defensively. (The same change happens to be necessary for the [Critical] line-404 fix, since the new code splices into nextParts and we no longer hold a stable boundary index.)

}
}
Comment on lines +359 to +367

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perf note (non-blocking): this loop is O(n²) — up to RECOVERY_OVERLAP_MAX_SCAN_CHARS (4000) iterations, each doing previousText.endsWith(overlap) (O(m)) plus byteLength(overlap) (also O(m)) inside isSignificantRecoveryOverlap. Worst-case ~16M char ops per recovery event. Fine for the current scale, but worth being aware of if recovery tails ever grow.

If you ever want to optimize: byteLength can be hoisted (the overlap grows monotonically from the previous iteration when scanning down) and the endsWith check could be replaced by precomputing a Z-array / failure function on continuationText and scanning once. Not needed today.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it's non-blocking — opted to document rather than refactor in this PR to keep the change focused on review polish. Added an inline comment in 3663e8b above the loop that:

  1. Names the O(n²) characteristic explicitly (RECOVERY_OVERLAP_MAX_SCAN_CHARS iterations × O(m) per endsWith + byteLength).
  2. Quantifies the current worst case (~16M char-ops per recovery event at the 4000-char cap) and notes why that's fine today (recovery is rare, cap is small).
  3. Records the Z-array / failure-function rewrite as the documented next step if the cap ever grows materially.

Happy to do the actual optimization in a follow-up if/when the scan cap becomes a real concern — keeping this PR scoped to the dedup correctness work felt cleaner than mixing in a perf rewrite that isn't needed yet.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it's fine at current scale — keeping the simple loop as-is. Did add an inline comment in 3663e8ba making the bound explicit so the next reader doesn't have to derive it:

Worst-case complexity here is O(n²): up to RECOVERY_OVERLAP_MAX_SCAN_CHARS iterations, each calling previousText.endsWith(overlap) plus byteLength(overlap) (both O(m)). At the current 4000-char scan cap that is ~16M char-ops per recovery event, which is fine because recovery is rare and the cap is small. If the cap ever grows materially, this can be rewritten with a precomputed Z-array / failure function on continuationText to scan once instead of repeatedly slicing/comparing.

See L285-L291. Recovery only fires after a MAX_TOKENS truncation (rare per session), so the ~16M-op worst case is not on any hot path.


// Providers/models frequently resume a MAX_TOKENS recovery from an anchor
// that appears near the tail of the previous response, rather than from the
// exact last byte. Drop that replayed leading prefix before coalescing the
// recovery model turn into durable history; otherwise later turns inherit
// duplicated Markdown tables/prose even if the live UI suppresses them.
const containedPrefixLength = findContainedRecoveryPrefixReplayLength(
previousText,
continuationText,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The newline-normalization path in getRecoveryContinuationSuffix (when replayedPrefix ends with newline, previousText does not, and suffix does not start with newline) is untested. Both existing contained-prefix tests use prefixes that do NOT end with a newline, so the newline-prepend block is never entered. If the three-condition normalization breaks, no test catches it.

Consider adding a test: previousText ends without newline (e.g., ### Section), continuation starts with ### Section followed by newline and more text, asserting coalesced text has no duplicate anchor and the newline separator is preserved.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a regression test in 556b015. The new prompt-recovery-newline-normalization test exercises exactly the three-condition branch: previous is 'Intro paragraph.\n### Section' (no trailing newline), continuation is '### Section\nbody prose continuation' so replayedPrefix ends with \n, previousText does NOT, and suffix does NOT start with \n. The assertion text === '${previous}\nbody prose continuation' would fail (missing separator → '### Sectionbody prose continuation') if the normalization branch regressed.

);
if (containedPrefixLength > 0) {
const replayedPrefix = continuationText.slice(0, containedPrefixLength);
let suffix = continuationText.slice(containedPrefixLength);
if (
suffix.length > 0 &&
replayedPrefix.endsWith('\n') &&
!previousText.endsWith('\n') &&
!suffix.startsWith('\n')
) {
suffix = `\n${suffix}`;
}
return suffix;
}

return continuationText;
}

function isPlainTextPart(part: Part | undefined): part is Part & {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] isPlainTextPart is a near-duplicate of the existing isValidNonThoughtTextPart (line 412), but omits three guards: thoughtSignature, inlineData, and fileData. It also uses stricter equality (part.thought !== true) vs the existing function's truthiness check (!part.thought). Two nearly-identical guard functions with subtly different semantics create a maintenance trap — future bugfixes to one will likely miss the other. Consider wrapping isValidNonThoughtTextPart or adding a comment explaining why the checks intentionally diverge.

— deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — fixed in 24582d4. isPlainTextPart now delegates to isValidNonThoughtTextPart, so the recovery-merge path and the consolidated-history path (line 1323) agree on what counts as plain text. The type predicate is preserved at the wrapper level for callers that rely on part.text: string narrowing; the underlying guards (thought, thoughtSignature, function*, inlineData, fileData) now live in one place.

text: string;
} {
return (
part !== undefined &&
typeof part.text === 'string' &&
part.thought !== true &&
part.functionCall === undefined &&
part.functionResponse === undefined
);
}

function getPlainTextFromParts(parts: Part[] | undefined): string {
return (parts ?? [])
.filter(isPlainTextPart)
.map((part) => part.text)
.join('');
}

function buildOutputRecoveryMessage(previousModelTurn: Content | undefined) {
const previousText =
previousModelTurn?.role === 'model'
? getPlainTextFromParts(previousModelTurn.parts)
: '';
if (previousText.trim().length === 0) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] buildOutputRecoveryMessage 的空文本分支 (previousText.trim().length === 0) 未被测试。当上一轮模型回复无有效文本时(如仅有 thought part),该分支应返回原始 OUTPUT_RECOVERY_MESSAGE 而不附加 <previous_response_suffix> 块。

Suggested change
if (previousText.trim().length === 0) {
// 建议添加测试:上一轮 parts 仅为 [{thought: true}] 或空文本,验证恢复消息不包含 <previous_response_suffix> 块

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 549f27a — same prompt-recovery-thought-only test: it captures the recovery user-turn payload from the mock and asserts recoveryMessage contains the Output token limit hit string but does NOT contain <previous_response_suffix>. That covers the previousText.trim().length === 0 branch in buildOutputRecoveryMessage.

return OUTPUT_RECOVERY_MESSAGE;
}

const tail =
previousText.length > OUTPUT_RECOVERY_TAIL_CHARS
? previousText.slice(-OUTPUT_RECOVERY_TAIL_CHARS)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] buildOutputRecoveryMessage 截断分支(previousText.slice(-OUTPUT_RECOVERY_TAIL_CHARS),即前一个回复 >1200 字符时)未被测试覆盖。这是一条核心生产路径,但所有新测试的前置响应均较短(最长约 540 字符),slice(-1200) 与多字节字符的交互未被验证。

建议添加测试:使用 'x'.repeat(1300) 作为前置响应,通过捕获 generateContentStream 参数断言 <previous_response_suffix> 块包含被截断的 1200 字符尾部。

— deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — added a regression test in 7bd70dc. It uses a 1300-char previous response ('A'.repeat(100) + 'B'.repeat(1200)), captures the recovery user-turn payload, and asserts the <previous_response_suffix> block contains exactly the trailing 1200 chars and that the 100-char head does not leak. This locks down the previousText.slice(-OUTPUT_RECOVERY_TAIL_CHARS) branch.

: previousText;

return (
`${OUTPUT_RECOVERY_MESSAGE}\n\n` +
'The previous assistant response ended with this exact suffix. ' +
'Do not repeat any line, table row, code line, or prose that already ' +
'appears in it; output only text that comes after this suffix:\n\n' +

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] buildOutputRecoveryMessage embeds raw model output inside <previous_response_suffix>...</previous_response_suffix> pseudo-XML tags without escaping. If the model's own response happens to contain the literal string </previous_response_suffix> (e.g., when generating XML/HTML examples), the recovery prompt structure breaks — the model would see a prematurely closed tag and misinterpret the suffix boundary. Low collision probability, but cheap to fix: escape </ as \<\/ before embedding, or switch to a delimiter with lower collision risk (e.g., a hash-delimited block).

— deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — fixed in 24582d4. Added sanitizeRecoverySuffixTail which neutralizes any literal <previous_response_suffix> / </previous_response_suffix> strings inside the tail by inserting a zero-width space (U+200B) between the angle bracket and the rest of the tag. The text remains visually identical to the model and the recovery instruction's intent is preserved, but the literal byte sequence no longer collides with our delimiter scan.

Regression test prompt-recovery-delimiter-collision asserts the recovery prompt has exactly one opening and one closing delimiter even when the previous response contains a raw </previous_response_suffix>. Went with sanitization over a random-nonce delimiter to keep the change minimal and the prompt text deterministic across runs.

'<previous_response_suffix>\n' +
tail +
'\n</previous_response_suffix>'
);
}

function appendRecoveryContinuationParts(
previousParts: Part[] | undefined,
continuationParts: Part[] | undefined,
): Part[] {
const mergedParts = [...(previousParts ?? [])];
const nextParts = [...(continuationParts ?? [])];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] appendRecoveryContinuationParts 检查 continuationFirstPart(即 nextParts[0])是否为纯文本来决定是否去重。但 processStreamResponse 以 [thoughtPart?, ...consolidatedHistoryParts] 的顺序构建 parts。当思维模型(如 gemini-2.5-pro)从 MAX_TOKENS 恢复时,续写的第一个 part 是 thought part(thought: true),isPlainTextPart 返回 false,整个去重代码块被跳过,重复文本泄漏到历史记录中。

Suggested change
const nextParts = [...(continuationParts ?? [])];
const prevTextIdx = findLastIndex(mergedParts, isPlainTextPart);
const contTextIdx = nextParts.findIndex(isPlainTextPart);
if (prevTextIdx >= 0 && contTextIdx >= 0) {
const suffix = getRecoveryContinuationSuffix(
mergedParts[prevTextIdx].text,
nextParts[contTextIdx].text,
);
if (suffix.length > 0) {
mergedParts[prevTextIdx].text += suffix;
}
nextParts.splice(contTextIdx, 1);
}

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed real bug — traced the part ordering in processStreamResponse (model turn parts = [thoughtContentPart?, ...consolidatedHistoryParts]), so for thinking models the first continuation part is the recovery turn's thought and the dedup block was being skipped wholesale.

Fixed in 08f2abd by scanning both sides for the plain-text anchor instead of locking onto the boundary indices, and splicing the matched text part instead of shifting the head. Added a regression test (should dedup recovery continuation when the continuation begins with a thought part) that mirrors the exact [thought, text] shape processStreamResponse produces.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] appendRecoveryContinuationParts has an implicit, undocumented dependency on processStreamResponse's text-part consolidation (lastPart.text += part.text). It assumes the last plain-text part in history contains ALL text output from that turn. If someone refactors processStreamResponse to remove in-place consolidation (e.g., for immutability), the dedup logic would silently break, comparing continuation against only the last unconsolidated text fragment and missing real overlaps. No compile-time or runtime error would flag this.

Consider adding a prominent comment above appendRecoveryContinuationParts documenting this coupling, and an integration test that verifies dedup works even when history contains multiple small adjacent text parts (bypassing consolidation).

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call — documented in 556b015. Added a JSDoc block above appendRecoveryContinuationParts titled Coupling with processStreamResponse that explicitly states the function assumes its parts arrays came from processStreamResponse's in-place text-part consolidation (lastPart.text += part.text), notes that only the last plain-text part of previousParts and the first plain-text part of continuationParts are inspected, and warns that any refactor emitting multiple adjacent unconsolidated text parts would silently miss real overlaps. The doc-block closes by noting both functions live in this file precisely so the coupling is reviewable in a single window.

Re: the integration test for multiple adjacent unconsolidated text parts — deferring. Such an array shape is unreachable from the live recovery pipeline (every callsite of appendRecoveryContinuationParts is coalesceRecoveryPairs, which feeds parts produced by processStreamResponse), so the test would need to bypass the recovery loop entirely and call appendRecoveryContinuationParts directly. Exporting an internal helper purely to document a "what if processStreamResponse changes" invariant adds API surface for a hypothetical regression; the JSDoc is the load-bearing signal here. Happy to revisit if the consolidation logic ever moves toward immutability.

const previousLastPart = mergedParts[mergedParts.length - 1];
const continuationFirstPart = nextParts[0];

if (
isPlainTextPart(previousLastPart) &&
isPlainTextPart(continuationFirstPart)
) {
const suffix = getRecoveryContinuationSuffix(
previousLastPart.text,
continuationFirstPart.text,
);
if (suffix.length > 0) {
previousLastPart.text += suffix;
}
nextParts.shift();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reads as if nextParts.shift() could be a bug at first glance because it runs even when suffix.length === 0. It's correct — empty suffix means the continuation's first text part was a complete replay of the previous tail and should be dropped — but a one-line comment would save the next reader a double-take, e.g.:

// Always shift the first continuation text part: a non-empty suffix has
// already been appended to previousLastPart, and an empty suffix means
// the part was a pure replay and should be discarded.
nextParts.shift();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call — added the explanatory comment in 3663e8b, very close to your suggested wording:

if (suffix.length > 0) {
  previousLastPart.text += suffix;
}
// Always drop the first continuation text part: a non-empty suffix has
// already been appended to previousLastPart above, and an empty suffix
// means the part was a pure replay of the previous tail and should be
// discarded so it does not duplicate into history.
nextParts.shift();

Saves the double-take exactly where you flagged it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed intentional, and added the clarifying comment you suggested (slightly reworded) in 3663e8ba:

// Always drop the first continuation text part: a non-empty suffix has
// already been appended to previousLastPart above, and an empty suffix
// means the part was a pure replay of the previous tail and should be
// discarded so it does not duplicate into history.
nextParts.shift();

See L419-L423. The two cases (non-empty suffix already merged vs. empty suffix = pure replay) both want the part gone, so the unconditional shift() is correct — just non-obvious without the note.

}

return [...mergedParts, ...nextParts];
}

/**
* Options for retrying on rate-limit throttling errors returned as stream content.
* Starts at 60s to match DashScope's per-minute quota window, then backs off
Expand Down Expand Up @@ -777,7 +947,9 @@ export class GeminiChat {
// (pushed by processStreamResponse). Push a recovery user
// message so the model sees its partial output and continues.
self.history.push(
createUserContent([{ text: OUTPUT_RECOVERY_MESSAGE }]),
createUserContent([
{ text: buildOutputRecoveryMessage(lastEntry) },
]),
);
// Signal UI/turn to clear pending (incomplete) tool calls.
// isContinuation tells the UI to keep the text buffer so the
Expand Down Expand Up @@ -1204,10 +1376,10 @@ export class GeminiChat {
return;
}

precedingModel.parts = [
...(precedingModel.parts ?? []),
...(modelContinuation.parts ?? []),
];
precedingModel.parts = appendRecoveryContinuationParts(
precedingModel.parts,
modelContinuation.parts,
);
// Drop the (userRecovery, modelContinuation) pair.
this.history.splice(len - 2, 2);
}
Expand Down
Loading