upstream-replay-server.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. /* eslint-disable max-lines -- Upstream E2E 回放服务需要集中维护 fixture 匹配、capture artifact、chunk timeline 和 SSE 时间轴回放,拆开会让录制/回放协议更难追踪。 */
  2. import { randomUUID } from "node:crypto";
  3. import { readFileSync } from "node:fs";
  4. import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
  5. import type { AddressInfo } from "node:net";
  6. import { resolve } from "node:path";
  7. import type {
  8. E2ENetworkCaptureArtifact,
  9. E2ENetworkCaptureRecord,
  10. E2ENetworkCaptureResponseEvent,
  11. E2ENetworkResponseChunk,
  12. } from "./network-capture-proxy.js";
  13. import { writeE2EJsonFileAtomically } from "./e2e-atomic-json-file.js";
  14. import {
  15. redactE2ENetworkCaptureJson,
  16. redactE2ENetworkCaptureJsonText,
  17. sanitizeE2ENetworkCaptureHeaders,
  18. } from "./e2e-network-capture-redaction.js";
  19. import { resolveUpstreamModels } from "./upstream-recorded-models.js";
  20. // 夹具未写模型时,回放响应使用与 E2E 供应商相同的模型(环境变量或录制模型)。
  21. const DEFAULT_REPLAY_MODEL = resolveUpstreamModels().model;
  22. const LATEST_AGENT_ID_REPLAY_TOKEN = "{{latestAgentId}}";
  23. const LATEST_BASH_TASK_ID_REPLAY_TOKEN = "{{latestBashTaskId}}";
  24. const MEMORY_ROOT_REPLAY_TOKEN = "{{memoryRoot}}";
  25. const LATEST_AUTOMATION_ID_REPLAY_TOKEN = "{{latestAutomationId}}";
  26. const BROWSER_FIXTURE_URL_REPLAY_TOKEN = "{{browserFixtureUrl}}";
  27. const LATEST_BROWSER_TAB_ID_REPLAY_TOKEN = "{{latestBrowserTabId}}";
  28. const LATEST_BROWSER_TAB_A_ID_REPLAY_TOKEN = "{{latestBrowserTabAId}}";
  29. const LATEST_BROWSER_TAB_B_ID_REPLAY_TOKEN = "{{latestBrowserTabBId}}";
  30. export interface UpstreamReplayServer {
  31. artifactPath: string;
  32. baseUrl: string;
  33. host: string;
  34. port: number;
  35. stop(): Promise<void>;
  36. }
  37. interface StartUpstreamReplayServerOptions {
  38. artifactPath: string;
  39. artifactWriter?: typeof writeE2EJsonFileAtomically;
  40. fixtureVariables?: Readonly<Record<string, string>>;
  41. fixturePaths: string[];
  42. host?: string;
  43. port?: number;
  44. }
  45. interface UpstreamReplayFixtureFile {
  46. fixtures: UpstreamReplayFixture[];
  47. version: 1;
  48. }
  49. type UpstreamReplayCloseMode = "end" | "destroy";
  50. interface UpstreamReplayFixture {
  51. metadata?: { timingPolicy?: string };
  52. captured?: {
  53. capturedAt?: string;
  54. model?: string;
  55. requestBodyBytes?: number;
  56. responseBodyBytes?: number;
  57. statusCode?: number;
  58. url?: string;
  59. };
  60. description?: string;
  61. id: string;
  62. maxMatches?: number;
  63. match: {
  64. bodyExcludes?: string[];
  65. bodyIncludes?: string[];
  66. lastUserMessageExcludes?: string[];
  67. lastUserMessageIncludes?: string[];
  68. method?: string;
  69. pathIncludes?: string;
  70. };
  71. replay?: {
  72. consumeOnce?: boolean;
  73. };
  74. response: {
  75. body?: string;
  76. chunks?: UpstreamReplayResponseChunk[];
  77. closeMode?: UpstreamReplayCloseMode;
  78. delayMs?: number;
  79. /** 仅 controlled-stream:写出 N 个 chunk 后等待测试完成关键操作再释放。 */
  80. releaseAfterChunks?: number;
  81. events?: E2ENetworkCaptureResponseEvent[];
  82. headers?: Record<string, string>;
  83. statusCode: number;
  84. statusMessage?: string;
  85. text?: UpstreamReplayTextResponse | string;
  86. toolUse?: UpstreamReplayToolUseResponse;
  87. toolUses?: UpstreamReplayToolUseResponse[];
  88. };
  89. }
  90. interface ReplayVariables {
  91. browserFixtureUrl?: string;
  92. latestBrowserTabAId?: string;
  93. latestBrowserTabBId?: string;
  94. latestBrowserTabId?: string;
  95. latestAgentId?: string;
  96. latestBashTaskId?: string;
  97. memoryRoot?: string;
  98. latestAutomationId?: string;
  99. }
  100. interface UpstreamReplayResponseChunk {
  101. base64?: string;
  102. byteLength?: number;
  103. offsetMs: number;
  104. text?: string;
  105. }
  106. interface UpstreamReplayTextResponse {
  107. id?: string;
  108. inputTokens?: number;
  109. model?: string;
  110. outputTokens?: number;
  111. text: string;
  112. }
  113. interface UpstreamReplayToolUseResponse {
  114. id?: string;
  115. input: Record<string, unknown>;
  116. inputTokens?: number;
  117. messageId?: string;
  118. model?: string;
  119. name: string;
  120. outputTokens?: number;
  121. }
  122. type MutableCaptureRecord = E2ENetworkCaptureRecord;
  123. export async function startUpstreamReplayServer(
  124. options: StartUpstreamReplayServerOptions,
  125. ): Promise<UpstreamReplayServer> {
  126. const host = options.host ?? "127.0.0.1";
  127. const requestedPort = options.port ?? 0;
  128. const artifactPath = resolve(options.artifactPath);
  129. const artifactWriter = options.artifactWriter ?? writeE2EJsonFileAtomically;
  130. // Bug 根因:provider fixture 里的绝对路径过去只能写死为 POSIX 临时目录,
  131. // Windows Node 与 Git Bash 因而会访问不同文件。静态变量必须在 matcher 之前展开,
  132. // 否则 response 虽能拿到正确路径,请求仍会先因 matcher 含 token 而 miss。
  133. const fixtures = options.fixturePaths.flatMap((path) =>
  134. loadFixtureFile(path, options.fixtureVariables),
  135. );
  136. for (const fixture of fixtures) {
  137. const count = fixture.response.releaseAfterChunks;
  138. if (count === undefined) continue;
  139. if (
  140. fixture.metadata?.timingPolicy !== "controlled-stream" ||
  141. !Number.isInteger(count) ||
  142. count < 1 ||
  143. count >= (fixture.response.chunks?.length ?? 0) ||
  144. fixture.response.events?.length
  145. ) {
  146. throw new Error(`无效受控流 fixture: ${fixture.id};不得改变 recorded/fault stream 的时间轴`);
  147. }
  148. }
  149. const fixtureMatchCounts = new Map<string, number>();
  150. const records: MutableCaptureRecord[] = [];
  151. const gates = new Map<string, { release(): void; cancel(): void }>();
  152. const holdStream = (id: string, response: ServerResponse) =>
  153. new Promise<void>((resolveGate, rejectGate) => {
  154. if (gates.has(id)) {
  155. rejectGate(new Error(`重复的受控请求: ${id}`));
  156. return;
  157. }
  158. const finish = (error?: Error) => {
  159. clearTimeout(timer);
  160. response.off("close", closed);
  161. gates.delete(id);
  162. if (error) rejectGate(error);
  163. else resolveGate();
  164. };
  165. const closed = () => finish(new Error(`受控流已断开: ${id}`));
  166. const timer = setTimeout(() => finish(new Error(`受控流未被测试释放: ${id}`)), 120_000);
  167. gates.set(id, { release: () => finish(), cancel: closed });
  168. response.once("close", closed);
  169. });
  170. let serverPort = requestedPort;
  171. let baseUrl = `http://${host}:${serverPort}`;
  172. let artifactWriteQueue = Promise.resolve();
  173. const writeArtifact = () => {
  174. const artifact = {
  175. generatedAt: new Date().toISOString(),
  176. proxy: {
  177. caCertPath: "",
  178. host,
  179. port: serverPort,
  180. proxyUrl: baseUrl,
  181. },
  182. records: records.map(serializeRecord),
  183. version: 1,
  184. } satisfies E2ENetworkCaptureArtifact;
  185. // 同一 replay server 内也必须串行替换 artifact;否则多个并发 child request
  186. // 会让各自的临时文件竞争目标路径,并可能把较旧快照写到较新快照之后。
  187. const nextWrite = artifactWriteQueue
  188. .catch(() => undefined)
  189. .then(() => artifactWriter(artifactPath, artifact));
  190. artifactWriteQueue = nextWrite;
  191. return nextWrite;
  192. };
  193. const server = createServer((request, response) => {
  194. // 控制端不进入模型请求台账;每个独立 replay server 只释放自己的正在等待的 fixture。
  195. if (request.method === "GET" && request.url === "/__e2e__/gates") {
  196. response.setHeader("content-type", "application/json");
  197. response.end(JSON.stringify([...gates.keys()]));
  198. return;
  199. }
  200. if (request.method === "POST" && request.url?.startsWith("/__e2e__/release/")) {
  201. const gate = gates.get(request.url.slice("/__e2e__/release/".length));
  202. response.statusCode = gate ? 204 : 409;
  203. gate?.release();
  204. response.end();
  205. return;
  206. }
  207. void handleReplayRequest(request, response, {
  208. baseUrl,
  209. fixtureMatchCounts,
  210. fixtures,
  211. records,
  212. writeArtifact,
  213. holdStream,
  214. }).catch((error: unknown) => {
  215. // Bug 根因:旧 handler 是裸 `void Promise`,capture 写入抛错后没有任何人
  216. // 收口 response,provider 只能一直等 socket。证据通道失败必须显式结束请求。
  217. closeReplayResponseAfterHandlerError(response, error);
  218. });
  219. });
  220. await new Promise<void>((resolveStart, rejectStart) => {
  221. server.listen(requestedPort, host, () => {
  222. const address = server.address() as AddressInfo | null;
  223. if (!address) {
  224. rejectStart(new Error("Upstream replay server did not expose an address"));
  225. return;
  226. }
  227. serverPort = address.port;
  228. baseUrl = `http://${host}:${serverPort}`;
  229. resolveStart();
  230. });
  231. server.once("error", rejectStart);
  232. });
  233. try {
  234. await writeArtifact();
  235. } catch (error) {
  236. // Bug 根因:listen 成功后首次 artifact 写入失败会直接退出启动流程,
  237. // 但旧实现没有关闭 HTTP server,导致端口和进程句柄跨测试泄漏。
  238. // 清理错误不能覆盖原始写入错误;同时显式等待队列收口再向调用方失败。
  239. await closeServerListener(server).catch(() => undefined);
  240. await artifactWriteQueue.catch(() => undefined);
  241. throw error;
  242. }
  243. return {
  244. artifactPath,
  245. baseUrl,
  246. host,
  247. port: serverPort,
  248. stop: () => {
  249. for (const gate of gates.values()) gate.cancel();
  250. return stopServer(server, writeArtifact);
  251. },
  252. };
  253. }
  254. async function handleReplayRequest(
  255. request: IncomingMessage,
  256. response: ServerResponse,
  257. context: {
  258. baseUrl: string;
  259. fixtureMatchCounts: Map<string, number>;
  260. fixtures: UpstreamReplayFixture[];
  261. records: MutableCaptureRecord[];
  262. writeArtifact(): Promise<void>;
  263. holdStream(id: string, response: ServerResponse): Promise<void>;
  264. },
  265. ) {
  266. const startedAt = new Date().toISOString();
  267. const requestBody = await readRequestBody(request);
  268. const requestText = requestBody.toString("utf-8");
  269. const requestJson = parseJson(requestText);
  270. const requestUrl = buildRequestUrl(request, context.baseUrl);
  271. const record: MutableCaptureRecord = {
  272. host: requestUrl.host,
  273. id: randomUUID(),
  274. method: request.method ?? "GET",
  275. path: requestUrl.pathname + requestUrl.search,
  276. protocol: requestUrl.protocol === "https:" ? "https" : "http",
  277. requestBodyBytes: requestBody.length,
  278. requestHeaders: sanitizeE2ENetworkCaptureHeaders(request.headers),
  279. requestJson: requestJson ? redactE2ENetworkCaptureJson(requestJson) : undefined,
  280. requestTextPreview: requestJson ? undefined : requestText,
  281. responseBodyBytes: 0,
  282. responseHeaders: {},
  283. startedAt,
  284. status: "pending",
  285. url: requestUrl.toString(),
  286. };
  287. context.records.push(record);
  288. await context.writeArtifact();
  289. const fixtureIndex = findFixtureIndex(
  290. context.fixtures,
  291. record,
  292. requestText,
  293. requestJson,
  294. context.fixtureMatchCounts,
  295. );
  296. const fixture = fixtureIndex >= 0 ? context.fixtures[fixtureIndex] : undefined;
  297. if (!fixture) {
  298. const body = JSON.stringify(
  299. {
  300. error: {
  301. message: `Missing Upstream e2e fixture for ${record.method} ${record.path}`,
  302. },
  303. },
  304. null,
  305. 2,
  306. );
  307. await writeResponse(response, record, {
  308. body,
  309. headers: { "content-type": "application/json; charset=utf-8" },
  310. statusCode: 500,
  311. statusMessage: "Missing Fixture",
  312. });
  313. await context.writeArtifact();
  314. return;
  315. }
  316. context.fixtureMatchCounts.set(fixture.id, (context.fixtureMatchCounts.get(fixture.id) ?? 0) + 1);
  317. record.replay = {
  318. closeMode: fixture.response.closeMode ?? "end",
  319. fixtureId: fixture.id,
  320. };
  321. await context.writeArtifact();
  322. if (fixture.response.delayMs && fixture.response.delayMs > 0) {
  323. await new Promise((resolveDelay) => setTimeout(resolveDelay, fixture.response.delayMs));
  324. }
  325. if (fixture.response.events?.length) {
  326. await writeEventStreamResponse(response, record, {
  327. events: fixture.response.events,
  328. closeMode: fixture.response.closeMode ?? "end",
  329. headers: fixture.response.headers ?? {},
  330. statusCode: fixture.response.statusCode,
  331. statusMessage: fixture.response.statusMessage ?? "OK",
  332. });
  333. } else {
  334. const resolvedBody = resolveFixtureResponseBody(
  335. fixture.response,
  336. extractReplayVariables(requestText, requestJson),
  337. );
  338. if (resolvedBody.body.includes(BROWSER_FIXTURE_URL_REPLAY_TOKEN)) {
  339. // 修复原因:动态 URL marker 缺失或格式错误时保留模板会让 Browser tool
  340. // 导航到字面量 `{{browserFixtureUrl}}`,随后可能被 compact 摘要掩盖成成功。
  341. // replay 必须 fail closed,让 fixture/request 契约错误直接可见。
  342. await writeResponse(response, record, {
  343. body: JSON.stringify({
  344. error: { message: "Missing E2E_BROWSER_FIXTURE_URL replay variable" },
  345. }),
  346. headers: { "content-type": "application/json; charset=utf-8" },
  347. statusCode: 500,
  348. statusMessage: "Missing Replay Variable",
  349. });
  350. // Bug 根因:artifact 写入改为异步后,这个 fail-closed 分支仍然 fire-and-forget;
  351. // Windows 原子替换最终失败时 rejection 会逃出统一 handler catch。返回前等待,
  352. // 让诊断落盘失败按请求生命周期收口,且不覆盖已经返回的 500 业务证据。
  353. await context.writeArtifact();
  354. return;
  355. }
  356. await writeResponse(response, record, {
  357. body: resolvedBody.body,
  358. chunks: fixture.response.chunks,
  359. closeMode: fixture.response.closeMode,
  360. ...(fixture.response.releaseAfterChunks === undefined
  361. ? {}
  362. : {
  363. releaseAfterChunks: fixture.response.releaseAfterChunks,
  364. release: () => {
  365. if (fixture.metadata?.timingPolicy !== "controlled-stream")
  366. throw new Error("仅 controlled-stream 允许显式释放");
  367. return context.holdStream(fixture.id, response);
  368. },
  369. }),
  370. headers: resolvedBody.headers,
  371. statusCode: fixture.response.statusCode,
  372. statusMessage: fixture.response.statusMessage ?? "OK",
  373. });
  374. }
  375. if (fixture.replay?.consumeOnce) {
  376. context.fixtures.splice(fixtureIndex, 1);
  377. }
  378. await context.writeArtifact();
  379. }
  380. function closeReplayResponseAfterHandlerError(response: ServerResponse, error: unknown): void {
  381. const message = error instanceof Error ? error.message : String(error);
  382. console.warn(`[upstream-replay] request handler failed: ${message}`);
  383. if (response.writableEnded || response.destroyed) {
  384. return;
  385. }
  386. if (response.headersSent) {
  387. response.destroy(error instanceof Error ? error : undefined);
  388. return;
  389. }
  390. const body = JSON.stringify({
  391. error: { message: `Upstream E2E replay handler failed: ${message}` },
  392. });
  393. response.writeHead(500, "Replay Handler Failed", {
  394. "content-length": String(Buffer.byteLength(body, "utf-8")),
  395. "content-type": "application/json; charset=utf-8",
  396. });
  397. response.end(body);
  398. }
  399. function resolveFixtureResponseBody(
  400. response: UpstreamReplayFixture["response"],
  401. variables: ReplayVariables,
  402. ): { body: string; headers: Record<string, string> } {
  403. if (response.body !== undefined) {
  404. return {
  405. body: applyReplayVariablesToString(response.body, variables),
  406. headers: response.headers ?? {},
  407. };
  408. }
  409. if (response.toolUses?.length) {
  410. return {
  411. body: buildToolUsesSseBody(
  412. response.toolUses.map((toolUse) => resolveReplayToolUse(toolUse, variables)),
  413. ),
  414. headers: withEventStreamHeaders(response.headers),
  415. };
  416. }
  417. if (response.toolUse) {
  418. return {
  419. body: buildToolUseSseBody(resolveReplayToolUse(response.toolUse, variables)),
  420. headers: withEventStreamHeaders(response.headers),
  421. };
  422. }
  423. if (response.toolUses?.length) {
  424. return {
  425. body: buildToolUsesSseBody(response.toolUses),
  426. headers: withEventStreamHeaders(response.headers),
  427. };
  428. }
  429. if (response.text !== undefined) {
  430. return {
  431. body: buildTextSseBody(resolveReplayText(response.text, variables)),
  432. headers: withEventStreamHeaders(response.headers),
  433. };
  434. }
  435. return {
  436. body: "",
  437. headers: response.headers ?? {},
  438. };
  439. }
  440. function extractReplayVariables(requestText: string, requestJson: unknown): ReplayVariables {
  441. const requestContent = `${requestText}\n${JSON.stringify(requestJson ?? {})}`;
  442. const browserTabIds = readLatestBrowserTabIds(requestJson);
  443. return {
  444. browserFixtureUrl: readBrowserFixtureUrl(requestContent),
  445. ...browserTabIds,
  446. latestAgentId: readLatestAgentId(requestContent),
  447. latestBashTaskId: readLatestBashTaskId(requestContent),
  448. memoryRoot: readMemoryRoot(requestContent),
  449. latestAutomationId: readLatestAutomationId(requestJson),
  450. };
  451. }
  452. function readLatestBrowserTabIds(
  453. value: unknown,
  454. ): Pick<ReplayVariables, "latestBrowserTabAId" | "latestBrowserTabBId" | "latestBrowserTabId"> {
  455. const ids = {
  456. e2eBrowserTabAId: [] as string[],
  457. e2eBrowserTabBId: [] as string[],
  458. e2eBrowserTabId: [] as string[],
  459. };
  460. const names = Object.keys(ids) as Array<keyof typeof ids>;
  461. const visit = (candidate: unknown): void => {
  462. if (typeof candidate === "string") {
  463. // Bug 根因:真实 Node REPL tool_result 是 `=> { ... }\nStructured content:`,
  464. // 不是可直接 JSON.parse 的纯 JSON;只解析带 E2E 命名空间的显式字段,避免
  465. // 从任意 tab 文本猜 id,让 replay 真正模拟模型读取上一条工具结果。
  466. for (const name of names) {
  467. const pattern = new RegExp(`["']${name}["']\\s*:\\s*["']([^"']+)["']`, "gu");
  468. for (const match of candidate.matchAll(pattern)) {
  469. if (match[1]?.trim()) ids[name].push(match[1].trim());
  470. }
  471. }
  472. return;
  473. }
  474. if (Array.isArray(candidate)) {
  475. for (const item of candidate) visit(item);
  476. return;
  477. }
  478. if (!candidate || typeof candidate !== "object") return;
  479. for (const [key, child] of Object.entries(candidate)) {
  480. if (names.includes(key as keyof typeof ids) && typeof child === "string" && child.trim()) {
  481. ids[key as keyof typeof ids].push(child.trim());
  482. }
  483. visit(child);
  484. }
  485. };
  486. visit(value);
  487. return {
  488. latestBrowserTabAId: ids.e2eBrowserTabAId.at(-1),
  489. latestBrowserTabBId: ids.e2eBrowserTabBId.at(-1),
  490. latestBrowserTabId: ids.e2eBrowserTabId.at(-1),
  491. };
  492. }
  493. function readBrowserFixtureUrl(value: string): string | undefined {
  494. // 修复原因:Browser Use E2E 的本地 HTTP server 使用随机端口,provider replay
  495. // 必须从用户 marker 回填真实 URL,不能依赖固定端口或公网页面制造并发/网络抖动。
  496. const match = value.match(
  497. /E2E_BROWSER_FIXTURE_URL:(https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?\/[^\s"'<>),]*)/u,
  498. );
  499. return match?.[1];
  500. }
  501. function readLatestAgentId(value: string): string | undefined {
  502. const matches = [...value.matchAll(/agentId:\s*(agent_[A-Za-z0-9_-]+)/gu)];
  503. return matches.at(-1)?.[1];
  504. }
  505. function readLatestBashTaskId(value: string): string | undefined {
  506. // Bash task ID 每次运行都不同;只从真实 launch result 回填,不能把 Agent ID 当作 Bash ID。
  507. const matches = [
  508. ...value.matchAll(/Command running in background with ID:\s*([A-Za-z0-9_-]+)\./gu),
  509. ];
  510. return matches.at(-1)?.[1];
  511. }
  512. function readMemoryRoot(value: string): string | undefined {
  513. // Memory root 由 Runtime 按 workspace 计算,fixture 不能硬编码本机绝对路径。
  514. // 只从已经进入 provider request 的既有 Memory prompt 提取路径并回填 tool input。
  515. const matches = [
  516. ...value.matchAll(/persistent(?:,\s*)? file-based memory(?: system)? at `([^`]+?)[/\\]`/giu),
  517. ];
  518. return matches.at(-1)?.[1];
  519. }
  520. function readLatestAutomationId(value: unknown): string | undefined {
  521. const ids: string[] = [];
  522. const visit = (candidate: unknown): void => {
  523. if (typeof candidate === "string") {
  524. const trimmed = candidate.trim();
  525. if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
  526. try {
  527. visit(JSON.parse(trimmed) as unknown);
  528. return;
  529. } catch {
  530. // tool_result 可能是带前后说明的文本,继续用正则提取其中的 JSON 字段。
  531. }
  532. }
  533. for (const match of candidate.matchAll(
  534. /["'](?:automationId|automation_id)["']\s*:\s*["']([^"']+)["']/gu,
  535. )) {
  536. if (match[1]?.trim()) ids.push(match[1].trim());
  537. }
  538. return;
  539. }
  540. if (Array.isArray(candidate)) {
  541. for (const item of candidate) visit(item);
  542. return;
  543. }
  544. if (!candidate || typeof candidate !== "object") return;
  545. for (const [key, child] of Object.entries(candidate)) {
  546. if (
  547. (key === "automationId" || key === "automation_id") &&
  548. typeof child === "string" &&
  549. child.trim()
  550. ) {
  551. ids.push(child.trim());
  552. }
  553. visit(child);
  554. }
  555. };
  556. visit(value);
  557. return ids.at(-1);
  558. }
  559. function resolveReplayToolUse(
  560. toolUse: UpstreamReplayToolUseResponse,
  561. variables: ReplayVariables,
  562. ): UpstreamReplayToolUseResponse {
  563. return {
  564. ...toolUse,
  565. id: toolUse.id === undefined ? undefined : applyReplayVariablesToString(toolUse.id, variables),
  566. input: applyReplayVariables(toolUse.input, variables) as Record<string, unknown>,
  567. messageId:
  568. toolUse.messageId === undefined
  569. ? undefined
  570. : applyReplayVariablesToString(toolUse.messageId, variables),
  571. };
  572. }
  573. function resolveReplayText(
  574. textResponse: UpstreamReplayTextResponse | string,
  575. variables: ReplayVariables,
  576. ): UpstreamReplayTextResponse | string {
  577. if (typeof textResponse === "string") {
  578. return applyReplayVariablesToString(textResponse, variables);
  579. }
  580. return {
  581. ...textResponse,
  582. id:
  583. textResponse.id === undefined
  584. ? undefined
  585. : applyReplayVariablesToString(textResponse.id, variables),
  586. text: applyReplayVariablesToString(textResponse.text, variables),
  587. };
  588. }
  589. function applyReplayVariables(value: unknown, variables: ReplayVariables): unknown {
  590. if (typeof value === "string") {
  591. return applyReplayVariablesToString(value, variables);
  592. }
  593. if (Array.isArray(value)) {
  594. return value.map((item) => applyReplayVariables(item, variables));
  595. }
  596. if (!value || typeof value !== "object") {
  597. return value;
  598. }
  599. return Object.fromEntries(
  600. Object.entries(value).map(([key, child]) => [key, applyReplayVariables(child, variables)]),
  601. );
  602. }
  603. function applyReplayVariablesToString(value: string, variables: ReplayVariables): string {
  604. let resolved = value;
  605. if (variables.latestBrowserTabId !== undefined) {
  606. resolved = resolved
  607. .split(LATEST_BROWSER_TAB_ID_REPLAY_TOKEN)
  608. .join(variables.latestBrowserTabId);
  609. }
  610. if (variables.latestBrowserTabAId !== undefined) {
  611. resolved = resolved
  612. .split(LATEST_BROWSER_TAB_A_ID_REPLAY_TOKEN)
  613. .join(variables.latestBrowserTabAId);
  614. }
  615. if (variables.latestBrowserTabBId !== undefined) {
  616. resolved = resolved
  617. .split(LATEST_BROWSER_TAB_B_ID_REPLAY_TOKEN)
  618. .join(variables.latestBrowserTabBId);
  619. }
  620. if (variables.latestAgentId !== undefined) {
  621. resolved = resolved.split(LATEST_AGENT_ID_REPLAY_TOKEN).join(variables.latestAgentId);
  622. }
  623. if (variables.latestBashTaskId !== undefined) {
  624. resolved = resolved.split(LATEST_BASH_TASK_ID_REPLAY_TOKEN).join(variables.latestBashTaskId);
  625. }
  626. if (variables.memoryRoot !== undefined) {
  627. resolved = resolved.split(MEMORY_ROOT_REPLAY_TOKEN).join(variables.memoryRoot);
  628. }
  629. if (variables.latestAutomationId !== undefined) {
  630. resolved = resolved.split(LATEST_AUTOMATION_ID_REPLAY_TOKEN).join(variables.latestAutomationId);
  631. }
  632. if (variables.browserFixtureUrl !== undefined) {
  633. resolved = resolved.split(BROWSER_FIXTURE_URL_REPLAY_TOKEN).join(variables.browserFixtureUrl);
  634. }
  635. return resolved;
  636. }
  637. function withEventStreamHeaders(
  638. headers: Record<string, string> | undefined,
  639. ): Record<string, string> {
  640. return {
  641. "cache-control": "no-cache",
  642. "content-type": "text/event-stream; charset=utf-8",
  643. ...headers,
  644. };
  645. }
  646. function buildToolUseSseBody(toolUse: UpstreamReplayToolUseResponse): string {
  647. return buildToolUsesSseBody([toolUse]);
  648. }
  649. function buildToolUsesSseBody(toolUses: UpstreamReplayToolUseResponse[]): string {
  650. const firstToolUse = toolUses[0];
  651. const messageId = firstToolUse?.messageId ?? `msg_${sanitizeSseId(firstToolUse?.name ?? "tool")}`;
  652. const inputTokens = firstToolUse?.inputTokens;
  653. const outputTokens = toolUses.reduce((sum, toolUse) => sum + (toolUse.outputTokens ?? 16), 0);
  654. return [
  655. sseEvent("message_start", {
  656. type: "message_start",
  657. message: {
  658. id: messageId,
  659. type: "message",
  660. role: "assistant",
  661. model: firstToolUse?.model ?? DEFAULT_REPLAY_MODEL,
  662. content: [],
  663. stop_reason: null,
  664. stop_sequence: null,
  665. usage: replayUsage(inputTokens, 0),
  666. },
  667. }),
  668. ...toolUses.flatMap((toolUse, index) => buildToolUseContentBlockEvents(toolUse, index)),
  669. sseEvent("message_delta", {
  670. type: "message_delta",
  671. delta: {
  672. stop_reason: "tool_use",
  673. stop_sequence: null,
  674. },
  675. usage: replayUsage(inputTokens, outputTokens),
  676. }),
  677. sseEvent("message_stop", { type: "message_stop" }),
  678. ].join("");
  679. }
  680. function buildToolUseContentBlockEvents(
  681. toolUse: UpstreamReplayToolUseResponse,
  682. index: number,
  683. ): string[] {
  684. const toolCallId = toolUse.id ?? `toolu_${sanitizeSseId(toolUse.name)}`;
  685. const inputJson = JSON.stringify(toolUse.input);
  686. return [
  687. sseEvent("content_block_start", {
  688. type: "content_block_start",
  689. index,
  690. content_block: {
  691. type: "tool_use",
  692. id: toolCallId,
  693. name: toolUse.name,
  694. input: {},
  695. },
  696. }),
  697. sseEvent("content_block_delta", {
  698. type: "content_block_delta",
  699. index,
  700. delta: {
  701. type: "input_json_delta",
  702. partial_json: inputJson,
  703. },
  704. }),
  705. sseEvent("content_block_stop", {
  706. type: "content_block_stop",
  707. index,
  708. }),
  709. ];
  710. }
  711. function buildTextSseBody(textResponse: UpstreamReplayTextResponse | string): string {
  712. const text = typeof textResponse === "string" ? textResponse : textResponse.text;
  713. const id =
  714. typeof textResponse === "string"
  715. ? "msg_upstream_e2e_text"
  716. : (textResponse.id ?? "msg_upstream_e2e_text");
  717. const model =
  718. typeof textResponse === "string"
  719. ? DEFAULT_REPLAY_MODEL
  720. : (textResponse.model ?? DEFAULT_REPLAY_MODEL);
  721. const inputTokens = typeof textResponse === "string" ? undefined : textResponse.inputTokens;
  722. const outputTokens = typeof textResponse === "string" ? undefined : textResponse.outputTokens;
  723. return [
  724. sseEvent("message_start", {
  725. type: "message_start",
  726. message: {
  727. id,
  728. type: "message",
  729. role: "assistant",
  730. model,
  731. content: [],
  732. stop_reason: null,
  733. stop_sequence: null,
  734. usage: replayUsage(inputTokens, 0),
  735. },
  736. }),
  737. sseEvent("content_block_start", {
  738. type: "content_block_start",
  739. index: 0,
  740. content_block: {
  741. type: "text",
  742. text: "",
  743. },
  744. }),
  745. sseEvent("content_block_delta", {
  746. type: "content_block_delta",
  747. index: 0,
  748. delta: {
  749. type: "text_delta",
  750. text,
  751. },
  752. }),
  753. sseEvent("content_block_stop", {
  754. type: "content_block_stop",
  755. index: 0,
  756. }),
  757. sseEvent("message_delta", {
  758. type: "message_delta",
  759. delta: {
  760. stop_reason: "end_turn",
  761. stop_sequence: null,
  762. },
  763. usage: replayUsage(inputTokens, outputTokens ?? 12),
  764. }),
  765. sseEvent("message_stop", { type: "message_stop" }),
  766. ].join("");
  767. }
  768. function replayUsage(inputTokens = 128, outputTokens = 0) {
  769. return {
  770. input_tokens: inputTokens,
  771. cache_creation_input_tokens: 0,
  772. cache_read_input_tokens: 0,
  773. output_tokens: outputTokens,
  774. service_tier: "standard",
  775. };
  776. }
  777. function sseEvent(event: string, data: unknown): string {
  778. return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
  779. }
  780. function sanitizeSseId(value: string): string {
  781. return value
  782. .replace(/[^a-zA-Z0-9]+/g, "_")
  783. .replace(/^_+|_+$/g, "")
  784. .toLowerCase();
  785. }
  786. async function writeResponse(
  787. response: ServerResponse,
  788. record: MutableCaptureRecord,
  789. fixtureResponse: {
  790. body: string;
  791. chunks?: UpstreamReplayResponseChunk[];
  792. closeMode?: UpstreamReplayCloseMode;
  793. releaseAfterChunks?: number;
  794. release?: () => Promise<void>;
  795. headers: Record<string, string>;
  796. statusCode: number;
  797. statusMessage: string;
  798. },
  799. ) {
  800. const responseChunks = normalizeReplayChunks(fixtureResponse.chunks);
  801. const destroyStream = fixtureResponse.closeMode === "destroy";
  802. // 同时带 text/chunks 的 fixture 实际发送 chunks,证据也必须记录真正发出的字节。
  803. const responseBody =
  804. responseChunks.length > 0
  805. ? Buffer.concat(responseChunks.map((chunk) => chunk.body))
  806. : Buffer.from(fixtureResponse.body, "utf-8");
  807. const responseHeaders = sanitizeResponseHeaders(fixtureResponse.headers);
  808. if (responseChunks.length === 0 && !destroyStream) {
  809. responseHeaders["content-length"] = String(responseBody.length);
  810. } else {
  811. delete responseHeaders["content-length"];
  812. }
  813. response.writeHead(fixtureResponse.statusCode, fixtureResponse.statusMessage, responseHeaders);
  814. let actualOffsets: number[] | undefined;
  815. if (responseChunks.length > 0) {
  816. if (
  817. fixtureResponse.release &&
  818. (!Number.isInteger(fixtureResponse.releaseAfterChunks) ||
  819. fixtureResponse.releaseAfterChunks! < 1 ||
  820. fixtureResponse.releaseAfterChunks! >= responseChunks.length)
  821. ) {
  822. throw new Error("releaseAfterChunks 必须位于流内部");
  823. }
  824. actualOffsets = await writeReplayChunks(response, responseChunks, fixtureResponse);
  825. if (!destroyStream) response.end();
  826. } else if (destroyStream) {
  827. await writeResponseChunk(response, responseBody);
  828. } else {
  829. response.end(responseBody);
  830. }
  831. record.status = destroyStream ? "error" : "complete";
  832. record.completedAt = new Date().toISOString();
  833. record.durationMs = durationMs(record.startedAt, record.completedAt);
  834. record.statusCode = fixtureResponse.statusCode;
  835. record.statusMessage = fixtureResponse.statusMessage;
  836. record.responseBodyBytes = responseBody.length;
  837. record.responseHeaders = sanitizeE2ENetworkCaptureHeaders(responseHeaders);
  838. record.responseTextPreview = redactE2ENetworkCaptureJsonText(responseBody.toString("utf-8"));
  839. if (responseChunks.length > 0) {
  840. record.responseChunkTimeline = responseChunks.map((chunk, index) => ({
  841. base64: chunk.body.toString("base64"),
  842. byteLength: chunk.byteLength,
  843. offsetMs: fixtureResponse.release ? actualOffsets![index]! : chunk.offsetMs,
  844. }));
  845. }
  846. if (destroyStream) {
  847. // chunks/body 与 events 必须执行相同的故障合同;只在 artifact 标 destroy
  848. // 却正常 end 会把网络中断测试变成正常 EOF,并制造“产品假完成”的错误结论。
  849. record.error = "Replay fixture destroyed SSE response stream";
  850. response.destroy();
  851. }
  852. }
  853. async function writeReplayChunks(
  854. response: ServerResponse,
  855. chunks: NormalizedReplayChunk[],
  856. control?: { releaseAfterChunks?: number; release?: () => Promise<void> },
  857. ) {
  858. let previousOffsetMs = 0;
  859. const startedAt = Date.now();
  860. const actualOffsets: number[] = [];
  861. for (const [index, chunk] of chunks.entries()) {
  862. if (index === control?.releaseAfterChunks && control.release) {
  863. await control.release();
  864. // 只移除被释放的那段人为慢窗口,后续 chunk 间距及内容原样保留。
  865. previousOffsetMs = chunk.offsetMs;
  866. }
  867. const delayMs = Math.max(0, chunk.offsetMs - previousOffsetMs);
  868. if (delayMs > 0) {
  869. await new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs));
  870. }
  871. previousOffsetMs = chunk.offsetMs;
  872. actualOffsets.push(Date.now() - startedAt);
  873. // 等待写入完成后再进入下一帧/销毁连接,避免最后一帧只进用户态队列就被丢弃。
  874. await writeResponseChunk(response, chunk.body);
  875. }
  876. return actualOffsets;
  877. }
  878. interface NormalizedReplayChunk {
  879. body: Buffer;
  880. byteLength: number;
  881. offsetMs: number;
  882. }
  883. function normalizeReplayChunks(
  884. chunks: UpstreamReplayResponseChunk[] | undefined,
  885. ): NormalizedReplayChunk[] {
  886. return (
  887. chunks
  888. ?.map((chunk) => {
  889. const body =
  890. chunk.base64 !== undefined
  891. ? Buffer.from(chunk.base64, "base64")
  892. : Buffer.from(chunk.text ?? "", "utf-8");
  893. return {
  894. body,
  895. byteLength: chunk.byteLength ?? body.length,
  896. offsetMs: Math.max(0, Math.round(chunk.offsetMs)),
  897. };
  898. })
  899. .filter((chunk) => chunk.body.length > 0) ?? []
  900. );
  901. }
  902. async function writeEventStreamResponse(
  903. response: ServerResponse,
  904. record: MutableCaptureRecord,
  905. fixtureResponse: {
  906. closeMode: UpstreamReplayCloseMode;
  907. events: E2ENetworkCaptureResponseEvent[];
  908. headers: Record<string, string>;
  909. statusCode: number;
  910. statusMessage: string;
  911. },
  912. ) {
  913. const responseHeaders = sanitizeResponseHeaders(fixtureResponse.headers);
  914. delete responseHeaders["content-length"];
  915. response.writeHead(fixtureResponse.statusCode, fixtureResponse.statusMessage, responseHeaders);
  916. const startedAtMs = Date.now();
  917. const sortedEvents = [...fixtureResponse.events].sort(
  918. (left, right) => left.offsetMs - right.offsetMs || left.sequence - right.sequence,
  919. );
  920. const chunks: string[] = [];
  921. const replayedEvents: E2ENetworkCaptureResponseEvent[] = [];
  922. for (const event of sortedEvents) {
  923. const elapsedMs = Date.now() - startedAtMs;
  924. const waitMs = Math.max(0, event.offsetMs - elapsedMs);
  925. if (waitMs > 0) {
  926. await new Promise((resolveDelay) => setTimeout(resolveDelay, waitMs));
  927. }
  928. const text = event.text;
  929. await writeResponseChunk(response, text);
  930. chunks.push(text);
  931. replayedEvents.push({
  932. byteLength: Buffer.byteLength(text, "utf-8"),
  933. offsetMs: Math.max(0, Date.now() - startedAtMs),
  934. ...(event.partial ? { partial: true } : {}),
  935. sequence: replayedEvents.length,
  936. text,
  937. });
  938. }
  939. const body = chunks.join("");
  940. record.status = fixtureResponse.closeMode === "destroy" ? "error" : "complete";
  941. record.completedAt = new Date().toISOString();
  942. record.durationMs = durationMs(record.startedAt, record.completedAt);
  943. record.statusCode = fixtureResponse.statusCode;
  944. record.statusMessage = fixtureResponse.statusMessage;
  945. record.responseBodyBytes = Buffer.byteLength(body, "utf-8");
  946. record.responseEvents = replayedEvents;
  947. record.responseHeaders = sanitizeE2ENetworkCaptureHeaders(responseHeaders);
  948. record.responseTextPreview = redactE2ENetworkCaptureJsonText(body);
  949. record.replay = {
  950. ...record.replay,
  951. closeMode: fixtureResponse.closeMode,
  952. };
  953. if (fixtureResponse.closeMode === "destroy") {
  954. // 修复原因:SSE fault case 需要区分“provider 正常 EOF 但内容不完整”和
  955. // “连接在流式响应中异常断开”。这里按 fixture 显式销毁 socket,artifact 也标记为 error,
  956. // 让后续 E2E 能稳定构造断流语义,而不是依赖真实网络抖动。
  957. record.error = "Replay fixture destroyed SSE response stream";
  958. response.destroy();
  959. return;
  960. }
  961. response.end();
  962. }
  963. function writeResponseChunk(response: ServerResponse, text: string | Buffer): Promise<void> {
  964. return new Promise((resolveWrite, rejectWrite) => {
  965. response.write(text, (error) => {
  966. if (error) {
  967. rejectWrite(error);
  968. return;
  969. }
  970. resolveWrite();
  971. });
  972. });
  973. }
  974. function findFixtureIndex(
  975. fixtures: UpstreamReplayFixture[],
  976. record: E2ENetworkCaptureRecord,
  977. requestText: string,
  978. requestJson: unknown,
  979. fixtureMatchCounts: ReadonlyMap<string, number>,
  980. ) {
  981. return fixtures.findIndex((fixture) => {
  982. // 回放需要表达“同一类请求前 N 次失败、之后成功”的时序。
  983. // maxMatches 只影响测试 fixture 匹配,不进入产品协议。
  984. if (
  985. fixture.maxMatches !== undefined &&
  986. (fixtureMatchCounts.get(fixture.id) ?? 0) >= fixture.maxMatches
  987. ) {
  988. return false;
  989. }
  990. const expectedMethod = fixture.match.method?.toUpperCase();
  991. if (expectedMethod && expectedMethod !== record.method.toUpperCase()) {
  992. return false;
  993. }
  994. if (fixture.match.pathIncludes && !record.path.includes(fixture.match.pathIncludes)) {
  995. return false;
  996. }
  997. const latestUserMessageText =
  998. fixture.match.lastUserMessageIncludes || fixture.match.lastUserMessageExcludes
  999. ? readLatestUserMessageText(requestJson)
  1000. : "";
  1001. return (
  1002. (fixture.match.bodyIncludes?.every(
  1003. (text) => requestText.includes(text) || captureContainsText(requestJson, text),
  1004. ) ??
  1005. true) &&
  1006. (fixture.match.bodyExcludes?.every(
  1007. (text) => !requestText.includes(text) && !captureContainsText(requestJson, text),
  1008. ) ??
  1009. true) &&
  1010. (fixture.match.lastUserMessageIncludes?.every((text) =>
  1011. latestUserMessageText.includes(text),
  1012. ) ??
  1013. true) &&
  1014. (fixture.match.lastUserMessageExcludes?.every(
  1015. (text) => !latestUserMessageText.includes(text),
  1016. ) ??
  1017. true)
  1018. );
  1019. });
  1020. }
  1021. function readLatestUserMessageText(requestJson: unknown): string {
  1022. if (!requestJson || typeof requestJson !== "object") {
  1023. return "";
  1024. }
  1025. const messages = (requestJson as { messages?: unknown }).messages;
  1026. if (!Array.isArray(messages)) {
  1027. return "";
  1028. }
  1029. for (let index = messages.length - 1; index >= 0; index -= 1) {
  1030. const message = messages[index];
  1031. if (!message || typeof message !== "object") {
  1032. continue;
  1033. }
  1034. if ((message as { role?: unknown }).role !== "user") {
  1035. continue;
  1036. }
  1037. return readMessageContentText((message as { content?: unknown }).content);
  1038. }
  1039. return "";
  1040. }
  1041. function readMessageContentText(content: unknown): string {
  1042. if (typeof content === "string") {
  1043. return content;
  1044. }
  1045. if (!Array.isArray(content)) {
  1046. return "";
  1047. }
  1048. return content
  1049. .map((part) => {
  1050. if (!part || typeof part !== "object") {
  1051. return "";
  1052. }
  1053. const text = (part as { text?: unknown }).text;
  1054. if (typeof text === "string") {
  1055. return text;
  1056. }
  1057. // 修复原因:Anthropic Messages continuation 把工具结果放在 user/tool_result.content,
  1058. // 旧实现只读 text,导致 fixture 只能在整段 body 搜 marker;而 tool code 本身
  1059. // 也包含成功 marker,会把真实失败结果误匹配成成功 continuation。
  1060. if ((part as { type?: unknown }).type === "tool_result") {
  1061. return readMessageContentText((part as { content?: unknown }).content);
  1062. }
  1063. return "";
  1064. })
  1065. .filter(Boolean)
  1066. .join("\n");
  1067. }
  1068. function loadFixtureFile(
  1069. path: string,
  1070. fixtureVariables: Readonly<Record<string, string>> = {},
  1071. ): UpstreamReplayFixture[] {
  1072. const resolvedPath = resolve(path);
  1073. const parsed = JSON.parse(readFileSync(resolvedPath, "utf-8")) as
  1074. | UpstreamReplayFixtureFile
  1075. | E2ENetworkCaptureArtifact;
  1076. if (isUpstreamReplayFixtureFile(parsed)) {
  1077. return applyFixtureVariables(parsed.fixtures, fixtureVariables) as UpstreamReplayFixture[];
  1078. }
  1079. if (isNetworkCaptureArtifact(parsed)) {
  1080. return applyFixtureVariables(
  1081. convertCaptureArtifactToFixtures(parsed, resolvedPath),
  1082. fixtureVariables,
  1083. ) as UpstreamReplayFixture[];
  1084. }
  1085. throw new Error(`Invalid Upstream e2e replay fixture: ${path}`);
  1086. }
  1087. function applyFixtureVariables(
  1088. value: unknown,
  1089. variables: Readonly<Record<string, string>>,
  1090. ): unknown {
  1091. if (typeof value === "string") {
  1092. return Object.entries(variables).reduce(
  1093. (resolvedValue, [name, replacement]) => resolvedValue.split(`{{${name}}}`).join(replacement),
  1094. value,
  1095. );
  1096. }
  1097. if (Array.isArray(value)) {
  1098. return value.map((item) => applyFixtureVariables(item, variables));
  1099. }
  1100. if (!value || typeof value !== "object") {
  1101. return value;
  1102. }
  1103. return Object.fromEntries(
  1104. Object.entries(value).map(([key, child]) => [key, applyFixtureVariables(child, variables)]),
  1105. );
  1106. }
  1107. function isUpstreamReplayFixtureFile(
  1108. value: UpstreamReplayFixtureFile | E2ENetworkCaptureArtifact,
  1109. ): value is UpstreamReplayFixtureFile {
  1110. return value.version === 1 && Array.isArray((value as UpstreamReplayFixtureFile).fixtures);
  1111. }
  1112. function isNetworkCaptureArtifact(
  1113. value: UpstreamReplayFixtureFile | E2ENetworkCaptureArtifact,
  1114. ): value is E2ENetworkCaptureArtifact {
  1115. return value.version === 1 && Array.isArray((value as E2ENetworkCaptureArtifact).records);
  1116. }
  1117. function convertCaptureArtifactToFixtures(
  1118. artifact: E2ENetworkCaptureArtifact,
  1119. sourcePath: string,
  1120. ): UpstreamReplayFixture[] {
  1121. const fixtures = artifact.records
  1122. .filter((record) => record.status === "complete" && record.statusCode)
  1123. .filter(
  1124. (record) =>
  1125. record.responseTextPreview ||
  1126. record.responseChunkTimeline?.length ||
  1127. record.responseEvents?.length,
  1128. )
  1129. .map((record, index) => {
  1130. const responseBody = resolveCapturedResponseBody(record);
  1131. return {
  1132. id: `capture-${String(index + 1).padStart(3, "0")}-${record.id}`,
  1133. description: `Captured replay response from ${sourcePath}`,
  1134. match: {
  1135. method: record.method,
  1136. pathIncludes: capturePathname(record),
  1137. },
  1138. replay: {
  1139. consumeOnce: true,
  1140. },
  1141. captured: {
  1142. capturedAt: record.completedAt ?? record.startedAt,
  1143. requestBodyBytes: record.requestBodyBytes,
  1144. responseBodyBytes: record.responseBodyBytes,
  1145. statusCode: record.statusCode,
  1146. url: record.url,
  1147. },
  1148. response: {
  1149. body: responseBody,
  1150. chunks: record.responseChunkTimeline?.map(captureChunkToReplayChunk),
  1151. events: record.responseEvents,
  1152. headers: record.responseHeaders,
  1153. statusCode: record.statusCode ?? 200,
  1154. statusMessage: record.statusMessage,
  1155. },
  1156. } satisfies UpstreamReplayFixture;
  1157. });
  1158. if (fixtures.length === 0) {
  1159. throw new Error(`Upstream capture artifact has no replayable records: ${sourcePath}`);
  1160. }
  1161. return fixtures;
  1162. }
  1163. function resolveCapturedResponseBody(record: E2ENetworkCaptureRecord) {
  1164. if (record.responseTextPreview && !record.responseBodyTruncated) {
  1165. return record.responseTextPreview;
  1166. }
  1167. if (record.responseEvents?.length) {
  1168. return record.responseEvents.map((event) => event.text).join("");
  1169. }
  1170. if (record.responseChunkTimeline?.length && !record.responseChunkTimelineTruncated) {
  1171. return Buffer.concat(
  1172. record.responseChunkTimeline.map((chunk) => Buffer.from(chunk.base64, "base64")),
  1173. ).toString("utf-8");
  1174. }
  1175. return record.responseTextPreview ?? "";
  1176. }
  1177. function captureChunkToReplayChunk(chunk: E2ENetworkResponseChunk): UpstreamReplayResponseChunk {
  1178. return {
  1179. base64: chunk.base64,
  1180. byteLength: chunk.byteLength,
  1181. offsetMs: chunk.offsetMs,
  1182. };
  1183. }
  1184. function capturePathname(record: E2ENetworkCaptureRecord) {
  1185. try {
  1186. return new URL(record.url).pathname;
  1187. } catch {
  1188. return record.path.split("?")[0] || record.path;
  1189. }
  1190. }
  1191. async function readRequestBody(request: IncomingMessage): Promise<Buffer> {
  1192. const chunks: Buffer[] = [];
  1193. for await (const chunk of request) {
  1194. chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  1195. }
  1196. return Buffer.concat(chunks);
  1197. }
  1198. function buildRequestUrl(request: IncomingMessage, baseUrl: string): URL {
  1199. const rawUrl = request.url ?? "/";
  1200. if (/^https?:\/\//i.test(rawUrl)) {
  1201. return new URL(rawUrl);
  1202. }
  1203. const path = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
  1204. return new URL(path, baseUrl);
  1205. }
  1206. function sanitizeResponseHeaders(headers: Record<string, string>): Record<string, string> {
  1207. const sanitized: Record<string, string> = {};
  1208. for (const [name, value] of Object.entries(headers)) {
  1209. const normalizedName = name.toLowerCase();
  1210. if (normalizedName === "connection" || normalizedName === "transfer-encoding") {
  1211. continue;
  1212. }
  1213. sanitized[normalizedName] = value;
  1214. }
  1215. return sanitized;
  1216. }
  1217. function parseJson(text: string): unknown {
  1218. if (!text.trim()) {
  1219. return undefined;
  1220. }
  1221. try {
  1222. return JSON.parse(text) as unknown;
  1223. } catch {
  1224. return undefined;
  1225. }
  1226. }
  1227. function captureContainsText(value: unknown, expected: string): boolean {
  1228. if (typeof value === "string") {
  1229. return value.includes(expected);
  1230. }
  1231. if (Array.isArray(value)) {
  1232. return value.some((item) => captureContainsText(item, expected));
  1233. }
  1234. if (!value || typeof value !== "object") {
  1235. return false;
  1236. }
  1237. return Object.values(value).some((child) => captureContainsText(child, expected));
  1238. }
  1239. function serializeRecord(record: MutableCaptureRecord): E2ENetworkCaptureRecord {
  1240. return record;
  1241. }
  1242. function durationMs(startedAt: string, completedAt: string): number {
  1243. return Math.max(0, Date.parse(completedAt) - Date.parse(startedAt));
  1244. }
  1245. async function stopServer(server: Server, writeArtifact: () => Promise<void>): Promise<void> {
  1246. await closeServerListener(server);
  1247. await writeArtifact();
  1248. }
  1249. async function closeServerListener(server: Server): Promise<void> {
  1250. await new Promise<void>((resolveStop, rejectStop) => {
  1251. server.close((error) => {
  1252. if (error) {
  1253. rejectStop(error);
  1254. return;
  1255. }
  1256. resolveStop();
  1257. });
  1258. });
  1259. }