diff --git a/core/autocomplete/filtering/streamTransforms/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts index 7ab8923fc..b466ae3cd 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.test.ts @@ -157,4 +157,20 @@ describe("stopAtStopTokens", () => { expect(output.join("")).toBe("Hello world!"); }); + + it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => { + const mockStream = createMockStream(["Hello world!STOP"]); + const stopTokens: string[] = [ + "STOP", + "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER", + ]; + const result = stopAtStopTokens(mockStream, stopTokens); + + const output = []; + for await (const char of result) { + output.push(char); + } + + expect(output.join("")).toBe("Hello world!"); + }); }); diff --git a/core/autocomplete/filtering/streamTransforms/charStream.ts b/core/autocomplete/filtering/streamTransforms/charStream.ts index 79fc33a0d..9f37e1f58 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.ts @@ -70,7 +70,8 @@ export async function* noFirstCharNewline(stream: AsyncGenerator) { * 2. Otherwise, buffers incoming chunks and checks for stop tokens. * 3. Yields characters one by one if no stop token is found at the start of the buffer. * 4. Stops yielding and returns if a stop token is encountered. - * 5. After the stream ends, yields any remaining buffered characters. + * 5. After the stream ends, filters encountered stop tokens in remaining buffer. + * 6. Yields any remaining buffered characters. */ export async function* stopAtStopTokens( stream: AsyncGenerator, @@ -106,6 +107,10 @@ export async function* stopAtStopTokens( } } } + // Filter out the possible stop tokens from remaining buffer + stopTokens.forEach((token) => { + buffer = buffer.replace(token, ""); + }); // Yield any remaining characters in the buffer for (const char of buffer) {