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

api.interrupts.test.ts

123 lines3.8 KB

1import { describe, expect, it } from 'vitest'
2import { EventType } from '@tanstack/ai'
3import {
4 createFeedingMiddleware,
5 feedingInterruptId,
6 resolveToolChoice,
7} from './api.interrupts'
8import type {
9 ChatMiddlewareConfig,
10 ChatMiddlewareContext,
11 StreamChunk,
12} from '@tanstack/ai'
13​
14function makeCtx(
15 overrides: Partial<ChatMiddlewareContext>,
16): ChatMiddlewareContext {
17 return {
18 requestId: 'req',
19 streamId: 'stream',
20 runId: 'run-1',
21 threadId: 'thread-1',
22 phase: 'init',
23 iteration: 0,
24 chunkIndex: 0,
25 abort: () => {},
26 defer: () => {},
27 context: undefined,
28 ...overrides,
29 } as unknown as ChatMiddlewareContext
31​
32describe('resolveToolChoice', () => {
33 // Regression: forcing a tool on the continuation made the model re-call the
34 // just-approved tool instead of answering, leaving an empty reply.
35 it('never forces a tool on a continuation (resume)', () => {
36 expect(
37 resolveToolChoice({ isResume: true, forceTool: 'admitRescue' }),
38 ).toBeUndefined()
39 expect(resolveToolChoice({ isResume: true, generic: true })).toBeUndefined()
40 })
41​
42 it('forces the requested tool on the first turn', () => {
43 expect(
44 resolveToolChoice({ isResume: false, forceTool: 'admitRescue' }),
45 ).toEqual({ type: 'function', name: 'admitRescue' })
46 })
47​
48 it('forbids tools for the generic scenario', () => {
49 expect(resolveToolChoice({ isResume: false, generic: true })).toBe('none')
50 })
51​
52 it('defaults to auto (undefined) with no hints', () => {
53 expect(resolveToolChoice({ isResume: false })).toBeUndefined()
54 })
55})
56​
57describe('feeding interrupt correlation', () => {
58 // Regression: the interrupt id was built from the provider chunk.runId
59 // (e.g. `openai-...`), but the client resumes with the request runId as
60 // parentRunId, so the ids never matched and resume failed as
61 // `unknown-interrupt`. It must key off ctx.runId.
62 it('keys the interrupt id off the request run id, not the provider chunk id', () => {
63 const middleware = createFeedingMiddleware()
64 const chunk = {
65 type: EventType.RUN_FINISHED,
66 runId: 'openai-provider-9',
67 threadId: 'thread-1',
68 timestamp: 0,
69 outcome: { type: 'success' },
70 } as unknown as StreamChunk
71​
72 const result = middleware.onChunk?.(makeCtx({ runId: 'req-1' }), chunk)
73 const outcome = (
74 result as { outcome?: { interrupts?: Array<{ id: string }> } } | undefined
75 )?.outcome
76 expect(outcome?.interrupts?.[0]?.id).toBe(feedingInterruptId('req-1'))
77 expect(outcome?.interrupts?.[0]?.id).not.toContain('openai-provider-9')
78 })
79​
80 it('accepts a resume that references feeding_<requestRunId>', () => {
81 const middleware = createFeedingMiddleware()
82 const config = {
83 messages: [{ role: 'user', content: 'set a feeding schedule' }],
84 resume: [
85 {
86 interruptId: feedingInterruptId('req-1'),
87 status: 'resolved',
88 payload: { mealsPerDay: 2, diet: 'mice and berries' },
89 },
90 ],
91 } as unknown as ChatMiddlewareConfig
92​
93 const patch = middleware.onConfig?.(
94 makeCtx({ phase: 'init', parentRunId: 'req-1' }),
95 config,
96 )
97 const messages = (patch as { messages?: Array<unknown> } | undefined)
98 ?.messages
99 // original message plus the appended confirmation prompt
100 expect(messages?.length).toBe(2)
101 })
102​
103 it('rejects a resume that references a different run id', () => {
104 const middleware = createFeedingMiddleware()
105 const config = {
106 messages: [],
107 resume: [
108 {
109 interruptId: feedingInterruptId('openai-provider-9'),
110 status: 'resolved',
111 payload: { mealsPerDay: 2, diet: 'mice and berries' },
112 },
113 ],
114 } as unknown as ChatMiddlewareConfig
115​
116 expect(() =>
117 middleware.onConfig?.(
118 makeCtx({ phase: 'init', parentRunId: 'req-1' }),
119 config,
120 ),
121 ).toThrow(/must resolve only/)
122 })
123})