Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.harness-transfer.ts

215 lines6.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { createAnthropicChat } from '@tanstack/ai-anthropic'
3import {
4 AccessDeniedError,
5 createHarnessHost,
6 defineHarness,
7 logIdOf,
8 membersOnly,
9} from '@tanstack/ai-harness'
10import { createHarnessHandler } from '@tanstack/ai-harness/server'
11import { memoryPersistence } from '@tanstack/ai-persistence'
12import type { HarnessHost, HarnessUser } from '@tanstack/ai-harness'
13import type { LogStore } from '@tanstack/ai-persistence'
14​
15/**
16 * A transfer of a conversation from the `support` harness to the `billing`
17 * harness, on one host with `membersOnly()` access. One `POST` runs it all
18 * and returns what the test checks:
19 *
20 * 1. olga of tenant `acme` has two turns with `support`.
21 * 2. gus of tenant `globex` tries the transfer, and is refused.
22 * 3. olga transfers the thread with `messages: 'all'`, then again with the
23 * same `transferId`.
24 * 4. The target thread opens with the handler of `billing`, as its own
25 * route would open it.
26 *
27 * A custom `fetch` answers with canned Anthropic streams, so no aimock
28 * fixture is needed.
29 */
30​
31const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
32const MODEL = 'claude-sonnet-5-5'
33const NOTE = 'Refund for order 42. The user waits.'
34​
35const reply = (id: string, text: string) =>
36 [
37 {
38 type: 'message_start',
39 message: {
40 id,
41 type: 'message',
42 role: 'assistant',
43 content: [],
44 model: MODEL,
45 stop_reason: null,
46 stop_sequence: null,
47 usage: { input_tokens: 5, output_tokens: 0 },
48 },
49 },
50 {
51 type: 'content_block_start',
52 index: 0,
53 content_block: { type: 'text', text: '' },
54 },
55 {
56 type: 'content_block_delta',
57 index: 0,
58 delta: { type: 'text_delta', text },
59 },
60 { type: 'content_block_stop', index: 0 },
61 {
62 type: 'message_delta',
63 delta: { stop_reason: 'end_turn', stop_sequence: null },
64 usage: { output_tokens: 1 },
65 },
66 { type: 'message_stop' },
67 ]
68 .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
69 .join('')
70​
71/** A harness whose model answers `answers`, in order. */
72function harnessWith(name: string, answers: Array<string>) {
73 let calls = 0
74 const scriptedFetch: typeof fetch = async () => {
75 calls += 1
76 const text = answers[calls - 1] ?? 'No more answers.'
77 return new Response(reply(`msg_${calls}`, text), {
78 headers: { 'Content-Type': 'text/event-stream' },
79 })
80 }
81 return defineHarness({
82 name,
83 adapter: createAnthropicChat(MODEL, DUMMY_KEY, { fetch: scriptedFetch }),
84 })
86​
87interface User extends HarnessUser {
88 tenantId: string
90const USERS: Record<string, User> = {
91 olga: { id: 'olga', tenantId: 'acme' },
92 gus: { id: 'gus', tenantId: 'globex' },
94​
95/** The `harness.transferred` records of the log of a thread of `acme`. */
96async function transfersIn(log: LogStore, threadId: string) {
97 const entries = await log.read({
98 logId: logIdOf({ tenantId: 'acme', logId: threadId }),
99 })
100 return entries
101 .map((entry) => entry.record)
102 .filter((record) => record.type === 'harness.transferred')
104​
105const errorOf = (error: unknown) =>
106 error instanceof Error ? error.message : String(error)
107​
108/** The role and text of each message. */
109const linesOf = (messages: Array<{ role: string; content: unknown }>) =>
110 messages.map((message) => ({
111 role: message.role,
112 text: typeof message.content === 'string' ? message.content : '',
113 }))
114​
115async function run() {
116 const runId = crypto.randomUUID()
117 const sourceId = `e2e-harness-transfer-${runId}`
118 const transferId = `tr-${runId}`
119 const persistence = memoryPersistence()
120 const { log } = persistence.stores
121 const host: HarnessHost<User> = createHarnessHost({
122 persistence,
123 access: {
124 getUser: ({ request }): User | null =>
125 USERS[request.headers.get('authorization') ?? ''] ?? null,
126 rules: membersOnly(),
127 },
128 })
129 const support = harnessWith('e2e/harness-transfer-support', [
130 'Support here.',
131 'I pass you to billing.',
132 ])
133 const billing = harnessWith('e2e/harness-transfer-billing', [])
134 try {
135 const source = await host.open(support, {
136 threadId: sourceId,
137 user: USERS.olga,
138 })
139 await source.send('Hi.')
140 await source.send('I want a refund.')
141 const options = {
142 from: { harness: support, threadId: sourceId },
143 to: { harness: billing },
144 envelope: { note: NOTE, messages: 'all' as const },
145 transferId,
146 }
147​
148 // A user of another tenant cannot move the thread.
149 const otherTenant = await host
150 .transfer({ ...options, user: USERS.gus })
151 .then(
152 () => 'allowed',
153 (error: unknown) =>
154 error instanceof AccessDeniedError ? 'denied' : errorOf(error),
155 )
156​
157 // The target opens with the handler of its own harness.
158 const handler = createHarnessHandler({ host, harness: billing })
159 const transcriptOf = async (threadId: string) => {
160 const res = await handler(
161 new Request(
162 `http://local/api/billing/transcript?threadId=${threadId}`,
163 {
164 headers: { authorization: 'olga' },
165 },
166 ),
167 )
168 const messages: Array<{ role: string; content: unknown }> =
169 await res.json()
170 return linesOf(messages)
171 }
172 const entryOf = (threadId: string) =>
173 host.sessions.get({ threadId, user: USERS.olga })
174​
175 const first = await host.transfer({ ...options, user: USERS.olga })
176 const afterFirst = {
177 messages: (await transcriptOf(first.threadId)).length,
178 records: (await transfersIn(log, first.threadId)).length,
179 }
180 // A retry with the same transferId.
181 const second = await host.transfer({ ...options, user: USERS.olga })
182​
183 const result = {
184 otherTenant,
185 first,
186 second,
187 sourceTranscript: linesOf(await source.transcript()),
188 targetTranscript: await transcriptOf(first.threadId),
189 targetEntry: await entryOf(first.threadId),
190 sourceEntry: await entryOf(sourceId),
191 threads: (await host.sessions.list({ user: USERS.olga })).entries.length,
192 globexThreads: (await host.sessions.list({ user: USERS.gus })).entries
193 .length,
194 transfers: {
195 afterFirst,
196 target: await transfersIn(log, first.threadId),
197 source: await transfersIn(log, sourceId),
198 },
199 }
200 await source.close()
201 return Response.json(result)
202 } catch (error) {
203 return Response.json({ error: errorOf(error) })
204 } finally {
205 await host.close()
206 }
208​
209export const Route = createFileRoute('/api/harness-transfer')({
210 server: {
211 handlers: {
212 POST: () => run(),
213 },
214 },
215})