Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

memory.test.ts

347 lines10.6 KB

1import { describe, expect, it } from 'vitest'
2import {
3 memoryLogState,
4 memoryLogStore,
5 memoryPersistence,
6} from '../src/memory'
7import { defineAIPersistence } from '../src/types'
8​
9describe('memoryPersistence', () => {
10 it('returns a namespaced AIPersistence with every state store present', () => {
11 const p = memoryPersistence()
12 expect(p.stores.messages).toBeDefined()
13 expect(p.stores.activities).toBeDefined()
14 expect(p.stores.runs).toBeDefined()
15 expect(p.stores.interrupts).toBeDefined()
16 expect(p.stores.metadata).toBeDefined()
17 expect(p.stores.log).toBeDefined()
18 })
19​
20 it('exposes the complete state store set (no locks)', () => {
21 expect(Object.keys(memoryPersistence().stores).sort()).toEqual([
22 'activities',
23 'artifacts',
24 'blobs',
25 'generationRuns',
26 'interrupts',
27 'log',
28 'messages',
29 'metadata',
30 'runs',
31 'sessions',
32 ])
33 })
34​
35 it('defineAIPersistence is an identity helper', () => {
36 const persistence = memoryPersistence()
37 expect(defineAIPersistence(persistence)).toBe(persistence)
38 })
39​
40 describe('runs', () => {
41 it('createOrResume is idempotent and update patches status', async () => {
42 const { runs } = memoryPersistence().stores
43 const a = await runs!.createOrResume({
44 runId: 'r1',
45 threadId: 't1',
46 startedAt: 100,
47 })
48 expect(a.status).toBe('running')
49 // Resume returns the SAME record, not a fresh one.
50 const b = await runs!.createOrResume({
51 runId: 'r1',
52 threadId: 't1',
53 startedAt: 999,
54 })
55 expect(b.startedAt).toBe(100)
56​
57 await runs!.update('r1', { status: 'completed', finishedAt: 200 })
58 const got = await runs!.get('r1')
59 expect(got?.status).toBe('completed')
60 expect(got?.finishedAt).toBe(200)
61 })
62​
63 it('implements the optional listByThread and listReclaimable methods', async () => {
64 const { runs } = memoryPersistence().stores
65 // `memoryPersistence()` is annotated `ChatPersistence`, so `runs` is typed
66 // as the bare `RunStore` interface and the optional methods come back as
67 // possibly-undefined even though this backend implements them. Assert
68 // their presence first: that is the feature detection every consumer of
69 // the contract performs, and it turns a genuine omission into a stated
70 // expectation instead of an opaque `TypeError` at the call site.
71 const listByThread = runs.listByThread?.bind(runs)
72 const listReclaimable = runs.listReclaimable?.bind(runs)
73 if (!listByThread || !listReclaimable) {
74 throw new Error(
75 'MemoryRunStore must implement listByThread and listReclaimable; ' +
76 'they are the only optional RunStore methods this backend promises.',
77 )
78 }
79​
80 await runs.createOrResume({ runId: 'a', threadId: 't1', startedAt: 2 })
81 await runs.createOrResume({ runId: 'b', threadId: 't1', startedAt: 1 })
82 expect((await listByThread('t1')).map((r) => r.runId)).toEqual(['b', 'a'])
83​
84 await runs.update('a', { detachedSince: 1_000 })
85 const reclaimable = await listReclaimable({
86 now: 10_000,
87 ttlMs: 5_000,
88 })
89 expect(reclaimable.map((r) => r.runId)).toEqual(['a'])
90 })
91 })
92​
93 describe('messages', () => {
94 const twoMessageTranscript = [
95 { role: 'user', content: 'first' },
96 { role: 'assistant', content: 'second' },
97 ] as const
98​
99 async function saveTwoMessageThread() {
100 const { messages } = memoryPersistence().stores
101 await messages.saveThread('t-two', [...twoMessageTranscript])
102 return messages
103 }
104​
105 it('round-trips a thread transcript', async () => {
106 const { messages } = memoryPersistence().stores
107 expect(await messages!.loadThread('t1')).toEqual([])
108 await messages!.saveThread('t1', [{ role: 'user', content: 'hi' }])
109 expect(await messages!.loadThread('t1')).toEqual([
110 { role: 'user', content: 'hi' },
111 ])
112 })
113​
114 it('returns the full saved array when loadThread is called with no options', async () => {
115 const messages = await saveTwoMessageThread()
116 const loaded = await messages.loadThread('t-two')
117 expect(Array.isArray(loaded)).toBe(true)
118 expect(loaded).toEqual(twoMessageTranscript)
119 })
120​
121 it('does not throw when loadThread is given limit and before', async () => {
122 const messages = await saveTwoMessageThread()
123 expect(
124 await messages.loadThread('t-two', {
125 limit: 1,
126 before: 'cursor-1',
127 }),
128 ).toEqual(twoMessageTranscript)
129 })
130 })
131​
132 describe('activities', () => {
133 it('round-trips a thread and replaces the full list', async () => {
134 const { activities } = memoryPersistence().stores
135 expect(await activities!.loadActivities('unknown')).toEqual([])
136 await activities!.saveActivities('t1', [
137 {
138 id: 'act-1',
139 activityType: 'SEARCH',
140 content: { q: 'x' },
141 index: 1,
142 },
143 ])
144 expect(await activities!.loadActivities('t1')).toEqual([
145 {
146 id: 'act-1',
147 activityType: 'SEARCH',
148 content: { q: 'x' },
149 index: 1,
150 },
151 ])
152 await activities!.saveActivities('t1', [
153 {
154 id: 'act-2',
155 activityType: 'PLAN',
156 content: { steps: [] },
157 index: 0,
158 },
159 ])
160 expect(await activities!.loadActivities('t1')).toEqual([
161 {
162 id: 'act-2',
163 activityType: 'PLAN',
164 content: { steps: [] },
165 index: 0,
166 },
167 ])
168 })
169 })
170​
171 describe('interrupts', () => {
172 it('creates, resolves, and lists pending interrupts by thread', async () => {
173 const { interrupts } = memoryPersistence().stores
174 await interrupts!.create({
175 interruptId: 'i1',
176 runId: 'r1',
177 threadId: 't1',
178 requestedAt: 1,
179 payload: { kind: 'approval' },
180 })
181 expect((await interrupts!.get('i1'))?.status).toBe('pending')
182 expect(await interrupts!.listPending('t1')).toHaveLength(1)
183 await interrupts!.resolve('i1', { action: 'approve' })
184 expect((await interrupts!.get('i1'))?.status).toBe('resolved')
185 expect(await interrupts!.listPending('t1')).toHaveLength(0)
186 })
187​
188 it('lists interrupts and pending interrupts by run', async () => {
189 const { interrupts } = memoryPersistence().stores
190 await interrupts!.create({
191 interruptId: 'i1',
192 runId: 'r1',
193 threadId: 't1',
194 requestedAt: 1,
195 payload: { kind: 'approval' },
196 })
197 await interrupts!.create({
198 interruptId: 'i2',
199 runId: 'r1',
200 threadId: 't2',
201 requestedAt: 2,
202 payload: { kind: 'input' },
203 })
204 await interrupts!.create({
205 interruptId: 'i3',
206 runId: 'r2',
207 threadId: 't1',
208 requestedAt: 3,
209 payload: { kind: 'other' },
210 })
211​
212 await interrupts!.resolve('i2')
213​
214 expect(
215 (await interrupts!.listByRun('r1')).map(
216 (interrupt) => interrupt.interruptId,
217 ),
218 ).toEqual(['i1', 'i2'])
219 expect(
220 (await interrupts!.listPendingByRun('r1')).map(
221 (interrupt) => interrupt.interruptId,
222 ),
223 ).toEqual(['i1'])
224 })
225​
226 it('orders list results by requestedAt even when inserts are reverse order', async () => {
227 const { interrupts } = memoryPersistence().stores
228 await interrupts!.create({
229 interruptId: 'late',
230 runId: 'r1',
231 threadId: 't1',
232 requestedAt: 30,
233 payload: {},
234 })
235 await interrupts!.create({
236 interruptId: 'early',
237 runId: 'r1',
238 threadId: 't1',
239 requestedAt: 10,
240 payload: {},
241 })
242 expect((await interrupts!.list('t1')).map((i) => i.interruptId)).toEqual([
243 'early',
244 'late',
245 ])
246 })
247 })
248​
249 describe('metadata', () => {
250 it('keeps colon-containing namespace and key pairs distinct', async () => {
251 const { metadata } = memoryPersistence().stores
252 await metadata!.set('a:b', 'c', 'left')
253 await metadata!.set('a', 'b:c', 'right')
254 expect(await metadata!.get('a:b', 'c')).toBe('left')
255 expect(await metadata!.get('a', 'b:c')).toBe('right')
256 })
257 })
258​
259 describe('metadata', () => {
260 it('returns null for missing metadata and preserves stored undefined', async () => {
261 const { metadata } = memoryPersistence().stores
262 expect(await metadata!.get('scope', 'missing')).toBeNull()
263​
264 await metadata!.set('scope', 'present', undefined)
265 expect(await metadata!.get('scope', 'present')).toBeUndefined()
266​
267 await metadata!.delete('scope', 'present')
268 expect(await metadata!.get('scope', 'present')).toBeNull()
269 })
270 })
271})
272​
273describe('memoryLogState({ now })', () => {
274 const logId = 'log-1'
275 const harness = 'test/clock'
276​
277 /** A store on a log state whose clock the test moves. */
278 function clockedStore() {
279 const clock = { now: 1_000 }
280 const store = memoryLogStore({
281 state: memoryLogState({ now: () => clock.now }),
282 })
283 return { clock, store }
284 }
285​
286 it('expires an ownership when its clock passes the ttl', async () => {
287 const { clock, store } = clockedStore()
288 await store.acquireOwnership({ logId, harness, ownerId: 'a', ttlMs: 500 })
289​
290 clock.now = 1_499
291 expect(
292 await store.acquireOwnership({
293 logId,
294 harness,
295 ownerId: 'b',
296 ttlMs: 500,
297 }),
298 ).toBeNull()
299 clock.now = 1_500
300 expect(
301 await store.acquireOwnership({
302 logId,
303 harness,
304 ownerId: 'b',
305 ttlMs: 500,
306 }),
307 ).toEqual({ epoch: 2, expired: true })
308 })
309​
310 it('lists a released log for its wake only when its clock reaches the wake time', async () => {
311 const { clock, store } = clockedStore()
312 const owned = await store.acquireOwnership({
313 logId,
314 harness,
315 ownerId: 'a',
316 ttlMs: 500,
317 })
318 if (owned === null) throw new Error('The first acquire must succeed.')
319 await store.releaseOwnership({
320 logId,
321 ownerId: 'a',
322 epoch: owned.epoch,
323 wakeInMs: 60_000,
324 })
325​
326 clock.now = 60_999
327 expect(await store.listLogsWithoutOwner({ limit: 10 })).toEqual([])
328 clock.now = 61_000
329 expect(await store.listLogsWithoutOwner({ limit: 10 })).toEqual([
330 { logId, harness, reason: 'wake' },
331 ])
332 })
333​
334 it('stamps an offer with its clock', async () => {
335 const { store } = clockedStore()
336 await store.offerInput({
337 logId,
338 harness,
339 inputId: 'in-1',
340 record: { type: 'app.input' },
341 })
342​
343 expect(await store.listOfferedInputs({ logId })).toEqual([
344 { inputId: 'in-1', record: { type: 'app.input' }, offeredAt: 1_000 },
345 ])
346 })
347})