-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbrowser-visual-compare.ts
More file actions
3015 lines (2840 loc) · 147 KB
/
Copy pathbrowser-visual-compare.ts
File metadata and controls
3015 lines (2840 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { access, readFile, writeFile } from "node:fs/promises"
import { dirname, join, relative } from "node:path"
import type { ExecutionSpec, RuntimeCreateSpec } from "@automattic/wp-codebox-core"
import { errorMessage, now, sha256 } from "@automattic/wp-codebox-core/internals"
import pixelmatch from "pixelmatch"
import { PNG } from "pngjs"
import { BrowserArtifactSession } from "./browser-artifact-session.js"
import type { BrowserArtifact, BrowserProbeViewport } from "./browser-artifacts.js"
import { launchChromiumBrowser } from "./browser-capture-session.js"
import { captureBrowserDomSnapshot, normalizeBrowserDomSnapshotArtifact, type BrowserDomElementSnapshot as VisualCompareDomElementSnapshot, type BrowserDomSelectorSnapshot as VisualCompareSelectorSnapshot, type BrowserDomSnapshot as VisualCompareDomSnapshot, type BrowserDomSnapshotArtifact as VisualCompareDomSnapshotArtifact } from "./browser-dom-snapshot.js"
import { browserCommandLivenessPolicy, withBrowserCommandLiveness } from "./browser-liveness.js"
import { browserPreviewRouting, resolveBrowserPreviewUrl } from "./browser-preview-routing.js"
import { browserProbeViewport } from "./browser-probe.js"
import { BrowserCommandArtifactError } from "./browser-command-artifact-error.js"
import { argValue, durationArg, jsonArrayArg, strictBooleanArg, viewportArg } from "./commands.js"
import type { PlaygroundCliServer } from "./preview-server.js"
import type { Page } from "playwright"
interface VisualCompareElementDelta {
path: string
tag: string
changes: {
text?: { source: string; candidate: string }
boundingBox?: { source: VisualCompareDomElementSnapshot["boundingBox"]; candidate: VisualCompareDomElementSnapshot["boundingBox"]; delta: { x: number; y: number; width: number; height: number } }
attributes?: Record<string, { source: string | null; candidate: string | null }>
styles?: Record<string, { source: string; candidate: string }>
}
}
interface VisualCompareMismatchRegion {
x: number
y: number
width: number
height: number
pixels: number
sourceElements?: VisualCompareRegionElementOverlap[]
candidateElements?: VisualCompareRegionElementOverlap[]
}
interface VisualCompareRegionElementOverlap {
path: string
tag: string
text?: string
className?: string
boundingBox: VisualCompareDomElementSnapshot["boundingBox"]
overlap: { x: number; y: number; width: number; height: number; area: number; regionCoverage: number; elementCoverage: number }
styles: Record<string, string>
}
export interface VisualCompareActionableStyleDelta {
property: string
source: string
candidate: string
category: "layout" | "typography" | "paint" | "effect"
severity: "info" | "warning" | "error"
hint: string
}
export interface VisualCompareSelectorDelta {
selector: string
sourcePath: string
candidatePath: string
source: { path: string; tag: string; boundingBox: VisualCompareDomElementSnapshot["boundingBox"] }
candidate: { path: string; tag: string; boundingBox: VisualCompareDomElementSnapshot["boundingBox"] }
boundingBox: { source: VisualCompareDomElementSnapshot["boundingBox"]; candidate: VisualCompareDomElementSnapshot["boundingBox"]; delta: { x: number; y: number; width: number; height: number }; severity: "none" | "info" | "warning" | "error"; category: "layout"; hint: string }
styles: VisualCompareActionableStyleDelta[]
}
interface VisualCompareDimensionDriftRegion extends VisualCompareMismatchRegion {
owner: "source" | "candidate"
}
interface VisualCompareDimensionDrift {
widthDelta: number
heightDelta: number
sourceOnly: VisualCompareDimensionDriftRegion[]
candidateOnly: VisualCompareDimensionDriftRegion[]
}
export type VisualCompareLayoutDriftDivergenceType = "height-delta" | "gap-delta" | "y-offset" | "added-flow-element" | "removed-flow-element" | "screenshot-only"
export interface VisualCompareLayoutDriftAnchor {
path: string
tag: string
text?: string
className?: string
source?: VisualCompareDomElementSnapshot["boundingBox"]
candidate?: VisualCompareDomElementSnapshot["boundingBox"]
delta?: { y?: number; height?: number; gap?: number }
}
export interface VisualCompareLayoutDriftDivergence {
type: VisualCompareLayoutDriftDivergenceType
path?: string
tag?: string
text?: string
className?: string
y?: number
previousPath?: string
source?: VisualCompareDomElementSnapshot["boundingBox"]
candidate?: VisualCompareDomElementSnapshot["boundingBox"]
delta?: { y?: number; height?: number; gap?: number }
}
export interface VisualCompareLayoutDrift {
summary: {
compact: string
firstDivergenceType: VisualCompareLayoutDriftDivergenceType
matchedFlowElements: number
addedFlowElements: number
removedFlowElements: number
changedFlowElements: number
maxAbsYOffset: number
maxAbsHeightDelta: number
maxAbsGapDelta: number
}
firstDivergence: VisualCompareLayoutDriftDivergence
anchors: VisualCompareLayoutDriftAnchor[]
}
interface VisualCompareExplanation {
schema: "wp-codebox/visual-explanation/v1"
source: { label: string; url: string; title: string; elementCount: number; capturedElements: number; truncated: boolean }
candidate: { label: string; url: string; title: string; elementCount: number; capturedElements: number; truncated: boolean }
viewport: BrowserProbeViewport | null
mismatchRegions: VisualCompareMismatchRegion[]
selectors?: Array<{ selector: string; source: VisualCompareSelectorSnapshot; candidate: VisualCompareSelectorSnapshot }>
selectorDeltas?: VisualCompareSelectorDelta[]
missingSelectors?: Array<{ selector: string; sourceMatched: boolean; candidateMatched: boolean; sourceError?: string; candidateError?: string }>
limits: { maxElements: number; maxCandidates: number }
truncation: { changed: boolean; added: boolean; removed: boolean }
summary: { changedElements: number; addedElements: number; removedElements: number; sourceCapturedElements: number; candidateCapturedElements: number }
layoutDrift?: VisualCompareLayoutDrift
changes: VisualCompareElementDelta[]
added: VisualCompareDomElementSnapshot[]
removed: VisualCompareDomElementSnapshot[]
limitations: string[]
}
interface VisualCompareComparisonMetrics {
status?: string
mismatchRatio?: number
mismatchPixels?: number
totalPixels?: number
dimensionMismatch?: boolean
// Dimension-fair signals: overlap region only (the trustworthy ratio) plus the
// canvas-size delta surfaced separately rather than smeared into mismatchRatio.
overlapMismatchRatio?: number
overlapMismatchPixels?: number
overlapPixels?: number
dimensionDeltaPixels?: number
dimensionDeltaRatio?: number
}
interface VisualCompareComparisonSummary extends VisualCompareComparisonMetrics {
source?: { label?: string; url?: string; screenshot?: string }
candidate?: { label?: string; url?: string; screenshot?: string }
}
export interface VisualCompareCaptureDiagnostics {
schema: "wp-codebox/visual-compare-capture-diagnostics/v1"
readiness: {
status: "ready" | "warning"
confidence: "high" | "medium" | "low"
afterSettle: true
reasons: string[]
}
assets: {
stylesheets: { total: number; loaded: number; pending: number; errored: number }
images: { total: number; loaded: number; loading: number; failed: number }
fonts: { status: string; total?: number; loaded?: number; loading?: number; error?: number }
}
environment: {
url: string
title: string
userAgent: string
viewport: { width: number; height: number }
devicePixelRatio: number
colorScheme: string
reducedMotion: boolean
timezone: string
}
dynamicContent: {
fixed: number
sticky: number
video: number
canvas: number
iframe: number
animated: number
focusedElement: boolean
focusedElementTag?: string
}
}
export interface VisualCompareCaptureDiagnosticsCompact {
readiness: "ready" | "warning"
confidence: "high" | "medium" | "low"
reasons: string[]
assets: {
stylesheets: { total: number; pending: number; errored: number }
images: { total: number; loading: number; failed: number }
fonts: { status: string; loading?: number; error?: number }
}
dynamicContent: VisualCompareCaptureDiagnostics["dynamicContent"]
environment: Pick<VisualCompareCaptureDiagnostics["environment"], "url" | "viewport" | "devicePixelRatio" | "colorScheme" | "reducedMotion">
}
interface VisualCompareBaselineDelta {
ref: string
selectedIndex: number
match: "labels" | "only-comparison" | "first-comparison"
availableComparisons: number
baseline: VisualCompareComparisonSummary
delta: {
status?: { baseline?: string; current: string; changed: boolean }
mismatchRatio?: { baseline: number; current: number; absoluteDelta: number; percentDelta?: number }
overlapMismatchRatio?: { baseline: number; current: number; absoluteDelta: number; percentDelta?: number }
mismatchPixels?: { baseline: number; current: number; absoluteDelta: number; percentDelta?: number }
totalPixels?: { baseline: number; current: number; absoluteDelta: number; percentDelta?: number }
dimensionMismatch?: { baseline: boolean; current: boolean; changed: boolean }
}
}
export interface BlocksEngineVisualParityReport {
schema: "blocks-engine/php-transformer/visual-parity-report/v1"
status: "pass" | "warning" | "fail" | "unknown"
severity: "none" | "info" | "warning" | "error" | "critical"
source_render: Record<string, unknown> & { kind: "source" }
target_render: Record<string, unknown> & { kind: "target" }
viewports: Array<{ id: string; label?: string; width: number; height: number; device_scale_factor?: number; source_screenshot_path?: string; target_screenshot_path?: string; diff_screenshot_path?: string }>
matches: Array<{ kind: "generic"; source_selector: string; target_selector: string; confidence: number; viewport_id?: string; selector_evidence?: Record<string, unknown> }>
computed_style_deltas?: Array<{ property: string; severity: "none" | "info" | "warning" | "error" | "critical"; viewport_id?: string; source_selector?: string; target_selector?: string; source_value?: unknown; target_value?: unknown; delta?: unknown }>
visual_diff?: { available: boolean; mismatch_percent?: number; mismatch_pixels?: number; total_pixels?: number; overlap_mismatch_percent?: number; overlap_mismatch_pixels?: number; overlap_pixels?: number; dimension_delta_pixels?: number; threshold?: number; diff_screenshot_path?: string; by_viewport?: Array<{ viewport_id: string; mismatch_percent?: number; overlap_mismatch_percent?: number; mismatch_pixels?: number; diff_screenshot_path?: string }> }
findings: Array<{ id: string; severity: "none" | "info" | "warning" | "error" | "critical"; category: "visual" | "layout" | "style" | "dom" | "interaction" | "content" | "asset" | "accessibility"; summary: string; viewport_id?: string; visual_diff?: { viewport_id: string; mismatch_percent?: number; mismatch_pixels?: number; diff_screenshot_path?: string }; recommendation_ids?: string[] }>
recommendations: Array<{ id: string; priority: "low" | "medium" | "high" | "blocking"; summary: string; rationale?: string; finding_ids?: string[] }>
metadata?: Record<string, unknown>
}
export function blocksEngineVisualParityReportFromVisualCompare(input: {
status?: string
source?: Record<string, unknown>
candidate?: Record<string, unknown>
viewport?: BrowserProbeViewport | null
files?: Record<string, unknown>
comparison?: VisualCompareComparisonMetrics
options?: Record<string, unknown>
captureDiagnostics?: { source?: VisualCompareCaptureDiagnostics; candidate?: VisualCompareCaptureDiagnostics }
explanation?: VisualCompareExplanation
comparisons?: Array<{ name: string; status?: string; source?: Record<string, unknown>; candidate?: Record<string, unknown>; viewport?: BrowserProbeViewport | null; files?: Record<string, unknown>; captureDiagnostics?: { source?: VisualCompareCaptureDiagnostics; candidate?: VisualCompareCaptureDiagnostics }; comparison?: VisualCompareComparisonMetrics }>
metrics?: Record<string, unknown>
command?: string
startedAt?: string
finishedAt?: string
updatedAt?: string
}): BlocksEngineVisualParityReport {
const comparisons = input.comparisons?.length ? input.comparisons : [{ name: "default", status: input.status, source: input.source, candidate: input.candidate, viewport: input.viewport, files: input.files, comparison: input.comparison }]
const completeComparisons = comparisons.filter((comparison) => comparison.comparison)
const status = input.status === "identical" ? "pass" : input.status === "different" ? "fail" : input.status === "partial" ? "warning" : input.status === "missing" || input.status === "failed" ? "unknown" : "unknown"
const severity = status === "pass" ? "none" : status === "fail" ? "error" : status === "warning" ? "warning" : "info"
const first = comparisons[0]
const sourceScreenshot = first?.files?.sourceScreenshot
const targetScreenshot = first?.files?.candidateScreenshot
const diffScreenshot = first?.files?.diffScreenshot
const viewports = comparisons.map((comparison, index) => blocksEngineVisualParityViewport(comparison, index)).filter((viewport): viewport is BlocksEngineVisualParityReport["viewports"][number] => Boolean(viewport))
const fallbackViewport = viewports.length > 0 ? viewports : [blocksEngineVisualParityViewport({ name: "default", viewport: input.viewport, files: input.files }, 0)].filter((viewport): viewport is BlocksEngineVisualParityReport["viewports"][number] => Boolean(viewport))
const findings = completeComparisons.filter((comparison) => (comparison.comparison?.mismatchPixels ?? 0) > 0 || comparison.comparison?.dimensionMismatch).map((comparison, index) => {
const viewport = blocksEngineVisualParityViewport(comparison, index)
const mismatchPercent = typeof comparison.comparison?.mismatchRatio === "number" ? comparison.comparison.mismatchRatio * 100 : undefined
const diffPath = stringFileRef(comparison.files?.diffScreenshot)
return {
id: `visual-diff-${sanitizeVisualCompareMatrixName(comparison.name || String(index + 1))}`,
severity: "error" as const,
category: "visual" as const,
summary: comparison.comparison?.dimensionMismatch ? "Rendered screenshots differ in dimensions." : "Rendered screenshots contain pixel differences.",
...(viewport ? { viewport_id: viewport.id } : {}),
...(viewport ? { visual_diff: { viewport_id: viewport.id, ...(mismatchPercent !== undefined ? { mismatch_percent: mismatchPercent } : {}), ...(typeof comparison.comparison?.mismatchPixels === "number" ? { mismatch_pixels: comparison.comparison.mismatchPixels } : {}), ...(diffPath ? { diff_screenshot_path: diffPath } : {}) } } : {}),
recommendation_ids: ["review-visual-diff"],
}
})
const matches = input.explanation?.selectors?.map((selector) => ({
kind: "generic" as const,
source_selector: selector.selector,
target_selector: selector.selector,
confidence: 1,
...(fallbackViewport[0] ? { viewport_id: fallbackViewport[0].id } : {}),
selector_evidence: {
source_selector: selector.selector,
target_selector: selector.selector,
},
})) ?? []
const computedStyleDeltas = blocksEngineComputedStyleDeltas(input.explanation?.selectorDeltas, fallbackViewport[0]?.id)
return {
schema: "blocks-engine/php-transformer/visual-parity-report/v1",
status,
severity,
source_render: blocksEngineVisualParityRender("source", input.source, stringFileRef(sourceScreenshot)),
target_render: blocksEngineVisualParityRender("target", input.candidate, stringFileRef(targetScreenshot)),
viewports: fallbackViewport,
matches,
...(computedStyleDeltas.length > 0 ? { computed_style_deltas: computedStyleDeltas } : {}),
visual_diff: {
available: completeComparisons.length > 0,
...(typeof input.comparison?.mismatchRatio === "number" ? { mismatch_percent: input.comparison.mismatchRatio * 100 } : {}),
...(typeof input.comparison?.mismatchPixels === "number" ? { mismatch_pixels: input.comparison.mismatchPixels } : {}),
...(typeof input.comparison?.totalPixels === "number" ? { total_pixels: input.comparison.totalPixels } : {}),
...(typeof input.comparison?.overlapMismatchRatio === "number" ? { overlap_mismatch_percent: input.comparison.overlapMismatchRatio * 100 } : {}),
...(typeof input.comparison?.overlapMismatchPixels === "number" ? { overlap_mismatch_pixels: input.comparison.overlapMismatchPixels } : {}),
...(typeof input.comparison?.overlapPixels === "number" ? { overlap_pixels: input.comparison.overlapPixels } : {}),
...(typeof input.comparison?.dimensionDeltaPixels === "number" ? { dimension_delta_pixels: input.comparison.dimensionDeltaPixels } : {}),
...(typeof input.options?.threshold === "number" ? { threshold: input.options.threshold } : {}),
...(stringFileRef(diffScreenshot) ? { diff_screenshot_path: stringFileRef(diffScreenshot) } : {}),
by_viewport: completeComparisons.map((comparison, index) => blocksEngineVisualParityDiffViewport(comparison, index)).filter((viewport): viewport is NonNullable<NonNullable<BlocksEngineVisualParityReport["visual_diff"]>["by_viewport"]>[number] => Boolean(viewport)),
},
findings,
recommendations: findings.length > 0 ? [{ id: "review-visual-diff", priority: "blocking", summary: "Review the visual diff evidence and repair source or target rendering until the parity report passes.", finding_ids: findings.map((finding) => finding.id) }] : [],
metadata: {
producer: "wp-codebox",
source_schema: input.comparisons ? "wp-codebox/visual-compare-matrix/v1" : "wp-codebox/visual-compare/v1",
...(input.command ? { command: input.command } : {}),
...(input.startedAt ? { started_at: input.startedAt } : {}),
...(input.finishedAt ? { finished_at: input.finishedAt } : {}),
...(input.updatedAt ? { updated_at: input.updatedAt } : {}),
...(input.metrics ? { source_metrics: input.metrics } : {}),
...(input.captureDiagnostics ? { capture_diagnostics: visualCompareCompactCaptureDiagnostics(input.captureDiagnostics) } : {}),
},
}
}
function blocksEngineComputedStyleDeltas(selectorDeltas: VisualCompareSelectorDelta[] | undefined, viewportId?: string): NonNullable<BlocksEngineVisualParityReport["computed_style_deltas"]> {
return (selectorDeltas ?? []).flatMap((selectorDelta) => {
const common = {
...(viewportId ? { viewport_id: viewportId } : {}),
source_selector: selectorDelta.selector,
target_selector: selectorDelta.selector,
}
const deltas: NonNullable<BlocksEngineVisualParityReport["computed_style_deltas"]> = []
if (selectorDelta.boundingBox.severity !== "none") {
deltas.push({
property: "bounding-box",
severity: selectorDelta.boundingBox.severity,
...common,
source_value: selectorDelta.boundingBox.source,
target_value: selectorDelta.boundingBox.candidate,
delta: { ...selectorDelta.boundingBox.delta, category: selectorDelta.boundingBox.category, hint: selectorDelta.boundingBox.hint },
})
}
for (const style of selectorDelta.styles) {
deltas.push({
property: style.property,
severity: style.severity,
...common,
source_value: style.source,
target_value: style.candidate,
delta: { category: style.category, hint: style.hint },
})
}
return deltas
})
}
function blocksEngineVisualParityRender(kind: "source", input?: Record<string, unknown>, screenshotPath?: string): BlocksEngineVisualParityReport["source_render"]
function blocksEngineVisualParityRender(kind: "target", input?: Record<string, unknown>, screenshotPath?: string): BlocksEngineVisualParityReport["target_render"]
function blocksEngineVisualParityRender(kind: "source" | "target", input?: Record<string, unknown>, screenshotPath?: string): BlocksEngineVisualParityReport["source_render"] | BlocksEngineVisualParityReport["target_render"] {
return {
kind,
...(typeof input?.url === "string" ? { url: input.url } : {}),
...(typeof input?.finalUrl === "string" ? { ref: input.finalUrl } : {}),
...(typeof input?.label === "string" ? { renderer: input.label } : {}),
...(typeof input?.screenshot === "string" ? { artifact_path: input.screenshot } : {}),
...(screenshotPath ? { screenshot_path: screenshotPath } : {}),
}
}
function blocksEngineVisualParityViewport(input: { name?: string; viewport?: BrowserProbeViewport | null; files?: Record<string, unknown> }, index: number): BlocksEngineVisualParityReport["viewports"][number] | undefined {
const width = input.viewport?.width
const height = input.viewport?.height
if (typeof width !== "number" || typeof height !== "number") {
return undefined
}
const id = sanitizeVisualCompareMatrixName(input.name || `viewport-${index + 1}`)
return {
id,
width,
height,
...(typeof input.viewport?.deviceScaleFactor === "number" ? { device_scale_factor: input.viewport.deviceScaleFactor } : {}),
...(stringFileRef(input.files?.sourceScreenshot) ? { source_screenshot_path: stringFileRef(input.files?.sourceScreenshot) } : {}),
...(stringFileRef(input.files?.candidateScreenshot) ? { target_screenshot_path: stringFileRef(input.files?.candidateScreenshot) } : {}),
...(stringFileRef(input.files?.diffScreenshot) ? { diff_screenshot_path: stringFileRef(input.files?.diffScreenshot) } : {}),
}
}
function blocksEngineVisualParityDiffViewport(input: { name?: string; viewport?: BrowserProbeViewport | null; files?: Record<string, unknown>; comparison?: VisualCompareComparisonMetrics }, index: number): NonNullable<NonNullable<BlocksEngineVisualParityReport["visual_diff"]>["by_viewport"]>[number] | undefined {
const viewport = blocksEngineVisualParityViewport(input, index)
if (!viewport || !input.comparison) {
return undefined
}
return {
viewport_id: viewport.id,
...(typeof input.comparison.mismatchRatio === "number" ? { mismatch_percent: input.comparison.mismatchRatio * 100 } : {}),
...(typeof input.comparison.overlapMismatchRatio === "number" ? { overlap_mismatch_percent: input.comparison.overlapMismatchRatio * 100 } : {}),
...(typeof input.comparison.mismatchPixels === "number" ? { mismatch_pixels: input.comparison.mismatchPixels } : {}),
...(stringFileRef(input.files?.diffScreenshot) ? { diff_screenshot_path: stringFileRef(input.files?.diffScreenshot) } : {}),
}
}
function stringFileRef(value: unknown): string | undefined {
if (typeof value === "string" && value) {
return value
}
if (Array.isArray(value) && typeof value[0] === "string" && value[0]) {
return value[0]
}
return undefined
}
export async function runVisualCompareCommand({
artifactRoot,
runtimeSpec,
server,
spec,
}: {
artifactRoot: string
runtimeSpec?: RuntimeCreateSpec
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<{ artifact: BrowserArtifact; output: string }> {
const args = spec.args ?? []
const matrixJson = argValue(args, "matrix-json")?.trim()
if (matrixJson) {
return runVisualCompareMatrixCommand({ artifactRoot, runtimeSpec, server, args, matrixJson })
}
return runVisualComparePairCommand({ artifactRoot, runtimeSpec, server, args })
}
async function runVisualComparePairCommand({
artifactRoot,
runtimeSpec,
server,
args,
artifactPathPrefix = "files/browser/visual-compare",
}: {
artifactRoot: string
runtimeSpec?: RuntimeCreateSpec
server: PlaygroundCliServer
args: string[]
artifactPathPrefix?: string
}): Promise<{ artifact: BrowserArtifact; output: string }> {
const sourceUrl = argValue(args, "source-url")?.trim()
const candidateUrl = argValue(args, "candidate-url")?.trim()
const sourceScreenshot = argValue(args, "source-screenshot")?.trim()
const candidateScreenshot = argValue(args, "candidate-screenshot")?.trim()
const sourceDomSnapshotRef = argValue(args, "source-dom-snapshot")?.trim()
const candidateDomSnapshotRef = argValue(args, "candidate-dom-snapshot")?.trim()
const baselineRef = argValue(args, "baseline")?.trim()
const sourceLabel = argValue(args, "source-label")?.trim() || "source"
const candidateLabel = argValue(args, "candidate-label")?.trim() || "candidate"
const waitFor = argValue(args, "wait-for")?.trim() || "domcontentloaded"
const durationMs = durationArg(args, "duration", 0)
const visualTimeoutMs = durationArg(args, "timeout", browserCommandLivenessPolicy().wallTimeoutMs)
const requestedViewport = viewportArg(args, "viewport")
const fullPage = strictBooleanArg(args, "full-page", true)
const maxFullPageHeight = positiveIntegerArg(args, "max-full-page-height", VISUAL_COMPARE_MAX_FULL_PAGE_HEIGHT_PX)
const threshold = numberArg(args, "threshold", 0.1)
const includeAA = strictBooleanArg(args, "include-aa", false)
const maxRegions = positiveIntegerArg(args, "max-regions", 8)
const maxExplanationElements = positiveIntegerArg(args, "max-explanation-elements", 25)
const maxExplanationCandidates = positiveIntegerArg(args, "max-explanation-candidates", 160)
const explainSelectors = visualCompareExplainSelectors(args)
// Disposable WP Codebox sandboxes have no outbound network egress. A captured
// page that references external resources (Google Fonts, CDNs, analytics) would
// otherwise leave those requests hanging until the navigation/screenshot hits
// the wall timeout, surfacing as a `capture-failed`/timeout even though the
// local document served fine. Aborting cross-origin requests up front makes
// both targets render deterministically (offline, system-font fallback) and
// fast. On by default; `block-external-requests=false` opts back into the live
// (egress-dependent) behavior.
const blockExternalRequests = strictBooleanArg(args, "block-external-requests", true)
if (threshold < 0 || threshold > 1) {
throw new Error("threshold must be between 0 and 1")
}
if (Boolean(sourceUrl) !== Boolean(candidateUrl) || Boolean(sourceScreenshot) !== Boolean(candidateScreenshot)) {
throw new Error("wordpress.visual-compare requires source-url and candidate-url, or source-screenshot and candidate-screenshot")
}
if (Boolean(sourceDomSnapshotRef) !== Boolean(candidateDomSnapshotRef)) {
throw new Error("wordpress.visual-compare requires both source-dom-snapshot and candidate-dom-snapshot when DOM snapshots are provided")
}
if (!sourceUrl && !sourceScreenshot) {
throw new Error("wordpress.visual-compare requires source-url/candidate-url or source-screenshot/candidate-screenshot")
}
const artifactSession = new BrowserArtifactSession(artifactRoot, artifactPathPrefix, { source: "wordpress.visual-compare", operation: "visual-compare" })
const sourcePath = artifactSession.absolutePath("source.png")
const candidatePath = artifactSession.absolutePath("candidate.png")
const diffPath = artifactSession.absolutePath("diff.png")
const startedAt = now()
const preview = browserPreviewRouting(args, runtimeSpec, server.serverUrl)
const sourceTargetUrl = sourceUrl ? resolveBrowserPreviewUrl(sourceUrl, preview.effectiveOrigin) : undefined
const candidateTargetUrl = candidateUrl ? resolveBrowserPreviewUrl(candidateUrl, preview.effectiveOrigin) : undefined
let finalSourceUrl = sourceTargetUrl
let finalCandidateUrl = candidateTargetUrl
let viewport: BrowserProbeViewport | null = null
let sourceDomSnapshot: VisualCompareDomSnapshot | undefined
let candidateDomSnapshot: VisualCompareDomSnapshot | undefined
let captureDiagnostics: { source?: VisualCompareCaptureDiagnostics; candidate?: VisualCompareCaptureDiagnostics } | undefined
const sourceSummary = (): Record<string, unknown> => ({
label: sourceLabel,
...(sourceUrl ? { url: sourceUrl, finalUrl: finalSourceUrl } : {}),
...(sourceScreenshot ? { screenshot: sourceScreenshot } : {}),
...(sourceDomSnapshotRef ? { domSnapshot: sourceDomSnapshotRef } : {}),
})
const candidateSummary = (): Record<string, unknown> => ({
label: candidateLabel,
...(candidateUrl ? { url: candidateUrl, finalUrl: finalCandidateUrl } : {}),
...(candidateScreenshot ? { screenshot: candidateScreenshot } : {}),
...(candidateDomSnapshotRef ? { domSnapshot: candidateDomSnapshotRef } : {}),
})
const writePartialSummary = async (stage: "source-captured" | "candidate-captured"): Promise<void> => {
await writeVisualComparePartialSummary(artifactSession, {
artifactPathPrefix,
stage,
startedAt,
source: sourceSummary(),
candidate: candidateSummary(),
options: { waitFor, durationMs, timeoutMs: visualTimeoutMs, fullPage, maxFullPageHeight, threshold, includeAA, maxRegions, maxExplanationElements, maxExplanationCandidates, ...(explainSelectors.length > 0 ? { explainSelectors } : {}) },
preview,
viewport,
})
}
if (sourceTargetUrl && candidateTargetUrl) {
const browser = await launchChromiumBrowser()
try {
const page = await browser.newPage(requestedViewport ? { viewport: requestedViewport } : undefined)
if (blockExternalRequests) {
await installVisualCompareOfflineIsolation(page, preview.effectiveOrigin)
}
// Determinism applies to BOTH source and candidate: the init script runs on
// every navigation of this shared page, so source and candidate are captured
// under identical reveal/animation conditions.
await installVisualCompareDeterministicReveal(page)
viewport = await browserProbeViewport(page)
try {
let sourceCapture: Awaited<ReturnType<typeof captureVisualCompareUrl>> | undefined
await artifactSession.writeGenerated("sourceScreenshot", "source.png", async (path) => {
sourceCapture = await withBrowserCommandLiveness({
command: "wordpress.visual-compare",
phase: "source-capture",
operation: captureVisualCompareUrl(page, sourceTargetUrl, path, waitFor, durationMs, fullPage, maxFullPageHeight, maxExplanationCandidates, explainSelectors, visualTimeoutMs),
policy: { wallTimeoutMs: visualTimeoutMs, idleTimeoutMs: 0 },
})
})
if (!sourceCapture) {
throw new Error("wordpress.visual-compare did not produce source capture")
}
finalSourceUrl = sourceCapture.finalUrl
sourceDomSnapshot = sourceCapture.domSnapshot
const sourceCaptureDiagnostics = sourceCapture.captureDiagnostics
await writePartialSummary("source-captured")
let candidateCapture: Awaited<ReturnType<typeof captureVisualCompareUrl>> | undefined
await artifactSession.writeGenerated("candidateScreenshot", "candidate.png", async (path) => {
candidateCapture = await withBrowserCommandLiveness({
command: "wordpress.visual-compare",
phase: "candidate-capture",
operation: captureVisualCompareUrl(page, candidateTargetUrl, path, waitFor, durationMs, fullPage, maxFullPageHeight, maxExplanationCandidates, explainSelectors, visualTimeoutMs),
policy: { wallTimeoutMs: visualTimeoutMs, idleTimeoutMs: 0 },
})
})
if (!candidateCapture) {
throw new Error("wordpress.visual-compare did not produce candidate capture")
}
finalCandidateUrl = candidateCapture.finalUrl
candidateDomSnapshot = candidateCapture.domSnapshot
const candidateCaptureDiagnostics = candidateCapture.captureDiagnostics
captureDiagnostics = { source: sourceCaptureDiagnostics, candidate: candidateCaptureDiagnostics }
await writePartialSummary("candidate-captured")
} catch (error) {
const result = await writeVisualCompareFailureSummary({
artifactSession,
artifactPathPrefix,
startedAt,
source: sourceSummary(),
candidate: candidateSummary(),
options: { waitFor, durationMs, timeoutMs: visualTimeoutMs, fullPage, maxFullPageHeight, threshold, includeAA, maxRegions, maxExplanationElements, maxExplanationCandidates, ...(explainSelectors.length > 0 ? { explainSelectors } : {}) },
preview,
viewport,
message: visualCompareErrorDetail(error),
copiedFiles: {
...(await fileExists(sourcePath) ? { sourceScreenshot: `${artifactPathPrefix}/source.png` } : {}),
...(await fileExists(candidatePath) ? { candidateScreenshot: `${artifactPathPrefix}/candidate.png` } : {}),
},
})
throw new BrowserCommandArtifactError(`wordpress.visual-compare failed during capture: ${visualCompareErrorDetail(error)}`, visualCompareFailureArtifact({ source: sourceSummary(), candidate: candidateSummary(), preview, viewport, files: result.files, summary: result.summary }))
}
} finally {
await browser.close()
}
} else if (sourceScreenshot && candidateScreenshot) {
const sourceResolvedPath = await maybeResolveVisualCompareScreenshotPath(sourceScreenshot, artifactRoot)
const candidateResolvedPath = await maybeResolveVisualCompareScreenshotPath(candidateScreenshot, artifactRoot)
const missingInputs = visualCompareMissingScreenshotInputs({ sourceScreenshot, candidateScreenshot, sourceResolvedPath, candidateResolvedPath })
if (missingInputs.length > 0) {
const copiedFiles: Partial<{ sourceScreenshot: string; candidateScreenshot: string }> = {}
if (sourceResolvedPath) {
await artifactSession.writeBuffer("sourceScreenshot", "source.png", await readFile(sourceResolvedPath))
copiedFiles.sourceScreenshot = `${artifactPathPrefix}/source.png`
}
if (candidateResolvedPath) {
await artifactSession.writeBuffer("candidateScreenshot", "candidate.png", await readFile(candidateResolvedPath))
copiedFiles.candidateScreenshot = `${artifactPathPrefix}/candidate.png`
}
const result = await writeVisualCompareMissingInputSummary({
artifactSession,
artifactPathPrefix,
startedAt,
source: sourceSummary(),
candidate: candidateSummary(),
options: { waitFor, durationMs, timeoutMs: visualTimeoutMs, fullPage, maxFullPageHeight, threshold, includeAA, maxRegions, maxExplanationElements, maxExplanationCandidates, ...(explainSelectors.length > 0 ? { explainSelectors } : {}) },
preview,
viewport,
missingInputs,
copiedFiles,
})
throw new BrowserCommandArtifactError("wordpress.visual-compare missing expected screenshot input", visualCompareMissingInputArtifact({ source: sourceSummary(), candidate: candidateSummary(), preview, viewport, files: result.files, summary: result.summary }))
}
const resolvedSourceScreenshotPath = sourceResolvedPath
const resolvedCandidateScreenshotPath = candidateResolvedPath
if (!resolvedSourceScreenshotPath || !resolvedCandidateScreenshotPath) {
throw new Error("wordpress.visual-compare expected screenshot inputs to be resolved after missing-input guard")
}
await artifactSession.writeBuffer("sourceScreenshot", "source.png", await readFile(resolvedSourceScreenshotPath))
await writePartialSummary("source-captured")
await artifactSession.writeBuffer("candidateScreenshot", "candidate.png", await readFile(resolvedCandidateScreenshotPath))
if (sourceDomSnapshotRef && candidateDomSnapshotRef) {
const sourceArtifact = await readVisualCompareDomSnapshotArtifact(sourceDomSnapshotRef, artifactRoot)
const candidateArtifact = await readVisualCompareDomSnapshotArtifact(candidateDomSnapshotRef, artifactRoot)
sourceDomSnapshot = sourceArtifact.snapshot
candidateDomSnapshot = candidateArtifact.snapshot
finalSourceUrl = sourceArtifact.finalUrl || sourceArtifact.snapshot.url
finalCandidateUrl = candidateArtifact.finalUrl || candidateArtifact.snapshot.url
viewport = candidateArtifact.viewport ?? sourceArtifact.viewport ?? viewport
}
await writePartialSummary("candidate-captured")
}
let comparison: Awaited<ReturnType<typeof comparePngFiles>> | undefined
await artifactSession.writeGenerated("diffScreenshot", "diff.png", async (path) => {
comparison = await comparePngFiles(sourcePath, candidatePath, path, { threshold, includeAA, maxRegions })
})
if (!comparison) {
throw new Error("wordpress.visual-compare did not produce comparison metrics")
}
const explanation = createVisualCompareExplanation({
source: sourceDomSnapshot,
candidate: candidateDomSnapshot,
sourceLabel,
candidateLabel,
viewport,
comparison,
limits: { maxElements: maxExplanationElements, maxCandidates: maxExplanationCandidates },
explainSelectors,
})
const finishedAt = now()
const status = comparison.mismatchPixels === 0 && !comparison.dimensionMismatch ? "identical" : "different"
const baseline = baselineRef
? await createVisualCompareBaselineDelta({
baselineRef,
artifactRoot,
current: { status, comparison, source: sourceSummary(), candidate: candidateSummary() },
})
: undefined
const files = {
sourceScreenshot: `${artifactPathPrefix}/source.png`,
candidateScreenshot: `${artifactPathPrefix}/candidate.png`,
...(sourceDomSnapshot && candidateDomSnapshot ? {
sourceDomSnapshot: `${artifactPathPrefix}/source-dom-snapshot.json`,
candidateDomSnapshot: `${artifactPathPrefix}/candidate-dom-snapshot.json`,
} : {}),
diffScreenshot: `${artifactPathPrefix}/diff.png`,
visualDiff: `${artifactPathPrefix}/visual-diff.json`,
...(explanation ? { visualExplanation: `${artifactPathPrefix}/visual-explanation.json` } : {}),
blocksEngineVisualParity: `${artifactPathPrefix}/blocks-engine-visual-parity-report.json`,
summary: `${artifactPathPrefix}/summary.json`,
}
const summary = {
schema: "wp-codebox/visual-compare/v1",
command: "wordpress.visual-compare",
status,
source: sourceSummary(),
candidate: candidateSummary(),
options: { waitFor, durationMs, timeoutMs: visualTimeoutMs, fullPage, maxFullPageHeight, threshold, includeAA, maxRegions, maxExplanationElements, maxExplanationCandidates, ...(explainSelectors.length > 0 ? { explainSelectors } : {}) },
limitations: explanation
? explanation.limitations
: ["visual explanations require source-url/candidate-url targets or source-dom-snapshot/candidate-dom-snapshot sidecars so WP Codebox can include DOM and computed style context; screenshot-only comparisons include pixel evidence only"],
preview,
viewport,
startedAt,
finishedAt,
files,
hashes: {
sourceScreenshot: { algorithm: "sha256", value: await fileSha256(sourcePath) },
candidateScreenshot: { algorithm: "sha256", value: await fileSha256(candidatePath) },
diffScreenshot: { algorithm: "sha256", value: await fileSha256(diffPath) },
},
...(captureDiagnostics ? { captureDiagnostics } : {}),
comparison,
...(baseline ? { baseline } : {}),
}
const blocksEngineVisualParity = blocksEngineVisualParityReportFromVisualCompare({ ...summary, explanation })
const summaryWithBlocksEngineVisualParity = { ...summary, blocksEngineVisualParity }
if (sourceDomSnapshot && candidateDomSnapshot) {
await artifactSession.writeJson("sourceDomSnapshot", "source-dom-snapshot.json", visualCompareDomSnapshotArtifact({
screenshot: files.sourceScreenshot,
finalUrl: finalSourceUrl ?? sourceDomSnapshot.url,
viewport,
maxElements: maxExplanationCandidates,
snapshot: sourceDomSnapshot,
}))
await artifactSession.writeJson("candidateDomSnapshot", "candidate-dom-snapshot.json", visualCompareDomSnapshotArtifact({
screenshot: files.candidateScreenshot,
finalUrl: finalCandidateUrl ?? candidateDomSnapshot.url,
viewport,
maxElements: maxExplanationCandidates,
snapshot: candidateDomSnapshot,
}))
}
await artifactSession.writeJson("visualDiff", "visual-diff.json", summaryWithBlocksEngineVisualParity)
if (explanation) {
await artifactSession.writeJson("visualExplanation", "visual-explanation.json", explanation)
}
await artifactSession.writeJson("blocksEngineVisualParity", "blocks-engine-visual-parity-report.json", blocksEngineVisualParity)
await artifactSession.writeJson("summary", "summary.json", summaryWithBlocksEngineVisualParity)
const artifact: BrowserArtifact = {
artifactType: "visual-compare",
requestedUrl: sourceTargetUrl ?? sourceScreenshot ?? sourceLabel,
url: candidateTargetUrl ?? candidateScreenshot ?? candidateLabel,
preview,
files,
summary: {
steps: 0,
consoleMessages: 0,
errors: 0,
finalUrl: finalCandidateUrl ?? finalSourceUrl ?? "",
htmlSnapshot: false,
networkEvents: 0,
replayability: "artifact-backed",
screenshot: true,
visualCompare: {
status: summary.status,
mismatchRatio: comparison.mismatchRatio,
mismatchPixels: comparison.mismatchPixels,
totalPixels: comparison.totalPixels,
overlapMismatchRatio: comparison.overlapMismatchRatio,
overlapMismatchPixels: comparison.overlapMismatchPixels,
overlapPixels: comparison.overlapPixels,
dimensionDeltaPixels: comparison.dimensionDeltaPixels,
dimensionDeltaRatio: comparison.dimensionDeltaRatio,
dimensionMismatch: comparison.dimensionMismatch,
...(captureDiagnostics ? { captureDiagnostics: visualCompareCompactCaptureDiagnostics(captureDiagnostics) } : {}),
...(explanation ? { explanation: files.visualExplanation } : {}),
blocksEngineVisualParity: files.blocksEngineVisualParity,
},
viewport,
},
}
return {
artifact,
output: `${JSON.stringify(summaryWithBlocksEngineVisualParity, null, 2)}\n`,
}
}
async function runVisualCompareMatrixCommand({
artifactRoot,
runtimeSpec,
server,
args,
matrixJson,
}: {
artifactRoot: string
runtimeSpec?: RuntimeCreateSpec
server: PlaygroundCliServer
args: string[]
matrixJson: string
}): Promise<{ artifact: BrowserArtifact; output: string }> {
const matrix = normalizeVisualCompareMatrixSpec(JSON.parse(matrixJson))
const baseArgs = args.filter((arg) => !arg.startsWith("matrix-json="))
const startedAt = now()
const entries: Array<{ name: string; artifact: BrowserArtifact; summary: VisualComparePairSummary }> = []
const failedEntries: VisualCompareMatrixFailedEntry[] = []
for (const entry of matrix.entries) {
const entryArgs = mergeVisualCompareMatrixArgs(baseArgs, entry.args)
try {
const result = await runVisualComparePairCommand({
artifactRoot,
runtimeSpec,
server,
args: entryArgs,
artifactPathPrefix: `files/browser/visual-compare/${entry.name}`,
})
entries.push({ name: entry.name, artifact: result.artifact, summary: JSON.parse(result.output) as VisualComparePairSummary })
await writeVisualCompareMatrixSummary(artifactRoot, args, runtimeSpec, server, matrix.entries, entries, failedEntries, startedAt, false)
} catch (error) {
failedEntries.push(await createVisualCompareMatrixFailedEntry(entry.name, entryArgs, artifactRoot, error))
const matrixSummary = await writeVisualCompareMatrixSummary(artifactRoot, args, runtimeSpec, server, matrix.entries, entries, failedEntries, startedAt, false)
throw new BrowserCommandArtifactError(`wordpress.visual-compare matrix incomplete: ${errorMessage(error)}`, visualCompareMatrixArtifact(args, runtimeSpec, server, matrix.entries, entries, matrixSummary))
}
}
const matrixSummary = await writeVisualCompareMatrixSummary(artifactRoot, args, runtimeSpec, server, matrix.entries, entries, failedEntries, startedAt, true)
const artifact = visualCompareMatrixArtifact(args, runtimeSpec, server, matrix.entries, entries, matrixSummary)
return {
artifact,
output: `${JSON.stringify(matrixSummary, null, 2)}\n`,
}
}
function visualCompareMatrixArtifact(
args: string[],
runtimeSpec: RuntimeCreateSpec | undefined,
server: PlaygroundCliServer,
expectedEntries: VisualCompareMatrixEntry[],
entries: Array<{ name: string; artifact: BrowserArtifact; summary: VisualComparePairSummary }>,
matrixSummary: VisualCompareMatrixSummary,
): BrowserArtifact {
const sourceScreenshots = entries.map((entry) => entry.artifact.files.sourceScreenshot).filter((file): file is string => typeof file === "string")
const candidateScreenshots = entries.map((entry) => entry.artifact.files.candidateScreenshot).filter((file): file is string => typeof file === "string")
const diffScreenshots = entries.map((entry) => entry.artifact.files.diffScreenshot).filter((file): file is string => typeof file === "string")
const visualDiffs = entries.map((entry) => entry.artifact.files.visualDiff).filter((file): file is string => typeof file === "string")
const visualExplanations = entries.map((entry) => entry.artifact.files.visualExplanation).filter((file): file is string => typeof file === "string")
const sourceDomSnapshots = entries.map((entry) => entry.artifact.files.sourceDomSnapshot).filter((file): file is string => typeof file === "string")
const candidateDomSnapshots = entries.map((entry) => entry.artifact.files.candidateDomSnapshot).filter((file): file is string => typeof file === "string")
const firstArtifact = entries[0]?.artifact
const captureDiagnostics = visualCompareMatrixCompactCaptureDiagnostics(matrixSummary)
return {
artifactType: "visual-compare",
requestedUrl: expectedEntries.map((entry) => entry.name).join(","),
url: firstArtifact?.url ?? "visual-compare-matrix",
preview: firstArtifact?.preview ?? browserPreviewRouting(args, runtimeSpec, server.serverUrl),
files: {
summary: matrixSummary.files.summary,
...(matrixSummary.files.blocksEngineVisualParity ? { blocksEngineVisualParity: matrixSummary.files.blocksEngineVisualParity } : {}),
visualDiff: visualDiffs,
sourceScreenshot: sourceScreenshots,
candidateScreenshot: candidateScreenshots,
...(sourceDomSnapshots.length > 0 ? { sourceDomSnapshot: sourceDomSnapshots } : {}),
...(candidateDomSnapshots.length > 0 ? { candidateDomSnapshot: candidateDomSnapshots } : {}),
diffScreenshot: diffScreenshots,
...(visualExplanations.length > 0 ? { visualExplanation: visualExplanations } : {}),
},
summary: {
steps: 0,
consoleMessages: entries.reduce((total, entry) => total + entry.artifact.summary.consoleMessages, 0),
errors: entries.reduce((total, entry) => total + entry.artifact.summary.errors, 0),
finalUrl: firstArtifact?.summary.finalUrl ?? "",
htmlSnapshot: false,
networkEvents: entries.reduce((total, entry) => total + entry.artifact.summary.networkEvents, 0),
replayability: "artifact-backed",
screenshot: entries.length > 0,
visualCompare: {
status: matrixSummary.status,
mismatchRatio: matrixSummary.metrics.maxMismatchRatio,
mismatchPixels: matrixSummary.metrics.maxMismatchPixels,
totalPixels: matrixSummary.comparisons.reduce((total, entry) => total + (entry.comparison?.totalPixels ?? 0), 0),
overlapMismatchRatio: matrixSummary.metrics.maxOverlapMismatchRatio,
dimensionMismatch: matrixSummary.comparisons.some((entry) => entry.comparison?.dimensionMismatch === true),
...(captureDiagnostics ? { captureDiagnostics } : {}),
explanation: matrixSummary.files.summary,
...(matrixSummary.files.blocksEngineVisualParity ? { blocksEngineVisualParity: matrixSummary.files.blocksEngineVisualParity } : {}),
},
viewport: firstArtifact?.summary.viewport ?? null,
},
}
}
async function writeVisualComparePartialSummary(artifactSession: BrowserArtifactSession, input: {
artifactPathPrefix: string
stage: "source-captured" | "candidate-captured"
startedAt: string
source: Record<string, unknown>
candidate: Record<string, unknown>
options: Record<string, unknown>
preview: ReturnType<typeof browserPreviewRouting>
viewport: BrowserProbeViewport | null
}): Promise<void> {
const files = {
sourceScreenshot: `${input.artifactPathPrefix}/source.png`,
...(input.stage === "candidate-captured" ? { candidateScreenshot: `${input.artifactPathPrefix}/candidate.png` } : {}),
summary: `${input.artifactPathPrefix}/summary.json`,
}
const summary = {
schema: "wp-codebox/visual-compare/v1",
command: "wordpress.visual-compare",
status: "partial",
partial: true,
stage: input.stage,
source: input.source,
candidate: input.candidate,
options: input.options,
limitations: ["visual compare was interrupted before full diff metrics were available; recovered files show the latest completed capture stage"],
preview: input.preview,
viewport: input.viewport,
startedAt: input.startedAt,
updatedAt: now(),
files,
}
await artifactSession.writeJson("summary", "summary.json", summary)
}
async function writeVisualCompareMissingInputSummary(input: {
artifactSession: BrowserArtifactSession
artifactPathPrefix: string
startedAt: string
source: Record<string, unknown>
candidate: Record<string, unknown>
options: Record<string, unknown>
preview: ReturnType<typeof browserPreviewRouting>
viewport: BrowserProbeViewport | null
missingInputs: VisualCompareMissingInput[]
copiedFiles: Partial<{ sourceScreenshot: string; candidateScreenshot: string }>
}): Promise<{ files: { sourceScreenshot: string | string[]; candidateScreenshot: string | string[]; diffScreenshot: string | string[]; visualDiff: string; blocksEngineVisualParity: string; summary: string }; summary: VisualCompareMissingInputSummary & { blocksEngineVisualParity: BlocksEngineVisualParityReport } }> {
const files = {
sourceScreenshot: input.copiedFiles.sourceScreenshot ?? [],
candidateScreenshot: input.copiedFiles.candidateScreenshot ?? [],
diffScreenshot: [],
visualDiff: `${input.artifactPathPrefix}/visual-diff.json`,
blocksEngineVisualParity: `${input.artifactPathPrefix}/blocks-engine-visual-parity-report.json`,
summary: `${input.artifactPathPrefix}/summary.json`,
}
const summary: VisualCompareMissingInputSummary = {
schema: "wp-codebox/visual-compare/v1",
command: "wordpress.visual-compare",
status: "missing",
partial: true,
stage: "missing-input",
source: input.source,
candidate: input.candidate,
options: input.options,
limitations: ["visual compare could not run because one or more expected screenshot inputs were missing; recovered files show any screenshots that were available before comparison"],
preview: input.preview,
viewport: input.viewport,
startedAt: input.startedAt,
updatedAt: now(),
files,
diagnostic: {
type: "missing-input",
message: "Visual compare is missing expected screenshot input.",
missingInputs: input.missingInputs,
},
}
const blocksEngineVisualParity = blocksEngineVisualParityReportFromVisualCompare(summary)
const summaryWithBlocksEngineVisualParity = { ...summary, blocksEngineVisualParity }
await input.artifactSession.writeJson("visualDiff", "visual-diff.json", summaryWithBlocksEngineVisualParity)
await input.artifactSession.writeJson("blocksEngineVisualParity", "blocks-engine-visual-parity-report.json", blocksEngineVisualParity)
await input.artifactSession.writeJson("summary", "summary.json", summaryWithBlocksEngineVisualParity)
return { files, summary: summaryWithBlocksEngineVisualParity }
}
async function writeVisualCompareFailureSummary(input: {
artifactSession: BrowserArtifactSession
artifactPathPrefix: string
startedAt: string
source: Record<string, unknown>
candidate: Record<string, unknown>
options: Record<string, unknown>
preview: ReturnType<typeof browserPreviewRouting>
viewport: BrowserProbeViewport | null
message: string
copiedFiles: Partial<{ sourceScreenshot: string; candidateScreenshot: string }>
}): Promise<{ files: { sourceScreenshot: string | string[]; candidateScreenshot: string | string[]; diffScreenshot: string | string[]; visualDiff: string; blocksEngineVisualParity: string; summary: string }; summary: VisualCompareFailureSummary & { blocksEngineVisualParity: BlocksEngineVisualParityReport } }> {
const files = {
sourceScreenshot: input.copiedFiles.sourceScreenshot ?? [],
candidateScreenshot: input.copiedFiles.candidateScreenshot ?? [],
diffScreenshot: [],
visualDiff: `${input.artifactPathPrefix}/visual-diff.json`,
blocksEngineVisualParity: `${input.artifactPathPrefix}/blocks-engine-visual-parity-report.json`,
summary: `${input.artifactPathPrefix}/summary.json`,
}
const summary: VisualCompareFailureSummary = {
schema: "wp-codebox/visual-compare/v1",
command: "wordpress.visual-compare",
status: "failed",
partial: true,
stage: "capture-failed",
source: input.source,
candidate: input.candidate,
options: input.options,
limitations: ["visual compare capture failed before full diff metrics were available; recovered files show any screenshots captured before failure"],
preview: input.preview,
viewport: input.viewport,
startedAt: input.startedAt,
updatedAt: now(),