@mizchi/vlmkit-ai 0.23.2 → 0.24.0

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.
@@ -0,0 +1,250 @@
1
+ import { JEV_IMAGE_LIMITS, askJev, jevBoxToPixels, pngImage } from "./jev-client.mjs";
2
+ import { decodeImage, encodePngImage, resample } from "./zoom-image.mjs";
3
+ import { regionKindScale, regionKindView, regionKindWindow } from "./region-kind.mjs";
4
+ import { firstLookScale } from "./locate.mjs";
5
+ import { claimInstruction } from "./claims.mjs";
6
+ import { judgeMotionPath } from "@mizchi/vlmkit-judge/motion-path.ts";
7
+ //#region src/motion-check.ts
8
+ /**
9
+ * Is an animation visually broken? Frames of it, a target described in words, and statements
10
+ * that must not be seen. Jev answers per frame; vlmkit judges the motion.
11
+ *
12
+ * One request per frame, on one image: for each target a `noul` (shown?) and a `box` (where?),
13
+ * and a `noul` per forbidden statement — so a frame costs about what one screenshot does
14
+ * (~3.1k tokens at 1280x800, $0.00013) however many questions it carries.
15
+ *
16
+ * Jev is asked only what it is good at, measured (`docs/reports/2026-10-18-jev-easing.md`):
17
+ * asked for an easing name it was at chance (7/21); asked where the object was in each frame and
18
+ * the curve fitted here, 21/21. So the motion — jumps, snap-backs, a target lost mid-way, the
19
+ * easing — is `judgeMotionPath`'s, from positions and presence, and Jev never names it.
20
+ *
21
+ * Advisory: a model's reading of the pixels. The deterministic motion checks (`check animation`,
22
+ * `check integrity --timeline`) measure; this asks what a person would see in the frames.
23
+ */
24
+ async function pool(items, n, f) {
25
+ const out = new Array(items.length);
26
+ let next = 0;
27
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
28
+ while (next < items.length) {
29
+ const i = next++;
30
+ out[i] = await f(items[i]);
31
+ }
32
+ }));
33
+ return out;
34
+ }
35
+ async function checkMotionFrames(frames, options) {
36
+ if (frames.length === 0) throw new Error("no frames to check");
37
+ if (options.targets.length === 0 && (options.forbid ?? []).length === 0) throw new Error("nothing to check: give a target or a forbidden statement");
38
+ const ask = options.ask ?? ((req) => askJev(req, options.client));
39
+ const threshold = options.threshold ?? .5;
40
+ const band = options.uncertainBand ?? .3;
41
+ const forbid = options.forbid ?? [];
42
+ const model = options.model ?? "jev-1.14.0";
43
+ let costUsd = 0;
44
+ let inputTokens = 0;
45
+ let served = model;
46
+ let frameSize;
47
+ let calls = 0;
48
+ if (options.jev === false) {
49
+ if (forbid.length > 0) throw new Error("a forbidden statement can only be asked of Jev (jev: true)");
50
+ const missing = options.targets.findIndex((_, i) => !frames.every((f) => f.dom?.[i]));
51
+ if (missing >= 0) throw new Error(`without Jev every target needs the page's measurement: ${options.targets[missing]}`);
52
+ }
53
+ const answers = options.jev === false ? frames.map((frame) => {
54
+ const img = decodeImage(Buffer.from(frame.png));
55
+ frameSize ??= {
56
+ width: img.width,
57
+ height: img.height
58
+ };
59
+ return {
60
+ atMs: frame.atMs,
61
+ rest: frame.atMs > options.endMs,
62
+ targets: options.targets.map((_, i) => {
63
+ const d = frame.dom[i];
64
+ return {
65
+ present: d.opacity < .05 ? 0 : d.visible ?? 1,
66
+ box: d.box
67
+ };
68
+ }),
69
+ forbid: []
70
+ };
71
+ }) : await askFrames();
72
+ async function askFrames() {
73
+ return pool(frames, options.concurrency ?? 4, async (frame) => {
74
+ const img = decodeImage(Buffer.from(frame.png));
75
+ frameSize ??= {
76
+ width: img.width,
77
+ height: img.height
78
+ };
79
+ const scale = firstLookScale(img.width, img.height);
80
+ if (scale === null) throw new Error(`a ${img.width}x${img.height} frame cannot be shown within Jev's ${JEV_IMAGE_LIMITS.minEdge}-${JEV_IMAGE_LIMITS.maxEdge}px edges`);
81
+ const shown = scale === 1 ? frame.png : encodePngImage(resample(img, {
82
+ width: Math.round(img.width * scale),
83
+ height: Math.round(img.height * scale)
84
+ }));
85
+ const questions = {};
86
+ options.targets.forEach((t, i) => {
87
+ questions[`p${i}`] = {
88
+ type: "noul",
89
+ instructions: claimInstruction(t)
90
+ };
91
+ questions[`b${i}`] = {
92
+ type: "box",
93
+ instructions: `${t.trim().replace(/[.\s]+$/, "")} in \`screenshot\``
94
+ };
95
+ });
96
+ forbid.forEach((f, i) => {
97
+ questions[`f${i}`] = {
98
+ type: "noul",
99
+ instructions: claimInstruction(f)
100
+ };
101
+ });
102
+ const r = await ask({
103
+ model,
104
+ state: { screenshot: "SHOT" },
105
+ assets: { SHOT: pngImage(shown) },
106
+ questions
107
+ });
108
+ calls++;
109
+ costUsd += r.costUsd;
110
+ inputTokens += r.usage.input_tokens;
111
+ served = r.model;
112
+ const a = r.answers;
113
+ const noul = (k) => a[k].noul;
114
+ return {
115
+ atMs: frame.atMs,
116
+ rest: frame.atMs > options.endMs,
117
+ targets: options.targets.map((_, i) => {
118
+ const b = jevBoxToPixels(a[`b${i}`].box, img.width, img.height);
119
+ return {
120
+ present: noul(`p${i}`),
121
+ box: {
122
+ x: b.x1,
123
+ y: b.y1,
124
+ width: b.x2 - b.x1,
125
+ height: b.y2 - b.y1
126
+ }
127
+ };
128
+ }),
129
+ forbid: forbid.map((_, i) => noul(`f${i}`))
130
+ };
131
+ });
132
+ }
133
+ if (options.jev !== false && options.refine !== false && frameSize) {
134
+ const size = frameSize;
135
+ for (const [i, target] of options.targets.entries()) {
136
+ if (frames.every((f) => f.dom?.[i])) continue;
137
+ const seen = answers.filter((f) => f.targets[i].present >= threshold);
138
+ if (seen.length === 0) continue;
139
+ const x1 = Math.min(...seen.map((f) => f.targets[i].box.x));
140
+ const y1 = Math.min(...seen.map((f) => f.targets[i].box.y));
141
+ const x2 = Math.max(...seen.map((f) => f.targets[i].box.x + f.targets[i].box.width));
142
+ const y2 = Math.max(...seen.map((f) => f.targets[i].box.y + f.targets[i].box.height));
143
+ const win = regionKindWindow({
144
+ x: x1,
145
+ y: y1,
146
+ width: x2 - x1,
147
+ height: y2 - y1
148
+ }, size);
149
+ const scale = regionKindScale(win.x2 - win.x1, win.y2 - win.y1);
150
+ if (scale === null || scale <= 1.05) continue;
151
+ const byTime = new Map(frames.map((f) => [f.atMs, f]));
152
+ await pool(seen, options.concurrency ?? 4, async (f) => {
153
+ const view = regionKindView(decodeImage(Buffer.from(byTime.get(f.atMs).png)), win, scale);
154
+ const r = await ask({
155
+ model,
156
+ state: { screenshot: "SHOT" },
157
+ assets: { SHOT: pngImage(encodePngImage(view)) },
158
+ questions: { b: {
159
+ type: "box",
160
+ instructions: `${target.trim().replace(/[.\s]+$/, "")} in \`screenshot\``
161
+ } }
162
+ });
163
+ calls++;
164
+ costUsd += r.costUsd;
165
+ inputTokens += r.usage.input_tokens;
166
+ const b = r.answers.b;
167
+ const w = win.x2 - win.x1;
168
+ const h = win.y2 - win.y1;
169
+ f.targets[i].box = {
170
+ x: win.x1 + b.box.left * w,
171
+ y: win.y1 + b.box.top * h,
172
+ width: (b.box.right - b.box.left) * w,
173
+ height: (b.box.bottom - b.box.top) * h
174
+ };
175
+ f.targets[i].refined = true;
176
+ });
177
+ }
178
+ }
179
+ const iou = (a, b) => {
180
+ const inter = Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
181
+ return inter / Math.max(1e-9, a.width * a.height + b.width * b.height - inter);
182
+ };
183
+ for (const f of answers) for (let i = 0; i < f.targets.length; i++) for (let j = i + 1; j < f.targets.length; j++) {
184
+ const [a, b] = [f.targets[i], f.targets[j]];
185
+ if (a.present >= threshold && b.present >= threshold && iou(a.box, b.box) > .5) a.unsure = b.unsure = true;
186
+ }
187
+ const domAt = new Map(frames.map((f) => [f.atMs, f.dom]));
188
+ const perTarget = (xs, i) => xs === void 0 ? void 0 : xs.length === 1 ? xs[0] : xs[i];
189
+ const originFor = (i) => typeof options.expectOrigin === "string" ? options.expectOrigin : options.expectOrigin?.[i];
190
+ let staggerFrom = options.expectStartMs?.[0];
191
+ const startFor = (i) => options.expectStartMs?.[i] ?? (options.expectStaggerMs !== void 0 && i > 0 && staggerFrom !== void 0 ? staggerFrom + i * options.expectStaggerMs : void 0);
192
+ const targets = options.targets.map((target, i) => {
193
+ const measured = frames.every((f) => f.dom?.[i]);
194
+ const samples = answers.map((f) => ({
195
+ atMs: f.atMs,
196
+ present: f.targets[i].present,
197
+ box: f.targets[i].box,
198
+ ...measured ? { dom: domAt.get(f.atMs)[i] } : f.targets[i].unsure ? { unsure: true } : {}
199
+ }));
200
+ const judged = {
201
+ target,
202
+ ...judgeMotionPath(samples, {
203
+ startMs: options.startMs,
204
+ endMs: options.endMs,
205
+ ...options.segments ? { segments: options.segments } : {},
206
+ ...frameSize ? { frame: frameSize } : {},
207
+ presenceThreshold: threshold,
208
+ ...options.exits || options.exitsFor?.[i] ? { exits: true } : {},
209
+ ...options.targetEasing?.[i] ?? options.expectEasing ? { expectEasing: options.targetEasing?.[i] ?? options.expectEasing } : {},
210
+ ...originFor(i) ? { expectOrigin: originFor(i) } : {},
211
+ ...startFor(i) !== void 0 ? { expectStartMs: startFor(i) } : {},
212
+ ...perTarget(options.expectDurationMs, i) !== void 0 ? { expectDurationMs: perTarget(options.expectDurationMs, i) } : {},
213
+ ...perTarget(options.expectDirection, i) !== void 0 ? { expectDirection: perTarget(options.expectDirection, i) } : {},
214
+ ...perTarget(options.expectIterations, i) !== void 0 ? { expectIterations: perTarget(options.expectIterations, i) } : {},
215
+ ...options.expectStill || options.expectStillFor?.[i] ? { expectStill: true } : {},
216
+ ...options.layoutMovers ? { layoutMovers: options.layoutMovers } : {}
217
+ })
218
+ };
219
+ if (i === 0) staggerFrom ??= judged.startsAtMs;
220
+ return judged;
221
+ });
222
+ const forbidden = [];
223
+ forbid.forEach((statement, i) => {
224
+ const seen = answers.filter((f) => f.forbid[i] >= threshold).map((f) => ({
225
+ atMs: f.atMs,
226
+ noul: f.forbid[i],
227
+ uncertain: Math.abs(f.forbid[i] - threshold) < band
228
+ }));
229
+ if (seen.length === 0) return;
230
+ const atRest = answers.some((f) => f.rest && f.forbid[i] >= threshold);
231
+ forbidden.push({
232
+ statement,
233
+ severity: atRest ? "fail" : "warn",
234
+ frames: seen,
235
+ atRest
236
+ });
237
+ });
238
+ return {
239
+ frames: answers,
240
+ targets,
241
+ forbidden,
242
+ passed: targets.every((t) => t.findings.every((f) => f.severity !== "fail")) && forbidden.every((f) => f.severity !== "fail"),
243
+ model: options.jev === false ? "none (measured from the page)" : served,
244
+ calls,
245
+ costUsd,
246
+ inputTokens
247
+ };
248
+ }
249
+ //#endregion
250
+ export { checkMotionFrames };
package/dist/nlp.d.mts CHANGED
@@ -2,7 +2,6 @@
2
2
  /**
3
3
  * Text-matching helpers shared between expectation matching and reasoning.
4
4
  */
