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

phase-capture.ts

68 lines2.1 KB

1/**
2 * Per-testId capture of middleware phase observations + yielded chunks for the
3 * `phase-recorder` mode of `/middleware-test`. Mirrors the pattern used by
4 * `otel-capture.ts`: server-side middleware records into a module-global Map
5 * keyed by `testId`; the test page fetches it via
6 * `GET /api/middleware-test?testId=...&kind=phase` after the run finishes and
7 * surfaces it in DOM elements that the Playwright spec reads.
8 */
9​
10export interface YieldedChunkSummary {
11 /** The chunk's discriminant (e.g. RUN_STARTED, TEXT_MESSAGE_CONTENT). */
12 type: string
14​
15export interface PhaseCapture {
16 /**
17 * Phases observed by `onChunk` across the entire run, in chunk-arrival
18 * order. Duplicates are preserved so tests can spot transitions; specs
19 * that only care about presence should use `.includes('structuredOutput')`.
20 */
21 phases: Array<string>
22 /** Count of `onFinish` invocations — must be exactly 1 per `chat()` call. */
23 onFinishCount: number
24 /**
25 * Chunks that were yielded out of `chat()` to the SSE consumer. Captured
26 * by teeing the iterable in `api.middleware-test.ts` after the middleware
27 * chain has applied its transformations.
28 */
29 yieldedChunks: Array<YieldedChunkSummary>
31​
32const captures: Map<string, PhaseCapture> = new Map()
33​
34function bucketFor(captureId: string): PhaseCapture {
35 let bucket = captures.get(captureId)
36 if (!bucket) {
37 bucket = { phases: [], onFinishCount: 0, yieldedChunks: [] }
38 captures.set(captureId, bucket)
39 }
40 return bucket
42​
43export function resetPhaseCapture(captureId: string): void {
44 captures.set(captureId, {
45 phases: [],
46 onFinishCount: 0,
47 yieldedChunks: [],
48 })
50​
51export function getPhaseCapture(captureId: string): PhaseCapture {
52 return bucketFor(captureId)
54​
55export function recordPhase(captureId: string, phase: string): void {
56 bucketFor(captureId).phases.push(phase)
58​
59export function recordOnFinish(captureId: string): void {
60 bucketFor(captureId).onFinishCount += 1
62​
63export function recordYieldedChunk(
64 captureId: string,
65 chunk: YieldedChunkSummary,
66): void {
67 bucketFor(captureId).yieldedChunks.push(chunk)