@midscene/core 1.15.2-beta-20261012123219.0 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/es/agent/action-readiness.mjs +6 -3
  2. package/dist/es/agent/action-readiness.mjs.map +1 -1
  3. package/dist/es/agent/agent.mjs +4 -2
  4. package/dist/es/agent/agent.mjs.map +1 -1
  5. package/dist/es/agent/execution-session.mjs.map +1 -1
  6. package/dist/es/agent/task-builder.mjs +35 -16
  7. package/dist/es/agent/task-builder.mjs.map +1 -1
  8. package/dist/es/agent/tasks.mjs +35 -12
  9. package/dist/es/agent/tasks.mjs.map +1 -1
  10. package/dist/es/agent/utils.mjs +1 -1
  11. package/dist/es/device/index.mjs +7 -6
  12. package/dist/es/device/index.mjs.map +1 -1
  13. package/dist/es/report-generator.mjs +30 -14
  14. package/dist/es/report-generator.mjs.map +1 -1
  15. package/dist/es/report-html-template.mjs +1 -1
  16. package/dist/es/report.mjs +121 -44
  17. package/dist/es/report.mjs.map +1 -1
  18. package/dist/es/service/index.mjs.map +1 -1
  19. package/dist/es/task-runner.mjs +22 -12
  20. package/dist/es/task-runner.mjs.map +1 -1
  21. package/dist/es/test-run-report.mjs.map +1 -1
  22. package/dist/es/test-runner/engine/case-runner.mjs +1 -1
  23. package/dist/es/test-runner/engine/case-runner.mjs.map +1 -1
  24. package/dist/es/test-runner/engine/document-runtime.mjs +42 -12
  25. package/dist/es/test-runner/engine/document-runtime.mjs.map +1 -1
  26. package/dist/es/test-runner/engine/execute-step.mjs +130 -12
  27. package/dist/es/test-runner/engine/execute-step.mjs.map +1 -1
  28. package/dist/es/test-runner/engine/index.mjs +1 -0
  29. package/dist/es/test-runner/engine/project-runtime.mjs +14 -5
  30. package/dist/es/test-runner/engine/project-runtime.mjs.map +1 -1
  31. package/dist/es/test-runner/engine/resource-operations.mjs +286 -35
  32. package/dist/es/test-runner/engine/resource-operations.mjs.map +1 -1
  33. package/dist/es/test-runner/engine/result-metadata.mjs +21 -0
  34. package/dist/es/test-runner/engine/result-metadata.mjs.map +1 -0
  35. package/dist/es/test-runner/engine/run-collected-case.mjs +30 -9
  36. package/dist/es/test-runner/engine/run-collected-case.mjs.map +1 -1
  37. package/dist/es/test-runner/engine/run-workflow-document.mjs +57 -10
  38. package/dist/es/test-runner/engine/run-workflow-document.mjs.map +1 -1
  39. package/dist/es/test-runner/errors.mjs +26 -13
  40. package/dist/es/test-runner/errors.mjs.map +1 -1
  41. package/dist/es/test-runner/execution-record.mjs +2 -0
  42. package/dist/es/test-runner/execution-record.mjs.map +1 -1
  43. package/dist/es/test-runner/index.mjs +3 -0
  44. package/dist/es/test-runner/reporting/agent-report.mjs +2 -7
  45. package/dist/es/test-runner/reporting/agent-report.mjs.map +1 -1
  46. package/dist/es/test-runner/reporting/merge-report.mjs +207 -6
  47. package/dist/es/test-runner/reporting/merge-report.mjs.map +1 -1
  48. package/dist/es/test-runner/reporting/metrics.mjs +77 -0
  49. package/dist/es/test-runner/reporting/metrics.mjs.map +1 -0
  50. package/dist/es/test-runner/reporting/sanitize.mjs +92 -16
  51. package/dist/es/test-runner/reporting/sanitize.mjs.map +1 -1
  52. package/dist/es/test-runner/reporting/test-plan.mjs +56 -0
  53. package/dist/es/test-runner/reporting/test-plan.mjs.map +1 -0
  54. package/dist/es/test-runner/reporting/test-run-report.mjs +208 -21
  55. package/dist/es/test-runner/reporting/test-run-report.mjs.map +1 -1
  56. package/dist/es/types.mjs.map +1 -1
  57. package/dist/es/utils.mjs +1 -1
  58. package/dist/es/yaml/legacy-yaml-runtime.mjs +3 -3
  59. package/dist/es/yaml/legacy-yaml-runtime.mjs.map +1 -1
  60. package/dist/lib/agent/action-readiness.js +6 -3
  61. package/dist/lib/agent/action-readiness.js.map +1 -1
  62. package/dist/lib/agent/agent.js +4 -2
  63. package/dist/lib/agent/agent.js.map +1 -1
  64. package/dist/lib/agent/execution-session.js.map +1 -1
  65. package/dist/lib/agent/task-builder.js +42 -23
  66. package/dist/lib/agent/task-builder.js.map +1 -1
  67. package/dist/lib/agent/tasks.js +35 -12
  68. package/dist/lib/agent/tasks.js.map +1 -1
  69. package/dist/lib/agent/utils.js +1 -1
  70. package/dist/lib/device/index.js +7 -6
  71. package/dist/lib/device/index.js.map +1 -1
  72. package/dist/lib/report-generator.js +30 -14
  73. package/dist/lib/report-generator.js.map +1 -1
  74. package/dist/lib/report-html-template.js +1 -1
  75. package/dist/lib/report.js +121 -44
  76. package/dist/lib/report.js.map +1 -1
  77. package/dist/lib/service/index.js.map +1 -1
  78. package/dist/lib/task-runner.js +22 -12
  79. package/dist/lib/task-runner.js.map +1 -1
  80. package/dist/lib/test-run-report.js.map +1 -1
  81. package/dist/lib/test-runner/engine/case-runner.js +1 -1
  82. package/dist/lib/test-runner/engine/case-runner.js.map +1 -1
  83. package/dist/lib/test-runner/engine/document-runtime.js +41 -11
  84. package/dist/lib/test-runner/engine/document-runtime.js.map +1 -1
  85. package/dist/lib/test-runner/engine/execute-step.js +131 -10
  86. package/dist/lib/test-runner/engine/execute-step.js.map +1 -1
  87. package/dist/lib/test-runner/engine/index.js +9 -2
  88. package/dist/lib/test-runner/engine/index.js.map +1 -1
  89. package/dist/lib/test-runner/engine/project-runtime.js +13 -4
  90. package/dist/lib/test-runner/engine/project-runtime.js.map +1 -1
  91. package/dist/lib/test-runner/engine/resource-operations.js +319 -38
  92. package/dist/lib/test-runner/engine/resource-operations.js.map +1 -1
  93. package/dist/lib/test-runner/engine/result-metadata.js +58 -0
  94. package/dist/lib/test-runner/engine/result-metadata.js.map +1 -0
  95. package/dist/lib/test-runner/engine/run-collected-case.js +29 -8
  96. package/dist/lib/test-runner/engine/run-collected-case.js.map +1 -1
  97. package/dist/lib/test-runner/engine/run-workflow-document.js +57 -10
  98. package/dist/lib/test-runner/engine/run-workflow-document.js.map +1 -1
  99. package/dist/lib/test-runner/errors.js +42 -23
  100. package/dist/lib/test-runner/errors.js.map +1 -1
  101. package/dist/lib/test-runner/execution-record.js +2 -0
  102. package/dist/lib/test-runner/execution-record.js.map +1 -1
  103. package/dist/lib/test-runner/index.js +88 -16
  104. package/dist/lib/test-runner/index.js.map +1 -1
  105. package/dist/lib/test-runner/node/index.js +2 -2
  106. package/dist/lib/test-runner/reporting/agent-report.js +2 -7
  107. package/dist/lib/test-runner/reporting/agent-report.js.map +1 -1
  108. package/dist/lib/test-runner/reporting/merge-report.js +207 -6
  109. package/dist/lib/test-runner/reporting/merge-report.js.map +1 -1
  110. package/dist/lib/test-runner/reporting/metrics.js +114 -0
  111. package/dist/lib/test-runner/reporting/metrics.js.map +1 -0
  112. package/dist/lib/test-runner/reporting/sanitize.js +94 -15
  113. package/dist/lib/test-runner/reporting/sanitize.js.map +1 -1
  114. package/dist/lib/test-runner/reporting/test-plan.js +90 -0
  115. package/dist/lib/test-runner/reporting/test-plan.js.map +1 -0
  116. package/dist/lib/test-runner/reporting/test-run-report.js +208 -21
  117. package/dist/lib/test-runner/reporting/test-run-report.js.map +1 -1
  118. package/dist/lib/types.js.map +1 -1
  119. package/dist/lib/utils.js +1 -1
  120. package/dist/lib/yaml/legacy-yaml-runtime.js +2 -2
  121. package/dist/lib/yaml/legacy-yaml-runtime.js.map +1 -1
  122. package/dist/types/agent/action-readiness.d.ts +1 -1
  123. package/dist/types/agent/action-readiness.d.ts.map +1 -1
  124. package/dist/types/agent/agent.d.ts +1 -1
  125. package/dist/types/agent/agent.d.ts.map +1 -1
  126. package/dist/types/agent/execution-session.d.ts +1 -1
  127. package/dist/types/agent/execution-session.d.ts.map +1 -1
  128. package/dist/types/agent/task-builder.d.ts +4 -2
  129. package/dist/types/agent/task-builder.d.ts.map +1 -1
  130. package/dist/types/agent/tasks.d.ts +3 -0
  131. package/dist/types/agent/tasks.d.ts.map +1 -1
  132. package/dist/types/device/index.d.ts +3 -3
  133. package/dist/types/device/index.d.ts.map +1 -1
  134. package/dist/types/report-generator.d.ts +4 -2
  135. package/dist/types/report-generator.d.ts.map +1 -1
  136. package/dist/types/report.d.ts.map +1 -1
  137. package/dist/types/service/index.d.ts +2 -2
  138. package/dist/types/service/index.d.ts.map +1 -1
  139. package/dist/types/task-runner.d.ts +1 -1
  140. package/dist/types/task-runner.d.ts.map +1 -1
  141. package/dist/types/test-run-report.d.ts +157 -8
  142. package/dist/types/test-run-report.d.ts.map +1 -1
  143. package/dist/types/test-runner/engine/document-runtime.d.ts.map +1 -1
  144. package/dist/types/test-runner/engine/execute-step.d.ts +1 -0
  145. package/dist/types/test-runner/engine/execute-step.d.ts.map +1 -1
  146. package/dist/types/test-runner/engine/index.d.ts +1 -0
  147. package/dist/types/test-runner/engine/index.d.ts.map +1 -1
  148. package/dist/types/test-runner/engine/project-runtime.d.ts.map +1 -1
  149. package/dist/types/test-runner/engine/resource-operations.d.ts +41 -3
  150. package/dist/types/test-runner/engine/resource-operations.d.ts.map +1 -1
  151. package/dist/types/test-runner/engine/result-metadata.d.ts +18 -0
  152. package/dist/types/test-runner/engine/result-metadata.d.ts.map +1 -0
  153. package/dist/types/test-runner/engine/run-collected-case.d.ts.map +1 -1
  154. package/dist/types/test-runner/engine/run-workflow-document.d.ts.map +1 -1
  155. package/dist/types/test-runner/engine/types.d.ts +47 -8
  156. package/dist/types/test-runner/engine/types.d.ts.map +1 -1
  157. package/dist/types/test-runner/errors.d.ts +7 -0
  158. package/dist/types/test-runner/errors.d.ts.map +1 -1
  159. package/dist/types/test-runner/execution-record.d.ts.map +1 -1
  160. package/dist/types/test-runner/index.d.ts +2 -0
  161. package/dist/types/test-runner/index.d.ts.map +1 -1
  162. package/dist/types/test-runner/node/types.d.ts +9 -1
  163. package/dist/types/test-runner/node/types.d.ts.map +1 -1
  164. package/dist/types/test-runner/parser/types.d.ts +5 -0
  165. package/dist/types/test-runner/parser/types.d.ts.map +1 -1
  166. package/dist/types/test-runner/reporting/agent-report.d.ts.map +1 -1
  167. package/dist/types/test-runner/reporting/merge-report.d.ts +1 -1
  168. package/dist/types/test-runner/reporting/merge-report.d.ts.map +1 -1
  169. package/dist/types/test-runner/reporting/metrics.d.ts +7 -0
  170. package/dist/types/test-runner/reporting/metrics.d.ts.map +1 -0
  171. package/dist/types/test-runner/reporting/sanitize.d.ts +1 -0
  172. package/dist/types/test-runner/reporting/sanitize.d.ts.map +1 -1
  173. package/dist/types/test-runner/reporting/test-plan.d.ts +8 -0
  174. package/dist/types/test-runner/reporting/test-plan.d.ts.map +1 -0
  175. package/dist/types/test-runner/reporting/test-run-report.d.ts.map +1 -1
  176. package/dist/types/test-runner/reporting/types.d.ts +6 -1
  177. package/dist/types/test-runner/reporting/types.d.ts.map +1 -1
  178. package/dist/types/types.d.ts +3 -1
  179. package/dist/types/types.d.ts.map +1 -1
  180. package/package.json +2 -2
@@ -9,6 +9,7 @@ import { imageRefFileExtension, normalizeStoredImageRef } from "./dump/image-ref
9
9
  import { parseBase64ImageDataUrl, resolveImageSource } from "./dump/screenshot-store.mjs";
10
10
  import { collectReportSummary } from "./report-stats.mjs";
11
11
  import { mergeTestRunReportDumps } from "./test-runner/reporting/merge-report.mjs";
12
+ import { collectTestRunReportMetrics } from "./test-runner/reporting/metrics.mjs";
12
13
  import { ReportActionDump } from "./types.mjs";
13
14
  import { getReportTpl, getVersion, reportHTMLContent } from "./utils.mjs";
14
15
  import { calculateTestRunHealth, classifyTestRunCase } from "./test-run-health.mjs";
@@ -228,14 +229,21 @@ class ReportMergingTool {
228
229
  appendFileSync(outputFilePath, reportHtmlStr);
229
230
  }
