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

fakes.ts

337 lines10.2 KB

1import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
2import { makeFakeShellSpawn } from '../src/testkit/shell-spawn'
3import type { InternalLogger } from '@tanstack/ai/adapter-internals'
4import type {
5 ExecResult,
6 SandboxCapabilities,
7 SandboxCreateInput,
8 SandboxDestroyInput,
9 SandboxHandle,
10 SandboxProvider,
11 SandboxRestoreInput,
12 SandboxResumeInput,
13 SnapshotRef,
14} from '../src/contracts'
15import type {
16 ChatMiddlewareContext,
17 StreamChunk,
18 StreamDurability,
19} from '@tanstack/ai'
20​
21export const FULL_CAPS: SandboxCapabilities = {
22 fs: true,
23 exec: true,
24 env: true,
25 ports: true,
26 backgroundProcesses: true,
27 writableStdin: true,
28 killableProcesses: true,
29 snapshots: true,
30 networkPolicy: true,
31 durableFilesystem: true,
32 fork: true,
34​
35/** A no-op handle whose fs/process/git are stubs; tracks created/destroyed. */
36export function makeFakeHandle(
37 id: string,
38 provider: string,
39 caps: SandboxCapabilities = FULL_CAPS,
40): SandboxHandle & { destroyed: boolean; files: Map<string, string> } {
41 const files = new Map<string, string>()
42 let snapshotCounter = 0
43 const handle: SandboxHandle & {
44 destroyed: boolean
45 files: Map<string, string>
46 } = {
47 id,
48 provider,
49 capabilities: caps,
50 destroyed: false,
51 files,
52 fs: {
53 read: (p) => Promise.resolve(files.get(p) ?? ''),
54 readBytes: (p) =>
55 Promise.resolve(new TextEncoder().encode(files.get(p) ?? '')),
56 write: (p, d) => {
57 files.set(p, typeof d === 'string' ? d : new TextDecoder().decode(d))
58 return Promise.resolve()
59 },
60 list: () => Promise.resolve([]),
61 lstat: (p) => {
62 const content = files.get(p)
63 if (content !== undefined) {
64 return Promise.resolve({
65 type: 'file' as const,
66 mode: 0o644,
67 size: new TextEncoder().encode(content).byteLength,
68 })
69 }
70 return Promise.resolve({ type: 'dir' as const, mode: 0o755 })
71 },
72 mkdir: () => Promise.resolve(),
73 remove: (p) => {
74 files.delete(p)
75 return Promise.resolve()
76 },
77 rename: () => Promise.resolve(),
78 exists: (p) => Promise.resolve(files.has(p)),
79 },
80 git: {
81 clone: ({ dir }) => {
82 files.set(`${dir ?? '/workspace'}/.git`, 'cloned')
83 return Promise.resolve()
84 },
85 status: () => Promise.resolve(''),
86 add: () => Promise.resolve(),
87 commit: () => Promise.resolve(),
88 push: () => Promise.resolve(),
89 pull: () => Promise.resolve(),
90 branch: () => Promise.resolve('main'),
91 },
92 process: {
93 exec: (): Promise<ExecResult> =>
94 Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }),
95 // A sentinel-driven `sh` good enough to drive the persistent bootstrap
96 // shell: every command succeeds (exit 0), `pwd`/`export -p` answer so
97 // forkState resolves. Mirrors the protocol in src/shell.ts.
98 spawn: () => Promise.resolve(makeFakeShellSpawn()),
99 },
100 ports: {
101 connect: (port) => Promise.resolve({ url: `http://localhost:${port}` }),
102 },
103 env: { set: () => Promise.resolve() },
104 snapshot: caps.snapshots
105 ? (label) =>
106 Promise.resolve<SnapshotRef>({
107 id: `snap-${id}-${++snapshotCounter}`,
108 label,
109 })
110 : undefined,
111 destroy: () => {
112 handle.destroyed = true
113 return Promise.resolve()
114 },
115 }
116 return handle
118​
119export interface FakeProviderOptions {
120 name?: string
121 caps?: SandboxCapabilities
122 /** Make resume() return null (simulate a sandbox that's gone). */
123 resumeReturnsNull?: boolean
125​
126export interface FakeProvider extends SandboxProvider {
127 readonly calls: {
128 create: number
129 resume: number
130 restoreSnapshot: number
131 destroy: number
132 }
133 readonly created: Array<SandboxHandle>
135​
136export function makeFakeProvider(
137 options: FakeProviderOptions = {},
138): FakeProvider {
139 const name = options.name ?? 'fake'
140 const caps = options.caps ?? FULL_CAPS
141 const calls = { create: 0, resume: 0, restoreSnapshot: 0, destroy: 0 }
142 const created: Array<SandboxHandle> = []
143 let counter = 0
144​
145 const provider: FakeProvider = {
146 name,
147 calls,
148 created,
149 capabilities: () => caps,
150 create: (input: SandboxCreateInput) => {
151 calls.create++
152 // Honor the deterministic id when supplied (mirrors real providers like
153 // Cloudflare); fall back to a counter for direct/advanced use.
154 const handle = makeFakeHandle(
155 input.id ?? `${name}-${++counter}`,
156 name,
157 caps,
158 )
159 created.push(handle)
160 return Promise.resolve(handle)
161 },
162 resume: (_input: SandboxResumeInput) => {
163 calls.resume++
164 if (options.resumeReturnsNull) return Promise.resolve(null)
165 const handle = makeFakeHandle(_input.id, name, caps)
166 return Promise.resolve(handle)
167 },
168 restoreSnapshot: caps.snapshots
169 ? (_input: SandboxRestoreInput) => {
170 calls.restoreSnapshot++
171 const handle = makeFakeHandle(
172 `${name}-restored-${++counter}`,
173 name,
174 caps,
175 )
176 created.push(handle)
177 return Promise.resolve(handle)
178 }
179 : undefined,
180 destroy: (_input: SandboxDestroyInput) => {
181 calls.destroy++
182 return Promise.resolve()
183 },
184 }
185 return provider
187​
188/**
189 * An `InternalLogger` (all categories on) that records every emitted call by
190 * its underlying level, for asserting that a code path logs rather than
191 * silently swallows. `sandbox`/other debug categories route to `debug`,
192 * `warn` to `warn`, and `errors` to `error`.
193 */
194export function captureLogger(): {
195 logger: InternalLogger
196 calls: Array<{ level: string; msg: string }>
197} {
198 const calls: Array<{ level: string; msg: string }> = []
199 const rec =
200 (level: string) =>
201 (msg: string): void =>
202 void calls.push({ level, msg })
203 const logger = resolveDebugOption({
204 logger: {
205 debug: rec('debug'),
206 info: rec('info'),
207 warn: rec('warn'),
208 error: rec('error'),
209 },
210 })
211 return { logger, calls }
213​
214/**
215 * A `ChatMiddlewareContext` good enough to drive middleware directly (as
216 * `buildEnsureCtx` at `src/middleware.ts:131-144` reads it) without going
217 * through a real `chat()` call: `threadId`, `runId`, `context`, `signal`, plus
218 * a working capability bus.
219 *
220 * `get`/`getOptional`/`provide` are wired exactly like the production context
221 * builder (`packages/ai/src/activities/chat/index.ts` around `middlewareCtx`):
222 * each delegates to the capability handle's own tuple `get`/`provide`
223 * function, keyed by *this* ctx object's identity. So a capability actually
224 * `provide`d on this ctx (via `ctx.provide` or a handle's own `provideX`
225 * accessor) is actually read back by `get`/`getOptional` — a consumer test
226 * asserting on a provided capability is not exercising a stub that always
227 * answers the same way.
228 *
229 * The capabilities field uses this test-local registry. It has the same
230 * behavior that capability accessors need, without making internal middleware
231 * bookkeeping a public API.
232 */
233class TestCapabilityRegistry {
234 private readonly provided = new Set<object>()
235 private onDuplicate?: (name: string) => void
236​
237 setOnDuplicate(callback: (name: string) => void): void {
238 this.onDuplicate = callback
239 }
240​
241 markProvided(handle: { capabilityName: string }): void {
242 if (this.provided.has(handle)) this.onDuplicate?.(handle.capabilityName)
243 this.provided.add(handle)
244 }
245​
246 has(handle: object): boolean {
247 return this.provided.has(handle)
248 }
250​
251export function makeMiddlewareCtx(input: {
252 threadId: string
253 runId: string
254}): ChatMiddlewareContext {
255 const controller = new AbortController()
256 const ctx: ChatMiddlewareContext = {
257 requestId: `req-${input.runId}`,
258 streamId: `stream-${input.runId}`,
259 runId: input.runId,
260 threadId: input.threadId,
261 conversationId: input.threadId,
262 phase: 'init',
263 iteration: 0,
264 chunkIndex: 0,
265 signal: controller.signal,
266 abort: (reason) => controller.abort(reason),
267 emitCustomEvent: () => {},
268 context: {},
269 defer: () => {},
270 activity: 'chat',
271 provider: 'fake',
272 model: 'fake-model',
273 source: 'server',
274 streaming: true,
275 systemPrompts: [],
276 toolNames: undefined,
277 options: undefined,
278 modelOptions: undefined,
279 messageCount: 0,
280 hasTools: false,
281 currentMessageId: null,
282 accumulatedContent: '',
283 messages: [],
284 createId: (prefix: string) =>
285 `${prefix}-${Math.random().toString(36).slice(2)}`,
286 capabilities:
287 // @ts-expect-error This test-only registry has the required methods, but the production class has private state and is nominally typed.
288 new TestCapabilityRegistry() as ChatMiddlewareContext['capabilities'],
289 get: (capability) => capability[0](ctx),
290 getOptional: (capability) => capability[0](ctx, { optional: true }),
291 provide: (capability, value) => capability[1](ctx, value),
292 }
293 return ctx
295​
296/**
297 * A controllable {@link StreamDurability}. `snapshot()` reflects whatever is
298 * seeded via `entries` plus anything since appended, in order — it is NOT a
299 * constant `[]`, so a test asserting alignment/resume behavior against
300 * `fakeLog().snapshot()` is checking real accumulated state, not a stub that
301 * happens to always look empty.
302 */
303export function fakeLog(entries: Array<StreamChunk> = []): StreamDurability {
304 const stored = [...entries]
305 return {
306 resumeFrom: () => null,
307 append: (chunks) => {
308 const start = stored.length
309 stored.push(...chunks)
310 return Promise.resolve(chunks.map((_, i) => `o:${start + i}`))
311 },
312 read: () => (async function* empty() {})(),
313 close: () => Promise.resolve(),
314 snapshot: () =>
315 Promise.resolve(stored.map((chunk, i) => ({ offset: `o:${i}`, chunk }))),
316 }
318​
319/** Drain an `AsyncIterable<StreamChunk>` to an array of chunk objects. */
320export async function collectChunks(
321 iter: AsyncIterable<StreamChunk>,
322): Promise<Array<StreamChunk>> {
323 const out: Array<StreamChunk> = []
324 for await (const chunk of iter) out.push(chunk)
325 return out
327​
328/** An `AsyncIterable<StreamChunk>` that yields exactly the given chunks. */
329export function fromChunkValues(
330 chunks: Array<StreamChunk>,
331): AsyncIterable<StreamChunk> {
332 return {
333 async *[Symbol.asyncIterator]() {
334 for (const chunk of chunks) yield chunk
335 },
336 }