From 4099066bf1cddf38073a36dff075aa2419f715ec Mon Sep 17 00:00:00 2001 From: VIOLETee0 <1842771550@qq.com> Date: Tue, 1 Dec 2026 18:26:52 +0800 Subject: [PATCH] Stop streamed text at the earliest matching sequence --- .../src/util/__tests__/stop-sequence.test.ts | 25 +++++++++++++++++++ common/src/util/stop-sequence.ts | 16 +++++++----- 2 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 common/src/util/__tests__/stop-sequence.test.ts diff --git a/common/src/util/__tests__/stop-sequence.test.ts b/common/src/util/__tests__/stop-sequence.test.ts new file mode 100644 index 0000000000..82513b5fec --- /dev/null +++ b/common/src/util/__tests__/stop-sequence.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from 'bun:test' + +import { StopSequenceHandler } from '../stop-sequence' + +test('stops at the earliest sequence regardless of configuration order or chunking', () => { + const text = 'answerhiddentail' + for (const stops of [ + ['', ''], + ['', ''], + ]) { + for (let split = 0; split <= text.length; split++) { + const handler = new StopSequenceHandler(stops) + const first = handler.process(text.slice(0, split)) + const second = handler.process(text.slice(split)) + expect((first.text ?? '') + (second.text ?? '') + handler.flush()).toBe( + 'answer', + ) + expect(second.endOfStream).toBe(true) + expect(handler.process('more output')).toEqual({ + text: null, + endOfStream: true, + }) + } + } +}) diff --git a/common/src/util/stop-sequence.ts b/common/src/util/stop-sequence.ts index c77b0cce47..d9b5383248 100644 --- a/common/src/util/stop-sequence.ts +++ b/common/src/util/stop-sequence.ts @@ -23,14 +23,18 @@ export class StopSequenceHandler { this.buffer += text let longestOverlap = '' + let stopIndex = -1 for (const stopSequence of this.stopSequences) { const index = this.buffer.indexOf(stopSequence) - if (index !== -1) { - this.finished = true - return { - text: this.buffer.slice(0, index), - endOfStream: true, - } + if (index !== -1 && (stopIndex === -1 || index < stopIndex)) { + stopIndex = index + } + } + if (stopIndex !== -1) { + this.finished = true + return { + text: this.buffer.slice(0, stopIndex), + endOfStream: true, } }