230
231
  if (hasRunnerDump) {
231
- const summary = collectReportSummary({
232
- executions: dedupeExecutionsKeepLatest(agentReports.flatMap((report)=>report.executions))
232
+ const executions = dedupeExecutionsKeepLatest(agentReports.flatMap((report)=>report.executions));
233
+ const metrics = collectTestRunReportMetrics({
234
+ executions
233
235
  });
234
- appendFileSync(outputFilePath, generateTestRunReportScriptTag(mergeTestRunReportDumps(runnerSources, {
235
- modelCallCount: summary.timing.modelCallCount,
236
- modelTimeMs: summary.timing.modelCallTimeMs,
237
- ...summary.tokens
238
- }, uuid())));
236
+ const executionMetrics = Object.fromEntries(executions.flatMap((execution)=>execution.id ? [
237
+ [
238
+ execution.id,
239
+ collectTestRunReportMetrics({
240
+ executions: [
241
+ execution
242
+ ]
243
+ })
244
+ ]
245
+ ] : []));
246
+ appendFileSync(outputFilePath, generateTestRunReportScriptTag(mergeTestRunReportDumps(runnerSources, metrics, uuid(), executionMetrics)));
239
247
  }
240
248
  const agentComment = mergedAgentReportComment(agentReports);
241
249
  if (agentComment) appendFileSync(outputFilePath, agentComment);
@@ -298,47 +306,78 @@ const uniqueTestRunReportSources = (sources)=>{
298
306
  };
299
307
  const prepareTestRunReportSources = (sources, loadedDumps)=>{
300
308
  const prepared = [];
309
+ const diagnostics = [];
301
310
  const ownerByScopedExecution = new Map();
302
311
  const preparedByPath = new Map();
303
312
  for (const [sourceIndex, source] of uniqueTestRunReportSources(sources).entries()){
313
+ let baseDump;
314
+ let executions;
315
+ try {
316
+ if (source.dumpPath) {
317
+ const contents = loadedDumps?.get(source.dumpPath) ?? readFileSync(source.dumpPath, 'utf8');
318
+ if (contents instanceof Error) throw contents;
319
+ baseDump = ReportActionDump.fromSerializedString(contents);
320
+ executions = baseDump.executions;
321
+ } else {
322
+ if (!existsSync(source.sourcePath)) throw new Error(`Agent report does not exist: ${source.sourcePath}`);
323
+ const sourceVersion = peekReportSdkVersion(source.sourcePath);
324
+ const currentVersion = getVersion();
325
+ if (sourceVersion && currentVersion && sourceVersion !== currentVersion && !warnedMismatchedVersions.has(sourceVersion)) {
326
+ warnedMismatchedVersions.add(sourceVersion);
327
+ logMsg(`[@midscene/core] TestRunReportAssembler version mismatch: source report was written by @midscene/core@${sourceVersion} but the assembler is @midscene/core@${currentVersion}. Align the workspace package versions before generating the Midscene Test report.`);
328
+ }
329
+ ({ baseDump, executions } = collectDedupedExecutions(source.sourcePath));
330
+ }
331
+ } catch (error) {
332
+ diagnostics.push({
333
+ level: 'warning',
334
+ code: 'agent-source-unavailable',
335
+ scopeId: source.scopeId,
336
+ sourcePaths: [
337
+ source.sourcePath
338
+ ],
339
+ message: `Agent source could not be collected: ${String(error)}`
340
+ });
341
+ continue;
342
+ }
304
343
  const sourceKey = source.sourcePath;
305
344
  const shared = preparedByPath.get(sourceKey);
306
345
  if (shared) {
307
- if (source.dumpPath) {
308
- const snapshot = ReportActionDump.fromSerializedString(loadedDumps?.get(source.dumpPath) ?? readFileSync(source.dumpPath, 'utf8'));
309
- shared.dump.executions = dedupeExecutionsKeepLatest([
310
- ...shared.dump.executions,
311
- ...snapshot.executions
312
- ]);
313
- shared.executionIds.splice(0, shared.executionIds.length, ...shared.dump.executions.flatMap((execution)=>execution.id ? [
314
- execution.id
315
- ] : []));
316
- }
317
- for (const executionId of shared.executionIds){
346
+ if (source.dumpPath) shared.dump.executions = dedupeExecutionsKeepLatest([
347
+ ...shared.dump.executions,
348
+ ...baseDump.executions
349
+ ]);
350
+ const scoped = prepared.find((item)=>item.reportId === shared.reportId && item.scopeId === source.scopeId);
351
+ const executionIds = [
352
+ ...new Set([
353
+ ...scoped?.executionIds ?? [],
354
+ ...executions.flatMap((execution)=>execution.id ? [
355
+ execution.id
356
+ ] : [])
357
+ ])
358
+ ];
359
+ for (const executionId of executionIds){
318
360
  const key = `${source.scopeId}\u0000${executionId}`;
319
361
  const owner = ownerByScopedExecution.get(key);
320
362
  if (owner && owner !== shared.reportId) throw new Error(`Agent execution ${executionId} is present in multiple reports for test scope ${source.scopeId}: ${owner}, ${shared.reportId}`);
321
363
  ownerByScopedExecution.set(key, shared.reportId);
322
364
  }
323
- prepared.push({
365
+ if (scoped) {
366
+ scoped.executionIds = executionIds;
367
+ const partial = [
368
+ scoped.collection,
369
+ source.collection
370
+ ].find((collection)=>collection?.status === 'partial');
371
+ scoped.collection = partial ?? source.collection ?? scoped.collection;
372
+ } else prepared.push({
324
373
  ...shared,
325
- scopeId: source.scopeId
374
+ scopeId: source.scopeId,
375
+ executionIds,
376
+ collection: source.collection
326
377
  });
327
378
  continue;
328
379
  }
329
- if (!source.dumpPath && !existsSync(source.sourcePath)) throw new Error(`Agent report does not exist: ${source.sourcePath}`);
330
- const sourceVersion = source.dumpPath ? void 0 : peekReportSdkVersion(source.sourcePath);
331
- const currentVersion = getVersion();
332
- if (sourceVersion && currentVersion && sourceVersion !== currentVersion && !warnedMismatchedVersions.has(sourceVersion)) {
333
- warnedMismatchedVersions.add(sourceVersion);
334
- logMsg(`[@midscene/core] TestRunReportAssembler version mismatch: source report was written by @midscene/core@${sourceVersion} but the assembler is @midscene/core@${currentVersion}. Align the workspace package versions before generating the Midscene Test report.`);
335
- }
336
380
  const reportId = `runner-report-${sourceIndex + 1}`;
337
- const snapshot = source.dumpPath ? ReportActionDump.fromSerializedString(loadedDumps?.get(source.dumpPath) ?? readFileSync(source.dumpPath, 'utf8')) : void 0;
338
- const { baseDump, executions } = snapshot ? {
339
- baseDump: snapshot,
340
- executions: snapshot.executions
341
- } : collectDedupedExecutions(source.sourcePath);
342
381
  const executionIds = [];
343
382
  for (const execution of executions){
344
383
  if (!execution.id) continue;
@@ -361,6 +400,7 @@ const prepareTestRunReportSources = (sources, loadedDumps)=>{
361
400
  scopeId: source.scopeId,
362
401
  sourcePath: source.sourcePath,
363
402
  executionIds,
403
+ collection: source.collection,
364
404
  dump,
365
405
  directoryMode: !!source.dumpPath || isDirectoryModeReport(source.sourcePath),
366
406
  ...source.dumpPath ? {
@@ -370,17 +410,43 @@ const prepareTestRunReportSources = (sources, loadedDumps)=>{
370
410
  prepared.push(preparedSource);
371
411
  preparedByPath.set(sourceKey, preparedSource);
372
412
  }
373
- const summary = collectReportSummary({
374
- executions: dedupeExecutionsKeepLatest([
375
- ...preparedByPath.values()
376
- ].flatMap((source)=>source.dump.executions))
413
+ const executions = dedupeExecutionsKeepLatest([
414
+ ...preparedByPath.values()
415
+ ].flatMap((source)=>source.dump.executions));
416
+ const metrics = collectTestRunReportMetrics({
417
+ executions
377
418
  });
419
+ const executionMetrics = Object.fromEntries(executions.flatMap((execution)=>execution.id ? [
420
+ [
421
+ execution.id,
422
+ collectTestRunReportMetrics({
423
+ executions: [
424
+ execution
425
+ ]
426
+ })
427
+ ]
428
+ ] : []));
378
429
  return {
379
430
  sources: prepared,
431
+ diagnostics,
432
+ capturedMetrics: metrics,
433
+ executionMetrics,
380
434
  metrics: {
381
- modelCallCount: summary.timing.modelCallCount,
382
- modelTimeMs: summary.timing.modelCallTimeMs,
383
- ...summary.tokens
435
+ ...metrics,
436
+ collection: {
437
+ ...metrics.collection,
438
+ fields: Object.fromEntries(Object.entries(metrics.collection.fields).map(([field, status])=>[
439
+ field,
440
+ diagnostics.length ? 0 === prepared.length ? 'unknown' : 'complete' === status ? 'partial' : status : status
441
+ ])),
442
+ status: diagnostics.length ? prepared.length ? 'partial' : 'unknown' : metrics.collection.status,
443
+ expectedExecutionCount: 0,
444
+ capturedExecutionCount: 0,
445
+ reasons: [
446
+ ...metrics.collection.reasons,
447
+ ...diagnostics.map((diagnostic)=>diagnostic.message)
448
+ ]
449
+ }
384
450
  }
385
451
  };
386
452
  };
@@ -389,12 +455,19 @@ class TestRunReportAssembler {
389
455
  validateTestRunReportFileName(options.reportFileName);
390
456
  const loaded = new Map();
391
457
  await Promise.all(options.sources.map(async (source)=>{
392
- if (source.dumpPath) loaded.set(source.dumpPath, await readFile(source.dumpPath, 'utf8'));
458
+ if (source.dumpPath) try {
459
+ loaded.set(source.dumpPath, await readFile(source.dumpPath, 'utf8'));
460
+ } catch (error) {
461
+ loaded.set(source.dumpPath, error instanceof Error ? error : new Error(String(error)));
462
+ }
393
463
  }));
394
464
  const prepared = prepareTestRunReportSources(options.sources, loaded);
395
465
  const dump = options.buildRunnerDump({
396
466
  sources: prepared.sources,
397
- metrics: prepared.metrics
467
+ metrics: prepared.metrics,
468
+ capturedMetrics: prepared.capturedMetrics,
469
+ executionMetrics: prepared.executionMetrics,
470
+ diagnostics: prepared.diagnostics
398
471
  });
399
472
  if ('test-runner' !== dump.kind || 1 !== dump.schemaVersion) throw new Error('Invalid Runner report dump');
400
473
  const directoryMode = prepared.sources.some((source)=>source.directoryMode);
@@ -482,13 +555,17 @@ class TestRunReportAssembler {
482
555
  });
483
556
  const prepared = prepareTestRunReportSources(options.sources);
484
557
  const index = {
485
- sources: prepared.sources.map(({ reportId, scopeId, sourcePath, executionIds })=>({
558
+ sources: prepared.sources.map(({ reportId, scopeId, sourcePath, executionIds, collection })=>({
486
559
  reportId,
487
560
  scopeId,
488
561
  sourcePath,
489
- executionIds
562
+ executionIds,
563
+ collection
490
564
  })),
491
- metrics: prepared.metrics
565
+ metrics: prepared.metrics,
566
+ capturedMetrics: prepared.capturedMetrics,
567
+ executionMetrics: prepared.executionMetrics,
568
+ diagnostics: prepared.diagnostics
492
569
  };
493
570
  const runnerDump = options.buildRunnerDump(index);
494
571
  if (1 !== runnerDump.schemaVersion || 'test-runner' !== runnerDump.kind) throw new Error('buildRunnerDump must return a Midscene Test report dump with schemaVersion 1 and kind "test-runner".');
@@ -1 +1 @@
1
- {"version":3,"file":"report.mjs","sources":["../../src/report.ts"],"sourcesContent":["import {\n appendFileSync,\n copyFileSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n readdirSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\nimport * as fsAsync from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { getMidsceneRunSubDir } from '@midscene/shared/common';\nimport { antiEscapeScriptTag, logMsg, uuid } from '@midscene/shared/utils';\nimport { getReportFileName } from './agent/report-file-name';\nimport {\n DATA_SCREENSHOT_MODE_ATTR,\n extractAllDumpScriptsSync,\n extractLastDumpScriptSync,\n extractTestRunReportDumpSync,\n generateAgentReportComment,\n getBaseUrlFixScript,\n generateTestRunReportScriptTag as runnerDumpScript,\n streamDumpScriptsSync,\n streamImageScriptsToFile,\n} from './dump/html-utils';\nimport {\n imageRefFileExtension,\n normalizeStoredImageRef,\n} from './dump/image-reference';\nimport {\n parseBase64ImageDataUrl,\n resolveImageSource,\n} from './dump/screenshot-store';\nimport { collectReportSummary } from './report-stats';\nimport type {\n AssembleTestRunReportOptions,\n IndexedTestRunReportSource,\n TestRunReportMetrics,\n TestRunReportSource,\n TestRunReportSourceIndex,\n} from './test-run-report';\nimport {\n type MergeTestRunReportSource,\n mergeTestRunReportDumps,\n} from './test-runner/reporting/merge-report';\nimport {\n type ExecutionDump,\n type IExecutionDump,\n ReportActionDump,\n type ScreenshotMode,\n} from './types';\nimport type { ReportFileWithAttributes } from './types';\nimport { getReportTpl, getVersion, reportHTMLContent } from './utils';\n\nexport {\n calculateTestRunHealth,\n classifyTestRunCase,\n} from './test-run-health';\n\n/**\n * Read the screenshot storage mode a report declared at generation time.\n *\n * Reports written by current versions stamp `data-screenshot-mode` onto every\n * dump script tag, so we only need to peek at the first real dump script (the\n * template's bundled JS also references the dump type string, hence the\n * `data-group-id` filter) and can stop streaming immediately.\n *\n * Returns undefined for legacy reports that predate the attribute or for\n * unreadable files, letting the caller fall back to a filesystem heuristic.\n */\nconst screenshotModeAttrRegExp = new RegExp(\n `${DATA_SCREENSHOT_MODE_ATTR}=\"(inline|directory)\"`,\n);\n\nfunction readDeclaredScreenshotMode(\n reportFilePath: string,\n): ScreenshotMode | undefined {\n let mode: ScreenshotMode | undefined;\n try {\n streamDumpScriptsSync(reportFilePath, ({ openTag }) => {\n // Skip false matches from the template's bundled JS code.\n if (!openTag.includes('data-group-id')) return false;\n const match = openTag.match(screenshotModeAttrRegExp);\n mode = match?.[1] as ScreenshotMode | undefined;\n return true; // the first real dump script decides the mode\n });\n } catch {\n // Unreadable / non-existent file — let the caller fall back.\n }\n return mode;\n}\n\n/**\n * Check if a report is in directory mode (html-and-external-assets).\n * Directory mode reports: {name}/index.html + {name}/screenshots/\n *\n * The mode is read from the report's own `data-screenshot-mode` metadata, which\n * is authoritative regardless of whether the run happened to capture any\n * screenshots. For legacy reports without the attribute we fall back to the old\n * filesystem heuristic (an `index.html` that has a sibling `screenshots/` dir).\n */\nexport function isDirectoryModeReport(reportFilePath: string): boolean {\n // Directory-mode reports are always written as `{name}/index.html`, so any\n // other filename is inline. Short-circuit before touching the file so the\n // common inline case (`{name}.html`) costs nothing.\n if (path.basename(reportFilePath) !== 'index.html') return false;\n\n const declared = readDeclaredScreenshotMode(reportFilePath);\n if (declared) return declared === 'directory';\n\n // Legacy fallback for reports generated before screenshotMode was embedded.\n return existsSync(path.join(path.dirname(reportFilePath), 'screenshots'));\n}\n\n/**\n * Whether a report lives in its own dedicated directory (`{name}/index.html`)\n * rather than being a single standalone file (`{name}.html`).\n *\n * This is a structural fact about *where the report file sits*, independent of\n * how it stores screenshots: a directory report can keep screenshots external\n * (a `screenshots/` sibling) OR inline them into `index.html`. Deletion needs\n * this — not the screenshot mode — to decide whether to remove the whole\n * directory or just unlink a file, so that an inline-screenshot report nested in\n * its own folder still has the folder removed instead of being orphaned.\n */\nfunction isDirectoryBasedReport(reportFilePath: string): boolean {\n return path.basename(reportFilePath) === 'index.html';\n}\n\n/**\n * Remove a complete report artifact from disk.\n *\n * Standalone reports own only their HTML file, while directory-based reports\n * own the directory containing `index.html`. Callers must decide whether they\n * own the source artifact and should only invoke this after its replacement\n * has been produced successfully.\n *\n * @param reportFilePath Path to the standalone report or directory report's\n * `index.html` entry point.\n * @throws When the owned report artifact cannot be removed.\n */\nexport function removeReportArtifact(reportFilePath: string): void {\n if (isDirectoryBasedReport(reportFilePath)) {\n rmSync(path.dirname(reportFilePath), { recursive: true, force: true });\n return;\n }\n unlinkSync(reportFilePath);\n}\n\n/**\n * Deduplicate executions by stable id, keeping only the last occurrence.\n * Old-format executions without id are always preserved.\n */\nexport function dedupeExecutionsKeepLatest<T extends Pick<ExecutionDump, 'id'>>(\n executions: T[],\n): T[] {\n let noIdCounter = 0;\n const deduped = new Map<string, T>();\n for (const exec of executions) {\n const key = exec.id || `__no_id_${noIdCounter++}`;\n deduped.set(key, exec);\n }\n return Array.from(deduped.values());\n}\n/**\n * Peek at the first `sdkVersion` field embedded in a midscene_web_dump\n * script tag inside the given report file. Returns undefined if no\n * recognizable tag or sdkVersion is present.\n */\nfunction peekReportSdkVersion(reportFilePath: string): string | undefined {\n try {\n const dump = extractLastDumpScriptSync(reportFilePath);\n if (!dump) return undefined;\n const match = dump.match(/\"sdkVersion\"\\s*:\\s*\"([^\"]+)\"/);\n return match?.[1];\n } catch {\n return undefined;\n }\n}\n\nconst warnedMismatchedVersions = new Set<string>();\n\nfunction tryParseAgentReportDump(dumpString: string): ReportActionDump | null {\n const trimmed = dumpString.trimStart();\n if (!trimmed.startsWith('{') || !trimmed.includes('\"executions\"')) {\n return null;\n }\n\n try {\n return ReportActionDump.fromSerializedString(trimmed);\n } catch {\n return null;\n }\n}\n\nfunction mergedAgentReportComment(reports: ReportActionDump[]): string {\n if (reports.length === 0) {\n return '';\n }\n if (reports.length === 1) {\n return generateAgentReportComment(reports[0]);\n }\n\n const deviceTypes = Array.from(\n new Set(reports.map((report) => report.deviceType).filter(Boolean)),\n );\n const mergedReport = new ReportActionDump({\n sdkVersion: reports[0].sdkVersion || getVersion(),\n groupName: 'Merged Midscene Report',\n groupDescription: 'Agent-readable summary for merged report HTML',\n modelBriefs: reports.flatMap((report) => report.modelBriefs ?? []),\n deviceType: deviceTypes.length === 1 ? deviceTypes[0] : 'mixed',\n executions: dedupeExecutionsKeepLatest(\n reports.flatMap((report) => report.executions ?? []),\n ),\n });\n return generateAgentReportComment(mergedReport);\n}\n\nexport class ReportMergingTool {\n private reportInfos: ReportFileWithAttributes[] = [];\n\n private createEmptyDumpString(groupName: string, groupDescription?: string) {\n return new ReportActionDump({\n sdkVersion: '',\n groupName,\n groupDescription,\n modelBriefs: [],\n executions: [],\n }).serialize();\n }\n\n public append(reportInfo: ReportFileWithAttributes) {\n if (\n !reportInfo.reportFilePath &&\n reportInfo.reportAttributes.testStatus !== 'skipped'\n ) {\n throw new Error(\n 'reportFilePath is required unless reportAttributes.testStatus is \"skipped\"',\n );\n }\n\n if (reportInfo.reportFilePath) {\n const sourceVersion = peekReportSdkVersion(reportInfo.reportFilePath);\n const currentVersion = getVersion();\n if (\n sourceVersion &&\n currentVersion &&\n sourceVersion !== currentVersion &&\n !warnedMismatchedVersions.has(sourceVersion)\n ) {\n warnedMismatchedVersions.add(sourceVersion);\n logMsg(\n `[@midscene/core] ReportMergingTool version mismatch: source report was written by @midscene/core@${sourceVersion} but the merger is @midscene/core@${currentVersion}. This commonly means @midscene/core and the device package (e.g. @midscene/android) resolve to different versions in node_modules. Merged output may silently drop intermediate steps. Align the versions and reinstall (rm -rf node_modules package-lock.json && npm install).`,\n );\n }\n }\n this.reportInfos.push(reportInfo);\n }\n public clear() {\n this.reportInfos = [];\n }\n\n /**\n * Merge multiple dump script contents (from the same source report)\n * into a single serialized ReportActionDump string.\n * If there's only one dump, return it as-is. If multiple, merge\n * all executions into the first dump's group structure.\n */\n private mergeDumpScripts(contents: string[]): string {\n const unescaped = contents\n .map((c) => antiEscapeScriptTag(c))\n .filter((c) => c.length > 0);\n if (unescaped.length === 0) return '';\n if (unescaped.length === 1) return unescaped[0];\n\n // Parse all dumps and collect executions, deduplicating by id (keep last).\n // Only executions with a stable id are deduped; old-format entries without\n // id are always kept (they may be distinct despite sharing the same name).\n const base = ReportActionDump.fromSerializedString(unescaped[0]);\n const allExecutions = [...base.executions];\n for (let i = 1; i < unescaped.length; i++) {\n const other = ReportActionDump.fromSerializedString(unescaped[i]);\n allExecutions.push(...other.executions);\n }\n base.executions = dedupeExecutionsKeepLatest(allExecutions);\n return base.serialize();\n }\n\n public mergeReports(\n reportFileName: 'AUTO' | string = 'AUTO',\n opts?: {\n rmOriginalReports?: boolean;\n overwrite?: boolean;\n outputDir?: string;\n },\n ): string | null {\n const {\n rmOriginalReports = false,\n overwrite = false,\n outputDir,\n } = opts ?? {};\n\n if (this.reportInfos.length === 0) {\n logMsg('No reports to merge');\n return null;\n }\n\n const runnerDumps = this.reportInfos.map((info) =>\n info.reportFilePath\n ? extractTestRunReportDumpSync(info.reportFilePath)\n : undefined,\n );\n const hasRunnerDump = runnerDumps.some(Boolean);\n\n const targetDir = outputDir\n ? path.resolve(outputDir)\n : getMidsceneRunSubDir('report');\n if (outputDir) {\n mkdirSync(targetDir, { recursive: true });\n }\n\n // Resolve each report's screenshot mode exactly once. isDirectoryModeReport\n // reads the file to find the authoritative metadata, so recomputing it for\n // both the output-path decision and the per-report merge loop would re-scan\n // every report twice.\n const isDirModeByIndex = this.reportInfos.map((info) =>\n Boolean(\n info.reportFilePath && isDirectoryModeReport(info.reportFilePath),\n ),\n );\n const hasDirectoryModeReport = isDirModeByIndex.some(Boolean);\n\n const resolvedName =\n reportFileName === 'AUTO'\n ? getReportFileName('merged-report')\n : reportFileName;\n\n // Directory mode: output as {name}/index.html to keep relative paths working\n // Inline mode: output as {name}.html (single file)\n const outputFilePath = hasDirectoryModeReport\n ? path.resolve(targetDir, resolvedName, 'index.html')\n : path.resolve(targetDir, `${resolvedName}.html`);\n\n if (reportFileName !== 'AUTO' && existsSync(outputFilePath)) {\n if (!overwrite) {\n throw new Error(\n `Report file already exists: ${outputFilePath}\\nSet overwrite to true to overwrite this file.`,\n );\n }\n if (hasDirectoryModeReport) {\n rmSync(path.dirname(outputFilePath), { recursive: true, force: true });\n } else {\n unlinkSync(outputFilePath);\n }\n }\n\n if (hasDirectoryModeReport) {\n mkdirSync(path.dirname(outputFilePath), { recursive: true });\n }\n\n logMsg(\n `Start merging ${this.reportInfos.length} reports...\\nCreating template file...`,\n );\n\n try {\n // Write template without closing </html> tag so we can append\n // dump scripts before it. The closing tag is added at the end.\n const htmlEndTag = '</html>';\n const tpl = getReportTpl();\n const htmlEndIdx = tpl.lastIndexOf(htmlEndTag);\n const tplWithoutClose =\n htmlEndIdx !== -1 ? tpl.slice(0, htmlEndIdx) : tpl;\n appendFileSync(outputFilePath, tplWithoutClose);\n\n // For directory-mode output, inject base URL fix script\n if (hasDirectoryModeReport) {\n appendFileSync(outputFilePath, getBaseUrlFixScript());\n }\n\n const agentReports: ReportActionDump[] = [];\n const runnerSources: MergeTestRunReportSource[] = [];\n const writtenInlineImageIds = new Set<string>();\n\n // Process all reports one by one\n for (let i = 0; i < this.reportInfos.length; i++) {\n const reportInfo = this.reportInfos[i];\n logMsg(`Processing report ${i + 1}/${this.reportInfos.length}`);\n\n const { reportAttributes } = reportInfo;\n let dumpString = this.createEmptyDumpString(\n reportAttributes.testTitle,\n reportAttributes.testDescription,\n );\n let mergedGroupId = `merged-group-${i}`;\n\n if (reportInfo.reportFilePath) {\n if (isDirModeByIndex[i]) {\n // Directory mode: copy external screenshot files. A directory-mode\n // report can legitimately have no screenshots/ dir (a run that\n // captured nothing), so only copy when the source dir exists.\n const reportDir = path.dirname(reportInfo.reportFilePath);\n const screenshotsDir = path.join(reportDir, 'screenshots');\n if (existsSync(screenshotsDir)) {\n const mergedScreenshotsDir = path.join(\n path.dirname(outputFilePath),\n 'screenshots',\n );\n mkdirSync(mergedScreenshotsDir, { recursive: true });\n for (const file of readdirSync(screenshotsDir)) {\n const src = path.join(screenshotsDir, file);\n const dest = path.join(mergedScreenshotsDir, file);\n copyFileSync(src, dest);\n }\n }\n } else {\n // Inline mode: stream image scripts to output file\n streamImageScriptsToFile(\n reportInfo.reportFilePath,\n outputFilePath,\n writtenInlineImageIds,\n );\n }\n\n // Extract all dump scripts from the source report.\n // After the per-execution append refactor, a single source report\n // may contain multiple <script type=\"midscene_web_dump\"> tags\n // (one per execution). We merge them into a single ReportActionDump.\n // Filter by data-group-id to exclude false matches from the template's\n // bundled JS code, which also references the midscene_web_dump type string.\n const allDumps = extractAllDumpScriptsSync(\n reportInfo.reportFilePath,\n ).filter((d) => d.openTag.includes('data-group-id'));\n const groupIdMatch = allDumps[0]?.openTag.match(\n /data-group-id=\"([^\"]+)\"/,\n );\n if (groupIdMatch && !hasRunnerDump) {\n mergedGroupId = decodeURIComponent(groupIdMatch[1]);\n }\n const extractedDumpString =\n allDumps.length > 0\n ? this.mergeDumpScripts(allDumps.map((d) => d.content))\n : extractLastDumpScriptSync(reportInfo.reportFilePath);\n if (extractedDumpString) {\n dumpString = extractedDumpString;\n }\n }\n\n const agentReport = tryParseAgentReportDump(dumpString);\n if (agentReport) {\n agentReports.push(agentReport);\n }\n if (hasRunnerDump)\n runnerSources.push({\n reportId: mergedGroupId,\n sourcePath: reportInfo.reportFilePath ?? '<skipped-agent-report>',\n attributes: reportAttributes,\n dump: runnerDumps[i],\n timing: agentReport\n ? agentReportTiming(agentReport, reportAttributes.testDuration)\n : undefined,\n });\n\n const reportHtmlStr = `${reportHTMLContent(\n {\n dumpString,\n attributes: {\n 'data-group-id': mergedGroupId,\n ...(hasRunnerDump ? { 'data-report-id': mergedGroupId } : {}),\n [DATA_SCREENSHOT_MODE_ATTR]: hasDirectoryModeReport\n ? 'directory'\n : 'inline',\n playwright_test_duration: reportAttributes.testDuration,\n playwright_test_status: reportAttributes.testStatus,\n playwright_test_title: reportAttributes.testTitle,\n playwright_test_id: reportAttributes.testId,\n playwright_test_description: reportAttributes.testDescription,\n is_merged: true,\n },\n },\n undefined,\n undefined,\n false,\n )}\\n`;\n\n appendFileSync(outputFilePath, reportHtmlStr);\n }\n\n if (hasRunnerDump) {\n const summary = collectReportSummary({\n executions: dedupeExecutionsKeepLatest(\n agentReports.flatMap((report) => report.executions),\n ),\n });\n appendFileSync(\n outputFilePath,\n runnerDumpScript(\n mergeTestRunReportDumps(\n runnerSources,\n {\n modelCallCount: summary.timing.modelCallCount,\n modelTimeMs: summary.timing.modelCallTimeMs,\n ...summary.tokens,\n },\n uuid(),\n ),\n ),\n );\n }\n\n const agentComment = mergedAgentReportComment(agentReports);\n if (agentComment) {\n appendFileSync(outputFilePath, agentComment);\n }\n\n // Close the HTML document\n appendFileSync(outputFilePath, `${htmlEndTag}\\n`);\n\n logMsg(`Successfully merged new report: ${outputFilePath}`);\n\n // Remove original reports if needed\n if (rmOriginalReports) {\n let removedReportCount = 0;\n let reportCountWithFilePath = 0;\n for (const info of this.reportInfos) {\n if (!info.reportFilePath) continue;\n reportCountWithFilePath += 1;\n try {\n removeReportArtifact(info.reportFilePath);\n removedReportCount += 1;\n } catch (error) {\n logMsg(`Error deleting report ${info.reportFilePath}: ${error}`);\n }\n }\n logMsg(\n `Removed ${removedReportCount}/${reportCountWithFilePath} original reports`,\n );\n }\n return outputFilePath;\n } catch (error) {\n logMsg(`Error in mergeReports: ${error}`);\n throw error;\n }\n }\n}\n\nfunction agentReportTiming(\n report: ReportActionDump,\n durationMs: number,\n): MergeTestRunReportSource['timing'] {\n const timing = collectReportSummary(report).timing;\n const executionTimes = report.executions\n .map((execution) => execution.logTime)\n .filter(\n (value): value is number =>\n typeof value === 'number' && Number.isFinite(value),\n );\n const started =\n timing.wallTimeStart ??\n (executionTimes.length ? Math.min(...executionTimes) : undefined);\n if (started === undefined) return undefined;\n const ended =\n timing.wallTimeEnd ??\n Math.max(\n ...executionTimes,\n started + (Number.isFinite(durationMs) ? Math.max(0, durationMs) : 0),\n );\n return {\n startedAt: new Date(started).toISOString(),\n endedAt: new Date(ended).toISOString(),\n durationMs: Math.max(0, ended - started),\n };\n}\n\ninterface PreparedTestRunReportSource extends IndexedTestRunReportSource {\n dump: ReportActionDump;\n directoryMode: boolean;\n dumpPath?: string;\n}\n\nconst validateTestRunReportFileName = (fileName: string): void => {\n if (\n !fileName ||\n fileName === '.' ||\n fileName === '..' ||\n path.basename(fileName) !== fileName ||\n fileName.endsWith('.html')\n ) {\n throw new Error(\n `Midscene Test reportFileName must be one path segment without an extension: ${fileName}`,\n );\n }\n};\n\nconst uniqueTestRunReportSources = (\n sources: readonly TestRunReportSource[],\n): TestRunReportSource[] => {\n const unique = new Map<string, TestRunReportSource>();\n\n for (const source of sources) {\n const scopeId = source.scopeId.trim();\n const sourcePath = path.resolve(source.sourcePath);\n if (!scopeId) {\n throw new Error('Midscene Test report source scopeId must not be empty.');\n }\n\n unique.set(`${scopeId}\\u0000${source.dumpPath ?? sourcePath}`, {\n ...source,\n scopeId,\n sourcePath,\n });\n }\n\n return [...unique.values()];\n};\n\nconst prepareTestRunReportSources = (\n sources: readonly TestRunReportSource[],\n loadedDumps?: ReadonlyMap<string, string>,\n): {\n sources: PreparedTestRunReportSource[];\n metrics: TestRunReportMetrics;\n} => {\n const prepared: PreparedTestRunReportSource[] = [];\n const ownerByScopedExecution = new Map<string, string>();\n const preparedByPath = new Map<string, PreparedTestRunReportSource>();\n\n for (const [sourceIndex, source] of uniqueTestRunReportSources(\n sources,\n ).entries()) {\n // A borrowed Agent can serve several sequential test scopes. Reuse its\n // report group and metrics while indexing each scope's execution links.\n const sourceKey = source.sourcePath;\n const shared = preparedByPath.get(sourceKey);\n if (shared) {\n if (source.dumpPath) {\n const snapshot = ReportActionDump.fromSerializedString(\n loadedDumps?.get(source.dumpPath) ??\n readFileSync(source.dumpPath, 'utf8'),\n );\n shared.dump.executions = dedupeExecutionsKeepLatest([\n ...shared.dump.executions,\n ...snapshot.executions,\n ]);\n shared.executionIds.splice(\n 0,\n shared.executionIds.length,\n ...shared.dump.executions.flatMap((execution) =>\n execution.id ? [execution.id] : [],\n ),\n );\n }\n for (const executionId of shared.executionIds) {\n const key = `${source.scopeId}\\u0000${executionId}`;\n const owner = ownerByScopedExecution.get(key);\n if (owner && owner !== shared.reportId)\n throw new Error(\n `Agent execution ${executionId} is present in multiple reports for test scope ${source.scopeId}: ${owner}, ${shared.reportId}`,\n );\n ownerByScopedExecution.set(key, shared.reportId);\n }\n prepared.push({ ...shared, scopeId: source.scopeId });\n continue;\n }\n if (!source.dumpPath && !existsSync(source.sourcePath)) {\n throw new Error(`Agent report does not exist: ${source.sourcePath}`);\n }\n\n const sourceVersion = source.dumpPath\n ? undefined\n : peekReportSdkVersion(source.sourcePath);\n const currentVersion = getVersion();\n if (\n sourceVersion &&\n currentVersion &&\n sourceVersion !== currentVersion &&\n !warnedMismatchedVersions.has(sourceVersion)\n ) {\n warnedMismatchedVersions.add(sourceVersion);\n logMsg(\n `[@midscene/core] TestRunReportAssembler version mismatch: source report was written by @midscene/core@${sourceVersion} but the assembler is @midscene/core@${currentVersion}. Align the workspace package versions before generating the Midscene Test report.`,\n );\n }\n\n const reportId = `runner-report-${sourceIndex + 1}`;\n const snapshot = source.dumpPath\n ? ReportActionDump.fromSerializedString(\n loadedDumps?.get(source.dumpPath) ??\n readFileSync(source.dumpPath, 'utf8'),\n )\n : undefined;\n const { baseDump, executions } = snapshot\n ? { baseDump: snapshot, executions: snapshot.executions }\n : collectDedupedExecutions(source.sourcePath);\n const executionIds: string[] = [];\n for (const execution of executions) {\n if (!execution.id) continue;\n const scopedExecution = `${source.scopeId}\\u0000${execution.id}`;\n const previousOwner = ownerByScopedExecution.get(scopedExecution);\n if (previousOwner && previousOwner !== reportId) {\n throw new Error(\n `Agent execution ${execution.id} is present in multiple reports for test scope ${source.scopeId}: ${previousOwner}, ${reportId}`,\n );\n }\n ownerByScopedExecution.set(scopedExecution, reportId);\n executionIds.push(execution.id);\n }\n\n const dump = new ReportActionDump({\n sdkVersion: baseDump.sdkVersion,\n groupName: baseDump.groupName,\n groupDescription: baseDump.groupDescription,\n modelBriefs: baseDump.modelBriefs,\n deviceType: baseDump.deviceType,\n executions,\n });\n const preparedSource = {\n reportId,\n scopeId: source.scopeId,\n sourcePath: source.sourcePath,\n executionIds,\n dump,\n directoryMode:\n !!source.dumpPath || isDirectoryModeReport(source.sourcePath),\n ...(source.dumpPath ? { dumpPath: source.dumpPath } : {}),\n };\n prepared.push(preparedSource);\n preparedByPath.set(sourceKey, preparedSource);\n }\n\n // A legacy invocation can preserve a snapshot of an Agent also used by\n // native scopes. Count stable executions once across both paths.\n const summary = collectReportSummary({\n executions: dedupeExecutionsKeepLatest(\n [...preparedByPath.values()].flatMap((source) => source.dump.executions),\n ),\n });\n return {\n sources: prepared,\n metrics: {\n modelCallCount: summary.timing.modelCallCount,\n modelTimeMs: summary.timing.modelCallTimeMs,\n ...summary.tokens,\n },\n };\n};\n\n/**\n * Build a self-contained Midscene Test report while preserving the existing\n * Agent dump format consumed by the Report App.\n *\n * Test hierarchy and status live in `midscene_test_run_dump`; Agent reports\n * remain independent `midscene_web_dump` groups addressed by `data-report-id`.\n */\nexport class TestRunReportAssembler {\n /** Runtime publisher: current Agent snapshots avoid parsing HTML or copying unused images. */\n public async assembleAsync(\n options: AssembleTestRunReportOptions,\n ): Promise<string> {\n validateTestRunReportFileName(options.reportFileName);\n const loaded = new Map<string, string>();\n await Promise.all(\n options.sources.map(async (source) => {\n if (source.dumpPath)\n loaded.set(\n source.dumpPath,\n await fsAsync.readFile(source.dumpPath, 'utf8'),\n );\n }),\n );\n const prepared = prepareTestRunReportSources(options.sources, loaded);\n const dump = options.buildRunnerDump({\n sources: prepared.sources,\n metrics: prepared.metrics,\n });\n if (dump.kind !== 'test-runner' || dump.schemaVersion !== 1)\n throw new Error('Invalid Runner report dump');\n const directoryMode = prepared.sources.some(\n (source) => source.directoryMode,\n );\n const outputDir = path.resolve(options.outputDir);\n await fsAsync.mkdir(outputDir, { recursive: true });\n const artifact = path.join(outputDir, options.reportFileName);\n const finalPath = directoryMode\n ? path.join(artifact, 'index.html')\n : `${artifact}.html`;\n if (\n !options.overwrite &&\n (existsSync(artifact) || existsSync(`${artifact}.html`))\n )\n throw new Error(`Report artifact already exists: ${artifact}`);\n const temporary = await fsAsync.mkdtemp(\n path.join(outputDir, '.test-run-report-'),\n );\n const htmlPath = path.join(temporary, 'index.html');\n try {\n const parts = [\n getReportTpl(),\n directoryMode ? getBaseUrlFixScript() : '',\n ];\n const imageIds = new Set<string>();\n const reports: ReportActionDump[] = [];\n for (const source of new Map(\n prepared.sources.map((source) => [source.reportId, source]),\n ).values()) {\n const serialized = source.dump.serialize();\n if (source.dumpPath) {\n const refs = new Map<\n string,\n ReturnType<typeof normalizeStoredImageRef> & {}\n >();\n JSON.parse(serialized, (_key, value) => {\n const ref = normalizeStoredImageRef(value);\n if (ref) refs.set(ref.id, ref);\n return value;\n });\n if (refs.size)\n await fsAsync.mkdir(path.join(temporary, 'screenshots'), {\n recursive: true,\n });\n for (const ref of refs.values()) {\n if (imageIds.has(ref.id)) continue;\n if (ref.storage !== 'file' || !ref.path)\n throw new Error(`Snapshot image ${ref.id} has no file source`);\n await fsAsync.copyFile(\n path.resolve(path.dirname(source.dumpPath), ref.path),\n path.join(\n temporary,\n 'screenshots',\n `${ref.id}.${imageRefFileExtension(ref)}`,\n ),\n );\n imageIds.add(ref.id);\n }\n } else {\n // An explicit external provider may still return a finalized HTML artifact.\n // This is a public provider contract, not a second execution/serialization schema.\n if (source.directoryMode) {\n const images = path.join(\n path.dirname(source.sourcePath),\n 'screenshots',\n );\n if (existsSync(images))\n await fsAsync.cp(images, path.join(temporary, 'screenshots'), {\n recursive: true,\n });\n } else {\n const html = await fsAsync.readFile(source.sourcePath, 'utf8');\n for (const match of html.matchAll(\n /<script\\b([^>]*)>[\\s\\S]*?<\\/script>/g,\n )) {\n if (/(?:^|\\s)type=[\"']midscene-image[\"']/.test(match[1]))\n parts.push(match[0]);\n }\n }\n }\n reports.push(source.dump);\n parts.push(\n reportHTMLContent(\n {\n dumpString: serialized,\n attributes: {\n 'data-group-id': source.reportId,\n 'data-report-id': source.reportId,\n 'data-runner-scope-id': source.scopeId,\n [DATA_SCREENSHOT_MODE_ATTR]: directoryMode\n ? 'directory'\n : 'inline',\n },\n },\n undefined,\n undefined,\n false,\n ),\n );\n }\n parts.push(runnerDumpScript(dump), mergedAgentReportComment(reports));\n await fsAsync.writeFile(htmlPath, parts.join('\\n'));\n if (options.overwrite) {\n await fsAsync.rm(artifact, { recursive: true, force: true });\n await fsAsync.rm(`${artifact}.html`, { force: true });\n }\n await fsAsync.rename(\n directoryMode ? temporary : htmlPath,\n directoryMode ? artifact : finalPath,\n );\n return finalPath;\n } finally {\n await fsAsync.rm(temporary, { recursive: true, force: true });\n }\n }\n\n public assemble(options: AssembleTestRunReportOptions): string {\n validateTestRunReportFileName(options.reportFileName);\n const outputDir = path.resolve(options.outputDir);\n mkdirSync(outputDir, { recursive: true });\n\n const prepared = prepareTestRunReportSources(options.sources);\n const index: TestRunReportSourceIndex = {\n sources: prepared.sources.map(\n ({ reportId, scopeId, sourcePath, executionIds }) => ({\n reportId,\n scopeId,\n sourcePath,\n executionIds,\n }),\n ),\n metrics: prepared.metrics,\n };\n const runnerDump = options.buildRunnerDump(index);\n if (runnerDump.schemaVersion !== 1 || runnerDump.kind !== 'test-runner') {\n throw new Error(\n 'buildRunnerDump must return a Midscene Test report dump with schemaVersion 1 and kind \"test-runner\".',\n );\n }\n // Validate serializability before creating any output artifact.\n JSON.stringify(runnerDump);\n\n const directoryMode = prepared.sources.some(\n (source) => source.directoryMode,\n );\n const finalArtifactPath = path.join(outputDir, options.reportFileName);\n const directoryReportPath = path.join(finalArtifactPath, 'index.html');\n const standaloneReportPath = `${finalArtifactPath}.html`;\n const finalReportPath = directoryMode\n ? directoryReportPath\n : standaloneReportPath;\n const existingArtifacts = [finalArtifactPath, standaloneReportPath].filter(\n existsSync,\n );\n if (existingArtifacts.length > 0 && !options.overwrite) {\n throw new Error(\n `Report artifact already exists: ${existingArtifacts[0]}\\nSet overwrite to true to overwrite this report.`,\n );\n }\n\n const temporaryRoot = mkdtempSync(\n path.join(outputDir, '.test-run-report-'),\n );\n const temporaryArtifactPath = path.join(\n temporaryRoot,\n options.reportFileName,\n );\n const temporaryReportPath = directoryMode\n ? path.join(temporaryArtifactPath, 'index.html')\n : `${temporaryArtifactPath}.html`;\n\n try {\n if (directoryMode) {\n mkdirSync(temporaryArtifactPath, { recursive: true });\n }\n\n const htmlEndTag = '</html>';\n const template = getReportTpl();\n const htmlEndIndex = template.lastIndexOf(htmlEndTag);\n appendFileSync(\n temporaryReportPath,\n htmlEndIndex === -1 ? template : template.slice(0, htmlEndIndex),\n );\n if (directoryMode) {\n appendFileSync(temporaryReportPath, getBaseUrlFixScript());\n }\n\n const agentReports: ReportActionDump[] = [];\n for (const source of new Map(\n prepared.sources.map((source) => [source.reportId, source]),\n ).values()) {\n if (source.directoryMode) {\n const screenshotsDir = path.join(\n path.dirname(source.sourcePath),\n 'screenshots',\n );\n if (existsSync(screenshotsDir)) {\n const targetScreenshotsDir = path.join(\n path.dirname(temporaryReportPath),\n 'screenshots',\n );\n mkdirSync(targetScreenshotsDir, { recursive: true });\n for (const file of readdirSync(screenshotsDir)) {\n copyFileSync(\n path.join(screenshotsDir, file),\n path.join(targetScreenshotsDir, file),\n );\n }\n }\n } else {\n streamImageScriptsToFile(source.sourcePath, temporaryReportPath);\n }\n\n agentReports.push(source.dump);\n appendFileSync(\n temporaryReportPath,\n `${reportHTMLContent(\n {\n dumpString: source.dump.serialize(),\n attributes: {\n 'data-group-id': source.reportId,\n 'data-report-id': source.reportId,\n 'data-runner-scope-id': source.scopeId,\n [DATA_SCREENSHOT_MODE_ATTR]: directoryMode\n ? 'directory'\n : 'inline',\n },\n },\n undefined,\n undefined,\n false,\n )}\\n`,\n );\n }\n\n appendFileSync(temporaryReportPath, runnerDumpScript(runnerDump));\n const agentComment = mergedAgentReportComment(agentReports);\n if (agentComment) {\n appendFileSync(temporaryReportPath, agentComment);\n }\n appendFileSync(temporaryReportPath, `${htmlEndTag}\\n`);\n\n if (existsSync(finalArtifactPath)) {\n rmSync(finalArtifactPath, { recursive: true, force: true });\n }\n if (existsSync(standaloneReportPath)) {\n unlinkSync(standaloneReportPath);\n }\n renameSync(\n directoryMode ? temporaryArtifactPath : temporaryReportPath,\n directoryMode ? finalArtifactPath : standaloneReportPath,\n );\n rmSync(temporaryRoot, { recursive: true, force: true });\n return finalReportPath;\n } catch (error) {\n rmSync(temporaryRoot, { recursive: true, force: true });\n throw error;\n }\n }\n}\n\nexport interface SplitReportHtmlOptions {\n htmlPath: string;\n outputDir: string;\n}\n\nexport interface SplitReportHtmlResult {\n executionJsonFiles: string[];\n screenshotFiles: string[];\n}\n\nexport interface CollectedReportExecutions {\n baseDump: ReportActionDump;\n executions: IExecutionDump[];\n}\n\n/**\n * Collect executions from a report HTML, deduplicating by stable id while\n * keeping only the latest occurrence. Old-format executions without id are\n * always preserved.\n */\nexport function collectDedupedExecutions(\n htmlPath: string,\n): CollectedReportExecutions {\n let baseDump: ReportActionDump | null = null;\n let executionSerial = 0;\n const latestSerialByExecutionId = new Map<string, number>();\n\n streamDumpScriptsSync(htmlPath, (dumpScript) => {\n if (!dumpScript.openTag.includes('data-group-id')) {\n return false;\n }\n const groupedDump = ReportActionDump.fromSerializedString(\n antiEscapeScriptTag(dumpScript.content),\n );\n for (const execution of groupedDump.executions) {\n executionSerial += 1;\n if (execution.id) {\n latestSerialByExecutionId.set(execution.id, executionSerial);\n }\n }\n return false;\n });\n\n const executions: IExecutionDump[] = [];\n executionSerial = 0;\n streamDumpScriptsSync(htmlPath, (dumpScript) => {\n if (!dumpScript.openTag.includes('data-group-id')) {\n return false;\n }\n\n const groupedDump = ReportActionDump.fromSerializedString(\n antiEscapeScriptTag(dumpScript.content),\n );\n if (!baseDump) {\n baseDump = groupedDump;\n }\n\n for (const execution of groupedDump.executions) {\n executionSerial += 1;\n if (\n execution.id &&\n latestSerialByExecutionId.get(execution.id) !== executionSerial\n ) {\n continue;\n }\n executions.push(execution);\n }\n\n return false;\n });\n\n if (!baseDump) {\n throw new Error(`No report dump scripts found in ${htmlPath}`);\n }\n\n return {\n baseDump,\n executions,\n };\n}\n\nfunction externalizeImagesInExecution(\n execution: IExecutionDump,\n opts: {\n htmlPath: string;\n screenshotsDir: string;\n writtenFiles: Set<string>;\n },\n): void {\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n visit(item);\n }\n return;\n }\n\n if (typeof node !== 'object' || node === null) return;\n\n const ref = normalizeStoredImageRef(node);\n if (ref) {\n const ext = imageRefFileExtension(ref);\n const fileName = `${ref.id}.${ext}`;\n const relativePath = `./screenshots/${fileName}`;\n const absolutePath = path.join(opts.screenshotsDir, fileName);\n\n if (!opts.writtenFiles.has(fileName)) {\n const resolved = resolveImageSource(ref, {\n reportPath: opts.htmlPath,\n });\n if (resolved.type === 'data-uri') {\n const { rawBase64 } = parseBase64ImageDataUrl(resolved.dataUri);\n writeFileSync(absolutePath, Buffer.from(rawBase64, 'base64'));\n } else {\n copyFileSync(resolved.filePath, absolutePath);\n }\n opts.writtenFiles.add(fileName);\n }\n\n ref.storage = 'file';\n ref.path = relativePath;\n return;\n }\n\n for (const value of Object.values(node)) {\n visit(value);\n }\n };\n\n visit(execution);\n}\n\n/**\n * Reverse parse a Midscene report HTML into per-execution JSON files and\n * externalized screenshots.\n */\nexport function splitReportHtmlByExecution(\n options: SplitReportHtmlOptions,\n): SplitReportHtmlResult {\n const { htmlPath, outputDir } = options;\n const screenshotsDir = path.join(outputDir, 'screenshots');\n\n mkdirSync(outputDir, { recursive: true });\n mkdirSync(screenshotsDir, { recursive: true });\n\n const executionJsonFiles: string[] = [];\n const writtenScreenshotFiles = new Set<string>();\n const { baseDump, executions } = collectDedupedExecutions(htmlPath);\n\n let fileIndex = 0;\n for (const execution of executions) {\n fileIndex += 1;\n externalizeImagesInExecution(execution, {\n htmlPath,\n screenshotsDir,\n writtenFiles: writtenScreenshotFiles,\n });\n const singleExecutionDump = new ReportActionDump({\n sdkVersion: baseDump.sdkVersion,\n groupName: baseDump.groupName,\n groupDescription: baseDump.groupDescription,\n modelBriefs: baseDump.modelBriefs,\n deviceType: baseDump.deviceType,\n executions: [execution],\n });\n\n const jsonFilePath = path.join(outputDir, `${fileIndex}.execution.json`);\n writeFileSync(jsonFilePath, singleExecutionDump.serialize(2), 'utf-8');\n executionJsonFiles.push(jsonFilePath);\n }\n\n return {\n executionJsonFiles,\n screenshotFiles: Array.from(writtenScreenshotFiles)\n .sort()\n .map((fileName) => path.join(screenshotsDir, fileName)),\n };\n}\n"],"names":["screenshotModeAttrRegExp","RegExp","DATA_SCREENSHOT_MODE_ATTR","readDeclaredScreenshotMode","reportFilePath","mode","streamDumpScriptsSync","openTag","match","isDirectoryModeReport","path","declared","existsSync","isDirectoryBasedReport","removeReportArtifact","rmSync","unlinkSync","dedupeExecutionsKeepLatest","executions","noIdCounter","deduped","Map","exec","key","Array","peekReportSdkVersion","dump","extractLastDumpScriptSync","warnedMismatchedVersions","Set","tryParseAgentReportDump","dumpString","trimmed","ReportActionDump","mergedAgentReportComment","reports","generateAgentReportComment","deviceTypes","report","Boolean","mergedReport","getVersion","ReportMergingTool","groupName","groupDescription","reportInfo","Error","sourceVersion","currentVersion","logMsg","contents","unescaped","c","antiEscapeScriptTag","base","allExecutions","i","other","reportFileName","opts","rmOriginalReports","overwrite","outputDir","runnerDumps","info","extractTestRunReportDumpSync","undefined","hasRunnerDump","targetDir","getMidsceneRunSubDir","mkdirSync","isDirModeByIndex","hasDirectoryModeReport","resolvedName","getReportFileName","outputFilePath","htmlEndTag","tpl","getReportTpl","htmlEndIdx","tplWithoutClose","appendFileSync","getBaseUrlFixScript","agentReports","runnerSources","writtenInlineImageIds","reportAttributes","mergedGroupId","reportDir","screenshotsDir","mergedScreenshotsDir","file","readdirSync","src","dest","copyFileSync","streamImageScriptsToFile","allDumps","extractAllDumpScriptsSync","d","groupIdMatch","decodeURIComponent","extractedDumpString","agentReport","agentReportTiming","reportHtmlStr","reportHTMLContent","summary","collectReportSummary","runnerDumpScript","mergeTestRunReportDumps","uuid","agentComment","removedReportCount","reportCountWithFilePath","error","durationMs","timing","executionTimes","execution","value","Number","started","Math","ended","Date","validateTestRunReportFileName","fileName","uniqueTestRunReportSources","sources","unique","source","scopeId","sourcePath","prepareTestRunReportSources","loadedDumps","prepared","ownerByScopedExecution","preparedByPath","sourceIndex","sourceKey","shared","snapshot","readFileSync","executionId","owner","reportId","baseDump","collectDedupedExecutions","executionIds","scopedExecution","previousOwner","preparedSource","TestRunReportAssembler","options","loaded","Promise","fsAsync","directoryMode","artifact","finalPath","temporary","htmlPath","parts","imageIds","serialized","refs","JSON","_key","ref","normalizeStoredImageRef","imageRefFileExtension","images","html","index","runnerDump","finalArtifactPath","directoryReportPath","standaloneReportPath","finalReportPath","existingArtifacts","temporaryRoot","mkdtempSync","temporaryArtifactPath","temporaryReportPath","template","htmlEndIndex","targetScreenshotsDir","renameSync","executionSerial","latestSerialByExecutionId","dumpScript","groupedDump","externalizeImagesInExecution","visit","node","item","ext","relativePath","absolutePath","resolved","resolveImageSource","rawBase64","parseBase64ImageDataUrl","writeFileSync","Buffer","Object","splitReportHtmlByExecution","executionJsonFiles","writtenScreenshotFiles","fileIndex","singleExecutionDump","jsonFilePath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAMA,2BAA2B,IAAIC,OACnC,GAAGC,0BAA0B,qBAAqB,CAAC;AAGrD,SAASC,2BACPC,cAAsB;IAEtB,IAAIC;IACJ,IAAI;QACFC,sBAAsBF,gBAAgB,CAAC,EAAEG,OAAO,EAAE;YAEhD,IAAI,CAACA,QAAQ,QAAQ,CAAC,kBAAkB,OAAO;YAC/C,MAAMC,QAAQD,QAAQ,KAAK,CAACP;YAC5BK,OAAOG,OAAO,CAAC,EAAE;YACjB,OAAO;QACT;IACF,EAAE,OAAM,CAER;IACA,OAAOH;AACT;AAWO,SAASI,sBAAsBL,cAAsB;IAI1D,IAAIM,AAAkC,iBAAlCA,SAAcN,iBAAkC,OAAO;IAE3D,MAAMO,WAAWR,2BAA2BC;IAC5C,IAAIO,UAAU,OAAOA,AAAa,gBAAbA;IAGrB,OAAOC,WAAWF,KAAUA,QAAaN,iBAAiB;AAC5D;AAaA,SAASS,uBAAuBT,cAAsB;IACpD,OAAOM,AAAkC,iBAAlCA,SAAcN;AACvB;AAcO,SAASU,qBAAqBV,cAAsB;IACzD,IAAIS,uBAAuBT,iBAAiB,YAC1CW,OAAOL,QAAaN,iBAAiB;QAAE,WAAW;QAAM,OAAO;IAAK;IAGtEY,WAAWZ;AACb;AAMO,SAASa,2BACdC,UAAe;IAEf,IAAIC,cAAc;IAClB,MAAMC,UAAU,IAAIC;IACpB,KAAK,MAAMC,QAAQJ,WAAY;QAC7B,MAAMK,MAAMD,KAAK,EAAE,IAAI,CAAC,QAAQ,EAAEH,eAAe;QACjDC,QAAQ,GAAG,CAACG,KAAKD;I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ACdA,IAAI,IAAI,GAAG6B;YACX;QACF;QAEA,KAAK,MAAM9E,SAASsF,OAAO,MAAM,CAACX,MAChCD,MAAM1E;IAEV;IAEA0E,MAAM3E;AACR;AAMO,SAASwF,2BACdrD,OAA+B;IAE/B,MAAM,EAAEQ,QAAQ,EAAEpG,SAAS,EAAE,GAAG4F;IAChC,MAAMjE,iBAAiB/E,KAAUoD,WAAW;IAE5CQ,UAAUR,WAAW;QAAE,WAAW;IAAK;IACvCQ,UAAUmB,gBAAgB;QAAE,WAAW;IAAK;IAE5C,MAAMuH,qBAA+B,EAAE;IACvC,MAAMC,yBAAyB,IAAIpL;IACnC,MAAM,EAAEsH,QAAQ,EAAEjI,UAAU,EAAE,GAAGkI,yBAAyBc;IAE1D,IAAIgD,YAAY;IAChB,KAAK,MAAM3F,aAAarG,WAAY;QAClCgM,aAAa;QACbjB,6BAA6B1E,WAAW;YACtC2C;YACAzE;YACA,cAAcwH;QAChB;QACA,MAAME,sBAAsB,IAAIlL,iBAAiB;YAC/C,YAAYkH,SAAS,UAAU;YAC/B,WAAWA,SAAS,SAAS;YAC7B,kBAAkBA,SAAS,gBAAgB;YAC3C,aAAaA,SAAS,WAAW;YACjC,YAAYA,SAAS,UAAU;YAC/B,YAAY;gBAAC5B;aAAU;QACzB;QAEA,MAAM6F,eAAe1M,KAAUoD,WAAW,GAAGoJ,UAAU,eAAe,CAAC;QACvEN,cAAcQ,cAAcD,oBAAoB,SAAS,CAAC,IAAI;QAC9DH,mBAAmB,IAAI,CAACI;IAC1B;IAEA,OAAO;QACLJ;QACA,iBAAiBxL,MAAM,IAAI,CAACyL,wBACzB,IAAI,GACJ,GAAG,CAAC,CAAClF,WAAarH,KAAU+E,gBAAgBsC;IACjD;AACF"}
1
+ {"version":3,"file":"report.mjs","sources":["../../src/report.ts"],"sourcesContent":["import {\n appendFileSync,\n copyFileSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n readdirSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\nimport * as fsAsync from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { getMidsceneRunSubDir } from '@midscene/shared/common';\nimport { antiEscapeScriptTag, logMsg, uuid } from '@midscene/shared/utils';\nimport { getReportFileName } from './agent/report-file-name';\nimport {\n DATA_SCREENSHOT_MODE_ATTR,\n extractAllDumpScriptsSync,\n extractLastDumpScriptSync,\n extractTestRunReportDumpSync,\n generateAgentReportComment,\n getBaseUrlFixScript,\n generateTestRunReportScriptTag as runnerDumpScript,\n streamDumpScriptsSync,\n streamImageScriptsToFile,\n} from './dump/html-utils';\nimport {\n imageRefFileExtension,\n normalizeStoredImageRef,\n} from './dump/image-reference';\nimport {\n parseBase64ImageDataUrl,\n resolveImageSource,\n} from './dump/screenshot-store';\nimport { collectReportSummary } from './report-stats';\nimport type {\n AssembleTestRunReportOptions,\n IndexedTestRunReportSource,\n TestRunReportMetrics,\n TestRunReportSource,\n TestRunReportSourceIndex,\n} from './test-run-report';\nimport {\n type MergeTestRunReportSource,\n mergeTestRunReportDumps,\n} from './test-runner/reporting/merge-report';\nimport { collectTestRunReportMetrics } from './test-runner/reporting/metrics';\nimport {\n type ExecutionDump,\n type IExecutionDump,\n ReportActionDump,\n type ScreenshotMode,\n} from './types';\nimport type { ReportFileWithAttributes } from './types';\nimport { getReportTpl, getVersion, reportHTMLContent } from './utils';\n\nexport {\n calculateTestRunHealth,\n classifyTestRunCase,\n} from './test-run-health';\n\n/**\n * Read the screenshot storage mode a report declared at generation time.\n *\n * Reports written by current versions stamp `data-screenshot-mode` onto every\n * dump script tag, so we only need to peek at the first real dump script (the\n * template's bundled JS also references the dump type string, hence the\n * `data-group-id` filter) and can stop streaming immediately.\n *\n * Returns undefined for legacy reports that predate the attribute or for\n * unreadable files, letting the caller fall back to a filesystem heuristic.\n */\nconst screenshotModeAttrRegExp = new RegExp(\n `${DATA_SCREENSHOT_MODE_ATTR}=\"(inline|directory)\"`,\n);\n\nfunction readDeclaredScreenshotMode(\n reportFilePath: string,\n): ScreenshotMode | undefined {\n let mode: ScreenshotMode | undefined;\n try {\n streamDumpScriptsSync(reportFilePath, ({ openTag }) => {\n // Skip false matches from the template's bundled JS code.\n if (!openTag.includes('data-group-id')) return false;\n const match = openTag.match(screenshotModeAttrRegExp);\n mode = match?.[1] as ScreenshotMode | undefined;\n return true; // the first real dump script decides the mode\n });\n } catch {\n // Unreadable / non-existent file — let the caller fall back.\n }\n return mode;\n}\n\n/**\n * Check if a report is in directory mode (html-and-external-assets).\n * Directory mode reports: {name}/index.html + {name}/screenshots/\n *\n * The mode is read from the report's own `data-screenshot-mode` metadata, which\n * is authoritative regardless of whether the run happened to capture any\n * screenshots. For legacy reports without the attribute we fall back to the old\n * filesystem heuristic (an `index.html` that has a sibling `screenshots/` dir).\n */\nexport function isDirectoryModeReport(reportFilePath: string): boolean {\n // Directory-mode reports are always written as `{name}/index.html`, so any\n // other filename is inline. Short-circuit before touching the file so the\n // common inline case (`{name}.html`) costs nothing.\n if (path.basename(reportFilePath) !== 'index.html') return false;\n\n const declared = readDeclaredScreenshotMode(reportFilePath);\n if (declared) return declared === 'directory';\n\n // Legacy fallback for reports generated before screenshotMode was embedded.\n return existsSync(path.join(path.dirname(reportFilePath), 'screenshots'));\n}\n\n/**\n * Whether a report lives in its own dedicated directory (`{name}/index.html`)\n * rather than being a single standalone file (`{name}.html`).\n *\n * This is a structural fact about *where the report file sits*, independent of\n * how it stores screenshots: a directory report can keep screenshots external\n * (a `screenshots/` sibling) OR inline them into `index.html`. Deletion needs\n * this — not the screenshot mode — to decide whether to remove the whole\n * directory or just unlink a file, so that an inline-screenshot report nested in\n * its own folder still has the folder removed instead of being orphaned.\n */\nfunction isDirectoryBasedReport(reportFilePath: string): boolean {\n return path.basename(reportFilePath) === 'index.html';\n}\n\n/**\n * Remove a complete report artifact from disk.\n *\n * Standalone reports own only their HTML file, while directory-based reports\n * own the directory containing `index.html`. Callers must decide whether they\n * own the source artifact and should only invoke this after its replacement\n * has been produced successfully.\n *\n * @param reportFilePath Path to the standalone report or directory report's\n * `index.html` entry point.\n * @throws When the owned report artifact cannot be removed.\n */\nexport function removeReportArtifact(reportFilePath: string): void {\n if (isDirectoryBasedReport(reportFilePath)) {\n rmSync(path.dirname(reportFilePath), { recursive: true, force: true });\n return;\n }\n unlinkSync(reportFilePath);\n}\n\n/**\n * Deduplicate executions by stable id, keeping only the last occurrence.\n * Old-format executions without id are always preserved.\n */\nexport function dedupeExecutionsKeepLatest<T extends Pick<ExecutionDump, 'id'>>(\n executions: T[],\n): T[] {\n let noIdCounter = 0;\n const deduped = new Map<string, T>();\n for (const exec of executions) {\n const key = exec.id || `__no_id_${noIdCounter++}`;\n deduped.set(key, exec);\n }\n return Array.from(deduped.values());\n}\n/**\n * Peek at the first `sdkVersion` field embedded in a midscene_web_dump\n * script tag inside the given report file. Returns undefined if no\n * recognizable tag or sdkVersion is present.\n */\nfunction peekReportSdkVersion(reportFilePath: string): string | undefined {\n try {\n const dump = extractLastDumpScriptSync(reportFilePath);\n if (!dump) return undefined;\n const match = dump.match(/\"sdkVersion\"\\s*:\\s*\"([^\"]+)\"/);\n return match?.[1];\n } catch {\n return undefined;\n }\n}\n\nconst warnedMismatchedVersions = new Set<string>();\n\nfunction tryParseAgentReportDump(dumpString: string): ReportActionDump | null {\n const trimmed = dumpString.trimStart();\n if (!trimmed.startsWith('{') || !trimmed.includes('\"executions\"')) {\n return null;\n }\n\n try {\n return ReportActionDump.fromSerializedString(trimmed);\n } catch {\n return null;\n }\n}\n\nfunction mergedAgentReportComment(reports: ReportActionDump[]): string {\n if (reports.length === 0) {\n return '';\n }\n if (reports.length === 1) {\n return generateAgentReportComment(reports[0]);\n }\n\n const deviceTypes = Array.from(\n new Set(reports.map((report) => report.deviceType).filter(Boolean)),\n );\n const mergedReport = new ReportActionDump({\n sdkVersion: reports[0].sdkVersion || getVersion(),\n groupName: 'Merged Midscene Report',\n groupDescription: 'Agent-readable summary for merged report HTML',\n modelBriefs: reports.flatMap((report) => report.modelBriefs ?? []),\n deviceType: deviceTypes.length === 1 ? deviceTypes[0] : 'mixed',\n executions: dedupeExecutionsKeepLatest(\n reports.flatMap((report) => report.executions ?? []),\n ),\n });\n return generateAgentReportComment(mergedReport);\n}\n\nexport class ReportMergingTool {\n private reportInfos: ReportFileWithAttributes[] = [];\n\n private createEmptyDumpString(groupName: string, groupDescription?: string) {\n return new ReportActionDump({\n sdkVersion: '',\n groupName,\n groupDescription,\n modelBriefs: [],\n executions: [],\n }).serialize();\n }\n\n public append(reportInfo: ReportFileWithAttributes) {\n if (\n !reportInfo.reportFilePath &&\n reportInfo.reportAttributes.testStatus !== 'skipped'\n ) {\n throw new Error(\n 'reportFilePath is required unless reportAttributes.testStatus is \"skipped\"',\n );\n }\n\n if (reportInfo.reportFilePath) {\n const sourceVersion = peekReportSdkVersion(reportInfo.reportFilePath);\n const currentVersion = getVersion();\n if (\n sourceVersion &&\n currentVersion &&\n sourceVersion !== currentVersion &&\n !warnedMismatchedVersions.has(sourceVersion)\n ) {\n warnedMismatchedVersions.add(sourceVersion);\n logMsg(\n `[@midscene/core] ReportMergingTool version mismatch: source report was written by @midscene/core@${sourceVersion} but the merger is @midscene/core@${currentVersion}. This commonly means @midscene/core and the device package (e.g. @midscene/android) resolve to different versions in node_modules. Merged output may silently drop intermediate steps. Align the versions and reinstall (rm -rf node_modules package-lock.json && npm install).`,\n );\n }\n }\n this.reportInfos.push(reportInfo);\n }\n public clear() {\n this.reportInfos = [];\n }\n\n /**\n * Merge multiple dump script contents (from the same source report)\n * into a single serialized ReportActionDump string.\n * If there's only one dump, return it as-is. If multiple, merge\n * all executions into the first dump's group structure.\n */\n private mergeDumpScripts(contents: string[]): string {\n const unescaped = contents\n .map((c) => antiEscapeScriptTag(c))\n .filter((c) => c.length > 0);\n if (unescaped.length === 0) return '';\n if (unescaped.length === 1) return unescaped[0];\n\n // Parse all dumps and collect executions, deduplicating by id (keep last).\n // Only executions with a stable id are deduped; old-format entries without\n // id are always kept (they may be distinct despite sharing the same name).\n const base = ReportActionDump.fromSerializedString(unescaped[0]);\n const allExecutions = [...base.executions];\n for (let i = 1; i < unescaped.length; i++) {\n const other = ReportActionDump.fromSerializedString(unescaped[i]);\n allExecutions.push(...other.executions);\n }\n base.executions = dedupeExecutionsKeepLatest(allExecutions);\n return base.serialize();\n }\n\n public mergeReports(\n reportFileName: 'AUTO' | string = 'AUTO',\n opts?: {\n rmOriginalReports?: boolean;\n overwrite?: boolean;\n outputDir?: string;\n },\n ): string | null {\n const {\n rmOriginalReports = false,\n overwrite = false,\n outputDir,\n } = opts ?? {};\n\n if (this.reportInfos.length === 0) {\n logMsg('No reports to merge');\n return null;\n }\n\n const runnerDumps = this.reportInfos.map((info) =>\n info.reportFilePath\n ? extractTestRunReportDumpSync(info.reportFilePath)\n : undefined,\n );\n const hasRunnerDump = runnerDumps.some(Boolean);\n\n const targetDir = outputDir\n ? path.resolve(outputDir)\n : getMidsceneRunSubDir('report');\n if (outputDir) {\n mkdirSync(targetDir, { recursive: true });\n }\n\n // Resolve each report's screenshot mode exactly once. isDirectoryModeReport\n // reads the file to find the authoritative metadata, so recomputing it for\n // both the output-path decision and the per-report merge loop would re-scan\n // every report twice.\n const isDirModeByIndex = this.reportInfos.map((info) =>\n Boolean(\n info.reportFilePath && isDirectoryModeReport(info.reportFilePath),\n ),\n );\n const hasDirectoryModeReport = isDirModeByIndex.some(Boolean);\n\n const resolvedName =\n reportFileName === 'AUTO'\n ? getReportFileName('merged-report')\n : reportFileName;\n\n // Directory mode: output as {name}/index.html to keep relative paths working\n // Inline mode: output as {name}.html (single file)\n const outputFilePath = hasDirectoryModeReport\n ? path.resolve(targetDir, resolvedName, 'index.html')\n : path.resolve(targetDir, `${resolvedName}.html`);\n\n if (reportFileName !== 'AUTO' && existsSync(outputFilePath)) {\n if (!overwrite) {\n throw new Error(\n `Report file already exists: ${outputFilePath}\\nSet overwrite to true to overwrite this file.`,\n );\n }\n if (hasDirectoryModeReport) {\n rmSync(path.dirname(outputFilePath), { recursive: true, force: true });\n } else {\n unlinkSync(outputFilePath);\n }\n }\n\n if (hasDirectoryModeReport) {\n mkdirSync(path.dirname(outputFilePath), { recursive: true });\n }\n\n logMsg(\n `Start merging ${this.reportInfos.length} reports...\\nCreating template file...`,\n );\n\n try {\n // Write template without closing </html> tag so we can append\n // dump scripts before it. The closing tag is added at the end.\n const htmlEndTag = '</html>';\n const tpl = getReportTpl();\n const htmlEndIdx = tpl.lastIndexOf(htmlEndTag);\n const tplWithoutClose =\n htmlEndIdx !== -1 ? tpl.slice(0, htmlEndIdx) : tpl;\n appendFileSync(outputFilePath, tplWithoutClose);\n\n // For directory-mode output, inject base URL fix script\n if (hasDirectoryModeReport) {\n appendFileSync(outputFilePath, getBaseUrlFixScript());\n }\n\n const agentReports: ReportActionDump[] = [];\n const runnerSources: MergeTestRunReportSource[] = [];\n const writtenInlineImageIds = new Set<string>();\n\n // Process all reports one by one\n for (let i = 0; i < this.reportInfos.length; i++) {\n const reportInfo = this.reportInfos[i];\n logMsg(`Processing report ${i + 1}/${this.reportInfos.length}`);\n\n const { reportAttributes } = reportInfo;\n let dumpString = this.createEmptyDumpString(\n reportAttributes.testTitle,\n reportAttributes.testDescription,\n );\n let mergedGroupId = `merged-group-${i}`;\n\n if (reportInfo.reportFilePath) {\n if (isDirModeByIndex[i]) {\n // Directory mode: copy external screenshot files. A directory-mode\n // report can legitimately have no screenshots/ dir (a run that\n // captured nothing), so only copy when the source dir exists.\n const reportDir = path.dirname(reportInfo.reportFilePath);\n const screenshotsDir = path.join(reportDir, 'screenshots');\n if (existsSync(screenshotsDir)) {\n const mergedScreenshotsDir = path.join(\n path.dirname(outputFilePath),\n 'screenshots',\n );\n mkdirSync(mergedScreenshotsDir, { recursive: true });\n for (const file of readdirSync(screenshotsDir)) {\n const src = path.join(screenshotsDir, file);\n const dest = path.join(mergedScreenshotsDir, file);\n copyFileSync(src, dest);\n }\n }\n } else {\n // Inline mode: stream image scripts to output file\n streamImageScriptsToFile(\n reportInfo.reportFilePath,\n outputFilePath,\n writtenInlineImageIds,\n );\n }\n\n // Extract all dump scripts from the source report.\n // After the per-execution append refactor, a single source report\n // may contain multiple <script type=\"midscene_web_dump\"> tags\n // (one per execution). We merge them into a single ReportActionDump.\n // Filter by data-group-id to exclude false matches from the template's\n // bundled JS code, which also references the midscene_web_dump type string.\n const allDumps = extractAllDumpScriptsSync(\n reportInfo.reportFilePath,\n ).filter((d) => d.openTag.includes('data-group-id'));\n const groupIdMatch = allDumps[0]?.openTag.match(\n /data-group-id=\"([^\"]+)\"/,\n );\n if (groupIdMatch && !hasRunnerDump) {\n mergedGroupId = decodeURIComponent(groupIdMatch[1]);\n }\n const extractedDumpString =\n allDumps.length > 0\n ? this.mergeDumpScripts(allDumps.map((d) => d.content))\n : extractLastDumpScriptSync(reportInfo.reportFilePath);\n if (extractedDumpString) {\n dumpString = extractedDumpString;\n }\n }\n\n const agentReport = tryParseAgentReportDump(dumpString);\n if (agentReport) {\n agentReports.push(agentReport);\n }\n if (hasRunnerDump)\n runnerSources.push({\n reportId: mergedGroupId,\n sourcePath: reportInfo.reportFilePath ?? '<skipped-agent-report>',\n attributes: reportAttributes,\n dump: runnerDumps[i],\n timing: agentReport\n ? agentReportTiming(agentReport, reportAttributes.testDuration)\n : undefined,\n });\n\n const reportHtmlStr = `${reportHTMLContent(\n {\n dumpString,\n attributes: {\n 'data-group-id': mergedGroupId,\n ...(hasRunnerDump ? { 'data-report-id': mergedGroupId } : {}),\n [DATA_SCREENSHOT_MODE_ATTR]: hasDirectoryModeReport\n ? 'directory'\n : 'inline',\n playwright_test_duration: reportAttributes.testDuration,\n playwright_test_status: reportAttributes.testStatus,\n playwright_test_title: reportAttributes.testTitle,\n playwright_test_id: reportAttributes.testId,\n playwright_test_description: reportAttributes.testDescription,\n is_merged: true,\n },\n },\n undefined,\n undefined,\n false,\n )}\\n`;\n\n appendFileSync(outputFilePath, reportHtmlStr);\n }\n\n if (hasRunnerDump) {\n const executions = dedupeExecutionsKeepLatest(\n agentReports.flatMap((report) => report.executions),\n );\n const metrics = collectTestRunReportMetrics({ executions });\n const executionMetrics = Object.fromEntries(\n executions.flatMap((execution) =>\n execution.id\n ? [\n [\n execution.id,\n collectTestRunReportMetrics({ executions: [execution] }),\n ],\n ]\n : [],\n ),\n );\n appendFileSync(\n outputFilePath,\n runnerDumpScript(\n mergeTestRunReportDumps(\n runnerSources,\n metrics,\n uuid(),\n executionMetrics,\n ),\n ),\n );\n }\n\n const agentComment = mergedAgentReportComment(agentReports);\n if (agentComment) {\n appendFileSync(outputFilePath, agentComment);\n }\n\n // Close the HTML document\n appendFileSync(outputFilePath, `${htmlEndTag}\\n`);\n\n logMsg(`Successfully merged new report: ${outputFilePath}`);\n\n // Remove original reports if needed\n if (rmOriginalReports) {\n let removedReportCount = 0;\n let reportCountWithFilePath = 0;\n for (const info of this.reportInfos) {\n if (!info.reportFilePath) continue;\n reportCountWithFilePath += 1;\n try {\n removeReportArtifact(info.reportFilePath);\n removedReportCount += 1;\n } catch (error) {\n logMsg(`Error deleting report ${info.reportFilePath}: ${error}`);\n }\n }\n logMsg(\n `Removed ${removedReportCount}/${reportCountWithFilePath} original reports`,\n );\n }\n return outputFilePath;\n } catch (error) {\n logMsg(`Error in mergeReports: ${error}`);\n throw error;\n }\n }\n}\n\nfunction agentReportTiming(\n report: ReportActionDump,\n durationMs: number,\n): MergeTestRunReportSource['timing'] {\n const timing = collectReportSummary(report).timing;\n const executionTimes = report.executions\n .map((execution) => execution.logTime)\n .filter(\n (value): value is number =>\n typeof value === 'number' && Number.isFinite(value),\n );\n const started =\n timing.wallTimeStart ??\n (executionTimes.length ? Math.min(...executionTimes) : undefined);\n if (started === undefined) return undefined;\n const ended =\n timing.wallTimeEnd ??\n Math.max(\n ...executionTimes,\n started + (Number.isFinite(durationMs) ? Math.max(0, durationMs) : 0),\n );\n return {\n startedAt: new Date(started).toISOString(),\n endedAt: new Date(ended).toISOString(),\n durationMs: Math.max(0, ended - started),\n };\n}\n\ninterface PreparedTestRunReportSource extends IndexedTestRunReportSource {\n dump: ReportActionDump;\n directoryMode: boolean;\n dumpPath?: string;\n}\n\nconst validateTestRunReportFileName = (fileName: string): void => {\n if (\n !fileName ||\n fileName === '.' ||\n fileName === '..' ||\n path.basename(fileName) !== fileName ||\n fileName.endsWith('.html')\n ) {\n throw new Error(\n `Midscene Test reportFileName must be one path segment without an extension: ${fileName}`,\n );\n }\n};\n\nconst uniqueTestRunReportSources = (\n sources: readonly TestRunReportSource[],\n): TestRunReportSource[] => {\n const unique = new Map<string, TestRunReportSource>();\n\n for (const source of sources) {\n const scopeId = source.scopeId.trim();\n const sourcePath = path.resolve(source.sourcePath);\n if (!scopeId) {\n throw new Error('Midscene Test report source scopeId must not be empty.');\n }\n\n unique.set(`${scopeId}\\u0000${source.dumpPath ?? sourcePath}`, {\n ...source,\n scopeId,\n sourcePath,\n });\n }\n\n return [...unique.values()];\n};\n\nconst prepareTestRunReportSources = (\n sources: readonly TestRunReportSource[],\n loadedDumps?: ReadonlyMap<string, string | Error>,\n): {\n sources: PreparedTestRunReportSource[];\n metrics: TestRunReportMetrics;\n capturedMetrics: TestRunReportMetrics;\n executionMetrics: Record<string, TestRunReportMetrics>;\n diagnostics: import('./test-run-report').TestRunReportDiagnostic[];\n} => {\n const prepared: PreparedTestRunReportSource[] = [];\n const diagnostics: import('./test-run-report').TestRunReportDiagnostic[] = [];\n const ownerByScopedExecution = new Map<string, string>();\n const preparedByPath = new Map<string, PreparedTestRunReportSource>();\n\n for (const [sourceIndex, source] of uniqueTestRunReportSources(\n sources,\n ).entries()) {\n let baseDump: ReportActionDump;\n let executions: IExecutionDump[];\n try {\n if (source.dumpPath) {\n const contents =\n loadedDumps?.get(source.dumpPath) ??\n readFileSync(source.dumpPath, 'utf8');\n if (contents instanceof Error) throw contents;\n baseDump = ReportActionDump.fromSerializedString(contents);\n executions = baseDump.executions;\n } else {\n if (!existsSync(source.sourcePath))\n throw new Error(`Agent report does not exist: ${source.sourcePath}`);\n const sourceVersion = peekReportSdkVersion(source.sourcePath);\n const currentVersion = getVersion();\n if (\n sourceVersion &&\n currentVersion &&\n sourceVersion !== currentVersion &&\n !warnedMismatchedVersions.has(sourceVersion)\n ) {\n warnedMismatchedVersions.add(sourceVersion);\n logMsg(\n `[@midscene/core] TestRunReportAssembler version mismatch: source report was written by @midscene/core@${sourceVersion} but the assembler is @midscene/core@${currentVersion}. Align the workspace package versions before generating the Midscene Test report.`,\n );\n }\n ({ baseDump, executions } = collectDedupedExecutions(\n source.sourcePath,\n ));\n }\n } catch (error) {\n diagnostics.push({\n level: 'warning',\n code: 'agent-source-unavailable',\n scopeId: source.scopeId,\n sourcePaths: [source.sourcePath],\n message: `Agent source could not be collected: ${String(error)}`,\n });\n continue;\n }\n // A borrowed Agent can serve several sequential test scopes. Reuse its\n // report group and metrics while indexing each scope's execution links.\n const sourceKey = source.sourcePath;\n const shared = preparedByPath.get(sourceKey);\n if (shared) {\n if (source.dumpPath) {\n shared.dump.executions = dedupeExecutionsKeepLatest([\n ...shared.dump.executions,\n ...baseDump.executions,\n ]);\n }\n const scoped = prepared.find(\n (item) =>\n item.reportId === shared.reportId && item.scopeId === source.scopeId,\n );\n const executionIds = [\n ...new Set([\n ...(scoped?.executionIds ?? []),\n ...executions.flatMap((execution) =>\n execution.id ? [execution.id] : [],\n ),\n ]),\n ];\n for (const executionId of executionIds) {\n const key = `${source.scopeId}\\u0000${executionId}`;\n const owner = ownerByScopedExecution.get(key);\n if (owner && owner !== shared.reportId)\n throw new Error(\n `Agent execution ${executionId} is present in multiple reports for test scope ${source.scopeId}: ${owner}, ${shared.reportId}`,\n );\n ownerByScopedExecution.set(key, shared.reportId);\n }\n if (scoped) {\n scoped.executionIds = executionIds;\n const partial = [scoped.collection, source.collection].find(\n (collection) => collection?.status === 'partial',\n );\n scoped.collection = partial ?? source.collection ?? scoped.collection;\n } else\n prepared.push({\n ...shared,\n scopeId: source.scopeId,\n executionIds,\n collection: source.collection,\n });\n continue;\n }\n const reportId = `runner-report-${sourceIndex + 1}`;\n const executionIds: string[] = [];\n for (const execution of executions) {\n if (!execution.id) continue;\n const scopedExecution = `${source.scopeId}\\u0000${execution.id}`;\n const previousOwner = ownerByScopedExecution.get(scopedExecution);\n if (previousOwner && previousOwner !== reportId) {\n throw new Error(\n `Agent execution ${execution.id} is present in multiple reports for test scope ${source.scopeId}: ${previousOwner}, ${reportId}`,\n );\n }\n ownerByScopedExecution.set(scopedExecution, reportId);\n executionIds.push(execution.id);\n }\n\n const dump = new ReportActionDump({\n sdkVersion: baseDump.sdkVersion,\n groupName: baseDump.groupName,\n groupDescription: baseDump.groupDescription,\n modelBriefs: baseDump.modelBriefs,\n deviceType: baseDump.deviceType,\n executions,\n });\n const preparedSource = {\n reportId,\n scopeId: source.scopeId,\n sourcePath: source.sourcePath,\n executionIds,\n collection: source.collection,\n dump,\n directoryMode:\n !!source.dumpPath || isDirectoryModeReport(source.sourcePath),\n ...(source.dumpPath ? { dumpPath: source.dumpPath } : {}),\n };\n prepared.push(preparedSource);\n preparedByPath.set(sourceKey, preparedSource);\n }\n\n // A legacy invocation can preserve a snapshot of an Agent also used by\n // native scopes. Count stable executions once across both paths.\n const executions = dedupeExecutionsKeepLatest(\n [...preparedByPath.values()].flatMap((source) => source.dump.executions),\n );\n const metrics = collectTestRunReportMetrics({ executions });\n const executionMetrics = Object.fromEntries(\n executions.flatMap((execution) =>\n execution.id\n ? [\n [\n execution.id,\n collectTestRunReportMetrics({ executions: [execution] }),\n ],\n ]\n : [],\n ),\n );\n return {\n sources: prepared,\n diagnostics,\n capturedMetrics: metrics,\n executionMetrics,\n metrics: {\n ...metrics,\n collection: {\n ...metrics.collection!,\n fields: Object.fromEntries(\n Object.entries(metrics.collection!.fields!).map(([field, status]) => [\n field,\n diagnostics.length\n ? prepared.length === 0\n ? 'unknown'\n : status === 'complete'\n ? 'partial'\n : status\n : status,\n ]),\n ) as NonNullable<\n NonNullable<TestRunReportMetrics['collection']>['fields']\n >,\n status: diagnostics.length\n ? prepared.length\n ? 'partial'\n : 'unknown'\n : metrics.collection!.status,\n expectedExecutionCount: 0,\n capturedExecutionCount: 0,\n reasons: [\n ...metrics.collection!.reasons,\n ...diagnostics.map((diagnostic) => diagnostic.message),\n ],\n },\n },\n };\n};\n\n/**\n * Build a self-contained Midscene Test report while preserving the existing\n * Agent dump format consumed by the Report App.\n *\n * Test hierarchy and status live in `midscene_test_run_dump`; Agent reports\n * remain independent `midscene_web_dump` groups addressed by `data-report-id`.\n */\nexport class TestRunReportAssembler {\n /** Runtime publisher: current Agent snapshots avoid parsing HTML or copying unused images. */\n public async assembleAsync(\n options: AssembleTestRunReportOptions,\n ): Promise<string> {\n validateTestRunReportFileName(options.reportFileName);\n const loaded = new Map<string, string | Error>();\n await Promise.all(\n options.sources.map(async (source) => {\n if (source.dumpPath) {\n try {\n loaded.set(\n source.dumpPath,\n await fsAsync.readFile(source.dumpPath, 'utf8'),\n );\n } catch (error) {\n loaded.set(\n source.dumpPath,\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }\n }),\n );\n const prepared = prepareTestRunReportSources(options.sources, loaded);\n const dump = options.buildRunnerDump({\n sources: prepared.sources,\n metrics: prepared.metrics,\n capturedMetrics: prepared.capturedMetrics,\n executionMetrics: prepared.executionMetrics,\n diagnostics: prepared.diagnostics,\n });\n if (dump.kind !== 'test-runner' || dump.schemaVersion !== 1)\n throw new Error('Invalid Runner report dump');\n const directoryMode = prepared.sources.some(\n (source) => source.directoryMode,\n );\n const outputDir = path.resolve(options.outputDir);\n await fsAsync.mkdir(outputDir, { recursive: true });\n const artifact = path.join(outputDir, options.reportFileName);\n const finalPath = directoryMode\n ? path.join(artifact, 'index.html')\n : `${artifact}.html`;\n if (\n !options.overwrite &&\n (existsSync(artifact) || existsSync(`${artifact}.html`))\n )\n throw new Error(`Report artifact already exists: ${artifact}`);\n const temporary = await fsAsync.mkdtemp(\n path.join(outputDir, '.test-run-report-'),\n );\n const htmlPath = path.join(temporary, 'index.html');\n try {\n const parts = [\n getReportTpl(),\n directoryMode ? getBaseUrlFixScript() : '',\n ];\n const imageIds = new Set<string>();\n const reports: ReportActionDump[] = [];\n for (const source of new Map(\n prepared.sources.map((source) => [source.reportId, source]),\n ).values()) {\n const serialized = source.dump.serialize();\n if (source.dumpPath) {\n const refs = new Map<\n string,\n ReturnType<typeof normalizeStoredImageRef> & {}\n >();\n JSON.parse(serialized, (_key, value) => {\n const ref = normalizeStoredImageRef(value);\n if (ref) refs.set(ref.id, ref);\n return value;\n });\n if (refs.size)\n await fsAsync.mkdir(path.join(temporary, 'screenshots'), {\n recursive: true,\n });\n for (const ref of refs.values()) {\n if (imageIds.has(ref.id)) continue;\n if (ref.storage !== 'file' || !ref.path)\n throw new Error(`Snapshot image ${ref.id} has no file source`);\n await fsAsync.copyFile(\n path.resolve(path.dirname(source.dumpPath), ref.path),\n path.join(\n temporary,\n 'screenshots',\n `${ref.id}.${imageRefFileExtension(ref)}`,\n ),\n );\n imageIds.add(ref.id);\n }\n } else {\n // An explicit external provider may still return a finalized HTML artifact.\n // This is a public provider contract, not a second execution/serialization schema.\n if (source.directoryMode) {\n const images = path.join(\n path.dirname(source.sourcePath),\n 'screenshots',\n );\n if (existsSync(images))\n await fsAsync.cp(images, path.join(temporary, 'screenshots'), {\n recursive: true,\n });\n } else {\n const html = await fsAsync.readFile(source.sourcePath, 'utf8');\n for (const match of html.matchAll(\n /<script\\b([^>]*)>[\\s\\S]*?<\\/script>/g,\n )) {\n if (/(?:^|\\s)type=[\"']midscene-image[\"']/.test(match[1]))\n parts.push(match[0]);\n }\n }\n }\n reports.push(source.dump);\n parts.push(\n reportHTMLContent(\n {\n dumpString: serialized,\n attributes: {\n 'data-group-id': source.reportId,\n 'data-report-id': source.reportId,\n 'data-runner-scope-id': source.scopeId,\n [DATA_SCREENSHOT_MODE_ATTR]: directoryMode\n ? 'directory'\n : 'inline',\n },\n },\n undefined,\n undefined,\n false,\n ),\n );\n }\n parts.push(runnerDumpScript(dump), mergedAgentReportComment(reports));\n await fsAsync.writeFile(htmlPath, parts.join('\\n'));\n if (options.overwrite) {\n await fsAsync.rm(artifact, { recursive: true, force: true });\n await fsAsync.rm(`${artifact}.html`, { force: true });\n }\n await fsAsync.rename(\n directoryMode ? temporary : htmlPath,\n directoryMode ? artifact : finalPath,\n );\n return finalPath;\n } finally {\n await fsAsync.rm(temporary, { recursive: true, force: true });\n }\n }\n\n public assemble(options: AssembleTestRunReportOptions): string {\n validateTestRunReportFileName(options.reportFileName);\n const outputDir = path.resolve(options.outputDir);\n mkdirSync(outputDir, { recursive: true });\n\n const prepared = prepareTestRunReportSources(options.sources);\n const index: TestRunReportSourceIndex = {\n sources: prepared.sources.map(\n ({ reportId, scopeId, sourcePath, executionIds, collection }) => ({\n reportId,\n scopeId,\n sourcePath,\n executionIds,\n collection,\n }),\n ),\n metrics: prepared.metrics,\n capturedMetrics: prepared.capturedMetrics,\n executionMetrics: prepared.executionMetrics,\n diagnostics: prepared.diagnostics,\n };\n const runnerDump = options.buildRunnerDump(index);\n if (runnerDump.schemaVersion !== 1 || runnerDump.kind !== 'test-runner') {\n throw new Error(\n 'buildRunnerDump must return a Midscene Test report dump with schemaVersion 1 and kind \"test-runner\".',\n );\n }\n // Validate serializability before creating any output artifact.\n JSON.stringify(runnerDump);\n\n const directoryMode = prepared.sources.some(\n (source) => source.directoryMode,\n );\n const finalArtifactPath = path.join(outputDir, options.reportFileName);\n const directoryReportPath = path.join(finalArtifactPath, 'index.html');\n const standaloneReportPath = `${finalArtifactPath}.html`;\n const finalReportPath = directoryMode\n ? directoryReportPath\n : standaloneReportPath;\n const existingArtifacts = [finalArtifactPath, standaloneReportPath].filter(\n existsSync,\n );\n if (existingArtifacts.length > 0 && !options.overwrite) {\n throw new Error(\n `Report artifact already exists: ${existingArtifacts[0]}\\nSet overwrite to true to overwrite this report.`,\n );\n }\n\n const temporaryRoot = mkdtempSync(\n path.join(outputDir, '.test-run-report-'),\n );\n const temporaryArtifactPath = path.join(\n temporaryRoot,\n options.reportFileName,\n );\n const temporaryReportPath = directoryMode\n ? path.join(temporaryArtifactPath, 'index.html')\n : `${temporaryArtifactPath}.html`;\n\n try {\n if (directoryMode) {\n mkdirSync(temporaryArtifactPath, { recursive: true });\n }\n\n const htmlEndTag = '</html>';\n const template = getReportTpl();\n const htmlEndIndex = template.lastIndexOf(htmlEndTag);\n appendFileSync(\n temporaryReportPath,\n htmlEndIndex === -1 ? template : template.slice(0, htmlEndIndex),\n );\n if (directoryMode) {\n appendFileSync(temporaryReportPath, getBaseUrlFixScript());\n }\n\n const agentReports: ReportActionDump[] = [];\n for (const source of new Map(\n prepared.sources.map((source) => [source.reportId, source]),\n ).values()) {\n if (source.directoryMode) {\n const screenshotsDir = path.join(\n path.dirname(source.sourcePath),\n 'screenshots',\n );\n if (existsSync(screenshotsDir)) {\n const targetScreenshotsDir = path.join(\n path.dirname(temporaryReportPath),\n 'screenshots',\n );\n mkdirSync(targetScreenshotsDir, { recursive: true });\n for (const file of readdirSync(screenshotsDir)) {\n copyFileSync(\n path.join(screenshotsDir, file),\n path.join(targetScreenshotsDir, file),\n );\n }\n }\n } else {\n streamImageScriptsToFile(source.sourcePath, temporaryReportPath);\n }\n\n agentReports.push(source.dump);\n appendFileSync(\n temporaryReportPath,\n `${reportHTMLContent(\n {\n dumpString: source.dump.serialize(),\n attributes: {\n 'data-group-id': source.reportId,\n 'data-report-id': source.reportId,\n 'data-runner-scope-id': source.scopeId,\n [DATA_SCREENSHOT_MODE_ATTR]: directoryMode\n ? 'directory'\n : 'inline',\n },\n },\n undefined,\n undefined,\n false,\n )}\\n`,\n );\n }\n\n appendFileSync(temporaryReportPath, runnerDumpScript(runnerDump));\n const agentComment = mergedAgentReportComment(agentReports);\n if (agentComment) {\n appendFileSync(temporaryReportPath, agentComment);\n }\n appendFileSync(temporaryReportPath, `${htmlEndTag}\\n`);\n\n if (existsSync(finalArtifactPath)) {\n rmSync(finalArtifactPath, { recursive: true, force: true });\n }\n if (existsSync(standaloneReportPath)) {\n unlinkSync(standaloneReportPath);\n }\n renameSync(\n directoryMode ? temporaryArtifactPath : temporaryReportPath,\n directoryMode ? finalArtifactPath : standaloneReportPath,\n );\n rmSync(temporaryRoot, { recursive: true, force: true });\n return finalReportPath;\n } catch (error) {\n rmSync(temporaryRoot, { recursive: true, force: true });\n throw error;\n }\n }\n}\n\nexport interface SplitReportHtmlOptions {\n htmlPath: string;\n outputDir: string;\n}\n\nexport interface SplitReportHtmlResult {\n executionJsonFiles: string[];\n screenshotFiles: string[];\n}\n\nexport interface CollectedReportExecutions {\n baseDump: ReportActionDump;\n executions: IExecutionDump[];\n}\n\n/**\n * Collect executions from a report HTML, deduplicating by stable id while\n * keeping only the latest occurrence. Old-format executions without id are\n * always preserved.\n */\nexport function collectDedupedExecutions(\n htmlPath: string,\n): CollectedReportExecutions {\n let baseDump: ReportActionDump | null = null;\n let executionSerial = 0;\n const latestSerialByExecutionId = new Map<string, number>();\n\n streamDumpScriptsSync(htmlPath, (dumpScript) => {\n if (!dumpScript.openTag.includes('data-group-id')) {\n return false;\n }\n const groupedDump = ReportActionDump.fromSerializedString(\n antiEscapeScriptTag(dumpScript.content),\n );\n for (const execution of groupedDump.executions) {\n executionSerial += 1;\n if (execution.id) {\n latestSerialByExecutionId.set(execution.id, executionSerial);\n }\n }\n return false;\n });\n\n const executions: IExecutionDump[] = [];\n executionSerial = 0;\n streamDumpScriptsSync(htmlPath, (dumpScript) => {\n if (!dumpScript.openTag.includes('data-group-id')) {\n return false;\n }\n\n const groupedDump = ReportActionDump.fromSerializedString(\n antiEscapeScriptTag(dumpScript.content),\n );\n if (!baseDump) {\n baseDump = groupedDump;\n }\n\n for (const execution of groupedDump.executions) {\n executionSerial += 1;\n if (\n execution.id &&\n latestSerialByExecutionId.get(execution.id) !== executionSerial\n ) {\n continue;\n }\n executions.push(execution);\n }\n\n return false;\n });\n\n if (!baseDump) {\n throw new Error(`No report dump scripts found in ${htmlPath}`);\n }\n\n return {\n baseDump,\n executions,\n };\n}\n\nfunction externalizeImagesInExecution(\n execution: IExecutionDump,\n opts: {\n htmlPath: string;\n screenshotsDir: string;\n writtenFiles: Set<string>;\n },\n): void {\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n visit(item);\n }\n return;\n }\n\n if (typeof node !== 'object' || node === null) return;\n\n const ref = normalizeStoredImageRef(node);\n if (ref) {\n const ext = imageRefFileExtension(ref);\n const fileName = `${ref.id}.${ext}`;\n const relativePath = `./screenshots/${fileName}`;\n const absolutePath = path.join(opts.screenshotsDir, fileName);\n\n if (!opts.writtenFiles.has(fileName)) {\n const resolved = resolveImageSource(ref, {\n reportPath: opts.htmlPath,\n });\n if (resolved.type === 'data-uri') {\n const { rawBase64 } = parseBase64ImageDataUrl(resolved.dataUri);\n writeFileSync(absolutePath, Buffer.from(rawBase64, 'base64'));\n } else {\n copyFileSync(resolved.filePath, absolutePath);\n }\n opts.writtenFiles.add(fileName);\n }\n\n ref.storage = 'file';\n ref.path = relativePath;\n return;\n }\n\n for (const value of Object.values(node)) {\n visit(value);\n }\n };\n\n visit(execution);\n}\n\n/**\n * Reverse parse a Midscene report HTML into per-execution JSON files and\n * externalized screenshots.\n */\nexport function splitReportHtmlByExecution(\n options: SplitReportHtmlOptions,\n): SplitReportHtmlResult {\n const { htmlPath, outputDir } = options;\n const screenshotsDir = path.join(outputDir, 'screenshots');\n\n mkdirSync(outputDir, { recursive: true });\n mkdirSync(screenshotsDir, { recursive: true });\n\n const executionJsonFiles: string[] = [];\n const writtenScreenshotFiles = new Set<string>();\n const { baseDump, executions } = collectDedupedExecutions(htmlPath);\n\n let fileIndex = 0;\n for (const execution of executions) {\n fileIndex += 1;\n externalizeImagesInExecution(execution, {\n htmlPath,\n screenshotsDir,\n writtenFiles: writtenScreenshotFiles,\n });\n const singleExecutionDump = new ReportActionDump({\n sdkVersion: baseDump.sdkVersion,\n groupName: baseDump.groupName,\n groupDescription: baseDump.groupDescription,\n modelBriefs: baseDump.modelBriefs,\n deviceType: baseDump.deviceType,\n executions: [execution],\n });\n\n const jsonFilePath = path.join(outputDir, `${fileIndex}.execution.json`);\n writeFileSync(jsonFilePath, singleExecutionDump.serialize(2), 'utf-8');\n executionJsonFiles.push(jsonFilePath);\n }\n\n return {\n executionJsonFiles,\n screenshotFiles: Array.from(writtenScreenshotFiles)\n .sort()\n .map((fileName) => path.join(screenshotsDir, fileName)),\n };\n}\n"],"names":["screenshotModeAttrRegExp","RegExp","DATA_SCREENSHOT_MODE_ATTR","readDeclaredScreenshotMode","reportFilePath","mode","streamDumpScriptsSync","openTag","match","isDirectoryModeReport","path","declared","existsSync","isDirectoryBasedReport","removeReportArtifact","rmSync","unlinkSync","dedupeExecutionsKeepLatest","executions","noIdCounter","deduped","Map","exec","key","Array","peekReportSdkVersion","dump","extractLastDumpScriptSync","warnedMismatchedVersions","Set","tryParseAgentReportDump","dumpString","trimmed","ReportActionDump","mergedAgentReportComment","reports","generateAgentReportComment","deviceTypes","report","Boolean","mergedReport","getVersion","ReportMergingTool","groupName","groupDescription","reportInfo","Error","sourceVersion","currentVersion","logMsg","contents","unescaped","c","antiEscapeScriptTag","base","allExecutions","i","other","reportFileName","opts","rmOriginalReports","overwrite","outputDir","runnerDumps","info","extractTestRunReportDumpSync","undefined","hasRunnerDump","targetDir","getMidsceneRunSubDir","mkdirSync","isDirModeByIndex","hasDirectoryModeReport","resolvedName","getReportFileName","outputFilePath","htmlEndTag","tpl","getReportTpl","htmlEndIdx","tplWithoutClose","appendFileSync","getBaseUrlFixScript","agentReports","runnerSources","writtenInlineImageIds","reportAttributes","mergedGroupId","reportDir","screenshotsDir","mergedScreenshotsDir","file","readdirSync","src","dest","copyFileSync","streamImageScriptsToFile","allDumps","extractAllDumpScriptsSync","d","groupIdMatch","decodeURIComponent","extractedDumpString","agentReport","agentReportTiming","reportHtmlStr","reportHTMLContent","metrics","collectTestRunReportMetrics","executionMetrics","Object","execution","runnerDumpScript","mergeTestRunReportDumps","uuid","agentComment","removedReportCount","reportCountWithFilePath","error","durationMs","timing","collectReportSummary","executionTimes","value","Number","started","Math","ended","Date","validateTestRunReportFileName","fileName","uniqueTestRunReportSources","sources","unique","source","scopeId","sourcePath","prepareTestRunReportSources","loadedDumps","prepared","diagnostics","ownerByScopedExecution","preparedByPath","sourceIndex","baseDump","readFileSync","collectDedupedExecutions","String","sourceKey","shared","scoped","item","executionIds","executionId","owner","partial","collection","reportId","scopedExecution","previousOwner","preparedSource","field","status","diagnostic","TestRunReportAssembler","options","loaded","Promise","fsAsync","directoryMode","artifact","finalPath","temporary","htmlPath","parts","imageIds","serialized","refs","JSON","_key","ref","normalizeStoredImageRef","imageRefFileExtension","images","html","index","runnerDump","finalArtifactPath","directoryReportPath","standaloneReportPath","finalReportPath","existingArtifacts","temporaryRoot","mkdtempSync","temporaryArtifactPath","temporaryReportPath","template","htmlEndIndex","targetScreenshotsDir","renameSync","executionSerial","latestSerialByExecutionId","dumpScript","groupedDump","externalizeImagesInExecution","visit","node","ext","relativePath","absolutePath","resolved","resolveImageSource","rawBase64","parseBase64ImageDataUrl","writeFileSync","Buffer","splitReportHtmlByExecution","executionJsonFiles","writtenScreenshotFiles","fileIndex","singleExecutionDump","jsonFilePath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,MAAMA,2BAA2B,IAAIC,OACnC,GAAGC,0BAA0B,qBAAqB,CAAC;AAGrD,SAASC,2BACPC,cAAsB;IAEtB,IAAIC;IACJ,IAAI;QACFC,sBAAsBF,gBAAgB,CAAC,EAAEG,OAAO,EAAE;YAEhD,IAAI,CAACA,QAAQ,QAAQ,CAAC,kBAAkB,OAAO;YAC/C,MAAMC,QAAQD,QAAQ,KAAK,CAACP;YAC5BK,OAAOG,OAAO,CAAC,EAAE;YACjB,OAAO;QACT;IACF,EAAE,OAAM,CAER;IACA,OAAOH;AACT;AAWO,SAASI,sBAAsBL,cAAsB;IAI1D,IAAIM,AAAkC,iBAAlCA,SAAcN,iBAAkC,OAAO;IA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