Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import type {
3 ChatMiddlewareConfig,
4 ChatMiddlewareContext,
5 MetadataStore,
6 ModelMessage,
7 ToolCall,
8} from '@tanstack/ai'
9import { provideMetadata } from '@tanstack/ai'
10import {
11 COMPACTION_ENDED_EVENT,
12 COMPACTION_STARTED_EVENT,
13 COMPACTION_STATE_EVENT,
14 clearToolResults,
15 composeStrategies,
16 estimateMessageTokens,
17 evictOldest,
18 summarizeOldest,
19 withCompaction,
20} from './index'
21
22interface RecordedCustom {
23 name: string
24 value: Record<string, unknown>
25}
26
27function recordingContext(
28 phase: ChatMiddlewareContext['phase'] = 'beforeModel',
29 extras: Partial<ChatMiddlewareContext> = {},
30): { ctx: ChatMiddlewareContext; events: Array<RecordedCustom> } {
31 const events: Array<RecordedCustom> = []
32 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- focused hook stub
33 const ctx = {
34 phase,
35 emitCustomEvent: (name: string, value: Record<string, unknown>) => {
36 events.push({ name, value })
37 },
38 ...extras,
39 } as unknown as ChatMiddlewareContext
40 return { ctx, events }
41}
42
43function runOnConfig(
44 mw: ReturnType<typeof withCompaction>,
45 messages: Array<ModelMessage>,
46 ctx: ChatMiddlewareContext = recordingContext().ctx,
47) {
48 const config: ChatMiddlewareConfig = {
49 messages,
50 systemPrompts: [],
51 tools: [],
52 }
53 return mw.onConfig?.(ctx, config)
54}
55
56function checkpointContext(
57 store: MetadataStore,
58 options: { aborted?: boolean; phase?: ChatMiddlewareContext['phase'] } = {},
59): ChatMiddlewareContext {
60 const recorded = recordingContext(options.phase)
61 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- focused hook stub
62 const ctx = {
63 ...recorded.ctx,
64 threadId: 'thread-1',
65 signal: options.aborted ? AbortSignal.abort() : undefined,
66 capabilities: { markProvided: () => undefined },
67 } as unknown as ChatMiddlewareContext
68 provideMetadata(ctx, store)
69 return ctx
70}
71
72function memoryStore(): MetadataStore {
73 const values = new Map<string, unknown>()
74 return {
75 get: async (namespace, key) => values.get(`${namespace}:${key}`) ?? null,
76 set: async (namespace, key, value) => {
77 values.set(`${namespace}:${key}`, value)
78 },
79 delete: async (namespace, key) => {
80 values.delete(`${namespace}:${key}`)
81 },
82 }
83}
84
85function phaseContext(
86 phase: ChatMiddlewareContext['phase'],
87): ChatMiddlewareContext {
88 return recordingContext(phase).ctx
89}
90
91const text = (role: ModelMessage['role'], content: string): ModelMessage => ({
92 role,
93 content,
94})
95// ~40 tokens each at chars/4.
96const big = (role: ModelMessage['role']) => text(role, 'x'.repeat(160))
97
98const call: ToolCall = {
99 id: 't1',
100 type: 'function',
101 function: { name: 'f', arguments: '{}' },
102}
103
104describe('withCompaction', () => {
105 it('passes through when under the token budget', async () => {
106 const mw = withCompaction({ maxTokens: 1000 })
107 const result = await runOnConfig(mw, [
108 text('user', 'hi'),
109 text('assistant', 'hello'),
110 ])
111 expect(result).toBeUndefined()
112 })
113
114 it('defaults to evictOldest', async () => {
115 const mw = withCompaction({ maxTokens: 100 })
116 const msgs = [big('user'), big('assistant'), big('user'), big('assistant')]
117 const result = await runOnConfig(mw, msgs)
118 const out = result?.providerMessages ?? []
119 expect(out[0]?.content).toContain('omitted')
120 expect(out[out.length - 1]).toBe(msgs[msgs.length - 1])
121 })
122
123 it('reports before/after token and message counts via onCompact', async () => {
124 const onCompact = vi.fn()
125 const mw = withCompaction({ maxTokens: 100, onCompact })
126 await runOnConfig(mw, [
127 big('user'),
128 big('assistant'),
129 big('user'),
130 big('assistant'),
131 ])
132 expect(onCompact).toHaveBeenCalledOnce()
133 const info = onCompact.mock.calls[0]?.[0]
134 expect(info.after).toBeLessThan(info.before)
135 expect(info.messagesAfter).toBeLessThan(info.messagesBefore)
136 })
137
138 it('emits started, state, and ended custom events when compacting', async () => {
139 const mw = withCompaction({ maxTokens: 100 })
140 const { ctx, events } = recordingContext('beforeModel')
141 const msgs = [big('user'), big('assistant'), big('user'), big('assistant')]
142 await runOnConfig(mw, msgs, ctx)
143 expect(events.map((event) => event.name)).toEqual([
144 COMPACTION_STARTED_EVENT,
145 COMPACTION_STATE_EVENT,
146 COMPACTION_ENDED_EVENT,
147 ])
148 const stateValue = events[1]?.value
149 expect(stateValue).toMatchObject({
150 reusedCheckpoint: false,
151 maxTokens: 100,
152 })
153 expect(Array.isArray(stateValue?.dropped)).toBe(true)
154 expect(Array.isArray(stateValue?.result)).toBe(true)
155 expect(
156 Array.isArray(stateValue?.dropped) ? stateValue.dropped.length : 0,
157 ).toBeGreaterThan(0)
158 expect(typeof events[2]?.value.durationMs).toBe('number')
159 })
160
161 it('emits started before summarizeOldest finishes', async () => {
162 let release!: (summary: string) => void
163 const gate = new Promise<string>((resolve) => {
164 release = resolve
165 })
166 const mw = withCompaction({
167 maxTokens: 100,
168 strategy: summarizeOldest({ summarize: () => gate }),
169 })
170 const { ctx, events } = recordingContext('beforeModel')
171 const pending = runOnConfig(
172 mw,
173 [big('user'), big('assistant'), big('user'), big('assistant')],
174 ctx,
175 )
176 await vi.waitFor(() => {
177 expect(events.map((event) => event.name)).toEqual([
178 COMPACTION_STARTED_EVENT,
179 ])
180 })
181 release('the gist')
182 await pending
183 expect(events.map((event) => event.name)).toEqual([
184 COMPACTION_STARTED_EVENT,
185 COMPACTION_STATE_EVENT,
186 COMPACTION_ENDED_EVENT,
187 ])
188 })
189
190 it('does not emit custom events when under the token budget', async () => {
191 const mw = withCompaction({ maxTokens: 1000 })
192 const { ctx, events } = recordingContext('beforeModel')
193 await runOnConfig(mw, [text('user', 'hi')], ctx)
194 expect(events).toEqual([])
195 })
196
197 it('does not compact during init', async () => {
198 const onCompact = vi.fn()
199 const mw = withCompaction({ maxTokens: 100, onCompact })
200 const result = await runOnConfig(
201 mw,
202 [big('user'), big('assistant'), big('user'), big('assistant')],
203 phaseContext('init'),
204 )
205 expect(result).toBeUndefined()
206 expect(onCompact).not.toHaveBeenCalled()
207 })
208
209 it('runs summarize once per beforeModel call with no metadata store', async () => {
210 const summarize = vi.fn(async () => 'the gist')
211 const onCompact = vi.fn()
212 const mw = withCompaction({
213 maxTokens: 100,
214 strategy: summarizeOldest({ summarize, keepRecentTokens: 50 }),
215 onCompact,
216 })
217 const msgs = [big('user'), big('assistant'), big('user'), big('assistant')]
218
219 await runOnConfig(mw, msgs, phaseContext('init'))
220 await runOnConfig(mw, msgs, phaseContext('beforeModel'))
221
222 expect(summarize).toHaveBeenCalledOnce()
223 expect(onCompact).toHaveBeenCalledOnce()
224 })
225
226 it('reuses a persisted checkpoint for an unchanged canonical prefix', async () => {
227 const store = memoryStore()
228 const summarize = vi.fn(async () => 'the gist')
229 const messages = [
230 big('user'),
231 big('assistant'),
232 big('user'),
233 big('assistant'),
234 ]
235 const options = {
236 maxTokens: 100,
237 strategy: summarizeOldest({ summarize, keepRecentTokens: 50 }),
238 strategyKey: 'summary-v1',
239 }
240
241 const first = await runOnConfig(
242 withCompaction(options),
243 messages,
244 checkpointContext(store),
245 )
246 const appended = [...messages, text('user', 'new')]
247 const second = await runOnConfig(
248 withCompaction(options),
249 appended,
250 checkpointContext(store),
251 )
252
253 expect(summarize).toHaveBeenCalledOnce()
254 expect(first?.providerMessages?.[0]?.content).toContain('the gist')
255 expect(second?.providerMessages?.[0]?.content).toContain('the gist')
256 expect(second?.providerMessages?.at(-1)?.content).toBe('new')
257 expect(appended).toHaveLength(5)
258 })
259
260 it('rejects a checkpoint when the canonical prefix changes', async () => {
261 const store = memoryStore()
262 const summarize = vi.fn(async () => 'the gist')
263 const options = {
264 maxTokens: 100,
265 strategy: summarizeOldest({ summarize, keepRecentTokens: 50 }),
266 strategyKey: 'summary-v1',
267 }
268 const messages = [
269 big('user'),
270 big('assistant'),
271 big('user'),
272 big('assistant'),
273 ]
274
275 await runOnConfig(
276 withCompaction(options),
277 messages,
278 checkpointContext(store),
279 )
280 await runOnConfig(
281 withCompaction(options),
282 [text('user', 'changed'.repeat(30)), ...messages.slice(1)],
283 checkpointContext(store),
284 )
285
286 expect(summarize).toHaveBeenCalledTimes(2)
287 })
288
289 it('does not write a checkpoint after cancellation', async () => {
290 const set = vi.fn<MetadataStore['set']>()
291 const store: MetadataStore = {
292 get: async () => null,
293 set,
294 delete: async () => undefined,
295 }
296
297 await runOnConfig(
298 withCompaction({ maxTokens: 100 }),
299 [big('user'), big('assistant'), big('user'), big('assistant')],
300 checkpointContext(store, { aborted: true }),
301 )
302
303 expect(set).not.toHaveBeenCalled()
304 })
305})
306
307describe('evictOldest', () => {
308 it('keeps the recent tail and drops the head', async () => {
309 const mw = withCompaction({
310 maxTokens: 100,
311 strategy: evictOldest({ keepRecentTokens: 50 }),
312 })
313 const msgs = [big('user'), big('assistant'), big('user'), big('assistant')]
314 const out = (await runOnConfig(mw, msgs))?.providerMessages ?? []
315 expect(out[0]?.content).toContain('omitted')
316 expect(out[out.length - 1]).toBe(msgs[msgs.length - 1])
317 })
318
319 it('never lets the tail start with an orphaned tool result', async () => {
320 const assistantCall: ModelMessage = {
321 role: 'assistant',
322 content: 'x'.repeat(160),
323 toolCalls: [call],
324 }
325 const toolResult: ModelMessage = {
326 role: 'tool',
327 content: 'x'.repeat(160),
328 toolCallId: 't1',
329 }
330 const msgs = [big('user'), assistantCall, toolResult, big('user')]
331 const mw = withCompaction({
332 maxTokens: 100,
333 strategy: evictOldest({ keepRecentTokens: 45 }),
334 })
335 const out = (await runOnConfig(mw, msgs))?.providerMessages ?? []
336 expect(out.slice(1).some((m) => m.role === 'tool')).toBe(false)
337 })
338
339 it('keeps the trailing assistant plus tool result when the transcript ends in a tool', async () => {
340 const assistantCall: ModelMessage = {
341 role: 'assistant',
342 content: 'x'.repeat(160),
343 toolCalls: [call],
344 }
345 const toolResult: ModelMessage = {
346 role: 'tool',
347 content: 'x'.repeat(160),
348 toolCallId: 't1',
349 }
350 const msgs = [big('user'), assistantCall, toolResult]
351 const mw = withCompaction({
352 maxTokens: 100,
353 strategy: evictOldest({ keepRecentTokens: 45 }),
354 })
355 const out = (await runOnConfig(mw, msgs))?.providerMessages ?? []
356 expect(out.at(-2)).toBe(assistantCall)
357 expect(out.at(-1)).toBe(toolResult)
358 expect(out.some((m) => m.role === 'tool')).toBe(true)
359 })
360
361 it('keeps a trailing parallel tool-result group with its assistant', async () => {
362 const assistantCall: ModelMessage = {
363 role: 'assistant',
364 content: 'x'.repeat(160),
365 toolCalls: [
366 call,
367 {
368 id: 't2',
369 type: 'function',
370 function: { name: 'g', arguments: '{}' },
371 },
372 ],
373 }
374 const toolA: ModelMessage = {
375 role: 'tool',
376 content: 'x'.repeat(160),
377 toolCallId: 't1',
378 }
379 const toolB: ModelMessage = {
380 role: 'tool',
381 content: 'x'.repeat(160),
382 toolCallId: 't2',
383 }
384 const msgs = [big('user'), assistantCall, toolA, toolB]
385 const mw = withCompaction({
386 maxTokens: 100,
387 strategy: evictOldest({ keepRecentTokens: 45 }),
388 })
389 const out = (await runOnConfig(mw, msgs))?.providerMessages ?? []
390 expect(out.slice(-3)).toEqual([assistantCall, toolA, toolB])
391 })
392})
393
394describe('summarizeOldest', () => {
395 it('replaces the head with a summary', async () => {
396 const summarize = vi.fn(async () => 'the gist')
397 const mw = withCompaction({
398 maxTokens: 100,
399 strategy: summarizeOldest({ summarize, keepRecentTokens: 50 }),
400 })
401 const result = await runOnConfig(mw, [
402 big('user'),
403 big('assistant'),
404 big('user'),
405 big('assistant'),
406 ])
407 expect(summarize).toHaveBeenCalledOnce()
408 expect(result?.providerMessages?.[0]?.role).toBe('assistant')
409 expect(result?.providerMessages?.[0]?.content).toBe(
410 '<untrusted-conversation-summary>\nthe gist\n</untrusted-conversation-summary>',
411 )
412 })
413
414 it('reuses a checkpoint without an explicit strategyKey', async () => {
415 const store = memoryStore()
416 const summarize = vi.fn(async () => 'the gist')
417 const messages = [
418 big('user'),
419 big('assistant'),
420 big('user'),
421 big('assistant'),
422 ]
423 const options = {
424 maxTokens: 100,
425 strategy: summarizeOldest({ summarize, keepRecentTokens: 50 }),
426 }
427
428 await runOnConfig(
429 withCompaction(options),
430 messages,
431 checkpointContext(store),
432 )
433 const second = await runOnConfig(
434 withCompaction(options),
435 [...messages, text('user', 'new')],
436 checkpointContext(store),
437 )
438
439 expect(summarize).toHaveBeenCalledOnce()
440 expect(second?.providerMessages?.at(-1)?.content).toBe('new')
441 })
442})
443
444describe('clearToolResults', () => {
445 const toolMsg = (id: string): ModelMessage => ({
446 role: 'tool',
447 content: 'x'.repeat(400),
448 toolCallId: id,
449 })
450
451 it('stubs old tool results but keeps recent ones and message count', async () => {
452 const msgs: Array<ModelMessage> = [
453 text('user', 'go'),
454 toolMsg('a'),
455 toolMsg('b'),
456 toolMsg('c'),
457 toolMsg('d'),
458 ]
459 const mw = withCompaction({
460 maxTokens: 100,
461 strategy: clearToolResults({ keepRecentToolResults: 2 }),
462 })
463 const out = (await runOnConfig(mw, msgs))?.providerMessages ?? []
464 // Same number of messages — structure is untouched.
465 expect(out.length).toBe(msgs.length)
466 // Oldest two tool results are stubbed.
467 expect(out[1]?.content).toBe('[tool output cleared to save context]')
468 expect(out[2]?.content).toBe('[tool output cleared to save context]')
469 // Two most recent tool results are untouched.
470 expect(out[3]?.content).toBe('x'.repeat(400))
471 expect(out[4]?.content).toBe('x'.repeat(400))
472 })
473
474 it('no-ops when there are not enough tool results to clear', async () => {
475 const msgs: Array<ModelMessage> = [big('user'), toolMsg('a'), big('user')]
476 const mw = withCompaction({
477 maxTokens: 50,
478 strategy: clearToolResults({ keepRecentToolResults: 3 }),
479 })
480 expect(await runOnConfig(mw, msgs)).toBeUndefined()
481 })
482})
483
484describe('composeStrategies', () => {
485 const assistantCall = (id: string): ModelMessage => ({
486 role: 'assistant',
487 content: '',
488 toolCalls: [
489 { id, type: 'function', function: { name: 'f', arguments: '{}' } },
490 ],
491 })
492 const toolMsg = (id: string): ModelMessage => ({
493 role: 'tool',
494 content: 'x'.repeat(800), // ~200 tokens
495 toolCallId: id,
496 })
497 const history = (): Array<ModelMessage> => [
498 text('user', 'HEAD_MARKER'),
499 assistantCall('a'),
500 toolMsg('a'),
501 assistantCall('b'),
502 toolMsg('b'),
503 text('user', 'last'),
504 ]
505
506 it('stops after the first strategy once back under budget', async () => {
507 const mw = withCompaction({
508 maxTokens: 260,
509 strategy: composeStrategies(
510 clearToolResults({ keepRecentToolResults: 1 }),
511 evictOldest({ keepRecentTokens: 50 }),
512 ),
513 })
514 const msgs = history()
515 const out = (await runOnConfig(mw, msgs))?.providerMessages ?? []
516 // Clearing one tool result was enough, so evict never ran:
517 // the head message and full message count survive.
518 expect(out.length).toBe(msgs.length)
519 expect(out.some((m) => m.content === 'HEAD_MARKER')).toBe(true)
520 expect(out[2]?.content).toBe('[tool output cleared to save context]')
521 })
522
523 it('escalates to the next strategy when the first is not enough', async () => {
524 const mw = withCompaction({
525 maxTokens: 60,
526 strategy: composeStrategies(
527 clearToolResults({ keepRecentToolResults: 1 }),
528 evictOldest({ keepRecentTokens: 30 }),
529 ),
530 })
531 const msgs = history()
532 const out = (await runOnConfig(mw, msgs))?.providerMessages ?? []
533 // Clearing was not enough, so evict ran too: the head is dropped.
534 expect(out.some((m) => m.content === 'HEAD_MARKER')).toBe(false)
535 expect(out[0]?.content).toContain('omitted')
536 })
537})
538
539describe('estimateMessageTokens', () => {
540 it('counts content and tool calls', () => {
541 expect(estimateMessageTokens(text('user', 'x'.repeat(40)))).toBe(10)
542 })
543})