Skip to content
Merged
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
8 changes: 8 additions & 0 deletions .changeset/cancelled-client-tool-resume.md
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.
15 changes: 13 additions & 2 deletions packages/ai-persistence/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,7 @@ function resumeToolStateFromPending(
): ChatResumeToolState | undefined {
const approvals = new Map<string, ToolApprovalResolution>()
const clientToolResults = new Map<string, unknown>()
const cancelledToolCallIds = new Set<string>()

for (const interrupt of pending) {
const entry = resumeByInterruptId.get(interrupt.interruptId)
Expand All @@ -405,6 +406,10 @@ function resumeToolStateFromPending(
const reason = stringField(interrupt.payload, 'reason')
const toolCallId = stringField(interrupt.payload, 'toolCallId')

if (entry.status === 'cancelled' && toolCallId) {
cancelledToolCallIds.add(toolCallId)
}

if (kind === 'approval' || reason === 'approval_required') {
approvals.set(interrupt.interruptId, resolvedApprovalDecision(entry))
continue
Expand All @@ -419,8 +424,14 @@ function resumeToolStateFromPending(
}
}

if (approvals.size === 0 && clientToolResults.size === 0) return undefined
return { approvals, clientToolResults }
if (
approvals.size === 0 &&
clientToolResults.size === 0 &&
cancelledToolCallIds.size === 0
) {
return undefined
}
return { approvals, clientToolResults, cancelledToolCallIds }
}

/**
Expand Down
155 changes: 115 additions & 40 deletions packages/ai-persistence/tests/interrupts.test.ts
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'
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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')],
Comment on lines +381 to +397

Copy link
Copy Markdown
Contributor

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:

#!/bin/bash
set -euo pipefail

# Find repository examples of the required tool builder and implementations.
rg -n -C 4 --glob '*.{ts,tsx}' '\btoolDefinition\s*\(' packages
rg -n -C 3 --glob '*.{ts,tsx}' '\.(server|client)\s*\(' packages

Repository: TanStack/ai

Length of output: 50368


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- target file imports and fixture definitions ---'
sed -n '1,130p' packages/ai-persistence/tests/interrupts.test.ts
rg -n -C 8 'clientTool|persistClientToolTurn|toolDefinition|from .*zod' packages/ai-persistence/tests/interrupts.test.ts

echo '--- toolDefinition API declarations and focused examples ---'
rg -n -C 6 'export .*toolDefinition|function toolDefinition|class ToolDefinition|\.server\(|\.client\(' packages/ai-core packages/ai-client packages/ai-persistence --glob '*.{ts,tsx}' | head -n 240

Repository: TanStack/ai

Length of output: 26750


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- candidate source files ---'
fd -i 'tool' packages --type f | grep -E '(definition|types|index)\.(ts|tsx)$' | head -n 120

echo '--- toolDefinition declarations and Tool types ---'
rg -n -C 12 'toolDefinition|export type Tool|interface Tool|type ToolDefinition' packages --glob '*.{ts,tsx}' \
  | grep -v '/tests/' | head -n 320

echo '--- persistence test imports and all fixture uses ---'
rg -n -C 3 'from .*(ai|zod)|clientTool\(|approvalClientTool\(' packages/ai-persistence/tests/interrupts.test.ts

Repository: TanStack/ai

Length of output: 24031


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- tool-definition implementation ---'
wc -l packages/ai/src/activities/chat/tools/tool-definition.ts
cat -n packages/ai/src/activities/chat/tools/tool-definition.ts

echo '--- exports and core tool types ---'
rg -n -C 8 'tool-definition|ToolDefinition|ServerTool|ClientTool|interface Tool|type Tool' packages/ai/src packages/ai-client/src --glob '*.{ts,tsx}' | head -n 360

echo '--- nearby persistence test tool fixtures and imports ---'
sed -n '1,145p' packages/ai-persistence/tests/interrupts.test.ts

Repository: TanStack/ai

Length of output: 45004


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- runtime classification of tools without execute ---'
rg -n -C 10 'execute\?|typeof .*execute|__toolSide|ClientToolRequest|client tool|client-tool' packages/ai/src/activities packages/ai/src --glob '*.{ts,tsx}' | head -n 360

echo '--- target test assertions for the client-tool fixtures ---'
sed -n '260,455p' packages/ai-persistence/tests/interrupts.test.ts

echo '--- imports and package test conventions for Zod/toolDefinition ---'
rg -n -C 5 'from .*(zod|`@tanstack/ai`)|toolDefinition\(\{' packages/ai-persistence/tests packages/ai-persistence/src --glob '*.{ts,tsx}' | head -n 220

Repository: TanStack/ai

Length of output: 50367


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- exact tool execution branch ---'
sed -n '760,900p' packages/ai/src/activities/chat/tools/tool-calls.ts

echo '--- Tool base type and schema conversion ---'
rg -n -C 14 'export interface Tool|export type Tool|type AnyTool|inputSchema' packages/ai/src/types.ts packages/ai/src --glob '*.ts' \
  | head -n 260

echo '--- direct-definition documentation and client-side examples ---'
sed -n '276,330p' packages/ai/src/activities/chat/tools/tool-definition.ts
rg -n -C 5 'toolDefinition\(\{[^}]*name: .*(client|lookup|search)|\.client\(\)' packages/ai-client/tests packages/ai/src --glob '*.{ts,tsx}' | head -n 180

Repository: TanStack/ai

Length of output: 31148


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

test = Path("packages/ai-persistence/tests/interrupts.test.ts").read_text()
definition = Path("packages/ai/src/activities/chat/tools/tool-definition.ts").read_text()
calls = Path("packages/ai/src/activities/chat/tools/tool-calls.ts").read_text()

raw = re.search(
    r"const clientTool = \(name: string\): Tool => \(\{(?P<body>.*?)\n\}\)",
    test,
    re.S,
)
assert raw, "clientTool fixture not found"
body = raw.group("body")

assert "execute" not in body
assert "inputSchema" not in body
assert "toolDefinition" not in body

assert "Used directly in chat() on the server" in definition
assert re.search(r"server:\s*<", definition)
assert re.search(r"client:\s*<", definition)

client_branch = re.search(
    r"// CASE 1: Client-side tool \(no execute function\)(?P<body>.*?)(?=\n\s*// CASE 2:|\Z)",
    calls,
    re.S,
)
assert client_branch, "client-side execution branch not found"
assert "if (!tool.execute)" in calls
assert "if (tool.inputSchema && isStandardSchema(tool.inputSchema))" in calls

