-
-
Notifications
You must be signed in to change notification settings - Fork 327
fix(ai-persistence): preserve cancelled tool resumes #1090
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| --- | ||
| '@tanstack/ai-persistence': patch | ||
| --- | ||
|
|
||
| `withPersistence` now maps cancelled client-tool and approval resume entries | ||
| into `cancelledToolCallIds`. A resume batch that is only cancellations still | ||
| produces a `resumeToolState`, so the engine can complete the turn instead of | ||
| emitting another `client_tool_*` interrupt. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| import { describe, expect, it, vi } from 'vitest' | ||
| import { EventType, chat } from '@tanstack/ai' | ||
| import { EventType, chat, defineChatMiddleware } from '@tanstack/ai' | ||
| import type { AnyTextAdapter, StreamChunk, Tool } from '@tanstack/ai' | ||
| import { memoryPersistence } from '../src/memory' | ||
| import { withPersistence } from '../src/middleware' | ||
|
|
@@ -87,6 +87,39 @@ const runFinished = (runId = 'r1'): StreamChunk => ({ | |
| timestamp: 1, | ||
| }) | ||
|
|
||
| const toolCallFinished = (runId = 'r1'): StreamChunk => ({ | ||
| type: EventType.RUN_FINISHED, | ||
| runId, | ||
| threadId: 't1', | ||
| finishReason: 'tool_calls', | ||
| timestamp: 1, | ||
| }) | ||
|
|
||
| const toolCallChunks = () => [ | ||
| runStarted(), | ||
| toolStart(), | ||
| toolArgs(), | ||
| toolCallFinished(), | ||
| ] | ||
|
|
||
| async function persistClientToolTurn( | ||
| persistence: ReturnType<typeof memoryPersistence>, | ||
| tools: Array<Tool>, | ||
| ) { | ||
| const first = mockAdapter([toolCallChunks()]) | ||
| await collect( | ||
| chat({ | ||
| adapter: first.adapter, | ||
| messages: [{ role: 'user', content: 'hi' }], | ||
| tools, | ||
| runId: 'r1', | ||
| threadId: 't1', | ||
| middleware: [withPersistence(persistence)], | ||
| }) as AsyncIterable<StreamChunk>, | ||
| ) | ||
| return first | ||
| } | ||
|
|
||
| const clientTool = (name: string): Tool => ({ | ||
| name, | ||
| description: `${name} client tool`, | ||
|
|
@@ -144,20 +177,7 @@ describe('interrupt persistence', () => { | |
| it('does not persist duplicate records before terminal interrupt outcome', async () => { | ||
| const persistence = memoryPersistence() | ||
| const create = vi.spyOn(persistence.stores.interrupts!, 'create') | ||
| const { adapter } = mockAdapter([ | ||
| [ | ||
| runStarted(), | ||
| toolStart(), | ||
| toolArgs(), | ||
| { | ||
| type: EventType.RUN_FINISHED, | ||
| runId: 'r1', | ||
| threadId: 't1', | ||
| finishReason: 'tool_calls', | ||
| timestamp: 1, | ||
| }, | ||
| ], | ||
| ]) | ||
| const { adapter } = mockAdapter([toolCallChunks()]) | ||
|
|
||
| await collect( | ||
| chat({ | ||
|
|
@@ -260,29 +280,9 @@ describe('interrupt persistence', () => { | |
| // interrupt. Feeding the client output then drives exactly one model call. | ||
| it('applies persisted approval and client-tool resume decisions with empty client messages', async () => { | ||
| const persistence = memoryPersistence() | ||
| const toolCallChunks = () => [ | ||
| runStarted(), | ||
| toolStart(), | ||
| toolArgs(), | ||
| { | ||
| type: EventType.RUN_FINISHED, | ||
| runId: 'r1', | ||
| threadId: 't1', | ||
| finishReason: 'tool_calls', | ||
| timestamp: 1, | ||
| } as StreamChunk, | ||
| ] | ||
| const first = mockAdapter([toolCallChunks()]) | ||
| await collect( | ||
| chat({ | ||
| adapter: first.adapter, | ||
| messages: [{ role: 'user', content: 'hi' }], | ||
| tools: [approvalClientTool('clientSearch')], | ||
| runId: 'r1', | ||
| threadId: 't1', | ||
| middleware: [withPersistence(persistence)], | ||
| }) as AsyncIterable<StreamChunk>, | ||
| ) | ||
| await persistClientToolTurn(persistence, [ | ||
| approvalClientTool('clientSearch'), | ||
| ]) | ||
|
|
||
| const approvalInterrupt = await persistence.stores.interrupts!.get( | ||
| 'approval_tool-call-1', | ||
|
|
@@ -373,6 +373,65 @@ describe('interrupt persistence', () => { | |
| expect(await persistence.stores.interrupts!.listPending('t1')).toEqual([]) | ||
| }) | ||
|
|
||
| // Issue #1088: cancelling a hydrated client-tool interrupt under | ||
| // withPersistence must complete the turn. Persistence clears `config.resume` | ||
| // and must therefore put the cancelled toolCallId on `cancelledToolCallIds`. | ||
| // Otherwise the engine treats the stored tool call as unhandled and emits | ||
| // another `client_tool_*` interrupt instead of an output-error. | ||
| it('completes a cancelled client-tool resume from persisted state with empty client messages', async () => { | ||
| const persistence = memoryPersistence() | ||
| await persistClientToolTurn(persistence, [clientTool('clientSearch')]) | ||
|
|
||
| const pending = await persistence.stores.interrupts!.get( | ||
| 'client_tool_tool-call-1', | ||
| ) | ||
| expect(pending?.status).toBe('pending') | ||
|
|
||
| const afterCancel = mockAdapter([ | ||
| [runStarted(), text('cancelled-and-done'), runFinished('r1')], | ||
| ]) | ||
| const chunks = await collect( | ||
| chat({ | ||
| adapter: afterCancel.adapter, | ||
| messages: [], | ||
| tools: [clientTool('clientSearch')], | ||
| runId: 'r1', | ||
| threadId: 't1', | ||
| resume: [ | ||
| { | ||
| interruptId: 'client_tool_tool-call-1', | ||
| status: 'cancelled', | ||
| }, | ||
| ], | ||
| middleware: [withPersistence(persistence)], | ||
| }) as AsyncIterable<StreamChunk>, | ||
| ) | ||
|
|
||
| expect(afterCancel.calls).toHaveLength(1) | ||
| expect(chunks).toContainEqual( | ||
| expect.objectContaining({ | ||
| type: EventType.TOOL_CALL_RESULT, | ||
| toolCallId: 'tool-call-1', | ||
| content: JSON.stringify({ error: 'Tool execution cancelled' }), | ||
| }), | ||
| ) | ||
| expect( | ||
| chunks.find( | ||
| (chunk) => | ||
| chunk.type === EventType.RUN_FINISHED && | ||
| chunk.outcome?.type === 'interrupt', | ||
| ), | ||
| ).toBeUndefined() | ||
| expect(chunks).toContainEqual( | ||
| expect.objectContaining({ delta: 'cancelled-and-done' }), | ||
| ) | ||
| expect( | ||
| (await persistence.stores.interrupts!.get('client_tool_tool-call-1')) | ||
| ?.status, | ||
| ).toBe('cancelled') | ||
| expect(await persistence.stores.interrupts!.listPending('t1')).toEqual([]) | ||
| }) | ||
|
|
||
| it('rejects invalid resume entries against pending interrupts', async () => { | ||
| const persistence = memoryPersistence() | ||
| const first = mockAdapter([[runStarted(), interruptFinished()]]) | ||
|
|
@@ -775,21 +834,29 @@ describe('interrupt persistence', () => { | |
| }) | ||
|
|
||
| const run = mockAdapter([[runStarted(), text('ok'), runFinished('r1')]]) | ||
| const resumeStates: Array<ReadonlySet<string> | undefined> = [] | ||
| const observeResumeState = defineChatMiddleware({ | ||
| name: 'observe-resume-state', | ||
| onConfig(_ctx, config) { | ||
| resumeStates.push(config.resumeToolState?.cancelledToolCallIds) | ||
| }, | ||
| }) | ||
| await collect( | ||
| chat({ | ||
| adapter: run.adapter, | ||
| messages: [], | ||
| runId: 'r1', | ||
| threadId: 't1', | ||
| resume: [{ interruptId: 'approval-1', status: 'cancelled' }], | ||
| middleware: [withPersistence(persistence)], | ||
| middleware: [withPersistence(persistence), observeResumeState], | ||
| }) as AsyncIterable<StreamChunk>, | ||
| ) | ||
|
|
||
| const approvals = ( | ||
| run.calls[0] as { approvals?: ReadonlyMap<string, boolean> } | ||
| ).approvals | ||
| expect(approvals?.get('approval-1')).toBe(false) | ||
| expect(resumeStates[0]?.has('tc1')).toBe(true) | ||
| expect( | ||
| (await persistence.stores.interrupts!.get('approval-1'))?.status, | ||
| ).toBe('cancelled') | ||
|
|
@@ -806,6 +873,13 @@ describe('interrupt persistence', () => { | |
| }) | ||
|
|
||
| const run = mockAdapter([[runStarted(), text('ok'), runFinished('r1')]]) | ||
| const resumeStates: Array<ReadonlySet<string> | undefined> = [] | ||
| const observeResumeState = defineChatMiddleware({ | ||
| name: 'observe-resume-state', | ||
| onConfig(_ctx, config) { | ||
| resumeStates.push(config.resumeToolState?.cancelledToolCallIds) | ||
| }, | ||
| }) | ||
| await collect( | ||
| chat({ | ||
| adapter: run.adapter, | ||
|
|
@@ -819,7 +893,7 @@ describe('interrupt persistence', () => { | |
| payload: { answer: 99 }, | ||
| }, | ||
| ], | ||
| middleware: [withPersistence(persistence)], | ||
| middleware: [withPersistence(persistence), observeResumeState], | ||
| }) as AsyncIterable<StreamChunk>, | ||
| ) | ||
|
|
||
|
|
@@ -829,6 +903,7 @@ describe('interrupt persistence', () => { | |
| run.calls[0] as { clientToolResults?: ReadonlyMap<string, unknown> } | ||
| ).clientToolResults | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [suggestion] The new assertions only prove the translator wrote Suggestion: Add a regression that mirrors that hydrate path for |
||
| expect(clientToolResults?.get('tc1')).toBeUndefined() | ||
| expect(resumeStates[0]?.has('tc1')).toBe(true) | ||
| expect((await persistence.stores.interrupts!.get('client-1'))?.status).toBe( | ||
| 'cancelled', | ||
| ) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: TanStack/ai
Length of output: 50368
🏁 Script executed:
Repository: TanStack/ai
Length of output: 26750
🏁 Script executed:
Repository: TanStack/ai
Length of output: 24031
🏁 Script executed:
Repository: TanStack/ai
Length of output: 45004
🏁 Script executed:
Repository: TanStack/ai
Length of output: 50367
🏁 Script executed:
Repository: TanStack/ai
Length of output: 31148
🏁 Script executed:
Repository: TanStack/ai
Length of output: 419
Use
toolDefinition()for the client-tool fixtures.Define the shared metadata with a Zod schema, such as
z.object({ query: z.string() }). Keep this client-only fixture as a bare definition or use.client();.server()is not required becausechat()treats tools withoutexecuteas client-side.🤖 Prompt for AI Agents
Source: Coding guidelines