Open History to see the last commit
1import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import {
5 afterAll,
6 beforeAll,
7 beforeEach,
8 describe,
9 expect,
10 it,
11 vi,
12} from 'vitest'
13import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
14import { mediaIdOf } from '@tanstack/ai-harness/media'
15import { memoryPersistence } from '@tanstack/ai-persistence'
16import { attach, defaultMediaDir, saveMedia } from '../src/attach'
17import type { AnyTextAdapter } from '@tanstack/ai'
18import type {
19 HarnessHost,
20 HarnessSession,
21 UserInput,
22} from '@tanstack/ai-harness'
23
24// The real file system, with spies, so a test can see which files are read.
25vi.mock('node:fs/promises', { spy: true })
26
27/** A model that is never called: these tests only store and save files. */
28function idleModel(): AnyTextAdapter {
29 return {
30 kind: 'text',
31 name: 'mock',
32 model: 'test-model',
33 // `~types` holds types only. Its values are never read, so they are casts.
34 '~types': {
35 providerOptions: {} as Record<string, unknown>,
36 inputModalities: ['text'] as readonly ['text'],
37 messageMetadataByModality: {
38 text: undefined as unknown,
39 image: undefined as unknown,
40 audio: undefined as unknown,
41 video: undefined as unknown,
42 document: undefined as unknown,
43 },
44 toolCapabilities: [] as ReadonlyArray<string>,
45 toolCallMetadata: undefined as unknown,
46 systemPromptMetadata: undefined as never,
47 },
48 chatStream: () => {
49 throw new Error('The model must not be called.')
50 },
51 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
52 }
53}
54
55/** The part that `attach` makes for a stored PNG. */
56const pngPart = {
57 type: 'image',
58 source: {
59 type: 'url',
60 value: expect.stringMatching(/^harness-media:./),
61 mimeType: 'image/png',
62 },
63}
64
65let dir = ''
66let host: HarnessHost
67let session: HarnessSession
68
69beforeAll(async () => {
70 dir = await mkdtemp(join(tmpdir(), 'harness-attach-'))
71 await writeFile(join(dir, 'cat.png'), 'hello')
72 await writeFile(join(dir, 'my cat.png'), 'meow')
73 await writeFile(join(dir, 'notes.xyz'), 'plain')
74 await mkdir(join(dir, 'folder.png'))
75 host = createHarnessHost({ persistence: memoryPersistence() })
76 session = await host.open(
77 defineHarness({ name: 'test/attach', adapter: idleModel() }),
78 {
79 threadId: 't',
80 },
81 )
82})
83
84afterAll(async () => {
85 await host.close()
86 await rm(dir, { recursive: true, force: true })
87})
88
89beforeEach(() => {
90 vi.clearAllMocks()
91})
92
93/** The name and text of each stored file that `input` sends. */
94async function storedFiles(input: UserInput) {
95 const parts = typeof input === 'string' ? [] : input
96 const ids = parts.flatMap((part) => mediaIdOf(part) ?? [])
97 return Promise.all(
98 ids.map(async (id) => ({
99 name: (await session.getMedia({ id }))?.name,
100 text: new TextDecoder().decode(await session.loadMedia({ id })),
101 })),
102 )
103}
104
105describe('attach', () => {
106 it('sends a file token as a media part and takes the token out of the text', async () => {
107 const input = await attach(session, 'what is wrong in @cat.png today', {
108 cwd: dir,
109 })
110
111 expect(input).toEqual([
112 { type: 'text', content: 'what is wrong in today' },
113 pngPart,
114 ])
115 expect(await storedFiles(input)).toEqual([
116 { name: 'cat.png', text: 'hello' },
117 ])
118 })
119
120 it('reads a quoted path with spaces', async () => {
121 const input = await attach(session, 'look at @"my cat.png"', { cwd: dir })
122
123 expect(input).toEqual([{ type: 'text', content: 'look at' }, pngPart])
124 expect(await storedFiles(input)).toEqual([
125 { name: 'my cat.png', text: 'meow' },
126 ])
127 })
128
129 it('sends no text part for a message that is only a file', async () => {
130 expect(await attach(session, '@cat.png', { cwd: dir })).toEqual([pngPart])
131 })
132
133 it('keeps an email and a package name as text, and reads no file for the email', async () => {
134 const email = 'write to me@acme.dev'
135 const packageName = 'install @types/node first'
136
137 expect(await attach(session, email, { cwd: dir })).toBe(email)
138 expect(stat).not.toHaveBeenCalled()
139 expect(readFile).not.toHaveBeenCalled()
140 expect(await attach(session, packageName, { cwd: dir })).toBe(packageName)
141 // A token that can be a path is looked up, so the spy above sees reads.
142 expect(stat).toHaveBeenCalled()
143 })
144
145 it.each([
146 ['a missing file', 'see @missing.png now'],
147 ['a folder', 'see @folder.png now'],
148 ])('keeps %s as text', async (_label, text) => {
149 expect(await attach(session, text, { cwd: dir })).toBe(text)
150 })
151
152 it('refuses a file of a type it does not know', async () => {
153 await expect(
154 attach(session, 'read @notes.xyz', { cwd: dir }),
155 ).rejects.toThrow(
156 'Cannot attach notes.xyz: the file type is not known. To send the path as text, remove the @.',
157 )
158 })
159})
160
161describe('saveMedia', () => {
162 it('makes the folder and adds a number instead of overwriting a file', async () => {
163 const record = await session.putMedia({
164 body: new TextEncoder().encode('hello'),
165 mimeType: 'image/png',
166 name: 'cat.png',
167 })
168 const out = join(dir, 'saved', 'media')
169
170 const paths = [
171 await saveMedia(session, record, out),
172 await saveMedia(session, record, out),
173 await saveMedia(session, record, out),
174 ]
175
176 expect(paths).toEqual([
177 join(out, 'cat.png'),
178 join(out, 'cat-1.png'),
179 join(out, 'cat-2.png'),
180 ])
181 expect(await readFile(join(out, 'cat-2.png'), 'utf8')).toBe('hello')
182 })
183
184 it.each(['../escaped.png', 'sub/escaped.png', 'sub\\escaped.png', '..'])(
185 'refuses the name %s',
186 async (name) => {
187 const record = await session.putMedia({
188 body: new TextEncoder().encode('x'),
189 mimeType: 'image/png',
190 name,
191 })
192 const out = join(dir, 'refused')
193
194 await expect(saveMedia(session, record, out)).rejects.toThrow(
195 'it is not a plain file name',
196 )
197 await expect(stat(join(dir, 'escaped.png'))).rejects.toThrow()
198 },
199 )
200})
201
202describe('defaultMediaDir', () => {
203 it.each([
204 ['acme/coder', 'acme-coder-media'],
205 ['@acme/coder', 'acme-coder-media'],
206 ])('saves the media of %s into %s', (name, folder) => {
207 expect(defaultMediaDir(name)).toBe(folder)
208 })
209})