Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-1107-snapshot-message-ids.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/ai': patch
---

Preserve existing message IDs on interrupt `MESSAGES_SNAPSHOT` events.
4 changes: 3 additions & 1 deletion packages/ai/src/activities/chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2177,7 +2177,9 @@ class TextEngine<
? undefined
: JSON.stringify(message.content)
return {
id: `snapshot_${this.runIdOverride ?? this.requestId}_${index}`,
id:
message.id ||
`snapshot_${this.runIdOverride ?? this.requestId}_${index}`,
role: message.role,
...(content !== undefined ? { content } : {}),
...('toolCalls' in message && message.toolCalls
Expand Down
66 changes: 66 additions & 0 deletions packages/ai/tests/chat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,72 @@ describe('chat()', () => {
})
})

it('preserves existing message ids on the interrupt MESSAGES_SNAPSHOT', async () => {
const { adapter } = createMockAdapter({
iterations: [
[
ev.runStarted(),
ev.textStart('stream-assistant'),
{
...ev.toolStart('call_1', 'clientSearch'),
parentMessageId: 'stream-assistant',
},
ev.toolArgs('call_1', '{"query":"test"}'),
ev.runFinished('tool_calls'),
],
],
})

const chunks = await collectChunks(
chat({
adapter,
runId: 'interrupt-run',
messages: [{ id: 'user-1', role: 'user', content: 'Search' }],
tools: [clientTool('clientSearch')],
}) as AsyncIterable<StreamChunk>,
)

const snapshot = chunks.find(
(chunk) => chunk.type === EventType.MESSAGES_SNAPSHOT,
)
expect(snapshot).toMatchObject({
messages: [
{ id: 'user-1', role: 'user', content: 'Search' },
{ id: 'stream-assistant', role: 'assistant' },
],
})
})

it('generates a snapshot id on the interrupt MESSAGES_SNAPSHOT when a message has no id', async () => {
const { adapter } = createMockAdapter({
iterations: [
[
ev.runStarted(),
ev.toolStart('call_1', 'clientSearch'),
ev.toolArgs('call_1', '{"query":"test"}'),
ev.runFinished('tool_calls'),
],
],
})

const chunks = await collectChunks(
chat({
adapter,
runId: 'interrupt-run',
messages: [{ role: 'user', content: 'Search' }],
tools: [clientTool('clientSearch')],
}) as AsyncIterable<StreamChunk>,
)

const snapshot = chunks.find(
(chunk) => chunk.type === EventType.MESSAGES_SNAPSHOT,
)
expect(snapshot?.messages[0]).toMatchObject({
id: 'snapshot_interrupt-run_0',
role: 'user',
})
})

it('should yield an interrupt outcome for client tools', async () => {
const { adapter } = createMockAdapter({
iterations: [
Expand Down
Loading