Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { RUN_CANCEL_REASON, requestRunCancel } from '@tanstack/ai'
3import { driving, runs } from '../run-durable'
4
5/**
6 * The explicit cancel — `chat.stop()` alone is NOT one. On a durable run a
7 * closed connection is indistinguishable from a refresh, so it detaches and
8 * the agent keeps working (and spending). Intent arrives out of band, on both
9 * bands:
10 *
11 * 1. durable — `requestRunCancel` records `cancelRequested` on the run record,
12 * which reaches a run this process is not currently driving;
13 * 2. in-process — abort the driving controller with `RUN_CANCEL_REASON`, the
14 * fast path that stops a co-located drive immediately AND destroys the
15 * sandbox (the only real cancel: no signal reaches the agent process).
16 */
17export const Route = createFileRoute('/api/run/cancel')({
18 server: {
19 handlers: ({ createHandlers }) =>
20 createHandlers({
21 POST: {
22 handler: async ({ request }) => {
23 let body: unknown
24 try {
25 body = await request.json()
26 } catch {
27 return new Response('invalid JSON body', { status: 400 })
28 }
29 if (
30 body === null ||
31 typeof body !== 'object' ||
32 !('threadId' in body) ||
33 typeof body.threadId !== 'string'
34 ) {
35 return new Response('threadId is required', { status: 400 })
36 }
37
38 const active = await runs.findActiveRun(body.threadId)
39 if (!active) return new Response(null, { status: 204 })
40
41 await requestRunCancel(runs, active.runId)
42 driving.get(active.runId)?.abort(RUN_CANCEL_REASON)
43 return new Response(null, { status: 204 })
44 },
45 },
46 }),
47 },
48})