diff --git a/README.md b/README.md index f2703b5..cab9c2c 100644 --- a/README.md +++ b/README.md @@ -251,7 +251,6 @@ node scripts/record-demo.mjs # re-record demo/traces/*.jsonl through the ## Roadmap - `streamscope serve` — record + replay in one process (a session list panel). -- Diff two traces frame by frame (`streamscope diff a.jsonl b.jsonl`). - Custom header/body redaction rules for traces that get committed (the built-in credential mask ships in 0.1.1). ## License @@ -285,3 +284,63 @@ Validation: `npm run verify && npm run test:e2e && npm run test:browser`. Runner Use Node.js 22.18.0 (`.nvmrc`) for development and CI. Vitest 5.1.1 requires Node 22.12+ on its supported release lines; Node 20.19 is outside its declared development support range. It may execute there, but CI does not treat that as supported test-runner usage. This development requirement does not change the package engine declaration. Runtime compatibility must be checked using the built package, separately from the test runner. TypeScript 7.0.2 is the development compiler baseline. Development minimum exception: tsup9 requires Node22.x from22.18.0. This does not change consumer runtime engines. + +## Trace diff and regression gates + +```sh +streamscope diff before.jsonl after.jsonl +streamscope diff before.jsonl after.jsonl --fail-on 'added,removed,payload,latency>200ms,count' +streamscope diff before.jsonl after.jsonl --json --html reports/diff.html +streamscope diff after.jsonl --baseline before.jsonl +``` + +With one trace and no explicit baseline, `.streams/baseline.json` is read: + +```json +{"path":"main/events.jsonl","sha256":"<64-character SHA-256 of the trace file bytes>"} +``` + +The path is relative to the manifest directory. `sha` is accepted as an alias +for `sha256`. The hash is verified before comparing; no baseline is created or +updated implicitly. Get a hash with `sha256sum .streams/main/events.jsonl`. + +Matching uses event type + event ID (including normalized tool-call IDs), or +native toolCallId/inputIndex/input_index/index when present, plus an occurrence +counter for repeated deltas. Without an identity, absolute frame ordinal is +used. Inserting an anonymous event can therefore appear as several payload +changes; this is positional alignment, not semantic inference. Reorder compares +the relative rank of matched events, so inserting an identified event alone +is not a reorder. Added and removed events report their own indices. + +Payload changes compare normalized event objects recursively, including native +`data`, with JSON Pointer key paths. JSON object key order is ignored. Wire +whitespace and frame `seq` are not payload changes. Elapsed `t_ms` deltas are +reported per matched frame: these are cumulative stream times, not processing +durations. A latency gate fails only for a positive delta strictly greater +than its threshold. Equal or faster frames do not fail. Count compares total +frame counts, so one addition and one removal does not trigger count alone. + +Different adapter/protocol/framing metadata, invalid frame metadata or truncated +JSONL is rejected. Identical traces print `no differences`. Exit codes are 0 +for successful comparison with no gate violations (even if differences exist), +1 for gate violations or I/O errors, and 2 for invalid input/options. JSON +includes `violations`; HTML embeds sandboxed before/after timeline viewers. +The HTML contains trace payloads, so handle it like the source recordings. + +See [`examples/ci/trace-diff.yml`](examples/ci/trace-diff.yml) for a two-job PR +workflow that downloads a base-commit recording artifact and fails on removed +frames. It uses the committed demo trace as a runnable placeholder; replace +both copy steps with the same deterministic application recording command. +It does not use elevated pull_request_target permissions or release packages. + +Use stable seeded tool/message/run IDs in both recordings. If providers generate +new IDs on each run, normalize them consistently (including references inside +native data) before hashing/comparing; otherwise ID changes are additions and +removals by design. Provider fragment indices are scoped by step/message ID. +Completed valid JSON argument strings are compared structurally; partial argument +fragments stay byte-sensitive. HTML output may not overwrite either input trace +or the baseline manifest (symlink and hardlink aliases are also rejected). + +Argument JSON numeric normalization is conservative: fractional, exponent-form and unsafe +integer values keep the original argument string, so rounding cannot hide a +payload change. Those strings may still flag whitespace/key-order changes. diff --git a/bin/cli.ts b/bin/cli.ts index c36844c..ea9d1e0 100644 --- a/bin/cli.ts +++ b/bin/cli.ts @@ -7,14 +7,16 @@ * streamscope inject .streams/ --with "dup(4)" -o checkout.broken.jsonl * streamscope inspect .streams/ --html viewer.html */ -import { existsSync, readFileSync, realpathSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { diffTraces, diffViolations, formatTraceDiff, parseDiffGates, renderDiffHtml } from '../src/diff.js'; +import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'; import { mkdir, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { applyFaults, FaultSyntaxError, defaultEncoder, formatScenario, parseScenario } from '../src/faults.js'; import { startRecordingProxy } from '../src/proxy.js'; import { startReplayServer } from '../src/replay.js'; -import { formatSummary, readTrace, resolveTracePath, summarize, traceToJsonl } from '../src/trace.js'; +import { formatSummary, parseTrace, readTrace, resolveTracePath, summarize, traceToJsonl } from '../src/trace.js'; import { renderPanelHtml } from '../src/ui/panel.js'; import type { Trace } from '../src/types.js'; @@ -30,7 +32,18 @@ const DEFAULT_IO: CliIO = { cwd: process.cwd(), }; -const BOOLEAN_FLAGS = new Set(['help', 'version', 'json', 'open', 'no-ui', 'print', 'quiet', 'force', 'frames', 'no-redact']); +const BOOLEAN_FLAGS = new Set([ + 'help', + 'version', + 'json', + 'open', + 'no-ui', + 'print', + 'quiet', + 'force', + 'frames', + 'no-redact', +]); const VALUE_FLAGS = new Set([ 'target', 'port', @@ -43,8 +56,10 @@ const VALUE_FLAGS = new Set([ 'speed', 'html', 'url', + 'baseline', + 'fail-on', ]); -const COMMANDS = ['record', 'replay', 'inject', 'inspect', 'help', 'version'] as const; +const COMMANDS = ['record', 'replay', 'inject', 'inspect', 'diff', 'help', 'version'] as const; type Command = (typeof COMMANDS)[number]; interface Parsed { @@ -78,7 +93,9 @@ export function readVersion(root = packageRoot()): string { try { const file = path.join(root, 'package.json'); if (existsSync(file)) { - const pkg = JSON.parse(readFileSync(file, 'utf8')) as { version?: unknown }; + const pkg = JSON.parse(readFileSync(file, 'utf8')) as { + version?: unknown; + }; if (typeof pkg.version === 'string') return pkg.version; } } catch { @@ -184,6 +201,10 @@ Replay Inject streamscope inject --with "truncate_tool_args(12),error(429)" -o out.jsonl +Diff + streamscope diff [--fail-on 'removed,payload,latency>200ms'] [--json] [--html diff.html] + streamscope diff --baseline + Inspect streamscope inspect [--json] [--html viewer.html] @@ -234,6 +255,8 @@ is written to //events.jsonl.`; streamscope inject --with "" [-o ] [--print] Without -o the result is written next to the input as .injected.jsonl.`; + case 'diff': + return `streamscope diff [--fail-on 'added,removed,payload,count,latency>200ms'] [--json] [--html diff.html]\nWith one trace, use --baseline or .streams/baseline.json containing {path,sha256}. Paths in the manifest are relative to the manifest directory.\nIdentity-less events match by ordinal; latency is elapsed frame time.`; case 'inspect': return `streamscope inspect — summarize a trace @@ -279,6 +302,8 @@ export async function run(argv: string[], io: CliIO = DEFAULT_IO): Promise { if (bool(parsed, 'frames')) { io.stdout('\n'); for (const frame of trace.frames) { - io.stdout(`#${frame.seq}\t${frame.t_ms}ms\t${frame.event.type}\t${JSON.stringify(frame.event.delta ?? frame.event.argsDelta ?? frame.event.message ?? '')}\n`); + io.stdout( + `#${frame.seq}\t${frame.t_ms}ms\t${frame.event.type}\t${JSON.stringify(frame.event.delta ?? frame.event.argsDelta ?? frame.event.message ?? '')}\n`, + ); } } } @@ -346,10 +373,17 @@ async function runInject(parsed: Parsed, io: CliIO): Promise { }); const meta = { ...trace.meta, - notes: { ...(trace.meta.notes ?? {}), inject: formatScenario(faults), outcome: result.outcome }, + notes: { + ...(trace.meta.notes ?? {}), + inject: formatScenario(faults), + outcome: result.outcome, + }, }; const injected: Trace = { meta, frames: result.frames, path: trace.path }; - const defaultOut = path.join(path.dirname(resolveTracePath(path.resolve(io.cwd, parsed.positionals[0] as string))), `${trace.meta.session}.injected.jsonl`); + const defaultOut = path.join( + path.dirname(resolveTracePath(path.resolve(io.cwd, parsed.positionals[0] as string))), + `${trace.meta.session}.injected.jsonl`, + ); const out = path.resolve(io.cwd, flag(parsed, 'out') ?? defaultOut); await writeFile(out, traceToJsonl(injected), 'utf8'); io.stdout(`wrote ${out}\n`); @@ -380,7 +414,9 @@ async function runRecord(parsed: Parsed, io: CliIO): Promise { onSession: () => undefined, }); if (bool(parsed, 'no-redact')) { - io.stderr('streamscope: warning: recording without header redaction — Authorization, Cookie, Set-Cookie, X-API-Key and Proxy-Authorization are stored verbatim\n'); + io.stderr( + 'streamscope: warning: recording without header redaction — Authorization, Cookie, Set-Cookie, X-API-Key and Proxy-Authorization are stored verbatim\n', + ); } io.stdout(`streamscope proxy: ${proxy.url} -> ${target}\n`); io.stdout(`traces: ${out}//events.jsonl (Ctrl-C to stop)\n`); @@ -448,3 +484,109 @@ if (isMain) { process.exitCode = 1; }); } + +async function runDiff(parsed: Parsed, io: CliIO): Promise { + if (parsed.positionals.length < 1 || parsed.positionals.length > 2) + throw new UsageError('diff needs , or with a baseline'); + let base: string | undefined, head: string | undefined, expected: string | undefined; + const explicit = flag(parsed, 'baseline'); + if (parsed.positionals.length === 2) { + if (explicit) throw new UsageError('--baseline cannot be combined with two traces'); + [base, head] = parsed.positionals; + } else { + head = parsed.positionals[0]; + if (explicit) base = explicit; + else { + const manifest = path.resolve(io.cwd, '.streams/baseline.json'); + const record = JSON.parse(readFileSync(manifest, 'utf8')) as { + path?: unknown; + sha256?: unknown; + sha?: unknown; + }; + const hash = record.sha256 ?? record.sha; + if (typeof record.path !== 'string' || typeof hash !== 'string' || !/^[a-f0-9]{64}$/i.test(hash)) + throw new UsageError('baseline manifest needs path and 64-character sha256 (sha alias accepted)'); + base = path.resolve(path.dirname(manifest), record.path); + expected = hash.toLowerCase(); + } + } + const before = await loadDiffTrace(base, io, expected), + after = await loadDiffTrace(head, io); + const html = flag(parsed, 'html'); + if (html) { + const output = path.resolve(io.cwd, html); + for (const input of [before.path!, after.path!, path.resolve(io.cwd, '.streams/baseline.json')]) { + if ( + output === input || + (existsSync(output) && + existsSync(input) && + (realpathSync(output) === realpathSync(input) || + (statSync(output).dev === statSync(input).dev && statSync(output).ino === statSync(input).ino))) + ) + throw new UsageError('--html must not overwrite an input trace or baseline manifest'); + } + } + const result = diffTraces(before, after), + raw = flag(parsed, 'fail-on'); + const violations = diffViolations(result, raw === undefined ? [] : parseDiffGates(raw)); + const output = { ...result, violations }; + io.stdout( + (bool(parsed, 'json') + ? JSON.stringify(output, null, 2) + : formatTraceDiff(result) + (violations.length ? `\nfailed gates: ${violations.join(', ')}` : '')) + '\n', + ); + if (html) { + const out = path.resolve(io.cwd, html); + await mkdir(path.dirname(out), { recursive: true }); + await writeFile(out, renderDiffHtml(result, before, after, violations), 'utf8'); + io.stderr(`diff report: ${out}\n`); + } + return violations.length ? 1 : 0; +} + +async function loadDiffTrace(input: string | undefined, io: CliIO, expected?: string): Promise { + if (!input) throw new UsageError('missing diff trace'); + const file = path.resolve(io.cwd, resolveTracePath(input)); + const bytes = readFileSync(file); + if (expected && createHash('sha256').update(bytes).digest('hex') !== expected) + throw new UsageError('baseline SHA-256 mismatch'); + const text = bytes.toString('utf8'); + const lines = text.split(/\r?\n/).filter((line) => line.trim()); + if (!lines.length) throw new UsageError(`empty diff trace: ${file}`); + const records = lines.map((line, i) => { + try { + return JSON.parse(line) as Record; + } catch { + throw new UsageError(`invalid JSON at ${file}:${i + 1}`); + } + }); + const meta = records[0]; + if ( + !meta || + meta.kind !== 'meta' || + meta.v !== 1 || + typeof meta.adapter !== 'string' || + !meta.adapter || + typeof meta.protocol !== 'string' || + typeof meta.framing !== 'string' + ) + throw new UsageError(`invalid trace metadata: ${file}`); + const seq = new Set(); + for (const [i, frame] of records.slice(1).entries()) { + const event = frame?.event as Record | undefined; + if ( + !frame || + !Number.isInteger(frame.seq) || + seq.has(frame.seq as number) || + typeof frame.t_ms !== 'number' || + !Number.isFinite(frame.t_ms) || + frame.t_ms < 0 || + typeof frame.raw !== 'string' || + !event || + typeof event.type !== 'string' + ) + throw new UsageError(`invalid diff frame at ${file}:${i + 2}`); + seq.add(frame.seq as number); + } + return parseTrace(text, file); +} diff --git a/e2e/run-e2e.mjs b/e2e/run-e2e.mjs index 99af4f9..9067145 100644 --- a/e2e/run-e2e.mjs +++ b/e2e/run-e2e.mjs @@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const { chromium } = await import('playwright-core'); const { replayStream } = await import(path.join(root, 'dist', 'playwright.js')); +const { diffTraces, renderDiffHtml, parseTrace } = await import(path.join(root, 'dist', 'index.js')); const { startReplayServer } = await import(path.join(root, 'dist', 'index.js')); const DEMO_PORT = 8795; @@ -115,6 +116,30 @@ try { check('panel: injected error is flagged as the break point', breakCard); await page.screenshot({ path: path.join(artifacts, 'panel.png'), fullPage: false }); await panelServer.close(); + + // Diff report: gates, both reused viewers and narrow-screen controls. + const original = parseTrace(await fs.readFile(path.join(root, 'demo', 'traces', 'chat-ai-sdk.jsonl'), 'utf8')); + const changed = structuredClone(original); + changed.frames.forEach(frame => { frame.t_ms += 200; }); + changed.frames.push({seq:100,t_ms:600,raw:'data: {}',event:{type:'tool-call-delta',id:'added-tool',argsDelta:'{}'}}); + const diff = diffTraces(original, changed); + await page.setContent(renderDiffHtml(diff, original, changed, ['added', 'latency>199ms'])); + const report = page.locator('body'); + check('diff: change summary and failed gates visible', (await report.innerText()).includes('Gate failed: added, latency>199ms')); + await page.setViewportSize({width:390,height:844}); + check('diff: no outer horizontal overflow', await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + for (const title of ['Before trace','After trace']) { + const iframe = page.frameLocator(`iframe[title="${title}"]`); + await iframe.locator('#scrub').waitFor(); + await iframe.locator('#next').click(); + check(`diff: ${title} next control works`, (await iframe.locator('#frame-title').innerText()).startsWith('#1 ')); + const fits = await iframe.locator('body').evaluate(() => document.documentElement.scrollWidth <= innerWidth && document.querySelector('#scrub').getBoundingClientRect().right <= innerWidth); + check(`diff: ${title} controls fit narrow viewport`, fits); + await iframe.locator('.counts').evaluate(el => { el.scrollLeft = el.scrollWidth; }); + check(`diff: ${title} counts can scroll`, await iframe.locator('.counts').evaluate(el => el.scrollWidth <= el.clientWidth || el.scrollLeft > 0)); + } + await page.screenshot({path:path.join(artifacts,'diff-mobile.png'),fullPage:true}); + } finally { if (browser) await browser.close(); demo.kill('SIGTERM'); diff --git a/examples/ci/trace-diff.yml b/examples/ci/trace-diff.yml new file mode 100644 index 0000000..0572c26 --- /dev/null +++ b/examples/ci/trace-diff.yml @@ -0,0 +1,54 @@ +# Copy into .github/workflows/trace-diff.yml after choosing a representative +# deterministic recording command for your app. This example compares the +# committed chat fixture; replace both cp commands with your recorder command. +name: Stream regression example +on: [pull_request] +permissions: + contents: read +jobs: + main-recording: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - run: | + mkdir -p baseline + cp demo/traces/chat-ai-sdk.jsonl baseline/events.jsonl + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: main-stream-recording + path: baseline/events.jsonl + if-no-files-found: error + compare: + needs: main-recording + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 22.18.0 + cache: npm + - run: npm ci && npm run build + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: main-stream-recording + path: baseline + - run: | + mkdir -p current + cp demo/traces/chat-ai-sdk.jsonl current/events.jsonl + node dist/cli.js diff baseline/events.jsonl current/events.jsonl --fail-on removed --json --html reports/diff.html > reports.json + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: always() + with: + name: stream-diff + path: | + reports.json + reports/diff.html + if-no-files-found: warn +# A removed frame makes the diff step exit 1 and fails this workflow. This uses +# pull_request, not pull_request_target; never run PR code with write secrets. +# Artifacts may contain trace payloads. Redact secrets before recording/upload. diff --git a/src/diff.ts b/src/diff.ts new file mode 100644 index 0000000..ec126e0 --- /dev/null +++ b/src/diff.ts @@ -0,0 +1,217 @@ +import type { Trace, TraceFrame } from './types.js'; +import { escapeHtml, renderPanelHtml } from './ui/panel.js'; + +export interface PayloadChange { + path: string; + before?: unknown; + after?: unknown; +} +export interface FrameChange { + key: string; + beforeIndex: number; + afterIndex: number; + latencyDeltaMs: number; + payload: PayloadChange[]; + reordered: boolean; +} +export interface TraceDiff { + version: 1; + adapter: string; + beforeCount: number; + afterCount: number; + added: Array<{ key: string; index: number }>; + removed: Array<{ key: string; index: number }>; + matched: FrameChange[]; + noDifferences: boolean; +} +export type DiffGate = { kind: 'added' | 'removed' | 'payload' | 'count' } | { kind: 'latency'; thresholdMs: number }; + +function stable(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`; + if (value && typeof value === 'object') + return `{${Object.entries(value) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`) + .join(',')}}`; + return JSON.stringify(value) ?? 'undefined'; +} +function payloadDiff(before: unknown, after: unknown, path = ''): PayloadChange[] { + if (stable(before) === stable(after)) return []; + if ( + before && + after && + typeof before === 'object' && + typeof after === 'object' && + Array.isArray(before) === Array.isArray(after) + ) { + const a = before as Record, + b = after as Record; + return [...new Set([...Object.keys(a), ...Object.keys(b)])] + .sort() + .flatMap((k) => payloadDiff(a[k], b[k], `${path}/${k.replace(/~/g, '~0').replace(/\//g, '~1')}`)); + } + return [ + { + path: path || '/', + ...(before === undefined ? {} : { before }), + ...(after === undefined ? {} : { after }), + }, + ]; +} +function nativeIndex(data: unknown): unknown { + const obj = (v: unknown): Record => + v !== null && typeof v === 'object' ? (v as Record) : {}; + const root = obj(data), + delta = obj(root.delta), + step = obj(delta.step_details); + const calls = step.tool_calls; + if (Array.isArray(calls) && calls.length === 1) { + const c = obj(calls[0]); + return c.id ?? (c.index === undefined ? undefined : { step: root.id, index: c.index }); + } + const message = obj(Array.isArray(data) ? data[0] : data), + chunks = message.tool_call_chunks; + if (Array.isArray(chunks) && chunks.length === 1) { + const c = obj(chunks[0]); + return c.id ?? (c.index === undefined ? undefined : { message: message.id, index: c.index }); + } + return undefined; +} +function comparisonEvent(frame: TraceFrame): unknown { + const event = frame.event; + if (event.type === 'tool-call-delta' && event.complete && typeof event.argsDelta === 'string') { + try { + const numericTokens=event.argsDelta.replace(/"(?:\\.|[^"\\])*"/g,'').match(/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g)??[]; + if(numericTokens.some(n=>! /^-?\d+$/.test(n)||!Number.isSafeInteger(Number(n))))return event; + return { + ...event, + argsDelta: { parsedJson: JSON.parse(event.argsDelta, (_key, value: unknown) => { + // Never round a numeric lexeme while deciding a regression gate. + // Fractional/unsafe numbers retain byte-sensitive argument comparison. + if (typeof value === 'number' && !Number.isSafeInteger(value)) throw new RangeError('non-exact JSON number'); + return value; + }) }, + }; + } catch { + /* Incomplete/invalid fragments remain byte-sensitive. */ + } + } + return event; +} +function keyed(frames: TraceFrame[]): Array<{ key: string; frame: TraceFrame; index: number }> { + const seen = new Map(); + return frames.map((frame, index) => { + const data = frame.event.data; + const native = data && typeof data === 'object' ? (data as Record) : {}; + const identity = + frame.event.id ?? + native.toolCallId ?? + native.tool_call_id ?? + native.inputIndex ?? + native.input_index ?? + native.index ?? + nativeIndex(data); + const base = `${frame.event.type}:${identity === undefined ? `ordinal=${index}` : stable(identity)}`; + const occurrence = seen.get(base) ?? 0; + seen.set(base, occurrence + 1); + return { key: `${base}#${occurrence}`, frame, index }; + }); +} +export function diffTraces(before: Trace, after: Trace): TraceDiff { + if ( + before.meta.adapter !== after.meta.adapter || + before.meta.protocol !== after.meta.protocol || + before.meta.framing !== after.meta.framing + ) + throw new RangeError( + `incompatible trace adapters: ${before.meta.adapter}/${before.meta.protocol}/${before.meta.framing} vs ${after.meta.adapter}/${after.meta.protocol}/${after.meta.framing}`, + ); + for (const trace of [before, after]) + for (const f of trace.frames) + if (!Number.isFinite(f.t_ms) || f.t_ms < 0) + throw new RangeError('trace timestamps must be finite and nonnegative'); + const a = keyed(before.frames), + b = keyed(after.frames), + am = new Map(a.map((x) => [x.key, x])), + bm = new Map(b.map((x) => [x.key, x])); + const commonA = a.filter((x) => bm.has(x.key)), + commonB = b.filter((x) => am.has(x.key)); + const ranks = new Map(commonB.map((x, i) => [x.key, i])); + const matched = commonA.map((x, rank) => { + const y = bm.get(x.key)!; + return { + key: x.key, + beforeIndex: x.index, + afterIndex: y.index, + latencyDeltaMs: y.frame.t_ms - x.frame.t_ms, + payload: (()=>{ + const changes=payloadDiff(comparisonEvent(x.frame), comparisonEvent(y.frame)); + const argsChanged=x.frame.event.argsDelta!==y.frame.event.argsDelta && changes.some(c=>c.path==='/argsDelta'||c.path.startsWith('/argsDelta/')); + return [...changes.filter(c=>c.path!=='/argsDelta'&&!c.path.startsWith('/argsDelta/')),...(argsChanged?[{path:'/argsDelta',before:x.frame.event.argsDelta,after:y.frame.event.argsDelta}]:[])]; + })(), + reordered: ranks.get(x.key) !== rank, + }; + }); + const added = b.filter((x) => !am.has(x.key)).map(({ key, index }) => ({ key, index })); + const removed = a.filter((x) => !bm.has(x.key)).map(({ key, index }) => ({ key, index })); + return { + version: 1, + adapter: before.meta.adapter, + beforeCount: a.length, + afterCount: b.length, + added, + removed, + matched, + noDifferences: + !added.length && + !removed.length && + matched.every((x) => !x.reordered && !x.payload.length && x.latencyDeltaMs === 0), + }; +} +export function parseDiffGates(input: string): DiffGate[] { + if (!input.trim()) throw new RangeError('--fail-on needs at least one gate'); + return input.split(',').map((raw) => { + const value = raw.trim(); + if (['added', 'removed', 'payload', 'count'].includes(value)) + return { kind: value as 'added' | 'removed' | 'payload' | 'count' }; + const m = /^latency>(\d+(?:\.\d+)?)ms$/.exec(value); + if (m) { + const thresholdMs = Number(m[1]); + if (Number.isFinite(thresholdMs)) return { kind: 'latency', thresholdMs }; + } + throw new RangeError(`invalid diff gate: ${value}`); + }); +} +export function diffViolations(diff: TraceDiff, gates: DiffGate[]): string[] { + return gates.flatMap((g) => { + const hit = + g.kind === 'added' + ? diff.added.length > 0 + : g.kind === 'removed' + ? diff.removed.length > 0 + : g.kind === 'payload' + ? diff.matched.some((x) => x.payload.length > 0) + : g.kind === 'count' + ? diff.beforeCount !== diff.afterCount + : diff.matched.some((x) => x.latencyDeltaMs > ('thresholdMs' in g ? g.thresholdMs : Infinity)); + return hit ? [g.kind === 'latency' ? `latency>${g.thresholdMs}ms` : g.kind] : []; + }); +} +export function formatTraceDiff(diff: TraceDiff): string { + if (diff.noDifferences) return 'no differences'; + const lines = [ + `frames ${diff.beforeCount} -> ${diff.afterCount}`, + `added ${diff.added.length}, removed ${diff.removed.length}`, + ]; + for (const x of diff.added) lines.push(`+ ${x.key} at ${x.index}`); + for (const x of diff.removed) lines.push(`- ${x.key} at ${x.index}`); + for (const x of diff.matched) { + if (x.reordered) lines.push(`order ${x.key}: ${x.beforeIndex} -> ${x.afterIndex}`); + if (x.payload.length) lines.push(`payload ${x.key}: ${x.payload.map((p) => p.path).join(', ')}`); + if (x.latencyDeltaMs) lines.push(`latency ${x.key}: ${x.latencyDeltaMs > 0 ? '+' : ''}${x.latencyDeltaMs}ms`); + } + return lines.join('\n'); +} +export function renderDiffHtml(diff: TraceDiff, before: Trace, after: Trace, violations: string[] = []): string { + return `streamscope trace diff

