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

cli-media.test.ts

218 lines6.1 KB

1import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
5import { defineAgent } from '@tanstack/ai'
6import { defineHarness } from '@tanstack/ai-harness'
7import { memoryPersistence } from '@tanstack/ai-persistence'
8import { EXIT, runCli } from '../src'
9import { capture, scripted, stdinFrom, textTurn, toolTurn } from './helpers'
10import type { ImageAdapter } from '@tanstack/ai'
11​
12/** An image model that paints the bytes "hello". */
13function imageAdapter(): ImageAdapter<string> {
14 return {
15 kind: 'image',
16 name: 'fake-image',
17 model: 'fake-image-model',
18 '~types': {
19 providerOptions: {},
20 modelProviderOptionsByName: {},
21 modelSizeByName: {},
22 modelInputModalitiesByName: {},
23 },
24 // 'aGVsbG8=' is base64 for "hello".
25 generateImages: async () => ({
26 id: 'image-1',
27 model: 'fake-image-model',
28 images: [{ b64Json: 'aGVsbG8=' }],
29 }),
30 }
32​
33const painter = defineAgent({
34 name: 'painter',
35 description: 'Paints',
36 run: async (ctx) => {
37 await ctx.generateImage({ adapter: imageAdapter(), prompt: 'a cat' })
38 return 'painted'
39 },
40})
41​
42/**
43 * Run a harness whose lead calls the painter once, then answers, with
44 * `argv` and the piped `lines`. Gives the exit code and the output.
45 */
46async function paint(argv: Array<string>, lines: Array<string> = []) {
47 const { adapter } = scripted([
48 toolTurn('painter', '{}'),
49 textTurn('Here is your cat.'),
50 ])
51 const harness = defineHarness({
52 name: 'test/painting',
53 adapter,
54 subagents: { agents: [painter] },
55 })
56 const stdout = capture()
57 const stderr = capture()
58 const code = await runCli(harness, {
59 argv,
60 stdin: stdinFrom(lines, { isTTY: false }),
61 stdout,
62 stderr,
63 persistence: memoryPersistence(),
64 })
65 return { code, stdout: stdout.text, stderr: stderr.text }
67​
68let root = ''
69​
70beforeAll(async () => {
71 root = await mkdtemp(join(tmpdir(), 'harness-cli-media-'))
72 await writeFile(join(root, 'cat.png'), 'hello')
73 await writeFile(join(root, 'notes.xyz'), 'plain')
74})
75​
76afterAll(async () => {
77 await rm(root, { recursive: true, force: true })
78})
79​
80/** A prompt that sends cat.png by its full path, quoted for spaces. */
81const aboutCat = () => `what is @"${join(root, 'cat.png')}"`
82​
83/** What the model sees for `aboutCat()`: the text, then the bytes. */
84const seenAboutCat = [
85 { type: 'text', content: 'what is' },
86 {
87 type: 'image',
88 source: { type: 'data', value: 'aGVsbG8=', mimeType: 'image/png' },
89 },
91​
92/** The one file in `dir`, as its path and its text. */
93async function onlyFile(dir: string) {
94 const names = await readdir(dir)
95 expect(names).toHaveLength(1)
96 const path = join(dir, names[0] ?? '')
97 return { path, text: await readFile(path, 'utf8') }
99​
100describe('media in line mode', () => {
101 it('saves a new image into the media folder once and prints where', async () => {
102 const mediaDir = join(root, 'lines')
103​
104 const { code, stdout } = await paint(
105 ['--media-dir', mediaDir],
106 ['paint a cat\n'],
107 )
108​
109 expect(code).toBe(EXIT.ok)
110 const saved = await onlyFile(mediaDir)
111 expect(saved.text).toBe('hello')
112 expect(stdout).toContain(`[image saved: ${saved.path}]\n`)
113 expect(stdout).toContain('Here is your cat.')
114 })
115​
116 it('prints why a file cannot go, and does not call the model', async () => {
117 const { adapter, seen } = scripted([])
118 const stdout = capture()
119​
120 await runCli(defineHarness({ name: 'test/media-refused', adapter }), {
121 argv: [],
122 stdin: stdinFrom([`read @"${join(root, 'notes.xyz')}"\n`], {
123 isTTY: false,
124 }),
125 stdout,
126 stderr: capture(),
127 persistence: memoryPersistence(),
128 })
129​
130 expect(stdout.text).toContain(
131 'Cannot attach notes.xyz: the file type is not known.',
132 )
133 expect(seen).toHaveLength(0)
134 })
135})
136​
137describe('media in print mode', () => {
138 it('prints the media event with the saved path in ndjson', async () => {
139 const mediaDir = join(root, 'ndjson')
140​
141 const { stdout } = await paint([
142 '-p',
143 'paint a cat',
144 '--output',
145 'ndjson',
146 '--media-dir',
147 mediaDir,
148 ])
149​
150 const saved = await onlyFile(mediaDir)
151 const media = stdout
152 .trim()
153 .split('\n')
154 .map((line) => JSON.parse(line))
155 .filter((event) => event.name === 'harness.media')
156 expect(media).toEqual([
157 expect.objectContaining({
158 type: 'CUSTOM',
159 value: expect.objectContaining({
160 kind: 'image',
161 source: 'generated',
162 size: 5,
163 path: saved.path,
164 }),
165 }),
166 ])
167 })
168​
169 it('prints the saved line to stderr and only the answer to stdout', async () => {
170 const mediaDir = join(root, 'text')
171​
172 const { code, stdout, stderr } = await paint([
173 '-p',
174 'paint a cat',
175 '--media-dir',
176 mediaDir,
177 ])
178​
179 expect(code).toBe(EXIT.ok)
180 const saved = await onlyFile(mediaDir)
181 expect(stdout).toBe('Here is your cat.\n')
182 expect(stderr).toBe(`[image saved: ${saved.path}]\n`)
183 })
184​
185 it('sends an @file to the model as data', async () => {
186 const { adapter, seen } = scripted([textTurn('A cat.')])
187​
188 const code = await runCli(defineHarness({ name: 'test/attach', adapter }), {
189 argv: ['-p', aboutCat()],
190 stdout: capture(),
191 stderr: capture(),
192 persistence: memoryPersistence(),
193 })
194​
195 expect(code).toBe(EXIT.ok)
196 expect(seen[0]?.at(-1)?.content).toEqual(seenAboutCat)
197 })
198})
199​
200describe('media in a custom ui', () => {
201 it('sends an @file of view.send to the model', async () => {
202 const { adapter, seen } = scripted([textTurn('A cat.')])
203​
204 await runCli(defineHarness({ name: 'test/ui-attach', adapter }), {
205 argv: [],
206 stdin: stdinFrom([], { isTTY: true }),
207 stdout: capture(),
208 stderr: capture(),
209 persistence: memoryPersistence(),
210 ui: async (view) => {
211 await view.send(aboutCat())
212 await vi.waitFor(() => expect(seen).toHaveLength(1))
213 },
214 })
215​
216 expect(seen[0]?.at(-1)?.content).toEqual(seenAboutCat)
217 })
218})