index.ts
7.99 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
import { tools } from 'evoltagent';
import { logger } from '../../utils/logger';
import { captureBrowserPositions } from './utils/capture-position';
import { calculatePositionMetrics } from './utils/position-metrics';
import { calculateComponentMetrics, toRect } from './utils/aggregate-elements';
import type {
AggregateElementsResult,
BrowserPositionInput,
ComponentData,
ComponentMisalignment,
ElementAbsolutePosition,
PositionToolMetrics,
PositionValidationOutput,
SkippedElement,
} from './types';
@tools({
capturePosition: {
description:
'Capture viewport-relative positions in the browser and compare to Figma absoluteBoundingBox, returning per-element deltas and metrics.',
params: [{ name: 'input', type: 'object', description: 'BrowserPositionInput (figmaJSON, structure, url, etc.)' }],
returns: { type: 'object', description: 'PositionValidationOutput containing metadata, positions, and errors.' },
},
aggregateElements: {
description:
'Aggregate element-level rectangles into component-level bounds and return misaligned components based on aggregate distance threshold.',
params: [
{ name: 'positions', type: 'object', description: 'Positions keyed by elementId (from capturePosition).' },
{
name: 'elementToComponentMap',
type: 'object',
description: 'Mapping from elementId -> {id,name,path} for parent component (built from structure tree).',
},
{ name: 'positionThreshold', type: 'number', description: 'Pixel threshold for aggregate distance.' },
],
returns: { type: 'object', description: 'AggregateElementsResult: misalignedComponents + skippedElements.' },
},
computeMetrics: {
description: 'Compute MAE/MSE/RMSE/accuracy metrics from element positions, and SAE from component misalignments.',
params: [
{ name: 'positions', type: 'object', description: 'Positions keyed by elementId (from capturePosition).' },
{
name: 'misalignedComponents',
type: 'object',
description: 'Optional component misalignments (from aggregateElements) used to compute SAE.',
optional: true,
},
],
returns: { type: 'object', description: 'PositionToolMetrics (ValidationMetrics + sae).' },
},
})
export class PositionTool {
async capturePosition(input: BrowserPositionInput): Promise<PositionValidationOutput> {
return await captureBrowserPositions(input);
}
/**
* Deterministic in-process aggregation.
* NOTE: Map-based inputs are not JSON-friendly for future agent calls; we can add a JSON form later.
*/
aggregateElements(
positions: Record<string, ElementAbsolutePosition>,
elementToComponentMap: Map<string, { id: string; name: string; path: string }>,
positionThreshold: number
): AggregateElementsResult {
const componentMap = new Map<string, ComponentData>();
const skippedElements: SkippedElement[] = [];
for (const [elementId, position] of Object.entries(positions)) {
if (!position.figmaPosition) {
skippedElements.push({
elementId,
reason: 'no_figma_position',
details: 'Element exists in render but has no corresponding Figma position data',
});
continue;
}
const component = elementToComponentMap.get(elementId);
if (!component) {
skippedElements.push({
elementId,
reason: 'missing_component_mapping',
details: 'Element has no component mapping in structure tree',
});
continue;
}
if (!componentMap.has(component.id)) {
componentMap.set(component.id, {
componentId: component.id,
componentName: component.name,
componentPath: component.path,
elementIds: [],
positions: [],
targets: [],
errors: [],
});
}
const compData = componentMap.get(component.id)!;
compData.elementIds.push(elementId);
compData.positions.push(toRect(position.boundingBox));
compData.targets.push(toRect(position.figmaPosition));
compData.errors.push({
x: Math.abs(position.metrics?.xDelta ?? 0),
y: Math.abs(position.metrics?.yDelta ?? 0),
});
}
this.logSkippedElementsSummary(skippedElements);
const misalignedComponents: ComponentMisalignment[] = [];
for (const compData of componentMap.values()) {
if (compData.positions.length === 0 || compData.targets.length === 0) {
for (const elemId of compData.elementIds) {
skippedElements.push({
elementId: elemId,
reason: 'incomplete_data',
details: `Component ${compData.componentName} has ${compData.positions.length} positions, ${compData.targets.length} targets`,
});
}
continue;
}
const metrics = calculateComponentMetrics(compData, positionThreshold);
if (!metrics) {
continue;
}
const { currentBounds, targetBounds, error } = metrics;
misalignedComponents.push({
name: compData.componentName,
componentId: compData.componentId,
elementIds: compData.elementIds,
path: compData.componentPath,
validationReport: {
currentPosition: [currentBounds.minX, currentBounds.minY],
targetPosition: [targetBounds.minX, targetBounds.minY],
absoluteError: [error.errorX, error.errorY],
},
currentX: currentBounds.minX,
currentY: currentBounds.minY,
targetX: targetBounds.minX,
targetY: targetBounds.minY,
currentWidth: currentBounds.width,
currentHeight: currentBounds.height,
targetWidth: targetBounds.width,
targetHeight: targetBounds.height,
distance: error.distance,
});
}
return { misalignedComponents, skippedElements };
}
computeMetrics(
positions: Record<string, ElementAbsolutePosition>,
misalignedComponents?: ComponentMisalignment[]
): PositionToolMetrics {
const metrics = calculatePositionMetrics(positions);
const sae =
misalignedComponents?.reduce((sum, comp) => {
const [errorX, errorY] = comp.validationReport.absoluteError;
return sum + errorX + errorY;
}, 0) ?? 0;
return { ...metrics, sae: Math.round(sae * 100) / 100 };
}
private logSkippedElementsSummary(skippedElements: SkippedElement[]): void {
if (skippedElements.length === 0) {
return;
}
const byReason: Record<SkippedElement['reason'], number> = {
missing_component_mapping: 0,
incomplete_data: 0,
no_figma_position: 0,
};
for (const elem of skippedElements) {
byReason[elem.reason] += 1;
}
const summary = (Object.entries(byReason) as Array<[SkippedElement['reason'], number]>)
.filter(([, count]) => count > 0)
.map(([reason, count]) => `${count} ${reason.replace(/_/g, ' ')}`)
.join(', ');
const firstFew = skippedElements
.slice(0, 3)
.map(e => e.elementId)
.join(', ');
logger.printWarnLog(`Skipped ${skippedElements.length} element(s): ${summary}. First few: ${firstFew}`);
}
}