Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

diff.ts

455 lines14.5 KB

1import * as Schema from "effect/Schema";
2​
3export const AuditPlatformSchema = Schema.Literals(["ios", "android"]);
4export type AuditPlatform = typeof AuditPlatformSchema.Type;
5​
6const AuditRectSchema = Schema.Struct({
7 x: Schema.Number,
8 y: Schema.Number,
9 width: Schema.Number,
10 height: Schema.Number,
11});
12export type AuditRect = typeof AuditRectSchema.Type;
13​
14const ViewportSchema = Schema.Struct({
15 width: Schema.Number,
16 height: Schema.Number,
17});
18export type AuditViewport = typeof ViewportSchema.Type;
19​
20const SmallTargetDetailSchema = Schema.Struct({
21 unit: Schema.String,
22 width: Schema.Number,
23 height: Schema.Number,
24 recommendedSize: Schema.Number,
25});
26​
27const AmbiguousNameDetailSchema = Schema.Struct({
28 name: Schema.String,
29 count: Schema.Number,
30});
31​
32const AuditFindingSchema = Schema.Struct({
33 ref: Schema.String,
34 kind: Schema.String,
35 severity: Schema.optional(Schema.String),
36 role: Schema.String,
37 label: Schema.optional(Schema.String),
38 identifier: Schema.optional(Schema.String),
39 rect: Schema.optional(AuditRectSchema),
40 detail: Schema.optional(Schema.Unknown),
41});
42export type AuditFinding = typeof AuditFindingSchema.Type;
43​
44const RawSnapshotNodeSchema = Schema.Struct({
45 index: Schema.Number,
46 parentIndex: Schema.optional(Schema.Number),
47 ref: Schema.optional(Schema.String),
48 type: Schema.optional(Schema.String),
49 role: Schema.optional(Schema.String),
50 label: Schema.optional(Schema.String),
51 identifier: Schema.optional(Schema.String),
52 contentDescription: Schema.optional(Schema.String),
53 text: Schema.optional(Schema.String),
54 rect: Schema.optional(AuditRectSchema),
55 enabled: Schema.optional(Schema.Boolean),
56 hittable: Schema.optional(Schema.Boolean),
57 visibleToUser: Schema.optional(Schema.Boolean),
58 keyboardOwned: Schema.optional(Schema.Boolean),
59 systemBar: Schema.optional(Schema.String),
60});
61export type RawSnapshotNode = typeof RawSnapshotNodeSchema.Type;
62​
63export const RawSnapshotDataSchema = Schema.Struct({
64 nodes: Schema.Array(RawSnapshotNodeSchema),
65 viewport: Schema.optional(ViewportSchema),
66 androidSnapshot: Schema.optional(
67 Schema.Struct({
68 pixelDensity: Schema.optional(Schema.Number),
69 backend: Schema.optional(Schema.String),
70 }),
71 ),
72});
73export type RawSnapshotData = typeof RawSnapshotDataSchema.Type;
74​
75export const AuditPayloadSchema = Schema.Struct({
76 findings: Schema.optional(Schema.Array(AuditFindingSchema)),
77 guidance: Schema.optional(Schema.Record(Schema.String, Schema.String)),
78 limitations: Schema.optional(Schema.Array(Schema.String)),
79});
80​
81export const AuditCaptureSchema = Schema.Struct({
82 platform: AuditPlatformSchema,
83 screen: Schema.String,
84 viewport: Schema.optional(ViewportSchema),
85 pixelDensity: Schema.Number,
86 findings: Schema.Array(AuditFindingSchema),
87 guidance: Schema.optional(Schema.Record(Schema.String, Schema.String)),
88 limitations: Schema.optional(Schema.Array(Schema.String)),
89});
90export type AuditCapture = typeof AuditCaptureSchema.Type;
91​
92export const AgentDeviceEnvelopeSchema = Schema.Struct({
93 success: Schema.optional(Schema.Boolean),
94 data: Schema.optional(Schema.Unknown),
95 error: Schema.optional(
96 Schema.Struct({
97 message: Schema.optional(Schema.String),
98 hint: Schema.optional(Schema.String),
99 }),
100 ),
101});
102​
103export interface FixedFinding {
104 readonly before: AuditFinding;
105 readonly afterNode?: RawSnapshotNode | undefined;
106 readonly afterMeasurement?: string | undefined;
108​
109export interface ScreenDiff {
110 readonly platform: AuditPlatform;
111 readonly screen: string;
112 readonly pixelDensity: number;
113 readonly beforeCount: number;
114 readonly afterCount: number;
115 readonly regressions: ReadonlyArray<AuditFinding>;
116 readonly fixed: ReadonlyArray<FixedFinding>;
117 readonly unchanged: ReadonlyArray<AuditFinding>;
118 readonly filteredNoiseCount: number;
120​
121export interface OverlayBox {
122 readonly x: number;
123 readonly y: number;
124 readonly width: number;
125 readonly height: number;
126 readonly tag: string;
127 readonly color: string;
128 readonly tagSide?: "above" | "below" | "right" | "inside-right";
130​
131const VIEWPORT_EDGE_CLIP_TOLERANCE = 10;
132​
133const isSmallTargetDetail = Schema.is(SmallTargetDetailSchema);
134const isAmbiguousNameDetail = Schema.is(AmbiguousNameDetailSchema);
135​
136export function unitForPlatform(platform: AuditPlatform): "pt" | "dp" {
137 return platform === "ios" ? "pt" : "dp";
139​
140export function resolveViewport(
141 capture: Pick<AuditCapture, "viewport">,
142 raw?: RawSnapshotData,
143): AuditViewport | undefined {
144 if (capture.viewport?.width && capture.viewport?.height) return capture.viewport;
145 if (raw?.viewport?.width && raw?.viewport?.height) return raw.viewport;
146 const rootRect = raw?.nodes[0]?.rect;
147 if (rootRect && rootRect.width > 0 && rootRect.height > 0) {
148 return { width: rootRect.width, height: rootRect.height };
149 }
150 return undefined;
152​
153export function formatHeight(rect: AuditRect, density: number, unit: "pt" | "dp"): string {
154 const h = Math.round((rect.height / density) * 10) / 10;
155 return `${h}${unit}`;
157​
158/**
159 * Filters known platform-chrome and viewport-clipping artifacts so regressions stay high-signal:
160 * - iOS 26/27 native UISwitch accessibility frames report 63×28pt.
161 * - iOS system keyboard dictation/predictive bar buttons when not tagged keyboardOwned.
162 * - Rows clipped at the top or bottom scroll-viewport edge.
163 */
164export function isPlatformNoise(
165 finding: AuditFinding,
166 platform: AuditPlatform,
167 viewport?: AuditViewport,
168): boolean {
169 if (platform === "ios") {
170 if (
171 finding.kind === "small-target" &&
172 finding.role === "switch" &&
173 isSmallTargetDetail(finding.detail) &&
174 finding.detail.width >= 50 &&
175 finding.detail.height <= 32
176 ) {
177 return true;
178 }
179 if (finding.identifier === "dictation" || finding.label === "Dictate") {
180 return true;
181 }
182 }
183 if (finding.kind === "small-target" && finding.rect && viewport) {
184 const bottomEdge = finding.rect.y + finding.rect.height;
185 const clippedAtBottom =
186 bottomEdge >= viewport.height - VIEWPORT_EDGE_CLIP_TOLERANCE &&
187 finding.rect.height < viewport.height * 0.04;
188 const clippedAtTop = finding.rect.y <= 0 && finding.rect.height < viewport.height * 0.04;
189 if (clippedAtBottom || clippedAtTop) return true;
190 }
191 return false;
193​
194/** Stable identity key for matching findings across before/after runs. */
195export function findingSignature(finding: AuditFinding): string {
196 const name = (
197 finding.label ??
198 (isAmbiguousNameDetail(finding.detail) ? finding.detail.name : undefined) ??
199 finding.identifier ??
200 ""
201 )
202 .trim()
203 .toLowerCase();
204 if (name) return `${finding.kind}|${finding.role}|${name}`;
205 const rx = finding.rect ? Math.round(finding.rect.x / 20) * 20 : -1;
206 const ry = finding.rect ? Math.round(finding.rect.y / 20) * 20 : -1;
207 return `${finding.kind}|${finding.role}|@${rx},${ry}`;
209​
210function roleMatchesNode(role: string, node: RawSnapshotNode): boolean {
211 const type = (node.type ?? "").toLowerCase();
212 switch (role) {
213 case "button":
214 return type.includes("button");
215 case "text-field":
216 return type.includes("edittext") || type.includes("textfield") || type.includes("textview");
217 case "search-field":
218 return type.includes("search");
219 case "radio":
220 return type.includes("radio");
221 case "switch":
222 return type.includes("switch");
223 case "link":
224 return type.includes("link");
225 default:
226 return true;
227 }
229​
230function findMatchingAfterNode(
231 finding: AuditFinding,
232 afterRaw?: RawSnapshotData,
233): RawSnapshotNode | undefined {
234 if (!afterRaw) return undefined;
235 const targetLabel = (
236 finding.label ?? (isAmbiguousNameDetail(finding.detail) ? finding.detail.name : undefined)
237 )?.trim();
238 const candidates = afterRaw.nodes.filter((node) => {
239 if (!node.rect || node.rect.width <= 0 || node.rect.height <= 0) return false;
240 if (!roleMatchesNode(finding.role, node)) return false;
241 if (targetLabel) {
242 return (
243 node.label?.trim() === targetLabel ||
244 node.contentDescription?.trim() === targetLabel ||
245 node.text?.trim() === targetLabel
246 );
247 }
248 if (finding.rect) {
249 return (
250 Math.abs(node.rect.x - finding.rect.x) <= 40 && Math.abs(node.rect.y - finding.rect.y) <= 40
251 );
252 }
253 return false;
254 });
255 if (candidates.length === 0) return undefined;
256 if (!finding.rect || candidates.length === 1) return candidates[0];
257 return candidates.reduce((best, curr) => {
258 const bestDist =
259 Math.abs(best.rect!.x - finding.rect!.x) + Math.abs(best.rect!.y - finding.rect!.y);
260 const currDist =
261 Math.abs(curr.rect!.x - finding.rect!.x) + Math.abs(curr.rect!.y - finding.rect!.y);
262 return currDist < bestDist ? curr : best;
263 });
265​
266export function diffAuditCaptures(input: {
267 readonly before: AuditCapture;
268 readonly after: AuditCapture;
269 readonly beforeRaw?: RawSnapshotData | undefined;
270 readonly afterRaw?: RawSnapshotData | undefined;
271}): ScreenDiff {
272 const beforeVp = resolveViewport(input.before, input.beforeRaw);
273 const afterVp = resolveViewport(input.after, input.afterRaw);
274​
275 let filteredNoiseCount = 0;
276 const beforeFindings = input.before.findings.filter((f) => {
277 if (isPlatformNoise(f, input.before.platform, beforeVp)) {
278 filteredNoiseCount += 1;
279 return false;
280 }
281 return true;
282 });
283 const afterFindings = input.after.findings.filter((f) => {
284 if (isPlatformNoise(f, input.after.platform, afterVp)) {
285 filteredNoiseCount += 1;
286 return false;
287 }
288 return true;
289 });
290​
291 // Multiset diff by signature so fixing 1 of 2 duplicate buttons still shows up accurately.
292 const remainingAfter = new Map<string, AuditFinding[]>();
293 for (const f of afterFindings) {
294 const key = findingSignature(f);
295 const list = remainingAfter.get(key) ?? [];
296 list.push(f);
297 remainingAfter.set(key, list);
298 }
299​
300 const unchanged: AuditFinding[] = [];
301 const fixed: FixedFinding[] = [];
302 const unit = unitForPlatform(input.after.platform);
303 const density = input.after.pixelDensity || 1;
304​
305 for (const bf of beforeFindings) {
306 const key = findingSignature(bf);
307 const bucket = remainingAfter.get(key);
308 if (bucket && bucket.length > 0) {
309 bucket.shift();
310 unchanged.push(bf);
311 } else {
312 const afterNode = findMatchingAfterNode(bf, input.afterRaw);
313 const afterMeasurement =
314 bf.kind === "ambiguous-name"
315 ? "1 btn ✓"
316 : afterNode?.rect
317 ? `${formatHeight(afterNode.rect, density, unit)} ✓`
318 : "fixed ✓";
319 fixed.push({ before: bf, afterNode, afterMeasurement });
320 }
321 }
322​
323 const regressions: AuditFinding[] = [];
324 for (const bucket of remainingAfter.values()) {
325 regressions.push(...bucket);
326 }
327​
328 return {
329 platform: input.after.platform,
330 screen: input.after.screen,
331 pixelDensity: density,
332 beforeCount: beforeFindings.length,
333 afterCount: afterFindings.length,
334 regressions,
335 fixed,
336 unchanged,
337 filteredNoiseCount,
338 };
340​
341function dedupeBoxes(boxes: ReadonlyArray<OverlayBox>): OverlayBox[] {
342 const seen = new Set<string>();
343 return boxes.filter((box) => {
344 const key = `${Math.round(box.x / 4)}:${Math.round(box.y / 4)}:${Math.round(box.width / 4)}:${Math.round(box.height / 4)}`;
345 if (seen.has(key)) return false;
346 seen.add(key);
347 return true;
348 });
350​
351export function findingTag(finding: AuditFinding, density: number, unit: "pt" | "dp"): string {
352 if (finding.kind === "small-target") {
353 if (isSmallTargetDetail(finding.detail)) {
354 return `${finding.detail.height}${finding.detail.unit}`;
355 }
356 if (finding.rect) return formatHeight(finding.rect, density, unit);
357 return "small";
358 }
359 if (finding.kind === "ambiguous-name") {
360 const count = isAmbiguousNameDetail(finding.detail) ? finding.detail.count : 2;
361 return `×${count} dup`;
362 }
363 if (finding.kind === "missing-name") return "no label";
364 if (finding.kind === "covered-control") return "covered";
365 return finding.kind;
367​
368export function buildOverlayBoxes(
369 diff: ScreenDiff,
370 density: number,
371 beforeDensity = density,
372): { readonly beforeBoxes: OverlayBox[]; readonly afterBoxes: OverlayBox[] } {
373 const unit = unitForPlatform(diff.platform);
374 const beforeBoxes: OverlayBox[] = [];
375 const afterBoxes: OverlayBox[] = [];
376​
377 for (const item of diff.fixed) {
378 if (item.before.rect) {
379 beforeBoxes.push({
380 ...item.before.rect,
381 tag: findingTag(item.before, beforeDensity, unit),
382 color: "#ef4444",
383 });
384 }
385 if (item.afterNode?.rect) {
386 afterBoxes.push({
387 ...item.afterNode.rect,
388 tag: item.afterMeasurement ?? "fixed ✓",
389 color: "#16a34a",
390 });
391 }
392 }
393​
394 for (const reg of diff.regressions) {
395 if (reg.rect) {
396 afterBoxes.push({
397 ...reg.rect,
398 tag: `NEW: ${findingTag(reg, density, unit)}`,
399 color: "#ef4444",
400 });
401 }
402 }
403​
404 return {
405 beforeBoxes: dedupeBoxes(beforeBoxes),
406 afterBoxes: dedupeBoxes(afterBoxes),
407 };
409​
410export function renderMarkdownReport(
411 diffs: ReadonlyArray<ScreenDiff & { readonly imagePath?: string }>,
412): string {
413 const totalRegressions = diffs.reduce((n, d) => n + d.regressions.length, 0);
414 const totalFixed = diffs.reduce((n, d) => n + d.fixed.length, 0);
415 const lines: string[] = [
416 "### Mobile accessibility audit (`agent-device audit`)",
417 "",
418 `Summary: **${totalFixed} fixed**, **${totalRegressions} regressions** across ${diffs.length} screen(s).`,
419 "",
420 "| Platform | Screen | Before | After | Fixed | Regressions |",
421 "| --- | --- | ---: | ---: | ---: | ---: |",
422 ];
423​
424 for (const d of diffs) {
425 lines.push(
426 `| ${d.platform} | \`${d.screen}\` | ${d.beforeCount} | ${d.afterCount} | ${d.fixed.length} | ${d.regressions.length} |`,
427 );
428 }
429​
430 for (const d of diffs) {
431 if (d.fixed.length === 0 && d.regressions.length === 0) continue;
432 lines.push("", `#### ${d.platform} · \`${d.screen}\``);
433 if (d.regressions.length > 0) {
434 lines.push("", "**Regressions:**");
435 for (const r of d.regressions) {
436 lines.push(
437 `- \`${r.kind}\` (${r.role}) ${r.label ? `\`${r.label}\`` : "(unnamed)"} — ${findingTag(r, d.pixelDensity || 1, unitForPlatform(d.platform))}`,
438 );
439 }
440 }
441 if (d.fixed.length > 0) {
442 lines.push("", "**Fixed:**");
443 for (const f of d.fixed) {
444 lines.push(
445 `- \`${f.before.kind}\` (${f.before.role}) ${f.before.label ? `\`${f.before.label}\`` : "(unnamed)"} → ${f.afterMeasurement ?? "fixed"}`,
446 );
447 }
448 }
449 if (d.imagePath) {
450 lines.push("", `![${d.platform} ${d.screen} before vs after](${d.imagePath})`);
451 }
452 }
453​
454 return `${lines.join("\n")}\n`;