Skip to content
Source
Sign inSign up
TanStack/ai

ai-client: after stop(), nothing on the client says the run was stopped #2227

Openozolcar(GitHub profile, opens in a new tab) opened this issue 2 comments
ozolcar(GitHub profile, opens in a new tab)commented

TanStack AI version

@tanstack/ai-client 1.2.1, @tanstack/ai 1.8.0 (both latest on npm)

Framework/Library version

Node 26.12.0; seen in React with @tanstack/ai-react 1.1.1, but the repro uses ChatClient directly

Describe the bug and the steps to reproduce it

With cancelUrl set, stop() drops the local stream and posts the cancel (src/chat-client.ts:3146-3168). The server writes a terminal RUN_ERROR with the cancel reason, but this client never reads it, because its stream is gone. After stop(), status is "ready", error is unset, and the assistant message has no metadata.tanstack.stopReason. events.stopped() reaches only devtools, and stopReason appears nowhere in chat-client.ts. So a UI that shows "Stopped" has to keep its own flag.

When the server's RUN_ERROR with metadata: { tanstack: { stopReason: 'aborted' } } does reach a client, the client stores it on the message, so the field path the script prints is the right one.

Steps:

  1. Install @tanstack/ai-client@1.2.1 and @tanstack/ai@1.8.0 in an ESM package.
  2. Save the script below as repro.mjs and run node repro.mjs.

repro.mjs:

import { ChatClient, fetchServerSentEvents } from '@tanstack/ai-client'

const sse = (chunk) => `data: ${JSON.stringify(chunk)}\n\n`
const tick = (ms = 10) => new Promise((r) => setTimeout(r, ms))

// Fake server. POST /api/chat streams the start of an answer and then holds the
// stream open (a long run). POST /api/cancel answers 200.
const requests = []
async function fakeFetch(url, init = {}) {
  const method = init.method ?? 'GET'
  requests.push(`${method} ${url}${init.body && url === '/api/cancel' ? ' ' + init.body : ''}`)
  if (method === 'POST' && url === '/api/cancel') return new Response(null, { status: 200 })
  if (method === 'POST' && url === '/api/chat') {
    const { threadId, runId } = JSON.parse(init.body)
    const body = new ReadableStream({
      start(c) {
        c.enqueue(new TextEncoder().encode(
          sse({ type: 'RUN_STARTED', threadId, runId }) +
          sse({ type: 'TEXT_MESSAGE_START', messageId: 'a1', role: 'assistant' }) +
          sse({ type: 'TEXT_MESSAGE_CONTENT', messageId: 'a1', delta: 'Partial answer' }),
        ))
        init.signal?.addEventListener('abort', () => c.error(new DOMException('Aborted', 'AbortError')))
      },
    })
    return new Response(body, { headers: { 'Content-Type': 'text/event-stream' } })
  }
  throw new Error(`unexpected request: ${method} ${url}`)
}

const client = new ChatClient({
  threadId: 't1',
  connection: fetchServerSentEvents('/api/chat', { cancelUrl: '/api/cancel', fetchClient: fakeFetch }),
})

const sending = client.sendMessage('Question')
const answered = () => client.getSnapshot().messages.some((m) => m.role === 'assistant' && m.parts.some((p) => p.content))
while (!answered()) await tick()
console.log('before stop():', { status: client.status, isLoading: client.isLoading })

client.stop()
await sending
await tick()

const last = client.getSnapshot().messages.at(-1)
console.log('requests:', requests)
console.log('after stop():', { status: client.status, isLoading: client.isLoading, error: client.error })
console.log('last message:', JSON.stringify({ id: last.id, role: last.role, parts: last.parts, metadata: last.metadata }))
console.log('stopReason:', last.metadata?.tanstack?.stopReason)

// Expected (bug): the cancel is posted, but status is "ready", error is undefined,
// and the assistant message has no metadata.tanstack.stopReason:
//   after stop(): { status: 'ready', isLoading: false, error: undefined }
//   stopReason: undefined
// Wanted: stopReason 'aborted' on the last assistant message (what a reload reads
// from storage), or a stopped status.

Output:

before stop(): { status: 'streaming', isLoading: true }
requests: [
  'POST /api/chat',
  'POST /api/cancel {"runId":"run-1795468405020-l69hhf","threadId":"t1"}'
]
after stop(): { status: 'ready', isLoading: false, error: undefined }
last message: {"id":"a1","role":"assistant","parts":[{"type":"text","content":"Partial answer"}]}
stopReason: undefined

Expected: stop() marks the last assistant message with stopReason: 'aborted', the value a reload reads from storage, or the client exposes a stopped status.

Inline above. Plain Node script, no network: a stub passed as fetchServerSentEvents's fetchClient plays the server and logs each request.

Screenshots or Videos (Optional)

None.

Do you intend to try to help solve this bug with your own PR?

Maybe, I'll investigate and start debugging

Terms & Code of Conduct

  • I agree to follow this project's Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
  1. tanstack-source added labelsbug

  2. Thanks for the report, @ozolcar! To help us reproduce this, could you add a minimal reproduction?

    A runnable example makes fixes dramatically faster — you can fork one of the official examples, or use StackBlitz / CodeSandbox. For TypeScript-only issues, a TS Playground link works too.

    Automated triage — a maintainer will follow up.
  3. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer

  4. I added a minimal, runnable reproduction to the description: a plain Node script with no network, no model and no API key, tested on the current npm releases.

Sign in to join this conversation.