Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { aiEventClient } from '@tanstack/ai-event-client'
3import { MEMORY_STATE_EVENT, memoryMiddleware } from '../src'
4import type { StreamChunk } from '@tanstack/ai'
5import type {
6 ChatMiddlewareConfig,
7 ChatMiddlewareContext,
8 FinishInfo,
9 Tool,
10} from '@tanstack/ai'
11import type { MemoryAdapter, MemoryScope, MemoryTurn } from '../src'
12
13const catTool: Tool = {
14 name: 'cat_tool',
15 description: 'A tool about cats.',
16 inputSchema: { type: 'object', properties: {}, additionalProperties: false },
17}
18
19function makeConfig(userText: string): ChatMiddlewareConfig {
20 return {
21 messages: [{ role: 'user', content: userText }],
22 systemPrompts: ['base prompt'],
23 tools: [],
24 }
25}
26
27function makeCtx(
28 config: ChatMiddlewareConfig,
29 deferred: Array<Promise<unknown>>,
30): ChatMiddlewareContext {
31 return {
32 phase: 'init',
33 messages: config.messages,
34 defer: (p: Promise<unknown>) => deferred.push(p),
35 } as unknown as ChatMiddlewareContext
36}
37
38function fakeAdapter(
39 saved: Array<{ scope: MemoryScope; turn: MemoryTurn }>,
40): MemoryAdapter {
41 return {
42 id: 'fake',
43 recall: async () => ({
44 systemPrompt: 'MEMORY: the user likes cats',
45 fragments: [{ text: 'the user likes cats', source: 'f1' }],
46 tools: [catTool],
47 toolGuidance: 'Use cat_tool when relevant.',
48 }),
49 save: async (scope, turn) => {
50 saved.push({ scope, turn })
51 return [{ ok: true }]
52 },
53 }
54}
55
56const scope: MemoryScope = { threadId: 's1', userId: 'u1' }
57
58describe('memoryMiddleware', () => {
59 it('injects recalled systemPrompt + toolGuidance + tools at init', async () => {
60 const mw = memoryMiddleware({ adapter: fakeAdapter([]), scope })
61 const config = makeConfig('tell me about my pets')
62 const result = await mw.onConfig?.(makeCtx(config, []), config)
63
64 expect(result).toBeTruthy()
65 const patch = result as Partial<ChatMiddlewareConfig>
66 expect(patch.systemPrompts).toEqual([
67 'base prompt',
68 'Use cat_tool when relevant.',
69 'MEMORY: the user likes cats',
70 ])
71 expect(patch.tools?.map((t) => t.name)).toEqual(['cat_tool'])
72 })
73
74 it('save-only role skips recall entirely', async () => {
75 const mw = memoryMiddleware({
76 adapter: fakeAdapter([]),
77 scope,
78 role: 'save-only',
79 })
80 const config = makeConfig('hello')
81 const result = await mw.onConfig?.(makeCtx(config, []), config)
82 expect(result).toBeUndefined()
83 })
84
85 it('defers save of the finished turn and reports receipts', async () => {
86 const saved: Array<{ scope: MemoryScope; turn: MemoryTurn }> = []
87 const onSave = vi.fn()
88 const mw = memoryMiddleware({ adapter: fakeAdapter(saved), scope, onSave })
89
90 const deferred: Array<Promise<unknown>> = []
91 const config = makeConfig('remember I like cats')
92 const ctx = makeCtx(config, deferred)
93 // Prime per-request state (captures lastUserText) via onConfig.
94 await mw.onConfig?.(ctx, config)
95
96 const info: FinishInfo = {
97 finishReason: 'stop',
98 duration: 1,
99 content: 'You like cats!',
100 }
101 mw.onFinish?.(ctx, info)
102 await Promise.all(deferred)
103
104 expect(saved).toHaveLength(1)
105 expect(saved[0]?.turn).toEqual({
106 user: 'remember I like cats',
107 assistant: 'You like cats!',
108 })
109 expect(onSave).toHaveBeenCalledOnce()
110 })
111
112 it('emits memory:snapshot after save when the adapter supports inspection', async () => {
113 const base = fakeAdapter([])
114 const inspectable: MemoryAdapter = {
115 ...base,
116 inspect: async () => ({
117 takenAt: '2026-07-22T00:00:00.000Z',
118 data: {
119 records: [{ id: 'r1', text: 'You like cats!', kind: 'message' }],
120 },
121 }),
122 listFacts: async () => [
123 { id: 'r1', text: 'You like cats!', source: 'assistant' },
124 ],
125 }
126 const emit = vi.spyOn(aiEventClient, 'emit').mockImplementation(() => {})
127 try {
128 const mw = memoryMiddleware({ adapter: inspectable, scope })
129 const deferred: Array<Promise<unknown>> = []
130 const config = makeConfig('remember I like cats')
131 const ctx = makeCtx(config, deferred)
132 await mw.onConfig?.(ctx, config)
133 mw.onFinish?.(ctx, {
134 finishReason: 'stop',
135 duration: 1,
136 content: 'You like cats!',
137 })
138 await Promise.all(deferred)
139
140 const snapshotCall = emit.mock.calls.find(
141 (c) => c[0] === 'memory:snapshot',
142 )
143 expect(snapshotCall).toBeTruthy()
144 expect(snapshotCall?.[1]).toMatchObject({
145 adapter: 'fake',
146 takenAt: '2026-07-22T00:00:00.000Z',
147 facts: [{ id: 'r1', text: 'You like cats!' }],
148 })
149 } finally {
150 emit.mockRestore()
151 }
152 })
153
154 it('does not emit memory:snapshot for adapters without inspect', async () => {
155 const emit = vi.spyOn(aiEventClient, 'emit').mockImplementation(() => {})
156 try {
157 const mw = memoryMiddleware({ adapter: fakeAdapter([]), scope })
158 const deferred: Array<Promise<unknown>> = []
159 const config = makeConfig('hi there')
160 const ctx = makeCtx(config, deferred)
161 await mw.onConfig?.(ctx, config)
162 mw.onFinish?.(ctx, {
163 finishReason: 'stop',
164 duration: 1,
165 content: 'hello',
166 })
167 await Promise.all(deferred)
168
169 expect(emit.mock.calls.some((c) => c[0] === 'memory:snapshot')).toBe(
170 false,
171 )
172 } finally {
173 emit.mockRestore()
174 }
175 })
176
177 it('injects one memory:state CUSTOM chunk carrying recall metrics + snapshot', async () => {
178 const inspectable = {
179 ...fakeAdapter([]),
180 inspect: async () => ({
181 takenAt: '2026-07-22T00:00:00.000Z',
182 data: { records: [{ id: 'r1', text: 'likes cats', kind: 'message' }] },
183 }),
184 listFacts: async () => [{ id: 'r1', text: 'likes cats', source: 'user' }],
185 }
186 const mw = memoryMiddleware({ adapter: inspectable, scope })
187 const config = makeConfig('what do I like?')
188 const ctx = makeCtx(config, [])
189 await mw.onConfig?.(ctx, config)
190
191 const runStarted = {
192 type: 'RUN_STARTED',
193 threadId: 't1',
194 runId: 'run1',
195 } as unknown as StreamChunk
196 const out = await mw.onChunk?.(ctx, runStarted)
197
198 expect(Array.isArray(out)).toBe(true)
199 const chunks = out as Array<StreamChunk>
200 expect(chunks[0]).toBe(runStarted)
201 const custom = chunks[1] as Extract<StreamChunk, { type: 'CUSTOM' }>
202 expect(custom.type).toBe('CUSTOM')
203 expect(custom.name).toBe(MEMORY_STATE_EVENT)
204 expect(custom.value).toMatchObject({
205 adapter: 'fake',
206 query: 'what do I like?',
207 recall: { fragmentCount: 1, hasTools: true },
208 snapshot: {
209 takenAt: '2026-07-22T00:00:00.000Z',
210 facts: [{ id: 'r1', text: 'likes cats' }],
211 },
212 })
213
214 // Injected exactly once per turn — a second chunk passes through untouched.
215 const again = await mw.onChunk?.(ctx, runStarted)
216 expect(again).toBeUndefined()
217 })
218
219 it('omits the snapshot in memory:state for adapters without inspect', async () => {
220 const mw = memoryMiddleware({ adapter: fakeAdapter([]), scope })
221 const config = makeConfig('hi')
222 const ctx = makeCtx(config, [])
223 await mw.onConfig?.(ctx, config)
224 const out = (await mw.onChunk?.(ctx, {
225 type: 'RUN_STARTED',
226 } as unknown as StreamChunk)) as Array<StreamChunk>
227 const custom = out[1] as Extract<StreamChunk, { type: 'CUSTOM' }>
228 expect(custom.name).toBe(MEMORY_STATE_EVENT)
229 expect((custom.value as { snapshot?: unknown }).snapshot).toBeUndefined()
230 })
231
232 it('recall failures are non-fatal (no throw, no injection)', async () => {
233 const failing: MemoryAdapter = {
234 id: 'boom',
235 recall: async () => {
236 throw new Error('recall exploded')
237 },
238 save: async () => [{ ok: true }],
239 }
240 const mw = memoryMiddleware({ adapter: failing, scope })
241 const config = makeConfig('hi')
242 const result = await mw.onConfig?.(makeCtx(config, []), config)
243 expect(result).toBeUndefined()
244 })
245})