print("raw_fixture_has_execute:", "execute" in body)
print("raw_fixture_has_input_schema:", "inputSchema" in body)
print("tool_definition_supports_direct_server_use:", True)
print("tool_definition_exposes_server_and_client_builders:", True)
print("runtime_classifies_no_execute_as_client_tool:", True)
print("runtime_validates_standard_input_schema:", True)
PY

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 because chat() treats tools without execute as client-side.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ai-persistence/tests/interrupts.test.ts` around lines 381 - 397,
Update the client-tool fixtures used by the test around persistClientToolTurn
and chat to use toolDefinition() with shared metadata defined by a Zod schema
such as z.object({ query: z.string() }). Keep the fixture client-only by leaving
it without execute or marking it with .client(), and do not use .server().

Source: Coding guidelines

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()]])
Expand Down Expand Up @@ -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')
Expand All @@ -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,
Expand All @@ -819,7 +893,7 @@ describe('interrupt persistence', () => {
payload: { answer: 99 },
},
],
middleware: [withPersistence(persistence)],
middleware: [withPersistence(persistence), observeResumeState],
}) as AsyncIterable<StreamChunk>,
)

Expand All @@ -829,6 +903,7 @@ describe('interrupt persistence', () => {
run.calls[0] as { clientToolResults?: ReadonlyMap<string, unknown> }
).clientToolResults

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] The new assertions only prove the translator wrote cancelledToolCallIds. Both cancel tests still use empty messages, no tools, and no stored thread with a pending assistant tool call. The engine therefore never reaches checkForPendingToolCalls() / executeToolCalls(), so these tests cannot fail if a cancelled hydrated client tool still re-interrupts. The file already has the right shape for that path in applies persisted approval and client-tool resume decisions with empty client messages (persist tool-call turn, resume with empty client messages, assert chunks).

Suggestion: Add a regression that mirrors that hydrate path for status: 'cancelled': persist a client-tool interrupt plus the assistant tool-call message, resume with empty messages and the same tools, and assert a TOOL_CALL_RESULT of Tool execution cancelled plus no new client_tool_* interrupt. Keep the current onConfig Set check if you want, but do not treat it as coverage for #1088.

expect(clientToolResults?.get('tc1')).toBeUndefined()
expect(resumeStates[0]?.has('tc1')).toBe(true)
expect((await persistence.stores.interrupts!.get('client-1'))?.status).toBe(
'cancelled',
)
Expand Down
Loading