Open History to see the last commit
1import { PassThrough } from 'node:stream'
2import { memoryCredentialStore } from '@tanstack/ai/byok/server'
3import { describe, expect, it, vi } from 'vitest'
4import { defineAgent, toolDefinition } from '@tanstack/ai'
5import { z } from 'zod'
6import {
7 configOption,
8 createHarnessHost,
9 defineCommand,
10 defineHarness,
11 definePlugin,
12 durableTool,
13 membersOnly,
14} from '@tanstack/ai-harness'
15import { question as questionTool } from '@tanstack/ai-harness/plugins'
16import { createMCPClient } from '@tanstack/ai-mcp'
17import { memoryPersistence } from '@tanstack/ai-persistence'
18import { EXIT, parseCliArgs, runCli } from '../src'
19import { serve } from '../src/serve'
20import {
21 asStdin,
22 capture,
23 gate,
24 heldTurn,
25 scripted,
26 stdinFrom,
27 textTurn,
28 toolTurn,
29} from './helpers'
30import type { AnyHarness } from '@tanstack/ai-harness'
31
32/** `/connect acme` asks for a key as a secret question, then saves it. */
33const acmeKeys = definePlugin({
34 name: 'test/acme-keys',
35 setup: () => ({
36 commands: {
37 'connect:acme': defineCommand({
38 description: 'Save an Acme API key',
39 run: async (_input, { credentials, step }) => {
40 const key = await step.ask({
41 name: 'key',
42 message: 'Paste your Acme API key',
43 schema: z.string(),
44 secret: true,
45 })
46 await credentials.set({
47 id: 'acme',
48 credential: { type: 'api_key', value: key },
49 })
50 return `Connected to Acme (key ...${key.slice(-4)}).`
51 },
52 }),
53 },
54 }),
55})
56
57const olga = { id: 'olga' }
58const cid = { id: 'cid' }
59const users = new Map([olga, cid].map((user) => [user.id, user]))
60
61/** A membersOnly() host whose users come from the `x-user` header. */
62function accessHost() {
63 return createHarnessHost({
64 persistence: memoryPersistence(),
65 access: {
66 getUser: ({ request }) =>
67 users.get(request.headers.get('x-user') ?? '') ?? null,
68 rules: membersOnly(),
69 },
70 })
71}
72
73describe('parseCliArgs', () => {
74 it('reads flags and rejects bad values', () => {
75 expect(parseCliArgs(['-p', 'hi', '--output', 'ndjson'])).toMatchObject({
76 print: 'hi',
77 output: 'ndjson',
78 thread: 'main',
79 })
80 expect(() => parseCliArgs(['--output', 'xml'])).toThrow('--output')
81 expect(() => parseCliArgs(['--nope'])).toThrow()
82 })
83
84 it('reads --mcp and --yes, both off by default', () => {
85 expect(parseCliArgs(['--mcp', '--yes'])).toMatchObject({
86 mcp: true,
87 yes: true,
88 })
89 expect(parseCliArgs([])).toMatchObject({ mcp: false, yes: false })
90 })
91})
92
93describe('print mode', () => {
94 it('prints the answer and exits 0', async () => {
95 const { adapter } = scripted([textTurn('Hello from the harness.')])
96 const stdout = capture()
97 const code = await runCli(defineHarness({ name: 'test/print', adapter }), {
98 argv: ['-p', 'hi'],
99 stdout,
100 stderr: capture(),
101 persistence: memoryPersistence(),
102 })
103 expect(code).toBe(EXIT.ok)
104 expect(stdout.text).toBe('Hello from the harness.\n')
105 })
106
107 it('prints NDJSON AG-UI events', async () => {
108 const { adapter } = scripted([textTurn('x')])
109 const stdout = capture()
110 await runCli(defineHarness({ name: 'test/ndjson', adapter }), {
111 argv: ['-p', 'hi', '--output', 'ndjson'],
112 stdout,
113 stderr: capture(),
114 persistence: memoryPersistence(),
115 })
116 const events = stdout.text
117 .trim()
118 .split('\n')
119 .map((line) => JSON.parse(line))
120 expect(events.map((event) => event.type)).toContain('TEXT_MESSAGE_CONTENT')
121 expect(events.at(-1).name).toBe('harness.operation.finished')
122 })
123
124 it('exits 3 when the turn waits for an approval', async () => {
125 const { adapter } = scripted([toolTurn('remove', '{}')])
126 const stderr = capture()
127 const code = await runCli(
128 defineHarness({
129 name: 'test/approval',
130 adapter,
131 tools: [
132 toolDefinition({
133 name: 'remove',
134 description: 'Remove',
135 needsApproval: true,
136 }).server(async () => 'ok'),
137 ],
138 }),
139 {
140 argv: ['-p', 'remove it'],
141 stdout: capture(),
142 stderr,
143 persistence: memoryPersistence(),
144 },
145 )
146 expect(code).toBe(EXIT.needsAction)
147 expect(EXIT.needsAction).toBe(3)
148 expect(stderr.text).toContain('approval')
149 })
150
151 it('exits 3 when the turn waits for the answer to a question', async () => {
152 const { adapter } = scripted([toolTurn('greet', '{}')])
153 const greet = durableTool(
154 toolDefinition({
155 name: 'greet',
156 description: 'Ask the user for a name',
157 inputSchema: z.object({}),
158 }),
159 async (_args, { step }) => {
160 const name = await step.ask({
161 name: 'name',
162 message: 'Name?',
163 schema: z.string(),
164 })
165 return `Hello, ${name}.`
166 },
167 )
168 const stderr = capture()
169 const code = await runCli(
170 defineHarness({ name: 'test/print-question', adapter, tools: [greet] }),
171 {
172 argv: ['-p', 'greet me'],
173 stdout: capture(),
174 stderr,
175 persistence: memoryPersistence(),
176 },
177 )
178 expect(code).toBe(EXIT.needsAction)
179 expect(stderr.text).toContain('an answer: Name?')
180 })
181})
182
183describe('line mode', () => {
184 it('runs piped lines as turns, answers approvals, and runs commands', async () => {
185 const remove = vi.fn(async () => 'removed')
186 const pricer = defineAgent({
187 name: 'pricer',
188 description: 'Prices a vendor',
189 run: async () => 'twelve dollars',
190 })
191 const { adapter } = scripted([
192 textTurn('First answer.'),
193 toolTurn('remove', '{}'),
194 textTurn('Done removing.'),
195 ])
196 const stdout = capture()
197 const code = await runCli(
198 defineHarness({
199 name: 'test/lines',
200 adapter,
201 agents: [pricer],
202 tools: [
203 toolDefinition({
204 name: 'remove',
205 description: 'Remove',
206 needsApproval: true,
207 }).server(remove),
208 ],
209 }),
210 {
211 argv: [],
212 stdin: stdinFrom(
213 ['hello\n', 'remove the file\n', 'y\n', '/agents\n', '/exit\n'],
214 { isTTY: false },
215 ),
216 stdout,
217 stderr: capture(),
218 persistence: memoryPersistence(),
219 },
220 )
221 expect(code).toBe(EXIT.ok)
222 expect(remove).toHaveBeenCalledTimes(1)
223 expect(stdout.text).toContain('First answer.')
224 expect(stdout.text).toContain('[y/n]')
225 expect(stdout.text).toContain('Done removing.')
226 expect(stdout.text).toContain('pricer: Prices a vendor')
227 })
228})
229
230describe('line mode in a terminal', () => {
231 /** Line mode on a terminal that the test types into. */
232 function terminal(harness: AnyHarness) {
233 const input = new PassThrough()
234 const stdout = capture()
235 const exit = runCli(harness, {
236 argv: [],
237 stdin: asStdin(input, { isTTY: true }),
238 stdout,
239 stderr: capture(),
240 persistence: memoryPersistence(),
241 })
242 return {
243 stdout,
244 type: (text: string) => input.write(`${text}\n`),
245 shows: (text: string) =>
246 vi.waitFor(() => expect(stdout.text).toContain(text)),
247 quit: () => {
248 input.end('/exit\n')
249 return exit
250 },
251 }
252 }
253
254 it('cancels the running turn at once with /cancel', async () => {
255 // Never opened: only the cancel can end this turn.
256 const release = gate()
257 const { adapter } = scripted([heldTurn('Working on it.', release.opened)])
258 const cli = terminal(defineHarness({ name: 'test/cancel', adapter }))
259 cli.type('write a long story')
260 await cli.shows('Working on it.')
261 cli.type('/cancel')
262 await cli.shows('Cancelled.')
263 expect(await cli.quit()).toBe(EXIT.ok)
264 })
265
266 it('sends a line typed while a turn runs as a steer that the turn sees', async () => {
267 const release = gate()
268 const { adapter, seen } = scripted([
269 heldTurn('Working on it.', release.opened),
270 textTurn('Checked the logs too.'),
271 ])
272 const joined: Array<unknown> = []
273 const cli = terminal(
274 defineHarness({
275 name: 'test/steer',
276 adapter,
277 turn: {
278 canJoin: (candidate) => {
279 joined.push(candidate.message)
280 return true
281 },
282 },
283 }),
284 )
285 cli.type('fix the bug')
286 await cli.shows('Working on it.')
287 cli.type('also check the logs')
288 // The steer waits for the next model call of the running turn.
289 cli.type('/status')
290 await cli.shows('Queued turns: 1.')
291 release.open()
292 await cli.shows('Checked the logs too.')
293 expect(await cli.quit()).toBe(EXIT.ok)
294 expect(joined).toEqual(['also check the logs'])
295 expect(seen[1]?.at(-1)).toMatchObject({
296 role: 'user',
297 content: 'also check the logs',
298 })
299 })
300
301 it('asks for an approval once, and the next line answers it', async () => {
302 const remove = vi.fn(async () => 'removed')
303 const { adapter } = scripted([
304 toolTurn('remove', '{}'),
305 textTurn('Done removing.'),
306 ])
307 const cli = terminal(
308 defineHarness({
309 name: 'test/approve',
310 adapter,
311 tools: [
312 toolDefinition({
313 name: 'remove',
314 description: 'Remove',
315 needsApproval: true,
316 }).server(remove),
317 ],
318 }),
319 )
320 cli.type('remove the file')
321 await cli.shows('[y/n]')
322 cli.type('y')
323 await cli.shows('Done removing.')
324 expect(await cli.quit()).toBe(EXIT.ok)
325 expect(remove).toHaveBeenCalledTimes(1)
326 expect(cli.stdout.text.split('[y/n]')).toHaveLength(2)
327 })
328})
329
330describe('waits in line mode', () => {
331 it('answers a question of the question tool by its schema', async () => {
332 const { adapter, seen } = scripted([
333 toolTurn(
334 'question',
335 JSON.stringify({
336 questions: [
337 {
338 question: 'Which database?',
339 options: [{ label: 'Postgres' }, { label: 'SQLite' }],
340 },
341 ],
342 }),
343 ),
344 textTurn('Picked.'),
345 ])
346 const stdout = capture()
347 const code = await runCli(
348 defineHarness({
349 name: 'test/lines-question',
350 adapter,
351 plugins: () => [questionTool()],
352 }),
353 {
354 argv: [],
355 stdin: stdinFrom(['ask me\n', 'SQLite\n', '/exit\n'], {
356 isTTY: false,
357 }),
358 stdout,
359 stderr: capture(),
360 persistence: memoryPersistence(),
361 },
362 )
363 expect(code).toBe(EXIT.ok)
364 expect(stdout.text).toContain('? Which database?')
365 expect(stdout.text).toContain('Picked.')
366 expect(JSON.stringify(seen[1])).toContain('SQLite')
367 })
368})
369
370describe('plugin commands in line mode', () => {
371 it('runs plugin commands, answers questions, and changes settings', async () => {
372 const tools = definePlugin({
373 name: 'test/tools',
374 setup: () => ({
375 config: {
376 tone: configOption.select({
377 options: ['plain', 'warm'],
378 default: 'plain',
379 }),
380 },
381 commands: {
382 greet: defineCommand({
383 description: 'Greet someone',
384 run: (input: unknown) =>
385 `Hello, ${typeof input === 'object' && input !== null && 'name' in input ? String(input.name) : 'you'}!`,
386 }),
387 confirm: defineCommand({
388 description: 'Ask first',
389 run: async (_input, { step }) => {
390 const sure = await step.ask({
391 name: 'sure',
392 message: 'Really?',
393 schema: { type: 'boolean' },
394 })
395 return sure === true ? 'Confirmed.' : 'Stopped.'
396 },
397 }),
398 },
399 }),
400 })
401 const { adapter } = scripted([])
402 const stdout = capture()
403 await runCli(
404 defineHarness({
405 name: 'test/plugin-lines',
406 adapter,
407 plugins: () => [tools],
408 }),
409 {
410 argv: [],
411 stdin: stdinFrom(
412 [
413 '/greet {"name":"Ada"}\n',
414 '/confirm\n',
415 'yes\n',
416 '/config tone warm\n',
417 '/config\n',
418 '/help\n',
419 '/exit\n',
420 ],
421 { isTTY: false },
422 ),
423 stdout,
424 stderr: capture(),
425 persistence: memoryPersistence(),
426 },
427 )
428 expect(stdout.text).toContain('Hello, Ada!')
429 expect(stdout.text).toContain('? Really?')
430 expect(stdout.text).toContain('Confirmed.')
431 expect(stdout.text).toContain('tone changed.')
432 expect(stdout.text).toContain('tone = "warm"')
433 expect(stdout.text).toContain('/greet Greet someone')
434 })
435})
436
437describe('secret answers in line mode', () => {
438 /** Run `/connect acme` and answer with `key`. Returns what was printed and saved. */
439 async function connect(
440 key: string,
441 stdin: (lines: Array<string>) => NodeJS.ReadStream,
442 ) {
443 const stdout = capture()
444 const persistence = memoryPersistence()
445 const credentials = memoryCredentialStore()
446 await runCli(
447 defineHarness({
448 name: 'test/secret',
449 adapter: scripted([]).adapter,
450 plugins: () => [acmeKeys],
451 }),
452 {
453 argv: [],
454 stdin: stdin(['/connect acme\n', `${key}\n`, '/exit\n']),
455 stdout,
456 stderr: capture(),
457 persistence,
458 credentials,
459 },
460 )
461 const saved = await credentials.get({
462 scope: { threadId: 'main' },
463 id: 'acme',
464 })
465 return { printed: stdout.text, saved }
466 }
467
468 it('saves a pasted key as typed and never prints it', async () => {
469 const { printed, saved } = await connect('12345678', (lines) =>
470 stdinFrom(lines, { isTTY: false }),
471 )
472 expect(saved).toEqual({ type: 'api_key', value: '12345678' })
473 expect(printed).toContain('[? Paste your Acme API key]')
474 expect(printed).toContain('Connected to Acme (key ...5678).')
475 expect(printed).not.toContain('12345678')
476 })
477
478 it('hides typing in a terminal while the key question waits', async () => {
479 const rawModes: Array<boolean> = []
480 const { printed, saved } = await connect('sk-acme-x\u007fy-4321', (lines) =>
481 Object.assign(stdinFrom(lines, { isTTY: true }), {
482 setRawMode: (mode: boolean) => rawModes.push(mode),
483 }),
484 )
485 expect(rawModes).toEqual([true, false])
486 // Raw mode does not edit the line, so line mode applies the backspace.
487 expect(saved).toEqual({ type: 'api_key', value: 'sk-acme-y-4321' })
488 expect(printed).toContain('[? Paste your Acme API key (typing is hidden)]')
489 expect(printed).not.toContain('sk-acme')
490 })
491})
492
493describe('a host and a user', () => {
494 it('uses the given host, leaves it open, and saves keys for the user', async () => {
495 const persistence = memoryPersistence()
496 const credentials = memoryCredentialStore()
497 const host = createHarnessHost({ persistence, credentials })
498 const close = vi.spyOn(host, 'close')
499 const code = await runCli(
500 defineHarness({
501 name: 'test/host',
502 adapter: scripted([]).adapter,
503 plugins: () => [acmeKeys],
504 }),
505 {
506 argv: [],
507 stdin: stdinFrom(['/connect acme\n', 'sk-ada\n', '/exit\n'], {
508 isTTY: false,
509 }),
510 stdout: capture(),
511 stderr: capture(),
512 host,
513 user: { id: 'ada' },
514 },
515 )
516 expect(code).toBe(EXIT.ok)
517 expect(close).not.toHaveBeenCalled()
518 const saved = (userId?: string) =>
519 credentials.get({
520 scope: { threadId: 'main', ...(userId ? { userId } : {}) },
521 id: 'acme',
522 })
523 expect(await saved('ada')).toEqual({ type: 'api_key', value: 'sk-ada' })
524 expect(await saved()).toBeNull()
525 await host.close()
526 })
527
528 it('opens the session as the user', async () => {
529 const { adapter } = scripted([textTurn('ok')])
530 const seen: Array<string | undefined> = []
531 const code = await runCli(
532 defineHarness({
533 name: 'test/user',
534 adapter,
535 plugins: () => [
536 definePlugin({
537 name: 'test/whoami',
538 setup: (ctx) => void seen.push(ctx.session.user?.id),
539 }),
540 ],
541 }),
542 {
543 argv: ['-p', 'hi'],
544 stdout: capture(),
545 stderr: capture(),
546 persistence: memoryPersistence(),
547 user: { id: 'ada' },
548 },
549 )
550 expect(code).toBe(EXIT.ok)
551 expect(seen).toEqual(['ada'])
552 })
553
554 it('refuses a host and persistence together', async () => {
555 const host = createHarnessHost({ persistence: memoryPersistence() })
556 const stderr = capture()
557 const code = await runCli(
558 defineHarness({ name: 'test/both', adapter: scripted([]).adapter }),
559 {
560 argv: ['-p', 'hi'],
561 stdout: capture(),
562 stderr,
563 host,
564 persistence: memoryPersistence(),
565 },
566 )
567 expect(code).toBe(EXIT.failed)
568 expect(stderr.text).toContain('not both')
569 await host.close()
570 })
571
572 it('serves as the user', async () => {
573 const persistence = memoryPersistence()
574 const credentials = memoryCredentialStore()
575 const host = createHarnessHost({ persistence, credentials })
576 const server = await serve({
577 host,
578 harness: defineHarness({
579 name: 'test/serve-user',
580 adapter: scripted([]).adapter,
581 plugins: () => [acmeKeys],
582 expose: { commands: ['connect:acme'] },
583 }),
584 port: 0,
585 hostname: '127.0.0.1',
586 token: 'secret',
587 user: { id: 'ada' },
588 })
589 try {
590 const control = (input: unknown) =>
591 fetch(`${server.url}/control`, {
592 method: 'POST',
593 headers: {
594 authorization: 'Bearer secret',
595 'content-type': 'application/json',
596 },
597 body: JSON.stringify({ threadId: 't', input }),
598 })
599 await control({ op: 'command', name: 'connect:acme' })
600 const question = await vi.waitFor(async () => {
601 const snapshot = await fetch(`${server.url}/snapshot?threadId=t`, {
602 headers: { authorization: 'Bearer secret' },
603 })
604 const [pending] = (await snapshot.json()).pendingWaits
605 expect(pending).toBeDefined()
606 return pending
607 })
608 await control({
609 op: 'answer',
610 questionId: question.waitId,
611 value: 'sk-ada',
612 })
613 await vi.waitFor(async () =>
614 expect(
615 await credentials.get({
616 scope: { threadId: 't', userId: 'ada' },
617 id: 'acme',
618 }),
619 ).toEqual({ type: 'api_key', value: 'sk-ada' }),
620 )
621 } finally {
622 await server.close()
623 await host.close()
624 }
625 })
626
627 it('serves /mcp as the user', async () => {
628 const host = createHarnessHost({ persistence: memoryPersistence() })
629 const server = await serve({
630 host,
631 harness: defineHarness({
632 name: 'test/serve-mcp',
633 adapter: scripted([textTurn('ok')]).adapter,
634 }),
635 port: 0,
636 hostname: '127.0.0.1',
637 token: 'secret',
638 user: { id: 'ada' },
639 })
640 const client = await createMCPClient({
641 transport: {
642 type: 'http',
643 url: `${server.url}/mcp`,
644 headers: { authorization: 'Bearer secret' },
645 },
646 })
647 try {
648 await client.callTool('chat', { threadId: 't-mcp', message: 'hi' })
649
650 expect(await host.sessions.get({ threadId: 't-mcp' })).toMatchObject({
651 members: [{ userId: 'ada', role: 'owner' }],
652 })
653 } finally {
654 await client.close()
655 await server.close()
656 await host.close()
657 }
658 })
659
660 it('passes the user to --acp, so a host with access starts', async () => {
661 const host = accessHost()
662 // The agent reads process.stdin. Ending it ends the agent.
663 const ends: Array<() => void> = []
664 const on = vi
665 .spyOn(process.stdin, 'on')
666 .mockImplementation((event: string | symbol, listener: () => void) => {
667 if (event === 'end') ends.push(listener)
668 return process.stdin
669 })
670 const stderr = capture()
671 try {
672 const running = runCli(
673 defineHarness({ name: 'test/acp', adapter: scripted([]).adapter }),
674 { argv: ['--acp'], stdout: capture(), stderr, host, user: olga },
675 )
676 await vi.waitFor(() => expect(ends).toHaveLength(1))
677 for (const end of ends) end()
678
679 expect(await running).toBe(EXIT.ok)
680 expect(stderr.text).toBe('')
681 } finally {
682 on.mockRestore()
683 await host.close()
684 }
685 })
686
687 it('refuses --mcp on a host with access, as stdio has no login', async () => {
688 const host = accessHost()
689 const stderr = capture()
690
691 const code = await runCli(
692 defineHarness({ name: 'test/mcp', adapter: scripted([]).adapter }),
693 { argv: ['--mcp'], stdout: capture(), stderr, host, user: olga },
694 )
695
696 expect(code).toBe(EXIT.failed)
697 expect(stderr.text).toBe(
698 '--mcp serves over stdio, which has no login, so it cannot use a host with access. Give runCli a host without access, and the local user as the user option.\n',
699 )
700 await host.close()
701 })
702})
703
704describe('serve mode', () => {
705 it('serves the session protocol and requires the token', async () => {
706 const { adapter } = scripted([textTurn('served')])
707 const harness = defineHarness({ name: 'test/serve', adapter })
708 const host = createHarnessHost({ persistence: memoryPersistence() })
709 const server = await serve({
710 host,
711 harness,
712 port: 0,
713 hostname: '127.0.0.1',
714 token: 'secret',
715 })
716 try {
717 const denied = await fetch(`${server.url}/capabilities`)
718 expect(denied.status).toBe(401)
719 const wrong = await fetch(`${server.url}/capabilities`, {
720 headers: { authorization: 'Bearer nope' },
721 })
722 expect(wrong.status).toBe(401)
723 const capabilities = await fetch(`${server.url}/capabilities`, {
724 headers: { authorization: 'Bearer secret' },
725 })
726 expect((await capabilities.json()).identity.name).toBe('test/serve')
727 const receipt = await fetch(`${server.url}/control`, {
728 method: 'POST',
729 headers: {
730 authorization: 'Bearer secret',
731 'content-type': 'application/json',
732 },
733 body: JSON.stringify({
734 threadId: 't',
735 input: { op: 'prompt', message: 'hi' },
736 }),
737 })
738 expect((await receipt.json()).status).toBe('accepted')
739 } finally {
740 await server.close()
741 await host.close()
742 }
743 })
744
745 it('signs media URLs with --media-key, never with the token', async () => {
746 expect(parseCliArgs(['--serve', '--media-key', 'k'])).toMatchObject({
747 mediaKey: 'k',
748 })
749 const host = createHarnessHost({ persistence: memoryPersistence() })
750 const start = (mediaKey?: string) =>
751 serve({
752 host,
753 harness: defineHarness({
754 name: 'test/serve-key',
755 adapter: scripted([]).adapter,
756 }),
757 port: 0,
758 hostname: '127.0.0.1',
759 token: 'secret',
760 ...(mediaKey !== undefined ? { mediaKey } : {}),
761 })
762
763 // The key is checked: a short one is refused at the start.
764 await expect(start('short')).rejects.toThrow('Media signing key 0 is 5')
765 // A short token is fine: it does not sign anything.
766 const server = await start()
767 await server.close()
768 await host.close()
769 })
770
771 it('reads the user of each request with getUser on a host with access, behind the token', async () => {
772 const host = accessHost()
773 const server = await serve({
774 host,
775 harness: defineHarness({
776 name: 'test/serve-access',
777 adapter: scripted([textTurn('ok')]).adapter,
778 }),
779 port: 0,
780 hostname: '127.0.0.1',
781 token: 'secret',
782 })
783 const call = (path: string, headers: Record<string, string>) =>
784 fetch(`${server.url}/${path}`, { headers })
785 const prompt = (headers: Record<string, string>) =>
786 fetch(`${server.url}/control`, {
787 method: 'POST',
788 headers: { 'content-type': 'application/json', ...headers },
789 body: JSON.stringify({
790 threadId: 't1',
791 input: { op: 'prompt', message: 'hi' },
792 }),
793 })
794 const token = { authorization: 'Bearer secret' }
795 try {
796 expect((await prompt({ ...token, 'x-user': 'olga' })).status).toBe(200)
797
798 const noToken = await call('transcript?threadId=t1', { 'x-user': 'olga' })
799 expect(noToken.status).toBe(401)
800 const noUser = await call('transcript?threadId=t1', token)
801 expect(noUser.status).toBe(401)
802 const stranger = await call('transcript?threadId=t1', {
803 ...token,
804 'x-user': 'cid',
805 })
806 expect(stranger.status).toBe(403)
807 expect(
808 await host.sessions.get({ threadId: 't1', user: olga }),
809 ).toMatchObject({ members: [{ userId: 'olga', role: 'owner' }] })
810 } finally {
811 await server.close()
812 await host.close()
813 }
814 })
815})
816
817describe('custom ui', () => {
818 it('gives an interactive terminal a ready session view and waits for the ui', async () => {
819 const { adapter } = scripted([textTurn('Hi from the ui.')])
820 const seen: Array<string> = []
821 const code = await runCli(defineHarness({ name: 'test/ui', adapter }), {
822 argv: [],
823 stdin: stdinFrom([], { isTTY: true }),
824 stdout: capture(),
825 stderr: capture(),
826 persistence: memoryPersistence(),
827 ui: async (view) => {
828 seen.push(view.store.get().threadId)
829 await view.send('hello')
830 await vi.waitFor(() =>
831 expect(JSON.stringify(view.store.get().messages)).toContain(
832 'Hi from the ui.',
833 ),
834 )
835 },
836 })
837 expect(code).toBe(EXIT.ok)
838 expect(seen).toEqual(['main'])
839 })
840
841 it('changes the thread settings and resets the context from the ui view', async () => {
842 const harness = defineHarness({
843 name: 'test/ui-actions',
844 adapter: scripted([]).adapter,
845 })
846 const host = createHarnessHost({ persistence: memoryPersistence() })
847 let errors: Array<string> = []
848 try {
849 const code = await runCli(harness, {
850 argv: [],
851 stdin: stdinFrom([], { isTTY: true }),
852 stdout: capture(),
853 stderr: capture(),
854 host,
855 ui: async (view) => {
856 await view.updateThreadSettings({
857 settings: { instructions: 'Answer in French.' },
858 })
859 await view.reset({ note: 'Start over.' })
860 errors = view.store
861 .get()
862 .messages.flatMap((message) =>
863 message.role === 'notice' && message.kind === 'error'
864 ? [message.text]
865 : [],
866 )
867 },
868 })
869 const session = await host.open(harness, { threadId: 'main' })
870 await session.whenIdle()
871
872 expect(code).toBe(EXIT.ok)
873 expect(errors).toEqual([])
874 expect(session.threadSettings()).toEqual({
875 instructions: 'Answer in French.',
876 })
877 expect(await session.transcript()).toMatchObject([
878 {
879 role: 'user',
880 content: 'Start over.',
881 metadata: { harness: { reset: { note: 'Start over.' } } },
882 },
883 ])
884 } finally {
885 await host.close()
886 }
887 })
888
889 it('uses line mode for piped input, even with a ui', async () => {
890 const { adapter } = scripted([textTurn('Piped answer.')])
891 const stdout = capture()
892 const ui = vi.fn()
893 const code = await runCli(
894 defineHarness({ name: 'test/ui-piped', adapter }),
895 {
896 argv: [],
897 stdin: stdinFrom(['hello\n'], { isTTY: false }),
898 stdout,
899 stderr: capture(),
900 persistence: memoryPersistence(),
901 ui,
902 },
903 )
904 expect(code).toBe(EXIT.ok)
905 expect(ui).not.toHaveBeenCalled()
906 expect(stdout.text).toContain('Piped answer.')
907 })
908
909 it('uses line mode in a terminal without a ui', async () => {
910 const { adapter } = scripted([textTurn('Terminal answer.')])
911 const stdout = capture()
912 const code = await runCli(
913 defineHarness({ name: 'test/ui-none', adapter }),
914 {
915 argv: [],
916 stdin: stdinFrom(['hello\n'], { isTTY: true }),
917 stdout,
918 stderr: capture(),
919 persistence: memoryPersistence(),
920 },
921 )
922 expect(code).toBe(EXIT.ok)
923 expect(stdout.text).toContain('Terminal answer.')
924 })
925})