Trace diff

${escapeHtml(formatTraceDiff(diff))}

${violations.length ? `Gate failed: ${escapeHtml(violations.join(', '))}` : 'No gate violations'}

Event identity: type + ID/index + occurrence. Events without identity use ordinal position. Latency is elapsed frame time, not server processing time.

Before

After

`; +} diff --git a/src/index.ts b/src/index.ts index f3e8f62..4a56cea 100644 --- a/src/index.ts +++ b/src/index.ts @@ -42,3 +42,6 @@ export { classifyPayload, encodeEvent, encodeErrorPayload } from './adapters/pro export { SseParser, formatSseMessage } from './adapters/sse.js'; export type { SseMessage } from './adapters/sse.js'; export { NdjsonParser } from './adapters/ndjson.js'; + +export { diffTraces, diffViolations, formatTraceDiff, parseDiffGates, renderDiffHtml } from './diff.js'; +export type { TraceDiff, FrameChange, PayloadChange, DiffGate } from './diff.js'; diff --git a/src/ui/panel.ts b/src/ui/panel.ts index 6005b22..ff6084d 100644 --- a/src/ui/panel.ts +++ b/src/ui/panel.ts @@ -155,14 +155,14 @@ header { display: flex; align-items: baseline; gap: 12px; padding: 14px 18px; bo header h1 { font-size: 15px; margin: 0; font-weight: 600; letter-spacing: .2px; } header .meta { color: var(--muted); font-family: var(--mono); font-size: 12px; } main { display: grid; grid-template-columns: minmax(320px, 420px) 1fr; height: calc(100vh - 54px); } -.timeline { border-right: 1px solid var(--line); display: flex; flex-direction: column; min-height: 0; } +.timeline { min-width: 0; border-right: 1px solid var(--line); display: flex; flex-direction: column; min-height: 0; } .controls { display: flex; gap: 8px; align-items: center; padding: 10px 12px; border-bottom: 1px solid var(--line); flex-wrap: wrap; } button, select { background: var(--panel-2); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 5px 10px; font: inherit; cursor: pointer; } button:hover, select:hover { border-color: #3b4248; } button.primary { border-color: #2f6f57; color: var(--accent); } input[type="range"] { flex: 1; accent-color: var(--accent); min-width: 120px; } .list { overflow: auto; flex: 1; min-height: 0; } -.row { display: grid; grid-template-columns: 42px 64px 1fr; gap: 8px; padding: 5px 12px; border-bottom: 1px solid #1d2125; cursor: pointer; font-family: var(--mono); font-size: 12px; align-items: center; } +.row { display: grid; grid-template-columns: 42px 64px minmax(0, 1fr); gap: 8px; padding: 5px 12px; border-bottom: 1px solid #1d2125; cursor: pointer; font-family: var(--mono); font-size: 12px; align-items: center; } .row:hover { background: #191d21; } .row.selected { background: #1d2a26; box-shadow: inset 2px 0 0 var(--accent); } .row.broken { box-shadow: inset 2px 0 0 var(--bad); } @@ -176,7 +176,7 @@ input[type="range"] { flex: 1; accent-color: var(--accent); min-width: 120px; } .badge.approval { color: #c4b5fd; border-color: #3b2f5f; } .badge.error { color: #fca5a5; border-color: #5f2323; } .badge.finish { color: #86efac; border-color: #1f5f34; } -.inspector { overflow: auto; padding: 16px 18px; display: flex; flex-direction: column; gap: 16px; min-height: 0; } +.inspector { min-width: 0; overflow: auto; padding: 16px 18px; display: flex; flex-direction: column; gap: 16px; min-height: 0; } .card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; } .card h2 { margin: 0 0 8px; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); font-weight: 600; } pre { margin: 0; white-space: pre-wrap; word-break: break-word; font-family: var(--mono); font-size: 12.5px; } @@ -190,7 +190,7 @@ pre { margin: 0; white-space: pre-wrap; word-break: break-word; font-family: var .empty { color: var(--muted); font-family: var(--mono); font-size: 12px; } .counts { display: flex; gap: 10px; padding: 7px 12px; border-bottom: 1px solid var(--line); font-family: var(--mono); font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow-x: auto; } .counts b { color: var(--text); font-weight: 600; } -@media (max-width: 860px) { main { grid-template-columns: 1fr; height: auto; } .timeline { border-right: 0; border-bottom: 1px solid var(--line); max-height: 50vh; } } +@media (max-width: 860px) { header { flex-wrap: wrap; } header h1, header .meta { overflow-wrap: anywhere; min-width: 0; } main { grid-template-columns: minmax(0, 1fr); height: auto; } .timeline { min-width: 0; border-right: 0; border-bottom: 1px solid var(--line); max-height: 50vh; } } diff --git a/test/cli.test.ts b/test/cli.test.ts index ef85798..bcb338a 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -66,7 +66,9 @@ describe('streamscope CLI', () => { const json = capture(); expect(await run(['inspect', fixture, '--json'], json.io)).toBe(0); - const parsed = JSON.parse(json.out()) as { summary: { frames: number; textChars: number; terminal: string } }; + const parsed = JSON.parse(json.out()) as { + summary: { frames: number; textChars: number; terminal: string }; + }; expect(parsed.summary.frames).toBe(16); expect(parsed.summary.textChars).toBe(120); expect(parsed.summary.terminal).toBe('finish'); @@ -88,7 +90,9 @@ describe('streamscope CLI', () => { expect(await run(['inject', fixture, '--with', 'drop(3),disconnect_at(0.5)', '-o', out], cli.io)).toBe(0); expect(cli.out()).toContain('outcome disconnect'); const lines = (await fs.readFile(out, 'utf8')).trim().split('\n'); - const meta = JSON.parse(lines[0] ?? '{}') as { notes?: { inject?: string; outcome?: string } }; + const meta = JSON.parse(lines[0] ?? '{}') as { + notes?: { inject?: string; outcome?: string }; + }; expect(meta.notes?.inject).toBe('drop(3), disconnect_at(0.5)'); expect(meta.notes?.outcome).toBe('disconnect'); expect(lines.length - 1).toBe(7); @@ -116,10 +120,7 @@ describe('streamscope CLI', () => { const dir = await tmpDir(); const cli = capture(); const before = new Set(process.listeners('SIGINT')); - const done = run( - ['record', '--target', 'http://127.0.0.1:1', '--port', '0', '--out', dir, '--no-redact'], - cli.io, - ); + const done = run(['record', '--target', 'http://127.0.0.1:1', '--port', '0', '--out', dir, '--no-redact'], cli.io); const start = Date.now(); while (!cli.err().includes('redaction') && Date.now() - start < 5000) { await new Promise((r) => setTimeout(r, 10)); @@ -143,3 +144,76 @@ describe('streamscope CLI', () => { expect(cli.err()).toContain('unknown option'); }); }); + +describe('diff CLI and baseline gates', () => { + it('prints identical text, emits machine JSON and standalone HTML', async () => { + const dir = await tmpDir(), + c = capture(); + expect(await run(['diff', fixture, fixture], c.io)).toBe(0); + expect(c.out()).toContain('no differences'); + const j = capture(); + expect(await run(['diff', fixture, fixture, '--json', '--html', path.join(dir, 'diff.html')], j.io)).toBe(0); + expect(JSON.parse(j.out()).noDifferences).toBe(true); + expect(await fs.readFile(path.join(dir, 'diff.html'), 'utf8')).toContain('Before trace'); + }); + it('fails removed gate and handles explicit baseline', async () => { + const dir = await tmpDir(), + removed = path.join(dir, 'removed.jsonl'); + const lines = (await fs.readFile(fixture, 'utf8')).trim().split('\n'); + await fs.writeFile(removed, lines.slice(0, -1).join('\n') + '\n'); + const c = capture(); + expect(await run(['diff', removed, '--baseline', fixture, '--fail-on', 'removed', '--json'], c.io)).toBe(1); + expect(JSON.parse(c.out()).violations).toEqual(['removed']); + }); + it('resolves manifest path relative to manifest, verifies SHA before comparison', async () => { + const dir = await tmpDir(); + await fs.mkdir(path.join(dir, '.streams')); + const bytes = await fs.readFile(fixture); + await fs.writeFile(path.join(dir, '.streams', 'base.jsonl'), bytes); + const { createHash } = await import('node:crypto'); + const manifest = path.join(dir, '.streams', 'baseline.json'); + await fs.writeFile( + manifest, + JSON.stringify({ + path: 'base.jsonl', + sha: createHash('sha256').update(bytes).digest('hex'), + }), + ); + const c = capture(); + c.io.cwd = dir; + expect(await run(['diff', fixture], c.io)).toBe(0); + await fs.appendFile(path.join(dir, '.streams', 'base.jsonl'), '\n'); + expect(await run(['diff', fixture], c.io)).toBe(2); + expect(c.err()).toContain('SHA-256 mismatch'); + }); + it('rejects invalid/truncated traces rather than passing a gate silently', async () => { + const dir = await tmpDir(), + bad = path.join(dir, 'bad.jsonl'); + await fs.writeFile(bad, (await fs.readFile(fixture, 'utf8')) + '{broken'); + const c = capture(); + expect(await run(['diff', fixture, bad], c.io)).toBe(2); + expect(c.err()).toContain('invalid JSON'); + }); +}); + +describe('diff report input safety', () => { + it('never overwrites either trace or symlink/hardlink aliases with HTML', async () => { + const dir = await tmpDir(), + a = path.join(dir, 'a.jsonl'), + b = path.join(dir, 'b.jsonl'), + sym = path.join(dir, 'alias'), + hard = path.join(dir, 'hard'); + const bytes = await fs.readFile(fixture); + await fs.writeFile(a, bytes); + await fs.writeFile(b, bytes); + await fs.symlink(a, sym); + await fs.link(b, hard); + for (const output of [a, b, sym, hard]) { + const c = capture(); + expect(await run(['diff', a, b, '--html', output], c.io)).toBe(2); + expect(c.err()).toContain('must not overwrite'); + } + expect(await fs.readFile(a)).toEqual(bytes); + expect(await fs.readFile(b)).toEqual(bytes); + }); +}); diff --git a/test/diff.test.ts b/test/diff.test.ts new file mode 100644 index 0000000..11f3ab1 --- /dev/null +++ b/test/diff.test.ts @@ -0,0 +1,209 @@ +import { describe, expect, it } from 'vitest'; +import { diffTraces, diffViolations, parseDiffGates, renderDiffHtml } from '../src/diff.js'; +import type { Trace } from '../src/types.js'; +const trace = (items: Array<{ id?: string; t?: number; delta?: string }>, adapter = 'ai-sdk'): Trace => ({ + meta: { + v: 1, + kind: 'meta', + session: 'x', + adapter, + framing: 'sse', + protocol: 'ai-sdk', + startedAt: '2026-01-01', + }, + frames: items.map((x, seq) => ({ + seq, + t_ms: x.t ?? seq, + raw: '', + event: { + type: 'text-delta', + ...(x.id ? { id: x.id } : {}), + delta: x.delta ?? 'x', + }, + })), +}); +describe('trace diff', () => { + it('reports identical traces and key-order-insensitive payloads', () => { + const a = trace([{ id: 'a' }]); + expect(diffTraces(a, a).noDifferences).toBe(true); + }); + it('separates added removed payload order and elapsed latency', () => { + const d = diffTraces( + trace([{ id: 'a' }, { id: 'b' }, { id: 'c' }]), + trace([ + { id: 'c', t: 202 }, + { id: 'a', t: 201, delta: 'changed' }, + { id: 'd', t: 203 }, + ]), + ); + expect(d.added).toHaveLength(1); + expect(d.removed).toHaveLength(1); + expect(d.matched.every((x) => x.reordered)).toBe(true); + expect(d.matched[0]?.payload[0]?.path).toBe('/delta'); + expect(diffViolations(d, parseDiffGates('added,removed,payload,latency>200ms,count'))).toEqual([ + 'added', + 'removed', + 'payload', + 'latency>200ms', + ]); + }); + it('does not call an insertion a reorder for identified events', () => { + const d = diffTraces(trace([{ id: 'a' }, { id: 'b' }]), trace([{ id: 'new' }, { id: 'a' }, { id: 'b' }])); + expect(d.matched.some((x) => x.reordered)).toBe(false); + }); + it('matches repeated deltas by id and occurrence, documenting anonymous ordinal fallback', () => { + const d = diffTraces(trace([{ id: 'a' }, { id: 'a' }]), trace([{ id: 'a' }, { id: 'a', delta: 'new' }])); + expect(d.matched).toHaveLength(2); + expect(d.matched[1]?.payload).toHaveLength(1); + expect(diffTraces(trace([{}]), trace([{ delta: 'x' }, {}])).added).toHaveLength(1); + }); + it('refuses adapter, protocol and framing mismatches', () => { + const a = trace([]), + b = trace([], 'ndjson'); + expect(() => diffTraces(a, b)).toThrow('incompatible'); + b.meta.adapter = a.meta.adapter; + b.meta.framing = 'raw'; + expect(() => diffTraces(a, b)).toThrow('incompatible'); + }); + it('rejects malformed gates and timestamps and uses positive strict latency thresholds', () => { + for (const g of ['', 'reorder', 'latency>NaNms', 'latency>-1ms']) expect(() => parseDiffGates(g)).toThrow(); + expect(() => diffTraces(trace([{ t: NaN }]), trace([]))).toThrow(); + const d = diffTraces(trace([{ id: 'a', t: 200 }]), trace([{ id: 'a', t: 400 }])); + expect(diffViolations(d, parseDiffGates('latency>200ms'))).toEqual([]); + }); + it('escapes text and reuses sandboxed before/after timeline panels', () => { + const a = trace([{ id: '' }]); + const html = renderDiffHtml(diffTraces(a, trace([])), a, trace([])); + expect(html).toContain('<script>'); + expect(html).toContain('title="Before trace" sandbox="allow-scripts"'); + }); +}); + +describe('tool-call acceptance and structural keys', () => { + it('distinguishes a removed tool, an added tool, and exactly +200ms', () => { + const before = trace([ + { id: 'call-keep', t: 0 }, + { id: 'call-old', t: 20 }, + ]); + const after = trace([ + { id: 'call-keep', t: 200 }, + { id: 'call-new', t: 220 }, + ]); + for (const t of [before, after]) for (const f of t.frames) f.event.type = 'tool-call-delta'; + const d = diffTraces(before, after); + expect(d.removed[0]?.key).toContain('call-old'); + expect(d.added[0]?.key).toContain('call-new'); + expect(d.matched[0]?.latencyDeltaMs).toBe(200); + expect(diffViolations(d, parseDiffGates('latency>199ms'))).toEqual(['latency>199ms']); + expect(diffViolations(d, parseDiffGates('latency>200ms'))).toEqual([]); + }); + it('ignores object key ordering, reports escaped JSON pointers, and matches native input indices', () => { + const a = trace([{}, {}]), + b = trace([{}, {}]); + a.frames[0]!.event.data = { inputIndex: 0, value: { b: 2, a: 1 } }; + a.frames[1]!.event.data = { inputIndex: 1, 'a/b~': { ok: true } }; + b.frames[0]!.event.data = { inputIndex: 1, 'a/b~': { ok: false } }; + b.frames[1]!.event.data = { value: { a: 1, b: 2 }, inputIndex: 0 }; + const d = diffTraces(a, b); + expect(d.added).toHaveLength(0); + expect(d.removed).toHaveLength(0); + expect(d.matched[0]?.payload).toHaveLength(0); + expect(d.matched[1]?.payload[0]?.path).toBe('/data/a~1b~0/ok'); + expect(d.matched.every((x) => x.reordered)).toBe(true); + }); +}); + +describe('provider identities and completed JSON args', () => { + it('aligns OpenAI nested tool indices instead of absolute ordinals', () => { + const a = trace([{}, {}]), + b = trace([{}]); + for (const [i, f] of a.frames.entries()) { + f.event.type = 'tool-call-delta'; + f.event.data = { id: 'step', delta: { step_details: { tool_calls: [{ index: i }] } } }; + } + b.frames[0]!.event = structuredClone(a.frames[1]!.event); + const d = diffTraces(a, b); + expect(d.removed).toHaveLength(1); + expect(d.added).toHaveLength(0); + expect(d.matched[0]?.beforeIndex).toBe(1); + }); + it('aligns LangGraph nested tool chunk index within message', () => { + const a = trace([{}, {}]), + b = trace([{}]); + for (const [i, f] of a.frames.entries()) { + f.event.type = 'tool-call-delta'; + f.event.data = [{ id: 'message', tool_call_chunks: [{ index: i }] }]; + } + b.frames[0]!.event = structuredClone(a.frames[1]!.event); + expect(diffTraces(a, b).matched[0]?.beforeIndex).toBe(1); + }); + it('treats valid completed JSON args structurally but not incomplete fragments', () => { + const a = trace([{ id: 'tool' }]), + b = trace([{ id: 'tool' }]); + for (const t of [a, b]) { + t.frames[0]!.event.type = 'tool-call-delta'; + t.frames[0]!.event.complete = true; + } + a.frames[0]!.event.argsDelta = '{"a":1,"b":2}'; + b.frames[0]!.event.argsDelta = '{"b":2,"a":1}'; + expect(diffTraces(a, b).noDifferences).toBe(true); + b.frames[0]!.event.complete = false; + expect(diffTraces(a, b).matched[0]?.payload.length).toBeGreaterThan(0); + }); +}); + +describe('conservative argument numbers and scoped indices', () => { + it('does not hide unsafe integer or fractional argument changes', () => { + for (const [left, right] of [ + ['9007199254740992', '9007199254740993'], + ['0.10000000000000001', '0.1'], + ['1.0000000000000001','1'], + ]) { + const a = trace([{ id: 'tool' }]), + b = trace([{ id: 'tool' }]); + for (const t of [a, b]) Object.assign(t.frames[0]!.event, { type: 'tool-call-delta', complete: true }); + a.frames[0]!.event.argsDelta = `{"n":${left}}`; + b.frames[0]!.event.argsDelta = `{"n":${right}}`; + expect(diffViolations(diffTraces(a, b), parseDiffGates('payload'))).toEqual(['payload']); + } + }); + it('keeps equal tool indices from different OpenAI steps or LangGraph messages distinct', () => { + for (const provider of ['openai', 'langgraph']) { + const a = trace([{}, {}]), + b = trace([{}]); + for (const [i, f] of a.frames.entries()) { + f.event.type = 'tool-call-delta'; + f.event.data = + provider === 'openai' + ? { id: `step-${i}`, delta: { step_details: { tool_calls: [{ index: 0 }] } } } + : [{ id: `message-${i}`, tool_call_chunks: [{ index: 0 }] }]; + } + b.frames[0]!.event = structuredClone(a.frames[1]!.event); + const d = diffTraces(a, b); + expect(d.removed[0]?.key).toContain(provider === 'openai' ? 'step-0' : 'message-0'); + expect(d.matched[0]?.beforeIndex).toBe(1); + } + }); +}); + + +it('never equates parsed JSON strings with unparsed argument source',()=>{ + const a=trace([{id:'tool'}]),b=trace([{id:'tool'}]); + for(const t of [a,b])Object.assign(t.frames[0]!.event,{type:'tool-call-delta',complete:true}); + a.frames[0]!.event.argsDelta='{"n":0.1}';b.frames[0]!.event.argsDelta=JSON.stringify(a.frames[0]!.event.argsDelta); + expect(diffViolations(diffTraces(a,b),parseDiffGates('payload'))).toEqual(['payload']); +}); + + +it('reports completed argument changes at the real string field, without internal wrapper keys',()=>{ + const a=trace([{id:'tool'}]),b=trace([{id:'tool'}]);for(const t of [a,b])Object.assign(t.frames[0]!.event,{type:'tool-call-delta',complete:true}); + a.frames[0]!.event.argsDelta='{"a":1}';b.frames[0]!.event.argsDelta='{"a":2}'; + expect(diffTraces(a,b).matched[0]?.payload).toEqual([{path:'/argsDelta',before:'{"a":1}',after:'{"a":2}'}]); +}); + + +it('reports completion-only changes without inventing an identical argument delta',()=>{ + const a=trace([{id:'tool'}]),b=trace([{id:'tool'}]);for(const t of [a,b])Object.assign(t.frames[0]!.event,{type:'tool-call-delta',argsDelta:'{"a":1}'}); + b.frames[0]!.event.complete=true;const changes=diffTraces(a,b).matched[0]!.payload; + expect(changes.map(c=>c.path)).toEqual(['/complete']); +}); diff --git a/test/proxy.test.ts b/test/proxy.test.ts index 9041e3d..9b3ac6e 100644 --- a/test/proxy.test.ts +++ b/test/proxy.test.ts @@ -188,7 +188,11 @@ describe('recording proxy', () => { const upstream = await startUpstream(); closers.push(upstream.close); const dir = await tmpDir(); - const middleware = createMiddleware({ target: upstream.url, outDir: dir }); + // Response completion precedes the asynchronous recording flush. Wait for + // onSession before removing the output directory in afterEach. + let resolveRecorded!: (trace: Trace) => void; + const recorded = new Promise((resolve) => { resolveRecorded = resolve; }); + const middleware = createMiddleware({ target: upstream.url, outDir: dir, onSession: resolveRecorded }); const server = http.createServer((req, res) => middleware(req, res)); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); closers.push( @@ -203,6 +207,9 @@ describe('recording proxy', () => { const response = await fetch(`http://127.0.0.1:${port}/api/chat`); expect(response.status).toBe(200); expect(await response.text()).toContain('world'); + const trace = await recorded; + expect(trace.frames.at(-1)?.event.type).toBe('finish'); + expect((await readTrace(trace.path!)).frames).toHaveLength(4); }); it('redacts credential headers in the trace by default', async () => {