@mizchi/vlmkit-ai 0.7.0 → 0.8.1
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.
- package/dist/errors.d.mts +24 -0
- package/dist/errors.mjs +11 -0
- package/dist/image-gen-client.d.mts +79 -0
- package/dist/image-gen-client.mjs +149 -0
- package/dist/index.d.mts +8 -0
- package/dist/index.mjs +8 -0
- package/dist/intent.d.mts +29 -0
- package/dist/intent.mjs +213 -0
- package/dist/llm-client.d.mts +87 -0
- package/dist/llm-client.mjs +310 -0
- package/dist/nlp.d.mts +8 -0
- package/dist/nlp.mjs +50 -0
- package/dist/reasoning-pipeline.d.mts +92 -0
- package/dist/reasoning-pipeline.mjs +256 -0
- package/dist/reasoning.d.mts +41 -0
- package/dist/reasoning.mjs +148 -0
- package/dist/vlm-client.d.mts +63 -0
- package/dist/vlm-client.mjs +430 -0
- package/package.json +18 -6
- package/src/errors.ts +0 -41
- package/src/image-gen-client.ts +0 -245
- package/src/index.ts +0 -89
- package/src/intent.ts +0 -322
- package/src/llm-client.ts +0 -421
- package/src/nlp.ts +0 -27
- package/src/reasoning-pipeline.ts +0 -407
- package/src/reasoning.ts +0 -268
- package/src/vlm-client.ts +0 -501
|
@@ -1,407 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* VRT Reasoning Pipeline -- two-stage VLM + LLM pipeline
|
|
3
|
-
*
|
|
4
|
-
* Stage 1 (VLM, cheap): heatmap/screenshot -> structured diff report
|
|
5
|
-
* Stage 2 (LLM, expensive): structured report + CSS source -> fix code generation
|
|
6
|
-
*
|
|
7
|
-
* Usage:
|
|
8
|
-
* const pipeline = createReasoningPipeline();
|
|
9
|
-
* const analysis = await pipeline.analyze(heatmapBase64, textReport);
|
|
10
|
-
* const fix = await pipeline.suggestFix(analysis, cssSource);
|
|
11
|
-
*/
|
|
12
|
-
import { createUnifiedLLMClient } from "./llm-client.ts";
|
|
13
|
-
import { createVlmClient, resolveModel, type VlmClient } from "./vlm-client.ts";
|
|
14
|
-
import { VrtConfigError } from "./errors.ts";
|
|
15
|
-
import { resizeBase64Png, type ResolutionPreset } from "@mizchi/vlmkit-core/image-resize.ts";
|
|
16
|
-
|
|
17
|
-
// ---- Types ----
|
|
18
|
-
|
|
19
|
-
export interface VisualChange {
|
|
20
|
-
element: string;
|
|
21
|
-
property: string;
|
|
22
|
-
before: string;
|
|
23
|
-
after: string;
|
|
24
|
-
severity: "low" | "medium" | "high";
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export interface StructuredDiffReport {
|
|
28
|
-
changes: VisualChange[];
|
|
29
|
-
summary: string;
|
|
30
|
-
regression: boolean;
|
|
31
|
-
raw: string;
|
|
32
|
-
vlmModel: string;
|
|
33
|
-
vlmLatencyMs: number;
|
|
34
|
-
vlmCostUsd: number;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export interface CssFix {
|
|
38
|
-
selector: string;
|
|
39
|
-
property: string;
|
|
40
|
-
value: string;
|
|
41
|
-
reason: string;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export interface FixSuggestion {
|
|
45
|
-
fixes: CssFix[];
|
|
46
|
-
explanation: string;
|
|
47
|
-
confidence: "high" | "medium" | "low";
|
|
48
|
-
raw: string;
|
|
49
|
-
llmModel: string;
|
|
50
|
-
llmLatencyMs: number;
|
|
51
|
-
llmCostUsd: number;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export interface PipelineConfig {
|
|
55
|
-
/** Stage 1: VLM for image analysis (default: qwen3-vl-8b via OpenRouter) */
|
|
56
|
-
vlmModel?: string;
|
|
57
|
-
/** Stage 2: LLM for code generation (default: from VRT_LLM_PROVIDER) */
|
|
58
|
-
llmProvider?: "gemini" | "anthropic" | "openrouter";
|
|
59
|
-
llmModel?: string;
|
|
60
|
-
/** Image resolution (default: medium = 400x300) */
|
|
61
|
-
resolution?: ResolutionPreset;
|
|
62
|
-
/** Auto-escalate when resolution is insufficient (default: true) */
|
|
63
|
-
adaptiveResolution?: boolean;
|
|
64
|
-
/** Escalation ceiling (default: high) */
|
|
65
|
-
maxResolution?: ResolutionPreset;
|
|
66
|
-
/**
|
|
67
|
-
* When `false`, returns `null` instead of throwing `VrtConfigError`
|
|
68
|
-
* if neither VLM nor LLM credentials are available. Default: `true`.
|
|
69
|
-
*/
|
|
70
|
-
throwIfMissing?: boolean;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export interface AnalyzeOptions {
|
|
74
|
-
heatmapBase64?: string;
|
|
75
|
-
baselineBase64?: string;
|
|
76
|
-
currentBase64?: string;
|
|
77
|
-
textReport?: string;
|
|
78
|
-
/** Resolution override (takes priority over pipeline config) */
|
|
79
|
-
resolution?: ResolutionPreset;
|
|
80
|
-
/** Cropped region for the target selector (base64 PNG) */
|
|
81
|
-
selectorCropBase64?: string;
|
|
82
|
-
/** Compact ASCII heatmap from DiffReport (10x10 grid + regions) */
|
|
83
|
-
compactHeatmap?: string;
|
|
84
|
-
/** Shift detection results */
|
|
85
|
-
shiftInfo?: {
|
|
86
|
-
globalShift: number;
|
|
87
|
-
shiftOnly: boolean;
|
|
88
|
-
compensatedDiffRatio: number;
|
|
89
|
-
contentChangeCount: number;
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export interface ReasoningPipeline {
|
|
94
|
-
/** Stage 1: image -> structured diff */
|
|
95
|
-
analyze(options: AnalyzeOptions): Promise<StructuredDiffReport>;
|
|
96
|
-
|
|
97
|
-
/** Stage 2: structured diff + CSS -> fix proposal */
|
|
98
|
-
suggestFix(report: StructuredDiffReport, cssSource: string, cssDiff?: string): Promise<FixSuggestion>;
|
|
99
|
-
|
|
100
|
-
/** Run Stage 1 + 2 sequentially. Auto-escalates resolution if needed */
|
|
101
|
-
analyzeAndFix(options: AnalyzeOptions & {
|
|
102
|
-
cssSource: string;
|
|
103
|
-
/** CSS text diff (MISSING/CHANGED lines. Passed directly to Stage 2) */
|
|
104
|
-
cssDiff?: string;
|
|
105
|
-
/** High-resolution image for escalation (used by adaptive resolution) */
|
|
106
|
-
highResHeatmapBase64?: string;
|
|
107
|
-
}): Promise<{ analysis: StructuredDiffReport; fix: FixSuggestion; escalated: boolean }>;
|
|
108
|
-
|
|
109
|
-
vlmModel: string;
|
|
110
|
-
llmModel: string;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// ---- Stage 1 prompt ----
|
|
114
|
-
|
|
115
|
-
const STAGE1_PROMPT = `You are analyzing a VRT (Visual Regression Testing) diff image. The red/pink areas in the heatmap show WHERE pixels differ, NOT the actual colors of the elements.
|
|
116
|
-
|
|
117
|
-
IMPORTANT: Red in the heatmap means "this area changed" — it does NOT mean the element is red. You must infer the actual CSS values from the element context, not from the heatmap color.
|
|
118
|
-
|
|
119
|
-
For each visual change, output ONE line in this EXACT format:
|
|
120
|
-
CHANGE: [element] | [css-property] | [before-value] | [after-value] | [severity:low/medium/high]
|
|
121
|
-
|
|
122
|
-
Example:
|
|
123
|
-
CHANGE: h1 heading | color | #333333 | #111111 | low
|
|
124
|
-
CHANGE: .card | padding | 16px | 12px | medium
|
|
125
|
-
CHANGE: .card | background-color | #f0f0f0 | #eff6ff | medium
|
|
126
|
-
CHANGE: table header | text-transform | none | uppercase | high
|
|
127
|
-
|
|
128
|
-
Rules:
|
|
129
|
-
- Do NOT repeat the same element+property combination.
|
|
130
|
-
- Do NOT confuse heatmap red with actual CSS colors.
|
|
131
|
-
- Use approximate CSS values based on visual appearance.
|
|
132
|
-
|
|
133
|
-
After all changes, add:
|
|
134
|
-
SUMMARY: <one sentence describing the overall change>
|
|
135
|
-
REGRESSION: <yes/no>`;
|
|
136
|
-
|
|
137
|
-
// ---- Stage 2 prompt ----
|
|
138
|
-
|
|
139
|
-
function buildStage2Prompt(report: StructuredDiffReport, cssSource: string, cssDiff?: string): string {
|
|
140
|
-
const changeList = report.changes
|
|
141
|
-
.map((c) => `- ${c.element}: ${c.property} changed from "${c.before}" to "${c.after}" (${c.severity})`)
|
|
142
|
-
.join("\n");
|
|
143
|
-
|
|
144
|
-
const cssDiffSection = cssDiff
|
|
145
|
-
? `\n## CSS Diff from Baseline (authoritative — use these exact values)\n${cssDiff}`
|
|
146
|
-
: "";
|
|
147
|
-
|
|
148
|
-
return `You are fixing CSS to match a target visual appearance.
|
|
149
|
-
|
|
150
|
-
## Visual Changes Detected (from image analysis)
|
|
151
|
-
${changeList}
|
|
152
|
-
|
|
153
|
-
Summary: ${report.summary}
|
|
154
|
-
${cssDiffSection}
|
|
155
|
-
|
|
156
|
-
## Current CSS
|
|
157
|
-
\`\`\`css
|
|
158
|
-
${cssSource}
|
|
159
|
-
\`\`\`
|
|
160
|
-
|
|
161
|
-
## Task
|
|
162
|
-
Provide CSS fixes to restore the baseline appearance. For each fix, output ONE line in this format:
|
|
163
|
-
FIX: [selector] | [property] | [value] | [reason]
|
|
164
|
-
|
|
165
|
-
IMPORTANT RULES:
|
|
166
|
-
- If "CSS Diff from Baseline" is provided above, use those EXACT selectors and values. They are authoritative.
|
|
167
|
-
- Do NOT modify selectors that are not mentioned in the diff.
|
|
168
|
-
- Do NOT guess CSS values — only use values from the diff or the visual analysis.
|
|
169
|
-
- For MISSING rules, add them back exactly as shown.
|
|
170
|
-
|
|
171
|
-
After all fixes, add:
|
|
172
|
-
EXPLANATION: <brief explanation of the root cause>
|
|
173
|
-
CONFIDENCE: <high/medium/low>`;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// ---- Parser ----
|
|
177
|
-
|
|
178
|
-
function parseStage1Response(raw: string): { changes: VisualChange[]; summary: string; regression: boolean } {
|
|
179
|
-
const changes: VisualChange[] = [];
|
|
180
|
-
const seen = new Set<string>();
|
|
181
|
-
let summary = "";
|
|
182
|
-
let regression = false;
|
|
183
|
-
|
|
184
|
-
for (const line of raw.split("\n")) {
|
|
185
|
-
const trimmed = line.trim();
|
|
186
|
-
|
|
187
|
-
const changeMatch = trimmed.match(/^CHANGE:\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(low|medium|high)/i);
|
|
188
|
-
if (changeMatch) {
|
|
189
|
-
const key = `${changeMatch[1].trim()}|${changeMatch[2].trim()}`;
|
|
190
|
-
if (seen.has(key)) continue; // deduplicate
|
|
191
|
-
seen.add(key);
|
|
192
|
-
changes.push({
|
|
193
|
-
element: changeMatch[1].trim(),
|
|
194
|
-
property: changeMatch[2].trim(),
|
|
195
|
-
before: changeMatch[3].trim(),
|
|
196
|
-
after: changeMatch[4].trim(),
|
|
197
|
-
severity: changeMatch[5].toLowerCase() as VisualChange["severity"],
|
|
198
|
-
});
|
|
199
|
-
continue;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
const summaryMatch = trimmed.match(/^SUMMARY:\s*(.+)/i);
|
|
203
|
-
if (summaryMatch) { summary = summaryMatch[1].trim(); continue; }
|
|
204
|
-
|
|
205
|
-
const regressionMatch = trimmed.match(/^REGRESSION:\s*(yes|no)/i);
|
|
206
|
-
if (regressionMatch) { regression = regressionMatch[1].toLowerCase() === "yes"; }
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return { changes, summary, regression };
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function parseStage2Response(raw: string): { fixes: CssFix[]; explanation: string; confidence: FixSuggestion["confidence"] } {
|
|
213
|
-
const fixes: CssFix[] = [];
|
|
214
|
-
let explanation = "";
|
|
215
|
-
let confidence: FixSuggestion["confidence"] = "medium";
|
|
216
|
-
|
|
217
|
-
for (const line of raw.split("\n")) {
|
|
218
|
-
const trimmed = line.trim();
|
|
219
|
-
|
|
220
|
-
const fixMatch = trimmed.match(/^FIX:\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+)/i);
|
|
221
|
-
if (fixMatch) {
|
|
222
|
-
fixes.push({
|
|
223
|
-
selector: fixMatch[1].trim(),
|
|
224
|
-
property: fixMatch[2].trim(),
|
|
225
|
-
value: fixMatch[3].trim(),
|
|
226
|
-
reason: fixMatch[4].trim(),
|
|
227
|
-
});
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const explMatch = trimmed.match(/^EXPLANATION:\s*(.+)/i);
|
|
232
|
-
if (explMatch) { explanation = explMatch[1].trim(); continue; }
|
|
233
|
-
|
|
234
|
-
const confMatch = trimmed.match(/^CONFIDENCE:\s*(high|medium|low)/i);
|
|
235
|
-
if (confMatch) { confidence = confMatch[1].toLowerCase() as FixSuggestion["confidence"]; }
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
return { fixes, explanation, confidence };
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
// ---- Pipeline factory ----
|
|
242
|
-
|
|
243
|
-
export function createReasoningPipeline(config?: PipelineConfig): ReasoningPipeline | null {
|
|
244
|
-
const throwIfMissing = config?.throwIfMissing ?? true;
|
|
245
|
-
// Stage 1: VLM
|
|
246
|
-
let vlmClient: VlmClient | null = null;
|
|
247
|
-
let vlmModelId = config?.vlmModel ?? process.env.VRT_VLM_MODEL ?? "bytedance/ui-tars-1.5-7b";
|
|
248
|
-
|
|
249
|
-
// Stage 2: LLM (try configured, then fallback). Always non-throwing here
|
|
250
|
-
// — we synthesize a single ConfigError below if everything fails.
|
|
251
|
-
let llmClient = createUnifiedLLMClient({
|
|
252
|
-
provider: config?.llmProvider,
|
|
253
|
-
model: config?.llmModel,
|
|
254
|
-
throwIfMissing: false,
|
|
255
|
-
});
|
|
256
|
-
if (!llmClient) {
|
|
257
|
-
// Fallback: try each provider
|
|
258
|
-
for (const provider of ["gemini", "anthropic", "openrouter"] as const) {
|
|
259
|
-
llmClient = createUnifiedLLMClient({ provider, throwIfMissing: false });
|
|
260
|
-
if (llmClient) break;
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// Need at least VLM or LLM
|
|
265
|
-
if (!llmClient && !process.env.OPENROUTER_API_KEY) {
|
|
266
|
-
if (throwIfMissing) {
|
|
267
|
-
throw new VrtConfigError(
|
|
268
|
-
"NO_PROVIDER_AVAILABLE",
|
|
269
|
-
"Reasoning pipeline needs an LLM (GEMINI/ANTHROPIC/OPENROUTER_API_KEY) or a VLM (OPENROUTER_API_KEY).",
|
|
270
|
-
);
|
|
271
|
-
}
|
|
272
|
-
return null;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
return {
|
|
276
|
-
vlmModel: vlmModelId,
|
|
277
|
-
llmModel: llmClient?.model ?? "none",
|
|
278
|
-
|
|
279
|
-
async analyze(options) {
|
|
280
|
-
// Lazy init VLM client — swallow config errors here so the pipeline
|
|
281
|
-
// can degrade to LLM-only mode (handled in the next branch).
|
|
282
|
-
if (!vlmClient) {
|
|
283
|
-
try {
|
|
284
|
-
const model = await resolveModel(vlmModelId);
|
|
285
|
-
vlmClient = await createVlmClient(model, { throwIfMissing: false });
|
|
286
|
-
} catch {
|
|
287
|
-
vlmClient = null;
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
if (!vlmClient) {
|
|
292
|
-
// Fallback: use LLM with text-only report
|
|
293
|
-
if (!llmClient) throw new Error("No VLM or LLM available");
|
|
294
|
-
const resp = await llmClient.completeWithImages(
|
|
295
|
-
options.textReport ?? "No visual data available",
|
|
296
|
-
{ maxTokens: 1024 },
|
|
297
|
-
);
|
|
298
|
-
const parsed = parseStage1Response(resp.content);
|
|
299
|
-
return {
|
|
300
|
-
...parsed,
|
|
301
|
-
raw: resp.content,
|
|
302
|
-
vlmModel: resp.model,
|
|
303
|
-
vlmLatencyMs: resp.latencyMs,
|
|
304
|
-
vlmCostUsd: resp.costUsd,
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
// Select image: selectorCrop > heatmap > current
|
|
309
|
-
let imageBase64: string | null = null;
|
|
310
|
-
if (options.selectorCropBase64) imageBase64 = options.selectorCropBase64;
|
|
311
|
-
else if (options.heatmapBase64) imageBase64 = options.heatmapBase64;
|
|
312
|
-
else if (options.currentBase64) imageBase64 = options.currentBase64;
|
|
313
|
-
|
|
314
|
-
if (!imageBase64) throw new Error("No image data provided for VLM analysis");
|
|
315
|
-
|
|
316
|
-
// Resize image to configured resolution
|
|
317
|
-
const resolution = options.resolution ?? config?.resolution ?? "medium";
|
|
318
|
-
imageBase64 = resizeBase64Png(imageBase64, { resolution });
|
|
319
|
-
|
|
320
|
-
let prompt = STAGE1_PROMPT;
|
|
321
|
-
if (options.shiftInfo) {
|
|
322
|
-
const si = options.shiftInfo;
|
|
323
|
-
prompt += `\n\nShift detection:`;
|
|
324
|
-
if (si.globalShift !== 0) {
|
|
325
|
-
prompt += `\n- Global vertical shift: ${si.globalShift > 0 ? "+" : ""}${si.globalShift}px`;
|
|
326
|
-
prompt += `\n- Compensated diff (shift excluded): ${(si.compensatedDiffRatio * 100).toFixed(1)}%`;
|
|
327
|
-
if (si.shiftOnly) {
|
|
328
|
-
prompt += `\n- SHIFT ONLY: all changes appear to be positional shifts, not content changes. Focus on layout-affecting properties (height, padding, margin).`;
|
|
329
|
-
} else {
|
|
330
|
-
prompt += `\n- ${si.contentChangeCount} content change region(s) detected beyond the shift.`;
|
|
331
|
-
}
|
|
332
|
-
} else {
|
|
333
|
-
prompt += `\n- No vertical shift detected.`;
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
if (options.compactHeatmap) {
|
|
337
|
-
prompt += `\n\nDiff heatmap (10x10 grid, X=changed, .=unchanged):\n${options.compactHeatmap}`;
|
|
338
|
-
}
|
|
339
|
-
if (options.textReport) {
|
|
340
|
-
prompt += `\n\nAdditional context from VRT pipeline:\n${options.textReport}`;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
const resp = await vlmClient.analyzeImage(imageBase64, prompt, { maxTokens: 1024 });
|
|
344
|
-
|
|
345
|
-
const parsed = parseStage1Response(resp.content);
|
|
346
|
-
return {
|
|
347
|
-
...parsed,
|
|
348
|
-
raw: resp.content,
|
|
349
|
-
vlmModel: resp.model,
|
|
350
|
-
vlmLatencyMs: resp.latencyMs,
|
|
351
|
-
vlmCostUsd: resp.costUsd,
|
|
352
|
-
};
|
|
353
|
-
},
|
|
354
|
-
|
|
355
|
-
async suggestFix(report, cssSource, cssDiff?) {
|
|
356
|
-
if (!llmClient) throw new Error("No LLM available for Stage 2");
|
|
357
|
-
|
|
358
|
-
const prompt = buildStage2Prompt(report, cssSource, cssDiff);
|
|
359
|
-
const resp = await llmClient.completeWithImages(prompt, { maxTokens: 2048 });
|
|
360
|
-
const parsed = parseStage2Response(resp.content);
|
|
361
|
-
|
|
362
|
-
return {
|
|
363
|
-
...parsed,
|
|
364
|
-
raw: resp.content,
|
|
365
|
-
llmModel: resp.model,
|
|
366
|
-
llmLatencyMs: resp.latencyMs,
|
|
367
|
-
llmCostUsd: resp.costUsd,
|
|
368
|
-
};
|
|
369
|
-
},
|
|
370
|
-
|
|
371
|
-
async analyzeAndFix(options) {
|
|
372
|
-
const adaptive = config?.adaptiveResolution !== false;
|
|
373
|
-
const maxRes = config?.maxResolution ?? "high";
|
|
374
|
-
const resolutionLadder: ResolutionPreset[] = ["low", "medium", "high", "full"];
|
|
375
|
-
|
|
376
|
-
// Step 1: analyze at initial resolution
|
|
377
|
-
let analysis = await this.analyze(options);
|
|
378
|
-
let fix = await this.suggestFix(analysis, options.cssSource, options.cssDiff);
|
|
379
|
-
let escalated = false;
|
|
380
|
-
|
|
381
|
-
// Step 2: if fix confidence is low and we can escalate, try higher resolution
|
|
382
|
-
if (adaptive && fix.confidence === "low" && analysis.changes.length <= 1) {
|
|
383
|
-
const currentRes = options.resolution ?? config?.resolution ?? "medium";
|
|
384
|
-
const currentIdx = resolutionLadder.indexOf(currentRes);
|
|
385
|
-
const maxIdx = resolutionLadder.indexOf(maxRes);
|
|
386
|
-
|
|
387
|
-
if (currentIdx < maxIdx) {
|
|
388
|
-
const nextRes = resolutionLadder[currentIdx + 1];
|
|
389
|
-
const escalationImage = options.highResHeatmapBase64 ?? options.heatmapBase64;
|
|
390
|
-
|
|
391
|
-
if (escalationImage) {
|
|
392
|
-
// Re-analyze at higher resolution
|
|
393
|
-
analysis = await this.analyze({
|
|
394
|
-
...options,
|
|
395
|
-
heatmapBase64: escalationImage,
|
|
396
|
-
resolution: nextRes,
|
|
397
|
-
});
|
|
398
|
-
fix = await this.suggestFix(analysis, options.cssSource, options.cssDiff);
|
|
399
|
-
escalated = true;
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
return { analysis, fix, escalated };
|
|
405
|
-
},
|
|
406
|
-
};
|
|
407
|
-
}
|
package/src/reasoning.ts
DELETED
|
@@ -1,268 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
A11yDiff,
|
|
3
|
-
A11yChange,
|
|
4
|
-
ChangeIntent,
|
|
5
|
-
ExpectedA11yChange,
|
|
6
|
-
PageExpectation,
|
|
7
|
-
} from "@mizchi/vlmkit-core/types.ts";
|
|
8
|
-
import { STOP_WORDS, SYNONYMS } from "./nlp.ts";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Expectation -> change -> realization reasoning chain
|
|
12
|
-
*
|
|
13
|
-
* 1. Expectation: what we intend to change (intent + expectation)
|
|
14
|
-
* 2. Change: what actually changed (a11y diff)
|
|
15
|
-
* 3. Realization: whether the expectation was realized in a11y semantics
|
|
16
|
-
*/
|
|
17
|
-
export interface ReasoningChain {
|
|
18
|
-
testId: string;
|
|
19
|
-
/** Expectation summary */
|
|
20
|
-
expectation: string;
|
|
21
|
-
/** Actual changes */
|
|
22
|
-
actualChanges: ActualChange[];
|
|
23
|
-
/** Expectation-to-actual mappings */
|
|
24
|
-
mappings: ExpectationMapping[];
|
|
25
|
-
/** Verdict */
|
|
26
|
-
verdict: "realized" | "partially-realized" | "not-realized" | "unexpected-side-effects";
|
|
27
|
-
/** Human-readable reasoning */
|
|
28
|
-
reasoning: string;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export interface ActualChange {
|
|
32
|
-
type: string;
|
|
33
|
-
description: string;
|
|
34
|
-
path: string;
|
|
35
|
-
severity: string;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export interface ExpectationMapping {
|
|
39
|
-
expected: string;
|
|
40
|
-
actual: string | null;
|
|
41
|
-
realized: boolean;
|
|
42
|
-
reasoning: string;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Reason about whether expected changes were realized in the a11y tree diff.
|
|
47
|
-
*/
|
|
48
|
-
export function reasonAboutChanges(
|
|
49
|
-
testId: string,
|
|
50
|
-
pageExp: PageExpectation,
|
|
51
|
-
a11yDiff: A11yDiff | undefined,
|
|
52
|
-
intent: ChangeIntent
|
|
53
|
-
): ReasoningChain {
|
|
54
|
-
const expectation = pageExp.expect
|
|
55
|
-
?? pageExp.expectedA11yChanges?.map((e) => e.description).join("; ")
|
|
56
|
-
?? intent.summary;
|
|
57
|
-
|
|
58
|
-
const actualChanges: ActualChange[] = (a11yDiff?.changes ?? []).map((c) => ({
|
|
59
|
-
type: c.type,
|
|
60
|
-
description: c.description,
|
|
61
|
-
path: c.path,
|
|
62
|
-
severity: c.severity,
|
|
63
|
-
}));
|
|
64
|
-
|
|
65
|
-
const expectedChanges = pageExp.expectedA11yChanges ?? [];
|
|
66
|
-
|
|
67
|
-
// Map expected to actual (consumed tracking prevents duplicate matches)
|
|
68
|
-
const mappings: ExpectationMapping[] = [];
|
|
69
|
-
const consumed = new Set<number>();
|
|
70
|
-
|
|
71
|
-
for (const exp of expectedChanges) {
|
|
72
|
-
const changes = a11yDiff?.changes ?? [];
|
|
73
|
-
const matchedIdx = findBestMatchIdx(exp, changes, consumed);
|
|
74
|
-
if (matchedIdx >= 0) {
|
|
75
|
-
consumed.add(matchedIdx);
|
|
76
|
-
const matchedActual = changes[matchedIdx];
|
|
77
|
-
mappings.push({
|
|
78
|
-
expected: exp.description,
|
|
79
|
-
actual: `${matchedActual.type}: ${matchedActual.description}`,
|
|
80
|
-
realized: true,
|
|
81
|
-
reasoning: buildMappingReasoning(exp, matchedActual),
|
|
82
|
-
});
|
|
83
|
-
} else {
|
|
84
|
-
mappings.push({
|
|
85
|
-
expected: exp.description,
|
|
86
|
-
actual: null,
|
|
87
|
-
realized: false,
|
|
88
|
-
reasoning: `Expected "${exp.description}" was not detected in the a11y diff`,
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// Unexpected changes (side effects)
|
|
94
|
-
const sideEffects = actualChanges.filter((_, i) => !consumed.has(i));
|
|
95
|
-
|
|
96
|
-
// Verdict
|
|
97
|
-
const allRealized = mappings.length > 0 && mappings.every((m) => m.realized);
|
|
98
|
-
const someRealized = mappings.some((m) => m.realized);
|
|
99
|
-
const hasSideEffects = sideEffects.length > 0;
|
|
100
|
-
|
|
101
|
-
let verdict: ReasoningChain["verdict"];
|
|
102
|
-
if (mappings.length === 0 && actualChanges.length === 0) {
|
|
103
|
-
verdict = "not-realized";
|
|
104
|
-
} else if (allRealized && !hasSideEffects) {
|
|
105
|
-
verdict = "realized";
|
|
106
|
-
} else if (allRealized && hasSideEffects) {
|
|
107
|
-
verdict = "unexpected-side-effects";
|
|
108
|
-
} else if (someRealized) {
|
|
109
|
-
verdict = "partially-realized";
|
|
110
|
-
} else {
|
|
111
|
-
verdict = "not-realized";
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// Human-readable reasoning
|
|
115
|
-
const reasoning = buildReasoning(
|
|
116
|
-
testId, expectation, mappings, sideEffects, verdict
|
|
117
|
-
);
|
|
118
|
-
|
|
119
|
-
return {
|
|
120
|
-
testId,
|
|
121
|
-
expectation,
|
|
122
|
-
actualChanges,
|
|
123
|
-
mappings,
|
|
124
|
-
verdict,
|
|
125
|
-
reasoning,
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function findBestMatchIdx(
|
|
130
|
-
exp: ExpectedA11yChange,
|
|
131
|
-
changes: A11yChange[],
|
|
132
|
-
consumed: Set<number>
|
|
133
|
-
): number {
|
|
134
|
-
// Best-score match on structured fields (optimal, not greedy)
|
|
135
|
-
if (exp.type || exp.role || exp.name) {
|
|
136
|
-
let bestIdx = -1;
|
|
137
|
-
let bestFieldScore = 0;
|
|
138
|
-
|
|
139
|
-
for (let i = 0; i < changes.length; i++) {
|
|
140
|
-
if (consumed.has(i)) continue;
|
|
141
|
-
const c = changes[i];
|
|
142
|
-
let fieldScore = 0;
|
|
143
|
-
let fieldCount = 0;
|
|
144
|
-
|
|
145
|
-
if (exp.type) {
|
|
146
|
-
fieldCount++;
|
|
147
|
-
if (c.type === exp.type) fieldScore++;
|
|
148
|
-
else continue; // type mismatch is disqualifying
|
|
149
|
-
}
|
|
150
|
-
if (exp.role) {
|
|
151
|
-
fieldCount++;
|
|
152
|
-
const inPath = c.path.toLowerCase().includes(exp.role.toLowerCase());
|
|
153
|
-
const inDesc = c.description.toLowerCase().includes(exp.role.toLowerCase());
|
|
154
|
-
if (inPath || inDesc) fieldScore++;
|
|
155
|
-
else continue;
|
|
156
|
-
}
|
|
157
|
-
if (exp.name) {
|
|
158
|
-
fieldCount++;
|
|
159
|
-
if (c.description.toLowerCase().includes(exp.name.toLowerCase())) fieldScore++;
|
|
160
|
-
else continue;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
if (fieldScore > bestFieldScore) {
|
|
164
|
-
bestFieldScore = fieldScore;
|
|
165
|
-
bestIdx = i;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
if (bestIdx >= 0) return bestIdx;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
// Description fuzzy match
|
|
173
|
-
// Remove stop words and expand synonyms before comparison
|
|
174
|
-
const rawKeywords = exp.description
|
|
175
|
-
.toLowerCase()
|
|
176
|
-
.split(/\s+/)
|
|
177
|
-
.filter((w) => w.length > 2 && !STOP_WORDS.has(w));
|
|
178
|
-
// Expand synonyms
|
|
179
|
-
const keywords = rawKeywords.flatMap((k) => [k, ...(SYNONYMS[k] ?? [])]);
|
|
180
|
-
|
|
181
|
-
let bestIdx = -1;
|
|
182
|
-
let bestScore = 0;
|
|
183
|
-
|
|
184
|
-
for (let i = 0; i < changes.length; i++) {
|
|
185
|
-
if (consumed.has(i)) continue;
|
|
186
|
-
const change = changes[i];
|
|
187
|
-
const target = `${change.type} ${change.description} ${change.path}`.toLowerCase();
|
|
188
|
-
const matched = keywords.filter((k) => target.includes(k)).length;
|
|
189
|
-
const score = keywords.length > 0 ? matched / keywords.length : 0;
|
|
190
|
-
// Require at least 2 keyword matches to be a candidate
|
|
191
|
-
if (score > bestScore && matched >= 2) {
|
|
192
|
-
bestScore = score;
|
|
193
|
-
bestIdx = i;
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
return bestIdx;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function buildMappingReasoning(exp: ExpectedA11yChange, actual: A11yChange): string {
|
|
201
|
-
const parts: string[] = [];
|
|
202
|
-
|
|
203
|
-
parts.push(`Expected: "${exp.description}"`);
|
|
204
|
-
parts.push(`Actual: [${actual.type}] ${actual.description}`);
|
|
205
|
-
parts.push(`Path: ${actual.path}`);
|
|
206
|
-
|
|
207
|
-
// Explain how the semantic was realized
|
|
208
|
-
if (actual.type === "node-added") {
|
|
209
|
-
parts.push("→ New element was added to the a11y tree, matching expectation");
|
|
210
|
-
} else if (actual.type === "node-removed" || actual.type === "landmark-changed") {
|
|
211
|
-
parts.push("→ Element was removed from the a11y tree, matching expectation");
|
|
212
|
-
} else if (actual.type === "name-changed") {
|
|
213
|
-
const before = actual.before?.name ?? "(none)";
|
|
214
|
-
const after = actual.after?.name ?? "(none)";
|
|
215
|
-
parts.push(`→ Accessible name changed: "${before}" → "${after}"`);
|
|
216
|
-
} else if (actual.type === "role-changed") {
|
|
217
|
-
parts.push(`→ Role changed: ${actual.before?.role} → ${actual.after?.role}`);
|
|
218
|
-
} else if (actual.type === "state-changed") {
|
|
219
|
-
parts.push("→ ARIA state changed");
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
return parts.join(". ");
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function buildReasoning(
|
|
226
|
-
testId: string,
|
|
227
|
-
expectation: string,
|
|
228
|
-
mappings: ExpectationMapping[],
|
|
229
|
-
sideEffects: ActualChange[],
|
|
230
|
-
verdict: ReasoningChain["verdict"]
|
|
231
|
-
): string {
|
|
232
|
-
const lines: string[] = [];
|
|
233
|
-
|
|
234
|
-
lines.push(`[${testId}] Expectation: "${expectation}"`);
|
|
235
|
-
lines.push("");
|
|
236
|
-
|
|
237
|
-
if (mappings.length > 0) {
|
|
238
|
-
lines.push("Expectation → Realization mapping:");
|
|
239
|
-
for (const m of mappings) {
|
|
240
|
-
const icon = m.realized ? "✓" : "✗";
|
|
241
|
-
lines.push(` ${icon} ${m.expected}`);
|
|
242
|
-
if (m.actual) {
|
|
243
|
-
lines.push(` ↔ ${m.actual}`);
|
|
244
|
-
}
|
|
245
|
-
lines.push(` ${m.reasoning}`);
|
|
246
|
-
}
|
|
247
|
-
lines.push("");
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
if (sideEffects.length > 0) {
|
|
251
|
-
lines.push("Side effects (not in expectations):");
|
|
252
|
-
for (const se of sideEffects) {
|
|
253
|
-
lines.push(` ! [${se.type}] ${se.description}`);
|
|
254
|
-
}
|
|
255
|
-
lines.push("");
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
const verdictText = {
|
|
259
|
-
"realized": "All expected changes were realized in the a11y tree",
|
|
260
|
-
"partially-realized": "Some expected changes were realized, but not all",
|
|
261
|
-
"not-realized": "Expected changes were not detected in the a11y tree",
|
|
262
|
-
"unexpected-side-effects": "All expected changes were realized, but additional unexpected changes were detected",
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
lines.push(`Verdict: ${verdict.toUpperCase()} — ${verdictText[verdict]}`);
|
|
266
|
-
|
|
267
|
-
return lines.join("\n");
|
|
268
|
-
}
|