diff --git a/apps/sim/lib/chunkers/token-chunker.test.ts b/apps/sim/lib/chunkers/token-chunker.test.ts index d0635391725..07e3183f13e 100644 --- a/apps/sim/lib/chunkers/token-chunker.test.ts +++ b/apps/sim/lib/chunkers/token-chunker.test.ts @@ -54,5 +54,18 @@ describe('TokenChunker', () => { expect(combined).toContain(word) } }) + + it.concurrent('keeps all text when a chunk ends at a space before the overlap', async () => { + const chunker = new TokenChunker({ + chunkSize: 20, + chunkOverlap: 5, + minCharactersPerChunk: 1, + }) + const unbroken = Array.from({ length: 200 }, (_, i) => String.fromCodePoint(0x4e00 + i)) + const chunks = await chunker.chunk(`API ${unbroken.join('')}`) + + const combined = chunks.map((c) => c.text).join('') + expect(unbroken.filter((character) => !combined.includes(character))).toEqual([]) + }) }) }) diff --git a/apps/sim/lib/chunkers/utils.ts b/apps/sim/lib/chunkers/utils.ts index 7672782c563..96e0def8cea 100644 --- a/apps/sim/lib/chunkers/utils.ts +++ b/apps/sim/lib/chunkers/utils.ts @@ -129,7 +129,9 @@ export function* iterateWordBoundaryChunkSpans( } if (stepChars !== undefined) { - const nextPos = pos + Math.max(1, stepChars) + // A window that snapped back to a space ends before `pos + stepChars`; stepping + // past its end would skip the text between them, so never start beyond it. + const nextPos = Math.min(pos + Math.max(1, stepChars), end) if (nextPos >= text.length) break pos = nextPos } else {