5
- declare const STOP_WORDS: Set<string>;
6
- declare const SYNONYMS: Record<string, string[]>;
7
- //#endregion
8
- export { STOP_WORDS, SYNONYMS };
5
+ export declare const STOP_WORDS: Set<string>;
6
+ export declare const SYNONYMS: Record<string, string[]>;
7
+ //#endregion
package/dist/nlp.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * Text-matching helpers shared between expectation matching and reasoning.
4
4
  */
5
- const STOP_WORDS = new Set([
5
+ const STOP_WORDS = /* @__PURE__ */ new Set([
6
6
  "gets",
7
7
  "from",
8
8
  "with",
@@ -1,14 +1,13 @@
1
1
  import { ResolutionPreset } from "@mizchi/vlmkit-core/image-resize.ts";
2
-
3
2
  //#region src/reasoning-pipeline.d.ts
4
- interface VisualChange {
3
+ export interface VisualChange {
5
4
  element: string;
6
5
  property: string;
7
6
  before: string;
8
7
  after: string;
9
8
  severity: "low" | "medium" | "high";
10
9
  }
11
- interface StructuredDiffReport {
10
+ export interface StructuredDiffReport {
12
11
  changes: VisualChange[];
13
12
  summary: string;
14
13
  regression: boolean;
@@ -17,13 +16,13 @@ interface StructuredDiffReport {
17
16
  vlmLatencyMs: number;
18
17
  vlmCostUsd: number;
19
18
  }
20
- interface CssFix {
19
+ export interface CssFix {
21
20
  selector: string;
22
21
  property: string;
23
22
  value: string;
24
23
  reason: string;
25
24
  }
26
- interface FixSuggestion {
25
+ export interface FixSuggestion {
27
26
  fixes: CssFix[];
28
27
  explanation: string;
29
28
  confidence: "high" | "medium" | "low";
@@ -32,7 +31,7 @@ interface FixSuggestion {
32
31
  llmLatencyMs: number;
33
32
  llmCostUsd: number;
34
33
  }
35
- interface PipelineConfig {
34
+ export interface PipelineConfig {
36
35
  /** Stage 1: VLM for image analysis (default: qwen3-vl-8b via OpenRouter) */
37
36
  vlmModel?: string;
38
37
  /** Stage 2: LLM for code generation (default: from VLMKIT_LLM_PROVIDER) */
@@ -50,7 +49,7 @@ interface PipelineConfig {
50
49
  */
51
50
  throwIfMissing?: boolean;
52
51
  }
53
- interface AnalyzeOptions {
52
+ export interface AnalyzeOptions {
54
53
  heatmapBase64?: string;
55
54
  baselineBase64?: string;
56
55
  currentBase64?: string;
@@ -69,15 +68,17 @@ interface AnalyzeOptions {
69
68
  contentChangeCount: number;
70
69
  };
71
70
  }
72
- interface ReasoningPipeline {
71
+ export interface ReasoningPipeline {
73
72
  /** Stage 1: image -> structured diff */
74
73
  analyze(options: AnalyzeOptions): Promise<StructuredDiffReport>;
75
74
  /** Stage 2: structured diff + CSS -> fix proposal */
76
75
  suggestFix(report: StructuredDiffReport, cssSource: string, cssDiff?: string): Promise<FixSuggestion>;
77
76
  /** Run Stage 1 + 2 sequentially. Auto-escalates resolution if needed */
78
77
  analyzeAndFix(options: AnalyzeOptions & {
79
- cssSource: string; /** CSS text diff (MISSING/CHANGED lines. Passed directly to Stage 2) */
80
- cssDiff?: string; /** High-resolution image for escalation (used by adaptive resolution) */
78
+ cssSource: string;
79
+ /** CSS text diff (MISSING/CHANGED lines. Passed directly to Stage 2) */
80
+ cssDiff?: string;
81
+ /** High-resolution image for escalation (used by adaptive resolution) */
81
82
  highResHeatmapBase64?: string;
82
83
  }): Promise<{
83
84
  analysis: StructuredDiffReport;
@@ -87,6 +88,5 @@ interface ReasoningPipeline {
87
88
  vlmModel: string;
88
89
  llmModel: string;
89
90
  }
90
- declare function createReasoningPipeline(config?: PipelineConfig): ReasoningPipeline | null;
91
- //#endregion
92
- export { AnalyzeOptions, CssFix, FixSuggestion, PipelineConfig, ReasoningPipeline, StructuredDiffReport, VisualChange, createReasoningPipeline };
91
+ export declare function createReasoningPipeline(config?: PipelineConfig): ReasoningPipeline | null;
92
+ //#endregion
@@ -160,7 +160,8 @@ function createReasoningPipeline(config) {
160
160
  llmModel: llmClient?.model ?? "none",
161
161
  async analyze(options) {
162
162
  if (!vlmClient) try {
163
- vlmClient = await createVlmClient(await resolveModel(vlmModelId), { throwIfMissing: false });
163
+ const model = await resolveModel(vlmModelId);
164
+ vlmClient = await createVlmClient(model, { throwIfMissing: false });
164
165
  } catch {
165
166
  vlmClient = null;
166
167
  }
@@ -1,5 +1,4 @@
1
1
  import { A11yDiff, ChangeIntent, PageExpectation } from "@mizchi/vlmkit-core/types.ts";
2
-
3
2
  //#region src/reasoning.d.ts
4
3
  /**
5
4
  * Expectation -> change -> realization reasoning chain
@@ -8,7 +7,7 @@ import { A11yDiff, ChangeIntent, PageExpectation } from "@mizchi/vlmkit-core/typ
8
7
  * 2. Change: what actually changed (a11y diff)
9
8
  * 3. Realization: whether the expectation was realized in a11y semantics
10
9
  */
11
- interface ReasoningChain {
10
+ export interface ReasoningChain {
12
11
  testId: string;
13
12
  /** Expectation summary */
14
13
  expectation: string;
@@ -21,13 +20,13 @@ interface ReasoningChain {
21
20
  /** Human-readable reasoning */
22
21
  reasoning: string;
23
22
  }
24
- interface ActualChange {
23
+ export interface ActualChange {
25
24
  type: string;
26
25
  description: string;
27
26
  path: string;
28
27
  severity: string;
29
28
  }
30
- interface ExpectationMapping {
29
+ export interface ExpectationMapping {
31
30
  expected: string;
32
31
  actual: string | null;
33
32
  realized: boolean;
@@ -36,6 +35,5 @@ interface ExpectationMapping {
36
35
  /**
37
36
  * Reason about whether expected changes were realized in the a11y tree diff.
38
37
  */
39
- declare function reasonAboutChanges(testId: string, pageExp: PageExpectation, a11yDiff: A11yDiff | undefined, intent: ChangeIntent): ReasoningChain;
40
- //#endregion
41
- export { ActualChange, ExpectationMapping, ReasoningChain, reasonAboutChanges };
38
+ export declare function reasonAboutChanges(testId: string, pageExp: PageExpectation, a11yDiff: A11yDiff | undefined, intent: ChangeIntent): ReasoningChain;
39
+ //#endregion
@@ -137,7 +137,7 @@ function buildReasoning(testId, expectation, mappings, sideEffects, verdict) {
137
137
  lines.push("");
138
138
  }
139
139
  lines.push(`Verdict: ${verdict.toUpperCase()} — ${{
140
- "realized": "All expected changes were realized in the a11y tree",
140
+ realized: "All expected changes were realized in the a11y tree",
141
141
  "partially-realized": "Some expected changes were realized, but not all",
142
142
  "not-realized": "Expected changes were not detected in the a11y tree",
143
143
  "unexpected-side-effects": "All expected changes were realized, but additional unexpected changes were detected"
@@ -0,0 +1,70 @@
1
+ import { JevClientOptions, JevResponse } from "./jev-client.mjs";
2
+ import { RgbaImage } from "./zoom-image.mjs";
3
+ //#region src/region-kind.d.ts
4
+ export type RegionKindLabel = "text" | "color" | "position" | "presence";
5
+ /** The options as Jev reads them. Changing a description changes the measured accuracy: re-run the bench. */
6
+ export declare const REGION_KIND_OPTIONS: Record<RegionKindLabel, string>;
7
+ export declare const REGION_KIND_QUESTION = "How does `current` differ from `baseline`?";
8
+ /**
9
+ * Below this confidence a label is marked `uncertain`: look at the crop before acting on it.
10
+ * Measured on real `diff png` regions (2026-10-16): every wrong label was below it (7 of 7),
11
+ * and 59 of 64 right ones were at or above it. A `choice`'s confidence carries signal here,
12
+ * unlike a `box`'s (AUROC 0.56 in the grounding bench).
13
+ */
14
+ export declare const REGION_KIND_SURE = 0.6;
15
+ export interface RegionKind {
16
+ label: RegionKindLabel;
17
+ confidence: number;
18
+ /** `confidence < REGION_KIND_SURE`. Shift-only regions of 1-2px are the usual case (read as colour). */
19
+ uncertain: boolean;
20
+ probabilities: Record<string, number>;
21
+ model: string;
22
+ }
23
+ export interface RegionBox {
24
+ x: number;
25
+ y: number;
26
+ width: number;
27
+ height: number;
28
+ }
29
+ /** A half-open box in image pixels. */
30
+ interface Win {
31
+ x1: number;
32
+ y1: number;
33
+ x2: number;
34
+ y2: number;
35
+ }
36
+ /**
37
+ * The window both captures are cut to. The region is padded by half its size on each side
38
+ * (at least 16px), then grown about its centre to Jev's 280px minimum where the image allows.
39
+ * It is snapped to whole pixels inside the image.
40
+ */
41
+ export declare function regionKindWindow(region: RegionBox, image: {
42
+ width: number;
43
+ height: number;
44
+ }): Win;
45
+ /**
46
+ * How much to magnify a window: up to 4x (the bench's setting) within Jev's limits, and at least
47
+ * enough to lift a short edge to 280px, past 4x if a small image needs it. Null when no scale
48
+ * fits both edges: a strip longer than 1568 / 280 = 5.6 times its width.
49
+ */
50
+ export declare function regionKindScale(width: number, height: number): number | null;
51
+ /** The view Jev gets of one capture: the window cropped and resampled, with edges clamped into the limits. */
52
+ export declare function regionKindView(img: RgbaImage, win: Win, scale: number): RgbaImage;
53
+ export type AskRegionKind = (baseline: Uint8Array, current: Uint8Array) => Promise<RegionKind>;
54
+ /** The real call: one `choice` over both views. Inject another `AskRegionKind` in tests. */
55
+ export declare function jevRegionKindAsker(options?: JevClientOptions & {
56
+ model?: string;
57
+ onResponse?: (r: JevResponse) => void;
58
+ }): AskRegionKind;
59
+ export type RegionKindOutcome = {
60
+ kind: RegionKind;
61
+ } | {
62
+ skipped: string;
63
+ };
64
+ /**
65
+ * Label each region, in input order. Regions are asked in parallel (`concurrency`, default 4),
66
+ * one request each: a request holding several regions' crops would pass Jev's 64k context.
67
+ * One region that fails is reported with its reason and leaves the others labelled.
68
+ */
69
+ export declare function labelRegionKinds(baseline: RgbaImage, current: RgbaImage, regions: readonly RegionBox[], ask: AskRegionKind, concurrency?: number): Promise<RegionKindOutcome[]>;
70
+ //#endregion
@@ -0,0 +1,140 @@
1
+ import { JEV_IMAGE_LIMITS, askJev, pngImage } from "./jev-client.mjs";
2
+ import { cropImage, encodePngImage, resample } from "./zoom-image.mjs";
3
+ //#region src/region-kind.ts
4
+ /**
5
+ * Name what changed in a pixel-diff region: text, colour, position, or presence.
6
+ *
7
+ * The pixel diff has already found WHERE, deterministically. This asks Jev only WHAT, on both
8
+ * captures cut to the region and magnified, as one typed `choice`. The split is the point. In
9
+ * `diff region` (deprecated) a VLM was asked for the regions and the values too, and fabricated
10
+ * both. Here the region and every value (shift, colours) stay the pixels', and the label is one
11
+ * that a person can check against the crop.
12
+ *
13
+ * Measured 2026-10-16 (`docs/reports/2026-10-16-jev-box-bench.md`, and the end-to-end round on
14
+ * real `diff png` regions in `…-jev-region-kind.md`). Do not take a shift's direction from here:
15
+ * Jev got it 8/16 on the crop, and `region.shift` measures it.
16
+ */
17
+ /** The options as Jev reads them. Changing a description changes the measured accuracy: re-run the bench. */
18
+ const REGION_KIND_OPTIONS = {
19
+ text: "A character or word of text is different",
20
+ color: "A colour is different (text, fill or border); the shapes are the same",
21
+ position: "Something moved: the same content sits a few pixels away from where it was",
22
+ presence: "Something appeared or disappeared: content is in one image and missing from the other"
23
+ };
24
+ const REGION_KIND_QUESTION = "How does `current` differ from `baseline`?";
25
+ /**
26
+ * Below this confidence a label is marked `uncertain`: look at the crop before acting on it.
27
+ * Measured on real `diff png` regions (2026-10-16): every wrong label was below it (7 of 7),
28
+ * and 59 of 64 right ones were at or above it. A `choice`'s confidence carries signal here,
29
+ * unlike a `box`'s (AUROC 0.56 in the grounding bench).
30
+ */
31
+ const REGION_KIND_SURE = .6;
32
+ /**
33
+ * The window both captures are cut to. The region is padded by half its size on each side
34
+ * (at least 16px), then grown about its centre to Jev's 280px minimum where the image allows.
35
+ * It is snapped to whole pixels inside the image.
36
+ */
37
+ function regionKindWindow(region, image) {
38
+ const grow = (lo, size, limit) => {
39
+ const pad = Math.max(16, size * .5);
40
+ let a = lo - pad;
41
+ let z = lo + size + pad;
42
+ const need = Math.max(0, JEV_IMAGE_LIMITS.minEdge - (z - a));
43
+ a -= need / 2;
44
+ z += need / 2;
45
+ if (a < 0) [a, z] = [0, z - a];
46
+ if (z > limit) [a, z] = [Math.max(0, a - (z - limit)), limit];
47
+ return [Math.max(0, Math.floor(a)), Math.min(limit, Math.ceil(z))];
48
+ };
49
+ const [x1, x2] = grow(region.x, region.width, image.width);
50
+ const [y1, y2] = grow(region.y, region.height, image.height);
51
+ return {
52
+ x1,
53
+ y1,
54
+ x2,
55
+ y2
56
+ };
57
+ }
58
+ /**
59
+ * How much to magnify a window: up to 4x (the bench's setting) within Jev's limits, and at least
60
+ * enough to lift a short edge to 280px, past 4x if a small image needs it. Null when no scale
61
+ * fits both edges: a strip longer than 1568 / 280 = 5.6 times its width.
62
+ */
63
+ function regionKindScale(width, height) {
64
+ const L = JEV_IMAGE_LIMITS;
65
+ const limit = Math.min(L.maxEdge / Math.max(width, height), Math.sqrt(L.maxPixels / (width * height)));
66
+ const min = L.minEdge / Math.min(width, height);
67
+ if (min > limit + 1e-9) return null;
68
+ return Math.max(min, Math.min(4, limit));
69
+ }
70
+ /** The view Jev gets of one capture: the window cropped and resampled, with edges clamped into the limits. */
71
+ function regionKindView(img, win, scale) {
72
+ const L = JEV_IMAGE_LIMITS;
73
+ const crop = cropImage(img, win);
74
+ const size = (n) => Math.min(L.maxEdge, Math.max(L.minEdge, Math.round(n * scale)));
75
+ return resample(crop, {
76
+ width: size(crop.width),
77
+ height: size(crop.height)
78
+ });
79
+ }
80
+ /** The real call: one `choice` over both views. Inject another `AskRegionKind` in tests. */
81
+ function jevRegionKindAsker(options = {}) {
82
+ return async (baseline, current) => {
83
+ const r = await askJev({
84
+ model: options.model ?? "jev-1.14.0",
85
+ state: {
86
+ baseline: "BASE",
87
+ current: "CUR"
88
+ },
89
+ assets: {
90
+ BASE: pngImage(baseline),
91
+ CUR: pngImage(current)
92
+ },
93
+ questions: { kind: {
94
+ type: "choice",
95
+ instructions: REGION_KIND_QUESTION,
96
+ criteria: { ...REGION_KIND_OPTIONS }
97
+ } }
98
+ }, options);
99
+ options.onResponse?.(r);
100
+ const a = r.answers.kind;
101
+ return {
102
+ label: a.choice,
103
+ confidence: a.confidence,
104
+ uncertain: a.confidence < REGION_KIND_SURE,
105
+ probabilities: a.probabilities,
106
+ model: r.model
107
+ };
108
+ };
109
+ }
110
+ /**
111
+ * Label each region, in input order. Regions are asked in parallel (`concurrency`, default 4),
112
+ * one request each: a request holding several regions' crops would pass Jev's 64k context.
113
+ * One region that fails is reported with its reason and leaves the others labelled.
114
+ */
115
+ async function labelRegionKinds(baseline, current, regions, ask, concurrency = 4) {
116
+ if (baseline.width !== current.width || baseline.height !== current.height) return regions.map(() => ({ skipped: `capture sizes differ (${baseline.width}x${baseline.height} vs ${current.width}x${current.height})` }));
117
+ const out = new Array(regions.length);
118
+ let next = 0;
119
+ const worker = async () => {
120
+ while (next < regions.length) {
121
+ const i = next++;
122
+ const win = regionKindWindow(regions[i], baseline);
123
+ const scale = regionKindScale(win.x2 - win.x1, win.y2 - win.y1);
124
+ if (scale === null) {
125
+ out[i] = { skipped: `window ${win.x2 - win.x1}x${win.y2 - win.y1} cannot fit Jev's 280-1568px edges` };
126
+ continue;
127
+ }
128
+ try {
129
+ const kind = await ask(encodePngImage(regionKindView(baseline, win, scale)), encodePngImage(regionKindView(current, win, scale)));
130
+ out[i] = { kind };
131
+ } catch (error) {
132
+ out[i] = { skipped: error.message.slice(0, 300) };
133
+ }
134
+ }
135
+ };
136
+ await Promise.all(Array.from({ length: Math.min(concurrency, regions.length) }, worker));
137
+ return out;
138
+ }
139
+ //#endregion
140
+ export { REGION_KIND_OPTIONS, REGION_KIND_QUESTION, REGION_KIND_SURE, jevRegionKindAsker, labelRegionKinds, regionKindScale, regionKindView, regionKindWindow };