Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { buildPrompt } from '../src/messages/prompt'
3import type { ModelMessage } from '@tanstack/ai'
4
5const user = (content: ModelMessage['content']): ModelMessage => ({
6 role: 'user',
7 content,
8})
9const assistant = (content: ModelMessage['content']): ModelMessage => ({
10 role: 'assistant',
11 content,
12})
13
14describe('buildPrompt', () => {
15 it('resumes with only the last user message when sessionId is provided', () => {
16 const result = buildPrompt(
17 [
18 user('first question'),
19 assistant('first answer'),
20 user('follow-up question'),
21 ],
22 'sess-1',
23 )
24 expect(result).toEqual({ prompt: 'follow-up question', resume: 'sess-1' })
25 })
26
27 it('throws when sessionId is provided but there is no trailing user message', () => {
28 expect(() => buildPrompt([user('q'), assistant('a')], 'sess-1')).toThrow(
29 /user message/i,
30 )
31 })
32
33 it('sends a single user message as-is for a fresh session', () => {
34 expect(buildPrompt([user('hello')], undefined)).toEqual({ prompt: 'hello' })
35 })
36
37 it('flattens prior turns into a transcript preamble for fresh multi-turn history', () => {
38 const { prompt, resume } = buildPrompt(
39 [user('What is 2+2?'), assistant('4'), user('And times 3?')],
40 undefined,
41 )
42 expect(resume).toBeUndefined()
43 expect(prompt).toBe(
44 'Previous conversation:\nUser: What is 2+2?\nAssistant: 4\n\nAnd times 3?',
45 )
46 })
47
48 it('skips tool messages and assistant tool-call-only turns when flattening', () => {
49 const messages: Array<ModelMessage> = [
50 user('list files'),
51 {
52 role: 'assistant',
53 content: null,
54 toolCalls: [
55 {
56 id: 't1',
57 type: 'function',
58 function: { name: 'ls', arguments: '{}' },
59 },
60 ],
61 } as unknown as ModelMessage,
62 { role: 'tool', content: 'file-a', toolCallId: 't1' },
63 assistant('There is one file.'),
64 user('thanks, which one?'),
65 ]
66 const { prompt } = buildPrompt(messages, undefined)
67 expect(prompt).toBe(
68 'Previous conversation:\nUser: list files\nAssistant: There is one file.\n\nthanks, which one?',
69 )
70 })
71
72 it('extracts text from content-part arrays and ignores non-text parts', () => {
73 const { prompt } = buildPrompt(
74 [
75 user([
76 { type: 'text', content: 'describe ' },
77 {
78 type: 'image',
79 source: { type: 'url', url: 'https://x/y.png' },
80 } as never,
81 { type: 'text', content: 'this' },
82 ] as ModelMessage['content']),
83 ],
84 undefined,
85 )
86 expect(prompt).toBe('describe this')
87 })
88
89 it('throws when there is no usable user content at all', () => {
90 expect(() => buildPrompt([], undefined)).toThrow(/user message/i)
91 })
92})