Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { createAnthropicChat } from '@tanstack/ai-anthropic'
3import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
4import { createHarnessHandler } from '@tanstack/ai-harness/server'
5import { memoryLogState, memoryLogStore } from '@tanstack/ai-persistence'
6
7/**
8 * Two hosts on one log backend, as two instances of a serverless app on one
9 * database. Each host has its own log store and its own model. The first
10 * host runs a turn. While it runs, the second host gets a follow-up for the
11 * same thread. The follow-up waits in the log for the owner (receipt
12 * `queued`), and the owner runs it after its turn.
13 *
14 * `?scenario=` picks another case on the same two hosts:
15 *
16 * - `status`: the owner runs a turn. The route returns the statuses that
17 * `host.events()` of the other host shows for the thread.
18 * - `cancel`: the model of the owner waits until the turn stops. The other
19 * host gets `POST control` with a `cancel` input for the turn.
20 *
21 * A custom `fetch` answers with canned Anthropic streams and holds the first
22 * answer until the follow-up is in, so no aimock fixture is needed.
23 */
24
25const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
26const MODEL = 'claude-sonnet-5-5'
27
28const reply = (id: string, text: string) =>
29 [
30 {
31 type: 'message_start',
32 message: {
33 id,
34 type: 'message',
35 role: 'assistant',
36 content: [],
37 model: MODEL,
38 stop_reason: null,
39 stop_sequence: null,
40 usage: { input_tokens: 5, output_tokens: 0 },
41 },
42 },
43 {
44 type: 'content_block_start',
45 index: 0,
46 content_block: { type: 'text', text: '' },
47 },
48 {
49 type: 'content_block_delta',
50 index: 0,
51 delta: { type: 'text_delta', text },
52 },
53 { type: 'content_block_stop', index: 0 },
54 {
55 type: 'message_delta',
56 delta: { stop_reason: 'end_turn', stop_sequence: null },
57 usage: { output_tokens: 1 },
58 },
59 { type: 'message_stop' },
60 ]
61 .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
62 .join('')
63
64/** The text of each message of the transcript. */
65const textsOf = (messages: Array<{ role: string; content: unknown }>) =>
66 messages.map((message) => ({
67 role: message.role,
68 text: typeof message.content === 'string' ? message.content : '',
69 }))
70
71/**
72 * A model whose answers are `texts`, in order. The first answer waits for
73 * `until`. `calls` counts the requests that reach it. With `hang`, each
74 * request waits until the turn stops, and then fails.
75 */
76function scriptedModel(
77 texts: Array<string>,
78 until: Promise<void>,
79 { hang = false } = {},
80) {
81 const counter = { calls: 0 }
82 const scriptedFetch: typeof fetch = async (_input, init) => {
83 counter.calls += 1
84 if (hang) {
85 return new Promise<Response>((_resolve, reject) => {
86 const signal = init?.signal
87 if (!signal) return
88 const stop = () => reject(signal.reason ?? new Error('Stopped.'))
89 if (signal.aborted) stop()
90 signal.addEventListener('abort', stop, { once: true })
91 })
92 }
93 if (counter.calls === 1) await until
94 const text = texts[counter.calls - 1] ?? 'No more answers.'
95 return new Response(reply(`msg_forwarding_${counter.calls}`, text), {
96 headers: { 'Content-Type': 'text/event-stream' },
97 })
98 }
99 const adapter = createAnthropicChat(MODEL, DUMMY_KEY, {
100 fetch: scriptedFetch,
101 })
102 return { adapter, counter }
103}
104
105/** Wait until `check()` is true, for at most 10 s. */
106async function waitUntil(check: () => boolean) {
107 const deadline = Date.now() + 10_000
108 while (!check()) {
109 if (Date.now() > deadline) return
110 await new Promise((resolve) => setTimeout(resolve, 20))
111 }
112}
113
114const NAME = 'e2e/harness-forwarding'
115const THREAD = 'e2e-harness-forwarding'
116
117/** Two hosts on one log backend, each with the session of the thread open. */
118async function twoHosts(
119 ownerModel: ReturnType<typeof scriptedModel>,
120 otherModel: ReturnType<typeof scriptedModel>,
121) {
122 const logState = memoryLogState()
123 const ownerHost = createHarnessHost({
124 persistence: { stores: { log: memoryLogStore({ state: logState }) } },
125 })
126 const otherHost = createHarnessHost({
127 persistence: { stores: { log: memoryLogStore({ state: logState }) } },
128 })
129 const close = async () => {
130 await ownerHost.close()
131 await otherHost.close()
132 }
133 try {
134 const owner = await ownerHost.open(
135 defineHarness({ name: NAME, adapter: ownerModel.adapter }),
136 { threadId: THREAD },
137 )
138 const otherHarness = defineHarness({
139 name: NAME,
140 adapter: otherModel.adapter,
141 })
142 const other = await otherHost.open(otherHarness, { threadId: THREAD })
143 return { ownerHost, otherHost, owner, other, otherHarness, close }
144 } catch (error) {
145 await close()
146 throw error
147 }
148}
149
150/** The follow-up from the other host waits in the log for the owner. */
151async function followUp() {
152 let release!: () => void
153 const released = new Promise<void>((resolve) => {
154 release = resolve
155 })
156 const ownerModel = scriptedModel(['One.', 'Two.'], released)
157 const otherModel = scriptedModel(['Not on this host.'], released)
158 const { owner, other, close } = await twoHosts(ownerModel, otherModel)
159 try {
160 const turn = owner.send('[harness-forwarding] go')
161 await turn.receipt
162 const receipt = await other.send('[harness-forwarding] and then', {
163 mode: 'followUp',
164 }).receipt
165 release()
166 const first = await turn
167 const settled = (await other.settled({ inputId: receipt.inputId })).outcome
168 return {
169 receipt: { status: receipt.status },
170 first: first.text,
171 followUp: settled,
172 ownerCalls: ownerModel.counter.calls,
173 otherCalls: otherModel.counter.calls,
174 transcript: textsOf(await owner.transcript()),
175 }
176 } finally {
177 await close()
178 }
179}
180
181/** The statuses of the thread on the host that does not own it. */
182async function status() {
183 const ownerModel = scriptedModel(['One.'], Promise.resolve())
184 const otherModel = scriptedModel(['Not on this host.'], Promise.resolve())
185 const { otherHost, owner, close } = await twoHosts(ownerModel, otherModel)
186 const reading = new AbortController()
187 try {
188 const statuses: Array<string> = []
189 const read = (async () => {
190 for await (const event of otherHost.events({ signal: reading.signal })) {
191 if (event.type === 'status' && event.threadId === THREAD)
192 statuses.push(event.status)
193 }
194 })()
195 // The first status shows that the feed reads, so start the turn now.
196 await waitUntil(() => statuses.length > 0)
197 const turn = await owner.send('[harness-forwarding] status')
198 await waitUntil(() => statuses.length >= 3)
199 reading.abort()
200 await read
201 return {
202 statuses,
203 text: turn.text,
204 ownerCalls: ownerModel.counter.calls,
205 otherCalls: otherModel.counter.calls,
206 }
207 } finally {
208 reading.abort()
209 await close()
210 }
211}
212
213/** A cancel that the other host gets stops the turn on the owner. */
214async function cancel() {
215 const ownerModel = scriptedModel([], Promise.resolve(), { hang: true })
216 const otherModel = scriptedModel(['Not on this host.'], Promise.resolve())
217 const { otherHost, owner, otherHarness, close } = await twoHosts(
218 ownerModel,
219 otherModel,
220 )
221 try {
222 const turn = owner.send('[harness-forwarding] cancel')
223 const ended = Promise.resolve(turn).then(
224 (result) => ({ text: result.text }),
225 (error: unknown) => ({
226 error: error instanceof Error ? error.message : String(error),
227 }),
228 )
229 const { operationId } = await turn.receipt
230 await waitUntil(() => ownerModel.counter.calls > 0)
231 const handler = createHarnessHandler({
232 host: otherHost,
233 harness: otherHarness,
234 openAccess: true,
235 })
236 const response = await handler(
237 new Request('http://local/api/harness/control', {
238 method: 'POST',
239 headers: { 'content-type': 'application/json' },
240 body: JSON.stringify({
241 threadId: THREAD,
242 input: { op: 'cancel', operationId },
243 }),
244 }),
245 )
246 const receipt: { status: string } = await response.json()
247 // A turn that does not stop ends the wait after 10 s.
248 const outcome = await Promise.race([
249 ended,
250 new Promise((resolve) =>
251 setTimeout(() => resolve({ error: 'The turn did not stop.' }), 10_000),
252 ),
253 ])
254 return {
255 receipt: { status: receipt.status },
256 outcome,
257 turnStatus: turn.status(),
258 ownerCalls: ownerModel.counter.calls,
259 otherCalls: otherModel.counter.calls,
260 }
261 } finally {
262 await close()
263 }
264}
265
266const scenarios = { followUp, status, cancel }
267
268export const Route = createFileRoute('/api/harness-forwarding')({
269 server: {
270 handlers: {
271 POST: async ({ request }) => {
272 const picked = new URL(request.url).searchParams.get('scenario')
273 const scenario =
274 picked === 'status' || picked === 'cancel' ? picked : 'followUp'
275 try {
276 return Response.json(await scenarios[scenario]())
277 } catch (error) {
278 return Response.json({
279 error: error instanceof Error ? error.message : String(error),
280 })
281 }
282 },
283 },
284 },
285})