Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { selectRelevantSnippets } from '../src/select-relevant-snippets'
3import { createMemorySnippetStorage } from '../src/storage/memory-storage'
4import type { AnyTextAdapter, ModelMessage } from '@tanstack/ai'
5import type { Snippet } from '../src/types'
6
7const chatMock = vi.hoisted(() => vi.fn())
8vi.mock('@tanstack/ai', async (importOriginal) => {
9 const actual = (await importOriginal()) as Record<string, unknown>
10 return { ...actual, chat: chatMock }
11})
12
13function makeSnippet(overrides: Partial<Snippet> = {}): Snippet {
14 return {
15 id: 'id',
16 name: 'fetch_data',
17 description: 'Fetches data',
18 code: 'return 1;',
19 inputSchema: {},
20 outputSchema: {},
21 usageHints: [],
22 dependsOn: [],
23 trustLevel: 'untrusted',
24 stats: { executions: 0, successRate: 0 },
25 createdAt: '',
26 updatedAt: '',
27 ...overrides,
28 }
29}
30
31function streamChunks(text: string) {
32 return (async function* () {
33 yield { type: 'TEXT_MESSAGE_CONTENT' as const, delta: text }
34 })()
35}
36
37const dummyAdapter = {} as AnyTextAdapter
38const userMessage: ModelMessage = {
39 role: 'user',
40 content: 'please use github tool',
41}
42
43describe('selectRelevantSnippets', () => {
44 it('returns empty array when the snippet index is empty', async () => {
45 const storage = createMemorySnippetStorage([])
46 const result = await selectRelevantSnippets({
47 threadId: 'thread-1',
48 adapter: dummyAdapter,
49 messages: [userMessage],
50 snippetIndex: [],
51 maxSnippets: 5,
52 storage,
53 })
54 expect(result).toEqual([])
55 expect(chatMock).not.toHaveBeenCalled()
56 })
57
58 it('returns empty array when there are no messages', async () => {
59 const storage = createMemorySnippetStorage([makeSnippet({ name: 'x' })])
60 const result = await selectRelevantSnippets({
61 threadId: 'thread-1',
62 adapter: dummyAdapter,
63 messages: [],
64 snippetIndex: await storage.loadIndex(),
65 maxSnippets: 5,
66 storage,
67 })
68 expect(result).toEqual([])
69 expect(chatMock).not.toHaveBeenCalled()
70 })
71
72 it('returns snippets whose names were selected by the model', async () => {
73 const snippet = makeSnippet({ name: 'github_stats' })
74 const storage = createMemorySnippetStorage([snippet])
75 chatMock.mockReturnValueOnce(streamChunks('["github_stats"]'))
76
77 const result = await selectRelevantSnippets({
78 threadId: 'thread-1',
79 adapter: dummyAdapter,
80 messages: [userMessage],
81 snippetIndex: await storage.loadIndex(),
82 maxSnippets: 5,
83 storage,
84 })
85 expect(result).toHaveLength(1)
86 expect(result[0]!.name).toBe('github_stats')
87 expect(chatMock).toHaveBeenCalledWith(
88 expect.objectContaining({ threadId: 'thread-1:snippets' }),
89 )
90 })
91
92 it('strips markdown code fences around the JSON response', async () => {
93 const snippet = makeSnippet({ name: 'github_stats' })
94 const storage = createMemorySnippetStorage([snippet])
95 chatMock.mockReturnValueOnce(streamChunks('```json\n["github_stats"]\n```'))
96
97 const result = await selectRelevantSnippets({
98 threadId: 'thread-1',
99 adapter: dummyAdapter,
100 messages: [userMessage],
101 snippetIndex: await storage.loadIndex(),
102 maxSnippets: 5,
103 storage,
104 })
105 expect(result).toHaveLength(1)
106 })
107
108 it('returns an empty array when the model response is not an array', async () => {
109 const snippet = makeSnippet({ name: 'github_stats' })
110 const storage = createMemorySnippetStorage([snippet])
111 chatMock.mockReturnValueOnce(streamChunks('{"not": "an array"}'))
112
113 const result = await selectRelevantSnippets({
114 threadId: 'thread-1',
115 adapter: dummyAdapter,
116 messages: [userMessage],
117 snippetIndex: await storage.loadIndex(),
118 maxSnippets: 5,
119 storage,
120 })
121 expect(result).toEqual([])
122 })
123
124 it('returns empty array when JSON parsing fails (safe fallback)', async () => {
125 const snippet = makeSnippet({ name: 'github_stats' })
126 const storage = createMemorySnippetStorage([snippet])
127 chatMock.mockReturnValueOnce(streamChunks('not json at all'))
128
129 const result = await selectRelevantSnippets({
130 threadId: 'thread-1',
131 adapter: dummyAdapter,
132 messages: [userMessage],
133 snippetIndex: await storage.loadIndex(),
134 maxSnippets: 5,
135 storage,
136 })
137 expect(result).toEqual([])
138 })
139
140 it('truncates model selections to maxSnippets', async () => {
141 const storage = createMemorySnippetStorage([
142 makeSnippet({ id: '1', name: 'a' }),
143 makeSnippet({ id: '2', name: 'b' }),
144 makeSnippet({ id: '3', name: 'c' }),
145 ])
146 chatMock.mockReturnValueOnce(streamChunks('["a","b","c"]'))
147
148 const result = await selectRelevantSnippets({
149 threadId: 'thread-1',
150 adapter: dummyAdapter,
151 messages: [userMessage],
152 snippetIndex: await storage.loadIndex(),
153 maxSnippets: 2,
154 storage,
155 })
156 expect(result).toHaveLength(2)
157 })
158
159 it('filters out snippet names that no longer resolve in storage', async () => {
160 const snippet = makeSnippet({ name: 'still_exists' })
161 const storage = createMemorySnippetStorage([snippet])
162 chatMock.mockReturnValueOnce(
163 streamChunks('["still_exists","deleted_snippet"]'),
164 )
165
166 const result = await selectRelevantSnippets({
167 threadId: 'thread-1',
168 adapter: dummyAdapter,
169 messages: [userMessage],
170 snippetIndex: await storage.loadIndex(),
171 maxSnippets: 5,
172 storage,
173 })
174 expect(result).toHaveLength(1)
175 expect(result[0]!.name).toBe('still_exists')
176 })
177
178 it('returns empty array when the chat stream throws', async () => {
179 const storage = createMemorySnippetStorage([makeSnippet({ name: 'x' })])
180 chatMock.mockImplementationOnce(() => {
181 throw new Error('network down')
182 })
183 const result = await selectRelevantSnippets({
184 threadId: 'thread-1',
185 adapter: dummyAdapter,
186 messages: [userMessage],
187 snippetIndex: await storage.loadIndex(),
188 maxSnippets: 5,
189 storage,
190 })
191 expect(result).toEqual([])
192 })
193})